Cotton code
277 lines · 11.6 KB · TypeScriptRaw
// Every test file this package owns must actually be COLLECTED.//// WHY THIS FILE EXISTS. Vitest is loud about the failures you would expect: a// file with a syntax error fails its transform and the run goes red; a file// that registers no tests fails with "No test suite found in file". Both were// measured on this repo before this guard was written. The one it cannot see// is a test file whose path the package's `include` never matches — that file// is not "skipped", it is INVISIBLE, and the suite reports green with a lower// number nobody was counting.//// It is a real drift, not a hypothetical: `include` is per package here (most// are `__tests__/**`, `apps/cotton` adds `src/**/__tests__/**`, the site is// `src/**` only), so a test co-located in a package whose glob does not reach// it disappears silently. Reproduced on this branch in `packages/relay`: a// deliberately FAILING test placed at `src/__tests__/` left the run green at// "14 passed", exit 0.//// The check runs in `globalSetup`, before any test: it sees the RESOLVED// config (so a preset's `include` is already merged in) and a throw there// fails the run immediately, naming the files. Both sides of the comparison// use the same globber with the same options, so the diff cannot drift on// matcher semantics.import { createRequire } from "node:module";import { existsSync, readFileSync } from "node:fs";import * as path from "node:path";import { glob } from "tinyglobby";/** * What this repo calls a test file, wherever it lives: in `__tests__/` beside * the source, or in a package's `test/` folder — the business Worker's, where * `@cloudflare/vitest-pool-workers` keeps its tests beside `src/`. */export const OWNED_TEST_FILES = "**/{__tests__,test}/**/*.test.{ts,tsx}";/** * Never ours to collect: build output, installed packages, the native * projects, and `e2e/` — Playwright owns that one and vitest must not. */export const NOT_OURS = [  "**/node_modules/**",  "**/dist/**",  "**/build/**",  "**/coverage/**",  "**/.turbo/**",  "**/ios/**",  "**/android/**",  "**/e2e/**",];export interface CollectionConfig {  root: string;  include: string[];  exclude?: string[];}/** * The test files on disk that this config's `include` does NOT reach. * * Both globs run from the same cwd with the same ignore list, so a file is * "uncollected" only because `include` missed it — never because the two sides * disagreed about what a path means. */export async function uncollectedTestFiles(config: CollectionConfig): Promise<string[]> {  const options = {    cwd: config.root,    ignore: [...NOT_OURS, ...(config.exclude ?? [])],    absolute: false,    dot: false,  };  const [owned, collected] = await Promise.all([    glob(OWNED_TEST_FILES, options),    glob(config.include, options),  ]);  const seen = new Set(collected);  return owned.filter((file) => !seen.has(file)).sort();}/** The message a failing run prints. Exported so the guard's own test asserts the wording. */export function uncollectedMessage(config: CollectionConfig, missing: string[]): string {  const one = missing.length === 1;  return [    `${missing.length} test file${one ? "" : "s"} in this package will never run — no \`include\` pattern matches ${one ? "it" : "them"}:`,    ...missing.map((file) => `  • ${file}`),    "",    `  package: ${config.root}`,    `  include: ${config.include.join(", ")}`,    "",    "  A file vitest does not collect is not skipped, it is invisible: the suite",    "  passes and its tests simply never ran. Either widen `include` in this",    "  package's vitest config, or move the file under a directory it matches.",  ].join("\n");}// ─────────────────────────────────────────────────────────────────────────// The native binding, and the Node it was built for.//// WHY THIS IS HERE TOO. `better-sqlite3` is a compiled addon: it is built for// one ABI (`NODE_MODULE_VERSION`) at install time, and loading it on a Node// with a different one throws. That throw happens per test file, deep inside// `bindings`, so a whole run comes back as dozens of ordinary-looking// failures with the real cause visible only inside a stack trace. Measured on// this repo: a Node 20 shell against a Node 22 install reported "82 failed"// across three files, every one of them that single error, and the run's// summary said nothing about Node at all. A count like that reads as a// regression, and the honest report of it is a regression that does not exist.//// So it is checked ONCE, before any test, in the same `globalSetup` that// already runs everywhere.//// The built ABI is read out of the LOAD ERROR, never written down here: the// number moves when the binding is rebuilt or the Node floor rises, and a// constant in this file would go stale silently — which is the failure this// guard exists to prevent, one level up./** What the addon was built for, and what is running — both as ABI numbers. */export interface BindingAbiMismatch {  built: number;  running: number;}/** * The ABI mismatch inside a module-load error, or null for any other failure. * * Only this one shape is claimed. A binding that is missing, corrupt or built * for another platform is a different problem with a different fix, and * dressing it up as "wrong Node" would send somebody to switch versions over * a broken install. */export function bindingAbiMismatch(error: unknown): BindingAbiMismatch | null {  const text = error instanceof Error ? error.message : String(error ?? "");  const found =    /compiled against a different Node\.js version using\s+NODE_MODULE_VERSION (\d+)[\s\S]*?requires\s+NODE_MODULE_VERSION (\d+)/.exec(      text,    );  if (!found) return null;  return { built: Number(found[1]), running: Number(found[2]) };}/** * The repo root: the nearest directory at or above `from` holding * `pnpm-workspace.yaml`. * * Walked rather than derived from this module's own location, because that * needs `import.meta.url` or `__dirname` and this file is loaded both ways — * by vitest as ESM config, and by its own test through vite's transform. * Answers `from` unchanged when there is no workspace above it, so a caller * always gets a usable directory. */export function repoRootFrom(from: string): string {  let at = path.resolve(from);  for (;;) {    if (existsSync(path.join(at, "pnpm-workspace.yaml"))) return at;    const up = path.dirname(at);    if (up === at) return path.resolve(from);    at = up;  }}/** * The Node this repo asks for, read from `.nvmrc` and then `engines.node`. * * Read rather than written down for the same reason as the ABI number: the * floor moves, and a sentence telling somebody to install a version the repo * no longer uses is worse than one that names none. */export function requiredNodeLabel(repoRoot: string): string {  try {    const pinned = readFileSync(path.join(repoRoot, ".nvmrc"), "utf8").trim();    if (pinned) return `Node ${pinned.replace(/^v/, "")}`;  } catch {    // No .nvmrc — fall through to the manifest.  }  try {    const manifest: unknown = JSON.parse(      readFileSync(path.join(repoRoot, "package.json"), "utf8"),    );    const range =      typeof manifest === "object" && manifest !== null        ? (manifest as { engines?: { node?: unknown } }).engines?.node        : undefined;    if (typeof range === "string" && range.length > 0) return `Node ${range}`;  } catch {    // No manifest either: say so without naming a version we cannot verify.  }  return "the Node version this repo installs against";}/** The message a failing run prints. Exported so the guard's own test asserts the wording. */export function bindingMessage(mismatch: BindingAbiMismatch, required: string): string {  return [    `better-sqlite3 was built for NODE_MODULE_VERSION ${mismatch.built}, but this Node is ` +      `NODE_MODULE_VERSION ${mismatch.running} — this repo pins ${required}.`,    "",    "  Every test that opens a database would fail with this same error, one file",    "  at a time, and the run's summary would look like a code regression rather",    "  than the wrong Node. Nothing is wrong with the tests.",    "",    "  Rebuild the addon for the Node you are running:",    "    cd node_modules/better-sqlite3 && npm rebuild --build-from-source",    "",    "  `pnpm install` and `pnpm rebuild better-sqlite3` do NOT do this. Both are",    "  no-ops once a built copy is present — pnpm serves the cached binary and",    "  leaves the file untouched, mtime and all (measured on this repo,",    "  2026-09-07). Switching Node is the other way out, and only helps when the",    "  addon was built for the Node you are switching to.",  ].join("\n");}/** * The mismatch behind a loader that threw, or null if it did not. * * The loader is a parameter so this is testable without a broken install: an * ABI mismatch exists only when the addon on disk disagrees with the running * Node, which is not a state a test can create for itself, and a guard that * could only be exercised by breaking the machine would never be exercised. */export function bindingMismatchFrom(load: () => void): BindingAbiMismatch | null {  try {    load();    return null;  } catch (error) {    return bindingAbiMismatch(error);  }}/** * Load the addon the way a test would, and answer the ABI mismatch if that is * why it failed. * * Resolution is attempted FROM THE PACKAGE UNDER TEST, and a package that * cannot reach `better-sqlite3` is skipped silently — it has nothing to * break. Any other load failure is passed over too: this guard claims one * specific confusion, and it must not become the place unrelated install * problems surface wearing the wrong sentence. */export function bindingMismatchFor(packageRoot: string): BindingAbiMismatch | null {  const require = createRequire(path.join(packageRoot, "noop.js"));  let entry: string;  try {    entry = require.resolve("better-sqlite3");  } catch {    return null;  }  return bindingMismatchFrom(() => {    // OPENING a database, not just requiring the module. `better-sqlite3`    // binds LAZILY: `require()` returns the JS entry and touches no addon at    // all, so a require-only check passes on a Node the binding cannot serve    // — measured here, both Nodes "loading" the same single-ABI .node. The    // addon is reached on construction, which is exactly what a test does.    const Database = require(entry) as new (file: string) => { close: () => void };    new Database(":memory:").close();  });}/** Vitest's `globalSetup` entry point — see the file header. */export async function setup(project: { config?: Partial<CollectionConfig> }): Promise<void> {  const config = project?.config;  if (!config || typeof config.root !== "string" || !Array.isArray(config.include)) {    // Never skip quietly: a guard that cannot read its input has stopped    // guarding, and that must look like a failure, not like a pass.    throw new Error(      "vitest.testfiles: could not read `root` and `include` off the resolved config — " +        "vitest's globalSetup argument changed shape. Fix this guard rather than removing it.",    );  }  // The native binding first: when the Node is wrong every other check is  // about to report the same error wearing a different hat.  const mismatch = bindingMismatchFor(config.root);  if (mismatch) {    throw new Error(bindingMessage(mismatch, requiredNodeLabel(repoRootFrom(config.root))));  }  const missing = await uncollectedTestFiles(config as CollectionConfig);  if (missing.length > 0) throw new Error(uncollectedMessage(config as CollectionConfig, missing));}