create-fs-app 2.0.5 → 3.0.0

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 (59) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +254 -150
  3. package/dist/cli/output.js +223 -0
  4. package/dist/cli/program.js +403 -0
  5. package/dist/cli/resolve-config.js +264 -0
  6. package/dist/cli/ui/errors.js +27 -0
  7. package/dist/cli/ui/help.js +43 -0
  8. package/dist/cli/ui/hints.js +22 -0
  9. package/dist/cli/ui/layer-log.js +109 -0
  10. package/dist/cli/ui/list.js +115 -0
  11. package/dist/cli/ui/text.js +56 -0
  12. package/dist/cli/wizard.js +275 -0
  13. package/dist/core/auth/jwt.js +478 -0
  14. package/dist/core/download.js +109 -0
  15. package/dist/core/health-check.js +42 -44
  16. package/dist/core/presets.js +75 -117
  17. package/dist/core/registry-fetch.js +101 -81
  18. package/dist/core/registry.fallback.json +892 -0
  19. package/dist/core/scaffold.js +121 -75
  20. package/dist/core/stack.js +109 -0
  21. package/dist/core/template-cache.js +95 -154
  22. package/dist/core/template-clone.js +351 -655
  23. package/dist/core/template-list.js +19 -141
  24. package/dist/core/template-registry.js +116 -216
  25. package/dist/index.js +13 -963
  26. package/dist/types/index.js +30 -82
  27. package/dist/utils/cli-error.js +15 -0
  28. package/dist/utils/exec.js +62 -0
  29. package/dist/utils/logger.js +10 -9
  30. package/dist/utils/theme.js +87 -0
  31. package/dist/utils/validation.js +24 -13
  32. package/package.json +22 -25
  33. package/dist/core/health-check.d.ts +0 -15
  34. package/dist/core/health-check.js.map +0 -1
  35. package/dist/core/presets.d.ts +0 -48
  36. package/dist/core/presets.js.map +0 -1
  37. package/dist/core/registry-fetch.d.ts +0 -20
  38. package/dist/core/registry-fetch.js.map +0 -1
  39. package/dist/core/scaffold.d.ts +0 -40
  40. package/dist/core/scaffold.js.map +0 -1
  41. package/dist/core/template-cache.d.ts +0 -38
  42. package/dist/core/template-cache.js.map +0 -1
  43. package/dist/core/template-clone.d.ts +0 -27
  44. package/dist/core/template-clone.js.map +0 -1
  45. package/dist/core/template-list.d.ts +0 -45
  46. package/dist/core/template-list.js.map +0 -1
  47. package/dist/core/template-registry.d.ts +0 -78
  48. package/dist/core/template-registry.js.map +0 -1
  49. package/dist/index.d.ts +0 -2
  50. package/dist/index.js.map +0 -1
  51. package/dist/types/index.d.ts +0 -102
  52. package/dist/types/index.js.map +0 -1
  53. package/dist/utils/errors.d.ts +0 -15
  54. package/dist/utils/errors.js +0 -50
  55. package/dist/utils/errors.js.map +0 -1
  56. package/dist/utils/logger.d.ts +0 -37
  57. package/dist/utils/logger.js.map +0 -1
  58. package/dist/utils/validation.d.ts +0 -48
  59. package/dist/utils/validation.js.map +0 -1
@@ -1,150 +1,170 @@
1
1
  /**
2
- * Template Cloning and Customization
3
- * Handles downloading templates and customizing them for the user
2
+ * Template download and customization
4
3
  */
5
- import { execa } from 'execa';
6
4
  import fs from 'fs/promises';
7
5
  import path from 'path';
8
- import os from 'os';
9
- import { randomUUID } from 'crypto';
10
6
  import { Logger } from '../utils/logger.js';
