Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

dev-watch.mjs

94 lines2.1 KB

1import { spawn } from "node:child_process";
2import { watch } from "node:fs";
3import { stat } from "node:fs/promises";
4import { dirname, extname, resolve } from "node:path";
5import { fileURLToPath } from "node:url";
6​
7const scriptsDir = dirname(fileURLToPath(import.meta.url));
8const serverDir = resolve(scriptsDir, "..");
9const srcDir = resolve(serverDir, "src");
10const entry = resolve(srcDir, "bin.ts");
11const sourceExtensions = new Set([".cjs", ".cts", ".js", ".json", ".mjs", ".mts", ".ts"]);
12​
13let child;
14let restartTimer;
15let stopping = false;
16​
17function start() {
18 child = spawn(process.execPath, [entry], {
19 stdio: "inherit",
20 env: process.env,
21 cwd: serverDir,
22 });
23​
24 child.on("exit", (code, signal) => {
25 if (stopping || restartTimer) {
26 return;
27 }
28 if (signal) {
29 process.kill(process.pid, signal);
30 return;
31 }
32 process.exit(code ?? 0);
33 });
35​
36async function shouldRestart(filename) {
37 if (!filename || typeof filename !== "string") {
38 return false;
39 }
40​
41 const changedPath = resolve(srcDir, filename);
42 if (!changedPath.startsWith(`${srcDir}/`)) {
43 return false;
44 }
45​
46 try {
47 const changedStat = await stat(changedPath);
48 if (changedStat.isDirectory()) {
49 return false;
50 }
51 } catch {
52 // Deleted source files still need a restart.
53 }
54​
55 return sourceExtensions.has(extname(changedPath));
57​
58function scheduleRestart() {
59 clearTimeout(restartTimer);
60 restartTimer = setTimeout(() => {
61 restartTimer = undefined;
62 console.log("Restarting server...");
63​
64 const previous = child;
65 previous.once("exit", () => {
66 if (!stopping) {
67 start();
68 }
69 });
70 previous.kill("SIGTERM");
71 }, 100);
73​
74const watcher = watch(srcDir, { recursive: true }, async (_event, filename) => {
75 if (await shouldRestart(filename)) {
76 scheduleRestart();
77 }
78});
79​
80function shutdown(signal) {
81 stopping = true;
82 clearTimeout(restartTimer);
83 watcher.close();
84 if (!child || child.killed) {
85 process.exit(0);
86 }
87 child.once("exit", () => process.exit(0));
88 child.kill(signal);
90​
91process.on("SIGINT", () => shutdown("SIGINT"));
92process.on("SIGTERM", () => shutdown("SIGTERM"));
93​
94start();