import test from "node:test"; import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/tts/route.test.ts" // // The adapter's surface: the token, the body's keys, the controller's // refusals answered as 400s before any job exists — and one synthesis through // the route with espeak-ng (the zero-install engine), read back from the job's // log as `pnpm ops tts --wait` reads it. The job itself is covered by // common/controller/ttsFile.test.ts. In a temp corpus with its own cache. const ROOT = await mkdtemp(path.join(os.tmpdir(), "tts-route-")); const CORPUS = path.join(ROOT, "transcripts"); const CACHE = path.join(ROOT, "cache"); await mkdir(CORPUS, { recursive: true }); const SETTINGS_FILE = path.join(ROOT, "settings.json"); const SETTINGS_TEXT = JSON.stringify({ workers: [], tts: { engine: "espeak-ng", voice: "en-us", dir: CACHE, home: path.join(ROOT, "home") }, }); await writeFile(SETTINGS_FILE, SETTINGS_TEXT); // Set before the route (and getPaths, which caches) is first imported. process.env.WORKER_TOKEN = "test-token"; process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = SETTINGS_FILE; const { POST } = await import("./route"); const { TTS_RESULT_MARKER } = await import("yt-dlp-transcript-common/controller/ttsFile"); test.after(() => rm(ROOT, { recursive: true, force: true })); async function post( body: Record, token = "test-token", ): Promise<{ status: number; json: { ok?: boolean; error?: string; jobId?: string } }> { const res = await POST( new Request("http://localhost/api/ops/tts", { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json", }, body: JSON.stringify(body), }), ); return { status: res.status, json: await res.json() }; } test("a wrong token is a 401", async () => { const { status } = await post({ text: "hi" }, "wrong"); assert.equal(status, 401); }); test("an unknown key is a 400 naming the accepted ones", async () => { const { status, json } = await post({ text: "hi", reference: "/voice.wav" }); assert.equal(status, 400); assert.match(json.error!, /unknown key\(s\): reference — this route accepts text, file, voice, engine, speed, out, tuning, reading/); }); test("the controller's refusals come back as 400s", async () => { const cases: [Record, RegExp][] = [ [{}, /"text" .* or "file" .* is required/], [{ text: "a", file: "/a.txt" }, /not both/], [{ file: "a.txt" }, /"file" must be an absolute path/], [{ file: path.join(ROOT, "missing.txt") }, /does not exist/], [{ text: "hi", engine: "piper" }, /no text-to-speech engine "piper"/], [{ text: "hi", voice: "af_heart" }, /espeak-ng has no stock voice "af_heart"/], [{ text: "hi", speed: 9 }, /"speed" must be between 0.5 and 2/], [{ text: "oh no" }, /a tag no engine knows: /], [{ text: "hi", engine: "kokoro" }, /Kokoro-82M is not installed .* run `archilyzer tts setup`/], [{ text: "hi", out: path.join(CORPUS, "a.wav") }, /inside the corpus/], [{ text: "hi", out: path.join(ROOT, "a.mp3") }, /must name a \.wav file/], [{ text: "hi", tuning: { top_p: 2 } }, /^"tuning\.top_p" must be a number from 0\.05 to 1 \(got 2\)$/], [{ text: "hi", tuning: { seed: 1 } }, /"tuning\.seed" is not a tuning field/], [{ text: "hi", reading: 100_000 }, /^"reading" must be a whole number from 0 to 99999/], ]; for (const [body, re] of cases) { const { status, json } = await post(body); assert.equal(status, 400, JSON.stringify(body)); assert.equal(json.ok, false); assert.match(json.error!, re); assert.equal(json.jobId, undefined); } assert.equal(await readFile(SETTINGS_FILE, "utf8"), SETTINGS_TEXT); }); let real = true; try { execFileSync("espeak-ng", ["--version"], { stdio: "ignore" }); execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); } catch { real = false; } test("a synthesis through the route: a job whose log ends with the result", { skip: !real && "espeak-ng or ffmpeg absent" }, async () => { const { status, json } = await post({ text: "Narrated in 2025." }); assert.equal(status, 200); assert.equal(json.ok, true); assert.ok(json.jobId); const logFile = path.join(CORPUS, ".jobs", `${json.jobId}.log`); let line: string | undefined; for (let i = 0; i < 300 && !line; i++) { const log = await readFile(logFile, "utf8").catch(() => ""); line = log.split("\n").find((l) => l.startsWith(TTS_RESULT_MARKER)); if (!line) await new Promise((r) => setTimeout(r, 50)); } assert.ok(line, "the result line"); const r = JSON.parse(line!.slice(TTS_RESULT_MARKER.length)); assert.deepEqual(Object.keys(r), [ "wav", "seconds", "engine", "voice", "cached", "durationMs", "waitedMs", "sha", "sampleRate", "speed", "disclosure", ]); assert.equal(r.engine, "espeak-ng"); assert.equal(r.cached, false); assert.equal(r.wav, path.join(CACHE, `${r.sha}.wav`)); assert.equal(r.sampleRate, 48000); assert.match(r.disclosure, /^Narration: synthetic voice \(eSpeak NG · en-us\)$/); const side = JSON.parse(await readFile(path.join(CACHE, `${r.sha}.json`), "utf8")); assert.equal(side.text, "Narrated in twenty twenty-five."); assert.equal(side.synthetic, true); });