Open History to see the last commit
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 = 12;
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());
59}
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());
87}
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());
97}
98
99function shellSingleQuote(value) {
100 return `'${value.replaceAll("'", "'\\''")}'`;
101}
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");
127}
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);
140}
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 }
166}
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 }
221}
222
223function patchMainBundleInfoPlist(appBundlePath, iconPath) {
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, "CFBundleIconFile", "icon.icns");
229 setPlistJson(infoPlistPath, "CFBundleURLTypes", [
230 {
231 CFBundleURLName: APP_BUNDLE_ID,
232 CFBundleURLSchemes: APP_PROTOCOL_SCHEMES,
233 },
234 ]);
235
236 const resourcesDir = NodePath.join(appBundlePath, "Contents", "Resources");
237 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "icon.icns"));
238 NodeFS.copyFileSync(iconPath, NodePath.join(resourcesDir, "electron.icns"));
239}
240
241function patchHelperBundleInfoPlists(appBundlePath) {
242 const helperBundleNames = [
243 ["Electron Helper.app", "helper", `${APP_DISPLAY_NAME} Helper`],
244 ["Electron Helper (GPU).app", "helper.gpu", `${APP_DISPLAY_NAME} Helper (GPU)`],
245 ["Electron Helper (Plugin).app", "helper.plugin", `${APP_DISPLAY_NAME} Helper (Plugin)`],
246 ["Electron Helper (Renderer).app", "helper.renderer", `${APP_DISPLAY_NAME} Helper (Renderer)`],
247 ];
248
249 for (const [bundleName, bundleIdentifierSuffix, bundleDisplayName] of helperBundleNames) {
250 const infoPlistPath = NodePath.join(
251 appBundlePath,
252 "Contents",
253 "Frameworks",
254 bundleName,
255 "Contents",
256 "Info.plist",
257 );
258 if (!NodeFS.existsSync(infoPlistPath)) {
259 continue;
260 }
261
262 setPlistString(infoPlistPath, "CFBundleDisplayName", bundleDisplayName);
263 setPlistString(infoPlistPath, "CFBundleName", bundleDisplayName);
264 setPlistString(
265 infoPlistPath,
266 "CFBundleIdentifier",
267 `${APP_BUNDLE_ID}.${bundleIdentifierSuffix}`,
268 );
269 }
270}
271
272function readJson(path) {
273 try {
274 return JSON.parse(NodeFS.readFileSync(path, "utf8"));
275 } catch {
276 return null;
277 }
278}
279
280function buildMacLauncher(electronBinaryPath) {
281 const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
282 const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
283 const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
284 const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
285 const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
286 const metadataPath = NodePath.join(runtimeDir, "metadata.json");
287
288 NodeFS.mkdirSync(runtimeDir, { recursive: true });
289
290 const expectedMetadata = {
291 launcherVersion: LAUNCHER_VERSION,
292 sourceAppBundlePath,
293 sourceAppMtimeMs: NodeFS.statSync(sourceAppBundlePath).mtimeMs,
294 iconMtimeMs: NodeFS.statSync(iconPath).mtimeMs,
295 appBundleId: APP_BUNDLE_ID,
296 appProtocolSchemes: APP_PROTOCOL_SCHEMES,
297 };
298
299 const currentMetadata = readJson(metadataPath);
300 if (
301 NodeFS.existsSync(targetBinaryPath) &&
302 currentMetadata &&
303 JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
304 ) {
305 if (isDevelopment) {
306 // The launcher also handles protocol activations outside the dev runner,
307 // so refresh its fallback environment on every launch. Never let a value
308 // captured by an older parent app override the live dev-runner environment.
309 writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
310 }
311 registerMacLauncherBundle(targetAppBundlePath);
312 return targetBinaryPath;
313 }
314
315 NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
316 // verbatimSymlinks keeps the framework's relative symlinks intact
317 // (e.g. Resources -> Versions/Current/Resources). Without it cpSync
318 // rewrites them to absolute paths into node_modules, which escape the
319 // bundle and crash sandboxed helper processes (icudtl.dat not found).
320 NodeFS.cpSync(sourceAppBundlePath, targetAppBundlePath, {
321 recursive: true,
322 verbatimSymlinks: true,
323 });
324 patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
325 patchHelperBundleInfoPlists(targetAppBundlePath);
326 if (isDevelopment) {
327 writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
328 }
329 NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
330 registerMacLauncherBundle(targetAppBundlePath);
331
332 return targetBinaryPath;
333}
334
335function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
336 if (hostPlatform !== "linux") {
337 return true;
338 }
339
340 const sandboxPath = NodePath.join(NodePath.dirname(electronBinaryPath), "chrome-sandbox");
341 try {
342 const sandboxStat = NodeFS.statSync(sandboxPath);
343 return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
344 } catch {
345 return false;
346 }
347}
348
349function resolveLinuxSandboxArgs(electronBinaryPath) {
350 if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
351 return [];
352 }
353
354 console.warn(
355 "[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
356 );
357 return ["--no-sandbox"];
358}
359
360export function resolveElectronPath() {
361 const electronBinaryPath = resolveElectronBinaryPath();
362
363 if (hostPlatform !== "darwin") {
364 return electronBinaryPath;
365 }
366
367 return buildMacLauncher(electronBinaryPath);
368}
369
370export function resolveElectronLaunchCommand(args = []) {
371 const electronPath = resolveElectronPath();
372 return {
373 electronPath,
374 args: [...resolveLinuxSandboxArgs(electronPath), ...args],
375 };
376}
377
378export function resolveElectronBinaryPath({
379 ensureRuntime = ensureElectronRuntime,
380 createRequire = NodeModule.createRequire,
381 moduleUrl = import.meta.url,
382} = {}) {
383 ensureRuntime();
384
385 const require = createRequire(moduleUrl);
386 return require("electron");
387}
388
389export function resolveDevProtocolClient() {
390 if (hostPlatform !== "darwin" || !isDevelopment) {
391 return null;
392 }
393
394 const electronBinaryPath = resolveElectronBinaryPath();
395 const launcherBinaryPath = buildMacLauncher(electronBinaryPath);
396 return {
397 appBundlePath: NodePath.resolve(launcherBinaryPath, "..", "..", ".."),
398 appBundleId: APP_BUNDLE_ID,
399 };
400}