@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,86 +1,91 @@
1
1
  import type { Element, Parent, Root } from "hast";
2
2
  import { visitParents } from "unist-util-visit-parents";
3
- import type { VFile } from "vfile";
4
- import { speakLatex } from "../lib/latex-to-speech/speak.js";
5
- import type { MathSpeechEntry } from "./remark-math-speech.js";
3
+ import { loadAudioMapSync, resolveSlug } from "./shared.js";
6
4
 
7
- const SR_SPEECH_CLASS = "vocasync-math-speech";
8
-
9
- interface RehypeMathSpeechOptions {
5
+ export interface RehypeMathSpeechOptions {
6
+ /**
7
+ * Path to the audio map JSON file (absolute or relative to project root).
8
+ * @default ".vocasync/audio-map.json"
9
+ */
10
+ audioMapPath?: string;
10
11
  /**
11
- * SRE domain style for math-to-speech conversion
12
- * @default "clearspeak"
12
+ * Content collection folder name used to extract slugs.
13
+ * @default "articles"
13
14
  */
14
- style?: "clearspeak" | "mathspeak";
15
+ collectionName?: string;
15
16
  }
16
17
 
17
18
  /**
18
- * Rehype plugin that injects hidden spoken text next to math elements.
19
- * This allows rehypeAudioWords to wrap the spoken words with timing data.
19
+ * Rehype plugin that attaches each math expression's spoken form as a
20
+ * `data-speech` attribute, so rehypeAudioWords can wrap the whole expression
21
+ * as one highlight unit whose `data-n` is the spoken token count.
20
22
  *
21
- * Must run AFTER rehype-katex or rehype-mathjax, and BEFORE rehypeAudioWords.
23
+ * The spoken forms are read from the audio map (where `vocasync sync` stored
24
+ * them, keyed by latex) — math-to-speech runs only in the CLI, never here.
25
+ * This guarantees the math tokens match what was synthesized AND avoids
26
+ * running the math engines inside Astro's Vite build.
27
+ *
28
+ * Reads the LaTeX from the `code.math-inline` / `code.math-display` elements
29
+ * that `remark-math` produces and wraps each in
30
+ * `<span class="vocasync-math" data-speech="…">`. MUST run BEFORE
31
+ * rehype-mathjax / rehype-katex (which replace the inner element) and before
32
+ * rehypeAudioWords.
22
33
  */
23
34
  export default function rehypeMathSpeech(options: RehypeMathSpeechOptions = {}) {
24
- const { style = "clearspeak" } = options;
35
+ const { audioMapPath = ".vocasync/audio-map.json", collectionName = "articles" } = options;
25
36
 
26
- return async function transformer(tree: Root, file: VFile) {
27
- const mathSpeech = file.data.mathSpeech as MathSpeechEntry[] | undefined;
28
- if (!mathSpeech?.length) return;
37
+ return function transformer(tree: Root, file: { path?: string; history?: string[] }) {
38
+ const audioMap = loadAudioMapSync(audioMapPath);
39
+ if (!audioMap) return;
40
+ const slug = resolveSlug(file, collectionName);
41
+ if (!slug) return;
42
+ const mathSpeech = audioMap.entries[slug]?.mathSpeech;
43
+ if (!mathSpeech) return;
29
44
 
30
- // Find all MathJax/KaTeX container elements
31
- const occurrences: Array<{ node: Element; parent: Parent }> = [];
45
+ const targets: Array<{ node: Element; parent: Parent; display: boolean }> = [];
32
46
  visitParents(tree, "element", (node, ancestors) => {
33
- // MathJax uses mjx-container, KaTeX uses .katex class
34
- const isMathJax = node.tagName === "mjx-container";
35
- const isKatex =
36
- node.tagName === "span" &&
37
- Array.isArray(node.properties?.className) &&
38
- (node.properties.className as string[]).includes("katex");
39
-
40
- if (!isMathJax && !isKatex) return;
41
-
47
+ const el = node as Element;
48
+ const classes = classNames(el);
49
+ const isInline = classes.includes("math-inline");
50
+ const isDisplay = classes.includes("math-display");
51
+ if (!isInline && !isDisplay) return;
42
52
  const parent = ancestors[ancestors.length - 1] as Parent | undefined;
43
53
  if (!parent) return;
44
- occurrences.push({ node, parent });
54
+ targets.push({ node: el, parent, display: isDisplay });
45
55
  });
46
56
 
47
- if (!occurrences.length) return;
48
-
49
- if (mathSpeech.length !== occurrences.length) {
50
- console.warn(
51
- `[vocasync] Math speech mismatch: collected ${mathSpeech.length} expression(s) from markdown but found ${occurrences.length} rendered math element(s). Check that remark-math and rehype-katex/rehype-mathjax are both configured.`
52
- );
53
- }
54
-
55
- let mathIndex = 0;
56
- for (const occurrence of occurrences) {
57
- if (mathIndex >= mathSpeech.length) break;
58
- const entry = mathSpeech[mathIndex];
59
- mathIndex += 1;
60
- const latex = entry.latex.trim();
57
+ for (const t of targets) {
58
+ const latex = textContent(t.node).trim();
61
59
  if (!latex) continue;
62
-
63
- const spoken = await speakLatex(latex, entry.display, style);
60
+ const spoken = mathSpeech[`${t.display ? "d" : "i"}:${latex}`];
64
61
  if (!spoken) continue;
65
-
66
- const parentChildren = occurrence.parent.children;
67
- const index = parentChildren.indexOf(occurrence.node);
62
+ const index = t.parent.children.indexOf(t.node);
68
63
  if (index === -1) continue;
69
-
70
- // Create a hidden span with the spoken text
71
- const speechNode: Element = {
64
+ // Wrap the math element; the wrapper survives the renderer replacing the
65
+ // inner code element with mjx-container / .katex.
66
+ const wrapper: Element = {
72
67
  type: "element",
73
68
  tagName: "span",
74
- properties: {
75
- className: ["sr-only", SR_SPEECH_CLASS],
76
- "data-math-speech": entry.display ? "display" : "inline",
77
- "aria-hidden": "true",
78
- },
79
- children: [{ type: "text", value: spoken }],
69
+ properties: { className: ["vocasync-math"], dataSpeech: spoken },
70
+ children: [t.node],
80
71
  };
81
-
82
- // Insert the speech node right after the math element
83
- parentChildren.splice(index + 1, 0, speechNode);
72
+ t.parent.children[index] = wrapper;
84
73
  }
85
74
  };
86
75
  }
76
+
77
+ function classNames(el: Element): string[] {
78
+ const cls = el.properties?.className;
79
+ if (Array.isArray(cls)) return cls.filter((c): c is string => typeof c === "string");
80
+ if (typeof cls === "string") return cls.split(/\s+/);
81
+ return [];
82
+ }
83
+
84
+ function textContent(node: Element): string {
85
+ let out = "";
86
+ for (const child of node.children) {
87
+ if (child.type === "text") out += child.value;
88
+ else if (child.type === "element") out += textContent(child as Element);
89
+ }
90
+ return out;
91
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import type { AudioMap } from "../types/index.js";
4
+
5
+ let audioMapCache: AudioMap | null = null;
6
+ let audioMapCachePath: string | null = null;
7
+
8
+ /** Load + cache the audio map from disk (returns null if missing/invalid). */
9
+ export function loadAudioMapSync(audioMapPath: string): AudioMap | null {
10
+ if (audioMapCache && audioMapCachePath === audioMapPath) return audioMapCache;
11
+ try {
12
+ const content = readFileSync(resolve(process.cwd(), audioMapPath), "utf-8");
13
+ audioMapCache = JSON.parse(content) as AudioMap;
14
+ audioMapCachePath = audioMapPath;
15
+ return audioMapCache;
16
+ } catch {
17
+ return null;
18
+ }
19
+ }
20
+
21
+ /** Resolve a content slug from a VFile path, preferring the collection folder. */
22
+ export function resolveSlug(
23
+ file: { path?: string; history?: string[] },
24
+ collectionName: string
25
+ ): string | undefined {
26
+ const filePath =
27
+ file.path ?? (Array.isArray(file.history) ? file.history[file.history.length - 1] : undefined);
28
+ if (!filePath) return undefined;
29
+ const normalized = filePath.replace(/\\/g, "/");
30
+ const collectionMatch = normalized.match(
31
+ new RegExp(`/content/${collectionName}/([^/]+)\\.(md|mdx)$`)
32
+ );
33
+ if (collectionMatch) return collectionMatch[1];
34
+ const filenameMatch = normalized.match(/\/([^/]+)\.(md|mdx)$/);
35
+ return filenameMatch ? filenameMatch[1] : undefined;
36
+ }
@@ -1,42 +1,69 @@
1
- import { type VocaSyncClient, getStreamingUrls } from "../api/client.js";
2
- import type { VocaSyncConfig } from "../config/index.js";
1
+ import { type VocaSyncClient, toAlignmentLocale, withPublishableKey } from "../api/client.js";
2
+ import { FormatSchema, LanguageSchema, type VocaSyncConfig, VoiceSchema } from "../config/index.js";
3
3
  import { getAudioEntry, loadAudioMap, saveAudioMap, setAudioEntry } from "../core/audio-map.js";
4
4
  import { loadContent } from "../core/content-loader.js";
5
- import { hasChanged } from "../core/hash-manager.js";
5
+ import { computeHash } from "../core/hash-manager.js";
6
6
  import { buildSpeechDocument } from "../core/speech-builder.js";
7
7
  import type {
8
8
  AudioArtifact,
9
9
  AudioMap,
10
10
  ContentItem,
11
11
  SyncResult,
12
- SyncStatus,
13
12
  SyncSummary,
14
13
  } from "../types/index.js";
15
14
 
16
- /**
17
- * Options for the sync operation.
18
- */
19
15
  export interface SyncOptions {
20
- /** Only sync this specific slug */
21
16
  only?: string;
22
- /** Force reprocessing even if content unchanged */
23
17
  force?: boolean;
24
- /** Dry run - don't make API calls */
25
18
  dryRun?: boolean;
26
- /** Progress callback */
27
19
  onProgress?: (message: string, type?: "info" | "success" | "warn" | "error") => void;
28
20
  }
29
21
 
30
- /**
31
- * Orchestrate the full sync process.
32
- *
33
- * 1. Load content from collection
34
- * 2. Build speech documents
35
- * 3. Compare hashes to detect changes
36
- * 4. Submit synthesis jobs (with align=true)
37
- * 5. Poll until complete
38
- * 6. Update audio-map.json
39
- */
22
+ type Progress = NonNullable<SyncOptions["onProgress"]>;
23
+
24
+ /** Resolve effective synthesis params from per-post frontmatter, falling back to config. */
25
+ function resolveParams(
26
+ item: ContentItem,
27
+ config: VocaSyncConfig
28
+ ): { voice: string; language: string; format: string } | { error: string } {
29
+ const fm = item.frontmatter;
30
+
31
+ let voice = config.synthesis.voice as string;
32
+ if (fm.voice !== undefined && fm.voice !== null) {
33
+ const parsed = VoiceSchema.safeParse(fm.voice);
34
+ if (!parsed.success) return { error: `invalid frontmatter voice "${String(fm.voice)}"` };
35
+ voice = parsed.data;
36
+ }
37
+
38
+ let language = config.language as string;
39
+ if (fm.language !== undefined && fm.language !== null) {
40
+ const parsed = LanguageSchema.safeParse(fm.language);
41
+ if (!parsed.success) return { error: `invalid frontmatter language "${String(fm.language)}"` };
42
+ language = parsed.data;
43
+ }
44
+
45
+ let format = config.synthesis.format as string;
46
+ if (fm.format !== undefined && fm.format !== null) {
47
+ const parsed = FormatSchema.safeParse(fm.format);
48
+ if (!parsed.success) return { error: `invalid frontmatter format "${String(fm.format)}"` };
49
+ format = parsed.data;
50
+ }
51
+
52
+ return { voice, language, format };
53
+ }
54
+
55
+ /** True when an existing entry is a complete v3 artifact matching the hash. */
56
+ function isUpToDate(entry: AudioArtifact | undefined, contentHash: string): boolean {
57
+ return Boolean(
58
+ entry &&
59
+ entry.contentHash === contentHash &&
60
+ entry.synthesisProjectUuid &&
61
+ entry.alignmentProjectUuid &&
62
+ Array.isArray(entry.words)
63
+ );
64
+ }
65
+
66
+ /** Orchestrate the full sync: load -> build -> two-POST synthesis+alignment -> persist. */
40
67
  export async function sync(
41
68
  config: VocaSyncConfig,
42
69
  client: VocaSyncClient,
@@ -49,202 +76,168 @@ export async function sync(
49
76
  let synced = 0;
50
77
  let errors = 0;
51
78
 
52
- // Load existing audio map
53
79
  onProgress("Loading audio map...", "info");
54
80
  const audioMap = await loadAudioMap(config.output.audioMapPath);
55
81
 
56
- // Load content from collection
57
82
  onProgress(`Loading content from ${config.collection.name}...`, "info");
58
83
  let items = await loadContent(config.collection, config.frontmatterField);
59
84
 
60
- // Filter by slug if specified
61
85
  if (only) {
62
86
  items = items.filter((item) => item.slug === only);
63
- if (items.length === 0) {
64
- throw new Error(`No content found with slug: ${only}`);
65
- }
87
+ if (items.length === 0) throw new Error(`No content found with slug: ${only}`);
66
88
  }
67
89
 
68
90
  onProgress(`Found ${items.length} content items`, "info");
69
91
 
70
- // Process each item
71
92
  for (const item of items) {
72
93
  const result = await processItem(item, config, client, audioMap, { force, dryRun, onProgress });
73
-
74
94
  results.push(result);
75
-
76
- if (result.status === "unchanged") {
77
- unchanged++;
78
- } else if (result.status === "error") {
79
- errors++;
80
- } else {
81
- synced++;
82
- }
95
+ if (result.status === "unchanged") unchanged++;
96
+ else if (result.status === "error") errors++;
97
+ else synced++;
83
98
  }
84
99
 
85
- // Save updated audio map
86
100
  if (!dryRun && synced > 0) {
87
101
  onProgress("Saving audio map...", "info");
102
+ audioMap.version = 3;
88
103
  await saveAudioMap(config.output.audioMapPath, audioMap);
89
104
  }
90
105
 
91
- return {
92
- total: items.length,
93
- unchanged,
94
- synced,
95
- errors,
96
- results,
97
- };
106
+ return { total: items.length, unchanged, synced, errors, results };
98
107
  }
99
108
 
100
- /**
101
- * Process a single content item.
102
- */
103
109
  async function processItem(
104
110
  item: ContentItem,
105
111
  config: VocaSyncConfig,
106
112
  client: VocaSyncClient,
107
113
  audioMap: AudioMap,
108
- options: {
109
- force: boolean;
110
- dryRun: boolean;
111
- onProgress: (message: string, type?: "info" | "success" | "warn" | "error") => void;
112
- }
114
+ options: { force: boolean; dryRun: boolean; onProgress: Progress }
113
115
  ): Promise<SyncResult> {
114
116
  const { force, dryRun, onProgress } = options;
115
117
 
116
118
  try {
117
- // Build speech document
119
+ const resolved = resolveParams(item, config);
120
+ if ("error" in resolved) {
121
+ onProgress(`⚠ ${item.slug} - skipped: ${resolved.error}`, "warn");
122
+ return { slug: item.slug, status: "error", error: resolved.error };
123
+ }
124
+ const { voice, language, format } = resolved;
125
+
118
126
  const speechDoc = await buildSpeechDocument(item, { math: config.math });
127
+ const contentHash = computeHash(
128
+ JSON.stringify([speechDoc.normalisedSpeechtext, voice, language, format])
129
+ );
119
130
 
120
- // Check if content has changed
121
131
  const existingEntry = getAudioEntry(audioMap, item.slug);
122
- const contentChanged = hasChanged(existingEntry?.contentHash, speechDoc.hash);
123
-
124
- // Check if existing entry is missing publishable key (migration from v1)
125
- const needsPublishableKey = existingEntry && !existingEntry.publishableKey;
126
-
127
- if (!force && !contentChanged && existingEntry && !needsPublishableKey) {
132
+ if (!force && isUpToDate(existingEntry, contentHash)) {
128
133
  onProgress(`⏭ ${item.slug} - unchanged`, "info");
129
134
  return { slug: item.slug, status: "unchanged" };
130
135
  }
131
136
 
132
- // If only missing publishable key, create it without re-synthesizing
133
- if (!force && !contentChanged && existingEntry && needsPublishableKey) {
134
- onProgress(`🔑 ${item.slug} - creating missing publishable key...`, "info");
135
-
136
- if (dryRun) {
137
- onProgress(`🔍 ${item.slug} - would create publishable key (dry run)`, "info");
138
- return { slug: item.slug, status: "unchanged" };
139
- }
140
-
141
- try {
142
- const { publishableKey } = await client.createPublishableKey(existingEntry.projectUuid);
143
-
144
- // Update existing entry with publishable key
145
- const updatedArtifact: AudioArtifact = {
146
- ...existingEntry,
147
- publishableKey,
148
- updatedAt: new Date().toISOString(),
149
- };
150
- setAudioEntry(audioMap, item.slug, updatedArtifact);
151
-
152
- onProgress(`✅ ${item.slug} - publishable key added`, "success");
153
- return { slug: item.slug, status: "updated", projectUuid: existingEntry.projectUuid };
154
- } catch (error) {
155
- const message = error instanceof Error ? error.message : String(error);
156
- onProgress(`❌ ${item.slug} - failed to create publishable key: ${message}`, "error");
157
- return { slug: item.slug, status: "error", error: message };
158
- }
159
- }
160
-
161
- const status: SyncStatus = existingEntry ? "updated" : "new";
162
- onProgress(`📤 ${item.slug} - ${status}, submitting...`, "info");
137
+ const status = existingEntry ? "updated" : "new";
163
138
 
164
139
  if (dryRun) {
165
- onProgress(`🔍 ${item.slug} - would ${status} (dry run)`, "info");
140
+ onProgress(
141
+ `🔍 ${item.slug} - would ${status} (voice=${voice}, lang=${language}) [dry run]`,
142
+ "info"
143
+ );
166
144
  return { slug: item.slug, status };
167
145
  }
168
146
 
169
- // Submit synthesis with align=true
170
- const response = await client.synthesize({
147
+ // 1. Synthesis ------------------------------------------------------------
148
+ onProgress(`📤 ${item.slug} - synthesizing (voice=${voice}, lang=${language})...`, "info");
149
+ const synthesis = await client.synthesize({
171
150
  name: `astro-${item.slug}`,
172
- text: speechDoc.text,
173
- voice: config.synthesis.voice,
151
+ text: speechDoc.speechtext,
152
+ voice,
174
153
  quality: config.synthesis.quality,
175
- language: config.language,
154
+ language,
155
+ outputFormat: format,
176
156
  });
177
-
178
- onProgress(`⏳ ${item.slug} - processing (${response.projectUuid})...`, "info");
179
-
180
- // Poll until complete
181
- const finalStatus = await client.pollUntilComplete(response.projectUuid, {
182
- onProgress: (status) => {
183
- const synthStatus = status.synthesisJob?.status || "pending";
184
- const alignStatus = status.alignmentJob?.status || "pending";
185
- onProgress(` synth: ${synthStatus}, align: ${alignStatus}`, "info");
186
- },
157
+ const synthUuid = synthesis.projectUuid;
158
+ await client.pollUntilComplete(synthUuid, {
159
+ onProgress: (s) => onProgress(` synthesis: ${s.status}`, "info"),
160
+ });
161
+ const synthesisPublishableKey = await client.createPublishableKey(synthUuid);
162
+
163
+ // 2. Alignment (explicit, client-supplied transcript) ---------------------
164
+ onProgress(`🔗 ${item.slug} - aligning...`, "info");
165
+ const audioStreamUrl = client.streamUrl(synthUuid, "synthesis");
166
+ const { bytes: audioBytes, contentType } = await client.downloadBytes(
167
+ withPublishableKey(audioStreamUrl, synthesisPublishableKey)
168
+ );
169
+ const transcriptBytes = new TextEncoder().encode(speechDoc.normalisedSpeechtext);
170
+ const alignmentLocale = toAlignmentLocale(language);
171
+
172
+ const presign = await client.presignAlignment({
173
+ audioName: `synthesis.${format}`,
174
+ audioType: contentType,
175
+ audioSize: audioBytes.byteLength,
176
+ transcriptSize: transcriptBytes.byteLength,
177
+ language: alignmentLocale,
187
178
  });
188
179
 
189
- // Fetch alignment data
190
- if (!finalStatus.alignmentJob?.alignmentUrl) {
191
- throw new Error("No alignment URL returned");
192
- }
193
-
194
- const alignmentData = await client.getAlignment(finalStatus.alignmentJob.alignmentUrl);
195
-
196
- // Create publishable key for public streaming access
197
- onProgress(`🔑 ${item.slug} - creating publishable key...`, "info");
198
- const { publishableKey } = await client.createPublishableKey(response.projectUuid);
180
+ await client.uploadToPresigned(presign.audio.uploadUrl, audioBytes, contentType);
181
+ await client.uploadToPresigned(presign.transcript.uploadUrl, transcriptBytes, "text/plain");
182
+
183
+ await client.submitAlignment({
184
+ projectUuid: presign.projectUuid,
185
+ audioFileKey: presign.audio.key,
186
+ transcriptFileKey: presign.transcript.key,
187
+ audioFileSizeBytes: audioBytes.byteLength,
188
+ transcriptFileSizeBytes: transcriptBytes.byteLength,
189
+ language: alignmentLocale,
190
+ projectName: `astro-${item.slug}`,
191
+ });
192
+ const alignUuid = presign.projectUuid;
193
+ await client.pollUntilComplete(alignUuid, {
194
+ onProgress: (s) => onProgress(` alignment: ${s.status}`, "info"),
195
+ });
196
+ const alignmentPublishableKey = await client.createPublishableKey(alignUuid);
199
197
 
200
- // Get stable streaming URLs
201
- const streamingUrls = getStreamingUrls(response.projectUuid);
198
+ // 3. Fetch timings + persist ---------------------------------------------
199
+ const { words, duration } = await client.fetchAlignmentWords(
200
+ withPublishableKey(client.streamUrl(alignUuid, "alignment"), alignmentPublishableKey)
201
+ );
202
+ // The alignment stream may omit total duration; fall back to the last word's end.
203
+ const effectiveDuration = duration || (words.length ? words[words.length - 1].end : 0);
202
204
 
203
- // Create audio artifact with publishable key
205
+ const now = new Date().toISOString();
204
206
  const artifact: AudioArtifact = {
205
- projectUuid: response.projectUuid,
206
- contentHash: speechDoc.hash,
207
- duration: alignmentData.duration,
208
- audioUrl: streamingUrls.synthesisUrl,
209
- alignmentUrl: streamingUrls.alignmentUrl,
210
- publishableKey,
211
- createdAt: existingEntry?.createdAt || new Date().toISOString(),
212
- updatedAt: new Date().toISOString(),
207
+ contentHash,
208
+ voice,
209
+ language,
210
+ format,
211
+ synthesisProjectUuid: synthUuid,
212
+ synthesisPublishableKey,
213
+ audioUrl: audioStreamUrl,
214
+ alignmentProjectUuid: alignUuid,
215
+ alignmentPublishableKey,
216
+ words,
217
+ duration: effectiveDuration,
218
+ mathSpeech: speechDoc.mathSpeech,
219
+ createdAt: existingEntry?.createdAt ?? now,
220
+ updatedAt: now,
213
221
  };
214
-
215
- // Update audio map
216
222
  setAudioEntry(audioMap, item.slug, artifact);
217
223
 
218
- onProgress(`✅ ${item.slug} - ${status} complete`, "success");
219
-
220
- return {
221
- slug: item.slug,
222
- status,
223
- projectUuid: response.projectUuid,
224
- };
224
+ onProgress(`✅ ${item.slug} - ${status} complete (${words.length} words)`, "success");
225
+ return { slug: item.slug, status, projectUuid: synthUuid };
225
226
  } catch (error) {
226
227
  const message = error instanceof Error ? error.message : String(error);
227
228
  onProgress(`❌ ${item.slug} - error: ${message}`, "error");
228
-
229
- return {
230
- slug: item.slug,
231
- status: "error",
232
- error: message,
233
- };
229
+ // Do not persist a partial entry; leave any prior entry intact.
230
+ return { slug: item.slug, status: "error", error: message };
234
231
  }
235
232
  }
236
233
 
237
- /**
238
- * Check if the configuration and API key are valid.
239
- */
234
+ /** Validate config + API key. Balance is returned by /me in cents. */
240
235
  export async function checkConfig(
241
236
  config: VocaSyncConfig,
242
237
  client: VocaSyncClient
243
- ): Promise<{ valid: boolean; message: string; balance?: number }> {
238
+ ): Promise<{ valid: boolean; message: string; balanceCents?: number }> {
244
239
  try {
245
- // Validate API key
246
240
  const validation = await client.validateApiKey();
247
-
248
241
  if (!validation.valid) {
249
242
  return {
250
243
  valid: false,
@@ -252,19 +245,19 @@ export async function checkConfig(
252
245
  };
253
246
  }
254
247
 
255
- // Check content collection
256
248
  const items = await loadContent(config.collection, config.frontmatterField);
249
+ const balance =
250
+ validation.balanceCents !== undefined
251
+ ? `$${(validation.balanceCents / 100).toFixed(2)}`
252
+ : "unknown";
257
253
 
258
254
  return {
259
255
  valid: true,
260
- message: `Configuration valid. Found ${items.length} content items. Balance: $${validation.balance?.toFixed(2) ?? "?"}.`,
261
- balance: validation.balance,
256
+ message: `Configuration valid. Found ${items.length} content items. Balance: ${balance}.`,
257
+ balanceCents: validation.balanceCents,
262
258
  };
263
259
  } catch (error) {
264
260
  const message = error instanceof Error ? error.message : String(error);
265
- return {
266
- valid: false,
267
- message: `Configuration error: ${message}`,
268
- };
261
+ return { valid: false, message: `Configuration error: ${message}` };
269
262
  }
270
263
  }