create-vanilla-vite 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/scripts/dev.mjs CHANGED
@@ -1,10 +1,100 @@
1
1
  import spawn from "cross-spawn";
2
- import { readFile } from "node:fs/promises";
2
+ import { copyFile, readFile, writeFile } from "node:fs/promises";
3
+ import { execFileSync } from "node:child_process";
4
+ import {
5
+ appendFileSync,
6
+ closeSync,
7
+ openSync,
8
+ readFileSync,
9
+ statSync,
10
+ unlinkSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { networkInterfaces } from "node:os";
3
14
  import { join } from "node:path";
4
15
  import { fileURLToPath } from "node:url";
5
16
 
6
17
  const root = fileURLToPath(new URL("../", import.meta.url));
18
+ const logFile = join(root, ".dev.log");
19
+ const lockFile = join(root, ".dev.lock");
20
+ const maxLogLines = 2000;
21
+ const maxLogBytes = 1_000_000;
7
22
  const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
23
+ const children = [];
24
+ let lockDescriptor;
25
+
26
+ function forceKillChildren() {
27
+ for (const child of children) {
28
+ if (child.exitCode !== null || child.signalCode !== null || !child.pid) continue;
29
+ if (process.platform === "win32") {
30
+ try {
31
+ execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
32
+ stdio: "ignore",
33
+ timeout: 1000,
34
+ });
35
+ } catch (error) {
36
+ console.error(`Unable to force-stop process tree ${child.pid}: ${error.message}`);
37
+ }
38
+ } else {
39
+ try {
40
+ process.kill(-child.pid, "SIGKILL");
41
+ } catch (error) {
42
+ if (error.code !== "ESRCH") {
43
+ console.error(`Unable to kill process ${child.pid}: ${error.message}`);
44
+ }
45
+ }
46
+ }
47
+ }
48
+ }
49
+
50
+ for (;;) {
51
+ try {
52
+ lockDescriptor = openSync(lockFile, "wx");
53
+ writeFileSync(lockDescriptor, `${process.pid}\n`);
54
+ break;
55
+ } catch (error) {
56
+ if (error.code !== "EEXIST") throw error;
57
+ let activePid;
58
+ try {
59
+ activePid = Number(readFileSync(lockFile, "utf8").trim());
60
+ } catch (readError) {
61
+ if (readError.code === "ENOENT") continue;
62
+ throw readError;
63
+ }
64
+ let runnerActive = Number.isInteger(activePid) && activePid > 0;
65
+ if (runnerActive) {
66
+ try {
67
+ process.kill(activePid, 0);
68
+ } catch (processError) {
69
+ if (processError.code === "ESRCH") runnerActive = false;
70
+ else if (processError.code !== "EPERM") throw processError;
71
+ }
72
+ }
73
+ if (runnerActive) {
74
+ console.error(`A development runner is already active (PID ${activePid}).`);
75
+ process.exit(1);
76
+ }
77
+ try {
78
+ unlinkSync(lockFile);
79
+ } catch (unlinkError) {
80
+ if (unlinkError.code !== "ENOENT") throw unlinkError;
81
+ }
82
+ }
83
+ }
84
+ process.on("exit", () => {
85
+ forceKillChildren();
86
+ try {
87
+ closeSync(lockDescriptor);
88
+ } catch (error) {
89
+ if (error.code !== "EBADF") console.error(`Unable to close runner lock: ${error.message}`);
90
+ }
91
+ try {
92
+ if (readFileSync(lockFile, "utf8") === `${process.pid}\n`) unlinkSync(lockFile);
93
+ } catch (error) {
94
+ if (error.code !== "ENOENT") console.error(`Unable to remove runner lock: ${error.message}`);
95
+ }
96
+ });
97
+ writeFileSync(logFile, "");
8
98
  const packageManager = process.env.npm_config_user_agent?.startsWith("pnpm/")
9
99
  ? "pnpm"
10
100
  : "npm";
@@ -13,33 +103,342 @@ const apps = project.workspaces.map((workspace) => ({
13
103
  workspace,
14
104
  }));
