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

build-cli-archive.ts

543 lines20.8 KB

1#!/usr/bin/env node
2/** Runtime archives must run without host Node, npm, or compilers. */
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as Config from "effect/Config";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as PlatformError from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import { Command, Flag } from "effect/cli";
15import { ChildProcess, ChildProcessSpawner } from "effect/process";
16​
17import * as HostProcess from "@t3tools/shared/HostProcess";
18import { fromYaml } from "@t3tools/shared/schemaYaml";
19import { resolveSpawnCommand } from "@t3tools/shared/shell";
20import rootPackageJson from "../package.json" with { type: "json" };
21import serverPackageJson from "../apps/server/package.json" with { type: "json" };
22​
23import {
24 createStagePatchedDependencies,
25 createStageWorkspaceConfig,
26 resolveFffNativeDependencies,
27 STAGE_INSTALL_ARGS,
28} from "./build-desktop-artifact.ts";
29import { selectCliRuntimeExternalDependencies } from "./lib/cli-external-packages.ts";
30import { signWithJsign } from "./lib/windows-jsign.ts";
31import { windowsSystemTar } from "./lib/windows-tar.ts";
32import { resolveCatalogDependencies } from "./lib/resolve-catalog.ts";
33​
34const BuildPlatform = Schema.Literals(["mac", "linux", "win"]);
35const BuildArch = Schema.Literals(["arm64", "x64"]);
36type BuildPlatform = typeof BuildPlatform.Type;
37type BuildArch = typeof BuildArch.Type;
38​
39const WorkspaceConfig = Schema.Struct({
40 catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
41 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
42 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
43 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
44});
45const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
46const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
47const StageWorkspaceConfig = Schema.Struct({
48 supportedArchitectures: Schema.Struct({
49 os: Schema.Array(Schema.String),
50 cpu: Schema.Array(Schema.String),
51 libc: Schema.optional(Schema.Array(Schema.String)),
52 }),
53 allowBuilds: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)),
54 patchedDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
55 overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
56 nodeLinker: Schema.optional(Schema.Literals(["hoisted"])),
57});
58const encodeStageWorkspaceConfig = Schema.encodeEffect(fromYaml(StageWorkspaceConfig));
59​
60const RepoRoot = Effect.service(Path.Path).pipe(
61 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
62);
63​
64export class CliArchiveCommandFailedError extends Schema.TaggedError<CliArchiveCommandFailedError>()(
65 "CliArchiveCommandFailedError",
66 { command: Schema.String, exitCode: Schema.Int },
67) {
68 override get message(): string {
69 return `${this.command} exited with code ${this.exitCode}.`;
70 }
72​
73export class CliArchiveInputMissingError extends Schema.TaggedError<CliArchiveInputMissingError>()(
74 "CliArchiveInputMissingError",
75 { inputPath: Schema.String, hint: Schema.String },
76) {
77 override get message(): string {
78 return `Missing ${this.inputPath}. ${this.hint}`;
79 }
81​
82export function cliArchivePlatformKey(platform: BuildPlatform, arch: BuildArch): string {
83 const nodePlatform = platform === "mac" ? "darwin" : platform === "win" ? "win32" : "linux";
84 return `${nodePlatform}-${arch}`;
86​
87export function cliArchiveStem(version: string, platform: BuildPlatform, arch: BuildArch): string {
88 return `t3-${version}-${cliArchivePlatformKey(platform, arch)}`;
90​
91export function cliArchiveFileName(version: string, platform: BuildPlatform, arch: BuildArch) {
92 // Minimal hosts may lack xz, but tar and Node zlib handle gzip without it.
93 return `${cliArchiveStem(version, platform, arch)}.${platform === "win" ? "zip" : "tar.gz"}`;
95​
96const runCommand = Effect.fn("runCommand")(function* (
97 command: ChildProcess.Command,
98 label: string,
99) {
100 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
101 const child = yield* spawner.spawn(
102 ChildProcess.isStandardCommand(command)
103 ? ChildProcess.make(command.command, command.args, {
104 ...command.options,
105 stdout: "inherit",
106 stderr: "inherit",
107 })
108 : command,
109 );
110 const exitCode = Number(yield* child.exitCode);
111 if (exitCode !== 0) {
112 return yield* new CliArchiveCommandFailedError({ command: label, exitCode });
113 }
114});
115​
116const requireInput = Effect.fn("requireInput")(function* (inputPath: string, hint: string) {
117 const fs = yield* FileSystem.FileSystem;
118 if (!(yield* fs.exists(inputPath))) {
119 return yield* new CliArchiveInputMissingError({ inputPath, hint });
120 }
121});
122​
123/** Installed runtimes cannot rely on pnpm's store layout surviving archival. */
124const stageRuntimeExternals = Effect.fn("stageRuntimeExternals")(function* (input: {
125 readonly repoRoot: string;
126 readonly stageDir: string;
127 readonly platform: BuildPlatform;
128 readonly arch: BuildArch;
129 readonly version: string;
130}) {
131 const fs = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const workspace = yield* decodeWorkspaceConfig(
134 yield* fs.readFileString(path.join(input.repoRoot, "pnpm-workspace.yaml")),
135 );
136 const catalog = workspace.catalog ?? {};
137 const serverDependencies = resolveCatalogDependencies(
138 serverPackageJson.dependencies,
139 catalog,
140 "apps/server",
141 );
142 const fffNodeVersion = serverDependencies["@ff-labs/fff-node"];
143 if (fffNodeVersion === undefined) {
144 return yield* new CliArchiveInputMissingError({
145 inputPath: "apps/server/package.json#dependencies['@ff-labs/fff-node']",
146 hint: "The archive stages fff's platform binary from this version.",
147 });
148 }
149 const dependencies = {
150 ...selectCliRuntimeExternalDependencies(serverDependencies),
151 ...resolveFffNativeDependencies(input.platform, input.arch, fffNodeVersion),
152 };
153 const patchedDependencies = createStagePatchedDependencies(
154 workspace.patchedDependencies ?? {},
155 dependencies,
156 );
157​
158 yield* fs.writeFileString(
159 path.join(input.stageDir, "package.json"),
160 `${yield* encodeJsonString({
161 name: "t3-runtime",
162 version: input.version,
163 private: true,
164 packageManager: rootPackageJson.packageManager,
165 dependencies,
166 })}\n`,
167 );
168 yield* fs.writeFileString(
169 path.join(input.stageDir, "pnpm-workspace.yaml"),
170 yield* encodeStageWorkspaceConfig({
171 ...createStageWorkspaceConfig({
172 platform: input.platform,
173 arch: input.arch,
174 ...(workspace.allowBuilds ? { allowBuilds: workspace.allowBuilds } : {}),
175 patchedDependencies,
176 overrides: resolveCatalogDependencies(workspace.overrides ?? {}, catalog, "apps/server"),
177 }),
178 nodeLinker: "hoisted",
179 }),
180 );
181 if (Object.keys(patchedDependencies).length > 0) {
182 yield* fs.copy(path.join(input.repoRoot, "patches"), path.join(input.stageDir, "patches"));
183 }
184​
185 const install = yield* resolveSpawnCommand("vp", [...STAGE_INSTALL_ARGS]);
186 yield* runCommand(
187 ChildProcess.make(install.command, install.args, {
188 cwd: input.stageDir,
189 shell: install.shell,
190 stdout: "inherit",
191 stderr: "inherit",
192 }),
193 "vp install --prod (cli archive runtime externals)",
194 );
195​
196 const platformKey = cliArchivePlatformKey(input.platform, input.arch);
197 const prebuildsDir = path.join(input.stageDir, "node_modules/node-pty/prebuilds");
198 const foreignPrebuilds = (yield* fs
199 .readDirectory(prebuildsDir)
200 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []))).filter(
201 (entry) => entry !== platformKey,
202 );
203 for (const entry of [
204 "package.json",
205 "pnpm-workspace.yaml",
206 "pnpm-lock.yaml",
207 "patches",
208 "node_modules/.pnpm",
209 "node_modules/.modules.yaml",
210 "node_modules/.pnpm-workspace-state-v1.json",
211 "node_modules/.bin",
212 ...foreignPrebuilds.map((entry) => `node_modules/node-pty/prebuilds/${entry}`),
213 ]) {
214 yield* fs.remove(path.join(input.stageDir, entry), { recursive: true, force: true });
215 }
216 // Nested .bin shims are unused symlinks, which the npm registry rejects in tarballs.
217 yield* removeNestedBinDirectories(fs, path, path.join(input.stageDir, "node_modules"));
218});
219​
220const removeNestedBinDirectories = Effect.fn("build-cli-archive.removeNestedBinDirectories")(
221 function* (
222 fs: FileSystem.FileSystem,
223 path: Path.Path,
224 root: string,
225 ): Effect.fn.Return<void, PlatformError.PlatformError> {
226 const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
227 for (const entry of entries) {
228 const child = path.join(root, entry);
229 if (entry === ".bin") {
230 yield* fs.remove(child, { recursive: true, force: true });
231 continue;
232 }
233 const info = yield* fs.stat(child).pipe(Effect.option);
234 if (Option.isSome(info) && info.value.type === "Directory") {
235 yield* removeNestedBinDirectories(fs, path, child);
236 }
237 }
238 },
239);
240​
241const stageWebClient = Effect.fn("stageWebClient")(function* (source: string, target: string) {
242 const fs = yield* FileSystem.FileSystem;
243 const path = yield* Path.Path;
244 yield* fs.copy(source, target);
245 const maps = (yield* fs.readDirectory(target, { recursive: true })).filter((entry) =>
246 entry.endsWith(".map"),
247 );
248 for (const entry of maps) {
249 yield* fs.remove(path.join(target, entry), { force: true });
250 }
251});
252​
253const MacSigningConfig = Config.all({
254 identity: Config.String("T3CODE_CLI_MAC_SIGN_IDENTITY").pipe(Config.option),
255 appleApiKey: Config.String("APPLE_API_KEY").pipe(Config.option),
256 appleApiKeyId: Config.String("APPLE_API_KEY_ID").pipe(Config.option),
257 appleApiIssuer: Config.String("APPLE_API_ISSUER").pipe(Config.option),
258});
259​
260/** Apple Silicon requires signed binaries; notarization's hardened runtime also requires every native addon signed. */
261const signMacArchiveContents = Effect.fn("signMacArchiveContents")(function* (input: {
262 readonly repoRoot: string;
263 readonly contentDir: string;
264 readonly executablePath: string;
265}) {
266 const fs = yield* FileSystem.FileSystem;
267 const path = yield* Path.Path;
268 const signing = yield* MacSigningConfig;
269 const identity = Option.getOrUndefined(signing.identity)?.trim() || "-";
270​
271 const entitlements = path.join(input.repoRoot, "apps/server/resources/cli-entitlements.plist");
272 const libraries = (yield* fs.readDirectory(input.contentDir, { recursive: true }))
273 .filter(
274 (entry) =>
275 entry.endsWith(".node") ||
276 entry.endsWith(".dylib") ||
277 entry.endsWith("spawn-helper") ||
278 entry.endsWith("t3-resource-monitor"),
279 )
280 .map((entry) => path.join(input.contentDir, entry));
281​
282 for (const target of [...libraries, input.executablePath]) {
283 yield* runCommand(
284 ChildProcess.make("codesign", [
285 "--force",
286 "--sign",
287 identity,
288 ...(identity === "-" ? [] : ["--options", "runtime", "--timestamp"]),
289 ...(target === input.executablePath ? ["--entitlements", entitlements] : []),
290 target,
291 ]),
292 `codesign ${path.relative(input.contentDir, target)}`,
293 );
294 }
295 if (identity === "-") {
296 yield* Effect.log("[cli-archive] Signed ad hoc (no T3CODE_CLI_MAC_SIGN_IDENTITY).");
297 return;
298 }
299​
300 const apiKey = Option.getOrUndefined(signing.appleApiKey);
301 const apiKeyId = Option.getOrUndefined(signing.appleApiKeyId);
302 const apiIssuer = Option.getOrUndefined(signing.appleApiIssuer);
303 if (!apiKey || !apiKeyId || !apiIssuer) {
304 yield* Effect.logWarning(
305 "[cli-archive] Developer ID signed but not notarized (missing APPLE_API_KEY*).",
306 );
307 return;
308 }
309 // notarytool requires an archive; bare executables rely on online tickets because they cannot be stapled.
310 const notarizeZip = path.join(path.dirname(input.executablePath), ".notarize-t3.zip");
311 yield* runCommand(
312 ChildProcess.make("ditto", ["-c", "-k", "--keepParent", input.executablePath, notarizeZip]),
313 "ditto (notarization zip)",
314 );
315 yield* runCommand(
316 ChildProcess.make("xcrun", [
317 "notarytool",
318 "submit",
319 notarizeZip,
320 "--key",
321 apiKey,
322 "--key-id",
323 apiKeyId,
324 "--issuer",
325 apiIssuer,
326 "--wait",
327 ]),
328 "notarytool submit",
329 ).pipe(Effect.ensuring(fs.remove(notarizeZip, { force: true }).pipe(Effect.ignore)));
330 yield* Effect.log("[cli-archive] Notarized t3.");
331});
332​
333const WindowsSigningConfig = Config.all({
334 endpoint: Config.String("AZURE_TRUSTED_SIGNING_ENDPOINT").pipe(Config.option),
335 accountName: Config.String("AZURE_TRUSTED_SIGNING_ACCOUNT_NAME").pipe(Config.option),
336 certificateProfileName: Config.String("AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME").pipe(
337 Config.option,
338 ),
339});
340​
341/** Node's Windows --build-sea leaves a stale Authenticode offset pointing into rebuilt resources instead of certificates. */
342const stripStaleAuthenticodeEntry = Effect.fn("stripStaleAuthenticodeEntry")(function* (
343 executablePath: string,
344) {
345 const fs = yield* FileSystem.FileSystem;
346 const bytes = yield* fs.readFile(executablePath);
347 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
348 const peOffset = view.getUint32(0x3c, true);
349 if (view.getUint32(peOffset, true) !== 0x00004550) {
350 return yield* new CliArchiveInputMissingError({
351 inputPath: executablePath,
352 hint: "Expected a PE executable to strip the stale signature entry from.",
353 });
354 }
355 const optionalHeader = peOffset + 24;
356 const magic = view.getUint16(optionalHeader, true);
357 // PE data directories start at +112 (PE32+) or +96 (PE32); index 4 holds the certificate offset and size.
358 const securityEntry = optionalHeader + (magic === 0x20b ? 112 : 96) + 4 * 8;
359 const offset = view.getUint32(securityEntry, true);
360 const size = view.getUint32(securityEntry + 4, true);
361 if (offset === 0 && size === 0) return;
362 if (offset + size === bytes.byteLength) {
363 // Let signtool replace intact certificate tables ending at EOF.
364 return;
365 }
366 view.setUint32(securityEntry, 0, true);
367 view.setUint32(securityEntry + 4, 0, true);
368 yield* fs.writeFile(executablePath, bytes);
369 yield* Effect.log(
370 `[cli-archive] Cleared the stale Authenticode entry (offset ${String(offset)}, size ${String(size)}) left by --build-sea.`,
371 );
372});
373​
374const signWindowsExecutable = Effect.fn("signWindowsExecutable")(function* (
375 executablePath: string,
376) {
377 const signing = yield* WindowsSigningConfig;
378 const endpoint = Option.getOrUndefined(signing.endpoint);
379 const accountName = Option.getOrUndefined(signing.accountName);
380 const profile = Option.getOrUndefined(signing.certificateProfileName);
381 if (!endpoint || !accountName || !profile) {
382 yield* Effect.log("[cli-archive] Windows signing disabled (missing Azure Trusted Signing).");
383 return;
384 }
385 yield* stripStaleAuthenticodeEntry(executablePath);
386 if ((yield* HostProcess.Platform) !== "win32") {
387 yield* signWithJsign(executablePath);
388 yield* Effect.log("[cli-archive] Signed t3.exe (Azure Trusted Signing via jsign).");
389 return;
390 }
391 const quote = (value: string) => `'${value.replaceAll("'", "''")}'`;
392 const script = [
393 "$ErrorActionPreference = 'Stop';",
394 "Invoke-TrustedSigning",
395 `-Endpoint ${quote(endpoint)}`,
396 `-CodeSigningAccountName ${quote(accountName)}`,
397 `-CertificateProfileName ${quote(profile)}`,
398 "-FileDigest 'SHA256'",
399 "-TimestampRfc3161 'http://timestamp.acs.microsoft.com'",
400 "-TimestampDigest 'SHA256'",
401 `-Files ${quote(executablePath)}`,
402 ].join(" ");
403 yield* runCommand(
404 ChildProcess.make("pwsh", ["-NoProfile", "-NonInteractive", "-Command", script]),
405 "Invoke-TrustedSigning t3.exe",
406 );
407 yield* Effect.log("[cli-archive] Signed t3.exe (Azure Trusted Signing).");
408});
409​
410const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: {
411 readonly platform: BuildPlatform;
412 readonly arch: BuildArch;
413 readonly version: string;
414 readonly outputDir: string;
415 readonly resourceMonitorDir: Option.Option<string>;
416}) {
417 const fs = yield* FileSystem.FileSystem;
418 const path = yield* Path.Path;
419 const repoRoot = yield* RepoRoot;
420 const serverDir = path.join(repoRoot, "apps/server");
421 const executableName = input.platform === "win" ? "t3.exe" : "t3";
422 // tsdown suffixes cross-built executables; prefer the exact target over the plain host build.
423 const targetKey = `${input.platform === "mac" ? "darwin" : input.platform}-${input.arch}`;
424 const targetExecutable = path.join(
425 serverDir,
426 "dist-exe",
427 `t3-${targetKey}${input.platform === "win" ? ".exe" : ""}`,
428 );
429 // The unsuffixed executable is valid only for the host platform and architecture.
430 const hostPlatform = yield* HostProcess.Platform;
431 const hostKey = `${hostPlatform === "win32" ? "win" : hostPlatform}-${yield* HostProcess.Architecture}`;
432 const builtExecutable = (yield* fs.exists(targetExecutable))
433 ? targetExecutable
434 : targetKey === hostKey
435 ? path.join(serverDir, "dist-exe", executableName)
436 : targetExecutable;
437 const webClient = path.join(serverDir, "dist/client");
438 const resourceMonitorDir = Option.getOrElse(input.resourceMonitorDir, () =>
439 path.join(serverDir, "dist/resource-monitor"),
440 );
441​
442 yield* requireInput(
443 builtExecutable,
444 `Run \`node apps/server/scripts/cli.ts build-exe --target ${targetKey}\` first.`,
445 );
446 yield* requireInput(path.join(webClient, "index.html"), "Run `vp run --filter t3 build` first.");
447 yield* requireInput(
448 resourceMonitorDir,
449 "Build the resource monitor or pass --resource-monitor-dir.",
450 );
451​
452 const stem = cliArchiveStem(input.version, input.platform, input.arch);
453 const stageRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-archive-" });
454 const contentDir = path.join(stageRoot, stem);
455 yield* fs.makeDirectory(contentDir, { recursive: true });
456​
457 yield* Effect.log(`[cli-archive] Staging ${stem}...`);
458 yield* fs.copyFile(builtExecutable, path.join(contentDir, executableName));
459 yield* stageWebClient(webClient, path.join(contentDir, "client"));
460 yield* fs.copy(resourceMonitorDir, path.join(contentDir, "resource-monitor"));
461 yield* stageRuntimeExternals({
462 repoRoot,
463 stageDir: contentDir,
464 platform: input.platform,
465 arch: input.arch,
466 version: input.version,
467 });
468​
469 const executablePath = path.join(contentDir, executableName);
470 if (input.platform === "mac") {
471 yield* signMacArchiveContents({ repoRoot, contentDir, executablePath });
472 } else if (input.platform === "win") {
473 yield* signWindowsExecutable(executablePath);
474 }
475 if (input.platform !== "win") {
476 yield* fs.chmod(executablePath, 0o755);
477 }
478​
479 yield* fs.makeDirectory(input.outputDir, { recursive: true });
480 const archivePath = path.join(
481 input.outputDir,
482 cliArchiveFileName(input.version, input.platform, input.arch),
483 );
484 yield* fs.remove(archivePath, { force: true });
485 if (input.platform === "win" && hostPlatform !== "win32") {
486 yield* runCommand(
487 ChildProcess.make("zip", ["-q", "-r", "-X", path.resolve(archivePath), stem], {
488 cwd: stageRoot,
489 }),
490 "zip",
491 );
492 } else if (input.platform === "win") {
493 // Windows ships bsdtar, which writes zip natively. Name it by path: under
494 // the Git Bash shell CI uses, a bare `tar` is GNU tar, which neither
495 // writes zip nor accepts a drive-letter path.
496 yield* runCommand(
497 ChildProcess.make(windowsSystemTar(), ["-a", "-c", "-f", archivePath, "-C", stageRoot, stem]),
498 "tar (zip)",
499 );
500 } else {
501 // npm rejects Linux hardlink entries; macOS pnpm clones and bsdtar lacks this flag.
502 yield* runCommand(
503 ChildProcess.make("tar", [
504 ...(input.platform === "linux" ? ["--hard-dereference"] : []),
505 "-czf",
506 archivePath,
507 "-C",
508 stageRoot,
509 stem,
510 ]),
511 "tar (gzip)",
512 );
513 }
514 const stat = yield* fs.stat(archivePath);
515 yield* Effect.log(`[cli-archive] Wrote ${archivePath} (${String(stat.size)} bytes).`);
516 return archivePath;
517});
518​
519const command = Command.make(
520 "build-cli-archive",
521 {
522 platform: Flag.Literals("platform", BuildPlatform.literals),
523 arch: Flag.Literals("arch", BuildArch.literals),
524 version: Flag.String("version").pipe(
525 Flag.withDescription("Release version for the archive name."),
526 ),
527 outputDir: Flag.String("output-dir").pipe(Flag.withDefault("release-cli")),
528 resourceMonitorDir: Flag.String("resource-monitor-dir").pipe(
529 Flag.withDescription(
530 "Directory laid out like dist/resource-monitor (defaults to apps/server/dist/resource-monitor).",
531 ),
532 Flag.optional,
533 ),
534 },
535 (input) => buildCliArchive(input).pipe(Effect.scoped),
536).pipe(Command.withDescription("Package the t3 single-executable into a per-platform archive."));
537​
538if (import.meta.main) {
539 Command.run(command, { version: "0.0.0" }).pipe(
540 Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
541 NodeRuntime.runMain,
542 );