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

dev.ts

131 lines5.0 KB

1// @effect-diagnostics nodeBuiltinImport:off globalConsole:off globalDate:off globalTimers:off - Standalone Node watch launcher.
2import * as NodeChildProcess from "node:child_process";
3import * as NodeFS from "node:fs";
4import * as NodeOS from "node:os";
5import * as NodePath from "node:path";
6​
7const serverDir = NodePath.resolve(import.meta.dirname, "..");
8const entry = "src/bin.ts";
9const packageDirs = [
10 serverDir,
11 ...NodeFS.globSync("../../packages/*/package.json", { cwd: serverDir }).map((file) =>
12 NodePath.resolve(serverDir, NodePath.dirname(file)),
13 ),
14];
15​
16let child: NodeChildProcess.ChildProcess | undefined;
17let startedAt = 0;
18let restartPending = false;
19let stopping = false;
20let debounce: NodeJS.Timeout | undefined;
21const changedPaths = new Map<string, NodeFS.WatchEventType>();
22​
23// `node --watch` cannot be used: on Windows, libuv reports NTFS last-access updates as changes,
24// so merely reading a source file (or an installed dependency directory) restarted the server.
25// A path counts as changed only when it is gone or written since the running server started.
26// A moved-in directory counts via its rename: its files may report nothing or keep older timestamps.
27const isWrittenSinceStart = ([path, event]: [string, NodeFS.WatchEventType]) => {
28 try {
29 const stats = NodeFS.statSync(path);
30 if (stats.isDirectory()) return event === "rename" && NodeFS.lstatSync(path).isDirectory();
31 return Math.max(stats.mtimeMs, stats.ctimeMs) >= startedAt;
32 } catch {
33 return true;
34 }
35};
36​
37const start = () => {
38 startedAt = Date.now();
39 restartPending = false;
40 child = NodeChildProcess.spawn(process.execPath, [entry, ...process.argv.slice(2)], {
41 cwd: serverDir,
42 stdio: "inherit",
43 });
44 child.on("error", (error) => console.error(error));
45 child.on("exit", (code, signal) => {
46 child = undefined;
47 if (stopping) {
48 process.exitCode = code ?? (signal === null ? 1 : 128 + NodeOS.constants.signals[signal]);
49 return;
50 }
51 if (restartPending) return start();
52 console.log(
53 `[dev] '${entry}' exited (${signal ?? code}). Waiting for file changes before restarting...`,
54 );
55 });
56};
57​
58const flush = () => {
59 debounce = undefined;
60 const [changed] = [...changedPaths].find(isWrittenSinceStart) ?? [];
61 changedPaths.clear();
62 if (changed === undefined || stopping || restartPending) return;
63 console.log(`[dev] Restarting '${entry}': ${NodePath.relative(serverDir, changed)} changed`);
64 if (!child) return start();
65 restartPending = true;
66 child.kill("SIGTERM");
67};
68​
69const onChange = (path: string, event: NodeFS.WatchEventType) => {
70 if (changedPaths.get(path) !== "rename") changedPaths.set(path, event);
71 debounce ??= setTimeout(flush, 200);
72};
73​
74// oxlint-disable-next-line t3code/no-global-process-runtime -- The standalone launcher has no Effect runtime.
75const linux = NodeOS.platform() === "linux";
76// Linux recursive watches stay on a replaced directory's old inode, so watch each directory
77// itself and reattach a child whenever its name is renamed.
78const watchSrc = (src: string, nested = false): { close(): void } | undefined => {
79 const children = new Map<string, { close(): void }>();
80 let watcher: NodeFS.FSWatcher | undefined;
81 const close = () => [watcher, ...children.values()].forEach((handle) => handle?.close());
82 const attach = (name: string) => {
83 children.get(name)?.close();
84 children.delete(name);
85 const child = watchSrc(NodePath.join(src, name), true);
86 if (child) children.set(name, child);
87 };
88 try {
89 if (nested && !NodeFS.lstatSync(src, { throwIfNoEntry: false })?.isDirectory()) return;
90 watcher = NodeFS.watch(src, { recursive: !linux }, (event, name) => {
91 if (linux && name && event === "rename") attach(name);
92 onChange(name ? NodePath.join(src, name) : src, event);
93 });
94 for (const name of linux ? NodeFS.readdirSync(src) : []) attach(name);
95 return { close };
96 } catch (error) {
97 close();
98 if (error instanceof Error && "code" in error && error.code === "ENOENT") return undefined;
99 if (linux && error instanceof Error && "code" in error && error.code === "ENOTDIR") return;
100 throw error;
101 }
102};
103​
104// Watch only each workspace package's src and package.json, never its node_modules.
105// A renamed src root keeps its watch on the old tree: reattach, or wait for the next rename if gone.
106const watchers = packageDirs.flatMap((dir) => {
107 const src = NodePath.join(dir, "src");
108 let srcWatcher = watchSrc(src);
109 return [
110 NodeFS.watch(dir, (event, name) => {
111 if (name === "package.json") onChange(NodePath.join(dir, name), event);
112 if (name !== "src" || event !== "rename") return;
113 srcWatcher?.close();
114 srcWatcher = watchSrc(src);
115 onChange(src, event);
116 }),
117 { close: () => srcWatcher?.close() },
118 ];
119});
120​
121const stop = (signal: NodeJS.Signals) => {
122 stopping = true;
123 clearTimeout(debounce);
124 for (const watcher of watchers) watcher.close();
125 if (child) child.kill(signal);
126};
127process.on("SIGINT", () => stop("SIGINT"));
128process.on("SIGTERM", () => stop("SIGTERM"));
129process.on("SIGHUP", () => stop("SIGTERM"));
130​
131start();