@codefast/cli 0.3.1-canary.1 → 0.3.1-canary.11

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 (79) hide show
  1. package/CHANGELOG.md +99 -1
  2. package/dist/index.cjs +1011 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.js +978 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +19 -12
  7. package/.turbo/turbo-build.log +0 -12
  8. package/dist/cjs/commands/update-exports/analyze-imports.cjs +0 -92
  9. package/dist/cjs/commands/update-exports/analyze-imports.cjs.map +0 -1
  10. package/dist/cjs/commands/update-exports/command.cjs +0 -58
  11. package/dist/cjs/commands/update-exports/command.cjs.map +0 -1
  12. package/dist/cjs/commands/update-exports/config.cjs +0 -113
  13. package/dist/cjs/commands/update-exports/config.cjs.map +0 -1
  14. package/dist/cjs/commands/update-exports/file-utils.cjs +0 -144
  15. package/dist/cjs/commands/update-exports/file-utils.cjs.map +0 -1
  16. package/dist/cjs/commands/update-exports/generate-exports.cjs +0 -76
  17. package/dist/cjs/commands/update-exports/generate-exports.cjs.map +0 -1
  18. package/dist/cjs/commands/update-exports/index.cjs +0 -36
  19. package/dist/cjs/commands/update-exports/process-package.cjs +0 -143
  20. package/dist/cjs/commands/update-exports/process-package.cjs.map +0 -1
  21. package/dist/cjs/commands/update-exports/types.cjs +0 -55
  22. package/dist/cjs/commands/update-exports/types.cjs.map +0 -1
  23. package/dist/cjs/index.cjs +0 -46
  24. package/dist/cjs/index.cjs.map +0 -1
  25. package/dist/cjs/lib/logger.cjs +0 -72
  26. package/dist/cjs/lib/logger.cjs.map +0 -1
  27. package/dist/esm/commands/update-exports/analyze-imports.js +0 -58
  28. package/dist/esm/commands/update-exports/analyze-imports.js.map +0 -1
  29. package/dist/esm/commands/update-exports/command.js +0 -24
  30. package/dist/esm/commands/update-exports/command.js.map +0 -1
  31. package/dist/esm/commands/update-exports/config.js +0 -62
  32. package/dist/esm/commands/update-exports/config.js.map +0 -1
  33. package/dist/esm/commands/update-exports/file-utils.js +0 -81
  34. package/dist/esm/commands/update-exports/file-utils.js.map +0 -1
  35. package/dist/esm/commands/update-exports/generate-exports.js +0 -42
  36. package/dist/esm/commands/update-exports/generate-exports.js.map +0 -1
  37. package/dist/esm/commands/update-exports/index.js +0 -3
  38. package/dist/esm/commands/update-exports/process-package.js +0 -93
  39. package/dist/esm/commands/update-exports/process-package.js.map +0 -1
  40. package/dist/esm/commands/update-exports/types.js +0 -18
  41. package/dist/esm/commands/update-exports/types.js.map +0 -1
  42. package/dist/esm/index.js +0 -18
  43. package/dist/esm/index.js.map +0 -1
  44. package/dist/esm/lib/logger.js +0 -28
  45. package/dist/esm/lib/logger.js.map +0 -1
  46. package/dist/types/src/commands/update-exports/analyze-imports.d.ts +0 -9
  47. package/dist/types/src/commands/update-exports/analyze-imports.d.ts.map +0 -1
  48. package/dist/types/src/commands/update-exports/command.d.ts +0 -7
  49. package/dist/types/src/commands/update-exports/command.d.ts.map +0 -1
  50. package/dist/types/src/commands/update-exports/config.d.ts +0 -16
  51. package/dist/types/src/commands/update-exports/config.d.ts.map +0 -1
  52. package/dist/types/src/commands/update-exports/file-utils.d.ts +0 -47
  53. package/dist/types/src/commands/update-exports/file-utils.d.ts.map +0 -1
  54. package/dist/types/src/commands/update-exports/generate-exports.d.ts +0 -11
  55. package/dist/types/src/commands/update-exports/generate-exports.d.ts.map +0 -1
  56. package/dist/types/src/commands/update-exports/index.d.ts +0 -2
  57. package/dist/types/src/commands/update-exports/index.d.ts.map +0 -1
  58. package/dist/types/src/commands/update-exports/process-package.d.ts +0 -23
  59. package/dist/types/src/commands/update-exports/process-package.d.ts.map +0 -1
  60. package/dist/types/src/commands/update-exports/types.d.ts +0 -83
  61. package/dist/types/src/commands/update-exports/types.d.ts.map +0 -1
  62. package/dist/types/src/index.d.ts +0 -3
  63. package/dist/types/src/index.d.ts.map +0 -1
  64. package/dist/types/src/lib/logger.d.ts +0 -15
  65. package/dist/types/src/lib/logger.d.ts.map +0 -1
  66. package/eslint.config.js +0 -18
  67. package/rslib.config.ts +0 -40
  68. package/src/commands/update-exports/analyze-imports.ts +0 -112
  69. package/src/commands/update-exports/command.ts +0 -38
  70. package/src/commands/update-exports/config.ts +0 -99
  71. package/src/commands/update-exports/file-utils.ts +0 -178
  72. package/src/commands/update-exports/generate-exports.ts +0 -74
  73. package/src/commands/update-exports/index.ts +0 -1
  74. package/src/commands/update-exports/process-package.ts +0 -164
  75. package/src/commands/update-exports/types.ts +0 -94
  76. package/src/index.ts +0 -28
  77. package/src/lib/logger.ts +0 -39
  78. package/tsconfig.build.json +0 -5
  79. package/tsconfig.json +0 -14
