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

electron-launcher.mjs

481 lines15.9 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, "");
18const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
19const 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 = 19;
24const developmentMacIconPngPath = NodePath.join(
25 repoRoot,
26 "assets",
27 "dev",
28 "blueprint-macos-1024.png",
29);
30const productionMacIconPngPath = NodePath.join(repoRoot, "assets", "prod", "black-macos-1024.png");
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​
99export function resolveMacCodeSignArguments(appBundlePath) {
100 return ["--force", "--deep", "--sign", "-", "--timestamp=none", appBundlePath];
102​
103function signMacLauncherBundle(appBundlePath) {
104 runChecked("codesign", resolveMacCodeSignArguments(appBundlePath));
106​
107function shellSingleQuote(value) {
108 return `'${value.replaceAll("'", "'\\''")}'`;
110​
111export function makeDevelopmentEnvironmentScript(environment) {
112 const envEntries = [
113 ["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
114 ["T3CODE_PORT", environment.T3CODE_PORT],
115 ["T3CODE_HOME", environment.T3CODE_HOME],
116 ["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
117 ["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
118 ["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
119 ["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
120 ].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
121 return [
122 ...envEntries.map(
123 ([name, value]) =>
124 `if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
125 ),
126 "",
127 ].join("\n");
129​
130export function makeDevelopmentLauncherScript({
131 electronBinaryPath,
132 mainEntryPath,
133 desktopRoot,
134 environmentFilePath,
135}) {
136 return [
137 "#!/bin/sh",
138 `if [ -f ${shellSingleQuote(environmentFilePath)} ]; then . ${shellSingleQuote(environmentFilePath)}; fi`,
139 `exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
140 "",
141 ].join("\n");
143​
144const developmentEnvironmentFilePath = NodePath.join(
145 desktopDir,
146 ".electron-runtime",
147 "dev-environment.sh",
148);
149​
150function writeDevelopmentEnvironmentScript() {
151 NodeFS.mkdirSync(NodePath.dirname(developmentEnvironmentFilePath), { recursive: true });
152 NodeFS.writeFileSync(
153 developmentEnvironmentFilePath,
154 makeDevelopmentEnvironmentScript(process.env),
155 );
157​
158export function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
159 const script = makeDevelopmentLauncherScript({
160 electronBinaryPath,
161 mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
162 desktopRoot: desktopDir,
163 environmentFilePath: developmentEnvironmentFilePath,
164 });
165 if (
166 NodeFS.existsSync(targetBinaryPath) &&
167 NodeFS.readFileSync(targetBinaryPath, "utf8") === script
168 ) {
169 NodeFS.chmodSync(targetBinaryPath, 0o755);
170 return false;
171 }
172 NodeFS.writeFileSync(targetBinaryPath, script);
173 NodeFS.chmodSync(targetBinaryPath, 0o755);
174 return true;
176​
177function registerMacLauncherBundle(appBundlePath) {
178 runChecked(
179 "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
180 ["-f", appBundlePath],
181 );
182​
183 if (!isDevelopment) {
184 return;
185 }
186​
187 for (const scheme of APP_PROTOCOL_SCHEMES) {
188 runChecked("osascript", [
189 "-l",
190 "JavaScript",
191 "-e",
192 [
193 'ObjC.import("CoreServices");',
194 `const scheme = $.NSString.alloc.initWithUTF8String(${JSON.stringify(scheme)});`,
195 `const bundle = $.NSString.alloc.initWithUTF8String(${JSON.stringify(APP_BUNDLE_ID)});`,
196 "const status = $.LSSetDefaultHandlerForURLScheme(scheme, bundle);",
197 "if (status !== 0) throw new Error(`LSSetDefaultHandlerForURLScheme failed: ${status}`);",
198 ].join(" "),
199 ]);
200 }
202​
203// Bundle-internal paths are macOS paths whatever host builds them.
204export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
205 return {
206 sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
207 generatedIconPath: NodePath.posix.join(
208 runtimeDir,
209 development ? "icon-dev.icns" : "icon-prod.icns",
210 ),
211 };
213​
214function ensureMacIconIcns(runtimeDir) {
215 const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
216 NodeFS.mkdirSync(runtimeDir, { recursive: true });
217​
218 if (!NodeFS.existsSync(sourceIconPath)) {
219 throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
220 }
221​
222 const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
223 if (
224 NodeFS.existsSync(generatedIconPath) &&
225 NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
226 ) {
227 return generatedIconPath;
228 }
229​
230 const iconsetRoot = NodeFS.mkdtempSync(NodePath.join(runtimeDir, "dev-iconset-"));
231 const iconsetDir = NodePath.join(iconsetRoot, "icon.iconset");
232 NodeFS.mkdirSync(iconsetDir, { recursive: true });
233​
234 try {
235 for (const size of [16, 32, 128, 256, 512]) {
236 runChecked("sips", [
237 "-z",
238 String(size),
239 String(size),
240 sourceIconPath,
241 "--out",
242 NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
243 ]);
244​
245 const retinaSize = size * 2;
246 runChecked("sips", [
247 "-z",
248 String(retinaSize),
249 String(retinaSize),
250 sourceIconPath,
251 "--out",
252 NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
253 ]);
254 }
255​
256 runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
257 return generatedIconPath;
258 } finally {
259 NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
260 }
262​
263export function resolveMacBundleInfoPlistStrings(executableName) {
264 return {
265 CFBundleDisplayName: APP_DISPLAY_NAME,
266 CFBundleName: APP_DISPLAY_NAME,
267 CFBundleIdentifier: APP_BUNDLE_ID,
268 CFBundleExecutable: executableName,
269 CFBundleIconFile: "icon.icns",
270 NSScreenCaptureUsageDescription:
271 "T3 Code captures the active window when you use the snapshot shortcut.",
272 NSDocumentsFolderUsageDescription: "T3 Code reads project files you open in the desktop app.",
273 };
275​
276function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
277 const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
278 for (const [key, value] of Object.entries(resolveMacBundleInfoPlistStrings(executableName))) {
279 setPlistString(infoPlistPath, key, value);
280 }
281 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
282 {
283 CFBundleURLName: APP_BUNDLE_ID,
284 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
285 },
286 ]);
287​
288 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
289 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
290 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
292​
293function patchHelperBundleInfoPlists(appBundlePath) {
294 const helperBundleNames = [
295 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
296 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
297 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
298 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
299 ];
300​
301 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
302 const infoPlistPath = NodePath.join(
303 appBundlePath,
304 "Contents",
305 "Frameworks",
306 bundleName,
307 "Contents",
308 "Info.plist",
309 );
310 if (!NodeFS.existsSync(infoPlistPath)) {
311 continue;
312 }
313​
314 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
315 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
316 setPlistString(
317 infoPlistPath,
318 "CFBundleIdentifier",
319 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
320 );
321 }
323​
324function readJson(path) {
325 try {
326 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
327 } catch {
328 return null;
329 }
331​
332export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
333 const executableDir = NodePath.posix.join(appBundlePath, "Contents", "MacOS");
334 const launcherExecutableName = `${displayName} Launcher`;
335 return {
336 launcherExecutableName,
337 launcherBinaryPath: NodePath.posix.join(executableDir, launcherExecutableName),
338 runtimeElectronBinaryPath: NodePath.posix.join(executableDir, "Electron"),
339 };
341​
342function buildMacLauncher(electronBinaryPath) {
343 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
344 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
345 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
346 const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
347 const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
348 const launcherBinaryPath = isDevelopment
349 ? developmentPaths.launcherBinaryPath
350 : runtimeElectronBinaryPath;
351 const iconPath = ensureMacIconIcns(runtimeDir);
352 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
353​
354 NodeFS.mkdirSync(runtimeDir, { recursive: true });
355​
356 const expectedMetadata = {
357 launcherVersion: LAUNCHER_VERSION,
358 sourceAppBundlePath,
359 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
360 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
361 appBundleId: APP_BUNDLE_ID,
362 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
363 };
364​
365 const currentMetadata = readJson(metadataPath);
366 if (
367 NodeFS.existsSync(launcherBinaryPath) &&
368 (!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
369 currentMetadata &&
370 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
371 ) {
372 if (isDevelopment) {
373 // The launcher also handles protocol activations outside the dev runner,
374 // so refresh its fallback environment on every launch. Never let a value
375 // captured by an older parent app override the live dev-runner environment.
376 writeDevelopmentEnvironmentScript();
377 if (writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath)) {
378 signMacLauncherBundle(targetAppBundlePath);
379 }
380 }
381 registerMacLauncherBundle(targetAppBundlePath);
382 return launcherBinaryPath;
383 }
384​
385 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
386 // verbatimSymlinks keeps the framework's relative symlinks intact
387 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
388 // rewrites them to absolute paths into node_modules, which escape the
389 // bundle and crash sandboxed helper processes (icudtl.dat not found).
390 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
391 recursive: true,
392 verbatimSymlinks: true,
393 });
394 patchMainBundleInfoPlist(
395 targetAppBundlePath,
396 iconPath,
397 isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
398 );
399 patchHelperBundleInfoPlists(targetAppBundlePath);
400 if (isDevelopment) {
401 // Keep Electron's native executable inside the branded bundle. Launching the
402 // node_modules copy makes macOS associate the process (and Dock label) with
403 // Electron.app even though this bundle's Info.plist has the T3 Code name.
404 // Its conventional executable name also keeps Electron's default-app runtime
405 // in development mode instead of making app.isPackaged report true.
406 writeDevelopmentEnvironmentScript();
407 writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
408 }
409 signMacLauncherBundle(targetAppBundlePath);
410 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
411 registerMacLauncherBundle(targetAppBundlePath);
412​
413 return launcherBinaryPath;
415​
416function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
417 if (hostPlatform !== "linux") {
418 return true;
419 }
420​
421 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
422 try {
423 const sandboxStat = NodeFS.statSync(sandboxPath);
424 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
425 } catch {
426 return false;
427 }
429​
430function resolveLinuxSandboxArgs(electronBinaryPath) {
431 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
432 return [];
433 }
434​
435 console.warn(
436 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
437 );
438 return ["--no-sandbox"];
440​
441function resolveElectronPath() {
442 const electronBinaryPath = resolveElectronBinaryPath();
443​
444 if (hostPlatform !== "darwin") {
445 return electronBinaryPath;
446 }
447​
448 return buildMacLauncher(electronBinaryPath);
450​
451export function resolveElectronLaunchCommand(args = []) {
452 const electronPath = resolveElectronPath();
453 return {
454 electronPath,
455 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
456 };
458​
459export function resolveElectronBinaryPath({
460 ensureRuntime = ensureElectronRuntime,
461 createRequire = NodeModule.createRequire,
462 moduleUrl = import.meta.url,
463} = {}) {
464 ensureRuntime();
465​
466 const require = createRequire(moduleUrl);
467 return require("electron");
469​
470export function resolveDevProtocolClient() {
471 if (hostPlatform !== "darwin" || !isDevelopment) {
472 return null;
473 }
474​
475 const electronBinaryPath = resolveElectronBinaryPath();
476 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
477 return {
478 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
479 appBundleId: APP_BUNDLE_ID,
480 };