create-vanilla-vite 1.2.1 → 1.2.3

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.
package/scripts/dev.mjs CHANGED
@@ -6,7 +6,6 @@ import {
6
6
  closeSync,
7
7
  openSync,
8
8
  readFileSync,
9
- statSync,
10
9
  unlinkSync,
11
10
  writeFileSync,
12
11
  } from "node:fs";
@@ -19,7 +18,9 @@ const logFile = join(root, ".dev.log");
19
18
  const lockFile = join(root, ".dev.lock");
20
19
  const maxLogLines = 2000;
21
20
  const maxLogBytes = 1_000_000;
21
+ let currentLogBytes = 0;
22
22
  const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
23
+ const installMode = project.vanillaVite?.installMode ?? "adD";
23
24
  const children = [];
24
25
  let lockDescriptor;
25
26
 
@@ -139,13 +140,31 @@ async function updateEnvValue(path, key, value) {
139
140
  if (error.code !== "ENOENT") throw error;
140
141
  contents = "";
141
142
  }
142
- const expression = new RegExp(`^${key}=.*$`, "m");
143
- if (expression.test(contents)) {
144
- contents = contents.replace(expression, `${key}=${value}`);
145
- } else {
146
- contents += `${contents.endsWith("\n") ? "" : "\n"}${key}=${value}\n`;
143
+ const lines = contents.split(/\r?\n/);
144
+ let found = false;
145
+ const newLines = [];
146
+ const keyPattern = new RegExp(`^\\s*${key}\\s*=`);
147
+ for (const line of lines) {
148
+ if (keyPattern.test(line)) {
149
+ if (!found) {
150
+ newLines.push(`${key}=${value}`);
151
+ found = true;
152
+ }
153
+ } else {
154
+ newLines.push(line);
155
+ }
156
+ }
157
+ if (!found) {
158
+ if (newLines.length > 0 && newLines[newLines.length - 1] === "") {
159
+ newLines[newLines.length - 1] = `${key}=${value}`;
160
+ newLines.push("");
161
+ } else {
162
+ newLines.push(`${key}=${value}`);
163
+ newLines.push("");
164
+ }
147
165
  }
148
- await writeFile(path, contents);
166
+ const result = newLines.join("\n");
167
+ await writeFile(path, result.endsWith("\n") ? result : `${result}\n`);
149
168
  }
150
169
 
