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

dev-electron.mjs

215 lines4.4 KB

1import { spawn, spawnSync } from "node:child_process";
2import { watch } from "node:fs";
3import { join } from "node:path";
4import waitOn from "wait-on";
5​
6import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
7​
8const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
9const devServerUrl = `http://localhost:${port}`;
10const requiredFiles = [
11 "dist-electron/main.js",
12 "dist-electron/preload.js",
13 "../server/dist/index.mjs",
14];
15const watchedDirectories = [
16 { directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
17 { directory: "../server/dist", files: new Set(["index.mjs"]) },
18];
19const forcedShutdownTimeoutMs = 1_500;
20const restartDebounceMs = 120;
21const childTreeGracePeriodMs = 1_200;
22​
23await waitOn({
24 resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
25});
26​
27const childEnv = { ...process.env };
28delete childEnv.ELECTRON_RUN_AS_NODE;
29​
30let shuttingDown = false;
31let restartTimer = null;
32let currentApp = null;
33let restartQueue = Promise.resolve();
34const expectedExits = new WeakSet();
35const watchers = [];
36​
37function killChildTreeByPid(pid, signal) {
38 if (process.platform === "win32" || typeof pid !== "number") {
39 return;
40 }
41​
42 spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
44​
45function cleanupStaleDevApps() {
46 if (process.platform === "win32") {
47 return;
48 }
49​
50 spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
52​
53function startApp() {
54 if (shuttingDown || currentApp !== null) {
55 return;
56 }
57​
58 const app = spawn(
59 resolveElectronPath(),
60 [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
61 {
62 cwd: desktopDir,
63 env: {
64 ...childEnv,
65 VITE_DEV_SERVER_URL: devServerUrl,
66 },
67 stdio: "inherit",
68 },
69 );
70​
71 currentApp = app;
72​
73 app.once("error", () => {
74 if (currentApp === app) {
75 currentApp = null;
76 }
77​
78 if (!shuttingDown) {
79 scheduleRestart();
80 }
81 });
82​
83 app.once("exit", () => {
84 if (currentApp === app) {
85 currentApp = null;
86 }
87​
88 if (!shuttingDown && !expectedExits.has(app)) {
89 scheduleRestart();
90 }
91 });
93​
94async function stopApp() {
95 const app = currentApp;
96 if (!app) {
97 return;
98 }
99​
100 currentApp = null;
101 expectedExits.add(app);
102​
103 await new Promise((resolve) => {
104 let settled = false;
105​
106 const finish = () => {
107 if (settled) {
108 return;
109 }
110​
111 settled = true;
112 resolve();
113 };
114​
115 app.once("exit", finish);
116 app.kill("SIGTERM");
117 killChildTreeByPid(app.pid, "TERM");
118​
119 setTimeout(() => {
120 if (settled) {
121 return;
122 }
123​
124 app.kill("SIGKILL");
125 killChildTreeByPid(app.pid, "KILL");
126 finish();
127 }, forcedShutdownTimeoutMs).unref();
128 });
130​
131function scheduleRestart() {
132 if (shuttingDown) {
133 return;
134 }
135​
136 if (restartTimer) {
137 clearTimeout(restartTimer);
138 }
139​
140 restartTimer = setTimeout(() => {
141 restartTimer = null;
142 restartQueue = restartQueue
143 .catch(() => undefined)
144 .then(async () => {
145 await stopApp();
146 if (!shuttingDown) {
147 startApp();
148 }
149 });
150 }, restartDebounceMs);
152​
153function startWatchers() {
154 for (const { directory, files } of watchedDirectories) {
155 const watcher = watch(
156 join(desktopDir, directory),
157 { persistent: true },
158 (_eventType, filename) => {
159 if (typeof filename !== "string" || !files.has(filename)) {
160 return;
161 }
162​
163 scheduleRestart();
164 },
165 );
166​
167 watchers.push(watcher);
168 }
170​
171function killChildTree(signal) {
172 if (process.platform === "win32") {
173 return;
174 }
175​
176 // Kill direct children as a final fallback in case normal shutdown leaves stragglers.
177 spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
179​
180async function shutdown(exitCode) {
181 if (shuttingDown) return;
182 shuttingDown = true;
183​
184 if (restartTimer) {
185 clearTimeout(restartTimer);
186 restartTimer = null;
187 }
188​
189 for (const watcher of watchers) {
190 watcher.close();
191 }
192​
193 await stopApp();
194 killChildTree("TERM");
195 await new Promise((resolve) => {
196 setTimeout(resolve, childTreeGracePeriodMs);
197 });
198 killChildTree("KILL");
199​
200 process.exit(exitCode);
202​
203startWatchers();
204cleanupStaleDevApps();
205startApp();
206​
207process.once("SIGINT", () => {
208 void shutdown(130);
209});
210process.once("SIGTERM", () => {
211 void shutdown(143);
212});
213process.once("SIGHUP", () => {
214 void shutdown(129);
215});