Cotton code
348 lines · 15.0 KB · TypeScriptRaw
import { execFileSync } from "node:child_process";import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { describe, expect, it } from "vitest";import {  bindingAbiMismatch,  bindingMessage,  bindingMismatchFor,  bindingMismatchFrom,  NOT_OURS,  OWNED_TEST_FILES,  repoRootFrom,  requiredNodeLabel,  setup,  uncollectedMessage,  uncollectedTestFiles,} from "../../vitest.testfiles";const ROOT = path.resolve(__dirname, "../..");/** A throwaway package tree: `files` are paths relative to its root. */function packageWith(files: string[]): string {  const root = mkdtempSync(path.join(tmpdir(), "cotton-testfiles-"));  for (const file of files) {    const full = path.join(root, file);    mkdirSync(path.dirname(full), { recursive: true });    writeFileSync(full, "import { it, expect } from 'vitest';\nit('x', () => expect(1).toBe(1));\n");  }  return root;}describe("uncollectedTestFiles — the files an `include` never reaches", () => {  it("answers nothing when every test file is collected", async () => {    const root = packageWith(["__tests__/a.test.ts", "__tests__/nested/b.test.ts"]);    expect(await uncollectedTestFiles({ root, include: ["__tests__/**/*.test.{ts,tsx}"] })).toEqual([]);  });  // RULE: A test file no configuration picks up is invisible rather than skipped, so every test file has to be reachable.  it("names a co-located test the package's glob misses", async () => {    // The measured failure: green run, exit 0, that file's tests never ran.    const root = packageWith(["__tests__/a.test.ts", "src/thing/__tests__/b.test.ts"]);    expect(await uncollectedTestFiles({ root, include: ["__tests__/**/*.test.ts"] })).toEqual([      "src/thing/__tests__/b.test.ts",    ]);  });  it("is satisfied by the wider glob apps/cotton actually uses", async () => {    const root = packageWith(["__tests__/a.test.ts", "src/thing/__tests__/b.test.ts"]);    const include = ["__tests__/**/*.test.{ts,tsx}", "src/**/__tests__/**/*.test.{ts,tsx}"];    expect(await uncollectedTestFiles({ root, include })).toEqual([]);  });  it("counts .tsx as well as .ts", async () => {    const root = packageWith(["src/__tests__/Screen.test.tsx"]);    expect(await uncollectedTestFiles({ root, include: ["__tests__/**/*.test.ts"] })).toEqual([      "src/__tests__/Screen.test.tsx",    ]);  });  it("ignores installed packages, build output and the native projects", async () => {    const root = packageWith([      "node_modules/dep/__tests__/x.test.ts",      "dist/__tests__/x.test.ts",      "ios/__tests__/x.test.ts",      "e2e/__tests__/x.test.ts",    ]);    expect(await uncollectedTestFiles({ root, include: ["__tests__/**/*.test.ts"] })).toEqual([]);  });  it("honours the config's own `exclude`, so a deliberate exclusion is not a failure", async () => {    const root = packageWith(["__tests__/a.test.ts", "src/__tests__/slow.test.ts"]);    const missing = await uncollectedTestFiles({      root,      include: ["__tests__/**/*.test.ts"],      exclude: ["src/**"],    });    expect(missing).toEqual([]);  });  it("does not treat a non-test file under __tests__ as a test", async () => {    const root = packageWith(["__tests__/a.test.ts", "__tests__/helpers.ts", "__tests__/setup.ts"]);    expect(await uncollectedTestFiles({ root, include: ["__tests__/**/*.test.ts"] })).toEqual([]);  });});describe("setup — how the guard fails a run", () => {  it("throws, naming every uncollected file and the patterns that missed it", async () => {    const root = packageWith(["src/__tests__/b.test.ts"]);    await expect(setup({ config: { root, include: ["__tests__/**/*.test.ts"] } })).rejects.toThrow(      /src\/__tests__\/b\.test\.ts/,    );  });  it("passes silently when the package is clean", async () => {    const root = packageWith(["__tests__/a.test.ts"]);    await expect(setup({ config: { root, include: ["__tests__/**/*.test.ts"] } })).resolves.toBeUndefined();  });  it("throws rather than skipping when vitest's argument changes shape", async () => {    // A guard that cannot read its input has stopped guarding; that must look    // like a failure, not like a pass.    await expect(setup({} as never)).rejects.toThrow(/changed shape/);    await expect(setup({ config: { root: "/tmp" } } as never)).rejects.toThrow(/changed shape/);  });  it("says what to do about it", () => {    const message = uncollectedMessage({ root: "/pkg", include: ["__tests__/**"] }, ["src/__tests__/b.test.ts"]);    expect(message).toContain("src/__tests__/b.test.ts");    expect(message).toContain("__tests__/**");    expect(message).toMatch(/widen `include`|move the file/);  });});describe("every package that runs vitest wires the guard", () => {  const manifests = execFileSync("git", ["ls-files", "packages/*/package.json", "apps/*/package.json"], {    cwd: ROOT,    encoding: "utf8",  })    .split("\n")    .filter(Boolean);  const dirs = manifests    .filter((m) => {      const pkg = JSON.parse(readFileSync(path.join(ROOT, m), "utf8")) as { scripts?: Record<string, string> };      return pkg.scripts?.test?.includes("vitest");    })    .map((m) => path.dirname(m));  it.each(dirs)("%s runs vitest.testfiles.ts as its globalSetup", (dir) => {    const config = ["vitest.config.ts", "vite.config.ts"]      .map((name) => path.join(ROOT, dir, name))      .find((file) => {        try {          readFileSync(file, "utf8");          return true;        } catch {          return false;        }      });    expect(config).toBeDefined();    const text = readFileSync(config as string, "utf8").replace(/\s+/g, " ");    expect(text).toMatch(/globalSetup: \[\s*"\.\.\/\.\.\/vitest\.testfiles\.ts"\s*\]/);  });});describe("what the guard considers a test file", () => {  it("matches this repo's stated convention — __tests__/ or a package's test/, .test.ts(x)", () => {    expect(OWNED_TEST_FILES).toBe("**/{__tests__,test}/**/*.test.{ts,tsx}");  });  it("leaves e2e to Playwright", () => {    expect(NOT_OURS).toContain("**/e2e/**");  });  // THERE IS NO EXEMPTION ANY MORE. The one suite deliberately outside  // `__tests__/` was the Rust core's TypeScript conformance harness, and step  // 5i deleted it with the TypeScript store it compared against: its four  // lanes are Rust integration tests now, reached by `cargo test` rather than  // by any vitest include. Every tracked test file is under `__tests__/`, or  // under the business Worker's `test/` (the pool-workers layout).  it("holds for the whole tree: every tracked test file lives under __tests__ or a package's test/", () => {    // If this ever fails, the convention moved and OWNED_TEST_FILES must move    // with it — otherwise the guard silently stops seeing a whole shape of file.    const tracked = execFileSync("git", ["ls-files"], { cwd: ROOT, encoding: "utf8" })      .split("\n")      .filter((f) => /\.test\.tsx?$/.test(f));    // A floor, not a headcount: it catches `git ls-files` finding NOTHING,    // which reads as a green run over an empty tree. The number fell from 500+    // to under a hundred when the phone wave and then the flip took their    // packages out, and it will keep falling.    expect(tracked.length).toBeGreaterThan(50);    expect(tracked.filter((f) => !f.includes("/__tests__/") && !/^apps\/[^/]+\/test\//.test(f))).toEqual([]);  });});describe("the native binding — the wrong Node, said once instead of eighty-two times", () => {  /**   * Verbatim from a Node 20 shell against a Node 22 install, 2026-09-07. The   * guard parses THIS, not a shape somebody imagined: the wording is the only   * contract better-sqlite3 offers, and a regex written from memory is a   * guard that quietly stops matching.   */  const REAL = [    "The module '/repo/node_modules/better-sqlite3/build/Release/better_sqlite3.node'",    "was compiled against a different Node.js version using",    "NODE_MODULE_VERSION 127. This version of Node.js requires",    "NODE_MODULE_VERSION 115. Please try re-compiling or re-installing",    "the module (for instance, using `npm rebuild` or `npm install`).",  ].join("\n");  it("reads BOTH ABI numbers out of the real error, in the right order", () => {    expect(bindingAbiMismatch(new Error(REAL))).toEqual({ built: 127, running: 115 });  });  it("hardcodes neither number — a rebuilt binding reports its own", () => {    const later = REAL.replace("127", "137").replace("115", "127");    expect(bindingAbiMismatch(new Error(later))).toEqual({ built: 137, running: 127 });  });  it("claims ONLY this failure — a missing or broken addon is somebody else's sentence", () => {    expect(bindingAbiMismatch(new Error("Cannot find module 'better-sqlite3'"))).toBeNull();    expect(bindingAbiMismatch(new Error("dlopen(...): symbol not found"))).toBeNull();    expect(bindingAbiMismatch(undefined)).toBeNull();    expect(bindingAbiMismatch("NODE_MODULE_VERSION 127")).toBeNull();  });  /**   * The defect this guard shipped with, caught by the same walk that found   * the rest: `better-sqlite3` binds LAZILY. `require()` returns the JS entry   * and touches no addon, so a require-only probe passes on a Node the   * binding cannot serve — measured, with one single-ABI .node "loading"   * under both Node 20 and Node 22. The addon is reached on construction,   * which is what a test does.   */  /**   * The defect this guard shipped with, caught by the same walk that found   * the rest: `better-sqlite3` binds LAZILY. `require()` returns the JS entry   * and touches no addon, so a require-only probe passes on a Node the   * binding cannot serve — measured, with one single-ABI .node "loading"   * under both Node 20 and Node 22 while `new Database()` threw.   *   * So this stands up a package whose require SUCCEEDS and whose constructor   * throws the real error, which is the shape of the thing being guarded. A   * probe that only requires cannot pass this test.   */  it("reaches the addon by OPENING a database, not by requiring the module", () => {    const root = mkdtempSync(path.join(tmpdir(), "cotton-lazybind-"));    const pkg = path.join(root, "node_modules", "better-sqlite3");    mkdirSync(pkg, { recursive: true });    writeFileSync(      path.join(pkg, "package.json"),      JSON.stringify({ name: "better-sqlite3", version: "0.0.0", main: "index.js" }),    );    // Requiring is free; the addon is reached on construction. Exactly what    // the real module does.    writeFileSync(      path.join(pkg, "index.js"),      `module.exports = class { constructor() { throw new Error(${JSON.stringify(REAL)}); } };\n`,    );    expect(bindingMismatchFor(root)).toEqual({ built: 127, running: 115 });  });  it("stays silent when that same package constructs cleanly", () => {    const root = mkdtempSync(path.join(tmpdir(), "cotton-lazybind-ok-"));    const pkg = path.join(root, "node_modules", "better-sqlite3");    mkdirSync(pkg, { recursive: true });    writeFileSync(      path.join(pkg, "package.json"),      JSON.stringify({ name: "better-sqlite3", version: "0.0.0", main: "index.js" }),    );    writeFileSync(      path.join(pkg, "index.js"),      "module.exports = class { close() {} };\n",    );    expect(bindingMismatchFor(root)).toBeNull();  });  it("answers null when the addon loads, and the mismatch when it does not", () => {    expect(bindingMismatchFrom(() => {})).toBeNull();    expect(      bindingMismatchFrom(() => {        throw new Error(REAL);      }),    ).toEqual({ built: 127, running: 115 });  });  it("passes over a load that failed for any other reason", () => {    expect(      bindingMismatchFrom(() => {        throw new Error("EACCES: permission denied");      }),    ).toBeNull();  });  it("skips a package that cannot reach the addon at all, silently", () => {    // A directory with no node_modules above it resolves nothing, and a    // package with nothing to break must not be failed by this guard.    expect(bindingMismatchFor(mkdtempSync(path.join(tmpdir(), "cotton-nobinding-")))).toBeNull();  });  it("names both versions and the pinned Node in the first sentence", () => {    const said = bindingMessage({ built: 127, running: 115 }, "Node 22");    const first = said.split("\n")[0];    expect(first).toContain("127");    expect(first).toContain("115");    expect(first).toContain("Node 22");    // The whole point: it must not read as a code failure.    expect(said).toContain("Nothing is wrong with the tests.");  });  /**   * The remedy is the half a message like this is actually read for, and the   * obvious two commands do NOT work. Measured on this repo, 2026-09-07, with   * a Node 20 shell against a Node 22 build: `pnpm rebuild better-sqlite3`   * and `pnpm install` both left the .node byte-for-byte and mtime-for-mtime   * unchanged — pnpm serves the cached binary — while `npm rebuild   * --build-from-source` inside the package flipped it to the running ABI.   * A sentence naming a command that does nothing is worse than none.   */  it("gives the rebuild that WORKS, and names the two that do not", () => {    const said = bindingMessage({ built: 115, running: 127 }, "Node 22");    expect(said).toContain("npm rebuild --build-from-source");    expect(said).toMatch(/pnpm install.*do NOT|do NOT.*pnpm install/s);    expect(said).toContain("pnpm rebuild better-sqlite3");    // Switching Node is real but conditional — it only helps in one    // direction, and the sentence has to say which.    expect(said).toMatch(/only helps when/i);  });  it("reads the required Node from .nvmrc, then engines, then says neither", () => {    const pinned = mkdtempSync(path.join(tmpdir(), "cotton-node-"));    writeFileSync(path.join(pinned, ".nvmrc"), "v22\n");    expect(requiredNodeLabel(pinned)).toBe("Node 22");    const engined = mkdtempSync(path.join(tmpdir(), "cotton-node-"));    writeFileSync(path.join(engined, "package.json"), JSON.stringify({ engines: { node: ">=22" } }));    expect(requiredNodeLabel(engined)).toBe("Node >=22");    const bare = mkdtempSync(path.join(tmpdir(), "cotton-node-"));    expect(requiredNodeLabel(bare)).toContain("this repo installs against");  });  it("finds the repo root by its workspace file, from any package under it", () => {    // Walked rather than taken from this module's location: the file is    // loaded as ESM config by vitest and through vite's transform by this    // test, and `import.meta` is not available both ways.    expect(repoRootFrom(path.join(ROOT, "packages/store"))).toBe(ROOT);    expect(repoRootFrom(ROOT)).toBe(ROOT);  });  it("answers a directory even with no workspace above it", () => {    const orphan = mkdtempSync(path.join(tmpdir(), "cotton-orphan-"));    expect(repoRootFrom(orphan)).toBe(path.resolve(orphan));  });  it("this repo's own root is found, and pins Node 22", () => {    // A real read, so a moved `.nvmrc` or a raised floor shows up here rather    // than in a sentence telling somebody to install the wrong version.    expect(requiredNodeLabel(ROOT)).toBe("Node 22");  });});