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
@@ -3,23 +3,33 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  // Live voice bridge: a tiny local HTTP server the player calls to synthesize
6
- // narration ON THE FLY (SPEC §8 live voice). The browser can't mint Google
6
+ // narration ON THE FLY (SPEC PRESENTING live voice). The browser can't mint Google
7
7
  // credentials (nor run piper), so this process holds them and exposes:
8
8
  //
9
9
  // GET /ping → { ok, engine, model, voices, stylable } (player probes)
10
10
  // GET /voices → [[name, flavor], …]
11
11
  // POST /tts → audio/wav { text, voice, style }
12
12
  //
13
- // decklight tts [--port 8787] [--engine gemini|chirp|piper]
13
+ // decklight tts [--port 8787] [--engine gemini|chirp|piper|elevenlabs]
14
14
  // [--project <id>] (or set GOOGLE_CLOUD_PROJECT)
15
15
  // [--tts-model gemini-2.5-flash-tts] [--location global]
16
16
  // [--voice en_US-ryan-high] [--data-dir <dir>] [--lang en-US]
17
+ // [--tts-format pcm|mp3] (elevenlabs)
18
+ // [--setup] (re-run the guided setup)
19
+ //
20
+ // First run: with nothing configured on a terminal, tts walks through the
21
+ // guided setup (tts-setup.mjs) instead of exiting with the engine's error —
22
+ // engine choice, that engine's prerequisites, one test synthesis — and saves
23
+ // the answers to ~/.config/decklight/tts.json ($XDG_CONFIG_HOME honored).
24
+ // Precedence: flags > environment > saved config > built-in default.
17
25
  //
18
26
  // Engines differ in what they cost and what they can be told (tts-engines.mjs):
19
27
  // gemini takes a style instruction and has no free tier; chirp is ~1s a
20
- // sentence with 1M free chars a month; piper is offline and unlimited. /ping
28
+ // sentence with 1M free chars a month; piper is offline and unlimited;
29
+ // elevenlabs speaks your account's own voices, cloned ones included. /ping
21
30
  // reports which one is live, so the player's picker offers only voices this
22
- // bridge can actually speak.
31
+ // bridge can actually speak — which for ElevenLabs means asking the account
32
+ // first, so /ping and /voices await that lookup rather than guessing.
23
33
  //
24
34
  // CORS is wide open (decks run on file://, origin "null") — the server binds
25
35
  // 127.0.0.1 only. Responses are cached in memory by (text, voice, style), so
@@ -27,84 +37,156 @@
27
37
 
28
38
  import { createServer } from 'node:http';
29
39
  import { createHash } from 'node:crypto';
30
- import { createEngine, ENGINES } from './tts-engines.mjs';
40
+ import { createInterface } from 'node:readline/promises';
41
+ import { resolveEngine, ENGINES } from './tts-engines.mjs';
42
+ import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
+ import { argReader, isMain } from './args.mjs';
44
+ import { corsHeaders, readBody } from './bridge.mjs';
45
+ import { installedVoices } from '../cli/units.mjs';
31
46
 