11
- import { getCachedTemplatePath, cacheTemplate, copyCachedTemplate } from './template-cache.js';
7
+ import { run } from '../utils/exec.js';
8
+ import { downloadTemplate } from './download.js';
9
+ import { getTemplateFromCache } from './template-cache.js';
10
+ import { describeJwtAuth, generateJwtAuth, jwtFiles, supportsAuth } from './auth/jwt.js';
12
11
  /**
13
- * Clone a template repository (with caching support)
12
+ * Copy a template into `targetDir` (which must not exist):
13
+ * local path → copy; otherwise cache (24 h) → tarball download.
14
+ * Returns the source actually used.
14
15
  */
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;
16
+ export async function cloneTemplate(template, targetDir, options = {}) {
17
+ const { url, localPath } = template;
18
+ if (localPath) {
19
+ Logger.verbose(`Using local template from: ${localPath}`);
20
+ try {
21
+ await fs.access(localPath);
31
22
  }
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
- }
23
+ catch {
24
+ throw new Error(`Local template not found at: ${localPath}`);
40
25
  }
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
- }
26
+ await fs.cp(localPath, targetDir, { recursive: true });
27
+ return 'local';
28
+ }
29
+ if (!url) {
30
+ throw new Error('Template has neither a local path nor a repository URL');
31
+ }
32
+ if (options.noCache) {
33
+ Logger.verbose('Cache skipped, downloading a fresh copy...');
34
+ await downloadTemplate({ repoUrl: url, ref: template.branch ?? 'HEAD', subfolder: template.subfolder }, targetDir);
35
+ return 'download';
36
+ }
37
+ const cached = await getTemplateFromCache(template);
38
+ await fs.cp(cached.path, targetDir, { recursive: true });
39
+ return cached.from;
40
+ }
41
+ const APP_PACKAGES = ['frontend', 'backend'];
42
+ async function readJson(file) {
43
+ try {
44
+ return JSON.parse(await fs.readFile(file, 'utf-8'));
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ async function writeJson(file, data) {
51
+ await fs.writeFile(file, JSON.stringify(data, null, 2) + '\n');
52
+ }
53
+ /** Root + apps/* package.json paths that exist. */
54
+ async function projectPackageFiles(targetDir) {
55
+ const candidates = [
56
+ path.join(targetDir, 'package.json'),
57
+ ...APP_PACKAGES.map(app => path.join(targetDir, 'apps', app, 'package.json')),
58
+ ];
59
+ const found = [];
60
+ for (const file of candidates) {
61
+ try {
62
+ await fs.access(file);
63
+ found.push(file);
87
64
  }
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
- }
65
+ catch {
66
+ // not part of this template
109
67
  }
110
68
  }
111
- catch (error) {
112
- throw new Error(`Failed to clone template: ${error instanceof Error ? error.message : 'Unknown error'}`);
113
- }
69
+ return found;
114
70
  }
115
71
  /**
116
- * Customize the cloned template with user's configuration
72
+ * Customize the copied template with the user's configuration.
117
73
  */
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.
74
+ export async function customizeTemplate(targetDir, config, options) {
75
+ const custom = options.kind === 'custom';
76
+ // 1. package.json names + packageManager (+ pnpm build allow-list)
77
+ await updatePackageJson(targetDir, config, custom);
78
+ // 2. Placeholders
79
+ await replacePlaceholders(targetDir, config, custom);
80
+ // 3. ESLint / Prettier / Docker toggles (official and contributed only)
81
+ if (!custom) {
82
+ await applyToggles(targetDir, config);
83
+ }
84
+ // 4. GitHub Actions CI
85
+ if (config.ci) {
86
+ await generateCiWorkflow(targetDir, config);
87
+ }
88
+ // 5. JWT auth (official and contributed only)
89
+ if (!custom && config.auth === 'jwt') {
90
+ const backend = config.stack?.backend;
91
+ if (!supportsAuth(backend)) {
92
+ throw new Error(`--auth jwt is not available for the ${backend ?? 'unknown'} backend`);
93
+ }
94
+ await generateJwtAuth(targetDir, backend, config.packageManager);
95
+ }
96
+ // 6. pnpm needs "workspace:*" for local packages (templates ship npm-style "*")
132
97
  if (config.packageManager === 'pnpm') {
133
98
  await fixWorkspaceProtocol(targetDir);
134
99
  }
135
100
  }
136
101
  /**
137
- * Detect the installed version of a package manager.
138
- * Returns e.g. "pnpm@9.15.0" or falls back to a safe default.
102
+ * The changes customizeTemplate will make, for --dry-run.
103
+ */
104
+ export function describeCustomizations(config, kind) {
105
+ const custom = kind === 'custom';
106
+ const actions = [];
107
+ actions.push(custom
108
+ ? `Set package.json name to "${config.name}"`
109
+ : `Set package names: ${config.name}, ${config.name}-frontend, ${config.name}-backend`);
110
+ actions.push(`Set packageManager to ${config.packageManager}`);
111
+ actions.push(custom
112
+ ? `Replace {{PROJECT_NAME}} with "${config.name}"`
113
+ : `Replace {{PROJECT_NAME}} and stack placeholders (project name "${config.name}")`);
114
+ if (config.packageManager === 'pnpm') {
115
+ actions.push(`Write pnpm-workspace.yaml and the pnpm build allow-list (${buildAllowList(config).join(', ')})`);
116
+ actions.push('Rewrite @repo/* dependencies to workspace:*');
117
+ }
118
+ if (!custom) {
119
+ if (!config.docker)
120
+ actions.push('Remove Docker files (docker-compose.yml, .dockerignore, Dockerfiles)');
121
+ if (!config.eslint)
122
+ actions.push('Remove ESLint configs, lint scripts and the turbo lint task');
123
+ if (!config.prettier)
124
+ actions.push('Remove Prettier configs, the format script and prettier devDependencies');
125
+ }
126
+ if (config.ci)
127
+ actions.push('Generate .github/workflows/ci.yml');
128
+ const backend = config.stack?.backend;
129
+ if (!custom && config.auth === 'jwt' && supportsAuth(backend)) {
130
+ actions.push(...describeJwtAuth(backend));
131
+ }
132
+ return actions;
133
+ }
134
+ /**
135
+ * Files customizeTemplate adds and removes (project-relative POSIX paths), for
136
+ * --dry-run. Removed paths are candidates: a template may not have them all.
137
+ */
138
+ export function plannedFileChanges(config, kind) {
139
+ const custom = kind === 'custom';
140
+ const added = [];
141
+ const removed = [];
142
+ if (config.packageManager === 'pnpm')
143
+ added.push('pnpm-workspace.yaml');
144
+ if (config.ci)
145
+ added.push('.github/workflows/ci.yml');
146
+ if (!custom) {
147
+ if (!config.docker)
148
+ removed.push(...DOCKER_FILES);
149
+ if (!config.eslint)
150
+ removed.push(...ESLINT_FILES);
151
+ if (!config.prettier)
152
+ removed.push(...PRETTIER_FILES);
153
+ const backend = config.stack?.backend;
154
+ if (config.auth === 'jwt' && supportsAuth(backend))
155
+ added.push(...jwtFiles(backend));
156
+ }
157
+ return { added, removed };
158
+ }
159
+ /**
160
+ * Detect the installed version of a package manager, e.g. "pnpm@9.15.0".
139
161
  */
140
162
  async function detectPackageManagerVersion(pm) {
141
163
  try {
142
- const result = await execa(pm, ['--version']);
143
- const version = result.stdout.trim();
144
- return `${pm}@${version}`;
164
+ const result = await run(pm, ['--version'], { timeout: 10_000 });
165
+ return `${pm}@${result.stdout.trim()}`;
145
166
  }
146
167
  catch {
147
- // Fallback versions if detection fails
148
168
  const defaults = {
149
169
  pnpm: 'pnpm@9.0.0',
150
170
  yarn: 'yarn@1.22.22',
@@ -154,70 +174,57 @@ async function detectPackageManagerVersion(pm) {
154
174
  }
155
175
  }
156
176
  /**
157
- * Update root and nested package.json files.
158
- * Also fixes the `packageManager` field in the root to match the user's choice.
177
+ * Update package.json files: root name + packageManager (all kinds); app
178
+ * package names and descriptions (official and contributed only).
159
179
  */
160
- async function updatePackageJson(targetDir, config) {
180
+ async function updatePackageJson(targetDir, config, custom) {
161
181
  const pm = config.packageManager;
162
182
  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');
183
+ const allowed = buildAllowList(config);
184
+ const rootFile = path.join(targetDir, 'package.json');
185
+ const root = await readJson(rootFile);
186
+ if (root) {
187
+ root.name = config.name;
188
+ root.packageManager = pmVersion;
189
+ if (!custom)
190
+ root.description = `${config.name} - Full-stack application`;
191
+ // Both formats so the project works across pnpm 9/10/11:
192
+ // pnpm 9/10: onlyBuiltDependencies (array), pnpm 11: allowBuilds (map)
193
+ if (pm === 'pnpm') {
194
+ root.pnpm = {
195
+ ...(root.pnpm ?? {}),
196
+ onlyBuiltDependencies: allowed,
197
+ allowBuilds: Object.fromEntries(allowed.map(n => [n, true])),
198
+ };
199
199
  }
200
- catch {
201
- // File might not exist, that's okay
202
- continue;
200
+ await writeJson(rootFile, root);
201
+ }
202
+ if (!custom) {
203
+ for (const app of APP_PACKAGES) {
204
+ const file = path.join(targetDir, 'apps', app, 'package.json');
205
+ const pkg = await readJson(file);
206
+ if (!pkg)
207
+ continue;
208
+ pkg.name = `${config.name}-${app}`;
209
+ pkg.description = `${config.name} - Full-stack application`;
210
+ await writeJson(file, pkg);
203
211
  }
204
212
  }
205
213
  // 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
+ // pnpm 9/10: onlyBuiltDependencies (array of names)
215
+ // pnpm 11: allowBuilds (map name → true)
214
216
  if (pm === 'pnpm') {
215
217
  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');
218
+ // A custom template's own workspace file knows its layout better than we do
219
+ if (custom) {
220
+ try {
221
+ await fs.access(workspaceFile);
222
+ return;
223
+ }
224
+ catch {
225
+ // none shipped: write ours
226
+ }
227
+ }
221
228
  const content = [
222
229
  'packages:',
223
230
  ' - "apps/*"',
@@ -225,217 +232,176 @@ async function updatePackageJson(targetDir, config) {
225
232
  '',
226
233
  '# pnpm 11+: allowBuilds map (package name → true/false)',
227
234
  'allowBuilds:',
228
- allowBuildsMap,
235
+ allowed.map(p => ` "${p}": true`).join('\n'),
229
236
  '',
230
237
  '# pnpm 9/10: onlyBuiltDependencies list (kept for older pnpm compat)',
231
238
  'onlyBuiltDependencies:',
232
- onlyBuiltList,
239
+ allowed.map(p => ` - "${p}"`).join('\n'),
233
240
  '',
234
241
  ].join('\n');
235
242
  await fs.writeFile(workspaceFile, content);
236
243
  }
237
244
  }
238
245
  /**
239
- * Packages that need to run postinstall/build scripts.
240
- * Listed in both package.json (pnpm <10) and pnpm-workspace.yaml (pnpm 10+).
246
+ * Packages that need to run postinstall/build scripts under pnpm.
241
247
  *
242
248
  * Discovery process: scaffold each template combination with --no-install,
243
249
  * run `pnpm install`, and collect ERR_PNPM_IGNORED_BUILDS output.
244
250
  *
245
- * Results per stack:
246
251
  * All templates → sharp, unrs-resolver, esbuild
247
252
  * 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
253
+ * NestJS templates → @nestjs/core, @scarf/scarf (NestJS telemetry)
251
254
  */
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') {
255
+ export function buildAllowList(config) {
256
+ const list = ['sharp', 'unrs-resolver', 'esbuild'];
257
+ if (config.stack?.orm === 'prisma') {
259
258
  list.push('@prisma/engines', 'prisma');
260
259
  }
261
- if (config.apps.backend.framework === 'nest.js') {
260
+ if (config.stack?.backend === 'nest.js') {
262
261
  list.push('@nestjs/core', '@scarf/scarf');
263
262
  }
264
263
  return list;
265
264
  }
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
265
+ // Only text files with these extensions are processed
266
+ const TEXT_EXTENSIONS = ['.md', '.json', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.env', '.example', '.yml', '.yaml', '.html', '.css'];
267
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist']);
268
+ async function walkFiles(dir, visit) {
269
+ const entries = await fs.readdir(dir, { withFileTypes: true });
270
+ for (const entry of entries) {
271
+ if (SKIP_DIRS.has(entry.name))
272
+ continue;
273
+ const fullPath = path.join(dir, entry.name);
274
+ if (entry.isDirectory()) {
275
+ await walkFiles(fullPath, visit);
306
276
  }
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
- }
277
+ else if (entry.isFile()) {
278
+ await visit(fullPath);
322
279
  }
323
280
  }
324
- await walkDir(targetDir);
325
281
  }
326
282
  /**
327
- * Update README with project-specific information
283
+ * Replace placeholders in text files. Custom templates only get {{PROJECT_NAME}}.
328
284
  */
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}`;
285
+ async function replacePlaceholders(targetDir, config, custom) {
286
+ const placeholders = { '{{PROJECT_NAME}}': config.name };
287
+ if (!custom) {
288
+ const stack = config.stack;
289
+ Object.assign(placeholders, {
290
+ '{{PACKAGE_MANAGER}}': config.packageManager,
291
+ // Scoped package names use 'my-app' as safe placeholder ({{}} is invalid in npm names)
292
+ '@my-app/': `@${config.name}/`,
293
+ '"name": "my-app"': `"name": "${config.name}"`,
294
+ });
295
+ if (stack) {
296
+ Object.assign(placeholders, {
297
+ '{{MONOREPO_FRAMEWORK}}': stack.monorepo,
298
+ '{{FRONTEND_FRAMEWORK}}': stack.frontend,
299
+ '{{BACKEND_FRAMEWORK}}': stack.backend,
300
+ '{{DATABASE}}': stack.database,
301
+ '{{ORM}}': stack.orm,
302
+ });
357
303
  }
358
- await fs.writeFile(readmePath, readme);
359
304
  }
360
- catch (error) {
361
- // README might not exist
305
+ await walkFiles(targetDir, async (filePath) => {
306
+ const name = path.basename(filePath);
307
+ if (!TEXT_EXTENSIONS.some(ext => name.endsWith(ext)) && !name.startsWith('.env'))
308
+ return;
309
+ let content;
310
+ try {
311
+ content = await fs.readFile(filePath, 'utf-8');
312
+ }
313
+ catch {
314
+ return; // unreadable: leave as is
315
+ }
316
+ let modified = false;
317
+ for (const [placeholder, value] of Object.entries(placeholders)) {
318
+ if (content.includes(placeholder)) {
319
+ content = content.split(placeholder).join(value);
320
+ modified = true;
321
+ }
322
+ }
323
+ if (modified)
324
+ await fs.writeFile(filePath, content);
325
+ });
326
+ }
327
+ async function removeFiles(targetDir, relativePaths) {
328
+ for (const relative of relativePaths) {
329
+ await fs.rm(path.join(targetDir, relative), { force: true });
362
330
  }
363
331
  }
332
+ const DOCKER_FILES = [
333
+ 'Dockerfile',
334
+ 'docker-compose.yml',
335
+ 'docker-compose.yaml',
336
+ 'compose.yml',
337
+ 'compose.yaml',
338
+ '.dockerignore',
339
+ 'apps/backend/Dockerfile',
340
+ 'apps/backend/.dockerignore',
341
+ 'apps/frontend/Dockerfile',
342
+ 'apps/frontend/.dockerignore',
343
+ ];
344
+ const ESLINT_FILES = [
345
+ 'eslint.config.mjs',
346
+ 'eslint.config.js',
347
+ '.eslintrc.json',
348
+ '.eslintrc.js',
349
+ 'apps/frontend/eslint.config.mjs',
350
+ 'apps/frontend/eslint.config.js',
351
+ 'apps/frontend/.eslintrc.json',
352
+ 'apps/backend/eslint.config.mjs',
353
+ 'apps/backend/eslint.config.js',
354
+ 'apps/backend/.eslintrc.json',
355
+ ];
356
+ const PRETTIER_FILES = [
357
+ '.prettierrc',
358
+ '.prettierrc.json',
359
+ '.prettierignore',
360
+ 'apps/frontend/.prettierrc',
361
+ 'apps/backend/.prettierrc',
362
+ ];
364
363
  /**
365
- * Handle optional features - remove config for unselected features,
366
- * patch files for enabled ones (Turbopack, CI, JWT auth).
364
+ * --no-docker, --no-eslint, --no-prettier.
367
365
  */
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 */ }
366
+ async function applyToggles(targetDir, config) {
367
+ if (!config.docker) {
368
+ await removeFiles(targetDir, DOCKER_FILES);
369
+ }
370
+ if (!config.eslint) {
371
+ await removeFiles(targetDir, ESLINT_FILES);
372
+ for (const file of await projectPackageFiles(targetDir)) {
373
+ const pkg = await readJson(file);
374
+ if (!pkg?.scripts)
375
+ continue;
376
+ delete pkg.scripts.lint;
377
+ delete pkg.scripts['lint:fix'];
378
+ await writeJson(file, pkg);
383
379
  }
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 */ }
380
+ const turboFile = path.join(targetDir, 'turbo.json');
381
+ const turbo = await readJson(turboFile);
382
+ if (turbo?.tasks && 'lint' in turbo.tasks) {
383
+ delete turbo.tasks.lint;
384
+ await writeJson(turboFile, turbo);
401
385
  }
402
386
  }
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);
387
+ if (!config.prettier) {
388
+ await removeFiles(targetDir, PRETTIER_FILES);
389
+ for (const file of await projectPackageFiles(targetDir)) {
390
+ const pkg = await readJson(file);
391
+ if (!pkg)
392
+ continue;
393
+ let changed = false;
394
+ if (pkg.scripts && 'format' in pkg.scripts) {
395
+ delete pkg.scripts.format;
396
+ changed = true;
415
397
  }
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');
398
+ if (pkg.devDependencies && 'prettier' in pkg.devDependencies) {
399
+ delete pkg.devDependencies.prettier;
400
+ changed = true;
428
401
  }
402
+ if (changed)
403
+ await writeJson(file, pkg);
429
404
  }
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
405
  }
440
406
  }
441
407
  // ─── CI workflow generator ────────────────────────────────────────────────────
@@ -444,8 +410,16 @@ async function generateCiWorkflow(targetDir, config) {
444
410
  await fs.mkdir(workflowDir, { recursive: true });
445
411
  const pm = config.packageManager;
446
412
  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`;
413
+ // setup-node's pnpm cache needs pnpm on the PATH first; the version comes
414
+ // from the packageManager field in package.json
415
+ const pnpmSetup = pm === 'pnpm' ? `
416
+ - name: Set up pnpm
417
+ uses: pnpm/action-setup@v4
418
+ ` : '';
419
+ const lintStep = config.eslint ? `
420
+ - name: Lint
421
+ run: ${pm} run lint
422
+ ` : '';
449
423
  const workflow = `name: CI
450
424
 
451
425
  on:
@@ -460,333 +434,61 @@ jobs:
460
434
 
461
435
  steps:
462
436
  - uses: actions/checkout@v4
463
-
437
+ ${pnpmSetup}
464
438
  - name: Set up Node.js
465
439
  uses: actions/setup-node@v4
466
440
  with:
467
- node-version: '20'
441
+ node-version: '22'
468
442
  cache: '${pm}'
469
443
 
470
444
  - name: Install dependencies
471
445
  run: ${installCmd}
472
- ${config.apps.frontend.eslint ? `
473
- - name: Lint
474
- run: ${lintCmd}
475
- ` : ''}
446
+ ${lintStep}
476
447
  - name: Build
477
- run: ${buildCmd}
448
+ run: ${pm} run build
478
449
  `;
479
450
  await fs.writeFile(path.join(workflowDir, 'ci.yml'), workflow);
480
451
  }
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
452
  /**
711
453
  * Rewrite "@repo/*": "*" → "@repo/*": "workspace:*" in every package.json.
712
454
  *
713
- * Templates ship with npm-style "*" for local workspace packages.
714
455
  * pnpm requires the explicit "workspace:*" protocol — without it pnpm treats
715
456
  * the dependency as an npm package and fails with a 404.
716
457
  */
717
458
  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')
459
+ await walkFiles(targetDir, async (file) => {
460
+ if (path.basename(file) !== 'package.json')
461
+ return;
462
+ const pkg = await readJson(file);
463
+ if (!pkg)
464
+ return;
465
+ let changed = false;
466
+ for (const field of ['dependencies', 'devDependencies', 'peerDependencies']) {
467
+ const deps = pkg[field];
468
+ if (!deps)
723
469
  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
470
+ for (const [name, version] of Object.entries(deps)) {
471
+ if (name.startsWith('@repo/') && version === '*') {
472
+ deps[name] = 'workspace:*';
473
+ changed = true;
749
474
  }
750
475
  }
751
476
  }
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
- }
477
+ if (changed)
478
+ await writeJson(file, pkg);
479
+ });
777
480
  }
778
481
  /**
779
482
  * Initialize git repository
780
483
  */
781
484
  export async function initializeGit(targetDir, config) {
782
485
  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');
486
+ await run('git', ['init'], { cwd: targetDir });
487
+ await run('git', ['add', '.'], { cwd: targetDir });
488
+ await run('git', ['commit', '-m', `Initial commit: ${config.name}`], { cwd: targetDir });
787
489
  }
788
- catch {
789
- console.warn('Warning: Git initialization failed');
490
+ catch (error) {
491
+ Logger.warn(`Git initialization failed: ${error instanceof Error ? error.message : String(error)}`);
790
492
  }
791
493
  }
792
494
  /**
@@ -794,15 +496,9 @@ export async function initializeGit(targetDir, config) {
794
496
  */
795
497
  export async function installDependencies(targetDir, packageManager) {
796
498
  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');
499
+ await run(packageManager, ['install'], { cwd: targetDir, stdio: 'inherit' });
803
500
  }
804
501
  catch (error) {
805
502
  throw new Error(`Failed to install dependencies: ${error instanceof Error ? error.message : 'Unknown error'}`);
806
503
  }
807
504
  }
808
- //# sourceMappingURL=template-clone.js.map