import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; /** * TEST FAKE. Not a speech synthesiser and not ElevenLabs. * * Accepts `POST /v1/text-to-speech/{voice_id}` with an `xi-api-key` header and a JSON body, as * the provider's documentation describes it (read 2026-11-29), and returns a few bytes labelled * audio/mpeg that are NOT playable audio. It proves what the bridge sends and how it handles * failures, and nothing about the real service, its voices, latency, limits or cost. */ export class FakeTts { readonly apiKey = 'fake-tts-key'; requests: Array<{ voiceId: string; text: string; model: string; outputFormat: string | null }> = []; private replies: Array<{ status?: number; delayMs?: number; body?: string }> = []; private server: Server | null = null; url = ''; async start(): Promise { this.server = createServer(async (req, res) => { const chunks: Buffer[] = []; for await (const chunk of req) chunks.push(chunk as Buffer); const url = new URL(req.url ?? '/', 'http://x'); const match = /^\/v1\/text-to-speech\/([^/]+)$/.exec(url.pathname); if (req.method !== 'POST' || !match) { res.writeHead(404).end(); return; } if (req.headers['xi-api-key'] !== this.apiKey) { res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"detail":{"status":"invalid_api_key"}}'); return; } const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { text: string; model_id: string }; this.requests.push({ voiceId: decodeURIComponent(match[1]!), text: body.text, model: body.model_id, outputFormat: url.searchParams.get('output_format') }); const reply = this.replies.shift() ?? {}; if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs)); if (reply.status && reply.status >= 400) { // A real provider may quote the text back in an error: the bridge must not pass it on. res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end(JSON.stringify({ detail: { message: `could not speak: ${body.text}` } })); return; } res.writeHead(200, { 'Content-Type': 'audio/mpeg' }).end(Buffer.from(reply.body ?? `FAKE-MP3:${match[1]}:${body.text.length}`)); }); await new Promise((resolve) => this.server!.listen(0, '127.0.0.1', resolve)); this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; } next(...replies: Array<{ status?: number; delayMs?: number; body?: string }>): void { this.replies.push(...replies); } async stop(): Promise { // The bridge keeps its connection to the provider open; do not wait for it to idle out. this.server?.closeAllConnections(); await new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve())); } }