import { createServer, type Server } from 'node:http'; import type { AddressInfo } from 'node:net'; /** * TEST FAKE. Not a speech recogniser. * * Accepts the OpenAI-style `POST /audio/transcriptions` multipart upload, * checks that what arrived really is a 16 kHz mono 16-bit WAV, and returns a * scripted transcript. It proves the bridge's upload format and failure * handling, and nothing about real transcription quality or latency. */ export class FakeStt { readonly apiKey = 'fake-stt-key'; calls = 0; lastWav: { sampleRate: number; channels: number; bitsPerSample: number; dataBytes: number } | null = null; lastFields: Record = {}; private replies: Array<{ text?: string; status?: number; delayMs?: number }> = []; 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 body = Buffer.concat(chunks); if (req.method !== 'POST' || !req.url?.endsWith('/audio/transcriptions')) { res.writeHead(404).end(); return; } if (req.headers.authorization !== `Bearer ${this.apiKey}`) { res.writeHead(401, { 'Content-Type': 'application/json' }).end('{"error":"unauthorized"}'); return; } this.calls += 1; const riff = body.indexOf('RIFF'); if (riff >= 0 && body.toString('ascii', riff + 8, riff + 12) === 'WAVE') { this.lastWav = { channels: body.readUInt16LE(riff + 22), sampleRate: body.readUInt32LE(riff + 24), bitsPerSample: body.readUInt16LE(riff + 34), dataBytes: body.readUInt32LE(riff + 40), }; } else { this.lastWav = null; } const text = body.toString('latin1'); this.lastFields = {}; for (const m of text.matchAll(/name="(model|language|response_format)"\r\n\r\n([^\r]*)\r\n/g)) { this.lastFields[m[1]!] = m[2]!; } const reply = this.replies.shift() ?? { text: 'what is the capital of france' }; if (reply.delayMs) await new Promise((r) => setTimeout(r, reply.delayMs)); if (res.destroyed) return; if (reply.status && reply.status !== 200) { res.writeHead(reply.status, { 'Content-Type': 'application/json' }).end('{"error":"scripted failure"}'); return; } res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ text: reply.text ?? '' })); }); 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<{ text?: string; status?: number; delayMs?: number }>): void { this.replies.push(...replies); } async stop(): Promise { const server = this.server; this.server = null; if (server) { server.closeAllConnections(); await new Promise((resolve) => server.close(() => resolve())); } } } /** Deterministic synthetic PCM (a sine tone). Stands in for speech in tests; it is not speech. */ export function syntheticPcm(seconds: number, sampleRate = 16000): Buffer { const samples = Math.floor(seconds * sampleRate); const buf = Buffer.alloc(samples * 2); for (let i = 0; i < samples; i++) buf.writeInt16LE(Math.round(Math.sin((2 * Math.PI * 440 * i) / sampleRate) * 8000), i * 2); return buf; }