32
47
  export async function ttsMain(args) {
33
48
  if (args.includes('--help')) {
34
- console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}] [--project <id>]
49
+ console.log(`usage: decklight tts [--port 8787] [--engine ${ENGINES.join('|')}|<installed>] [--project <id>]
35
50
  [--tts-model id] [--location global] [--voice name] [--data-dir dir] [--lang en-US]
51
+ [--tts-format pcm|mp3] [--tts-stability creative|natural|robust] [--setup]
36
52
 
37
53
  gemini gemini-2.5-pro-tts (default) or --tts-model gemini-2.5-flash-tts — Vertex AI, best
38
54
  delivery, the only engine that honors a style instruction. No free tier.
39
55
  chirp Chirp 3: HD on the Cloud Text-to-Speech API — same 30 voices, ~1s a sentence,
40
56
  1M characters a month free. Needs texttospeech.googleapis.com enabled.
41
57
  piper local neural TTS — offline, unlimited, no credentials, no cost.
58
+ elevenlabs your ElevenLabs account's own voices — the ones you cloned included, listed
59
+ first in the picker. Needs $ELEVENLABS_API_KEY (never written to disk).
60
+ --tts-model eleven_multilingual_v2 (default) / eleven_turbo_v2_5 for latency /
61
+ eleven_v3 to opt into style direction via audio tags — higher latency, more
62
+ variable consistency, and best on short prompts; the only ElevenLabs model
63
+ the picker's tone step appears for.
64
+ --tts-stability creative|natural|robust — how hard v3 follows a tag (v3 only;
65
+ refused on any other model rather than silently doing nothing).
66
+ --tts-format mp3 if your plan has no PCM output (costs you ⇧V and lip-sync).
67
+
68
+ <installed> any engine from a marketplace (decklight engine add <name>) — --engine
69
+ takes its name like any of the six above, and the picker treats it the same.
42
70
 
43
- project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)`);
71
+ project also read from $GOOGLE_CLOUD_PROJECT (gemini and chirp only)
72
+
73
+ first run: with nothing configured on a terminal, tts asks a few guided
74
+ questions (engine, prerequisites, one test synthesis) and saves the answers
75
+ to ${ttsConfigPath()} — --setup re-runs them.
76
+ precedence: flags > environment > saved config > built-in default`);
44
77
  return;
45
78
  }
46
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
79
+ const { opt } = argReader(args);
47
80
  const port = Number(opt('--port', 8787));
48
- const engineName = opt('--engine', 'gemini');
49
- if (!ENGINES.includes(engineName)) {
50
- console.error(`decklight tts: unknown engine '${engineName}' — use ${ENGINES.join(', ')}`);
51
- process.exitCode = 1;
52
- return;
53
- }
81
+ const saved = loadTtsConfig();
82
+ const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
83
+ const engineName = opt('--engine') ?? saved?.engine ?? 'gemini';
84
+ // saved voice/data-dir belong to the engine they were saved for — a piper
85
+ // model name is meaningless to gemini
86
+ const savedFor = saved?.engine === engineName ? saved : null;
87
+
88
+ const wizard = async () => {
89
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
90
+ try { return await runSetupWizard({ ask: (q) => rl.question(q), prefill: saved ?? {} }); }
91
+ finally { rl.close(); }
92
+ };
54
93
 
55
94
  let engine;
56
- try {
57
- engine = createEngine({
58
- engine: engineName,
59
- project: opt('--project', process.env.GOOGLE_CLOUD_PROJECT),
60
- model: opt('--tts-model'),
61
- location: opt('--location'),
62
- voice: opt('--voice'),
63
- dataDir: opt('--data-dir'),
64
- lang: opt('--lang'),
65
- });
66
- } catch (e) {
67
- console.error(`decklight tts: ${e.message}`);
68
- process.exitCode = 1;
69
- return;
95
+ if (args.includes('--setup')) {
96
+ if (!tty) {
97
+ console.error('decklight tts: --setup needs a terminal to ask its questions on');
98
+ process.exitCode = 1;
99
+ return;
100
+ }
101
+ engine = (await wizard())?.engine;
102
+ if (!engine) { process.exitCode = 1; return; }
103
+ } else {
104
+ try {
105
+ // resolveEngine, not createEngine: a name that is not one of the six
106
+ // built-ins may still be an INSTALLED engine (SPEC ENGINE_UNITS), and
107
+ // the bridge cannot know which kind it was handed.
108
+ engine = await resolveEngine({
109
+ engine: engineName,
110
+ project: opt('--project') ?? process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project,
111
+ model: opt('--tts-model'),
112
+ location: opt('--location'),
113
+ voice: opt('--voice') ?? savedFor?.voice,
114
+ dataDir: opt('--data-dir') ?? savedFor?.dataDir,
115
+ lang: opt('--lang'),
116
+ format: opt('--tts-format') ?? savedFor?.format,
117
+ stability: opt('--tts-stability'),
118
+ });
119
+ } catch (e) {
120
+ // an explicit --engine/--project is a hand on the wheel — fail exactly
121
+ // as before; otherwise, on a terminal, the error becomes the first
122
+ // question of the guided setup instead of the end of the road
123
+ if (!tty || args.includes('--engine') || args.includes('--project')) {
124
+ console.error(`decklight tts: ${e.message}`);
125
+ process.exitCode = 1;
126
+ return;
127
+ }
128
+ console.log(`no voice engine configured yet (${e.message})`);
129
+ engine = (await wizard())?.engine;
130
+ if (!engine) { process.exitCode = 1; return; }
131
+ }
70
132
  }
71
133
 
134
+ // ElevenLabs' roster belongs to the account, so it is a network call, not a
135
+ // constant. Cached inside the engine; this just picks whichever kind of
136
+ // answer the live engine has.
137
+ // Installed marketplace voices are references, not audio (SPEC VOICE_UNITS):
138
+ // the library holds `{engine, voiceId}` and the engine does the speaking. Read
139
+ // once at startup — the library is a local directory the presenter edits with
140
+ // a CLI, not something that changes under a running bridge.
141
+ //
142
+ // The picker offers the human-readable name, so the id it stands for has to be
143
+ // put back before synth; that resolution lives HERE, next to the merge that
144
+ // made the name offerable, rather than in each engine — an engine that had to
145
+ // know about the unit library would be an engine that could no longer be
146
+ // tested without one.
147
+ const refs = installedVoices(engine.name);
148
+ const refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
149
+ if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
150
+
151
+ const voiceRoster = async () => [
152
+ ...(engine.listVoices ? (await engine.listVoices()).map((v) => [v.name, v.flavor]) : engine.voices),
153
+ ...refs.map((r) => [r.label, r.marketplace ?? 'installed']),
154
+ ];
155
+
72
156
  const cache = new Map();
73
157
 
74
- const CORS = {
75
- 'access-control-allow-origin': '*',
76
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
77
- 'access-control-allow-headers': 'content-type',
78
- // the player reads the cost estimate for its debug window
79
- 'access-control-expose-headers': 'x-tts-cost, x-tts-tokens, x-tts-cached',
80
- };
158
+ // the player reads the cost estimate for its debug window
159
+ const CORS = corsHeaders('x-tts-cost, x-tts-tokens, x-tts-cached');
81
160
  let totalCost = 0;
82
161
  let totalChars = 0;
83
162
 
84
163
  const server = createServer(async (req, res) => {
85
164
  if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
86
165
  if (req.method === 'GET' && req.url === '/ping') {
166
+ // A roster the bridge cannot fetch is not a reason to report itself dead:
167
+ // the player falls back to its built-in list, and a synth would say why.
168
+ const voices = await voiceRoster().catch((e) => {
169
+ console.error(` voices: ${String(e.message ?? e).slice(0, 160)}`);
170
+ return [];
171
+ });
87
172
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
88
173
  return res.end(JSON.stringify({
89
174
  ok: true,
90
175
  engine: engine.name,
91
176
  model: engine.model,
92
177
  stylable: engine.stylable, // gemini alone can be told HOW to say it
93
- voices: engine.voices, // piper speaks one voice, not the star roster
178
+ voices, // piper speaks one voice, not the star roster
94
179
  }));
95
180
  }
96
181
  if (req.method === 'GET' && req.url === '/voices') {
97
182
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
98
- return res.end(JSON.stringify(engine.voices));
183
+ return res.end(JSON.stringify(await voiceRoster()));
99
184
  }
100
185
  if (req.method === 'POST' && req.url === '/tts') {
101
186
  try {
102
- // body read INSIDE the try: a client abort mid-request rejects the
103
- // stream, and outside the try it would crash the whole bridge
104
- let body = '';
105
- for await (const chunk of req) body += chunk;
106
- const { text, voice, style } = JSON.parse(body);
187
+ const { text, voice: picked, style } = JSON.parse((await readBody(req)).toString());
107
188
  if (!text?.trim()) { res.writeHead(400, CORS); return res.end('no text'); }
189
+ const voice = refIds.get(picked) ?? picked;
108
190
  // NUL joins the fields so they cannot run together (a style ending in a
109
191
  // space and a text starting with one must not hash like their neighbours)
110
192
  // — but written as an ESCAPE, not a raw byte. This file used to carry
@@ -114,25 +196,45 @@ export async function ttsMain(args) {
114
196
  .update([engine.name, voice, style, text].join('\u0000')).digest('hex');
115
197
  const fresh = !cache.has(key);
116
198
  if (fresh) {
117
- process.stdout.write(` ${engine.name} ${voice}: ${text.length} chars … `);
199
+ process.stdout.write(` ${engine.name} ${picked}: ${text.length} chars … `);
118
200
  const t0 = Date.now();
119
201
  cache.set(key, await engine.synth(text, { voice, style }));
120
202
  const u = cache.get(key).usage;
121
- totalCost += u.cost;
203
+ // `cost` is OPTIONAL, and an installed engine is why (SPEC
204
+ // ENGINE_UNITS): the six built-ins all happen to report one, so
205
+ // reading it unguarded worked until a marketplace engine that
206
+ // meters differently — or not at all — returned usage without it
207
+ // and took the sentence down mid-talk with a TypeError. A missing
208
+ // price is not zero either; it is "no list price to quote", which
209
+ // is what `hasCost` below shows instead of inventing $0.0000.
210
+ const hasCost = typeof u.cost === 'number' && Number.isFinite(u.cost);
211
+ if (hasCost) totalCost += u.cost;
122
212
  totalChars += u.chars ?? text.length;
123
213
  // chirp's free tier is denominated in CHARACTERS, so show those too —
124
214
  // a dollar estimate alone would read as a bill for something free
215
+ // A dollar figure is only honest where a list price exists. Chirp has
216
+ // one behind a free tier; ElevenLabs meters characters against a plan
217
+ // rate we cannot see, so it gets characters and no invented number.
125
218
  const spend = engine.name === 'chirp'
126
219
  ? `${(totalChars / 1000).toFixed(1)}k/1000k free chars this month · ~$${totalCost.toFixed(4)} list`
127
- : `~$${u.cost.toFixed(4)} (session ~$${totalCost.toFixed(4)})`;
128
- console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s · ${u.note} · ${spend}`);
220
+ : engine.name === 'elevenlabs'
221
+ ? `${totalChars} chars this session · billed against your plan`
222
+ : hasCost
223
+ ? `~$${u.cost.toFixed(4)} (session ~$${totalCost.toFixed(4)})`
224
+ : `${totalChars} chars this session`;
225
+ console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s · ${u.note ?? `${text.length} chars`} · ${spend}`);
129
226
  }
130
227
  const { wav, usage } = cache.get(key);
131
228
  res.writeHead(200, {
132
229
  ...CORS,
133
- 'content-type': 'audio/wav',
134
- // cost is charged once, at synthesis — cache replays are free
135
- 'x-tts-cost': fresh ? usage.cost.toFixed(6) : '0',
230
+ // mp3 is an ElevenLabs opt-in; every other path is a real WAV
231
+ 'content-type': engine.synth.mimeType ?? 'audio/wav',
232
+ // cost is charged once, at synthesis — cache replays are free.
233
+ // An engine that quotes no price sends no number rather than '0',
234
+ // which would read as "this was free" (SPEC ENGINE_UNITS).
235
+ 'x-tts-cost': fresh && typeof usage.cost === 'number' && Number.isFinite(usage.cost)
236
+ ? usage.cost.toFixed(6)
237
+ : '0',
136
238
  'x-tts-tokens': usage.note ?? '',
137
239
  'x-tts-cached': fresh ? '0' : '1',
138
240
  });
@@ -148,10 +250,17 @@ export async function ttsMain(args) {
148
250
  });
149
251
 
150
252
  server.listen(port, '127.0.0.1', () => {
151
- const cost = engine.name === 'piper' ? 'free · offline'
152
- : engine.name === 'chirp' ? 'first 1M chars/month free'
153
- : 'billed per call — no free tier';
154
- console.log(`decklight tts bridge on http://127.0.0.1:${port} — ${engine.name} · ${engine.model} (${cost}) — Ctrl-C stops`);
253
+ // The BOUND port, not the requested one: `--port 0` legitimately means
254
+ // "pick a free one", and printing the 0 back made the one line telling a
255
+ // presenter where their bridge is into an unusable URL.
256
+ const bound = server.address()?.port ?? port;
257
+ // `cost` is optional (SPEC ENGINE_UNITS) — an installed engine that
258
+ // quotes no list price says nothing here rather than "(undefined)".
259
+ const price = engine.cost ? ` (${engine.cost})` : '';
260
+ console.log(`decklight tts bridge on http://127.0.0.1:${bound} — ${engine.name} · ${engine.model}${price} — Ctrl-C stops`);
261
+ // Stated here, once, where the presenter is still choosing — not
262
+ // discovered mid-talk when the delivery already varied more than expected.
263
+ if (engine.caveat) console.log(` ${engine.caveat}`);
155
264
  // piper loads a ~120 MB model on start; do it now, while the deck is still
