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

build-desktop-artifact.ts

957 lines30.6 KB

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