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

build-desktop-artifact.ts

829 lines26.9 KB

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