Skip to content
Myr

steps.ts

This file

Path

scripts/lib/release/steps.ts

611 lines · 16.2 KiB · TypeScript

Last changed by

Merge examples/cli-dev-dependency into mainoscabrielbefore adoption83ea953

History of this file

Take it

1import { commandDocs } from "@repo/agent-kit/command-doc";2import { platformSkill } from "@repo/agent-kit/platform";3import { Brand } from "@repo/brand";4import { Contracts } from "@repo/protocol/contracts";5import {6  Array as Arr,7  Console,8  Crypto,9  Effect,10  FileSystem,11  Match,12  Option,13  Order,14  Path,15  Schema,16  Stream,17} from "effect";18import { ChildProcess, ChildProcessSpawner } from "effect/process";1920import { resources } from "../../../infra/stages.ts";21import type { Stage } from "../../../infra/stages.ts";22import {23  binaryName,24  checksumsFile,25  importedPackages,26  installScript,27  machineOf,28  MANIFEST_KEY,29  namedFiles,30  pinnedDependencies,31  publishManifest,32  ReleaseManifest,33  releaseManifest,34  servedAsLatest,35  targets,36  unreleased,37  uploads,38} from "../release.ts";39import type { ReleaseAsset, ReleaseStep } from "../release.ts";40import { packageReadme } from "./readme.ts";4142export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(43  "ReleaseFailed",44  { reason: Schema.String, step: Schema.String }45) {46  override get message() {47    return `${this.step}: ${this.reason}`;48  }49}5051export interface Layout {52  readonly root: string;53  readonly cli: string;54  readonly dist: string;55  readonly release: string;56  /** Staged outside `dist/`, whose `bin/` holds the binaries npm must not ship. */57  readonly npm: string;58}5960export const layoutOf = (root: string) =>61  Effect.map(Path.Path, (path): Layout => {62    const cli = path.join(root, "apps", "cli");63    const release = path.join(cli, "release");6465    return {66      cli,67      dist: path.join(cli, "dist"),68      npm: path.join(release, "npm"),69      release,70      root,71    };72  });7374export interface Release {75  readonly version: string;76  readonly origin: string;77  readonly stage: Option.Option<Stage>;78}7980export const publishCommand = (layout: Layout, path: Path.Path) =>81  `npm publish ${path.relative(layout.root, layout.npm)} --access public`;8283const failed = (step: ReleaseStep, reason: string) =>84  new ReleaseFailed({ reason, step });8586const run = (87  step: ReleaseStep,88  command: string,89  args: readonly string[],90  cwd: string91) =>92  Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>93    spawner.exitCode(94      ChildProcess.make(command, args, {95        cwd,96        stderr: "inherit",97        stdin: "inherit",98        stdout: "inherit",99      })100    )101  ).pipe(102    Effect.mapError(({ message }) => failed(step, message)),103    Effect.filterOrFail(104      (exitCode) => exitCode === 0,105      (exitCode) =>106        failed(step, `${command} ${args.join(" ")} exited ${exitCode}`)107    ),108    Effect.asVoid109  );110111const PackageJson = Schema.fromJsonString(112  Schema.Struct({113    dependencies: Schema.optionalKey(114      Schema.Record(Schema.String, Schema.String)115    ),116    version: Schema.optionalKey(Schema.String),117    workspaces: Schema.optionalKey(118      Schema.Struct({119        catalog: Schema.optionalKey(120          Schema.Record(Schema.String, Schema.String)121        ),122      })123    ),124  })125);126127const readPackage = (step: ReleaseStep, file: string) =>128  Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(file)).pipe(129    Effect.flatMap(Schema.decodeEffect(PackageJson)),130    Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))131  );132133const builtFiles = (layout: Layout) =>134  Effect.gen(function* () {135    const fs = yield* FileSystem.FileSystem;136    const path = yield* Path.Path;137    const names = yield* fs.readDirectory(layout.dist);138139    const files = yield* Effect.filter(140      names.filter((name) => /\.(?:js|d\.ts)$/u.test(name)),141      (name) =>142        Effect.map(143          fs.stat(path.join(layout.dist, name)),144          ({ type }) => type === "File"145        )146    );147148    return Arr.sort(files, Order.String);149  });150151const stagePackage = (layout: Layout, release: Release) =>152  Effect.gen(function* () {153    const fs = yield* FileSystem.FileSystem;154    const path = yield* Path.Path;155156    const files = yield* builtFiles(layout).pipe(157      Effect.filterOrFail(158        (names) => names.includes("bin.js"),159        () =>160          failed(161            "manifest",162            "apps/cli/dist has no bin.js: build first (--build)"163          )164      )165    );166167    yield* fs.remove(layout.npm, { force: true, recursive: true });168    yield* fs.makeDirectory(path.join(layout.npm, "dist"), { recursive: true });169170    const sources = yield* Effect.forEach(files, (name) =>171      fs172        .copyFile(173          path.join(layout.dist, name),174          path.join(layout.npm, "dist", name)175        )176        .pipe(Effect.andThen(fs.readFileString(path.join(layout.dist, name))))177    );178179    const cli = yield* readPackage(180      "manifest",181      path.join(layout.cli, "package.json")182    );183184    const workspace = yield* readPackage(185      "manifest",186      path.join(layout.root, "package.json")187    );188189    const dependencies = yield* Effect.fromResult(190      pinnedDependencies({191        catalog: workspace.workspaces?.catalog ?? {},192        declared: cli.dependencies ?? {},193        imported: Arr.sort(194          Arr.dedupe(sources.flatMap(importedPackages)),195          Order.String196        ),197      })198    ).pipe(199      Effect.mapError(({ packages }) =>200        failed(201          "manifest",202          `the build imports ${packages.join(", ")}, which apps/cli/package.json doesn't pin`203        )204      )205    );206207    const manifest = publishManifest(Brand, {208      dependencies,209      version: release.version,210    });211212    yield* fs.writeFileString(213      path.join(layout.npm, "package.json"),214      `${JSON.stringify(manifest, undefined, 2)}\n`215    );216217    yield* fs.writeFileString(218      path.join(layout.npm, "README.md"),219      packageReadme({ brand: Brand, version: release.version })220    );221222    yield* fs.copyFile(223      path.join(layout.root, "LICENSE"),224      path.join(layout.npm, "LICENSE")225    );226227    return manifest;228  });229230const writeSkills = (layout: Layout) =>231  Effect.gen(function* () {232    const fs = yield* FileSystem.FileSystem;233    const path = yield* Path.Path;234    const skills = yield* platformSkill({ commands: commandDocs(Contracts) });235236    yield* Effect.forEach(skills, ({ content, path: file }) =>237      Effect.andThen(238        fs.makeDirectory(path.dirname(path.join(layout.npm, file)), {239          recursive: true,240        }),241        fs.writeFileString(path.join(layout.npm, file), content)242      )243    );244  });245246const collectBinaries = (layout: Layout) =>247  Effect.gen(function* () {248    const fs = yield* FileSystem.FileSystem;249    const path = yield* Path.Path;250251    yield* fs.makeDirectory(layout.release, { recursive: true });252253    return yield* Effect.forEach(targets, (target) =>254      Effect.gen(function* () {255        const built = path.join(256          layout.dist,257          "bin",258          machineOf(target),259          Brand.cli260        );261262        const released = path.join(layout.release, binaryName(Brand, target));263264        yield* fs.exists(built).pipe(265          Effect.filterOrFail(266            (exists) => exists,267            () =>268              failed(269                "compile",270                `${path.relative(layout.root, built)} is missing: build first (--build)`271              )272          )273        );274275        yield* fs.copyFile(built, released);276        yield* fs.chmod(released, 0o755);277278        return released;279      })280    );281  });282283const releasedFiles = [284  ...targets.map((target) => binaryName(Brand, target)),285  "install.sh",286];287288const assetOf = (file: string) =>289  Effect.gen(function* () {290    const fs = yield* FileSystem.FileSystem;291    const crypto = yield* Crypto.Crypto;292    const bytes = yield* fs.readFile(file);293    const digest = yield* crypto.digest("SHA-256", bytes);294295    return {296      bytes: bytes.length,297      sha256: [...digest]298        .map((byte) => byte.toString(16).padStart(2, "0"))299        .join(""),300    } satisfies ReleaseAsset;301  });302303const assetsIn = (layout: Layout) =>304  Effect.flatMap(Path.Path, (path) =>305    Effect.forEach(releasedFiles, (name) =>306      Effect.map(307        assetOf(path.join(layout.release, name)),308        (asset) => [name, asset] as const309      )310    )311  ).pipe(Effect.map((entries) => Object.fromEntries(entries)));312313const writeChecksums = (layout: Layout) =>314  Effect.gen(function* () {315    const fs = yield* FileSystem.FileSystem;316    const path = yield* Path.Path;317    const assets = yield* assetsIn(layout);318319    yield* fs.writeFileString(320      path.join(layout.release, "SHA256SUMS"),321      checksumsFile(assets)322    );323  });324325/** How the bucket keeps each file: the platform sets its own reply headers. */326const contentTypes = new Map([327  ["install.sh", "text/x-shellscript; charset=utf-8"],328  ["manifest.json", "application/json"],329]);330331const contentTypeOf = (file: string) =>332  contentTypes.get(file) ?? "application/octet-stream";333334const wranglerOf = (layout: Layout, path: Path.Path) =>335  path.join(336    layout.root,337    "apps",338    "platform",339    "node_modules",340    ".bin",341    "wrangler"342  );343344// Wrangler's own login, never the read-mostly infra token.345const wrangler = (346  step: ReleaseStep,347  layout: Layout,348  cwd: string,349  args: readonly string[]350) =>351  Effect.gen(function* () {352    const path = yield* Path.Path;353    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;354355    const child = yield* spawner.spawn(356      ChildProcess.make(wranglerOf(layout, path), args, {357        cwd,358        env: {359          CLOUDFLARE_API_TOKEN: undefined,360          WRANGLER_SEND_METRICS: "false",361        },362        extendEnv: true,363      })364    );365366    const [output, exitCode] = yield* Effect.all(367      [Stream.mkString(Stream.decodeText(child.all)), child.exitCode],368      { concurrency: "unbounded" }369    );370371    return { exitCode: Number(exitCode), output };372  }).pipe(373    Effect.scoped,374    Effect.mapError(({ message }) =>375      failed(step, `wrangler didn't run: ${message}`)376    )377  );378379const NO_SUCH_KEY = "The specified key does not exist";380381const bucketManifest = (382  step: ReleaseStep,383  layout: Layout,384  bucket: string,385  scratch: string386) =>387  Effect.gen(function* () {388    const fs = yield* FileSystem.FileSystem;389    const path = yield* Path.Path;390    const file = path.join(scratch, "previous.json");391392    const got = yield* wrangler(step, layout, scratch, [393      "r2",394      "object",395      "get",396      `${bucket}/${MANIFEST_KEY}`,397      "--remote",398      "--file",399      file,400    ]);401402    if (got.exitCode !== 0) {403      return got.output.includes(NO_SUCH_KEY)404        ? Option.none()405        : yield* failed(406            step,407            `wrangler r2 object get ${bucket}/${MANIFEST_KEY} failed:\n${got.output.trim()}`408          );409    }410411    const text = yield* fs.readFileString(file);412413    return Option.some(414      yield* Schema.decodeEffect(Schema.fromJsonString(ReleaseManifest))(415        text416      ).pipe(417        Effect.mapError(({ message }) =>418          failed(419            step,420            `${bucket}/${MANIFEST_KEY} doesn't decode, so the platform answers 503 until it is fixed by hand: ${message}`421          )422        )423      )424    );425  });426427const upload = (layout: Layout, release: Release) =>428  Effect.gen(function* () {429    const fs = yield* FileSystem.FileSystem;430    const path = yield* Path.Path;431432    const stage = yield* Effect.fromOption(release.stage).pipe(433      Effect.mapError(() => failed("upload", "an upload names its --stage"))434    );435436    const bucket = resources(stage).releases;437438    const scratch = yield* fs.makeTempDirectoryScoped({439      prefix: "release-715-",440    });441442    const previous = yield* bucketManifest("upload", layout, bucket, scratch);443    const assets = yield* assetsIn(layout);444445    yield* Effect.fromResult(446      unreleased({447        assets,448        previous: Option.getOrUndefined(previous),449        version: release.version,450      })451    ).pipe(Effect.mapError(({ message }) => failed("upload", message)));452453    const manifest = releaseManifest({454      assets,455      previous: Option.getOrUndefined(previous),456      version: release.version,457    });458459    yield* fs.writeFileString(460      path.join(layout.release, "manifest.json"),461      `${yield* Schema.encodeEffect(Schema.fromJsonString(ReleaseManifest))(462        manifest463      ).pipe(Effect.mapError(({ message }) => failed("upload", message)))}\n`464    );465466    for (const { file, key } of uploads({467      files: Object.keys(assets),468      version: release.version,469    })) {470      yield* wrangler("upload", layout, scratch, [471        "r2",472        "object",473        "put",474        `${bucket}/${key}`,475        "--remote",476        "--file",477        path.join(layout.release, file),478        "--content-type",479        contentTypeOf(file),480      ]).pipe(481        Effect.filterOrFail(482          ({ exitCode }) => exitCode === 0,483          ({ output }) =>484            failed(485              "upload",486              `wrangler r2 object put ${bucket}/${key} failed:\n${output.trim()}`487            )488        )489      );490491      yield* Console.log(`  uploaded ${bucket}/${key}`);492    }493494    return manifest;495  }).pipe(Effect.scoped);496497export const missingFromPackage = (layout: Layout, version: string) =>498  Effect.gen(function* () {499    const fs = yield* FileSystem.FileSystem;500    const path = yield* Path.Path;501502    const manifest = publishManifest(Brand, { dependencies: {}, version });503504    return yield* Effect.filter(namedFiles(manifest), (file) =>505      Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)506    );507  });508509export const publishable = (layout: Layout, release: Release) =>510  Effect.gen(function* () {511    const path = yield* Path.Path;512513    yield* readPackage("publish", path.join(layout.npm, "package.json")).pipe(514      Effect.filterOrFail(515        ({ version }) => version === release.version,516        ({ version }) =>517          failed(518            "publish",519            `the staged package is ${version ?? "unversioned"}, not ${release.version}: run --build --version ${release.version} first`520          )521      )522    );523524    yield* missingFromPackage(layout, release.version).pipe(525      Effect.filterOrFail(526        (missing) => missing.length === 0,527        (missing) =>528          failed("publish", `the staged package lacks ${missing.join(", ")}`)529      )530    );531532    const stage = yield* Effect.fromOption(release.stage).pipe(533      Effect.mapError(() => failed("publish", "a publish names its --stage"))534    );535536    const scratch = yield* FileSystem.FileSystem.pipe(537      Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "release-" }))538    );539540    const manifest = yield* bucketManifest(541      "publish",542      layout,543      resources(stage).releases,544      scratch545    );546547    yield* Effect.fromResult(548      servedAsLatest({549        manifest: Option.getOrUndefined(manifest),550        version: release.version,551      })552    ).pipe(Effect.mapError(({ message }) => failed("publish", message)));553  }).pipe(Effect.scoped);554555const publish = (layout: Layout, release: Release) =>556  Effect.andThen(557    publishable(layout, release),558    run(559      "publish",560      "npm",561      ["publish", layout.npm, "--access", "public"],562      layout.root563    )564  );565566const writeInstallScript = (layout: Layout, release: Release) =>567  Effect.gen(function* () {568    const fs = yield* FileSystem.FileSystem;569    const path = yield* Path.Path;570571    yield* fs.makeDirectory(layout.release, { recursive: true });572573    yield* fs.writeFileString(574      path.join(layout.release, "install.sh"),575      installScript({576        baseUrl: `${release.origin}/releases/${release.version}`,577        brand: Brand,578        version: release.version,579      })580    );581582    yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);583  });584585export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>586  Match.value(step).pipe(587    Match.when("tsdown", () =>588      run(589        "tsdown",590        "bun",591        [592          "run",593          "build",594          "--",595          "--targets",596          targets.join(","),597          "--version",598          release.version,599        ],600        layout.cli601      )602    ),603    Match.when("manifest", () => stagePackage(layout, release)),604    Match.when("copySkills", () => writeSkills(layout)),605    Match.when("compile", () => collectBinaries(layout)),606    Match.when("installScript", () => writeInstallScript(layout, release)),607    Match.when("checksums", () => writeChecksums(layout)),608    Match.when("upload", () => upload(layout, release)),609    Match.when("publish", () => publish(layout, release)),610    Match.exhaustive611  );