All files / cli/src/generators package-scaffold.js

93.87% Statements 46/49
76.47% Branches 13/17
90.9% Functions 10/11
93.87% Lines 46/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507                6x 6x           26x                                                                                                                                                                             26x                       8x                                                 8x                                                                                                               8x                         8x                                           8x                         8x                         8x                         8x                             8x                               8x                       8x                                 8x                       8x                                                                               8x                       8x                                   8x                                   8x                                                           26x 26x 26x   26x     74x   26x 26x   8x 8x   8x 8x   8x 8x   8x 8x   8x 8x   8x 8x           74x 74x 188x 74x   114x           26x    
/**
 * Package Scaffolding Generator
 * Generates basic scaffolding for optional @coherent.js packages
 */
 
import { getCLIVersion, getDependencyRange } from '../utils/version.js';
 
// Get current CLI version automatically
const cliVersion = getCLIVersion();
const cliRange = getDependencyRange(cliVersion);
 
/**
 * Generate @coherent.js/api scaffolding
 */
export function generateApiScaffolding() {
  const routes = `
import { createRouter } from '@coherent.js/api';
 
const router = createRouter();
 
// Business Logic
async function getUserById(id) {
  return { id, name: 'Example User', email: 'user@example.com' };
}
 
async function createUser(data) {
  return { id: 1, ...data };
}
 
// Router Definitions (for Express/Fastify/Koa usage).
// Handlers return plain data; the router serializes objects as JSON.
router.get('/users/:id', async (req) => {
  const id = Number(req.params.id);
  return getUserById(id);
});
 
router.post('/users', async (req) => {
  return createUser(req.body);
});
 
// Handler for GET /api/users/:id (Built-in Server)
export async function getUsersByIdHandler(req, res) {
  try {
    const { id } = req.params;
    const result = await getUserById(id);
 
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(result));
  } catch (error) {
    console.error('API Error:', error);
    res.writeHead(500, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Internal server error' }));
  }
}
 
// Handler for POST /api/users (Built-in Server)
export async function postUsersHandler(req, res) {
  try {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
 
    req.on('end', async () => {
      try {
        const parsedBody = JSON.parse(body);
        const result = await createUser(parsedBody);
 
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(result));
      } catch (error) {
        console.error('API Error:', error);
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Internal server error' }));
      }
    });
  } catch (error) {
    console.error('API Error:', error);
    res.writeHead(500, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Internal server error' }));
  }
}
 
// For built-in HTTP server compatibility
export function setupRoutes() {
  return [
    {
      path: '/api/users/:id',
      method: 'GET',
      handler: getUsersByIdHandler
    },
    {
      path: '/api/users',
      method: 'POST',
      handler: postUsersHandler
    }
  ];
}
 
export default router;
`;
 
  return {
    'src/api/routes.js': routes,
    dependencies: {
      '@coherent.js/api': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/client scaffolding
 */
export function generateClientScaffolding() {
  const hydration = `
import { hydrate } from '@coherent.js/client';
 
// Hydrate interactive components on page load
document.addEventListener('DOMContentLoaded', () => {
  // Find all components marked for hydration
  const components = document.querySelectorAll('[data-hydrate]');
 
  components.forEach(async (element) => {
    const componentName = element.getAttribute('data-hydrate');
 
    try {
      // Dynamically import component
      const module = await import(\`/components/\${componentName}.js\`);
      const Component = module.default || module[componentName];
 
      // Hydrate component
      hydrate(element, Component);
    } catch (error) {
      console.error(\`Failed to hydrate component: \${componentName}\`, error);
    }
  });
});
`;
 
  const interactiveExample = `
/**
 * Example interactive component for client-side hydration
 */
export function InteractiveCounter(props = {}) {
  const { initialCount = 0 } = props;
 
  return {
    div: {
      'data-hydrate': 'InteractiveCounter',
      'data-count': initialCount,
      className: 'counter',
      children: [
        {
          button: {
            className: 'counter-button',
            'data-action': 'decrement',
            text: '-'
          }
        },
        {
          span: {
            className: 'counter-value',
            text: String(initialCount)
          }
        },
        {
          button: {
            className: 'counter-button',
            'data-action': 'increment',
            text: '+'
          }
        }
      ]
    }
  };
}
 
// Client-side hydration logic (safe to import on the server; only does
// anything when called with a DOM element in the browser)
export function hydrateCounter(element) {
  let count = parseInt(element.getAttribute('data-count') || '0');
  const valueSpan = element.querySelector('.counter-value');
 
  element.addEventListener('click', (e) => {
    if (e.target.matches('[data-action="increment"]')) {
      count++;
      valueSpan.textContent = count;
    } else if (e.target.matches('[data-action="decrement"]')) {
      count--;
      valueSpan.textContent = count;
    }
  });
}
`;
 
  return {
    'public/js/hydration.js': hydration,
    'src/components/InteractiveCounter.js': interactiveExample,
    dependencies: {
      '@coherent.js/client': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/i18n scaffolding
 */
export function generateI18nScaffolding() {
  const config = `
import { readFileSync } from 'node:fs';
import { createTranslator } from '@coherent.js/i18n';
 
const loadLocale = (locale) =>
  JSON.parse(readFileSync(new URL(\`./locales/\${locale}.json\`, import.meta.url), 'utf8'));
 
export const translator = createTranslator({
  defaultLocale: 'en',
  fallbackLocale: 'en'
});
 
for (const locale of ['en', 'fr', 'es']) {
  translator.addTranslations(locale, loadLocale(locale));
}
 
// Usage:
//   translator.t('common.welcome')
//   translator.t('common.hello', { name: 'Ada' })
//   translator.setLocale('fr')
`;
 
  const enLocale = JSON.stringify({
    common: {
      welcome: 'Welcome',
      hello: 'Hello, {{name}}!',
      loading: 'Loading...'
    },
    nav: {
      home: 'Home',
      about: 'About',
      contact: 'Contact'
    }
  }, null, 2);
 
  const frLocale = JSON.stringify({
    common: {
      welcome: 'Bienvenue',
      hello: 'Bonjour, {{name}}!',
      loading: 'Chargement...'
    },
    nav: {
      home: 'Accueil',
      about: 'À propos',
      contact: 'Contact'
    }
  }, null, 2);
 
  const esLocale = JSON.stringify({
    common: {
      welcome: 'Bienvenido',
      hello: '¡Hola, {{name}}!',
      loading: 'Cargando...'
    },
    nav: {
      home: 'Inicio',
      about: 'Acerca de',
      contact: 'Contacto'
    }
  }, null, 2);
 
  return {
    'src/i18n/config.js': config,
    'src/i18n/locales/en.json': enLocale,
    'src/i18n/locales/fr.json': frLocale,
    'src/i18n/locales/es.json': esLocale,
    dependencies: {
      '@coherent.js/i18n': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/forms scaffolding
 */
export function generateFormsScaffolding() {
  const exampleForm = `
import { createFormBuilder } from '@coherent.js/forms';
 
export function ContactForm() {
  const form = createFormBuilder({
    fields: [
      { name: 'name', type: 'text', label: 'Name', required: true },
      { name: 'email', type: 'email', label: 'Email', required: true },
      { name: 'message', type: 'textarea', label: 'Message', required: true }
    ]
  });
 
  return form.buildForm({ submitText: 'Submit' });
}
`;
 
  return {
    'src/components/ContactForm.js': exampleForm,
    dependencies: {
      '@coherent.js/forms': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/devtools scaffolding
 */
export function generateDevtoolsScaffolding() {
  const config = `
import { inspect, createProfiler, createLogger } from '@coherent.js/devtools';
 
// Dev-time helpers — import these where useful during development.
export const profiler = createProfiler();
export const logger = createLogger();
 
/**
 * Log a component tree analysis to the console (development only).
 */
export function inspectComponent(component) {
  if (process.env.NODE_ENV !== 'production') {
    return inspect(component);
  }
}
`;
 
  return {
    'src/utils/devtools.js': config,
    dependencies: {
      '@coherent.js/devtools': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/seo scaffolding
 */
export function generateSeoScaffolding(projectName = 'My App') {
  const metaHelper = `
import { generateMeta, generateSitemap } from '@coherent.js/seo';
 
export function getPageMeta(page, data = {}) {
  const baseUrl = process.env.BASE_URL || 'https://example.com';
 
  const metaConfigs = {
    home: {
      title: 'Welcome to ${projectName}',
      description: 'A ${projectName} application built with Coherent.js',
      image: { url: \`\${baseUrl}/images/og-home.jpg\` },
      canonical: baseUrl
    },
    about: {
      title: 'About - ${projectName}',
      description: 'Learn more about ${projectName}',
      image: { url: \`\${baseUrl}/images/og-about.jpg\` },
      canonical: \`\${baseUrl}/about\`
    }
  };
 
  const config = metaConfigs[page] || metaConfigs.home;
 
  return generateMeta({
    ...config,
    siteName: '${projectName}',
    locale: 'en_US',
    ...data
  });
}
 
export function getSitemap() {
  return generateSitemap([
    { url: '/', priority: 1.0, changefreq: 'daily' },
    { url: '/about', priority: 0.8, changefreq: 'weekly' },
    { url: '/contact', priority: 0.6, changefreq: 'monthly' }
  ]);
}
`;
 
  return {
    'src/utils/seo.js': metaHelper,
    dependencies: {
      '@coherent.js/seo': cliRange
    }
  };
}
 
/**
 * Generate @coherent.js/tooling/testing scaffolding
 */
export function generateTestingScaffolding() {
  const testHelper = `
import { renderComponent } from '@coherent.js/tooling/testing';
import { describe, it, expect } from 'vitest';
 
/**
 * Reusable smoke test for any component
 */
export function testComponent(Component, props = {}) {
  describe(Component.name || 'Component', () => {
    it('renders without errors', () => {
      const { html } = renderComponent(Component(props));
      expect(html).toBeTypeOf('string');
      expect(html.length).toBeGreaterThan(0);
    });
  });
}
`;
 
  const exampleTest = `
import { describe, it, expect } from 'vitest';
import { renderComponent } from '@coherent.js/tooling/testing';
import { HomePage } from '../../src/components/HomePage.js';
 
describe('HomePage', () => {
  it('should render the home page', () => {
    const { html } = renderComponent(HomePage({}));
    expect(html).toContain('Welcome');
  });
 
  it('should render with custom props', () => {
    const { html } = renderComponent(HomePage({ title: 'Custom Title' }));
    expect(html).toContain('Custom Title');
  });
});
`;
 
  return {
    'tests/helpers/testing.js': testHelper,
    'tests/components/HomePage.test.js': exampleTest,
    dependencies: {
      '@coherent.js/tooling': cliRange
    }
  };
}
 
/**
 * Get dependencies for a package
 */
export function getPackageDependencies(packageName) {
  const scaffolding = {
    api: generateApiScaffolding(),
    client: generateClientScaffolding(),
    i18n: generateI18nScaffolding(),
    forms: generateFormsScaffolding(),
    devtools: generateDevtoolsScaffolding(),
    seo: generateSeoScaffolding(),
    testing: generateTestingScaffolding()
  };
 
  return scaffolding[packageName]?.dependencies || {};
}
 
/**
 * Generate scaffolding for selected packages
 */
export function generatePackageScaffolding(packages, options = {}) {
  const { projectName = 'My App' } = options;
  const files = {};
  const dependencies = {};
 
  packages.forEach(pkg => {
    let scaffolding;
 
    switch (pkg) {
      case 'api':
        scaffolding = generateApiScaffolding();
        break;
      case 'client':
        scaffolding = generateClientScaffolding();
        break;
      case 'i18n':
        scaffolding = generateI18nScaffolding();
        break;
      case 'forms':
        scaffolding = generateFormsScaffolding();
        break;
      case 'devtools':
        scaffolding = generateDevtoolsScaffolding();
        break;
      case 'seo':
        scaffolding = generateSeoScaffolding(projectName);
        break;
      case 'testing':
        scaffolding = generateTestingScaffolding();
        break;
      default:
        return;
    }
 
    // Merge files and dependencies
    Eif (scaffolding) {
      Object.entries(scaffolding).forEach(([key, value]) => {
        if (key === 'dependencies') {
          Object.assign(dependencies, value);
        } else {
          files[key] = value;
        }
      });
    }
  });
 
  return { files, dependencies };
}