@adea-ai/voice 0.2.0 → 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 (45) hide show
  1. package/README.md +86 -1
  2. package/dist/cli/helpers-cli.js +17 -2
  3. package/dist/contract/contract.d.ts +21 -2
  4. package/dist/contract/index.d.ts +1 -0
  5. package/dist/contract/index.js +12 -2
  6. package/dist/contract/session.d.ts +13 -0
  7. package/dist/contract/turns.d.ts +91 -0
  8. package/dist/contract/wire.d.ts +92 -1
  9. package/dist/desktop/conversation.d.ts +86 -0
  10. package/dist/desktop/desktop-voice.d.ts +61 -1
  11. package/dist/desktop/helper-lock.d.ts +45 -7
  12. package/dist/desktop/helper-process.d.ts +4 -0
  13. package/dist/desktop/index.d.ts +2 -0
  14. package/dist/desktop/index.js +427 -15
  15. package/dist/desktop/macho-digest.d.ts +9 -0
  16. package/dist/{index-rehs788p.js → index-7n7epq1a.js} +7 -2
  17. package/dist/{index-s270cw30.js → index-a7d617zr.js} +1 -1
  18. package/dist/{index-9kerqn9r.js → index-ght8wwpd.js} +9 -3
  19. package/dist/{index-acm1yvvv.js → index-m4g2tpeq.js} +258 -26
  20. package/dist/index.js +13 -3
  21. package/dist/settings/index.js +1 -1
  22. package/dist/web/index.d.ts +1 -0
  23. package/dist/web/index.js +459 -49
  24. package/dist/web/stt/speech-recognition.d.ts +128 -7
  25. package/dist/web/tts/locale-match.d.ts +40 -0
  26. package/dist/web/tts/system-voices.d.ts +44 -4
  27. package/dist/web/turns.d.ts +15 -25
  28. package/package.json +1 -1
  29. package/src/cli/helpers-cli.ts +18 -2
  30. package/src/contract/contract.ts +32 -4
  31. package/src/contract/index.ts +1 -0
  32. package/src/contract/session.ts +14 -2
  33. package/src/contract/turns.ts +48 -0
  34. package/src/contract/wire.ts +123 -2
  35. package/src/desktop/conversation.ts +347 -0
  36. package/src/desktop/desktop-voice.ts +197 -1
  37. package/src/desktop/helper-lock.ts +195 -20
  38. package/src/desktop/helper-process.ts +17 -10
  39. package/src/desktop/index.ts +2 -0
  40. package/src/desktop/macho-digest.ts +135 -0
  41. package/src/web/index.ts +1 -0
  42. package/src/web/stt/speech-recognition.ts +454 -24
  43. package/src/web/tts/locale-match.ts +131 -0
  44. package/src/web/tts/system-voices.ts +144 -35
  45. package/src/web/turns.ts +22 -11
package/dist/web/index.js CHANGED
@@ -4,9 +4,10 @@ import {
4
4
  import {
5
5
  VOICE_CONTRACT2,
6
6
  AVAILABLE2,
7
+ availableWithMatch2,
7
8
  unavailable2,
8
9
  isAvailable2
9
- } from "../index-9kerqn9r.js";
10
+ } from "../index-ght8wwpd.js";
10
11
  import {
11
12
  VoiceError2
12
13
  } from "../index-tvz9s9nz.js";
