@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,117 +1,84 @@
1
1
  import { visitParents } from "unist-util-visit-parents";
2
- const SR_SPEECH_CLASS = "vocasync-math-speech";
3
- let latexToSpeech = null;
4
- let latexToSpeechLoadAttempted = false;
5
- const latexSpeechCache = new Map();
6
- let warnedLatexSpeechFailure = false;
2
+ import { loadAudioMapSync, resolveSlug } from "./shared.js";
7
3
  /**
8
- * Convert LaTeX to spoken text using speech-rule-engine and mathjax-full.
9
- */
10
- async function speakLatex(value, style = "clearspeak") {
11
- const trimmed = String(value ?? "").trim();
12
- if (!trimmed)
13
- return "";
14
- // Lazy load our internal latex-to-speech module
15
- if (!latexToSpeechLoadAttempted) {
16
- latexToSpeechLoadAttempted = true;
17
- try {
18
- const mod = await import("../lib/latex-to-speech/index.js");
19
- latexToSpeech = mod.latexToSpeech || mod.default;
20
- }
21
- catch {
22
- console.warn("[vocasync] Math-to-speech initialization failed. Install optional dependencies:", "\n npm install speech-rule-engine mathjax-full");
23
- }
24
- }
25
- if (!latexToSpeech) {
26
- return trimmed; // Fallback to raw latex if library not available
27
- }
28
- const cacheKey = `${style}:${trimmed}`;
29
- if (!latexSpeechCache.has(cacheKey)) {
30
- const pending = (async () => {
31
- try {
32
- const result = await latexToSpeech([trimmed], {
33
- domain: style,
34
- style: "default",
35
- locale: "en",
36
- modality: "speech",
37
- });
38
- const spoken = Array.isArray(result) ? result[0] : String(result ?? "");
39
- return normalizeWhitespace(spoken);
40
- }
41
- catch (error) {
42
- if (!warnedLatexSpeechFailure) {
43
- console.warn("[vocasync] Failed to convert LaTeX to speech:", error instanceof Error ? error.message : error);
44
- warnedLatexSpeechFailure = true;
45
- }
46
- return normalizeWhitespace(trimmed);
47
- }
48
- })();
49
- latexSpeechCache.set(cacheKey, pending);
50
- }
51
- return latexSpeechCache.get(cacheKey);
52
- }
53
- function normalizeWhitespace(value = "") {
54
- return value.replace(/\r/g, "").replace(/\s+/g, " ").trim();
55
- }
56
- /**
57
- * Rehype plugin that injects hidden spoken text next to math elements.
58
- * This allows rehypeAudioWords to wrap the spoken words with timing data.
4
+ * Rehype plugin that attaches each math expression's spoken form as a
5
+ * `data-speech` attribute, so rehypeAudioWords can wrap the whole expression
6
+ * as one highlight unit whose `data-n` is the spoken token count.
7
+ *
8
+ * The spoken forms are read from the audio map (where `vocasync sync` stored
9
+ * them, keyed by latex) — math-to-speech runs only in the CLI, never here.
10
+ * This guarantees the math tokens match what was synthesized AND avoids
11
+ * running the math engines inside Astro's Vite build.
59
12
  *
60
- * Must run AFTER rehype-katex or rehype-mathjax, and BEFORE rehypeAudioWords.
13
+ * Reads the LaTeX from the `code.math-inline` / `code.math-display` elements
14
+ * that `remark-math` produces and wraps each in
15
+ * `<span class="vocasync-math" data-speech="…">`. MUST run BEFORE
16
+ * rehype-mathjax / rehype-katex (which replace the inner element) and before
17
+ * rehypeAudioWords.
61
18
  */
