import { existsSync, readFileSync } from 'fs'; import { basename, extname } from 'path'; import { getWorkspaceConfigFile, getWorkspaceDir } from './init-command.js'; type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }; type JsonObject = { [key: string]: JsonValue }; export type CustomTtsResponseType = 'binary' | 'json_base64' | 'json_url'; export type CustomTtsAudioFormat = 'mp3' | 'wav' | 'm4a' | 'ogg' | 'webm'; export interface CustomTtsRequestConfig { url: string; method: 'POST'; headers: Record; text_field?: string; body: JsonObject; timeout_ms: number; } export interface CustomTtsResponseConfig { type: CustomTtsResponseType; path?: string; format?: string; format_path?: string; content_type?: string; filename?: string; } export interface CustomTtsConfig { customize_tts: true; request: CustomTtsRequestConfig; response: CustomTtsResponseConfig; } export interface CustomTtsAudio { audio: Buffer; contentType: string; filename: string; } const DEFAULT_TIMEOUT_MS = 10_000; const MAX_TIMEOUT_MS = 60_000; const MAX_AUDIO_BYTES = 10 * 1024 * 1024; const SUPPORTED_AUDIO_FORMATS = 'mp3, wav, m4a, ogg, webm'; interface ResolvedAudioFormat { format: CustomTtsAudioFormat; contentType: string; extension: string; } const AUDIO_FORMATS: Record = { mp3: { format: 'mp3', contentType: 'audio/mpeg', extension: '.mp3' }, wav: { format: 'wav', contentType: 'audio/wav', extension: '.wav' }, m4a: { format: 'm4a', contentType: 'audio/mp4', extension: '.m4a' }, ogg: { format: 'ogg', contentType: 'audio/ogg', extension: '.ogg' }, webm: { format: 'webm', contentType: 'audio/webm', extension: '.webm' }, }; const AUDIO_FORMAT_ALIASES: Record = { mp3: 'mp3', mpeg: 'mp3', 'audio/mpeg': 'mp3', 'audio/mp3': 'mp3', wav: 'wav', wave: 'wav', 'audio/wav': 'wav', 'audio/x-wav': 'wav', m4a: 'm4a', mp4: 'm4a', 'audio/mp4': 'm4a', 'audio/x-m4a': 'm4a', ogg: 'ogg', oga: 'ogg', 'audio/ogg': 'ogg', webm: 'webm', 'audio/webm': 'webm', }; export class CustomTtsError extends Error { constructor(message: string) { super(message); this.name = 'CustomTtsError'; } } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); } function validateHttpUrl(raw: unknown, field: string): string { if (typeof raw !== 'string' || raw.trim() === '') { throw new CustomTtsError(`${field} must be a non-empty HTTP(S) URL.`); } let url: URL; try { url = new URL(raw); } catch { throw new CustomTtsError(`${field} must be a valid HTTP(S) URL.`); } if (url.protocol !== 'http:' && url.protocol !== 'https:') { throw new CustomTtsError(`${field} must use http:// or https://.`); } return url.toString(); } function validateHeaders(raw: unknown): Record { if (raw === undefined) return { 'Content-Type': 'application/json' }; if (!isRecord(raw)) throw new CustomTtsError('request.headers must be a JSON object.'); const headers: Record = {}; for (const [name, value] of Object.entries(raw)) { if (typeof value !== 'string') { throw new CustomTtsError(`request.headers.${name} must be a string.`); } headers[name] = value; } if (!Object.keys(headers).some(name => name.toLowerCase() === 'content-type')) { headers['Content-Type'] = 'application/json'; } return headers; } function validateTimeout(raw: unknown): number { if (raw === undefined) return DEFAULT_TIMEOUT_MS; if (!Number.isInteger(raw) || Number(raw) <= 0 || Number(raw) > MAX_TIMEOUT_MS) { throw new CustomTtsError(`request.timeout_ms must be an integer between 1 and ${MAX_TIMEOUT_MS}.`); } return Number(raw); } function validateResponse(raw: unknown): CustomTtsResponseConfig { if (raw === undefined) return { type: 'binary' }; if (!isRecord(raw)) throw new CustomTtsError('response must be a JSON object.'); const type = raw.type ?? 'binary'; if (type !== 'binary' && type !== 'json_base64' && type !== 'json_url') { throw new CustomTtsError('response.type must be binary, json_base64, or json_url.'); } const path = raw.path; if (type !== 'binary' && (typeof path !== 'string' || path.trim() === '')) { throw new CustomTtsError(`response.path is required when response.type is ${type}.`); } if (raw.content_type !== undefined && (typeof raw.content_type !== 'string' || raw.content_type.trim() === '')) { throw new CustomTtsError('response.content_type must be a non-empty string.'); } if (raw.format !== undefined && (typeof raw.format !== 'string' || raw.format.trim() === '')) { throw new CustomTtsError('response.format must be a non-empty string.'); } if (raw.format_path !== undefined && (typeof raw.format_path !== 'string' || raw.format_path.trim() === '')) { throw new CustomTtsError('response.format_path must be a non-empty string.'); } if (type === 'binary' && raw.format_path !== undefined) { throw new CustomTtsError('response.format_path is only supported for json_base64 and json_url responses.'); } if (raw.filename !== undefined) { if (typeof raw.filename !== 'string' || raw.filename.trim() === '' || basename(raw.filename) !== raw.filename) { throw new CustomTtsError('response.filename must be a plain filename without directories.'); } } const configuredFormat = typeof raw.format === 'string' ? resolveAudioFormat(raw.format, 'response.format') : undefined; const configuredContentType = typeof raw.content_type === 'string' ? resolveAudioFormat(raw.content_type, 'response.content_type') : undefined; if (configuredFormat && configuredContentType && configuredFormat.format !== configuredContentType.format) { throw new CustomTtsError('response.format and response.content_type describe different audio formats.'); } return { type, ...(typeof path === 'string' ? { path } : {}), ...(typeof raw.format === 'string' ? { format: raw.format.trim() } : {}), ...(typeof raw.format_path === 'string' ? { format_path: raw.format_path.trim() } : {}), ...(typeof raw.content_type === 'string' ? { content_type: raw.content_type } : {}), ...(typeof raw.filename === 'string' ? { filename: raw.filename } : {}), }; } function validateTextField(raw: unknown): string | undefined { if (raw === undefined) return undefined; if (typeof raw !== 'string' || raw.trim() === '') { throw new CustomTtsError('request.text_field must be a non-empty string.'); } return raw.trim(); } function validateBody(raw: unknown): JsonObject { if (raw === undefined) return {}; if (!isRecord(raw)) throw new CustomTtsError('request.body must be a JSON object.'); return raw as JsonObject; } function containsTextPlaceholder(value: JsonValue): boolean { if (typeof value === 'string') return value.includes('{{text}}'); if (Array.isArray(value)) return value.some(containsTextPlaceholder); if (value !== null && typeof value === 'object') { return Object.values(value).some(containsTextPlaceholder); } return false; } function substituteText(value: JsonValue, text: string): JsonValue { if (typeof value === 'string') return value.replaceAll('{{text}}', text); if (Array.isArray(value)) return value.map(item => substituteText(item, text)); if (value !== null && typeof value === 'object') { return Object.fromEntries( Object.entries(value).map(([key, item]) => [key, substituteText(item, text)]), ); } return value; } export function parseCustomTtsConfig(raw: unknown): CustomTtsConfig | null { if (!isRecord(raw)) throw new CustomTtsError('TTS config must be a JSON object.'); if (raw.customize_tts === undefined || raw.customize_tts === false) return null; if (raw.customize_tts !== true) throw new CustomTtsError('customize_tts must be a JSON boolean.'); if (!isRecord(raw.request)) throw new CustomTtsError('request must be a JSON object.'); const method = typeof raw.request.method === 'string' ? raw.request.method.toUpperCase() : 'POST'; if (method !== 'POST') throw new CustomTtsError('request.method currently supports POST only.'); const textField = validateTextField(raw.request.text_field); const body = validateBody(raw.request.body); if (!textField && !containsTextPlaceholder(body)) { throw new CustomTtsError( 'Configure request.text_field or place {{text}} in request.body to specify the speech text.', ); } return { customize_tts: true, request: { url: validateHttpUrl(raw.request.url, 'request.url'), method: 'POST', headers: validateHeaders(raw.request.headers), ...(textField ? { text_field: textField } : {}), body, timeout_ms: validateTimeout(raw.request.timeout_ms), }, response: validateResponse(raw.response), }; } export function loadCustomTtsConfig(workspaceDir = getWorkspaceDir()): CustomTtsConfig | null { const path = getWorkspaceConfigFile(workspaceDir); if (!existsSync(path)) return null; let raw: unknown; try { raw = JSON.parse(readFileSync(path, 'utf8')); } catch (err) { const detail = err instanceof Error ? err.message : String(err); throw new CustomTtsError(`Cannot parse ${path}: ${detail}`); } if (!isRecord(raw)) throw new CustomTtsError(`${path} must contain a JSON object.`); if (raw.tts === undefined) return null; return parseCustomTtsConfig(raw.tts); } function valueAtPath(value: unknown, path: string): unknown { let current = value; for (const segment of path.split('.')) { if (segment === '') throw new CustomTtsError(`Invalid response.path: ${path}`); if (Array.isArray(current) && /^\d+$/.test(segment)) { current = current[Number(segment)]; } else if (isRecord(current)) { current = current[segment]; } else { return undefined; } } return current; } function normalizeContentType(value: string | null | undefined): string | undefined { const normalized = value?.split(';', 1)[0].trim().toLowerCase(); return normalized || undefined; } function resolveAudioFormat(raw: string, label: string): ResolvedAudioFormat { const normalized = normalizeContentType(raw)?.replace(/^\./, ''); const format = normalized ? AUDIO_FORMAT_ALIASES[normalized] : undefined; if (!format) { throw new CustomTtsError(`${label} has unsupported audio format "${raw}". Supported: ${SUPPORTED_AUDIO_FORMATS}.`); } return AUDIO_FORMATS[format]; } function formatFromServerContentType(contentType: string | null, label: string): ResolvedAudioFormat | undefined { const normalized = normalizeContentType(contentType); if (!normalized || normalized === 'application/octet-stream' || normalized === 'binary/octet-stream') { return undefined; } return resolveAudioFormat(normalized, `${label} content-type`); } function configuredAudioFormat(response: CustomTtsResponseConfig): ResolvedAudioFormat | undefined { return response.format ? resolveAudioFormat(response.format, 'response.format') : response.content_type ? resolveAudioFormat(response.content_type, 'response.content_type') : undefined; } function selectAudioFormat( response: CustomTtsResponseConfig, serverFormats: Array<{ value: ResolvedAudioFormat | undefined; label: string }>, ): ResolvedAudioFormat { const authoritative = serverFormats.filter( (candidate): candidate is { value: ResolvedAudioFormat; label: string } => candidate.value !== undefined, ); const first = authoritative[0]; for (const candidate of authoritative.slice(1)) { if (candidate.value.format !== first.value.format) { throw new CustomTtsError( `TTS response audio formats conflict: ${first.label} is ${first.value.format}, ` + `${candidate.label} is ${candidate.value.format}.`, ); } } const configured = configuredAudioFormat(response); if (first && configured && first.value.format !== configured.format) { throw new CustomTtsError( `TTS response audio format ${first.value.format} conflicts with configured format ${configured.format}.`, ); } if (first) return first.value; if (configured) return configured; throw new CustomTtsError( 'Cannot determine custom TTS audio format. ' + 'Return a supported audio Content-Type/format or set response.format in config.json.', ); } function validateAudio(audio: Buffer): Buffer { if (audio.length === 0) throw new CustomTtsError('Custom TTS returned empty audio.'); if (audio.length > MAX_AUDIO_BYTES) { throw new CustomTtsError(`Custom TTS audio exceeds ${MAX_AUDIO_BYTES / 1024 / 1024} MB.`); } return audio; } async function responseError(response: Response, label: string): Promise { let detail = ''; try { detail = (await response.text()).trim().slice(0, 500); } catch {} return new CustomTtsError(`${label} failed with status ${response.status}${detail ? `: ${detail}` : ''}`); } async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs: number, label: string): Promise { try { return await fetch(url, { ...init, signal: AbortSignal.timeout(timeoutMs) }); } catch (err) { if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError')) { throw new CustomTtsError(`${label} timed out after ${timeoutMs} ms.`); } throw new CustomTtsError(`${label} failed: ${err instanceof Error ? err.message : String(err)}`); } } function decodeBase64(raw: string): { audio: Buffer; contentType?: string } { const dataUrl = raw.match(/^data:([^;,]+)?;base64,([\s\S]*)$/i); const encoded = (dataUrl?.[2] ?? raw).replace(/\s+/g, ''); if (encoded === '') throw new CustomTtsError('Custom TTS returned empty base64 audio.'); const audio = Buffer.from(encoded, 'base64'); return { audio: validateAudio(audio), contentType: normalizeContentType(dataUrl?.[1]) }; } function finalAudio( audio: Buffer, response: CustomTtsResponseConfig, serverFormats: Array<{ value: ResolvedAudioFormat | undefined; label: string }>, ): CustomTtsAudio { const format = selectAudioFormat(response, serverFormats); const filename = response.filename ?? `tts${format.extension}`; const filenameExtension = extname(filename).toLowerCase(); if (filenameExtension !== format.extension) { throw new CustomTtsError( `response.filename extension "${filenameExtension || '(none)'}" does not match audio format ${format.format}.`, ); } return { audio: validateAudio(audio), contentType: format.contentType, filename }; } export async function synthesizeCustomTts(text: string, config: CustomTtsConfig): Promise { const substitutedBody = substituteText(config.request.body, text) as JsonObject; const requestBody = config.request.text_field ? { ...substitutedBody, [config.request.text_field]: text } : substitutedBody; const response = await fetchWithTimeout(config.request.url, { method: config.request.method, headers: config.request.headers, body: JSON.stringify(requestBody), }, config.request.timeout_ms, 'Custom TTS request'); if (!response.ok) throw await responseError(response, 'Custom TTS request'); if (config.response.type === 'binary') { const contentTypeFormat = formatFromServerContentType(response.headers.get('content-type'), 'Custom TTS request'); return finalAudio(Buffer.from(await response.arrayBuffer()), config.response, [ { value: contentTypeFormat, label: 'HTTP Content-Type' }, ]); } let payload: unknown; try { payload = await response.json(); } catch { throw new CustomTtsError('Custom TTS response is not valid JSON.'); } const value = valueAtPath(payload, config.response.path!); if (typeof value !== 'string' || value.trim() === '') { throw new CustomTtsError(`Custom TTS response path "${config.response.path}" did not contain a string.`); } if (config.response.type === 'json_base64') { const decoded = decodeBase64(value); const dataUrlFormat = decoded.contentType ? resolveAudioFormat(decoded.contentType, 'Base64 data URL content-type') : undefined; const responseFormat = config.response.format_path ? valueAtPath(payload, config.response.format_path) : undefined; if (config.response.format_path && (typeof responseFormat !== 'string' || responseFormat.trim() === '')) { throw new CustomTtsError( `Custom TTS response format path "${config.response.format_path}" did not contain a string.`, ); } const formatPathFormat = typeof responseFormat === 'string' ? resolveAudioFormat(responseFormat, `response.format_path "${config.response.format_path}"`) : undefined; return finalAudio(decoded.audio, config.response, [ { value: dataUrlFormat, label: 'Base64 data URL' }, { value: formatPathFormat, label: `response.format_path "${config.response.format_path}"` }, ]); } const audioUrl = validateHttpUrl(value, `response.${config.response.path}`); const responseFormat = config.response.format_path ? valueAtPath(payload, config.response.format_path) : undefined; if (config.response.format_path && (typeof responseFormat !== 'string' || responseFormat.trim() === '')) { throw new CustomTtsError( `Custom TTS response format path "${config.response.format_path}" did not contain a string.`, ); } const formatPathFormat = typeof responseFormat === 'string' ? resolveAudioFormat(responseFormat, `response.format_path "${config.response.format_path}"`) : undefined; const download = await fetchWithTimeout(audioUrl, { method: 'GET' }, config.request.timeout_ms, 'Custom TTS audio download'); if (!download.ok) throw await responseError(download, 'Custom TTS audio download'); const downloadFormat = formatFromServerContentType(download.headers.get('content-type'), 'Custom TTS audio download'); return finalAudio(Buffer.from(await download.arrayBuffer()), config.response, [ { value: downloadFormat, label: 'download HTTP Content-Type' }, { value: formatPathFormat, label: `response.format_path "${config.response.format_path}"` }, ]); } export async function synthesizeConfiguredTts(text: string, workspaceDir = getWorkspaceDir()): Promise { const config = loadCustomTtsConfig(workspaceDir); if (!config) return null; return synthesizeCustomTts(text, config); }