import test from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm, readdir } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { CENSUS_FORMAT, censusFile, readCensus, writeCensus } from "./census.mjs"; const H = "local:/x/export/public"; const C = { "ch-a": { total: 3, transcript: 1, captions: 2, unknown: 0, byYear: { 2024: { transcript: 1, captions: 2, unknown: 0 } } } }; test("a census round-trips for its build, and is stale for another", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-")); try { assert.deepEqual(await readCensus(root, H, "b1"), {}); await writeCensus(root, H, "b1", C, { now: new Date("2026-10-14T00:00:00Z") }); const r = await readCensus(root, H, "b1"); assert.deepEqual(r.channels, C); assert.equal(r.updatedAt, "2026-10-14T00:00:00.000Z"); assert.deepEqual(await readCensus(root, H, "b2"), { stale: { identity: "b1", updatedAt: "2026-10-14T00:00:00.000Z" } }); const doc = JSON.parse(await readFile(censusFile(root, H), "utf8")); assert.equal(doc.format, CENSUS_FORMAT); assert.equal(doc.handle, H); assert.ok(censusFile(root, H).includes(`${path.sep}.umtool${path.sep}research${path.sep}census${path.sep}`)); // another source, another file assert.notEqual(censusFile(root, H), censusFile(root, "remote:https://a.example")); } finally { await rm(root, { recursive: true, force: true }); } }); test("writes are serialised and leave no temp file; bad files are reported, never trusted", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-")); try { await Promise.all(Array.from({ length: 10 }, (_, i) => writeCensus(root, H, `b${i}`, C))); assert.equal((await readCensus(root, H, "b9")).channels["ch-a"].total, 3); assert.deepEqual(await readdir(path.dirname(censusFile(root, H))), [path.basename(censusFile(root, H))]); await writeCensus(root, "other", "b1", C); const { writeFile } = await import("node:fs/promises"); await writeFile(censusFile(root, "other"), "{nope"); assert.match((await readCensus(root, "other", "b1")).error, /cannot be read/); } finally { await rm(root, { recursive: true, force: true }); } });