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

dev-electron.mjs

196 lines5.2 KB

1import { spawn } from "node:child_process";
2import fs from "node:fs";
3import net from "node:net";
4import path from "node:path";
5​
6const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5173);
7const STARTUP_TIMEOUT_MS = Number(process.env.T3CODE_ELECTRON_STARTUP_TIMEOUT_MS ?? 120_000);
8​
9async function canConnect(host, probePort, timeoutMs = 1_000) {
10 return new Promise((resolve) => {
11 const socket = new net.Socket();
12 let settled = false;
13​
14 const finish = (value) => {
15 if (settled) return;
16 settled = true;
17 socket.destroy();
18 resolve(value);
19 };
20​
21 socket.setTimeout(timeoutMs);
22 socket.once("connect", () => finish(true));
23 socket.once("timeout", () => finish(false));
24 socket.once("error", () => finish(false));
25 socket.connect(probePort, host);
26 });
28​
29const f = (p) => path.join(import.meta.dirname, "..", p);
30​
31function inspectBundleFile(bundleFile) {
32 let stat = null;
33 try {
34 stat = fs.statSync(bundleFile.path);
35 } catch {
36 return {
37 ...bundleFile,
38 status: "missing",
39 mtimeMs: null,
40 reason: "not found",
41 };
42 }
43​
44 return {
45 ...bundleFile,
46 status: "ready",
47 mtimeMs: stat.mtimeMs,
48 reason: "ok",
49 };
51​
52function describeBundleStates(states) {
53 return states
54 .map((state) => {
55 const mtime =
56 typeof state.mtimeMs === "number" ? new Date(state.mtimeMs).toISOString() : "n/a";
57 return `${state.label}=${state.status} (mtime=${mtime}; reason=${state.reason})`;
58 })
59 .join("; ");
61​
62function waitForDesktopBundles(timeoutMs) {
63 const startedAt = Date.now();
64 const bundleFiles = [
65 {
66 path: f("dist-electron/main.mjs"),
67 label: "desktop/main.mjs",
68 },
69 {
70 path: f("dist-electron/preload.cjs"),
71 label: "desktop/preload.cjs",
72 },
73 {
74 path: f("../server/dist/index.mjs"),
75 label: "server/index.mjs",
76 },
77 ];
78 let lastProgressLogAt = 0;
79​
80 return new Promise((resolve, reject) => {
81 const tick = () => {
82 const states = bundleFiles.map(inspectBundleFile);
83 const missing = states.filter((state) => state.status === "missing");
84​
85 if (missing.length === 0) {
86 resolve();
87 return;
88 }
89​
90 const elapsedMs = Date.now() - startedAt;
91 if (elapsedMs >= timeoutMs) {
92 const parts = [];
93 if (missing.length > 0) {
94 parts.push(`missing: ${missing.map((state) => state.label).join(", ")}`);
95 }
96 reject(
97 new Error(
98 `[dev-electron] timed out after ${timeoutMs}ms waiting for bundles (${parts.join("; ")})\n[dev-electron] bundle state: ${describeBundleStates(states)}`,
99 ),
100 );
101 return;
102 }
103​
104 if (Date.now() - lastProgressLogAt >= 5_000) {
105 lastProgressLogAt = Date.now();
106 const waitParts = [];
107 if (missing.length > 0) {
108 waitParts.push(`missing=${missing.map((state) => state.label).join(",")}`);
109 }
110 console.log(
111 `[dev-electron] still waiting for bundles after ${elapsedMs}ms (${waitParts.join("; ")})`,
112 );
113 }
114​
115 setTimeout(tick, 250);
116 };
117​
118 tick();
119 });
121​
122function waitForDevServer(probePort, timeoutMs) {
123 const startedAt = Date.now();
124 const candidates = [
125 { host: "127.0.0.1", url: `http://127.0.0.1:${probePort}` },
126 { host: "::1", url: `http://[::1]:${probePort}` },
127 { host: "localhost", url: `http://localhost:${probePort}` },
128 ];
129​
130 return new Promise((resolve, reject) => {
131 const tick = () => {
132 void Promise.all(
133 candidates.map(async (candidate) => ({
134 candidate,
135 connected: await canConnect(candidate.host, probePort),
136 })),
137 )
138 .then((results) => {
139 const ready = results.find((entry) => entry.connected);
140 if (ready) {
141 resolve(ready.candidate.url);
142 return;
143 }
144​
145 if (Date.now() - startedAt >= timeoutMs) {
146 reject(
147 new Error(
148 `[dev-electron] timed out after ${timeoutMs}ms waiting for renderer dev server on port ${probePort}`,
149 ),
150 );
151 return;
152 }
153​
154 setTimeout(tick, 250);
155 })
156 .catch((error) => {
157 reject(error);
158 });
159 };
160​
161 tick();
162 });
164​
165console.log("[dev-electron] waiting for desktop/server bundles");
166await waitForDesktopBundles(STARTUP_TIMEOUT_MS);
167​
168console.log(`[dev-electron] waiting for renderer dev server on port ${port}`);
169const devServerUrl = await waitForDevServer(port, STARTUP_TIMEOUT_MS);
170console.log(`[dev-electron] launching electron with renderer url ${devServerUrl}`);
171​
172const command = process.platform === "win32" ? "electronmon.cmd" : "electronmon";
173const childEnv = { ...process.env };
174delete childEnv.ELECTRON_RUN_AS_NODE;
175​
176if (process.platform === "linux" && !childEnv.ELECTRON_DISABLE_SANDBOX) {
177 childEnv.ELECTRON_DISABLE_SANDBOX = "1";
178 console.log("[dev-electron] enabling ELECTRON_DISABLE_SANDBOX=1 on Linux");
180​
181const child = spawn(command, ["dist-electron/main.mjs"], {
182 stdio: "inherit",
183 env: {
184 ...childEnv,
185 VITE_DEV_SERVER_URL: devServerUrl,
186 },
187});
188​
189child.on("exit", (code) => {
190 process.exit(code ?? 0);
191});
192​
193child.on("error", (error) => {
194 console.error("[dev-electron] failed to launch electronmon:", error.message);
195 process.exit(1);
196});