@@ -86,13 +87,63 @@ class BrowserRecognitionProvider {
86
87
  if (options?.allowDownload !== true) {
87
88
  throw new VoiceError2("denied", "installing a recognition model needs the person's explicit download consent");
88
89
  }
89
- const install = recognitionConstructor(this.environment)?.install;
90
- if (install === undefined) {
90
+ if (options.settings?.privacy.offlineOnly === true) {
91
+ throw new VoiceError2("denied", "offline-only mode forbids downloading a recognition model");
92
+ }
93
+ const constructor = recognitionConstructor(this.environment);
94
+ const install = constructor?.install;
95
+ if (constructor === undefined || install === undefined) {
91
96
  throw new VoiceError2("assets_missing", "this browser has no on-device recognition install path");
92
97
  }
93
- return install({ langs: [locale] });
98
+ const signal = options.signal;
99
+ if (signal?.aborted)
100
+ throw new VoiceError2("cancelled", "the model install was cancelled before it started");
101
+ const report = (phase) => {
102
+ try {
103
+ options.onProgress?.({ locale, phase });
104
+ } catch {}
105
+ };
106
+ report("started");
107
+ let settled = false;
108
+ let onAbort;
109
+ const aborted = new Promise((_, reject) => {
110
+ onAbort = () => reject(new VoiceError2("cancelled", "the model install was cancelled; the browser may finish it in the background"));
111
+ signal?.addEventListener("abort", onAbort, { once: true });
112
+ });
113
+ this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
114
+ try {
115
+ const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
116
+ report(installed ? "installed" : "failed");
117
+ return installed;
118
+ } catch (error) {
119
+ const wrapped = VoiceError2.wrapping(error);
120
+ report(wrapped.code === "cancelled" ? "cancelled" : "failed");
121
+ throw error instanceof VoiceError2 ? error : wrapped;
122
+ } finally {
123
+ settled = true;
124
+ if (onAbort)
125
+ signal?.removeEventListener("abort", onAbort);
126
+ }
127
+ }
128
+ async pollInstall(constructor, locale, intervalMs, done, downloading) {
129
+ if (constructor.available === undefined)
130
+ return;
131
+ const sleep = this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
132
+ while (!done()) {
133
+ const state = await probeOnDevice(constructor, locale);
134
+ if (done())
135
+ return;
136
+ if (state === "downloading") {
137
+ downloading();
138
+ return;
139
+ }
140
+ await sleep(intervalMs);
141
+ }
94
142
  }
95
143
  async createSession(options) {
144
+ if (this.mode === "service" && options.settings?.privacy.offlineOnly === true) {
145
+ throw new VoiceError2("denied", "offline-only mode forbids the browser's network recognition service");
146
+ }
96
147
  const availability = await this.availability(options.locale);
97
148
  if (!isAvailable2(availability)) {
98
149
  const reason = availability.unavailable;
@@ -101,6 +152,14 @@ class BrowserRecognitionProvider {
101
152
  if (this.mode === "service" && !options.allowNetwork) {
102
153
  throw new VoiceError2("denied", "browser service recognition sends audio to the browser vendor; it needs explicit consent");
103
154
  }
155
+ const navigator = this.navigator;
156
+ if (this.mode === "service" && navigator?.onLine === false) {
157
+ throw new VoiceError2("unavailable", "the device is offline, so the browser's recognition service cannot be reached");
158
+ }
159
+ const permission = await queryMicrophone(navigator);
160
+ if (permission?.state === "denied") {
161
+ throw new VoiceError2("denied", "microphone permission is denied for this site");
162
+ }
104
163
  const constructor = recognitionConstructor(this.environment);
105
164
  if (constructor === undefined)
106
165
  throw new VoiceError2("unavailable");
@@ -109,14 +168,95 @@ class BrowserRecognitionProvider {
109
168
  recognition.continuous = true;
110
169
  recognition.interimResults = true;
111
170
  recognition.maxAlternatives = 1;
112
- if (this.mode === "local")
171
+ if (this.mode === "local") {
113
172
  recognition.processLocally = true;
173
+ if (recognition.processLocally !== true) {
174
+ throw new VoiceError2("unavailable", "this browser did not accept on-device recognition, so offline dictation cannot be proven");
175
+ }
176
+ }
177
+ const audio = await this.openMicrophone(options, recognition);
114
178
  return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
115
179
  endpointing: options.endpointing ?? DEFAULT_ENDPOINTING2,
116
180
  now: this.environment.now ?? (() => performance.now()),
117
- sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
181
+ sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
182
+ audio,
183
+ permission,
184
+ onSpeechStart: options.onSpeechStart,
185
+ onEarlyEnd: options.onEarlyEnd ?? "finalize",
186
+ maxRestarts: options.maxRestarts ?? 50,
187
+ whenHidden: options.whenHidden ?? "finalize",
188
+ document: this.environment.document,
189
+ window: this.window
118
190
  });
119
191
  }
192
+ get navigator() {
193
+ return this.environment.navigator;
194
+ }
195
+ get window() {
196
+ const add = this.environment.addEventListener;
197
+ const remove = this.environment.removeEventListener;
198
+ if (add && remove) {
199
+ const target = this.environment;
200
+ return { addEventListener: (type, listener) => add.call(target, type, listener), removeEventListener: (type, listener) => remove.call(target, type, listener) };
201
+ }
202
+ return;
203
+ }
204
+ async openMicrophone(options, recognition) {
205
+ const microphone = options.microphone;
206
+ if (microphone === undefined)
207
+ return;
208
+ const accepts = this.environment.recognitionAcceptsAudioTrack ?? "processLocally" in recognition;
209
+ if (!accepts) {
210
+ throw new VoiceError2("unavailable", "this browser cannot recognise from a chosen microphone, only the default one");
211
+ }
212
+ if ("track" in microphone) {
213
+ return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };
214
+ }
215
+ const getUserMedia = this.navigator?.mediaDevices?.getUserMedia;
216
+ if (getUserMedia === undefined) {
217
+ throw new VoiceError2("unavailable", "this browser cannot open a chosen microphone");
218
+ }
219
+ let stream;
220
+ try {
221
+ stream = await getUserMedia.call(this.navigator.mediaDevices, { audio: { deviceId: { exact: microphone.deviceId } } });
222
+ } catch (error) {
223
+ throw mapMediaError(error);
224
+ }
225
+ const tracks = stream.getTracks?.() ?? stream.getAudioTracks();
226
+ const track = stream.getAudioTracks()[0];
227
+ if (track === undefined) {
228
+ for (const owned of tracks)
229
+ owned.stop();
230
+ throw new VoiceError2("unavailable", "the chosen microphone produced no audio track");
231
+ }
232
+ return { track, owned: tracks, stopTrack: true };
233
+ }
234
+ }
235
+ async function queryMicrophone(navigator) {
236
+ const permissions = navigator?.permissions;
237
+ if (permissions === undefined || typeof permissions.query !== "function")
238
+ return;
239
+ try {
240
+ return await permissions.query({ name: "microphone" });
241
+ } catch {
242
+ return;
243
+ }
244
+ }
245
+ function mapMediaError(error) {
246
+ const name = error?.name;
247
+ switch (name) {
248
+ case "NotAllowedError":
249
+ case "SecurityError":
250
+ return new VoiceError2("denied", "microphone permission was denied");
251
+ case "NotFoundError":
252
+ case "OverconstrainedError":
253
+ return new VoiceError2("unavailable", "the chosen microphone is not available");
254
+ case "NotReadableError":
255
+ case "AbortError":
256
+ return new VoiceError2("busy", "the chosen microphone is in use or could not be opened");
257
+ default:
258
+ return VoiceError2.wrapping(error);
259
+ }
120
260
  }
