soma-voice 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,67 +1,90 @@
1
1
  import 'server-only';
2
+ import {
3
+ AUDIO_CONTAINER_EXTENSION,
4
+ AUDIO_CONTAINER_MIME,
5
+ AUDIO_SNIFF_BYTES,
6
+ sniffAudioContainer,
7
+ type AudioContainer,
8
+ } from '../shared/audio-format';
9
+ import { parseTranscriptionResult, type TranscriptionResult } from '../shared/transcription';
2
10
  import type { VoiceConfig } from './config';
3
11
  import { acquireVoicePermit } from './concurrency';
4
12
  import { VoiceErrorCodes, VoiceServerError } from './errors';
5
13
 
6
- const MAGIC: Record<string, (bytes: Uint8Array) => boolean> = {
7
- 'audio/wav': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
8
- && String.fromCharCode(...bytes.slice(8, 12)) === 'WAVE',
9
- 'audio/x-wav': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
10
- && String.fromCharCode(...bytes.slice(8, 12)) === 'WAVE',
11
- 'audio/mpeg': (bytes) => String.fromCharCode(...bytes.slice(0, 3)) === 'ID3'
12
- || (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0),
13
- 'audio/webm': (bytes) => bytes[0] === 0x1a && bytes[1] === 0x45
14
- && bytes[2] === 0xdf && bytes[3] === 0xa3,
15
- 'audio/ogg': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'OggS',
16
- 'audio/mp4': (bytes) => String.fromCharCode(...bytes.slice(4, 8)) === 'ftyp',
17
- };
14
+ /** multipart 封装余量:Content-Length 预检按 maxAudioBytes + 64KiB 判定。 */
15
+ const MULTIPART_OVERHEAD_BYTES = 64 * 1024;
16
+ /** 合成请求 JSON 的字节上限:每码点按最坏 12 字节(`\uXXXX\uXXXX`)加 4KiB 字段余量。 */
17
+ const JSON_BYTES_PER_CODE_POINT = 12;
18
+ const JSON_OVERHEAD_BYTES = 4 * 1024;
19
+ /** 上游错误体只读这么多,仅用于挑选映射,不回传原文。 */
20
+ const ERROR_BODY_BYTES = 8 * 1024;
21
+ const LANGUAGE_PATTERN = /^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/;
22
+ const MAX_LANGUAGE_LENGTH = 32;
23
+ const MAX_PROMPT_CODE_POINTS = 1_000;
24
+ const SYNTHESIS_AUDIO_TYPES = new Set(['audio/wav', 'audio/x-wav', 'audio/wave', 'audio/mpeg']);
18
25
 
19
26
  interface BlobLike {
20
27
  size: number;
21
- type: string;
22
28
  slice(start?: number, end?: number): Blob;
23
29
  arrayBuffer(): Promise<ArrayBuffer>;
24
- name?: string;
25
30
  }
26
31
 
27
32
  function isBlobLike(value: unknown): value is BlobLike {
28
33
  if (!value || typeof value !== 'object') return false;
29
34
  const candidate = value as Partial<BlobLike>;
30
35
  return typeof candidate.size === 'number'
31
- && typeof candidate.type === 'string'
32
36
  && typeof candidate.slice === 'function'
33
37
  && typeof candidate.arrayBuffer === 'function';
34
38
  }
35
39
 
