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

79.33% Statements 119/150
76.31% Branches 87/114
100% Functions 9/9
79.33% Lines 119/150

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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646                                10x 10x           10x                                           76x 76x 420x 1x     76x 76x 76x 76x 76x 76x 40x   76x 76x                                                           76x   76x       76x 1x     75x 75x     76x                   76x 39x   75x 34x   75x 23x 5x     18x     75x 4x     75x 622x     75x     75x 75x   75x     75x 11x 11x   64x 64x     75x     75x                 75x   75x     75x   75x     75x 34x 34x 34x 34x     34x                                         34x 34x       34x 34x         34x       75x 23x     23x 23x     23x       23x       23x 23x 23x 23x     23x       75x 16x   16x 60x 60x 60x         75x             76x                                         75x                             75x   75x 75x   75x                                                                     75x 11x 11x 11x 11x     11x 4x 7x           75x   75x         75x 75x     75x 34x 34x       75x 23x 23x       75x 16x 16x     75x             75x                                                                                                                                                                     75x     75x                                                                       75x             75x 75x     75x                                                                                     75x     75x                                                                                                                 75x     75x                               75x    
/**
 * Project scaffolding generator
 */
 
import { writeFileSync, mkdirSync, copyFileSync, constants, readFileSync, appendFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { execSync } from 'node:child_process';
import { getCLIVersion, getDependencyRange } from '../utils/version.js';
import { generateServerFile, getRuntimeDependencies, getRuntimeTypeDependencies } from './runtime-scaffold.js';
import { generateDatabaseScaffolding } from './database-scaffold.js';
import { generateAuthScaffolding } from './auth-scaffold.js';
import { generateDockerScaffolding, generateHealthCheck } from './docker-scaffold.js';
import { generatePackageScaffolding } from './package-scaffold.js';
import { generateTsConfig, generateJsConfig, getTypeScriptDependencies } from './typescript-config.js';
 
// Get current CLI version automatically
const cliVersion = getCLIVersion();
const cliRange = getDependencyRange(cliVersion);
 
/**
 * Values scaffoldProject() accepts; everything else is rejected up front.
 * (Unknown templates are not listed: they fall back to the basic layout.)
 */
export const SCAFFOLD_CHOICES = {
  runtime: ['built-in', 'express', 'fastify', 'koa'],
  database: ['postgres', 'mysql', 'sqlite', 'mongodb'],
  auth: ['jwt', 'session'],
  language: ['javascript', 'typescript'],
  packageManager: ['npm', 'yarn', 'pnpm'],
  packages: ['api', 'client', 'i18n', 'forms', 'devtools', 'seo', 'testing']
};
 
/**
 * Check scaffold options before anything is written, so a bad option
 * cannot leave a half-created project behind.
 *
 * @param {Object} options - runtime, database, auth, packages, language, packageManager.
 * @param {Object} [config]
 * @param {boolean} [config.combinations=true] - Also reject option combinations
 *   the generated code does not support (auth without a SQL database, session
 *   auth outside express). `coherent create` checks them; scaffoldProject()
 *   itself only rejects unknown values.
 * @returns {string[]} Human-readable problems; empty when the options are valid.
 */
export function validateScaffoldOptions(options = {}, { combinations = true } = {}) {
  const problems = [];
  const check = (key, value) => {
    if (value !== undefined && value !== null && !SCAFFOLD_CHOICES[key].includes(value)) {
      problems.push(`Unknown ${key} "${value}". Choose one of: ${SCAFFOLD_CHOICES[key].join(', ')}`);
    }
  };
  check('runtime', options.runtime);
  check('database', options.database);
  check('auth', options.auth);
  check('language', options.language);
  check('packageManager', options.packageManager);
  for (const pkg of options.packages ?? []) {
    check('packages', pkg);
  }
  Eif (!combinations) {
    return problems;
  }
  if (options.auth && !options.database) {
    problems.push('Auth scaffolding requires a database (it generates login against the User model). Add --database sqlite|postgres|mysql.');
  }
  if (options.auth && options.database === 'mongodb') {
    problems.push('Auth scaffolding requires a SQL database (sqlite, postgres, mysql); MongoDB auth is not supported yet.');
  }
  if (options.auth === 'session' && options.runtime && options.runtime !== 'express') {
    problems.push('Session auth scaffolding is only available for the express runtime. Use --auth jwt, or --runtime express.');
  }
  return problems;
}
 
/**
 * Scaffold a new Coherent.js project
 */
export async function scaffoldProject(projectPath, options) {
  const {
    name,
    template,
    skipInstall,
    skipGit,
    runtime = 'built-in',
    database = null,
    auth = null,
    packages = [],
    language = 'javascript',
    packageManager = 'npm',
    onProgress = () => {}
  } = options;
 
  const problems = validateScaffoldOptions(
    { runtime, database, auth, packages, language, packageManager },
    { combinations: false }
  );
  if (problems.length > 0) {
    throw new Error(problems.join('\n'));
  }
 
  const isTypeScript = language === 'typescript';
  const fileExtension = isTypeScript ? '.ts' : '.js';
 
  // Create directory structure
  const dirs = [
    'src',
    'src/components',
    'src/pages',
    'src/utils',
    'public',
    'tests'
  ];
 
  // Add directories based on selections
  if (packages.includes('api') || auth) {
    dirs.push('src/api');
  }
  if (database) {
    dirs.push('src/db', 'src/db/models', 'data');
  }
  if (auth) {
    if (runtime === 'fastify') {
      dirs.push('src/plugins');
    } else {
      // For built-in, express, and koa
      dirs.push('src/middleware');
    }
  }
  if (packages.includes('i18n')) {
    dirs.push('src/i18n', 'src/i18n/locales');
  }
 
  dirs.forEach(dir => {
    mkdirSync(join(projectPath, dir), { recursive: true });
  });
 
  onProgress('Created project structure');
 
  // Generate package.json
  const packageJson = generatePackageJson(name, { template, runtime, database, auth, packages, language, packageManager });
  writeFileSync(join(projectPath, 'package.json'), JSON.stringify(packageJson, null, 2));
 
  onProgress('Generated package.json');
 
  // Generate TypeScript or JavaScript config
  if (isTypeScript) {
    const tsConfig = generateTsConfig();
    writeFileSync(join(projectPath, 'tsconfig.json'), JSON.stringify(tsConfig, null, 2));
  } else {
    const jsConfig = generateJsConfig();
    writeFileSync(join(projectPath, 'jsconfig.json'), JSON.stringify(jsConfig, null, 2));
  }
 
  onProgress('Created configuration files');
 
  // Generate main server file
  const serverContent = generateServerFile(runtime, {
    port: 3000,
    // hasApi gates the './api/routes.js' import, which only exists when the
    // api package was selected — auth has its own routes file and hasAuth flag.
    hasApi: packages.includes('api'),
    hasDatabase: !!database,
    hasAuth: !!auth,
    isTypeScript
  });
  writeFileSync(join(projectPath, `src/index${fileExtension}`), serverContent);
 
  onProgress('Set up server');
 
  // Generate HomePage component
  await generateHomePageComponent(projectPath, name, isTypeScript, fileExtension);
 
  onProgress('Created components');
 
  // Generate database scaffolding
  if (database) {
    const dbScaffolding = generateDatabaseScaffolding(database, language);
    writeFileSync(join(projectPath, `src/db/config${fileExtension}`), dbScaffolding.config);
    writeFileSync(join(projectPath, `src/db/index${fileExtension}`), dbScaffolding.init);
    writeFileSync(join(projectPath, `src/db/models/User${fileExtension}`), dbScaffolding.model);
 
    // Generate Docker configuration if requested
    Iif (options.dockerConfig && database !== 'sqlite') {
      const dockerScaffolding = generateDockerScaffolding(database, options.dockerConfig);
 
      // Write Docker files
      writeFileSync(join(projectPath, 'docker-compose.yml'), dockerScaffolding['docker-compose.yml']);
      writeFileSync(join(projectPath, 'Dockerfile'), dockerScaffolding['Dockerfile']);
      writeFileSync(join(projectPath, '.dockerignore'), dockerScaffolding['.dockerignore']);
 
      // Generate health check script
      writeFileSync(join(projectPath, `healthcheck${fileExtension}`), generateHealthCheck());
 
      // Update .env.example with Docker configuration
      let envContent = '';
      for (const [key, value] of Object.entries(dockerScaffolding.envConfig)) {
        envContent += `${key}=${value}\n`;
      }
      writeFileSync(join(projectPath, '.env.example'), envContent);
 
      onProgress('Created Docker configuration');
    } else {
      // Generate or update .env.example without Docker
      const existingEnv = '';
      writeFileSync(join(projectPath, '.env.example'), existingEnv + dbScaffolding.env);
    }
 
    // Create .env from .env.example if it doesn't exist
    try {
      copyFileSync(join(projectPath, '.env.example'), join(projectPath, '.env'), constants.COPYFILE_EXCL);
    } catch {
      // Ignore if .env already exists
    }
 
    onProgress('Configured database');
  }
 
  // Generate auth scaffolding
  if (auth) {
    const authScaffolding = generateAuthScaffolding(auth, runtime, language);
 
    // Write auth middleware/plugin
    const authDir = runtime === 'fastify' ? 'plugins' : 'middleware';
    writeFileSync(join(projectPath, `src/${authDir}/auth${fileExtension}`), authScaffolding.middleware);
 
    // Write auth routes
    writeFileSync(join(projectPath, `src/api/auth${fileExtension}`), authScaffolding.routes);
 
    // .env.example (committed) gets the variable names with empty values;
    // appended so the database settings written above are kept.
    appendFileSync(join(projectPath, '.env.example'), authScaffolding.envExample);
 
    // .env (git-ignored) gets a freshly generated random secret, so the app
    // never runs with a value that is known to anyone else.
    const envPath = join(projectPath, '.env');
    const envContent = existsSync(envPath) ? readFileSync(envPath, 'utf8') : '';
    Eif (!/^(JWT_SECRET|SESSION_SECRET)=./m.test(envContent)) {
      appendFileSync(envPath, authScaffolding.env);
    }
 
    onProgress('Set up authentication');
  }
 
  // Generate optional package scaffolding
  if (packages.length > 0) {
    const { files } = generatePackageScaffolding(packages, { projectName: name });
 
    Object.entries(files).forEach(([filePath, content]) => {
      const fullPath = join(projectPath, filePath);
      mkdirSync(dirname(fullPath), { recursive: true });
      writeFileSync(fullPath, content);
    });
  }
 
  // Generate common files
  generateCommonFiles(projectPath, name, {
    fileExtension,
    packageManager,
    hasApi: packages.includes('api') || !!auth
  });
 
  // Install dependencies
  Iif (!skipInstall) {
    console.log(`📦 Installing dependencies with ${packageManager}...`);
    try {
      const installCommands = {
        npm: 'npm install',
        yarn: 'yarn install',
        pnpm: 'pnpm install'
      };
 
      const installCmd = installCommands[packageManager] || 'npm install';
 
      execSync(installCmd, {
        cwd: projectPath,
        stdio: 'inherit'
      });
    } catch {
      console.warn(`⚠️  Failed to install dependencies with ${packageManager}`);
    }
  }
 
  // Initialize git
  Iif (!skipGit) {
    try {
      execSync('git init', { cwd: projectPath, stdio: 'pipe' });
      execSync('git add .', { cwd: projectPath, stdio: 'pipe' });
      execSync('git commit -m "Initial commit"', { cwd: projectPath, stdio: 'pipe' });
    } catch {
      console.warn('⚠️  Failed to initialize git repository');
    }
  }
}
 
/**
 * Generate package.json based on options
 */
function generatePackageJson(name, options) {
  const { runtime = 'built-in', database = null, auth = null, packages = [], language = 'javascript', packageManager = 'npm' } = options;
 
  const isTypeScript = language === 'typescript';
  const fileExt = isTypeScript ? '.ts' : '.js';
 
  const base = {
    name,
    version: '1.0.0',
    description: 'A Coherent.js application',
    type: 'module',
    main: isTypeScript ? 'dist/index.js' : `src/index${fileExt}`,
    // --env-file-if-exists loads .env (secrets, DB credentials) without a
    // dotenv dependency; `dev` restarts the server when a source file changes.
    scripts: isTypeScript ? {
      dev: 'tsx watch --env-file-if-exists=.env src/index.ts',
      build: 'tsc',
      start: 'node --env-file-if-exists=.env dist/index.js',
      typecheck: 'tsc --noEmit',
      test: 'vitest run'
    } : {
      dev: 'node --watch --env-file-if-exists=.env src/index.js',
      build: 'coherent build',
      start: 'node --env-file-if-exists=.env src/index.js',
      test: 'vitest run'
    },
    // --env-file-if-exists needs Node >= 22.9; match the CLI's own floor.
    engines: {
      node: '>=22.12.0'
    },
    dependencies: {
      '@coherent.js/core': cliRange
    },
    devDependencies: {
      '@coherent.js/cli': cliRange,
      // Same major as the monorepo's own vitest.
      vitest: '^5.0.0'
    }
  };
 
  // Add TypeScript dependencies
  if (isTypeScript) {
    const tsDeps = getTypeScriptDependencies();
    Object.assign(base.devDependencies, tsDeps);
    base.devDependencies.tsx = '^4.19.2'; // For running TypeScript files directly
    Object.assign(base.devDependencies, getRuntimeTypeDependencies(runtime));
 
    // Add @types for auth packages if auth is enabled
    if (auth === 'jwt') {
      base.devDependencies['@types/jsonwebtoken'] = '^9.0.7';
    } else Iif (auth === 'session') {
      base.devDependencies['@types/express-session'] = '^1.18.0';
    }
  }
 
  // Add packageManager field (Corepack standard)
  Iif (packageManager === 'pnpm') {
    base.packageManager = 'pnpm@9.0.0';
  } else Iif (packageManager === 'yarn') {
    base.packageManager = 'yarn@4.0.0';
  }
 
  // Runtime dependencies
  const runtimeDeps = getRuntimeDependencies(runtime);
  Object.assign(base.dependencies, runtimeDeps);
 
  // Database dependencies
  if (database) {
    const { dependencies: dbDeps } = generateDatabaseScaffolding(database, language);
    Object.assign(base.dependencies, dbDeps);
  }
 
  // Auth dependencies
  if (auth) {
    const { dependencies: authDeps } = generateAuthScaffolding(auth, runtime, language);
    Object.assign(base.dependencies, authDeps);
  }
 
  // Optional package dependencies
  if (packages.length > 0) {
    const { dependencies: pkgDeps } = generatePackageScaffolding(packages);
    Object.assign(base.dependencies, pkgDeps);
  }
 
  return base;
}
 
/**
 * Generate HomePage component
 */
async function generateHomePageComponent(projectPath, name, isTypeScript, fileExtension) {
  const homePage = isTypeScript ? `/**
 * HomePage Component
 */
interface HomePageProps {
  title?: string;
}
 
export function HomePage(props: HomePageProps = {}): object {
  const { title = 'Welcome to ${name}!' } = props;
 
  return {
    div: {
      className: 'container',
      children: [
        { h1: { text: title } },
        {
          p: {
            text: 'This is a Coherent.js application built with pure JavaScript objects.'
          }
        },
        {
          div: {
            className: 'features',
            children: [
              { h2: { text: 'Features:' } },
              {
                ul: {
                  children: [
                    { li: { text: '⚡ Lightning fast SSR' } },
                    { li: { text: '🎯 Pure JavaScript objects' } },
                    { li: { text: '🔒 Built-in XSS protection' } },
                    { li: { text: '📦 Minimal bundle size' } },
                    { li: { text: '📘 TypeScript support' } }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  };
}
` : `/**
 * HomePage Component
 */
export function HomePage(props = {}) {
  const { title = 'Welcome to ${name}!' } = props;
 
  return {
    div: {
      className: 'container',
      children: [
        { h1: { text: title } },
        {
          p: {
            text: 'This is a Coherent.js application built with pure JavaScript objects.'
          }
        },
        {
          div: {
            className: 'features',
            children: [
              { h2: { text: 'Features:' } },
              {
                ul: {
                  children: [
                    { li: { text: '⚡ Lightning fast SSR' } },
                    { li: { text: '🎯 Pure JavaScript objects' } },
                    { li: { text: '🔒 Built-in XSS protection' } },
                    { li: { text: '📦 Minimal bundle size' } }
                  ]
                }
              }
            ]
          }
        }
      ]
    }
  };
}
`;
 
  writeFileSync(join(projectPath, `src/components/HomePage${fileExtension}`), homePage);
 
  // Simple Button component example
  const buttonComponent = isTypeScript ? `/**
 * Button Component
 */
interface ButtonProps {
  text?: string;
  onClick?: () => void;
  className?: string;
}
 
export function Button(props: ButtonProps = {}): object {
  const { text = 'Click me', onClick, className = '' } = props;
 
  return {
    button: {
      className: \`btn \${className}\`,
      onclick: onClick,
      text
    }
  };
}
` : `/**
 * Button Component
 */
export function Button(props = {}) {
  const { text = 'Click me', onClick, className = '' } = props;
 
  return {
    button: {
      className: \`btn \${className}\`,
      onclick: onClick,
      text
    }
  };
}
`;
 
  writeFileSync(join(projectPath, `src/components/Button${fileExtension}`), buttonComponent);
}
 
/**
 * Generate common files (README, gitignore, etc.)
 */
function generateCommonFiles(projectPath, name, options = {}) {
  const { fileExtension = '.js', packageManager = 'npm', hasApi = false } = options;
  const runCmd = packageManager === 'npm' ? 'npm run' : packageManager;
 
  // README.md
  const readme = `# ${name}
 
A Coherent.js application built with pure JavaScript objects.
 
## Getting Started
 
\`\`\`bash
# Install dependencies
${packageManager} install
 
# Start development server
${runCmd} dev
 
# Build for production
${runCmd} build
 
# Run tests
${packageManager} test
\`\`\`
 
## Project Structure
 
\`\`\`
src/
  components/     # Reusable components
  pages/         # Page components
${hasApi ? `  api/           # API routes
` : ''}  utils/         # Utility functions
  index${fileExtension}       # Main entry point
public/          # Static assets
tests/           # Test files
\`\`\`
 
## Learn More
 
- [Coherent.js Documentation](https://github.com/Tomdrouv1/coherent.js)
- [API Reference](https://github.com/Tomdrouv1/coherent.js/blob/main/docs/api/reference.md)
 
## License
 
MIT
`;
 
  writeFileSync(join(projectPath, 'README.md'), readme);
 
  // .gitignore
  const gitignore = `# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
 
# Production builds
dist/
build/
 
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
 
# Runtime data
pids
*.pid
*.seed
*.pid.lock
 
# Coverage directory used by tools like istanbul
coverage/
*.lcov
 
# nyc test coverage
.nyc_output
 
# IDE files
.vscode/
.idea/
*.swp
*.swo
*~
 
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
 
# Logs
logs
*.log
 
# Optional npm cache directory
.npm
 
# Optional REPL history
.node_repl_history
`;
 
  writeFileSync(join(projectPath, '.gitignore'), gitignore);
 
  // Basic test file
  const testFile = `import { describe, it, expect } from 'vitest';
import { render } from '@coherent.js/core';
 
describe('Basic Component Rendering', () => {
  it('renders basic component', () => {
    const component = {
      div: {
        text: 'Hello, World!'
      }
    };
 
    const html = render(component);
    expect(html).toContain('Hello, World!');
  });
});`;
 
  writeFileSync(join(projectPath, `tests/basic.test${fileExtension}`), testFile);
}