@vocasync/astro 0.1.10 → 1.0.1

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 (76) 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 +141 -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 +72 -116
  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.map +1 -1
  27. package/dist/lib/latex-to-speech/index.js +9 -11
  28. package/dist/lib/latex-to-speech/index.js.map +1 -1
  29. package/dist/lib/latex-to-speech/speak.d.ts +7 -2
  30. package/dist/lib/latex-to-speech/speak.d.ts.map +1 -1
  31. package/dist/lib/latex-to-speech/speak.js +10 -27
  32. package/dist/lib/latex-to-speech/speak.js.map +1 -1
  33. package/dist/rehype/audio-words.d.ts +14 -24
  34. package/dist/rehype/audio-words.d.ts.map +1 -1
  35. package/dist/rehype/audio-words.js +131 -252
  36. package/dist/rehype/audio-words.js.map +1 -1
  37. package/dist/rehype/index.d.ts +1 -2
  38. package/dist/rehype/index.d.ts.map +1 -1
  39. package/dist/rehype/index.js +0 -1
  40. package/dist/rehype/index.js.map +1 -1
  41. package/dist/rehype/rehype-math-speech.d.ts +26 -10
  42. package/dist/rehype/rehype-math-speech.d.ts.map +1 -1
  43. package/dist/rehype/rehype-math-speech.js +59 -43
  44. package/dist/rehype/rehype-math-speech.js.map +1 -1
  45. package/dist/rehype/shared.d.ts +9 -0
  46. package/dist/rehype/shared.d.ts.map +1 -0
  47. package/dist/rehype/shared.js +31 -0
  48. package/dist/rehype/shared.js.map +1 -0
  49. package/dist/sync/orchestrator.d.ts +4 -22
  50. package/dist/sync/orchestrator.d.ts.map +1 -1
  51. package/dist/sync/orchestrator.js +123 -123
  52. package/dist/sync/orchestrator.js.map +1 -1
  53. package/dist/types/index.d.ts +82 -46
  54. package/dist/types/index.d.ts.map +1 -1
  55. package/package.json +14 -11
  56. package/src/api/client.ts +175 -190
  57. package/src/api/index.ts +8 -1
  58. package/src/cli.ts +7 -14
  59. package/src/components/AudioPlayer.astro +141 -137
  60. package/src/config/schema.ts +15 -4
  61. package/src/core/audio-map.ts +1 -1
  62. package/src/core/speech-builder.ts +74 -130
  63. package/src/core/spoken-form.ts +298 -0
  64. package/src/lib/latex-to-speech/index.ts +8 -9
  65. package/src/lib/latex-to-speech/speak.ts +11 -34
  66. package/src/rehype/audio-words.ts +145 -307
  67. package/src/rehype/index.ts +1 -2
  68. package/src/rehype/rehype-math-speech.ts +64 -59
  69. package/src/rehype/shared.ts +36 -0
  70. package/src/sync/orchestrator.ts +150 -157
  71. package/src/types/index.ts +85 -47
  72. package/dist/rehype/remark-math-speech.d.ts +0 -14
  73. package/dist/rehype/remark-math-speech.d.ts.map +0 -1
  74. package/dist/rehype/remark-math-speech.js +0 -27
  75. package/dist/rehype/remark-math-speech.js.map +0 -1
  76. package/src/rehype/remark-math-speech.ts +0 -32
@@ -1,41 +1,22 @@
1
- import type { LaTeXExpression, SREOptions } from "./index.js";
2
-
3
- let latexToSpeech: ((exprs: LaTeXExpression[], options?: SREOptions) => Promise<string[]>) | null =
4
- null;
5
- let loadAttempted = false;
6
- let warnedFailure = false;
1
+ import { latexToSpeech } from "./index.js";
7
2
 
8
3
  const cache = new Map<string, Promise<string>>();
4
+ let warnedFailure = false;
9
5
 
10
6
  function normalizeWhitespace(value = ""): string {
11
7
  return value.replace(/\r/g, "").replace(/\s+/g, " ").trim();
12
8
  }
13
9
 
