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

build-npm-platform-packages.ts

443 lines16.3 KB

1#!/usr/bin/env node
2/**
3 * Turns the per-platform CLI archives of one release into the npm packages
4 * behind `npx t3` / `npm i -g t3`: one `@t3code/t3-<platformKey>` package per
5 * archive holding the archive's contents verbatim, plus the `t3` launcher
6 * that lists them as optionalDependencies and execs the one npm installed.
7 * The bytes a user gets from npm are therefore the release archive's, and
8 * running them needs neither a Node runtime, npm, nor a native build.
9 *
10 * Output layout under `--output-dir`:
11 *
12 * @t3code/t3-<platformKey>/ archive contents flattened + package.json
13 * @t3code/t3-<platformKey>.tgz the same tree as an npm tarball
14 * t3/ launcher: package.json, bin/t3.js, README.md
15 * t3.tgz the launcher as an npm tarball
16 *
17 * The tarballs are what gets published. `npm publish <dir>` always drops
18 * `node_modules/` (npm-packlist ignores it whatever `files` says, and
19 * bundleDependencies needs an arborist tree these flattened installs are
20 * not), whereas `npm publish <tarball>` uploads the bytes as given.
21 */
22import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
23import * as NodeServices from "@effect/platform-node/NodeServices";
24import * as Effect from "effect/Effect";
25import * as FileSystem from "effect/FileSystem";
26import * as Layer from "effect/Layer";
27import * as Logger from "effect/Logger";
28import * as Path from "effect/Path";
29import * as Schema from "effect/Schema";
30import { Command, Flag } from "effect/unstable/cli";
31import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
32​
33import {
34 CLI_ARCHIVE_PLATFORM_KEYS,
35 cliArchiveFileName,
36 type CliArchivePlatformKey,
37} from "@t3tools/shared/cliRelease";
38import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
39import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
40import { isCommandAvailable } from "@t3tools/shared/shell";
41import serverPackageJson from "../apps/server/package.json" with { type: "json" };
42​
43import { windowsSystemTar } from "./build-cli-archive.ts";
44​
45export const NPM_PLATFORM_PACKAGE_SCOPE = "@t3code";
46export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
47​
48const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
49​
50export class NpmPackagesCommandFailedError extends Schema.TaggedError<NpmPackagesCommandFailedError>()(
51 "NpmPackagesCommandFailedError",
52 { command: Schema.String, exitCode: Schema.Int },
53) {
54 override get message(): string {
55 return `${this.command} exited with code ${this.exitCode}.`;
56 }
58​
59export class NpmPackagesToolMissingError extends Schema.TaggedError<NpmPackagesToolMissingError>()(
60 "NpmPackagesToolMissingError",
61 { tool: Schema.String, purpose: Schema.String },
62) {
63 override get message(): string {
64 return `\`${this.tool}\` is not on PATH; it is needed to ${this.purpose}.`;
65 }
67​
68export class NpmPackagesArchivesMissingError extends Schema.TaggedError<NpmPackagesArchivesMissingError>()(
69 "NpmPackagesArchivesMissingError",
70 { archivesDir: Schema.String, missing: Schema.Array(Schema.String) },
71) {
72 override get message(): string {
73 return `${this.archivesDir} lacks archives for ${this.missing.join(", ")}. A launcher published without them would silently skip those platforms; pass --allow-missing for a deliberately partial build.`;
74 }
76​
77export class NpmPackagesArchiveLayoutError extends Schema.TaggedError<NpmPackagesArchiveLayoutError>()(
78 "NpmPackagesArchiveLayoutError",
79 { archive: Schema.String, detail: Schema.String },
80) {
81 override get message(): string {
82 return `${this.archive}: ${this.detail}`;
83 }
85​
86export function npmPlatformPackageName(platformKey: CliArchivePlatformKey): string {
87 return `${NPM_PLATFORM_PACKAGE_SCOPE}/t3-${platformKey}`;
89​
90/** package.json for one platform package; `os`/`cpu` let npm skip the other five. */
91export function npmPlatformPackageManifest(platformKey: CliArchivePlatformKey, version: string) {
92 const [os, cpu] = platformKey.split("-") as [string, string];
93 return {
94 name: npmPlatformPackageName(platformKey),
95 version,
96 description: `T3 Code CLI executable for ${platformKey}`,
97 license: serverPackageJson.license,
98 repository: serverPackageJson.repository,
99 os: [os],
100 cpu: [cpu],
101 files: ["t3", "t3.exe", "client", "resource-monitor", "node_modules"],
102 preferUnplugged: true,
103 };
105​
106/**
107 * README for one platform package. Without one at the package root, npm
108 * shows the first README it finds in the tarball, which is a bundled
109 * dependency's (ffi-rs).
110 */
111export function npmPlatformPackageReadme(platformKey: CliArchivePlatformKey): string {
112 return [
113 `# ${npmPlatformPackageName(platformKey)}`,
114 "",
115 `The T3 Code CLI executable for ${platformKey}. Do not install this package directly:`,
116 `it is an optional dependency of \`${NPM_LAUNCHER_PACKAGE_NAME}\`, which picks the package for the`,
117 "current platform and runs the executable inside it.",
118 "",
119 "```sh",
120 `npx ${NPM_LAUNCHER_PACKAGE_NAME}@latest`,
121 "```",
122 "",
123 "Source and documentation: https://github.com/pingdotgg/t3code",
124 "",
125 ].join("\n");
127​
128/** package.json for the `t3` launcher. No engines: bin/t3.js is trivial CJS. */
129export function npmLauncherPackageManifest(
130 version: string,
131 platformKeys: ReadonlyArray<CliArchivePlatformKey>,
132) {
133 return {
134 name: NPM_LAUNCHER_PACKAGE_NAME,
135 version,
136 description: "T3 Code CLI. Installs the self-contained executable for this platform.",
137 license: serverPackageJson.license,
138 repository: serverPackageJson.repository,
139 bin: { t3: "./bin/t3.js" },
140 files: ["bin"],
141 optionalDependencies: Object.fromEntries(
142 platformKeys.map((key) => [npmPlatformPackageName(key), version]),
143 ),
144 };
146​
147/**
148 * The launcher every `npx t3` runs. Plain CommonJS with no dependencies so it
149 * loads on any Node that npm itself runs on; the real work happens in the
150 * single-executable it execs.
151 */
152export const NPM_LAUNCHER_SCRIPT = `#!/usr/bin/env node
153"use strict";
154const { spawnSync } = require("node:child_process");
155const { constants } = require("node:os");
156const { dirname, join } = require("node:path");
157​
158const SUPPORTED = [${CLI_ARCHIVE_PLATFORM_KEYS.map((key) => `"${key}"`).join(", ")}];
159const key = process.platform + "-" + process.arch;
160​
161let packageDir;
162try {
163 packageDir = dirname(require.resolve("${NPM_PLATFORM_PACKAGE_SCOPE}/t3-" + key + "/package.json"));
164} catch {
165 process.stderr.write(
166 [
167 "t3: no T3 Code CLI build is available for this platform (" + key + ").",
168 "Supported platforms: " + SUPPORTED.join(", ") + ".",
169 "If yours is listed, reinstall t3 so npm fetches its optional dependency.",
170 "The desktop app and release archives are at https://github.com/pingdotgg/t3code/releases",
171 "",
172 ].join("\\n"),
173 );
174 process.exit(1);
176​
177const executable = join(packageDir, process.platform === "win32" ? "t3.exe" : "t3");
178const result = spawnSync(executable, process.argv.slice(2), { stdio: "inherit" });
179if (result.error) {
180 process.stderr.write("t3: failed to start " + executable + ": " + result.error.message + "\\n");
181 process.exit(1);
183// A child killed by a signal has no status; report it the way a shell would.
184process.exit(result.status ?? 128 + (constants.signals[result.signal] || 1));
185`;
186​
187const runCommand = Effect.fn("runCommand")(function* (
188 command: ChildProcess.StandardCommand,
189 label: string,
190) {
191 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
192 const child = yield* spawner.spawn(
193 ChildProcess.make(command.command, command.args, {
194 ...command.options,
195 stdout: "inherit",
196 stderr: "inherit",
197 }),
198 );
199 const exitCode = Number(yield* child.exitCode);
200 if (exitCode !== 0) {
201 return yield* new NpmPackagesCommandFailedError({ command: label, exitCode });
202 }
203});
204​
205/**
206 * Extracts an archive and returns its single top-level directory. `.tar.gz`
207 * goes through tar everywhere; `.zip` through the bsdtar Windows ships or,
208 * elsewhere, `unzip`, since GNU tar cannot read zip.
209 */
210const extractArchive = Effect.fn("extractArchive")(function* (archive: string, into: string) {
211 const fs = yield* FileSystem.FileSystem;
212 const path = yield* Path.Path;
213 const platform = yield* HostProcessPlatform;
214 if (!archive.endsWith(".zip")) {
215 yield* runCommand(ChildProcess.make("tar", ["-xf", archive, "-C", into]), "tar -xf");
216 } else if (platform === "win32") {
217 yield* runCommand(
218 ChildProcess.make(windowsSystemTar(), ["-xf", archive, "-C", into]),
219 "tar.exe -xf (zip)",
220 );
221 } else {
222 if (!(yield* isCommandAvailable("unzip"))) {
223 return yield* new NpmPackagesToolMissingError({
224 tool: "unzip",
225 purpose: `extract ${path.basename(archive)} (GNU tar cannot read zip)`,
226 });
227 }
228 yield* runCommand(ChildProcess.make("unzip", ["-q", archive, "-d", into]), "unzip");
229 }
230 const entries = yield* fs.readDirectory(into);
231 const [root] = entries;
232 if (root === undefined || entries.length !== 1) {
233 return yield* new NpmPackagesArchiveLayoutError({
234 archive: path.basename(archive),
235 detail: `expected exactly one top-level directory, found ${String(entries.length)} entries`,
236 });
237 }
238 return path.join(into, root);
239});
240​
241/** Tar to build npm tarballs with; see build-cli-archive.ts for why Windows names bsdtar by path. */
242const hostTar = Effect.map(HostProcessPlatform, (platform) =>
243 platform === "win32" ? windowsSystemTar() : "tar",
244);
245​
246/**
247 * Writes `stageDir/package` as a gzipped npm tarball and then moves the tree
248 * to `packageDir` so the contents stay inspectable beside the tarball.
249 */
250const packAndPlace = Effect.fn("packAndPlace")(function* (input: {
251 readonly stageDir: string;
252 readonly packageDir: string;
253 readonly tarball: string;
254}) {
255 const fs = yield* FileSystem.FileSystem;
256 yield* fs.remove(input.tarball, { force: true });
257 yield* runCommand(
258 ChildProcess.make(yield* hostTar, ["-czf", input.tarball, "-C", input.stageDir, "package"]),
259 `tar (${input.tarball})`,
260 );
261 yield* fs.remove(input.packageDir, { recursive: true, force: true });
262 yield* fs.rename(`${input.stageDir}/package`, input.packageDir);
263});
264​
265export interface NpmPackageOutput {
266 readonly name: string;
267 readonly packageDir: string;
268 readonly tarball: string;
270​
271/**
272 * Extracts one archive, adds its package.json, and emits the package dir and
273 * tarball. The scratch dir lives inside the output dir so the extracted tree
274 * is renamed into place rather than copied across filesystems.
275 */
276const stagePlatformPackage = Effect.fn("stagePlatformPackage")(function* (input: {
277 readonly key: CliArchivePlatformKey;
278 readonly archive: string;
279 readonly outputDir: string;
280 readonly version: string;
281}) {
282 const fs = yield* FileSystem.FileSystem;
283 const path = yield* Path.Path;
284 yield* Effect.log(`[npm-packages] Extracting ${path.basename(input.archive)}...`);
285 const scratch = yield* fs.makeTempDirectoryScoped({
286 directory: input.outputDir,
287 prefix: ".extract-",
288 });
289 const extractDir = path.join(scratch, "extract");
290 yield* fs.makeDirectory(extractDir);
291 const contentDir = yield* extractArchive(input.archive, extractDir);
292 const executableName = input.key.startsWith("win32") ? "t3.exe" : "t3";
293 const executable = path.join(contentDir, executableName);
294 if (!(yield* fs.exists(executable))) {
295 return yield* new NpmPackagesArchiveLayoutError({
296 archive: path.basename(input.archive),
297 detail: `missing ${executableName} at the archive root`,
298 });
299 }
300 // The tarball carries the on-disk mode, so the bit must be set before packing.
301 if (executableName === "t3") {
302 yield* fs.chmod(executable, 0o755);
303 }
304 yield* fs.writeFileString(
305 path.join(contentDir, "package.json"),
306 `${yield* encodePackageJson(npmPlatformPackageManifest(input.key, input.version))}\n`,
307 );
308 yield* fs.writeFileString(
309 path.join(contentDir, "README.md"),
310 npmPlatformPackageReadme(input.key),
311 );
312 // npm tarballs root everything under `package/`.
313 yield* fs.rename(contentDir, path.join(scratch, "package"));
314 const name = npmPlatformPackageName(input.key);
315 const output: NpmPackageOutput = {
316 name,
317 packageDir: path.join(input.outputDir, name),
318 tarball: path.join(input.outputDir, `${name}.tgz`),
319 };
320 yield* packAndPlace({ stageDir: scratch, ...output });
321 return output;
322}, Effect.scoped);
323​
324/** Writes the launcher package (package.json, bin/t3.js, README) and its tarball. */
325const stageLauncherPackage = Effect.fn("stageLauncherPackage")(function* (input: {
326 readonly outputDir: string;
327 readonly version: string;
328 readonly platformKeys: ReadonlyArray<CliArchivePlatformKey>;
329}) {
330 const fs = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const scratch = yield* fs.makeTempDirectoryScoped({
333 directory: input.outputDir,
334 prefix: ".launcher-",
335 });
336 const stageDir = path.join(scratch, "package");
337 yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
338 yield* fs.writeFileString(
339 path.join(stageDir, "package.json"),
340 `${yield* encodePackageJson(npmLauncherPackageManifest(input.version, input.platformKeys))}\n`,
341 );
342 const launcherScript = path.join(stageDir, "bin/t3.js");
343 yield* fs.writeFileString(launcherScript, NPM_LAUNCHER_SCRIPT);
344 yield* fs.chmod(launcherScript, 0o755);
345 const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
346 if (yield* fs.exists(readme)) {
347 yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
348 }
349 const output: NpmPackageOutput = {
350 name: NPM_LAUNCHER_PACKAGE_NAME,
351 packageDir: path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME),
352 tarball: path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`),
353 };
354 yield* packAndPlace({ stageDir: scratch, ...output });
355 return output;
356}, Effect.scoped);
357​
358export const buildNpmPlatformPackages = Effect.fn("buildNpmPlatformPackages")(function* (input: {
359 readonly archivesDir: string;
360 readonly version: string;
361 readonly outputDir: string;
362 readonly allowMissing: boolean;
363}) {
364 const fs = yield* FileSystem.FileSystem;
365 const path = yield* Path.Path;
366​
367 const present = yield* fs.readDirectory(input.archivesDir);
368 const archives = CLI_ARCHIVE_PLATFORM_KEYS.flatMap((key) => {
369 const fileName = cliArchiveFileName(input.version, key);
370 return present.includes(fileName)
371 ? [{ key, archive: path.join(input.archivesDir, fileName) }]
372 : [];
373 });
374 const missing = CLI_ARCHIVE_PLATFORM_KEYS.filter(
375 (key) => !archives.some((entry) => entry.key === key),
376 );
377 if (missing.length > 0 && (!input.allowMissing || archives.length === 0)) {
378 return yield* new NpmPackagesArchivesMissingError({ archivesDir: input.archivesDir, missing });
379 }
380​
381 yield* fs.makeDirectory(path.join(input.outputDir, NPM_PLATFORM_PACKAGE_SCOPE), {
382 recursive: true,
383 });
384 const outputs: Array<NpmPackageOutput> = [];
385 for (const { key, archive } of archives) {
386 outputs.push(
387 yield* stagePlatformPackage({
388 key,
389 archive,
390 outputDir: input.outputDir,
391 version: input.version,
392 }),
393 );
394 }
395 outputs.push(
396 yield* stageLauncherPackage({
397 outputDir: input.outputDir,
398 version: input.version,
399 platformKeys: archives.map((entry) => entry.key),
400 }),
401 );
402​
403 for (const output of outputs) {
404 yield* Effect.log(`[npm-packages] Wrote ${output.packageDir} and ${output.tarball}`);
405 }
406 if (missing.length > 0) {
407 yield* Effect.logWarning(
408 `[npm-packages] Launcher omits ${missing.join(", ")} (--allow-missing).`,
409 );
410 }
411 return outputs;
412});
413​
414const command = Command.make(
415 "build-npm-platform-packages",
416 {
417 archivesDir: Flag.string("archives-dir").pipe(
418 Flag.withDescription("Directory holding the release's t3-<version>-<platform> archives."),
419 ),
420 version: Flag.string("version").pipe(
421 Flag.withDescription(
422 "Exact release version; selects the archives and versions the packages.",
423 ),
424 ),
425 outputDir: Flag.string("output-dir").pipe(Flag.withDefault("npm-packages")),
426 allowMissing: Flag.boolean("allow-missing").pipe(
427 Flag.withDefault(false),
428 Flag.withDescription("Build a launcher that lists only the platforms present."),
429 ),
430 },
431 buildNpmPlatformPackages,
432).pipe(
433 Command.withDescription(
434 "Build the t3 launcher and @t3code/t3-<platform> npm packages from CLI release archives.",
435 ),
436);
437​
438if (import.meta.main) {
439 Command.run(command, { version: "0.0.0" }).pipe(
440 Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
441 NodeRuntime.runMain,
442 );