15
105
  const colors = { client: 36, server: 35, dev: 90 };
16
- const children = [];
17
106
  let stopping = false;
18
107
  let restarting = false;
108
+ let hostEnabled = process.argv.includes("--host");
109
+ const hasServer = apps.some((app) => app.name === "server");
110
+ const logLayouts = hasServer
111
+ ? ["combined", "side-by-side", "stacked"]
112
+ : ["combined", "stacked"];
113
+ let logLayoutIndex = 0;
114
+
115
+ function getNetworkAddress() {
116
+ const addresses = getNetworkAddresses();
117
+ const privateAddress = addresses.find(({ address }) => {
118
+ const [first, second] = address.split(".").map(Number);
119
+ return (
120
+ first === 10 ||
121
+ (first === 192 && second === 168) ||
122
+ (first === 172 && second >= 16 && second <= 31)
123
+ );
124
+ });
125
+ return (privateAddress ?? addresses[0])?.address;
126
+ }
127
+
128
+ function getNetworkAddresses() {
129
+ return Object.values(networkInterfaces())
130
+ .flatMap((interfaces) => interfaces ?? [])
131
+ .filter((address) => address.family === "IPv4" && !address.internal);
132
+ }
133
+
134
+ async function updateEnvValue(path, key, value) {
135
+ let contents;
136
+ try {
137
+ contents = await readFile(path, "utf8");
138
+ } catch (error) {
139
+ if (error.code !== "ENOENT") throw error;
140
+ contents = "";
141
+ }
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`;
147
+ }
148
+ await writeFile(path, contents);
149
+ }
150
+
151
+ async function ensureEnvFiles() {
152
+ for (const app of apps) {
153
+ const workspaceRoot = join(root, app.workspace);
154
+ const envName = app.name === "client" ? ".env.local" : ".env";
155
+ const envPath = join(workspaceRoot, envName);
156
+ try {
157
+ await readFile(envPath);
158
+ } catch (error) {
159
+ if (error.code !== "ENOENT") throw error;
160
+ try {
161
+ await copyFile(join(workspaceRoot, ".env.example"), envPath);
162
+ } catch (exampleError) {
163
+ if (exampleError.code !== "ENOENT") throw exampleError;
164
+ await writeFile(envPath, "");
165
+ }
166
+ }
167
+ }
168
+ }
169
+
170
+ async function updateNetworkEnvironment(enabled, address) {
171
+ const client = apps.find((app) => app.name === "client");
172
+ const server = apps.find((app) => app.name === "server");
173
+ if (!client) return;
174
+
175
+ const serverPort = server
176
+ ? (await readFile(join(root, server.workspace, ".env"), "utf8"))
177
+ .match(/^PORT=(\d+)$/m)?.[1] ?? "4000"
178
+ : "4000";
179
+ await updateEnvValue(
180
+ join(root, client.workspace, ".env.local"),
181
+ "VITE_API_URL",
182
+ enabled ? `http://${address}:${serverPort}` : `http://localhost:${serverPort}`,
183
+ );
184
+ if (server) {
185
+ await updateEnvValue(
186
+ join(root, server.workspace, ".env"),
187
+ "HOST",
188
+ enabled ? "0.0.0.0" : "localhost",
189
+ );
190
+ const allowedOrigins = enabled
191
+ ? [
192
+ "http://localhost:5173",
193
+ "http://127.0.0.1:5173",
194
+ ...new Set(
195
+ getNetworkAddresses().map(({ address }) => `http://${address}:5173`),
196
+ ),
197
+ ]
198
+ : ["http://localhost:5173", "http://127.0.0.1:5173"];
199
+ await updateEnvValue(
200
+ join(root, server.workspace, ".env"),
201
+ "CORS_ORIGIN",
202
+ allowedOrigins.join(","),
203
+ );
204
+ }
205
+ return serverPort;
206
+ }
19
207
 
