Skip to content
Myr

Merge build/1104 into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 9c64f9b, dbfd41b · Browse files · 9 files+430 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+430 added−56 removed

  • tests:+236 added−0 removed
  • other:+194 added−56 removed

9 files+430 added−56 removed

modified:apps/cli/src/main.ts+2 added-6 removed
21 unmodified lines
22 RemoteClient,23 transportMessage,24} from "./remote.ts";25import { commands, mcp, UnknownCommand } from "./surfaces.ts";26import { cliVersion } from "./version.ts";2728/**29 * The three commands that start any contribution, first in `--help`, so a30 * person or an agent who knows nothing else knows where to begin.
12 unmodified lines
43 Command.withDescription(banner),44 Command.withSubcommands(tree)45);4646/**47 * The CLI's version until the release build stamps its own.48 */49const version = "0.0.0";5047/** The exit code of a usage error, as for a command line effect/cli can't parse. */48const USAGE = 2;4950/**
120 unmodified lines
171172 const exit = yield* Effect.exit(173 Command.runWith(root.pipe(Command.provideEffectDiscard(stdout.open)), {174 renderErrors: false,179 version,175 version: cliVersion,176 })(argv).pipe(177 Effect.provideService(178 CliConfig.CliConfig,179 CliConfig.make({ builtIns: builtInsFor(policy) })
28 unmodified lines
modified:apps/cli/src/surfaces.ts+2 added-1 removed
40 unmodified lines
41import { Output } from "./output.ts";42import { refusalsIn, views } from "./render.ts";43import { repoContext } from "./repo-context.ts";44import { today } from "./tui/command.ts";45import { cliVersion } from "./version.ts";4647/** The folder the CLI stands in: the process's own, unless a test says otherwise. */48export const WorkingDirectory = Context.Reference<string>(49 "cli/WorkingDirectory",
265 unmodified lines
315 McpProtocol.v2025_06_18,316 McpProtocol.v2025_03_26,317 McpProtocol.v2024_11_05,318 ],318 version: "0.0.0",319 version: cliVersion,320 })321 )322 );323
11 unmodified lines
added:apps/cli/src/version.ts+26 added
added:apps/cli/test/version.test.ts+169 added
1/**2 * The CLI's version: `src/version.ts` says it, a run no build stamped says3 * `0.0.0`, and `build.ts` stamps a release's version into both bundlers'4 * output through one define. The real build compiles binaries, so it is5 * run by hand (issue 1104's comments), not here.6 */7import { NodeServices } from "@effect/platform-node";8import { describe, expect, it } from "@effect/vitest";9import { Brand } from "@repo/brand";10import { Client } from "@repo/protocol/contracts";11import { Effect, FileSystem, Layer, Option, Path, Ref, Schema } from "effect";12import { CliOutput } from "effect/cli";13import { TestConsole } from "effect/testing";14import { build } from "tsdown";1516import { compileArgs, parseBuild, versionDefine } from "../build.ts";17import type { BuildOptions } from "../build.ts";18import { program } from "../src/main.ts";19import { OutputPlain } from "../src/output.ts";20import { cliVersion } from "../src/version.ts";21import { npm } from "../tsdown.config.ts";22import { SignedOut } from "./signed-out.ts";2324const services = Layer.mergeAll(25 TestConsole.layer,26 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),27 Layer.mock(Client)({}),28 OutputPlain,29 SignedOut30).pipe(Layer.provideMerge(NodeServices.layer));3132/** What a built `version.ts` exports. */33const Built = Schema.Struct({ cliVersion: Schema.String });3435describe("the CLI's version, unbuilt", () => {36 it.effect("is 0.0.0, and --version prints it", () =>37 Effect.gen(function* () {38 yield* program(["--version"]);3940 expect({41 cliVersion,42 printed: (yield* TestConsole.logLines).map(String),43 }).toStrictEqual({44 cliVersion: "0.0.0",45 printed: [`${Brand.cli} v0.0.0`],46 });47 }).pipe(Effect.provide(services))48 );49});5051describe("the build's version stamp", () => {52 it.effect(53 "replaces the expression version.ts reads with the version, as a string literal",54 () =>55 Effect.gen(function* () {56 const fs = yield* FileSystem.FileSystem;57 const path = yield* Path.Path;58 const root = yield* path.fromFileUrl(new URL("..", import.meta.url));5960 const source = yield* fs.readFileString(61 path.join(root, "src", "version.ts")62 );6364 const define = versionDefine("9.9.9-test");6566 expect({67 define,68 unread: Object.keys(define).filter((key) => !source.includes(key)),69 }).toStrictEqual({70 define: { "import.meta.env.CLI_BUILD_VERSION": '"9.9.9-test"' },71 unread: [],72 });73 }).pipe(Effect.provide(NodeServices.layer))74 );7576 it("is in every config tsdown.config.ts makes, for the version it is given", () => {77 expect(npm("9.9.9-test").map((config) => config.define)).toStrictEqual(78 Array.from({ length: 3 }, () => versionDefine("9.9.9-test"))79 );80 });8182 it.live(83 "stamps the npm build: tsdown's build of version.ts reads the version",84 () =>85 Effect.gen(function* () {86 const fs = yield* FileSystem.FileSystem;87 const path = yield* Path.Path;88 const root = yield* path.fromFileUrl(new URL("..", import.meta.url));8990 const out = yield* fs.makeTempDirectoryScoped({91 prefix: "cli-version-",92 });9394 const [first] = npm("9.9.9-test");9596 yield* Effect.tryPromise(() =>97 build({98 ...first,99 config: false,100 cwd: root,101 entry: { version: path.join(root, "src", "version.ts") },102 logLevel: "silent",103 outDir: out,104 })105 );106107 const built = yield* Effect.tryPromise(108 () => import(path.join(out, "version.js"))109 ).pipe(Effect.flatMap(Schema.decodeUnknownEffect(Built)));110111 expect(built.cliVersion).toBe("9.9.9-test");112 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))113 );114115 it("stamps each compiled binary with the same define", () => {116 expect(117 compileArgs({118 entry: "/b/main.ts",119 outfile: "/b/out",120 target: "linux-x64",121 version: "9.9.9-test",122 })123 ).toStrictEqual([124 "build",125 "--compile",126 "--minify",127 "--define",128 'import.meta.env.CLI_BUILD_VERSION="9.9.9-test"',129 "--target=bun-linux-x64",130 "/b/main.ts",131 "--outfile",132 "/b/out",133 ]);134 });135});136137/** What the build would run with for `argv`, if it would run. */138const parsed = (argv: readonly string[]) =>139 Effect.gen(function* () {140 const seen = yield* Ref.make(Option.none<BuildOptions>());141142 yield* parseBuild(argv, (options) => Ref.set(seen, Option.some(options)));143144 return yield* Ref.get(seen);145 }).pipe(Effect.provide(services));146147describe("the build's flags", () => {148 it.effect(149 "read --version and --targets, and build 0.0.0 without a version",150 () =>151 Effect.gen(function* () {152 expect({153 stamped: yield* parsed([154 "--targets",155 "bun-linux-x64,darwin-arm64",156 "--version",157 "9.9.9-test",158 ]),159 unstamped: yield* parsed([]),160 }).toStrictEqual({161 stamped: Option.some({162 targets: ["linux-x64", "darwin-arm64"],163 version: "9.9.9-test",164 }),165 unstamped: Option.some({ targets: [], version: "0.0.0" }),166 });167 })168 );169});
modified:apps/cli/build.ts+116 added-38 removed
15 unmodified lines
16 * 4. Beside each binary, `git-credential-<slug>` links to it: the binary17 * sees the name it was started by (`src/bin.ts`), so the link is git's18 * credential helper.19 *20 * `--version <semver>` stamps both builds (`versionDefine`): it is what21 * the CLI's `--version` prints. Without it the build says `0.0.0`.22 *23 * A Bun script, outside every Worker's graph. Names come from `Brand`.24 * Importing it builds nothing (`tsdown.config.ts` and the tests read its25 * pure parts): only `bun build.ts` runs the build.26 */27import { BunRuntime, BunServices } from "@effect/platform-bun";28import { Brand } from "@repo/brand";29import {
3 unmodified lines
33 Option,34 Path,35 Predicate,36 Schema,37 Stdio,38} from "effect";33import { Command, Flag } from "effect/cli";39import { CliConfig, Command, Flag, GlobalFlag } from "effect/cli";40import { ChildProcess, ChildProcessSpawner } from "effect/process";41import { build } from "tsdown";4243import { NATIVE, npmMachineOf } from "./build-targets.ts";44import { EMBEDDED_KEY } from "./src/local/config-runtime.ts";39import { declarations, library } from "./tsdown.config.ts";45import {46 declarations,47 library,48 npm,49 UNSTAMPED,50 versionDefine,51} from "./tsdown.config.ts";5253// The one define both bundlers get, kept beside tsdown's configs, which54// this module imports (lint refuses an import cycle).55export { versionDefine } from "./tsdown.config.ts";5657/** What one build is asked for. */58export interface BuildOptions {59 /** Bun targets to cross-compile for, without `bun-`; none builds for this machine. */60 readonly targets: readonly string[];61 /** The version both builds are stamped with. */62 readonly version: string;63}6465/**66 * `bun build --compile`'s arguments for one binary: `entry` compiled to67 * `outfile`, for `target` (this machine when absent), stamped with `version`.68 */69export const compileArgs = (input: {70 readonly entry: string;71 readonly outfile: string;72 readonly target?: string;73 readonly version: string;74}) => [75 "build",76 "--compile",77 "--minify",78 ...Object.entries(versionDefine(input.version)).flatMap(([key, value]) => [79 "--define",80 `${key}=${value}`,81 ]),82 ...(input.target === undefined ? [] : [`--target=bun-${input.target}`]),83 input.entry,84 "--outfile",85 input.outfile,86];8788class BuildFailed extends Data.TaggedError("BuildFailed")<{89 readonly step: string;90 readonly detail: string;91}> {}
71 unmodified lines
163 catch: (cause) => new BuildFailed({ detail: String(cause), step }),164 try: () => build(config),165 });166120const make = (targets: readonly string[]) =>167const make = ({ targets, version }: BuildOptions) =>168 Effect.gen(function* () {169 const fs = yield* FileSystem.FileSystem;170 const path = yield* Path.Path;171 const root = yield* path.fromFileUrl(new URL(".", import.meta.url));
36 unmodified lines
208 fs.writeFileString(path.join(dir, name), JSON.stringify(config)),209 path.join(dir, name)210 );211165 // 1. The npm build.166 yield* tsdown("tsdown", {167 config: path.join(root, "tsdown.config.ts"),168 cwd: root,169 });212 // 1. The npm build, one entry at a time: the first cleans `dist/`.213 for (const config of npm(version)) {214 yield* tsdown(`tsdown ${Object.keys(config.entry).join(", ")}`, {215 ...config,216 config: false,217 cwd: root,218 });219 }220221 // 2. The library entries' types. tsgo declares them in a folder at a222 // fixed path, removed once the build ends: the bundled `.d.ts` files keep223 // each source's path in a comment, so a temp folder's random name would
171 unmodified lines
395396 yield* run(397 "bun build --compile",398 "bun",349 [350 "build",351 "--compile",352 "--minify",399 compileArgs({400 entry: path.join(compile, "main.ts"),401 outfile: path.join(dir, Brand.cli),402 version,403 ...Option.match(target, {354 onNone: () => [],355 onSome: (name) => [`--target=bun-${name}`],404 onNone: () => ({}),405 onSome: (name) => ({ target: name }),406 }),357 path.join(compile, "main.ts"),358 "--outfile",359 path.join(dir, Brand.cli),360 ],407 }),408 { env }409 );410411 yield* fs.symlink(Brand.cli, path.join(dir, Brand.gitCredentialHelper));
6 unmodified lines
418 ),419 Flag.optional420);421375const command = Command.make("build", { targets }, (flags) =>376 make(377 Option.match(flags.targets, {378 onNone: () => [],379 onSome: (list) =>380 list381 .split(",")382 .map((target) => target.trim().replace(/^bun-/u, ""))383 .filter((target) => target.length > 0),384 })385 )386).pipe(387 Command.withDescription(388 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."389 )422const version = Flag.String("version").pipe(423 Flag.withDescription(424 `The version both builds are stamped with, which the CLI's --version prints (default ${UNSTAMPED}).`425 ),426 Flag.optional427);428392BunRuntime.runMain(393 Command.run(command, { version: "0.0.0" }).pipe(394 Effect.provide(BunServices.layer)395 )396);429/** The build's command line, running `then` with what it asks for. */430const command = <E, R>(431 then: (options: BuildOptions) => Effect.Effect<void, E, R>432) =>433 Command.make("build", { targets, version }, (flags) =>434 then({435 targets: Option.match(flags.targets, {436 onNone: () => [],437 onSome: (list) =>438 list439 .split(",")440 .map((target) => target.trim().replace(/^bun-/u, ""))441 .filter((target) => target.length > 0),442 }),443 version: Option.getOrElse(flags.version, () => UNSTAMPED),444 })445 ).pipe(446 Command.withDescription(447 "Build the CLI: the npm dist/, and a standalone binary that is also git's credential helper."448 )449 );450451/**452 * The build's own `--version` takes a value, so effect/cli's built-in453 * `--version` (a boolean that prints and exits) is left out.454 */455const builtIns = CliConfig.make({456 builtIns: GlobalFlag.BuiltIns.filter((flag) => flag !== GlobalFlag.Version),457});458459/** Runs `then` with what `argv`, the build's arguments, asks for. */460export const parseBuild = <E, R>(461 argv: readonly string[],462 then: (options: BuildOptions) => Effect.Effect<void, E, R>463) =>464 Command.runWith(command(then), { version: UNSTAMPED })(argv).pipe(465 Effect.provideService(CliConfig.CliConfig, builtIns)466 );467468if (import.meta.main) {469 BunRuntime.runMain(470 Stdio.Stdio.use(({ args }) =>471 Effect.flatMap(args, (argv) => parseBuild(argv, make))472 ).pipe(Effect.provide(BunServices.layer))473 );474}
modified:apps/cli/tsdown.config.ts+33 added-7 removed
modified:packages/config/test/release.test.ts+67 added
9 unmodified lines
10 Array as Arr,11 Crypto,12 Effect,13 FileSystem,14 Layer,15 Option,16 Order,17 Path,18 Ref,19 Result,20 Schema,21 Sink,22 Stream,23} from "effect";24import { ChildProcess, ChildProcessSpawner } from "effect/process";25
18 unmodified lines
44 uploads,45 VersionNeeded,46 VersionReleased,47} from "../../../scripts/lib/release.ts";48import { layoutOf, runStep } from "../../../scripts/lib/release/steps.ts";49import { Brand } from "../../brand/src/index.ts";50import { repoRoot } from "./root.ts";5152/** What the test reads of a package manifest. */
378 unmodified lines
431 [`${Brand.slug}-darwin-arm64`]: { bytes: 62_800_000, sha256: digest("d") },432 [`${Brand.slug}-linux-x64`]: { bytes: 81_900_000, sha256: digest("e") },433};434435/**436 * A spawner that runs nothing and exits 0: each command it was asked for,437 * as `<folder>$ <command> <args>`, its folder relative to the repo root.438 */439const recordingSpawner = Effect.gen(function* () {440 const path = yield* Path.Path;441 const root = yield* repoRoot;442 const lines = yield* Ref.make<readonly string[]>([]);443444 const spawner = ChildProcessSpawner.make((command) =>445 Effect.gen(function* () {446 if (!ChildProcess.isStandardCommand(command)) {447 return yield* Effect.die("the release pipes no commands");448 }449450 yield* Ref.update(lines, (all) => [451 ...all,452 `${path.relative(root, command.options.cwd ?? root)}$ ${[command.command, ...command.args].join(" ")}`,453 ]);454455 return ChildProcessSpawner.makeHandle({456 all: Stream.empty,457 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),458 getInputFd: () => Sink.drain,459 getOutputFd: () => Stream.empty,460 isRunning: Effect.succeed(false),461 kill: () => Effect.void,462 pid: ChildProcessSpawner.ProcessId(1),463 stderr: Stream.empty,464 stdin: Sink.drain,465 stdout: Stream.empty,466 unref: Effect.succeed(Effect.void),467 });468 })469 );470471 return {472 layer: Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),473 spawned: Ref.get(lines),474 };475});476477describe("a release's build step", () => {478 it.effect(479 "builds the CLI stamped with the release's version, for both targets",480 () =>481 Effect.gen(function* () {482 const { layer, spawned } = yield* recordingSpawner;483 const layout = yield* layoutOf(yield* repoRoot);484485 yield* runStep("tsdown", layout, {486 origin: "https://platform.example",487 stage: Option.none(),488 version: "0.2.0-demo.1",489 }).pipe(Effect.provide(layer));490491 expect(yield* spawned).toStrictEqual([492 "apps/cli$ bun run build -- --targets bun-linux-x64,bun-darwin-arm64 --version 0.2.0-demo.1",493 ]);494 }).pipe(Effect.provide(NodeServices.layer))495 );496});497498describe("the release manifest", () => {499 it.effect(500 "keeps every earlier version, makes the new one latest, and is what the platform decodes",501 () =>
259 unmodified lines
modified:scripts/lib/release/steps.ts+11 added-2 removed
1 unmodified line
2 * What each step of a release does on this machine, over the3 * plan `scripts/lib/release.ts` makes:4 *5 * - `tsdown`: the CLI's `bun run build` in `apps/cli`, with both targets6 * (`dist/`, and `dist/bin/<target>/` per target);6 * (`dist/`, and `dist/bin/<target>/` per target), stamped with the7 * release's version (what `--version` prints);8 * - `manifest`: the npm package, staged in `apps/cli/release/npm/`: the9 * build's `dist/*.js` and `*.d.ts`, the generated `package.json`, its10 * README and the repo's licence;11 * - `copySkills`: the platform's skill (`@repo/agent-kit`'s
603 unmodified lines
615 Match.when("tsdown", () =>616 run(617 "tsdown",618 "bun",618 ["run", "build", "--", "--targets", targets.join(",")],619 [620 "run",621 "build",622 "--",623 "--targets",624 targets.join(","),625 "--version",626 release.version,627 ],628 layout.cli629 )630 ),631 Match.when("manifest", () => stagePackage(layout, release)),
8 unmodified lines
modified:scripts/lib/release.ts+4 added-2 removed
388 unmodified lines
389 })390 );391392/**393 * What the CLI reports itself as until a build stamps it (`main.ts`394 * says `0.0.0`), and so what a build that neither uploads nor publishes is.393 * What a build that neither uploads nor publishes is stamped with. The394 * build stamps the release's version into the CLI (`apps/cli/build.ts`'s395 * `--version`, which the `tsdown` step passes), and a run no build stamped396 * reports this too (`apps/cli/src/version.ts`).397 */398const UNRELEASED = "0.0.0";399400/**
136 unmodified lines