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