create-fs-app 1.1.10 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +340 -57
  2. package/dist/core/health-check.d.ts +15 -0
  3. package/dist/core/health-check.js +138 -0
  4. package/dist/core/health-check.js.map +1 -0
  5. package/dist/core/presets.d.ts +48 -0
  6. package/dist/core/presets.js +220 -0
  7. package/dist/core/presets.js.map +1 -0
  8. package/dist/core/registry-fetch.d.ts +20 -0
  9. package/dist/core/registry-fetch.js +121 -0
  10. package/dist/core/registry-fetch.js.map +1 -0
  11. package/dist/core/scaffold.d.ts +40 -0
  12. package/dist/core/scaffold.js +104 -0
  13. package/dist/core/scaffold.js.map +1 -0
  14. package/dist/core/template-cache.d.ts +38 -0
  15. package/dist/core/template-cache.js +233 -0
  16. package/dist/core/template-cache.js.map +1 -0
  17. package/dist/core/template-clone.d.ts +27 -0
  18. package/dist/core/template-clone.js +808 -0
  19. package/dist/core/template-clone.js.map +1 -0
  20. package/dist/core/template-list.d.ts +45 -0
  21. package/dist/core/template-list.js +191 -0
  22. package/dist/core/template-list.js.map +1 -0
  23. package/dist/core/template-registry.d.ts +78 -0
  24. package/dist/core/template-registry.js +238 -0
  25. package/dist/core/template-registry.js.map +1 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +964 -0
  28. package/dist/index.js.bak +872 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/types/index.d.ts +102 -0
  31. package/dist/types/index.js +85 -0
  32. package/dist/types/index.js.map +1 -0
  33. package/dist/utils/errors.d.ts +15 -0
  34. package/dist/utils/errors.js +50 -0
  35. package/dist/utils/errors.js.map +1 -0
  36. package/dist/utils/logger.d.ts +37 -0
  37. package/dist/utils/logger.js +62 -0
  38. package/dist/utils/logger.js.map +1 -0
  39. package/dist/utils/validation.d.ts +48 -0
  40. package/dist/utils/validation.js +100 -0
  41. package/dist/utils/validation.js.map +1 -0
  42. package/package.json +81 -35
  43. package/.github/workflows/npm-publish-github-packages.yml +0 -36
  44. package/SECURITY.md +0 -21
  45. package/assets/logo.png +0 -0
  46. package/assets/s1.png +0 -0
  47. package/create-fs-app.js +0 -181