156
265
  // being opened, so the first sentence isn't a 13-second silence
157
266
  if (engine.synth.warm) {
@@ -161,4 +270,4 @@ export async function ttsMain(args) {
161
270
  });
162
271
  }
163
272
 
164
- if (import.meta.url === `file://${process.argv[1]}`) ttsMain(process.argv.slice(2));
273
+ if (isMain(import.meta.url)) ttsMain(process.argv.slice(2));
@@ -4,7 +4,7 @@
4
4
 
5
5
  // Voice-over generator: per-slide narration audio from a deck's speaker notes.
6
6
  //
7
- // node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|chirp|gemini]
7
+ // node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|chirp|gemini|elevenlabs]
8
8
  // [--voice <name>] [--data-dir <dir>]
9
9
  // [--project <id>] [--location global] [--lang en-US]
10
10
  // [--tts-model gemini-2.5-pro-tts]
@@ -17,13 +17,21 @@
17
17
  // piper — neural local TTS, fully offline, unlimited, free. --voice takes a
18
18
  // piper model name (default en_US-ryan-high, a natural US male):
19
19
  // uv tool install piper-tts
20
- // python -m piper.download_voices en_US-ryan-high (in --data-dir)
20
+ // uvx --from piper-tts python -m piper.download_voices en_US-ryan-high
21
+ // (into --data-dir; a plain `python -m …` only works when piper was
22
+ // pip-installed into the active environment, not `uv tool install`ed)
21
23
  // chirp — Chirp 3: HD on the Cloud Text-to-Speech API. Same 30 star-named
