create-next-pro-cli 0.1.5 → 0.1.7

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.
@@ -0,0 +1,520 @@
1
+ // src/index.ts
2
+
3
+ import * as prompts from "prompts";
4
+ import { scaffoldProject } from "@/scaffold";
5
+ import { mkdir, writeFile, readdir, readFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { existsSync } from "node:fs";
8
+ import { addComponent } from "./lib/addComponent";
9
+ import { addPage } from "./lib/addPage";
10
+ import { rmPage } from "./lib/rmPage";
11
+ import { create } from "node:domain";
12
+ import { createProject } from "./lib/createProject";
13
+
14
+ /**
15
+ * Main CLI entry point for create-next-pro.
16
+ *
17
+ * Note: For now, the project behaves as if --force is always enabled and no creation prompt is taken into account.
18
+ * All actions are performed directly without confirmation.
19
+ */
20
+ export async function main() {
21
+ console.log("🚀 Welcome to create-next-pro\n");
22
+
23
+ let args = Bun.argv.slice(2);
24
+ const force = args.includes("--force");
25
+ // For now, --force is always considered enabled but do not overwrite existing projects
26
+ // WARNING: if you enable --force it will overwrite existing projects. This is a temporary setting for development purposes.
27
+ // const force = true;
28
+
29
+ // If addpage is called without options, add default flags -LPl
30
+ if (args[0] === "addpage" && args.length === 1) {
31
+ args.push("-LPl");
32
+ }
33
+
34
+ /**
35
+ * Handle addcomponent command: create a component in the correct location and update translation JSON.
36
+ */
37
+ if (args[0] === "addcomponent") {
38
+ addComponent(args);
39
+ /* let componentName = args[1];
40
+ let pageScope = null;
41
+ let pageIndex = args.findIndex((arg) => arg === "-P" || arg === "--page");
42
+ if (pageIndex !== -1 && args[pageIndex + 1]) {
43
+ pageScope = args[pageIndex + 1];
44
+ }
45
+
46
+ // Handle nested pageScope (e.g. ParentPage.ChildPage)
47
+ let nestedPath = null;
48
+ if (pageScope && pageScope.includes(".")) {
49
+ nestedPath = join(...pageScope.split("."));
50
+ }
51
+
52
+ if (!componentName || componentName.startsWith("-")) {
53
+ // Si le nom n'est pas fourni ou est une option, demander via prompt
54
+ const response = await prompts.prompt({
55
+ type: "text",
56
+ name: "componentName",
57
+ message: "🧩 Component name to add:",
58
+ validate: (name: string) =>
59
+ name ? true : "Component name is required",
60
+ });
61
+ componentName = response.componentName;
62
+ }
63
+
64
+ const componentNameUpper = capitalize(componentName);
65
+ const templatePath = join(import.meta.dir, "..", "templates", "Component");
66
+ const messagesPath = join(process.cwd(), "messages");
67
+
68
+ // Determine target path for the component
69
+ let componentTargetPath;
70
+ let translationKey;
71
+ if (pageScope) {
72
+ if (nestedPath) {
73
+ componentTargetPath = join(process.cwd(), "src", "ui", nestedPath);
74
+ translationKey = pageScope;
75
+ } else {
76
+ componentTargetPath = join(process.cwd(), "src", "ui", pageScope);
77
+ translationKey = pageScope;
78
+ }
79
+ } else {
80
+ componentTargetPath = join(process.cwd(), "src", "ui", "_global");
81
+ translationKey = "_global_ui";
82
+ }
83
+ if (!existsSync(componentTargetPath)) {
84
+ await mkdir(componentTargetPath, { recursive: true });
85
+ }
86
+ const componentFile = join(
87
+ componentTargetPath,
88
+ `${componentNameUpper}.tsx`
89
+ );
90
+
91
+ // Read and adapt the TSX template
92
+ const templateComponentPath = join(templatePath, "Component.tsx");
93
+ if (existsSync(templateComponentPath)) {
94
+ let content = await readFile(templateComponentPath, "utf-8");
95
+ // Remplacement du nom du component et de la clé de traduction
96
+ content = content
97
+ .replace(/Component/g, componentNameUpper)
98
+ .replace(/componentPage/g, translationKey);
99
+ await writeFile(componentFile, content);
100
+ console.log(`📄 File created: ${componentFile}`);
101
+ } else {
102
+ console.error(
103
+ "❌ Template Component.tsx introuvable :",
104
+ templateComponentPath
105
+ );
106
+ }
107
+
108
+ // Add the component to each language's JSON file (only folders)
109
+ const entries = await readdir(messagesPath, { withFileTypes: true });
110
+ const langDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
111
+ const jsonTemplate = join(templatePath, "component.json");
112
+ if (!existsSync(jsonTemplate)) {
113
+ console.error("❌ Template component.json not found:", jsonTemplate);
114
+ return;
115
+ }
116
+ const jsonContent = await readFile(jsonTemplate, "utf-8");
117
+ const parsed = JSON.parse(jsonContent);
118
+
119
+ for (const locale of langDirs) {
120
+ // Only process if messages/<locale> is a directory
121
+ const localeDir = join(messagesPath, locale);
122
+ if (
123
+ !existsSync(localeDir) ||
124
+ !require("node:fs").statSync(localeDir).isDirectory()
125
+ )
126
+ continue;
127
+ let jsonTarget;
128
+ if (pageScope) {
129
+ jsonTarget = join(messagesPath, locale, `${pageScope}.json`);
130
+ } else {
131
+ jsonTarget = join(messagesPath, locale, `_global_ui.json`);
132
+ }
133
+
134
+ let current: Record<string, any> = {};
135
+ if (existsSync(jsonTarget)) {
136
+ const jsonFile = await readFile(jsonTarget, "utf-8");
137
+ current = JSON.parse(jsonFile) as Record<string, any>;
138
+ }
139
+ current[componentNameUpper] = parsed;
140
+ await writeFile(jsonTarget, JSON.stringify(current, null, 2));
141
+ }
142
+
143
+ console.log(
144
+ `✅ Component "${componentNameUpper}" added ${
145
+ pageScope ? `to page ${pageScope}` : "globally"
146
+ } with localized messages.`
147
+ ); */
148
+ return;
149
+ }
150
+
151
+ /**
152
+ * Handle addpage command: create a page (nested or not) and update translation JSON.
153
+ */
154
+ if (args[0] === "addpage") {
155
+ addPage(args);
156
+ /* let pageName = args[1];
157
+ if (!pageName || pageName.startsWith("-")) {
158
+ const response = await prompts.prompt({
159
+ type: "text",
160
+ name: "pageName",
161
+ message: "📝 Page name to add:",
162
+ validate: (name: string) => (name ? true : "Page name is required"),
163
+ });
164
+ pageName = response.pageName;
165
+ }
166
+
167
+ // Handle nested pages
168
+ let parentName = null;
169
+ let childName = null;
170
+ if (pageName.includes(".")) {
171
+ [parentName, childName] = pageName.split(".");
172
+ }
173
+
174
+ let shortFlags = args.find((arg) => /^-[A-Za-z]+$/.test(arg));
175
+ let longFlags = new Set(args.filter((a) => a.startsWith("--")));
176
+ const flags = new Set<string>();
177
+
178
+ if (!shortFlags && Array.from(longFlags).length === 0) {
179
+ shortFlags = "-LPl";
180
+ }
181
+
182
+ if (shortFlags) {
183
+ for (const char of shortFlags.slice(1)) {
184
+ switch (char) {
185
+ case "L":
186
+ flags.add("layout");
187
+ break;
188
+ case "P":
189
+ flags.add("page");
190
+ break;
191
+ case "l":
192
+ flags.add("loading");
193
+ break;
194
+ case "n":
195
+ flags.add("not-found");
196
+ break;
197
+ case "e":
198
+ flags.add("error");
199
+ break;
200
+ case "g":
201
+ flags.add("global-error");
202
+ break;
203
+ case "r":
204
+ flags.add("route");
205
+ break;
206
+ case "t":
207
+ flags.add("template");
208
+ break;
209
+ case "d":
210
+ flags.add("default");
211
+ break;
212
+ }
213
+ }
214
+ }
215
+
216
+ for (const flag of [
217
+ "layout",
218
+ "page",
219
+ "loading",
220
+ "not-found",
221
+ "error",
222
+ "global-error",
223
+ "route",
224
+ "template",
225
+ "default",
226
+ ]) {
227
+ if (longFlags.has("--" + flag)) flags.add(flag);
228
+ }
229
+
230
+ const srcPath = join(process.cwd(), "src", "app", "[locale]");
231
+ const messagesPath = join(process.cwd(), "messages");
232
+ const templatePath = join(import.meta.dir, "..", "templates", "Page");
233
+ const entries = await readdir(messagesPath, { withFileTypes: true });
234
+ const locales = entries.filter((e) => e.isDirectory()).map((e) => e.name);
235
+
236
+ // Create folders/files for nested or simple page
237
+ let uiPageDir, localePagePath, jsonFileName;
238
+ if (parentName && childName) {
239
+ uiPageDir = join(process.cwd(), "src", "ui", parentName, childName);
240
+ localePagePath = join(srcPath, parentName, childName);
241
+ jsonFileName = parentName;
242
+ } else {
243
+ uiPageDir = join(process.cwd(), "src", "ui", pageName);
244
+ localePagePath = join(srcPath, pageName);
245
+ jsonFileName = pageName;
246
+ }
247
+ if (!existsSync(uiPageDir)) {
248
+ await mkdir(uiPageDir, { recursive: true });
249
+ }
250
+ const uiPageFile = join(uiPageDir, "page-ui.tsx");
251
+ const uiPageTemplate = join(templatePath, "page-ui.tsx");
252
+ if (existsSync(uiPageTemplate)) {
253
+ let uiContent = await readFile(uiPageTemplate, "utf-8");
254
+ uiContent = uiContent
255
+ .replace(/template/g, childName || pageName)
256
+ .replace(/Template/g, capitalize(childName || pageName));
257
+ await writeFile(uiPageFile, uiContent);
258
+ console.log(`📄 File created: ${uiPageFile}`);
259
+ } else {
260
+ console.warn("⚠️ Template page-ui.tsx manquant.");
261
+ }
262
+ if (!existsSync(localePagePath)) {
263
+ await mkdir(localePagePath, { recursive: true });
264
+ }
265
+ for (const flag of flags) {
266
+ const filename = toFileName(flag);
267
+ const src = join(templatePath, filename);
268
+ const dst = join(localePagePath, filename);
269
+ if (!existsSync(src)) {
270
+ console.warn(`⚠️ Missing template file: ${filename}`);
271
+ continue;
272
+ }
273
+ const content = await readFile(src, "utf-8");
274
+ const replaced = content
275
+ .replace(/template/g, childName || pageName)
276
+ .replace(/Template/g, capitalize(childName || pageName));
277
+ await writeFile(dst, replaced);
278
+ console.log(`📄 File created: ${dst}`);
279
+ }
280
+
281
+ // Add JSON to parent object if nested, otherwise create a simple file
282
+ const jsonTemplate = join(templatePath, "page.json");
283
+ if (!existsSync(jsonTemplate)) {
284
+ console.warn("⚠️ Missing template page.json.");
285
+ }
286
+ const content = await readFile(jsonTemplate, "utf-8");
287
+ const replaced = content
288
+ .replace(/template/g, childName || pageName)
289
+ .replace(/Template/g, capitalize(childName || pageName));
290
+ for (const locale of locales) {
291
+ // Only process if messages/<locale> is a directory
292
+ const localeDir = join(messagesPath, locale);
293
+ if (
294
+ !existsSync(localeDir) ||
295
+ !require("node:fs").statSync(localeDir).isDirectory()
296
+ )
297
+ continue;
298
+ const jsonTarget = join(messagesPath, locale, `${jsonFileName}.json`);
299
+ let current: Record<string, any> = {};
300
+ if (existsSync(jsonTarget)) {
301
+ const jsonFile = await readFile(jsonTarget, "utf-8");
302
+ try {
303
+ current = JSON.parse(jsonFile) as Record<string, any>;
304
+ } catch {
305
+ current = {};
306
+ }
307
+ }
308
+ if (parentName && childName) {
309
+ current[childName] = JSON.parse(replaced);
310
+ } else {
311
+ // fichier simple
312
+ current = JSON.parse(replaced);
313
+ }
314
+ await writeFile(jsonTarget, JSON.stringify(current, null, 2));
315
+ }
316
+
317
+ console.log(`✅ Page "${pageName}" with templates added for each locale.`); */
318
+ return;
319
+ }
320
+
321
+ /**
322
+ * Handle rmpage command: remove a page and all related files/folders.
323
+ */
324
+ if (args[0] === "rmpage") {
325
+ rmPage(args);
326
+ /* let pageName = args[1];
327
+ if (!pageName || pageName.startsWith("-")) {
328
+ const response = await prompts.prompt({
329
+ type: "text",
330
+ name: "pageName",
331
+ message: "🗑️ Page name to remove:",
332
+ validate: (name: string) => (name ? true : "Page name is required"),
333
+ });
334
+ pageName = response.pageName;
335
+ }
336
+
337
+ // Remove translation files messages/<lang>/<PageName>.json
338
+ const messagesPath = join(process.cwd(), "messages");
339
+ const entries = await readdir(messagesPath, { withFileTypes: true });
340
+ const langDirs = entries.filter((e) => e.isDirectory()).map((e) => e.name);
341
+ for (const locale of langDirs) {
342
+ const jsonTarget = join(messagesPath, locale, `${pageName}.json`);
343
+ if (existsSync(jsonTarget)) {
344
+ await writeFile(jsonTarget, "");
345
+ await import("node:child_process").then((cp) =>
346
+ cp.execSync(`rm -f '${jsonTarget}'`)
347
+ );
348
+ console.log(`🗑️ Deleted: ${jsonTarget}`);
349
+ }
350
+ }
351
+
352
+ // Remove folder src/ui/<PageName>
353
+ const uiPageDir = join(process.cwd(), "src", "ui", pageName);
354
+ if (existsSync(uiPageDir)) {
355
+ await import("node:child_process").then((cp) =>
356
+ cp.execSync(`rm -rf '${uiPageDir}'`)
357
+ );
358
+ console.log(`🗑️ Deleted: ${uiPageDir}`);
359
+ }
360
+
361
+ // Remove folder src/app/[locale]/<PageName>
362
+ const appLocaleDir = join(
363
+ process.cwd(),
364
+ "src",
365
+ "app",
366
+ "[locale]",
367
+ pageName
368
+ );
369
+ if (existsSync(appLocaleDir)) {
370
+ await import("node:child_process").then((cp) =>
371
+ cp.execSync(`rm -rf '${appLocaleDir}'`)
372
+ );
373
+ console.log(`🗑️ Deleted: ${appLocaleDir}`);
374
+ }
375
+
376
+ console.log(`✅ Page "${pageName}" deleted.`); */
377
+ return;
378
+ }
379
+
380
+ /**
381
+ * Handle direct project creation if a name argument is provided.
382
+ */
383
+ const nameArg = args.find((arg) => !arg.startsWith("--"));
384
+
385
+ if (nameArg) {
386
+ createProject(nameArg, force);
387
+ /* const response = {
388
+ projectName: nameArg,
389
+ useTypescript: true,
390
+ useEslint: true,
391
+ useTailwind: true,
392
+ useSrcDir: true,
393
+ useTurbopack: true,
394
+ useI18n: true,
395
+ customAlias: false,
396
+ importAlias: "@/*",
397
+ force,
398
+ };
399
+
400
+ console.log(`📦 Creating project "${response.projectName}"...`);
401
+ await scaffoldProject(response); */
402
+ return;
403
+ }
404
+
405
+ /**
406
+ * Interactive prompt for project creation (not currently used, see note above).
407
+ */
408
+ const response = await prompts.prompt([
409
+ {
410
+ type: "text",
411
+ name: "projectName",
412
+ message: "🧱 Project name:",
413
+ initial: "my-next-app",
414
+ },
415
+ {
416
+ type: "toggle",
417
+ name: "useTypescript",
418
+ message: "✔ Use TypeScript?",
419
+ initial: true,
420
+ active: "Yes",
421
+ inactive: "No",
422
+ },
423
+ {
424
+ type: "toggle",
425
+ name: "useEslint",
426
+ message: "✔ Use ESLint?",
427
+ initial: true,
428
+ active: "Yes",
429
+ inactive: "No",
430
+ },
431
+ {
432
+ type: "toggle",
433
+ name: "useTailwind",
434
+ message: "✔ Use Tailwind CSS?",
435
+ initial: true,
436
+ active: "Yes",
437
+ inactive: "No",
438
+ },
439
+ {
440
+ type: "toggle",
441
+ name: "useSrcDir",
442
+ message: "✔ Use `src/` directory?",
443
+ initial: false,
444
+ active: "Yes",
445
+ inactive: "No",
446
+ },
447
+ {
448
+ type: "toggle",
449
+ name: "useTurbopack",
450
+ message: "✔ Use Turbopack for `next dev`?",
451
+ initial: true,
452
+ active: "Yes",
453
+ inactive: "No",
454
+ },
455
+ {
456
+ type: "toggle",
457
+ name: "useI18n",
458
+ message: "✔ Use i18n with next-intl for translations?",
459
+ initial: true,
460
+ active: "Yes",
461
+ inactive: "No",
462
+ },
463
+ {
464
+ type: "toggle",
465
+ name: "customAlias",
466
+ message: "✔ Customize import alias (`@/*` by default)?",
467
+ initial: false,
468
+ active: "Yes",
469
+ inactive: "No",
470
+ },
471
+ {
472
+ type: (prev: boolean) => (prev ? "text" : null),
473
+ name: "importAlias",
474
+ message: "✔ What import alias would you like?",
475
+ initial: "@core/*",
476
+ },
477
+ ]);
478
+
479
+ console.log("\n✅ Your choices:");
480
+ console.log(response);
481
+
482
+ await scaffoldProject(response);
483
+ }
484
+
485
+ /**
486
+ * Capitalize the first letter of a string.
487
+ */
488
+ function capitalize(str: string): string {
489
+ return str.charAt(0).toUpperCase() + str.slice(1);
490
+ }
491
+
492
+ /**
493
+ * Map a key to its corresponding file name for page/component templates.
494
+ * @param key string
495
+ * @returns file name string
496
+ */
497
+ function toFileName(key: string): string {
498
+ switch (key) {
499
+ case "layout":
500
+ return "layout.tsx";
501
+ case "page":
502
+ return "page.tsx";
503
+ case "loading":
504
+ return "loading.tsx";
505
+ case "not-found":
506
+ return "not-found.tsx";
507
+ case "error":
508
+ return "error.tsx";
509
+ case "global-error":
510
+ return "global-error.tsx";
511
+ case "route":
512
+ return "route.ts";
513
+ case "template":
514
+ return "template.tsx";
515
+ case "default":
516
+ return "default.tsx";
517
+ default:
518
+ return `${key}.tsx`;
519
+ }
520
+ }