{"draft":null,"from":96,"to":97,"files":[{"path":"scripts/check-changed.mjs","added":239,"removed":0,"diff":"--- /dev/null\n+++ b/scripts/check-changed.mjs\n@@ -0,0 +1,239 @@\n+// The check for what a change reaches, for running by hand before a publish. The full check (abso.json's)\n+// still runs on every publish, in the merge queue; this one is only the quick local run, so agents don't run\n+// the whole suite by hand.\n+//\n+//   npm run check:changed [-- file ...]   (paths from the repo root; none: this folder's draft, from abso diff\n+//                                          and abso status)   --list says what it would run and runs nothing.\n+//\n+// What it runs, for the changed files:\n+// - tests: every test file that imports a changed file, through any number of imports, plus changed test\n+//   files themselves. A changed file that isn't code (a fixture, a saved log) brings in the test files that\n+//   name it.\n+// - typecheck: tsconfig.json, when it includes a changed file or anything that imports one, incrementally\n+//   (its build info under node_modules/.cache), so a second run reads only what changed.\n+// - biome: the changed files only.\n+// A change to setup (package.json, the lockfile, tsconfig.json, abso.json, biome.json) runs the full check.\n+import { spawn, spawnSync } from \"node:child_process\";\n+import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\n+import { availableParallelism } from \"node:os\";\n+import { dirname, extname, join, matchesGlob, relative, resolve, sep } from \"node:path\";\n+import { fileURLToPath } from \"node:url\";\n+import ts from \"typescript\";\n+\n+const root = resolve(dirname(fileURLToPath(import.meta.url)), \"..\");\n+\n+/** Test runs: a folder, the test globs its npm test uses (from that folder), and node's extra arguments. */\n+const TESTS = [\n+\t{\n+\t\tcwd: \".\",\n+\t\tglobs: [\"src/**/*.test.ts\", \"worker/project/**/*.test.ts\", \"client/test/**/*.test.ts\", \"scripts/**/*.test.ts\"],\n+\t\targs: [\"--import\", \"./client/test/setup.ts\"],\n+\t},\n+];\n+/** Typechecks: a tsconfig, from the repo root. */\n+const TYPECHECKS = [{ tsconfig: \"tsconfig.json\" }];\n+/** Files whose change can reach anything: the full check runs instead. */\n+const SETUP = [\n+\t\"**/package.json\",\n+\t\"**/package-lock.json\",\n+\t\"**/tsconfig*.json\",\n+\t\"abso.json\",\n+\t\"biome.json\",\n+\t\"biome.jsonc\",\n+\t\"client/test/setup.ts\",\n+];\n+const SKIP_DIRS = new Set([\"node_modules\", \".abso\", \".wrangler\", \"dist\", \".git\"]);\n+const CODE = new Set([\".ts\", \".tsx\", \".mts\", \".mjs\", \".js\", \".cjs\"]);\n+\n+const posix = (p) => p.split(sep).join(\"/\");\n+const matches = (path, globs) => globs.some((g) => matchesGlob(path, g));\n+\n+/** Every file under the repo, posix paths from the root, skipping dependency and build folders. */\n+function allFiles(dir = root, out = []) {\n+\tfor (const name of readdirSync(dir)) {\n+\t\tif (SKIP_DIRS.has(name)) continue;\n+\t\tconst p = join(dir, name);\n+\t\tconst s = statSync(p);\n+\t\tif (s.isDirectory()) allFiles(p, out);\n+\t\telse out.push(posix(relative(root, p)));\n+\t}\n+\treturn out;\n+}\n+\n+/**\n+ * Each code file's imports, kept between runs in node_modules/.cache by the file's time and size, so a run\n+ * reads only the files that changed since the last one.\n+ */\n+const CACHE = join(root, \"node_modules/.cache/check-changed.json\");\n+function importGraph(code, known) {\n+\tlet cache = {};\n+\ttry {\n+\t\tcache = JSON.parse(readFileSync(CACHE, \"utf8\"));\n+\t} catch {}\n+\tconst next = {};\n+\tconst importers = new Map();\n+\tfor (const f of code) {\n+\t\tconst s = statSync(join(root, f));\n+\t\tconst hit = cache[f];\n+\t\tconst imports = hit && hit.t === s.mtimeMs && hit.n === s.size ? hit.i : importsOf(f, known);\n+\t\tnext[f] = { t: s.mtimeMs, n: s.size, i: imports };\n+\t\tfor (const i of imports) (importers.get(i) ?? importers.set(i, new Set()).get(i)).add(f);\n+\t}\n+\ttry {\n+\t\tmkdirSync(dirname(CACHE), { recursive: true });\n+\t\twriteFileSync(CACHE, JSON.stringify(next));\n+\t} catch {}\n+\treturn importers;\n+}\n+\n+/** The files a code file imports, as repo paths (relative imports only; packages can't change in a draft). */\n+function importsOf(file, known) {\n+\tconst text = readFileSync(join(root, file), \"utf8\");\n+\tconst out = [];\n+\tconst re = /(?:\\bfrom\\s*|\\bimport\\s*\\(\\s*|\\bimport\\s+|\\brequire\\s*\\(\\s*)[\"'](\\.{1,2}\\/[^\"']+)[\"']/g;\n+\tfor (const m of text.matchAll(re)) {\n+\t\tconst base = posix(join(dirname(file), m[1]));\n+\t\tconst stem = base.replace(/\\.(m?js|cjs)$/, \"\");\n+\t\tfor (const c of [base, `${stem}.ts`, `${stem}.tsx`, `${stem}.mts`, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`])\n+\t\t\tif (known.has(c)) {\n+\t\t\t\tout.push(c);\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t}\n+\treturn out;\n+}\n+\n+/** This folder's changed files: the draft's, from abso diff, and edits not yet recorded, from abso status. */\n+function draftFiles() {\n+\tconst run = (args) => {\n+\t\t// One command string: abso is a .cmd on Windows, which needs a shell, and the args are fixed words.\n+\t\tconst r = spawnSync(`abso ${args.join(\" \")}`, { cwd: root, encoding: \"utf8\", shell: true });\n+\t\tif (r.status !== 0) throw new Error(`abso ${args.join(\" \")} failed: ${(r.stderr || r.stdout).trim()}`);\n+\t\treturn r.stdout;\n+\t};\n+\tconst files = new Set();\n+\tfor (const m of run([\"diff\"]).matchAll(/^(?:\\+\\+\\+ b|--- a)\\/(.+)$/gm)) files.add(m[1].trim());\n+\tconst unrecorded = /^Not yet recorded[^:]*:\\s*(.+)$/m.exec(run([\"status\"]));\n+\tif (unrecorded) for (const f of unrecorded[1].split(/,\\s*/)) files.add(f.trim());\n+\treturn [...files].filter(Boolean);\n+}\n+\n+/** What the changed files reach: test files to run per test group, tsconfigs to check, files for biome. */\n+export function plan(changed, files = allFiles()) {\n+\tconst known = new Set(files);\n+\tif (changed.some((f) => matches(f, SETUP))) return { full: changed.filter((f) => matches(f, SETUP)) };\n+\tconst code = files.filter((f) => CODE.has(extname(f)) && !f.endsWith(\".d.ts\"));\n+\tconst importers = importGraph(code, known);\n+\t// Everything that imports a changed file, through any number of imports.\n+\tconst reached = new Set(changed.filter((f) => known.has(f)));\n+\tconst queue = [...reached];\n+\twhile (queue.length)\n+\t\tfor (const by of importers.get(queue.pop()) ?? []) if (!reached.has(by)) reached.add(by), queue.push(by);\n+\t// A changed file that isn't code: the test files that name it.\n+\tconst tests = TESTS.map((t) => ({ ...t, files: [] }));\n+\tconst owner = (f) =>\n+\t\ttests.find(\n+\t\t\t(t) =>\n+\t\t\t\t(t.cwd === \".\" || f.startsWith(`${t.cwd}/`)) && matches(t.cwd === \".\" ? f : f.slice(t.cwd.length + 1), t.globs),\n+\t\t);\n+\tconst allTests = files.filter((f) => owner(f));\n+\tfor (const f of changed.filter((c) => known.has(c) && !CODE.has(extname(c)))) {\n+\t\tconst name = f.split(\"/\").pop();\n+\t\tfor (const t of allTests) if (readFileSync(join(root, t), \"utf8\").includes(name)) reached.add(t);\n+\t}\n+\tfor (const f of reached) {\n+\t\tconst t = owner(f);\n+\t\tif (t) t.files.push(t.cwd === \".\" ? f : f.slice(t.cwd.length + 1));\n+\t}\n+\tconst typechecks = TYPECHECKS.filter((c) => {\n+\t\tconst cfg = ts.readConfigFile(join(root, c.tsconfig), (p) => readFileSync(p, \"utf8\")).config ?? {};\n+\t\tconst dir = posix(dirname(c.tsconfig));\n+\t\tconst inc = (cfg.include ?? [\"**/*\"]).map((g) => posix(join(dir, g)));\n+\t\tconst exc = (cfg.exclude ?? []).map((g) => posix(join(dir, g)));\n+\t\treturn [...reached].some((f) => matches(f, inc) && !matches(f, exc));\n+\t});\n+\tconst lint = changed.filter((f) => known.has(f) && /\\.(m?[jt]sx?|cjs|json|jsonc|css)$/.test(f));\n+\treturn { tests: tests.filter((t) => t.files.length), typechecks, lint };\n+}\n+\n+/** Runs one command, its output kept, and resolves with its exit and time. */\n+function runOne(name, cmd, args, cwd) {\n+\tconst started = Date.now();\n+\treturn new Promise((done) => {\n+\t\tconst child = spawn(cmd, args, { cwd: join(root, cwd) });\n+\t\tlet out = \"\";\n+\t\tchild.stdout.on(\"data\", (d) => (out += d));\n+\t\tchild.stderr.on(\"data\", (d) => (out += d));\n+\t\tchild.on(\"close\", (code) => done({ name, code, out, ms: Date.now() - started }));\n+\t});\n+}\n+\n+async function main() {\n+\tconst argv = process.argv.slice(2);\n+\tconst listOnly = argv.includes(\"--list\");\n+\tconst given = argv.filter((a) => a !== \"--list\").map((a) => posix(a).replace(/^\\.\\//, \"\"));\n+\tconst changed = given.length ? given : draftFiles();\n+\tif (!changed.length) {\n+\t\tconsole.log(\"Nothing changed in this folder: nothing to check.\");\n+\t\treturn;\n+\t}\n+\tconst p = plan(changed);\n+\tif (p.full) {\n+\t\tconsole.log(`Setup changed (${p.full.join(\", \")}): running the full check.`);\n+\t\tif (listOnly) return;\n+\t\tconst { check } = JSON.parse(readFileSync(join(root, \"abso.json\"), \"utf8\"));\n+\t\tconst r = spawnSync(check, { cwd: root, stdio: \"inherit\", shell: true });\n+\t\tprocess.exit(r.status ?? 1);\n+\t}\n+\tconst jobs = [];\n+\tfor (const t of p.tests)\n+\t\tjobs.push({\n+\t\t\tname: `test ${t.cwd} (${t.files.length} files)`,\n+\t\t\tcmd: process.execPath,\n+\t\t\targs: [...t.args, \"--test\", ...t.files],\n+\t\t\tcwd: t.cwd,\n+\t\t});\n+\tfor (const c of p.typechecks) {\n+\t\tconst info = `node_modules/.cache/tsc/${c.tsconfig.replace(/[/\\\\]/g, \"_\")}.tsbuildinfo`;\n+\t\tjobs.push({\n+\t\t\tname: `typecheck ${c.tsconfig}`,\n+\t\t\tcmd: process.execPath,\n+\t\t\targs: [\n+\t\t\t\tjoin(root, \"node_modules/typescript/bin/tsc\"),\n+\t\t\t\t\"--noEmit\",\n+\t\t\t\t\"-p\",\n+\t\t\t\tc.tsconfig,\n+\t\t\t\t\"--incremental\",\n+\t\t\t\t\"--tsBuildInfoFile\",\n+\t\t\t\tinfo,\n+\t\t\t],\n+\t\t\tcwd: \".\",\n+\t\t});\n+\t}\n+\tif (p.lint.length)\n+\t\tjobs.push({\n+\t\t\tname: `biome (${p.lint.length} files)`,\n+\t\t\tcmd: process.execPath,\n+\t\t\targs: [join(root, \"node_modules/@biomejs/biome/bin/biome\"), \"check\", \"--no-errors-on-unmatched\", ...p.lint],\n+\t\t\tcwd: \".\",\n+\t\t});\n+\tconsole.log(`Changed: ${changed.join(\", \")}`);\n+\tfor (const j of jobs)\n+\t\tconsole.log(\n+\t\t\t`  ${j.name}${j.name.startsWith(\"test\") ? `: ${j.args.filter((a) => /\\.test\\./.test(a)).join(\" \")}` : \"\"}`,\n+\t\t);\n+\tif (listOnly || !jobs.length) return;\n+\tconst started = Date.now();\n+\tconst slots = Math.max(1, Number(process.env.ABSO_CHECK_SLOTS) || availableParallelism());\n+\tconst results = [];\n+\tfor (let i = 0; i < jobs.length; i += slots)\n+\t\tresults.push(...(await Promise.all(jobs.slice(i, i + slots).map((j) => runOne(j.name, j.cmd, j.args, j.cwd)))));\n+\tfor (const r of results.filter((r) => r.code !== 0)) console.log(`\\n--- ${r.name} failed ---\\n${r.out.trimEnd()}`);\n+\tconsole.log(\"\");\n+\tfor (const r of results)\n+\t\tconsole.log(`${r.code === 0 ? \"ok  \" : \"FAIL\"} ${(r.ms / 1000).toFixed(1).padStart(6)} s  ${r.name}`);\n+\tconsole.log(`${((Date.now() - started) / 1000).toFixed(1)} s in all. The full check runs when you publish.`);\n+\tif (results.some((r) => r.code !== 0)) process.exitCode = 1;\n+}\n+\n+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();"}],"unmatched":[]}