soma-voice 1.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.
- package/README.md +85 -0
- package/manifest.md +11 -0
- package/package.json +61 -0
- package/src/api/service/index.ts +5 -0
- package/src/api/service/voice/Synthesize.ts +15 -0
- package/src/api/service/voice/Transcribe.ts +16 -0
- package/src/api/service/voice/synthesize/Stream.ts +15 -0
- package/src/api/service/voice/transcribe/Raw.ts +15 -0
- package/src/client/audio-conversion.ts +127 -0
- package/src/client/audio-processing.ts +153 -0
- package/src/client/browser-codec.ts +73 -0
- package/src/client/capabilities.ts +72 -0
- package/src/client/errors.ts +10 -0
- package/src/client/http.ts +237 -0
- package/src/client/index.ts +15 -0
- package/src/client/indexeddb-storage.ts +109 -0
- package/src/client/offline.ts +139 -0
- package/src/client/player.ts +117 -0
- package/src/client/realtime-stt.ts +261 -0
- package/src/client/recorder.ts +280 -0
- package/src/client/storage.ts +89 -0
- package/src/client/streaming-tts.ts +156 -0
- package/src/client/transports.ts +221 -0
- package/src/client/wav.ts +58 -0
- package/src/index.ts +1 -0
- package/src/server/concurrency.ts +75 -0
- package/src/server/config.ts +173 -0
- package/src/server/errors.ts +49 -0
- package/src/server/index.ts +9 -0
- package/src/server/raw-transcription.ts +70 -0
- package/src/server/runtime.ts +425 -0
- package/src/server/speech-stream.ts +176 -0
- package/src/server/streaming.ts +160 -0
- package/src/server/upload.ts +94 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import type { VoiceConfig } from './config';
|
|
3
|
+
import { acquireVoicePermit } from './concurrency';
|
|
4
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
5
|
+
|
|
6
|
+
interface SpeechStreamInput {
|
|
7
|
+
text: string;
|
|
8
|
+
voice: string;
|
|
9
|
+
format: string;
|
|
10
|
+
speed: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function exceedsCodePoints(text: string, maximum: number): boolean {
|
|
14
|
+
let count = 0;
|
|
15
|
+
for (const _point of text) {
|
|
16
|
+
count += 1;
|
|
17
|
+
if (count > maximum) return true;
|
|
18
|
+
}
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function readInput(request: Request, config: VoiceConfig): Promise<SpeechStreamInput> {
|
|
23
|
+
if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) {
|
|
24
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Expected application/json.');
|
|
25
|
+
}
|
|
26
|
+
let source: Record<string, unknown>;
|
|
27
|
+
try {
|
|
28
|
+
source = await request.json() as Record<string, unknown>;
|
|
29
|
+
} catch {
|
|
30
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed JSON.');
|
|
31
|
+
}
|
|
32
|
+
const text = source.text;
|
|
33
|
+
const voice = source.voice ?? config.voices[0];
|
|
34
|
+
const format = source.format ?? config.formats[0];
|
|
35
|
+
const speed = source.speed ?? 1;
|
|
36
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
37
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'text is required.');
|
|
38
|
+
}
|
|
39
|
+
if (exceedsCodePoints(text, config.maxTextCodePoints)) {
|
|
40
|
+
throw new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.');
|
|
41
|
+
}
|
|
42
|
+
if (typeof voice !== 'string' || !config.voices.includes(voice)
|
|
43
|
+
|| typeof format !== 'string' || !config.formats.includes(format)
|
|
44
|
+
|| typeof speed !== 'number' || !config.speeds.includes(speed)) {
|
|
45
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice, format, or speed.');
|
|
46
|
+
}
|
|
47
|
+
return { text, voice, format, speed };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const MIME_BY_FORMAT: Record<string, string> = {
|
|
51
|
+
mp3: 'audio/mpeg',
|
|
52
|
+
wav: 'audio/wav',
|
|
53
|
+
opus: 'audio/ogg',
|
|
54
|
+
ogg: 'audio/ogg',
|
|
55
|
+
aac: 'audio/aac',
|
|
56
|
+
flac: 'audio/flac',
|
|
57
|
+
mp4: 'audio/mp4',
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export async function synthesizeStream(request: Request, config: VoiceConfig): Promise<Response> {
|
|
61
|
+
const input = await readInput(request, config);
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
let timedOut = false;
|
|
64
|
+
let finalizeStream: ((reason?: unknown) => Promise<void>) | undefined;
|
|
65
|
+
const timeout = setTimeout(() => {
|
|
66
|
+
timedOut = true;
|
|
67
|
+
const reason = new DOMException('Timed out', 'TimeoutError');
|
|
68
|
+
controller.abort(reason);
|
|
69
|
+
void finalizeStream?.(reason);
|
|
70
|
+
}, config.timeoutMs);
|
|
71
|
+
const abort = () => controller.abort(request.signal.reason);
|
|
72
|
+
request.signal.addEventListener('abort', abort, { once: true });
|
|
73
|
+
let release: (() => void) | undefined;
|
|
74
|
+
let upstream: Response;
|
|
75
|
+
try {
|
|
76
|
+
if (request.signal.aborted) controller.abort(request.signal.reason);
|
|
77
|
+
release = await acquireVoicePermit(config, controller.signal);
|
|
78
|
+
upstream = await fetch(`${config.baseUrl}/audio/speech`, {
|
|
79
|
+
method: 'POST',
|
|
80
|
+
headers: {
|
|
81
|
+
authorization: `Bearer ${config.apiKey}`,
|
|
82
|
+
'content-type': 'application/json',
|
|
83
|
+
},
|
|
84
|
+
body: JSON.stringify({
|
|
85
|
+
model: config.speechModel,
|
|
86
|
+
input: input.text,
|
|
87
|
+
voice: input.voice,
|
|
88
|
+
response_format: input.format,
|
|
89
|
+
speed: input.speed,
|
|
90
|
+
}),
|
|
91
|
+
signal: controller.signal,
|
|
92
|
+
});
|
|
93
|
+
if (!upstream.ok || !upstream.body) {
|
|
94
|
+
await upstream.body?.cancel().catch(() => undefined);
|
|
95
|
+
if (upstream.status === 429) {
|
|
96
|
+
throw new VoiceServerError(VoiceErrorCodes.BUSY, 'Voice upstream is rate limited.', 429);
|
|
97
|
+
}
|
|
98
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream failed.', 502);
|
|
99
|
+
}
|
|
100
|
+
} catch (error) {
|
|
101
|
+
release?.();
|
|
102
|
+
clearTimeout(timeout);
|
|
103
|
+
request.signal.removeEventListener('abort', abort);
|
|
104
|
+
if (error instanceof VoiceServerError) throw error;
|
|
105
|
+
if (timedOut) throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice upstream timed out.', 504);
|
|
106
|
+
if (request.signal.aborted) {
|
|
107
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499);
|
|
108
|
+
}
|
|
109
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream unavailable.', 502);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const explicitType = upstream.headers.get('content-type');
|
|
113
|
+
if (explicitType && !explicitType.toLowerCase().startsWith('audio/')) {
|
|
114
|
+
await upstream.body.cancel().catch(() => undefined);
|
|
115
|
+
release?.();
|
|
116
|
+
clearTimeout(timeout);
|
|
117
|
+
request.signal.removeEventListener('abort', abort);
|
|
118
|
+
throw new VoiceServerError(
|
|
119
|
+
VoiceErrorCodes.UPSTREAM,
|
|
120
|
+
'Voice upstream returned a non-audio response.',
|
|
121
|
+
502,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
const reader = upstream.body.getReader();
|
|
125
|
+
let total = 0;
|
|
126
|
+
let finalized = false;
|
|
127
|
+
const finalize = async (reason?: unknown) => {
|
|
128
|
+
if (finalized) return;
|
|
129
|
+
finalized = true;
|
|
130
|
+
if (!controller.signal.aborted) controller.abort(reason);
|
|
131
|
+
await reader.cancel(reason).catch(() => undefined);
|
|
132
|
+
clearTimeout(timeout);
|
|
133
|
+
request.signal.removeEventListener('abort', abort);
|
|
134
|
+
release?.();
|
|
135
|
+
};
|
|
136
|
+
finalizeStream = finalize;
|
|
137
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
138
|
+
async pull(output) {
|
|
139
|
+
try {
|
|
140
|
+
const result = await reader.read();
|
|
141
|
+
if (timedOut) {
|
|
142
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice upstream timed out.', 504);
|
|
143
|
+
}
|
|
144
|
+
if (request.signal.aborted) {
|
|
145
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499);
|
|
146
|
+
}
|
|
147
|
+
if (result.done) {
|
|
148
|
+
output.close();
|
|
149
|
+
await finalize();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
total += result.value.byteLength;
|
|
153
|
+
if (total > config.maxResponseBytes) {
|
|
154
|
+
throw new VoiceServerError(
|
|
155
|
+
VoiceErrorCodes.UPSTREAM,
|
|
156
|
+
'Voice upstream response is too large.',
|
|
157
|
+
502,
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
output.enqueue(result.value);
|
|
161
|
+
} catch (error) {
|
|
162
|
+
await finalize(error);
|
|
163
|
+
output.error(error);
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
cancel: finalize,
|
|
167
|
+
});
|
|
168
|
+
const mimeType = explicitType ?? MIME_BY_FORMAT[input.format] ?? 'application/octet-stream';
|
|
169
|
+
return new Response(stream, {
|
|
170
|
+
headers: {
|
|
171
|
+
'content-type': mimeType,
|
|
172
|
+
'cache-control': 'no-store',
|
|
173
|
+
'x-content-type-options': 'nosniff',
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
3
|
+
|
|
4
|
+
export interface VoiceStreamWord {
|
|
5
|
+
text: string;
|
|
6
|
+
startMs?: number;
|
|
7
|
+
endMs?: number;
|
|
8
|
+
speaker?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface VoiceStreamTranscriptEvent {
|
|
12
|
+
type: 'partial' | 'final';
|
|
13
|
+
text: string;
|
|
14
|
+
startMs?: number;
|
|
15
|
+
endMs?: number;
|
|
16
|
+
speaker?: string;
|
|
17
|
+
words?: VoiceStreamWord[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface VoiceStreamingProviderSession {
|
|
21
|
+
write(chunk: Uint8Array): Promise<void>;
|
|
22
|
+
finish(): Promise<void>;
|
|
23
|
+
close(reason?: unknown): Promise<void> | void;
|
|
24
|
+
events: AsyncIterable<VoiceStreamTranscriptEvent>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface BoundedVoiceStreamSession {
|
|
28
|
+
write(chunk: Uint8Array): Promise<void>;
|
|
29
|
+
finish(): Promise<void>;
|
|
30
|
+
close(reason?: unknown): Promise<void>;
|
|
31
|
+
events: AsyncIterable<VoiceStreamTranscriptEvent>;
|
|
32
|
+
getBytesReceived(): number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function validateTranscriptEvent(value: unknown): VoiceStreamTranscriptEvent {
|
|
36
|
+
if (!value || typeof value !== 'object') {
|
|
37
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Invalid streaming transcript event.', 502);
|
|
38
|
+
}
|
|
39
|
+
const event = value as Record<string, unknown>;
|
|
40
|
+
if (!['partial', 'final'].includes(String(event.type)) || typeof event.text !== 'string') {
|
|
41
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Invalid streaming transcript event.', 502);
|
|
42
|
+
}
|
|
43
|
+
const words = Array.isArray(event.words)
|
|
44
|
+
? event.words.map((word) => {
|
|
45
|
+
if (!word || typeof word !== 'object' || typeof (word as { text?: unknown }).text !== 'string') {
|
|
46
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Invalid streaming transcript word.', 502);
|
|
47
|
+
}
|
|
48
|
+
const source = word as Record<string, unknown>;
|
|
49
|
+
return {
|
|
50
|
+
text: source.text as string,
|
|
51
|
+
...(typeof source.startMs === 'number' ? { startMs: source.startMs } : {}),
|
|
52
|
+
...(typeof source.endMs === 'number' ? { endMs: source.endMs } : {}),
|
|
53
|
+
...(typeof source.speaker === 'string' ? { speaker: source.speaker } : {}),
|
|
54
|
+
};
|
|
55
|
+
})
|
|
56
|
+
: undefined;
|
|
57
|
+
return {
|
|
58
|
+
type: event.type as 'partial' | 'final',
|
|
59
|
+
text: event.text,
|
|
60
|
+
...(typeof event.startMs === 'number' ? { startMs: event.startMs } : {}),
|
|
61
|
+
...(typeof event.endMs === 'number' ? { endMs: event.endMs } : {}),
|
|
62
|
+
...(typeof event.speaker === 'string' ? { speaker: event.speaker } : {}),
|
|
63
|
+
...(words ? { words } : {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function createBoundedVoiceStreamSession(
|
|
68
|
+
provider: VoiceStreamingProviderSession,
|
|
69
|
+
options: { maxAudioBytes: number; signal?: AbortSignal },
|
|
70
|
+
): BoundedVoiceStreamSession {
|
|
71
|
+
if (!Number.isSafeInteger(options.maxAudioBytes) || options.maxAudioBytes < 1) {
|
|
72
|
+
throw new TypeError('maxAudioBytes must be a positive safe integer.');
|
|
73
|
+
}
|
|
74
|
+
let bytes = 0;
|
|
75
|
+
let closed = false;
|
|
76
|
+
let closePromise: Promise<void> | undefined;
|
|
77
|
+
let abort = () => undefined;
|
|
78
|
+
const close = (reason?: unknown): Promise<void> => {
|
|
79
|
+
if (closePromise) return closePromise;
|
|
80
|
+
closed = true;
|
|
81
|
+
options.signal?.removeEventListener('abort', abort);
|
|
82
|
+
closePromise = Promise.resolve(provider.close(reason));
|
|
83
|
+
return closePromise;
|
|
84
|
+
};
|
|
85
|
+
abort = () => { void close(options.signal?.reason); };
|
|
86
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
87
|
+
|
|
88
|
+
const assertOpen = () => {
|
|
89
|
+
if (closed) throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Streaming session is closed.');
|
|
90
|
+
if (options.signal?.aborted) {
|
|
91
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Streaming session was aborted.', 499);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
return {
|
|
95
|
+
async write(chunk) {
|
|
96
|
+
assertOpen();
|
|
97
|
+
bytes += chunk.byteLength;
|
|
98
|
+
if (bytes > options.maxAudioBytes) {
|
|
99
|
+
await close('limit exceeded');
|
|
100
|
+
throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Streaming audio is too large.', 413);
|
|
101
|
+
}
|
|
102
|
+
await provider.write(chunk);
|
|
103
|
+
},
|
|
104
|
+
async finish() {
|
|
105
|
+
assertOpen();
|
|
106
|
+
await provider.finish();
|
|
107
|
+
},
|
|
108
|
+
close,
|
|
109
|
+
events: {
|
|
110
|
+
async *[Symbol.asyncIterator]() {
|
|
111
|
+
for await (const event of provider.events) yield validateTranscriptEvent(event);
|
|
112
|
+
},
|
|
113
|
+
},
|
|
114
|
+
getBytesReceived: () => bytes,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function transcriptEventsToSse(
|
|
119
|
+
events: AsyncIterable<VoiceStreamTranscriptEvent>,
|
|
120
|
+
options: { signal?: AbortSignal } = {},
|
|
121
|
+
): ReadableStream<Uint8Array> {
|
|
122
|
+
const encoder = new TextEncoder();
|
|
123
|
+
const iterator = events[Symbol.asyncIterator]();
|
|
124
|
+
return new ReadableStream<Uint8Array>({
|
|
125
|
+
async pull(controller) {
|
|
126
|
+
if (options.signal?.aborted) {
|
|
127
|
+
await iterator.return?.();
|
|
128
|
+
controller.close();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const next = iterator.next();
|
|
133
|
+
const result = options.signal
|
|
134
|
+
? await new Promise<IteratorResult<VoiceStreamTranscriptEvent>>((resolve, reject) => {
|
|
135
|
+
const abort = () => reject(
|
|
136
|
+
options.signal?.reason ?? new DOMException('Aborted', 'AbortError'),
|
|
137
|
+
);
|
|
138
|
+
options.signal!.addEventListener('abort', abort, { once: true });
|
|
139
|
+
next.then(resolve, reject).finally(() => {
|
|
140
|
+
options.signal?.removeEventListener('abort', abort);
|
|
141
|
+
});
|
|
142
|
+
})
|
|
143
|
+
: await next;
|
|
144
|
+
if (result.done) {
|
|
145
|
+
controller.close();
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const event = validateTranscriptEvent(result.value);
|
|
149
|
+
controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`));
|
|
150
|
+
} catch (error) {
|
|
151
|
+
await iterator.return?.();
|
|
152
|
+
if (options.signal?.aborted) controller.close();
|
|
153
|
+
else controller.error(error);
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
async cancel(reason) {
|
|
157
|
+
await iterator.return?.(reason);
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
3
|
+
|
|
4
|
+
export function validateContentLength(value: string | null, maxBytes: number): number | undefined {
|
|
5
|
+
if (!value) return undefined;
|
|
6
|
+
if (!/^\d+$/.test(value)) {
|
|
7
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Invalid Content-Length.');
|
|
8
|
+
}
|
|
9
|
+
const length = Number(value);
|
|
10
|
+
if (!Number.isSafeInteger(length)) {
|
|
11
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Invalid Content-Length.');
|
|
12
|
+
}
|
|
13
|
+
if (length > maxBytes) {
|
|
14
|
+
throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Request body is too large.', 413);
|
|
15
|
+
}
|
|
16
|
+
return length;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function readBoundedStream(
|
|
20
|
+
stream: ReadableStream<Uint8Array> | null,
|
|
21
|
+
options: {
|
|
22
|
+
maxBytes: number;
|
|
23
|
+
contentLength?: string | null;
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
},
|
|
27
|
+
): Promise<Uint8Array> {
|
|
28
|
+
if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) {
|
|
29
|
+
throw new TypeError('maxBytes must be a non-negative safe integer.');
|
|
30
|
+
}
|
|
31
|
+
validateContentLength(options.contentLength ?? null, options.maxBytes);
|
|
32
|
+
if (options.signal?.aborted) {
|
|
33
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read was aborted.', 499);
|
|
34
|
+
}
|
|
35
|
+
if (!stream) return new Uint8Array();
|
|
36
|
+
|
|
37
|
+
const reader = stream.getReader();
|
|
38
|
+
const chunks: Uint8Array[] = [];
|
|
39
|
+
let total = 0;
|
|
40
|
+
let timedOut = false;
|
|
41
|
+
const timeout = options.timeoutMs === undefined
|
|
42
|
+
? undefined
|
|
43
|
+
: setTimeout(() => {
|
|
44
|
+
timedOut = true;
|
|
45
|
+
void reader.cancel('timeout');
|
|
46
|
+
}, options.timeoutMs);
|
|
47
|
+
const abort = () => { void reader.cancel(options.signal?.reason); };
|
|
48
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
while (true) {
|
|
52
|
+
if (options.signal?.aborted) {
|
|
53
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read was aborted.', 499);
|
|
54
|
+
}
|
|
55
|
+
if (timedOut) {
|
|
56
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read timed out.', 408);
|
|
57
|
+
}
|
|
58
|
+
const { done, value } = await reader.read();
|
|
59
|
+
if (timedOut) {
|
|
60
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read timed out.', 408);
|
|
61
|
+
}
|
|
62
|
+
if (options.signal?.aborted) {
|
|
63
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read was aborted.', 499);
|
|
64
|
+
}
|
|
65
|
+
if (done) break;
|
|
66
|
+
total += value.byteLength;
|
|
67
|
+
if (total > options.maxBytes) {
|
|
68
|
+
await reader.cancel('limit exceeded').catch(() => undefined);
|
|
69
|
+
throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Request body is too large.', 413);
|
|
70
|
+
}
|
|
71
|
+
chunks.push(value);
|
|
72
|
+
}
|
|
73
|
+
} catch (error) {
|
|
74
|
+
await reader.cancel(error).catch(() => undefined);
|
|
75
|
+
if (error instanceof VoiceServerError) throw error;
|
|
76
|
+
if (timedOut) throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read timed out.', 408);
|
|
77
|
+
if (options.signal?.aborted) {
|
|
78
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Request body read was aborted.', 499);
|
|
79
|
+
}
|
|
80
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Unable to read request body.');
|
|
81
|
+
} finally {
|
|
82
|
+
if (timeout) clearTimeout(timeout);
|
|
83
|
+
options.signal?.removeEventListener('abort', abort);
|
|
84
|
+
reader.releaseLock();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const result = new Uint8Array(total);
|
|
88
|
+
let offset = 0;
|
|
89
|
+
for (const chunk of chunks) {
|
|
90
|
+
result.set(chunk, offset);
|
|
91
|
+
offset += chunk.byteLength;
|
|
92
|
+
}
|
|
93
|
+
return result;
|
|
94
|
+
}
|