62
19
  export default function rehypeMathSpeech(options = {}) {
63
- const { style = "clearspeak" } = options;
64
- return async function transformer(tree, file) {
65
- const mathSpeech = file.data.mathSpeech;
66
- if (!mathSpeech?.length)
20
+ const { audioMapPath = ".vocasync/audio-map.json", collectionName = "articles" } = options;
21
+ return function transformer(tree, file) {
22
+ const audioMap = loadAudioMapSync(audioMapPath);
23
+ if (!audioMap)
24
+ return;
25
+ const slug = resolveSlug(file, collectionName);
26
+ if (!slug)
27
+ return;
28
+ const mathSpeech = audioMap.entries[slug]?.mathSpeech;
29
+ if (!mathSpeech)
67
30
  return;
68
- // Find all MathJax/KaTeX container elements
69
- const occurrences = [];
31
+ const targets = [];
70
32
  visitParents(tree, "element", (node, ancestors) => {
71
- // MathJax uses mjx-container, KaTeX uses .katex class
72
- const isMathJax = node.tagName === "mjx-container";
73
- const isKatex = node.tagName === "span" &&
74
- Array.isArray(node.properties?.className) &&
75
- node.properties.className.includes("katex");
76
- if (!isMathJax && !isKatex)
33
+ const el = node;
34
+ const classes = classNames(el);
35
+ const isInline = classes.includes("math-inline");
36
+ const isDisplay = classes.includes("math-display");
37
+ if (!isInline && !isDisplay)
77
38
  return;
78
39
  const parent = ancestors[ancestors.length - 1];
79
40
  if (!parent)
80
41
  return;
81
- occurrences.push({ node, parent });
42
+ targets.push({ node: el, parent, display: isDisplay });
82
43
  });
83
- if (!occurrences.length)
84
- return;
85
- let mathIndex = 0;
86
- for (const occurrence of occurrences) {
87
- if (mathIndex >= mathSpeech.length)
88
- break;
89
- const entry = mathSpeech[mathIndex];
90
- mathIndex += 1;
91
- const latex = entry.latex.trim();
44
+ for (const t of targets) {
45
+ const latex = textContent(t.node).trim();
92
46
  if (!latex)
93
47
  continue;
94
- const spoken = await speakLatex(latex, style);
48
+ const spoken = mathSpeech[`${t.display ? "d" : "i"}:${latex}`];
95
49
  if (!spoken)
96
50
  continue;
97
- const parentChildren = occurrence.parent.children;
98
- const index = parentChildren.indexOf(occurrence.node);
51
+ const index = t.parent.children.indexOf(t.node);
99
52
  if (index === -1)
100
53
  continue;
101
- // Create a hidden span with the spoken text
102
- const speechNode = {
54
+ // Wrap the math element; the wrapper survives the renderer replacing the
55
+ // inner code element with mjx-container / .katex.
56
+ const wrapper = {
103
57
  type: "element",
104
58
  tagName: "span",
105
- properties: {
106
- className: ["sr-only", SR_SPEECH_CLASS],
107
- "data-math-speech": entry.display ? "display" : "inline",
108
- "aria-hidden": "true",
109
- },
110
- children: [{ type: "text", value: spoken }],
59
+ properties: { className: ["vocasync-math"], dataSpeech: spoken },
60
+ children: [t.node],
111
61
  };
112
- // Insert the speech node right after the math element
113
- parentChildren.splice(index + 1, 0, speechNode);
62
+ t.parent.children[index] = wrapper;
114
63
  }
115
64
  };
116
65
  }
66
+ function classNames(el) {
67
+ const cls = el.properties?.className;
68
+ if (Array.isArray(cls))
69
+ return cls.filter((c) => typeof c === "string");
70
+ if (typeof cls === "string")
71
+ return cls.split(/\s+/);
72
+ return [];
73
+ }
74
+ function textContent(node) {
75
+ let out = "";
76
+ for (const child of node.children) {
77
+ if (child.type === "text")
78
+ out += child.value;
79
+ else if (child.type === "element")
80
+ out += textContent(child);
81
+ }
82
+ return out;
83
+ }
117
84
  //# sourceMappingURL=rehype-math-speech.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rehype-math-speech.js","sourceRoot":"","sources":["../../src/rehype/rehype-math-speech.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAIxD,MAAM,eAAe,GAAG,sBAAsB,CAAC;AAE/C,IAAI,aAAa,GAEN,IAAI,CAAC;AAChB,IAAI,0BAA0B,GAAG,KAAK,CAAC;AAEvC,MAAM,gBAAgB,GAAG,IAAI,GAAG,EAA2B,CAAC;AAC5D,IAAI,wBAAwB,GAAG,KAAK,CAAC;AAUrC;;GAEG;AACH,KAAK,UAAU,UAAU,CAAC,KAAa,EAAE,KAAK,GAAG,YAAY;IAC3D,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3C,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,gDAAgD;IAChD,IAAI,CAAC,0BAA0B,EAAE,CAAC;QAChC,0BAA0B,GAAG,IAAI,CAAC;QAClC,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,iCAAiC,CAAC,CAAC;YAC5D,aAAa,GAAG,GAAG,CAAC,aAAa,IAAI,GAAG,CAAC,OAAO,CAAC;QACnD,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,CAAC,IAAI,CACV,iFAAiF,EACjF,iDAAiD,CAClD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,OAAO,OAAO,CAAC,CAAC,iDAAiD;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,GAAG,KAAK,IAAI,OAAO,EAAE,CAAC;IACvC,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC;QACpC,MAAM,OAAO,GAAG,CAAC,KAAK,IAAI,EAAE;YAC1B,IAA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AAC,CAAC;IAC1E,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { AudioMap } from "../types/index.js";
2
+ /** Load + cache the audio map from disk (returns null if missing/invalid). */
3
+ export declare function loadAudioMapSync(audioMapPath: string): AudioMap | null;
4
+ /** Resolve a content slug from a VFile path, preferring the collection folder. */
5
+ export declare function resolveSlug(file: {
6
+ path?: string;
7
+ history?: string[];
8
+ }, collectionName: string): string | undefined;
9
+ //# sourceMappingURL=shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/rehype/shared.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAKlD,8EAA8E;AAC9E,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,QAAQ,GAAG,IAAI,CAUtE;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CACzB,IAAI,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,EAC3C,cAAc,EAAE,MAAM,GACrB,MAAM,GAAG,SAAS,CAWpB"}
@@ -0,0 +1,31 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ let audioMapCache = null;
4
+ let audioMapCachePath = null;
5
+ /** Load + cache the audio map from disk (returns null if missing/invalid). */
6
+ export function loadAudioMapSync(audioMapPath) {
7
+ if (audioMapCache && audioMapCachePath === audioMapPath)
8
+ return audioMapCache;
9
+ try {
10
+ const content = readFileSync(resolve(process.cwd(), audioMapPath), "utf-8");
11
+ audioMapCache = JSON.parse(content);
12
+ audioMapCachePath = audioMapPath;
13
+ return audioMapCache;
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ /** Resolve a content slug from a VFile path, preferring the collection folder. */
20
+ export function resolveSlug(file, collectionName) {
21
+ const filePath = file.path ?? (Array.isArray(file.history) ? file.history[file.history.length - 1] : undefined);
22
+ if (!filePath)
23
+ return undefined;
24
+ const normalized = filePath.replace(/\\/g, "/");
25
+ const collectionMatch = normalized.match(new RegExp(`/content/${collectionName}/([^/]+)\\.(md|mdx)$`));
26
+ if (collectionMatch)
27
+ return collectionMatch[1];
28
+ const filenameMatch = normalized.match(/\/([^/]+)\.(md|mdx)$/);
29
+ return filenameMatch ? filenameMatch[1] : undefined;
30
+ }
31
+ //# sourceMappingURL=shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/rehype/shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGpC,IAAI,aAAa,GAAoB,IAAI,CAAC;AAC1C,IAAI,iBAAiB,GAAkB,IAAI,CAAC;AAE5C,8EAA8E;AAC9E,MAAM,UAAU,gBAAgB,CAAC,YAAoB;IACnD,IAAI,aAAa,IAAI,iBAAiB,KAAK,YAAY;QAAE,OAAO,aAAa,CAAC;IAC9E,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,YAAY,CAAC,EAAE,OAAO,CAAC,CAAC;QAC5E,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAa,CAAC;QAChD,iBAAiB,GAAG,YAAY,CAAC;QACjC,OAAO,aAAa,CAAC;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,UAAU,WAAW,CACzB,IAA2C,EAC3C,cAAsB;IAEtB,MAAM,QAAQ,GACZ,IAAI,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;IACjG,IAAI,CAAC,QAAQ;QAAE,OAAO,SAAS,CAAC;IAChC,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAChD,MAAM,eAAe,GAAG,UAAU,CAAC,KAAK,CACtC,IAAI,MAAM,CAAC,YAAY,cAAc,sBAAsB,CAAC,CAC7D,CAAC;IACF,IAAI,eAAe;QAAE,OAAO,eAAe,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAC;IAC/D,OAAO,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACtD,CAAC"}
@@ -1,36 +1,18 @@
1
1
  import { type VocaSyncClient } from "../api/client.js";
2
- import type { VocaSyncConfig } from "../config/index.js";
2
+ import { type VocaSyncConfig } from "../config/index.js";
3
3
  import type { SyncSummary } from "../types/index.js";
4
- /**
5
- * Options for the sync operation.
6
- */
7
4
  export interface SyncOptions {
8
- /** Only sync this specific slug */
9
5
  only?: string;
10
- /** Force reprocessing even if content unchanged */
11
6
  force?: boolean;
12
- /** Dry run - don't make API calls */
13
7
  dryRun?: boolean;
14
- /** Progress callback */
15
8
  onProgress?: (message: string, type?: "info" | "success" | "warn" | "error") => void;
16
9
  }
17
- /**
18
- * Orchestrate the full sync process.
19
- *
20
- * 1. Load content from collection
21
- * 2. Build speech documents
22
- * 3. Compare hashes to detect changes
23
- * 4. Submit synthesis jobs (with align=true)
24
- * 5. Poll until complete
25
- * 6. Update audio-map.json
26
- */
10
+ /** Orchestrate the full sync: load -> build -> two-POST synthesis+alignment -> persist. */
27
11
  export declare function sync(config: VocaSyncConfig, client: VocaSyncClient, options?: SyncOptions): Promise<SyncSummary>;
28
- /**
29
- * Check if the configuration and API key are valid.
30
- */
12
+ /** Validate config + API key. Balance is returned by /me in cents. */
31
13
  export declare function checkConfig(config: VocaSyncConfig, client: VocaSyncClient): Promise<{
32
14
  valid: boolean;
33
15
  message: string;
34
- balance?: number;
16
+ balanceCents?: number;
35
17
  }>;
36
18
  //# sourceMappingURL=orchestrator.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/sync/orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAoB,MAAM,kBAAkB,CAAC;AACzE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAKzD,OAAO,KAAK,EAMV,WAAW,EACZ,MAAM,mBAAmB,CAAC;AAE3B;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,mCAAmC;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mDAAmD;IACnD,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,qCAAqC;IACrC,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,wBAAwB;IACxB,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,KAAK,IAAI,CAAC;CACtF;AAED;;;;;;;;;GASG;AACH,wBAAsB,IAAI,CACxB,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,WAAW,CAAC,CAsDtB;AA2ID;;GAEG;AACH,wBAAsB,WAAW,CAC/B,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,GACrB,OAAO,CAAC;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CA2BhE"}
1
+ {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../../src/sync/orchestrator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,cAAc,EAAyC,MAAM,kBAAkB,CAAC;AAC9F,OAAO,EAAgC,KAAK,cAAc,EAAe,MAAM,oBAAoB,CAAC;AAKpG,OAAO,KAAK,EAKV,WAAW,EACZ,MAAM,mBAAmB,CAAC;AAE3B,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,OAAO,KAAK,IAAI,CAAC;CACtF;AA8CD,2FAA2F;AAC3F,wBAAsB,IAAI,CACxB,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,EACtB,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,WAAW,CAAC,CAoCtB;AA+HD,sEAAsE;AACtE,wBAAsB,WAAW,CAC/B,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,GACrB,OAAO,CAAC;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAyBrE"}
@@ -1,176 +1,177 @@
1
- import { getStreamingUrls } from "../api/client.js";
1
+ import { toAlignmentLocale, withPublishableKey } from "../api/client.js";
2
+ import { FormatSchema, LanguageSchema, VoiceSchema } from "../config/index.js";
2
3
  import { getAudioEntry, loadAudioMap, saveAudioMap, setAudioEntry } from "../core/audio-map.js";
3
4
  import { loadContent } from "../core/content-loader.js";
4
- import { hasChanged } from "../core/hash-manager.js";
5
+ import { computeHash } from "../core/hash-manager.js";
5
6
  import { buildSpeechDocument } from "../core/speech-builder.js";
6
- /**
7
- * Orchestrate the full sync process.
8
- *
9
- * 1. Load content from collection
10
- * 2. Build speech documents
11
- * 3. Compare hashes to detect changes
12
- * 4. Submit synthesis jobs (with align=true)
13
- * 5. Poll until complete
14
- * 6. Update audio-map.json
15
- */
7
+ /** Resolve effective synthesis params from per-post frontmatter, falling back to config. */
8
+ function resolveParams(item, config) {
9
+ const fm = item.frontmatter;
10
+ let voice = config.synthesis.voice;
11
+ if (fm.voice !== undefined && fm.voice !== null) {
12
+ const parsed = VoiceSchema.safeParse(fm.voice);
13
+ if (!parsed.success)
14
+ return { error: `invalid frontmatter voice "${String(fm.voice)}"` };
15
+ voice = parsed.data;
16
+ }
17
+ let language = config.language;
18
+ if (fm.language !== undefined && fm.language !== null) {
19
+ const parsed = LanguageSchema.safeParse(fm.language);
20
+ if (!parsed.success)
21
+ return { error: `invalid frontmatter language "${String(fm.language)}"` };
22
+ language = parsed.data;
23
+ }
24
+ let format = config.synthesis.format;
25
+ if (fm.format !== undefined && fm.format !== null) {
26
+ const parsed = FormatSchema.safeParse(fm.format);
27
+ if (!parsed.success)
28
+ return { error: `invalid frontmatter format "${String(fm.format)}"` };
29
+ format = parsed.data;
30
+ }
31
+ return { voice, language, format };
32
+ }
33
+ /** True when an existing entry is a complete v3 artifact matching the hash. */
34
+ function isUpToDate(entry, contentHash) {
35
+ return Boolean(entry &&
36
+ entry.contentHash === contentHash &&
37
+ entry.synthesisProjectUuid &&
38
+ entry.alignmentProjectUuid &&
39
+ Array.isArray(entry.words));
40
+ }
41
+ /** Orchestrate the full sync: load -> build -> two-POST synthesis+alignment -> persist. */
16
42
  export async function sync(config, client, options = {}) {
17
43
  const { only, force = false, dryRun = false, onProgress = () => { } } = options;
18
44
  const results = [];
19
45
  let unchanged = 0;
20
46
  let synced = 0;
21
47
  let errors = 0;
22
- // Load existing audio map
23
48
  onProgress("Loading audio map...", "info");
24
49
  const audioMap = await loadAudioMap(config.output.audioMapPath);
25
- // Load content from collection
26
50
  onProgress(`Loading content from ${config.collection.name}...`, "info");
27
51
  let items = await loadContent(config.collection, config.frontmatterField);
28
- // Filter by slug if specified
29
52
  if (only) {
30
53
  items = items.filter((item) => item.slug === only);
31
- if (items.length === 0) {
54
+ if (items.length === 0)
32
55
  throw new Error(`No content found with slug: ${only}`);
33
- }
34
56
  }
35
57
  onProgress(`Found ${items.length} content items`, "info");
36
- // Process each item
37
58
  for (const item of items) {
38
59
  const result = await processItem(item, config, client, audioMap, { force, dryRun, onProgress });
39
60
  results.push(result);
40
- if (result.status === "unchanged") {
61
+ if (result.status === "unchanged")
41
62
  unchanged++;
42
- }
43
- else if (result.status === "error") {
63
+ else if (result.status === "error")
44
64
  errors++;
45
- }
46
- else {
65
+ else
47
66
  synced++;
48
- }
49
67
  }
50
- // Save updated audio map
51
68
  if (!dryRun && synced > 0) {
52
69
  onProgress("Saving audio map...", "info");
70
+ audioMap.version = 3;
53
71
  await saveAudioMap(config.output.audioMapPath, audioMap);
54
72
  }
55
- return {
56
- total: items.length,
57
- unchanged,
58
- synced,
59
- errors,
60
- results,
61
- };
73
+ return { total: items.length, unchanged, synced, errors, results };
62
74
  }
63
- /**
64
- * Process a single content item.
65
- */
66
75
  async function processItem(item, config, client, audioMap, options) {
67
76
  const { force, dryRun, onProgress } = options;
68
77
  try {
69
- // Build speech document
78
+ const resolved = resolveParams(item, config);
79
+ if ("error" in resolved) {
80
+ onProgress(`⚠ ${item.slug} - skipped: ${resolved.error}`, "warn");
81
+ return { slug: item.slug, status: "error", error: resolved.error };
82
+ }
83
+ const { voice, language, format } = resolved;
70
84
  const speechDoc = await buildSpeechDocument(item, { math: config.math });
71
- // Check if content has changed
85
+ const contentHash = computeHash(JSON.stringify([speechDoc.normalisedSpeechtext, voice, language, format]));
72
86
  const existingEntry = getAudioEntry(audioMap, item.slug);
73
- const contentChanged = hasChanged(existingEntry?.contentHash, speechDoc.hash);
74
- // Check if existing entry is missing publishable key (migration from v1)
75
- const needsPublishableKey = existingEntry && !existingEntry.publishableKey;
76
- if (!force && !contentChanged && existingEntry && !needsPublishableKey) {
87
+ if (!force && isUpToDate(existingEntry, contentHash)) {
77
88
  onProgress(`⏭ ${item.slug} - unchanged`, "info");
78
89
  return { slug: item.slug, status: "unchanged" };
79
90
  }
80
- // If only missing publishable key, create it without re-synthesizing
81
- if (!force && !contentChanged && existingEntry && needsPublishableKey) {
82
- onProgress(`🔑 ${item.slug} - creating missing publishable key...`, "info");
83
- if (dryRun) {
84
- onProgress(`🔍 ${item.slug} - would create publishable key (dry run)`, "info");
85
- return { slug: item.slug, status: "unchanged" };
86
- }
87
- try {
88
- const { publishableKey } = await client.createPublishableKey(existingEntry.projectUuid);
89
- // Update existing entry with publishable key
90
- const updatedArtifact = {
91
- ...existingEntry,
92
- publishableKey,
93
- updatedAt: new Date().toISOString(),
94
- };
95
- setAudioEntry(audioMap, item.slug, updatedArtifact);
96
- onProgress(`✅ ${item.slug} - publishable key added`, "success");
97
- return { slug: item.slug, status: "updated", projectUuid: existingEntry.projectUuid };
98
- }
99
- catch (error) {
100
- const message = error instanceof Error ? error.message : String(error);
101
- onProgress(`❌ ${item.slug} - failed to create publishable key: ${message}`, "error");
102
- return { slug: item.slug, status: "error", error: message };
103
- }
104
- }
105
91
  const status = existingEntry ? "updated" : "new";
106
- onProgress(`📤 ${item.slug} - ${status}, submitting...`, "info");
107
92
  if (dryRun) {
108
- onProgress(`🔍 ${item.slug} - would ${status} (dry run)`, "info");
93
+ onProgress(`🔍 ${item.slug} - would ${status} (voice=${voice}, lang=${language}) [dry run]`, "info");
109
94
  return { slug: item.slug, status };
110
95
  }
111
- // Submit synthesis with align=true
112
- const response = await client.synthesize({
96
+ // 1. Synthesis ------------------------------------------------------------
97
+ onProgress(`📤 ${item.slug} - synthesizing (voice=${voice}, lang=${language})...`, "info");
98
+ const synthesis = await client.synthesize({
113
99
  name: `astro-${item.slug}`,
114
- text: speechDoc.text,
115
- voice: config.synthesis.voice,
100
+ text: speechDoc.speechtext,
101
+ voice,
116
102
  quality: config.synthesis.quality,
117
- language: config.language,
103
+ language,
104
+ outputFormat: format,
118
105
  });
119
- onProgress(`⏳ ${item.slug} - processing (${response.projectUuid})...`, "info");
120
- // Poll until complete
121
- const finalStatus = await client.pollUntilComplete(response.projectUuid, {
122
- onProgress: (status) => {
123
- const synthStatus = status.synthesisJob?.status || "pending";
124
- const alignStatus = status.alignmentJob?.status || "pending";
125
- onProgress(` synth: ${synthStatus}, align: ${alignStatus}`, "info");
126
- },
106
+ const synthUuid = synthesis.projectUuid;
107
+ await client.pollUntilComplete(synthUuid, {
108
+ onProgress: (s) => onProgress(` synthesis: ${s.status}`, "info"),
127
109
  });
128
- // Fetch alignment data
129
- if (!finalStatus.alignmentJob?.alignmentUrl) {
130
- throw new Error("No alignment URL returned");
131
- }
132
- const alignmentData = await client.getAlignment(finalStatus.alignmentJob.alignmentUrl);
133
- // Create publishable key for public streaming access
134
- onProgress(`🔑 ${item.slug} - creating publishable key...`, "info");
135
- const { publishableKey } = await client.createPublishableKey(response.projectUuid);
136
- // Get stable streaming URLs
137
- const streamingUrls = getStreamingUrls(response.projectUuid);
138
- // Create audio artifact with publishable key
110
+ const synthesisPublishableKey = await client.createPublishableKey(synthUuid);
111
+ // 2. Alignment (explicit, client-supplied transcript) ---------------------
112
+ onProgress(`🔗 ${item.slug} - aligning...`, "info");
113
+ const audioStreamUrl = client.streamUrl(synthUuid, "synthesis");
114
+ const { bytes: audioBytes, contentType } = await client.downloadBytes(withPublishableKey(audioStreamUrl, synthesisPublishableKey));
115
+ const transcriptBytes = new TextEncoder().encode(speechDoc.normalisedSpeechtext);
116
+ const alignmentLocale = toAlignmentLocale(language);
117
+ const presign = await client.presignAlignment({
118
+ audioName: `synthesis.${format}`,
119
+ audioType: contentType,
120
+ audioSize: audioBytes.byteLength,
121
+ transcriptSize: transcriptBytes.byteLength,
122
+ language: alignmentLocale,
123
+ });
124
+ await client.uploadToPresigned(presign.audio.uploadUrl, audioBytes, contentType);
125
+ await client.uploadToPresigned(presign.transcript.uploadUrl, transcriptBytes, "text/plain");
126
+ await client.submitAlignment({
127
+ projectUuid: presign.projectUuid,
128
+ audioFileKey: presign.audio.key,
129
+ transcriptFileKey: presign.transcript.key,
130
+ audioFileSizeBytes: audioBytes.byteLength,
131
+ transcriptFileSizeBytes: transcriptBytes.byteLength,
132
+ language: alignmentLocale,
133
+ projectName: `astro-${item.slug}`,
134
+ });
135
+ const alignUuid = presign.projectUuid;
136
+ await client.pollUntilComplete(alignUuid, {
137
+ onProgress: (s) => onProgress(` alignment: ${s.status}`, "info"),
138
+ });
139
+ const alignmentPublishableKey = await client.createPublishableKey(alignUuid);
140
+ // 3. Fetch timings + persist ---------------------------------------------
141
+ const { words, duration } = await client.fetchAlignmentWords(withPublishableKey(client.streamUrl(alignUuid, "alignment"), alignmentPublishableKey));
142
+ // The alignment stream may omit total duration; fall back to the last word's end.
143
+ const effectiveDuration = duration || (words.length ? words[words.length - 1].end : 0);
144
+ const now = new Date().toISOString();
139
145
  const artifact = {
140
- projectUuid: response.projectUuid,
141
- contentHash: speechDoc.hash,
142
- duration: alignmentData.duration,
143
- audioUrl: streamingUrls.synthesisUrl,
144
- alignmentUrl: streamingUrls.alignmentUrl,
145
- publishableKey,
146
- createdAt: existingEntry?.createdAt || new Date().toISOString(),
147
- updatedAt: new Date().toISOString(),
146
+ contentHash,
147
+ voice,
148
+ language,
149
+ format,
150
+ synthesisProjectUuid: synthUuid,
151
+ synthesisPublishableKey,
152
+ audioUrl: audioStreamUrl,
153
+ alignmentProjectUuid: alignUuid,
154
+ alignmentPublishableKey,
155
+ words,
156
+ duration: effectiveDuration,
157
+ mathSpeech: speechDoc.mathSpeech,
158
+ createdAt: existingEntry?.createdAt ?? now,
159
+ updatedAt: now,
148
160
  };
149
- // Update audio map
150
161
  setAudioEntry(audioMap, item.slug, artifact);
151
- onProgress(`✅ ${item.slug} - ${status} complete`, "success");
152
- return {
153
- slug: item.slug,
154
- status,
155
- projectUuid: response.projectUuid,
156
- };
162
+ onProgress(`✅ ${item.slug} - ${status} complete (${words.length} words)`, "success");
163
+ return { slug: item.slug, status, projectUuid: synthUuid };
157
164
  }
158
165
  catch (error) {
159
166
  const message = error instanceof Error ? error.message : String(error);
160
167
  onProgress(`❌ ${item.slug} - error: ${message}`, "error");
161
- return {
162
- slug: item.slug,
163
- status: "error",
164
- error: message,
165
- };
168
+ // Do not persist a partial entry; leave any prior entry intact.
169
+ return { slug: item.slug, status: "error", error: message };
166
170
  }
167
171
  }
168
- /**
169
- * Check if the configuration and API key are valid.
170
- */
172
+ /** Validate config + API key. Balance is returned by /me in cents. */
171
173
  export async function checkConfig(config, client) {
172
174
  try {
173
- // Validate API key
174
175
  const validation = await client.validateApiKey();
175
176
  if (!validation.valid) {
176
177
  return {
@@ -178,20 +179,19 @@ export async function checkConfig(config, client) {
178
179
  message: "Invalid API key. Check your VOCASYNC_API_KEY environment variable.",
179
180
  };
180
181
  }
181
- // Check content collection
182
182
  const items = await loadContent(config.collection, config.frontmatterField);
183
+ const balance = validation.balanceCents !== undefined
184
+ ? `$${(validation.balanceCents / 100).toFixed(2)}`
185
+ : "unknown";
183
186
  return {
184
187
  valid: true,
185
- message: `Configuration valid. Found ${items.length} content items. Balance: $${validation.balance?.toFixed(2) ?? "?"}.`,
186
- balance: validation.balance,
188
+ message: `Configuration valid. Found ${items.length} content items. Balance: ${balance}.`,
189
+ balanceCents: validation.balanceCents,
187
190
  };
188
191
  }
189
192
  catch (error) {
190
193
  const message = error instanceof Error ? error.message : String(error);
191
- return {
192
- valid: false,
193
- message: `Configuration error: ${message}`,
194
- };
194
+ return { valid: false, message: `Configuration error: ${message}` };
195
195
  }
196
196
  }
197
197
  //# sourceMappingURL=orchestrator.js.map