#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off - Node's typed junction API avoids Windows symlink privileges while keeping the probe isolated.
import * as NodeFSP from "node:fs/promises";
import * as NodeCrypto from "node:crypto";
import * as NodeModule from "node:module";
// plist is CommonJS; Node cannot load its named exports from an ES module.
import Plist from "plist";
import {
createPackageWithOptions,
extractAll,
getRawHeader,
statFile,
type DirectoryRecord,
} from "@electron/asar";
import { fromYaml } from "@t3tools/shared/schemaYaml";
import * as HostProcess from "@t3tools/shared/HostProcess";
import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/relayAuth";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import rootPackageJson from "../package.json" with { type: "json" };
import desktopPackageJson from "../apps/desktop/package.json" with { type: "json" };
import gnomeCaptureBundle from "../apps/desktop/gnome-extension/bundle.json" with { type: "json" };
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
import {
ReleasePackageManifestError,
releasePackageFiles,
updateReleasePackageVersions,
} from "./update-release-package-versions.ts";
import { applyWebBrandAssets } from "./apply-web-brand-assets.ts";
import {
BRAND_ASSET_PATHS,
resolveWebAssetBrandForChannel,
type WebAssetBrand,
} from "./lib/brand-assets.ts";
import { getDefaultBuildArch } from "./lib/build-target-arch.ts";
import {
findInlinedExternalPackages,
selectCliRuntimeExternalDependencies,
} from "./lib/cli-external-packages.ts";
import { loadRepoEnv } from "./lib/public-config.ts";
import { selectDesktopRuntimeExternalDependencies } from "./lib/desktop-external-packages.ts";
import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Config from "effect/Config";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import type { PlatformError } from "effect/PlatformError";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { Command, Flag } from "effect/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
const LINUX_ICON_SIZES = [16, 22, 24, 32, 48, 64, 128, 256, 512] as const;
const DESKTOP_APP_ID = "com.t3tools.t3code";
const APPLE_TEAM_ID_PATTERN = /^[A-Z0-9]{10}$/u;
const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
const BuildArch = Schema.Literals(["arm64", "x64", "universal"]);
const WorkspaceConfig = Schema.Struct({
catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
});
type WorkspaceConfig = typeof WorkspaceConfig.Type;
const StageWorkspaceConfig = Schema.Struct({
supportedArchitectures: Schema.Struct({
os: Schema.Array(Schema.String),
cpu: Schema.Array(Schema.String),
libc: Schema.optional(Schema.Array(Schema.String)),
}),
// pnpm 11 reads build approvals only from pnpm-workspace.yaml; omission fails staged lifecycle installs.
allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
packageExtensions: Schema.optional(
Schema.Record(
Schema.String,
Schema.Struct({
peerDependenciesMeta: Schema.Record(
Schema.String,
Schema.Struct({ optional: Schema.Boolean }),
),
}),
),
),
nodeLinker: Schema.optional(Schema.Literals(["hoisted"])),
});
type StageWorkspaceConfig = typeof StageWorkspaceConfig.Type;
// TypeScript is a typings-only peer; pnpm auto-installation would ship a compiler.
const STAGE_PACKAGE_EXTENSIONS = {
"electron-webauthn": { peerDependenciesMeta: { typescript: { optional: true } } },
"@electron-webauthn/macos": { peerDependenciesMeta: { typescript: { optional: true } } },
} as const;
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
);
const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
const decodeReleasePackageManifest = Schema.decodeEffect(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
);
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
export const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
return yield* decodeWorkspaceConfig(workspaceYaml);
});
interface DesktopBuildIconAssets {
readonly macIconPng: string;
readonly linuxIconPng: string;
readonly windowsIconIco: string;
}
interface PlatformConfig {
readonly cliFlag: "--mac" | "--linux" | "--win";
readonly defaultTarget: string;
readonly archChoices: ReadonlyArray<typeof BuildArch.Type>;
}
export function resolveResourceMonitorRustTargets(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): ReadonlyArray<string> {
if (platform === "mac") {
if (arch === "universal") {
return ["aarch64-apple-darwin", "x86_64-apple-darwin"];
}
return [arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin"];
}
if (platform === "linux") {
return [arch === "arm64" ? "aarch64-unknown-linux-gnu" : "x86_64-unknown-linux-gnu"];
}
return [arch === "arm64" ? "aarch64-pc-windows-msvc" : "x86_64-pc-windows-msvc"];
}
export function resourceMonitorExecutableName(platform: typeof BuildPlatform.Type): string {
return platform === "win" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
}
const PLATFORM_CONFIG: Record<typeof BuildPlatform.Type, PlatformConfig> = {
mac: {
cliFlag: "--mac",
defaultTarget: "dmg",
archChoices: ["arm64", "x64", "universal"],
},
linux: {
cliFlag: "--linux",
defaultTarget: "AppImage",
archChoices: ["x64", "arm64"],
},
win: {
cliFlag: "--win",
defaultTarget: "nsis",
archChoices: ["x64", "arm64"],
},
};
interface BuildCliInput {
readonly platform: Option.Option<typeof BuildPlatform.Type>;
readonly target: Option.Option<string>;
readonly arch: Option.Option<typeof BuildArch.Type>;
readonly buildVersion: Option.Option<string>;
readonly outputDir: Option.Option<string>;
readonly skipBuild: Option.Option<boolean>;
readonly keepStage: Option.Option<boolean>;
readonly signed: Option.Option<boolean>;
readonly verbose: Option.Option<boolean>;
readonly mockUpdates: Option.Option<boolean>;
readonly mockUpdateServerPort: Option.Option<number>;
readonly wslRuntime: Option.Option<string>;
}
function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined {
if (hostPlatform === "darwin") return "mac";
if (hostPlatform === "linux") return "linux";
if (hostPlatform === "win32") return "win";
return undefined;
}
const getDefaultArch = Effect.fn("getDefaultArch")(function* (platform: typeof BuildPlatform.Type) {
const config = PLATFORM_CONFIG[platform];
if (!config) {
return "x64";
}
return yield* getDefaultBuildArch(platform, config);
});
export class MacPasskeySigningConfigurationResolutionError extends Schema.TaggedError<MacPasskeySigningConfigurationResolutionError>()(
"MacPasskeySigningConfigurationResolutionError",
{
cause: Schema.Defect(),
},
) {
static fromCause(
cause: unknown,
): MacPasskeySigningConfigurationError | MacPasskeySigningConfigurationResolutionError {
return isMacPasskeySigningConfigurationError(cause)
? cause
: new MacPasskeySigningConfigurationResolutionError({ cause });
}
override get message(): string {
return "Failed to resolve macOS passkey signing configuration.";
}
}
export class KeyringNativePackageMissingError extends Schema.TaggedError<KeyringNativePackageMissingError>()(
"KeyringNativePackageMissingError",
{
packageName: Schema.String,
binaryFileName: Schema.String,
packageEntryPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Keyring native package is missing: ${this.packageName}`;
}
}
export class ClerkPasskeyNativePackageMissingError extends Schema.TaggedError<ClerkPasskeyNativePackageMissingError>()(
"ClerkPasskeyNativePackageMissingError",
{
packageName: Schema.String,
binaryFileName: Schema.String,
packageEntryPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Clerk passkey native package is missing: ${this.packageName}`;
}
}
export class UnsupportedHostBuildPlatformError extends Schema.TaggedError<UnsupportedHostBuildPlatformError>()(
"UnsupportedHostBuildPlatformError",
{
hostPlatform: Schema.String,
},
) {
override get message(): string {
return `Unsupported host platform '${this.hostPlatform}'.`;
}
}
export class UnsupportedDesktopBuildArchitectureError extends Schema.TaggedError<UnsupportedDesktopBuildArchitectureError>()(
"UnsupportedDesktopBuildArchitectureError",
{
platform: BuildPlatform,
arch: BuildArch,
supportedArchitectures: Schema.Array(BuildArch),
},
) {
override get message(): string {
return `Unsupported architecture '${this.arch}' for ${this.platform}.`;
}
}
const InvalidMockUpdateServerPortReason = Schema.Literals([
"not-numeric",
"not-integer",
"out-of-range",
]);
export class InvalidMockUpdateServerPortError extends Schema.TaggedError<InvalidMockUpdateServerPortError>()(
"InvalidMockUpdateServerPortError",
{
reason: InvalidMockUpdateServerPortReason,
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Invalid mock update server port.";
}
static fromConfigValue(configuredPort: string, cause: unknown) {
return new InvalidMockUpdateServerPortError({
reason: invalidMockUpdateServerPortReason(configuredPort),
inputLength: configuredPort.length,
cause,
});
}
}
export class DesktopBuildManifestRestoreError extends Schema.TaggedError<DesktopBuildManifestRestoreError>()(
"DesktopBuildManifestRestoreError",
{ failures: Schema.Array(ReleasePackageManifestError) },
) {
override get message(): string {
return `Failed to restore release manifests: ${this.failures.map((failure) => failure.filePath).join(", ")}`;
}
}
export class BuildCommandFailedError extends Schema.TaggedError<BuildCommandFailedError>()(
"BuildCommandFailedError",
{
command: Schema.String,
exitCode: Schema.Int,
stdoutTail: Schema.optionalKey(Schema.String),
stderrTail: Schema.optionalKey(Schema.String),
},
) {
override get message(): string {
const outputSections = [
`Command: ${this.command}`,
formatOutputSection("stdout", this.stdoutTail ?? ""),
formatOutputSection("stderr", this.stderrTail ?? ""),
].filter((section): section is string => section !== undefined);
const outputSuffix = outputSections.length > 0 ? `\n\n${outputSections.join("\n\n")}` : "";
return `Command exited with non-zero exit code (${this.exitCode})${outputSuffix}`;
}
}
export const LINUX_DESKTOP_BUILD_PREREQUISITES = [
{ id: "cargo", description: "Rust compiler and Cargo", packages: ["cargo", "rustc"] },
{ id: "rust-target", description: "Requested Rust standard library", packages: [] },
{ id: "cc", description: "C/C++ build toolchain", packages: ["build-essential"] },
{ id: "make", description: "Make", packages: ["build-essential"] },
{
id: "libsecret",
description: "libsecret development headers and pkg-config",
packages: ["libsecret-1-dev", "pkg-config"],
},
{ id: "imagemagick", description: "ImageMagick", packages: ["imagemagick"] },
] as const;
export class LinuxDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<LinuxDesktopBuildPrerequisitesMissingError>()(
"LinuxDesktopBuildPrerequisitesMissingError",
{
missing: Schema.Array(Schema.String),
rustTarget: Schema.String,
},
) {
override get message(): string {
const missingRequirements = LINUX_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
this.missing.includes(requirement.id),
);
const details = missingRequirements
.map((requirement) =>
requirement.packages.length > 0
? ` - ${requirement.description} (${requirement.packages.join(", ")})`
: ` - ${requirement.description}`,
)
.join("\n");
const packages = [
...new Set(missingRequirements.flatMap((requirement) => requirement.packages)),
];
return [
"Linux desktop build prerequisites are missing:",
details,
"",
...(packages.length > 0
? ["On Ubuntu/Debian, install them with:", ` sudo apt-get install ${packages.join(" ")}`]
: []),
...(this.missing.includes("rust-target")
? ["Add the requested Rust target with:", ` rustup target add ${this.rustTarget}`]
: []),
"",
"For other distributions, see docs/operations/development.md#linux-appimage-prerequisites.",
"Then rerun `vp run dist:desktop:linux`.",
].join("\n");
}
}
const MAC_DESKTOP_BUILD_PREREQUISITES = [
{ id: "rust", description: "Rust/Cargo and the requested Rust target" },
{ id: "clang", description: "Xcode Command Line Tools (clang)" },
{ id: "make", description: "Xcode Command Line Tools (make)" },
{ id: "sips", description: "macOS image tool (sips)" },
{ id: "iconutil", description: "macOS icon tool (iconutil)" },
{ id: "lipo", description: "Xcode universal-binary tool (lipo)" },
] as const;
export class MacDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<MacDesktopBuildPrerequisitesMissingError>()(
"MacDesktopBuildPrerequisitesMissingError",
{
missing: Schema.Array(Schema.String),
rustTargets: Schema.Array(Schema.String),
},
) {
override get message(): string {
const details = MAC_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
this.missing.includes(requirement.id),
)
.map((requirement) => ` - ${requirement.description}`)
.join("\n");
return [
"macOS desktop build prerequisites are missing:",
details,
"",
"Install Apple's build tools with:",
" xcode-select --install",
"Install Rust from https://rustup.rs, then add the requested target(s):",
` rustup target add ${this.rustTargets.join(" ")}`,
"",
"Then rerun the desktop artifact command.",
].join("\n");
}
}
const WINDOWS_DESKTOP_BUILD_PREREQUISITES = [
{ id: "rust", description: "Rust/Cargo and the requested MSVC Rust target" },
{ id: "python", description: "Python 3 for node-gyp" },
{
id: "msvc",
description: "Visual Studio Build Tools with C++, Windows SDK, and Spectre libraries",
},
{ id: "tar", description: "tar to inspect the bundled WSL runtime archive" },
] as const;
export class WindowsDesktopBuildPrerequisitesMissingError extends Schema.TaggedError<WindowsDesktopBuildPrerequisitesMissingError>()(
"WindowsDesktopBuildPrerequisitesMissingError",
{
missing: Schema.Array(Schema.String),
rustTarget: Schema.String,
},
) {
override get message(): string {
const details = WINDOWS_DESKTOP_BUILD_PREREQUISITES.filter((requirement) =>
this.missing.includes(requirement.id),
)
.map((requirement) => ` - ${requirement.description}`)
.join("\n");
return [
"Windows desktop build prerequisites are missing:",
details,
"",
"Install Rust from https://rustup.rs and add the requested target:",
` rustup target add ${this.rustTarget}`,
"Install Python 3 and the Visual Studio Build Tools components listed in",
"docs/operations/development.md#windows-installer-prerequisites.",
"",
"Then rerun the desktop artifact command.",
].join("\n");
}
}
export class ResourceMonitorBuildOutputMissingError extends Schema.TaggedError<ResourceMonitorBuildOutputMissingError>()(
"ResourceMonitorBuildOutputMissingError",
{
binaryPath: Schema.String,
rustTarget: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Resource monitor build for ${this.rustTarget} did not produce ${this.binaryPath}.`;
}
}
const desktopIconPlatformNames = {
mac: "macOS",
linux: "Linux",
win: "Windows",
} satisfies Record<typeof BuildPlatform.Type, string>;
export class LinuxBrowserSecretHostError extends Schema.TaggedError<LinuxBrowserSecretHostError>()(
"LinuxBrowserSecretHostError",
{ hostPlatform: Schema.String },
) {
override get message(): string {
return `Linux desktop builds must run on a Linux host: the browser secret helper links against libsecret and cannot be built on '${this.hostPlatform}'.`;
}
}
export class DesktopIconSourceMissingError extends Schema.TaggedError<DesktopIconSourceMissingError>()(
"DesktopIconSourceMissingError",
{
platform: BuildPlatform,
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Desktop ${desktopIconPlatformNames[this.platform]} icon source is missing at ${this.sourcePath}`;
}
}
export class DesktopDmgBackgroundSourceMissingError extends Schema.TaggedError<DesktopDmgBackgroundSourceMissingError>()(
"DesktopDmgBackgroundSourceMissingError",
{
channel: Schema.Literals(["latest", "nightly"]),
sourcePath: Schema.String,
},
) {
override get message(): string {
return `Desktop ${this.channel} DMG background source is missing at ${this.sourcePath}`;
}
}
export class BundledClientAssetsMissingError extends Schema.TaggedError<BundledClientAssetsMissingError>()(
"BundledClientAssetsMissingError",
{
indexPath: Schema.String,
missingFiles: Schema.Array(Schema.String),
},
) {
override get message(): string {
const preview = this.missingFiles.slice(0, 6).join(", ");
const suffix = this.missingFiles.length > 6 ? ` (+${this.missingFiles.length - 6} more)` : "";
return `Bundled client references missing files in ${this.indexPath}: ${preview}${suffix}. Rebuild web/server artifacts.`;
}
}
export class UnsupportedDesktopBuildPlatformError extends Schema.TaggedError<UnsupportedDesktopBuildPlatformError>()(
"UnsupportedDesktopBuildPlatformError",
{
platform: Schema.String,
},
) {
override get message(): string {
return `Unsupported platform '${this.platform}'.`;
}
}
const dependencyResolutionDescriptions = {
"server-production": "production dependencies",
"workspace-overrides": "overrides",
"desktop-runtime": "desktop runtime dependencies",
} as const;
const DependencyResolutionKind = Schema.Literals([
"server-production",
"workspace-overrides",
"desktop-runtime",
]);
export class DesktopBuildDependencyResolutionError extends Schema.TaggedError<DesktopBuildDependencyResolutionError>()(
"DesktopBuildDependencyResolutionError",
{
kind: DependencyResolutionKind,
manifestPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Could not resolve ${dependencyResolutionDescriptions[this.kind]} from ${this.manifestPath}.`;
}
}
export class MissingServerProductionDependenciesError extends Schema.TaggedError<MissingServerProductionDependenciesError>()(
"MissingServerProductionDependenciesError",
{
manifestPath: Schema.String,
},
) {
override get message(): string {
return `Could not resolve production dependencies from ${this.manifestPath}.`;
}
}
const DesktopBuildInputArtifact = Schema.Literals([
"desktop-dist",
"desktop-resources",
"server-dist",
"bundled-server-client",
]);
type DesktopBuildInputArtifact = typeof DesktopBuildInputArtifact.Type;
const desktopBuildInputArtifactNames = {
"desktop-dist": "desktopDist",
"desktop-resources": "desktopResources",
"server-dist": "serverDist",
"bundled-server-client": "bundled server client",
} satisfies Record<DesktopBuildInputArtifact, string>;
/** Effect is always inlined; absence signals externalized dependencies beyond the sidecar runtime closure. */
const BUNDLE_SELF_CONTAINED_SENTINEL = "effect";
const BUNDLE_SELF_CHECK_TIMEOUT = Duration.seconds(120);
const WINDOWS_PRIMARY_NATIVE_PROBE_TIMEOUT = Duration.seconds(30);
const WINDOWS_PRIMARY_FFF_PROBE_SOURCE = `
const { join } = await import("node:path");
const { pathToFileURL } = await import("node:url");
const { FileFinder } = await import(pathToFileURL(process.argv[1]).href);
const probeRoot = process.argv[2];
const result = FileFinder.create({
basePath: probeRoot,
frecencyDbPath: join(probeRoot, "frecency.mdb"),
historyDbPath: join(probeRoot, "history.mdb"),
disableWatch: true,
disableMmapCache: true,
disableContentIndexing: true,
});
if (!result.ok) throw new Error(result.error);
result.value.destroy();
`;
export class ExternalizedBundleError extends Schema.TaggedError<ExternalizedBundleError>()(
"ExternalizedBundleError",
{ sentinel: Schema.String, inlinedPackageCount: Schema.Number },
) {
override get message(): string {
return `The server bundle did not inline "${this.sentinel}" (${this.inlinedPackageCount} packages inlined). The bundle is meant to be self-contained apart from the runtime externals; if its dependencies are external again they will be absent from the sidecar, and the backend will fail with ERR_MODULE_NOT_FOUND. Check the deps.alwaysBundle wiring in apps/server/vite.config.ts.`;
}
}
export class BundleNotSelfContainedError extends Schema.TaggedError<BundleNotSelfContainedError>()(
"BundleNotSelfContainedError",
{ exitCode: Schema.Number, output: Schema.String },
) {
override get message(): string {
return `The packaged server bundle could not load from the isolated, extracted sidecar (exit ${this.exitCode}). Anything it imports that is neither a Node built-in nor in the selected runtime-external closure is unavailable to both backends. Output:
${this.output}`;
}
}
export class InlinedNativePackageError extends Schema.TaggedError<InlinedNativePackageError>()(
"InlinedNativePackageError",
{ packages: Schema.Array(Schema.String) },
) {
override get message(): string {
return `The server bundle inlined packages that load native binaries: ${this.packages.join(", ")}. A node-gyp-build style loader resolves prebuilds relative to its own file, so inlined into a chunk it finds none and the importer quietly falls back to a slower JS path. Add them to CLI_RUNTIME_EXTERNAL_PREFIXES in scripts/lib/cli-external-packages.ts so they stay external and are staged in the sidecar.`;
}
}
export class InlinedExternalPackageError extends Schema.TaggedError<InlinedExternalPackageError>()(
"InlinedExternalPackageError",
{ packages: Schema.Array(Schema.String) },
) {
override get message(): string {
return `The server bundle inlined packages that must stay external: ${this.packages.join(", ")}. These are native addons or their loaders; inlined, they resolve prebuilds relative to the bundle and silently lose native acceleration. Check the deps.neverBundle wiring in apps/server/vite.config.ts.`;
}
}
export class MissingDesktopBuildInputError extends Schema.TaggedError<MissingDesktopBuildInputError>()(
"MissingDesktopBuildInputError",
{
artifact: DesktopBuildInputArtifact,
artifactPath: Schema.String,
buildCommand: Schema.Literal("vp run build:desktop"),
},
) {
override get message(): string {
return `Missing ${desktopBuildInputArtifactNames[this.artifact]} at ${this.artifactPath}. Run '${this.buildCommand}' first.`;
}
}
export class MacProvisioningProfileNotFoundError extends Schema.TaggedError<MacProvisioningProfileNotFoundError>()(
"MacProvisioningProfileNotFoundError",
{
provisioningProfilePath: Schema.String,
},
) {
override get message(): string {
return `macOS provisioning profile not found: ${this.provisioningProfilePath}`;
}
}
export class DesktopBuildDistDirectoryMissingError extends Schema.TaggedError<DesktopBuildDistDirectoryMissingError>()(
"DesktopBuildDistDirectoryMissingError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but dist directory was not found at ${this.distPath}`;
}
}
export class DesktopBuildArtifactCopyError extends Schema.TaggedError<DesktopBuildArtifactCopyError>()(
"DesktopBuildArtifactCopyError",
{ from: Schema.String, to: Schema.String, cause: Schema.Defect() },
) {
override get message(): string {
return `Failed to copy build artifact ${this.from} to ${this.to}.`;
}
}
export class DesktopBuildNoArtifactsProducedError extends Schema.TaggedError<DesktopBuildNoArtifactsProducedError>()(
"DesktopBuildNoArtifactsProducedError",
{
distPath: Schema.String,
platform: BuildPlatform,
arch: BuildArch,
},
) {
override get message(): string {
return `Build completed but no files were produced in ${this.distPath}`;
}
}
export class WslRuntimeArchiveMissingError extends Schema.TaggedError<WslRuntimeArchiveMissingError>()(
"WslRuntimeArchiveMissingError",
{
archivePath: Schema.String,
},
) {
override get message(): string {
return `WSL runtime archive not found at ${this.archivePath}.`;
}
}
export class WindowsServerSidecarPackError extends Schema.TaggedError<WindowsServerSidecarPackError>()(
"WindowsServerSidecarPackError",
{
asarPath: Schema.String,
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
return `Failed to pack the Windows server sidecar at ${this.asarPath}.`;
}
}
export class WindowsPrimaryNativeProbeError extends Schema.TaggedError<WindowsPrimaryNativeProbeError>()(
"WindowsPrimaryNativeProbeError",
{
executablePath: Schema.String,
exitCode: Schema.Number,
output: Schema.String,
},
) {
override get message(): string {
return `The packaged Windows primary could not load fff from server.asar (exit ${this.exitCode}). Output:\n${this.output}`;
}
}
const WindowsPackagedPayloadValidationReason = Schema.Literals([
"packaged-app-missing",
"sidecar-missing",
"sidecar-invalid",
"unpacked-native-missing",
"resource-monitor-missing",
"wsl-runtime-missing",
"wsl-runtime-invalid",
"file-limit-exceeded",
]);
export class WindowsPackagedPayloadValidationError extends Schema.TaggedError<WindowsPackagedPayloadValidationError>()(
"WindowsPackagedPayloadValidationError",
{
reason: WindowsPackagedPayloadValidationReason,
packagedAppDir: Schema.String,
missingFiles: Schema.optionalKey(Schema.Array(Schema.String)),
fileCount: Schema.optionalKey(Schema.Int),
fileLimit: Schema.optionalKey(Schema.Int),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
if (this.reason === "file-limit-exceeded") {
return `Windows packaged payload contains ${String(this.fileCount)} files; expected at most ${String(this.fileLimit)}.`;
}
if (this.reason === "unpacked-native-missing") {
return `Windows server sidecar is missing ${String(this.missingFiles?.length ?? 0)} unpacked native files.`;
}
if (this.reason === "resource-monitor-missing") {
return "Windows packaged payload is missing the resource monitor executable.";
}
if (this.reason === "wsl-runtime-missing") {
return "Windows packaged payload is missing the WSL runtime archive or SHA-256 sidecar.";
}
if (this.reason === "wsl-runtime-invalid") {
return "Windows packaged payload contains an invalid WSL runtime archive.";
}
if (this.reason === "sidecar-invalid") {
return "Windows packaged payload contains an invalid server.asar sidecar.";
}
if (this.reason === "sidecar-missing") {
return "Windows packaged payload is missing resources/server.asar.";
}
return `Windows packaged application directory was not found at ${this.packagedAppDir}.`;
}
}
export class LinuxIconResizeError extends Schema.TaggedError<LinuxIconResizeError>()(
"LinuxIconResizeError",
{
operation: Schema.Literal("resize"),
iconSize: Schema.Int,
primaryTool: Schema.Literal("magick"),
fallbackTool: Schema.Literal("convert"),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} the Linux desktop icon to ${this.iconSize}x${this.iconSize} with \`${this.primaryTool}\` or \`${this.fallbackTool}\`. Install ImageMagick so either tool is available.`;
}
}
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const COMMAND_OUTPUT_TAIL_LENGTH = 20_000;
function appendOutputTail(acc: string, chunk: string): string {
const next = acc + chunk;
return next.length > COMMAND_OUTPUT_TAIL_LENGTH ? next.slice(-COMMAND_OUTPUT_TAIL_LENGTH) : next;
}
function formatOutputSection(label: string, output: string): string | undefined {
const trimmed = output.trim();
if (!trimmed) return undefined;
return `${label} tail:\n${trimmed}`;
}
const collectCommandStream = <E>(
stream: Stream.Stream<Uint8Array, E>,
output: NodeJS.WriteStream,
verbose: boolean,
): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFoldEffect(
() => "",
(acc, chunk) =>
Effect.as(
verbose ? Effect.sync(() => output.write(chunk)) : Effect.void,
appendOutputTail(acc, chunk),
),
),
);
const spawnAndCollectOutput = Effect.fn("spawnAndCollectOutput")(function* (
command: ChildProcess.Command,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, exitCode } as const;
});
const resolveGitCommitHash = Effect.fn("resolveGitCommitHash")(function* (repoRoot: string) {
const result = yield* spawnAndCollectOutput(
ChildProcess.make("git", ["rev-parse", "--short=12", "HEAD"], {
cwd: repoRoot,
}),
).pipe(
Effect.orElseSucceed(() => ({
stdout: "",
stderr: "",
exitCode: 1,
})),
);
if (result.exitCode !== 0) {
return "unknown";
}
const hash = result.stdout.trim();
if (!/^[0-9a-f]{7,40}$/i.test(hash)) {
return "unknown";
}
return hash.toLowerCase();
});
const resolvePythonForNodeGyp = Effect.fn("resolvePythonForNodeGyp")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const hostPlatform = yield* HostProcess.Platform;
const env = yield* Config.all({
configuredPython: Config.String("npm_config_python").pipe(
Config.orElse(() => Config.String("PYTHON")),
Config.option,
),
localAppData: Config.String("LOCALAPPDATA").pipe(Config.option),
});
const isPython3 = (candidate: string) =>
spawnAndCollectOutput(
ChildProcess.make(candidate, [
"-c",
"import sys; raise SystemExit(0 if sys.version_info.major == 3 else 1)",
]),
).pipe(
Effect.map((result) => result.exitCode === 0),
Effect.orElseSucceed(() => false),
);
const configured = Option.getOrUndefined(env.configuredPython);
if (configured && (yield* fs.exists(configured)) && (yield* isPython3(configured))) {
return configured;
}
if (hostPlatform === "win32") {
const localAppData = Option.getOrUndefined(env.localAppData);
if (localAppData) {
for (const version of ["Python313", "Python312", "Python311", "Python310"]) {
const candidate = path.join(localAppData, "Programs", "Python", version, "python.exe");
if ((yield* fs.exists(candidate)) && (yield* isPython3(candidate))) {
return candidate;
}
}
}
}
const probe = yield* spawnAndCollectOutput(
ChildProcess.make("python", ["-c", "import sys;print(sys.executable)"]),
).pipe(
Effect.orElseSucceed(() => ({
stdout: "",
stderr: "",
exitCode: 1,
})),
);
if (probe.exitCode !== 0) {
return undefined;
}
const executable = probe.stdout.trim();
if (!executable || !(yield* fs.exists(executable)) || !(yield* isPython3(executable))) {
return undefined;
}
return executable;
});
interface ResolvedBuildOptions {
readonly platform: typeof BuildPlatform.Type;
readonly target: string;
readonly arch: typeof BuildArch.Type;
readonly version: string | undefined;
readonly outputDir: string;
readonly skipBuild: boolean;
readonly keepStage: boolean;
readonly signed: boolean;
readonly verbose: boolean;
readonly mockUpdates: boolean;
readonly mockUpdateServerPort: number | undefined;
readonly wslRuntime: string | undefined;
}
interface StagePackageJson {
readonly name: string;
readonly version: string;
readonly buildVersion: string;
readonly t3codeCommitHash: string;
readonly t3codeWebAuthn?: MacWebAuthnEntitlements;
readonly private: true;
readonly packageManager: string;
readonly description: string;
readonly license: string;
readonly homepage: string;
readonly author: string;
readonly main: string;
readonly build: Record<string, unknown>;
readonly dependencies: Record<string, unknown>;
readonly devDependencies: {
readonly electron: string;
};
}
export const STAGE_INSTALL_ARGS = ["install", "--prod"] as const;
export const DESKTOP_ELECTRON_LANGUAGES = ["en-US"] as const;
export const DESKTOP_FILE_EXCLUSIONS = [
// Cursor walks from argv[1] to platform assets; helpers and native addons need real paths outside ASAR.
"!**/node_modules/@cursor/sdk-*/**/*",
"!apps/desktop/prod-resources/cursor-sdk",
"!apps/desktop/prod-resources/cursor-sdk/**/*",
// The installed Claude CLI is supplied explicitly; exclude optional bundled executables, retaining SDK JavaScript.
"!**/node_modules/@anthropic-ai/claude-agent-sdk-*/**/*",
"!**/*.map",
"!**/*.d.cts",
"!apps/desktop/resources/browser-secret",
"!apps/desktop/resources/browser-secret/**/*",
"!apps/desktop/prod-resources/browser-secret",
"!apps/desktop/prod-resources/browser-secret/**/*",
"!apps/desktop/prod-resources/windows-server",
"!apps/desktop/prod-resources/windows-server/**/*",
"!apps/desktop/prod-resources/wsl-runtime.tar.gz",
"!apps/desktop/prod-resources/wsl-runtime.tar.gz.sha256",
"!apps/desktop/gnome-extension",
"!apps/desktop/gnome-extension/**/*",
] as const;
// Windows terminal helpers cannot run on macOS and slow signing and notarization.
export const MAC_FILE_EXCLUSIONS = [
"!**/node_modules/node-pty/prebuilds/win32-*/**/*",
"!**/node_modules/node-pty/third_party/conpty/**/*",
] as const;
// Linux builds node-pty from source; its prebuilds target other platforms.
export const LINUX_FILE_EXCLUSIONS = [
...MAC_FILE_EXCLUSIONS,
"!**/node_modules/node-pty/prebuilds/darwin-*/**/*",
] as const;
// Native packages (node-pty, objc-js) ship prebuilds for both Darwin architectures; only universal
// apps need both. macOS 27 warns that an arm64 app holding x64-only code won't open on macOS 28.
export function resolveMacFileExclusions(arch?: typeof BuildArch.Type) {
if (arch === undefined || arch === "universal") {
return [...MAC_FILE_EXCLUSIONS];
}
const unusedArch = arch === "arm64" ? "x64" : "arm64";
return [...MAC_FILE_EXCLUSIONS, `!**/node_modules/**/prebuilds/darwin-${unusedArch}/**/*`];
}
// Large ASAR sidecars avoid NSIS extracting thousands of loose files during installs and updates.
export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar";
// Native modules and executables need real paths, so place them in ASAR's .unpacked sibling.
export const WINDOWS_NATIVE_ASAR_UNPACK_GLOB =
"{**/*.node,**/*.dll,**/*.exe,**/*.so,**/*.so.*,**/*.dylib}";
export const WINDOWS_SERVER_ASAR_UNPACK_GLOBS = [
"**/*.dll",
"**/*.exe",
"**/*.so",
"**/*.so.*",
"**/*.dylib",
] as const;
// Keep sidecar exclusions aligned with the app; .bin symlinks are unused and unsupported by ASAR extraction.
export const WINDOWS_SERVER_ASAR_IGNORE_GLOBS = [
"**/node_modules/@cursor/sdk-*",
"**/node_modules/@cursor/sdk-*/**",
"**/node_modules/@anthropic-ai/claude-agent-sdk-*",
"**/node_modules/@anthropic-ai/claude-agent-sdk-*/**",
"**/node_modules/.bin",
"**/node_modules/.bin/**",
"**/*.map",
] as const;
export function resolveWindowsServerAsarIgnoreGlobs(arch: typeof BuildArch.Type) {
const unusedArch = arch === "arm64" ? "x64" : "arm64";
const unusedPrebuild = `**/node_modules/node-pty/prebuilds/win32-${unusedArch}`;
const unusedConpty = `**/node_modules/node-pty/third_party/conpty/*/win10-${unusedArch}`;
return [
...WINDOWS_SERVER_ASAR_IGNORE_GLOBS,
unusedPrebuild,
`${unusedPrebuild}/**`,
unusedConpty,
`${unusedConpty}/**`,
];
}
export const WINDOWS_PACKAGED_PAYLOAD_FILE_LIMIT = 80;
export const WINDOWS_SERVER_RESOURCE_SOURCE_DIR = "apps/desktop/prod-resources/windows-server";
export const WINDOWS_SERVER_EXTRA_RESOURCES = [
{
from: WINDOWS_SERVER_RESOURCE_SOURCE_DIR,
to: ".",
filter: [WINDOWS_SERVER_ASAR_RESOURCE, `${WINDOWS_SERVER_ASAR_RESOURCE}.unpacked/**/*`],
},
] as const;
export const WSL_RUNTIME_ARCHIVE_NAME = "wsl-runtime.tar.gz";
export const WSL_RUNTIME_ARCHIVE_HASH_NAME = `${WSL_RUNTIME_ARCHIVE_NAME}.sha256`;
export const WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE = {
from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_NAME}`,
to: WSL_RUNTIME_ARCHIVE_NAME,
} as const;
export const WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE = {
from: `apps/desktop/prod-resources/${WSL_RUNTIME_ARCHIVE_HASH_NAME}`,
to: WSL_RUNTIME_ARCHIVE_HASH_NAME,
} as const;
export const bundlesWslRuntime = (input: {
readonly platform: typeof BuildPlatform.Type;
readonly runtimeArchivePath: string | undefined;
}): boolean => input.platform === "win" && input.runtimeArchivePath !== undefined;
export const WSL_RUNTIME_EXTRA_RESOURCES = [
WSL_RUNTIME_ARCHIVE_EXTRA_RESOURCE,
WSL_RUNTIME_ARCHIVE_HASH_EXTRA_RESOURCE,
] as const;
export const DESKTOP_EXTRA_RESOURCES = [
{
from: "apps/desktop/prod-resources/cursor-sdk",
to: "node_modules/@cursor",
},
{
from: "apps/desktop/prod-resources/resource-monitor",
to: "resource-monitor",
},
] as const;
export const LINUX_CAPTURE_EXTRA_RESOURCES = [
{
from: "apps/desktop/prod-resources/hyprland-capture",
to: "hyprland-capture",
},
{
from: "apps/desktop/prod-resources/kde-capture",
to: "kde-capture",
},
{
from: "apps/desktop/gnome-extension",
to: "gnome-extension",
filter: gnomeCaptureBundle.files,
},
] as const;
export const LINUX_BROWSER_SECRET_EXTRA_RESOURCES = [
{ from: "apps/desktop/prod-resources/browser-secret", to: "browser-secret" },
] as const;
export interface MacPasskeySigningConfiguration {
readonly appId: string;
readonly teamId: string;
readonly rpDomains: readonly string[];
readonly provisioningProfilePath: string;
}
export const InvalidMacPasskeyRpDomainReason = Schema.Literals([
"empty",
"scheme-not-allowed",
"parse-failed",
"credentials-not-allowed",
"port-not-allowed",
"path-not-allowed",
"query-not-allowed",
"fragment-not-allowed",
"hostname-mismatch",
]);
export type InvalidMacPasskeyRpDomainReason = typeof InvalidMacPasskeyRpDomainReason.Type;
export class InvalidMacPasskeyRpDomainError extends Schema.TaggedError<InvalidMacPasskeyRpDomainError>()(
"InvalidMacPasskeyRpDomainError",
{
reason: InvalidMacPasskeyRpDomainReason,
inputLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
return `Invalid passkey RP domain (${this.reason}).`;
}
}
export class InvalidAppleTeamIdError extends Schema.TaggedError<InvalidAppleTeamIdError>()(
"InvalidAppleTeamIdError",
{
teamId: Schema.String,
},
) {
override get message(): string {
return `T3CODE_APPLE_TEAM_ID '${this.teamId}' must be a 10-character Apple Developer Team ID.`;
}
}
export class MissingMacPasskeyProvisioningProfileError extends Schema.TaggedError<MissingMacPasskeyProvisioningProfileError>()(
"MissingMacPasskeyProvisioningProfileError",
{},
) {
override get message(): string {
return "T3CODE_MACOS_PROVISIONING_PROFILE must point to an Associated Domains provisioning profile.";
}
}
export class MissingMacPasskeyDomainConfigurationError extends Schema.TaggedError<MissingMacPasskeyDomainConfigurationError>()(
"MissingMacPasskeyDomainConfigurationError",
{},
) {
override get message(): string {
return "T3CODE_CLERK_PUBLISHABLE_KEY or T3CODE_CLERK_PASSKEY_RP_DOMAINS is required for signed macOS passkey builds.";
}
}
export class InvalidMacPasskeyPublishableKeyError extends Schema.TaggedError<InvalidMacPasskeyPublishableKeyError>()(
"InvalidMacPasskeyPublishableKeyError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "T3CODE_CLERK_PUBLISHABLE_KEY is invalid.";
}
}
export class MissingMacPasskeyRpDomainError extends Schema.TaggedError<MissingMacPasskeyRpDomainError>()(
"MissingMacPasskeyRpDomainError",
{},
) {
override get message(): string {
return "At least one Clerk passkey RP domain is required.";
}
}
export const MacPasskeySigningConfigurationError = Schema.Union([
InvalidMacPasskeyRpDomainError,
InvalidAppleTeamIdError,
MissingMacPasskeyProvisioningProfileError,
MissingMacPasskeyDomainConfigurationError,
InvalidMacPasskeyPublishableKeyError,
MissingMacPasskeyRpDomainError,
]);
export type MacPasskeySigningConfigurationError = typeof MacPasskeySigningConfigurationError.Type;
export const isMacPasskeySigningConfigurationError = Schema.is(MacPasskeySigningConfigurationError);
function normalizePasskeyRpDomain(value: string): string {
const normalized = value.trim().toLowerCase();
const inputLength = value.length;
if (normalized.length === 0) {
throw new InvalidMacPasskeyRpDomainError({ reason: "empty", inputLength });
}
if (/^[a-z][a-z\d+.-]*:\/\//u.test(normalized)) {
throw new InvalidMacPasskeyRpDomainError({
reason: "scheme-not-allowed",
inputLength,
});
}
let parsed: URL;
try {
parsed = new URL(`https://${normalized}`);
} catch (cause) {
throw new InvalidMacPasskeyRpDomainError({ reason: "parse-failed", inputLength, cause });
}
let reason: InvalidMacPasskeyRpDomainReason | undefined;
if (parsed.username.length > 0 || parsed.password.length > 0) {
reason = "credentials-not-allowed";
} else if (parsed.port.length > 0) {
reason = "port-not-allowed";
} else if (parsed.pathname !== "/") {
reason = "path-not-allowed";
} else if (parsed.search.length > 0) {
reason = "query-not-allowed";
} else if (parsed.hash.length > 0) {
reason = "fragment-not-allowed";
} else if (parsed.host !== normalized) {
reason = "hostname-mismatch";
}
if (reason) {
throw new InvalidMacPasskeyRpDomainError({ reason, inputLength });
}
return parsed.hostname;
}
export function resolveMacPasskeySigningConfiguration(
env: Readonly<Record<string, string | undefined>>,
): MacPasskeySigningConfiguration {
const teamId = env.T3CODE_APPLE_TEAM_ID?.trim().toUpperCase() ?? "";
if (!APPLE_TEAM_ID_PATTERN.test(teamId)) {
throw new InvalidAppleTeamIdError({ teamId });
}
const provisioningProfilePath = env.T3CODE_MACOS_PROVISIONING_PROFILE?.trim() ?? "";
if (provisioningProfilePath.length === 0) {
throw new MissingMacPasskeyProvisioningProfileError();
}
const configuredRpDomains = env.T3CODE_CLERK_PASSKEY_RP_DOMAINS?.trim();
let rpDomains: readonly string[];
if (configuredRpDomains) {
rpDomains = configuredRpDomains.split(",").map(normalizePasskeyRpDomain);
} else {
const publishableKey = env.T3CODE_CLERK_PUBLISHABLE_KEY?.trim();
if (!publishableKey) {
throw new MissingMacPasskeyDomainConfigurationError();
}
let hostname: string;
try {
hostname = clerkFrontendApiHostnameFromPublishableKey(publishableKey);
} catch (cause) {
throw new InvalidMacPasskeyPublishableKeyError({ cause });
}
rpDomains = [normalizePasskeyRpDomain(hostname)];
}
const uniqueRpDomains = [...new Set(rpDomains)];
if (uniqueRpDomains.length === 0) {
throw new MissingMacPasskeyRpDomainError();
}
return {
appId: DESKTOP_APP_ID,
teamId,
rpDomains: uniqueRpDomains,
provisioningProfilePath,
};
}
function escapeXml(value: string): string {
return value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
/** macOS refuses restricted entitlements absent from the provisioning profile. */
export interface MacWebAuthnEntitlements {
readonly touchIdKeychainAccessGroup: string | undefined;
readonly browserPasskeys: boolean;
}
const BROWSER_PASSKEYS_ENTITLEMENT = "com.apple.developer.web-browser.public-key-credential";
const ProvisioningProfilePlist = Schema.Struct({
Entitlements: Schema.Struct({
"keychain-access-groups": Schema.optional(Schema.Array(Schema.String)),
[BROWSER_PASSKEYS_ENTITLEMENT]: Schema.optional(Schema.Boolean),
}),
});
const isProvisioningProfilePlist = Schema.is(ProvisioningProfilePlist);
const readProfileEntitlements = (provisioningProfile: string) => {
const start = provisioningProfile.indexOf("<?xml");
const end = provisioningProfile.indexOf("</plist>", start);
if (start === -1 || end === -1) return undefined;
try {
const profile: unknown = Plist.parse(provisioningProfile.slice(start, end + "</plist>".length));
return isProvisioningProfilePlist(profile) ? profile.Entitlements : undefined;
} catch {
return undefined;
}
};
export function resolveMacWebAuthnEntitlements(
provisioningProfile: string,
configuration: Pick<MacPasskeySigningConfiguration, "appId" | "teamId">,
): MacWebAuthnEntitlements {
const entitlements = readProfileEntitlements(provisioningProfile);
const keychainAccessGroup = `${configuration.teamId}.${configuration.appId}.webauthn`;
const keychainGroupAuthorized = (entitlements?.["keychain-access-groups"] ?? []).some((group) =>
group.endsWith("*")
? keychainAccessGroup.startsWith(group.slice(0, -1))
: group === keychainAccessGroup,
);
return {
touchIdKeychainAccessGroup: keychainGroupAuthorized ? keychainAccessGroup : undefined,
browserPasskeys: entitlements?.[BROWSER_PASSKEYS_ENTITLEMENT] === true,
};
}
export function renderMacPasskeyEntitlements(
configuration: MacPasskeySigningConfiguration,
webAuthn: MacWebAuthnEntitlements,
): string {
const associatedDomains = configuration.rpDomains
.map((domain) => ` <string>webcredentials:${escapeXml(domain)}</string>`)
.join("\n");
const keychainAccessGroups = webAuthn.touchIdKeychainAccessGroup
? `
<key>keychain-access-groups</key>
<array>
<string>${escapeXml(webAuthn.touchIdKeychainAccessGroup)}</string>
</array>`
: "";
const browserPasskeys = webAuthn.browserPasskeys
? `
<key>${BROWSER_PASSKEYS_ENTITLEMENT}</key>
<true/>`
: "";
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.application-identifier</key>
<string>${escapeXml(`${configuration.teamId}.${configuration.appId}`)}</string>
<key>com.apple.developer.team-identifier</key>
<string>${escapeXml(configuration.teamId)}</string>
<key>com.apple.developer.associated-domains</key>
<array>
${associatedDomains}
</array>${keychainAccessGroups}${browserPasskeys}
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<!-- The hardened runtime denies camera and microphone to the app and every
child process, with no prompt, unless the app claims these. Terminals
and coding agents inherit the app's TCC identity, so without these a
command like ffmpeg or imagesnap gets silent access-denied. -->
<key>com.apple.security.device.camera</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
</plist>
`;
}
export function resolveFffNativeDependencies(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
version: string,
): Record<string, string> {
const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
if (platform === "mac") {
return Object.fromEntries(
architectures.map((architecture) => [`@ff-labs/fff-bin-darwin-${architecture}`, version]),
);
}
if (platform === "win") {
return Object.fromEntries(
architectures.map((architecture) => [`@ff-labs/fff-bin-win32-${architecture}`, version]),
);
}
return Object.fromEntries(
architectures.flatMap((architecture) =>
["gnu", "musl"].map((libc) => [`@ff-labs/fff-bin-linux-${architecture}-${libc}`, version]),
),
);
}
// macOS and Linux share one app.asar; stage the union of both bundles' external dependencies.
export function resolveMergedStageDependencies(input: {
readonly platform: "mac" | "linux";
readonly serverDependencies: Record<string, string>;
readonly desktopDependencies: Record<string, string>;
readonly arch: typeof BuildArch.Type;
readonly fffNodeVersion: string;
}) {
return {
...selectCliRuntimeExternalDependencies(input.serverDependencies),
...input.desktopDependencies,
...resolveFffNativeDependencies(input.platform, input.arch, input.fffNodeVersion),
};
}
/** Cursor's helper lookup falls through the archive to this real resources tree. */
export const stageCursorSdkPlatformPackages = Effect.fn("stageCursorSdkPlatformPackages")(
function* (nodeModulesDir: string, destination: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(destination, { recursive: true });
const sdkDirectory = path.join(nodeModulesDir, "@cursor/sdk");
if (!(yield* fs.exists(sdkDirectory))) return;
const cursorDirectory = path.dirname(yield* fs.realPath(sdkDirectory));
for (const name of yield* fs.readDirectory(cursorDirectory)) {
if (!name.startsWith("sdk-")) continue;
const source = yield* fs.realPath(path.join(cursorDirectory, name));
yield* fs.copy(source, path.join(destination, name));
}
},
);
export interface ClerkPasskeyNativeArtifact {
readonly packageName: string;
readonly binaryFileName: string;
}
export function resolveClerkPasskeyNativeArtifacts(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): readonly ClerkPasskeyNativeArtifact[] {
const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
if (platform === "mac") {
return architectures.map((architecture) => ({
packageName: `@clerk/electron-passkeys-darwin-${architecture}`,
binaryFileName: `electron-passkeys.darwin-${architecture}.node`,
}));
}
if (platform === "win") {
return architectures.map((architecture) => ({
packageName: `@clerk/electron-passkeys-win32-${architecture}-msvc`,
binaryFileName: `electron-passkeys.win32-${architecture}-msvc.node`,
}));
}
return [];
}
export function resolveKeyringNativeArtifacts(
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
): readonly ClerkPasskeyNativeArtifact[] {
const architectures = arch === "universal" ? (["arm64", "x64"] as const) : [arch];
if (platform === "mac") {
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-darwin-${architecture}`,
binaryFileName: `keyring.darwin-${architecture}.node`,
}));
}
if (platform === "win") {
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-win32-${architecture}-msvc`,
binaryFileName: `keyring.win32-${architecture}-msvc.node`,
}));
}
return architectures.map((architecture) => ({
packageName: `@napi-rs/keyring-linux-${architecture}-gnu`,
binaryFileName: `keyring.linux-${architecture}-gnu.node`,
}));
}
/** electron-builder omits pnpm-nested platform packages; stage keyring's binary beside its loader, which checks there first. */
const stageKeyringNativeBinaries = Effect.fn("stageKeyringNativeBinaries")(function* (
stageAppDir: string,
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const packageEntryPath = yield* fs.realPath(
path.join(stageAppDir, "node_modules", "@napi-rs", "keyring", "index.js"),
);
const packageDir = path.dirname(packageEntryPath);
const packageRequire = NodeModule.createRequire(packageEntryPath);
for (const artifact of resolveKeyringNativeArtifacts(platform, arch)) {
const sourcePath = yield* Effect.try({
try: () => packageRequire.resolve(`${artifact.packageName}/${artifact.binaryFileName}`),
catch: (cause) =>
new KeyringNativePackageMissingError({
packageName: artifact.packageName,
binaryFileName: artifact.binaryFileName,
packageEntryPath,
platform,
arch,
cause,
}),
});
yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
}
});
// Stage pnpm-nested Clerk binaries beside index.js so the loader finds them and electron-builder unpacks them.
const stageClerkPasskeyNativeBinaries = Effect.fn("stageClerkPasskeyNativeBinaries")(function* (
stageAppDir: string,
platform: typeof BuildPlatform.Type,
arch: typeof BuildArch.Type,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const packageEntryPath = yield* fs.realPath(
path.join(stageAppDir, "node_modules", "@clerk", "electron-passkeys", "index.js"),
);
const packageDir = path.dirname(packageEntryPath);
const packageRequire = NodeModule.createRequire(packageEntryPath);
for (const artifact of resolveClerkPasskeyNativeArtifacts(platform, arch)) {
const sourcePath = yield* Effect.try({
try: () => packageRequire.resolve(artifact.packageName),
catch: (cause) =>
new ClerkPasskeyNativePackageMissingError({
packageName: artifact.packageName,
binaryFileName: artifact.binaryFileName,
packageEntryPath,
platform,
arch,
cause,
}),
});
yield* fs.copyFile(sourcePath, path.join(packageDir, artifact.binaryFileName));
}
});
export function createStageWorkspaceConfig(input: {
readonly platform: typeof BuildPlatform.Type;
readonly arch: typeof BuildArch.Type;
readonly allowBuilds?: Record<string, boolean>;
readonly patchedDependencies?: Record<string, string>;
readonly overrides?: Record<string, string>;
}): StageWorkspaceConfig {
const { platform, arch, allowBuilds, patchedDependencies, overrides } = input;
const hostOs = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
const hostCpu = arch === "universal" ? ["arm64", "x64"] : [arch];
// Linux AppImages require glibc native optional dependencies; tell pnpm explicitly.
const supportedArchitectures =
platform === "linux"
? {
os: [hostOs],
cpu: hostCpu,
libc: ["glibc"],
}
: {
os: [hostOs],
cpu: hostCpu,
};
return {
supportedArchitectures,
...(allowBuilds && Object.keys(allowBuilds).length > 0 ? { allowBuilds } : {}),
...(patchedDependencies && Object.keys(patchedDependencies).length > 0
? { patchedDependencies }
: {}),
...(overrides && Object.keys(overrides).length > 0 ? { overrides } : {}),
packageExtensions: STAGE_PACKAGE_EXTENSIONS,
};
}
export function createStagePatchedDependencies(
patchedDependencies: Record<string, string>,
dependencies: Record<string, unknown>,
): Record<string, string> {
return Object.fromEntries(
Object.entries(patchedDependencies).filter(([patchKey]) =>
Object.hasOwn(dependencies, getPatchedDependencyPackageName(patchKey)),
),
);
}
function getPatchedDependencyPackageName(patchKey: string): string {
const versionSeparator = patchKey.lastIndexOf("@");
return versionSeparator > 0 ? patchKey.slice(0, versionSeparator) : patchKey;
}
const AzureTrustedSigningOptionsConfig = Config.all({
publisherName: Config.String("AZURE_TRUSTED_SIGNING_PUBLISHER_NAME"),
endpoint: Config.String("AZURE_TRUSTED_SIGNING_ENDPOINT"),
certificateProfileName: Config.String("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME"),
codeSigningAccountName: Config.String("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME"),
fileDigest: Config.String("AZURE_TRUSTED_SIGNING_FILE_DIGEST").pipe(Config.withDefault("SHA256")),
timestampDigest: Config.String("AZURE_TRUSTED_SIGNING_TIMESTAMP_DIGEST").pipe(
Config.withDefault("SHA256"),
),
timestampRfc3161: Config.String("AZURE_TRUSTED_SIGNING_TIMESTAMP_RFC3161").pipe(
Config.withDefault("http://timestamp.acs.microsoft.com"),
),
});
const BuildEnvConfig = Config.all({
platform: Config.schema(BuildPlatform, "T3CODE_DESKTOP_PLATFORM").pipe(Config.option),
target: Config.String("T3CODE_DESKTOP_TARGET").pipe(Config.option),
arch: Config.schema(BuildArch, "T3CODE_DESKTOP_ARCH").pipe(Config.option),
version: Config.String("T3CODE_DESKTOP_VERSION").pipe(Config.option),
outputDir: Config.String("T3CODE_DESKTOP_OUTPUT_DIR").pipe(Config.option),
skipBuild: Config.Boolean("T3CODE_DESKTOP_SKIP_BUILD").pipe(Config.withDefault(false)),
keepStage: Config.Boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)),
signed: Config.Boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)),
verbose: Config.Boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)),
mockUpdates: Config.Boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)),
mockUpdateServerPort: Config.String("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option),
wslRuntime: Config.String("T3CODE_DESKTOP_WSL_RUNTIME").pipe(Config.option),
});
const MockUpdateServerPortSchema = Schema.NumberFromString.check(
Schema.isInt(),
Schema.isBetween({ minimum: 1, maximum: 65535 }),
);
const decodeMockUpdateServerPort = Schema.decodeUnknownEffect(MockUpdateServerPortSchema);
function invalidMockUpdateServerPortReason(
configuredPort: string,
): typeof InvalidMockUpdateServerPortReason.Type {
const parsed = Number(configuredPort);
if (!Number.isFinite(parsed)) return "not-numeric";
if (!Number.isInteger(parsed)) return "not-integer";
if (parsed < 1 || parsed > 65535) return "out-of-range";
// Decoding already failed; valid integers here used unsupported representations.
return "not-numeric";
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(flag, () => envValue);
const mergeOptions = <A>(a: Option.Option<A>, b: Option.Option<A>, defaultValue: A) =>
Option.getOrElse(a, () => Option.getOrElse(b, () => defaultValue));
export const resolveMockUpdateServerPort = Effect.fn("resolveMockUpdateServerPort")(function* (
mockUpdateServerPort: string | undefined,
) {
const port = mockUpdateServerPort?.trim();
if (!port) {
return undefined;
}
return yield* decodeMockUpdateServerPort(port);
});
export const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (
input: BuildCliInput,
) {
const path = yield* Path.Path;
const repoRoot = yield* RepoRoot;
const env = yield* BuildEnvConfig;
const hostPlatform = yield* HostProcess.Platform;
const platform = mergeOptions(
input.platform,
env.platform,
detectHostBuildPlatform(hostPlatform),
);
if (!platform) {
return yield* new UnsupportedHostBuildPlatformError({ hostPlatform });
}
const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget);
const defaultArch = yield* getDefaultArch(platform);
const arch = mergeOptions(input.arch, env.arch, defaultArch);
const supportedArchitectures = PLATFORM_CONFIG[platform].archChoices;
if (!supportedArchitectures.includes(arch)) {
return yield* new UnsupportedDesktopBuildArchitectureError({
platform,
arch,
supportedArchitectures: [...supportedArchitectures],
});
}
const version = mergeOptions(input.buildVersion, env.version, undefined);
const releaseDir = resolveBooleanFlag(input.mockUpdates, env.mockUpdates)
? "release-mock"
: "release";
const outputDir = path.resolve(
repoRoot,
mergeOptions(input.outputDir, env.outputDir, releaseDir),
);
const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild);
const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage);
const signed = resolveBooleanFlag(input.signed, env.signed);
const verbose = resolveBooleanFlag(input.verbose, env.verbose);
const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates);
const configuredMockUpdateServerPort = Option.getOrUndefined(env.mockUpdateServerPort);
const mockUpdateServerPort =
Option.getOrUndefined(input.mockUpdateServerPort) ??
(configuredMockUpdateServerPort === undefined
? undefined
: yield* resolveMockUpdateServerPort(configuredMockUpdateServerPort).pipe(
Effect.mapError((cause) =>
InvalidMockUpdateServerPortError.fromConfigValue(configuredMockUpdateServerPort, cause),
),
));
const wslRuntime =
Option.getOrUndefined(input.wslRuntime) ?? Option.getOrUndefined(env.wslRuntime);
return {
platform,
target,
arch,
version,
outputDir,
skipBuild,
keepStage,
signed,
verbose,
mockUpdates,
mockUpdateServerPort,
wslRuntime,
} satisfies ResolvedBuildOptions;
});
const runCommand = Effect.fn("runCommand")(function* (
command: ChildProcess.Command,
options: {
readonly label: string;
readonly verbose: boolean;
},
) {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* commandSpawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectCommandStream(child.stdout, process.stdout, options.verbose),
collectCommandStream(child.stderr, process.stderr, options.verbose),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
return yield* new BuildCommandFailedError({
command: options.label,
exitCode,
...(stdout.trim() ? { stdoutTail: stdout } : {}),
...(stderr.trim() ? { stderrTail: stderr } : {}),
});
}
});
export class DesktopBuildAlreadyRunningError extends Schema.TaggedError<DesktopBuildAlreadyRunningError>()(
"DesktopBuildAlreadyRunningError",
{ lockPath: Schema.String },
) {
override get message(): string {
return `Another desktop build owns '${this.lockPath}'. Wait for it to finish. If a build was killed, confirm no desktop build is running, inspect and restore any changed release manifests, then remove this lock.`;
}
}
const withDesktopBuildLock = Effect.fn("withDesktopBuildLock")(function* <A, E, R>(
repoRoot: string,
build: Effect.Effect<A, E, R>,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const lockPath = path.join(repoRoot, ".desktop-build.lock");
return yield* Effect.acquireUseRelease(
fs
.makeDirectory(lockPath)
.pipe(
Effect.mapError((error) =>
error.reason._tag === "AlreadyExists"
? new DesktopBuildAlreadyRunningError({ lockPath })
: error,
),
),
// Stop packaging children and finish stage cleanup before another build can enter.
() => build.pipe(Effect.scoped),
(_, exit) =>
fs
.remove(lockPath, { recursive: true })
.pipe(
Effect.catch((error) =>