release.ts
This file
Path
scripts/lib/release.ts
431 lines · 13.2 KiB · TypeScript
Last changed by
Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
History of this fileTake it
The walk stopped after 200 commits: lines older than 1c958b4 point at it.
Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 1–18why, one step back1import type { Brand } from "@repo/brand";2import { detectHarness } from "@repo/protocol/audit";3import { Array as Arr, Option, Order, Predicate, Result, Schema } from "effect";45import { ReleaseManifest } from "../../apps/platform/src/releases.ts";6import { declaredStage, NoStage, UnknownStage } from "../../infra/stages.ts";7import { installScriptFor } from "./release/install-script.ts";89export type Target = "bun-linux-x64" | "bun-darwin-arm64";1011export const targets: readonly Target[] = ["bun-linux-x64", "bun-darwin-arm64"];1213export const machineOf = (target: Target) => target.replace(/^bun-/u, "");1415export const binaryName = (brand: typeof Brand, target: Target) =>16 `${brand.slug}-${machineOf(target)}`;1718/**Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 19–21why, one step back19 * A module statement as rolldown writes one, at the start of a line. A20 * template literal's line that starts with `import` and names a package is21 * read as an import too, which fails the pin loudly rather than slip through.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 22–33why, one step back22 */23const STATEMENT =24 /^(?:import|export)\b[^;"'`]*?\bfrom\s*["'](?<from>[^"']+)["']|^import\s*["'](?<bare>[^"']+)["']/gmu;2526const packageOf = (specifier: string) =>27 specifier28 .split("/")29 .slice(0, specifier.startsWith("@") ? 2 : 1)30 .join("/");3132const isPackage = (specifier: string) => !/^(?:\.|\/|node:)/u.test(specifier);33Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 34why, one step back34/** Static imports only: a package reached only by a dynamic `import()` is not listed. */Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 35–46why, one step back35export const importedPackages = (source: string): readonly string[] =>36 Arr.sort(37 Arr.dedupe(38 [...source.matchAll(STATEMENT)].flatMap(({ groups }) => {39 const specifier = groups?.from ?? groups?.bare ?? "";4041 return isPackage(specifier) ? [packageOf(specifier)] : [];42 })43 ),44 Order.String45 );46Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 47why, one step back47/** The host the package plugs into: an optional peer, never bundled or depended on. */Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 48–96why, one step back48const PI_HOST = "@earendil-works/pi-coding-agent";4950export class Unpinned extends Schema.TaggedError<Unpinned>()("Unpinned", {51 packages: Schema.Array(Schema.String),52}) {}5354const pinOf = (55 specifier: string | undefined,56 catalogued: string | undefined57) => {58 const version = specifier === "catalog:" ? catalogued : specifier;5960 return version === undefined || /^(?:workspace|catalog):/u.test(version)61 ? undefined62 : version;63};6465export const pinnedDependencies = (input: {66 readonly imported: readonly string[];67 readonly declared: Readonly<Record<string, string>>;68 readonly catalog: Readonly<Record<string, string>>;69}): Result.Result<Readonly<Record<string, string>>, Unpinned> => {70 const pins = input.imported71 .filter((name) => name !== PI_HOST)72 .map(73 (name) =>74 [75 name,76 name.startsWith("@repo/")77 ? undefined78 : pinOf(input.declared[name], input.catalog[name]),79 ] as const80 );8182 const unpinned = pins.flatMap(([name, version]) =>83 version === undefined ? [name] : []84 );8586 return unpinned.length > 087 ? Result.fail(new Unpinned({ packages: unpinned }))88 : Result.succeed(89 Object.fromEntries(90 pins.flatMap(([name, version]) =>91 version === undefined ? [] : [[name, version]]92 )93 )94 );95};96Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
lines 97–98why, one step back97// `exports` takes the path with `./`; `bin` takes npm's normal form without98// it, which `npm publish` would otherwise rewrite with a warning.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 99–100why, one step back99const BIN = "./dist/bin.js";100Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
lines 101–102why, one step back101const BIN_TARGET = "dist/bin.js";102Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 103–137why, one step back103interface LibraryEntry {104 readonly types: string;105 readonly default: string;106}107108export interface PublishManifest {109 readonly bin: Readonly<Record<string, string>>;110 readonly dependencies: Readonly<Record<string, string>>;111 readonly description: string;112 readonly exports: Readonly<Record<string, string | LibraryEntry>>;113 readonly files: readonly string[];114 readonly keywords: readonly string[];115 readonly license: "MIT";116 readonly name: string;117 readonly peerDependencies: Readonly<Record<string, string>>;118 readonly peerDependenciesMeta: Readonly<119 Record<string, { readonly optional: boolean }>120 >;121 readonly pi: {122 readonly extensions: readonly string[];123 readonly skills: readonly string[];124 };125 readonly publishConfig: { readonly access: "public" };126 readonly type: "module";127 readonly version: string;128}129130const library = (name: "protocol" | "rules"): LibraryEntry =>131 // oxlint-disable-next-line sort-keys -- Node matches export conditions in key order and needs "default" last; TypeScript reads "types" only before it132 ({133 types: `./dist/${name}.d.ts`,134 default: `./dist/${name}.js`,135 });136137/**Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 138–139why, one step back138 * Both bins point at one entry, which reads its own name to act as git's139 * credential helper. The `pi` key and `pi-package` keyword make it a pi package.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 140–147why, one step back140 */141export const publishManifest = (142 brand: typeof Brand,143 input: {144 readonly version: string;145 readonly dependencies: Readonly<Record<string, string>>;146 }147): PublishManifest => ({Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
line 148why, one step back148 bin: { [brand.cli]: BIN_TARGET, [brand.gitCredentialHelper]: BIN_TARGET },Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 149–201why, one step back149 dependencies: input.dependencies,150 description: `The ${brand.name} command line: find an ask, claim it, check your answer, and read its verdict; also git's credential helper, and a pi package.`,151 exports: {152 ".": BIN,153 "./protocol": library("protocol"),154 "./rules": library("rules"),155 },156 files: ["dist/", "skills/", "README.md", "LICENSE"],157 keywords: [brand.slug, "cli", "git", "pi-package"],158 license: "MIT",159 name: brand.cliPackage,160 peerDependencies: { [PI_HOST]: "*" },161 peerDependenciesMeta: { [PI_HOST]: { optional: true } },162 pi: { extensions: ["./dist/pi.js"], skills: ["./skills"] },163 publishConfig: { access: "public" },164 type: "module",165 version: input.version,166});167168const fromRoot = (file: string) =>169 file.replace(/^\.\//u, "").replace(/\/$/u, "");170171export const namedFiles = (manifest: PublishManifest): readonly string[] =>172 Arr.sort(173 Arr.dedupe(174 [175 ...Object.values(manifest.bin),176 ...Object.values(manifest.exports).flatMap((entry) =>177 Predicate.isString(entry) ? [entry] : [entry.default, entry.types]178 ),179 ...manifest.pi.extensions,180 ...manifest.pi.skills,181 ...manifest.files.filter((file) => !file.endsWith("/")),182 ].map(fromRoot)183 ),184 Order.String185 );186187export type ReleaseStep =188 | "tsdown"189 | "manifest"190 | "copySkills"191 | "compile"192 | "installScript"193 | "checksums"194 | "upload"195 | "publish";196197export class PublishNeedsAPerson extends Schema.TaggedError<PublishNeedsAPerson>()(198 "PublishNeedsAPerson",199 { markers: Schema.Array(Schema.String) }200) {}201Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 202why, one step back202// Reads `detectHarness`'s table rather than copying it.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 203–229why, one step back203export const agentMarkers = (204 env: Readonly<Record<string, string | undefined>>205): readonly string[] =>206 Arr.sort(207 Object.keys(env).filter(208 (key) => detectHarness({ [key]: env[key] }).harness !== undefined209 ),210 Order.String211 );212213const BUILD: readonly ReleaseStep[] = [214 "tsdown",215 "manifest",216 "copySkills",217 "compile",218];219220const RELEASE_FILES: readonly ReleaseStep[] = ["installScript", "checksums"];221222export interface ReleaseFlags {223 readonly build: boolean;224 readonly upload: boolean;225 readonly stage?: string;226 readonly publish: boolean;227 readonly env: Readonly<Record<string, string | undefined>>;228}229Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
lines 230–231why, one step back230// A publish reads the stage's release manifest, so it names its stage even231// when it is handed to a person: `runsPublish` is whether this run runs it.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
line 232why, one step back232const stepsOf = (Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
lines 233–234why, one step back233 flags: ReleaseFlags,234 runsPublish = flags.publishDeploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
line 235why, one step back235): Result.Result<readonly ReleaseStep[], NoStage | UnknownStage> => {Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
line 236why, one step back236 if (flags.stage === undefined && (flags.upload || flags.publish)) {Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 237–247why, one step back237 return Result.fail(new NoStage());238 }239240 if (flags.stage !== undefined && Option.isNone(declaredStage(flags.stage))) {241 return Result.fail(new UnknownStage({ stage: flags.stage }));242 }243244 return Result.succeed([245 ...(flags.build ? BUILD : []),246 ...(flags.build || flags.upload ? RELEASE_FILES : []),247 ...(flags.upload ? (["upload"] as const) : []),Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
line 248why, one step back248 ...(runsPublish ? (["publish"] as const) : []),Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 249–270why, one step back249 ]);250};251252export const releasePlan = (253 flags: ReleaseFlags254): Result.Result<255 readonly ReleaseStep[],256 PublishNeedsAPerson | NoStage | UnknownStage257> => {258 const markers = flags.publish ? agentMarkers(flags.env) : [];259260 return markers.length > 0261 ? Result.fail(new PublishNeedsAPerson({ markers }))262 : stepsOf(flags);263};264265export interface ReleaseRun {266 readonly steps: readonly ReleaseStep[];267 readonly handOver: readonly string[];268}269270/**Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
lines 271–272why, one step back271 * Under an agent, a run that publishes still runs every other step it names272 * and hands the publish to a person instead of running it.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 273–279why, one step back273 */274export const releaseRun = (275 flags: ReleaseFlags276): Result.Result<ReleaseRun, NoStage | UnknownStage> => {277 const handOver = flags.publish ? agentMarkers(flags.env) : [];278279 return Result.map(Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
line 280why, one step back280 stepsOf(flags, flags.publish && handOver.length === 0),Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 281–369why, one step back281 (steps) => ({ handOver, steps })282 );283};284285export class VersionNeeded extends Schema.TaggedError<VersionNeeded>()(286 "VersionNeeded",287 { given: Schema.optionalKey(Schema.String) }288) {289 override get message() {290 return this.given === undefined291 ? "an upload or a publish names its --version (semver, such as 0.1.0)"292 : `--version ${this.given} is not a version the platform serves (semver, such as 0.1.0)`;293 }294}295296const served = (version: string) =>297 Option.isSome(298 Schema.decodeOption(ReleaseManifest)({299 latest: version,300 versions: { [version]: { assets: {} } },301 })302 );303304const UNRELEASED = "0.0.0";305306export const releaseVersion = (input: {307 readonly version?: string;308 readonly upload: boolean;309 readonly publish: boolean;310}): Result.Result<string, VersionNeeded> => {311 if (input.version === undefined) {312 return input.upload || input.publish313 ? Result.fail(new VersionNeeded({}))314 : Result.succeed(UNRELEASED);315 }316317 return served(input.version)318 ? Result.succeed(input.version)319 : Result.fail(new VersionNeeded({ given: input.version }));320};321322export interface ReleaseAsset {323 readonly sha256: string;324 readonly bytes: number;325}326327export { ReleaseManifest } from "../../apps/platform/src/releases.ts";328329export const releaseManifest = (input: {330 readonly version: string;331 readonly previous: ReleaseManifest | undefined;332 readonly assets: Readonly<Record<string, ReleaseAsset>>;333}): ReleaseManifest => ({334 latest: input.version,335 versions: {336 ...input.previous?.versions,337 [input.version]: { assets: input.assets },338 },339});340341export class VersionReleased extends Schema.TaggedError<VersionReleased>()(342 "VersionReleased",343 { version: Schema.String }344) {345 override get message() {346 return `${this.version} is already released with other bytes, and its files are cached for good: release a new --version`;347 }348}349350const sameAssets = (351 one: Readonly<Record<string, ReleaseAsset>>,352 other: Readonly<Record<string, ReleaseAsset>>353) =>354 Object.keys(one).length === Object.keys(other).length &&355 Object.entries(one).every(356 ([name, { bytes, sha256 }]) =>357 other[name]?.bytes === bytes && other[name]?.sha256 === sha256358 );359360export const unreleased = (input: {361 readonly version: string;362 readonly previous: ReleaseManifest | undefined;363 readonly assets: Readonly<Record<string, ReleaseAsset>>;364}): Result.Result<void, VersionReleased> => {365 const released = input.previous?.versions[input.version];366367 return released === undefined || sameAssets(released.assets, input.assets)368 ? Result.void369 : Result.fail(new VersionReleased({ version: input.version }));Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953
lines 370–400why, one step back370};371372export class NotServedAsLatest extends Schema.TaggedError<NotServedAsLatest>()(373 "NotServedAsLatest",374 { latest: Schema.optionalKey(Schema.String), version: Schema.String }375) {376 override get message() {377 const serves =378 this.latest === undefined ? "serves no release" : `serves ${this.latest}`;379380 return `npm gets only the version the stage's install script serves as latest, and it ${serves}, not ${this.version}: upload --version ${this.version} to the stage first, or in the same run`;381 }382}383384/** npm and the install script give one version: the stage's latest. */385export const servedAsLatest = (input: {386 readonly version: string;387 readonly manifest: ReleaseManifest | undefined;388}): Result.Result<void, NotServedAsLatest> => {389 if (input.manifest === undefined) {390 return Result.fail(new NotServedAsLatest({ version: input.version }));391 }392393 return input.manifest.latest === input.version394 ? Result.void395 : Result.fail(396 new NotServedAsLatest({397 latest: input.manifest.latest,398 version: input.version,399 })400 );Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 401–414why, one step back401};402403export const MANIFEST_KEY = "releases/manifest.json";404405const byName = <A>(record: Readonly<Record<string, A>>) =>406 Arr.sortWith(Object.entries(record), ([name]) => name, Order.String);407408export const checksumsFile = (409 assets: Readonly<Record<string, ReleaseAsset>>410): string =>411 byName(assets)412 .map(([name, { sha256 }]) => `${sha256} ${name}\n`)413 .join("");414Merge build/comments-ops into mainoscabrielbefore adoptione4c407e
line 415why, one step back415// The manifest goes last, so it never names a file the bucket lacks.Deploy and seed the demo stage, and make the deployed-web check wait for the platform's rowsoscabrielbefore adoption1c958b4
lines 416–431why, one step back416export const uploads = (input: {417 readonly version: string;418 readonly files: readonly string[];419}): readonly { readonly file: string; readonly key: string }[] => [420 ...Arr.sort(input.files, Order.String).map((file) => ({421 file,422 key: `releases/${input.version}/${file}`,423 })),424 { file: "manifest.json", key: MANIFEST_KEY },425];426427export const installScript = (input: {428 readonly brand: typeof Brand;429 readonly version: string;430 readonly baseUrl: string;431}): string => installScriptFor({ ...input, machines: targets.map(machineOf) });