22
24
  // voices as gemini, ~1s a sentence, and 1M characters a month free.
23
25
  // No --style: Chirp has no delivery-instruction channel.
24
26
  // gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. The only engine that
25
27
  // honors --style (default: warm, welcoming battle-hardened senior
26
28
  // engineer). No free tier, and pro is slow.
29
+ // elevenlabs — your ElevenLabs account's own voices, cloned ones included.
30
+ // --voice takes the voice's NAME (or its id); omit it and the first
31
+ // of YOUR voices is used, which is the point of the engine. Needs
32
+ // $ELEVENLABS_API_KEY. No --style. --tts-format mp3 if your plan has
33
+ // no PCM output — but this tool wants WAV (--keep-wav feeds
34
+ // tools/lipsync.mjs), so pcm is the sane choice here.
27
35
  // Cloud engines: --project or $GOOGLE_CLOUD_PROJECT, auth via
28
36
  // gcloud auth application-default login.
29
37
  //
@@ -40,14 +48,19 @@ import { execFileSync } from 'node:child_process';
40
48
  import { resolve, join, basename } from 'node:path';
41
49
  import { homedir } from 'node:os';
42
50
  import { createEngine } from './tts-engines.mjs';
51
+ import { argReader } from './args.mjs';
52
+ import { sectionBodies, NOTES_ASIDE } from './deck-html.mjs';
43
53
 
