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

build-desktop-dmg.mjs

392 lines12.2 KB

1#!/usr/bin/env node
2​
3import { spawn } from "node:child_process";
4import fs from "node:fs/promises";
5import os from "node:os";
6import path from "node:path";
7import { fileURLToPath } from "node:url";
8​
9const __dirname = path.dirname(fileURLToPath(import.meta.url));
10const repoRoot = path.resolve(__dirname, "..");
11const PRODUCTION_ICON_SOURCE = path.join(repoRoot, "assets/macos-icon-1024.png");
12​
13const ARCH_CHOICES = new Set(["arm64", "x64", "universal"]);
14​
15function printUsage() {
16 console.log(`Build a shareable macOS .dmg for T3 Code desktop.
17​
18Usage:
19 node scripts/build-desktop-dmg.mjs [options]
20​
21Options:
22 --arch <arm64|x64|universal> Target arch (default: host arch if supported)
23 --version <semver> App version in DMG metadata (default: apps/server version)
24 --output-dir <path> Output folder for final artifacts (default: release)
25 --skip-build Skip 'bun run build:desktop' (requires existing dist artifacts)
26 --keep-stage Keep temporary staging directory
27 --signed Allow automatic code signing discovery
28 --help Show this message
29`);
31​
32function fail(message) {
33 console.error(`[desktop-dmg] ${message}`);
34 process.exit(1);
36​
37function parseArgs(argv) {
38 const defaultArch = process.arch === "arm64" || process.arch === "x64" ? process.arch : "arm64";
39 const options = {
40 arch: defaultArch,
41 version: null,
42 skipBuild: false,
43 keepStage: false,
44 signed: false,
45 outputDir: path.join(repoRoot, "release"),
46 };
47​
48 for (let i = 0; i < argv.length; i += 1) {
49 const arg = argv[i];
50 if (arg === "--help") {
51 options.help = true;
52 continue;
53 }
54 if (arg === "--skip-build") {
55 options.skipBuild = true;
56 continue;
57 }
58 if (arg === "--keep-stage") {
59 options.keepStage = true;
60 continue;
61 }
62 if (arg === "--signed") {
63 options.signed = true;
64 continue;
65 }
66 if (arg === "--arch" || arg === "--version" || arg === "--output-dir") {
67 const value = argv[i + 1];
68 if (!value || value.startsWith("--")) {
69 fail(`Missing value for ${arg}`);
70 }
71 i += 1;
72 if (arg === "--arch") options.arch = value;
73 if (arg === "--version") options.version = value;
74 if (arg === "--output-dir") options.outputDir = path.resolve(repoRoot, value);
75 continue;
76 }
77 fail(`Unknown argument: ${arg}`);
78 }
79​
80 if (!ARCH_CHOICES.has(options.arch)) {
81 fail(`Invalid arch '${options.arch}'. Expected one of: ${Array.from(ARCH_CHOICES).join(", ")}`);
82 }
83​
84 return options;
86​
87async function readJson(filePath) {
88 const raw = await fs.readFile(filePath, "utf8");
89 return JSON.parse(raw);
91​
92async function exists(filePath) {
93 try {
94 await fs.access(filePath);
95 return true;
96 } catch {
97 return false;
98 }
100​
101function run(command, args, { cwd, env = process.env, stdio = "inherit" } = {}) {
102 return new Promise((resolve, reject) => {
103 const child = spawn(command, args, {
104 cwd,
105 env,
106 stdio,
107 });
108​
109 child.on("error", reject);
110 child.on("exit", (code, signal) => {
111 if (signal) {
112 reject(new Error(`${command} exited via signal ${signal}`));
113 return;
114 }
115 if (code !== 0) {
116 reject(new Error(`${command} exited with code ${code}`));
117 return;
118 }
119 resolve();
120 });
121 });
123​
124async function generateMacIconSet(sourcePng, targetIcns, tmpRoot) {
125 const iconsetDir = path.join(tmpRoot, "icon.iconset");
126 await fs.mkdir(iconsetDir, { recursive: true });
127​
128 const iconSizes = [16, 32, 128, 256, 512];
129 for (const size of iconSizes) {
130 await run(
131 "sips",
132 [
133 "-z",
134 String(size),
135 String(size),
136 sourcePng,
137 "--out",
138 path.join(iconsetDir, `icon_${size}x${size}.png`),
139 ],
140 { stdio: "ignore" },
141 );
142 const retinaSize = size * 2;
143 await run(
144 "sips",
145 [
146 "-z",
147 String(retinaSize),
148 String(retinaSize),
149 sourcePng,
150 "--out",
151 path.join(iconsetDir, `icon_${size}x${size}@2x.png`),
152 ],
153 { stdio: "ignore" },
154 );
155 }
156​
157 await run("iconutil", ["-c", "icns", iconsetDir, "-o", targetIcns], { stdio: "ignore" });
159​
160async function stageProductionIcons(stageResourcesDir) {
161 if (!(await exists(PRODUCTION_ICON_SOURCE))) {
162 fail(`Production icon source is missing at ${PRODUCTION_ICON_SOURCE}`);
163 }
164​
165 const tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "t3code-icon-build-"));
166 try {
167 const iconPngPath = path.join(stageResourcesDir, "icon.png");
168 const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
169 await run("sips", ["-z", "512", "512", PRODUCTION_ICON_SOURCE, "--out", iconPngPath], {
170 stdio: "ignore",
171 });
172 await generateMacIconSet(PRODUCTION_ICON_SOURCE, iconIcnsPath, tmpRoot);
173 } finally {
174 await fs.rm(tmpRoot, { recursive: true, force: true });
175 }
177​
178async function validateBundledClientAssets(clientDir) {
179 const indexPath = path.join(clientDir, "index.html");
180 const indexHtml = await fs.readFile(indexPath, "utf8");
181 const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)].map((match) => match[1]);
182 const missing = [];
183​
184 for (const ref of refs) {
185 const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
186 if (!normalizedRef) continue;
187 if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
188 if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
189​
190 const ext = path.extname(normalizedRef);
191 if (!ext) continue;
192​
193 const relativePath = normalizedRef.replace(/^\/+/, "");
194 const assetPath = path.join(clientDir, relativePath);
195 if (!(await exists(assetPath))) {
196 missing.push(normalizedRef);
197 }
198 }
199​
200 if (missing.length > 0) {
201 const preview = missing.slice(0, 6).join(", ");
202 const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
203 fail(
204 `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
205 );
206 }
208​
209function readWorkspaceCatalog(rootPackageJson) {
210 const workspaces = rootPackageJson?.workspaces;
211 if (!workspaces || typeof workspaces !== "object" || Array.isArray(workspaces)) {
212 return {};
213 }
214​
215 const catalog = workspaces.catalog;
216 if (!catalog || typeof catalog !== "object" || Array.isArray(catalog)) {
217 return {};
218 }
219​
220 return catalog;
222​
223function resolveCatalogDependencies(dependencies, catalog, dependencySourceLabel) {
224 return Object.fromEntries(
225 Object.entries(dependencies).map(([dependencyName, spec]) => {
226 if (typeof spec !== "string" || !spec.startsWith("catalog:")) {
227 return [dependencyName, spec];
228 }
229​
230 const catalogKey = spec.slice("catalog:".length).trim();
231 const lookupKey = catalogKey.length > 0 ? catalogKey : dependencyName;
232 const resolvedSpec = catalog[lookupKey];
233 if (typeof resolvedSpec !== "string" || resolvedSpec.length === 0) {
234 fail(
235 `Unable to resolve '${spec}' for ${dependencySourceLabel} dependency '${dependencyName}'. ` +
236 `Expected key '${lookupKey}' in root workspace catalog.`,
237 );
238 }
239​
240 return [dependencyName, resolvedSpec];
241 }),
242 );
244​
245async function main() {
246 const options = parseArgs(process.argv.slice(2));
247 if (options.help) {
248 printUsage();
249 return;
250 }
251​
252 if (process.platform !== "darwin") {
253 fail("This script only builds macOS .dmg artifacts and must run on macOS.");
254 }
255​
256 const rootPkg = await readJson(path.join(repoRoot, "package.json"));
257 const desktopPkg = await readJson(path.join(repoRoot, "apps/desktop/package.json"));
258 const serverPkg = await readJson(path.join(repoRoot, "apps/server/package.json"));
259​
260 const electronVersion = desktopPkg.dependencies?.electron;
261 if (typeof electronVersion !== "string" || electronVersion.length === 0) {
262 fail("Could not resolve apps/desktop electron dependency version.");
263 }
264​
265 const dependencies = serverPkg.dependencies;
266 if (!dependencies || Object.keys(dependencies).length === 0) {
267 fail("Could not resolve production dependencies from apps/server/package.json.");
268 }
269 const resolvedDependencies = resolveCatalogDependencies(
270 dependencies,
271 readWorkspaceCatalog(rootPkg),
272 "apps/server",
273 );
274​
275 const appVersion = options.version ?? serverPkg.version ?? "0.1.0";
276 const stageRoot = path.join(os.tmpdir(), "t3code-desktop-dmg-stage");
277 const stageAppDir = path.join(stageRoot, "app");
278 const distDirs = {
279 desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
280 desktopResources: path.join(repoRoot, "apps/desktop/resources"),
281 serverDist: path.join(repoRoot, "apps/server/dist"),
282 };
283 const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
284​
285 if (!options.skipBuild) {
286 console.log("[desktop-dmg] Building desktop/server/web artifacts...");
287 await run("bun", ["run", "build:desktop"], { cwd: repoRoot });
288 }
289​
290 for (const [label, dir] of Object.entries(distDirs)) {
291 if (!(await exists(dir))) {
292 fail(`Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`);
293 }
294 }
295 if (!(await exists(bundledClientEntry))) {
296 fail(
297 `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
298 );
299 }
300 await validateBundledClientAssets(path.dirname(bundledClientEntry));
301​
302 await fs.rm(stageRoot, { recursive: true, force: true });
303 await fs.mkdir(path.join(stageAppDir, "apps/desktop"), { recursive: true });
304 await fs.mkdir(path.join(stageAppDir, "apps/server"), { recursive: true });
305​
306 console.log("[desktop-dmg] Staging release app...");
307 await fs.cp(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"), {
308 recursive: true,
309 });
310 await fs.cp(distDirs.desktopResources, path.join(stageAppDir, "apps/desktop/resources"), {
311 recursive: true,
312 });
313 await fs.cp(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"), { recursive: true });
314 await stageProductionIcons(path.join(stageAppDir, "apps/desktop/resources"));
315​
316 const stagePackageJson = {
317 name: "t3-code-desktop",
318 version: appVersion,
319 private: true,
320 description: "T3 Code desktop build",
321 author: "T3 Tools",
322 main: "apps/desktop/dist-electron/main.js",
323 build: {
324 appId: "com.t3tools.t3code",
325 productName: desktopPkg.productName ?? "T3 Code",
326 artifactName: "T3-Code-${version}-${arch}.${ext}",
327 directories: {
328 buildResources: "apps/desktop/resources",
329 },
330 mac: {
331 target: ["dmg"],
332 icon: "icon.icns",
333 category: "public.app-category.developer-tools",
334 },
335 },
336 dependencies: resolvedDependencies,
337 devDependencies: {
338 electron: electronVersion,
339 },
340 };
341​
342 await fs.writeFile(
343 path.join(stageAppDir, "package.json"),
344 `${JSON.stringify(stagePackageJson, null, 2)}\n`,
345 "utf8",
346 );
347​
348 console.log("[desktop-dmg] Installing staged production dependencies...");
349 await run("bun", ["install", "--production"], { cwd: stageAppDir });
350​
351 const buildEnv = {
352 ...process.env,
353 };
354 if (!options.signed) {
355 buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
356 }
357​
358 const buildArgs = ["--bun", "electron-builder", "--mac", "dmg", `--${options.arch}`];
359 console.log(`[desktop-dmg] Building .dmg (arch=${options.arch}, version=${appVersion})...`);
360 await run("bunx", buildArgs, { cwd: stageAppDir, env: buildEnv });
361​
362 const stageDistDir = path.join(stageAppDir, "dist");
363 const stageFiles = await fs.readdir(stageDistDir);
364 const dmgFiles = stageFiles.filter((file) => file.endsWith(".dmg"));
365 if (dmgFiles.length === 0) {
366 fail(`Build completed but no .dmg found in ${stageDistDir}`);
367 }
368​
369 await fs.mkdir(options.outputDir, { recursive: true });
370 const copiedArtifacts = [];
371 for (const file of stageFiles) {
372 if (!file.endsWith(".dmg") && !file.endsWith(".dmg.blockmap")) continue;
373 const from = path.join(stageDistDir, file);
374 const to = path.join(options.outputDir, file);
375 await fs.copyFile(from, to);
376 copiedArtifacts.push(to);
377 }
378​
379 if (!options.keepStage) {
380 await fs.rm(stageRoot, { recursive: true, force: true });
381 }
382​
383 console.log("[desktop-dmg] Done. Artifacts:");
384 for (const artifact of copiedArtifacts) {
385 console.log(` - ${artifact}`);
386 }
388​
389main().catch((error) => {
390 const message = error instanceof Error ? error.message : String(error);
391 fail(message);
392});