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

electron-launcher.mjs

425 lines14.1 KB

1// This file mostly exists because we want dev mode to say "T3 Code (Dev)" instead of "electron"
2​
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeModule from "node:module";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import * as NodeURL from "node:url";
9import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
10​
11const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
12const __dirname = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
13export const desktopDir = NodePath.resolve(__dirname, "..");
14const repoRoot = NodePath.resolve(desktopDir, "..", "..");
15const devBundleIdSuffix = NodePath.basename(repoRoot)
16 .toLowerCase()
17 .replaceAll(/[^a-z0-9]+/g, "");
18export const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
19export const APP_BUNDLE_ID = isDevelopment
20 ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
21 : "com.t3tools.t3code";
22const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
23const LAUNCHER_VERSION = 14;
24const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
25const developmentMacIconPngPath = NodePath.join(
26 repoRoot,
27 "assets",
28 "dev",
29 "blueprint-macos-1024.png",
30);
31// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
32const hostPlatform = NodeOS.platform();
33​
34function setPlistString(plistPath, key, value) {
35 const replaceResult = NodeChildProcess.spawnSync(
36 "plutil",
37 ["-replace", key, "-string", value, plistPath],
38 {
39 encoding: "utf8",
40 },
41 );
42 if (replaceResult.status === 0) {
43 return;
44 }
45​
46 const insertResult = NodeChildProcess.spawnSync(
47 "plutil",
48 ["-insert", key, "-string", value, plistPath],
49 {
50 encoding: "utf8",
51 },
52 );
53 if (insertResult.status === 0) {
54 return;
55 }
56​
57 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
58 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
60​
61function setPlistJson(plistPath, key, value) {
62 const serialized = JSON.stringify(value);
63 const replaceResult = NodeChildProcess.spawnSync(
64 "plutil",
65 ["-replace", key, "-json", serialized, plistPath],
66 {
67 encoding: "utf8",
68 },
69 );
70 if (replaceResult.status === 0) {
71 return;
72 }
73​
74 const insertResult = NodeChildProcess.spawnSync(
75 "plutil",
76 ["-insert", key, "-json", serialized, plistPath],
77 {
78 encoding: "utf8",
79 },
80 );
81 if (insertResult.status === 0) {
82 return;
83 }
84​
85 const details = [replaceResult.stderr, insertResult.stderr].filter(Boolean).join("\n");
86 throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
88​
89function runChecked(command, args) {
90 const result = NodeChildProcess.spawnSync(command, args, { encoding: "utf8" });
91 if (result.status === 0) {
92 return;
93 }
94​
95 const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
96 throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
98​
99function shellSingleQuote(value) {
100 return `'${value.replaceAll("'", "'\\''")}'`;
102​
103export function makeDevelopmentLauncherScript({
104 electronBinaryPath,
105 mainEntryPath,
106 desktopRoot,
107 environment,
108}) {
109 const envEntries = [
110 ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
111 ["T3CODE_PORT", environment.T3CODE_PORT],
112 ["T3CODE_HOME", environment.T3CODE_HOME],
113 ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
114 ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
115 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
116 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
117 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
118 return [
119 "#!/bin/sh",
120 ...envEntries.map(
121 ([name, value]) =>
122 `if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
123 ),
124 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
125 "",
126 ].join("\n");
128​
129function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
130 NodeFS.writeFileSync(
131 targetBinaryPath,
132 makeDevelopmentLauncherScript({
133 electronBinaryPath,
134 mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
135 desktopRoot: desktopDir,
136 environment: process.env,
137 }),
138 );
139 NodeFS.chmodSync(targetBinaryPath, 0o755);
141​
142function registerMacLauncherBundle(appBundlePath) {
143 runChecked(
144 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
145 ["-f", appBundlePath],
146 );
147​
148 if (!isDevelopment) {
149 return;
150 }
151​
152 for (const scheme of APP_PROTOCOL_SCHEMES) {
153 runChecked("osascript", [
154 "-l",
155 "JavaScript",
156 "-e",
157 [
158 'ObjC.import("CoreServices");',
159 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
160 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
161 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
162 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
163 ].join(" "),
164 ]);
165 }
167​
168function ensureDevelopmentIconIcns(runtimeDir) {
169 const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
170 NodeFS.mkdirSync(runtimeDir, { recursive: true });
171​
172 if (!NodeFS.existsSync(developmentMacIconPngPath)) {
173 return defaultIconPath;
174 }
175​
176 const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
177 if (
178 NodeFS.existsSync(generatedIconPath) &&
179 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
180 ) {
181 return generatedIconPath;
182 }
183​
184 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
185 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
186 NodeFS.mkdirSync(iconsetDir, { recursive: true });
187​
188 try {
189 for (const size of [16, 32, 128, 256, 512]) {
190 runChecked("sips", [
191 "-z",
192 String(size),
193 String(size),
194 developmentMacIconPngPath,
195 "--out",
196 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
197 ]);
198​
199 const retinaSize = size * 2;
200 runChecked("sips", [
201 "-z",
202 String(retinaSize),
203 String(retinaSize),
204 developmentMacIconPngPath,
205 "--out",
206 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
207 ]);
208 }
209​
210 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
211 return generatedIconPath;
212 } catch (error) {
213 console.warn(
214 "[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
215 error,
216 );
217 return defaultIconPath;
218 } finally {
219 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
220 }
222​
223function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
224 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
225 setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
226 setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
227 setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
228 setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
229 setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
230 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
231 {
232 CFBundleURLName: APP_BUNDLE_ID,
233 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
234 },
235 ]);
236​
237 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
238 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
239 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
241​
242function patchHelperBundleInfoPlists(appBundlePath) {
243 const helperBundleNames = [
244 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
245 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
246 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
247 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
248 ];
249​
250 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
251 const infoPlistPath = NodePath.join(
252 appBundlePath,
253 "Contents",
254 "Frameworks",
255 bundleName,
256 "Contents",
257 "Info.plist",
258 );
259 if (!NodeFS.existsSync(infoPlistPath)) {
260 continue;
261 }
262​
263 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
264 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
265 setPlistString(
266 infoPlistPath,
267 "CFBundleIdentifier",
268 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
269 );
270 }
272​
273function readJson(path) {
274 try {
275 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
276 } catch {
277 return null;
278 }
280​
281export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
282 const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
283 const launcherExecutableName = `${displayName} Launcher`;
284 return {
285 launcherExecutableName,
286 launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
287 runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
288 };
290​
291function buildMacLauncher(electronBinaryPath) {
292 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
293 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
294 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
295 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
296 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
297 const launcherBinaryPath = isDevelopment
298 ? developmentPaths.launcherBinaryPath
299 : runtimeElectronBinaryPath;
300 const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
301 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
302​
303 NodeFS.mkdirSync(runtimeDir, { recursive: true });
304​
305 const expectedMetadata = {
306 launcherVersion: LAUNCHER_VERSION,
307 sourceAppBundlePath,
308 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
309 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
310 appBundleId: APP_BUNDLE_ID,
311 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
312 };
313​
314 const currentMetadata = readJson(metadataPath);
315 if (
316 NodeFS.existsSync(launcherBinaryPath) &&
317 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
318 currentMetadata &&
319 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
320 ) {
321 if (isDevelopment) {
322 // The launcher also handles protocol activations outside the dev runner,
323 // so refresh its fallback environment on every launch. Never let a value
324 // captured by an older parent app override the live dev-runner environment.
325 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
326 }
327 registerMacLauncherBundle(targetAppBundlePath);
328 return launcherBinaryPath;
329 }
330​
331 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
332 // verbatimSymlinks keeps the framework's relative symlinks intact
333 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
334 // rewrites them to absolute paths into node_modules, which escape the
335 // bundle and crash sandboxed helper processes (icudtl.dat not found).
336 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
337 recursive: true,
338 verbatimSymlinks: true,
339 });
340 patchMainBundleInfoPlist(
341 targetAppBundlePath,
342 iconPath,
343 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
344 );
345 patchHelperBundleInfoPlists(targetAppBundlePath);
346 if (isDevelopment) {
347 // Keep Electron's native executable inside the branded bundle. Launching the
348 // node_modules copy makes macOS associate the process (and Dock label) with
349 // Electron.app even though this bundle's Info.plist has the T3 Code name.
350 // Its conventional executable name also keeps Electron's default-app runtime
351 // in development mode instead of making app.isPackaged report true.
352 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
353 }
354 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
355 registerMacLauncherBundle(targetAppBundlePath);
356​
357 return launcherBinaryPath;
359​
360function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
361 if (hostPlatform !== "linux") {
362 return true;
363 }
364​
365 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
366 try {
367 const sandboxStat = NodeFS.statSync(sandboxPath);
368 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
369 } catch {
370 return false;
371 }
373​
374function resolveLinuxSandboxArgs(electronBinaryPath) {
375 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
376 return [];
377 }
378​
379 console.warn(
380 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
381 );
382 return ["--no-sandbox"];
384​
385export function resolveElectronPath() {
386 const electronBinaryPath = resolveElectronBinaryPath();
387​
388 if (hostPlatform !== "darwin") {
389 return electronBinaryPath;
390 }
391​
392 return buildMacLauncher(electronBinaryPath);
394​
395export function resolveElectronLaunchCommand(args = []) {
396 const electronPath = resolveElectronPath();
397 return {
398 electronPath,
399 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
400 };
402​
403export function resolveElectronBinaryPath({
404 ensureRuntime = ensureElectronRuntime,
405 createRequire = NodeModule.createRequire,
406 moduleUrl = import.meta.url,
407} = {}) {
408 ensureRuntime();
409​
410 const require = createRequire(moduleUrl);
411 return require("electron");
413​
414export function resolveDevProtocolClient() {
415 if (hostPlatform !== "darwin" || !isDevelopment) {
416 return null;
417 }
418​
419 const electronBinaryPath = resolveElectronBinaryPath();
420 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
421 return {
422 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
423 appBundleId: APP_BUNDLE_ID,
424 };