44
54
  const args = process.argv.slice(2);
45
55
  const deckPath = args.find((a) => !a.startsWith('-'));
46
- if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--engine piper|gemini] [--voice name] [--no-llm] [--reuse-text]'); process.exit(1); }
47
- const opt = (flag, dflt) => { const i = args.indexOf(flag); return i >= 0 ? args[i + 1] : dflt; };
56
+ if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--engine piper|chirp|gemini|elevenlabs] [--voice name] [--no-llm] [--reuse-text]'); process.exit(1); }
57
+ const { opt } = argReader(args);
48
58
  const outDir = resolve(opt('-o', join(resolve(deckPath, '..'), 'voiceover')));
49
59
  const engine = opt('--engine', 'piper');
50
- const voice = opt('--voice', engine === 'piper' ? 'en_US-ryan-high' : 'Alnilam');
60
+ // elevenlabs has no default name worth guessing: the roster is the account's,
61
+ // and undefined means "the first of yours", which is what you came for
62
+ const voice = opt('--voice', engine === 'piper' ? 'en_US-ryan-high'
63
+ : engine === 'elevenlabs' ? undefined : 'Alnilam');
51
64
  const style = opt('--style',
52
65
  'Read in a warm, welcoming tone, like a friendly battle-hardened senior ' +
53
66
  'engineer who is still curious about new technology.');
