@adea-ai/voice 0.0.0-stage → 0.4.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.
Files changed (60) hide show
  1. package/README.md +136 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +117 -0
  4. package/dist/contract/contract.d.ts +157 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +10 -0
  7. package/dist/contract/index.js +64 -0
  8. package/dist/contract/session.d.ts +71 -0
  9. package/dist/contract/turns.d.ts +91 -0
  10. package/dist/contract/wire.d.ts +279 -0
  11. package/dist/desktop/conversation.d.ts +86 -0
  12. package/dist/desktop/desktop-voice.d.ts +212 -0
  13. package/dist/desktop/helper-lock.d.ts +121 -0
  14. package/dist/desktop/helper-process.d.ts +96 -0
  15. package/dist/desktop/index.d.ts +9 -0
  16. package/dist/desktop/index.js +1454 -0
  17. package/dist/desktop/macho-digest.d.ts +9 -0
  18. package/dist/index-7n7epq1a.js +47 -0
  19. package/dist/index-a7d617zr.js +295 -0
  20. package/dist/index-ght8wwpd.js +156 -0
  21. package/dist/index-m4g2tpeq.js +522 -0
  22. package/dist/index-r4hz8gk0.js +10 -0
  23. package/dist/index-tvz9s9nz.js +77 -0
  24. package/dist/index.d.ts +7 -0
  25. package/dist/index.js +96 -0
  26. package/dist/settings/index.d.ts +5 -0
  27. package/dist/settings/index.js +34 -0
  28. package/dist/settings/settings.d.ts +163 -0
  29. package/dist/web/index.d.ts +16 -0
  30. package/dist/web/index.js +1697 -0
  31. package/dist/web/stt/speech-recognition.d.ts +226 -0
  32. package/dist/web/tts/locale-match.d.ts +40 -0
  33. package/dist/web/tts/phonon.d.ts +139 -0
  34. package/dist/web/tts/player.d.ts +115 -0
  35. package/dist/web/tts/system-voices.d.ts +162 -0
  36. package/dist/web/turns.d.ts +91 -0
  37. package/package.json +68 -4
  38. package/src/cli/helpers-cli.ts +135 -0
  39. package/src/contract/contract.ts +393 -0
  40. package/src/contract/errors.ts +98 -0
  41. package/src/contract/index.ts +10 -0
  42. package/src/contract/session.ts +77 -0
  43. package/src/contract/turns.ts +48 -0
  44. package/src/contract/wire.ts +384 -0
  45. package/src/desktop/conversation.ts +347 -0
  46. package/src/desktop/desktop-voice.ts +1129 -0
  47. package/src/desktop/helper-lock.ts +550 -0
  48. package/src/desktop/helper-process.ts +408 -0
  49. package/src/desktop/index.ts +18 -0
  50. package/src/desktop/macho-digest.ts +135 -0
  51. package/src/index.ts +7 -0
  52. package/src/settings/index.ts +5 -0
  53. package/src/settings/settings.ts +478 -0
  54. package/src/web/index.ts +16 -0
  55. package/src/web/stt/speech-recognition.ts +1013 -0
  56. package/src/web/tts/locale-match.ts +131 -0
  57. package/src/web/tts/phonon.ts +386 -0
  58. package/src/web/tts/player.ts +271 -0
  59. package/src/web/tts/system-voices.ts +510 -0
  60. package/src/web/turns.ts +235 -0