121
261
  async function probeOnDevice(constructor, locale) {
122
262
  try {
@@ -142,6 +282,7 @@ function codeFor(reason) {
142
282
  return "unavailable";
143
283
  }
144
284
  }
285
+ var MAX_IDLE_RESTARTS = 3;
145
286
 
146
287
  class WebRecognitionSession {
147
288
  execution;
@@ -166,12 +307,18 @@ class WebRecognitionSession {
166
307
  words = false;
167
308
  stopRequested = false;
168
309
  endPromise;
169
- constructor(recognition, execution, timing) {
310
+ config;
311
+ cleanups = [];
312
+ speechSignalled = false;
313
+ restarts = 0;
314
+ idleRestarts = 0;
315
+ constructor(recognition, execution, config) {
170
316
  this.recognition = recognition;
171
317
  this.execution = execution;
172
- this.endpointing = timing.endpointing;
173
- this.now = timing.now;
174
- this.sleep = timing.sleep;
318
+ this.config = config;
319
+ this.endpointing = config.endpointing;
320
+ this.now = config.now;
321
+ this.sleep = config.sleep;
175
322
  recognition.onstart = () => {
176
323
  this.started = true;
177
324
  this.lastWordAt = this.now();
@@ -179,6 +326,76 @@ class WebRecognitionSession {
179
326
  recognition.onresult = (event) => this.onResult(event);
180
327
  recognition.onerror = (event) => this.onError(event);
181
328
  recognition.onend = () => this.onEnd();
329
+ recognition.onspeechstart = () => this.signalSpeech();
330
+ this.watchEnvironment();
331
+ }
332
+ watchEnvironment() {
333
+ const permission = this.config.permission;
334
+ if (permission !== undefined) {
335
+ const onChange = () => {
336
+ if (permission.state === "denied")
337
+ this.fail(new VoiceError2("denied", "microphone permission was revoked"));
338
+ };
339
+ if (permission.addEventListener && permission.removeEventListener) {
340
+ permission.addEventListener("change", onChange);
341
+ this.cleanups.push(() => permission.removeEventListener("change", onChange));
342
+ } else if ("onchange" in permission) {
343
+ const previous = permission.onchange ?? null;
344
+ permission.onchange = () => {
345
+ previous?.();
346
+ onChange();
347
+ };
348
+ this.cleanups.push(() => {
349
+ permission.onchange = previous;
350
+ });
351
+ }
352
+ }
353
+ const window = this.config.window;
354
+ if (window !== undefined) {
355
+ if (this.execution === "network") {
356
+ const onOffline = () => this.fail(new VoiceError2("unavailable", "the device went offline, so the browser's recognition service was lost"));
357
+ window.addEventListener("offline", onOffline);
358
+ this.cleanups.push(() => window.removeEventListener("offline", onOffline));
359
+ }
360
+ if (this.config.whenHidden !== "ignore") {
361
+ const onPageHide = () => this.pageHidden();
362
+ window.addEventListener("pagehide", onPageHide);
363
+ this.cleanups.push(() => window.removeEventListener("pagehide", onPageHide));
364
+ }
365
+ }
366
+ const document = this.config.document;
367
+ if (document !== undefined && this.config.whenHidden !== "ignore") {
368
+ const onVisibility = () => {
369
+ if (document.visibilityState === "hidden")
370
+ this.pageHidden();
371
+ };
372
+ document.addEventListener("visibilitychange", onVisibility);
373
+ this.cleanups.push(() => document.removeEventListener("visibilitychange", onVisibility));
374
+ }
375
+ }
376
+ pageHidden() {
377
+ if (this.terminal)
378
+ return;
379
+ this.started = true;
380
+ if (this.config.whenHidden === "cancel")
381
+ this.emitTerminal({ type: "cancelled" });
382
+ else
383
+ this.finishWithCollected();
384
+ }
385
+ signalSpeech() {
386
+ if (this.terminal || this.speechSignalled)
387
+ return;
388
+ this.speechSignalled = true;
389
+ try {
390
+ this.config.onSpeechStart?.();
391
+ } catch {}
392
+ }
393
+ startRecognizer() {
394
+ const track = this.config.audio?.track;
395
+ if (track !== undefined)
396
+ this.recognition.start(track);
397
+ else
398
+ this.recognition.start();
182
399
  }
183
400
  events() {
184
401
  if (this.iterated) {
@@ -190,7 +407,7 @@ class WebRecognitionSession {
190
407
  this.lastWordAt = this.now();
191
408
  this.startWatching();
192
409
  try {
193
- this.recognition.start();
410
+ this.startRecognizer();
194
411
  } catch (error) {
195
412
  this.fail(VoiceError2.wrapping(error));
196
413
  }
@@ -243,6 +460,7 @@ class WebRecognitionSession {
243
460
  onResult(event) {
244
461
  if (this.terminal)
245
462
  return;
463
+ this.idleRestarts = 0;
246
464
  let changed = false;
247
465
  const volatile = [];
248
466
  for (let index = event.resultIndex;index < event.results.length; index += 1) {
@@ -269,6 +487,8 @@ class WebRecognitionSession {
269
487
  }
270
488
  }
271
489
  const volatileText = volatile.reduce(joinText, "");
490
+ if (this.words)
491
+ this.signalSpeech();
272
492
  if (volatileText !== this.volatileText)
273
493
  changed = true;
274
494
  this.volatileText = volatileText;
@@ -287,6 +507,14 @@ class WebRecognitionSession {
287
507
  if (this.terminal)
288
508
  return;
289
509
  const error = mapRecognitionError(event);
510
+ if (error.code === "no_speech") {
511
+ if (this.words) {
512
+ this.finishWithCollected();
513
+ return;
514
+ }
515
+ if (this.config.onEarlyEnd === "restart" && !this.stopRequested)
516
+ return;
517
+ }
290
518
  if (error.code === "cancelled") {
291
519
  this.emitTerminal({ type: "cancelled" });
292
520
  return;
@@ -296,10 +524,32 @@ class WebRecognitionSession {
296
524
  onEnd() {
297
525
  if (this.terminal)
298
526
  return;
527
+ if (!this.stopRequested && this.config.onEarlyEnd === "restart" && this.restart())
528
+ return;
299
529
  this.finishWithCollected(true);
300
530
  }
531
+ restart() {
532
+ if (this.restarts >= this.config.maxRestarts || this.idleRestarts >= MAX_IDLE_RESTARTS)
533
+ return false;
534
+ if (this.volatileText.length > 0) {
535
+ this.finalizedText = joinText(this.finalizedText, this.volatileText);
536
+ this.volatileText = "";
537
+ }
538
+ this.restarts += 1;
539
+ this.idleRestarts += 1;
540
+ this.speechSignalled = false;
541
+ try {
542
+ this.startRecognizer();
543
+ return true;
544
+ } catch {
545
+ return false;
546
+ }
547
+ }
301
548
  finishWithCollected(fromEnd = false) {
302
- this.emitTerminal(this.words ? { type: "final", text: this.text } : { type: "failed", error: new VoiceError2("no_speech") }, fromEnd);
549
+ this.emitTerminal(this.words ? { type: "final", text: this.text, execution: this.recognitionExecution } : { type: "failed", error: new VoiceError2("no_speech"), execution: this.recognitionExecution }, fromEnd);
550
+ }
551
+ get recognitionExecution() {
552
+ return this.execution === "onDevice" && this.recognition.processLocally === true ? "local" : "service";
303
553
  }
304
554
  startWatching() {
305
555
  this.watch();
@@ -336,7 +586,7 @@ class WebRecognitionSession {
336
586
  return joinText(this.finalizedText, this.volatileText);
337
587
  }
338
588
  fail(error) {
339
- this.emitTerminal({ type: "failed", error });
589
+ this.emitTerminal({ type: "failed", error, execution: this.recognitionExecution });
340
590
  }
341
591
  emitTerminal(event, fromEnd = false) {
342
592
  if (this.terminal)
@@ -354,11 +604,29 @@ class WebRecognitionSession {
354
604
  recognition.onresult = null;
355
605
  recognition.onerror = null;
356
606
  recognition.onend = null;
357
- if (fromEnd)
358
- return;
359
- try {
360
- recognition.abort();
361
- } catch {}
607
+ if ("onspeechstart" in recognition)
608
+ recognition.onspeechstart = null;
609
+ for (const cleanup of this.cleanups.splice(0)) {
610
+ try {
611
+ cleanup();
612
+ } catch {}
613
+ }
614
+ if (!fromEnd) {
615
+ try {
616
+ recognition.abort();
617
+ } catch {}
618
+ }
619
+ const audio = this.config.audio;
620
+ if (audio !== undefined) {
621
+ const tracks = new Set(audio.owned);
622
+ if (audio.stopTrack)
623
+ tracks.add(audio.track);
624
+ for (const track of tracks) {
625
+ try {
626
+ track.stop();
627
+ } catch {}
628
+ }
629
+ }
362
630
  }
363
631
  drain() {
364
632
  const resolve = this.resolved;
@@ -843,6 +1111,95 @@ function defaultSupportsSimd() {
843
1111
  return false;
844
1112
  }
845
1113
  }
1114
+ // src/web/tts/locale-match.ts
1115
+ function parseLocale(tag) {
1116
+ const parts = tag.trim().replace(/_/g, "-").split("-").filter((part) => part.length > 0);
1117
+ const language = (parts[0] ?? "").toLowerCase();
1118
+ let script;
1119
+ let region;
1120
+ for (const part of parts.slice(1)) {
1121
+ if (script === undefined && region === undefined && /^[a-z]{4}$/i.test(part)) {
1122
+ script = part[0].toUpperCase() + part.slice(1).toLowerCase();
1123
+ } else if (region === undefined && (/^[a-z]{2}$/i.test(part) || /^\d{3}$/.test(part))) {
1124
+ region = part.toUpperCase();
1125
+ }
1126
+ }
1127
+ return { language, ...script ? { script } : {}, ...region ? { region } : {} };
1128
+ }
1129
+ var REGION_GROUPS = {
1130
+ es: [
1131
+ ["419", "MX", "US", "AR", "CO", "CL", "PE", "VE", "EC", "GT", "CU", "BO", "DO", "HN", "PY", "SV", "NI", "CR", "PA", "UY", "PR"],
1132
+ ["ES", "GQ", "150"]
1133
+ ],
1134
+ pt: [
1135
+ ["BR"],
1136
+ ["PT", "AO", "MZ", "CV", "GW", "ST", "TL", "MO", "150"]
1137
+ ],
1138
+ en: [
1139
+ ["US", "CA", "PH"],
1140
+ ["GB", "IE", "AU", "NZ", "ZA", "IN", "SG", "HK", "150"]
1141
+ ],
1142
+ fr: [
1143
+ ["FR", "BE", "CH", "LU", "MC", "150"],
1144
+ ["CA"]
1145
+ ],
1146
+ zh: [
1147
+ ["HANS", "CN", "SG", "MY"],
1148
+ ["HANT", "TW", "HK", "MO"]
1149
+ ]
1150
+ };
1151
+ function groupKey(locale) {
1152
+ if (locale.language === "zh" && locale.script)
1153
+ return locale.script.toUpperCase();
1154
+ return locale.region;
1155
+ }
1156
+ function groupOf(locale) {
1157
+ const key = groupKey(locale);
1158
+ if (key === undefined)
1159
+ return;
1160
+ const group = REGION_GROUPS[locale.language]?.find((candidate) => candidate.includes(key));
1161
+ return group ? { group } : undefined;
1162
+ }
1163
+ function matchLocale(requested, voiceLang) {
1164
+ const want = parseLocale(requested);
1165
+ const have = parseLocale(voiceLang);
1166
+ if (want.language.length === 0 || want.language !== have.language)
1167
+ return;
1168
+ if (normalize(requested) === normalize(voiceLang))
1169
+ return { match: "exact", rank: 0 };
1170
+ const wantKey = groupKey(want);
1171
+ const haveKey = groupKey(have);
1172
+ if (wantKey === undefined) {
1173
+ return { match: "region", rank: haveKey === undefined ? 100 : 200 + preferenceIndex(have) };
1174
+ }
1175
+ if (haveKey === wantKey && (want.region === have.region || want.region === undefined || have.region === undefined)) {
1176
+ return { match: "exact", rank: 1 };
1177
+ }
1178
+ const wanted = groupOf(want);
1179
+ if (wanted && haveKey !== undefined && wanted.group.includes(haveKey)) {
1180
+ return { match: "region", rank: 100 + wanted.group.indexOf(haveKey) };
1181
+ }
1182
+ if (have.region === undefined && haveKey === undefined)
1183
+ return { match: "language", rank: 1000 };
1184
+ return { match: "language", rank: 1100 + preferenceIndex(have) };
1185
+ }
1186
+ function preferenceIndex(locale) {
1187
+ const key = groupKey(locale);
1188
+ const groups = REGION_GROUPS[locale.language];
1189
+ if (key === undefined || groups === undefined)
1190
+ return 99;
1191
+ let offset = 0;
1192
+ for (const group of groups) {
1193
+ const index = group.indexOf(key);
1194
+ if (index >= 0)
1195
+ return offset + index;
1196
+ offset += group.length;
1197
+ }
1198
+ return 99;
1199
+ }
1200
+ function normalize(tag) {
1201
+ return tag.trim().replace(/_/g, "-").toLowerCase();
1202
+ }
846
1203
  // src/web/tts/system-voices.ts
847
1204
  var SYSTEM_VOICES_ID = "web.system-voices";
848
1205
  var DEFAULT_VOICES_TIMEOUT_MS = 1500;
@@ -871,16 +1228,25 @@ class SystemVoiceProvider {
871
1228
  return this.environment.Utterance ?? this.environment.SpeechSynthesisUtterance;
872
1229
  }
873
1230
  voices(locale) {
874
- const synthesis = this.environment.speechSynthesis;
875
- if (synthesis === undefined)
876
- return { local: [], remote: [] };
877
- const wanted = language(locale);
878
- const matches = synthesis.getVoices().filter((voice) => language(voice.lang) === wanted);
1231
+ const ranked = this.rankVoices(locale);
879
1232
  return {
880
- local: matches.filter((voice) => voice.localService === true),
881
- remote: matches.filter((voice) => voice.localService !== true)
1233
+ local: ranked.filter((entry) => entry.voice.localService === true).map((entry) => entry.voice),
1234
+ remote: ranked.filter((entry) => entry.voice.localService !== true).map((entry) => entry.voice)
882
1235
  };
883
1236
  }
1237
+ rankVoices(locale) {
1238
+ const synthesis = this.environment.speechSynthesis;
1239
+ if (synthesis === undefined)
1240
+ return [];
1241
+ return rank(synthesis.getVoices(), locale).map(({ voice, match }) => ({ voice, match: match.match }));
1242
+ }
1243
+ chooseVoice(options = {}) {
1244
+ const synthesis = this.environment.speechSynthesis;
1245
+ if (synthesis === undefined)
1246
+ return new VoiceError2("unavailable");
1247
+ const selection = this.selectVoice(synthesis.getVoices(), options);
1248
+ return selection === undefined || selection instanceof VoiceError2 ? selection : describe(selection);
1249
+ }
884
1250
  waitForVoices() {
885
1251
  const synthesis = this.environment.speechSynthesis;
886
1252
  if (synthesis === undefined || synthesis.getVoices().length > 0)
@@ -912,9 +1278,16 @@ class SystemVoiceProvider {
912
1278
  });
913
1279
  }
914
1280
  await this.waitForVoices();
915
- const { local, remote } = this.voices(locale);
916
- if (local.length > 0)
917
- return AVAILABLE2;
1281
+ const ranked = this.rankVoices(locale);
1282
+ const local = ranked.filter((entry) => entry.voice.localService === true);
1283
+ const remote = ranked.filter((entry) => entry.voice.localService !== true);
1284
+ const best = local[0];
1285
+ if (best !== undefined) {
1286
+ if (best.match === "language") {
1287
+ return availableWithMatch2("language", `no local ${locale} voice; only ${best.voice.lang} (${best.voice.name}) of the language is installed`);
1288
+ }
1289
+ return availableWithMatch2(best.match);
1290
+ }
918
1291
  if (remote.length > 0) {
919
1292
  return unavailable2("networkRequired", `only remote ${locale} voices are installed`, {
920
1293
  kind: "grantPermission",
@@ -939,7 +1312,8 @@ class SystemVoiceProvider {
939
1312
  if (selection instanceof VoiceError2) {
940
1313
  return { done: Promise.reject(selection), cancel: () => {} };
941
1314
  }
942
- const voice = selection;
1315
+ const chosen = selection;
1316
+ const voice = chosen?.voice;
943
1317
  const build = () => {
944
1318
  const utterance = new Utterance(text);
945
1319
  utterance.lang = voice?.lang ?? options.locale ?? "";
@@ -949,9 +1323,10 @@ class SystemVoiceProvider {
949
1323
  utterance.volume = options.volume ?? 1;
950
1324
  return utterance;
951
1325
  };
1326
+ const info = chosen === undefined ? undefined : describe(chosen);
952
1327
  let request;
953
1328
  const done = new Promise((resolve, reject) => {
954
- request = { build, options, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
1329
+ request = { build, options, voice: info, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
955
1330
  });
956
1331
  this.inFlight.push(request);
957
1332
  this.bind(request);
@@ -964,7 +1339,11 @@ class SystemVoiceProvider {
964
1339
  } catch (error) {
965
1340
  this.settle(request, VoiceError2.wrapping(error));
966
1341
  }
967
- return { done, cancel: () => this.abandon(request, new VoiceError2("cancelled")) };
1342
+ return {
1343
+ done,
1344
+ ...info === undefined ? {} : { voice: info },
1345
+ cancel: () => this.abandon(request, new VoiceError2("cancelled"))
1346
+ };
968
1347
  }
969
1348
  get isSpeaking() {
970
1349
  return this.environment.speechSynthesis?.speaking === true || this.environment.speechSynthesis?.pending === true;
@@ -977,26 +1356,28 @@ class SystemVoiceProvider {
977
1356
  if (requested.localService !== true && !allowNetwork) {
978
1357
  return new VoiceError2("denied", "a remote voice needs explicit consent");
979
1358
  }
980
- return requested;
1359
+ const match = options.locale ? matchLocale(options.locale, requested.lang)?.match ?? "language" : "named";
1360
+ return { voice: requested, match, offRegion: options.locale ? isOffRegion(options.locale, match) : false };
981
1361
  }
982
1362
  }
983
1363
  if (options.locale) {
984
- const wanted = language(options.locale);
985
- const tag = normalizeTag(options.locale);
986
- const sameLanguage = available.filter((voice) => language(voice.lang) === wanted);
987
- const pick = (pool) => pool.find((voice) => normalizeTag(voice.lang) === tag && voice.default === true) ?? pool.find((voice) => normalizeTag(voice.lang) === tag) ?? pool.find((voice) => voice.default === true) ?? pool[0];
988
- const local = pick(sameLanguage.filter((voice) => voice.localService === true));
989
- if (local)
990
- return local;
991
- if (allowNetwork)
992
- return pick(sameLanguage);
993
- return new VoiceError2("language_unsupported", `no local ${options.locale} voice is installed`);
1364
+ const ranked = rank(available, options.locale);
1365
+ const local = ranked.find((entry) => entry.voice.localService === true);
1366
+ const remote = ranked.find((entry) => entry.voice.localService !== true);
1367
+ let pick = local;
1368
+ if (allowNetwork && remote !== undefined && (pick === undefined || tier(remote.match.match) < tier(pick.match.match))) {
1369
+ pick = remote;
1370
+ }
1371
+ if (pick === undefined) {
1372
+ return new VoiceError2("language_unsupported", `no local ${options.locale} voice is installed`);
1373
+ }
1374
+ return { voice: pick.voice, match: pick.match.match, offRegion: isOffRegion(options.locale, pick.match.match) };
994
1375
  }
995
1376
  const fallback = available.find((voice) => voice.localService === true && voice.default === true) ?? available.find((voice) => voice.localService === true);
996
1377
  if (fallback === undefined && !allowNetwork) {
997
1378
  return new VoiceError2("language_unsupported", "no local voice is installed");
998
1379
  }
999
- return fallback;
1380
+ return fallback === undefined ? undefined : { voice: fallback, match: "default", offRegion: false };
1000
1381
  }
1001
1382
  bind(request) {
1002
1383
  const utterance = request.utterance;
@@ -1009,11 +1390,15 @@ class SystemVoiceProvider {
1009
1390
  return;
1010
1391
  }
1011
1392
  request.started = true;
1012
- options.onStart?.();
1393
+ options.onStart?.(request.voice);
1013
1394
  };
1014
1395
  utterance.onend = () => {
1015
1396
  if (request.utterance !== utterance || request.settled)
1016
1397
  return;
1398
+ if (!request.started) {
1399
+ this.settle(request, new VoiceError2("cancelled", "the platform voice was cancelled before it started"));
1400
+ return;
1401
+ }
1017
1402
  options.onEnd?.();
1018
1403
  this.settle(request);
1019
1404
  };
@@ -1084,11 +1469,25 @@ function detach(utterance) {
1084
1469
  utterance.onend = null;
1085
1470
  utterance.onerror = null;
1086
1471
  }
1087
- function normalizeTag(tag) {
1088
- return tag.replace(/_/g, "-").toLowerCase();
1472
+ function rank(available, locale) {
1473
+ return available.map((voice, index) => ({ voice, index, match: matchLocale(locale, voice.lang) })).filter((entry) => entry.match !== undefined).sort((a, b) => a.match.rank - b.match.rank || Number(b.voice.default === true) - Number(a.voice.default === true) || a.index - b.index);
1474
+ }
1475
+ function tier(match) {
1476
+ return match === "exact" ? 0 : match === "region" ? 1 : 2;
1089
1477
  }
1090
- function language(locale) {
1091
- return locale.toLowerCase().split(/[-_]/)[0] ?? locale.toLowerCase();
1478
+ function isOffRegion(locale, match) {
1479
+ return match === "language" && /[-_]/.test(locale.trim());
1480
+ }
1481
+ function describe(selection) {
1482
+ const voice = selection.voice;
1483
+ return {
1484
+ name: voice.name,
1485
+ ...voice.voiceURI === undefined ? {} : { voiceURI: voice.voiceURI },
1486
+ lang: voice.lang,
1487
+ localService: voice.localService === true,
1488
+ match: selection.match,
1489
+ offRegion: selection.offRegion
1490
+ };
1092
1491
  }
1093
1492
  function mapSynthesisError(error) {
1094
1493
  switch (error) {
@@ -1138,7 +1537,11 @@ class VoiceTurnManager {
1138
1537
  try {
1139
1538
  session = await this.options.transcription.createSession({
1140
1539
  locale: this.options.locale,
1141
- allowNetwork: this.options.allowNetwork === true
1540
+ allowNetwork: this.options.allowNetwork === true,
1541
+ onSpeechStart: () => {
1542
+ if (!this.finished && generation === this.generation)
1543
+ this.notifySpeechDetected();
1544
+ }
1142
1545
  });
1143
1546
  } catch (error) {
1144
1547
  if (this.finished)
@@ -1265,6 +1668,9 @@ class VoiceTurnManager {
1265
1668
  function defaultListenerError(error) {
1266
1669
  console.error("voice turn listener threw", error);
1267
1670
  }
1671
+ function bargeInOnSpeechStart(manager) {
1672
+ return { onSpeechStart: () => manager.notifySpeechDetected() };
1673
+ }
1268
1674
  export {
1269
1675
  BrowserRecognitionProvider,
1270
1676
  DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
@@ -1273,15 +1679,19 @@ export {
1273
1679
  PHONON_PROVIDER_ID,
1274
1680
  PhononProvider,
1275
1681
  PlaybackUtterance,
1682
+ REGION_GROUPS,
1276
1683
  SERVICE_RECOGNITION_ID,
1277
1684
  SYSTEM_VOICES_ID,
1278
1685
  StreamingPcmPlayer,
1279
1686
  SystemVoiceProvider,
1280
1687
  VoiceTurnManager,
1688
+ bargeInOnSpeechStart,
1281
1689
  browserRecognitionLocal,
1282
1690
  browserRecognitionService,
1283
1691
  clearPhononCache,
1284
1692
  defaultAudioContextFactory,
1285
1693
  defaultPhononRuntime,
1694
+ matchLocale,
1695
+ parseLocale,
1286
1696
  recognitionConstructor
1287
1697
  };