20
208
  function log(name, message, write = console.log) {
209
+ displayLog(name, message, write);
210
+ }
211
+
212
+ function formatLog(name, message) {
21
213
  const prefix = `[${name}]`;
22
- write(
23
- `${process.env.NO_COLOR === undefined && process.stdout.isTTY ? `\x1b[${colors[name]}m${prefix}\x1b[0m` : prefix} ${message}`,
24
- );
214
+ return `${process.env.NO_COLOR === undefined && process.stdout.isTTY ? `\x1b[${colors[name]}m${prefix}\x1b[0m` : prefix} ${message}`;
215
+ }
216
+
217
+ function showDependencyCommands() {
218
+ const commands =
219
+ packageManager === "pnpm"
220
+ ? [" > pnpm adD <package>", " > pnpm add-dependency <package>"]
221
+ : [" > npm run adD -- <package>", " > npm run add-dependency -- <package>"];
222
+ const lines = [">>> ADD DEPENDENCIES LATER <<<", ...commands];
223
+ const width = Math.max(...lines.map((line) => line.length));
224
+ const border = "+".repeat(width);
225
+ const color = process.stdout.isTTY && process.env.NO_COLOR === undefined;
226
+ const paint = (code, text) => color ? `\x1b[${code}m${text}\x1b[0m` : text;
227
+ console.log(paint("1;33", border));
228
+ console.log(paint("1;33", lines[0].padEnd(width)));
229
+ for (const line of lines.slice(1)) console.log(paint("1;36", line.padEnd(width)));
230
+ console.log(paint("1;33", border));
231
+ }
232
+
233
+ function showShortcuts() {
234
+ const layoutHelp = hasServer
235
+ ? " [g] Change log layout: combined / split / stacked "
236
+ : " [g] Toggle combined / divided client logs ";
237
+ const lines = [
238
+ " VANILLA VITE · DEVELOPMENT CONTROLS ",
239
+ " [r] Restart [h] Network host [c] Clear [Ctrl+C] Stop ",
240
+ layoutHelp,
241
+ ];
242
+ const width = Math.max(...lines.map((line) => line.length));
243
+ const border = "+".repeat(width);
244
+ const color = process.stdout.isTTY && process.env.NO_COLOR === undefined;
245
+ const paint = (text) => color ? `\x1b[1;36m${text}\x1b[0m` : text;
246
+ console.log(paint(border));
247
+ for (const line of lines) console.log(paint(line.padEnd(width)));
248
+ console.log(paint(border));
249
+ }
250
+
251
+ function clippedLine(value, width) {
252
+ const plain = value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
253
+ const content = plain.length > width ? `${plain.slice(0, Math.max(0, width - 1))}…` : plain;
254
+ return `${content}${" ".repeat(Math.max(0, width - content.length))}`;
255
+ }
256
+
257
+ function panelLines(name, width, lines) {
258
+ return [
259
+ name.toUpperCase(),
260
+ "-".repeat(width),
261
+ ...lines.map((line) => clippedLine(line, width)),
262
+ ];
263
+ }
264
+
265
+ function sideBySideRow(name, formatted, panelWidth) {
266
+ const line = clippedLine(formatted, panelWidth);
267
+ const empty = " ".repeat(panelWidth);
268
+ const left = name === "client" ? line : empty;
269
+ const right = name === "server" ? line : empty;
270
+ return `${left} | ${right}\n`;
271
+ }
272
+
273
+ function renderLogLayout() {
274
+ if (!process.stdout.isTTY) return;
275
+ process.stdout.write("\x1b[2J\x1b[H");
276
+ showDependencyCommands();
277
+ showShortcuts();
278
+
279
+ const layout = logLayouts[logLayoutIndex];
280
+ const entries = readFileSync(logFile, "utf8")
281
+ .split(/\r?\n/)
282
+ .filter(Boolean)
283
+ .slice(-maxLogLines)
284
+ .map((line) => {
285
+ const match = /^\[(client|server|dev)\]\s?(.*)$/.exec(line);
286
+ return match ? { name: match[1], message: match[2] } : null;
287
+ })
288
+ .filter(Boolean);
289
+ if (layout === "combined") {
290
+ for (const entry of entries) {
291
+ process.stdout.write(`${formatLog(entry.name, entry.message)}\n`);
292
+ }
293
+ return;
294
+ }
295
+
296
+ const columns = Math.max(40, process.stdout.columns ?? 80);
297
+ if (layout === "side-by-side" && columns >= 80) {
298
+ const panelWidth = Math.floor((columns - 3) / 2);
299
+ process.stdout.write(`${"CLIENT".padEnd(panelWidth)} | SERVER\n`);
300
+ process.stdout.write(`${"-".repeat(panelWidth)} | ${"-".repeat(panelWidth)}\n`);
301
+ for (const entry of entries) {
302
+ const formatted = formatLog(entry.name, entry.message);
303
+ process.stdout.write(
304
+ entry.name === "dev"
305
+ ? `${formatted}\n`
306
+ : sideBySideRow(entry.name, formatted, panelWidth),
307
+ );
308
+ }
309
+ return;
310
+ }
311
+
312
+ const clientLogs = entries
313
+ .filter((entry) => entry.name === "client")
314
+ .map((entry) => formatLog(entry.name, entry.message));
315
+ const serverLogs = entries
316
+ .filter((entry) => entry.name === "server")
317
+ .map((entry) => formatLog(entry.name, entry.message));
318
+ const runnerLogs = entries.filter((entry) => entry.name === "dev");
319
+
320
+ for (const entry of runnerLogs) {
321
+ process.stdout.write(`${formatLog("dev", entry.message)}\n`);
322
+ }
323
+
324
+ const panelWidth = columns;
325
+ for (const [index, { name }] of apps.entries()) {
326
+ const lines = panelLines(
327
+ name,
328
+ panelWidth,
329
+ name === "client" ? clientLogs : serverLogs,
330
+ );
331
+ if (index > 0) process.stdout.write(`${"-".repeat(panelWidth)}\n`);
332
+ process.stdout.write(`${lines.join("\n")}\n`);
333
+ }
334
+ }
335
+
336
+ function displayRunnerLog(message) {
337
+ displayLog("dev", message);
338
+ }
339
+
340
+ function appendLogInLayout(name, formatted) {
341
+ const layout = logLayouts[logLayoutIndex];
342
+ if (layout === "side-by-side" && (process.stdout.columns ?? 80) >= 80) {
343
+ if (name !== "client" && name !== "server") {
344
+ process.stdout.write(`${formatted}\n`);
345
+ return;
346
+ }
347
+ const panelWidth = Math.floor(((process.stdout.columns ?? 80) - 3) / 2);
348
+ process.stdout.write(sideBySideRow(name, formatted, panelWidth));
349
+ return;
350
+ }
351
+
352
+ process.stdout.write(`${formatted}\n`);
353
+ }
354
+
355
+ function displayLog(name, message, write = console.log) {
356
+ const cleanMessage = message
357
+ .replace(/\x1Bc/g, "")
358
+ .replace(/\x1B\[[0-?]*[ -/]*[JKH]/g, "");
359
+ const formatted = formatLog(name, cleanMessage);
360
+ const plain = formatted.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
361
+ appendFileSync(logFile, `${plain}\n`);
362
+ if (statSync(logFile).size > maxLogBytes - 1) {
363
+ const lines = readFileSync(logFile, "utf8")
364
+ .split(/\r?\n/)
365
+ .filter(Boolean)
366
+ .slice(-maxLogLines);
367
+ let content = lines.join("\n");
368
+ let bytes = Buffer.from(content);
369
+ if (bytes.length > maxLogBytes - 1) {
370
+ let start = bytes.length - (maxLogBytes - 1);
371
+ while (start < bytes.length && (bytes[start] & 0b11000000) === 0b10000000) {
372
+ start += 1;
373
+ }
374
+ content = bytes.subarray(start).toString("utf8");
375
+ const firstLineBreak = content.indexOf("\n");
376
+ if (firstLineBreak !== -1) content = content.slice(firstLineBreak + 1);
377
+ bytes = Buffer.from(content);
378
+ if (bytes.length > maxLogBytes - 1) {
379
+ content = bytes.subarray(-(maxLogBytes - 1)).toString("utf8");
380
+ }
381
+ }
382
+ writeFileSync(logFile, content ? `${content}\n` : "");
383
+ }
384
+
385
+ if (
386
+ write === console.log &&
387
+ process.stdout.isTTY &&
388
+ logLayouts[logLayoutIndex] !== "combined"
389
+ ) {
390
+ appendLogInLayout(name, formatted);
391
+ } else {
392
+ write(formatted);
393
+ }
394
+ }
395
+
396
+ function displayAppLog(name, message) {
397
+ displayLog(name, message);
398
+ }
399
+
400
+ function cycleLogLayout() {
401
+ logLayoutIndex = (logLayoutIndex + 1) % logLayouts.length;
402
+ renderLogLayout();
25
403
  }
26
404
 
27
405
  function start({ name, workspace }) {
28
406
  const args =
29
407
  packageManager === "pnpm"
30
- ? ["--filter", workspace, "run", "dev"]
31
- : ["run", "dev", "--workspace", workspace];
408
+ ? ["--filter", workspace, "run", "dev", ...(name === "client" && hostEnabled ? ["--host"] : [])]
409
+ : [
410
+ "run",
411
+ "dev",
412
+ "--workspace",
413
+ workspace,
414
+ ...(name === "client" && hostEnabled ? ["--", "--host"] : []),
415
+ ];
32
416
  const child = spawn(packageManager, args, {
33
417
  cwd: root,
34
418
  detached: process.platform !== "win32",
419
+ env: { ...process.env, FORCE_COLOR: "1" },
35
420
  stdio: ["ignore", "pipe", "pipe"],
36
421
  });
422
+ child.appName = name;
37
423
  children.push(child);
38
424
  for (const stream of [child.stdout, child.stderr]) {
39
425
  stream.setEncoding("utf8");
426
+ let pending = "";
427
+ const displayChildLine = (line) => {
428
+ if (!line) return;
429
+ const expectedPnpmStop =
430
+ packageManager === "pnpm" &&
431
+ (stopping || restarting) &&
432
+ (line.includes("ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL") ||
433
+ line.includes('"pnpm recursive run" failed'));
434
+ if (!expectedPnpmStop) displayAppLog(name, line);
435
+ };
40
436
  stream.on("data", (chunk) => {
41
- for (const line of chunk.split(/\r?\n/).filter(Boolean)) log(name, line);
437
+ const lines = `${pending}${chunk}`.split(/\r?\n/);
438
+ pending = lines.pop() ?? "";
439
+ for (const line of lines) displayChildLine(line);
42
440
  });
441
+ stream.once("end", () => displayChildLine(pending));
43
442
  }
44
443
  child.once("error", (error) => {
45
444
  log(name, `Unable to start: ${error.message}`, console.error);
@@ -48,6 +447,9 @@ function start({ name, workspace }) {
48
447
  });
49
448
  child.once("close", (code) => {
50
449
  if (!stopping && !restarting) {
450
+ if (code !== 0) {
451
+ log(name, `Process exited with code ${code ?? "unknown"}.`, console.error);
452
+ }
51
453
  process.exitCode = code ?? 1;
52
454
  void stop();
53
455
  }
@@ -56,7 +458,7 @@ function start({ name, workspace }) {
56
458
 
57
459
  function signalChild(child, signal) {
58
460
  try {
59
- if (process.platform !== "win32" && child.pid) {
461
+ if (child.pid) {
60
462
  process.kill(-child.pid, signal);
61
463
  } else if (child.exitCode === null && child.signalCode === null) {
62
464
  child.kill(signal);
@@ -81,15 +483,37 @@ function waitForClose(child, timeout) {
81
483
  });
82
484
  }
83
485
 
84
- async function stopChildren() {
85
- const running = [...children];
486
+ async function stopChildren(name) {
487
+ const running = children.filter((child) => !name || child.appName === name);
488
+ if (process.platform === "win32") {
489
+ for (const child of running) {
490
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) continue;
491
+ try {
492
+ execFileSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
493
+ stdio: "ignore",
494
+ timeout: 1000,
495
+ });
496
+ } catch (error) {
497
+ log("dev", `Unable to force-stop process tree ${child.pid}: ${error.message}`, console.error);
498
+ }
499
+ }
500
+ await Promise.all(running.map((child) => waitForClose(child, 750)));
501
+ for (const child of running) {
502
+ const index = children.indexOf(child);
503
+ if (index !== -1) children.splice(index, 1);
504
+ }
505
+ return;
506
+ }
86
507
  for (const child of running) signalChild(child, "SIGINT");
87
508
  await Promise.all(running.map((child) => waitForClose(child, 3000)));
88
509
  for (const child of running) signalChild(child, "SIGTERM");
89
510
  await Promise.all(running.map((child) => waitForClose(child, 1000)));
90
511
  for (const child of running) signalChild(child, "SIGKILL");
91
512
  await Promise.all(running.map((child) => waitForClose(child, 1000)));
92
- children.length = 0;
513
+ for (const child of running) {
514
+ const index = children.indexOf(child);
515
+ if (index !== -1) children.splice(index, 1);
516
+ }
93
517
  }
94
518
 
95
519
  async function stop() {
@@ -103,30 +527,99 @@ async function stop() {
103
527
  async function restart() {
104
528
  if (restarting || stopping) return;
105
529
  restarting = true;
106
- log("dev", "Restarting application processes...");
530
+ displayRunnerLog("Restarting application processes...");
107
531
  await stopChildren();
108
532
  if (stopping) return;
109
533
  restarting = false;
110
534
  for (const app of apps) start(app);
111
- log("dev", "Application processes restarted.");
112
535
  }
113
536
 
537
+ async function toggleHost() {
538
+ if (restarting || stopping) return;
539
+ if (!apps.some((app) => app.name === "client")) {
540
+ log("dev", "No frontend workspace is available to host.");
541
+ return;
542
+ }
543
+ const nextHostEnabled = !hostEnabled;
544
+ const address = nextHostEnabled ? getNetworkAddress() : undefined;
545
+ if (nextHostEnabled && !address) {
546
+ log("dev", "Unable to find a network IPv4 address; hosting mode was not changed.", console.error);
547
+ return;
548
+ }
549
+ restarting = true;
550
+ let serverPort;
551
+ try {
552
+ serverPort = await updateNetworkEnvironment(nextHostEnabled, address);
553
+ } catch (error) {
554
+ restarting = false;
555
+ log("dev", `Unable to update network environment: ${error.message}`, console.error);
556
+ return;
557
+ }
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
+ }
570
+
571
+ let environmentSetupFailed = false;
572
+ try {
573
+ await ensureEnvFiles();
574
+ } catch (error) {
575
+ log("dev", `Unable to initialize workspace environment files: ${error.message}`, console.error);
576
+ process.exit(1);
577
+ }
578
+
579
+ const startupAddress = hostEnabled ? getNetworkAddress() : undefined;
580
+ if (hostEnabled && !startupAddress) {
581
+ log("dev", "Unable to find a network IPv4 address; API URL remains on localhost.", console.error);
582
+ hostEnabled = false;
583
+ }
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;
590
+ }
591
+
592
+ if (environmentSetupFailed) process.exit(1);
593
+ showDependencyCommands();
594
+ showShortcuts();
114
595
  for (const app of apps) start(app);
115
596
 
116
- for (const signal of ["SIGINT", "SIGTERM"]) {
117
- process.once(signal, () => void stop());
597
+ let signalCount = 0;
598
+ const signalExitCodes = { SIGINT: 130, SIGTERM: 143, SIGHUP: 129 };
599
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
600
+ process.on(signal, () => {
601
+ signalCount += 1;
602
+ if (signalCount === 1) {
603
+ process.exitCode = signalExitCodes[signal];
604
+ void stop();
605
+ } else {
606
+ forceKillChildren();
607
+ process.exit(signalExitCodes[signal]);
608
+ }
609
+ });
118
610
  }
119
611
 
120
612
  if (process.stdin.isTTY) {
121
- console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
122
613
  process.stdin.setRawMode(true);
123
614
  process.stdin.resume();
124
615
  process.stdin.on("data", (key) => {
125
616
  if (key.includes("\u0003")) void stop();
126
617
  else if (key.toString().toLowerCase() === "r") void restart();
618
+ else if (key.toString().toLowerCase() === "h") void toggleHost();
619
+ else if (key.toString().toLowerCase() === "g") cycleLogLayout();
127
620
  else if (key.toString().toLowerCase() === "c") {
128
- process.stdout.write("\x1b[2J\x1b[H");
129
- console.log("Shortcuts: r = restart, c = clear terminal, Ctrl+C = stop.");
621
+ writeFileSync(logFile, "");
622
+ renderLogLayout();
130
623
  }
131
624
  });
132
625
  }
@@ -1,20 +1,73 @@
1
- import { readFile } from "node:fs/promises";
2
- import { join } from "node:path";
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import { join, relative } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
 
5
6
  const root = fileURLToPath(new URL("../", import.meta.url));
6
7
  const project = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
8
+ const installStatePath = join(root, ".install-state");
9
+ if (process.argv.includes("--complete")) {
10
+ await writeFile(installStatePath, "installed\n");
11
+ process.exit(0);
12
+ }
13
+ const workspaces = await Promise.all(
14
+ project.workspaces.map(async (workspace) => ({
15
+ path: join(root, workspace),
16
+ manifest: JSON.parse(await readFile(join(root, workspace, "package.json"), "utf8")),
17
+ })),
18
+ );
19
+ const declaredDependencies = [
20
+ ...Object.keys(project.dependencies ?? {}),
21
+ ...Object.keys(project.devDependencies ?? {}),
22
+ ...workspaces.flatMap(({ manifest }) => [
23
+ ...Object.keys(manifest.dependencies ?? {}),
24
+ ...Object.keys(manifest.devDependencies ?? {}),
25
+ ]),
26
+ ];
27
+ const hasInstalledDependencies = declaredDependencies.some(
28
+ (dependency) =>
29
+ existsSync(join(root, "node_modules", dependency)) ||
30
+ workspaces.some(({ path }) => existsSync(join(path, "node_modules", dependency))),
31
+ );
32
+ let installState;
33
+ try {
34
+ installState = (await readFile(installStatePath, "utf8")).trim();
35
+ } catch (error) {
36
+ if (error.code !== "ENOENT") throw error;
37
+ }
38
+ const freshInstall = installState === undefined && process.env.npm_command === "install";
7
39
 
8
- console.log("Installing workspace dependencies:");
9
- for (const workspace of project.workspaces) {
10
- const manifest = JSON.parse(
11
- await readFile(join(root, workspace, "package.json"), "utf8"),
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.",
12
51
  );
52
+ process.exit(1);
53
+ }
54
+
55
+ if (
56
+ process.env.VANILLA_VITE_ALLOW_INSTALL === "1" ||
57
+ process.env.CI !== undefined ||
58
+ process.env.npm_command === "ci" ||
59
+ freshInstall
60
+ ) {
61
+ await writeFile(installStatePath, "installing\n");
62
+ }
63
+
64
+ console.log("Installing workspace dependencies:");
65
+ for (const { path, manifest } of workspaces) {
13
66
  const dependencies = {
14
67
  ...manifest.dependencies,
15
68
  ...manifest.devDependencies,
16
69
  };
17
- console.log(`\n${manifest.name} (${workspace}):`);
70
+ console.log(`\n${manifest.name} (${relative(root, path)}):`);
18
71
  if (!Object.keys(dependencies).length) {
19
72
  console.log(" No dependencies declared.");
20
73
  continue;