import test from "node:test"; import assert from "node:assert/strict"; import { splitPage, normalizeSpeakers, assemble } from "../server/transcribe.mjs"; import { anthropicProvider, openRouterProvider, makeProvider, PageError } from "../server/providers.mjs"; import { parsePlay, lint } from "../public/parse.js"; test("splitPage takes the page number from the first line", () => { assert.deepEqual(splitPage("=-12-\n@Lída\nAno."), { num: "12", body: "@Lída\nAno." }); assert.deepEqual(splitPage("=?\ntext"), { num: "?", body: "text" }); assert.deepEqual(splitPage("```\n=3\n@A\nx\n=4\n```"), { num: "3", body: "@A\nx" }); assert.equal(splitPage("@A\nx").num, "?"); }); test("speaker spellings are unified across pages", () => { const out = normalizeSpeakers(["@LÍDA\nx\n@Lida\ny", "@Lida:\nz\n@PANÍ BÁBA\nw\n@Paní bába\nv"]); assert.deepEqual(out, ["@Lída\nx\n@Lída\ny", "@Lída\nz\n@Paní bába\nw\n@Paní bába\nv"]); }); test("assemble numbers pages, marks gaps and failed pages", () => { const text = assemble([ { num: "5", body: "@Mise\nAno." }, { num: "?", body: "dál" }, { num: "9", body: "@Lída\nNe." }, { error: "model declined" }, ]); assert.equal(text, "=5\n@Mise\nAno.\n=6\ndál\n!7-8\n=9\n@Lída\nNe.\n=10\n>(Stranu se nepodařilo přepsat: model declined)\n"); const pages = parsePlay(text); assert.deepEqual(pages.map((p) => p.num), ["5", "6", "7-8", "9", "10"]); assert.equal(pages[1].blocks[0].speaker, "Mise"); // continues across the page break assert.deepEqual(lint(pages), []); }); const stub = (response) => ({ messages: { create: async (params) => { stub.last = params; return response; } } }); const JPEG = Buffer.from([0xff, 0xd8, 1]); test("anthropic: sends the image and reads text blocks", async () => { const client = stub({ stop_reason: "end_turn", content: [{ type: "thinking", thinking: "" }, { type: "text", text: "=1\n@A\nx" }], usage: {} }); const text = await anthropicProvider({ client, model: "claude-haiku-5-5" }).transcribe(JPEG); assert.equal(text, "=1\n@A\nx"); assert.equal(stub.last.messages[0].content[0].source.media_type, "image/jpeg"); assert.equal(stub.last.model, "claude-haiku-5-5"); }); test("anthropic: refusals and truncation become page errors", async () => { const p = (r) => anthropicProvider({ client: stub(r), model: "m" }).transcribe(JPEG); await assert.rejects(p({ stop_reason: "refusal", content: [] }), PageError); await assert.rejects(p({ stop_reason: "max_tokens", content: [{ type: "text", text: "x" }] }), PageError); }); // fake fetch: returns the queued responses in order and records the requests function fakeFetch(...responses) { const calls = []; const f = async (url, init) => { calls.push({ url, init, body: JSON.parse(init.body) }); const r = responses.shift(); if (r instanceof Error) throw r; return new Response(JSON.stringify(r.body), { status: r.status || 200, headers: { "content-type": "application/json" } }); }; f.calls = calls; return f; } const ok = (text, finish = "stop") => ({ body: { choices: [{ finish_reason: finish, message: { role: "assistant", content: text } }] } }); test("openrouter: sends a data-URL image with the key and reads the answer", async () => { const f = fakeFetch(ok("=2\n@Lída\nAno.")); const p = openRouterProvider({ apiKey: "sk-or-test", model: "google/gemini-3.1-flash-lite", fetchImpl: f }); assert.equal(await p.transcribe(JPEG), "=2\n@Lída\nAno."); const [{ url, init, body }] = f.calls; assert.equal(url, "https://openrouter.ai/api/v1/chat/completions"); assert.equal(init.headers.Authorization, "Bearer sk-or-test"); assert.equal(body.model, "google/gemini-3.1-flash-lite"); assert.equal(body.messages[0].role, "system"); assert.match(body.messages[1].content[0].image_url.url, /^data:image\/jpeg;base64,/); }); test("openrouter: retries rate limits and network errors, then gives up with a readable message", async () => { const f = fakeFetch({ status: 429, body: { error: { code: 429, message: "slow down" } } }, new Error("ECONNRESET"), ok("=1\nx")); assert.equal(await openRouterProvider({ apiKey: "k", model: "m", fetchImpl: f, retryDelayMs: 1 }).transcribe(JPEG), "=1\nx"); assert.equal(f.calls.length, 3); const g = fakeFetch({ status: 402, body: { error: { code: 402, message: "Insufficient credits" } } }); await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: g, retryDelayMs: 1 }).transcribe(JPEG), /out of credit/); assert.equal(g.calls.length, 1); // not retried // an error inside a 200 body counts too const h = fakeFetch({ body: { error: { code: 401, message: "No auth" } } }); await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: h }).transcribe(JPEG), /key rejected/); }); test("openrouter: truncated, filtered or empty answers are page errors", async () => { for (const r of [ok("x", "length"), ok("x", "content_filter"), ok(""), { body: { choices: [] } }]) await assert.rejects(openRouterProvider({ apiKey: "k", model: "m", fetchImpl: fakeFetch(r) }).transcribe(JPEG), PageError); }); test("provider choice: OpenRouter first, then Anthropic, else off", () => { assert.equal(makeProvider({}), null); assert.equal(makeProvider({ ANTHROPIC_API_KEY: "a" }).name, "anthropic"); const p = makeProvider({ ANTHROPIC_API_KEY: "a", OPENROUTER_API_KEY: "o" }); assert.deepEqual([p.name, p.model], ["openrouter", "google/gemini-3.1-flash-lite"]); assert.equal(makeProvider({ OPENROUTER_API_KEY: "o", OPENROUTER_MODEL: "qwen/x" }).model, "qwen/x"); });