// node --test umtool/lib/ingredients/stages.test.mjs import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { lastEndOf, readJsonHead, scanHead } from "./heads.mjs"; import { parseWindowParam, pillGlyph, readIngredient, STAGES } from "./stages.mjs"; test("scanHead: the top-level primitives, nested members skipped, a truncated text read as far as it is whole", () => { const text = JSON.stringify({ id: "abc", title: "A \"quoted\" title", formats: [{ duration: 9, x: "}" }], duration: 120, live: false, n: null, cues: [{ end: 5 }] }); const all = scanHead(text); assert.deepEqual(all.fields, { id: "abc", title: 'A "quoted" title', duration: 120, live: false, n: null }); assert.deepEqual(all.nested, ["formats", "cues"]); assert.equal(all.complete, true); const stopped = scanHead(text, { stopKey: "formats" }); assert.deepEqual(stopped.fields, { id: "abc", title: 'A "quoted" title' }); // Cut in the middle of the formats array: what came before is still read. const cut = scanHead(text.slice(0, text.indexOf("duration") + 4)); assert.deepEqual(cut.fields, { id: "abc", title: 'A "quoted" title' }); assert.equal(cut.complete, false); // A number at the very end of the buffer may be cut short: not read. assert.deepEqual(scanHead('{"a": 12').fields, {}); }); test("parseWindowParam", () => { assert.deepEqual(parseWindowParam("10.00-40.00"), { from: 10, to: 40 }); assert.equal(parseWindowParam("40-10"), null); assert.equal(parseWindowParam("x"), null); }); async function corpus() { const root = await mkdtemp(path.join(tmpdir(), "stages-")); const channels = path.join(root, "channels"); const reports = path.join(root, "reports"); const vdir = path.join(channels, "chan", "data", "vid"); await mkdir(path.join(vdir, "clips"), { recursive: true }); await writeFile(path.join(channels, "chan", "config.json"), JSON.stringify({ platform: "youtube" })); // A metadata file whose formats push everything past the head. const formats = Array.from({ length: 4000 }, (_, i) => ({ format_id: String(i), duration: 1, url: "https://x.example/" + "y".repeat(20) })); await writeFile(path.join(vdir, "metadata.info.json"), JSON.stringify({ id: "vid", title: "The Recording", formats, webpage_url: "https://www.youtube.com/watch?v=vid", duration: 300 })); const cues = Array.from({ length: 50 }, (_, i) => ({ start: i * 6, end: i * 6 + 5.5, text: `cue ${i}` })); await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ version: 2, source: "vtt", title: "The Recording", uploadDate: "20261101", duration: 300, cues })); await writeFile(path.join(vdir, "transcript.en.vtt"), "WEBVTT\n"); await writeFile(path.join(vdir, "download-outcome.json"), JSON.stringify({ videoId: "vid", status: "ok", attempts: [{ n: 0 }] })); await writeFile(path.join(vdir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: "2026-11-01T00:00:00Z" })); await writeFile(path.join(vdir, "clips", "10.00-40.00.mp4"), Buffer.alloc(100)); await writeFile(path.join(vdir, "clips", "10.00-40.00.json"), JSON.stringify({ requestedBy: "a cut", clipId: "a1", fetchedAt: "2026-11-02T00:00:00Z" })); await writeFile(path.join(vdir, "clips", "200.00-230.00.mp4"), Buffer.alloc(50)); await writeFile(path.join(vdir, "clips", "200.00-230.00.json"), JSON.stringify({ requestedBy: "gone cut", clipId: "zz" })); const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid", start, end, ...extra }); const m = (timeline) => ({ provenance: { channelSlug: "chan", siteOrigin: "https://site.example" }, render: {}, timeline }); const a = path.join(reports, "f", "a"); await mkdir(path.join(a, "takes", "v1"), { recursive: true }); await writeFile(path.join(a, "video.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" }), clip("a2", 100, 110, { quote: "another" })]))); await writeFile(path.join(a, "takes", "v1", "take.json"), "{}"); await writeFile(path.join(a, "takes", "v1", "base.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" })]))); await writeFile(path.join(a, "takes", "v1", "preview.mp4"), Buffer.alloc(10)); await writeFile(path.join(a, "takes", "v1", "render.json"), JSON.stringify({ state: "done", mp4: "preview.mp4", seconds: 8 })); await writeFile(path.join(a, "quote-check.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-03T00:00:00Z", clips: { a1: { status: "ok", cut: { from: 12, to: 20 }, quote: "the quote" }, a2: { status: "moved", cut: { from: 100, to: 110 }, quote: "another" } } })); const b = path.join(reports, "f", "b"); await mkdir(path.join(b, "out"), { recursive: true }); await writeFile(path.join(b, "video.manifest.json"), JSON.stringify(m([clip("b1", 15, 25)]))); await writeFile(path.join(b, "out", "links.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-04T00:00:00Z", links: [{ clip: "b1", url: "https://site.example/?v=chan%2Fvid&t=15", state: "ok" }] })); return { root, channels, reports, vdir }; } async function listTree(dir) { const out = []; for (const e of await readdir(dir, { withFileTypes: true, recursive: true })) out.push(path.join(e.parentPath ?? e.path, e.name)); const st = await Promise.all(out.map((p) => stat(p).then((s) => `${p}:${s.size}:${s.mtimeMs}`))); return st.sort(); } test("the nine stages of a recording used by two projects, read without writing to the corpus", async () => { const { root, channels, reports, vdir } = await corpus(); try { const before = await listTree(channels); const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", indexFile: path.join(root, "state", "usage.json") }); assert.deepEqual(await listTree(channels), before, "nothing under the channels dir changed"); assert.deepEqual(r.stages.map((s) => s.key), STAGES.map((s) => s.key)); const by = Object.fromEntries(r.stages.map((s) => [s.key, s])); assert.equal(r.title, "The Recording"); assert.equal(r.webpageUrl, null, "webpage_url is past the head: not read"); assert.equal(by.downloaded.pill.kind, "ok"); assert.equal(by.downloaded.meta.id, "vid"); assert.equal(by.transcribed.pill.kind, "ok"); assert.equal(by.transcribed.cues.lastEnd, 299.5); assert.ok(Math.abs(by.transcribed.cues.coverage - 299.5 / 300) < 1e-9); assert.equal(pillGlyph(by.clock.pill), "—"); // Windows: a2 (100-110) has no window -> the stage warns; the 200-230 window's clip no project uses. assert.equal(by.windows.pill.kind, "warn"); assert.deepEqual(by.windows.uncovered.map((u) => u.clipId), ["a2"]); const w10 = by.windows.windows.find((w) => w.name === "10.00-40.00"); assert.deepEqual(w10.serves.map((s) => s.clipId).sort(), ["a1", "b1"]); assert.equal(by.windows.windows.find((w) => w.name === "200.00-230.00").orphan, true); assert.deepEqual(by.used.rows.map((u) => `${u.project}#${u.clipId}`), ["f/a#a1", "f/a#a2", "f/b#b1"]); assert.equal(pillGlyph(by.used.pill), "3"); assert.equal(by.checked.pill.kind, "warn"); assert.match(by.checked.line, /a2 moved/); assert.deepEqual(by.rendered.renders.filter((x) => x.state === "done").map((x) => `${x.clipId}@${x.version}`), ["a1@v1"]); assert.equal(pillGlyph(by.rendered.pill), "1"); const b1 = by.published.links.find((l) => l.clipId === "b1"); assert.equal(b1.state, "ok"); assert.equal(b1.url, "https://site.example/?v=chan%2Fvid&t=15"); assert.equal(by.published.links.find((l) => l.clipId === "a1").state, null); void vdir; } finally { await rm(root, { recursive: true, force: true }); } }); test("?window= focuses one window: the stages after it narrow to the clips it plays", async () => { const { root, channels, reports } = await corpus(); try { const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", window: "10.00-40.00", indexFile: path.join(root, "state", "usage.json") }); const by = Object.fromEntries(r.stages.map((s) => [s.key, s])); assert.deepEqual(r.focus, { from: 10, to: 40, name: "10.00-40.00", found: true }); assert.equal(by.windows.windows.filter((w) => w.focused).length, 1); assert.deepEqual(by.used.rows.map((u) => u.clipId), ["a1", "b1"]); assert.match(by.used.line, /of 3 from this recording/); assert.deepEqual(by.checked.clips.map((c) => c.clipId), ["a1", "b1"]); } finally { await rm(root, { recursive: true, force: true }); } }); test("an id the corpus does not hold: every stage says so, nothing throws", async () => { const { root, channels, reports } = await corpus(); try { const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "nope", indexFile: path.join(root, "state", "usage.json") }); assert.equal(r.exists, false); assert.equal(r.stages.length, 9); assert.match(r.stages[1].line, /Not in the corpus/); assert.equal(r.stages[4].line, "No windows cut yet"); } finally { await rm(root, { recursive: true, force: true }); } }); test("the head and tail readers read only their ends", async () => { const { root, vdir } = await corpus(); try { const h = await readJsonHead(path.join(vdir, "metadata.info.json")); assert.ok(h.size > 64 * 1024); assert.deepEqual(Object.keys(h.fields), ["id", "title"]); assert.equal(await lastEndOf(path.join(vdir, "transcript.cues.json")), 299.5); assert.equal(await lastEndOf(path.join(vdir, "nope.json")), null); } finally { await rm(root, { recursive: true, force: true }); } });