decklight 0.2.0 → 0.4.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 (137) hide show
  1. package/README.md +69 -31
  2. package/SPEC.md +881 -80
  3. package/cli/agents.mjs +116 -10
  4. package/cli/associate.mjs +286 -0
  5. package/cli/audit.mjs +424 -0
  6. package/cli/bundle.mjs +174 -46
  7. package/cli/deckfile.mjs +233 -0
  8. package/cli/decklight.mjs +201 -8
  9. package/cli/dev.mjs +244 -55
  10. package/cli/edit.mjs +577 -107
  11. package/cli/extension.mjs +108 -0
  12. package/cli/git.mjs +141 -0
  13. package/cli/import.mjs +398 -0
  14. package/cli/init.mjs +421 -116
  15. package/cli/loader.mjs +263 -0
  16. package/cli/marketplace.mjs +911 -0
  17. package/cli/pdf.mjs +156 -0
  18. package/cli/pkg.mjs +69 -0
  19. package/cli/plugin.mjs +654 -0
  20. package/cli/port-conflict.mjs +94 -0
  21. package/cli/present.mjs +564 -0
  22. package/cli/publish.mjs +342 -0
  23. package/cli/qr.mjs +334 -0
  24. package/cli/rec.mjs +5 -8
  25. package/cli/remote.mjs +149 -0
  26. package/cli/report-bug.mjs +97 -0
  27. package/cli/restore.mjs +174 -0
  28. package/cli/serve.mjs +247 -0
  29. package/cli/sign.mjs +216 -0
  30. package/cli/skill-content.mjs +222 -0
  31. package/cli/skills.mjs +338 -0
  32. package/cli/supervise.mjs +57 -0
  33. package/cli/theme.mjs +219 -0
  34. package/cli/units.mjs +500 -0
  35. package/cli/upgrade.mjs +250 -0
  36. package/cli/util.mjs +90 -0
  37. package/cli/wizard.mjs +432 -0
  38. package/cli/zip.mjs +121 -0
  39. package/dist/decklight.css +716 -29
  40. package/dist/decklight.js +198 -125
  41. package/dist/decklight.js.map +4 -4
  42. package/docs/architecture.svg +1 -1
  43. package/package.json +7 -5
  44. package/themes/README.md +6 -4
  45. package/themes/aurora.css +1 -1
  46. package/themes/berry.css +1 -1
  47. package/themes/carbon.css +1 -1
  48. package/themes/citrus.css +1 -1
  49. package/themes/coastal.css +1 -1
  50. package/themes/cosmos.css +1 -1
  51. package/themes/dune.css +1 -1
  52. package/themes/eclipse.css +1 -1
  53. package/themes/ember.css +1 -1
  54. package/themes/fjord.css +1 -1
  55. package/themes/gallery.html +3 -11
  56. package/themes/glacier.css +1 -1
  57. package/themes/graphite.css +1 -1
  58. package/themes/harvest.css +1 -1
  59. package/themes/ibm-modern.css +1 -1
  60. package/themes/ink.css +1 -1
  61. package/themes/latte.css +1 -1
  62. package/themes/linen.css +1 -1
  63. package/themes/meadow.css +1 -1
  64. package/themes/metropolis.css +1 -1
  65. package/themes/midnight.css +1 -1
  66. package/themes/mint.css +1 -1
  67. package/themes/moss.css +1 -1
  68. package/themes/obsidian.css +1 -1
  69. package/themes/orchid.css +1 -1
  70. package/themes/packs.json +2 -30
  71. package/themes/paper.css +1 -1
  72. package/themes/peony.css +1 -1
  73. package/themes/porcelain.css +1 -1
  74. package/themes/reveal-beige.css +1 -1
  75. package/themes/reveal-black.css +1 -1
  76. package/themes/reveal-blood.css +1 -1
  77. package/themes/reveal-dracula.css +1 -1
  78. package/themes/reveal-league.css +1 -1
  79. package/themes/reveal-moon.css +1 -1
  80. package/themes/reveal-night.css +1 -1
  81. package/themes/reveal-serif.css +1 -1
  82. package/themes/reveal-simple.css +1 -1
  83. package/themes/reveal-sky.css +1 -1
  84. package/themes/reveal-solarized.css +1 -1
  85. package/themes/reveal-white.css +1 -1
  86. package/themes/sepia.css +1 -1
  87. package/themes/seriph.css +1 -1
  88. package/themes/slate.css +1 -1
  89. package/themes/storm.css +1 -1
  90. package/themes/synthwave.css +1 -1
  91. package/themes/velvet.css +1 -1
  92. package/themes/yamabuki.css +1 -1
  93. package/tools/args.mjs +32 -0
  94. package/tools/bridge.mjs +30 -0
  95. package/tools/chrome.mjs +46 -11
  96. package/tools/color.mjs +110 -0
  97. package/tools/deck-html.mjs +138 -0
  98. package/tools/elevenlabs-tts.mjs +248 -0
  99. package/tools/escape.mjs +40 -0
  100. package/tools/extension-check-runner.mjs +41 -0
  101. package/tools/extension-check.mjs +266 -0
  102. package/tools/gemini-tts.mjs +25 -3
  103. package/tools/lipsync-engines.mjs +81 -0
  104. package/tools/lipsync-server.mjs +78 -37
  105. package/tools/lipsync.mjs +36 -21
  106. package/tools/local-voice.mjs +209 -0
  107. package/tools/ooxml.mjs +151 -0
  108. package/tools/pptx.mjs +320 -0
  109. package/tools/publish-site-voices.mjs +2 -1
  110. package/tools/publish-targets.mjs +143 -0
  111. package/tools/publish-voices.mjs +230 -0
  112. package/tools/shot.mjs +91 -47
  113. package/tools/theme-check.mjs +144 -0
  114. package/tools/tts-engines.mjs +270 -41
  115. package/tools/tts-setup.mjs +257 -0
  116. package/tools/veo.mjs +204 -0
  117. package/tools/video.mjs +440 -0
  118. package/tools/voiceover-server.mjs +163 -54
  119. package/tools/voiceover.mjs +24 -7
  120. package/tools/zip.mjs +143 -0
  121. package/docs/demo.svg +0 -124
  122. package/themes/aliens.css +0 -87
  123. package/themes/apple2.css +0 -129
  124. package/themes/blade-runner.css +0 -86
  125. package/themes/c64.css +0 -88
  126. package/themes/friends.css +0 -85
  127. package/themes/gameboy.css +0 -121
  128. package/themes/genesis.css +0 -87
  129. package/themes/godfather.css +0 -85
  130. package/themes/ibm-oldschool.css +0 -87
  131. package/themes/miami-vice.css +0 -87
  132. package/themes/pulp-fiction.css +0 -87
  133. package/themes/severance.css +0 -85
  134. package/themes/snes.css +0 -85
  135. package/themes/star-wars.css +0 -88
  136. package/themes/stranger-things.css +0 -87
  137. package/themes/terminator.css +0 -87
