create-vanilla-vite 1.2.0 → 1.2.2

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.
@@ -1,1764 +1,1848 @@
1
- #!/usr/bin/env node
2
-
3
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
- import { spawnSync } from "node:child_process";
5
- import spawn from "cross-spawn";
6
- import { emitKeypressEvents } from "node:readline";
7
- import { createInterface } from "node:readline/promises";
8
- import { stdin, stdout } from "node:process";
9
- import { dirname, join, resolve } from "node:path";
10
- import { fileURLToPath } from "node:url";
11
-
12
- const args = process.argv.slice(2);
13
- const allowedOptions = [
14
- "--yes",
15
- "--default",
16
- "--host",
17
- "--tailwind",
18
- "--no-tailwind",
19
- "--axios",
20
- "--no-axios",
21
- "--router",
22
- "--no-router",
23
- "--icons",
24
- "--backend",
25
- "--ts",
26
- "--js",
27
- "--structure",
28
- "--pm",
29
- "--template",
30
- "--no-start",
31
- "--no-update-check",
32
- "--no-git",
33
- ];
34
- const valueOptions = new Set(["--icons", "--backend", "--structure", "--pm", "--template"]);
35
- const optionNames = new Set(allowedOptions);
36
- const positionalArgs = [];
37
- const optionErrors = [];
38
- for (let index = 0; index < args.length; index += 1) {
39
- const argument = args[index];
40
- if (!argument.startsWith("--")) {
41
- positionalArgs.push(argument);
42
- continue;
43
- }
44
- const separator = argument.indexOf("=");
45
- const name = separator === -1 ? argument : argument.slice(0, separator);
46
- if (!optionNames.has(name)) {
47
- optionErrors.push(`Unknown option: ${name}`);
48
- continue;
49
- }
50
- if (valueOptions.has(name)) {
51
- if (separator === -1 || !argument.slice(separator + 1)) {
52
- optionErrors.push(`${name} requires a value in the form ${name}=<value>`);
53
- if (separator === -1 && args[index + 1] && !args[index + 1].startsWith("--")) {
54
- index += 1;
55
- }
56
- }
57
- } else if (separator !== -1) {
58
- optionErrors.push(`${name} does not accept a value`);
59
- }
60
- }
61
- const readOption = (name) =>
62
- args.find((argument) => argument.startsWith(`--${name}=`))?.slice(name.length + 3);
63
- const hasOption = (name) => args.includes(`--${name}`);
64
- const yes = hasOption("yes");
65
- let activeChild;
66
- let creationCancelled = false;
67
- const useDefaultStructure =
68
- hasOption("default") || process.env.npm_config_default === "true";
69
- const exposeClient = hasOption("host");
70
- const noTailwind = hasOption("no-tailwind");
71
- const noAxios = hasOption("no-axios");
72
- const noStart = hasOption("no-start");
73
- const skipUpdateCheck =
74
- hasOption("no-update-check") || yes || process.env.CI !== undefined;
75
- const backendOption = readOption("backend");
76
- const languageOption = hasOption("ts") ? "ts" : hasOption("js") ? "js" : null;
77
- const structureOption = readOption("structure");
78
- const requestedPackageManager = readOption("pm");
79
- const templateOption = readOption("template");
80
- const iconsOption = readOption("icons");
81
- if (backendOption !== undefined && !["none", "basic", "express"].includes(backendOption)) {
82
- optionErrors.push("--backend must be none, basic, or express");
83
- }
84
- if (hasOption("ts") && hasOption("js")) {
85
- optionErrors.push("Use only one of --ts or --js");
86
- }
87
- if (hasOption("router") && hasOption("no-router")) {
88
- optionErrors.push("Use only one of --router or --no-router");
89
- }
90
- if (structureOption !== undefined && !["simple", "module"].includes(structureOption)) {
91
- optionErrors.push("--structure must be simple or module");
92
- }
93
- if (
94
- requestedPackageManager !== undefined &&
95
- !["npm", "pnpm"].includes(requestedPackageManager)
96
- ) {
97
- optionErrors.push("--pm must be npm or pnpm");
98
- }
99
- if (noTailwind && hasOption("tailwind")) {
100
- optionErrors.push("Use only one of --tailwind or --no-tailwind");
101
- }
102
- if (noAxios && hasOption("axios")) {
103
- optionErrors.push("Use only one of --axios or --no-axios");
104
- }
105
- if (
106
- iconsOption !== undefined &&
107
- !["react-icons", "animateicons", "none"].includes(iconsOption)
108
- ) {
109
- optionErrors.push("--icons must be react-icons, animateicons, or none");
110
- }
111
- if (args.some((argument) => argument.startsWith("--template=")) && !templateOption) {
112
- optionErrors.push("--template must include a template name");
113
- }
114
- if (optionErrors.length) {
115
- console.error(
116
- `${optionErrors.join("\n")}\nAllowed options: ${allowedOptions.join(", ")}`,
117
- );
118
- process.exit(1);
119
- }
120
- let projectName = positionalArgs[0];
121
- const validProjectName = (name) => /^[a-z0-9][a-z0-9_-]*$/.test(name);
122
-
123
- if (!projectName && stdin.isTTY) {
124
- const prompt = createInterface({ input: stdin, output: stdout });
125
- try {
126
- do {
127
- projectName = (await prompt.question("Project name: ")).trim();
128
- if (!validProjectName(projectName)) {
129
- console.error("Use lowercase letters, numbers, hyphens, or underscores.");
130
- }
131
- } while (!validProjectName(projectName));
132
- } finally {
133
- prompt.close();
134
- }
135
- }
136
-
137
- if (!projectName || !validProjectName(projectName)) {
138
- console.error("Usage: create-vanilla-vite <lowercase-project-name>");
139
- if (!projectName && !stdin.isTTY) {
140
- console.error("Run this command in an interactive terminal to be prompted for a name.");
141
- }
142
- process.exit(1);
143
- }
144
-
145
- const packageManager =
146
- requestedPackageManager ??
147
- (process.env.npm_config_user_agent?.startsWith("pnpm/") ? "pnpm" : "npm");
148
- const root = resolve(process.cwd(), projectName);
149
- let rootCreated = false;
150
- const clientFolder = `${projectName}-client`;
151
- const serverFolder = `${projectName}-server`;
152
- const packageRoot = fileURLToPath(new URL("../", import.meta.url));
153
- const scriptRoot = fileURLToPath(new URL("../scripts/", import.meta.url));
154
- const cliPackage = JSON.parse(
155
- await readFile(join(packageRoot, "package.json"), "utf8"),
156
- );
157
- const delay = (milliseconds) =>
158
- new Promise((resolveDelay) => setTimeout(resolveDelay, milliseconds));
159
- const removeIncompleteProject = async () => {
160
- process.off("SIGINT", handleCreationSignal);
161
- process.off("SIGTERM", handleCreationSignal);
162
- if (!rootCreated) return;
163
- rootCreated = false;
164
- for (let attempt = 0; attempt < 6; attempt += 1) {
165
- try {
166
- await rm(root, { recursive: true, force: true });
167
- return;
168
- } catch (error) {
169
- if (!["EBUSY", "ENOTEMPTY"].includes(error.code) || attempt === 5) {
170
- console.error(`Unable to remove the incomplete project directory: ${error.message}`);
171
- return;
172
- }
173
- await delay(100 * (attempt + 1));
174
- }
175
- }
176
- };
177
- const handleCreationSignal = async () => {
178
- if (creationCancelled) return;
179
- creationCancelled = true;
180
- const child = activeChild;
181
- if (child && child.exitCode === null && child.signalCode === null) {
182
- child.kill("SIGTERM");
183
- await Promise.race([
184
- new Promise((resolveClose) => child.once("close", resolveClose)),
185
- delay(3000),
186
- ]);
187
- if (child.exitCode === null && child.signalCode === null) {
188
- child.kill("SIGKILL");
189
- await new Promise((resolveClose) => child.once("close", resolveClose));
190
- }
191
- }
192
- await removeIncompleteProject();
193
- process.exit(130);
194
- };
195
-
196
- function parseSemver(version) {
197
- const match =
198
- /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version);
199
- if (!match) throw new Error(`Invalid semantic version: ${version}`);
200
- const prerelease = match[4]?.split(".") ?? [];
201
- return {
202
- major: BigInt(match[1]),
203
- minor: BigInt(match[2]),
204
- patch: BigInt(match[3]),
205
- prerelease,
206
- };
207
- }
208
-
209
- function compareSemver(left, right) {
210
- const a = parseSemver(left);
211
- const b = parseSemver(right);
212
- for (const component of ["major", "minor", "patch"]) {
213
- if (a[component] !== b[component]) {
214
- return a[component] < b[component] ? -1 : 1;
215
- }
216
- }
217
- if (!a.prerelease.length || !b.prerelease.length) {
218
- return a.prerelease.length === b.prerelease.length
219
- ? 0
220
- : a.prerelease.length
221
- ? -1
222
- : 1;
223
- }
224
- const length = Math.max(a.prerelease.length, b.prerelease.length);
225
- for (let index = 0; index < length; index += 1) {
226
- const leftId = a.prerelease[index];
227
- const rightId = b.prerelease[index];
228
- if (leftId === undefined || rightId === undefined) {
229
- return leftId === rightId ? 0 : leftId === undefined ? -1 : 1;
230
- }
231
- if (leftId === rightId) continue;
232
- const leftNumeric = /^\d+$/.test(leftId);
233
- const rightNumeric = /^\d+$/.test(rightId);
234
- if (leftNumeric && rightNumeric) {
235
- return BigInt(leftId) < BigInt(rightId) ? -1 : 1;
236
- }
237
- if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
238
- return leftId < rightId ? -1 : 1;
239
- }
240
- return 0;
241
- }
242
-
243
- async function updateIfOutdated() {
244
- if (skipUpdateCheck) return;
245
- const { version: installedVersion } = cliPackage;
246
- const registry = (process.env.npm_config_registry || "https://registry.npmjs.org")
247
- .replace(/\/$/, "");
248
-
249
- let latestVersion;
250
- try {
251
- const response = await fetch(`${registry}/create-vanilla-vite/latest`, {
252
- signal: AbortSignal.timeout(3000),
253
- });
254
- if (!response.ok) throw new Error(`registry returned HTTP ${response.status}`);
255
- latestVersion = (await response.json()).version;
256
- if (typeof latestVersion !== "string") {
257
- throw new Error("registry response did not include a version");
258
- }
259
- } catch (error) {
260
- console.warn(`\nCould not check for CLI updates: ${error.message}`);
261
- return;
262
- }
263
-
264
- try {
265
- if (compareSemver(latestVersion, installedVersion) <= 0) return;
266
- } catch (error) {
267
- console.warn(`\nCould not compare CLI versions: ${error.message}`);
268
- return;
269
- }
270
- if (!stdin.isTTY) {
271
- console.warn(
272
- `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}). Run ${packageManager} create vanilla-vite@latest to use it.`,
273
- );
274
- return;
275
- }
276
-
277
- console.warn(
278
- `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}).`,
279
- );
280
- const useLatest = await selectOption("Which version would you like to use?", [
281
- { label: `Use the latest version (${latestVersion})`, value: true },
282
- { label: `Continue with the current version (${installedVersion})`, value: false },
283
- ]);
284
- if (!useLatest) return;
285
-
286
- const relaunchArgs = [
287
- ...args.filter((arg) => arg !== "--no-update-check"),
288
- ...(args.some((arg) => !arg.startsWith("--")) ? [] : [projectName]),
289
- "--no-update-check",
290
- ];
291
- const updateArgs =
292
- packageManager === "pnpm"
293
- ? ["dlx", "create-vanilla-vite@latest", ...relaunchArgs]
294
- : [
295
- "exec",
296
- "--yes",
297
- "--package=create-vanilla-vite@latest",
298
- "--",
299
- "create-vanilla-vite",
300
- ...relaunchArgs,
301
- ];
302
- try {
303
- await run(packageManager, updateArgs, process.cwd());
304
- } catch (error) {
305
- console.error(`Unable to start the latest CLI version: ${error.message}`);
306
- process.exit(1);
307
- }
308
- process.exit(0);
309
- }
310
-
311
- function run(command, commandArgs, cwd, env = process.env) {
312
- return new Promise((resolveRun, rejectRun) => {
313
- const child = spawn(command, commandArgs, { cwd, stdio: "inherit", env });
314
- activeChild = child;
315
- child.once("error", (error) => {
316
- if (activeChild === child) activeChild = undefined;
317
- rejectRun(error);
318
- });
319
- child.once("close", (code, signal) => {
320
- if (activeChild === child) activeChild = undefined;
321
- if (code === 0) resolveRun();
322
- else {
323
- rejectRun(
324
- new Error(`${command} exited ${signal ? `from ${signal}` : `with code ${code}`}`),
325
- );
326
- }
327
- });
328
- });
329
- }
330
-
331
- async function selectOption(question, options, defaultIndex = 0, color = "cyan") {
332
- if (!stdin.isTTY) return options[defaultIndex].value;
333
- let selected = defaultIndex;
334
- emitKeypressEvents(stdin);
335
-
336
- return new Promise((resolveSelection) => {
337
- function render() {
338
- const prompt = stdout.isTTY && process.env.NO_COLOR === undefined
339
- ? `\x1b[1;${color === "cyan" ? "36" : "33"}m${question}\x1b[0m`
340
- : question;
341
- stdout.write(`\r\x1b[2K${prompt}\n`);
342
- for (const [index, option] of options.entries()) {
343
- stdout.write(` ${index === selected ? "❯" : " "} ${option.label}\n`);
344
- }
345
- stdout.write(" Use ↑/↓ to select, Enter to confirm, or Esc to keep the default.\n");
346
- stdout.write(`\x1b[${options.length + 2}A`);
347
- }
348
-
349
- function finish(value) {
350
- stdin.off("keypress", onKeypress);
351
- stdin.setRawMode(false);
352
- stdin.pause();
353
- stdout.write(`\x1b[${options.length + 2}B\n`);
354
- resolveSelection(value);
355
- }
356
-
357
- function onKeypress(_input, key) {
358
- if (key?.name === "up" || key?.name === "down") {
359
- selected =
360
- (selected + (key.name === "down" ? 1 : options.length - 1)) %
361
- options.length;
362
- render();
363
- } else if (key?.name === "return") finish(options[selected].value);
364
- else if (key?.name === "escape") {
365
- finish(options[defaultIndex].value);
366
- } else if (key?.ctrl && key.name === "c") {
367
- stdin.off("keypress", onKeypress);
368
- stdin.setRawMode(false);
369
- stdin.pause();
370
- stdout.write(`\x1b[${options.length + 2}B\n`);
371
- void handleCreationSignal();
372
- }
373
- }
374
-
375
- stdin.setRawMode(true);
376
- stdin.resume();
377
- stdin.on("keypress", onKeypress);
378
- render();
379
- });
380
- }
381
-
382
- function chooseOption(question, options, defaultIndex = 0, color = "cyan") {
383
- return yes
384
- ? Promise.resolve(options[defaultIndex].value)
385
- : selectOption(question, options, defaultIndex, color);
386
- }
387
-
388
- async function configureTailwind(clientRoot) {
389
- let viteConfigName = (await readdir(clientRoot)).find((file) =>
390
- /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
391
- );
392
- if (!viteConfigName) {
393
- const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
394
- viteConfigName = `vite.config.${isTypeScript ? "ts" : "js"}`;
395
- await writeFile(
396
- join(clientRoot, viteConfigName),
397
- 'import { defineConfig } from "vite";\n' +
398
- 'import tailwindcss from "@tailwindcss/vite";\n\n' +
399
- "export default defineConfig({\n" +
400
- " plugins: [tailwindcss()],\n" +
401
- "});\n",
402
- );
403
- }
404
-
405
- const viteConfigPath = join(clientRoot, viteConfigName);
406
- let viteConfig = await readFile(viteConfigPath, "utf8");
407
- if (!viteConfig.includes("@tailwindcss/vite")) {
408
- viteConfig = `import tailwindcss from "@tailwindcss/vite";\n${viteConfig}`;
409
- const plugins = /(\bplugins\s*:\s*\[)/;
410
- if (plugins.test(viteConfig)) {
411
- viteConfig = viteConfig.replace(plugins, "$1tailwindcss(), ");
412
- } else {
413
- const configObject = /(\bdefineConfig\s*\(\s*\{)/;
414
- if (!configObject.test(viteConfig)) {
415
- throw new Error("Could not add Tailwind CSS to the Vite config.");
416
- }
417
- viteConfig = viteConfig.replace(configObject, "$1\n plugins: [tailwindcss()],");
418
- }
419
- }
420
- await writeFile(viteConfigPath, viteConfig);
421
-
422
- let entryPath;
423
- for (const directory of [join(clientRoot, "src"), clientRoot]) {
424
- let files;
425
- try {
426
- files = await readdir(directory);
427
- } catch (error) {
428
- if (error.code === "ENOENT") continue;
429
- throw error;
430
- }
431
- const entryFile = files.find((file) => /^main\.[cm]?[jt]sx?$/.test(file));
432
- if (entryFile) {
433
- entryPath = join(directory, entryFile);
434
- break;
435
- }
436
- }
437
- if (!entryPath) {
438
- throw new Error("Could not find the frontend entry file to configure Tailwind CSS.");
439
- }
440
- const entry = await readFile(entryPath, "utf8");
441
- let cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
442
- if (!cssImport) {
443
- const cssPath = join(dirname(entryPath), "style.css");
444
- await writeFile(cssPath, '@import "tailwindcss";\n');
445
- await writeFile(entryPath, `import "./style.css";\n${entry}`);
446
- cssImport = ['import "./style.css";', "./style.css"];
447
- }
448
- const cssPath = resolve(dirname(entryPath), cssImport[1]);
449
- const css = await readFile(cssPath, "utf8");
450
- if (!css.includes('@import "tailwindcss";')) {
451
- await writeFile(cssPath, `@import "tailwindcss";\n${css}`);
452
- }
453
- }
454
-
455
- async function configureStrictPort(clientRoot) {
456
- let configName = (await readdir(clientRoot)).find((file) =>
457
- /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
458
- );
459
- if (!configName) {
460
- const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
461
- configName = `vite.config.${isTypeScript ? "ts" : "js"}`;
462
- await writeFile(
463
- join(clientRoot, configName),
464
- 'import { defineConfig } from "vite";\n\nexport default defineConfig({});\n',
465
- );
466
- }
467
-
468
- const configPath = join(clientRoot, configName);
469
- let config = await readFile(configPath, "utf8");
470
- if (/\bstrictPort\s*:/.test(config)) {
471
- config = config.replace(/\bstrictPort\s*:\s*(?:true|false)/, "strictPort: true");
472
- } else if (/\bserver\s*:\s*\{/.test(config)) {
473
- config = config.replace(/\bserver\s*:\s*\{/, "server: { strictPort: true,");
474
- } else {
475
- const configObject = /(\bdefineConfig\s*\(\s*\{|\bexport\s+default\s*\{)/;
476
- if (!configObject.test(config)) {
477
- console.warn(
478
- `Could not configure strictPort in ${configName}; the Vite config shape was not recognized.`,
479
- );
480
- return;
481
- }
482
- config = config.replace(configObject, "$1\n server: { strictPort: true },");
483
- }
484
- await writeFile(configPath, config);
485
- }
486
-
487
- async function scaffoldReactRouter(clientRoot, useTailwind) {
488
- const sourceRoot = join(clientRoot, "src");
489
- const sourceFiles = await readdir(sourceRoot);
490
- const appFile = sourceFiles.find((file) => /^App\.(?:jsx|tsx)$/.test(file));
491
- const entryFile = sourceFiles.find((file) => /^main\.(?:jsx|tsx)$/.test(file));
492
- if (!appFile || !entryFile) {
493
- throw new Error("Could not find the React app and entry files to configure routing.");
494
- }
495
-
496
- const typed = appFile.endsWith(".tsx");
497
- const extension = typed ? "tsx" : "jsx";
498
- const appPath = join(sourceRoot, appFile);
499
- const entryPath = join(sourceRoot, entryFile);
500
- const entry = await readFile(entryPath, "utf8");
501
- const cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
502
- if (!cssImport) {
503
- throw new Error("Could not find a CSS import for the React Router starter.");
504
- }
505
-
506
- const cssPath = resolve(sourceRoot, cssImport[1]);
507
- const tailwindImport = (await readFile(cssPath, "utf8"))
508
- .includes('@import "tailwindcss";')
509
- ? '@import "tailwindcss";\n'
510
- : "";
511
- const styles = useTailwind
512
- ? {
513
- shell: "min-h-screen flex flex-col bg-[#f5f7f4] text-[#17231f]",
514
- container: "w-[calc(100%_-_2rem)] sm:w-[calc(100%_-_3rem)] max-w-[1040px] mx-auto",
515
- header: "min-h-[72px] sm:min-h-[84px] flex items-center justify-between border-b border-[#dfe6df]",
516
- brand: "flex items-center gap-[10px] text-sm font-bold text-[#17231f] no-underline",
517
- brandMark: "w-[30px] h-[30px] grid place-items-center rounded-[9px] bg-[#315d4a] text-white",
518
- nav: "flex items-center gap-2",
519
- navLink: "min-h-10 flex items-center px-[10px] sm:px-[14px] rounded-lg text-sm text-[#5b6861] no-underline hover:bg-[#e7eee8] hover:text-[#244b39]",
520
- navActive: "bg-[#e7eee8] text-[#244b39]",
521
- page: "flex-1",
522
- footer: "py-6 border-t border-[#dfe6df] text-[13px] text-[#78857d]",
523
- home: "py-[72px] sm:pt-[clamp(72px,12vw,132px)] sm:pb-[84px]",
524
- eyebrow: "text-xs font-bold tracking-[0.12em] text-[#557663]",
525
- title: "max-w-[680px] my-[18px] text-[clamp(40px,7vw,68px)] font-semibold leading-[1.05] tracking-[-0.055em]",
526
- authTitle: "max-w-[680px] my-[18px] text-[clamp(38px,7vw,52px)] font-semibold leading-[1.05] tracking-[-0.055em]",
527
- copy: "max-w-[550px] mb-7 text-[17px] leading-[1.7] text-[#627068]",
528
- button: "min-h-[46px] inline-flex items-center justify-center gap-[14px] px-[18px] rounded-lg font-semibold no-underline cursor-pointer",
529
- buttonPrimary: "bg-[#315d4a] text-white hover:bg-[#244b39]",
530
- grid: "grid grid-cols-1 sm:grid-cols-2 gap-4 mt-14 sm:mt-[72px]",
531
- card: "min-h-[164px] p-6 border border-[#dfe6df] rounded-xl bg-[#fbfcfa]",
532
- cardIndex: "text-xs font-bold tracking-[0.12em] text-[#557663]",
533
- cardTitle: "mt-4 mb-2 text-lg",
534
- cardCopy: "m-0 leading-[1.6] text-[#627068]",
535
- code: "text-[#315d4a]",
536
- auth: "w-full max-w-[440px] mx-auto py-[88px] pb-[72px]",
537
- authIntro: "",
538
- authCopy: "max-w-[550px] mb-8 text-[17px] leading-[1.7] text-[#627068]",
539
- form: "grid gap-[10px]",
540
- label: "mt-2 text-sm font-semibold text-[#35443c]",
541
- input: "w-full min-h-[46px] px-[13px] border border-[#ccd7ce] rounded-lg bg-white text-[#17231f] focus:border-[#557663] focus:outline-3 focus:outline-[#dce8df]",
542
- formButton: "mt-3",
543
- notice: "min-h-6 m-0 text-sm leading-[1.5] text-[#557663]",
544
- back: "inline-block mt-[18px] text-sm text-[#486353] hover:underline",
545
- }
546
- : {
547
- shell: "app-shell",
548
- container: "layout-container",
549
- header: "site-header",
550
- brand: "brand",
551
- brandMark: "brand-mark",
552
- nav: "site-nav",
553
- navLink: "nav-link",
554
- navActive: "is-active",
555
- page: "page-content",
556
- footer: "site-footer",
557
- home: "home-page",
558
- eyebrow: "eyebrow",
559
- title: "",
560
- authTitle: "",
561
- copy: "hero-copy",
562
- button: "button",
563
- buttonPrimary: "button-primary",
564
- grid: "route-grid",
565
- card: "route-card",
566
- cardIndex: "card-index",
567
- cardTitle: "",
568
- cardCopy: "",
569
- code: "",
570
- auth: "auth-page",
571
- authIntro: "auth-intro",
572
- authCopy: "hero-copy",
573
- form: "login-form",
574
- label: "",
575
- input: "",
576
- formButton: "",
577
- notice: "form-notice",
578
- back: "back-link",
579
- };
580
- const appCssImport = useTailwind ? "" : 'import "./App.css";\n';
581
- const homeDirectory = join(sourceRoot, "Pages", "Home");
582
- const authDirectory = join(sourceRoot, "Pages", "Auth");
583
- await Promise.all([
584
- mkdir(homeDirectory, { recursive: true }),
585
- mkdir(authDirectory, { recursive: true }),
586
- ]);
587
- await Promise.all([
588
- writeFile(
589
- join(sourceRoot, `MainRouter.${extension}`),
590
- `import { createBrowserRouter } from "react-router";
591
- import App from "./App";
592
- import Home from "./Pages/Home/Home";
593
- import AuthPage from "./Pages/Auth/AuthPage";
594
-
595
- const MainRouter = createBrowserRouter([
596
- {
597
- path: "/",
598
- element: <App />,
599
- children: [
600
- { index: true, element: <Home /> },
601
- { path: "login", element: <AuthPage /> },
602
- ],
603
- },
604
- ]);
605
-
606
- // eslint-disable-next-line react-refresh/only-export-components
607
- export default MainRouter;
608
- `,
609
- ),
610
- writeFile(
611
- appPath,
612
- `import { NavLink, Outlet } from "react-router";
613
- ${appCssImport}
614
-
615
- function App() {
616
- return (
617
- <div className="${styles.shell}">
618
- <header className="${styles.container} ${styles.header}">
619
- <NavLink className="${styles.brand}" to="/" end>
620
- <span className="${styles.brandMark}" aria-hidden="true">V</span>
621
- <span>Workspace starter</span>
622
- </NavLink>
623
- <nav className="${styles.nav}" aria-label="Main navigation">
624
- <NavLink to="/" end className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
625
- Home
626
- </NavLink>
627
- <NavLink to="/login" className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
628
- Login
629
- </NavLink>
630
- </nav>
631
- </header>
632
- <main className="${styles.container} ${styles.page}">
633
- <Outlet />
634
- </main>
635
- <footer className="${styles.container} ${styles.footer}">A small starting point for your next project.</footer>
636
- </div>
637
- );
638
- }
639
-
640
- export default App;
641
- `,
642
- ),
643
- writeFile(
644
- join(homeDirectory, `Home.${extension}`),
645
- `import { Link } from "react-router";
646
-
647
- function Home() {
648
- return (
649
- <section className="${styles.home}">
650
- <p className="${styles.eyebrow}">YOUR PROJECT STARTS HERE</p>
651
- <h1 className="${styles.title}">A faster start for your next project.</h1>
652
- <p className="${styles.copy}">
653
- This starter makes setting up your development environment quick and
654
- straightforward. React Router is ready with Home and Login pages so you
655
- can test navigation right away.
656
- </p>
657
- <Link className="${styles.button} ${styles.buttonPrimary}" to="/login">Visit the login page <span aria-hidden="true">→</span></Link>
658
- <div className="${styles.grid}">
659
- <article className="${styles.card}">
660
- <span className="${styles.cardIndex}">01</span>
661
- <h2 className="${styles.cardTitle}">Home</h2>
662
- <p className="${styles.cardCopy}">An example landing page at <code className="${styles.code}">/</code> to help you get started.</p>
663
- </article>
664
- <article className="${styles.card}">
665
- <span className="${styles.cardIndex}">02</span>
666
- <h2 className="${styles.cardTitle}">Login</h2>
667
- <p className="${styles.cardCopy}">A sample page at <code className="${styles.code}">/login</code> for checking route navigation.</p>
668
- </article>
669
- </div>
670
- </section>
671
- );
672
- }
673
-
674
- export default Home;
675
- `,
676
- ),
677
- writeFile(
678
- join(authDirectory, `AuthPage.${extension}`),
679
- `import { useState${typed ? ", type FormEvent" : ""} } from "react";
680
- import { Link } from "react-router";
681
-
682
- function AuthPage() {
683
- const [notice, setNotice] = useState("");
684
-
685
- function handleSubmit(event${typed ? ": FormEvent<HTMLFormElement>" : ""}) {
686
- event.preventDefault();
687
- setNotice("This starter form is ready to connect to your authentication service.");
688
- }
689
-
690
- return (
691
- <section className="${styles.auth}">
692
- <div className="${styles.authIntro}">
693
- <p className="${styles.eyebrow}">WELCOME BACK</p>
694
- <h1 className="${styles.authTitle}">Login</h1>
695
- <p className="${styles.authCopy}">Sign in to continue to your workspace.</p>
696
- </div>
697
- <form className="${styles.form}" onSubmit={handleSubmit}>
698
- <label className="${styles.label}" htmlFor="email">Email address</label>
699
- <input className="${styles.input}" id="email" name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
700
- <label className="${styles.label}" htmlFor="password">Password</label>
701
- <input className="${styles.input}" id="password" name="password" type="password" autoComplete="current-password" placeholder="Enter your password" required />
702
- <button className="${styles.button} ${styles.buttonPrimary} ${styles.formButton}" type="submit">Continue</button>
703
- <p className="${styles.notice}" role="status">{notice}</p>
704
- </form>
705
- <Link className="${styles.back}" to="/">← Back to home</Link>
706
- </section>
707
- );
708
- }
709
-
710
- export default AuthPage;
711
- `,
712
- ),
713
- writeFile(
714
- cssPath,
715
- useTailwind
716
- ? tailwindImport
717
- : `${tailwindImport}:root {
718
- font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
719
- color: #17231f;
720
- background: #f5f7f4;
721
- font-synthesis: none;
722
- text-rendering: optimizeLegibility;
723
- -webkit-font-smoothing: antialiased;
724
- -moz-osx-font-smoothing: grayscale;
725
- }
726
-
727
- * {
728
- box-sizing: border-box;
729
- }
730
-
731
- body {
732
- min-width: 320px;
733
- min-height: 100vh;
734
- margin: 0;
735
- }
736
-
737
- button,
738
- input {
739
- font: inherit;
740
- }
741
-
742
- a {
743
- color: inherit;
744
- }
745
- `,
746
- ),
747
- ...(!useTailwind
748
- ? [
749
- writeFile(
750
- join(sourceRoot, "App.css"),
751
- `.app-shell {
752
- min-height: 100vh;
753
- display: flex;
754
- flex-direction: column;
755
- }
756
-
757
- .layout-container,
758
- .site-header,
759
- .page-content,
760
- .site-footer {
761
- width: min(100% - 48px, 1040px);
762
- margin-inline: auto;
763
- }
764
-
765
- .site-header {
766
- min-height: 84px;
767
- display: flex;
768
- align-items: center;
769
- justify-content: space-between;
770
- border-bottom: 1px solid #dfe6df;
771
- }
772
-
773
- .brand,
774
- .site-nav,
775
- .nav-link {
776
- display: flex;
777
- align-items: center;
778
- }
779
-
780
- .brand {
781
- gap: 10px;
782
- color: #17231f;
783
- font-size: 14px;
784
- font-weight: 700;
785
- text-decoration: none;
786
- }
787
-
788
- .brand-mark {
789
- width: 30px;
790
- height: 30px;
791
- display: grid;
792
- place-items: center;
793
- border-radius: 9px;
794
- background: #315d4a;
795
- color: #fff;
796
- }
797
-
798
- .site-nav {
799
- gap: 8px;
800
- }
801
-
802
- .nav-link {
803
- min-height: 40px;
804
- padding: 0 14px;
805
- border-radius: 8px;
806
- color: #5b6861;
807
- font-size: 14px;
808
- text-decoration: none;
809
- }
810
-
811
- .nav-link:hover,
812
- .nav-link.is-active {
813
- background: #e7eee8;
814
- color: #244b39;
815
- }
816
-
817
- .page-content {
818
- flex: 1;
819
- }
820
-
821
- .home-page {
822
- padding: clamp(72px, 12vw, 132px) 0 84px;
823
- }
824
-
825
- .eyebrow,
826
- .card-index {
827
- color: #557663;
828
- font-size: 12px;
829
- font-weight: 700;
830
- letter-spacing: 0.12em;
831
- }
832
-
833
- .home-page h1,
834
- .auth-intro h1 {
835
- max-width: 680px;
836
- margin: 18px 0;
837
- font-size: clamp(40px, 7vw, 68px);
838
- font-weight: 600;
839
- letter-spacing: -0.055em;
840
- line-height: 1.05;
841
- }
842
-
843
- .hero-copy {
844
- max-width: 550px;
845
- margin: 0 0 28px;
846
- color: #627068;
847
- font-size: 17px;
848
- line-height: 1.7;
849
- }
850
-
851
- .button {
852
- min-height: 46px;
853
- display: inline-flex;
854
- align-items: center;
855
- justify-content: center;
856
- gap: 14px;
857
- padding: 0 18px;
858
- border: 0;
859
- border-radius: 8px;
860
- cursor: pointer;
861
- font-weight: 600;
862
- text-decoration: none;
863
- }
864
-
865
- .button-primary {
866
- background: #315d4a;
867
- color: white;
868
- }
869
-
870
- .button-primary:hover {
871
- background: #244b39;
872
- }
873
-
874
- .route-grid {
875
- display: grid;
876
- grid-template-columns: repeat(2, minmax(0, 1fr));
877
- gap: 16px;
878
- margin-top: 72px;
879
- }
880
-
881
- .route-card {
882
- min-height: 164px;
883
- padding: 24px;
884
- border: 1px solid #dfe6df;
885
- border-radius: 12px;
886
- background: #fbfcfa;
887
- }
888
-
889
- .route-card h2 {
890
- margin: 16px 0 8px;
891
- font-size: 18px;
892
- }
893
-
894
- .route-card p {
895
- margin: 0;
896
- color: #627068;
897
- line-height: 1.6;
898
- }
899
-
900
- .route-card code {
901
- color: #315d4a;
902
- }
903
-
904
- .auth-page {
905
- width: min(100%, 440px);
906
- margin: 0 auto;
907
- padding: 88px 0 72px;
908
- }
909
-
910
- .auth-intro h1 {
911
- font-size: clamp(38px, 7vw, 52px);
912
- }
913
-
914
- .auth-intro .hero-copy {
915
- margin-bottom: 32px;
916
- }
917
-
918
- .login-form {
919
- display: grid;
920
- gap: 10px;
921
- }
922
-
923
- .login-form label {
924
- margin-top: 8px;
925
- color: #35443c;
926
- font-size: 14px;
927
- font-weight: 600;
928
- }
929
-
930
- .login-form input {
931
- width: 100%;
932
- min-height: 46px;
933
- padding: 0 13px;
934
- border: 1px solid #ccd7ce;
935
- border-radius: 8px;
936
- background: #fff;
937
- color: #17231f;
938
- }
939
-
940
- .login-form input:focus {
941
- border-color: #557663;
942
- outline: 3px solid #dce8df;
943
- }
944
-
945
- .login-form .button {
946
- margin-top: 12px;
947
- }
948
-
949
- .form-notice {
950
- min-height: 24px;
951
- margin: 2px 0 0;
952
- color: #557663;
953
- font-size: 14px;
954
- line-height: 1.5;
955
- }
956
-
957
- .back-link {
958
- display: inline-block;
959
- margin-top: 18px;
960
- color: #486353;
961
- font-size: 14px;
962
- text-decoration: none;
963
- }
964
-
965
- .back-link:hover {
966
- text-decoration: underline;
967
- }
968
-
969
- .site-footer {
970
- padding: 24px 0;
971
- border-top: 1px solid #dfe6df;
972
- color: #78857d;
973
- font-size: 13px;
974
- }
975
-
976
- @media (max-width: 560px) {
977
- .site-header,
978
- .page-content,
979
- .site-footer {
980
- width: min(100% - 32px, 1040px);
981
- }
982
-
983
- .site-header {
984
- min-height: 72px;
985
- }
986
-
987
- .nav-link {
988
- padding: 0 10px;
989
- }
990
-
991
- .route-grid {
992
- grid-template-columns: 1fr;
993
- margin-top: 56px;
994
- }
995
- }
996
- `,
997
- ),
998
- ]
999
- : []),
1000
- writeFile(
1001
- entryPath,
1002
- `import { StrictMode } from "react";
1003
- import { createRoot } from "react-dom/client";
1004
- import { RouterProvider } from "react-router/dom";
1005
- import MainRouter from "./MainRouter";
1006
- ${cssImport[0]};
1007
-
1008
- createRoot(document.getElementById("root")${typed ? "!" : ""}).render(
1009
- <StrictMode>
1010
- <RouterProvider router={MainRouter} />
1011
- </StrictMode>,
1012
- );
1013
- `,
1014
- ),
1015
- ]);
1016
-
1017
- return true;
1018
- }
1019
-
1020
- async function scaffoldBackendStatus(clientRoot) {
1021
- const indexPath = join(clientRoot, "index.html");
1022
- const html = await readFile(indexPath, "utf8");
1023
- if (!/<\/body\s*>/i.test(html)) {
1024
- throw new Error("Could not find the closing body tag for the backend status control.");
1025
- }
1026
- await writeFile(
1027
- indexPath,
1028
- html.replace(
1029
- /<\/body\s*>/i,
1030
- ' <script type="module" src="/backend-status.js"></script>\n</body>',
1031
- ),
1032
- );
1033
- await writeFile(
1034
- join(clientRoot, "backend-status.js"),
1035
- `if (import.meta.env.DEV) {
1036
- import("./backend-status.css");
1037
- const apiUrl = (import.meta.env.VITE_API_URL || "http://localhost:4000").replace(/\\/+$/, "");
1038
- const panel = document.createElement("aside");
1039
- panel.className = "backend-status";
1040
- panel.setAttribute("aria-label", "Backend connection");
1041
- panel.innerHTML = \`
1042
- <span class="backend-status__dot" aria-hidden="true"></span>
1043
- <div class="backend-status__content">
1044
- <strong class="backend-status__title">Backend</strong>
1045
- <span class="backend-status__message" role="status" aria-live="polite">Not checked yet</span>
1046
- </div>
1047
- <button class="backend-status__button" type="button">Check connection</button>
1048
- \`;
1049
-
1050
- const message = panel.querySelector(".backend-status__message");
1051
- const button = panel.querySelector(".backend-status__button");
1052
- button.addEventListener("click", async () => {
1053
- button.disabled = true;
1054
- panel.dataset.state = "checking";
1055
- message.textContent = "Checking…";
1056
- const controller = new AbortController();
1057
- const timeout = setTimeout(() => controller.abort(), 5000);
1058
- try {
1059
- const response = await fetch(\`\${apiUrl}/api/health\`, {
1060
- headers: { Accept: "application/json" },
1061
- signal: controller.signal,
1062
- });
1063
- const result = await response.json();
1064
- if (!response.ok || result.status !== "ok") {
1065
- throw new Error("Backend health check returned an unexpected response.");
1066
- }
1067
- panel.dataset.state = "connected";
1068
- message.textContent = "Connected";
1069
- } catch {
1070
- panel.dataset.state = "disconnected";
1071
- message.textContent = "Unavailable — check the server and network";
1072
- } finally {
1073
- clearTimeout(timeout);
1074
- button.disabled = false;
1075
- }
1076
- });
1077
-
1078
- document.body.append(panel);
1079
- }
1080
- `,
1081
- );
1082
- await writeFile(
1083
- join(clientRoot, "backend-status.css"),
1084
- `.backend-status {
1085
- position: fixed;
1086
- z-index: 1000;
1087
- right: 18px;
1088
- bottom: 18px;
1089
- display: grid;
1090
- grid-template-columns: 9px minmax(0, 1fr) auto;
1091
- align-items: center;
1092
- gap: 12px;
1093
- width: min(390px, calc(100vw - 36px));
1094
- padding: 14px;
1095
- border: 1px solid #dfe6df;
1096
- border-radius: 12px;
1097
- background: #fbfcfa;
1098
- color: #17231f;
1099
- box-shadow: 0 8px 28px rgb(23 35 31 / 12%);
1100
- font: 13px/1.4 Inter, ui-sans-serif, system-ui, sans-serif;
1101
- }
1102
-
1103
- .backend-status__dot {
1104
- width: 9px;
1105
- height: 9px;
1106
- border-radius: 50%;
1107
- background: #9aa59e;
1108
- }
1109
-
1110
- .backend-status[data-state="checking"] .backend-status__dot {
1111
- background: #c28a30;
1112
- }
1113
-
1114
- .backend-status[data-state="connected"] .backend-status__dot {
1115
- background: #31835b;
1116
- }
1117
-
1118
- .backend-status[data-state="disconnected"] .backend-status__dot {
1119
- background: #bd4d43;
1120
- }
1121
-
1122
- .backend-status__content {
1123
- display: grid;
1124
- gap: 2px;
1125
- min-width: 0;
1126
- }
1127
-
1128
- .backend-status__title {
1129
- font-size: 13px;
1130
- }
1131
-
1132
- .backend-status__message {
1133
- color: #627068;
1134
- font-size: 12px;
1135
- }
1136
-
1137
- .backend-status__button {
1138
- min-height: 36px;
1139
- padding: 0 12px;
1140
- border: 0;
1141
- border-radius: 8px;
1142
- background: #315d4a;
1143
- color: #fff;
1144
- font: inherit;
1145
- font-weight: 600;
1146
- cursor: pointer;
1147
- }
1148
-
1149
- .backend-status__button:hover:not(:disabled) {
1150
- background: #244b39;
1151
- }
1152
-
1153
- .backend-status__button:focus-visible {
1154
- outline: 3px solid #9db9a5;
1155
- outline-offset: 2px;
1156
- }
1157
-
1158
- .backend-status__button:disabled {
1159
- cursor: wait;
1160
- opacity: 0.7;
1161
- }
1162
-
1163
- @media (max-width: 420px) {
1164
- .backend-status {
1165
- right: 12px;
1166
- bottom: 12px;
1167
- width: calc(100vw - 24px);
1168
- }
1169
- }
1170
- `,
1171
- );
1172
- }
1173
-
1174
- async function configureFrontend(clientRoot, clientPackage) {
1175
- const tailwind = noTailwind
1176
- ? false
1177
- : hasOption("tailwind")
1178
- ? true
1179
- : await chooseOption("Would you like to install Tailwind CSS?", [
1180
- { label: "Yes — add Tailwind CSS v4", value: true },
1181
- { label: "No", value: false },
1182
- ]);
1183
- const axios = hasOption("axios")
1184
- ? true
1185
- : noAxios
1186
- ? false
1187
- : await chooseOption("Would you like to install Axios?", [
1188
- { label: "Yes — add Axios", value: true },
1189
- { label: "No", value: false },
1190
- ]);
1191
- const isReact = Boolean(
1192
- clientPackage.dependencies?.react || clientPackage.devDependencies?.react,
1193
- );
1194
- const installRouter =
1195
- isReact &&
1196
- (hasOption("router")
1197
- ? true
1198
- : hasOption("no-router")
1199
- ? false
1200
- : await chooseOption("Would you like to install React Router?", [
1201
- { label: "Yes — add Home and Login pages with navigation", value: true },
1202
- { label: "No", value: false },
1203
- ]));
1204
- const iconPackages = {
1205
- "react-icons": ["react-icons", "^5.7.0"],
1206
- animateicons: ["@animateicons/react", "^0.13.0"],
1207
- };
1208
- const icons =
1209
- !isReact || iconsOption === "none"
1210
- ? null
1211
- : iconsOption
1212
- ? iconPackages[iconsOption]
1213
- : (await chooseOption("Would you like to install an icon library?", [
1214
- { label: "Yes", value: true },
1215
- { label: "No", value: false },
1216
- ]))
1217
- ? await chooseOption("Which React icon library would you like to install?", [
1218
- { label: "React Icons (default)", value: iconPackages["react-icons"] },
1219
- { label: "@animateicons/react", value: iconPackages.animateicons },
1220
- ])
1221
- : null;
1222
-
1223
- if (tailwind) {
1224
- clientPackage.devDependencies ??= {};
1225
- clientPackage.devDependencies["@tailwindcss/vite"] = "^4.3.5";
1226
- clientPackage.devDependencies.tailwindcss = "^4.3.5";
1227
- await configureTailwind(clientRoot);
1228
- }
1229
- if (axios) {
1230
- clientPackage.dependencies ??= {};
1231
- clientPackage.dependencies.axios = "^1.21.1";
1232
- }
1233
- if (icons) {
1234
- clientPackage.dependencies ??= {};
1235
- clientPackage.dependencies[icons[0]] = icons[1];
1236
- }
1237
- if (installRouter) {
1238
- clientPackage.dependencies ??= {};
1239
- clientPackage.dependencies["react-router"] = "^7";
1240
- await scaffoldReactRouter(clientRoot, tailwind);
1241
- }
1242
- await configureStrictPort(clientRoot);
1243
- }
1244
-
1245
- async function copyScript(name) {
1246
- const source = await readFile(join(scriptRoot, name), "utf8");
1247
- await writeFile(join(root, "scripts", name), source);
1248
- }
1249
-
1250
- function expressErrorHandlerParameters(language) {
1251
- return language === "ts"
1252
- ? `error: unknown,
1253
- _request: import("express").Request,
1254
- response: import("express").Response,
1255
- _next: import("express").NextFunction`
1256
- : "error, _request, response, _next";
1257
- }
1258
-
1259
- function backendFiles(language, framework) {
1260
- const extension = language;
1261
- const typeAnnotation = language === "ts" ? ": number" : "";
1262
- const app = framework === "express"
1263
- ? `import cors from "cors";
1264
- import express from "express";
1265
-
1266
- export function createApp() {
1267
- const app = express();
1268
- const origins = (process.env.CORS_ORIGIN ?? "*")
1269
- .split(",")
1270
- .map((origin) => origin.trim());
1271
- app.use((request, response, next) => {
1272
- const origin = request.headers.origin;
1273
- if (origin && !origins.includes("*") && origins.includes(origin)) {
1274
- response.vary("Origin");
1275
- }
1276
- next();
1277
- });
1278
- app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
1279
- app.use(express.json());
1280
- app.get("/", (_request, response) => response.json({ message: "Backend is running" }));
1281
- app.get("/api/health", (_request, response) => response.json({ status: "ok" }));
1282
- app.use((${expressErrorHandlerParameters(language)}) => {
1283
- console.error(error);
1284
- response.status(500).json({ error: "Internal Server Error" });
1285
- });
1286
- return app;
1287
- }
1288
- `
1289
- : `import { createServer } from "node:http";
1290
- import { handleRequest } from "./basicHandler.${extension}";
1291
-
1292
- export function createApp() {
1293
- return createServer(handleRequest);
1294
- }
1295
- `;
1296
- const basicHandler =
1297
- framework === "basic"
1298
- ? `export function handleRequest(
1299
- request${language === "ts" ? ": import('node:http').IncomingMessage" : ""},
1300
- response${language === "ts" ? ": import('node:http').ServerResponse" : ""},
1301
- ) {
1302
- const origins = (process.env.CORS_ORIGIN ?? "*")
1303
- .split(",")
1304
- .map((origin) => origin.trim());
1305
- const requestOrigin = request.headers.origin;
1306
- const allowedOrigin = origins.includes("*")
1307
- ? "*"
1308
- : typeof requestOrigin === "string" && origins.includes(requestOrigin)
1309
- ? requestOrigin
1310
- : undefined;
1311
- const corsHeaders = {
1312
- ...(allowedOrigin ? { "access-control-allow-origin": allowedOrigin } : {}),
1313
- ...(allowedOrigin && allowedOrigin !== "*" ? { vary: "Origin" } : {}),
1314
- "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1315
- "access-control-allow-headers": "Content-Type, Authorization",
1316
- };
1317
-
1318
- try {
1319
- if (request.method === "OPTIONS") {
1320
- response.writeHead(204, corsHeaders);
1321
- response.end();
1322
- return;
1323
- }
1324
-
1325
- const path = new URL(request.url ?? "/", "http://localhost").pathname;
1326
- const payload =
1327
- request.method === "GET" && path === "/"
1328
- ? { status: 200, body: { message: "Backend is running" } }
1329
- : request.method === "GET" && path === "/api/health"
1330
- ? { status: 200, body: { status: "ok" } }
1331
- : { status: 404, body: { message: "Not Found" } };
1332
-
1333
- response.writeHead(payload.status, {
1334
- ...corsHeaders,
1335
- "content-type": "application/json",
1336
- });
1337
- response.end(JSON.stringify(payload.body));
1338
- } catch (error) {
1339
- console.error(error);
1340
- response.writeHead(500, {
1341
- ...corsHeaders,
1342
- "content-type": "application/json",
1343
- });
1344
- response.end(JSON.stringify({ error: "Internal Server Error" }));
1345
- }
1346
- }
1347
- `
1348
- : null;
1349
- const server = `import "dotenv/config";
1350
- import { createApp } from "./app.${extension}";
1351
-
1352
- const port${typeAnnotation} = Number(process.env.PORT ?? 4000);
1353
- const host = process.env.HOST ?? "localhost";
1354
- const app = createApp();
1355
- const server = app.listen(port, host, () => {
1356
- console.log(\`Backend listening at http://\${host}:\${port}\`);
1357
- });
1358
- for (const signal of ["SIGINT", "SIGTERM"]) {
1359
- process.once(signal, () => {
1360
- server.close((error) => {
1361
- if (error) {
1362
- console.error("Unable to close the backend server:", error);
1363
- process.exitCode = 1;
1364
- }
1365
- });
1366
- });
1367
- }
1368
- `;
1369
- return { app, server, basicHandler };
1370
- }
1371
-
1372
- async function createBackend(serverRoot) {
1373
- const language =
1374
- languageOption ??
1375
- (await chooseOption("Select a language for the backend:", [
1376
- { label: "JavaScript", value: "js" },
1377
- { label: "TypeScript", value: "ts" },
1378
- ], 0, "yellow"));
1379
- const framework =
1380
- backendOption && backendOption !== "none"
1381
- ? backendOption
1382
- : await chooseOption("Select a backend framework:", [
1383
- { label: "Basic Node.js — no additional framework", value: "basic" },
1384
- { label: "Express — install Express, CORS, and dotenv (default)", value: "express" },
1385
- ], 1, "yellow");
1386
- const structure = structureOption
1387
- ? structureOption
1388
- : useDefaultStructure
1389
- ? "simple"
1390
- : await chooseOption("Select a backend folder structure:", [
1391
- { label: "Simple — standard folders", value: "simple" },
1392
- { label: "Module-based — organized by feature (default)", value: "module" },
1393
- ], 1, "yellow");
1394
- const typed = language === "ts";
1395
- let { app, server, basicHandler } = backendFiles(language, framework);
1396
- const sourceRoot = join(serverRoot, "src");
1397
- const folders =
1398
- structure === "simple"
1399
- ? ["routes", "controllers", "middleware", "config"]
1400
- : ["module", "config", "middleware", "utils"];
1401
- for (const folder of folders) {
1402
- const folderPath = join(sourceRoot, folder);
1403
- await mkdir(folderPath, { recursive: true });
1404
- await writeFile(join(folderPath, ".gitkeep"), "");
1405
- }
1406
- if (structure === "module") {
1407
- const router =
1408
- framework === "express"
1409
- ? `import { Router } from "express";
1410
-
1411
- export const mainRouter = Router();
1412
- mainRouter.get("/", (_request, response) => {
1413
- response.json({ message: "Backend is running" });
1414
- });
1415
- mainRouter.get("/api/health", (_request, response) => {
1416
- response.json({ status: "ok" });
1417
- });
1418
- `
1419
- : `export { handleRequest } from "./basicHandler.${language}";
1420
- `;
1421
- await writeFile(join(sourceRoot, `mainRouter.${language}`), router);
1422
- app =
1423
- framework === "express"
1424
- ? `import cors from "cors";
1425
- import express from "express";
1426
- import { mainRouter } from "./mainRouter.${language}";
1427
-
1428
- export function createApp() {
1429
- const app = express();
1430
- const origins = (process.env.CORS_ORIGIN ?? "*")
1431
- .split(",")
1432
- .map((origin) => origin.trim());
1433
- app.use((request, response, next) => {
1434
- const origin = request.headers.origin;
1435
- if (origin && !origins.includes("*") && origins.includes(origin)) {
1436
- response.vary("Origin");
1437
- }
1438
- next();
1439
- });
1440
- app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
1441
- app.use(express.json());
1442
- app.use(mainRouter);
1443
- app.use((_request, response) => {
1444
- response.status(404).json({ error: "Not Found" });
1445
- });
1446
- app.use((${expressErrorHandlerParameters(language)}) => {
1447
- console.error(error);
1448
- response.status(500).json({ error: "Internal Server Error" });
1449
- });
1450
- return app;
1451
- }
1452
- `
1453
- : `import { createServer } from "node:http";
1454
- import { handleRequest } from "./mainRouter.${language}";
1455
-
1456
- export function createApp() {
1457
- return createServer(handleRequest);
1458
- }
1459
- `;
1460
- }
1461
- if (basicHandler) {
1462
- await writeFile(join(sourceRoot, `basicHandler.${language}`), basicHandler);
1463
- }
1464
- await writeFile(join(sourceRoot, `app.${language}`), app);
1465
- await writeFile(join(sourceRoot, `server.${language}`), server);
1466
-
1467
- const scripts = typed
1468
- ? framework === "basic"
1469
- ? {
1470
- dev: `tsx watch src/server.${language}`,
1471
- start: `tsx src/server.${language}`,
1472
- }
1473
- : { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
1474
- : framework === "basic"
1475
- ? {
1476
- dev: `node --watch src/server.${language}`,
1477
- start: `node src/server.${language}`,
1478
- }
1479
- : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
1480
- const dependencies =
1481
- framework === "express"
1482
- ? { express: "^5", cors: "^2.8.5", dotenv: "^16" }
1483
- : { dotenv: "^16" };
1484
- const packageJson = {
1485
- name: serverFolder,
1486
- version: "1.0.0",
1487
- private: true,
1488
- type: "module",
1489
- scripts,
1490
- ...(typed
1491
- ? {
1492
- dependencies: { ...dependencies, tsx: "^4" },
1493
- devDependencies: {
1494
- ...(framework === "express"
1495
- ? { "@types/cors": "^2.8.19", "@types/express": "^5" }
1496
- : {}),
1497
- "@types/node": "^22",
1498
- typescript: "^5",
1499
- },
1500
- }
1501
- : Object.keys(dependencies).length
1502
- ? { dependencies }
1503
- : {}),
1504
- };
1505
- await writeFile(join(serverRoot, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`);
1506
- if (typed) {
1507
- await writeFile(
1508
- join(serverRoot, "tsconfig.json"),
1509
- `${JSON.stringify(
1510
- {
1511
- compilerOptions: {
1512
- target: "ES2022",
1513
- module: "NodeNext",
1514
- moduleResolution: "NodeNext",
1515
- strict: true,
1516
- esModuleInterop: true,
1517
- skipLibCheck: true,
1518
- noEmit: true,
1519
- allowImportingTsExtensions: true,
1520
- },
1521
- include: ["**/*.ts"],
1522
- },
1523
- null,
1524
- 2,
1525
- )}\n`,
1526
- );
1527
- }
1528
- await writeFile(
1529
- join(serverRoot, ".env"),
1530
- "# Local backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
1531
- { flag: "wx" },
1532
- );
1533
- await writeFile(
1534
- join(serverRoot, ".env.example"),
1535
- "# Backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
1536
- );
1537
- }
1538
-
1539
- await updateIfOutdated();
1540
-
1541
- try {
1542
- await mkdir(root);
1543
- rootCreated = true;
1544
- process.on("SIGINT", handleCreationSignal);
1545
- process.on("SIGTERM", handleCreationSignal);
1546
- } catch (error) {
1547
- if (error.code === "EEXIST") console.error(`The destination already exists: ${root}`);
1548
- else console.error(`Unable to create project directory: ${error.message}`);
1549
- process.exit(1);
1550
- }
1551
-
1552
- let installFailed = false;
1553
- try {
1554
- console.log(`\nCreating the frontend in ${clientFolder} with create-vite...\n`);
1555
- const viteArgs =
1556
- packageManager === "pnpm"
1557
- ? [
1558
- "create",
1559
- "vite@latest",
1560
- clientFolder,
1561
- "--no-immediate",
1562
- ...(templateOption ? ["--template", templateOption] : []),
1563
- ]
1564
- : [
1565
- "create",
1566
- "vite@latest",
1567
- "--",
1568
- clientFolder,
1569
- "--no-immediate",
1570
- ...(templateOption ? ["--template", templateOption] : []),
1571
- ];
1572
- await run(packageManager, viteArgs, root);
1573
-
1574
- const clientRoot = join(root, clientFolder);
1575
- await Promise.all(
1576
- [".git", "node_modules", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"].map(
1577
- (entry) => rm(join(clientRoot, entry), { recursive: true, force: true }),
1578
- ),
1579
- );
1580
- const clientPackagePath = join(clientRoot, "package.json");
1581
- const clientPackage = JSON.parse(await readFile(clientPackagePath, "utf8"));
1582
- clientPackage.scripts ??= {};
1583
- clientPackage.scripts.start ??= clientPackage.scripts.dev;
1584
- await configureFrontend(clientRoot, clientPackage);
1585
- await writeFile(clientPackagePath, `${JSON.stringify(clientPackage, null, 2)}\n`);
1586
- await writeFile(
1587
- join(clientRoot, ".env.local"),
1588
- "# Local frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
1589
- { flag: "wx" },
1590
- );
1591
- await writeFile(
1592
- join(clientRoot, ".env.example"),
1593
- "# Frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
1594
- );
1595
-
1596
- const includeServer =
1597
- backendOption !== undefined
1598
- ? backendOption !== "none"
1599
- : await chooseOption(
1600
- "Would you like to add a separate backend server?",
1601
- [
1602
- { label: "Yes — include a backend workspace", value: true },
1603
- { label: "No — create a frontend-only project", value: false },
1604
- ],
1605
- 0,
1606
- "yellow",
1607
- );
1608
- const workspaces = [clientFolder];
1609
- if (includeServer) {
1610
- await scaffoldBackendStatus(clientRoot);
1611
- await createBackend(join(root, serverFolder));
1612
- workspaces.push(serverFolder);
1613
- }
1614
-
1615
- await mkdir(join(root, "scripts"), { recursive: true });
1616
- await Promise.all(
1617
- ["dev.mjs", "run-app.mjs", "install-info.mjs", "add-dependency.mjs"].map(copyScript),
1618
- );
1619
- const rootPackage = {
1620
- name: projectName,
1621
- version: "1.0.0",
1622
- private: true,
1623
- engines: { node: ">=20.6" },
1624
- workspaces,
1625
- scripts: {
1626
- preinstall: "node scripts/install-info.mjs",
1627
- postinstall: "node scripts/install-info.mjs --complete",
1628
- dev: `node scripts/dev.mjs${exposeClient ? " --host" : ""}`,
1629
- build:
1630
- packageManager === "pnpm"
1631
- ? "pnpm -r --if-present run build"
1632
- : "npm run build --workspaces --if-present",
1633
- lint:
1634
- packageManager === "pnpm"
1635
- ? "pnpm -r --if-present run lint"
1636
- : "npm run lint --workspaces --if-present",
1637
- client: "node scripts/run-app.mjs client",
1638
- adD: "node scripts/add-dependency.mjs",
1639
- "add-dependency": "node scripts/add-dependency.mjs",
1640
- ...(includeServer ? { server: "node scripts/run-app.mjs server" } : {}),
1641
- },
1642
- type: "module",
1643
- dependencies: {
1644
- "cross-spawn": cliPackage.dependencies["cross-spawn"],
1645
- },
1646
- };
1647
- await writeFile(join(root, "package.json"), `${JSON.stringify(rootPackage, null, 2)}\n`);
1648
- if (packageManager === "pnpm") {
1649
- await writeFile(
1650
- join(root, "pnpm-workspace.yaml"),
1651
- [
1652
- "packages:",
1653
- ...workspaces.map((workspace) => ` - ${workspace}`),
1654
- "",
1655
- "onlyBuiltDependencies: [esbuild]",
1656
- "",
1657
- "allowBuilds:",
1658
- " esbuild: true",
1659
- " sharp: false",
1660
- " unrs-resolver: false",
1661
- "",
1662
- ].join("\n"),
1663
- );
1664
- }
1665
- await writeFile(
1666
- join(root, ".gitignore"),
1667
- [
1668
- "# Dependencies",
1669
- "node_modules/",
1670
- "",
1671
- "# Build output",
1672
- "**/dist/",
1673
- "**/coverage/",
1674
- "",
1675
- "# Local environment files",
1676
- "**/.env*",
1677
- "!**/.env.example",
1678
- "",
1679
- "# Logs",
1680
- "npm-debug.log*",
1681
- "pnpm-debug.log*",
1682
- "yarn-debug.log*",
1683
- ".dev.log",
1684
- ".dev.lock",
1685
- ".install-state",
1686
- "",
1687
- ].join("\n"),
1688
- );
1689
-
1690
- console.log(`\nInstalling dependencies for ${workspaces.join(" and ")}...`);
1691
- try {
1692
- await run(packageManager, ["install"], root, {
1693
- ...process.env,
1694
- VANILLA_VITE_ALLOW_INSTALL: "1",
1695
- });
1696
- } catch (error) {
1697
- installFailed = true;
1698
- await rm(join(root, ".install-state"), { force: true });
1699
- console.error(
1700
- `Dependency installation failed: ${error.message}\nRetry with:\n cd "${projectName}" && ${packageManager} install`,
1701
- );
1702
- }
1703
- rootCreated = false;
1704
- process.off("SIGINT", handleCreationSignal);
1705
- process.off("SIGTERM", handleCreationSignal);
1706
- if (!hasOption("no-git")) {
1707
- const repositoryCheck = spawnSync(
1708
- "git",
1709
- ["rev-parse", "--is-inside-work-tree"],
1710
- { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
1711
- );
1712
- if (repositoryCheck.status === 0 && repositoryCheck.stdout.trim() === "true") {
1713
- console.log("Skipping Git initialization because this project is already inside a Git work tree.");
1714
- } else {
1715
- const initializeGit = await chooseOption(
1716
- "Would you like to initialize Git and create an initial commit?",
1717
- [
1718
- { label: "Yes — initialize Git and commit the project", value: true },
1719
- { label: "No", value: false },
1720
- ],
1721
- 0,
1722
- );
1723
- if (initializeGit) {
1724
- try {
1725
- await run("git", ["init"], root);
1726
- await run("git", ["add", "-A"], root);
1727
- await run("git", ["commit", "-m", "Initial commit"], root);
1728
- } catch (error) {
1729
- console.error(`Unable to create the initial Git commit: ${error.message}`);
1730
- }
1731
- }
1732
- }
1733
- }
1734
- console.log(
1735
- `\nProject created successfully: ${projectName}/\n${
1736
- installFailed
1737
- ? "Install dependencies with the retry command above.\n"
1738
- : noStart
1739
- ? "Skipping the development server.\n"
1740
- : "Starting the development server...\n"
1741
- }`,
1742
- );
1743
- } catch (error) {
1744
- if (!creationCancelled) {
1745
- await removeIncompleteProject();
1746
- console.error(`\nProject creation failed: ${error.message}`);
1747
- process.exit(1);
1748
- }
1749
- }
1750
-
1751
- if (!creationCancelled && !noStart && !installFailed) {
1752
- try {
1753
- await run(
1754
- packageManager,
1755
- packageManager === "pnpm" ? ["dev"] : ["run", "dev"],
1756
- root,
1757
- );
1758
- } catch (error) {
1759
- console.error(
1760
- `\nProject created successfully, but the development server could not be started: ${error.message}`,
1761
- );
1762
- process.exitCode = 1;
1763
- }
1764
- }
1
+ #!/usr/bin/env node
2
+
3
+ import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
4
+ import { spawnSync } from "node:child_process";
5
+ import spawn from "cross-spawn";
6
+ import { emitKeypressEvents } from "node:readline";
7
+ import { createInterface } from "node:readline/promises";
8
+ import { stdin, stdout } from "node:process";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const args = process.argv.slice(2);
13
+ const allowedOptions = [
14
+ "--yes",
15
+ "--default",
16
+ "--host",
17
+ "--tailwind",
18
+ "--no-tailwind",
19
+ "--axios",
20
+ "--no-axios",
21
+ "--router",
22
+ "--no-router",
23
+ "--icons",
24
+ "--backend",
25
+ "--ts",
26
+ "--js",
27
+ "--structure",
28
+ "--pm",
29
+ "--template",
30
+ "--no-start",
31
+ "--no-update-check",
32
+ "--no-git",
33
+ "--install-mode",
34
+ ];
35
+ const valueOptions = new Set([
36
+ "--icons",
37
+ "--backend",
38
+ "--structure",
39
+ "--pm",
40
+ "--template",
41
+ "--install-mode",
42
+ ]);
43
+ const optionNames = new Set(allowedOptions);
44
+ const positionalArgs = [];
45
+ const optionErrors = [];
46
+ for (let index = 0; index < args.length; index += 1) {
47
+ const argument = args[index];
48
+ if (!argument.startsWith("--")) {
49
+ positionalArgs.push(argument);
50
+ continue;
51
+ }
52
+ const separator = argument.indexOf("=");
53
+ const name = separator === -1 ? argument : argument.slice(0, separator);
54
+ if (!optionNames.has(name)) {
55
+ optionErrors.push(`Unknown option: ${name}`);
56
+ continue;
57
+ }
58
+ if (valueOptions.has(name)) {
59
+ if (separator === -1 || !argument.slice(separator + 1)) {
60
+ optionErrors.push(`${name} requires a value in the form ${name}=<value>`);
61
+ if (separator === -1 && args[index + 1] && !args[index + 1].startsWith("--")) {
62
+ index += 1;
63
+ }
64
+ }
65
+ } else if (separator !== -1) {
66
+ optionErrors.push(`${name} does not accept a value`);
67
+ }
68
+ }
69
+ const readOption = (name) =>
70
+ args.find((argument) => argument.startsWith(`--${name}=`))?.slice(name.length + 3);
71
+ const hasOption = (name) => args.includes(`--${name}`);
72
+ const yes = hasOption("yes");
73
+ let activeChild;
74
+ let creationCancelled = false;
75
+ const useDefaultStructure =
76
+ hasOption("default") || process.env.npm_config_default === "true";
77
+ const exposeClient = hasOption("host");
78
+ const noTailwind = hasOption("no-tailwind");
79
+ const noAxios = hasOption("no-axios");
80
+ const noStart = hasOption("no-start");
81
+ const skipUpdateCheck =
82
+ hasOption("no-update-check") || yes || process.env.CI !== undefined;
83
+ const backendOption = readOption("backend");
84
+ const languageOption = hasOption("ts") ? "ts" : hasOption("js") ? "js" : null;
85
+ const structureOption = readOption("structure");
86
+ const requestedPackageManager = readOption("pm");
87
+ const templateOption = readOption("template");
88
+ const iconsOption = readOption("icons");
89
+ const installModeOption = readOption("install-mode");
90
+ if (
91
+ installModeOption !== undefined &&
92
+ !["adD", "plain", "both"].includes(installModeOption)
93
+ ) {
94
+ optionErrors.push("--install-mode must be adD, plain, or both");
95
+ }
96
+ if (backendOption !== undefined && !["none", "basic", "express"].includes(backendOption)) {
97
+ optionErrors.push("--backend must be none, basic, or express");
98
+ }
99
+ if (hasOption("ts") && hasOption("js")) {
100
+ optionErrors.push("Use only one of --ts or --js");
101
+ }
102
+ if (hasOption("router") && hasOption("no-router")) {
103
+ optionErrors.push("Use only one of --router or --no-router");
104
+ }
105
+ if (structureOption !== undefined && !["simple", "module"].includes(structureOption)) {
106
+ optionErrors.push("--structure must be simple or module");
107
+ }
108
+ if (
109
+ requestedPackageManager !== undefined &&
110
+ !["npm", "pnpm"].includes(requestedPackageManager)
111
+ ) {
112
+ optionErrors.push("--pm must be npm or pnpm");
113
+ }
114
+ if (noTailwind && hasOption("tailwind")) {
115
+ optionErrors.push("Use only one of --tailwind or --no-tailwind");
116
+ }
117
+ if (noAxios && hasOption("axios")) {
118
+ optionErrors.push("Use only one of --axios or --no-axios");
119
+ }
120
+ if (
121
+ iconsOption !== undefined &&
122
+ !["react-icons", "animateicons", "none"].includes(iconsOption)
123
+ ) {
124
+ optionErrors.push("--icons must be react-icons, animateicons, or none");
125
+ }
126
+ if (args.some((argument) => argument.startsWith("--template=")) && !templateOption) {
127
+ optionErrors.push("--template must include a template name");
128
+ }
129
+ if (optionErrors.length) {
130
+ console.error(
131
+ `${optionErrors.join("\n")}\nAllowed options: ${allowedOptions.join(", ")}`,
132
+ );
133
+ process.exit(1);
134
+ }
135
+ let projectName = positionalArgs[0];
136
+ const validProjectName = (name) => /^[a-z0-9][a-z0-9_-]*$/.test(name);
137
+
138
+ if (!projectName && stdin.isTTY) {
139
+ const prompt = createInterface({ input: stdin, output: stdout });
140
+ try {
141
+ do {
142
+ projectName = (await prompt.question("Project name: ")).trim();
143
+ if (!validProjectName(projectName)) {
144
+ console.error("Use lowercase letters, numbers, hyphens, or underscores.");
145
+ }
146
+ } while (!validProjectName(projectName));
147
+ } finally {
148
+ prompt.close();
149
+ }
150
+ }
151
+
152
+ if (!projectName || !validProjectName(projectName)) {
153
+ console.error("Usage: create-vanilla-vite <lowercase-project-name>");
154
+ if (!projectName && !stdin.isTTY) {
155
+ console.error("Run this command in an interactive terminal to be prompted for a name.");
156
+ }
157
+ process.exit(1);
158
+ }
159
+
160
+ const packageManager =
161
+ requestedPackageManager ??
162
+ (process.env.npm_config_user_agent?.startsWith("pnpm/") ? "pnpm" : "npm");
163
+ const root = resolve(process.cwd(), projectName);
164
+ let rootCreated = false;
165
+ const clientFolder = `${projectName}-client`;
166
+ const serverFolder = `${projectName}-server`;
167
+ const packageRoot = fileURLToPath(new URL("../", import.meta.url));
168
+ const scriptRoot = fileURLToPath(new URL("../scripts/", import.meta.url));
169
+ const cliPackage = JSON.parse(
170
+ await readFile(join(packageRoot, "package.json"), "utf8"),
171
+ );
172
+ const delay = (milliseconds) =>
173
+ new Promise((resolveDelay) => setTimeout(resolveDelay, milliseconds));
174
+ const removeIncompleteProject = async () => {
175
+ process.off("SIGINT", handleCreationSignal);
176
+ process.off("SIGTERM", handleCreationSignal);
177
+ if (!rootCreated) return;
178
+ rootCreated = false;
179
+ for (let attempt = 0; attempt < 6; attempt += 1) {
180
+ try {
181
+ await rm(root, { recursive: true, force: true });
182
+ return;
183
+ } catch (error) {
184
+ if (!["EBUSY", "ENOTEMPTY"].includes(error.code) || attempt === 5) {
185
+ console.error(`Unable to remove the incomplete project directory: ${error.message}`);
186
+ return;
187
+ }
188
+ await delay(100 * (attempt + 1));
189
+ }
190
+ }
191
+ };
192
+ const handleCreationSignal = async () => {
193
+ if (creationCancelled) return;
194
+ creationCancelled = true;
195
+ const child = activeChild;
196
+ if (child && child.exitCode === null && child.signalCode === null) {
197
+ child.kill("SIGTERM");
198
+ await Promise.race([
199
+ new Promise((resolveClose) => child.once("close", resolveClose)),
200
+ delay(3000),
201
+ ]);
202
+ if (child.exitCode === null && child.signalCode === null) {
203
+ child.kill("SIGKILL");
204
+ await new Promise((resolveClose) => child.once("close", resolveClose));
205
+ }
206
+ }
207
+ await removeIncompleteProject();
208
+ process.exit(130);
209
+ };
210
+
211
+ process.on("SIGINT", handleCreationSignal);
212
+ process.on("SIGTERM", handleCreationSignal);
213
+
214
+ function parseSemver(version) {
215
+ const match =
216
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(version);
217
+ if (!match) throw new Error(`Invalid semantic version: ${version}`);
218
+ const prerelease = match[4]?.split(".") ?? [];
219
+ return {
220
+ major: BigInt(match[1]),
221
+ minor: BigInt(match[2]),
222
+ patch: BigInt(match[3]),
223
+ prerelease,
224
+ };
225
+ }
226
+
227
+ function compareSemver(left, right) {
228
+ const a = parseSemver(left);
229
+ const b = parseSemver(right);
230
+ for (const component of ["major", "minor", "patch"]) {
231
+ if (a[component] !== b[component]) {
232
+ return a[component] < b[component] ? -1 : 1;
233
+ }
234
+ }
235
+ if (!a.prerelease.length || !b.prerelease.length) {
236
+ return a.prerelease.length === b.prerelease.length
237
+ ? 0
238
+ : a.prerelease.length
239
+ ? -1
240
+ : 1;
241
+ }
242
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
243
+ for (let index = 0; index < length; index += 1) {
244
+ const leftId = a.prerelease[index];
245
+ const rightId = b.prerelease[index];
246
+ if (leftId === undefined || rightId === undefined) {
247
+ return leftId === rightId ? 0 : leftId === undefined ? -1 : 1;
248
+ }
249
+ if (leftId === rightId) continue;
250
+ const leftNumeric = /^\d+$/.test(leftId);
251
+ const rightNumeric = /^\d+$/.test(rightId);
252
+ if (leftNumeric && rightNumeric) {
253
+ return BigInt(leftId) < BigInt(rightId) ? -1 : 1;
254
+ }
255
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
256
+ return leftId < rightId ? -1 : 1;
257
+ }
258
+ return 0;
259
+ }
260
+
261
+ async function updateIfOutdated() {
262
+ if (skipUpdateCheck) return;
263
+ const { version: installedVersion } = cliPackage;
264
+ const registry = (process.env.npm_config_registry || "https://registry.npmjs.org")
265
+ .replace(/\/$/, "");
266
+
267
+ let latestVersion;
268
+ try {
269
+ const response = await fetch(`${registry}/create-vanilla-vite/latest`, {
270
+ signal: AbortSignal.timeout(3000),
271
+ });
272
+ if (!response.ok) throw new Error(`registry returned HTTP ${response.status}`);
273
+ latestVersion = (await response.json()).version;
274
+ if (typeof latestVersion !== "string") {
275
+ throw new Error("registry response did not include a version");
276
+ }
277
+ } catch (error) {
278
+ console.warn(`\nCould not check for CLI updates: ${error.message}`);
279
+ return;
280
+ }
281
+
282
+ try {
283
+ if (compareSemver(latestVersion, installedVersion) <= 0) return;
284
+ } catch (error) {
285
+ console.warn(`\nCould not compare CLI versions: ${error.message}`);
286
+ return;
287
+ }
288
+ if (!stdin.isTTY) {
289
+ console.warn(
290
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}). Run ${packageManager} create vanilla-vite@latest to use it.`,
291
+ );
292
+ return;
293
+ }
294
+
295
+ console.warn(
296
+ `\nA newer version of create-vanilla-vite is available (${latestVersion}; current: ${installedVersion}).`,
297
+ );
298
+ const useLatest = await selectOption("Which version would you like to use?", [
299
+ { label: `Use the latest version (${latestVersion})`, value: true },
300
+ { label: `Continue with the current version (${installedVersion})`, value: false },
301
+ ]);
302
+ if (!useLatest) return;
303
+
304
+ const relaunchArgs = [
305
+ ...args.filter((arg) => arg !== "--no-update-check"),
306
+ ...(args.some((arg) => !arg.startsWith("--")) ? [] : [projectName]),
307
+ "--no-update-check",
308
+ ];
309
+ const updateArgs =
310
+ packageManager === "pnpm"
311
+ ? ["dlx", "create-vanilla-vite@latest", ...relaunchArgs]
312
+ : [
313
+ "exec",
314
+ "--yes",
315
+ "--package=create-vanilla-vite@latest",
316
+ "--",
317
+ "create-vanilla-vite",
318
+ ...relaunchArgs,
319
+ ];
320
+ try {
321
+ await run(packageManager, updateArgs, process.cwd());
322
+ } catch (error) {
323
+ console.error(`Unable to start the latest CLI version: ${error.message}`);
324
+ process.exit(1);
325
+ }
326
+ process.exit(0);
327
+ }
328
+
329
+ function run(command, commandArgs, cwd, env = process.env) {
330
+ return new Promise((resolveRun, rejectRun) => {
331
+ const child = spawn(command, commandArgs, { cwd, stdio: "inherit", env });
332
+ activeChild = child;
333
+ child.once("error", (error) => {
334
+ if (activeChild === child) activeChild = undefined;
335
+ rejectRun(error);
336
+ });
337
+ child.once("close", (code, signal) => {
338
+ if (activeChild === child) activeChild = undefined;
339
+ if (code === 0) resolveRun();
340
+ else {
341
+ rejectRun(
342
+ new Error(`${command} exited ${signal ? `from ${signal}` : `with code ${code}`}`),
343
+ );
344
+ }
345
+ });
346
+ });
347
+ }
348
+
349
+ async function selectOption(question, options, defaultIndex = 0, color = "cyan") {
350
+ if (!stdin.isTTY) return options[defaultIndex].value;
351
+ let selected = defaultIndex;
352
+ emitKeypressEvents(stdin);
353
+
354
+ return new Promise((resolveSelection) => {
355
+ function render() {
356
+ const prompt = stdout.isTTY && process.env.NO_COLOR === undefined
357
+ ? `\x1b[1;${color === "cyan" ? "36" : "33"}m${question}\x1b[0m`
358
+ : question;
359
+ stdout.write(`\r\x1b[2K${prompt}\n`);
360
+ for (const [index, option] of options.entries()) {
361
+ stdout.write(` ${index === selected ? "❯" : " "} ${option.label}\n`);
362
+ }
363
+ stdout.write(" Use ↑/↓ to select, Enter to confirm, or Esc to keep the default.\n");
364
+ stdout.write(`\x1b[${options.length + 2}A`);
365
+ }
366
+
367
+ function finish(value) {
368
+ stdin.off("keypress", onKeypress);
369
+ stdin.setRawMode(false);
370
+ stdin.pause();
371
+ stdout.write(`\x1b[${options.length + 2}B\n`);
372
+ resolveSelection(value);
373
+ }
374
+
375
+ function onKeypress(_input, key) {
376
+ if (key?.name === "up" || key?.name === "down") {
377
+ selected =
378
+ (selected + (key.name === "down" ? 1 : options.length - 1)) %
379
+ options.length;
380
+ render();
381
+ } else if (key?.name === "return") finish(options[selected].value);
382
+ else if (key?.name === "escape") {
383
+ finish(options[defaultIndex].value);
384
+ } else if (key?.ctrl && key.name === "c") {
385
+ stdin.off("keypress", onKeypress);
386
+ stdin.setRawMode(false);
387
+ stdin.pause();
388
+ stdout.write(`\x1b[${options.length + 2}B\n`);
389
+ void handleCreationSignal();
390
+ }
391
+ }
392
+
393
+ stdin.setRawMode(true);
394
+ stdin.resume();
395
+ stdin.on("keypress", onKeypress);
396
+ render();
397
+ });
398
+ }
399
+
400
+ function chooseOption(question, options, defaultIndex = 0, color = "cyan") {
401
+ return yes
402
+ ? Promise.resolve(options[defaultIndex].value)
403
+ : selectOption(question, options, defaultIndex, color);
404
+ }
405
+
406
+ async function configureTailwind(clientRoot) {
407
+ let viteConfigName = (await readdir(clientRoot)).find((file) =>
408
+ /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
409
+ );
410
+ if (!viteConfigName) {
411
+ const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
412
+ viteConfigName = `vite.config.${isTypeScript ? "ts" : "js"}`;
413
+ await writeFile(
414
+ join(clientRoot, viteConfigName),
415
+ 'import { defineConfig } from "vite";\n' +
416
+ 'import tailwindcss from "@tailwindcss/vite";\n\n' +
417
+ "export default defineConfig({\n" +
418
+ " plugins: [tailwindcss()],\n" +
419
+ "});\n",
420
+ );
421
+ }
422
+
423
+ const viteConfigPath = join(clientRoot, viteConfigName);
424
+ let viteConfig = await readFile(viteConfigPath, "utf8");
425
+ if (!viteConfig.includes("@tailwindcss/vite")) {
426
+ viteConfig = `import tailwindcss from "@tailwindcss/vite";\n${viteConfig}`;
427
+ const plugins = /(\bplugins\s*:\s*\[)/;
428
+ if (plugins.test(viteConfig)) {
429
+ viteConfig = viteConfig.replace(plugins, "$1tailwindcss(), ");
430
+ } else {
431
+ const configObject = /(\bdefineConfig\s*\(\s*\{)/;
432
+ if (!configObject.test(viteConfig)) {
433
+ throw new Error("Could not add Tailwind CSS to the Vite config.");
434
+ }
435
+ viteConfig = viteConfig.replace(configObject, "$1\n plugins: [tailwindcss()],");
436
+ }
437
+ }
438
+ await writeFile(viteConfigPath, viteConfig);
439
+
440
+ let entryPath;
441
+ for (const directory of [join(clientRoot, "src"), clientRoot]) {
442
+ let files;
443
+ try {
444
+ files = await readdir(directory);
445
+ } catch (error) {
446
+ if (error.code === "ENOENT") continue;
447
+ throw error;
448
+ }
449
+ const entryFile = files.find((file) => /^main\.[cm]?[jt]sx?$/.test(file));
450
+ if (entryFile) {
451
+ entryPath = join(directory, entryFile);
452
+ break;
453
+ }
454
+ }
455
+ if (!entryPath) {
456
+ throw new Error("Could not find the frontend entry file to configure Tailwind CSS.");
457
+ }
458
+ const entry = await readFile(entryPath, "utf8");
459
+ let cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
460
+ if (!cssImport) {
461
+ const cssPath = join(dirname(entryPath), "style.css");
462
+ await writeFile(cssPath, '@import "tailwindcss";\n');
463
+ await writeFile(entryPath, `import "./style.css";\n${entry}`);
464
+ cssImport = ['import "./style.css";', "./style.css"];
465
+ }
466
+ const cssPath = resolve(dirname(entryPath), cssImport[1]);
467
+ const css = await readFile(cssPath, "utf8");
468
+ if (!css.includes('@import "tailwindcss";')) {
469
+ await writeFile(cssPath, `@import "tailwindcss";\n${css}`);
470
+ }
471
+ }
472
+
473
+ async function configureStrictPort(clientRoot) {
474
+ let configName = (await readdir(clientRoot)).find((file) =>
475
+ /^vite\.config\.(?:[cm]?[jt]s)$/.test(file),
476
+ );
477
+ if (!configName) {
478
+ const isTypeScript = (await readdir(clientRoot)).includes("tsconfig.json");
479
+ configName = `vite.config.${isTypeScript ? "ts" : "js"}`;
480
+ await writeFile(
481
+ join(clientRoot, configName),
482
+ 'import { defineConfig } from "vite";\n\nexport default defineConfig({});\n',
483
+ );
484
+ }
485
+
486
+ const configPath = join(clientRoot, configName);
487
+ let config = await readFile(configPath, "utf8");
488
+ if (/\bstrictPort\s*:/.test(config)) {
489
+ config = config.replace(/\bstrictPort\s*:\s*(?:true|false)/, "strictPort: true");
490
+ } else if (/\bserver\s*:\s*\{/.test(config)) {
491
+ config = config.replace(/\bserver\s*:\s*\{/, "server: { strictPort: true,");
492
+ } else {
493
+ const configObject = /(\bdefineConfig\s*\(\s*\{|\bexport\s+default\s*\{)/;
494
+ if (!configObject.test(config)) {
495
+ console.warn(
496
+ `Could not configure strictPort in ${configName}; the Vite config shape was not recognized.`,
497
+ );
498
+ return;
499
+ }
500
+ config = config.replace(configObject, "$1\n server: { strictPort: true },");
501
+ }
502
+ await writeFile(configPath, config);
503
+ }
504
+
505
+ async function scaffoldReactRouter(clientRoot, useTailwind) {
506
+ const sourceRoot = join(clientRoot, "src");
507
+ const sourceFiles = await readdir(sourceRoot);
508
+ const appFile = sourceFiles.find((file) => /^App\.(?:jsx|tsx)$/.test(file));
509
+ const entryFile = sourceFiles.find((file) => /^main\.(?:jsx|tsx)$/.test(file));
510
+ if (!appFile || !entryFile) {
511
+ throw new Error("Could not find the React app and entry files to configure routing.");
512
+ }
513
+
514
+ const typed = appFile.endsWith(".tsx");
515
+ const extension = typed ? "tsx" : "jsx";
516
+ const appPath = join(sourceRoot, appFile);
517
+ const entryPath = join(sourceRoot, entryFile);
518
+ const entry = await readFile(entryPath, "utf8");
519
+ const cssImport = entry.match(/import\s+["']([^"']+\.css)["']/);
520
+ if (!cssImport) {
521
+ throw new Error("Could not find a CSS import for the React Router starter.");
522
+ }
523
+
524
+ const cssPath = resolve(sourceRoot, cssImport[1]);
525
+ const tailwindImport = (await readFile(cssPath, "utf8"))
526
+ .includes('@import "tailwindcss";')
527
+ ? '@import "tailwindcss";\n'
528
+ : "";
529
+ const styles = useTailwind
530
+ ? {
531
+ shell: "min-h-screen flex flex-col bg-[#f5f7f4] text-[#17231f]",
532
+ container: "w-[calc(100%_-_2rem)] sm:w-[calc(100%_-_3rem)] max-w-[1040px] mx-auto",
533
+ header: "min-h-[72px] sm:min-h-[84px] flex items-center justify-between border-b border-[#dfe6df]",
534
+ brand: "flex items-center gap-[10px] text-sm font-bold text-[#17231f] no-underline",
535
+ brandMark: "w-[30px] h-[30px] grid place-items-center rounded-[9px] bg-[#315d4a] text-white",
536
+ nav: "flex items-center gap-2",
537
+ navLink: "min-h-10 flex items-center px-[10px] sm:px-[14px] rounded-lg text-sm text-[#5b6861] no-underline hover:bg-[#e7eee8] hover:text-[#244b39]",
538
+ navActive: "bg-[#e7eee8] text-[#244b39]",
539
+ page: "flex-1",
540
+ footer: "py-6 border-t border-[#dfe6df] text-[13px] text-[#78857d]",
541
+ home: "py-[72px] sm:pt-[clamp(72px,12vw,132px)] sm:pb-[84px]",
542
+ eyebrow: "text-xs font-bold tracking-[0.12em] text-[#557663]",
543
+ title: "max-w-[680px] my-[18px] text-[clamp(40px,7vw,68px)] font-semibold leading-[1.05] tracking-[-0.055em]",
544
+ authTitle: "max-w-[680px] my-[18px] text-[clamp(38px,7vw,52px)] font-semibold leading-[1.05] tracking-[-0.055em]",
545
+ copy: "max-w-[550px] mb-7 text-[17px] leading-[1.7] text-[#627068]",
546
+ button: "min-h-[46px] inline-flex items-center justify-center gap-[14px] px-[18px] rounded-lg font-semibold no-underline cursor-pointer",
547
+ buttonPrimary: "bg-[#315d4a] text-white hover:bg-[#244b39]",
548
+ grid: "grid grid-cols-1 sm:grid-cols-2 gap-4 mt-14 sm:mt-[72px]",
549
+ card: "min-h-[164px] p-6 border border-[#dfe6df] rounded-xl bg-[#fbfcfa]",
550
+ cardIndex: "text-xs font-bold tracking-[0.12em] text-[#557663]",
551
+ cardTitle: "mt-4 mb-2 text-lg",
552
+ cardCopy: "m-0 leading-[1.6] text-[#627068]",
553
+ code: "text-[#315d4a]",
554
+ auth: "w-full max-w-[440px] mx-auto py-[88px] pb-[72px]",
555
+ authIntro: "",
556
+ authCopy: "max-w-[550px] mb-8 text-[17px] leading-[1.7] text-[#627068]",
557
+ form: "grid gap-[10px]",
558
+ label: "mt-2 text-sm font-semibold text-[#35443c]",
559
+ input: "w-full min-h-[46px] px-[13px] border border-[#ccd7ce] rounded-lg bg-white text-[#17231f] focus:border-[#557663] focus:outline-3 focus:outline-[#dce8df]",
560
+ formButton: "mt-3",
561
+ notice: "min-h-6 m-0 text-sm leading-[1.5] text-[#557663]",
562
+ back: "inline-block mt-[18px] text-sm text-[#486353] hover:underline",
563
+ }
564
+ : {
565
+ shell: "app-shell",
566
+ container: "layout-container",
567
+ header: "site-header",
568
+ brand: "brand",
569
+ brandMark: "brand-mark",
570
+ nav: "site-nav",
571
+ navLink: "nav-link",
572
+ navActive: "is-active",
573
+ page: "page-content",
574
+ footer: "site-footer",
575
+ home: "home-page",
576
+ eyebrow: "eyebrow",
577
+ title: "",
578
+ authTitle: "",
579
+ copy: "hero-copy",
580
+ button: "button",
581
+ buttonPrimary: "button-primary",
582
+ grid: "route-grid",
583
+ card: "route-card",
584
+ cardIndex: "card-index",
585
+ cardTitle: "",
586
+ cardCopy: "",
587
+ code: "",
588
+ auth: "auth-page",
589
+ authIntro: "auth-intro",
590
+ authCopy: "hero-copy",
591
+ form: "login-form",
592
+ label: "",
593
+ input: "",
594
+ formButton: "",
595
+ notice: "form-notice",
596
+ back: "back-link",
597
+ };
598
+ const appCssImport = useTailwind ? "" : 'import "./App.css";\n';
599
+ const homeDirectory = join(sourceRoot, "Pages", "Home");
600
+ const authDirectory = join(sourceRoot, "Pages", "Auth");
601
+ await Promise.all([
602
+ mkdir(homeDirectory, { recursive: true }),
603
+ mkdir(authDirectory, { recursive: true }),
604
+ ]);
605
+ await Promise.all([
606
+ writeFile(
607
+ join(sourceRoot, `MainRouter.${extension}`),
608
+ `import { createBrowserRouter } from "react-router";
609
+ import App from "./App";
610
+ import Home from "./Pages/Home/Home";
611
+ import AuthPage from "./Pages/Auth/AuthPage";
612
+
613
+ const MainRouter = createBrowserRouter([
614
+ {
615
+ path: "/",
616
+ element: <App />,
617
+ children: [
618
+ { index: true, element: <Home /> },
619
+ { path: "login", element: <AuthPage /> },
620
+ ],
621
+ },
622
+ ]);
623
+
624
+ // eslint-disable-next-line react-refresh/only-export-components
625
+ export default MainRouter;
626
+ `,
627
+ ),
628
+ writeFile(
629
+ appPath,
630
+ `import { NavLink, Outlet } from "react-router";
631
+ ${appCssImport}
632
+
633
+ function App() {
634
+ return (
635
+ <div className="${styles.shell}">
636
+ <header className="${styles.container} ${styles.header}">
637
+ <NavLink className="${styles.brand}" to="/" end>
638
+ <span className="${styles.brandMark}" aria-hidden="true">V</span>
639
+ <span>Workspace starter</span>
640
+ </NavLink>
641
+ <nav className="${styles.nav}" aria-label="Main navigation">
642
+ <NavLink to="/" end className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
643
+ Home
644
+ </NavLink>
645
+ <NavLink to="/login" className={({ isActive }) => isActive ? "${styles.navLink} ${styles.navActive}" : "${styles.navLink}"}>
646
+ Login
647
+ </NavLink>
648
+ </nav>
649
+ </header>
650
+ <main className="${styles.container} ${styles.page}">
651
+ <Outlet />
652
+ </main>
653
+ <footer className="${styles.container} ${styles.footer}">A small starting point for your next project.</footer>
654
+ </div>
655
+ );
656
+ }
657
+
658
+ export default App;
659
+ `,
660
+ ),
661
+ writeFile(
662
+ join(homeDirectory, `Home.${extension}`),
663
+ `import { Link } from "react-router";
664
+
665
+ function Home() {
666
+ return (
667
+ <section className="${styles.home}">
668
+ <p className="${styles.eyebrow}">YOUR PROJECT STARTS HERE</p>
669
+ <h1 className="${styles.title}">A faster start for your next project.</h1>
670
+ <p className="${styles.copy}">
671
+ This starter makes setting up your development environment quick and
672
+ straightforward. React Router is ready with Home and Login pages so you
673
+ can test navigation right away.
674
+ </p>
675
+ <Link className="${styles.button} ${styles.buttonPrimary}" to="/login">Visit the login page <span aria-hidden="true">→</span></Link>
676
+ <div className="${styles.grid}">
677
+ <article className="${styles.card}">
678
+ <span className="${styles.cardIndex}">01</span>
679
+ <h2 className="${styles.cardTitle}">Home</h2>
680
+ <p className="${styles.cardCopy}">An example landing page at <code className="${styles.code}">/</code> to help you get started.</p>
681
+ </article>
682
+ <article className="${styles.card}">
683
+ <span className="${styles.cardIndex}">02</span>
684
+ <h2 className="${styles.cardTitle}">Login</h2>
685
+ <p className="${styles.cardCopy}">A sample page at <code className="${styles.code}">/login</code> for checking route navigation.</p>
686
+ </article>
687
+ </div>
688
+ </section>
689
+ );
690
+ }
691
+
692
+ export default Home;
693
+ `,
694
+ ),
695
+ writeFile(
696
+ join(authDirectory, `AuthPage.${extension}`),
697
+ `import { useState${typed ? ", type FormEvent" : ""} } from "react";
698
+ import { Link } from "react-router";
699
+
700
+ function AuthPage() {
701
+ const [notice, setNotice] = useState("");
702
+
703
+ function handleSubmit(event${typed ? ": FormEvent<HTMLFormElement>" : ""}) {
704
+ event.preventDefault();
705
+ setNotice("This starter form is ready to connect to your authentication service.");
706
+ }
707
+
708
+ return (
709
+ <section className="${styles.auth}">
710
+ <div className="${styles.authIntro}">
711
+ <p className="${styles.eyebrow}">WELCOME BACK</p>
712
+ <h1 className="${styles.authTitle}">Login</h1>
713
+ <p className="${styles.authCopy}">Sign in to continue to your workspace.</p>
714
+ </div>
715
+ <form className="${styles.form}" onSubmit={handleSubmit}>
716
+ <label className="${styles.label}" htmlFor="email">Email address</label>
717
+ <input className="${styles.input}" id="email" name="email" type="email" autoComplete="email" placeholder="you@example.com" required />
718
+ <label className="${styles.label}" htmlFor="password">Password</label>
719
+ <input className="${styles.input}" id="password" name="password" type="password" autoComplete="current-password" placeholder="Enter your password" required />
720
+ <button className="${styles.button} ${styles.buttonPrimary} ${styles.formButton}" type="submit">Continue</button>
721
+ <p className="${styles.notice}" role="status">{notice}</p>
722
+ </form>
723
+ <Link className="${styles.back}" to="/">← Back to home</Link>
724
+ </section>
725
+ );
726
+ }
727
+
728
+ export default AuthPage;
729
+ `,
730
+ ),
731
+ writeFile(
732
+ cssPath,
733
+ useTailwind
734
+ ? tailwindImport
735
+ : `${tailwindImport}:root {
736
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
737
+ color: #17231f;
738
+ background: #f5f7f4;
739
+ font-synthesis: none;
740
+ text-rendering: optimizeLegibility;
741
+ -webkit-font-smoothing: antialiased;
742
+ -moz-osx-font-smoothing: grayscale;
743
+ }
744
+
745
+ * {
746
+ box-sizing: border-box;
747
+ }
748
+
749
+ body {
750
+ min-width: 320px;
751
+ min-height: 100vh;
752
+ margin: 0;
753
+ }
754
+
755
+ button,
756
+ input {
757
+ font: inherit;
758
+ }
759
+
760
+ a {
761
+ color: inherit;
762
+ }
763
+ `,
764
+ ),
765
+ ...(!useTailwind
766
+ ? [
767
+ writeFile(
768
+ join(sourceRoot, "App.css"),
769
+ `.app-shell {
770
+ min-height: 100vh;
771
+ display: flex;
772
+ flex-direction: column;
773
+ }
774
+
775
+ .layout-container,
776
+ .site-header,
777
+ .page-content,
778
+ .site-footer {
779
+ width: min(100% - 48px, 1040px);
780
+ margin-inline: auto;
781
+ }
782
+
783
+ .site-header {
784
+ min-height: 84px;
785
+ display: flex;
786
+ align-items: center;
787
+ justify-content: space-between;
788
+ border-bottom: 1px solid #dfe6df;
789
+ }
790
+
791
+ .brand,
792
+ .site-nav,
793
+ .nav-link {
794
+ display: flex;
795
+ align-items: center;
796
+ }
797
+
798
+ .brand {
799
+ gap: 10px;
800
+ color: #17231f;
801
+ font-size: 14px;
802
+ font-weight: 700;
803
+ text-decoration: none;
804
+ }
805
+
806
+ .brand-mark {
807
+ width: 30px;
808
+ height: 30px;
809
+ display: grid;
810
+ place-items: center;
811
+ border-radius: 9px;
812
+ background: #315d4a;
813
+ color: #fff;
814
+ }
815
+
816
+ .site-nav {
817
+ gap: 8px;
818
+ }
819
+
820
+ .nav-link {
821
+ min-height: 40px;
822
+ padding: 0 14px;
823
+ border-radius: 8px;
824
+ color: #5b6861;
825
+ font-size: 14px;
826
+ text-decoration: none;
827
+ }
828
+
829
+ .nav-link:hover,
830
+ .nav-link.is-active {
831
+ background: #e7eee8;
832
+ color: #244b39;
833
+ }
834
+
835
+ .page-content {
836
+ flex: 1;
837
+ }
838
+
839
+ .home-page {
840
+ padding: clamp(72px, 12vw, 132px) 0 84px;
841
+ }
842
+
843
+ .eyebrow,
844
+ .card-index {
845
+ color: #557663;
846
+ font-size: 12px;
847
+ font-weight: 700;
848
+ letter-spacing: 0.12em;
849
+ }
850
+
851
+ .home-page h1,
852
+ .auth-intro h1 {
853
+ max-width: 680px;
854
+ margin: 18px 0;
855
+ font-size: clamp(40px, 7vw, 68px);
856
+ font-weight: 600;
857
+ letter-spacing: -0.055em;
858
+ line-height: 1.05;
859
+ }
860
+
861
+ .hero-copy {
862
+ max-width: 550px;
863
+ margin: 0 0 28px;
864
+ color: #627068;
865
+ font-size: 17px;
866
+ line-height: 1.7;
867
+ }
868
+
869
+ .button {
870
+ min-height: 46px;
871
+ display: inline-flex;
872
+ align-items: center;
873
+ justify-content: center;
874
+ gap: 14px;
875
+ padding: 0 18px;
876
+ border: 0;
877
+ border-radius: 8px;
878
+ cursor: pointer;
879
+ font-weight: 600;
880
+ text-decoration: none;
881
+ }
882
+
883
+ .button-primary {
884
+ background: #315d4a;
885
+ color: white;
886
+ }
887
+
888
+ .button-primary:hover {
889
+ background: #244b39;
890
+ }
891
+
892
+ .route-grid {
893
+ display: grid;
894
+ grid-template-columns: repeat(2, minmax(0, 1fr));
895
+ gap: 16px;
896
+ margin-top: 72px;
897
+ }
898
+
899
+ .route-card {
900
+ min-height: 164px;
901
+ padding: 24px;
902
+ border: 1px solid #dfe6df;
903
+ border-radius: 12px;
904
+ background: #fbfcfa;
905
+ }
906
+
907
+ .route-card h2 {
908
+ margin: 16px 0 8px;
909
+ font-size: 18px;
910
+ }
911
+
912
+ .route-card p {
913
+ margin: 0;
914
+ color: #627068;
915
+ line-height: 1.6;
916
+ }
917
+
918
+ .route-card code {
919
+ color: #315d4a;
920
+ }
921
+
922
+ .auth-page {
923
+ width: min(100%, 440px);
924
+ margin: 0 auto;
925
+ padding: 88px 0 72px;
926
+ }
927
+
928
+ .auth-intro h1 {
929
+ font-size: clamp(38px, 7vw, 52px);
930
+ }
931
+
932
+ .auth-intro .hero-copy {
933
+ margin-bottom: 32px;
934
+ }
935
+
936
+ .login-form {
937
+ display: grid;
938
+ gap: 10px;
939
+ }
940
+
941
+ .login-form label {
942
+ margin-top: 8px;
943
+ color: #35443c;
944
+ font-size: 14px;
945
+ font-weight: 600;
946
+ }
947
+
948
+ .login-form input {
949
+ width: 100%;
950
+ min-height: 46px;
951
+ padding: 0 13px;
952
+ border: 1px solid #ccd7ce;
953
+ border-radius: 8px;
954
+ background: #fff;
955
+ color: #17231f;
956
+ }
957
+
958
+ .login-form input:focus {
959
+ border-color: #557663;
960
+ outline: 3px solid #dce8df;
961
+ }
962
+
963
+ .login-form .button {
964
+ margin-top: 12px;
965
+ }
966
+
967
+ .form-notice {
968
+ min-height: 24px;
969
+ margin: 2px 0 0;
970
+ color: #557663;
971
+ font-size: 14px;
972
+ line-height: 1.5;
973
+ }
974
+
975
+ .back-link {
976
+ display: inline-block;
977
+ margin-top: 18px;
978
+ color: #486353;
979
+ font-size: 14px;
980
+ text-decoration: none;
981
+ }
982
+
983
+ .back-link:hover {
984
+ text-decoration: underline;
985
+ }
986
+
987
+ .site-footer {
988
+ padding: 24px 0;
989
+ border-top: 1px solid #dfe6df;
990
+ color: #78857d;
991
+ font-size: 13px;
992
+ }
993
+
994
+ @media (max-width: 560px) {
995
+ .site-header,
996
+ .page-content,
997
+ .site-footer {
998
+ width: min(100% - 32px, 1040px);
999
+ }
1000
+
1001
+ .site-header {
1002
+ min-height: 72px;
1003
+ }
1004
+
1005
+ .nav-link {
1006
+ padding: 0 10px;
1007
+ }
1008
+
1009
+ .route-grid {
1010
+ grid-template-columns: 1fr;
1011
+ margin-top: 56px;
1012
+ }
1013
+ }
1014
+ `,
1015
+ ),
1016
+ ]
1017
+ : [rm(join(sourceRoot, "App.css"), { force: true })]),
1018
+ writeFile(
1019
+ entryPath,
1020
+ `import { StrictMode } from "react";
1021
+ import { createRoot } from "react-dom/client";
1022
+ import { RouterProvider } from "react-router/dom";
1023
+ import MainRouter from "./MainRouter";
1024
+ ${cssImport[0]};
1025
+
1026
+ createRoot(document.getElementById("root")${typed ? "!" : ""}).render(
1027
+ <StrictMode>
1028
+ <RouterProvider router={MainRouter} />
1029
+ </StrictMode>,
1030
+ );
1031
+ `,
1032
+ ),
1033
+ ]);
1034
+
1035
+ return true;
1036
+ }
1037
+
1038
+ async function scaffoldBackendStatus(clientRoot) {
1039
+ const indexPath = join(clientRoot, "index.html");
1040
+ const html = await readFile(indexPath, "utf8");
1041
+ if (!/<\/body\s*>/i.test(html)) {
1042
+ throw new Error("Could not find the closing body tag for the backend status control.");
1043
+ }
1044
+ await writeFile(
1045
+ indexPath,
1046
+ html.replace(
1047
+ /<\/body\s*>/i,
1048
+ ' <script type="module" src="/backend-status.js"></script>\n</body>',
1049
+ ),
1050
+ );
1051
+ await writeFile(
1052
+ join(clientRoot, "backend-status.js"),
1053
+ `if (import.meta.env.DEV) {
1054
+ import("./backend-status.css");
1055
+ const apiUrl = (import.meta.env.VITE_API_URL || "http://localhost:4000").replace(/\\/+$/, "");
1056
+ const panel = document.createElement("aside");
1057
+ panel.className = "backend-status";
1058
+ panel.setAttribute("aria-label", "Backend connection");
1059
+ panel.innerHTML = \`
1060
+ <span class="backend-status__dot" aria-hidden="true"></span>
1061
+ <div class="backend-status__content">
1062
+ <strong class="backend-status__title">Backend</strong>
1063
+ <span class="backend-status__message" role="status" aria-live="polite">Not checked yet</span>
1064
+ </div>
1065
+ <button class="backend-status__button" type="button">Check connection</button>
1066
+ \`;
1067
+
1068
+ const message = panel.querySelector(".backend-status__message");
1069
+ const button = panel.querySelector(".backend-status__button");
1070
+ button.addEventListener("click", async () => {
1071
+ button.disabled = true;
1072
+ panel.dataset.state = "checking";
1073
+ message.textContent = "Checking…";
1074
+ const controller = new AbortController();
1075
+ const timeout = setTimeout(() => controller.abort(), 5000);
1076
+ try {
1077
+ const response = await fetch(\`\${apiUrl}/api/health\`, {
1078
+ headers: { Accept: "application/json" },
1079
+ signal: controller.signal,
1080
+ });
1081
+ const result = await response.json();
1082
+ if (!response.ok || result.status !== "ok") {
1083
+ throw new Error("Backend health check returned an unexpected response.");
1084
+ }
1085
+ panel.dataset.state = "connected";
1086
+ message.textContent = "Connected";
1087
+ } catch {
1088
+ panel.dataset.state = "disconnected";
1089
+ message.textContent = "Unavailable — check the server and network";
1090
+ } finally {
1091
+ clearTimeout(timeout);
1092
+ button.disabled = false;
1093
+ }
1094
+ });
1095
+
1096
+ document.body.append(panel);
1097
+ }
1098
+ `,
1099
+ );
1100
+ await writeFile(
1101
+ join(clientRoot, "backend-status.css"),
1102
+ `.backend-status {
1103
+ position: fixed;
1104
+ z-index: 1000;
1105
+ right: 18px;
1106
+ bottom: 18px;
1107
+ display: grid;
1108
+ grid-template-columns: 9px minmax(0, 1fr) auto;
1109
+ align-items: center;
1110
+ gap: 12px;
1111
+ width: min(390px, calc(100vw - 36px));
1112
+ padding: 14px;
1113
+ border: 1px solid #dfe6df;
1114
+ border-radius: 12px;
1115
+ background: #fbfcfa;
1116
+ color: #17231f;
1117
+ box-shadow: 0 8px 28px rgb(23 35 31 / 12%);
1118
+ font: 13px/1.4 Inter, ui-sans-serif, system-ui, sans-serif;
1119
+ }
1120
+
1121
+ .backend-status__dot {
1122
+ width: 9px;
1123
+ height: 9px;
1124
+ border-radius: 50%;
1125
+ background: #9aa59e;
1126
+ }
1127
+
1128
+ .backend-status[data-state="checking"] .backend-status__dot {
1129
+ background: #c28a30;
1130
+ }
1131
+
1132
+ .backend-status[data-state="connected"] .backend-status__dot {
1133
+ background: #31835b;
1134
+ }
1135
+
1136
+ .backend-status[data-state="disconnected"] .backend-status__dot {
1137
+ background: #bd4d43;
1138
+ }
1139
+
1140
+ .backend-status__content {
1141
+ display: grid;
1142
+ gap: 2px;
1143
+ min-width: 0;
1144
+ }
1145
+
1146
+ .backend-status__title {
1147
+ font-size: 13px;
1148
+ }
1149
+
1150
+ .backend-status__message {
1151
+ color: #627068;
1152
+ font-size: 12px;
1153
+ }
1154
+
1155
+ .backend-status__button {
1156
+ min-height: 36px;
1157
+ padding: 0 12px;
1158
+ border: 0;
1159
+ border-radius: 8px;
1160
+ background: #315d4a;
1161
+ color: #fff;
1162
+ font: inherit;
1163
+ font-weight: 600;
1164
+ cursor: pointer;
1165
+ }
1166
+
1167
+ .backend-status__button:hover:not(:disabled) {
1168
+ background: #244b39;
1169
+ }
1170
+
1171
+ .backend-status__button:focus-visible {
1172
+ outline: 3px solid #9db9a5;
1173
+ outline-offset: 2px;
1174
+ }
1175
+
1176
+ .backend-status__button:disabled {
1177
+ cursor: wait;
1178
+ opacity: 0.7;
1179
+ }
1180
+
1181
+ @media (max-width: 420px) {
1182
+ .backend-status {
1183
+ right: 12px;
1184
+ bottom: 12px;
1185
+ width: calc(100vw - 24px);
1186
+ }
1187
+ }
1188
+ `,
1189
+ );
1190
+ }
1191
+
1192
+ async function configureFrontend(clientRoot, clientPackage) {
1193
+ const tailwind = noTailwind
1194
+ ? false
1195
+ : hasOption("tailwind")
1196
+ ? true
1197
+ : await chooseOption("Would you like to install Tailwind CSS?", [
1198
+ { label: "Yes — add Tailwind CSS v4", value: true },
1199
+ { label: "No", value: false },
1200
+ ]);
1201
+ const axios = hasOption("axios")
1202
+ ? true
1203
+ : noAxios
1204
+ ? false
1205
+ : await chooseOption("Would you like to install Axios?", [
1206
+ { label: "Yes — add Axios", value: true },
1207
+ { label: "No", value: false },
1208
+ ]);
1209
+ const isReact = Boolean(
1210
+ clientPackage.dependencies?.react || clientPackage.devDependencies?.react,
1211
+ );
1212
+ const installRouter =
1213
+ isReact &&
1214
+ (hasOption("router")
1215
+ ? true
1216
+ : hasOption("no-router")
1217
+ ? false
1218
+ : await chooseOption("Would you like to install React Router?", [
1219
+ { label: "Yes — add Home and Login pages with navigation", value: true },
1220
+ { label: "No", value: false },
1221
+ ]));
1222
+ const iconPackages = {
1223
+ "react-icons": ["react-icons", "^5.7.0"],
1224
+ animateicons: ["@animateicons/react", "^0.13.0"],
1225
+ };
1226
+ const icons =
1227
+ !isReact || iconsOption === "none"
1228
+ ? null
1229
+ : iconsOption
1230
+ ? iconPackages[iconsOption]
1231
+ : (await chooseOption("Would you like to install an icon library?", [
1232
+ { label: "Yes", value: true },
1233
+ { label: "No", value: false },
1234
+ ]))
1235
+ ? await chooseOption("Which React icon library would you like to install?", [
1236
+ { label: "React Icons (default)", value: iconPackages["react-icons"] },
1237
+ { label: "@animateicons/react", value: iconPackages.animateicons },
1238
+ ])
1239
+ : null;
1240
+
1241
+ if (tailwind) {
1242
+ clientPackage.devDependencies ??= {};
1243
+ clientPackage.devDependencies["@tailwindcss/vite"] = "^4.3.5";
1244
+ clientPackage.devDependencies.tailwindcss = "^4.3.5";
1245
+ await configureTailwind(clientRoot);
1246
+ }
1247
+ if (axios) {
1248
+ clientPackage.dependencies ??= {};
1249
+ clientPackage.dependencies.axios = "^1.21.1";
1250
+ }
1251
+ if (icons) {
1252
+ clientPackage.dependencies ??= {};
1253
+ clientPackage.dependencies[icons[0]] = icons[1];
1254
+ }
1255
+ if (installRouter) {
1256
+ clientPackage.dependencies ??= {};
1257
+ clientPackage.dependencies["react-router"] = "^7";
1258
+ await scaffoldReactRouter(clientRoot, tailwind);
1259
+ }
1260
+ await configureStrictPort(clientRoot);
1261
+ }
1262
+
1263
+ async function copyScript(name) {
1264
+ const source = await readFile(join(scriptRoot, name), "utf8");
1265
+ await writeFile(join(root, "scripts", name), source);
1266
+ }
1267
+
1268
+ function expressErrorHandlerParameters(language) {
1269
+ return language === "ts"
1270
+ ? `error: unknown,
1271
+ _request: import("express").Request,
1272
+ response: import("express").Response,
1273
+ _next: import("express").NextFunction`
1274
+ : "error, _request, response, _next";
1275
+ }
1276
+
1277
+ function backendFiles(language, framework) {
1278
+ const extension = language;
1279
+ const typeAnnotation = language === "ts" ? ": number" : "";
1280
+ const app = framework === "express"
1281
+ ? `import cors from "cors";
1282
+ import express from "express";
1283
+
1284
+ export function createApp() {
1285
+ const app = express();
1286
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1287
+ .split(",")
1288
+ .map((origin) => origin.trim());
1289
+ app.use((request, response, next) => {
1290
+ const origin = request.headers.origin;
1291
+ if (origin && !origins.includes("*") && origins.includes(origin)) {
1292
+ response.vary("Origin");
1293
+ }
1294
+ next();
1295
+ });
1296
+ app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
1297
+ app.use(express.json());
1298
+ app.get("/", (_request, response) => response.json({ message: "Backend is running" }));
1299
+ app.get("/api/health", (_request, response) => response.json({ status: "ok" }));
1300
+ app.use((${expressErrorHandlerParameters(language)}) => {
1301
+ console.error(error);
1302
+ response.status(500).json({ error: "Internal Server Error" });
1303
+ });
1304
+ return app;
1305
+ }
1306
+ `
1307
+ : `import { createServer } from "node:http";
1308
+ import { handleRequest } from "./basicHandler.${extension}";
1309
+
1310
+ export function createApp() {
1311
+ return createServer(handleRequest);
1312
+ }
1313
+ `;
1314
+ const basicHandler =
1315
+ framework === "basic"
1316
+ ? `export function handleRequest(
1317
+ request${language === "ts" ? ": import('node:http').IncomingMessage" : ""},
1318
+ response${language === "ts" ? ": import('node:http').ServerResponse" : ""},
1319
+ ) {
1320
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1321
+ .split(",")
1322
+ .map((origin) => origin.trim());
1323
+ const requestOrigin = request.headers.origin;
1324
+ const allowedOrigin = origins.includes("*")
1325
+ ? "*"
1326
+ : typeof requestOrigin === "string" && origins.includes(requestOrigin)
1327
+ ? requestOrigin
1328
+ : undefined;
1329
+ const corsHeaders = {
1330
+ ...(allowedOrigin ? { "access-control-allow-origin": allowedOrigin } : {}),
1331
+ ...(allowedOrigin && allowedOrigin !== "*" ? { vary: "Origin" } : {}),
1332
+ "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
1333
+ "access-control-allow-headers": "Content-Type, Authorization",
1334
+ };
1335
+
1336
+ try {
1337
+ if (request.method === "OPTIONS") {
1338
+ response.writeHead(204, corsHeaders);
1339
+ response.end();
1340
+ return;
1341
+ }
1342
+
1343
+ const path = new URL(request.url ?? "/", "http://localhost").pathname;
1344
+ const payload =
1345
+ request.method === "GET" && path === "/"
1346
+ ? { status: 200, body: { message: "Backend is running" } }
1347
+ : request.method === "GET" && path === "/api/health"
1348
+ ? { status: 200, body: { status: "ok" } }
1349
+ : { status: 404, body: { message: "Not Found" } };
1350
+
1351
+ response.writeHead(payload.status, {
1352
+ ...corsHeaders,
1353
+ "content-type": "application/json",
1354
+ });
1355
+ response.end(JSON.stringify(payload.body));
1356
+ } catch (error) {
1357
+ console.error(error);
1358
+ response.writeHead(500, {
1359
+ ...corsHeaders,
1360
+ "content-type": "application/json",
1361
+ });
1362
+ response.end(JSON.stringify({ error: "Internal Server Error" }));
1363
+ }
1364
+ }
1365
+ `
1366
+ : null;
1367
+ const listenErrorParam = language === "ts" ? "error?: Error" : "error";
1368
+ const server = `import "dotenv/config";
1369
+ import { createApp } from "./app.${extension}";
1370
+
1371
+ function parsePort(value${language === "ts" ? ": string | undefined" : ""})${typeAnnotation} {
1372
+ if (!value || value.trim() === "") return 4000;
1373
+ const parsed = Number(value);
1374
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
1375
+ console.warn(\`Invalid PORT "\${value}"; falling back to 4000.\`);
1376
+ return 4000;
1377
+ }
1378
+ return parsed;
1379
+ }
1380
+
1381
+ const port${typeAnnotation} = parsePort(process.env.PORT);
1382
+ const host = process.env.HOST ?? "localhost";
1383
+ const app = createApp();
1384
+ const server = app.listen(port, host, (${listenErrorParam}) => {
1385
+ if (error) return;
1386
+ console.log(\`Backend listening at http://\${host}:\${port}\`);
1387
+ });
1388
+ server.on("error", (error${language === "ts" ? ": NodeJS.ErrnoException" : ""}) => {
1389
+ if (error.code === "EADDRINUSE") {
1390
+ console.error(\`Port \${port} is already in use.\`);
1391
+ } else {
1392
+ console.error("Backend failed to start:", error.message || error);
1393
+ }
1394
+ process.exit(1);
1395
+ });
1396
+ for (const signal of ["SIGINT", "SIGTERM"]) {
1397
+ process.once(signal, () => {
1398
+ server.close((error) => {
1399
+ if (error) {
1400
+ console.error("Unable to close the backend server:", error);
1401
+ process.exitCode = 1;
1402
+ }
1403
+ });
1404
+ });
1405
+ }
1406
+ `;
1407
+ return { app, server, basicHandler };
1408
+ }
1409
+
1410
+ async function createBackend(serverRoot) {
1411
+ const language =
1412
+ languageOption ??
1413
+ (await chooseOption("Select a language for the backend:", [
1414
+ { label: "JavaScript", value: "js" },
1415
+ { label: "TypeScript", value: "ts" },
1416
+ ], 0, "yellow"));
1417
+ const framework =
1418
+ backendOption && backendOption !== "none"
1419
+ ? backendOption
1420
+ : await chooseOption("Select a backend framework:", [
1421
+ { label: "Basic Node.js — no additional framework", value: "basic" },
1422
+ { label: "Express — install Express, CORS, and dotenv (default)", value: "express" },
1423
+ ], 1, "yellow");
1424
+ const structure = structureOption
1425
+ ? structureOption
1426
+ : useDefaultStructure
1427
+ ? "simple"
1428
+ : await chooseOption("Select a backend folder structure:", [
1429
+ { label: "Simple — standard folders", value: "simple" },
1430
+ { label: "Module-based — organized by feature (default)", value: "module" },
1431
+ ], 1, "yellow");
1432
+ const typed = language === "ts";
1433
+ let { app, server, basicHandler } = backendFiles(language, framework);
1434
+ const sourceRoot = join(serverRoot, "src");
1435
+ const folders =
1436
+ structure === "simple"
1437
+ ? ["routes", "controllers", "middleware", "config"]
1438
+ : ["module", "config", "middleware", "utils"];
1439
+ for (const folder of folders) {
1440
+ const folderPath = join(sourceRoot, folder);
1441
+ await mkdir(folderPath, { recursive: true });
1442
+ await writeFile(join(folderPath, ".gitkeep"), "");
1443
+ }
1444
+ if (structure === "module") {
1445
+ const router =
1446
+ framework === "express"
1447
+ ? `import { Router } from "express";
1448
+
1449
+ export const mainRouter = Router();
1450
+ mainRouter.get("/", (_request, response) => {
1451
+ response.json({ message: "Backend is running" });
1452
+ });
1453
+ mainRouter.get("/api/health", (_request, response) => {
1454
+ response.json({ status: "ok" });
1455
+ });
1456
+ `
1457
+ : `export { handleRequest } from "./basicHandler.${language}";
1458
+ `;
1459
+ await writeFile(join(sourceRoot, `mainRouter.${language}`), router);
1460
+ app =
1461
+ framework === "express"
1462
+ ? `import cors from "cors";
1463
+ import express from "express";
1464
+ import { mainRouter } from "./mainRouter.${language}";
1465
+
1466
+ export function createApp() {
1467
+ const app = express();
1468
+ const origins = (process.env.CORS_ORIGIN ?? "*")
1469
+ .split(",")
1470
+ .map((origin) => origin.trim());
1471
+ app.use((request, response, next) => {
1472
+ const origin = request.headers.origin;
1473
+ if (origin && !origins.includes("*") && origins.includes(origin)) {
1474
+ response.vary("Origin");
1475
+ }
1476
+ next();
1477
+ });
1478
+ app.use(cors({ origin: origins.includes("*") ? "*" : origins }));
1479
+ app.use(express.json());
1480
+ app.use(mainRouter);
1481
+ app.use((_request, response) => {
1482
+ response.status(404).json({ error: "Not Found" });
1483
+ });
1484
+ app.use((${expressErrorHandlerParameters(language)}) => {
1485
+ console.error(error);
1486
+ response.status(500).json({ error: "Internal Server Error" });
1487
+ });
1488
+ return app;
1489
+ }
1490
+ `
1491
+ : `import { createServer } from "node:http";
1492
+ import { handleRequest } from "./mainRouter.${language}";
1493
+
1494
+ export function createApp() {
1495
+ return createServer(handleRequest);
1496
+ }
1497
+ `;
1498
+ }
1499
+ if (basicHandler) {
1500
+ await writeFile(join(sourceRoot, `basicHandler.${language}`), basicHandler);
1501
+ }
1502
+ await writeFile(join(sourceRoot, `app.${language}`), app);
1503
+ await writeFile(join(sourceRoot, `server.${language}`), server);
1504
+
1505
+ const scripts = typed
1506
+ ? framework === "basic"
1507
+ ? {
1508
+ dev: `tsx watch src/server.${language}`,
1509
+ start: `tsx src/server.${language}`,
1510
+ }
1511
+ : { dev: `tsx watch src/server.${language}`, start: `tsx src/server.${language}` }
1512
+ : framework === "basic"
1513
+ ? {
1514
+ dev: `node --watch src/server.${language}`,
1515
+ start: `node src/server.${language}`,
1516
+ }
1517
+ : { dev: `node --watch src/server.${language}`, start: `node src/server.${language}` };
1518
+ const dependencies =
1519
+ framework === "express"
1520
+ ? { express: "^5", cors: "^2.8.5", dotenv: "^16" }
1521
+ : { dotenv: "^16" };
1522
+ const packageJson = {
1523
+ name: serverFolder,
1524
+ version: "1.0.0",
1525
+ private: true,
1526
+ type: "module",
1527
+ scripts,
1528
+ ...(typed
1529
+ ? {
1530
+ dependencies: { ...dependencies, tsx: "^4" },
1531
+ devDependencies: {
1532
+ ...(framework === "express"
1533
+ ? { "@types/cors": "^2.8.19", "@types/express": "^5" }
1534
+ : {}),
1535
+ "@types/node": "^22",
1536
+ typescript: "^5",
1537
+ },
1538
+ }
1539
+ : Object.keys(dependencies).length
1540
+ ? { dependencies }
1541
+ : {}),
1542
+ };
1543
+ await writeFile(join(serverRoot, "package.json"), `${JSON.stringify(packageJson, null, 2)}\n`);
1544
+ if (typed) {
1545
+ await writeFile(
1546
+ join(serverRoot, "tsconfig.json"),
1547
+ `${JSON.stringify(
1548
+ {
1549
+ compilerOptions: {
1550
+ target: "ES2022",
1551
+ module: "NodeNext",
1552
+ moduleResolution: "NodeNext",
1553
+ strict: true,
1554
+ esModuleInterop: true,
1555
+ skipLibCheck: true,
1556
+ noEmit: true,
1557
+ allowImportingTsExtensions: true,
1558
+ },
1559
+ include: ["**/*.ts"],
1560
+ },
1561
+ null,
1562
+ 2,
1563
+ )}\n`,
1564
+ );
1565
+ }
1566
+ await writeFile(
1567
+ join(serverRoot, ".env"),
1568
+ "# Local backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
1569
+ { flag: "wx" },
1570
+ );
1571
+ await writeFile(
1572
+ join(serverRoot, ".env.example"),
1573
+ "# Backend environment variables\nPORT=4000\nHOST=localhost\nCORS_ORIGIN=http://localhost:5173,http://127.0.0.1:5173\n",
1574
+ );
1575
+ }
1576
+
1577
+ await updateIfOutdated();
1578
+
1579
+ try {
1580
+ await mkdir(root);
1581
+ rootCreated = true;
1582
+ } catch (error) {
1583
+ if (error.code === "EEXIST") console.error(`The destination already exists: ${root}`);
1584
+ else console.error(`Unable to create project directory: ${error.message}`);
1585
+ process.exit(1);
1586
+ }
1587
+
1588
+ let installFailed = false;
1589
+ try {
1590
+ console.log(`\nCreating the frontend in ${clientFolder} with create-vite...\n`);
1591
+ const viteArgs =
1592
+ packageManager === "pnpm"
1593
+ ? [
1594
+ "create",
1595
+ "vite@latest",
1596
+ clientFolder,
1597
+ "--no-immediate",
1598
+ ...(templateOption ? ["--template", templateOption] : []),
1599
+ ]
1600
+ : [
1601
+ "create",
1602
+ "vite@latest",
1603
+ "--",
1604
+ clientFolder,
1605
+ "--no-immediate",
1606
+ ...(templateOption ? ["--template", templateOption] : []),
1607
+ ];
1608
+ await run(packageManager, viteArgs, root);
1609
+
1610
+ const clientRoot = join(root, clientFolder);
1611
+ await Promise.all(
1612
+ [".git", "node_modules", "package-lock.json", "pnpm-lock.yaml", "yarn.lock"].map(
1613
+ (entry) => rm(join(clientRoot, entry), { recursive: true, force: true }),
1614
+ ),
1615
+ );
1616
+ const clientPackagePath = join(clientRoot, "package.json");
1617
+ const clientPackage = JSON.parse(await readFile(clientPackagePath, "utf8"));
1618
+ clientPackage.scripts ??= {};
1619
+ clientPackage.scripts.start ??= clientPackage.scripts.dev;
1620
+ await configureFrontend(clientRoot, clientPackage);
1621
+ await writeFile(clientPackagePath, `${JSON.stringify(clientPackage, null, 2)}\n`);
1622
+ await writeFile(
1623
+ join(clientRoot, ".env.local"),
1624
+ "# Local frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
1625
+ { flag: "wx" },
1626
+ );
1627
+ await writeFile(
1628
+ join(clientRoot, ".env.example"),
1629
+ "# Frontend environment variables\nVITE_API_URL=http://localhost:4000\n",
1630
+ );
1631
+
1632
+ const includeServer =
1633
+ backendOption !== undefined
1634
+ ? backendOption !== "none"
1635
+ : await chooseOption(
1636
+ "Would you like to add a separate backend server?",
1637
+ [
1638
+ { label: "Yes — include a backend workspace", value: true },
1639
+ { label: "No — create a frontend-only project", value: false },
1640
+ ],
1641
+ 0,
1642
+ "yellow",
1643
+ );
1644
+ const workspaces = [clientFolder];
1645
+ if (includeServer) {
1646
+ await scaffoldBackendStatus(clientRoot);
1647
+ await createBackend(join(root, serverFolder));
1648
+ workspaces.push(serverFolder);
1649
+ }
1650
+
1651
+ const installMode =
1652
+ installModeOption !== undefined
1653
+ ? installModeOption
1654
+ : await chooseOption(
1655
+ "How do you want to install dependencies later?",
1656
+ [
1657
+ {
1658
+ label:
1659
+ packageManager === "pnpm"
1660
+ ? "adD only — use `pnpm adD <pkg>` to choose workspaces (default)"
1661
+ : "adD only — use `npm run adD -- <pkg>` to choose workspaces (default)",
1662
+ value: "adD",
1663
+ },
1664
+ {
1665
+ label:
1666
+ packageManager === "pnpm"
1667
+ ? "Plain install only — use standard `pnpm add <pkg>`"
1668
+ : "Plain install only — use standard `npm install <pkg>`",
1669
+ value: "plain",
1670
+ },
1671
+ {
1672
+ label: "Both — allow plain installs and provide adD for choosing workspaces",
1673
+ value: "both",
1674
+ },
1675
+ ],
1676
+ 0,
1677
+ "yellow",
1678
+ );
1679
+
1680
+ await mkdir(join(root, "scripts"), { recursive: true });
1681
+ const scriptsToCopy = [
1682
+ "dev.mjs",
1683
+ "run-app.mjs",
1684
+ "install-info.mjs",
1685
+ ...(installMode !== "plain" ? ["add-dependency.mjs"] : []),
1686
+ ];
1687
+ await Promise.all(scriptsToCopy.map(copyScript));
1688
+ const rootPackage = {
1689
+ name: projectName,
1690
+ version: "1.0.0",
1691
+ private: true,
1692
+ engines: { node: ">=20.6" },
1693
+ workspaces,
1694
+ vanillaVite: {
1695
+ installMode,
1696
+ },
1697
+ scripts: {
1698
+ preinstall: "node scripts/install-info.mjs",
1699
+ postinstall: "node scripts/install-info.mjs --complete",
1700
+ dev: `node scripts/dev.mjs${exposeClient ? " --host" : ""}`,
1701
+ build:
1702
+ packageManager === "pnpm"
1703
+ ? "pnpm -r --if-present run build"
1704
+ : "npm run build --workspaces --if-present",
1705
+ lint:
1706
+ packageManager === "pnpm"
1707
+ ? "pnpm -r --if-present run lint"
1708
+ : "npm run lint --workspaces --if-present",
1709
+ client: "node scripts/run-app.mjs client",
1710
+ ...(installMode !== "plain"
1711
+ ? {
1712
+ adD: "node scripts/add-dependency.mjs",
1713
+ "add-dependency": "node scripts/add-dependency.mjs",
1714
+ }
1715
+ : {}),
1716
+ ...(includeServer ? { server: "node scripts/run-app.mjs server" } : {}),
1717
+ },
1718
+ type: "module",
1719
+ dependencies: {
1720
+ "cross-spawn": cliPackage.dependencies["cross-spawn"],
1721
+ },
1722
+ };
1723
+ await writeFile(join(root, "package.json"), `${JSON.stringify(rootPackage, null, 2)}\n`);
1724
+ if (packageManager === "pnpm") {
1725
+ await writeFile(
1726
+ join(root, "pnpm-workspace.yaml"),
1727
+ [
1728
+ "packages:",
1729
+ ...workspaces.map((workspace) => ` - ${workspace}`),
1730
+ "",
1731
+ "onlyBuiltDependencies: [esbuild]",
1732
+ "",
1733
+ "allowBuilds:",
1734
+ " esbuild: true",
1735
+ " sharp: false",
1736
+ " unrs-resolver: false",
1737
+ "",
1738
+ ].join("\n"),
1739
+ );
1740
+ }
1741
+ await writeFile(
1742
+ join(root, ".gitignore"),
1743
+ [
1744
+ "# Dependencies",
1745
+ "node_modules/",
1746
+ "",
1747
+ "# Build output",
1748
+ "**/dist/",
1749
+ "**/coverage/",
1750
+ "",
1751
+ "# Local environment files",
1752
+ "**/.env*",
1753
+ "!**/.env.example",
1754
+ "",
1755
+ "# Logs",
1756
+ "npm-debug.log*",
1757
+ "pnpm-debug.log*",
1758
+ "yarn-debug.log*",
1759
+ ".dev.log",
1760
+ ".dev.lock",
1761
+ ".install-state",
1762
+ "",
1763
+ ].join("\n"),
1764
+ );
1765
+
1766
+ console.log(`\nInstalling dependencies for ${workspaces.join(" and ")}...`);
1767
+ try {
1768
+ await run(packageManager, ["install"], root, {
1769
+ ...process.env,
1770
+ VANILLA_VITE_ALLOW_INSTALL: "1",
1771
+ });
1772
+ } catch (error) {
1773
+ installFailed = true;
1774
+ await rm(join(root, ".install-state"), { force: true });
1775
+ console.error(
1776
+ `Dependency installation failed: ${error.message}\nRetry with:\n cd "${projectName}" && ${packageManager} install`,
1777
+ );
1778
+ }
1779
+ rootCreated = false;
1780
+ process.off("SIGINT", handleCreationSignal);
1781
+ process.off("SIGTERM", handleCreationSignal);
1782
+ if (!hasOption("no-git")) {
1783
+ const repositoryCheck = spawnSync(
1784
+ "git",
1785
+ ["rev-parse", "--is-inside-work-tree"],
1786
+ { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
1787
+ );
1788
+ if (repositoryCheck.status === 0 && repositoryCheck.stdout.trim() === "true") {
1789
+ console.log("Skipping Git initialization because this project is already inside a Git work tree.");
1790
+ } else {
1791
+ const initializeGit = await chooseOption(
1792
+ "Would you like to initialize Git and create an initial commit?",
1793
+ [
1794
+ { label: "Yes — initialize Git and commit the project", value: true },
1795
+ { label: "No", value: false },
1796
+ ],
1797
+ 0,
1798
+ );
1799
+ if (initializeGit) {
1800
+ try {
1801
+ await run("git", ["init"], root);
1802
+ await run("git", ["add", "-A"], root);
1803
+ await run("git", ["commit", "-m", "Initial commit"], root);
1804
+ } catch (error) {
1805
+ console.error(`Unable to create the initial Git commit: ${error.message}`);
1806
+ }
1807
+ }
1808
+ }
1809
+ }
1810
+ console.log(
1811
+ `\nProject created successfully: ${projectName}/\n${
1812
+ installFailed
1813
+ ? "Install dependencies with the retry command above.\n"
1814
+ : noStart
1815
+ ? "Skipping the development server.\n"
1816
+ : "Starting the development server...\n"
1817
+ }`,
1818
+ );
1819
+ } catch (error) {
1820
+ if (!creationCancelled) {
1821
+ await removeIncompleteProject();
1822
+ console.error(`\nProject creation failed: ${error.message}`);
1823
+ process.exit(1);
1824
+ }
1825
+ }
1826
+
1827
+ if (!creationCancelled && !noStart && !installFailed) {
1828
+ try {
1829
+ await run(
1830
+ packageManager,
1831
+ packageManager === "pnpm" ? ["dev"] : ["run", "dev"],
1832
+ root,
1833
+ );
1834
+ } catch (error) {
1835
+ if (
1836
+ !creationCancelled &&
1837
+ error?.message &&
1838
+ !error.message.includes("SIGINT") &&
1839
+ !error.message.includes("SIGTERM") &&
1840
+ !error.message.includes("code 130")
1841
+ ) {
1842
+ console.error(
1843
+ `\nProject created successfully, but the development server could not be started: ${error.message}`,
1844
+ );
1845
+ process.exitCode = 1;
1846
+ }
1847
+ }
1848
+ }