Skip to content
Myr

steps.ts

This file

Path

scripts/lib/release/steps.ts

578 lines · 15.5 KiB · TypeScript

Last changed by

Merge build/comments-ops into mainoscabrielbefore adoptione4c407e

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  targets,35  unreleased,36  uploads,37} from "../release.ts";38import type { ReleaseAsset, ReleaseStep } from "../release.ts";39import { packageReadme } from "./readme.ts";4041export class ReleaseFailed extends Schema.TaggedError<ReleaseFailed>()(42  "ReleaseFailed",43  { reason: Schema.String, step: Schema.String }44) {45  override get message() {46    return `${this.step}: ${this.reason}`;47  }48}4950export interface Layout {51  readonly root: string;52  readonly cli: string;53  readonly dist: string;54  readonly release: string;55  /** Staged outside `dist/`, whose `bin/` holds the binaries npm must not ship. */56  readonly npm: string;57}5859export const layoutOf = (root: string) =>60  Effect.map(Path.Path, (path): Layout => {61    const cli = path.join(root, "apps", "cli");62    const release = path.join(cli, "release");6364    return {65      cli,66      dist: path.join(cli, "dist"),67      npm: path.join(release, "npm"),68      release,69      root,70    };71  });7273export interface Release {74  readonly version: string;75  readonly origin: string;76  readonly stage: Option.Option<Stage>;77}7879export const publishCommand = (layout: Layout, path: Path.Path) =>80  `npm publish ${path.relative(layout.root, layout.npm)} --access public`;8182const failed = (step: ReleaseStep, reason: string) =>83  new ReleaseFailed({ reason, step });8485const run = (86  step: ReleaseStep,87  command: string,88  args: readonly string[],89  cwd: string90) =>91  Effect.flatMap(ChildProcessSpawner.ChildProcessSpawner, (spawner) =>92    spawner.exitCode(93      ChildProcess.make(command, args, {94        cwd,95        stderr: "inherit",96        stdin: "inherit",97        stdout: "inherit",98      })99    )100  ).pipe(101    Effect.mapError(({ message }) => failed(step, message)),102    Effect.filterOrFail(103      (exitCode) => exitCode === 0,104      (exitCode) =>105        failed(step, `${command} ${args.join(" ")} exited ${exitCode}`)106    ),107    Effect.asVoid108  );109110const PackageJson = Schema.fromJsonString(111  Schema.Struct({112    dependencies: Schema.optionalKey(113      Schema.Record(Schema.String, Schema.String)114    ),115    version: Schema.optionalKey(Schema.String),116    workspaces: Schema.optionalKey(117      Schema.Struct({118        catalog: Schema.optionalKey(119          Schema.Record(Schema.String, Schema.String)120        ),121      })122    ),123  })124);125126const readPackage = (step: ReleaseStep, file: string) =>127  Effect.flatMap(FileSystem.FileSystem, (fs) => fs.readFileString(file)).pipe(128    Effect.flatMap(Schema.decodeEffect(PackageJson)),129    Effect.mapError(({ message }) => failed(step, `${file}: ${message}`))130  );131132const builtFiles = (layout: Layout) =>133  Effect.gen(function* () {134    const fs = yield* FileSystem.FileSystem;135    const path = yield* Path.Path;136    const names = yield* fs.readDirectory(layout.dist);137138    const files = yield* Effect.filter(139      names.filter((name) => /\.(?:js|d\.ts)$/u.test(name)),140      (name) =>141        Effect.map(142          fs.stat(path.join(layout.dist, name)),143          ({ type }) => type === "File"144        )145    );146147    return Arr.sort(files, Order.String);148  });149150const stagePackage = (layout: Layout, release: Release) =>151  Effect.gen(function* () {152    const fs = yield* FileSystem.FileSystem;153    const path = yield* Path.Path;154155    const files = yield* builtFiles(layout).pipe(156      Effect.filterOrFail(157        (names) => names.includes("bin.js"),158        () =>159          failed(160            "manifest",161            "apps/cli/dist has no bin.js: build first (--build)"162          )163      )164    );165166    yield* fs.remove(layout.npm, { force: true, recursive: true });167    yield* fs.makeDirectory(path.join(layout.npm, "dist"), { recursive: true });168169    const sources = yield* Effect.forEach(files, (name) =>170      fs171        .copyFile(172          path.join(layout.dist, name),173          path.join(layout.npm, "dist", name)174        )175        .pipe(Effect.andThen(fs.readFileString(path.join(layout.dist, name))))176    );177178    const cli = yield* readPackage(179      "manifest",180      path.join(layout.cli, "package.json")181    );182183    const workspace = yield* readPackage(184      "manifest",185      path.join(layout.root, "package.json")186    );187188    const dependencies = yield* Effect.fromResult(189      pinnedDependencies({190        catalog: workspace.workspaces?.catalog ?? {},191        declared: cli.dependencies ?? {},192        imported: Arr.sort(193          Arr.dedupe(sources.flatMap(importedPackages)),194          Order.String195        ),196      })197    ).pipe(198      Effect.mapError(({ packages }) =>199        failed(200          "manifest",201          `the build imports ${packages.join(", ")}, which apps/cli/package.json doesn't pin`202        )203      )204    );205206    const manifest = publishManifest(Brand, {207      dependencies,208      version: release.version,209    });210211    yield* fs.writeFileString(212      path.join(layout.npm, "package.json"),213      `${JSON.stringify(manifest, undefined, 2)}\n`214    );215216    yield* fs.writeFileString(217      path.join(layout.npm, "README.md"),218      packageReadme({ brand: Brand, version: release.version })219    );220221    yield* fs.copyFile(222      path.join(layout.root, "LICENSE"),223      path.join(layout.npm, "LICENSE")224    );225226    return manifest;227  });228229const writeSkills = (layout: Layout) =>230  Effect.gen(function* () {231    const fs = yield* FileSystem.FileSystem;232    const path = yield* Path.Path;233    const skills = yield* platformSkill({ commands: commandDocs(Contracts) });234235    yield* Effect.forEach(skills, ({ content, path: file }) =>236      Effect.andThen(237        fs.makeDirectory(path.dirname(path.join(layout.npm, file)), {238          recursive: true,239        }),240        fs.writeFileString(path.join(layout.npm, file), content)241      )242    );243  });244245const collectBinaries = (layout: Layout) =>246  Effect.gen(function* () {247    const fs = yield* FileSystem.FileSystem;248    const path = yield* Path.Path;249250    yield* fs.makeDirectory(layout.release, { recursive: true });251252    return yield* Effect.forEach(targets, (target) =>253      Effect.gen(function* () {254        const built = path.join(255          layout.dist,256          "bin",257          machineOf(target),258          Brand.cli259        );260261        const released = path.join(layout.release, binaryName(Brand, target));262263        yield* fs.exists(built).pipe(264          Effect.filterOrFail(265            (exists) => exists,266            () =>267              failed(268                "compile",269                `${path.relative(layout.root, built)} is missing: build first (--build)`270              )271          )272        );273274        yield* fs.copyFile(built, released);275        yield* fs.chmod(released, 0o755);276277        return released;278      })279    );280  });281282const releasedFiles = [283  ...targets.map((target) => binaryName(Brand, target)),284  "install.sh",285];286287const assetOf = (file: string) =>288  Effect.gen(function* () {289    const fs = yield* FileSystem.FileSystem;290    const crypto = yield* Crypto.Crypto;291    const bytes = yield* fs.readFile(file);292    const digest = yield* crypto.digest("SHA-256", bytes);293294    return {295      bytes: bytes.length,296      sha256: [...digest]297        .map((byte) => byte.toString(16).padStart(2, "0"))298        .join(""),299    } satisfies ReleaseAsset;300  });301302const assetsIn = (layout: Layout) =>303  Effect.flatMap(Path.Path, (path) =>304    Effect.forEach(releasedFiles, (name) =>305      Effect.map(306        assetOf(path.join(layout.release, name)),307        (asset) => [name, asset] as const308      )309    )310  ).pipe(Effect.map((entries) => Object.fromEntries(entries)));311312const writeChecksums = (layout: Layout) =>313  Effect.gen(function* () {314    const fs = yield* FileSystem.FileSystem;315    const path = yield* Path.Path;316    const assets = yield* assetsIn(layout);317318    yield* fs.writeFileString(319      path.join(layout.release, "SHA256SUMS"),320      checksumsFile(assets)321    );322  });323324/** How the bucket keeps each file: the platform sets its own reply headers. */325const contentTypes = new Map([326  ["install.sh", "text/x-shellscript; charset=utf-8"],327  ["manifest.json", "application/json"],328]);329330const contentTypeOf = (file: string) =>331  contentTypes.get(file) ?? "application/octet-stream";332333const wranglerOf = (layout: Layout, path: Path.Path) =>334  path.join(335    layout.root,336    "apps",337    "platform",338    "node_modules",339    ".bin",340    "wrangler"341  );342343// Wrangler's own login, never the read-mostly infra token.344const wrangler = (layout: Layout, cwd: string, args: readonly string[]) =>345  Effect.gen(function* () {346    const path = yield* Path.Path;347    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;348349    const child = yield* spawner.spawn(350      ChildProcess.make(wranglerOf(layout, path), args, {351        cwd,352        env: {353          CLOUDFLARE_API_TOKEN: undefined,354          WRANGLER_SEND_METRICS: "false",355        },356        extendEnv: true,357      })358    );359360    const [output, exitCode] = yield* Effect.all(361      [Stream.mkString(Stream.decodeText(child.all)), child.exitCode],362      { concurrency: "unbounded" }363    );364365    return { exitCode: Number(exitCode), output };366  }).pipe(367    Effect.scoped,368    Effect.mapError(({ message }) =>369      failed("upload", `wrangler didn't run: ${message}`)370    )371  );372373const NO_SUCH_KEY = "The specified key does not exist";374375const previousManifest = (layout: Layout, bucket: string, scratch: string) =>376  Effect.gen(function* () {377    const fs = yield* FileSystem.FileSystem;378    const path = yield* Path.Path;379    const file = path.join(scratch, "previous.json");380381    const got = yield* wrangler(layout, scratch, [382      "r2",383      "object",384      "get",385      `${bucket}/${MANIFEST_KEY}`,386      "--remote",387      "--file",388      file,389    ]);390391    if (got.exitCode !== 0) {392      return got.output.includes(NO_SUCH_KEY)393        ? Option.none()394        : yield* failed(395            "upload",396            `wrangler r2 object get ${bucket}/${MANIFEST_KEY} failed:\n${got.output.trim()}`397          );398    }399400    const text = yield* fs.readFileString(file);401402    return Option.some(403      yield* Schema.decodeEffect(Schema.fromJsonString(ReleaseManifest))(404        text405      ).pipe(406        Effect.mapError(({ message }) =>407          failed(408            "upload",409            `${bucket}/${MANIFEST_KEY} doesn't decode, so the platform answers 503 until it is fixed by hand: ${message}`410          )411        )412      )413    );414  });415416const upload = (layout: Layout, release: Release) =>417  Effect.gen(function* () {418    const fs = yield* FileSystem.FileSystem;419    const path = yield* Path.Path;420421    const stage = yield* Effect.fromOption(release.stage).pipe(422      Effect.mapError(() => failed("upload", "an upload names its --stage"))423    );424425    const bucket = resources(stage).releases;426427    const scratch = yield* fs.makeTempDirectoryScoped({428      prefix: "release-715-",429    });430431    const previous = yield* previousManifest(layout, bucket, scratch);432    const assets = yield* assetsIn(layout);433434    yield* Effect.fromResult(435      unreleased({436        assets,437        previous: Option.getOrUndefined(previous),438        version: release.version,439      })440    ).pipe(Effect.mapError(({ message }) => failed("upload", message)));441442    const manifest = releaseManifest({443      assets,444      previous: Option.getOrUndefined(previous),445      version: release.version,446    });447448    yield* fs.writeFileString(449      path.join(layout.release, "manifest.json"),450      `${yield* Schema.encodeEffect(Schema.fromJsonString(ReleaseManifest))(451        manifest452      ).pipe(Effect.mapError(({ message }) => failed("upload", message)))}\n`453    );454455    for (const { file, key } of uploads({456      files: Object.keys(assets),457      version: release.version,458    })) {459      yield* wrangler(layout, scratch, [460        "r2",461        "object",462        "put",463        `${bucket}/${key}`,464        "--remote",465        "--file",466        path.join(layout.release, file),467        "--content-type",468        contentTypeOf(file),469      ]).pipe(470        Effect.filterOrFail(471          ({ exitCode }) => exitCode === 0,472          ({ output }) =>473            failed(474              "upload",475              `wrangler r2 object put ${bucket}/${key} failed:\n${output.trim()}`476            )477        )478      );479480      yield* Console.log(`  uploaded ${bucket}/${key}`);481    }482483    return manifest;484  }).pipe(Effect.scoped);485486export const missingFromPackage = (layout: Layout, version: string) =>487  Effect.gen(function* () {488    const fs = yield* FileSystem.FileSystem;489    const path = yield* Path.Path;490491    const manifest = publishManifest(Brand, { dependencies: {}, version });492493    return yield* Effect.filter(namedFiles(manifest), (file) =>494      Effect.map(fs.exists(path.join(layout.npm, file)), (exists) => !exists)495    );496  });497498export const publishable = (layout: Layout, release: Release) =>499  Effect.gen(function* () {500    const path = yield* Path.Path;501502    yield* readPackage("publish", path.join(layout.npm, "package.json")).pipe(503      Effect.filterOrFail(504        ({ version }) => version === release.version,505        ({ version }) =>506          failed(507            "publish",508            `the staged package is ${version ?? "unversioned"}, not ${release.version}: run --build --version ${release.version} first`509          )510      )511    );512513    yield* missingFromPackage(layout, release.version).pipe(514      Effect.filterOrFail(515        (missing) => missing.length === 0,516        (missing) =>517          failed("publish", `the staged package lacks ${missing.join(", ")}`)518      )519    );520  });521522const publish = (layout: Layout, release: Release) =>523  Effect.andThen(524    publishable(layout, release),525    run(526      "publish",527      "npm",528      ["publish", layout.npm, "--access", "public"],529      layout.root530    )531  );532533const writeInstallScript = (layout: Layout, release: Release) =>534  Effect.gen(function* () {535    const fs = yield* FileSystem.FileSystem;536    const path = yield* Path.Path;537538    yield* fs.makeDirectory(layout.release, { recursive: true });539540    yield* fs.writeFileString(541      path.join(layout.release, "install.sh"),542      installScript({543        baseUrl: `${release.origin}/releases/${release.version}`,544        brand: Brand,545        version: release.version,546      })547    );548549    yield* fs.chmod(path.join(layout.release, "install.sh"), 0o755);550  });551552export const runStep = (step: ReleaseStep, layout: Layout, release: Release) =>553  Match.value(step).pipe(554    Match.when("tsdown", () =>555      run(556        "tsdown",557        "bun",558        [559          "run",560          "build",561          "--",562          "--targets",563          targets.join(","),564          "--version",565          release.version,566        ],567        layout.cli568      )569    ),570    Match.when("manifest", () => stagePackage(layout, release)),571    Match.when("copySkills", () => writeSkills(layout)),572    Match.when("compile", () => collectBinaries(layout)),573    Match.when("installScript", () => writeInstallScript(layout, release)),574    Match.when("checksums", () => writeChecksums(layout)),575    Match.when("upload", () => upload(layout, release)),576    Match.when("publish", () => publish(layout, release)),577    Match.exhaustive578  );