@burdenoff/microfe-healthybowl 2026.901.3 → 2026.901.4
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,6 +1,9 @@
|
|
|
1
1
|
//#region src/services/speech/hostedTtsProtocol.ts
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
function e(e, t) {
|
|
3
|
+
return t ? !1 : e === "not-allowed" || e === "unsupported";
|
|
4
|
+
}
|
|
5
|
+
var t = 2e3;
|
|
6
|
+
function n(e, t, n, r, i) {
|
|
4
7
|
let a = {
|
|
5
8
|
text: e,
|
|
6
9
|
languageCode: t,
|
|
@@ -8,27 +11,27 @@ function t(e, t, n, r, i) {
|
|
|
8
11
|
};
|
|
9
12
|
return r && r.toLowerCase().startsWith(t.toLowerCase()) && (a.voiceName = r), i !== void 0 && (a.speakingRate = i), a;
|
|
10
13
|
}
|
|
11
|
-
function
|
|
14
|
+
function r(e) {
|
|
12
15
|
return e === 401 || e === 403 ? "not-allowed" : e === 404 || e === 501 ? "unsupported" : "unknown";
|
|
13
16
|
}
|
|
14
|
-
function
|
|
17
|
+
function i(e) {
|
|
15
18
|
let t = globalThis.Buffer, n = typeof atob == "function" ? atob(e) : t?.from(e, "base64").toString("binary") ?? "", r = new Uint8Array(n.length);
|
|
16
19
|
for (let e = 0; e < n.length; e += 1) r[e] = n.charCodeAt(e);
|
|
17
20
|
return r;
|
|
18
21
|
}
|
|
19
|
-
function
|
|
22
|
+
function a(e, t) {
|
|
20
23
|
if (t instanceof ArrayBuffer) return t.byteLength > 0 ? new Uint8Array(t) : null;
|
|
21
24
|
if (e?.includes("json") || typeof t == "object") {
|
|
22
25
|
let e = t.audioContent;
|
|
23
26
|
if (!e) return null;
|
|
24
|
-
let n =
|
|
27
|
+
let n = i(e);
|
|
25
28
|
return n.length > 0 ? n : null;
|
|
26
29
|
}
|
|
27
30
|
return null;
|
|
28
31
|
}
|
|
29
|
-
function
|
|
30
|
-
if (
|
|
31
|
-
let r = [], i =
|
|
32
|
+
function o(e, n = t) {
|
|
33
|
+
if (e.length <= n) return [e];
|
|
34
|
+
let r = [], i = e;
|
|
32
35
|
for (; i.length > n;) {
|
|
33
36
|
let e = i.slice(0, n).lastIndexOf(" "), t = e > n * .5 ? e : n;
|
|
34
37
|
r.push(i.slice(0, t).trim()), i = i.slice(t).trim();
|
|
@@ -36,6 +39,6 @@ function a(t, n = e) {
|
|
|
36
39
|
return i && r.push(i), r.filter((e) => e.length > 0);
|
|
37
40
|
}
|
|
38
41
|
//#endregion
|
|
39
|
-
export {
|
|
42
|
+
export { n as buildRequest, r as classifyHttpFailure, a as decodeAudioResponse, e as shouldDisableEngine, o as splitForVendor };
|
|
40
43
|
|
|
41
44
|
//# sourceMappingURL=hostedTtsProtocol.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hostedTtsProtocol.js","names":[],"sources":["../../../src/services/speech/hostedTtsProtocol.ts"],"sourcesContent":["/**\n * The wire contract for the hosted TTS proxy, kept pure so it can be tested\n * (BOFF-7111).\n *\n * `browserSpeechEngine` carries a note explaining that it is untestable in this\n * repo — vitest runs in the `node` environment with no DOM and no audio — and\n * that the testable logic was deliberately kept out of it. Same discipline\n * here: request building, response decoding and error classification live in\n * this file with no `window`, `Audio` or `fetch` reference, and the engine file\n * holds only the parts that genuinely need a browser.\n *\n * The browser never talks to the vendor directly. A Google Cloud service-account\n * key cannot be shipped to a client, so every request goes to our own proxy,\n * which holds the credential and does the vendor call.\n */\n\nimport type { SpeechErrorReason } from './types';\n\n/** What the client sends per chunk. */\nexport interface HostedTtsRequest {\n text: string;\n /** BCP-47, e.g. `ta-IN`. The vendor needs the region, not a bare subtag. */\n languageCode: string;\n /** Vendor voice id, e.g. `ta-IN-Chirp3-HD-Kore`. Omitted = server default. */\n voiceName?: string;\n /** Vendor voice tier, so the backend need not infer it from the name. */\n tier: string;\n /**\n * The same knob the device engine calls `rate`.\n *\n * ★ The accepted range depends on which vendor ENDPOINT the proxy calls, not\n * on the voice tier — see `SPEAKING_RATE_MAX_SYNC` below. Values in use are\n * 0.9, and 0.85 for Indic scripts and Arabic, comfortably inside every\n * variant, so this has never affected playback.\n */\n speakingRate?: number;\n}\n\n/**\n * Google's synthesize response is `{ audioContent: <base64 mp3> }`. We accept\n * that shape directly so the proxy can be a thin pass-through, but the proxy is\n * also free to return raw audio bytes — see `decodeAudioResponse`.\n */\nexport interface HostedTtsJsonResponse {\n audioContent?: string;\n error?: { message?: string };\n}\n\n/**\n * The accepted speaking-rate bounds, for any caller that clamps.\n *\n * ★ The ceiling is a property of the ENDPOINT, not of the voice tier, and the\n * vendor's own rejection message says both numbers out loud:\n *\n * \"Unable to adjust speaking rate. Please ensure that speaking_rate is in the\n * range [0.25, 4.0] for sync synthesis and in the range [0.25, 2.0] for\n * streaming synthesis.\"\n *\n * Measured against the live API on 2026-08-31 with `en-IN-Chirp3-HD-Puck` and a\n * fixed sentence, reading the returned LINEAR16 duration rather than trusting\n * the HTTP status — 4.0 synthesises and is genuinely ~4x faster (21.93s at 0.25\n * down to 1.37s at 4.0); 4.1, 5.0 and 0.2 are all rejected with the message\n * above.\n *\n * This corrects a previous edit of this file which narrowed the ceiling to 2.0\n * and attributed 4.0 to \"the older Standard/WaveNet tiers\". That reading was\n * wrong: 2.0 is the STREAMING limit, and the tier has nothing to do with it.\n *\n * `SPEAKING_RATE_MAX` is the sync ceiling because the proxy calls\n * `v1/text:synthesize`. Moving it to `v1/text:streamingSynthesize` — tempting,\n * since that is how you cut time-to-first-audio — halves the ceiling, and rates\n * the client had treated as valid would start returning 400. That switch has to\n * change this alias in the same commit, which is why both bounds are named\n * rather than one being a magic number.\n */\nexport const SPEAKING_RATE_MIN = 0.25;\nexport const SPEAKING_RATE_MAX_SYNC = 4.0;\nexport const SPEAKING_RATE_MAX_STREAMING = 2.0;\nexport const SPEAKING_RATE_MAX = SPEAKING_RATE_MAX_SYNC;\n\n/** Vendor limit is 5000 bytes per request; stay well inside it. */\nexport const HOSTED_TTS_MAX_CHARS = 2000;\n\nexport function buildRequest(\n text: string,\n languageCode: string,\n tier: string,\n voiceName?: string | null,\n speakingRate?: number\n): HostedTtsRequest {\n const request: HostedTtsRequest = { text, languageCode, tier };\n // A voice name from ANOTHER language must never be forwarded: the vendor\n // would either error or, worse, read the text with the wrong phoneme model.\n // The caller resolves the voice, but this is the last line of defence.\n if (voiceName && voiceName.toLowerCase().startsWith(languageCode.toLowerCase())) {\n request.voiceName = voiceName;\n }\n if (speakingRate !== undefined) request.speakingRate = speakingRate;\n return request;\n}\n\n/**\n * Map a transport failure onto the reasons the UI already knows how to explain.\n *\n * `cancelled` is deliberately NOT produced here — an aborted request is the\n * caller's own doing and the engine reports it, exactly as the browser engine\n * swallows its own `canceled` utterance errors.\n */\nexport function classifyHttpFailure(status: number): SpeechErrorReason {\n // 401/403 mean the proxy rejected us; there is nothing the user can do and\n // \"unsupported\" is what disables the control rather than showing a retry\n // that will fail identically.\n if (status === 401 || status === 403) return 'not-allowed';\n if (status === 404 || status === 501) return 'unsupported';\n return 'unknown';\n}\n\n/** Base64 → bytes, without assuming a DOM (`atob` is not in node). */\nexport function base64ToBytes(base64: string): Uint8Array {\n // `Buffer` only exists under node (the test environment); typed rather than\n // cast through `any`, which this repo's conventions forbid.\n const nodeBuffer = (\n globalThis as unknown as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n const binary =\n typeof atob === 'function' ? atob(base64) : (nodeBuffer?.from(base64, 'base64').toString('binary') ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Accept either shape the proxy may return: a JSON body carrying base64\n * (the vendor's own shape, so the proxy can pass it straight through) or raw\n * audio bytes.\n *\n * Returns null when the payload carries no audio at all — which must be treated\n * as a failure, not as silence. A zero-byte \"success\" that plays nothing is the\n * dead-button bug this feature already fixed once.\n */\nexport function decodeAudioResponse(\n contentType: string | null,\n body: ArrayBuffer | HostedTtsJsonResponse\n): Uint8Array | null {\n if (body instanceof ArrayBuffer) {\n return body.byteLength > 0 ? new Uint8Array(body) : null;\n }\n if (contentType?.includes('json') || typeof body === 'object') {\n const encoded = body.audioContent;\n if (!encoded) return null;\n const bytes = base64ToBytes(encoded);\n return bytes.length > 0 ? bytes : null;\n }\n return null;\n}\n\n/**\n * Split text the hosted vendor would reject for length.\n *\n * `chunkForSpeech` already splits for the browser engine's ~15s utterance\n * ceiling, and those chunks are normally far under the vendor limit — this is a\n * backstop for a single pathological sentence, and it splits on whitespace so a\n * word is never cut in half.\n */\nexport function splitForVendor(text: string, limit = HOSTED_TTS_MAX_CHARS): string[] {\n if (text.length <= limit) return [text];\n const out: string[] = [];\n let rest = text;\n while (rest.length > limit) {\n const window = rest.slice(0, limit);\n const cut = window.lastIndexOf(' ');\n // No space at all (CJK, or one enormous token): hard-cut at the limit\n // rather than sending something the vendor will reject outright.\n const at = cut > limit * 0.5 ? cut : limit;\n out.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n }\n if (rest) out.push(rest);\n return out.filter((part) => part.length > 0);\n}\n"],"mappings":";AAiFA,IAAa,IAAuB;AAEpC,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkB;CAClB,IAAM,IAA4B;EAAE;EAAM;EAAc;CAAK;CAQ7D,OAJI,KAAa,EAAU,YAAY,EAAE,WAAW,EAAa,YAAY,CAAC,MAC5E,EAAQ,YAAY,IAElB,MAAiB,KAAA,MAAW,EAAQ,eAAe,IAChD;AACT;AASA,SAAgB,EAAoB,GAAmC;CAMrE,OAFI,MAAW,OAAO,MAAW,MAAY,gBACzC,MAAW,OAAO,MAAW,MAAY,gBACtC;AACT;AAGA,SAAgB,EAAc,GAA4B;CAGxD,IAAM,IACJ,WAGA,QACI,IACJ,OAAO,QAAS,aAAa,KAAK,CAAM,IAAK,GAAY,KAAK,GAAQ,QAAQ,EAAE,SAAS,QAAQ,KAAK,IAClG,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,GAAG,EAAM,KAAK,EAAO,WAAW,CAAC;CACzE,OAAO;AACT;AAWA,SAAgB,EACd,GACA,GACmB;CACnB,IAAI,aAAgB,aAClB,OAAO,EAAK,aAAa,IAAI,IAAI,WAAW,CAAI,IAAI;CAEtD,IAAI,GAAa,SAAS,MAAM,KAAK,OAAO,KAAS,UAAU;EAC7D,IAAM,IAAU,EAAK;EACrB,IAAI,CAAC,GAAS,OAAO;EACrB,IAAM,IAAQ,EAAc,CAAO;EACnC,OAAO,EAAM,SAAS,IAAI,IAAQ;CACpC;CACA,OAAO;AACT;AAUA,SAAgB,EAAe,GAAc,IAAQ,GAAgC;CACnF,IAAI,EAAK,UAAU,GAAO,OAAO,CAAC,CAAI;CACtC,IAAM,IAAgB,CAAC,GACnB,IAAO;CACX,OAAO,EAAK,SAAS,IAAO;EAE1B,IAAM,IADS,EAAK,MAAM,GAAG,CACjB,EAAO,YAAY,GAAG,GAG5B,IAAK,IAAM,IAAQ,KAAM,IAAM;EAErC,AADA,EAAI,KAAK,EAAK,MAAM,GAAG,CAAE,EAAE,KAAK,CAAC,GACjC,IAAO,EAAK,MAAM,CAAE,EAAE,KAAK;CAC7B;CAEA,OADI,KAAM,EAAI,KAAK,CAAI,GAChB,EAAI,QAAQ,MAAS,EAAK,SAAS,CAAC;AAC7C"}
|
|
1
|
+
{"version":3,"file":"hostedTtsProtocol.js","names":[],"sources":["../../../src/services/speech/hostedTtsProtocol.ts"],"sourcesContent":["/**\n * The wire contract for the hosted TTS proxy, kept pure so it can be tested\n * (BOFF-7111).\n *\n * `browserSpeechEngine` carries a note explaining that it is untestable in this\n * repo — vitest runs in the `node` environment with no DOM and no audio — and\n * that the testable logic was deliberately kept out of it. Same discipline\n * here: request building, response decoding and error classification live in\n * this file with no `window`, `Audio` or `fetch` reference, and the engine file\n * holds only the parts that genuinely need a browser.\n *\n * The browser never talks to the vendor directly. A Google Cloud service-account\n * key cannot be shipped to a client, so every request goes to our own proxy,\n * which holds the credential and does the vendor call.\n */\n\nimport type { SpeechErrorReason } from './types';\n\n/** What the client sends per chunk. */\nexport interface HostedTtsRequest {\n text: string;\n /** BCP-47, e.g. `ta-IN`. The vendor needs the region, not a bare subtag. */\n languageCode: string;\n /** Vendor voice id, e.g. `ta-IN-Chirp3-HD-Kore`. Omitted = server default. */\n voiceName?: string;\n /** Vendor voice tier, so the backend need not infer it from the name. */\n tier: string;\n /**\n * The same knob the device engine calls `rate`.\n *\n * ★ The accepted range depends on which vendor ENDPOINT the proxy calls, not\n * on the voice tier — see `SPEAKING_RATE_MAX_SYNC` below. Values in use are\n * 0.9, and 0.85 for Indic scripts and Arabic, comfortably inside every\n * variant, so this has never affected playback.\n */\n speakingRate?: number;\n}\n\n/**\n * Google's synthesize response is `{ audioContent: <base64 mp3> }`. We accept\n * that shape directly so the proxy can be a thin pass-through, but the proxy is\n * also free to return raw audio bytes — see `decodeAudioResponse`.\n */\nexport interface HostedTtsJsonResponse {\n audioContent?: string;\n error?: { message?: string };\n}\n\n/**\n * The accepted speaking-rate bounds, for any caller that clamps.\n *\n * ★ The ceiling is a property of the ENDPOINT, not of the voice tier, and the\n * vendor's own rejection message says both numbers out loud:\n *\n * \"Unable to adjust speaking rate. Please ensure that speaking_rate is in the\n * range [0.25, 4.0] for sync synthesis and in the range [0.25, 2.0] for\n * streaming synthesis.\"\n *\n * Measured against the live API on 2026-08-31 with `en-IN-Chirp3-HD-Puck` and a\n * fixed sentence, reading the returned LINEAR16 duration rather than trusting\n * the HTTP status — 4.0 synthesises and is genuinely ~4x faster (21.93s at 0.25\n * down to 1.37s at 4.0); 4.1, 5.0 and 0.2 are all rejected with the message\n * above.\n *\n * This corrects a previous edit of this file which narrowed the ceiling to 2.0\n * and attributed 4.0 to \"the older Standard/WaveNet tiers\". That reading was\n * wrong: 2.0 is the STREAMING limit, and the tier has nothing to do with it.\n *\n * `SPEAKING_RATE_MAX` is the sync ceiling because the proxy calls\n * `v1/text:synthesize`. Moving it to `v1/text:streamingSynthesize` — tempting,\n * since that is how you cut time-to-first-audio — halves the ceiling, and rates\n * the client had treated as valid would start returning 400. That switch has to\n * change this alias in the same commit, which is why both bounds are named\n * rather than one being a magic number.\n */\nexport const SPEAKING_RATE_MIN = 0.25;\nexport const SPEAKING_RATE_MAX_SYNC = 4.0;\nexport const SPEAKING_RATE_MAX_STREAMING = 2.0;\nexport const SPEAKING_RATE_MAX = SPEAKING_RATE_MAX_SYNC;\n\n/**\n * Should a failure stop the engine claiming support for the rest of the page?\n *\n * ★ `not-allowed` has TWO producers and only one of them is terminal:\n *\n * - `classifyHttpFailure` maps HTTP 401/403 to it — the proxy refuses us, and\n * every later request will be refused identically. Latching is right: it\n * makes `routingSpeechEngine` fall back to device voices instead of\n * repeating a request that cannot succeed.\n * - the engine maps the browser's `NotAllowedError` to it — the autoplay\n * policy declining to play audio that was not started by a user gesture.\n * That is PER-GESTURE and entirely transient; the very next tap works.\n *\n * Latching on the second silently deleted the hosted voice for the whole page\n * after a single refusal — and auto-speak is precisely the path that triggers\n * it, because an arriving reply is not a gesture. The user would hear Chirp 3\n * once, be refused once, and get device voices for the rest of the session with\n * nothing explaining why.\n *\n * Pure and exported because the engine itself cannot be unit-tested here (no\n * DOM, no Audio), so the decision is kept where it CAN be.\n */\nexport function shouldDisableEngine(reason: string | undefined, transient: boolean): boolean {\n if (transient) return false;\n return reason === 'not-allowed' || reason === 'unsupported';\n}\n\n/** Vendor limit is 5000 bytes per request; stay well inside it. */\nexport const HOSTED_TTS_MAX_CHARS = 2000;\n\nexport function buildRequest(\n text: string,\n languageCode: string,\n tier: string,\n voiceName?: string | null,\n speakingRate?: number\n): HostedTtsRequest {\n const request: HostedTtsRequest = { text, languageCode, tier };\n // A voice name from ANOTHER language must never be forwarded: the vendor\n // would either error or, worse, read the text with the wrong phoneme model.\n // The caller resolves the voice, but this is the last line of defence.\n if (voiceName && voiceName.toLowerCase().startsWith(languageCode.toLowerCase())) {\n request.voiceName = voiceName;\n }\n if (speakingRate !== undefined) request.speakingRate = speakingRate;\n return request;\n}\n\n/**\n * Map a transport failure onto the reasons the UI already knows how to explain.\n *\n * `cancelled` is deliberately NOT produced here — an aborted request is the\n * caller's own doing and the engine reports it, exactly as the browser engine\n * swallows its own `canceled` utterance errors.\n */\nexport function classifyHttpFailure(status: number): SpeechErrorReason {\n // 401/403 mean the proxy rejected us; there is nothing the user can do and\n // \"unsupported\" is what disables the control rather than showing a retry\n // that will fail identically.\n if (status === 401 || status === 403) return 'not-allowed';\n if (status === 404 || status === 501) return 'unsupported';\n return 'unknown';\n}\n\n/** Base64 → bytes, without assuming a DOM (`atob` is not in node). */\nexport function base64ToBytes(base64: string): Uint8Array {\n // `Buffer` only exists under node (the test environment); typed rather than\n // cast through `any`, which this repo's conventions forbid.\n const nodeBuffer = (\n globalThis as unknown as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n const binary =\n typeof atob === 'function' ? atob(base64) : (nodeBuffer?.from(base64, 'base64').toString('binary') ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Accept either shape the proxy may return: a JSON body carrying base64\n * (the vendor's own shape, so the proxy can pass it straight through) or raw\n * audio bytes.\n *\n * Returns null when the payload carries no audio at all — which must be treated\n * as a failure, not as silence. A zero-byte \"success\" that plays nothing is the\n * dead-button bug this feature already fixed once.\n */\nexport function decodeAudioResponse(\n contentType: string | null,\n body: ArrayBuffer | HostedTtsJsonResponse\n): Uint8Array | null {\n if (body instanceof ArrayBuffer) {\n return body.byteLength > 0 ? new Uint8Array(body) : null;\n }\n if (contentType?.includes('json') || typeof body === 'object') {\n const encoded = body.audioContent;\n if (!encoded) return null;\n const bytes = base64ToBytes(encoded);\n return bytes.length > 0 ? bytes : null;\n }\n return null;\n}\n\n/**\n * Split text the hosted vendor would reject for length.\n *\n * `chunkForSpeech` already splits for the browser engine's ~15s utterance\n * ceiling, and those chunks are normally far under the vendor limit — this is a\n * backstop for a single pathological sentence, and it splits on whitespace so a\n * word is never cut in half.\n */\nexport function splitForVendor(text: string, limit = HOSTED_TTS_MAX_CHARS): string[] {\n if (text.length <= limit) return [text];\n const out: string[] = [];\n let rest = text;\n while (rest.length > limit) {\n const window = rest.slice(0, limit);\n const cut = window.lastIndexOf(' ');\n // No space at all (CJK, or one enormous token): hard-cut at the limit\n // rather than sending something the vendor will reject outright.\n const at = cut > limit * 0.5 ? cut : limit;\n out.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n }\n if (rest) out.push(rest);\n return out.filter((part) => part.length > 0);\n}\n"],"mappings":";AAsGA,SAAgB,EAAoB,GAA4B,GAA6B;CAE3F,OADI,IAAkB,KACf,MAAW,iBAAiB,MAAW;AAChD;AAGA,IAAa,IAAuB;AAEpC,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkB;CAClB,IAAM,IAA4B;EAAE;EAAM;EAAc;CAAK;CAQ7D,OAJI,KAAa,EAAU,YAAY,EAAE,WAAW,EAAa,YAAY,CAAC,MAC5E,EAAQ,YAAY,IAElB,MAAiB,KAAA,MAAW,EAAQ,eAAe,IAChD;AACT;AASA,SAAgB,EAAoB,GAAmC;CAMrE,OAFI,MAAW,OAAO,MAAW,MAAY,gBACzC,MAAW,OAAO,MAAW,MAAY,gBACtC;AACT;AAGA,SAAgB,EAAc,GAA4B;CAGxD,IAAM,IACJ,WAGA,QACI,IACJ,OAAO,QAAS,aAAa,KAAK,CAAM,IAAK,GAAY,KAAK,GAAQ,QAAQ,EAAE,SAAS,QAAQ,KAAK,IAClG,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,GAAG,EAAM,KAAK,EAAO,WAAW,CAAC;CACzE,OAAO;AACT;AAWA,SAAgB,EACd,GACA,GACmB;CACnB,IAAI,aAAgB,aAClB,OAAO,EAAK,aAAa,IAAI,IAAI,WAAW,CAAI,IAAI;CAEtD,IAAI,GAAa,SAAS,MAAM,KAAK,OAAO,KAAS,UAAU;EAC7D,IAAM,IAAU,EAAK;EACrB,IAAI,CAAC,GAAS,OAAO;EACrB,IAAM,IAAQ,EAAc,CAAO;EACnC,OAAO,EAAM,SAAS,IAAI,IAAQ;CACpC;CACA,OAAO;AACT;AAUA,SAAgB,EAAe,GAAc,IAAQ,GAAgC;CACnF,IAAI,EAAK,UAAU,GAAO,OAAO,CAAC,CAAI;CACtC,IAAM,IAAgB,CAAC,GACnB,IAAO;CACX,OAAO,EAAK,SAAS,IAAO;EAE1B,IAAM,IADS,EAAK,MAAM,GAAG,CACjB,EAAO,YAAY,GAAG,GAG5B,IAAK,IAAM,IAAQ,KAAM,IAAM;EAErC,AADA,EAAI,KAAK,EAAK,MAAM,GAAG,CAAE,EAAE,KAAK,CAAC,GACjC,IAAO,EAAK,MAAM,CAAE,EAAE,KAAK;CAC7B;CAEA,OADI,KAAM,EAAI,KAAK,CAAI,GAChB,EAAI,QAAQ,MAAS,EAAK,SAAS,CAAC;AAC7C"}
|
|
@@ -1,26 +1,26 @@
|
|
|
1
1
|
import { HOSTED_TTS_TIER as e, HOSTED_VOICES as t, hostedLocaleFor as n } from "./hostedVoiceCatalogue.js";
|
|
2
|
-
import { buildRequest as r, classifyHttpFailure as i, decodeAudioResponse as a,
|
|
2
|
+
import { buildRequest as r, classifyHttpFailure as i, decodeAudioResponse as a, shouldDisableEngine as o, splitForVendor as s } from "./hostedTtsProtocol.js";
|
|
3
3
|
//#region src/services/speech/hostedTtsSpeechEngine.ts
|
|
4
|
-
function
|
|
5
|
-
let
|
|
6
|
-
|
|
7
|
-
},
|
|
8
|
-
if (
|
|
9
|
-
|
|
4
|
+
function c(c) {
|
|
5
|
+
let l = c.fetchImpl ?? ((...e) => fetch(...e)), u = null, d = null, f = 0, p = null, m = !1, h = () => {
|
|
6
|
+
d &&= (URL.revokeObjectURL(d), null);
|
|
7
|
+
}, g = () => {
|
|
8
|
+
if (u) {
|
|
9
|
+
u.onended = null, u.onerror = null;
|
|
10
10
|
try {
|
|
11
|
-
|
|
11
|
+
u.pause();
|
|
12
12
|
} catch {}
|
|
13
|
-
|
|
13
|
+
u = null;
|
|
14
14
|
}
|
|
15
|
-
|
|
15
|
+
h();
|
|
16
16
|
};
|
|
17
|
-
async function
|
|
18
|
-
let u = r(t, n(o.lang) ?? o.lang, e, o.voice?.name ?? null, o.rate), d = await c
|
|
17
|
+
async function _(t, o, s) {
|
|
18
|
+
let u = r(t, n(o.lang) ?? o.lang, e, o.voice?.name ?? null, o.rate), d = await l(c.endpoint, {
|
|
19
19
|
method: "POST",
|
|
20
|
-
signal:
|
|
20
|
+
signal: s,
|
|
21
21
|
headers: {
|
|
22
22
|
"content-type": "application/json",
|
|
23
|
-
...
|
|
23
|
+
...c.getHeaders?.() ?? {}
|
|
24
24
|
},
|
|
25
25
|
body: JSON.stringify(u)
|
|
26
26
|
});
|
|
@@ -35,40 +35,40 @@ function s(s) {
|
|
|
35
35
|
}
|
|
36
36
|
return p;
|
|
37
37
|
}
|
|
38
|
-
function
|
|
38
|
+
function v(e, t, n) {
|
|
39
39
|
return new Promise((r, i) => {
|
|
40
|
-
if (t !==
|
|
40
|
+
if (t !== f) {
|
|
41
41
|
r();
|
|
42
42
|
return;
|
|
43
43
|
}
|
|
44
44
|
let a = new Blob([e.slice().buffer], { type: "audio/mpeg" });
|
|
45
|
-
|
|
46
|
-
let o = new Audio(
|
|
47
|
-
|
|
48
|
-
t ===
|
|
45
|
+
h(), d = URL.createObjectURL(a);
|
|
46
|
+
let o = new Audio(d);
|
|
47
|
+
u = o, o.onended = () => {
|
|
48
|
+
t === f && r();
|
|
49
49
|
}, o.onerror = () => {
|
|
50
|
-
if (t !==
|
|
50
|
+
if (t !== f) {
|
|
51
51
|
r();
|
|
52
52
|
return;
|
|
53
53
|
}
|
|
54
54
|
let e = /* @__PURE__ */ Error("audio playback failed");
|
|
55
55
|
e.reason = "unknown", i(e);
|
|
56
56
|
}, o.play().then(() => {
|
|
57
|
-
t ===
|
|
57
|
+
t === f && n?.();
|
|
58
58
|
}, (e) => {
|
|
59
|
-
if (t !==
|
|
59
|
+
if (t !== f) {
|
|
60
60
|
r();
|
|
61
61
|
return;
|
|
62
62
|
}
|
|
63
|
-
let n = /* @__PURE__ */ Error("audio play rejected");
|
|
64
|
-
n.reason =
|
|
63
|
+
let n = /* @__PURE__ */ Error("audio play rejected"), a = e?.name === "NotAllowedError";
|
|
64
|
+
n.reason = a ? "not-allowed" : "unknown", n.transient = a, i(n);
|
|
65
65
|
});
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
68
|
return {
|
|
69
69
|
id: "hosted-tts",
|
|
70
70
|
isSupported() {
|
|
71
|
-
return
|
|
71
|
+
return m ? !1 : typeof window < "u" && typeof window.Audio == "function" && typeof fetch == "function";
|
|
72
72
|
},
|
|
73
73
|
listVoices() {
|
|
74
74
|
return [...t];
|
|
@@ -77,47 +77,47 @@ function s(s) {
|
|
|
77
77
|
return () => {};
|
|
78
78
|
},
|
|
79
79
|
speak(e, t, n = {}) {
|
|
80
|
-
let r = e.filter((e) => e.trim().length > 0).flatMap((e) =>
|
|
80
|
+
let r = e.filter((e) => e.trim().length > 0).flatMap((e) => s(e));
|
|
81
81
|
if (r.length === 0) {
|
|
82
82
|
n.onEnd?.();
|
|
83
83
|
return;
|
|
84
84
|
}
|
|
85
|
-
|
|
86
|
-
let i =
|
|
87
|
-
|
|
85
|
+
f += 1;
|
|
86
|
+
let i = f;
|
|
87
|
+
g();
|
|
88
88
|
let a = new AbortController();
|
|
89
|
-
|
|
90
|
-
let
|
|
91
|
-
|
|
92
|
-
},
|
|
93
|
-
let n =
|
|
89
|
+
p = a;
|
|
90
|
+
let c = !1, l = () => {
|
|
91
|
+
c || (c = !0, n.onStart?.());
|
|
92
|
+
}, u = (e) => {
|
|
93
|
+
let n = _(e, t, a.signal);
|
|
94
94
|
return n.catch(() => {}), n;
|
|
95
95
|
};
|
|
96
96
|
(async () => {
|
|
97
97
|
try {
|
|
98
|
-
let e =
|
|
98
|
+
let e = u(r[0]);
|
|
99
99
|
for (let t = 0; t < r.length; t += 1) {
|
|
100
|
-
if (i !==
|
|
100
|
+
if (i !== f) return;
|
|
101
101
|
let n = await e;
|
|
102
|
-
if (i !==
|
|
102
|
+
if (i !== f) return;
|
|
103
103
|
let a = r[t + 1];
|
|
104
|
-
a !== void 0 && (e =
|
|
104
|
+
a !== void 0 && (e = u(a)), await v(n, i, l);
|
|
105
105
|
}
|
|
106
|
-
i ===
|
|
106
|
+
i === f && n.onEnd?.();
|
|
107
107
|
} catch (e) {
|
|
108
|
-
if (a.abort(), i !==
|
|
109
|
-
|
|
108
|
+
if (a.abort(), i !== f) return;
|
|
109
|
+
f += 1, g();
|
|
110
110
|
let t = e?.reason;
|
|
111
|
-
(t
|
|
111
|
+
o(t, e?.transient === !0) && (m = !0), n.onError?.(t === "not-allowed" || t === "unsupported" || t === "cancelled" ? t : "unknown");
|
|
112
112
|
}
|
|
113
113
|
})();
|
|
114
114
|
},
|
|
115
115
|
cancel() {
|
|
116
|
-
|
|
116
|
+
f += 1, p?.abort(), p = null, g();
|
|
117
117
|
}
|
|
118
118
|
};
|
|
119
119
|
}
|
|
120
120
|
//#endregion
|
|
121
|
-
export {
|
|
121
|
+
export { c as createHostedTtsEngine };
|
|
122
122
|
|
|
123
123
|
//# sourceMappingURL=hostedTtsSpeechEngine.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hostedTtsSpeechEngine.js","names":[],"sources":["../../../src/services/speech/hostedTtsSpeechEngine.ts"],"sourcesContent":["/**\n * Hosted (server-side) implementation of the `SpeechEngine` seam (BOFF-7111).\n *\n * The device-voice engine is as good as it is ever going to get: the Web Speech\n * API can only play voices the OS has installed, and on the devices that matter\n * here those are compact voices that do not sound human. Every knob was already\n * turned — rate, voice ranking, punctuation — and the result is still not close\n * to Assistant quality. The remaining gap IS the synthesiser, so this engine\n * replaces it.\n *\n * Structure mirrors `browserSpeechEngine` deliberately:\n * - **A generation counter.** `cancel()` bumps it; any fetch or `ended` event\n * from an older batch is dropped rather than clearing the state of a\n * playback that has already started.\n * - **Chunks played in order**, with the NEXT chunk fetched while the current\n * one plays. Without that prefetch every chunk boundary costs a full network\n * round trip and the reply sounds stuttered — worse than the device voice it\n * replaces.\n * - **Everything testable lives elsewhere** (`hostedTtsProtocol.ts`,\n * `hostedVoiceCatalogue.ts`) because this repo's vitest has no DOM and no\n * audio, so this file cannot be unit-tested.\n *\n * Failure is never silent: any error surfaces through `onError`, and the caller\n * (`createSpeechEngine`) is what decides to fall back to the device engine.\n */\n\nimport { HOSTED_TTS_TIER, HOSTED_VOICES, hostedLocaleFor } from './hostedVoiceCatalogue';\nimport { buildRequest, classifyHttpFailure, decodeAudioResponse, splitForVendor } from './hostedTtsProtocol';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface HostedTtsOptions {\n /** Absolute or same-origin path of OUR proxy. Never the vendor directly. */\n endpoint: string;\n /** Extra headers per request (auth). Called fresh each time so a rotated token is picked up. */\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createHostedTtsEngine(options: HostedTtsOptions): SpeechEngine {\n const doFetch = options.fetchImpl ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let audio: HTMLAudioElement | null = null;\n let objectUrl: string | null = null;\n /**\n * Bumped on every `speak`/`cancel`; anything from an older batch is ignored.\n *\n * Per INSTANCE, not per module. `browserSpeechEngine` can keep this at module\n * scope because it is a singleton object; this is a factory, so a shared\n * counter would let one engine's `cancel()` silently invalidate another\n * engine's in-flight playback.\n */\n let generation = 0;\n /** The in-flight batch's controller, so `cancel()` can actually abort it. */\n let active: AbortController | null = null;\n /**\n * Set after a terminal proxy failure (401/403/404/501). Retrying cannot\n * succeed, and leaving the engine \"supported\" means every later press repeats\n * the same failing request. Reporting unsupported makes the routing engine\n * fall back to device voices, which still work.\n */\n let disabled = false;\n\n const releaseUrl = () => {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrl = null;\n }\n };\n\n const stopAudio = () => {\n if (audio) {\n audio.onended = null;\n audio.onerror = null;\n try {\n audio.pause();\n } catch {\n /* pausing an already-dead element is harmless */\n }\n audio = null;\n }\n releaseUrl();\n };\n\n /** One chunk of text -> audio bytes. Throws with a `reason` the engine maps. */\n async function synthesise(text: string, opts: SpeechSpeakOptions, signal: AbortSignal): Promise<Uint8Array> {\n // The vendor's locale, not the app's: the app says `ar-SA`, Google only has\n // `ar-XA`. Sending the app tag would be an unsupported locale AND would\n // make `buildRequest` drop the chosen `ar-XA` voice as a mismatch.\n const languageCode = hostedLocaleFor(opts.lang) ?? opts.lang;\n const body = buildRequest(text, languageCode, HOSTED_TTS_TIER, opts.voice?.name ?? null, opts.rate);\n const response = await doFetch(options.endpoint, {\n method: 'POST',\n signal,\n headers: { 'content-type': 'application/json', ...(options.getHeaders?.() ?? {}) },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n const err = new Error(`hosted tts ${response.status}`) as Error & { reason?: string };\n err.reason = classifyHttpFailure(response.status);\n throw err;\n }\n const contentType = response.headers.get('content-type');\n const payload = contentType?.includes('json') ? await response.json() : await response.arrayBuffer();\n const bytes = decodeAudioResponse(contentType, payload);\n if (!bytes) {\n // A 200 carrying no audio is a failure, not silence. Treating it as\n // success is exactly the dead-button bug this feature already fixed once.\n const err = new Error('hosted tts returned no audio') as Error & { reason?: string };\n err.reason = 'unknown';\n throw err;\n }\n return bytes;\n }\n\n /**\n * `onBegin` fires when audio genuinely starts, not when it is requested, and\n * not when the chunk ends. The distinction matters to the routing engine: a\n * failure before any sound reached the user can be retried on the device\n * engine, and a failure after it cannot without repeating words.\n */\n function play(bytes: Uint8Array, batch: number, onBegin?: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Copy into a fresh ArrayBuffer: the Uint8Array may be a view over a\n // larger buffer, and Blob would then include the neighbouring bytes.\n const blob = new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'audio/mpeg' });\n releaseUrl();\n objectUrl = URL.createObjectURL(blob);\n const element = new Audio(objectUrl);\n audio = element;\n element.onended = () => {\n if (batch !== generation) return;\n resolve();\n };\n element.onerror = () => {\n if (batch !== generation) {\n resolve();\n return;\n }\n const err = new Error('audio playback failed') as Error & { reason?: string };\n err.reason = 'unknown';\n reject(err);\n };\n element.play().then(\n () => {\n if (batch === generation) onBegin?.();\n },\n (cause: unknown) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Autoplay policy: playback needs a user gesture. Every path that\n // starts speech here is a button press, but an auto-speak triggered\n // by an arriving reply is not, and that is the case this reports.\n const err = new Error('audio play rejected') as Error & { reason?: string };\n err.reason = (cause as DOMException)?.name === 'NotAllowedError' ? 'not-allowed' : 'unknown';\n reject(err);\n }\n );\n });\n }\n\n return {\n id: 'hosted-tts',\n\n isSupported(): boolean {\n if (disabled) return false;\n return typeof window !== 'undefined' && typeof window.Audio === 'function' && typeof fetch === 'function';\n },\n\n listVoices(): SpeechVoiceLike[] {\n // A hosted catalogue is known up front, so unlike the browser engine\n // there is never an empty-then-populated race: `voiceAvailability` sees a\n // full list on the first read and never reports `pending`.\n return [...HOSTED_VOICES];\n },\n\n subscribeVoices(): () => void {\n // The catalogue is static — nothing to subscribe to. Returning a no-op\n // unsubscribe keeps the caller identical for both engines.\n return () => {};\n },\n\n speak(chunks: readonly string[], opts: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0).flatMap((chunk) => splitForVendor(chunk));\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n generation += 1;\n const batch = generation;\n stopAudio();\n const controller = new AbortController();\n active = controller;\n\n // Announced at most once per batch: the caller only needs to know that\n // sound reached the user, not how many chunks did.\n let announcedStart = false;\n const notifyStarted = (): void => {\n if (announcedStart) return;\n announcedStart = true;\n handlers.onStart?.();\n };\n\n /**\n * Start a request and neutralise it as an unhandled rejection.\n *\n * A prefetched chunk is abandoned whenever the batch is cancelled\n * mid-loop. Attaching a swallow handler here does NOT consume the\n * rejection for the real `await` — `.catch` returns a NEW promise and the\n * original still rejects — so the error is still reported if we get that\n * far, and is silent if we never do.\n */\n const start = (text: string): Promise<Uint8Array> => {\n const request = synthesise(text, opts, controller.signal);\n request.catch(() => {});\n return request;\n };\n\n void (async () => {\n try {\n // Fetch the first chunk, then keep exactly one chunk in flight ahead\n // of playback so a boundary never costs a whole round trip.\n let pending: Promise<Uint8Array> = start(speakable[0] as string);\n for (let i = 0; i < speakable.length; i += 1) {\n if (batch !== generation) return;\n const current = await pending;\n if (batch !== generation) return;\n const next = speakable[i + 1];\n // On the last chunk nothing new is queued; `pending` keeps its\n // already-settled value and the loop simply ends.\n if (next !== undefined) pending = start(next);\n await play(current, batch, notifyStarted);\n }\n if (batch === generation) handlers.onEnd?.();\n } catch (cause) {\n controller.abort();\n if (batch !== generation) return; // cancelled — the caller already knows\n generation += 1; // abandon the rest of this batch\n stopAudio();\n const reason = (cause as { reason?: string })?.reason;\n // Terminal: the proxy is missing or refuses us, and retrying cannot\n // succeed. Stop claiming support so the routing engine falls back to\n // device voices from now on, instead of every later press repeating\n // the same failing request.\n if (reason === 'not-allowed' || reason === 'unsupported') disabled = true;\n handlers.onError?.(\n reason === 'not-allowed' || reason === 'unsupported' || reason === 'cancelled' ? reason : 'unknown'\n );\n }\n })();\n },\n\n cancel(): void {\n generation += 1;\n // Abort the in-flight synthesis too. Without this a cancelled reply keeps\n // downloading — and keeps costing billable vendor characters — until it\n // completes into a batch nobody is listening to.\n active?.abort();\n active = null;\n stopAudio();\n },\n };\n}\n"],"mappings":";;;AAsCA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,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EAAQ,YAAY,CAAC,CAAC,GACf;GACT;GAEA,CAAM,YAAY;IAChB,IAAI;KAGF,IAAI,IAA+B,EAAM,EAAU,EAAY;KAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,EAAU,QAAQ,KAAK,GAAG;MAC5C,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAU,MAAM;MACtB,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAO,EAAU,IAAI;MAI3B,AADI,MAAS,KAAA,MAAW,IAAU,EAAM,CAAI,IAC5C,MAAM,EAAK,GAAS,GAAO,CAAa;KAC1C;KACA,AAAI,MAAU,KAAY,EAAS,QAAQ;IAC7C,SAAS,GAAO;KAEd,IADA,EAAW,MAAM,GACb,MAAU,GAAY;KAE1B,AADA,KAAc,GACd,EAAU;KACV,IAAM,IAAU,GAA+B;KAM/C,CADI,MAAW,iBAAiB,MAAW,mBAAe,IAAW,KACrE,EAAS,UACP,MAAW,iBAAiB,MAAW,iBAAiB,MAAW,cAAc,IAAS,SAC5F;IACF;GACF,GAAG;EACL;EAEA,SAAe;GAOb,AANA,KAAc,GAId,GAAQ,MAAM,GACd,IAAS,MACT,EAAU;EACZ;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"hostedTtsSpeechEngine.js","names":[],"sources":["../../../src/services/speech/hostedTtsSpeechEngine.ts"],"sourcesContent":["/**\n * Hosted (server-side) implementation of the `SpeechEngine` seam (BOFF-7111).\n *\n * The device-voice engine is as good as it is ever going to get: the Web Speech\n * API can only play voices the OS has installed, and on the devices that matter\n * here those are compact voices that do not sound human. Every knob was already\n * turned — rate, voice ranking, punctuation — and the result is still not close\n * to Assistant quality. The remaining gap IS the synthesiser, so this engine\n * replaces it.\n *\n * Structure mirrors `browserSpeechEngine` deliberately:\n * - **A generation counter.** `cancel()` bumps it; any fetch or `ended` event\n * from an older batch is dropped rather than clearing the state of a\n * playback that has already started.\n * - **Chunks played in order**, with the NEXT chunk fetched while the current\n * one plays. Without that prefetch every chunk boundary costs a full network\n * round trip and the reply sounds stuttered — worse than the device voice it\n * replaces.\n * - **Everything testable lives elsewhere** (`hostedTtsProtocol.ts`,\n * `hostedVoiceCatalogue.ts`) because this repo's vitest has no DOM and no\n * audio, so this file cannot be unit-tested.\n *\n * Failure is never silent: any error surfaces through `onError`, and the caller\n * (`createSpeechEngine`) is what decides to fall back to the device engine.\n */\n\nimport { HOSTED_TTS_TIER, HOSTED_VOICES, hostedLocaleFor } from './hostedVoiceCatalogue';\nimport {\n buildRequest,\n classifyHttpFailure,\n decodeAudioResponse,\n shouldDisableEngine,\n splitForVendor,\n} from './hostedTtsProtocol';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface HostedTtsOptions {\n /** Absolute or same-origin path of OUR proxy. Never the vendor directly. */\n endpoint: string;\n /** Extra headers per request (auth). Called fresh each time so a rotated token is picked up. */\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createHostedTtsEngine(options: HostedTtsOptions): SpeechEngine {\n const doFetch = options.fetchImpl ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let audio: HTMLAudioElement | null = null;\n let objectUrl: string | null = null;\n /**\n * Bumped on every `speak`/`cancel`; anything from an older batch is ignored.\n *\n * Per INSTANCE, not per module. `browserSpeechEngine` can keep this at module\n * scope because it is a singleton object; this is a factory, so a shared\n * counter would let one engine's `cancel()` silently invalidate another\n * engine's in-flight playback.\n */\n let generation = 0;\n /** The in-flight batch's controller, so `cancel()` can actually abort it. */\n let active: AbortController | null = null;\n /**\n * Set after a terminal proxy failure (401/403/404/501). Retrying cannot\n * succeed, and leaving the engine \"supported\" means every later press repeats\n * the same failing request. Reporting unsupported makes the routing engine\n * fall back to device voices, which still work.\n */\n let disabled = false;\n\n const releaseUrl = () => {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrl = null;\n }\n };\n\n const stopAudio = () => {\n if (audio) {\n audio.onended = null;\n audio.onerror = null;\n try {\n audio.pause();\n } catch {\n /* pausing an already-dead element is harmless */\n }\n audio = null;\n }\n releaseUrl();\n };\n\n /** One chunk of text -> audio bytes. Throws with a `reason` the engine maps. */\n async function synthesise(text: string, opts: SpeechSpeakOptions, signal: AbortSignal): Promise<Uint8Array> {\n // The vendor's locale, not the app's: the app says `ar-SA`, Google only has\n // `ar-XA`. Sending the app tag would be an unsupported locale AND would\n // make `buildRequest` drop the chosen `ar-XA` voice as a mismatch.\n const languageCode = hostedLocaleFor(opts.lang) ?? opts.lang;\n const body = buildRequest(text, languageCode, HOSTED_TTS_TIER, opts.voice?.name ?? null, opts.rate);\n const response = await doFetch(options.endpoint, {\n method: 'POST',\n signal,\n headers: { 'content-type': 'application/json', ...(options.getHeaders?.() ?? {}) },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n const err = new Error(`hosted tts ${response.status}`) as Error & { reason?: string };\n err.reason = classifyHttpFailure(response.status);\n throw err;\n }\n const contentType = response.headers.get('content-type');\n const payload = contentType?.includes('json') ? await response.json() : await response.arrayBuffer();\n const bytes = decodeAudioResponse(contentType, payload);\n if (!bytes) {\n // A 200 carrying no audio is a failure, not silence. Treating it as\n // success is exactly the dead-button bug this feature already fixed once.\n const err = new Error('hosted tts returned no audio') as Error & { reason?: string };\n err.reason = 'unknown';\n throw err;\n }\n return bytes;\n }\n\n /**\n * `onBegin` fires when audio genuinely starts, not when it is requested, and\n * not when the chunk ends. The distinction matters to the routing engine: a\n * failure before any sound reached the user can be retried on the device\n * engine, and a failure after it cannot without repeating words.\n */\n function play(bytes: Uint8Array, batch: number, onBegin?: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Copy into a fresh ArrayBuffer: the Uint8Array may be a view over a\n // larger buffer, and Blob would then include the neighbouring bytes.\n const blob = new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'audio/mpeg' });\n releaseUrl();\n objectUrl = URL.createObjectURL(blob);\n const element = new Audio(objectUrl);\n audio = element;\n element.onended = () => {\n if (batch !== generation) return;\n resolve();\n };\n element.onerror = () => {\n if (batch !== generation) {\n resolve();\n return;\n }\n const err = new Error('audio playback failed') as Error & { reason?: string };\n err.reason = 'unknown';\n reject(err);\n };\n element.play().then(\n () => {\n if (batch === generation) onBegin?.();\n },\n (cause: unknown) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Autoplay policy: playback needs a user gesture. Every path that\n // starts speech here is a button press, but an auto-speak triggered\n // by an arriving reply is not, and that is the case this reports.\n const err = new Error('audio play rejected') as Error & { reason?: string; transient?: boolean };\n const autoplayBlocked = (cause as DOMException)?.name === 'NotAllowedError';\n err.reason = autoplayBlocked ? 'not-allowed' : 'unknown';\n // ★ Marked transient so it cannot latch the engine off. An autoplay\n // refusal is per-gesture; the next tap plays. See shouldDisableEngine.\n err.transient = autoplayBlocked;\n reject(err);\n }\n );\n });\n }\n\n return {\n id: 'hosted-tts',\n\n isSupported(): boolean {\n if (disabled) return false;\n return typeof window !== 'undefined' && typeof window.Audio === 'function' && typeof fetch === 'function';\n },\n\n listVoices(): SpeechVoiceLike[] {\n // A hosted catalogue is known up front, so unlike the browser engine\n // there is never an empty-then-populated race: `voiceAvailability` sees a\n // full list on the first read and never reports `pending`.\n return [...HOSTED_VOICES];\n },\n\n subscribeVoices(): () => void {\n // The catalogue is static — nothing to subscribe to. Returning a no-op\n // unsubscribe keeps the caller identical for both engines.\n return () => {};\n },\n\n speak(chunks: readonly string[], opts: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0).flatMap((chunk) => splitForVendor(chunk));\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n generation += 1;\n const batch = generation;\n stopAudio();\n const controller = new AbortController();\n active = controller;\n\n // Announced at most once per batch: the caller only needs to know that\n // sound reached the user, not how many chunks did.\n let announcedStart = false;\n const notifyStarted = (): void => {\n if (announcedStart) return;\n announcedStart = true;\n handlers.onStart?.();\n };\n\n /**\n * Start a request and neutralise it as an unhandled rejection.\n *\n * A prefetched chunk is abandoned whenever the batch is cancelled\n * mid-loop. Attaching a swallow handler here does NOT consume the\n * rejection for the real `await` — `.catch` returns a NEW promise and the\n * original still rejects — so the error is still reported if we get that\n * far, and is silent if we never do.\n */\n const start = (text: string): Promise<Uint8Array> => {\n const request = synthesise(text, opts, controller.signal);\n request.catch(() => {});\n return request;\n };\n\n void (async () => {\n try {\n // Fetch the first chunk, then keep exactly one chunk in flight ahead\n // of playback so a boundary never costs a whole round trip.\n let pending: Promise<Uint8Array> = start(speakable[0] as string);\n for (let i = 0; i < speakable.length; i += 1) {\n if (batch !== generation) return;\n const current = await pending;\n if (batch !== generation) return;\n const next = speakable[i + 1];\n // On the last chunk nothing new is queued; `pending` keeps its\n // already-settled value and the loop simply ends.\n if (next !== undefined) pending = start(next);\n await play(current, batch, notifyStarted);\n }\n if (batch === generation) handlers.onEnd?.();\n } catch (cause) {\n controller.abort();\n if (batch !== generation) return; // cancelled — the caller already knows\n generation += 1; // abandon the rest of this batch\n stopAudio();\n const reason = (cause as { reason?: string })?.reason;\n // Terminal: the proxy is missing or refuses us, and retrying cannot\n // succeed. Stop claiming support so the routing engine falls back to\n // device voices from now on, instead of every later press repeating\n // the same failing request.\n //\n // ★ A browser autoplay refusal reports the SAME reason and must not\n // latch — it is per-gesture, and auto-speak is exactly the path that\n // triggers it.\n if (shouldDisableEngine(reason, (cause as { transient?: boolean })?.transient === true)) disabled = true;\n handlers.onError?.(\n reason === 'not-allowed' || reason === 'unsupported' || reason === 'cancelled' ? reason : 'unknown'\n );\n }\n })();\n },\n\n cancel(): void {\n generation += 1;\n // Abort the in-flight synthesis too. Without this a cancelled reply keeps\n // downloading — and keeps costing billable vendor characters — until it\n // completes into a batch nobody is listening to.\n active?.abort();\n active = null;\n stopAudio();\n },\n };\n}\n"],"mappings":";;;AA4CA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,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