@vocasync/astro 0.1.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +77 -41
  2. package/dist/api/client.d.ts +63 -50
  3. package/dist/api/client.d.ts.map +1 -1
  4. package/dist/api/client.js +132 -145
  5. package/dist/api/client.js.map +1 -1
  6. package/dist/api/index.d.ts +1 -1
  7. package/dist/api/index.d.ts.map +1 -1
  8. package/dist/api/index.js +1 -1
  9. package/dist/api/index.js.map +1 -1
  10. package/dist/cli.js +7 -7
  11. package/dist/cli.js.map +1 -1
  12. package/dist/components/AudioPlayer.astro +136 -137
  13. package/dist/config/schema.d.ts +21 -20
  14. package/dist/config/schema.d.ts.map +1 -1
  15. package/dist/config/schema.js +15 -4
  16. package/dist/config/schema.js.map +1 -1
  17. package/dist/core/audio-map.js +1 -1
  18. package/dist/core/speech-builder.d.ts +10 -7
  19. package/dist/core/speech-builder.d.ts.map +1 -1
  20. package/dist/core/speech-builder.js +73 -168
  21. package/dist/core/speech-builder.js.map +1 -1
  22. package/dist/core/spoken-form.d.ts +52 -0
  23. package/dist/core/spoken-form.d.ts.map +1 -0
  24. package/dist/core/spoken-form.js +279 -0
  25. package/dist/core/spoken-form.js.map +1 -0
  26. package/dist/lib/latex-to-speech/index.d.ts +9 -2
  27. package/dist/lib/latex-to-speech/index.d.ts.map +1 -1
  28. package/dist/lib/latex-to-speech/index.js +20 -22
  29. package/dist/lib/latex-to-speech/index.js.map +1 -1
  30. package/dist/lib/latex-to-speech/speak.d.ts +13 -0
  31. package/dist/lib/latex-to-speech/speak.d.ts.map +1 -0
  32. package/dist/lib/latex-to-speech/speak.js +47 -0
  33. package/dist/lib/latex-to-speech/speak.js.map +1 -0
  34. package/dist/rehype/audio-words.d.ts +14 -24
  35. package/dist/rehype/audio-words.d.ts.map +1 -1
  36. package/dist/rehype/audio-words.js +131 -252
  37. package/dist/rehype/audio-words.js.map +1 -1
  38. package/dist/rehype/index.d.ts +1 -2
  39. package/dist/rehype/index.d.ts.map +1 -1
  40. package/dist/rehype/index.js +0 -1
  41. package/dist/rehype/index.js.map +1 -1
  42. package/dist/rehype/rehype-math-speech.d.ts +26 -10
  43. package/dist/rehype/rehype-math-speech.d.ts.map +1 -1
  44. package/dist/rehype/rehype-math-speech.js +59 -92
  45. package/dist/rehype/rehype-math-speech.js.map +1 -1
  46. package/dist/rehype/shared.d.ts +9 -0
  47. package/dist/rehype/shared.d.ts.map +1 -0
  48. package/dist/rehype/shared.js +31 -0
  49. package/dist/rehype/shared.js.map +1 -0
  50. package/dist/sync/orchestrator.d.ts +4 -22
  51. package/dist/sync/orchestrator.d.ts.map +1 -1
  52. package/dist/sync/orchestrator.js +123 -123
  53. package/dist/sync/orchestrator.js.map +1 -1
  54. package/dist/types/index.d.ts +82 -46
  55. package/dist/types/index.d.ts.map +1 -1
  56. package/package.json +14 -11
  57. package/src/api/client.ts +175 -190
  58. package/src/api/index.ts +8 -1
  59. package/src/cli.ts +7 -14
  60. package/src/components/AudioPlayer.astro +136 -137
  61. package/src/config/schema.ts +15 -4
  62. package/src/core/audio-map.ts +1 -1
  63. package/src/core/speech-builder.ts +75 -192
  64. package/src/core/spoken-form.ts +298 -0
  65. package/src/lib/latex-to-speech/index.ts +32 -22
  66. package/src/lib/latex-to-speech/speak.ts +55 -0
  67. package/src/rehype/audio-words.ts +145 -307
  68. package/src/rehype/index.ts +1 -2
  69. package/src/rehype/rehype-math-speech.ts +64 -117
  70. package/src/rehype/shared.ts +36 -0
  71. package/src/sync/orchestrator.ts +150 -157
  72. package/src/types/index.ts +85 -47
  73. package/src/types/modules.d.ts +5 -2
  74. package/dist/rehype/remark-math-speech.d.ts +0 -13
  75. package/dist/rehype/remark-math-speech.d.ts.map +0 -1
  76. package/dist/rehype/remark-math-speech.js +0 -26
  77. package/dist/rehype/remark-math-speech.js.map +0 -1
  78. package/src/rehype/remark-math-speech.ts +0 -31