@@ -6,7 +6,7 @@
6
6
  /* ═══════════════════════════════════════════════════════════════
7
7
  Decklight theme · synthwave
8
8
  dark · Retro-future horizon — neon pink and cyan over violet dusk
9
- Token contract: SPEC.md §5 — all values validated by test/contrast.mjs
9
+ Token contract: SPEC.md THEMING — all values validated by test/contrast.mjs
10
10
  ═══════════════════════════════════════════════════════════════ */
11
11
 
12
12
  /* palette-rule exceptions (test/palette-rules.mjs):
package/themes/velvet.css CHANGED
@@ -4,7 +4,7 @@
4
4
  /* ═══════════════════════════════════════════════════════════════
5
5
  Decklight theme · velvet
6
6
  dark · Plum velvet and rose gold — an opera box after dark
7
- Token contract: SPEC.md §5 — all values validated by test/contrast.mjs
7
+ Token contract: SPEC.md THEMING — all values validated by test/contrast.mjs
8
8
  ═══════════════════════════════════════════════════════════════ */
9
9
 
10
10
  .decklight {
@@ -7,7 +7,7 @@
7
7
  Named for 山吹色, the gold of the kerria flower. One warm accent on a
8
8
  near-neutral cool ground; the red is reserved for things that fail.
9
9
  Mono headings — the type is machine-set, like the subject.
10
- Token contract: SPEC.md §5 — all values validated by test/contrast.mjs
10
+ Token contract: SPEC.md THEMING — all values validated by test/contrast.mjs
11
11
  ═══════════════════════════════════════════════════════════════ */
12
12
 
13
13
  .decklight {
package/tools/args.mjs ADDED
@@ -0,0 +1,32 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The small argv/entry-point helpers every Node script here reached for and
5
+ // re-rolled — nine byte-identical copies of `opt` alone. Lives under tools/
6
+ // because both the CLI and the tools are Node-only and the CLI already imports
7
+ // from tools/, so the dependency only ever flows one way.
8
+
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ /**
13
+ * A reader over one argv array. Keeps the familiar call shape so a site swaps
14
+ * its hand-rolled one-liner for `const { opt } = argReader(args)` and every
15
+ * `opt('--flag', dflt)` below it stays exactly as written.
16
+ *
17
+ * opt('--flag', dflt) → the token after the first --flag, or dflt
18
+ * opts('--flag') → the token after every --flag (a repeatable flag)
19
+ */
20
+ export function argReader(argv) {
21
+ const opt = (flag, dflt) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : dflt; };
22
+ const opts = (flag) => argv.flatMap((a, i) => (a === flag ? [argv[i + 1]] : []));
23
+ return { opt, opts };
24
+ }
25
+
26
+ /**
27
+ * True when this module file was run directly (`node tools/x.mjs`), false when
28
+ * imported. Path-resolved so it survives relative paths, symlinks and Windows —
29
+ * the bare `import.meta.url === \`file://${process.argv[1]}\`` form does not.
30
+ */
31
+ export const isMain = (metaUrl) =>
32
+ !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(metaUrl);
@@ -0,0 +1,30 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The bits every localhost bridge repeats. A file://-opened deck probes these
5
+ // servers directly (origin "null"), so they answer wide-open CORS — but bind
6
+ // 127.0.0.1 only, so "open" means "open to this machine". The tts bridge, the
7
+ // lipsync bridge, and the edit live-reload server each carried their own copy.
8
+
9
+ /**
10
+ * CORS headers for a bridge. `expose` is the comma-list of response headers the
11
+ * player is allowed to read (cost estimates, cache flags); omit it when there
12
+ * are none.
13
+ */
14
+ export const corsHeaders = (expose = '') => ({
15
+ 'access-control-allow-origin': '*',
16
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
17
+ 'access-control-allow-headers': 'content-type',
18
+ ...(expose ? { 'access-control-expose-headers': expose } : {}),
19
+ });
20
+
21
+ /**
22
+ * Read a request body to a Buffer. Call it INSIDE the route's try: a client
23
+ * abort mid-request rejects the stream, and unguarded that would crash the
24
+ * whole bridge. Callers that want text `.toString()` the result.
25
+ */
26
+ export async function readBody(req) {
27
+ const chunks = [];
28
+ for await (const c of req) chunks.push(c);
29
+ return Buffer.concat(chunks);
30
+ }
package/tools/chrome.mjs CHANGED
@@ -8,18 +8,53 @@
8
8
 
9
9
  import { existsSync } from 'node:fs';
10
10
 
11
- const CANDIDATES = [
12
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
13
- '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
14
- '/usr/bin/chromium', '/usr/bin/chromium-browser',
15
- '/snap/bin/chromium',
16
- `${process.env.HOME}/.nix-profile/bin/chromium`,
17
- ];
11
+ /**
12
+ * Where a browser installs itself, per platform.
13
+ *
14
+ * Windows was simply missing, which is not a small omission: with nothing here
15
+ * to find, `findChrome` returned null on every Windows machine that had not set
16
+ * $CHROME, so `decklight pdf`, `decklight video` and tools/shot.mjs all refused
17
+ * to run on the platform — on decks they render perfectly everywhere else.
18
+ *
19
+ * `%LOCALAPPDATA%` first among the Windows paths because a per-user install
20
+ * (what Chrome's own installer does without admin rights) is both the common
21
+ * case and the one no fixed path can guess. Edge is deliberately NOT listed
22
+ * even though it is Chromium and would probably work: "probably" is not
23
+ * something to hard-code into every render path, and `$CHROME` already lets
24
+ * anyone point at it deliberately.
25
+ */
26
+ export const candidates = (platform = process.platform, env = process.env) => (platform === 'win32'
27
+ ? [
28
+ `${env.LOCALAPPDATA ?? ''}\\Google\\Chrome\\Application\\chrome.exe`,
29
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
30
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
31
+ `${env.LOCALAPPDATA ?? ''}\\Chromium\\Application\\chrome.exe`,
32
+ 'C:\\Program Files\\Chromium\\Application\\chrome.exe',
33
+ ].filter((p) => !p.startsWith('\\'))
34
+ : [
35
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
36
+ '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable',
37
+ '/usr/bin/chromium', '/usr/bin/chromium-browser',
38
+ '/snap/bin/chromium',
39
+ `${env.HOME}/.nix-profile/bin/chromium`,
40
+ ]);
41
+
42
+ /**
43
+ * Where Chrome is, or null — the non-fatal half. `$CHROME` wins, else the first
44
+ * one installed. `decklight report-bug` needs to REPORT that a machine has no
45
+ * Chrome, which it cannot do if merely asking exits the process.
46
+ *
47
+ * Pure over injected `exists`/`platform`/`env`, the way tools/local-voice.mjs
48
+ * is: the whole point is branching on an operating system the tests are not
49
+ * running on, and a branch nothing can reach is a branch nobody can check.
50
+ */
51
+ export function findChrome({ exists = existsSync, platform = process.platform, env = process.env } = {}) {
52
+ return env.CHROME || env.DECKLIGHT_CHROME
53
+ || candidates(platform, env).find((p) => exists(p)) || null;
54
+ }
18
55
 
19
- /** The browser to drive: $CHROME wins, else the first one installed. */
20
- export function chromeBin(who = 'chrome') {
21
- const bin = process.env.CHROME || process.env.DECKLIGHT_CHROME
22
- || CANDIDATES.find((p) => existsSync(p));
56
+ export function chromeBin(who = 'chrome', opts = {}) {
57
+ const bin = findChrome(opts);
23
58
  if (!bin) {
24
59
  console.error(`${who}: no Chrome found — install one, or point $CHROME at it`);
25
60
  process.exit(1);
@@ -0,0 +1,110 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The color math the two theme graders (contrast.mjs, palette-rules.mjs) each
5
+ // carried a copy of — and the copies had drifted: only one parsed hsl(), only
6
+ // one saw the `white`/`black` keywords, and only one resolved var() references
7
+ // (so a token written `--accent: var(--brand)` was graded by one grader and
8
+ // silently skipped by the other). This is the single, superset implementation.
9
+ //
10
+ // NOT imported by test/themegen.test.mjs on purpose: that file keeps an
11
+ // independent copy of the contrast math so the theme GENERATOR can't grade its
12
+ // own homework. The constraint is "not the same code as src/core/themegen.js",
13
+ // which sharing this test-only module does not violate — but it is left alone
14
+ // to avoid the churn, and its independence is by design.
15
+
16
+ const NAMED = { white: [255, 255, 255], black: [0, 0, 0] };
17
+
18
+ /** A CSS color literal → [r,g,b] (0–255), or null. Handles #hex (3/4/6/8),
19
+ * rgb()/rgba(), hsl()/hsla(), and the white/black keywords. */
20
+ export function parseColor(str) {
21
+ str = str.trim();
22
+ if (NAMED[str.toLowerCase()]) return NAMED[str.toLowerCase()];
23
+ let m = str.match(/^#([0-9a-f]{3,8})$/i);
24
+ if (m) {
25
+ let h = m[1];
26
+ if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join('');
27
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
28
+ }
29
+ m = str.match(/^rgba?\(([^)]*)\)$/i);
30
+ if (m) return m[1].split(/[\s,\/]+/).filter(Boolean).map(parseFloat).slice(0, 3);
31
+ m = str.match(/^hsla?\(([^)]*)\)$/i);
32
+ if (m) {
33
+ const p = m[1].split(/[\s,\/]+/).filter(Boolean);
34
+ const h = parseFloat(p[0]), s = parseFloat(p[1]) / 100, l = parseFloat(p[2]) / 100;
35
+ const c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), mm = l - c / 2;
36
+ const seg = Math.floor(h / 60) % 6;
37
+ const rgb = [[c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x]][seg];
38
+ return rgb.map((v) => Math.round((v + mm) * 255));
39
+ }
40
+ return null;
41
+ }
42
+
43
+ /** Every color literal in a value — handles a gradient's every stop, and the
44
+ * white/black keywords (R6 forbids a pure one). */
45
+ export function colorsIn(value) {
46
+ const out = [];
47
+ const re = /#[0-9a-f]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)|\b(?:white|black)\b/gi;
48
+ for (const m of value.match(re) ?? []) {
49
+ const c = parseColor(m);
50
+ if (c) out.push(c);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /** WCAG relative luminance of an [r,g,b]. */
56
+ export function luminance([r, g, b]) {
57
+ const lin = [r, g, b].map((v) => {
58
+ v /= 255;
59
+ return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
60
+ });
61
+ return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
62
+ }
63
+
64
+ /** WCAG contrast ratio between two [r,g,b]. */
65
+ export function contrast(c1, c2) {
66
+ const [l1, l2] = [luminance(c1), luminance(c2)].sort((a, b) => b - a);
67
+ return (l1 + 0.05) / (l2 + 0.05);
68
+ }
69
+
70
+ /** [r,g,b] → { h(0–360), s(0–100), l(0–100), chroma(0–1) }. */
71
+ export function rgbToHsl([r, g, b]) {
72
+ r /= 255; g /= 255; b /= 255;
73
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
74
+ const l = (max + min) / 2;
75
+ const c = max - min;
76
+ let h = 0;
77
+ if (c) {
78
+ if (max === r) h = ((g - b) / c) % 6;
79
+ else if (max === g) h = (b - r) / c + 2;
80
+ else h = (r - g) / c + 4;
81
+ h = (h * 60 + 360) % 360;
82
+ }
83
+ const s = c === 0 ? 0 : c / (1 - Math.abs(2 * l - 1));
84
+ return { h, s: s * 100, l: l * 100, chroma: c };
85
+ }
86
+
87
+ /**
88
+ * Parse a theme's CSS custom properties into { tokens, exceptions }. var()
89
+ * references are resolved (depth-limited) so `--accent: var(--brand)` grades as
90
+ * its target. `exceptions` maps a rule id (R2, …) to the reason a theme file
91
+ * declared with `rule-exception:`.
92
+ */
93
+ export function parseTheme(css) {
94
+ const tokens = {};
95
+ const noComments = css.replace(/\/\*[\s\S]*?\*\//g, '');
96
+ for (const m of noComments.matchAll(/--([a-z0-9-]+)\s*:\s*([^;]+);/gi)) {
97
+ tokens[m[1].toLowerCase()] = m[2].trim();
98
+ }
99
+ const resolve = (v, depth = 0) => {
100
+ if (depth > 5) return v;
101
+ return v.replace(/var\(--([a-z0-9-]+)\)/gi, (_, name) =>
102
+ tokens[name.toLowerCase()] !== undefined ? resolve(tokens[name.toLowerCase()], depth + 1) : _);
103
+ };
104
+ for (const k of Object.keys(tokens)) tokens[k] = resolve(tokens[k]);
105
+ const exceptions = {};
106
+ for (const m of css.matchAll(/rule-exception:\s*(R\d)\s+([^\n*]+)/g)) {
107
+ exceptions[m[1]] = m[2].trim();
108
+ }
109
+ return { tokens, exceptions };
110
+ }
@@ -0,0 +1,138 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // A deck is a flat list of top-level <section>s — they never nest — so a split
5
+ // on the open tag is exact. Five call sites across cli/ and tools/ each
6
+ // re-derived that shape; this is the one place that knows it, so the slide
7
+ // count video sees and the slide count voiceover's manifest is keyed on can
8
+ // never drift apart. Lives under tools/ because tools/shot.mjs is a consumer
9
+ // and the dependency only ever flows cli/ → tools/.
10
+
11
+ /**
12
+ * A section's `<aside class="notes">`. Capture group [1] is the inner HTML (what
13
+ * voiceover pulls); the whole match is what edit tests for and replaces.
14
+ */
15
+ export const NOTES_ASIDE = /<aside class="notes">([\s\S]*?)<\/aside>/;
16
+
17
+ /**
18
+ * Read-only: each slide's `<section>` body, in order (the open tag is dropped).
19
+ * What video and voiceover walk to count slides and pull notes — they MUST see
20
+ * the same list, which is exactly why they share this.
21
+ */
22
+ export const sectionBodies = (html) => html.split(/<section\b/).slice(1);
23
+
24
+ /**
25
+ * Locate slide `n` (1-based) for a round-trip rewrite. Returns the capturing
26
+ * split (`[preamble, '<section', body1, '<section', body2, …]`) and the index
27
+ * of slide n's body segment; throws with the deck's real slide count when n is
28
+ * out of range. The caller rewrites `parts[idx]` and `parts.join('')`s it back.
29
+ */
30
+ export function locateSlide(html, n) {
31
+ const parts = html.split(/(<section\b)/);
32
+ const idx = 2 * n; // parts[0] preamble, then [tag, body] pairs
33
+ if (!parts[idx]) throw new Error(`no slide ${n} (deck has ${(parts.length - 1) / 2})`);
34
+ return { parts, idx };
35
+ }
36
+
37
+ /**
38
+ * Insert `fragment` right before the deck's LAST `</body>`. A bundled deck
39
+ * inlines decklight.js, whose speaker-view popup template carries a literal
40
+ * `</body>` that a first-match search would split mid-string, corrupting the
41
+ * runtime. Returns null when there is no `</body>`, so each caller picks its
42
+ * own fallback (bundle fails; shot appends).
43
+ */
44
+ export function injectBeforeBodyEnd(html, fragment) {
45
+ const at = html.toLowerCase().lastIndexOf('</body>');
46
+ return at === -1 ? null : html.slice(0, at) + fragment + html.slice(at);
47
+ }
48
+
49
+ // ── a raw section's top-level children (element edit mode, #112) ──────────
50
+ // Void/self-closing tags never open a nesting level, and <script>/<style>
51
+ // bodies are never tag-parsed (a chart's embedded JSON spec is not markup) —
52
+ // between those two, everything else nests by genuine recursion rather than a
53
+ // same-tag-name counter, so a <div> holding another <div>, or an <svg> full of
54
+ // self-closing children, still ends exactly where it should.
55
+ const VOID_ELEMENTS = new Set([
56
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
57
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
58
+ ]);
59
+ const OPAQUE_ELEMENTS = new Set(['script', 'style']);
60
+
61
+ function skipComment(html, at) {
62
+ const end = html.indexOf('-->', at + 4);
63
+ return end === -1 ? html.length : end + 3;
64
+ }
65
+
66
+ function readTagName(html, at) {
67
+ let j = at;
68
+ while (j < html.length && /[a-zA-Z0-9:_-]/.test(html[j])) j++;
69
+ return html.slice(at, j).toLowerCase();
70
+ }
71
+
72
+ /** Index of the '>' that closes the tag opening at `at` (html[at] === '<'), skipping quoted attribute values (a `>` inside `"..."` or `'...'` ends nothing). */
73
+ function findTagEnd(html, at) {
74
+ let quote = null;
75
+ for (let j = at + 1; j < html.length; j++) {
76
+ const c = html[j];
77
+ if (quote) { if (c === quote) quote = null; }
78
+ else if (c === '"' || c === "'") quote = c;
79
+ else if (c === '>') return j;
80
+ }
81
+ return html.length - 1;
82
+ }
83
+
84
+ /**
85
+ * One element starting at `start` (html[start] === '<', an opening tag — never
86
+ * '</' or '<!--', which the caller has already stepped past). Recurses into
87
+ * children to find ITS OWN matching close, so nesting depth falls out of the
88
+ * recursion instead of a counter that would have to know every tag name
89
+ * involved. Malformed input (an unclosed tag) ends at the string's end rather
90
+ * than throwing: a best-effort range for a slide someone is mid-edit on.
91
+ */
92
+ function consumeElement(html, start) {
93
+ const name = readTagName(html, start + 1);
94
+ const tagEnd = findTagEnd(html, start);
95
+ if (html[tagEnd - 1] === '/' || VOID_ELEMENTS.has(name)) {
96
+ return { tag: name, start, end: tagEnd + 1 };
97
+ }
98
+ if (OPAQUE_ELEMENTS.has(name)) {
99
+ const marker = `</${name}`;
100
+ const at = html.toLowerCase().indexOf(marker, tagEnd + 1);
101
+ const end = at === -1 ? html.length : findTagEnd(html, at) + 1;
102
+ return { tag: name, start, end };
103
+ }
104
+ let i = tagEnd + 1;
105
+ while (i < html.length) {
106
+ if (html[i] !== '<') { i++; continue; }
107
+ if (html.startsWith('<!--', i)) { i = skipComment(html, i); continue; }
108
+ if (html[i + 1] === '/') return { tag: name, start, end: findTagEnd(html, i) + 1 };
109
+ i = consumeElement(html, i).end; // a whole child, skipped over regardless of its own name
110
+ }
111
+ return { tag: name, start, end: html.length };
112
+ }
113
+
114
+ /**
115
+ * The top-level element children of slide `n`'s raw `<section>` segment (as
116
+ * `locateSlide` returns it in `parts[idx]`), by RAW POSITION — title included,
117
+ * not filtered as chrome the way the engine's own `splitContent()` filters a
118
+ * live, parsed DOM. `start`/`end` are offsets into `seg` itself, so a caller
119
+ * splices directly: `seg.slice(0, r.start) + replacement + seg.slice(r.end)`.
120
+ * Top-level text and comments are not children and never appear in the list.
121
+ */
122
+ export function sectionChildRanges(seg) {
123
+ const gt = seg.indexOf('>');
124
+ if (gt < 0) throw new Error('malformed <section> tag');
125
+ const close = seg.indexOf('</section>', gt);
126
+ const body = close === -1 ? seg.slice(gt + 1) : seg.slice(gt + 1, close);
127
+ const ranges = [];
128
+ let i = 0;
129
+ while (i < body.length) {
130
+ if (body[i] !== '<') { i++; continue; }
131
+ if (body.startsWith('<!--', i)) { i = skipComment(body, i); continue; }
132
+ if (body[i + 1] === '/') break; // this section's own closing tag
133
+ const el = consumeElement(body, i);
134
+ ranges.push({ tag: el.tag, start: el.start + gt + 1, end: el.end + gt + 1 });
135
+ i = el.end;
136
+ }
137
+ return ranges;
138
+ }
@@ -0,0 +1,248 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // ElevenLabs TTS — the engine you reach for when the voice should be YOURS.
5
+ //
6
+ // The other three engines offer a fixed roster: Google's thirty star names, or
7
+ // whichever piper model is on disk. ElevenLabs is the one whose roster is your
8
+ // account's, so a voice you cloned shows up in the deck's N picker beside the
9
+ // stock ones. That is the whole reason it is here, and it is why this engine
10
+ // alone fetches its voices instead of shipping them: they are not knowable
11
+ // until someone's key is in hand.
12
+ //
13
+ // The key is read from $ELEVENLABS_API_KEY and is NEVER written to
14
+ // ~/.config/decklight/tts.json. That file records choices (which engine, which
15
+ // project, which voice) in plain text and is meant to be boring enough to sit
16
+ // in a dotfiles repo. A key is not boring, so decklight remembers that you
17
+ // chose ElevenLabs and lets your environment remember the secret.
18
+
19
+ import { wavFromPcm } from './gemini-tts.mjs';
20
+
21
+ export const KEY_ENV = 'ELEVENLABS_API_KEY';
22
+ const API = 'https://api.elevenlabs.io/v1';
23
+
24
+ // eleven_multilingual_v2 is the quality default and speaks every voice a
25
+ // clone produces; --tts-model eleven_turbo_v2_5 trades a little of it for
26
+ // latency, which live narration may prefer on a long deck.
27
+ export const DEFAULT_MODEL = 'eleven_multilingual_v2';
28
+
29
+ // The only ElevenLabs model that reads bracketed audio tags ([excited],
30
+ // [whispers], …) as performance direction instead of words to pronounce — v3
31
+ // joins the same style channel gemini has always had, opt-in only, because
32
+ // every other model would read the brackets aloud (SPEC PRESENTING).
33
+ export const V3_MODEL = 'eleven_v3';
34
+
35
+ // v3's stability slider is not the continuous 0–1 knob older models expose —
36
+ // ElevenLabs documents exactly these three named positions. Creative follows
37
+ // a tag hardest and drifts most; Robust barely moves and mostly ignores tags;
38
+ // Natural is the middle ground. Unnamed values are refused rather than
39
+ // silently rounded to the nearest preset.
40
+ export const STABILITY_PRESETS = { creative: 0, natural: 0.5, robust: 1 };
41
+
42
+ // A tag this long stops being a short performance cue and starts being a
43
+ // second sentence — cut it back rather than let it run on. 40 chars covers
44
+ // every named ElevenLabs tag with room for a typed phrase like "on the verge
45
+ // of tears" and still reads as direction, not dialogue.
46
+ const MAX_TAG_LEN = 40;
47
+
48
+ /**
49
+ * A `style` string, or free-typed text, as a single ElevenLabs v3 audio tag —
50
+ * or '' if there is nothing to say.
51
+ *
52
+ * Someone who already knows v3 syntax can type `[whispers]` and get exactly
53
+ * that cue: the first well-formed bracketed group survives untouched (and
54
+ * only the first — a second `[…]` later in the string would be a second cue
55
+ * riding along uninvited, so everything after the first close-bracket is
56
+ * dropped). Anyone else just types a word or a short phrase, which is wrapped
57
+ * in brackets for them. Either way the result is capped to MAX_TAG_LEN so a
58
+ * persona too long to be a cue is cut back rather than spoken.
59
+ */
60
+ export function styleTag(style, maxLen = MAX_TAG_LEN) {
61
+ const raw = String(style ?? '').trim();
62
+ if (!raw) return '';
63
+ const bracketed = raw.match(/^\[([^[\]]+)\]/);
64
+ const cue = (bracketed ? bracketed[1] : raw).trim().slice(0, maxLen).trim();
65
+ return cue ? `[${cue}]` : '';
66
+ }
67
+
68
+ // PCM is what the rest of decklight is built on: ⇧V stitches per-slide WAVs
69
+ // out of the sentence cache, and rhubarb reads WAV to find visemes. mp3 plays
70
+ // perfectly well in the deck but does neither, so it is opt-in rather than a
71
+ // silent downgrade. PCM output needs a paid ElevenLabs tier; see synthError.
72
+ export const FORMATS = ['pcm', 'mp3'];
73
+ const OUTPUT = { pcm: 'pcm_24000', mp3: 'mp3_44100_128' };
74
+ const PCM_RATE = 24000;
75
+
76
+ export const apiKey = (env = process.env) => env[KEY_ENV]?.trim() || null;
77
+
78
+ /**
79
+ * The account's voices as the picker wants them: `[[name, flavor], …]`.
80
+ *
81
+ * YOUR voices come first. The picker lists them in order and preselects the
82
+ * first, and someone who cloned a voice came here to use that voice — burying
83
+ * it under twenty stock ones would make the feature technically present and
84
+ * practically useless. Within a group the API's own order is kept.
85
+ */
86
+ export function shapeVoices(json) {
87
+ const rank = { cloned: 0, professional: 1, generated: 2, premade: 3 };
88
+ return (json?.voices ?? [])
89
+ .map((v, i) => ({
90
+ name: String(v.name ?? '').trim() || v.voice_id,
91
+ id: v.voice_id,
92
+ // `category` is ElevenLabs' own word for where a voice came from, and
93
+ // "cloned" is exactly the label that makes yours findable at a glance
94
+ flavor: v.category === 'premade'
95
+ ? (v.labels?.description || v.labels?.accent || 'premade')
96
+ : (v.category ?? 'voice'),
97
+ order: [rank[v.category] ?? 2, i],
98
+ }))
99
+ .filter((v) => v.id)
100
+ .sort((a, b) => a.order[0] - b.order[0] || a.order[1] - b.order[1]);
101
+ }
102
+
103
+ /**
104
+ * Which voice the player meant. It sends a NAME — that is what it persists per
105
+ * deck and what a human recognises — but a raw voice_id is accepted too, so an
106
+ * id pasted from the ElevenLabs dashboard works without a lookup. Matching is
107
+ * case- and space-insensitive because the name came from a text field.
108
+ */
109
+ export function pickVoice(roster, requested) {
110
+ if (!roster.length) return null;
111
+ if (!requested) return roster[0];
112
+ const want = String(requested).trim().toLowerCase();
113
+ return roster.find((v) => v.id === requested)
114
+ ?? roster.find((v) => v.name.toLowerCase() === want)
115
+ ?? roster.find((v) => v.name.toLowerCase().replace(/\s+/g, '') === want.replace(/\s+/g, ''))
116
+ ?? null;
117
+ }
118
+
119
+ /**
120
+ * Turn an API failure into a sentence that names the way out. The two that
121
+ * actually happen are a key that isn't one (401) and PCM on a tier that does
122
+ * not include it (422) — and the second is worth catching by hand, because
123
+ * ElevenLabs phrases it as a validation error on a query parameter and nobody
124
+ * would guess that means "upgrade, or pass --tts-format mp3".
125
+ */
126
+ export function synthError(status, body, { format = 'pcm' } = {}) {
127
+ const text = String(body ?? '').slice(0, 300);
128
+ if (status === 401 || status === 403) {
129
+ return `ElevenLabs rejected the key (${status}) — check $${KEY_ENV}`;
130
+ }
131
+ if (format === 'pcm' && /output_format|pcm|tier|subscription/i.test(text)) {
132
+ return 'ElevenLabs will not serve pcm_24000 on this plan (PCM output is a paid tier). '
133
+ + 'Pass --tts-format mp3 to use mp3 instead — the deck plays it fine, but ⇧V offline '
134
+ + 'recording and the lip-sync bridge both need WAV and will not work with it.';
135
+ }
136
+ if (status === 429) return 'ElevenLabs rate limit (429) — the lookahead buffer is bursty; try a smaller deck or wait';
137
+ return `${status} ${text}`;
138
+ }
139
+
140
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
141
+
142
+ /**
143
+ * Returns `{ listVoices, synth }`.
144
+ *
145
+ * `listVoices()` resolves the account roster once and caches the promise — the
146
+ * bridge's /ping, its /voices, and every synth share that one call. A failure
147
+ * evicts itself, so a key fixed in another terminal is picked up on the next
148
+ * probe rather than needing a restart.
149
+ */
150
+ export function createSynth({
151
+ key, model = DEFAULT_MODEL, format = 'pcm', stability, fetchImpl = fetch,
152
+ } = {}) {
153
+ if (!key) {
154
+ throw new Error(`ElevenLabs needs an API key — set $${KEY_ENV} `
155
+ + '(create one at https://elevenlabs.io/app/settings/api-keys)');
156
+ }
157
+ if (!FORMATS.includes(format)) throw new Error(`unknown --tts-format '${format}' — use ${FORMATS.join(' or ')}`);
158
+ // A stability preset means nothing to a model with no such slider — refused
159
+ // up front, at construction, rather than accepted and quietly doing nothing.
160
+ let stabilityValue;
161
+ if (stability != null) {
162
+ if (model !== V3_MODEL) {
163
+ throw new Error(`--tts-stability is a v3 feature — pass --tts-model ${V3_MODEL}, or drop --tts-stability`);
164
+ }
165
+ stabilityValue = STABILITY_PRESETS[stability];
166
+ if (stabilityValue == null) {
167
+ throw new Error(`unknown --tts-stability '${stability}' — use ${Object.keys(STABILITY_PRESETS).join(', ')}`);
168
+ }
169
+ }
170
+ const headers = { 'xi-api-key': key };
171
+
172
+ let roster = null;
173
+ function listVoices() {
174
+ roster ??= (async () => {
175
+ const res = await fetchImpl(`${API}/voices`, { headers });
176
+ if (!res.ok) throw new Error(synthError(res.status, await res.text(), { format }));
177
+ const shaped = shapeVoices(await res.json());
178
+ if (!shaped.length) throw new Error('ElevenLabs returned no voices for this key');
179
+ return shaped;
180
+ })();
181
+ roster.catch(() => { roster = null; });
182
+ return roster;
183
+ }
184
+
185
+ async function call(text, voice) {
186
+ const payload = { text, model_id: model };
187
+ // Unasked, the account's own voice settings are left alone — sending a
188
+ // voice_settings object at all overrides them, even to "no opinion".
189
+ if (stabilityValue != null) payload.voice_settings = { stability: stabilityValue };
190
+ const res = await fetchImpl(
191
+ `${API}/text-to-speech/${encodeURIComponent(voice.id)}?output_format=${OUTPUT[format]}`,
192
+ {
193
+ method: 'POST',
194
+ headers: { ...headers, 'content-type': 'application/json' },
195
+ body: JSON.stringify(payload),
196
+ },
197
+ );
198
+ if (!res.ok) {
199
+ const e = new Error(synthError(res.status, await res.text(), { format }));
200
+ e.status = res.status;
201
+ throw e;
202
+ }
203
+ const body = Buffer.from(await res.arrayBuffer());
204
+ // pcm_24000 is headerless 16-bit mono; mp3 is already a container
205
+ return format === 'pcm' ? wavFromPcm(body, PCM_RATE) : body;
206
+ }
207
+
208
+ async function synth(text, { voice, style } = {}) {
209
+ const list = await listVoices();
210
+ const picked = pickVoice(list, voice);
211
+ if (!picked) {
212
+ throw new Error(`no ElevenLabs voice named ${JSON.stringify(voice)} on this key — have: `
213
+ + list.map((v) => v.name).join(', '));
214
+ }
215
+ // Audio tags are a v3-only delivery channel (SPEC PRESENTING). Sent to any
216
+ // other model the brackets are read aloud as words, so a tone is NEVER
217
+ // attached unless this is the model that can act on it.
218
+ const tag = model === V3_MODEL ? styleTag(style) : '';
219
+ const sent = tag ? `${tag} ${text}` : text;
220
+ let lastErr;
221
+ for (let attempt = 0; attempt < 3; attempt++) {
222
+ try {
223
+ return {
224
+ wav: await call(sent, picked),
225
+ usage: {
226
+ model,
227
+ // Billed on what actually went out — the tag rides inside the same
228
+ // text field ElevenLabs meters, so a report that ignored it would
229
+ // undercount every styled sentence.
230
+ chars: sent.length,
231
+ // ElevenLabs meters CHARACTERS against a monthly plan allowance, and
232
+ // the per-character rate depends on a tier we cannot see. Reporting a
233
+ // dollar figure would be inventing one, so the bridge shows characters.
234
+ cost: 0,
235
+ note: tag ? `${sent.length} chars · ${picked.name} · ${tag}` : `${sent.length} chars · ${picked.name}`,
236
+ },
237
+ };
238
+ } catch (e) {
239
+ lastErr = e;
240
+ if (e.status === 429 || e.status >= 500) { await sleep(2000 * (attempt + 1)); continue; }
241
+ break;
242
+ }
243
+ }
244
+ throw lastErr;
245
+ }
246
+ synth.mimeType = format === 'pcm' ? 'audio/wav' : 'audio/mpeg';
247
+ return { listVoices, synth };
248
+ }