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