@@ -1,255 +1,143 @@
1
- import type { Code, Content, Emphasis, Heading, InlineCode, Root, Strong, Text } from "mdast";
1
+ import type { Content, Emphasis, Heading, Root, Strong, Text } from "mdast";
2
2
  import remarkMath from "remark-math";
3
3
  import remarkParse from "remark-parse";
4
4
  import { unified } from "unified";
5
5
  import type { MathConfig } from "../config/index.js";
6
+ import { speakLatex } from "../lib/latex-to-speech/speak.js";
6
7
  import type { ContentItem, SpeechDocument } from "../types/index.js";
7
- import { computeHash } from "./hash-manager.js";
8
+ import { buildSpeechtextPair } from "./spoken-form.js";
8
9
 
9
- /**
10
- * LaTeX to speech converter interface
11
- */
12
- interface LaTeXConverter {
13
- convert(latex: string, display: boolean): Promise<string>;
14
- }
15
-
16
- // Cache for latex-to-speech results
17
- const latexSpeechCache = new Map<string, Promise<string>>();
18
- let latexToSpeech:
19
- | ((exprs: string[], options?: Record<string, unknown>) => Promise<string[]>)
20
- | null = null;
21
- let latexToSpeechLoadAttempted = false;
22
- let warnedLatexSpeechFailure = false;
23
-
24
- /**
25
- * Normalize whitespace in text.
26
- */
27
- function normalizeWhitespace(value = ""): string {
28
- return value.replace(/\r/g, "").replace(/\s+/g, " ").trim();
29
- }
30
-
31
- /**
32
- * Create a lazy-loaded LaTeX converter using our internal latex-to-speech module.
33
- * This uses speech-rule-engine and mathjax-full as optional peer dependencies.
34
- */
35
- async function createLatexConverter(config: MathConfig): Promise<LaTeXConverter | null> {
36
- if (!config.enabled) {
37
- return null;
38
- }
39
-
40
- // Lazy load our internal latex-to-speech module
41
- if (!latexToSpeechLoadAttempted) {
42
- latexToSpeechLoadAttempted = true;
43
- try {
44
- const mod = await import("../lib/latex-to-speech/index.js");
45
- latexToSpeech = mod.latexToSpeech || mod.default;
46
- } catch {
47
- console.warn(
48
- "[vocasync] Math-to-speech initialization failed. Install optional dependencies:",
49
- "\n npm install speech-rule-engine mathjax-full"
50
- );
51
- }
52
- }
53
-
54
- if (!latexToSpeech) {
55
- return null;
56
- }
57
-
58
- const options = {
59
- domain: config.style || "clearspeak",
60
- style: "default",
61
- locale: "en",
62
- modality: "speech",
63
- };
64
-
65
- return {
66
- async convert(latex: string, display: boolean): Promise<string> {
67
- const trimmed = latex.trim();
68
- if (!trimmed) return "";
69
-
70
- const cacheKey = `${display}:${trimmed}`;
71
- if (!latexSpeechCache.has(cacheKey)) {
72
- const pending = (async () => {
73
- try {
74
- const result = await latexToSpeech!([trimmed], options);
75
- const spoken = Array.isArray(result) ? result[0] : String(result ?? "");
76
- return normalizeWhitespace(spoken);
77
- } catch (error) {
78
- if (!warnedLatexSpeechFailure) {
79
- console.warn(
80
- "[vocasync] Failed to convert LaTeX to speech:",
81
- error instanceof Error ? error.message : error
82
- );
83
- warnedLatexSpeechFailure = true;
84
- }
85
- return normalizeWhitespace(trimmed);
86
- }
87
- })();
88
- latexSpeechCache.set(cacheKey, pending);
89
- }
90
- return latexSpeechCache.get(cacheKey)!;
91
- },
92
- };
93
- }
94
-
95
- /**
96
- * Options for building speech document
97
- */
98
10
  interface BuildOptions {
99
11
  math?: MathConfig;
100
12
  }