package/dist/index.js ADDED
@@ -0,0 +1,978 @@
1
+ #!/usr/bin/env node
2
+ import * as __WEBPACK_EXTERNAL_MODULE_commander__ from "commander";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__ from "node:child_process";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_node_readline_91c31510__ from "node:readline";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_glob__ from "glob";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_ts_morph_07c7ce60__ from "ts-morph";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__ from "lodash-es";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_zod__ from "zod";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
12
+ const rl = __WEBPACK_EXTERNAL_MODULE_node_readline_91c31510__["default"].createInterface({
13
+ input: process.stdin,
14
+ output: process.stdout
15
+ });
16
+ function utils_prompt(question) {
17
+ return new Promise((resolve)=>{
18
+ rl.question(question, (answer)=>{
19
+ resolve(answer.trim());
20
+ });
21
+ });
22
+ }
23
+ function runCommand(command) {
24
+ (0, __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__.execSync)(command, {
25
+ stdio: "inherit"
26
+ });
27
+ }
28
+ function writeConfigFile(filePath, content) {
29
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(filePath, content);
30
+ console.log(`📝 Created ${filePath}`);
31
+ }
32
+ function validateProjectName(name) {
33
+ if (!name || /^\s*$/.test(name)) return {
34
+ valid: false,
35
+ error: "Project name cannot be empty or contain only whitespace."
36
+ };
37
+ if (name.length > 100) return {
38
+ valid: false,
39
+ error: "Project name is too long (maximum 100 characters)."
40
+ };
41
+ const npmNameRegex = /^[a-z0-9-~][a-z0-9-._~]*$/;
42
+ if (!npmNameRegex.test(name)) return {
43
+ valid: false,
44
+ error: "Project name must be URL-friendly (letters, numbers, hyphens, underscores, dots; no @ or scoped packages)."
45
+ };
46
+ if ("." === name || ".." === name) return {
47
+ valid: false,
48
+ error: "Project name cannot be '.' or '..'."
49
+ };
50
+ const reservedNames = /^(?<reserved>CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
51
+ if (reservedNames.test(name)) return {
52
+ valid: false,
53
+ error: `Project name "${name}" is a reserved system name.`
54
+ };
55
+ const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(process.cwd(), name);
56
+ if (__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(fullPath)) return {
57
+ valid: false,
58
+ error: `A directory named "${name}" already exists.`
59
+ };
60
+ try {
61
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].accessSync(process.cwd(), __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].constants.W_OK);
62
+ } catch {
63
+ return {
64
+ valid: false,
65
+ error: "Cannot create project: No write permission in current directory."
66
+ };
67
+ }
68
+ return {
69
+ valid: true
70
+ };
71
+ }
72
+ async function getValidProjectName(initialName, attempts = 0, maxAttempts = 3) {
73
+ const projectName = initialName ?? await utils_prompt("Enter project name: ");
74
+ const validation = validateProjectName(projectName);
75
+ if (validation.valid) return projectName;
76
+ if (attempts >= maxAttempts - 1) throw new Error(`❌ Exceeded maximum attempts to enter a valid project name.`);
77
+ console.error(`❌ ${validation.error} (${maxAttempts - attempts - 1} attempts remaining)`);
78
+ return getValidProjectName(void 0, attempts + 1, maxAttempts);
79
+ }
80
+ async function checkExistingProject(projectNameArg) {
81
+ const packageJsonPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(process.cwd(), "package.json");
82
+ const packageJsonExists = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(packageJsonPath);
83
+ if (packageJsonExists) {
84
+ console.log(`⚠️ A package.json file has been detected in the current directory.`);
85
+ const confirm = await utils_prompt("Do you want to continue configuring this existing project? [Y/n]: ");
86
+ if ("" === confirm || "y" === confirm.toLowerCase()) {
87
+ const packageJson = JSON.parse(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(packageJsonPath, "utf8"));
88
+ const projectName = packageJson.name ?? await getValidProjectName(projectNameArg);
89
+ return {
90
+ projectName,
91
+ packageJsonExists
92
+ };
93
+ }
94
+ console.log("Aborting...");
95
+ throw new Error("User aborted the operation.");
96
+ }
97
+ const projectName = await getValidProjectName(projectNameArg);
98
+ return {
99
+ projectName,
100
+ packageJsonExists
101
+ };
102
+ }
103
+ const MAIN_DEPENDENCIES = [
104
+ "@codefast/ui",
105
+ "@codefast/hooks",
106
+ "recharts",
107
+ "react-hook-form",
108
+ "next-themes",
109
+ "date-fns",
110
+ "lucide-react"
111
+ ];
112
+ const DEV_DEPENDENCIES = {
113
+ commitLint: [
114
+ "@commitlint/cli",
115
+ "@commitlint/config-conventional",
116
+ "@commitlint/types"
117
+ ],
118
+ gitTools: [
119
+ "simple-git-hooks"
120
+ ],
121
+ formatting: [
122
+ "prettier",
123
+ "prettier-plugin-packagejson",
124
+ "prettier-plugin-tailwindcss",
125
+ "lint-staged"
126
+ ],
127
+ linting: [
128
+ "@codefast/eslint-config"
129
+ ]
130
+ };
131
+ const PACKAGES_TO_REMOVE = [
132
+ "@eslint/eslintrc",
133
+ "eslint-config-next"
134
+ ];
135
+ const configGroups = {
136
+ deployment: [
137
+ {
138
+ path: ".vercelignore",
139
+ content: `#-------------------------------------------------------------------------------
140
+ # Dependencies and package managers
141
+ #-------------------------------------------------------------------------------
142
+
143
+ # Node dependencies
144
+ node_modules
145
+ .pnpm-store
146
+ .yarn
147
+
148
+ #-------------------------------------------------------------------------------
149
+ # Development and environment
150
+ #-------------------------------------------------------------------------------
151
+
152
+ # Environment variables (except examples)
153
+ .env*
154
+ !.env.example
155
+
156
+ # Build artifacts
157
+ .next
158
+ build
159
+ dist
160
+ .git
161
+ .github
162
+ .turbo
163
+ .changeset
164
+ .eslintcache
165
+
166
+ # Debug logs
167
+ npm-debug.log*
168
+ yarn-debug.log*
169
+
170
+ #-------------------------------------------------------------------------------
171
+ # Testing
172
+ #-------------------------------------------------------------------------------
173
+
174
+ # Test coverage reports and config snapshots
175
+ coverage
176
+ *.test.*
177
+ *.e2e.*
178
+
179
+ #-------------------------------------------------------------------------------
180
+ # Editor and IDE configuration
181
+ #-------------------------------------------------------------------------------
182
+
183
+ # IDE project files
184
+ .idea
185
+ *.suo
186
+ *.ntvs*
187
+ *.njsproj
188
+ *.sln
189
+
190
+ #-------------------------------------------------------------------------------
191
+ # Operating system files
192
+ #-------------------------------------------------------------------------------
193
+
194
+ # System metadata files
195
+ .DS_Store
196
+ Thumbs.db
197
+
198
+ #-------------------------------------------------------------------------------
199
+ # Deployment
200
+ #-------------------------------------------------------------------------------
201
+
202
+ # Vercel deployment configuration
203
+ .vercel
204
+ `,
205
+ description: "Ignore files that should not be deployed to Vercel"
206
+ }
207
+ ],
208
+ formatting: [
209
+ {
210
+ path: "prettier.config.mjs",
211
+ content: `/**
212
+ * @see https://prettier.io/docs/en/configuration.html
213
+ * @type {import('prettier').Config}
214
+ */
215
+ const config = {
216
+ plugins: ["prettier-plugin-packagejson", "prettier-plugin-tailwindcss"],
217
+ printWidth: 100,
218
+ tailwindAttributes: ["classNames"],
219
+ tailwindFunctions: ["tv"],
220
+ };
221
+
222
+ export default config;
223
+ `,
224
+ description: "Prettier configuration for source code formatting"
225
+ },
226
+ {
227
+ path: ".editorconfig",
228
+ content: `# https://editorconfig.org
229
+ root = true
230
+
231
+ [*]
232
+ charset = utf-8
233
+ insert_final_newline = true
234
+
235
+ end_of_line = lf
236
+ indent_style = space
237
+ indent_size = 2
238
+ max_line_length = 120
239
+
240
+ trim_trailing_whitespace = true
241
+
242
+ [Makefile]
243
+ indent_style = tab
244
+
245
+ [{go.mod,go.sum,*.go}]
246
+ indent_style = tab
247
+
248
+ [*.rs]
249
+ # Keep in sync with rustfmt
250
+ indent_size = 4
251
+ `,
252
+ description: "Editor configuration for source code formatting"
253
+ },
254
+ {
255
+ path: ".prettierignore",
256
+ content: `# changesets
257
+ .changeset
258
+
259
+ # debug
260
+ npm-debug.log*
261
+ yarn-debug.log*
262
+ yarn-error.log*
263
+ .pnpm-debug.log*
264
+
265
+ # lock files
266
+ package-lock.json
267
+ yarn.lock
268
+ pnpm-lock.yaml
269
+ src/app/globals.css
270
+ `,
271
+ description: ""
272
+ }
273
+ ],
274
+ linting: [
275
+ {
276
+ path: "commitlint.config.mjs",
277
+ content: `/**
278
+ * @see https://commitlint.js.org/reference/configuration.html
279
+ * @type {import('@commitlint/types').UserConfig}
280
+ */
281
+ const config = {
282
+ extends: ["@commitlint/config-conventional"],
283
+ rules: {
284
+ "body-max-line-length": [2, "always", 350],
285
+ },
286
+ };
287
+
288
+ export default config;
289
+ `,
290
+ description: "Commitlint configuration"
291
+ },
292
+ {
293
+ path: "eslint.config.mjs",
294
+ content: `import { config } from "@codefast/eslint-config/next";
295
+ /**
296
+ * @see https://eslint.org/docs/latest/use/configure/configuration-files
297
+ * @type {import('eslint').Linter.Config[]}
298
+ */
299
+ const eslintConfig = [...config];
300
+
301
+ export default eslintConfig;
302
+ `,
303
+ description: "ESLint configuration for the project"
304
+ },
305
+ {
306
+ path: "lint-staged.config.mjs",
307
+ content: `import { relative } from "node:path";
308
+
309
+ /**
310
+ * Builds an ESLint command with the given filenames.
311
+ *
312
+ * @param {string[]} filenames - An array of filenames to be passed to the
313
+ * ESLint command.
314
+ * @returns {string} - The generated ESLint command.
315
+ */
316
+ function buildEslintCommand(filenames) {
317
+ return \`next lint --fix --max-warnings 0 --file \${filenames.map((file) => relative(import.meta.dirname, file)).
318
+ join(" --file ")}\`;
319
+ }
320
+
321
+ /**
322
+ * @see https://www.npmjs.com/package/lint-staged
323
+ * @type {import('lint-staged').Configuration}
324
+ */
325
+ const config = {
326
+ "*.{js,mjs,jsx,ts,tsx}": [buildEslintCommand, "prettier --list-different --write"],
327
+ "*.{json,css,md,mdx}": ["prettier --list-different --write"],
328
+ };
329
+
330
+ export default config;
331
+ `,
332
+ description: "Configure lint-staged for pre-commit checks"
333
+ }
334
+ ],
335
+ styles: [
336
+ {
337
+ path: "src/lib/fonts.ts",
338
+ content: `import { cn } from "@codefast/ui";
339
+ import { Geist, Geist_Mono as GeistMono } from "next/font/google";
340
+
341
+ const fontGeistSans = Geist({
342
+ subsets: ["latin"],
343
+ variable: "--font-geist-sans",
344
+ });
345
+
346
+ const fontGeistMono = GeistMono({
347
+ subsets: ["latin"],
348
+ variable: "--font-geist-mono",
349
+ });
350
+
351
+ export const fontVariables = cn(fontGeistSans.variable, fontGeistMono.variable);
352
+ `,
353
+ description: "Font configuration for the application"
354
+ },
355
+ {
356
+ path: "src/app/globals.css",
357
+ content: `@import "tailwindcss";
358
+
359
+ @import "@codefast/ui/styles.css";
360
+
361
+ @source '../../node_modules/@codefast/ui';
362
+
363
+ @custom-variant dark (&:where(.dark, .dark *));
364
+
365
+ @layer base {
366
+ :root {
367
+ --font-sans: var(--font-geist-sans);
368
+ --font-mono: var(--font-geist-mono);
369
+ --input: var(--color-neutral-200);
370
+ --border: var(--color-neutral-200);
371
+ --ring: var(--color-neutral-400);
372
+ --background: var(--color-white);
373
+ --foreground: var(--color-neutral-950);
374
+ --primary: var(--color-sky-500);
375
+ --primary-foreground: var(--color-neutral-50);
376
+ --secondary: var(--color-neutral-100);
377
+ --secondary-foreground: var(--color-neutral-900);
378
+ --destructive: var(--color-red-600);
379
+ --accent: var(--color-neutral-100);
380
+ --accent-foreground: var(--color-neutral-900);
381
+ --muted: var(--color-neutral-100);
382
+ --muted-foreground: var(--color-neutral-500);
383
+ --popover: var(--color-white);
384
+ --popover-foreground: var(--color-neutral-950);
385
+ --popover-overlay: --alpha(var(--color-neutral-900) / 20%);
386
+ --card: var(--color-white);
387
+ --card-foreground: var(--color-neutral-950);
388
+ --sidebar: var(--color-neutral-50);
389
+ --sidebar-foreground: var(--color-neutral-950);
390
+ --sidebar-primary: var(--color-sky-500);
391
+ --sidebar-primary-foreground: var(--color-neutral-50);
392
+ --sidebar-accent: var(--color-neutral-100);
393
+ --sidebar-accent-foreground: var(--color-neutral-900);
394
+ --sidebar-border: var(--color-neutral-200);
395
+ --sidebar-ring: var(--color-neutral-400);
396
+ --chart-1: var(--color-orange-600);
397
+ --chart-2: var(--color-teal-600);
398
+ --chart-3: var(--color-cyan-600);
399
+ --chart-4: var(--color-amber-600);
400
+ --chart-5: var(--color-amber-500);
401
+ }
402
+ .dark {
403
+ --input: var(--color-neutral-700);
404
+ --border: --alpha(var(--color-neutral-700) / 50%);
405
+ --ring: var(--color-neutral-500);
406
+ --background: var(--color-neutral-950);
407
+ --foreground: var(--color-neutral-50);
408
+ --primary: var(--color-sky-700);
409
+ --primary-foreground: var(--color-neutral-50);
410
+ --secondary: var(--color-neutral-800);
411
+ --secondary-foreground: var(--color-neutral-50);
412
+ --destructive: var(--color-red-400);
413
+ --accent: var(--color-neutral-700);
414
+ --accent-foreground: var(--color-neutral-50);
415
+ --muted: var(--color-neutral-800);
416
+ --muted-foreground: var(--color-neutral-400);
417
+ --popover: var(--color-neutral-800);
418
+ --popover-foreground: var(--color-neutral-50);
419
+ --popover-overlay: --alpha(var(--color-neutral-900) / 80%);
420
+ --card: var(--color-neutral-900);
421
+ --card-foreground: var(--color-neutral-50);
422
+ --sidebar: var(--color-neutral-900);
423
+ --sidebar-foreground: var(--color-neutral-50);
424
+ --sidebar-primary: var(--color-sky-700);
425
+ --sidebar-primary-foreground: var(--color-neutral-50);
426
+ --sidebar-accent: var(--color-neutral-800);
427
+ --sidebar-accent-foreground: var(--color-neutral-50);
428
+ --sidebar-border: var(--color-neutral-800);
429
+ --sidebar-ring: var(--color-neutral-600);
430
+ --chart-1: var(--color-blue-700);
431
+ --chart-2: var(--color-emerald-500);
432
+ --chart-3: var(--color-amber-500);
433
+ --chart-4: var(--color-purple-500);
434
+ --chart-5: var(--color-rose-500);
435
+ }
436
+ }
437
+ `,
438
+ description: "Global CSS variables for the application"
439
+ }
440
+ ]
441
+ };
442
+ function updatePostcssConfig(projectDir) {
443
+ const postcssConfigPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(projectDir, "postcss.config.mjs");
444
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(postcssConfigPath)) return void console.warn(`⚠️ postcss.config.mjs not found, skipping update.`);
445
+ let content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(postcssConfigPath, "utf8");
446
+ const typeComment = `/** @type {import('postcss-load-config').Config} */\n`;
447
+ if (content.includes(typeComment)) console.log(`📝 postcss.config.mjs already contains type comment, no changes made.`);
448
+ else {
449
+ content = content.replace("const config = {", `${typeComment}const config = {`);
450
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(postcssConfigPath, content);
451
+ console.log(`📝 Updated postcss.config.mjs with type comment.`);
452
+ }
453
+ }
454
+ function updateLayoutFile(projectDir) {
455
+ const layoutPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(projectDir, "src/app/layout.tsx");
456
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(layoutPath)) return void console.warn(`⚠️ src/app/layout.tsx not found, skipping update.`);
457
+ let content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(layoutPath, "utf8");
458
+ if (content.includes('<html className={cn(fontVariables, "antialiased")} lang="en">')) return void console.log(`📝 src/app/layout.tsx already uses fontVariables in html tag, no changes made.`);
459
+ const newImports = `import type { Metadata } from "next";
460
+
461
+ import { cn } from "@codefast/ui";
462
+
463
+ import { fontVariables } from "@/lib/fonts";
464
+ import "@/app/globals.css";`;
465
+ content = content.replaceAll(/import\s+{[^}]+}\s+from\s+["']next\/font\/google["'];\s*/g, "");
466
+ content = content.replace(/const\s+geistSans\s*=[^;]+;\s*const\s+geistMono\s*=[^;]+;\s*/, "");
467
+ content = content.replace(/import\s+type\s+{[^}]+}\s+from\s+["']next["'];\s*import\s+["']\.\/globals\.css["'];\s*/, newImports);
468
+ const htmlRegex = /<html\s+lang="en"\s*>/;
469
+ const newHtml = '<html className={cn(fontVariables, "antialiased")} lang="en">';
470
+ content = content.replace(htmlRegex, newHtml);
471
+ const bodyRegex = /<body\s+className={`[^`]*`}\s*>/;
472
+ const newBody = "<body>";
473
+ content = content.replace(bodyRegex, newBody);
474
+ try {
475
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(layoutPath, content);
476
+ console.log(`📝 Updated src/app/layout.tsx to use fontVariables in html tag and removed className from body`);
477
+ } catch (error) {
478
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
479
+ console.warn(`⚠️ Failed to update src/app/layout.tsx: ${errorMessage}`);
480
+ }
481
+ }
482
+ function updatePackageJson(projectDir) {
483
+ const packageJsonPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(projectDir, "package.json");
484
+ const packageJson = JSON.parse(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(packageJsonPath, "utf8"));
485
+ packageJson.scripts = {
486
+ ...packageJson.scripts,
487
+ "deploy:preview": "vercel deploy --archive=tgz",
488
+ "deploy:prod": "vercel deploy --archive=tgz --prod",
489
+ format: "prettier --write --ignore-unknown .",
490
+ "format:check": "prettier --check --ignore-unknown .",
491
+ lint: "next lint --fix --max-warnings 0",
492
+ "lint:check": "next lint --max-warnings 0",
493
+ "package:install": "pnpm install",
494
+ "package:outdated": "pnpm outdated",
495
+ "package:upgrade": "pnpm update --latest",
496
+ preview: "pnpm build && pnpm start"
497
+ };
498
+ packageJson["simple-git-hooks"] = {
499
+ "pre-commit": "pnpm lint-staged",
500
+ "commit-msg": "pnpm commitlint --edit"
501
+ };
502
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
503
+ console.log(`📝 Updated package.json`);
504
+ }
505
+ function updateNextConfig(projectDir) {
506
+ const nextConfigPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(projectDir, "next.config.ts");
507
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(nextConfigPath)) return void console.warn(`⚠️ next.config.ts not found, skipping update.`);
508
+ let content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(nextConfigPath, "utf8");
509
+ if (content.includes('optimizePackageImports: ["@codefast/ui"]')) return void console.log(`📝 next.config.ts already contains optimizePackageImports configuration, no changes made.`);
510
+ const configPattern = /const nextConfig: NextConfig = \{/;
511
+ const experimentalConfig = `const nextConfig: NextConfig = {
512
+ experimental: {
513
+ optimizePackageImports: ["@codefast/ui"],
514
+ },`;
515
+ content = content.replace(configPattern, experimentalConfig);
516
+ try {
517
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(nextConfigPath, content);
518
+ console.log(`📝 Updated next.config.ts with optimizePackageImports configuration.`);
519
+ } catch (error) {
520
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
521
+ console.warn(`⚠️ Failed to update next.config.ts: ${errorMessage}`);
522
+ }
523
+ }
524
+ function createConfigFiles(projectDir) {
525
+ console.log(`\n📝 Creating configuration files...`);
526
+ for (const [category, configs] of Object.entries(configGroups)){
527
+ console.log(`\n📂 Setting up ${category} configurations:`);
528
+ for (const { path: filePath, content, description } of configs){
529
+ const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(projectDir, filePath);
530
+ const dir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(fullPath);
531
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(dir)) __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].mkdirSync(dir, {
532
+ recursive: true
533
+ });
534
+ writeConfigFile(fullPath, content);
535
+ if (description) console.log(` ℹ️ ${filePath}: ${description}`);
536
+ }
537
+ }
538
+ }
539
+ function installDependencies() {
540
+ console.log(`\n📚 Installing dependencies...`);
541
+ if (MAIN_DEPENDENCIES.length > 0) runCommand(`pnpm add ${MAIN_DEPENDENCIES.join(" ")}`);
542
+ const allDevDependencies = Object.values(DEV_DEPENDENCIES).flat().join(" ");
543
+ if (allDevDependencies) runCommand(`pnpm add -D ${allDevDependencies}`);
544
+ }
545
+ function cleanupPackages() {
546
+ console.log(`\n🧹 Cleaning up unnecessary packages...`);
547
+ const packageJsonPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.join(process.cwd(), "package.json");
548
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.existsSync(packageJsonPath)) return void console.warn(`⚠️ package.json not found, skipping cleanup.`);
549
+ let packageJson;
550
+ try {
551
+ packageJson = JSON.parse(__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.readFileSync(packageJsonPath, "utf8"));
552
+ } catch (error) {
553
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
554
+ console.warn(`⚠️ Error reading package.json: ${errorMessage}, skipping cleanup.`);
555
+ return;
556
+ }
557
+ const dependencies = packageJson.dependencies ?? {};
558
+ const devDependencies = packageJson.devDependencies ?? {};
559
+ const packagesToRemove = PACKAGES_TO_REMOVE.filter((pkg)=>pkg in dependencies || pkg in devDependencies);
560
+ if (packagesToRemove.length > 0) runCommand(`pnpm remove ${packagesToRemove.join(" ")}`);
561
+ else console.log(`ℹ️ No unnecessary packages found in package.json to remove.`);
562
+ }
563
+ function checkEnvironment() {
564
+ try {
565
+ (0, __WEBPACK_EXTERNAL_MODULE_node_child_process_27f17141__.execSync)("pnpm --version", {
566
+ stdio: "ignore"
567
+ });
568
+ } catch {
569
+ console.error(`❌ PNPM chưa được cài đặt. Vui lòng cài đặt PNPM trước.`);
570
+ process.exit(1);
571
+ }
572
+ }
573
+ function createNextProject(projectName) {
574
+ console.log(`📦 Creating Next.js project...`);
575
+ const flags = '--ts --tailwind --eslint --app --turbo --use-pnpm --src-dir --turbopack --import-alias "@/*"';
576
+ runCommand(`npx create-next-app@latest ${projectName} ${flags}`);
577
+ }
578
+ function createProjectCommand(program) {
579
+ program.command("create-project [name]").description("Create a new Next.js project with recommended setup").action(async (projectNameArg)=>{
580
+ try {
581
+ checkEnvironment();
582
+ const { projectName, packageJsonExists } = await checkExistingProject(projectNameArg);
583
+ if (!packageJsonExists) {
584
+ console.log(`\n🚀 Starting project creation for ${projectName}...\n`);
585
+ createNextProject(projectName);
586
+ process.chdir(projectName);
587
+ console.log(`📂 Moved to ${projectName}`);
588
+ }
589
+ updateLayoutFile(process.cwd());
590
+ updatePostcssConfig(process.cwd());
591
+ installDependencies();
592
+ cleanupPackages();
593
+ createConfigFiles(process.cwd());
594
+ updateNextConfig(process.cwd());
595
+ updatePackageJson(process.cwd());
596
+ console.log(`\n🔄 Activating git hooks...`);
597
+ runCommand("pnpm simple-git-hooks");
598
+ console.log(`\n📝 Formatting files with Prettier...`);
599
+ runCommand("pnpm format");
600
+ console.log(`\n✅ Project ${packageJsonExists ? "configured" : "created"} successfully!`);
601
+ console.log(`- Project: ${projectName}`);
602
+ console.log("- Next.js with TypeScript");
603
+ console.log("- TailwindCSS and @codefast/ui");
604
+ console.log("- ESLint, Prettier, Commitlint, and Git Hooks");
605
+ console.log("- Lint-staged for pre-commit checks");
606
+ console.log(`\n📁 Project directory: ${process.cwd()}`);
607
+ console.log(`\n🚀 To start development:`);
608
+ console.log(`cd ${projectName} && pnpm dev`);
609
+ } catch (error) {
610
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
611
+ console.error(`\n❌ An error occurred: ${errorMessage}`);
612
+ process.exit(1);
613
+ } finally{
614
+ rl.close();
615
+ }
616
+ });
617
+ }
618
+ function makeRegexPrefixesToRemove(prefixes) {
619
+ const prefixPattern = prefixes.join("|");
620
+ return new RegExp(`^.?\\/?(?:${prefixPattern})\\/(.*)$`);
621
+ }
622
+ function processExportPath(modulePath, regexPattern) {
623
+ let processedPath = modulePath;
624
+ const match = processedPath.match(regexPattern);
625
+ if (match) {
626
+ const remainingPath = match[1];
627
+ processedPath = remainingPath.startsWith("./") ? remainingPath : `./${remainingPath}`;
628
+ }
629
+ return processedPath;
630
+ }
631
+ function analyzeImports(indexFilePath, packageConfig) {
632
+ const project = new __WEBPACK_EXTERNAL_MODULE_ts_morph_07c7ce60__.Project();
633
+ let sourceFile;
634
+ try {
635
+ sourceFile = project.addSourceFileAtPath(indexFilePath);
636
+ } catch (error) {
637
+ console.error(`Error loading source file at ${indexFilePath}:`, error);
638
+ return {
639
+ imports: []
640
+ };
641
+ }
642
+ const imports = [];
643
+ const prefixesToRemove = packageConfig.exportPathPrefixesToRemove ?? [];
644
+ const regexPattern = makeRegexPrefixesToRemove(prefixesToRemove);
645
+ for (const exportDecl of sourceFile.getExportDeclarations()){
646
+ let moduleSpecifier = exportDecl.getModuleSpecifierValue();
647
+ if (!moduleSpecifier) continue;
648
+ if (moduleSpecifier.startsWith("@/")) moduleSpecifier = `./${moduleSpecifier.slice(2)}`;
649
+ const isExternal = !moduleSpecifier.startsWith(".");
650
+ if (isExternal) continue;
651
+ const parts = moduleSpecifier.split("/").filter(Boolean);
652
+ if (parts.length < 2) continue;
653
+ let directory;
654
+ if (parts.length <= 1) directory = ".";
655
+ else {
656
+ directory = parts.slice(0, -1).join("/");
657
+ if (directory.startsWith("./")) directory = directory.slice(2);
658
+ }
659
+ const name = parts.at(-1) ?? "";
660
+ const importPath = {
661
+ originalPath: moduleSpecifier,
662
+ directory,
663
+ name,
664
+ exportPath: processExportPath(moduleSpecifier, regexPattern)
665
+ };
666
+ imports.push(importPath);
667
+ }
668
+ return {
669
+ imports
670
+ };
671
+ }
672
+ const PackageConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z["interface"]({
673
+ cjsOutputPattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
674
+ esmOutputPattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
675
+ packageJsonPath: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
676
+ srcIndexPath: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
677
+ typesOutputCjsPattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
678
+ typesOutputPattern: __WEBPACK_EXTERNAL_MODULE_zod__.z.string(),
679
+ "exportPathPrefixesToRemove?": __WEBPACK_EXTERNAL_MODULE_zod__.z.array(__WEBPACK_EXTERNAL_MODULE_zod__.z.string())
680
+ });
681
+ const ScriptConfigSchema = __WEBPACK_EXTERNAL_MODULE_zod__.z["interface"]({
682
+ customPackageConfigs: __WEBPACK_EXTERNAL_MODULE_zod__.z.record(__WEBPACK_EXTERNAL_MODULE_zod__.z.string(), PackageConfigSchema.partial()),
683
+ defaultPackageConfig: PackageConfigSchema,
684
+ packagesGlob: __WEBPACK_EXTERNAL_MODULE_zod__.z.string()
685
+ });
686
+ let cachedConfig = null;
687
+ function loadConfigFile(configPath) {
688
+ if (!configPath) return {};
689
+ try {
690
+ const fullPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(configPath);
691
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(fullPath)) {
692
+ console.warn(`Configuration file not found at ${fullPath}`);
693
+ return {};
694
+ }
695
+ const configContent = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(fullPath, "utf8");
696
+ const config = JSON.parse(configContent);
697
+ return ScriptConfigSchema.parse(config);
698
+ } catch (error) {
699
+ console.error("Error reading configuration file:", error);
700
+ return {};
701
+ }
702
+ }
703
+ function getConfig(configPath) {
704
+ if (cachedConfig && !configPath) return cachedConfig;
705
+ const userConfig = loadConfigFile(configPath);
706
+ const config = (0, __WEBPACK_EXTERNAL_MODULE_lodash_es_18c59938__.merge)({}, defaultConfig, userConfig);
707
+ if (!configPath) cachedConfig = config;
708
+ return config;
709
+ }
710
+ function getPackageConfig(packageName, config) {
711
+ const configObj = config ?? getConfig();
712
+ const customConfig = configObj.customPackageConfigs[packageName] ?? {};
713
+ return {
714
+ ...configObj.defaultPackageConfig,
715
+ ...customConfig
716
+ };
717
+ }
718
+ const defaultConfig = {
719
+ packagesGlob: "./packages/**/package.json",
720
+ defaultPackageConfig: {
721
+ cjsOutputPattern: "./dist/cjs/{dir}/{name}.cjs",
722
+ esmOutputPattern: "./dist/esm/{dir}/{name}.js",
723
+ packageJsonPath: "package.json",
724
+ srcIndexPath: "src/index.ts",
725
+ typesOutputCjsPattern: "./dist/types/{dir}/{name}.d.ts",
726
+ typesOutputPattern: "./dist/types/{dir}/{name}.d.ts"
727
+ },
728
+ customPackageConfigs: {
729
+ "@codefast/ui": {
730
+ exportPathPrefixesToRemove: [
731
+ "components"
732
+ ]
733
+ },
734
+ "@codefast/style-guide": {
735
+ exportPathPrefixesToRemove: [
736
+ "configs"
737
+ ]
738
+ }
739
+ }
740
+ };
741
+ const EXPORTS_ANALYSIS_DIR = ".exports-analysis";
742
+ const EXPORTS_PREVIEW_FILE = "exports-preview.json";
743
+ const EXPORTS_ANALYSIS_FILE = "exports-analysis.json";
744
+ const ENCODING = "utf8";
745
+ const JSON_INDENT = 2;
746
+ const FileUtils = {
747
+ exists (filePath) {
748
+ return __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(filePath);
749
+ },
750
+ ensureDirectoryExists (dirPath) {
751
+ if (!__WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].existsSync(dirPath)) __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].mkdirSync(dirPath, {
752
+ recursive: true
753
+ });
754
+ },
755
+ readJsonFile (filePath) {
756
+ try {
757
+ const content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(filePath, ENCODING);
758
+ return JSON.parse(content);
759
+ } catch (error) {
760
+ console.error(`Error reading JSON file at ${filePath}:`, error);
761
+ return null;
762
+ }
763
+ },
764
+ writeJsonFile (filePath, content) {
765
+ try {
766
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(filePath, `${JSON.stringify(content, null, JSON_INDENT)}\n`, ENCODING);
767
+ return true;
768
+ } catch (error) {
769
+ console.error(`Error writing JSON file at ${filePath}:`, error);
770
+ return false;
771
+ }
772
+ },
773
+ getAnalysisDir (packageDir) {
774
+ const outputDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(packageDir, EXPORTS_ANALYSIS_DIR);
775
+ this.ensureDirectoryExists(outputDir);
776
+ return outputDir;
777
+ },
778
+ createBackupFilename (baseFilename) {
779
+ const timestamp = new Date().toISOString().replaceAll(/[:.]/g, "-");
780
+ return `${baseFilename}.backup.${timestamp}`;
781
+ }
782
+ };
783
+ function fileExists(filePath) {
784
+ return FileUtils.exists(filePath);
785
+ }
786
+ function readPackageJson(filePath) {
787
+ return FileUtils.readJsonFile(filePath);
788
+ }
789
+ function backupPackageJson(filePath) {
790
+ try {
791
+ const content = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].readFileSync(filePath, ENCODING);
792
+ const dir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(filePath);
793
+ const backupDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(dir, EXPORTS_ANALYSIS_DIR);
794
+ FileUtils.ensureDirectoryExists(backupDir);
795
+ const baseName = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].basename(filePath);
796
+ const backupPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(backupDir, FileUtils.createBackupFilename(baseName));
797
+ __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__["default"].writeFileSync(backupPath, content, ENCODING);
798
+ return true;
799
+ } catch (error) {
800
+ console.error(`Error backing up package.json at ${filePath}:`, error);
801
+ return false;
802
+ }
803
+ }
804
+ function savePackageJson(filePath, content) {
805
+ return FileUtils.writeJsonFile(filePath, content);
806
+ }
807
+ function saveJsonToFile(packageDir, fileName, content) {
808
+ const outputDir = FileUtils.getAnalysisDir(packageDir);
809
+ FileUtils.writeJsonFile(__WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(outputDir, fileName), content);
810
+ }
811
+ function saveExportsAnalysis(packageDir, analysis) {
812
+ saveJsonToFile(packageDir, EXPORTS_ANALYSIS_FILE, analysis);
813
+ }
814
+ function saveExportsPreview(packageDir, exports) {
815
+ saveJsonToFile(packageDir, EXPORTS_PREVIEW_FILE, exports);
816
+ }
817
+ function formatOutputPath(pattern, directory, name) {
818
+ const dirPart = "." === directory ? "" : `${directory}/`;
819
+ return pattern.replace("{dir}/", dirPart).replace("{dir}", directory).replace("{name}", name);
820
+ }
821
+ function generateExports(packageName, imports, existingExports = {}, config) {
822
+ const packageConfig = getPackageConfig(packageName, config);
823
+ const exports = {
824
+ ".": existingExports["."] ?? {
825
+ import: {
826
+ types: "./dist/types/index.d.ts",
827
+ default: "./dist/esm/index.js"
828
+ },
829
+ require: {
830
+ types: "./dist/types/index.d.cts",
831
+ default: "./dist/cjs/index.cjs"
832
+ }
833
+ }
834
+ };
835
+ if (existingExports["./styles.css"]) exports["./styles.css"] = existingExports["./styles.css"];
836
+ for (const importPath of imports){
837
+ const { directory, name, exportPath } = importPath;
838
+ const esmOutput = formatOutputPath(packageConfig.esmOutputPattern, directory, name);
839
+ const cjsOutput = formatOutputPath(packageConfig.cjsOutputPattern, directory, name);
840
+ const typesOutput = formatOutputPath(packageConfig.typesOutputPattern, directory, name);
841
+ const typesCjsOutput = formatOutputPath(packageConfig.typesOutputCjsPattern, directory, name);
842
+ exports[exportPath] = {
843
+ import: {
844
+ types: typesOutput,
845
+ default: esmOutput
846
+ },
847
+ require: {
848
+ types: typesCjsOutput,
849
+ default: cjsOutput
850
+ }
851
+ };
852
+ }
853
+ return exports;
854
+ }
855
+ const DEFAULT_IGNORE_PATTERN = [
856
+ "**/node_modules/**"
857
+ ];
858
+ async function findAllPackages(config) {
859
+ const configObj = config ?? getConfig();
860
+ return await (0, __WEBPACK_EXTERNAL_MODULE_glob__.glob)(configObj.packagesGlob, {
861
+ ignore: DEFAULT_IGNORE_PATTERN
862
+ });
863
+ }
864
+ function processPackage(packageJsonPath, options) {
865
+ const packageDir = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(packageJsonPath);
866
+ const packageJson = readPackageJson(packageJsonPath);
867
+ if (!packageJson) {
868
+ console.error(`Failed to read ${packageJsonPath}`);
869
+ return false;
870
+ }
871
+ const packageName = packageJson.name;
872
+ if (options.packageFilter && packageName !== options.packageFilter) {
873
+ console.debug(`Skipping ${packageName} (does not match filter)`);
874
+ return false;
875
+ }
876
+ console.info(`Processing package: ${packageName}`);
877
+ const config = getConfig(options.configPath);
878
+ const packageConfig = getPackageConfig(packageName, config);
879
+ const srcIndexPath = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].join(packageDir, packageConfig.srcIndexPath);
880
+ if (!fileExists(srcIndexPath)) {
881
+ console.error(`Source file not found at ${srcIndexPath}`);
882
+ return false;
883
+ }
884
+ console.info(`Analyzing imports from ${srcIndexPath}...`);
885
+ const { imports } = analyzeImports(srcIndexPath, packageConfig);
886
+ if (0 === imports.length) {
887
+ console.warn(`No imports found to analyze in ${packageName}`);
888
+ return false;
889
+ }
890
+ console.log(`Analysis complete. Found ${imports.length} subpath exports.`);
891
+ saveExportsAnalysis(packageDir, {
892
+ imports
893
+ });
894
+ const newExports = generateExports(packageName, imports, packageJson.exports, config);
895
+ const currentExportsCount = packageJson.exports ? Object.keys(packageJson.exports).length : 0;
896
+ const newExportsCount = Object.keys(newExports).length;
897
+ console.info(`Exports: ${currentExportsCount} -> ${newExportsCount}`);
898
+ if (options.dryRun) {
899
+ saveExportsPreview(packageDir, newExports);
900
+ console.warn("Saved exports preview to .exports-analysis");
901
+ console.warn(`Dry run: no changes saved for ${packageName}`);
902
+ return true;
903
+ }
904
+ if (backupPackageJson(packageJsonPath)) console.log(`Backed up ${packageJsonPath}`);
905
+ const updatedPackageJson = {
906
+ ...packageJson,
907
+ exports: newExports
908
+ };
909
+ if (savePackageJson(packageJsonPath, updatedPackageJson)) {
910
+ console.log(`Updated exports for ${packageName}`);
911
+ return true;
912
+ }
913
+ console.error(`Failed to update ${packageJsonPath}`);
914
+ return false;
915
+ }
916
+ async function processAllPackages(options) {
917
+ try {
918
+ console.info("Searching for packages...");
919
+ const config = getConfig(options.configPath);
920
+ const packageJsonPaths = await findAllPackages(config);
921
+ if (0 === packageJsonPaths.length) return void console.warn("No packages found.");
922
+ console.log(`Found ${packageJsonPaths.length} packages.`);
923
+ let successCount = 0;
924
+ let skipCount = 0;
925
+ let errorCount = 0;
926
+ for (const packageJsonPath of packageJsonPaths){
927
+ const result = processPackage(packageJsonPath, options);
928
+ if (result) successCount++;
929
+ else if (options.packageFilter) skipCount++;
930
+ else errorCount++;
931
+ }
932
+ console.log("Completed exports update.");
933
+ console.info(`Stats: ${successCount} succeeded, ${skipCount} skipped, ${errorCount} failed`);
934
+ } catch (error) {
935
+ console.error("Error processing packages:", error);
936
+ throw error;
937
+ }
938
+ }
939
+ function createUpdateExportsCommand(program) {
940
+ program.command("update-exports").description("Updates exports for all packages").option("-p, --package <package>", "Filter by package name").option("-d, --dry-run", "Run without making changes").option("-c, --config <path>", "Path to configuration file").action(async (options)=>{
941
+ const processorOptions = {
942
+ packageFilter: options.package,
943
+ dryRun: Boolean(options.dryRun),
944
+ configPath: options.config
945
+ };
946
+ try {
947
+ await processAllPackages(processorOptions);
948
+ } catch (error) {
949
+ console.error("Error processing packages:", error);
950
+ process.exit(1);
951
+ }
952
+ });
953
+ }
954
+ function getPackageInfo() {
955
+ const __filename = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.fileURLToPath)(import.meta.url);
956
+ const __dirname = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.dirname)(__filename);
957
+ const packageJsonPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.resolve)(__dirname, "../package.json");
958
+ return JSON.parse((0, __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__.readFileSync)(packageJsonPath, "utf8"));
959
+ }
960
+ function getPackageVersion() {
961
+ return getPackageInfo().version;
962
+ }
963
+ function main() {
964
+ const program = new __WEBPACK_EXTERNAL_MODULE_commander__.Command();
965
+ program.name("codefast").description("CodeFast CLI - A development toolkit for CodeFast.").version(getPackageVersion(), "-v, --version", "display CLI version");
966
+ createUpdateExportsCommand(program);
967
+ createProjectCommand(program);
968
+ program.action(()=>{
969
+ console.log('Use "codefast create-project" to create a new Next.js project.');
970
+ console.log('Use "codefast update-exports" to update exports.');
971
+ console.log('Run "codefast --help" to see all available commands.');
972
+ program.help();
973
+ });
974
+ program.parse(process.argv);
975
+ }
976
+ main();
977
+
978
+ //# sourceMappingURL=index.js.map