14
- /**
15
- * Lazily load the latex-to-speech module.
16
- * Returns false if optional peer dependencies are not installed.
17
- */
18
- async function ensureLoaded(): Promise<boolean> {
19
- if (loadAttempted) return latexToSpeech !== null;
20
- loadAttempted = true;
21
- try {
22
- const mod = await import("./index.js");
23
- latexToSpeech = mod.latexToSpeech || mod.default;
24
- return latexToSpeech !== null;
25
- } catch {
26
- console.warn(
27
- "[vocasync] Math-to-speech initialization failed. Install optional dependencies:",
28
- "\n npm install speech-rule-engine mathjax-full"
29
- );
30
- return false;
31
- }
32
- }
33
-
34
10
  /**
35
11
  * Convert a LaTeX expression to spoken text.
36
12
  *
37
- * Handles lazy loading, caching, normalization, and error recovery.
38
- * Cache key includes style and display mode for correctness.
13
+ * `latexToSpeech` is imported statically (it lazy-loads the optional
14
+ * speech-rule-engine / mathjax-full deps internally), which is robust under
15
+ * Astro's Vite SSR loader where a lazy `import()` of this module returned a
16
+ * namespace without the expected named export.
17
+ *
18
+ * Falls back to the raw LaTeX if the math dependencies are unavailable or
19
+ * conversion fails, so a build never crashes on math content.
39
20
  */