@@ -0,0 +1,808 @@
1
+ /**
2
+ * Template Cloning and Customization
3
+ * Handles downloading templates and customizing them for the user
4
+ */
5
+ import { execa } from 'execa';
6
+ import fs from 'fs/promises';
7
+ import path from 'path';
8
+ import os from 'os';
9
+ import { randomUUID } from 'crypto';
10
+ import { Logger } from '../utils/logger.js';
11
+ import { getCachedTemplatePath, cacheTemplate, copyCachedTemplate } from './template-cache.js';
12
+ /**
13
+ * Clone a template repository (with caching support)
14
+ */
15
+ export async function cloneTemplate(template, targetDir, branch = 'main', skipCache = false) {
16
+ const { url, subfolder, localPath } = template;
17
+ try {
18
+ // If it's a local template, just copy it
19
+ if (localPath) {
20
+ Logger.verbose(`Using local template from: ${localPath}`);
21
+ // Check if local template exists
22
+ try {
23
+ await fs.access(localPath);
24
+ }
25
+ catch {
26
+ throw new Error(`Local template not found at: ${localPath}`);
27
+ }
28
+ // Copy local template to target
29
+ await fs.cp(localPath, targetDir, { recursive: true });
30
+ return;
31
+ }
32
+ // Check if template is cached (skipped when --no-cache is passed)
33
+ if (!skipCache) {
34
+ const cachedPath = await getCachedTemplatePath(template);
35
+ if (cachedPath) {
36
+ Logger.verbose('Using cached template');
37
+ await copyCachedTemplate(cachedPath, targetDir);
38
+ return;
39
+ }
40
+ }
41
+ Logger.verbose(skipCache ? 'Cache skipped, downloading fresh copy...' : 'Template not cached, downloading...');
42
+ if (subfolder && url) {
43
+ // Clone entire repo to temp directory, then copy specific subfolder
44
+ // Use UUID to prevent race conditions with simultaneous runs
45
+ const tempDir = path.join(os.tmpdir(), `.cfs-temp-${randomUUID()}`);
46
+ try {
47
+ // Clone with shallow depth for speed
48
+ await execa('git', [
49
+ 'clone',
50
+ '--depth',
51
+ '1',
52
+ '--branch',
53
+ branch,
54
+ '--single-branch',
55
+ url,
56
+ tempDir
57
+ ]);
58
+ // Copy the specific subfolder to target directory
59
+ const templatePath = path.join(tempDir, subfolder);
60
+ // Check if the subfolder exists
61
+ try {
62
+ await fs.access(templatePath);
63
+ }
64
+ catch {
65
+ throw new Error(`Template subfolder "${subfolder}" not found in repository`);
66
+ }
67
+ // Copy the template folder contents to target
68
+ await fs.cp(templatePath, targetDir, { recursive: true });
69
+ // Cache the template for future use (skipped when --no-cache)
70
+ if (!skipCache) {
71
+ Logger.verbose('Caching template for future use...');
72
+ await cacheTemplate(template, branch).catch(() => {
73
+ Logger.warn('Failed to cache template, continuing anyway');
74
+ });
75
+ }
76
+ // Clean up temp directory
77
+ await fs.rm(tempDir, { recursive: true, force: true });
78
+ }
79
+ catch (error) {
80
+ // Clean up temp directory on error
81
+ try {
82
+ await fs.rm(tempDir, { recursive: true, force: true });
83
+ }
84
+ catch { }
85
+ throw error;
86
+ }
87
+ }
88
+ else if (url) {
89
+ // Direct clone (for individual template repositories)
90
+ await execa('git', [
91
+ 'clone',
92
+ '--depth',
93
+ '1',
94
+ '--branch',
95
+ branch,
96
+ url,
97
+ targetDir
98
+ ]);
99
+ // Remove .git directory to start fresh
100
+ const gitDir = path.join(targetDir, '.git');
101
+ await fs.rm(gitDir, { recursive: true, force: true });
102
+ // Cache the template (skipped when --no-cache)
103
+ if (!skipCache) {
104
+ Logger.verbose('Caching template for future use...');
105
+ await cacheTemplate(template, branch).catch(() => {
106
+ Logger.warn('Failed to cache template, continuing anyway');
107
+ });
108
+ }
109
+ }
110
+ }
111
+ catch (error) {
112
+ throw new Error(`Failed to clone template: ${error instanceof Error ? error.message : 'Unknown error'}`);
113
+ }
114
+ }
115
+ /**
116
+ * Customize the cloned template with user's configuration
117
+ */
118
+ export async function customizeTemplate(targetDir, config) {
119
+ // 1. Update package.json with project name + packageManager field
120
+ await updatePackageJson(targetDir, config);
121
+ // 2. Replace placeholders in files
122
+ await replacePlaceholders(targetDir, config);
123
+ // 3. Update README with project-specific info
124
+ await updateReadme(targetDir, config);
125
+ // 4. Handle optional features (remove if not selected)
126
+ await handleOptionalFeatures(targetDir, config);
127
+ // 5. Update environment variables template
128
+ await updateEnvTemplate(targetDir, config);
129
+ // 6. Fix workspace protocol for pnpm
130
+ // Templates ship with "@repo/*": "*" (npm-style).
131
+ // pnpm requires "workspace:*" — without it pnpm tries the npm registry → 404.
132
+ if (config.packageManager === 'pnpm') {
133
+ await fixWorkspaceProtocol(targetDir);
134
+ }
135
+ }
136
+ /**
137
+ * Detect the installed version of a package manager.
138
+ * Returns e.g. "pnpm@9.15.0" or falls back to a safe default.
139
+ */
140
+ async function detectPackageManagerVersion(pm) {
141
+ try {
142
+ const result = await execa(pm, ['--version']);
143
+ const version = result.stdout.trim();
144
+ return `${pm}@${version}`;
145
+ }
146
+ catch {
147
+ // Fallback versions if detection fails
148
+ const defaults = {
149
+ pnpm: 'pnpm@9.0.0',
150
+ yarn: 'yarn@1.22.22',
151
+ npm: 'npm@10.0.0',
152
+ };
153
+ return defaults[pm] ?? `${pm}@latest`;
154
+ }
155
+ }
156
+ /**
157
+ * Update root and nested package.json files.
158
+ * Also fixes the `packageManager` field in the root to match the user's choice.
159
+ */
160
+ async function updatePackageJson(targetDir, config) {
161
+ const pm = config.packageManager;
162
+ const pmVersion = await detectPackageManagerVersion(pm);
163
+ const packageJsonPaths = [
164
+ path.join(targetDir, 'package.json'),
165
+ path.join(targetDir, 'apps', 'frontend', 'package.json'),
166
+ path.join(targetDir, 'apps', 'backend', 'package.json'),
167
+ ];
168
+ for (const pkgPath of packageJsonPaths) {
169
+ try {
170
+ const pkgContent = await fs.readFile(pkgPath, 'utf-8');
171
+ const pkg = JSON.parse(pkgContent);
172
+ // Update name based on location
173
+ if (pkgPath.includes('frontend')) {
174
+ pkg.name = `${config.name}-frontend`;
175
+ }
176
+ else if (pkgPath.includes('backend')) {
177
+ pkg.name = `${config.name}-backend`;
178
+ }
179
+ else {
180
+ pkg.name = config.name;
181
+ // Fix the packageManager field in root package.json only
182
+ pkg.packageManager = pmVersion;
183
+ // Write both formats so the project works across pnpm 9/10/11.
184
+ // pnpm 9/10: onlyBuiltDependencies (array of names)
185
+ // pnpm 11: allowBuilds (object map name → true)
186
+ if (pm === 'pnpm') {
187
+ const allowed = buildAllowList(config);
188
+ const allowBuildsMap = Object.fromEntries(allowed.map(n => [n, true]));
189
+ pkg.pnpm = {
190
+ ...(pkg.pnpm ?? {}),
191
+ onlyBuiltDependencies: allowed, // pnpm 9/10
192
+ allowBuilds: allowBuildsMap, // pnpm 11
193
+ };
194
+ }
195
+ }
196
+ // Update description
197
+ pkg.description = `${config.name} - Full-stack application`;
198
+ await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
199
+ }
200
+ catch {
201
+ // File might not exist, that's okay
202
+ continue;
203
+ }
204
+ }
205
+ // pnpm-workspace.yaml — workspace discovery + build-script allowlist.
206
+ //
207
+ // pnpm changed the config key across major versions:
208
+ // pnpm 9: package.json pnpm.onlyBuiltDependencies (array of names)
209
+ // pnpm 10: package.json pnpm.onlyBuiltDependencies (array of names)
210
+ // pnpm-workspace.yaml onlyBuiltDependencies (array of names)
211
+ // pnpm 11: pnpm-workspace.yaml allowBuilds (map name→true)
212
+ //
213
+ // We write BOTH formats so the project works on pnpm 9/10/11.
214
+ if (pm === 'pnpm') {
215
+ const workspaceFile = path.join(targetDir, 'pnpm-workspace.yaml');
216
+ const allowed = buildAllowList(config);
217
+ // pnpm 11 format: allowBuilds map (name → true)
218
+ const allowBuildsMap = allowed.map(p => ` "${p}": true`).join('\n');
219
+ // pnpm 9/10 format: onlyBuiltDependencies list
220
+ const onlyBuiltList = allowed.map(p => ` - "${p}"`).join('\n');
221
+ const content = [
222
+ 'packages:',
223
+ ' - "apps/*"',
224
+ ' - "packages/*"',
225
+ '',
226
+ '# pnpm 11+: allowBuilds map (package name → true/false)',
227
+ 'allowBuilds:',
228
+ allowBuildsMap,
229
+ '',
230
+ '# pnpm 9/10: onlyBuiltDependencies list (kept for older pnpm compat)',
231
+ 'onlyBuiltDependencies:',
232
+ onlyBuiltList,
233
+ '',
234
+ ].join('\n');
235
+ await fs.writeFile(workspaceFile, content);
236
+ }
237
+ }
238
+ /**
239
+ * Packages that need to run postinstall/build scripts.
240
+ * Listed in both package.json (pnpm <10) and pnpm-workspace.yaml (pnpm 10+).
241
+ *
242
+ * Discovery process: scaffold each template combination with --no-install,
243
+ * run `pnpm install`, and collect ERR_PNPM_IGNORED_BUILDS output.
244
+ *
245
+ * Results per stack:
246
+ * All templates → sharp, unrs-resolver, esbuild
247
+ * Prisma templates → @prisma/engines, prisma
248
+ * NestJS templates → @nestjs/core, @scarf/scarf
249
+ * (@scarf/scarf is NestJS's telemetry runner)
250
+ * Express templates → no additional packages
251
+ */
252
+ function buildAllowList(config) {
253
+ const list = [
254
+ 'sharp', // Next.js image optimisation (all templates)
255
+ 'unrs-resolver', // Rust-based module resolver (all templates)
256
+ 'esbuild', // Build tool used across the stack (all templates)
257
+ ];
258
+ if (config.apps.backend.orm === 'prisma') {
259
+ list.push('@prisma/engines', 'prisma');
260
+ }
261
+ if (config.apps.backend.framework === 'nest.js') {
262
+ list.push('@nestjs/core', '@scarf/scarf');
263
+ }
264
+ return list;
265
+ }
266
+ /**
267
+ * Replace placeholder variables in all files
268
+ * Placeholders: {{PROJECT_NAME}}, {{FRONTEND_FRAMEWORK}}, etc.
269
+ */
270
+ async function replacePlaceholders(targetDir, config) {
271
+ const placeholders = {
272
+ '{{PROJECT_NAME}}': config.name,
273
+ '{{FRONTEND_FRAMEWORK}}': config.apps.frontend.framework,
274
+ '{{BACKEND_FRAMEWORK}}': config.apps.backend.framework,
275
+ '{{DATABASE}}': config.apps.backend.database,
276
+ '{{ORM}}': config.apps.backend.orm || 'none',
277
+ '{{PACKAGE_MANAGER}}': config.packageManager,
278
+ '{{MONOREPO_FRAMEWORK}}': config.monorepo,
279
+ // Scoped package names use 'my-app' as safe placeholder ({{}} invalid in npm names)
280
+ '@my-app/': `@${config.name}/`,
281
+ '"name": "my-app"': `"name": "${config.name}"`,
282
+ };
283
+ // Only process text files with these extensions for performance
284
+ const TEXT_EXTENSIONS = ['.md', '.json', '.ts', '.tsx', '.js', '.jsx', '.env', '.example', '.yml', '.yaml'];
285
+ async function processFile(filePath) {
286
+ try {
287
+ // Skip non-text files for performance
288
+ const hasTextExtension = TEXT_EXTENSIONS.some(ext => filePath.endsWith(ext));
289
+ if (!hasTextExtension)
290
+ return;
291
+ let content = await fs.readFile(filePath, 'utf-8');
292
+ let modified = false;
293
+ // Use simple string replacement instead of regex to avoid issues with special characters
294
+ for (const [placeholder, value] of Object.entries(placeholders)) {
295
+ if (content.includes(placeholder)) {
296
+ content = content.split(placeholder).join(value);
297
+ modified = true;
298
+ }
299
+ }
300
+ if (modified) {
301
+ await fs.writeFile(filePath, content);
302
+ }
303
+ }
304
+ catch (error) {
305
+ // Skip files that can't be read as text
306
+ }
307
+ }
308
+ async function walkDir(dir) {
309
+ const entries = await fs.readdir(dir, { withFileTypes: true });
310
+ for (const entry of entries) {
311
+ const fullPath = path.join(dir, entry.name);
312
+ // Skip node_modules and .git
313
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'dist') {
314
+ continue;
315
+ }
316
+ if (entry.isDirectory()) {
317
+ await walkDir(fullPath);
318
+ }
319
+ else if (entry.isFile()) {
320
+ await processFile(fullPath);
321
+ }
322
+ }
323
+ }
324
+ await walkDir(targetDir);
325
+ }
326
+ /**
327
+ * Update README with project-specific information
328
+ */
329
+ async function updateReadme(targetDir, config) {
330
+ const readmePath = path.join(targetDir, 'README.md');
331
+ try {
332
+ let readme = await fs.readFile(readmePath, 'utf-8');
333
+ // Add project name as title if not already there
334
+ if (!readme.startsWith(`# ${config.name}`)) {
335
+ const techStack = `
336
+ ## Tech Stack
337
+
338
+ | Layer | Choice |
339
+ |-----------------|--------|
340
+ | Monorepo | ${config.monorepo} |
341
+ | Frontend | ${config.apps.frontend.framework} |
342
+ | Styling | ${config.apps.frontend.styling} |
343
+ | Backend | ${config.apps.backend.framework} |
344
+ | Database | ${config.apps.backend.database} |
345
+ | ORM | ${config.apps.backend.orm || 'none'} |
346
+ | API style | ${config.apps.backend.apiStyle} |
347
+ | Auth | ${config.apps.backend.auth} |
348
+ | Package manager | ${config.packageManager} |
349
+ | ESLint | ${config.apps.frontend.eslint ? '✓' : '✗'} |
350
+ | Prettier | ${config.apps.frontend.prettier ? '✓' : '✗'} |
351
+ | Turbopack | ${config.apps.frontend.turbopack ? '✓' : '✗'} |
352
+ | Docker | ${config.apps.backend.docker ? '✓' : '✗'} |
353
+ | GitHub Actions | ${config.ci ? '✓' : '✗'} |
354
+
355
+ `;
356
+ readme = `# ${config.name}\n\n${techStack}${readme}`;
357
+ }
358
+ await fs.writeFile(readmePath, readme);
359
+ }
360
+ catch (error) {
361
+ // README might not exist
362
+ }
363
+ }
364
+ /**
365
+ * Handle optional features - remove config for unselected features,
366
+ * patch files for enabled ones (Turbopack, CI, JWT auth).
367
+ */
368
+ async function handleOptionalFeatures(targetDir, config) {
369
+ // ── Docker ────────────────────────────────────────────────────────────────
370
+ if (!config.apps.backend.docker) {
371
+ const dockerFiles = [
372
+ path.join(targetDir, 'Dockerfile'),
373
+ path.join(targetDir, 'docker-compose.yml'),
374
+ path.join(targetDir, '.dockerignore'),
375
+ path.join(targetDir, 'apps', 'backend', 'Dockerfile'),
376
+ path.join(targetDir, 'apps', 'frontend', 'Dockerfile'),
377
+ ];
378
+ for (const file of dockerFiles) {
379
+ try {
380
+ await fs.unlink(file);
381
+ }
382
+ catch { /* ok */ }
383
+ }
384
+ }
385
+ // ── ESLint ────────────────────────────────────────────────────────────────
386
+ if (!config.apps.frontend.eslint) {
387
+ const eslintFiles = [
388
+ path.join(targetDir, 'eslint.config.mjs'),
389
+ path.join(targetDir, '.eslintrc.json'),
390
+ path.join(targetDir, '.eslintrc.js'),
391
+ path.join(targetDir, 'apps', 'frontend', 'eslint.config.mjs'),
392
+ path.join(targetDir, 'apps', 'frontend', '.eslintrc.json'),
393
+ path.join(targetDir, 'apps', 'backend', 'eslint.config.mjs'),
394
+ path.join(targetDir, 'apps', 'backend', '.eslintrc.json'),
395
+ ];
396
+ for (const file of eslintFiles) {
397
+ try {
398
+ await fs.unlink(file);
399
+ }
400
+ catch { /* ok */ }
401
+ }
402
+ }
403
+ // ── Prettier ──────────────────────────────────────────────────────────────
404
+ if (!config.apps.frontend.prettier) {
405
+ const prettierFiles = [
406
+ path.join(targetDir, '.prettierrc'),
407
+ path.join(targetDir, '.prettierrc.json'),
408
+ path.join(targetDir, '.prettierignore'),
409
+ path.join(targetDir, 'apps', 'frontend', '.prettierrc'),
410
+ path.join(targetDir, 'apps', 'backend', '.prettierrc'),
411
+ ];
412
+ for (const file of prettierFiles) {
413
+ try {
414
+ await fs.unlink(file);
415
+ }
416
+ catch { /* ok */ }
417
+ }
418
+ }
419
+ // ── Turbopack (Next.js) ───────────────────────────────────────────────────
420
+ if (config.apps.frontend.turbopack && config.apps.frontend.framework === 'next.js') {
421
+ const frontendPkgPath = path.join(targetDir, 'apps', 'frontend', 'package.json');
422
+ try {
423
+ const raw = await fs.readFile(frontendPkgPath, 'utf-8');
424
+ const pkg = JSON.parse(raw);
425
+ if (pkg.scripts?.dev && !pkg.scripts.dev.includes('--turbopack')) {
426
+ pkg.scripts.dev = pkg.scripts.dev.replace('next dev', 'next dev --turbopack');
427
+ await fs.writeFile(frontendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
428
+ }
429
+ }
430
+ catch { /* package.json missing — skip */ }
431
+ }
432
+ // ── GitHub Actions CI ─────────────────────────────────────────────────────
433
+ if (config.ci) {
434
+ await generateCiWorkflow(targetDir, config);
435
+ }
436
+ // ── JWT auth scaffolding ──────────────────────────────────────────────────
437
+ if (config.apps.backend.auth === 'jwt') {
438
+ await generateJwtAuth(targetDir, config);
439
+ }
440
+ }
441
+ // ─── CI workflow generator ────────────────────────────────────────────────────
442
+ async function generateCiWorkflow(targetDir, config) {
443
+ const workflowDir = path.join(targetDir, '.github', 'workflows');
444
+ await fs.mkdir(workflowDir, { recursive: true });
445
+ const pm = config.packageManager;
446
+ const installCmd = pm === 'npm' ? 'npm ci' : pm === 'yarn' ? 'yarn install --frozen-lockfile' : 'pnpm install --frozen-lockfile';
447
+ const lintCmd = `${pm} run lint`;
448
+ const buildCmd = `${pm} run build`;
449
+ const workflow = `name: CI
450
+
451
+ on:
452
+ push:
453
+ branches: [main, master]
454
+ pull_request:
455
+ branches: [main, master]
456
+
457
+ jobs:
458
+ build:
459
+ runs-on: ubuntu-latest
460
+
461
+ steps:
462
+ - uses: actions/checkout@v4
463
+
464
+ - name: Set up Node.js
465
+ uses: actions/setup-node@v4
466
+ with:
467
+ node-version: '20'
468
+ cache: '${pm}'
469
+
470
+ - name: Install dependencies
471
+ run: ${installCmd}
472
+ ${config.apps.frontend.eslint ? `
473
+ - name: Lint
474
+ run: ${lintCmd}
475
+ ` : ''}
476
+ - name: Build
477
+ run: ${buildCmd}
478
+ `;
479
+ await fs.writeFile(path.join(workflowDir, 'ci.yml'), workflow);
480
+ }
481
+ // ─── JWT auth scaffolding ─────────────────────────────────────────────────────
482
+ async function generateJwtAuth(targetDir, config) {
483
+ const framework = config.apps.backend.framework;
484
+ if (framework === 'nest.js') {
485
+ await generateNestJwtAuth(targetDir);
486
+ }
487
+ else {
488
+ // Express / Fastify / Koa — generic middleware approach
489
+ await generateGenericJwtAuth(targetDir, framework);
490
+ }
491
+ }
492
+ async function generateNestJwtAuth(targetDir) {
493
+ const authDir = path.join(targetDir, 'apps', 'backend', 'src', 'auth');
494
+ await fs.mkdir(authDir, { recursive: true });
495
+ // auth.module.ts
496
+ await fs.writeFile(path.join(authDir, 'auth.module.ts'), `import { Module } from '@nestjs/common';
497
+ import { JwtModule } from '@nestjs/jwt';
498
+ import { PassportModule } from '@nestjs/passport';
499
+ import { AuthService } from './auth.service';
500
+ import { AuthController } from './auth.controller';
501
+ import { JwtStrategy } from './jwt.strategy';
502
+
503
+ @Module({
504
+ imports: [
505
+ PassportModule,
506
+ JwtModule.register({
507
+ secret: process.env.JWT_SECRET || 'change-me',
508
+ signOptions: { expiresIn: '7d' },
509
+ }),
510
+ ],
511
+ providers: [AuthService, JwtStrategy],
512
+ controllers: [AuthController],
513
+ exports: [AuthService],
514
+ })
515
+ export class AuthModule {}
516
+ `);
517
+ // auth.service.ts
518
+ await fs.writeFile(path.join(authDir, 'auth.service.ts'), `import { Injectable, UnauthorizedException } from '@nestjs/common';
519
+ import { JwtService } from '@nestjs/jwt';
520
+
521
+ export interface JwtPayload {
522
+ sub: string;
523
+ email: string;
524
+ }
525
+
526
+ @Injectable()
527
+ export class AuthService {
528
+ constructor(private readonly jwtService: JwtService) {}
529
+
530
+ async login(userId: string, email: string): Promise<{ access_token: string }> {
531
+ const payload: JwtPayload = { sub: userId, email };
532
+ return { access_token: this.jwtService.sign(payload) };
533
+ }
534
+
535
+ async verifyToken(token: string): Promise<JwtPayload> {
536
+ try {
537
+ return this.jwtService.verify<JwtPayload>(token);
538
+ } catch {
539
+ throw new UnauthorizedException('Invalid or expired token');
540
+ }
541
+ }
542
+ }
543
+ `);
544
+ // jwt.strategy.ts
545
+ await fs.writeFile(path.join(authDir, 'jwt.strategy.ts'), `import { Injectable } from '@nestjs/common';
546
+ import { PassportStrategy } from '@nestjs/passport';
547
+ import { ExtractJwt, Strategy } from 'passport-jwt';
548
+ import { JwtPayload } from './auth.service';
549
+
550
+ @Injectable()
551
+ export class JwtStrategy extends PassportStrategy(Strategy) {
552
+ constructor() {
553
+ super({
554
+ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
555
+ ignoreExpiration: false,
556
+ secretOrKey: process.env.JWT_SECRET || 'change-me',
557
+ });
558
+ }
559
+
560
+ async validate(payload: JwtPayload) {
561
+ return { userId: payload.sub, email: payload.email };
562
+ }
563
+ }
564
+ `);
565
+ // jwt-auth.guard.ts
566
+ await fs.writeFile(path.join(authDir, 'jwt-auth.guard.ts'), `import { Injectable } from '@nestjs/common';
567
+ import { AuthGuard } from '@nestjs/passport';
568
+
569
+ @Injectable()
570
+ export class JwtAuthGuard extends AuthGuard('jwt') {}
571
+ `);
572
+ // auth.controller.ts (login endpoint stub)
573
+ await fs.writeFile(path.join(authDir, 'auth.controller.ts'), `import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
574
+ import { ApiTags, ApiOperation } from '@nestjs/swagger';
575
+ import { AuthService } from './auth.service';
576
+ import { IsEmail, IsString, MinLength } from 'class-validator';
577
+
578
+ export class LoginDto {
579
+ @IsEmail()
580
+ email!: string;
581
+
582
+ @IsString()
583
+ @MinLength(6)
584
+ password!: string;
585
+ }
586
+
587
+ @ApiTags('auth')
588
+ @Controller('auth')
589
+ export class AuthController {
590
+ constructor(private readonly authService: AuthService) {}
591
+
592
+ /** POST /auth/login — returns a signed JWT */
593
+ @Post('login')
594
+ @HttpCode(HttpStatus.OK)
595
+ @ApiOperation({ summary: 'Log in and receive a JWT' })
596
+ async login(@Body() dto: LoginDto) {
597
+ // TODO: validate credentials against DB, then:
598
+ // return this.authService.login(user.id, user.email);
599
+ return this.authService.login('placeholder-id', dto.email);
600
+ }
601
+ }
602
+ `);
603
+ // Append JWT_SECRET to .env.example if present
604
+ const envExample = path.join(targetDir, 'apps', 'backend', '.env.example');
605
+ try {
606
+ let env = await fs.readFile(envExample, 'utf-8');
607
+ if (!env.includes('JWT_SECRET')) {
608
+ env += '\n# JWT\nJWT_SECRET=change-me-in-production\n';
609
+ await fs.writeFile(envExample, env);
610
+ }
611
+ }
612
+ catch { /* file missing — skip */ }
613
+ // Add JWT-related packages to backend package.json
614
+ const backendPkgPath = path.join(targetDir, 'apps', 'backend', 'package.json');
615
+ try {
616
+ const raw = await fs.readFile(backendPkgPath, 'utf-8');
617
+ const pkg = JSON.parse(raw);
618
+ pkg.dependencies = pkg.dependencies ?? {};
619
+ pkg.dependencies['@nestjs/jwt'] = '^10.2.0';
620
+ pkg.dependencies['@nestjs/passport'] = '^10.0.3';
621
+ pkg.dependencies['passport'] = '^0.7.0';
622
+ pkg.dependencies['passport-jwt'] = '^4.0.1';
623
+ pkg.devDependencies = pkg.devDependencies ?? {};
624
+ pkg.devDependencies['@types/passport-jwt'] = '^4.0.1';
625
+ await fs.writeFile(backendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
626
+ }
627
+ catch { /* backend package.json missing */ }
628
+ // Wire AuthModule into AppModule
629
+ const appModulePath = path.join(targetDir, 'apps', 'backend', 'src', 'app.module.ts');
630
+ try {
631
+ let appModule = await fs.readFile(appModulePath, 'utf-8');
632
+ if (!appModule.includes('AuthModule')) {
633
+ // Add import statement after the last import line
634
+ appModule = appModule.replace(/^(import .+;\n)(?!import)/m, `$1import { AuthModule } from './auth/auth.module';\n`);
635
+ // Add AuthModule to imports array
636
+ appModule = appModule.replace(/imports:\s*\[/, 'imports: [\n AuthModule,');
637
+ await fs.writeFile(appModulePath, appModule);
638
+ }
639
+ }
640
+ catch { /* app.module.ts not present in template */ }
641
+ }
642
+ async function generateGenericJwtAuth(targetDir, framework) {
643
+ const middlewareDir = path.join(targetDir, 'apps', 'backend', 'src', 'middleware');
644
+ await fs.mkdir(middlewareDir, { recursive: true });
645
+ await fs.writeFile(path.join(middlewareDir, 'jwt.middleware.ts'), `/**
646
+ * Generic JWT middleware — works with Express, Fastify, Koa.
647
+ * Install: npm i jsonwebtoken @types/jsonwebtoken
648
+ */
649
+ import jwt from 'jsonwebtoken';
650
+
651
+ const JWT_SECRET = process.env.JWT_SECRET || 'change-me';
652
+
653
+ export interface JwtPayload {
654
+ sub: string;
655
+ email: string;
656
+ iat?: number;
657
+ exp?: number;
658
+ }
659
+
660
+ /** Sign a payload — call after validating credentials */
661
+ export function signToken(payload: Omit<JwtPayload, 'iat' | 'exp'>): string {
662
+ return jwt.sign(payload, JWT_SECRET, { expiresIn: '7d' });
663
+ }
664
+
665
+ /** Verify a token — throws if invalid or expired */
666
+ export function verifyToken(token: string): JwtPayload {
667
+ return jwt.verify(token, JWT_SECRET) as JwtPayload;
668
+ }
669
+
670
+ /** Express/Koa-style auth middleware */
671
+ export function requireAuth(req: any, res: any, next: any) {
672
+ const header = req.headers?.authorization ?? '';
673
+ const token = header.startsWith('Bearer ') ? header.slice(7) : null;
674
+
675
+ if (!token) {
676
+ return res.status(401).json({ message: 'Missing Authorization header' });
677
+ }
678
+
679
+ try {
680
+ req.user = verifyToken(token);
681
+ next();
682
+ } catch {
683
+ return res.status(401).json({ message: 'Invalid or expired token' });
684
+ }
685
+ }
686
+ `);
687
+ // Append JWT_SECRET to .env.example if present
688
+ const envExample = path.join(targetDir, 'apps', 'backend', '.env.example');
689
+ try {
690
+ let env = await fs.readFile(envExample, 'utf-8');
691
+ if (!env.includes('JWT_SECRET')) {
692
+ env += '\n# JWT\nJWT_SECRET=change-me-in-production\n';
693
+ await fs.writeFile(envExample, env);
694
+ }
695
+ }
696
+ catch { /* file missing — skip */ }
697
+ // Add jsonwebtoken to backend package.json
698
+ const backendPkgPath = path.join(targetDir, 'apps', 'backend', 'package.json');
699
+ try {
700
+ const raw = await fs.readFile(backendPkgPath, 'utf-8');
701
+ const pkg = JSON.parse(raw);
702
+ pkg.dependencies = pkg.dependencies ?? {};
703
+ pkg.dependencies['jsonwebtoken'] = '^9.0.2';
704
+ pkg.devDependencies = pkg.devDependencies ?? {};
705
+ pkg.devDependencies['@types/jsonwebtoken'] = '^9.0.7';
706
+ await fs.writeFile(backendPkgPath, JSON.stringify(pkg, null, 2) + '\n');
707
+ }
708
+ catch { /* backend package.json missing */ }
709
+ }
710
+ /**
711
+ * Rewrite "@repo/*": "*" → "@repo/*": "workspace:*" in every package.json.
712
+ *
713
+ * Templates ship with npm-style "*" for local workspace packages.
714
+ * pnpm requires the explicit "workspace:*" protocol — without it pnpm treats
715
+ * the dependency as an npm package and fails with a 404.
716
+ */
717
+ async function fixWorkspaceProtocol(targetDir) {
718
+ async function walkDir(dir) {
719
+ const entries = await fs.readdir(dir, { withFileTypes: true });
720
+ for (const entry of entries) {
721
+ const fullPath = path.join(dir, entry.name);
722
+ if (entry.name === 'node_modules' || entry.name === '.git')
723
+ continue;
724
+ if (entry.isDirectory()) {
725
+ await walkDir(fullPath);
726
+ }
727
+ else if (entry.name === 'package.json') {
728
+ try {
729
+ const raw = await fs.readFile(fullPath, 'utf-8');
730
+ const pkg = JSON.parse(raw);
731
+ let changed = false;
732
+ for (const depField of ['dependencies', 'devDependencies', 'peerDependencies']) {
733
+ const deps = pkg[depField];
734
+ if (!deps)
735
+ continue;
736
+ for (const [name, version] of Object.entries(deps)) {
737
+ if (name.startsWith('@repo/') && version === '*') {
738
+ deps[name] = 'workspace:*';
739
+ changed = true;
740
+ }
741
+ }
742
+ }
743
+ if (changed) {
744
+ await fs.writeFile(fullPath, JSON.stringify(pkg, null, 2) + '\n');
745
+ }
746
+ }
747
+ catch {
748
+ // skip unreadable files
749
+ }
750
+ }
751
+ }
752
+ }
753
+ await walkDir(targetDir);
754
+ }
755
+ /**
756
+ * Update environment variables template
757
+ */
758
+ async function updateEnvTemplate(targetDir, config) {
759
+ const envExamplePath = path.join(targetDir, 'apps', 'backend', '.env.example');
760
+ try {
761
+ let envContent = await fs.readFile(envExamplePath, 'utf-8');
762
+ // Update database URL based on selected database
763
+ const dbUrls = {
764
+ postgresql: 'postgresql://user:password@localhost:5432/{{PROJECT_NAME}}',
765
+ mysql: 'mysql://user:password@localhost:3306/{{PROJECT_NAME}}',
766
+ mongodb: 'mongodb://localhost:27017/{{PROJECT_NAME}}',
767
+ sqlite: 'file:./dev.db',
768
+ };
769
+ const dbUrl = dbUrls[config.apps.backend.database] || '';
770
+ envContent = envContent.replace(/DATABASE_URL=.*/g, `DATABASE_URL="${dbUrl}"`);
771
+ envContent = envContent.replace(/{{PROJECT_NAME}}/g, config.name);
772
+ await fs.writeFile(envExamplePath, envContent);
773
+ }
774
+ catch (error) {
775
+ // .env.example might not exist
776
+ }
777
+ }
778
+ /**
779
+ * Initialize git repository
780
+ */
781
+ export async function initializeGit(targetDir, config) {
782
+ try {
783
+ await execa('git', ['init'], { cwd: targetDir });
784
+ await execa('git', ['add', '.'], { cwd: targetDir });
785
+ await execa('git', ['commit', '-m', `Initial commit: ${config.name}`], { cwd: targetDir });
786
+ console.log('✓ Initialized git repository');
787
+ }
788
+ catch {
789
+ console.warn('Warning: Git initialization failed');
790
+ }
791
+ }
792
+ /**
793
+ * Install dependencies
794
+ */
795
+ export async function installDependencies(targetDir, packageManager) {
796
+ try {
797
+ console.log(`Installing dependencies with ${packageManager}...`);
798
+ await execa(packageManager, ['install'], {
799
+ cwd: targetDir,
800
+ stdio: 'inherit',
801
+ });
802
+ console.log('✓ Dependencies installed');
803
+ }
804
+ catch (error) {
805
+ throw new Error(`Failed to install dependencies: ${error instanceof Error ? error.message : 'Unknown error'}`);
806
+ }
807
+ }
808
+ //# sourceMappingURL=template-clone.js.map