101
13
 
102
14
  /**
103
15
  * Build a speech document from markdown content.
104
- * Converts markdown to plain text suitable for TTS synthesis.
105
16
  *
106
- * @param item - The content item to process
107
- * @param options - Build options including math configuration
108
- * @returns A speech document ready for synthesis
17
+ * Produces plain text from the SAME visible tokens the rehype word-wrapper
18
+ * sees — no phantom tokens (no "Quote:", "Image:", "[Code in X]", inline
19
+ * code), and code blocks / images are skipped exactly as rehype skips
20
+ * `pre`/`code`/`img`. This keeps the alignment transcript
21
+ * (`normalisedSpeechtext`) token-for-token with the rehype `data-i` stream.
22
+ *
23
+ * Headings keep a leading "# " marker so the synthesis backend chunks at
24
+ * heading boundaries; `stripForAlignment` removes it, so it never becomes an
25
+ * alignment token. Math expressions contribute their `speakLatex` output at
26
+ * their reading position (the same string the rehype math handler counts).
109
27
  */
110
28
  export async function buildSpeechDocument(
111
29
  item: ContentItem,
112
30
  options: BuildOptions = {}
113
31
  ): Promise<SpeechDocument> {
114
32
  const mathConfig = options.math ?? { enabled: false, style: "clearspeak" };
115
- const latexConverter = await createLatexConverter(mathConfig);
33
+ const style = mathConfig.style || "clearspeak";
116
34
 
117
- // Parse markdown with math support
118
35
  const processor = unified().use(remarkParse).use(remarkMath);
119
-
120
36
  const tree = processor.parse(item.content) as Root;
121
37
 
122
- // Extract text from AST - can contain strings or promises
123
38
  const textParts: (string | Promise<string>)[] = [];
39
+ // Collect math spoken forms keyed by `${'d'|'i'}:${latex}` so the rehype
40
+ // plugin can reuse them without running math-to-speech in the Vite build.
41
+ const mathKeys: string[] = [];
42
+ const mathPromises: Promise<string>[] = [];
43
+
44
+ function recordMath(latex: string, display: boolean): Promise<string> {
45
+ const p = speakLatex(latex, display, style);
46
+ mathKeys.push(`${display ? "d" : "i"}:${latex.trim()}`);
47
+ mathPromises.push(p);
48
+ return p;
49
+ }
50
+
51
+ function processChildren(node: { children: Content[] }): void {
52
+ for (const child of node.children) {
53
+ processNode(child);
54
+ }
55
+ }
124
56
 
125
57
  function processNode(node: Content | Root): void {
126
58
  switch (node.type) {
127
59
  case "text": {
128
- const textNode = node as Text;
129
- textParts.push(textNode.value);
130
- break;
131
- }
132
-
133
- case "inlineCode": {
134
- const codeNode = node as InlineCode;
135
- // Skip short code, read longer code
136
- if (codeNode.value.length > 10) {
137
- textParts.push(codeNode.value);
138
- }
60
+ textParts.push((node as Text).value);
139
61
  break;
140
62
  }
141
63
 
64
+ // Inline code and code blocks are skipped by the rehype word-wrapper
65
+ // (pre/code in its skip set), so they must not contribute speech tokens.
66
+ case "inlineCode":
142
67
  case "code": {
143
- const blockCode = node as Code;
144
- // Skip code blocks entirely for TTS
145
- // Could optionally add language hint: "Code block in {lang}"
146
- if (blockCode.lang) {
147
- textParts.push(`[Code in ${blockCode.lang}]`);
148
- }
149
68
  break;
150
69
  }
151
70
 
152
71
  case "heading": {
153
72
  const heading = node as Heading;
154
- // Add single # marker for synthesis chunking (backend expects single # for all heading levels)
73
+ // Single "#" chunk marker for all heading levels (synthesis backend
74
+ // expects it). Removed by stripForAlignment, so not an alignment token.
155
75
  textParts.push("\n# ");
156
- // Process children
157
- for (const child of heading.children) {
158
- processNode(child as Content);
159
- }
160
- // Add newline after headings for separation
76
+ processChildren(heading);
161
77
  textParts.push("\n");
162
78
  break;
163
79
  }
164
80
 
165
81
  case "paragraph": {
166
- const para = node as { children: Content[] };
167
- for (const child of para.children) {
168
- processNode(child);
169
- }
170
- // Paragraph break
82
+ processChildren(node as { children: Content[] });
171
83
  textParts.push("\n");
172
84
  break;
173
85
  }
174
86
 
175
87
  case "emphasis": {
176
- const em = node as Emphasis;
177
- for (const child of em.children) {
178
- processNode(child as Content);
179
- }
88
+ processChildren(node as Emphasis);
180
89
  break;
181
90
  }
182
91
 
183
92
  case "strong": {
184
- const strong = node as Strong;
185
- for (const child of strong.children) {
186
- processNode(child as Content);
187
- }
93
+ processChildren(node as Strong);
188
94
  break;
189
95
  }
190
96
 
191
97
  case "link": {
192
- const link = node as { children: Content[] };
193
- // Only read link text, not URL
194
- for (const child of link.children) {
195
- processNode(child);
196
- }
98
+ // Read link text only, not the URL (matches rehype: <a> text is walked).
99
+ processChildren(node as { children: Content[] });
197
100
  break;
198
101
  }
199
102
 
103
+ // Images are skipped by the rehype word-wrapper (img in its skip set);
104
+ // alt text is an attribute, not a rendered text node — emit nothing.
200
105
  case "image": {
201
- const img = node as { alt?: string };
202
- // Read alt text
203
- if (img.alt) {
204
- textParts.push(`Image: ${img.alt}`);
205
- }
206
106
  break;
207
107
  }
208
108
 
209
109
  case "list": {
210
- const list = node as { children: Content[] };
211
- for (const child of list.children) {
212
- processNode(child);
213
- }
110
+ processChildren(node as { children: Content[] });
214
111
  break;
215
112
  }
216
113
 
217
114
  case "listItem": {
218
- const listItem = node as { children: Content[] };
219
- for (const child of listItem.children) {
220
- processNode(child);
221
- }
115
+ processChildren(node as { children: Content[] });
116
+ // Sentence break for TTS prosody; punctuation only, not an alignment token.
222
117
  textParts.push(". ");
223
118
  break;
224
119
  }
225
120
 
226
121
  case "blockquote": {
227
- const quote = node as { children: Content[] };
228
- textParts.push("Quote: ");
229
- for (const child of quote.children) {
230
- processNode(child);
231
- }
232
- textParts.push(" End quote.");
122
+ // Just the quote's text — no "Quote:"/"End quote." wrappers (those
123
+ // words have no rendered-DOM counterpart and would desync data-i).
124
+ processChildren(node as { children: Content[] });
125
+ textParts.push("\n");
233
126
  break;
234
127
  }
235
128
 
236
- // Math nodes from remark-math
237
129
  case "math": {
238
130
  const mathNode = node as { value: string };
239
- if (latexConverter) {
240
- textParts.push(latexConverter.convert(mathNode.value, true));
241
- } else {
242
- textParts.push(`[Math: ${mathNode.value.slice(0, 30)}]`);
131
+ if (mathConfig.enabled) {
132
+ textParts.push(recordMath(mathNode.value, true));
243
133
  }
244
134
  break;
245
135
  }
246
136
 
247
137
  case "inlineMath": {
248
138
  const inlineMathNode = node as { value: string };
249
- if (latexConverter) {
250
- textParts.push(latexConverter.convert(inlineMathNode.value, false));
251
- } else {
252
- textParts.push(inlineMathNode.value);
139
+ if (mathConfig.enabled) {
140
+ textParts.push(recordMath(inlineMathNode.value, false));
253
141
  }
254
142
  break;
255
143
  }
@@ -259,51 +147,46 @@ export async function buildSpeechDocument(
259
147
  break;
260
148
  }
261
149
 
262
- // Handle container nodes with children
263
150
  case "root": {
264
- const root = node as Root;
265
- for (const child of root.children) {
266
- processNode(child);
267
- }
151
+ processChildren(node as Root);
268
152
  break;
269
153
  }
270
154
 
271
155
  default: {
272
- // Try to process children if they exist
273
156
  const maybeParent = node as { children?: Content[] };
274
- if (maybeParent.children) {
275
- for (const child of maybeParent.children) {
276
- processNode(child);
277
- }
278
- }
157
+ if (maybeParent.children) processChildren(maybeParent as { children: Content[] });
279
158
  }
280
159
  }
281
160
  }
282
161
 
283
162
  processNode(tree);
284
163
 
285
- // Resolve all promises in textParts (for async math conversion)
164
+ // Resolve async math conversions.
286
165
  const resolvedParts = await Promise.all(textParts);
287
166
 
288
- // Clean up and normalize text
289
- const text = resolvedParts
167
+ // Normalize whitespace. The title is intentionally excluded so the
168
+ // alignment data matches the article body only.
169
+ const plainText = resolvedParts
290
170
  .join(" ")
291
- .replace(/\s+/g, " ") // Normalize whitespace
292
- .replace(/\n\s*\n/g, "\n\n") // Preserve paragraph breaks
293
- .replace(/\s*\.\s*\./g, ".") // Clean up double periods
171
+ .replace(/[ \t]+/g, " ")
172
+ .replace(/\n\s*\n/g, "\n\n")
173
+ .replace(/\s*\.\s*\./g, ".")
294
174
  .trim();
295
175
 
296
- // Note: We intentionally do NOT include the title in the speech text.
297
- // The title is displayed visually and doesn't need to be in the audio.
298
- // This also ensures alignment data matches the article body content.
176
+ const { speechtext, normalisedSpeechtext } = buildSpeechtextPair(plainText);
299
177
 
300
- // Compute hash for change detection
301
- const hash = computeHash(text);
178
+ // Map each math expression's latex key to its resolved spoken form.
179
+ const resolvedMath = await Promise.all(mathPromises);
180
+ const mathSpeech: Record<string, string> = {};
181
+ for (let i = 0; i < mathKeys.length; i++) {
182
+ mathSpeech[mathKeys[i]] = resolvedMath[i];
183
+ }
302
184
 
303
185
  return {
304
186
  slug: item.slug,
305
- text,
306
- hash,
187
+ speechtext,
188
+ normalisedSpeechtext,
189
+ mathSpeech,
307
190
  source: item.filePath,
308
191
  };
309
192
  }
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Spoken-form normalization primitives.
3
+ *
4
+ * Ported from the Valeon blog's audio pipeline so the plugin's
5
+ * build-time tokenization reproduces VocaSync's alignment token stream
6
+ * exactly. Two transforms:
7
+ *
8
+ * expandSpokenForms(text) — expands currencies, numbers, percentages
9
+ * into spoken word equivalents. Preserves
10
+ * punctuation/casing so it reads naturally
11
+ * for TTS. This is the `speechtext` POSTed
12
+ * to synthesis.
13
+ *
14
+ * stripForAlignment(text) — derives the alignment-friendly form:
15
+ * lowercase, punctuation removed, whitespace
16
+ * collapsed, contractions preserved. This is
17
+ * the `normalisedSpeechtext` POSTed as the
18
+ * alignment transcript AND the basis for the
19
+ * rehype plugin's `data-i`/`data-n` indices.
20
+ *
21
+ * Because the alignment transcript IS `stripForAlignment(expandSpokenForms(text))`,
22
+ * the worker's own normalizer is a no-op over it and word indices line up
23
+ * token-for-token with the rehype output.
24
+ */
25
+
26
+ const CURRENCY_SYMBOL_WORDS: Record<string, string> = {
27
+ "£": "pound",
28
+ $: "dollar",
29
+ "€": "euro",
30
+ "¥": "yen",
31
+ "₹": "rupee",
32
+ "₽": "ruble",
33
+ "₩": "won",
34
+ "₪": "shekel",
35
+ "₺": "lira",
36
+ "฿": "baht",
37
+ "₫": "dong",
38
+ "₴": "hryvnia",
39
+ "₦": "naira",
40
+ "₱": "peso",
41
+ "₲": "guarani",
42
+ "₡": "colon",
43
+ "₭": "kip",
44
+ "₮": "tugrik",
45
+ "₿": "bitcoin",
46
+ "₣": "franc",
47
+ "¢": "cent",
48
+ "₤": "lira",
49
+ };
50
+
51
+ const CURRENCY_SYMBOL_LIST = Object.keys(CURRENCY_SYMBOL_WORDS);
52
+ const CURRENCY_SYMBOL_CLASS = CURRENCY_SYMBOL_LIST.join("");
53
+ const CURRENCY_SYMBOL_RANGE = `[${CURRENCY_SYMBOL_CLASS}]`;
54
+ const CURRENCY_SYMBOL_BEFORE_NUMBER_REGEX = new RegExp(
55
+ `(${CURRENCY_SYMBOL_RANGE})\\s*([0-9]+(?:[.,][0-9]+)*)`,
56
+ "gu"
57
+ );
58
+ const CURRENCY_SYMBOL_AFTER_NUMBER_REGEX = new RegExp(
59
+ `([0-9]+(?:[.,][0-9]+)*)\\s*(${CURRENCY_SYMBOL_RANGE})`,
60
+ "gu"
61
+ );
62
+ const CURRENCY_SYMBOL_REGEX = new RegExp(CURRENCY_SYMBOL_RANGE, "gu");
63
+
64
+ const DIGIT_WORDS = [
65
+ "zero",
66
+ "one",
67
+ "two",
68
+ "three",
69
+ "four",
70
+ "five",
71
+ "six",
72
+ "seven",
73
+ "eight",
74
+ "nine",
75
+ ];
76
+
77
+ const SMALL_WORDS = [
78
+ "zero",
79
+ "one",
80
+ "two",
81
+ "three",
82
+ "four",
83
+ "five",
84
+ "six",
85
+ "seven",
86
+ "eight",
87
+ "nine",
88
+ "ten",
89
+ "eleven",
90
+ "twelve",
91
+ "thirteen",
92
+ "fourteen",
93
+ "fifteen",
94
+ "sixteen",
95
+ "seventeen",
96
+ "eighteen",
97
+ "nineteen",
98
+ ];
99
+
100
+ const TENS_WORDS = [
101
+ "",
102
+ "",
103
+ "twenty",
104
+ "thirty",
105
+ "forty",
106
+ "fifty",
107
+ "sixty",
108
+ "seventy",
109
+ "eighty",
110
+ "ninety",
111
+ ];
112
+
113
+ const SCALE_WORDS = [
114
+ "",
115
+ "thousand",
116
+ "million",
117
+ "billion",
118
+ "trillion",
119
+ "quadrillion",
120
+ "quintillion",
121
+ "sextillion",
122
+ ];
123
+
124
+ function threeDigitWords(value: number): string {
125
+ const parts: string[] = [];
126
+ let v = value;
127
+ if (v >= 100) {
128
+ parts.push(SMALL_WORDS[Math.floor(v / 100)]);
129
+ parts.push("hundred");
130
+ v %= 100;
131
+ }
132
+ if (v >= 20) {
133
+ parts.push(TENS_WORDS[Math.floor(v / 10)]);
134
+ v %= 10;
135
+ if (v > 0) parts.push(SMALL_WORDS[v]);
136
+ } else if (v > 0 || parts.length === 0) {
137
+ parts.push(SMALL_WORDS[v]);
138
+ }
139
+ return parts.join(" ").trim();
140
+ }
141
+
142
+ const BIG_ZERO = BigInt(0);
143
+ const BIG_THOUSAND = BigInt(1000);
144
+
145
+ function integerToWords(value: bigint): string {
146
+ if (value === BIG_ZERO) return "zero";
147
+ const parts: string[] = [];
148
+ let remaining = value;
149
+ let scale = 0;
150
+ while (remaining > BIG_ZERO) {
151
+ const chunk = Number(remaining % BIG_THOUSAND);
152
+ if (chunk > 0) {
153
+ const words = threeDigitWords(chunk);
154
+ const scaleWord = SCALE_WORDS[scale];
155
+ parts.unshift(scaleWord ? `${words} ${scaleWord}`.trim() : words);
156
+ }
157
+ remaining /= BIG_THOUSAND;
158
+ scale += 1;
159
+ }
160
+ return parts.join(" ").trim();
161
+ }
162
+
163
+ function expandNumberToken(token: string): string {
164
+ let working = token;
165
+ const result: string[] = [];
166
+ let negative = false;
167
+ if (working.startsWith("-")) {
168
+ negative = true;
169
+ working = working.slice(1);
170
+ }
171
+ if (!working) working = "0";
172
+ const [intPart, decPart] = working.split(".");
173
+ const integerValue = intPart ? BigInt(intPart) : BIG_ZERO;
174
+ const integerWords = integerToWords(integerValue);
175
+ if (negative) result.push("minus");
176
+ result.push(integerWords);
177
+ if (decPart) {
178
+ result.push("point");
179
+ for (const digit of decPart) {
180
+ const value = Number(digit);
181
+ if (!Number.isNaN(value) && value >= 0 && value <= 9) {
182
+ result.push(DIGIT_WORDS[value]);
183
+ }
184
+ }
185
+ }
186
+ return result.join(" ");
187
+ }
188
+
189
+ function expandNumbers(input: string): string {
190
+ return input.replace(/-?\d+(\.\d+)?/g, expandNumberToken);
191
+ }
192
+
193
+ function expandCurrencySymbols(input: string): string {
194
+ let text = input.replace(CURRENCY_SYMBOL_BEFORE_NUMBER_REGEX, (_, symbol, digits) => {
195
+ const word = CURRENCY_SYMBOL_WORDS[symbol];
196
+ return word ? `${digits} ${word}` : `${symbol}${digits}`;
197
+ });
198
+ text = text.replace(CURRENCY_SYMBOL_AFTER_NUMBER_REGEX, (_, digits, symbol) => {
199
+ const word = CURRENCY_SYMBOL_WORDS[symbol];
200
+ return word ? `${digits} ${word}` : `${digits}${symbol}`;
201
+ });
202
+ return text.replace(CURRENCY_SYMBOL_REGEX, (symbol) => {
203
+ const word = CURRENCY_SYMBOL_WORDS[symbol];
204
+ return word ? ` ${word} ` : " ";
205
+ });
206
+ }
207
+
208
+ function expandPercents(input: string): string {
209
+ // Match number-followed-by-% (with optional space). "50%" -> "50 percent".
210
+ // Runs before number expansion so the digits still parse cleanly.
211
+ return input.replace(/([0-9]+(?:\.[0-9]+)?)\s*%/g, "$1 percent");
212
+ }
213
+
214
+ /**
215
+ * Expand currency symbols, numbers, and percentages into their spoken
216
+ * word forms. Preserves punctuation and surrounding text — this is the
217
+ * surface that becomes `speechtext`.
218
+ */
219
+ export function expandSpokenForms(input: string): string {
220
+ let text = input.normalize("NFKC");
221
+ text = expandPercents(text);
222
+ text = expandCurrencySymbols(text);
223
+ text = text.replace(/(?<=\d),(?=\d)/g, "");
224
+ text = expandNumbers(text);
225
+ // Collapse any double-spaces introduced by symbol expansion.
226
+ return text.replace(/[ \t]+/g, " ");
227
+ }
228
+
229
+ /**
230
+ * Strip a speechtext-form string into the alignment form: lowercase,
231
+ * punctuation removed, whitespace collapsed. Contractions are preserved
232
+ * (e.g. "don't" stays one token).
233
+ */
234
+ export function stripForAlignment(input: string): string {
235
+ let text = input.normalize("NFKC");
236
+ // Strip control (C0/C1) + DEL, then zero-width / BiDi formatting chars.
237
+ // Code-point filtering avoids embedding raw control bytes in a regex literal.
238
+ text = Array.from(text)
239
+ .map((ch) => {
240
+ const c = ch.codePointAt(0) ?? 0;
241
+ if (c <= 0x1f || (c >= 0x7f && c <= 0x9f)) return " ";
242
+ if (c === 0xa0) return " ";
243
+ if (
244
+ (c >= 0x200b && c <= 0x200f) ||
245
+ (c >= 0x202a && c <= 0x202e) ||
246
+ (c >= 0x2060 && c <= 0x2064)
247
+ ) {
248
+ return "";
249
+ }
250
+ return ch;
251
+ })
252
+ .join("");
253
+ // Quote / dash normalisation.
254
+ text = text.replace(/[“”„‟]/g, '"');
255
+ text = text.replace(/[‘’‚‛]/g, "'");
256
+ text = text.replace(/…/g, " ");
257
+ text = text.replace(/[-‐‑⁃–—−]/g, " ");
258
+ // Strip emoji + URLs + emails + handles before the catch-all punctuation pass.
259
+ text = text.replace(/\p{Extended_Pictographic}/gu, " ");
260
+ text = text.replace(/https?:\/\/\S+/gi, " ");
261
+ text = text.replace(/\bwww\.[^\s/]+\b/gi, " ");
262
+ text = text.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/gi, " ");
263
+ text = text.replace(/@\w+/g, " ");
264
+ // NFKD-then-strip-marks to drop combining diacritics.
265
+ text = text.normalize("NFKD").replace(/\p{M}/gu, "").normalize("NFKC");
266
+ // Strip stray apostrophes that aren't part of a contraction.
267
+ text = text.replace(/(^|[^A-Za-z0-9])'(?=[^A-Za-z0-9]|$)/g, "$1");
268
+ text = text.replace(/(^|[^A-Za-z0-9])'(?=[A-Za-z0-9])/g, "$1");
269
+ // Everything that's not a contraction-letter, digit, or whitespace -> space.
270
+ text = text.replace(/[^A-Za-z0-9'\s]/g, " ");
271
+ text = text.replace(/\s+/g, " ").trim();
272
+ return text.toLowerCase();
273
+ }
274
+
275
+ /**
276
+ * Produce both the speechtext (POSTed to synthesis) and
277
+ * normalisedSpeechtext (POSTed as the alignment transcript) forms from a
278
+ * single plain-text input.
279
+ */
280
+ export function buildSpeechtextPair(plainText: string): {
281
+ speechtext: string;
282
+ normalisedSpeechtext: string;
283
+ } {
284
+ const speechtext = expandSpokenForms(plainText);
285
+ const normalisedSpeechtext = stripForAlignment(speechtext);
286
+ return { speechtext, normalisedSpeechtext };
287
+ }
288
+
289
+ /**
290
+ * How many alignment tokens a visible string expands to. Used by the
291
+ * rehype plugin to compute `data-n` for each wrapped word / math unit.
292
+ * "$50" -> 2 ("fifty dollar"); "1995" -> 6; unambiguous words -> 1.
293
+ */
294
+ export function spokenTokenCount(visible: string): number {
295
+ const normalised = stripForAlignment(expandSpokenForms(visible));
296
+ if (!normalised) return 0;
297
+ return normalised.split(/\s+/).filter(Boolean).length;
298
+ }