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

build-desktop-artifact.ts

783 lines25.4 KB

1#!/usr/bin/env node
2​
3import { spawnSync } from "node:child_process";
4import { existsSync } from "node:fs";
5import { join } from "node:path";
6​
7import rootPackageJson from "../package.json" with { type: "json" };
8import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
9import serverPackageJson from "../apps/server/package.json" with { type: "json" };
10​
11import { BRAND_ASSET_PATHS } from "./lib/brand-assets.ts";
12import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
13​
14import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
15import * as NodeServices from "@effect/platform-node/NodeServices";
16import { Config, Data, Effect, FileSystem, Layer, Logger, Option, Path, Schema } from "effect";
17import { Command, Flag } from "effect/unstable/cli";
18import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
19​
20const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
21const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
22​
23const RepoRoot = Effect.service(Path.Path).pipe(
24 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
25);
26const ProductionMacIconSource = Effect.zipWith(
27 RepoRoot,
28 Effect.service(Path.Path),
29 (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionMacIconPng),
30);
31const ProductionLinuxIconSource = Effect.zipWith(
32 RepoRoot,
33 Effect.service(Path.Path),
34 (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionLinuxIconPng),
35);
36const ProductionWindowsIconSource = Effect.zipWith(
37 RepoRoot,
38 Effect.service(Path.Path),
39 (repoRoot, path) => path.join(repoRoot, BRAND_ASSET_PATHS.productionWindowsIconIco),
40);
41const encodeJsonString = Schema.encodeEffect(Schema.UnknownFromJsonString);
42​
43interface PlatformConfig {
44 readonly cliFlag: "--mac" | "--linux" | "--win";
45 readonly defaultTarget: string;
46 readonly archChoices: ReadonlyArray<typeof BuildArch.Type>;
48​
49const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = {
50 mac: {
51 cliFlag: "--mac",
52 defaultTarget: "dmg",
53 archChoices: ["arm64", "x64", "universal"],
54 },
55 linux: {
56 cliFlag: "--linux",
57 defaultTarget: "AppImage",
58 archChoices: ["x64", "arm64"],
59 },
60 win: {
61 cliFlag: "--win",
62 defaultTarget: "nsis",
63 archChoices: ["x64", "arm64"],
64 },
65};
66​
67interface BuildCliInput {
68 readonly platform: Option.Option<typeof BuildPlatform.Type>;
69 readonly target: Option.Option<string>;
70 readonly arch: Option.Option<typeof BuildArch.Type>;
71 readonly buildVersion: Option.Option<string>;
72 readonly outputDir: Option.Option<string>;
73 readonly skipBuild: Option.Option<boolean>;
74 readonly keepStage: Option.Option<boolean>;
75 readonly signed: Option.Option<boolean>;
76 readonly verbose: Option.Option<boolean>;
78​
79function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
80 if (hostPlatform === "darwin") return "mac";
81 if (hostPlatform === "linux") return "linux";
82 if (hostPlatform === "win32") return "win";
83 return undefined;
85​
86function getDefaultArch(platform: typeof BuildPlatform.Type): typeof BuildArch.Type {
87 const config = PLATFORM_CONFIG[platform];
88 if (!config) {
89 return "x64";
90 }
91​
92 if (process.arch === "arm64" && config.archChoices.includes("arm64")) {
93 return "arm64";
94 }
95 if (process.arch === "x64" && config.archChoices.includes("x64")) {
96 return "x64";
97 }
98​
99 return config.archChoices[0] ?? "x64";
101​
102class BuildScriptError extends Data.TaggedError("BuildScriptError")<{
103 readonly message: string;
104 readonly cause?: unknown;
105}> {}
106​
107function resolveGitCommitHash(repoRoot: string): string {
108 const result = spawnSync("git", ["rev-parse", "--short=12", "HEAD"], {
109 cwd: repoRoot,
110 encoding: "utf8",
111 });
112 if (result.status !== 0) {
113 return "unknown";
114 }
115 const hash = result.stdout.trim();
116 if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
117 return "unknown";
118 }
119 return hash.toLowerCase();
121​
122function resolvePythonForNodeGyp(): string | undefined {
123 const configured = process.env.npm_config_python ?? process.env.PYTHON;
124 if (configured && existsSync(configured)) {
125 return configured;
126 }
127​
128 if (process.platform === "win32") {
129 const localAppData = process.env.LOCALAPPDATA;
130 if (localAppData) {
131 for (const version of ["Python313", "Python312", "Python311", "Python310"]) {
132 const candidate = join(localAppData, "Programs", "Python", version, "python.exe");
133 if (existsSync(candidate)) {
134 return candidate;
135 }
136 }
137 }
138 }
139​
140 const probe = spawnSync("python", ["-c", "import sys;print(sys.executable)"], {
141 encoding: "utf8",
142 });
143 if (probe.status !== 0) {
144 return undefined;
145 }
146​
147 const executable = probe.stdout.trim();
148 if (!executable || !existsSync(executable)) {
149 return undefined;
150 }
151​
152 return executable;
154​
155interface ResolvedBuildOptions {
156 readonly platform: typeof BuildPlatform.Type;
157 readonly target: string;
158 readonly arch: typeof BuildArch.Type;
159 readonly version: string | undefined;
160 readonly outputDir: string;
161 readonly skipBuild: boolean;
162 readonly keepStage: boolean;
163 readonly signed: boolean;
164 readonly verbose: boolean;
166​
167interface StagePackageJson {
168 readonly name: string;
169 readonly version: string;
170 readonly buildVersion: string;
171 readonly t3codeCommitHash: string;
172 readonly private: true;
173 readonly description: string;
174 readonly author: string;
175 readonly main: string;
176 readonly build: Record<string, unknown>;
177 readonly dependencies: Record<string, unknown>;
178 readonly devDependencies: {
179 readonly electron: string;
180 };
182​
183const AzureTrustedSigningOptionsConfig = Config.all({
184 publisherName: Config.string("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
185 endpoint: Config.string("AZURE_TRUSTED_SIGNING_ENDPOINT"),
186 certificateProfileName: Config.string("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
187 codeSigningAccountName: Config.string("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
188 fileDigest: Config.string("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
189 timestampDigest: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
190 Config.withDefault("SHA256"),
191 ),
192 timestampRfc3161: Config.string("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
193 Config.withDefault("http://timestamp.acs.microsoft.com"),
194 ),
195});
196​
197const BuildEnvConfig = Config.all({
198 platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
199 target: Config.string("T3CODE_DESKTOP_TARGET").pipe(Config.option),
200 arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
201 version: Config.string("T3CODE_DESKTOP_VERSION").pipe(Config.option),
202 outputDir: Config.string("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
203 skipBuild: Config.boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
204 keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
205 signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
206 verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
207});
208​
209const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
210 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
211const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
212 Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
213​
214const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: BuildCliInput) {
215 const path = yield* Path.Path;
216 const repoRoot = yield* RepoRoot;
217 const env = yield* BuildEnvConfig.asEffect();
218​
219 const platform = mergeOptions(
220 input.platform,
221 env.platform,
222 detectHostBuildPlatform(process.platform),
223 );
224​
225 if (!platform) {
226 return yield* new BuildScriptError({
227 message: `Unsupported host platform '${process.platform}'.`,
228 });
229 }
230​
231 const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
232 const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform));
233 const version = mergeOptions(input.buildVersion, env.version, undefined);
234 const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release"));
235​
236 const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
237 const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
238 const signed = resolveBooleanFlag(input.signed, env.signed);
239 const verbose = resolveBooleanFlag(input.verbose, env.verbose);
240​
241 return {
242 platform,
243 target,
244 arch,
245 version,
246 outputDir,
247 skipBuild,
248 keepStage,
249 signed,
250 verbose,
251 } satisfies ResolvedBuildOptions;
252});
253​
254const commandOutputOptions = (verbose: boolean) =>
255 ({
256 stdout: verbose ? "inherit" : "ignore",
257 stderr: "inherit",
258 }) as const;
259​
260const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
261 const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
262 const child = yield* commandSpawner.spawn(command);
263 const exitCode = yield* child.exitCode;
264​
265 if (exitCode !== 0) {
266 return yield* new BuildScriptError({
267 message: `Command exited with non-zero exit code (${exitCode})`,
268 });
269 }
270});
271​
272function generateMacIconSet(
273 sourcePng: string,
274 targetIcns: string,
275 tmpRoot: string,
276 path: Path.Path,
277 verbose: boolean,
278) {
279 return Effect.gen(function* () {
280 const fs = yield* FileSystem.FileSystem;
281 const iconsetDir = path.join(tmpRoot, "icon.iconset");
282 yield* fs.makeDirectory(iconsetDir, { recursive: true });
283​
284 const iconSizes = [16, 32, 128, 256, 512] as const;
285 for (const size of iconSizes) {
286 yield* runCommand(
287 ChildProcess.make({
288 ...commandOutputOptions(verbose),
289 })`sips -z ${size} ${size} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}.png`)}`,
290 );
291​
292 const retinaSize = size * 2;
293 yield* runCommand(
294 ChildProcess.make({
295 ...commandOutputOptions(verbose),
296 })`sips -z ${retinaSize} ${retinaSize} ${sourcePng} --out ${path.join(iconsetDir, `icon_${size}x${size}@2x.png`)}`,
297 );
298 }
299​
300 yield* runCommand(
301 ChildProcess.make({
302 ...commandOutputOptions(verbose),
303 })`iconutil -c icns ${iconsetDir} -o ${targetIcns}`,
304 );
305 });
307​
308function stageMacIcons(stageResourcesDir: string, verbose: boolean) {
309 return Effect.gen(function* () {
310 const fs = yield* FileSystem.FileSystem;
311 const path = yield* Path.Path;
312 const iconSource = yield* ProductionMacIconSource;
313 if (!(yield* fs.exists(iconSource))) {
314 return yield* new BuildScriptError({
315 message: `Production icon source is missing at ${iconSource}`,
316 });
317 }
318​
319 const tmpRoot = yield* fs.makeTempDirectoryScoped({
320 prefix: "t3code-icon-build-",
321 });
322​
323 const iconPngPath = path.join(stageResourcesDir, "icon.png");
324 const iconIcnsPath = path.join(stageResourcesDir, "icon.icns");
325​
326 yield* runCommand(
327 ChildProcess.make({
328 ...commandOutputOptions(verbose),
329 })`sips -z 512 512 ${iconSource} --out ${iconPngPath}`,
330 );
331​
332 yield* generateMacIconSet(iconSource, iconIcnsPath, tmpRoot, path, verbose);
333 });
335​
336function stageLinuxIcons(stageResourcesDir: string) {
337 return Effect.gen(function* () {
338 const fs = yield* FileSystem.FileSystem;
339 const path = yield* Path.Path;
340 const iconSource = yield* ProductionLinuxIconSource;
341 if (!(yield* fs.exists(iconSource))) {
342 return yield* new BuildScriptError({
343 message: `Production icon source is missing at ${iconSource}`,
344 });
345 }
346​
347 const iconPath = path.join(stageResourcesDir, "icon.png");
348 yield* fs.copyFile(iconSource, iconPath);
349 });
351​
352function stageWindowsIcons(stageResourcesDir: string) {
353 return Effect.gen(function* () {
354 const fs = yield* FileSystem.FileSystem;
355 const path = yield* Path.Path;
356 const iconSource = yield* ProductionWindowsIconSource;
357 if (!(yield* fs.exists(iconSource))) {
358 return yield* new BuildScriptError({
359 message: `Production Windows icon source is missing at ${iconSource}`,
360 });
361 }
362​
363 const iconPath = path.join(stageResourcesDir, "icon.ico");
364 yield* fs.copyFile(iconSource, iconPath);
365 });
367​
368function validateBundledClientAssets(clientDir: string) {
369 return Effect.gen(function* () {
370 const fs = yield* FileSystem.FileSystem;
371 const path = yield* Path.Path;
372 const indexPath = path.join(clientDir, "index.html");
373 const indexHtml = yield* fs.readFileString(indexPath);
374 const refs = [...indexHtml.matchAll(/\b(?:src|href)=["']([^"']+)["']/g)]
375 .map((match) => match[1])
376 .filter((value): value is string => value !== undefined);
377 const missing: string[] = [];
378​
379 for (const ref of refs) {
380 const normalizedRef = ref.split("#")[0]?.split("?")[0] ?? "";
381 if (!normalizedRef) continue;
382 if (normalizedRef.startsWith("http://") || normalizedRef.startsWith("https://")) continue;
383 if (normalizedRef.startsWith("data:") || normalizedRef.startsWith("mailto:")) continue;
384​
385 const ext = path.extname(normalizedRef);
386 if (!ext) continue;
387​
388 const relativePath = normalizedRef.replace(/^\/+/, "");
389 const assetPath = path.join(clientDir, relativePath);
390 if (!(yield* fs.exists(assetPath))) {
391 missing.push(normalizedRef);
392 }
393 }
394​
395 if (missing.length > 0) {
396 const preview = missing.slice(0, 6).join(", ");
397 const suffix = missing.length > 6 ? ` (+${missing.length - 6} more)` : "";
398 return yield* new BuildScriptError({
399 message: `Bundled client references missing files in ${indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`,
400 });
401 }
402 });
404​
405function resolveDesktopRuntimeDependencies(
406 dependencies: Record<string, unknown> | undefined,
407 catalog: Record<string, unknown>,
408): Record<string, unknown> {
409 if (!dependencies || Object.keys(dependencies).length === 0) {
410 return {};
411 }
412​
413 const runtimeDependencies = Object.fromEntries(
414 Object.entries(dependencies).filter(([dependencyName]) => dependencyName !== "electron"),
415 );
416​
417 return resolveCatalogDependencies(runtimeDependencies, catalog, "apps/desktop");
419​
420function resolveGitHubPublishConfig():
421 | {
422 readonly provider: "github";
423 readonly owner: string;
424 readonly repo: string;
425 readonly releaseType: "release";
426 }
427 | undefined {
428 const rawRepo =
429 process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() ||
430 process.env.GITHUB_REPOSITORY?.trim() ||
431 "";
432 if (!rawRepo) return undefined;
433​
434 const [owner, repo, ...rest] = rawRepo.split("/");
435 if (!owner || !repo || rest.length > 0) return undefined;
436​
437 return {
438 provider: "github",
439 owner,
440 repo,
441 releaseType: "release",
442 };
444​
445const createBuildConfig = Effect.fn("createBuildConfig")(function* (
446 platform: typeof BuildPlatform.Type,
447 target: string,
448 productName: string,
449 signed: boolean,
450) {
451 const buildConfig: Record<string, unknown> = {
452 appId: "com.t3tools.t3code",
453 productName,
454 artifactName: "T3-Code-${version}-${arch}.${ext}",
455 directories: {
456 buildResources: "apps/desktop/resources",
457 },
458 };
459 const publishConfig = resolveGitHubPublishConfig();
460 if (publishConfig) {
461 buildConfig.publish = [publishConfig];
462 }
463​
464 if (platform === "mac") {
465 buildConfig.mac = {
466 target: target === "dmg" ? [target, "zip"] : [target],
467 icon: "icon.icns",
468 category: "public.app-category.developer-tools",
469 };
470 }
471​
472 if (platform === "linux") {
473 buildConfig.linux = {
474 target: [target],
475 icon: "icon.png",
476 category: "Development",
477 };
478 }
479​
480 if (platform === "win") {
481 const winConfig: Record<string, unknown> = {
482 target: [target],
483 icon: "icon.ico",
484 };
485 if (signed) {
486 winConfig.azureSignOptions = yield* AzureTrustedSigningOptionsConfig;
487 }
488 buildConfig.win = winConfig;
489 }
490​
491 return buildConfig;
492});
493​
494const assertPlatformBuildResources = Effect.fn("assertPlatformBuildResources")(function* (
495 platform: typeof BuildPlatform.Type,
496 stageResourcesDir: string,
497 verbose: boolean,
498) {
499 if (platform === "mac") {
500 yield* stageMacIcons(stageResourcesDir, verbose);
501 return;
502 }
503​
504 if (platform === "linux") {
505 yield* stageLinuxIcons(stageResourcesDir);
506 return;
507 }
508​
509 if (platform === "win") {
510 yield* stageWindowsIcons(stageResourcesDir);
511 }
512});
513​
514const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
515 options: ResolvedBuildOptions,
516) {
517 const repoRoot = yield* RepoRoot;
518 const path = yield* Path.Path;
519 const fs = yield* FileSystem.FileSystem;
520​
521 const platformConfig = PLATFORM_CONFIG[options.platform];
522 if (!platformConfig) {
523 return yield* new BuildScriptError({
524 message: `Unsupported platform '${options.platform}'.`,
525 });
526 }
527​
528 const electronVersion = desktopPackageJson.dependencies.electron;
529​
530 const serverDependencies = serverPackageJson.dependencies;
531 if (!serverDependencies || Object.keys(serverDependencies).length === 0) {
532 return yield* new BuildScriptError({
533 message: "Could not resolve production dependencies from apps/server/package.json.",
534 });
535 }
536​
537 const resolvedServerDependencies = yield* Effect.try({
538 try: () =>
539 resolveCatalogDependencies(
540 serverDependencies,
541 rootPackageJson.workspaces.catalog,
542 "apps/server",
543 ),
544 catch: (cause) =>
545 new BuildScriptError({
546 message: "Could not resolve production dependencies from apps/server/package.json.",
547 cause,
548 }),
549 });
550 const resolvedDesktopRuntimeDependencies = yield* Effect.try({
551 try: () =>
552 resolveDesktopRuntimeDependencies(
553 desktopPackageJson.dependencies,
554 rootPackageJson.workspaces.catalog,
555 ),
556 catch: (cause) =>
557 new BuildScriptError({
558 message: "Could not resolve desktop runtime dependencies from apps/desktop/package.json.",
559 cause,
560 }),
561 });
562​
563 const appVersion = options.version ?? serverPackageJson.version;
564 const commitHash = resolveGitCommitHash(repoRoot);
565 const mkdir = options.keepStage ? fs.makeTempDirectory : fs.makeTempDirectoryScoped;
566 const stageRoot = yield* mkdir({
567 prefix: `t3code-desktop-${options.platform}-stage-`,
568 });
569​
570 const stageAppDir = path.join(stageRoot, "app");
571 const stageResourcesDir = path.join(stageAppDir, "apps/desktop/resources");
572 const distDirs = {
573 desktopDist: path.join(repoRoot, "apps/desktop/dist-electron"),
574 desktopResources: path.join(repoRoot, "apps/desktop/resources"),
575 serverDist: path.join(repoRoot, "apps/server/dist"),
576 };
577 const bundledClientEntry = path.join(distDirs.serverDist, "client/index.html");
578​
579 if (!options.skipBuild) {
580 yield* Effect.log("[desktop-artifact] Building desktop/server/web artifacts...");
581 yield* runCommand(
582 ChildProcess.make({
583 cwd: repoRoot,
584 ...commandOutputOptions(options.verbose),
585 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
586 shell: process.platform === "win32",
587 })`bun run build:desktop`,
588 );
589 }
590​
591 for (const [label, dir] of Object.entries(distDirs)) {
592 if (!(yield* fs.exists(dir))) {
593 return yield* new BuildScriptError({
594 message: `Missing ${label} at ${dir}. Run 'bun run build:desktop' first.`,
595 });
596 }
597 }
598​
599 if (!(yield* fs.exists(bundledClientEntry))) {
600 return yield* new BuildScriptError({
601 message: `Missing bundled server client at ${bundledClientEntry}. Run 'bun run build:desktop' first.`,
602 });
603 }
604​
605 yield* validateBundledClientAssets(path.dirname(bundledClientEntry));
606​
607 yield* fs.makeDirectory(path.join(stageAppDir, "apps/desktop"), { recursive: true });
608 yield* fs.makeDirectory(path.join(stageAppDir, "apps/server"), { recursive: true });
609​
610 yield* Effect.log("[desktop-artifact] Staging release app...");
611 yield* fs.copy(distDirs.desktopDist, path.join(stageAppDir, "apps/desktop/dist-electron"));
612 yield* fs.copy(distDirs.desktopResources, stageResourcesDir);
613 yield* fs.copy(distDirs.serverDist, path.join(stageAppDir, "apps/server/dist"));
614​
615 yield* assertPlatformBuildResources(options.platform, stageResourcesDir, options.verbose);
616​
617 // electron-builder is filtering out stageResourcesDir directory in the AppImage for production
618 yield* fs.copy(stageResourcesDir, path.join(stageAppDir, "apps/desktop/prod-resources"));
619​
620 const stagePackageJson: StagePackageJson = {
621 name: "t3-code-desktop",
622 version: appVersion,
623 buildVersion: appVersion,
624 t3codeCommitHash: commitHash,
625 private: true,
626 description: "T3 Code desktop build",
627 author: "T3 Tools",
628 main: "apps/desktop/dist-electron/main.js",
629 build: yield* createBuildConfig(
630 options.platform,
631 options.target,
632 desktopPackageJson.productName ?? "T3 Code",
633 options.signed,
634 ),
635 dependencies: {
636 ...resolvedServerDependencies,
637 ...resolvedDesktopRuntimeDependencies,
638 },
639 devDependencies: {
640 electron: electronVersion,
641 },
642 };
643​
644 const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
645 yield* fs.writeFileString(path.join(stageAppDir, "package.json"), `${stagePackageJsonString}\n`);
646​
647 yield* Effect.log("[desktop-artifact] Installing staged production dependencies...");
648 yield* runCommand(
649 ChildProcess.make({
650 cwd: stageAppDir,
651 ...commandOutputOptions(options.verbose),
652 // Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
653 shell: process.platform === "win32",
654 })`bun install --production`,
655 );
656​
657 const buildEnv: NodeJS.ProcessEnv = {
658 ...process.env,
659 };
660 for (const [key, value] of Object.entries(buildEnv)) {
661 if (value === "") {
662 delete buildEnv[key];
663 }
664 }
665 if (!options.signed) {
666 buildEnv.CSC_IDENTITY_AUTO_DISCOVERY = "false";
667 delete buildEnv.CSC_LINK;
668 delete buildEnv.CSC_KEY_PASSWORD;
669 delete buildEnv.APPLE_API_KEY;
670 delete buildEnv.APPLE_API_KEY_ID;
671 delete buildEnv.APPLE_API_ISSUER;
672 }
673​
674 if (process.platform === "win32") {
675 const python = resolvePythonForNodeGyp();
676 if (python) {
677 buildEnv.PYTHON = python;
678 buildEnv.npm_config_python = python;
679 }
680 buildEnv.npm_config_msvs_version = buildEnv.npm_config_msvs_version ?? "2022";
681 buildEnv.GYP_MSVS_VERSION = buildEnv.GYP_MSVS_VERSION ?? "2022";
682 }
683​
684 yield* Effect.log(
685 `[desktop-artifact] Building ${options.platform}/${options.target} (arch=${options.arch}, version=${appVersion})...`,
686 );
687 yield* runCommand(
688 ChildProcess.make({
689 cwd: stageAppDir,
690 env: buildEnv,
691 ...commandOutputOptions(options.verbose),
692 // Windows needs shell mode to resolve .cmd shims.
693 shell: process.platform === "win32",
694 })`bunx electron-builder ${platformConfig.cliFlag} --${options.arch} --publish never`,
695 );
696​
697 const stageDistDir = path.join(stageAppDir, "dist");
698 if (!(yield* fs.exists(stageDistDir))) {
699 return yield* new BuildScriptError({
700 message: `Build completed but dist directory was not found at ${stageDistDir}`,
701 });
702 }
703​
704 const stageEntries = yield* fs.readDirectory(stageDistDir);
705 yield* fs.makeDirectory(options.outputDir, { recursive: true });
706​
707 const copiedArtifacts: string[] = [];
708 for (const entry of stageEntries) {
709 const from = path.join(stageDistDir, entry);
710 const stat = yield* fs.stat(from).pipe(Effect.catch(() => Effect.succeed(null)));
711 if (!stat || stat.type !== "File") continue;
712​
713 const to = path.join(options.outputDir, entry);
714 yield* fs.copyFile(from, to);
715 copiedArtifacts.push(to);
716 }
717​
718 if (copiedArtifacts.length === 0) {
719 return yield* new BuildScriptError({
720 message: `Build completed but no files were produced in ${stageDistDir}`,
721 });
722 }
723​
724 yield* Effect.log("[desktop-artifact] Done. Artifacts:").pipe(
725 Effect.annotateLogs({ artifacts: copiedArtifacts }),
726 );
727});
728​
729const buildDesktopArtifactCli = Command.make("build-desktop-artifact", {
730 platform: Flag.choice("platform", BuildPlatform.literals).pipe(
731 Flag.withDescription("Build platform (env: T3CODE_DESKTOP_PLATFORM)."),
732 Flag.optional,
733 ),
734 target: Flag.string("target").pipe(
735 Flag.withDescription(
736 "Artifact target, for example dmg/AppImage/nsis (env: T3CODE_DESKTOP_TARGET).",
737 ),
738 Flag.optional,
739 ),
740 arch: Flag.choice("arch", BuildArch.literals).pipe(
741 Flag.withDescription("Build arch, for example arm64/x64/universal (env: T3CODE_DESKTOP_ARCH)."),
742 Flag.optional,
743 ),
744 buildVersion: Flag.string("build-version").pipe(
745 Flag.withDescription("Artifact version metadata (env: T3CODE_DESKTOP_VERSION)."),
746 Flag.optional,
747 ),
748 outputDir: Flag.string("output-dir").pipe(
749 Flag.withDescription("Output directory for artifacts (env: T3CODE_DESKTOP_OUTPUT_DIR)."),
750 Flag.optional,
751 ),
752 skipBuild: Flag.boolean("skip-build").pipe(
753 Flag.withDescription(
754 "Skip `bun run build:desktop` and use existing dist artifacts (env: T3CODE_DESKTOP_SKIP_BUILD).",
755 ),
756 Flag.optional,
757 ),
758 keepStage: Flag.boolean("keep-stage").pipe(
759 Flag.withDescription("Keep temporary staging files (env: T3CODE_DESKTOP_KEEP_STAGE)."),
760 Flag.optional,
761 ),
762 signed: Flag.boolean("signed").pipe(
763 Flag.withDescription(
764 "Enable signing/notarization discovery; Windows uses Azure Trusted Signing (env: T3CODE_DESKTOP_SIGNED).",
765 ),
766 Flag.optional,
767 ),
768 verbose: Flag.boolean("verbose").pipe(
769 Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."),
770 Flag.optional,
771 ),
772}).pipe(
773 Command.withDescription("Build a desktop artifact for T3 Code."),
774 Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)),
775);
776​
777const cliRuntimeLayer = Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer);
778​
779Command.run(buildDesktopArtifactCli, { version: "0.0.0" }).pipe(
780 Effect.scoped,
781 Effect.provide(cliRuntimeLayer),
782 NodeRuntime.runMain,
783);