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