36
- export async function validateAudio(file: BlobLike, max: number): Promise<void> {
37
- if (!isBlobLike(file) || file.size < 4) {
40
+ /**
41
+ * 校验上传音频并按文件头魔数判定容器。只读前 {@link AUDIO_SNIFF_BYTES} 字节,
42
+ * 完全不看声明 MIME(各浏览器 MediaRecorder 报出的类型不可信)。
43
+ */
44
+ export async function validateAudioUpload(file: unknown, maxBytes: number): Promise<AudioContainer> {
45
+ if (!isBlobLike(file)) {
46
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Missing audio file.');
47
+ }
48
+ if (file.size === 0) {
38
49
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Audio file is empty.');
39
50
  }
40
- if (file.size > max) {
51
+ // 最短的魔数(OggS、fLaC、EBML、ID3)是 4 字节:更短的文件无从判定容器。
52
+ if (file.size < 4) {
53
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Audio file is too short to identify.');
54
+ }
55
+ if (file.size > maxBytes) {
41
56
  throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Audio file is too large.', 413);
42
57
  }
43
- const mime = file.type.toLowerCase().split(';', 1)[0];
44
- const check = MAGIC[mime];
45
- if (!check) {
46
- throw new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, 'Unsupported audio MIME type.');
58
+ let head: Uint8Array;
59
+ try {
60
+ head = new Uint8Array(await file.slice(0, AUDIO_SNIFF_BYTES).arrayBuffer());
61
+ } catch {
62
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Audio file cannot be read.');
47
63
  }
48
- const bytes = new Uint8Array(await file.slice(0, 16).arrayBuffer());
49
- if (!check(bytes)) {
50
- throw new VoiceServerError(
51
- VoiceErrorCodes.UNSUPPORTED_AUDIO,
52
- 'Audio content does not match MIME type.',
53
- );
64
+ const container = sniffAudioContainer(head);
65
+ if (!container) {
66
+ throw new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, 'Unsupported audio format.', 415);
54
67
  }
68
+ return container;
55
69
  }
56
70
 
57
- async function readLimited(response: Response, maxBytes: number): Promise<Uint8Array> {
58
- const declared = Number(response.headers.get('content-length'));
59
- if (Number.isFinite(declared) && declared > maxBytes) {
60
- await response.body?.cancel().catch(() => undefined);
61
- throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream response is too large.', 502);
71
+ function concatChunks(chunks: Uint8Array[], total: number): Uint8Array {
72
+ const result = new Uint8Array(total);
73
+ let offset = 0;
74
+ for (const chunk of chunks) {
75
+ result.set(chunk, offset);
76
+ offset += chunk.byteLength;
62
77
  }
63
- if (!response.body) return new Uint8Array();
64
- const reader = response.body.getReader();
78
+ return result;
79
+ }
80
+
81
+ async function readBounded(
82
+ stream: ReadableStream<Uint8Array> | null,
83
+ maxBytes: number,
84
+ tooLarge: () => VoiceServerError,
85
+ ): Promise<Uint8Array> {
86
+ if (!stream) return new Uint8Array();
87
+ const reader = stream.getReader();
65
88
  const chunks: Uint8Array[] = [];
66
89
  let total = 0;
67
90
  try {
@@ -69,44 +92,120 @@ async function readLimited(response: Response, maxBytes: number): Promise<Uint8A
69
92
  const { done, value } = await reader.read();
70
93
  if (done) break;
71
94
  total += value.byteLength;
72
- if (total > maxBytes) {
73
- await reader.cancel().catch(() => undefined);
74
- throw new VoiceServerError(
75
- VoiceErrorCodes.UPSTREAM,
76
- 'Voice upstream response is too large.',
77
- 502,
78
- );
79
- }
95
+ if (total > maxBytes) throw tooLarge();
80
96
  chunks.push(value);
81
97
  }
82
98
  } catch (error) {
83
99
  await reader.cancel().catch(() => undefined);
84
100
  throw error;
85
101
  }
86
- const result = new Uint8Array(total);
87
- let offset = 0;
88
- for (const chunk of chunks) {
89
- result.set(chunk, offset);
90
- offset += chunk.byteLength;
102
+ return concatChunks(chunks, total);
103
+ }
104
+
105
+ async function readLimited(response: Response, maxBytes: number): Promise<Uint8Array> {
106
+ const tooLarge = () => new VoiceServerError(
107
+ VoiceErrorCodes.UPSTREAM,
108
+ 'Voice service response is too large.',
109
+ 502,
110
+ );
111
+ const declared = Number(response.headers.get('content-length'));
112
+ if (Number.isFinite(declared) && declared > maxBytes) {
113
+ await response.body?.cancel().catch(() => undefined);
114
+ throw tooLarge();
91
115
  }
92
- return result;
116
+ return readBounded(response.body, maxBytes, tooLarge);
117
+ }
118
+
119
+ function toArrayBuffer(bytes: Uint8Array): ArrayBuffer {
120
+ return bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength
121
+ ? bytes.buffer as ArrayBuffer
122
+ : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
93
123
  }
94
124
 
95
- async function discardErrorResponse(response: Response): Promise<void> {
96
- if (!response.body) return;
125
+ /** 读取上游错误体(≤8KiB)里的 `{error:{code}}`,只用于挑选映射;读不到或不合法返回 undefined。 */
126
+ async function readUpstreamErrorCode(response: Response): Promise<string | undefined> {
127
+ if (!response.body) return undefined;
97
128
  const reader = response.body.getReader();
98
- let read = 0;
129
+ const chunks: Uint8Array[] = [];
130
+ let total = 0;
99
131
  try {
100
- while (read < 8192) {
132
+ while (total < ERROR_BODY_BYTES) {
101
133
  const { done, value } = await reader.read();
102
- if (done) return;
103
- read += value.byteLength;
134
+ if (done) break;
135
+ chunks.push(value);
136
+ total += value.byteLength;
104
137
  }
138
+ } catch {
139
+ return undefined;
105
140
  } finally {
106
141
  await reader.cancel().catch(() => undefined);
107
142
  }
143
+ try {
144
+ const body = JSON.parse(new TextDecoder().decode(concatChunks(chunks, total))) as unknown;
145
+ const error = body && typeof body === 'object'
146
+ ? (body as { error?: unknown }).error
147
+ : undefined;
148
+ const code = error && typeof error === 'object'
149
+ ? (error as { code?: unknown }).code
150
+ : undefined;
151
+ return typeof code === 'string' ? code : undefined;
152
+ } catch {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ /** 上游非 2xx 映射为 Host 错误;消息由 Host 给出,不回传上游 message 原文。 */
158
+ function upstreamError(status: number, upstreamCode: string | undefined): VoiceServerError {
159
+ switch (status) {
160
+ case 401:
161
+ case 403:
162
+ return new VoiceServerError(
163
+ VoiceErrorCodes.UPSTREAM,
164
+ 'Voice service rejected the Host credentials.',
165
+ 502,
166
+ );
167
+ case 413:
168
+ if (upstreamCode === 'TEXT_TOO_LONG') {
169
+ return new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.', 413);
170
+ }
171
+ return new VoiceServerError(
172
+ VoiceErrorCodes.AUDIO_TOO_LARGE,
173
+ upstreamCode === 'AUDIO_TOO_LONG' ? 'Audio recording is too long.' : 'Audio file is too large.',
174
+ 413,
175
+ );
176
+ case 415:
177
+ return new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, 'Unsupported audio format.', 415);
178
+ case 422:
179
+ return new VoiceServerError(
180
+ VoiceErrorCodes.UNDECODABLE_AUDIO,
181
+ 'Audio could not be decoded.',
182
+ 422,
183
+ );
184
+ case 429:
185
+ case 503:
186
+ // 引擎未配置 / 模型加载失败重试不会自愈,单列一码(不带 Retry-After);其余 503 与 429 才是「稍后重试」。
187
+ if (status === 503 && upstreamCode === 'ENGINE_UNAVAILABLE') {
188
+ return new VoiceServerError(VoiceErrorCodes.ENGINE_UNAVAILABLE, 'Voice engine is unavailable.', 503);
189
+ }
190
+ return new VoiceServerError(VoiceErrorCodes.BUSY, 'Voice service is busy.', 503);
191
+ case 400:
192
+ return new VoiceServerError(
193
+ VoiceErrorCodes.INVALID_OPTION,
194
+ 'Voice service rejected the request options.',
195
+ );
196
+ default:
197
+ return new VoiceServerError(
198
+ VoiceErrorCodes.UPSTREAM,
199
+ `Voice service failed (${status}).`,
200
+ 502,
201
+ );
202
+ }
108
203
  }
109
204
 
205
+ /**
206
+ * 转发到内部语音服务:超时、并发许可、调用方取消联动;许可覆盖到响应体读完为止。
207
+ * 凭据只在配置了 serviceToken 时进 `Authorization` 头。
208
+ */
110
209
  async function upstream<T>(
111
210
  config: VoiceConfig,
112
211
  upstreamPath: string,
@@ -126,32 +225,26 @@ async function upstream<T>(
126
225
  try {
127
226
  if (signal?.aborted) controller.abort();
128
227
  release = await acquireVoicePermit(config, controller.signal);
129
- const response = await fetch(`${config.baseUrl}${upstreamPath}`, {
228
+ const headers = new Headers(init.headers);
229
+ if (config.serviceToken) headers.set('authorization', `Bearer ${config.serviceToken}`);
230
+ const response = await fetch(`${config.serviceUrl}${upstreamPath}`, {
130
231
  ...init,
131
- headers: { ...init.headers, authorization: `Bearer ${config.apiKey}` },
232
+ headers,
132
233
  signal: controller.signal,
133
234
  });
134
235
  if (!response.ok) {
135
- await discardErrorResponse(response);
136
- if (response.status === 429) {
137
- throw new VoiceServerError(VoiceErrorCodes.BUSY, 'Voice upstream is rate limited.', 429);
138
- }
139
- throw new VoiceServerError(
140
- VoiceErrorCodes.UPSTREAM,
141
- `Voice upstream failed (${response.status}).`,
142
- 502,
143
- );
236
+ throw upstreamError(response.status, await readUpstreamErrorCode(response));
144
237
  }
145
238
  return await read(response);
146
239
  } catch (error) {
147
- if (error instanceof VoiceServerError) throw error;
148
240
  if (timedOut) {
149
- throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice upstream timed out.', 504);
241
+ throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice service timed out.', 504);
150
242
  }
243
+ if (error instanceof VoiceServerError) throw error;
151
244
  if (signal?.aborted) {
152
245
  throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499);
153
246
  }
154
- throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream unavailable.', 502);
247
+ throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice service unavailable.', 502);
155
248
  } finally {
156
249
  release?.();
157
250
  clearTimeout(timer);
@@ -159,13 +252,15 @@ async function upstream<T>(
159
252
  }
160
253
  }
161
254
 
162
- function rejectOversizedContentLength(request: Request, maxBytes: number): void {
255
+ function rejectOversizedContentLength(
256
+ request: Request,
257
+ maxBytes: number,
258
+ tooLarge: () => VoiceServerError,
259
+ ): void {
163
260
  const raw = request.headers.get('content-length');
164
261
  if (!raw) return;
165
262
  const length = Number(raw);
166
- if (Number.isFinite(length) && length > maxBytes) {
167
- throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Audio request is too large.', 413);
168
- }
263
+ if (Number.isFinite(length) && length > maxBytes) throw tooLarge();
169
264
  }
170
265
 
171
266
  function exceedsCodePoints(text: string, maximum: number): boolean {
@@ -177,101 +272,64 @@ function exceedsCodePoints(text: string, maximum: number): boolean {
177
272
  return false;
178
273
  }
179
274
 
180
- const AUDIO_MIME_BY_FORMAT: Record<string, string> = {
181
- mp3: 'audio/mpeg',
182
- wav: 'audio/wav',
183
- opus: 'audio/ogg',
184
- ogg: 'audio/ogg',
185
- aac: 'audio/aac',
186
- flac: 'audio/flac',
187
- mp4: 'audio/mp4',
188
- };
189
-
190
- export interface ServerTranscriptionWord {
191
- text: string;
192
- startMs?: number;
193
- endMs?: number;
194
- speaker?: string;
275
+ function mediaType(value: string | null): string {
276
+ return String(value ?? '').toLowerCase().split(';', 1)[0]!.trim();
195
277
  }
196
278
 
197
- export interface ServerTranscriptionSegment {
198
- text: string;
199
- startMs?: number;
200
- endMs?: number;
201
- speaker?: string;
202
- words?: ServerTranscriptionWord[];
279
+ /** 读取可选文本字段;缺省或空串视为未给出,文件等非文本值报 INVALID_OPTION。 */
280
+ function optionalTextField(form: FormData, name: string, message: string): string | undefined {
281
+ const value = form.get(name);
282
+ if (value === null || value === '') return undefined;
283
+ if (typeof value !== 'string') {
284
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, message);
285
+ }
286
+ return value;
203
287
  }
204
288
 
205
- export interface ServerTranscriptionResult {
206
- text: string;
289
+ interface TranscriptionOptions {
207
290
  language?: string;
208
- durationMs?: number;
209
- segments?: ServerTranscriptionSegment[];
210
- }
211
-
212
- function secondsToMilliseconds(value: unknown): number | undefined {
213
- return typeof value === 'number' && Number.isFinite(value) && value >= 0
214
- ? Math.round(value * 1000)
215
- : undefined;
291
+ prompt?: string;
292
+ wordTimestamps?: 'true' | 'false';
216
293
  }
217
294
 
218
- function parseProviderTranscription(value: unknown): ServerTranscriptionResult | undefined {
219
- if (!value || typeof value !== 'object') return undefined;
220
- const source = value as Record<string, unknown>;
221
- if (typeof source.text !== 'string') return undefined;
222
- const segments = Array.isArray(source.segments)
223
- ? source.segments.flatMap((segment) => {
224
- if (!segment || typeof segment !== 'object') return [];
225
- const item = segment as Record<string, unknown>;
226
- if (typeof item.text !== 'string') return [];
227
- const startMs = secondsToMilliseconds(item.start);
228
- const endMs = secondsToMilliseconds(item.end);
229
- const words = Array.isArray(item.words)
230
- ? item.words.flatMap((word) => {
231
- if (!word || typeof word !== 'object') return [];
232
- const entry = word as Record<string, unknown>;
233
- const text = typeof entry.word === 'string'
234
- ? entry.word
235
- : typeof entry.text === 'string' ? entry.text : undefined;
236
- if (!text) return [];
237
- const wordStartMs = secondsToMilliseconds(entry.start);
238
- const wordEndMs = secondsToMilliseconds(entry.end);
239
- return [{
240
- text,
241
- ...(wordStartMs !== undefined ? { startMs: wordStartMs } : {}),
242
- ...(wordEndMs !== undefined ? { endMs: wordEndMs } : {}),
243
- ...(typeof entry.speaker === 'string' ? { speaker: entry.speaker } : {}),
244
- }];
245
- })
246
- : undefined;
247
- return [{
248
- text: item.text,
249
- ...(startMs !== undefined ? { startMs } : {}),
250
- ...(endMs !== undefined ? { endMs } : {}),
251
- ...(typeof item.speaker === 'string' ? { speaker: item.speaker } : {}),
252
- ...(words ? { words } : {}),
253
- }];
254
- })
255
- : undefined;
256
- const durationMs = secondsToMilliseconds(source.duration);
295
+ function readTranscriptionOptions(form: FormData): TranscriptionOptions {
296
+ const language = optionalTextField(form, 'language', 'Invalid voice language.');
297
+ if (language !== undefined
298
+ && (language.length > MAX_LANGUAGE_LENGTH || !LANGUAGE_PATTERN.test(language))) {
299
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice language.');
300
+ }
301
+ const prompt = optionalTextField(form, 'prompt', 'Invalid voice prompt.');
302
+ if (prompt !== undefined && exceedsCodePoints(prompt, MAX_PROMPT_CODE_POINTS)) {
303
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Voice prompt is too long.');
304
+ }
305
+ const wordTimestamps = optionalTextField(form, 'word_timestamps', 'Invalid word_timestamps.');
306
+ if (wordTimestamps !== undefined && wordTimestamps !== 'true' && wordTimestamps !== 'false') {
307
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid word_timestamps.');
308
+ }
257
309
  return {
258
- text: source.text,
259
- ...(typeof source.language === 'string' ? { language: source.language } : {}),
260
- ...(durationMs !== undefined ? { durationMs } : {}),
261
- ...(segments ? { segments } : {}),
310
+ ...(language !== undefined ? { language } : {}),
311
+ ...(prompt !== undefined ? { prompt } : {}),
312
+ ...(wordTimestamps !== undefined ? { wordTimestamps } : {}),
262
313
  };
263
314
  }
264
315
 
265
- export async function transcribeDetailed(
316
+ /**
317
+ * `POST /api/voice/transcribe`:multipart 字段 `file`(必填)、`language`、`prompt`、`word_timestamps`。
318
+ * 按魔数判定容器后以规范 MIME 与文件名转发到 `${serviceUrl}/api/transcribe`,返回契约形状的转写结果。
319
+ */
320
+ export async function transcribe(
266
321
  request: Request,
267
322
  config: VoiceConfig,
268
- ): Promise<ServerTranscriptionResult> {
269
- const type = request.headers.get('content-type') ?? '';
270
- if (!type.toLowerCase().startsWith('multipart/form-data')) {
323
+ ): Promise<TranscriptionResult> {
324
+ if (mediaType(request.headers.get('content-type')) !== 'multipart/form-data') {
271
325
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Expected multipart/form-data.');
272
326
  }
273
- // The framework still buffers multipart parsing; Content-Length rejects obvious oversize bodies first.
274
- rejectOversizedContentLength(request, config.maxAudioBytes + 64 * 1024);
327
+ // formData() 仍会整体缓冲请求体;先按 Content-Length 拒绝明显超限的请求。
328
+ rejectOversizedContentLength(
329
+ request,
330
+ config.maxAudioBytes + MULTIPART_OVERHEAD_BYTES,
331
+ () => new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Audio request is too large.', 413),
332
+ );
275
333
  let form: FormData;
276
334
  try {
277
335
  form = await request.formData();
@@ -279,43 +337,28 @@ export async function transcribeDetailed(
279
337
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed multipart request.');
280
338
  }
281
339
  const file = form.get('file');
282
- if (!isBlobLike(file)) {
283
- throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Missing audio file.');
284
- }
285
- await validateAudio(file, config.maxAudioBytes);
340
+ const container = await validateAudioUpload(file, config.maxAudioBytes);
341
+ const options = readTranscriptionOptions(form);
342
+
286
343
  const body = new FormData();
287
- body.append('file', file as Blob, file.name || 'recording');
288
- body.append('model', config.transcriptionModel);
289
- const language = form.get('language');
290
- const prompt = form.get('prompt');
291
- if (language !== null
292
- && (typeof language !== 'string'
293
- || language.length > 32
294
- || !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language))) {
295
- throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice language.');
296
- }
297
- if (prompt !== null
298
- && (typeof prompt !== 'string' || [...prompt].length > 1_000)) {
299
- throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Voice prompt is too long.');
300
- }
301
- if (language) body.append('language', language);
302
- if (prompt) body.append('prompt', prompt);
303
- const responseFormat = form.get('response_format');
304
- if (responseFormat !== null
305
- && responseFormat !== 'json'
306
- && responseFormat !== 'verbose_json') {
307
- throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid response_format.');
308
- }
309
- body.append('response_format', responseFormat === 'verbose_json' ? 'verbose_json' : 'json');
310
- return upstream(config, '/audio/transcriptions', { method: 'POST', body }, async (response) => {
344
+ body.append(
345
+ 'file',
346
+ new Blob([file as Blob], { type: AUDIO_CONTAINER_MIME[container] }),
347
+ `recording.${AUDIO_CONTAINER_EXTENSION[container]}`,
348
+ );
349
+ if (options.language) body.append('language', options.language);
350
+ if (options.prompt) body.append('prompt', options.prompt);
351
+ if (options.wordTimestamps) body.append('word_timestamps', options.wordTimestamps);
352
+
353
+ return upstream(config, '/api/transcribe', { method: 'POST', body }, async (response) => {
311
354
  const bytes = await readLimited(response, config.maxResponseBytes);
312
355
  let json: unknown;
313
356
  try {
314
357
  json = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
315
358
  } catch {
316
- // Mapped below as an invalid upstream response.
359
+ // 下面按非法上游响应处理。
317
360
  }
318
- const result = parseProviderTranscription(json);
361
+ const result = parseTranscriptionResult(json);
319
362
  if (!result) {
320
363
  throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Invalid transcription response.', 502);
321
364
  }
@@ -323,103 +366,120 @@ export async function transcribeDetailed(
323
366
  }, request.signal);
324
367
  }
325
368
 
326
- export async function transcribe(request: Request, config: VoiceConfig): Promise<string> {
327
- return (await transcribeDetailed(request, config)).text;
328
- }
329
-
330
369
  interface SynthesisRequest {
331
370
  text: string;
332
371
  voice: string;
333
- format: string;
372
+ format: 'wav' | 'mp3';
334
373
  speed: number;
335
374
  }
336
375
 
376
+ async function readJsonBody(request: Request, maxBytes: number): Promise<unknown> {
377
+ const tooLarge = () => new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.', 413);
378
+ rejectOversizedContentLength(request, maxBytes, tooLarge);
379
+ let bytes: Uint8Array;
380
+ try {
381
+ bytes = await readBounded(request.body, maxBytes, tooLarge);
382
+ } catch (error) {
383
+ if (error instanceof VoiceServerError) throw error;
384
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Unable to read request body.');
385
+ }
386
+ try {
387
+ return JSON.parse(new TextDecoder().decode(bytes)) as unknown;
388
+ } catch {
389
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed JSON.');
390
+ }
391
+ }
392
+
337
393
  async function readSynthesisRequest(
338
394
  request: Request,
339
395
  config: VoiceConfig,
340
396
  ): Promise<SynthesisRequest> {
341
- if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) {
397
+ if (mediaType(request.headers.get('content-type')) !== 'application/json') {
342
398
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Expected application/json.');
343
399
  }
344
- let input: unknown;
345
- try {
346
- input = await request.json();
347
- } catch {
348
- throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed JSON.');
349
- }
350
- if (!input || typeof input !== 'object') {
400
+ const input = await readJsonBody(
401
+ request,
402
+ config.maxTextCodePoints * JSON_BYTES_PER_CODE_POINT + JSON_OVERHEAD_BYTES,
403
+ );
404
+ if (!input || typeof input !== 'object' || Array.isArray(input)) {
351
405
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Invalid speech request.');
352
406
  }
353
407
  const values = input as Record<string, unknown>;
354
408
  const text = values.text;
409
+ // trim() 去掉的是 ECMAScript WhiteSpace + LineTerminator:语音服务按同一集合(TEXT_WHITESPACE)判空,两端对同一段文本给出同一结论。
355
410
  if (typeof text !== 'string' || !text.trim()) {
356
411
  throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'text is required.');
357
412
  }
358
413
  if (exceedsCodePoints(text, config.maxTextCodePoints)) {
359
- throw new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.');
414
+ throw new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.', 413);
415
+ }
416
+ // 孤立代理项(如截断在 emoji 中间的 "\ud83d")编不成 UTF-8;与语音服务同一规则,转发前就拒绝。
417
+ if (/\p{Cs}/u.test(text)) {
418
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'text must be valid Unicode.');
360
419
  }
361
420
  const voice = values.voice ?? config.voices[0];
421
+ if (typeof voice !== 'string' || !config.voices.includes(voice)) {
422
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice.');
423
+ }
362
424
  const format = values.format ?? config.formats[0];
363
- const speed = values.speed ?? 1;
364
- if (typeof voice !== 'string' || !config.voices.includes(voice)
365
- || typeof format !== 'string' || !config.formats.includes(format)
366
- || typeof speed !== 'number' || !config.speeds.includes(speed)) {
367
- throw new VoiceServerError(
368
- VoiceErrorCodes.INVALID_OPTION,
369
- 'Invalid voice, format, or speed.',
370
- );
425
+ if (typeof format !== 'string' || !config.formats.includes(format as 'wav' | 'mp3')) {
426
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid audio format.');
371
427
  }
372
- return { text, voice, format, speed };
373
- }
374
-
375
- function synthesisUpstreamInit(config: VoiceConfig, input: SynthesisRequest): RequestInit {
376
- return {
377
- method: 'POST',
378
- headers: { 'content-type': 'application/json' },
379
- body: JSON.stringify({
380
- model: config.speechModel,
381
- input: input.text,
382
- voice: input.voice,
383
- response_format: input.format,
384
- speed: input.speed,
385
- }),
386
- };
428
+ // 缺省语速 1 为常速,不受 speeds 白名单约束;显式给出的语速须在白名单内。
429
+ const explicitSpeed = values.speed !== undefined && values.speed !== null;
430
+ const speed = explicitSpeed ? values.speed : 1;
431
+ if (typeof speed !== 'number' || (explicitSpeed && !config.speeds.includes(speed))) {
432
+ throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid speed.');
433
+ }
434
+ return { text, voice, format: format as 'wav' | 'mp3', speed };
387
435
  }
388
436
 
437
+ /**
438
+ * `POST /api/voice/synthesize`:JSON `{ text, voice?, format?, speed? }`。
439
+ * 转发到 `${serviceUrl}/api/synthesize`,有界读取整段音频后回写给浏览器。
440
+ */
389
441
  export async function synthesize(request: Request, config: VoiceConfig): Promise<Response> {
390
442
  const input = await readSynthesisRequest(request, config);
391
443
  const result = await upstream(
392
444
  config,
393
- '/audio/speech',
394
- synthesisUpstreamInit(config, input),
445
+ '/api/synthesize',
446
+ {
447
+ method: 'POST',
448
+ headers: { 'content-type': 'application/json' },
449
+ body: JSON.stringify({
450
+ text: input.text,
451
+ voice: input.voice,
452
+ format: input.format,
453
+ speed: input.speed,
454
+ }),
455
+ },
395
456
  async (response) => {
396
- const explicitType = response.headers.get('content-type');
397
- if (explicitType && !explicitType.toLowerCase().startsWith('audio/')) {
457
+ const mimeType = mediaType(response.headers.get('content-type'));
458
+ if (!SYNTHESIS_AUDIO_TYPES.has(mimeType)) {
398
459
  await response.body?.cancel().catch(() => undefined);
399
460
  throw new VoiceServerError(
400
461
  VoiceErrorCodes.UPSTREAM,
401
- 'Voice upstream returned a non-audio response.',
462
+ 'Voice service returned a non-audio response.',
402
463
  502,
403
464
  );
404
465
  }
405
- return {
406
- bytes: await readLimited(response, config.maxResponseBytes),
407
- mimeType: explicitType,
408
- };
466
+ const bytes = await readLimited(response, config.maxResponseBytes);
467
+ if (!bytes.byteLength) {
468
+ throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice service returned empty audio.', 502);
469
+ }
470
+ return { bytes, mimeType, durationMs: response.headers.get('x-audio-duration-ms') };
409
471
  },
410
472
  request.signal,
411
473
  );
412
- const responseBody = result.bytes.buffer.slice(
413
- result.bytes.byteOffset,
414
- result.bytes.byteOffset + result.bytes.byteLength,
415
- ) as ArrayBuffer;
416
- return new Response(responseBody, {
417
- status: 200,
418
- headers: {
419
- 'content-type': result.mimeType || AUDIO_MIME_BY_FORMAT[input.format] || 'application/octet-stream',
420
- 'content-length': String(result.bytes.byteLength),
421
- 'cache-control': 'no-store',
422
- 'x-content-type-options': 'nosniff',
423
- },
474
+ const headers = new Headers({
475
+ 'content-type': result.mimeType,
476
+ 'content-length': String(result.bytes.byteLength),
477
+ 'cache-control': 'no-store',
478
+ 'x-content-type-options': 'nosniff',
424
479
  });
480
+ const durationMs = result.durationMs?.trim();
481
+ if (durationMs && /^\d+$/.test(durationMs) && Number.isSafeInteger(Number(durationMs))) {
482
+ headers.set('x-audio-duration-ms', String(Number(durationMs)));
483
+ }
484
+ return new Response(toArrayBuffer(result.bytes), { status: 200, headers });
425
485
  }