feat(release): publish npx t3 as a launcher over per-platform executable packages (#11607)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 authored and GitHub committed 2026-09-13 21:24:24 -07:00
1 parent 2f7616ef17
commit 91cd91c087
9 files changed
+819 -261

No files matched your search

+39 -1
View File
@@ -23,6 +23,7 @@ import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -241,8 +242,33 @@ const stageRuntimeExternals = Effect.fn("stageRuntimeExternals")(function* (inpu
]) {
yield* fs.remove(path.join(input.stageDir, entry), { recursive: true, force: true });
}
// A hoisted install still leaves nested `node_modules/.bin` shim directories
// inside packages that declare bins (msgpackr-extract's). They are symlinks
// nothing runs, and the npm registry refuses a tarball that contains any
// symlink, so strip every `.bin` directory below node_modules.
yield* removeNestedBinDirectories(fs, path, path.join(input.stageDir, "node_modules"));
});
const removeNestedBinDirectories = (
fs: FileSystem.FileSystem,
path: Path.Path,
root: string,
): Effect.Effect<void, PlatformError.PlatformError> =>
Effect.gen(function* () {
const entries = yield* fs.readDirectory(root).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
const child = path.join(root, entry);
if (entry === ".bin") {
yield* fs.remove(child, { recursive: true, force: true });
continue;
}
const info = yield* fs.stat(child).pipe(Effect.option);
if (Option.isSome(info) && info.value.type === "Directory") {
yield* removeNestedBinDirectories(fs, path, child);
}
}
});
/** Copies the web client without its sourcemaps, which nothing serves. */
const stageWebClient = Effect.fn("stageWebClient")(function* (source: string, target: string) {
const fs = yield* FileSystem.FileSystem;
@@ -516,8 +542,20 @@ const buildCliArchive = Effect.fn("buildCliArchive")(function* (input: {
"tar (zip)",
);
} else {
// On Linux, pnpm hard-links identical files out of its store and node-gyp
// hard-links build outputs, and GNU tar records those as link entries.
// The npm registry rejects a tarball containing any, and the npm platform
// packages are re-packed from this archive's contents, so store every
// file as a file. macOS's bsdtar has no such flag; pnpm clones there.
yield* runCommand(
ChildProcess.make("tar", ["-czf", archivePath, "-C", stageRoot, stem]),
ChildProcess.make("tar", [
...(input.platform === "linux" ? ["--hard-dereference"] : []),
"-czf",
archivePath,
"-C",
stageRoot,
stem,
]),
"tar (gzip)",
);
}
+203
View File
@@ -0,0 +1,203 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
buildNpmPlatformPackages,
NpmPackagesArchivesMissingError,
} from "./build-npm-platform-packages.ts";
const VERSION = "1.2.3";
const decodeManifest = Schema.decodeEffect(
Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
);
const KEYS = ["linux-x64", "darwin-arm64"] as const;
const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
const run = Effect.fn("test.run")(function* (
command: string,
args: ReadonlyArray<string>,
options: { readonly cwd: string; readonly env?: Record<string, string> },
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(
ChildProcess.make(command, args, { cwd: options.cwd, env: options.env ?? {} }),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
{ concurrency: "unbounded" },
);
return { stdout, stderr, exitCode };
});
/** A tar.gz laid out like build-cli-archive.ts writes, with a stub `t3` that echoes its args. */
const makeFakeArchives = Effect.fn("test.makeFakeArchives")(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-packages-test-" });
const archivesDir = path.join(root, "archives");
yield* fs.makeDirectory(archivesDir);
for (const key of KEYS) {
const stem = `t3-${VERSION}-${key}`;
const stage = path.join(root, "stage", key);
const contentDir = path.join(stage, stem);
for (const dir of ["client", "resource-monitor", "node_modules/node-pty"]) {
yield* fs.makeDirectory(path.join(contentDir, dir), { recursive: true });
}
yield* fs.writeFileString(path.join(contentDir, "client/index.html"), "<html></html>\n");
yield* fs.writeFileString(
path.join(contentDir, "t3"),
`#!/bin/sh\necho "stub ${key} $*"\nexit 7\n`,
);
yield* fs.chmod(path.join(contentDir, "t3"), 0o755);
const exit = yield* run("tar", ["-czf", path.join(archivesDir, `${stem}.tar.gz`), stem], {
cwd: stage,
});
assert.equal(exit.exitCode, 0, exit.stderr);
}
yield* fs.writeFileString(path.join(archivesDir, "SHA256SUMS"), "");
return { root, archivesDir, outputDir: path.join(root, "out") };
});
it.layer(NodeServices.layer)("build-npm-platform-packages", (it) => {
it.effect("refuses a partial release unless --allow-missing is passed", () =>
Effect.gen(function* () {
const fixture = yield* makeFakeArchives();
const error = yield* buildNpmPlatformPackages({
...fixture,
version: VERSION,
allowMissing: false,
}).pipe(Effect.flip);
assert.instanceOf(error, NpmPackagesArchivesMissingError);
assert.deepStrictEqual((error as NpmPackagesArchivesMissingError).missing, [
"linux-arm64",
"win32-arm64",
"win32-x64",
]);
}),
);
it.effect("builds platform packages and a launcher that execs the installed one", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const fixture = yield* makeFakeArchives();
const outputs = yield* buildNpmPlatformPackages({
...fixture,
version: VERSION,
allowMissing: true,
});
// Platform packages in CLI_ARCHIVE_PLATFORM_KEYS order, launcher last.
assert.deepStrictEqual(
outputs.map((output) => output.name),
["@t3code/t3-darwin-arm64", "@t3code/t3-linux-x64", "t3"],
);
for (const output of outputs) {
assert.isTrue(yield* fs.exists(output.tarball), output.tarball);
}
const linuxDir = path.join(fixture.outputDir, "@t3code/t3-linux-x64");
const linuxManifest = yield* decodeManifest(
yield* fs.readFileString(path.join(linuxDir, "package.json")),
);
assert.equal(linuxManifest.name, "@t3code/t3-linux-x64");
assert.equal(linuxManifest.version, VERSION);
assert.deepStrictEqual(linuxManifest.os, ["linux"]);
assert.deepStrictEqual(linuxManifest.cpu, ["x64"]);
assert.deepStrictEqual(linuxManifest.files, [
"t3",
"t3.exe",
"client",
"resource-monitor",
"node_modules",
]);
assert.equal(linuxManifest.preferUnplugged, true);
assert.isUndefined(linuxManifest.bin);
// Archive contents sit at the package root, not under the archive stem.
assert.isTrue(yield* fs.exists(path.join(linuxDir, "client/index.html")));
// A root README, or npm would display a bundled dependency's.
assert.include(
yield* fs.readFileString(path.join(linuxDir, "README.md")),
"# @t3code/t3-linux-x64",
);
assert.isTrue(yield* fs.exists(path.join(linuxDir, "node_modules/node-pty")));
assert.equal(Number((yield* fs.stat(path.join(linuxDir, "t3"))).mode) & 0o111, 0o111);
const darwinManifest = yield* decodeManifest(
yield* fs.readFileString(
path.join(fixture.outputDir, "@t3code/t3-darwin-arm64/package.json"),
),
);
assert.deepStrictEqual(darwinManifest.os, ["darwin"]);
assert.deepStrictEqual(darwinManifest.cpu, ["arm64"]);
const launcherDir = path.join(fixture.outputDir, "t3");
const launcherManifest = yield* decodeManifest(
yield* fs.readFileString(path.join(launcherDir, "package.json")),
);
assert.equal(launcherManifest.name, "t3");
assert.equal(launcherManifest.version, VERSION);
assert.deepStrictEqual(launcherManifest.bin, { t3: "./bin/t3.js" });
assert.deepStrictEqual(launcherManifest.files, ["bin"]);
assert.deepStrictEqual(launcherManifest.optionalDependencies, {
"@t3code/t3-darwin-arm64": VERSION,
"@t3code/t3-linux-x64": VERSION,
});
assert.isUndefined(launcherManifest.engines);
assert.isTrue(yield* fs.exists(path.join(launcherDir, "bin/t3.js")));
// The scratch dirs must not be left behind next to the packages.
const outputEntries = yield* fs.readDirectory(fixture.outputDir);
assert.deepStrictEqual(outputEntries.sort(), ["@t3code", "t3", "t3.tgz"]);
// The tarball is what gets published: it must carry node_modules (which
// `npm publish <dir>` would strip) under npm's `package/` root, with the
// executable bit intact.
const listing = yield* run(
"tar",
["-tzvf", path.join(fixture.outputDir, "@t3code/t3-linux-x64.tgz")],
{ cwd: fixture.outputDir },
);
assert.equal(listing.exitCode, 0, listing.stderr);
const lines = listing.stdout.split("\n");
assert.isTrue(lines.some((line) => line.endsWith(" package/node_modules/node-pty/")));
assert.isTrue(lines.some((line) => line.endsWith(" package/package.json")));
assert.isTrue(
lines.some((line) => /^-rwxr-xr-x .* package\/t3$/.test(line)),
listing.stdout,
);
// NODE_PATH stands in for node_modules: require.resolve finds the
// platform package there exactly as it would after `npm install`.
const env = { ...process.env, NODE_PATH: fixture.outputDir } as Record<string, string>;
const passthrough = yield* run(process.execPath, ["bin/t3.js", "serve", "--port", "1234"], {
cwd: launcherDir,
env,
});
assert.equal(passthrough.stdout.trim(), "stub linux-x64 serve --port 1234");
assert.equal(passthrough.exitCode, 7);
const unsupported = yield* run(process.execPath, ["bin/t3.js", "--version"], {
cwd: launcherDir,
env: { ...env, NODE_PATH: path.join(fixture.root, "nowhere") },
});
assert.equal(unsupported.exitCode, 1);
assert.include(unsupported.stderr, "linux-x64");
assert.include(unsupported.stderr, "win32-arm64");
assert.include(unsupported.stderr, "https://github.com/pingdotgg/t3code/releases");
}),
);
});
+443
View File
@@ -0,0 +1,443 @@
#!/usr/bin/env node
/**
* Turns the per-platform CLI archives of one release into the npm packages
* behind `npx t3` / `npm i -g t3`: one `@t3code/t3-<platformKey>` package per
* archive holding the archive's contents verbatim, plus the `t3` launcher
* that lists them as optionalDependencies and execs the one npm installed.
* The bytes a user gets from npm are therefore the release archive's, and
* running them needs neither a Node runtime, npm, nor a native build.
*
* Output layout under `--output-dir`:
*
* @t3code/t3-<platformKey>/ archive contents flattened + package.json
* @t3code/t3-<platformKey>.tgz the same tree as an npm tarball
* t3/ launcher: package.json, bin/t3.js, README.md
* t3.tgz the launcher as an npm tarball
*
* The tarballs are what gets published. `npm publish <dir>` always drops
* `node_modules/` (npm-packlist ignores it whatever `files` says, and
* bundleDependencies needs an arborist tree these flattened installs are
* not), whereas `npm publish <tarball>` uploads the bytes as given.
*/
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
CLI_ARCHIVE_PLATFORM_KEYS,
cliArchiveFileName,
type CliArchivePlatformKey,
} from "@t3tools/shared/cliRelease";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import { isCommandAvailable } from "@t3tools/shared/shell";
import serverPackageJson from "../apps/server/package.json" with { type: "json" };
import { windowsSystemTar } from "./build-cli-archive.ts";
export const NPM_PLATFORM_PACKAGE_SCOPE = "@t3code";
export const NPM_LAUNCHER_PACKAGE_NAME = "t3";
const encodePackageJson = Schema.encodeEffect(fromJsonStringPretty(Schema.Unknown));
export class NpmPackagesCommandFailedError extends Schema.TaggedError<NpmPackagesCommandFailedError>()(
"NpmPackagesCommandFailedError",
{ command: Schema.String, exitCode: Schema.Int },
) {
override get message(): string {
return `${this.command} exited with code ${this.exitCode}.`;
}
}
export class NpmPackagesToolMissingError extends Schema.TaggedError<NpmPackagesToolMissingError>()(
"NpmPackagesToolMissingError",
{ tool: Schema.String, purpose: Schema.String },
) {
override get message(): string {
return `\`${this.tool}\` is not on PATH; it is needed to ${this.purpose}.`;
}
}
export class NpmPackagesArchivesMissingError extends Schema.TaggedError<NpmPackagesArchivesMissingError>()(
"NpmPackagesArchivesMissingError",
{ archivesDir: Schema.String, missing: Schema.Array(Schema.String) },
) {
override get message(): string {
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.`;
}
}
export class NpmPackagesArchiveLayoutError extends Schema.TaggedError<NpmPackagesArchiveLayoutError>()(
"NpmPackagesArchiveLayoutError",
{ archive: Schema.String, detail: Schema.String },
) {
override get message(): string {
return `${this.archive}: ${this.detail}`;
}
}
export function npmPlatformPackageName(platformKey: CliArchivePlatformKey): string {
return `${NPM_PLATFORM_PACKAGE_SCOPE}/t3-${platformKey}`;
}
/** package.json for one platform package; `os`/`cpu` let npm skip the other five. */
export function npmPlatformPackageManifest(platformKey: CliArchivePlatformKey, version: string) {
const [os, cpu] = platformKey.split("-") as [string, string];
return {
name: npmPlatformPackageName(platformKey),
version,
description: `T3 Code CLI executable for ${platformKey}`,
license: serverPackageJson.license,
repository: serverPackageJson.repository,
os: [os],
cpu: [cpu],
files: ["t3", "t3.exe", "client", "resource-monitor", "node_modules"],
preferUnplugged: true,
};
}
/**
* README for one platform package. Without one at the package root, npm
* shows the first README it finds in the tarball, which is a bundled
* dependency's (ffi-rs).
*/
export function npmPlatformPackageReadme(platformKey: CliArchivePlatformKey): string {
return [
`# ${npmPlatformPackageName(platformKey)}`,
"",
`The T3 Code CLI executable for ${platformKey}. Do not install this package directly:`,
`it is an optional dependency of \`${NPM_LAUNCHER_PACKAGE_NAME}\`, which picks the package for the`,
"current platform and runs the executable inside it.",
"",
"```sh",
`npx ${NPM_LAUNCHER_PACKAGE_NAME}@latest`,
"```",
"",
"Source and documentation: https://github.com/pingdotgg/t3code",
"",
].join("\n");
}
/** package.json for the `t3` launcher. No engines: bin/t3.js is trivial CJS. */
export function npmLauncherPackageManifest(
version: string,
platformKeys: ReadonlyArray<CliArchivePlatformKey>,
) {
return {
name: NPM_LAUNCHER_PACKAGE_NAME,
version,
description: "T3 Code CLI. Installs the self-contained executable for this platform.",
license: serverPackageJson.license,
repository: serverPackageJson.repository,
bin: { t3: "./bin/t3.js" },
files: ["bin"],
optionalDependencies: Object.fromEntries(
platformKeys.map((key) => [npmPlatformPackageName(key), version]),
),
};
}
/**
* The launcher every `npx t3` runs. Plain CommonJS with no dependencies so it
* loads on any Node that npm itself runs on; the real work happens in the
* single-executable it execs.
*/
export const NPM_LAUNCHER_SCRIPT = `#!/usr/bin/env node
"use strict";
const { spawnSync } = require("node:child_process");
const { constants } = require("node:os");
const { dirname, join } = require("node:path");
const SUPPORTED = [${CLI_ARCHIVE_PLATFORM_KEYS.map((key) => `"${key}"`).join(", ")}];
const key = process.platform + "-" + process.arch;
let packageDir;
try {
packageDir = dirname(require.resolve("${NPM_PLATFORM_PACKAGE_SCOPE}/t3-" + key + "/package.json"));
} catch {
process.stderr.write(
[
"t3: no T3 Code CLI build is available for this platform (" + key + ").",
"Supported platforms: " + SUPPORTED.join(", ") + ".",
"If yours is listed, reinstall t3 so npm fetches its optional dependency.",
"The desktop app and release archives are at https://github.com/pingdotgg/t3code/releases",
"",
].join("\\n"),
);
process.exit(1);
}
const executable = join(packageDir, process.platform === "win32" ? "t3.exe" : "t3");
const result = spawnSync(executable, process.argv.slice(2), { stdio: "inherit" });
if (result.error) {
process.stderr.write("t3: failed to start " + executable + ": " + result.error.message + "\\n");
process.exit(1);
}
// A child killed by a signal has no status; report it the way a shell would.
process.exit(result.status ?? 128 + (constants.signals[result.signal] || 1));
`;
const runCommand = Effect.fn("runCommand")(function* (
command: ChildProcess.StandardCommand,
label: string,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(
ChildProcess.make(command.command, command.args, {
...command.options,
stdout: "inherit",
stderr: "inherit",
}),
);
const exitCode = Number(yield* child.exitCode);
if (exitCode !== 0) {
return yield* new NpmPackagesCommandFailedError({ command: label, exitCode });
}
});
/**
* Extracts an archive and returns its single top-level directory. `.tar.gz`
* goes through tar everywhere; `.zip` through the bsdtar Windows ships or,
* elsewhere, `unzip`, since GNU tar cannot read zip.
*/
const extractArchive = Effect.fn("extractArchive")(function* (archive: string, into: string) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const platform = yield* HostProcessPlatform;
if (!archive.endsWith(".zip")) {
yield* runCommand(ChildProcess.make("tar", ["-xf", archive, "-C", into]), "tar -xf");
} else if (platform === "win32") {
yield* runCommand(
ChildProcess.make(windowsSystemTar(), ["-xf", archive, "-C", into]),
"tar.exe -xf (zip)",
);
} else {
if (!(yield* isCommandAvailable("unzip"))) {
return yield* new NpmPackagesToolMissingError({
tool: "unzip",
purpose: `extract ${path.basename(archive)} (GNU tar cannot read zip)`,
});
}
yield* runCommand(ChildProcess.make("unzip", ["-q", archive, "-d", into]), "unzip");
}
const entries = yield* fs.readDirectory(into);
const [root] = entries;
if (root === undefined || entries.length !== 1) {
return yield* new NpmPackagesArchiveLayoutError({
archive: path.basename(archive),
detail: `expected exactly one top-level directory, found ${String(entries.length)} entries`,
});
}
return path.join(into, root);
});
/** Tar to build npm tarballs with; see build-cli-archive.ts for why Windows names bsdtar by path. */
const hostTar = Effect.map(HostProcessPlatform, (platform) =>
platform === "win32" ? windowsSystemTar() : "tar",
);
/**
* Writes `stageDir/package` as a gzipped npm tarball and then moves the tree
* to `packageDir` so the contents stay inspectable beside the tarball.
*/
const packAndPlace = Effect.fn("packAndPlace")(function* (input: {
readonly stageDir: string;
readonly packageDir: string;
readonly tarball: string;
}) {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(input.tarball, { force: true });
yield* runCommand(
ChildProcess.make(yield* hostTar, ["-czf", input.tarball, "-C", input.stageDir, "package"]),
`tar (${input.tarball})`,
);
yield* fs.remove(input.packageDir, { recursive: true, force: true });
yield* fs.rename(`${input.stageDir}/package`, input.packageDir);
});
export interface NpmPackageOutput {
readonly name: string;
readonly packageDir: string;
readonly tarball: string;
}
/**
* Extracts one archive, adds its package.json, and emits the package dir and
* tarball. The scratch dir lives inside the output dir so the extracted tree
* is renamed into place rather than copied across filesystems.
*/
const stagePlatformPackage = Effect.fn("stagePlatformPackage")(function* (input: {
readonly key: CliArchivePlatformKey;
readonly archive: string;
readonly outputDir: string;
readonly version: string;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* Effect.log(`[npm-packages] Extracting ${path.basename(input.archive)}...`);
const scratch = yield* fs.makeTempDirectoryScoped({
directory: input.outputDir,
prefix: ".extract-",
});
const extractDir = path.join(scratch, "extract");
yield* fs.makeDirectory(extractDir);
const contentDir = yield* extractArchive(input.archive, extractDir);
const executableName = input.key.startsWith("win32") ? "t3.exe" : "t3";
const executable = path.join(contentDir, executableName);
if (!(yield* fs.exists(executable))) {
return yield* new NpmPackagesArchiveLayoutError({
archive: path.basename(input.archive),
detail: `missing ${executableName} at the archive root`,
});
}
// The tarball carries the on-disk mode, so the bit must be set before packing.
if (executableName === "t3") {
yield* fs.chmod(executable, 0o755);
}
yield* fs.writeFileString(
path.join(contentDir, "package.json"),
`${yield* encodePackageJson(npmPlatformPackageManifest(input.key, input.version))}\n`,
);
yield* fs.writeFileString(
path.join(contentDir, "README.md"),
npmPlatformPackageReadme(input.key),
);
// npm tarballs root everything under `package/`.
yield* fs.rename(contentDir, path.join(scratch, "package"));
const name = npmPlatformPackageName(input.key);
const output: NpmPackageOutput = {
name,
packageDir: path.join(input.outputDir, name),
tarball: path.join(input.outputDir, `${name}.tgz`),
};
yield* packAndPlace({ stageDir: scratch, ...output });
return output;
}, Effect.scoped);
/** Writes the launcher package (package.json, bin/t3.js, README) and its tarball. */
const stageLauncherPackage = Effect.fn("stageLauncherPackage")(function* (input: {
readonly outputDir: string;
readonly version: string;
readonly platformKeys: ReadonlyArray<CliArchivePlatformKey>;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const scratch = yield* fs.makeTempDirectoryScoped({
directory: input.outputDir,
prefix: ".launcher-",
});
const stageDir = path.join(scratch, "package");
yield* fs.makeDirectory(path.join(stageDir, "bin"), { recursive: true });
yield* fs.writeFileString(
path.join(stageDir, "package.json"),
`${yield* encodePackageJson(npmLauncherPackageManifest(input.version, input.platformKeys))}\n`,
);
const launcherScript = path.join(stageDir, "bin/t3.js");
yield* fs.writeFileString(launcherScript, NPM_LAUNCHER_SCRIPT);
yield* fs.chmod(launcherScript, 0o755);
const readme = yield* path.fromFileUrl(new URL("../apps/server/README.md", import.meta.url));
if (yield* fs.exists(readme)) {
yield* fs.copyFile(readme, path.join(stageDir, "README.md"));
}
const output: NpmPackageOutput = {
name: NPM_LAUNCHER_PACKAGE_NAME,
packageDir: path.join(input.outputDir, NPM_LAUNCHER_PACKAGE_NAME),
tarball: path.join(input.outputDir, `${NPM_LAUNCHER_PACKAGE_NAME}.tgz`),
};
yield* packAndPlace({ stageDir: scratch, ...output });
return output;
}, Effect.scoped);
export const buildNpmPlatformPackages = Effect.fn("buildNpmPlatformPackages")(function* (input: {
readonly archivesDir: string;
readonly version: string;
readonly outputDir: string;
readonly allowMissing: boolean;
}) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const present = yield* fs.readDirectory(input.archivesDir);
const archives = CLI_ARCHIVE_PLATFORM_KEYS.flatMap((key) => {
const fileName = cliArchiveFileName(input.version, key);
return present.includes(fileName)
? [{ key, archive: path.join(input.archivesDir, fileName) }]
: [];
});
const missing = CLI_ARCHIVE_PLATFORM_KEYS.filter(
(key) => !archives.some((entry) => entry.key === key),
);
if (missing.length > 0 && (!input.allowMissing || archives.length === 0)) {
return yield* new NpmPackagesArchivesMissingError({ archivesDir: input.archivesDir, missing });
}
yield* fs.makeDirectory(path.join(input.outputDir, NPM_PLATFORM_PACKAGE_SCOPE), {
recursive: true,
});
const outputs: Array<NpmPackageOutput> = [];
for (const { key, archive } of archives) {
outputs.push(
yield* stagePlatformPackage({
key,
archive,
outputDir: input.outputDir,
version: input.version,
}),
);
}
outputs.push(
yield* stageLauncherPackage({
outputDir: input.outputDir,
version: input.version,
platformKeys: archives.map((entry) => entry.key),
}),
);
for (const output of outputs) {
yield* Effect.log(`[npm-packages] Wrote ${output.packageDir} and ${output.tarball}`);
}
if (missing.length > 0) {
yield* Effect.logWarning(
`[npm-packages] Launcher omits ${missing.join(", ")} (--allow-missing).`,
);
}
return outputs;
});
const command = Command.make(
"build-npm-platform-packages",
{
archivesDir: Flag.string("archives-dir").pipe(
Flag.withDescription("Directory holding the release's t3-<version>-<platform> archives."),
),
version: Flag.string("version").pipe(
Flag.withDescription(
"Exact release version; selects the archives and versions the packages.",
),
),
outputDir: Flag.string("output-dir").pipe(Flag.withDefault("npm-packages")),
allowMissing: Flag.boolean("allow-missing").pipe(
Flag.withDefault(false),
Flag.withDescription("Build a launcher that lists only the platforms present."),
),
},
buildNpmPlatformPackages,
).pipe(
Command.withDescription(
"Build the t3 launcher and @t3code/t3-<platform> npm packages from CLI release archives.",
),
);
if (import.meta.main) {
Command.run(command, { version: "0.0.0" }).pipe(
Effect.provide(Layer.mergeAll(Logger.layer([Logger.consolePretty()]), NodeServices.layer)),
NodeRuntime.runMain,
);
}