import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/normalizeLiveChat.test.ts // // ONE CLOCK PER RECORDING, THE CUES' — for the live chat (lane chat-clock). // A chat yt-dlp captures WHILE THE STREAM IS LIVE is timed from the moment the // capture began (`videoOffsetTimeMsec = timestampUsec/1000 − start_time`, // every line `"isLive": true`); a recording made from the broadcast's start is // timed from the broadcast's start. These cases pin the normalizer putting the // chat on the recording's clock. Temp dirs, synthetic names, no network. const ROOT = await mkdtemp(path.join(tmpdir(), "chat-clock-")); test.after(() => rm(ROOT, { recursive: true, force: true })); const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat"); // The broadcast went live at T0; the chat capture began 2,235 s later. const T0_MS = Date.UTC(2026, 0, 2, 3, 0, 0); const SHIFT_MS = 2_235_000; const CAPTURE_MS = T0_MS + SHIFT_MS; const URL = "https://www.youtube.com/watch?v=abc123"; type Msg = { id?: string; author: string; text: string }; function renderer(m: Msg, postedMs: number) { return { liveChatTextMessageRenderer: { message: { runs: [{ text: m.text }] }, authorName: { simpleText: m.author }, ...(m.id ? { id: m.id } : {}), timestampUsec: String(postedMs * 1000), }, }; } // yt-dlp's live pseudo-replay line: the offset is from the capture's start. function liveLine(offsetMs: number, m: Msg, captureMs = CAPTURE_MS): string { return JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: renderer(m, captureMs + offsetMs) } }] }, videoOffsetTimeMsec: String(offsetMs), isLive: true, }); } // A replay line (after the stream): YouTube's offset, on the VOD's clock. function replayLine(offsetMs: number, m: Msg): string { return JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: renderer(m, T0_MS + offsetMs) } }], videoOffsetTimeMsec: String(offsetMs), }, }); } const META = { id: "abc123", title: "Demo stream", upload_date: "20260102", release_timestamp: T0_MS / 1000, live_status: "post_live", was_live: true, duration: 10_000, webpage_url: URL, }; function recording(o: { fromStart?: boolean; status?: string; startedAtMs?: number } = {}) { const startedAt = new Date(o.startedAtMs ?? CAPTURE_MS - 5_000).toISOString(); const fromStart = o.fromStart ?? true; return { status: o.status ?? "landed", url: URL, platform: "youtube", fromStart, startedAt, parts: [{ method: "ytdlp", url: URL, fromStart, startedAt, seconds: 10_000 }], ...((o.status ?? "landed") === "landed" ? { landedPart: 0 } : {}), }; } let n = 0; async function videoDir(files: { meta?: object; raw: string[]; rec?: object }): Promise { const dir = path.join(ROOT, `case-${++n}`, "demo-channel", "data", "abc123"); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(files.meta ?? META)); await writeFile(path.join(dir, "transcript.live_chat.json"), files.raw.join("\n") + "\n"); if (files.rec) await writeFile(path.join(dir, "live-recording.json"), JSON.stringify(files.rec)); return dir; } type Doc = { version: number; cues: { start: number; text: string }[]; clock?: Record }; async function normalize(dir: string): Promise { const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false }); assert.equal(out.status, "wrote"); return JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; } test("a chat captured while live lands on a from-start recording's clock (the broadcast's start)", async () => { const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }), liveLine(-300_000, { id: "m0", author: "viewer0", text: "backlog" })], rec: recording(), }); const doc = await normalize(dir); assert.deepEqual( doc.cues.map((c) => [c.start, c.text]), [ [1935, "viewer0: backlog"], [2335, "viewer1: hello"], ], ); assert.equal(doc.version, 2); assert.equal(doc.clock?.basis, "broadcast-start"); assert.equal(doc.clock?.certain, true); assert.equal(doc.clock?.shiftSeconds, 2235); assert.equal(doc.clock?.zeroAt, new Date(T0_MS).toISOString()); assert.equal(doc.clock?.liveLines, 2); }); test("a recording still in progress has the same zero (the chat may be normalized before it lands)", async () => { const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], rec: recording({ status: "recording" }), }); const doc = await normalize(dir); assert.equal(doc.cues[0].start, 2335); assert.equal(doc.clock?.basis, "broadcast-start"); }); test("no recording: the media is the post-live VOD, timed from the broadcast's start too", async () => { const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); const doc = await normalize(dir); assert.equal(doc.cues[0].start, 2335); assert.equal(doc.clock?.basis, "broadcast-start"); }); test("a live head then a replay (a resumed .part): the replay copy wins, a head-only message is shifted, an id-less line is kept", async () => { const dir = await videoDir({ raw: [ liveLine(10_000, { id: "dup", author: "viewer1", text: "said twice" }), liveLine(20_000, { id: "head-only", author: "viewer2", text: "only live" }), liveLine(30_000, { author: "viewer3", text: "no id" }), replayLine(500_000, { id: "early", author: "viewer4", text: "replay" }), replayLine(2_245_000, { id: "dup", author: "viewer1", text: "said twice" }), ], }); const doc = await normalize(dir); assert.deepEqual( doc.cues.map((c) => [c.start, c.text]), [ [500, "viewer4: replay"], [2245, "viewer1: said twice"], [2255, "viewer2: only live"], [2265, "viewer3: no id"], ], ); assert.equal(doc.clock?.duplicatesDropped, 1); assert.equal(doc.clock?.liveLines, 3); assert.equal(doc.clock?.replayLines, 2); }); test("a recording NOT from the start: its part's start is the zero, and it is not certain", async () => { const startedAtMs = T0_MS + 3_000_000; const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" }, startedAtMs + 2_000)], rec: recording({ fromStart: false, startedAtMs }), }); const doc = await normalize(dir); assert.equal(doc.cues[0].start, 102); assert.equal(doc.clock?.basis, "recording-start"); assert.equal(doc.clock?.certain, false); }); test("no zero to be had (no release_timestamp, no recording): the capture's clock, said so", async () => { const { release_timestamp, ...meta } = META; void release_timestamp; const dir = await videoDir({ meta, raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })] }); const doc = await normalize(dir); assert.equal(doc.cues[0].start, 100); assert.equal(doc.clock?.basis, "capture-start"); assert.equal(doc.clock?.certain, false); }); test("a recording NOT from the start with no readable start: no zero, the capture's clock, and the log says so", async () => { const rec = recording({ fromStart: false }); const parts = rec.parts.map(({ startedAt, ...p }) => (void startedAt, p)); const dir = await videoDir({ raw: [liveLine(100_000, { id: "m1", author: "viewer1", text: "hello" })], rec: { ...rec, parts }, }); const logs: string[] = []; const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", force: true, tier: false, log: (m) => logs.push(m) }); assert.equal(out.status, "wrote"); const doc = JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")) as Doc; assert.equal(doc.cues[0].start, 100); assert.equal(doc.clock?.basis, "capture-start"); assert.equal(doc.clock?.certain, false); assert.ok(logs.some((l) => /left on the capture's clock/.test(l)), logs.join("\n")); }); test("a pure replay: the same starts as ever, basis replay", async () => { const dir = await videoDir({ raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" }), replayLine(14_000, { id: "b", author: "viewer2", text: "W" })], rec: recording(), }); const doc = await normalize(dir); assert.deepEqual(doc.cues.map((c) => c.start), [12, 14]); assert.equal(doc.clock?.basis, "replay"); assert.equal(doc.clock?.liveLines, 0); }); test("the version bump makes no v1 file stale: a v1 cues file over a pure replay stays fresh and byte-unchanged", async () => { const dir = await videoDir({ raw: [replayLine(12_000, { id: "a", author: "viewer1", text: "lol" })] }); const cuesPath = path.join(dir, "live_chat.cues.json"); const v1 = '{"version":1,"source":"live_chat","id":"abc123","cues":[{"start":12,"end":17,"text":"viewer1: lol"}]}'; await writeFile(cuesPath, v1); const older = new Date(Date.now() - 60_000); await utimes(path.join(dir, "metadata.info.json"), older, older); await utimes(path.join(dir, "transcript.live_chat.json"), older, older); assert.equal((await isLiveChatCuesFresh(dir)).fresh, true); const out = await normalizeLiveChat({ videoDir: dir, channelSlug: "demo-channel", tier: false }); assert.equal(out.status, "fresh"); assert.equal(await readFile(cuesPath, "utf8"), v1); });