Skip to content
Myr

build.test.ts

This file

Path

apps/cli/test/build.test.ts

523 lines · 15.0 KiB · TypeScript

Last changed by

Merge build/comments-cli-protocol-checks into mainoscabrielbefore adoptionc86204f

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { expect, layer } from "@effect/vitest";3import { Brand } from "@repo/brand";4import {5  Config,6  Context,7  Effect,8  FileSystem,9  Hash,10  Layer,11  Path,12  Schema,13  Stream,14} from "effect";15import { ChildProcess, ChildProcessSpawner } from "effect/process";1617interface Ran {18  readonly exitCode: number;19  readonly stderr: string;20  readonly stdout: string;21}2223const text = <E>(bytes: Stream.Stream<Uint8Array, E>) =>24  bytes.pipe(Stream.decodeText(), Stream.mkString);2526interface Bare {27  readonly HOME: string;28  readonly PATH: string;29  readonly XDG_CONFIG_HOME: string;30}3132const run = (33  command: string,34  args: readonly string[],35  options: {36    readonly cwd?: string;37    readonly only?: Bare;38    readonly stdin?: string;39  } = {}40) =>41  Effect.scoped(42    Effect.gen(function* () {43      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;4445      const child = yield* spawner.spawn(46        ChildProcess.make(command, args, {47          cwd: options.cwd,48          env: { ...options.only },49          extendEnv: options.only === undefined,50          stdin:51            options.stdin === undefined52              ? "ignore"53              : Stream.make(new TextEncoder().encode(options.stdin)),54        })55      );5657      const [stdout, stderr, exitCode] = yield* Effect.all(58        [text(child.stdout), text(child.stderr), child.exitCode],59        { concurrency: "unbounded" }60      );6162      return { exitCode, stderr, stdout } satisfies Ran;63    })64  ).pipe(Effect.orDie);6566const npmFiles = (dist: string) =>67  Effect.gen(function* () {68    const fs = yield* FileSystem.FileSystem;69    const path = yield* Path.Path;70    const files: Record<string, number> = {};7172    if (yield* fs.exists(dist)) {73      for (const file of yield* fs.readDirectory(dist)) {74        if (/\.(?:js|d\.ts)$/u.test(file)) {75          files[file] = Hash.string(76            yield* fs.readFileString(path.join(dist, file))77          );78        }79      }80    }8182    return files;83  });8485class Built extends Context.Service<86  Built,87  {88    readonly build: Ran;89    readonly rebuild: Ran;90    readonly firstFiles: Readonly<Record<string, number>>;91    readonly secondFiles: Readonly<Record<string, number>>;92    readonly root: string;93    readonly dist: string;94    readonly bare: Bare;95    readonly onPath: Bare;96    readonly withNode: Bare;97  }98>()("cli/test/Built") {}99100const BuiltOnce = Layer.effect(101  Built,102  Effect.gen(function* () {103    const fs = yield* FileSystem.FileSystem;104    const path = yield* Path.Path;105    const root = yield* path.fromFileUrl(new URL("..", import.meta.url));106    const dist = path.join(root, "dist");107    const home = yield* fs.makeTempDirectoryScoped({ prefix: "cli-build-" });108    const empty = path.join(home, "empty-bin");109    const config = path.join(home, "config");110111    yield* fs.makeDirectory(empty);112    yield* fs.makeDirectory(config);113114    const build = yield* run("bun", ["run", "build"], { cwd: root });115    const firstFiles = yield* npmFiles(dist);116    const rebuild = yield* run("bun", ["run", "build"], { cwd: root });117    const secondFiles = yield* npmFiles(dist);118    const bare = { HOME: home, PATH: empty, XDG_CONFIG_HOME: config };119120    return Built.of({121      bare,122      build,123      dist,124      firstFiles,125      onPath: { ...bare, PATH: path.join(dist, "bin") },126      rebuild,127      root,128      secondFiles,129      withNode: { ...bare, PATH: yield* Config.String("PATH") },130    });131  })132).pipe(Layer.provideMerge(NodeServices.layer));133134const written = (...segments: readonly string[]) =>135  Effect.gen(function* () {136    const { dist } = yield* Built;137    const fs = yield* FileSystem.FileSystem;138    const path = yield* Path.Path;139    const file = path.join(dist, ...segments);140    const label = ["dist", ...segments].join("/");141142    expect({ [label]: yield* fs.exists(file) }).toStrictEqual({143      [label]: true,144    });145146    return file;147  });148149const spawning = { timeout: 60_000 };150151const banner = [152  "Start here:",153  `${Brand.cli} asks      list the open asks you could take`,154  `${Brand.cli} claim     take one; you get a fork to push your answer to`,155  `${Brand.cli} check     run the gate's checks locally before you push`,156];157158const bannerIn = (stdout: string) => {159  const lines = stdout.split("\n").map((line) => line.trim());160  const start = lines.indexOf("Start here:");161162  return start === -1 ? [] : lines.slice(start, start + banner.length);163};164165const exportedNames = (source: string) => {166  const listed = [167    ...source.matchAll(/\bexport\s+(?:type\s+)?\{(?<list>[^}]*)\}/gu),168  ]169    .flatMap((match) => (match.groups?.list ?? "").split(","))170    .map((entry) =>171      (172        entry173          .trim()174          .replace(/^type\s+/u, "")175          .split(/\s+as\s+/u)176          .at(-1) ?? ""177      ).trim()178    );179180  const declared = [181    ...source.matchAll(182      /\bexport\s+(?:declare\s+)?(?:const|let|function|class|type|interface|enum)\s+(?<name>[\w$]+)/gu183    ),184  ].map((match) => match.groups?.name ?? "");185186  const starred = /\bexport\s*\*/u.test(source) ? ["*"] : [];187188  return [...new Set([...listed, ...declared, ...starred])]189    .filter((name) => name.length > 0)190    .toSorted();191};192193const request = "protocol=https\nhost=example.test\n\n";194195// A static import or export quotes its module, never with backticks, so196// prose in a doc comment is not one.197const workspaceSpecifier =198  /(?:\b(?:from|import)\s*["']|\b(?:import|require)\s*\(\s*["'`])@repo\//u;199200layer(BuiltOnce, { excludeTestServices: true, timeout: "180 seconds" })(201  "bun run build",202  (it) => {203    it.effect(204      "exits 0 and writes the binary, its helper link and the npm entries",205      () =>206        Effect.gen(function* () {207          const { build } = yield* Built;208          const fs = yield* FileSystem.FileSystem;209210          expect(build).toMatchObject({ exitCode: 0 });211212          for (const file of [213            "bin.js",214            "rules.js",215            "rules.d.ts",216            "protocol.js",217            "protocol.d.ts",218          ]) {219            yield* written(file);220          }221222          const binary = yield* fs.stat(yield* written("bin", Brand.cli));223224          expect(binary.type).toBe("File");225          expect(Math.floor(binary.mode / 0o100) % 2).toBe(1);226227          // A link, not a shim: the compiled binary sees the name it was228          // invoked by.229          expect(230            yield* fs.readLink(yield* written("bin", Brand.gitCredentialHelper))231          ).toBe(Brand.cli);232        })233    );234235    it.effect(236      "the binary prints the banner with neither bun nor node on its PATH",237      () =>238        Effect.gen(function* () {239          const { bare } = yield* Built;240241          const help = yield* run(242            yield* written("bin", Brand.cli),243            ["--help"],244            {245              only: bare,246            }247          );248249          expect(help).toMatchObject({ exitCode: 0 });250          expect(bannerIn(help.stdout)).toStrictEqual(banner);251        }),252      spawning253    );254255    it.effect(256      "the binary evaluates a TypeScript config folder for check with neither bun nor node on its PATH",257      () =>258        Effect.gen(function* () {259          const { bare } = yield* Built;260          const fs = yield* FileSystem.FileSystem;261          const path = yield* Path.Path;262          const binary = yield* written("bin", Brand.cli);263264          const repo = yield* fs.makeTempDirectoryScoped({265            prefix: "ts-config-",266          });267268          const tools = path.join(bare.HOME, "git-only-bin");269270          // git alone on the PATH: `check` reads the repo with it.271          yield* fs.makeDirectory(tools, { recursive: true });272          yield* fs.symlink("/usr/bin/git", path.join(tools, "git"));273274          const env = { ...bare, PATH: tools };275276          const git = (...args: readonly string[]) =>277            run("git", args, { cwd: repo, only: env }).pipe(278              Effect.tap((ran) =>279                Effect.sync(() => {280                  expect(ran).toMatchObject({ exitCode: 0 });281                })282              )283            );284285          yield* fs.makeDirectory(path.join(repo, Brand.configDir));286          yield* fs.writeFileString(287            path.join(repo, Brand.configDir, "project.ts"),288            [289              `import { project } from "${Brand.cliPackage}/rules";`,290              "",291              "export default project({",292              '  run: { checks: { unit: "true" }, test: "true {path}" },',293              "});",294              "",295            ].join("\n")296          );297298          yield* git("init", "--quiet", "--initial-branch=main");299          yield* git("add", ".");300          yield* git(301            "-c",302            "user.name=Ada",303            "-c",304            "user.email=ada@example.test",305            "commit",306            "--quiet",307            "--message",308            "Write the project in TypeScript"309          );310311          // The policy evaluates, so the ask it lacks is the refusal.312          const checked = yield* run(313            binary,314            [315              "check",316              "--offline",317              "--shape-only",318              "--json",319              "--project",320              "datekit",321              "--ask",322              "fix-week",323            ],324            { cwd: repo, only: env }325          );326327          expect({328            exitCode: checked.exitCode,329            stderr: checked.stderr,330          }).toStrictEqual({331            // UnknownAsk: the ask named is not one the policy has.332            exitCode: 66,333            stderr: "",334          });335336          const envelope = yield* Schema.decodeEffect(337            Schema.fromJsonString(338              Schema.Struct({339                ok: Schema.Boolean,340                refusals: Schema.Array(Schema.Struct({ _tag: Schema.String })),341              })342            )343          )(checked.stdout);344345          expect({346            ok: envelope.ok,347            tags: envelope.refusals.map(({ _tag }) => _tag),348          }).toStrictEqual({ ok: false, tags: ["UnknownAsk"] });349        }).pipe(Effect.scoped),350      spawning351    );352353    it.effect(354      `invoked as ${Brand.gitCredentialHelper}, the binary is its credential command`,355      () =>356        Effect.gen(function* () {357          const { onPath } = yield* Built;358          const binary = yield* written("bin", Brand.cli);359360          yield* written("bin", Brand.gitCredentialHelper);361362          const helper = yield* run(Brand.gitCredentialHelper, ["get"], {363            only: onPath,364            stdin: request,365          });366367          const direct = yield* run(binary, ["credential", "get"], {368            only: onPath,369            stdin: request,370          });371372          const unrouted = yield* run(binary, ["get"], {373            only: onPath,374            stdin: request,375          });376377          // No profile is stored under the temp HOME: the helper says378          // nothing, so git goes on without a credential.379          expect(helper).toMatchObject({ exitCode: 0, stdout: "" });380          expect(helper).toStrictEqual(direct);381          expect(helper).not.toStrictEqual(unrouted);382        }),383      spawning384    );385386    it.effect(387      "node runs the npm entry, so the npm build is not Bun-only",388      () =>389        Effect.gen(function* () {390          const { withNode } = yield* Built;391392          // vitest runs under Node, so `node` is on this machine's PATH.393          const help = yield* run(394            "node",395            [yield* written("bin.js"), "--help"],396            {397              only: withNode,398            }399          );400401          expect(help).toMatchObject({ exitCode: 0 });402          expect(bannerIn(help.stdout)).toStrictEqual(banner);403        }),404      spawning405    );406407    it.effect(408      `under node, an npm bin link named ${Brand.gitCredentialHelper} is the credential command too`,409      () =>410        Effect.gen(function* () {411          const { withNode } = yield* Built;412          const fs = yield* FileSystem.FileSystem;413          const path = yield* Path.Path;414          const entry = yield* written("bin.js");415416          // npm links each `bin` name to the entry; node then sees the417          // link's path as `argv[1]`.418          const link = path.join(withNode.HOME, Brand.gitCredentialHelper);419420          yield* fs.symlink(entry, link);421422          const helper = yield* run("node", [link, "get"], {423            only: withNode,424            stdin: request,425          });426427          const direct = yield* run("node", [entry, "credential", "get"], {428            only: withNode,429            stdin: request,430          });431432          expect(helper).toStrictEqual(direct);433        }),434      spawning435    );436437    it.effect(438      "rules.js imports in Bun as the whole sdk, and no dist file imports a workspace package",439      () =>440        Effect.gen(function* () {441          const { dist, root } = yield* Built;442          const fs = yield* FileSystem.FileSystem;443          const path = yield* Path.Path;444          const rules = yield* written("rules.js");445446          // Run from the CLI package, where `@repo/sdk` resolves.447          const imported = yield* run(448            "bun",449            [450              "--eval",451              `const rules = await import(${JSON.stringify(rules)});452const sdk = await import("@repo/sdk");453console.log(JSON.stringify({454  kind: typeof rules.kind,455  missing: Object.keys(sdk).filter((name) => !(name in rules)),456  project: typeof rules.project,457}));`,458            ],459            { cwd: root }460          );461462          expect(imported).toMatchObject({ exitCode: 0 });463          expect(JSON.parse(imported.stdout)).toStrictEqual({464            kind: "function",465            missing: [],466            project: "function",467          });468469          const files = (yield* fs.readDirectory(dist)).filter((file) =>470            /\.(?:js|d\.ts)$/u.test(file)471          );472473          expect(files).toContain("rules.d.ts");474475          const importing: string[] = [];476477          for (const file of files) {478            if (479              workspaceSpecifier.test(480                yield* fs.readFileString(path.join(dist, file))481              )482            ) {483              importing.push(file);484            }485          }486487          expect(importing).toStrictEqual([]);488        }),489      spawning490    );491492    it.effect(493      "rules.d.ts declares every name the sdk exports, its types included",494      () =>495        Effect.gen(function* () {496          const { root } = yield* Built;497          const fs = yield* FileSystem.FileSystem;498          const path = yield* Path.Path;499500          const sdk = yield* fs.readFileString(501            path.join(root, "..", "..", "packages", "sdk", "src", "index.ts")502          );503504          const declared = yield* fs.readFileString(505            yield* written("rules.d.ts")506          );507508          expect(exportedNames(sdk)).toContain("project");509          expect(exportedNames(declared)).toStrictEqual(exportedNames(sdk));510        })511    );512513    it.effect("a second build writes the same npm files", () =>514      Effect.gen(function* () {515        const { firstFiles, rebuild, secondFiles } = yield* Built;516517        expect(rebuild).toMatchObject({ exitCode: 0 });518        expect(Object.keys(firstFiles)).toContain("rules.d.ts");519        expect(secondFiles).toStrictEqual(firstFiles);520      })521    );522  }523);