@@ -64,6 +77,7 @@ try {
64
77
  tts = createEngine({
65
78
  engine, project, voice, dataDir,
66
79
  model: opt('--tts-model'), location: opt('--location'), lang: opt('--lang'),
80
+ format: opt('--tts-format'),
67
81
  });
68
82
  } catch (e) {
69
83
  console.error(e.message);
@@ -87,7 +101,7 @@ const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
87
101
 
88
102
  // ── extract per-slide narration text ─────────────────────────────────────────
89
103
  const html = readFileSync(deckPath, 'utf8');
90
- const sections = html.split(/<section\b/).slice(1);
104
+ const sections = sectionBodies(html);
91
105
  const clean = (s) => s
92
106
  .replace(/⟨CLICK⟩/g, ' ')
93
107
  .replace(/<[^>]+>/g, ' ')
@@ -95,7 +109,7 @@ const clean = (s) => s
95
109
  .replace(/\s+/g, ' ')
96
110
  .trim();
97
111
  const slides = sections.map((sec, i) => {
98
- const aside = sec.match(/<aside class="notes">([\s\S]*?)<\/aside>/);
112
+ const aside = sec.match(NOTES_ASIDE);
99
113
  if (aside) return clean(aside[1]);
100
114
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
101
115
  if (md) return clean(md[1]);
@@ -168,5 +182,8 @@ for (let i = 0; i < slides.length; i++) {
168
182
  }
169
183
  writeFileSync(join(outDir, 'manifest.json'),
170
184
  JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
185
+ // piper is held resident (§ createPiper) — without this the tool prints `done`
186
+ // and then hangs on the live child process
187
+ tts.synth.close?.();
171
188
  console.log(`done → ${outDir}${skipped ? ` (${skipped} unchanged, skipped)` : ''}`
172
189
  + (totalCost ? ` · estimated cost ~$${totalCost.toFixed(4)}` : ''));
package/tools/zip.mjs ADDED
@@ -0,0 +1,143 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Enough of the ZIP format to read an Office file, and nothing more.
5
+ //
6
+ // A .pptx is a ZIP of XML parts, so importing one means unzipping one — and
7
+ // the repo's rule is that the runtime has zero dependencies while the CLI may
8
+ // have Node-only ones. This could have been a dependency. It is ~90 lines
9
+ // instead, because `node:zlib` already does the only hard part (inflate) and
10
+ // what remains is reading a well-documented directory structure.
11
+ //
12
+ // Deliberately partial: read-only, no ZIP64, no encryption, no multi-disk, no
13
+ // data descriptors trusted over the central directory. Every one of those is
14
+ // absent from files Office and Keynote write, and each is a loud error rather
15
+ // than a wrong answer if it ever shows up.
16
+ //
17
+ // And deliberately bounded: everything this reads is something someone SENT —
18
+ // a `.pptx` on import, a `.decklight` container that `present` must unzip
19
+ // BEFORE it can even find the signature — so a few-KB archive that inflates to
20
+ // gigabytes (a zip bomb) would detonate ahead of every trust decision. Two
21
+ // caps, both far above anything Office or `bundle --deck` writes, and the
22
+ // central directory's declared size is enforced rather than merely read: an
23
+ // entry whose inflated bytes disagree with its declaration is hostile or
24
+ // corrupt, and either way the answer is a loud refusal, not an allocation.
25
+
26
+ import { inflateRawSync } from 'node:zlib';
27
+
28
+ /** The most one entry may inflate to. */
29
+ export const MAX_ENTRY_BYTES = 512 * 1024 * 1024;
30
+ /** The most a whole archive may declare, summed across its entries. */
31
+ export const MAX_TOTAL_BYTES = 1024 * 1024 * 1024;
32
+
33
+ const EOCD_SIG = 0x06054b50;
34
+ const CEN_SIG = 0x02014b50;
35
+ const LOC_SIG = 0x04034b50;
36
+ const STORED = 0;
37
+ const DEFLATED = 8;
38
+
39
+ /**
40
+ * The End Of Central Directory record, scanned backwards from the end.
41
+ *
42
+ * It is last in the file but variable in position, because a trailing comment
43
+ * may follow it — so the only way to find it is to look for its signature from
44
+ * the back. The comment is at most 65535 bytes, which bounds the search.
45
+ */
46
+ function findEocd(buf) {
47
+ const min = Math.max(0, buf.length - 22 - 0xffff);
48
+ for (let i = buf.length - 22; i >= min; i -= 1) {
49
+ if (buf.readUInt32LE(i) === EOCD_SIG) return i;
50
+ }
51
+ return -1;
52
+ }
53
+
54
+ /**
55
+ * List a ZIP's entries from its central directory.
56
+ *
57
+ * The central directory is authoritative: the per-file local headers may carry
58
+ * zeroed sizes (a streaming writer fills them in a trailing data descriptor
59
+ * instead), so sizes and offsets are taken from here and the local header is
60
+ * read only for where its data actually begins.
61
+ */
62
+ export function zipEntries(buf) {
63
+ const eocd = findEocd(buf);
64
+ if (eocd < 0) throw new Error('not a zip file (no end-of-central-directory record)');
65
+ const count = buf.readUInt16LE(eocd + 10);
66
+ const start = buf.readUInt32LE(eocd + 16);
67
+ if (start === 0xffffffff || count === 0xffff) {
68
+ throw new Error('zip64 archives are not supported');
69
+ }
70
+
71
+ const entries = [];
72
+ let p = start;
73
+ for (let i = 0; i < count; i += 1) {
74
+ if (buf.readUInt32LE(p) !== CEN_SIG) throw new Error(`corrupt zip: bad central directory entry ${i}`);
75
+ const method = buf.readUInt16LE(p + 10);
76
+ const compressedSize = buf.readUInt32LE(p + 20);
77
+ const size = buf.readUInt32LE(p + 24);
78
+ const nameLen = buf.readUInt16LE(p + 28);
79
+ const extraLen = buf.readUInt16LE(p + 30);
80
+ const commentLen = buf.readUInt16LE(p + 32);
81
+ const offset = buf.readUInt32LE(p + 42);
82
+ // Office writes UTF-8 names; the flag bit that says so is set, and the
83
+ // legacy CP437 alternative has no characters we would read differently.
84
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
85
+ entries.push({ name, method, compressedSize, size, offset });
86
+ p += 46 + nameLen + extraLen + commentLen;
87
+ }
88
+ return entries;
89
+ }
90
+
91
+ /** The bytes of one entry, inflated if it needs to be. */
92
+ export function zipRead(buf, entry) {
93
+ if (buf.readUInt32LE(entry.offset) !== LOC_SIG) {
94
+ throw new Error(`corrupt zip: ${entry.name} does not start with a local file header`);
95
+ }
96
+ if (entry.size > MAX_ENTRY_BYTES) {
97
+ throw new Error(`${entry.name}: declares ${entry.size} bytes inflated, past the ${MAX_ENTRY_BYTES}-byte entry cap`);
98
+ }
99
+ const nameLen = buf.readUInt16LE(entry.offset + 26);
100
+ const extraLen = buf.readUInt16LE(entry.offset + 28);
101
+ const start = entry.offset + 30 + nameLen + extraLen;
102
+ const raw = buf.subarray(start, start + entry.compressedSize);
103
+ if (entry.method === STORED) return Buffer.from(raw);
104
+ if (entry.method === DEFLATED) {
105
+ let out;
106
+ // maxOutputLength makes zlib stop AT the declared size instead of
107
+ // allocating whatever the stream expands to — the declaration is the cap.
108
+ // (zlib refuses a cap of 0; a genuinely empty entry still inflates to
109
+ // nothing under a cap of 1, and anything else fails the check below.)
110
+ try {
111
+ out = inflateRawSync(raw, { maxOutputLength: Math.max(entry.size, 1) });
112
+ } catch (e) {
113
+ if (e.code !== 'ERR_BUFFER_TOO_LARGE') throw e;
114
+ throw new Error(`${entry.name}: inflates past the ${entry.size} bytes its central directory entry declares`);
115
+ }
116
+ if (out.length !== entry.size) {
117
+ throw new Error(`${entry.name}: inflates to ${out.length} bytes, not the ${entry.size} its central directory entry declares`);
118
+ }
119
+ return out;
120
+ }
121
+ throw new Error(`${entry.name}: unsupported compression method ${entry.method}`);
122
+ }
123
+
124
+ /**
125
+ * The whole archive as a name → Buffer map.
126
+ *
127
+ * An Office file is a few dozen small parts read in an order the code decides,
128
+ * not the archive, so holding them all beats seeking repeatedly. Directory
129
+ * entries (trailing slash, zero length) are dropped — they are not content.
130
+ */
131
+ export function unzip(buf) {
132
+ const entries = zipEntries(buf).filter((e) => !e.name.endsWith('/'));
133
+ // Summed up front, from the directory alone — an archive that declares more
134
+ // than the cap is refused before a single entry is inflated, and zipRead
135
+ // holds every entry to its declaration, so the sum is a real bound.
136
+ const total = entries.reduce((n, e) => n + e.size, 0);
137
+ if (total > MAX_TOTAL_BYTES) {
138
+ throw new Error(`archive declares ${total} bytes inflated, past the ${MAX_TOTAL_BYTES}-byte cap`);
139
+ }
140
+ const out = new Map();
141
+ for (const entry of entries) out.set(entry.name, zipRead(buf, entry));
142
+ return out;
143
+ }