151
170
  async function ensureEnvFiles() {
@@ -172,10 +191,29 @@ async function updateNetworkEnvironment(enabled, address) {
172
191
  const server = apps.find((app) => app.name === "server");
173
192
  if (!client) return;
174
193
 
175
- const serverPort = server
176
- ? (await readFile(join(root, server.workspace, ".env"), "utf8"))
177
- .match(/^PORT=(\d+)$/m)?.[1] ?? "4000"
178
- : "4000";
194
+ let serverPort = "4000";
195
+ if (server) {
196
+ try {
197
+ const serverEnv = await readFile(join(root, server.workspace, ".env"), "utf8");
198
+ const match = serverEnv.match(/^\s*PORT\s*=\s*(.*)$/m);
199
+ if (match) {
200
+ const portCandidate = match[1].trim();
201
+ if (portCandidate !== "") {
202
+ const parsed = Number(portCandidate);
203
+ if (Number.isInteger(parsed) && parsed >= 1 && parsed <= 65535) {
204
+ serverPort = String(parsed);
205
+ } else {
206
+ log(
207
+ "dev",
208
+ `Warning: Invalid PORT "${portCandidate}" in ${server.workspace}/.env; using fallback 4000.`,
209
+ );
210
+ }
211
+ }
212
+ }
213
+ } catch (error) {
214
+ if (error.code !== "ENOENT") throw error;
215
+ }
216
+ }
179
217
  await updateEnvValue(
180
218
  join(root, client.workspace, ".env.local"),
181
219
  "VITE_API_URL",
@@ -215,10 +253,15 @@ function formatLog(name, message) {
215
253
  }
216
254
 
217
255
  function showDependencyCommands() {
256
+ if (installMode === "plain") return;
218
257
  const commands =
219
- packageManager === "pnpm"
220
- ? [" > pnpm adD <package>", " > pnpm add-dependency <package>"]
221
- : [" > npm run adD -- <package>", " > npm run add-dependency -- <package>"];
258
+ installMode === "both"
259
+ ? packageManager === "pnpm"
260
+ ? [" > pnpm adD <package> (choose workspace)", " > pnpm add <package> (or direct install)"]
261
+ : [" > npm run adD -- <package> (choose workspace)", " > npm install <package> (or direct install)"]
262
+ : packageManager === "pnpm"
263
+ ? [" > pnpm adD <package>", " > pnpm add-dependency <package>"]
264
+ : [" > npm run adD -- <package>", " > npm run add-dependency -- <package>"];
222
265
  const lines = [">>> ADD DEPENDENCIES LATER <<<", ...commands];
223
266
  const width = Math.max(...lines.map((line) => line.length));
224
267
  const border = "+".repeat(width);
@@ -358,8 +401,10 @@ function displayLog(name, message, write = console.log) {
358
401
  .replace(/\x1B\[[0-?]*[ -/]*[JKH]/g, "");
359
402
  const formatted = formatLog(name, cleanMessage);
360
403
  const plain = formatted.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
361
- appendFileSync(logFile, `${plain}\n`);
362
- if (statSync(logFile).size > maxLogBytes - 1) {
404
+ const lineBuffer = Buffer.from(`${plain}\n`);
405
+ appendFileSync(logFile, lineBuffer);
406
+ currentLogBytes += lineBuffer.length;
407
+ if (currentLogBytes > maxLogBytes - 1) {
363
408
  const lines = readFileSync(logFile, "utf8")
364
409
  .split(/\r?\n/)
365
410
  .filter(Boolean)
@@ -379,7 +424,9 @@ function displayLog(name, message, write = console.log) {
379
424
  content = bytes.subarray(-(maxLogBytes - 1)).toString("utf8");
380
425
  }
381
426
  }
382
- writeFileSync(logFile, content ? `${content}\n` : "");
427
+ const finalContent = content ? `${content}\n` : "";
428
+ writeFileSync(logFile, finalContent);
429
+ currentLogBytes = Buffer.byteLength(finalContent);
383
430
  }
384
431
 
385
432
  if (
@@ -420,6 +467,7 @@ function start({ name, workspace }) {
420
467
  stdio: ["ignore", "pipe", "pipe"],
421
468
  });
422
469
  child.appName = name;
470
+ child.intentionallyStopped = false;
423
471
  children.push(child);
424
472
  for (const stream of [child.stdout, child.stderr]) {
425
473
  stream.setEncoding("utf8");
@@ -441,11 +489,13 @@ function start({ name, workspace }) {
441
489
  stream.once("end", () => displayChildLine(pending));
442
490
  }
443
491
  child.once("error", (error) => {
492
+ if (child.intentionallyStopped) return;
444
493
  log(name, `Unable to start: ${error.message}`, console.error);
445
494
  process.exitCode = 1;
446
495
  void stop();
447
496
  });
448
497
  child.once("close", (code) => {
498
+ if (child.intentionallyStopped) return;
449
499
  if (!stopping && !restarting) {
450
500
  if (code !== 0) {
451
501
  log(name, `Process exited with code ${code ?? "unknown"}.`, console.error);
@@ -457,10 +507,12 @@ function start({ name, workspace }) {
457
507
  }
458
508
 
459
509
  function signalChild(child, signal) {
510
+ child.intentionallyStopped = true;
511
+ if (child.exitCode !== null || child.signalCode !== null) return;
460
512
  try {
461
513
  if (child.pid) {
462
514
  process.kill(-child.pid, signal);
463
- } else if (child.exitCode === null && child.signalCode === null) {
515
+ } else {
464
516
  child.kill(signal);
465
517
  }
466
518
  } catch (error) {
@@ -471,20 +523,24 @@ function signalChild(child, signal) {
471
523
  function waitForClose(child, timeout) {
472
524
  if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
473
525
  return new Promise((resolve) => {
474
- const timer = setTimeout(() => {
475
- child.off("close", onClose);
476
- resolve();
477
- }, timeout);
526
+ let timer;
478
527
  const onClose = () => {
479
528
  clearTimeout(timer);
480
529
  resolve();
481
530
  };
531
+ timer = setTimeout(() => {
532
+ child.off("close", onClose);
533
+ resolve();
534
+ }, timeout);
482
535
  child.once("close", onClose);
483
536
  });
484
537
  }
485
538
 
486
- async function stopChildren(name) {
487
- const running = children.filter((child) => !name || child.appName === name);
539
+ async function stopChildren() {
540
+ const running = [...children];
541
+ for (const child of running) {
542
+ child.intentionallyStopped = true;
543
+ }
488
544
  if (process.platform === "win32") {
489
545
  for (const child of running) {
490
546
  if (!child.pid || child.exitCode !== null || child.signalCode !== null) continue;
@@ -519,6 +575,9 @@ async function stopChildren(name) {
519
575
  async function stop() {
520
576
  if (stopping) return;
521
577
  stopping = true;
578
+ if (process.exitCode === undefined) {
579
+ process.exitCode = 0;
580
+ }
522
581
  if (process.stdin.isTTY) process.stdin.setRawMode(false);
523
582
  process.stdin.pause();
524
583
  await stopChildren();
@@ -527,11 +586,14 @@ async function stop() {
527
586
  async function restart() {
528
587
  if (restarting || stopping) return;
529
588
  restarting = true;
530
- displayRunnerLog("Restarting application processes...");
531
- await stopChildren();
532
- if (stopping) return;
533
- restarting = false;
534
- for (const app of apps) start(app);
589
+ try {
590
+ displayRunnerLog("Restarting application processes...");
591
+ await stopChildren();
592
+ if (stopping) return;
593
+ for (const app of apps) start(app);
594
+ } finally {
595
+ restarting = false;
596
+ }
535
597
  }
536
598
 
537
599
  async function toggleHost() {
@@ -547,25 +609,27 @@ async function toggleHost() {
547
609
  return;
548
610
  }
549
611
  restarting = true;
550
- let serverPort;
551
612
  try {
552
- serverPort = await updateNetworkEnvironment(nextHostEnabled, address);
553
- } catch (error) {
613
+ let serverPort;
614
+ try {
615
+ serverPort = await updateNetworkEnvironment(nextHostEnabled, address);
616
+ } catch (error) {
617
+ log("dev", `Unable to update network environment: ${error.message}`, console.error);
618
+ return;
619
+ }
620
+ hostEnabled = nextHostEnabled;
621
+ await stopChildren();
622
+ if (stopping) return;
623
+ for (const app of apps) start(app);
624
+ log(
625
+ "dev",
626
+ hostEnabled
627
+ ? `Frontend is available at http://${address}:5173; backend API is http://${address}:${serverPort}.`
628
+ : "Frontend and backend are using localhost.",
629
+ );
630
+ } finally {
554
631
  restarting = false;
555
- log("dev", `Unable to update network environment: ${error.message}`, console.error);
556
- return;
557
632
  }
558
- hostEnabled = nextHostEnabled;
559
- await stopChildren();
560
- if (stopping) return;
561
- for (const app of apps) start(app);
562
- restarting = false;
563
- log(
564
- "dev",
565
- hostEnabled
566
- ? `Frontend is available at http://${address}:5173; backend API is http://${address}:${serverPort}.`
567
- : "Frontend and backend are using localhost.",
568
- );
569
633
  }
570
634
 
571
635
  let environmentSetupFailed = false;
@@ -581,12 +645,14 @@ if (hostEnabled && !startupAddress) {
581
645
  log("dev", "Unable to find a network IPv4 address; API URL remains on localhost.", console.error);
582
646
  hostEnabled = false;
583
647
  }
584
- try {
585
- await updateNetworkEnvironment(hostEnabled, startupAddress);
586
- } catch (error) {
587
- log("dev", `Unable to update network environment: ${error.message}`, console.error);
588
- environmentSetupFailed = true;
589
- process.exitCode = 1;
648
+ if (hostEnabled) {
649
+ try {
650
+ await updateNetworkEnvironment(true, startupAddress);
651
+ } catch (error) {
652
+ log("dev", `Unable to update network environment: ${error.message}`, console.error);
653
+ environmentSetupFailed = true;
654
+ process.exitCode = 1;
655
+ }
590
656
  }
591
657
 
592
658
  if (environmentSetupFailed) process.exit(1);
@@ -599,8 +665,8 @@ const signalExitCodes = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
599
665
  for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
600
666
  process.on(signal, () => {
601
667
  signalCount += 1;
668
+ process.exitCode = signalExitCodes[signal];
602
669
  if (signalCount === 1) {
603
- process.exitCode = signalExitCodes[signal];
604
670
  void stop();
605
671
  } else {
606
672
  forceKillChildren();
@@ -613,12 +679,15 @@ if (process.stdin.isTTY) {
613
679
  process.stdin.setRawMode(true);
614
680
  process.stdin.resume();
615
681
  process.stdin.on("data", (key) => {
616
- if (key.includes("\u0003")) void stop();
617
- else if (key.toString().toLowerCase() === "r") void restart();
682
+ if (key.includes("\u0003")) {
683
+ process.exitCode = 130;
684
+ void stop();
685
+ } else if (key.toString().toLowerCase() === "r") void restart();
618
686
  else if (key.toString().toLowerCase() === "h") void toggleHost();
619
687
  else if (key.toString().toLowerCase() === "g") cycleLogLayout();
620
688
  else if (key.toString().toLowerCase() === "c") {
621
689
  writeFileSync(logFile, "");
690
+ currentLogBytes = 0;
622
691
  renderLogLayout();
623
692
  }
624
693
  });
@@ -37,26 +37,59 @@ try {
37
37
  }
38
38
  const freshInstall = installState === undefined && process.env.npm_command === "install";
39
39
 
40
- if (
41
- process.env.VANILLA_VITE_ALLOW_INSTALL !== "1" &&
42
- process.env.CI === undefined &&
43
- process.env.npm_command !== "ci" &&
44
- !freshInstall &&
45
- (installState === "installing" || installState === "installed" || hasInstalledDependencies)
46
- ) {
47
- console.error(
48
- "\nDirect installs are disabled to keep dependencies in the intended workspace.\n" +
49
- "Use `pnpm adD <package>` or `pnpm add-dependency <package>`; with npm, use `npm run adD -- <package>` or `npm run add-dependency -- <package>`.\n" +
50
- "The adD commands are the supported way to add packages.",
51
- );
52
- process.exit(1);
40
+ const installMode = project.vanillaVite?.installMode ?? "adD";
41
+
42
+ if (installMode === "both") {
43
+ if (
44
+ process.env.VANILLA_VITE_ALLOW_INSTALL !== "1" &&
45
+ process.env.CI === undefined &&
46
+ process.env.npm_command !== "ci" &&
47
+ installState !== undefined
48
+ ) {
49
+ const isPnpm = process.env.npm_config_user_agent?.startsWith("pnpm/");
50
+ console.log(
51
+ isPnpm
52
+ ? "Tip: `pnpm adD <package>` lets you pick the workspace."
53
+ : "Tip: `npm run adD -- <package>` lets you pick the workspace.",
54
+ );
55
+ }
56
+ } else if (installMode === "adD") {
57
+ if (
58
+ process.env.VANILLA_VITE_ALLOW_INSTALL !== "1" &&
59
+ process.env.CI === undefined &&
60
+ process.env.npm_command !== "ci" &&
61
+ !freshInstall &&
62
+ (installState === "installing" || installState === "installed" || hasInstalledDependencies)
63
+ ) {
64
+ const isPnpm = process.env.npm_config_user_agent?.startsWith("pnpm/");
65
+ const syncCmd = isPnpm ? "pnpm adD" : "npm run adD";
66
+ const allowCmd = isPnpm
67
+ ? "VANILLA_VITE_ALLOW_INSTALL=1 pnpm install"
68
+ : "VANILLA_VITE_ALLOW_INSTALL=1 npm install";
69
+ const rerunCmd = isPnpm
70
+ ? "rm -f .install-state && pnpm install"
71
+ : "rm -f .install-state && npm install";
72
+ console.error(
73
+ "\nDirect installs are disabled to keep dependencies in the intended workspace.\n" +
74
+ "Use `pnpm adD <package>` or `pnpm add-dependency <package>`; with npm, use `npm run adD -- <package>` or `npm run add-dependency -- <package>`.\n" +
75
+ "The adD commands are the supported way to add packages.\n\n" +
76
+ "Recovery instructions:\n" +
77
+ ` - To install dependencies across all workspaces, run \`${syncCmd}\` with no arguments to sync dependencies\n` +
78
+ ` (or ${allowCmd}).\n` +
79
+ " - If an installation was interrupted, remove .install-state and rerun:\n" +
80
+ ` ${rerunCmd}\n`,
81
+ );
82
+ process.exit(1);
83
+ }
53
84
  }
54
85
 
55
86
  if (
56
87
  process.env.VANILLA_VITE_ALLOW_INSTALL === "1" ||
57
88
  process.env.CI !== undefined ||
58
89
  process.env.npm_command === "ci" ||
59
- freshInstall
90
+ freshInstall ||
91
+ installMode === "plain" ||
92
+ installMode === "both"
60
93
  ) {
61
94
  await writeFile(installStatePath, "installing\n");
62
95
  }
@@ -11,7 +11,7 @@ const { workspaces } = JSON.parse(
11
11
  const workspace = workspaces.find((name) => name.endsWith(`-${app}`));
12
12
 
13
13
  if (!workspace || !["client", "server"].includes(app)) {
14
- console.error("Usage: npm|pnpm client|server [dev|-dev]");
14
+ console.error("Usage: pnpm client|server [dev|-dev] | npm run client|server [dev|-dev]");
15
15
  process.exit(1);
16
16
  }
17
17
 
@@ -26,7 +26,11 @@ if (args.length === 0 || (args.length === 1 && ["dev", "-dev"].includes(args[0])
26
26
  ? ["--filter", workspace, "run", script]
27
27
  : ["run", script, "--workspace", workspace];
28
28
  } else {
29
- console.error(`Usage: ${packageManager} ${app} [dev|-dev]`);
29
+ console.error(
30
+ packageManager === "pnpm"
31
+ ? `Usage: pnpm ${app} [dev|-dev]`
32
+ : `Usage: npm run ${app} [dev|-dev]`,
33
+ );
30
34
  process.exit(1);
31
35
  }
32
36
 
@@ -36,5 +40,13 @@ child.once("error", (error) => {
36
40
  process.exitCode = 1;
37
41
  });
38
42
  child.once("exit", (code, signal) => {
39
- process.exitCode = code ?? (signal ? 1 : 0);
43
+ process.exitCode =
44
+ code ??
45
+ (signal === "SIGINT"
46
+ ? 130
47
+ : signal === "SIGTERM"
48
+ ? 143
49
+ : signal
50
+ ? 1
51
+ : 0);
40
52
  });