40
21
  export async function speakLatex(
41
22
  latex: string,
@@ -45,22 +26,18 @@ export async function speakLatex(
45
26
  const trimmed = String(latex ?? "").trim();
46
27
  if (!trimmed) return "";
47
28
 
48
- if (!(await ensureLoaded())) {
49
- return trimmed; // Fallback to raw LaTeX
50
- }
51
-
52
29
  const cacheKey = `${style}:${display}:${trimmed}`;
53
30
  if (!cache.has(cacheKey)) {
54
31
  const pending = (async () => {
55
32
  try {
56
- const result = await latexToSpeech!([{ latex: trimmed, display }], {
33
+ const result = await latexToSpeech([{ latex: trimmed, display }], {
57
34
  domain: style,
58
35
  style: "default",
59
36
  locale: "en",
60
37
  modality: "speech",
61
38
  });
62
39
  const spoken = Array.isArray(result) ? result[0] : String(result ?? "");
63
- return normalizeWhitespace(spoken);
40
+ return normalizeWhitespace(spoken) || trimmed;
64
41
  } catch (error) {
65
42
  if (!warnedFailure) {
66
43
  console.warn(
@@ -1,132 +1,64 @@
1
- import { execFileSync } from "node:child_process";
2
- import { readFileSync } from "node:fs";
3
- import { resolve } from "node:path";
4
1
  import type { Element, Root, Text } from "hast";
5
2
  import type { Plugin } from "unified";
6
3
  import { visitParents } from "unist-util-visit-parents";
7
- import type { AlignedWord, AudioMap } from "../types/index.js";
4
+ import { spokenTokenCount } from "../core/spoken-form.js";
5
+ import { loadAudioMapSync, resolveSlug } from "./shared.js";
8
6
 
9
7
  /**
10
8
  * Options for the rehype audio words plugin.
11
9
  */
12
10
  export interface RehypeAudioWordsOptions {
13
11
  /**
14
- * Path to the audio map JSON file.
15
- * Can be absolute or relative to the project root.
12
+ * Path to the audio map JSON file (absolute or relative to project root).
16
13
  * @default ".vocasync/audio-map.json"
17
14
  */
18
15
  audioMapPath?: string;
19
-
20
16
  /**
21
- * CSS class prefix for generated elements.
22
- * @default "vocasync"
17
+ * CSS class for generated word spans.
18
+ * @default "vocasync" (spans get the class `${classPrefix}-word`)
23
19
  */
24
20
  classPrefix?: string;
25
-
26
21
  /**
27
- * The name of the content collection folder to extract slugs from.
22
+ * Content collection folder name used to extract slugs.
28
23
  * @default "articles"
29
24
  */
30
25
  collectionName?: string;
31
26
  }
32
27
 
33
- // Cache the loaded audio map to avoid re-reading on every file
34
- let audioMapCache: AudioMap | null = null;
35
- let audioMapCachePath: string | null = null;
36
-
37
- // Cache for fetched alignment data per slug
38
- const alignmentCache: Map<string, AlignedWord[]> = new Map();
39
-
40
- function loadAudioMapSync(audioMapPath: string): AudioMap | null {
41
- // Use cache if same path
42
- if (audioMapCache && audioMapCachePath === audioMapPath) {
43
- return audioMapCache;
44
- }
45
-
46
- try {
47
- const absolutePath = resolve(process.cwd(), audioMapPath);
48
- const content = readFileSync(absolutePath, "utf-8");
49
- audioMapCache = JSON.parse(content) as AudioMap;
50
- audioMapCachePath = audioMapPath;
51
- return audioMapCache;
52
- } catch {
53
- // File doesn't exist or is invalid - return null
54
- return null;
55
- }
56
- }
57
-
58
- /**
59
- * Fetch alignment data from URL (synchronously using a worker thread approach).
60
- * Since rehype plugins must be synchronous, we use a sync HTTP request.
61
- * @param alignmentUrl - The base alignment URL
62
- * @param slug - The content slug for caching
63
- * @param publishableKey - Optional publishable key for authentication
64
- */
65
- function fetchAlignmentSync(
66
- alignmentUrl: string,
67
- slug: string,
68
- publishableKey?: string
69
- ): AlignedWord[] | null {
70
- // Check cache first
71
- if (alignmentCache.has(slug)) {
72
- return alignmentCache.get(slug) ?? null;
73
- }
74
-
75
- try {
76
- // Build the URL with publishable key if provided
77
- let fetchUrl = alignmentUrl;
78
- if (publishableKey) {
79
- const url = new URL(alignmentUrl);
80
- url.searchParams.set("pk", publishableKey);
81
- fetchUrl = url.toString();
82
- }
83
-
84
- // Use execFileSync with curl to make a synchronous HTTP request
85
- // execFileSync avoids shell invocation, preventing command injection
86
- // Note: -L flag follows redirects (required for vocasync.io signed URLs)
87
- const result = execFileSync("curl", ["-sL", fetchUrl], {
88
- encoding: "utf-8",
89
- timeout: 30000,
90
- });
91
-
92
- const data = JSON.parse(result);
93
-
94
- // The alignment response contains a words array
95
- const words = data.words as AlignedWord[] | undefined;
96
- if (words && Array.isArray(words)) {
97
- alignmentCache.set(slug, words);
98
- return words;
99
- }
100
-
101
- return null;
102
- } catch {
103
- // Failed to fetch - return null
104
- return null;
105
- }
106
- }
28
+ // Matches a visible "word": letters/digits/currency/percent, with intra-word
29
+ // apostrophes. Currency (\p{Sc}) and % are kept attached to their number so
30
+ // "$50" and "50%" stay single tokens whose spokenTokenCount matches the
31
+ // transcript ("fifty dollar", "fifty percent"). Comma-grouped numbers
32
+ // (e.g. "1,000,000") are a known limitation — author numbers without commas.
33
+ const WORD_PATTERN = /[\p{L}\p{N}\p{Sc}%]+(?:['’][\p{L}\p{N}\p{Sc}%]+)*/gu;
34
+
35
+ const SKIP_TAGS = new Set([
36
+ "pre",
37
+ "code",
38
+ "script",
39
+ "style",
40
+ "textarea",
41
+ "svg",
42
+ "math",
43
+ "mjx-container",
44
+ "img",
45
+ "figcaption",
46
+ ]);
47
+ const SKIP_CLASSES = new Set(["katex", "katex-mathml", "katex-html"]);
107
48
 
108
49
  /**
109
- * Rehype plugin that wraps words with timing spans for audio sync.
110
- *
111
- * For each text node in the document, this plugin:
112
- * 1. Tokenizes the text into words
113
- * 2. Matches words against alignment data
114
- * 3. Wraps matched words in <span> elements with data-start and data-end attributes
50
+ * Rehype plugin that wraps each visible word in
51
+ * `<span class="vocasync-word" data-i="N" data-n="K">…</span>`:
115
52
  *
116
- * @example
117
- * ```typescript
118
- * // astro.config.mjs
119
- * import { defineConfig } from "astro/config";
120
- * import { rehypeAudioWords } from "@vocasync/astro/rehype";
53
+ * data-i = the word's starting index in the alignment word stream
54
+ * (the normalisedSpeechtext POSTed to VocaSync).
55
+ * data-n = how many alignment tokens this visible word expands to
56
+ * (via spokenTokenCount): "$50" -> 2, "1995" -> 6, words -> 1.
121
57
  *
122
- * export default defineConfig({
123
- * markdown: {
124
- * rehypePlugins: [
125
- * [rehypeAudioWords, { collectionName: "articles" }]
126
- * ]
127
- * }
128
- * });
129
- * ```
58
+ * No alignment data is fetched here — tokenization is deterministic and runs
59
+ * the same `spokenTokenCount` used to build the transcript, so indices line
60
+ * up token-for-token. Math containers carrying `data-speech` (attached by
61
+ * rehypeMathSpeech) are wrapped as a single unit with their token count.
130
62
  */
131
63
  const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}) => {
132
64
  const {
@@ -134,229 +66,135 @@ const rehypeAudioWords: Plugin<[RehypeAudioWordsOptions?], Root> = (options = {}
134
66
  classPrefix = "vocasync",
135
67
  collectionName = "articles",
136
68
  } = options;
69
+ const wordClass = `${classPrefix}-word`;
137
70
 
138
71
  return (tree, file) => {
139
- // Load audio map (cached after first load)
140
72
  const audioMap = loadAudioMapSync(audioMapPath);
141
- if (!audioMap) {
142
- return; // No audio map available, skip processing
143
- }
144
-
145
- // Resolve slug from file path
146
- // Files are typically at paths like: /src/content/articles/hello-world.md
147
- const filePath =
148
- file.path ??
149
- (Array.isArray(file.history) ? file.history[file.history.length - 1] : undefined);
150
-
151
- if (!filePath) {
152
- return; // No file path, skip processing
153
- }
154
-
155
- // Normalize path separators
156
- const normalizedPath = filePath.replace(/\\/g, "/");
73
+ if (!audioMap) return;
74
+
75
+ const slug = resolveSlug(file, collectionName);
76
+ if (!slug || !audioMap.entries[slug]) return; // only wrap posts that have audio
77
+
78
+ let nextIndex = 0;
79
+ const replacements: Array<{
80
+ parent: Element | Root;
81
+ index: number;
82
+ nodes: (Text | Element)[];
83
+ }> = [];
84
+
85
+ visitParents(
86
+ tree,
87
+ (node) => node.type === "text" || (node.type === "element" && hasDataSpeech(node as Element)),
88
+ (node, ancestors) => {
89
+ const parent = ancestors[ancestors.length - 1] as Element | Root | undefined;
90
+ if (!parent) return;
91
+
92
+ // Math container with attached spoken form -> wrap as one unit.
93
+ if (node.type === "element") {
94
+ const speech = (node as Element).properties?.dataSpeech;
95
+ if (typeof speech !== "string" || !speech) return;
96
+ const count = spokenTokenCount(speech);
97
+ if (count === 0) return;
98
+ const index = parent.children.indexOf(node as Element);
99
+ if (index === -1) return;
100
+ replacements.push({
101
+ parent,
102
+ index,
103
+ nodes: [wrapSpan([node as Element], nextIndex, count, wordClass)],
104
+ });
105
+ nextIndex += count;
106
+ return;
107
+ }
157
108
 
158
- // Try to extract slug from collection path
159
- // Pattern: /src/content/{collectionName}/{slug}.md or .mdx
160
- const collectionPattern = new RegExp(`/content/${collectionName}/([^/]+)\\.(md|mdx)$`);
161
- const match = normalizedPath.match(collectionPattern);
109
+ // Text node -> wrap each word, skipping non-textual ancestors.
110
+ if (isSkipped(ancestors)) return;
111
+ const text = (node as Text).value;
112
+ if (!text) return;
113
+ const matches = Array.from(text.matchAll(WORD_PATTERN));
114
+ if (matches.length === 0) return;
115
+
116
+ const index = parent.children.indexOf(node as Text);
117
+ if (index === -1) return;
118
+
119
+ const out: (Text | Element)[] = [];
120
+ let cursor = 0;
121
+ for (const m of matches) {
122
+ const start = m.index ?? 0;
123
+ const end = start + m[0].length;
124
+ if (start > cursor) out.push({ type: "text", value: text.slice(cursor, start) });
125
+ const count = spokenTokenCount(m[0]);
126
+ if (count > 0) {
127
+ out.push(wrapText(m[0], nextIndex, count, wordClass));
128
+ nextIndex += count;
129
+ } else {
130
+ out.push({ type: "text", value: m[0] });
131
+ }
132
+ cursor = end;
133
+ }
134
+ if (cursor < text.length) out.push({ type: "text", value: text.slice(cursor) });
162
135
 
163
- let slug: string | undefined;
164
- if (match) {
165
- slug = match[1];
166
- } else {
167
- // Fallback: just get the filename without extension
168
- const filenameMatch = normalizedPath.match(/\/([^/]+)\.(md|mdx)$/);
169
- if (filenameMatch) {
170
- slug = filenameMatch[1];
136
+ replacements.push({ parent, index, nodes: out });
171
137
  }
172
- }
138
+ );
173
139
 
174
- if (!slug) {
175
- return; // No slug, skip processing
140
+ // Apply in reverse so earlier indices stay valid.
141
+ for (let i = replacements.length - 1; i >= 0; i--) {
142
+ const r = replacements[i];
143
+ r.parent.children.splice(r.index, 1, ...r.nodes);
176
144
  }
145
+ };
146
+ };
177
147
 
178
- // Get alignment URL for this slug from audio map
179
- const entry = audioMap.entries[slug];
180
- if (!entry?.alignmentUrl) {
181
- return; // No alignment URL, skip
182
- }
183
-
184
- // Fetch alignment words from URL with publishable key
185
- const words = fetchAlignmentSync(entry.alignmentUrl, slug, entry.publishableKey);
186
-
187
- if (!words || words.length === 0) {
188
- return; // No alignment data, skip
189
- }
190
-
191
- // Track word index as we process text nodes
192
- let wordIndex = 0;
193
-
194
- // Process all text nodes in the document
195
- visitParents(tree, "text", (node, ancestors) => {
196
- const textNode = node as Text;
197
- const parent = ancestors[ancestors.length - 1] as Element;
198
-
199
- // Skip text in code blocks, scripts, styles
200
- if (isInNonTextualElement(ancestors)) {
201
- return;
202
- }
203
-
204
- // Tokenize and match words
205
- const result = processTextNode(textNode.value, words, wordIndex, classPrefix);
206
-
207
- if (result.nodes.length === 0 || result.nodes.length === 1) {
208
- return; // No changes needed
209
- }
210
-
211
- // Update word index
212
- wordIndex = result.nextWordIndex;
213
-
214
- // Replace text node with annotated nodes
215
- const parentChildren = parent.children;
216
- const nodeIndex = parentChildren.indexOf(node);
148
+ function wrapText(word: string, dataI: number, dataN: number, wordClass: string): Element {
149
+ return {
150
+ type: "element",
151
+ tagName: "span",
152
+ properties: {
153
+ className: [wordClass],
154
+ "data-i": String(dataI),
155
+ "data-n": String(dataN),
156
+ },
157
+ children: [{ type: "text", value: word }],
158
+ };
159
+ }
217
160
 
218
- if (nodeIndex !== -1) {
219
- parentChildren.splice(nodeIndex, 1, ...result.nodes);
220
- }
221
- });
161
+ function wrapSpan(
162
+ children: (Text | Element)[],
163
+ dataI: number,
164
+ dataN: number,
165
+ wordClass: string
166
+ ): Element {
167
+ return {
168
+ type: "element",
169
+ tagName: "span",
170
+ properties: {
171
+ className: [wordClass],
172
+ "data-i": String(dataI),
173
+ "data-n": String(dataN),
174
+ },
175
+ children,
222
176
  };
223
- };
177
+ }
224
178
 
225
- /**
226
- * Check if ancestors include non-textual elements (code, script, style, KaTeX).
227
- */
228
- function isInNonTextualElement(ancestors: (Root | Element)[]): boolean {
229
- const nonTextualTags = new Set(["code", "pre", "script", "style", "svg", "math"]);
230
- const nonTextualClasses = new Set(["katex", "katex-mathml", "katex-html", "mjx-container"]);
179
+ function hasDataSpeech(node: Element): boolean {
180
+ const props = node.properties ?? {};
181
+ return typeof props.dataSpeech === "string" && props.dataSpeech.length > 0;
182
+ }
231
183
 
184
+ function isSkipped(ancestors: (Root | Element)[]): boolean {
232
185
  for (const ancestor of ancestors) {
233
- if ("tagName" in ancestor && nonTextualTags.has(ancestor.tagName)) {
234
- return true;
235
- }
236
- // Check for KaTeX/MathJax class names
237
- if ("properties" in ancestor && ancestor.properties?.className) {
238
- const classes = Array.isArray(ancestor.properties.className)
239
- ? ancestor.properties.className
240
- : [ancestor.properties.className];
186
+ if (!("tagName" in ancestor)) continue;
187
+ if (SKIP_TAGS.has(ancestor.tagName)) return true;
188
+ const className = ancestor.properties?.className;
189
+ if (className) {
190
+ const classes = Array.isArray(className) ? className : [className];
241
191
  for (const cls of classes) {
242
- if (typeof cls === "string" && nonTextualClasses.has(cls)) {
243
- return true;
244
- }
192
+ if (typeof cls === "string" && SKIP_CLASSES.has(cls)) return true;
245
193
  }
246
194
  }
247
195
  }
248
196
  return false;
249
197
  }
250
198
 
251
- /**
252
- * Process a text node and create annotated nodes.
253
- */
254
- function processTextNode(
255
- text: string,
256
- words: AlignedWord[],
257
- startIndex: number,
258
- classPrefix: string
259
- ): {
260
- nodes: (Text | Element)[];
261
- nextWordIndex: number;
262
- } {
263
- const nodes: (Text | Element)[] = [];
264
- let wordIndex = startIndex;
265
- let lastEnd = 0;
266
-
267
- // Regex to match words (similar to word boundaries)
268
- const wordPattern = /[\p{L}\p{N}'']+/gu;
269
- let match: RegExpExecArray | null;
270
-
271
- // biome-ignore lint/suspicious/noAssignInExpressions: regex exec loop requires assignment in condition
272
- while ((match = wordPattern.exec(text)) !== null) {
273
- const word = match[0];
274
- const start = match.index;
275
-
276
- // Add text before this word
277
- if (start > lastEnd) {
278
- nodes.push({
279
- type: "text",
280
- value: text.slice(lastEnd, start),
281
- });
282
- }
283
-
284
- // Try to match with alignment data - look ahead if needed
285
- const normalizedWord = normalizeWord(word);
286
- let matchedIndex = -1;
287
- let matchedAligned: AlignedWord | null = null;
288
-
289
- // Search forward from current index to find matching word
290
- // Look ahead up to 10 words to handle minor ordering differences
291
- const maxLookahead = 10;
292
- for (let i = wordIndex; i < Math.min(wordIndex + maxLookahead, words.length); i++) {
293
- const candidate = words[i];
294
- if (normalizeWord(candidate.word) === normalizedWord) {
295
- matchedIndex = i;
296
- matchedAligned = candidate;
297
- break;
298
- }
299
- }
300
-
301
- if (matchedAligned && matchedIndex !== -1) {
302
- // Create annotated span
303
- nodes.push({
304
- type: "element",
305
- tagName: "span",
306
- properties: {
307
- className: [`${classPrefix}-word`],
308
- "data-word-index": matchedIndex,
309
- "data-start": matchedAligned.start.toFixed(3),
310
- "data-end": matchedAligned.end.toFixed(3),
311
- },
312
- children: [{ type: "text", value: word }],
313
- });
314
- wordIndex = matchedIndex + 1;
315
- } else {
316
- // No match, just add as text
317
- nodes.push({
318
- type: "text",
319
- value: word,
320
- });
321
- }
322
-
323
- lastEnd = start + word.length;
324
- }
325
-
326
- // Add remaining text
327
- if (lastEnd < text.length) {
328
- nodes.push({
329
- type: "text",
330
- value: text.slice(lastEnd),
331
- });
332
- }
333
-
334
- // Merge adjacent text nodes
335
- const merged: (Text | Element)[] = [];
336
- for (const node of nodes) {
337
- const last = merged[merged.length - 1];
338
- if (node.type === "text" && last?.type === "text") {
339
- last.value += node.value;
340
- } else {
341
- merged.push(node);
342
- }
343
- }
344
-
345
- return {
346
- nodes: merged,
347
- nextWordIndex: wordIndex,
348
- };
349
- }
350
-
351
- /**
352
- * Normalize a word for comparison (lowercase, remove punctuation).
353
- */
354
- function normalizeWord(word: string): string {
355
- return word
356
- .toLowerCase()
357
- .replace(/[^\p{L}\p{N}]/gu, "")
358
- .trim();
359
- }
360
-
361
199
  export default rehypeAudioWords;
362
200
  export { rehypeAudioWords };
@@ -2,5 +2,4 @@ export { default, rehypeAudioWords } from "./audio-words.js";
2
2
  export type { RehypeAudioWordsOptions } from "./audio-words.js";
3
3
 
4
4
  export { default as rehypeMathSpeech } from "./rehype-math-speech.js";
5
- export { default as remarkMathSpeech } from "./remark-math-speech.js";
6
- export type { MathSpeechEntry } from "./remark-math-speech.js";
5
+ export type { RehypeMathSpeechOptions } from "./rehype-math-speech.js";