@@ -0,0 +1,510 @@
1
+ /**
2
+ * Platform voices as the browser's fallback for languages Phonon cannot ship (issue #36).
3
+ *
4
+ * `speechSynthesis` is not uniformly offline: the voices a browser exposes can be local
5
+ * (`localService === true`) or remote, and the two are indistinguishable to a person unless the
6
+ * app says so. This provider is therefore **local-voice only** by default: a locale with no local
7
+ * voice reports `networkRequired`, not "available", and a remote voice is only used when the host
8
+ * passes `allowNetwork: true` after a privacy notice.
9
+ *
10
+ * Phonon stays the English default; this provider answers for ES-419 and for English devices where
11
+ * the person declines the model download.
12
+ */
13
+ import {
14
+ VOICE_CONTRACT,
15
+ availableWithMatch,
16
+ unavailable,
17
+ type VoiceLocaleMatch,
18
+ type VoiceProvider,
19
+ type VoiceProviderAvailability,
20
+ type VoiceProviderDescriptor,
21
+ } from "../../contract/contract";
22
+ import { VoiceError } from "../../contract/errors";
23
+ import { matchLocale } from "./locale-match";
24
+
25
+ export interface SynthesisVoiceLike {
26
+ readonly name: string;
27
+ readonly lang: string;
28
+ readonly localService?: boolean;
29
+ readonly default?: boolean;
30
+ readonly voiceURI?: string;
31
+ }
32
+
33
+ export interface SynthesisUtteranceLike {
34
+ text: string;
35
+ lang: string;
36
+ voice: SynthesisVoiceLike | null;
37
+ rate: number;
38
+ pitch: number;
39
+ volume: number;
40
+ onstart: (() => void) | null;
41
+ onend: (() => void) | null;
42
+ onerror: ((event: { error: string }) => void) | null;
43
+ }
44
+
45
+ export interface SpeechSynthesisLike {
46
+ getVoices(): SynthesisVoiceLike[];
47
+ speak(utterance: SynthesisUtteranceLike): void;
48
+ cancel(): void;
49
+ pause?(): void;
50
+ resume?(): void;
51
+ readonly speaking?: boolean;
52
+ readonly pending?: boolean;
53
+ /** `voiceschanged` fires when the browser finished loading its voice list (Chrome loads late). */
54
+ addEventListener?(type: "voiceschanged", listener: () => void): void;
55
+ removeEventListener?(type: "voiceschanged", listener: () => void): void;
56
+ }
57
+
58
+ /** A timer handle; only passed back to `clearTimeout`. */
59
+ export type TimerHandle = unknown;
60
+
61
+ export interface SystemVoicesEnvironment {
62
+ readonly speechSynthesis?: SpeechSynthesisLike;
63
+ readonly Utterance?: new (text: string) => SynthesisUtteranceLike;
64
+ /** The browser's own constructor name; used when `Utterance` is not injected. */
65
+ readonly SpeechSynthesisUtterance?: new (text: string) => SynthesisUtteranceLike;
66
+ readonly now?: () => number;
67
+ /** Timers for the voice-list wait and the speech watchdog. Default: the global timers. */
68
+ readonly setTimeout?: (callback: () => void, milliseconds: number) => TimerHandle;
69
+ readonly clearTimeout?: (handle: TimerHandle) => void;
70
+ /** How long the first probe waits for `voiceschanged` when the list is empty. Default 1500 ms. */
71
+ readonly voicesTimeoutMs?: number;
72
+ }
73
+
74
+ export interface SpeakWithPlatformVoiceOptions {
75
+ /** A BCP-47 tag. Selects a local voice of this language and sets the utterance language. */
76
+ readonly locale?: string;
77
+ /** An exact voice name; wins over `locale` when both are given. */
78
+ readonly voiceName?: string;
79
+ readonly rate?: number;
80
+ readonly pitch?: number;
81
+ readonly volume?: number;
82
+ /** Whether the host has consent for a remote voice. Default false. */
83
+ readonly allowNetwork?: boolean;
84
+ /** Called when the audio starts, with the voice that speaks (also on `handle.voice`). */
85
+ readonly onStart?: (voice: ChosenVoice | undefined) => void;
86
+ readonly onEnd?: () => void;
87
+ /**
88
+ * Reject with `failed` if the browser never reports an end (Chrome can drop `end` events).
89
+ * Default: 15 s plus 200 ms per character, scaled by `rate`.
90
+ */
91
+ readonly timeoutMs?: number;
92
+ }
93
+
94
+ /**
95
+ * How a voice was chosen:
96
+ * - `exact` / `region` / `language`: matched against `locale` (see `VoiceLocaleMatch`);
97
+ * - `named`: the host named it with `voiceName` and gave no locale to compare with;
98
+ * - `default`: no locale and no name, so the browser's default local voice.
99
+ */
100
+ export type VoiceSelectionMatch = VoiceLocaleMatch | "named" | "default";
101
+
102
+ /** The voice a request speaks with, for a host to show ("Paulina, Spanish (Mexico), on device"). */
103
+ export interface ChosenVoice {
104
+ readonly name: string;
105
+ readonly voiceURI?: string;
106
+ readonly lang: string;
107
+ /** Whether the voice runs on the device. A remote voice is only chosen with `allowNetwork`. */
108
+ readonly localService: boolean;
109
+ readonly match: VoiceSelectionMatch;
110
+ /**
111
+ * True when the requested locale names a region and the only usable voice is from another region
112
+ * of the language (`es-ES` for `es-419`). The host should say so rather than imply a match.
113
+ */
114
+ readonly offRegion: boolean;
115
+ }
116
+
117
+ export interface PlatformSpeechHandle {
118
+ readonly done: Promise<void>;
119
+ /** The voice that speaks this request; undefined when the request was refused before speaking. */
120
+ readonly voice?: ChosenVoice;
121
+ cancel(): void;
122
+ }
123
+
124
+ export const SYSTEM_VOICES_ID = "web.system-voices";
125
+
126
+ const DEFAULT_VOICES_TIMEOUT_MS = 1_500;
127
+
128
+ /** One `speak()` call's state. Every handle settles its own promise; nothing is shared. */
129
+ interface Request {
130
+ readonly build: () => SynthesisUtteranceLike;
131
+ readonly options: SpeakWithPlatformVoiceOptions;
132
+ readonly voice: ChosenVoice | undefined;
133
+ utterance: SynthesisUtteranceLike;
134
+ started: boolean;
135
+ settled: boolean;
136
+ /** Cancelled while queued behind another request's audio: drop it the moment it starts. */
137
+ zombie: boolean;
138
+ watchdog: TimerHandle | undefined;
139
+ resolve: () => void;
140
+ reject: (error: unknown) => void;
141
+ }
142
+
143
+ export class SystemVoiceProvider implements VoiceProvider {
144
+ readonly descriptor: VoiceProviderDescriptor;
145
+ private readonly environment: SystemVoicesEnvironment;
146
+ /** Requests in browser queue order that have not settled. */
147
+ private inFlight: Request[] = [];
148
+ private voicesReady: Promise<void> | undefined;
149
+
150
+ constructor(environment: SystemVoicesEnvironment = globalThis as never) {
151
+ this.environment = environment;
152
+ this.descriptor = {
153
+ id: SYSTEM_VOICES_ID,
154
+ displayName: "Platform voices",
155
+ kind: "textToSpeech",
156
+ platforms: ["web"],
157
+ execution: "systemProvided",
158
+ contract: VOICE_CONTRACT,
159
+ requiresModelDownload: false,
160
+ modelFamilies: ["browser.speechSynthesis"],
161
+ licenses: [{ spdxIdentifier: "Browser-System-Voices", commercialUse: true }],
162
+ capabilities: { trueCancellation: true, voiceSelection: true, wordBoundaryPause: true, localeSelection: true },
163
+ };
164
+ }
165
+
166
+ private get Utterance(): (new (text: string) => SynthesisUtteranceLike) | undefined {
167
+ return this.environment.Utterance ?? this.environment.SpeechSynthesisUtterance;
168
+ }
169
+
170
+ /**
171
+ * Voices the browser exposes for a locale's language, split by where they run, each list in
172
+ * preference order: exact tag, then the requested region group (for `es-419`: es-MX, es-US,
173
+ * es-AR, other Latin-American regions), then the rest of the language (`es-ES` last).
174
+ */
175
+ voices(locale: string): { local: SynthesisVoiceLike[]; remote: SynthesisVoiceLike[] } {
176
+ const ranked = this.rankVoices(locale);
177
+ return {
178
+ local: ranked.filter((entry) => entry.voice.localService === true).map((entry) => entry.voice),
179
+ remote: ranked.filter((entry) => entry.voice.localService !== true).map((entry) => entry.voice),
180
+ };
181
+ }
182
+
183
+ /** Every voice of the locale's language with its match quality, best first. */
184
+ rankVoices(locale: string): Array<{ voice: SynthesisVoiceLike; match: VoiceLocaleMatch }> {
185
+ const synthesis = this.environment.speechSynthesis;
186
+ if (synthesis === undefined) return [];
187
+ return rank(synthesis.getVoices(), locale).map(({ voice, match }) => ({ voice, match: match.match }));
188
+ }
189
+
190
+ /**
191
+ * The voice `speak()` would use for these options, without speaking: lets a host show the voice
192
+ * (and an off-region warning) before the first utterance. A `VoiceError` when it would refuse.
193
+ */
194
+ chooseVoice(options: SpeakWithPlatformVoiceOptions = {}): ChosenVoice | undefined | VoiceError {
195
+ const synthesis = this.environment.speechSynthesis;
196
+ if (synthesis === undefined) return new VoiceError("unavailable");
197
+ const selection = this.selectVoice(synthesis.getVoices(), options);
198
+ return selection === undefined || selection instanceof VoiceError ? selection : describe(selection);
199
+ }
200
+
201
+ /**
202
+ * Resolves once the browser has a voice list, or after `voicesTimeoutMs`. Chrome returns an empty
203
+ * list until `voiceschanged`, which would otherwise read as "no voice installed".
204
+ */
205
+ waitForVoices(): Promise<void> {
206
+ const synthesis = this.environment.speechSynthesis;
207
+ if (synthesis === undefined || synthesis.getVoices().length > 0) return Promise.resolve();
208
+ if (this.voicesReady) return this.voicesReady;
209
+ this.voicesReady = new Promise<void>((resolve) => {
210
+ let timer: TimerHandle | undefined;
211
+ const finish = () => {
212
+ synthesis.removeEventListener?.("voiceschanged", finish);
213
+ if (timer !== undefined) this.clearTimer(timer);
214
+ resolve();
215
+ };
216
+ if (synthesis.addEventListener === undefined) {
217
+ resolve();
218
+ return;
219
+ }
220
+ synthesis.addEventListener("voiceschanged", finish);
221
+ timer = this.setTimer(finish, this.environment.voicesTimeoutMs ?? DEFAULT_VOICES_TIMEOUT_MS);
222
+ });
223
+ return this.voicesReady;
224
+ }
225
+
226
+ async availability(locale: string): Promise<VoiceProviderAvailability> {
227
+ if (this.environment.speechSynthesis === undefined || this.Utterance === undefined) {
228
+ return unavailable("unsupportedPlatform", "this browser has no speech synthesis", {
229
+ kind: "chooseAnotherProvider",
230
+ detail: "use a browser with platform voices",
231
+ });
232
+ }
233
+ await this.waitForVoices();
234
+ const ranked = this.rankVoices(locale);
235
+ const local = ranked.filter((entry) => entry.voice.localService === true);
236
+ const remote = ranked.filter((entry) => entry.voice.localService !== true);
237
+ const best = local[0];
238
+ if (best !== undefined) {
239
+ if (best.match === "language") {
240
+ // Region-level truth: `pt-PT` with only `pt-BR` installed is the language, not the locale.
241
+ return availableWithMatch(
242
+ "language",
243
+ `no local ${locale} voice; only ${best.voice.lang} (${best.voice.name}) of the language is installed`,
244
+ );
245
+ }
246
+ return availableWithMatch(best.match);
247
+ }
248
+ if (remote.length > 0) {
249
+ return unavailable("networkRequired", `only remote ${locale} voices are installed`, {
250
+ kind: "grantPermission",
251
+ detail: "use a network voice only with an explicit privacy choice",
252
+ });
253
+ }
254
+ return unavailable("unsupportedLocale", `no ${locale} voice is installed`, {
255
+ kind: "installModel",
256
+ detail: `install a ${locale} voice in the operating system`,
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Speaks with a platform voice. Local voices only unless `allowNetwork` is set. With `locale`,
262
+ * the voice is the best local voice of that language: exact tag, then the region group, then
263
+ * another region (flagged `offRegion` on `handle.voice`).
264
+ */
265
+ speak(text: string, options: SpeakWithPlatformVoiceOptions = {}): PlatformSpeechHandle {
266
+ const synthesis = this.environment.speechSynthesis;
267
+ const Utterance = this.Utterance;
268
+ if (synthesis === undefined || Utterance === undefined) {
269
+ return { done: Promise.reject(new VoiceError("unavailable")), cancel: () => {} };
270
+ }
271
+ if (text.trim().length === 0) {
272
+ return { done: Promise.reject(new VoiceError("bad_request", "cannot speak empty text")), cancel: () => {} };
273
+ }
274
+ const selection = this.selectVoice(synthesis.getVoices(), options);
275
+ if (selection instanceof VoiceError) {
276
+ return { done: Promise.reject(selection), cancel: () => {} };
277
+ }
278
+ const chosen = selection;
279
+ const voice = chosen?.voice;
280
+ const build = () => {
281
+ const utterance = new Utterance(text);
282
+ utterance.lang = voice?.lang ?? options.locale ?? "";
283
+ utterance.voice = voice ?? null;
284
+ utterance.rate = options.rate ?? 1;
285
+ utterance.pitch = options.pitch ?? 1;
286
+ utterance.volume = options.volume ?? 1;
287
+ return utterance;
288
+ };
289
+
290
+ const info = chosen === undefined ? undefined : describe(chosen);
291
+ let request!: Request;
292
+ const done = new Promise<void>((resolve, reject) => {
293
+ request = { build, options, voice: info, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
294
+ });
295
+ this.inFlight.push(request);
296
+ this.bind(request);
297
+ const timeout = options.timeoutMs ?? 15_000 + (text.length * 200) / Math.max(0.1, options.rate ?? 1);
298
+ request.watchdog = this.setTimer(() => {
299
+ this.abandon(request, new VoiceError("failed", "the platform voice never reported the end of the speech"));
300
+ }, timeout);
301
+ try {
302
+ synthesis.speak(request.utterance);
303
+ } catch (error) {
304
+ this.settle(request, VoiceError.wrapping(error));
305
+ }
306
+
307
+ return {
308
+ done,
309
+ ...(info === undefined ? {} : { voice: info }),
310
+ cancel: () => this.abandon(request, new VoiceError("cancelled")),
311
+ };
312
+ }
313
+
314
+ /** Whether a synthesis request is in flight. */
315
+ get isSpeaking(): boolean {
316
+ return this.environment.speechSynthesis?.speaking === true || this.environment.speechSynthesis?.pending === true;
317
+ }
318
+
319
+ private selectVoice(
320
+ available: SynthesisVoiceLike[],
321
+ options: SpeakWithPlatformVoiceOptions,
322
+ ): Selection | undefined | VoiceError {
323
+ const allowNetwork = options.allowNetwork === true;
324
+ if (options.voiceName) {
325
+ const requested = available.find((voice) => voice.name === options.voiceName);
326
+ if (requested !== undefined) {
327
+ if (requested.localService !== true && !allowNetwork) {
328
+ return new VoiceError("denied", "a remote voice needs explicit consent");
329
+ }
330
+ const match = options.locale ? matchLocale(options.locale, requested.lang)?.match ?? "language" : "named";
331
+ return { voice: requested, match, offRegion: options.locale ? isOffRegion(options.locale, match) : false };
332
+ }
333
+ }
334
+ if (options.locale) {
335
+ const ranked = rank(available, options.locale);
336
+ const local = ranked.find((entry) => entry.voice.localService === true);
337
+ const remote = ranked.find((entry) => entry.voice.localService !== true);
338
+ // Local first. With consent, a remote voice wins only on a strictly better match tier
339
+ // (an es-MX cloud voice over a local es-ES one); within a tier the local voice keeps it.
340
+ let pick = local;
341
+ if (allowNetwork && remote !== undefined && (pick === undefined || tier(remote.match.match) < tier(pick.match.match))) {
342
+ pick = remote;
343
+ }
344
+ if (pick === undefined) {
345
+ return new VoiceError("language_unsupported", `no local ${options.locale} voice is installed`);
346
+ }
347
+ return { voice: pick.voice, match: pick.match.match, offRegion: isOffRegion(options.locale, pick.match.match) };
348
+ }
349
+ const fallback =
350
+ available.find((voice) => voice.localService === true && voice.default === true) ??
351
+ available.find((voice) => voice.localService === true);
352
+ if (fallback === undefined && !allowNetwork) {
353
+ return new VoiceError("language_unsupported", "no local voice is installed");
354
+ }
355
+ return fallback === undefined ? undefined : { voice: fallback, match: "default", offRegion: false };
356
+ }
357
+
358
+ /** Wires one utterance object's events to its request. A rebuilt utterance is wired again. */
359
+ private bind(request: Request): void {
360
+ const utterance = request.utterance;
361
+ const options = request.options;
362
+ utterance.onstart = () => {
363
+ if (request.utterance !== utterance) return;
364
+ if (request.zombie) {
365
+ // It was cancelled while queued behind other audio: drop it now that it is the speaker.
366
+ this.purge();
367
+ return;
368
+ }
369
+ request.started = true;
370
+ options.onStart?.(request.voice);
371
+ };
372
+ utterance.onend = () => {
373
+ if (request.utterance !== utterance || request.settled) return;
374
+ if (!request.started) {
375
+ // Firefox reports a cancelled utterance with `end`, not `error: canceled`. An utterance that
376
+ // ends without ever starting was not heard, so it is a cancel, never a successful finish.
377
+ this.settle(request, new VoiceError("cancelled", "the platform voice was cancelled before it started"));
378
+ return;
379
+ }
380
+ options.onEnd?.();
381
+ this.settle(request);
382
+ };
383
+ utterance.onerror = (event) => {
384
+ if (request.utterance !== utterance || request.settled) return;
385
+ this.settle(request, mapSynthesisError(event.error));
386
+ };
387
+ }
388
+
389
+ /**
390
+ * Ends one request early (cancel or watchdog) without touching the others' promises. The browser
391
+ * can only cancel its whole queue, so the other unstarted requests are re-queued afterwards.
392
+ */
393
+ private abandon(request: Request, error: VoiceError): void {
394
+ if (request.settled) return;
395
+ const speakerIsOther = this.inFlight.some((other) => other !== request && other.started);
396
+ this.settle(request, error);
397
+ if (!request.started && speakerIsOther) {
398
+ // Another request is audible right now; cancelling would cut it off. Drop this one when its
399
+ // turn comes instead.
400
+ request.zombie = true;
401
+ return;
402
+ }
403
+ this.purge();
404
+ }
405
+
406
+ /** Cancels the browser queue and re-queues every unsettled request that had not started. */
407
+ private purge(): void {
408
+ const synthesis = this.environment.speechSynthesis;
409
+ if (synthesis === undefined) return;
410
+ const survivors = this.inFlight.filter((request) => !request.settled && !request.started);
411
+ for (const request of this.inFlight) detach(request.utterance);
412
+ synthesis.cancel();
413
+ for (const request of survivors) {
414
+ // A fresh object: late events from the cancelled one can never be mistaken for this run.
415
+ request.utterance = request.build();
416
+ this.bind(request);
417
+ try {
418
+ synthesis.speak(request.utterance);
419
+ } catch (error) {
420
+ this.settle(request, VoiceError.wrapping(error));
421
+ }
422
+ }
423
+ }
424
+
425
+ private settle(request: Request, error?: VoiceError): void {
426
+ if (request.settled) return;
427
+ request.settled = true;
428
+ if (request.watchdog !== undefined) this.clearTimer(request.watchdog);
429
+ request.watchdog = undefined;
430
+ this.inFlight = this.inFlight.filter((candidate) => candidate !== request);
431
+ if (error) request.reject(error);
432
+ else request.resolve();
433
+ }
434
+
435
+ private setTimer(callback: () => void, milliseconds: number): TimerHandle {
436
+ if (this.environment.setTimeout) return this.environment.setTimeout(callback, milliseconds);
437
+ const handle = setTimeout(callback, milliseconds) as unknown as { unref?: () => void };
438
+ handle.unref?.();
439
+ return handle;
440
+ }
441
+
442
+ private clearTimer(handle: TimerHandle): void {
443
+ if (this.environment.clearTimeout) this.environment.clearTimeout(handle);
444
+ else clearTimeout(handle as ReturnType<typeof setTimeout>);
445
+ }
446
+ }
447
+
448
+ function detach(utterance: SynthesisUtteranceLike): void {
449
+ utterance.onstart = null;
450
+ utterance.onend = null;
451
+ utterance.onerror = null;
452
+ }
453
+
454
+ interface Selection {
455
+ readonly voice: SynthesisVoiceLike;
456
+ readonly match: VoiceSelectionMatch;
457
+ readonly offRegion: boolean;
458
+ }
459
+
460
+ /**
461
+ * Voices of the locale's language, best first: match rank, then the browser's default flag, then
462
+ * the browser's own order (the sort is stable).
463
+ */
464
+ function rank(available: SynthesisVoiceLike[], locale: string) {
465
+ return available
466
+ .map((voice, index) => ({ voice, index, match: matchLocale(locale, voice.lang) }))
467
+ .filter((entry): entry is { voice: SynthesisVoiceLike; index: number; match: NonNullable<typeof entry.match> } => entry.match !== undefined)
468
+ .sort(
469
+ (a, b) =>
470
+ a.match.rank - b.match.rank ||
471
+ Number(b.voice.default === true) - Number(a.voice.default === true) ||
472
+ a.index - b.index,
473
+ );
474
+ }
475
+
476
+ function tier(match: VoiceLocaleMatch): number {
477
+ return match === "exact" ? 0 : match === "region" ? 1 : 2;
478
+ }
479
+
480
+ function isOffRegion(locale: string, match: VoiceSelectionMatch): boolean {
481
+ return match === "language" && /[-_]/.test(locale.trim());
482
+ }
483
+
484
+ function describe(selection: Selection): ChosenVoice {
485
+ const voice = selection.voice;
486
+ return {
487
+ name: voice.name,
488
+ ...(voice.voiceURI === undefined ? {} : { voiceURI: voice.voiceURI }),
489
+ lang: voice.lang,
490
+ localService: voice.localService === true,
491
+ match: selection.match,
492
+ offRegion: selection.offRegion,
493
+ };
494
+ }
495
+
496
+ function mapSynthesisError(error: string): VoiceError {
497
+ switch (error) {
498
+ case "interrupted":
499
+ case "canceled":
500
+ case "cancelled":
501
+ return new VoiceError("cancelled");
502
+ case "not-allowed":
503
+ return new VoiceError("denied");
504
+ case "language-unavailable":
505
+ case "voice-unavailable":
506
+ return new VoiceError("language_unsupported");
507
+ default:
508
+ return new VoiceError("failed", `platform synthesis error: ${error}`);
509
+ }
510
+ }