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
@@ -0,0 +1,440 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight video — render a deck to a narrated mp4.
6
+ //
7
+ // decklight video deck.html -o deck.mp4
8
+ // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
+ // [--build-hold <s>] [--theme <name>] [--slides a-b] [--voiceover]
10
+ //
11
+ // A still per FRAME — a narrated slide is one still, fully built, held for its
12
+ // audio; a silent slide builds as it goes, one still per step — muxed with the
13
+ // audio into one mp4, so a deck becomes a watchable, shareable video in one
14
+ // command. Every frame of a silent slide holds --hold, builds included, so a
15
+ // build lands at the pace the deck moves at; --build-hold paces the build-up
16
+ // frames alone. Narration resolves --narration <dir> → <deckdir>/voiceover/
17
+ // (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
18
+ // slide holds --hold seconds (per-slide override: data-video-hold="8" on the
19
+ // section). Silent slides still carry a silent audio segment (anullsrc) so the
20
+ // concatenated audio track stays continuous.
21
+ //
22
+ // Capture is the tools/shot.mjs mechanism: one one-shot headless Chrome per
23
+ // frame against the deck served over http://127.0.0.1 at #/n/999 (an oversized
24
+ // step clamps to the last build, so every slide renders fully built). The deck
25
+ // is served under the `present` CSP, NOT opened over file:// with
26
+ // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
27
+ // local file and exfiltrate it, and video renders decks you may not have
28
+ // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
29
+ // frames are stills, so the character overlay appears but frozen and a build
30
+ // CUTS rather than animating (animated capture needs a CDP screencast — a
31
+ // Node ≥22 follow-up). How far each slide builds is asked of the deck itself,
32
+ // in one extra load, because the grouping is the runtime's and a second counter
33
+ // written here would be a copy that drifts.
34
+
35
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
36
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
+ import { tmpdir } from 'node:os';
38
+ import { basename, join, relative, resolve, sep } from 'node:path';
39
+ import { promisify } from 'node:util';
40
+ import { fileURLToPath } from 'node:url';
41
+ import { chromeBin, chromeArgs } from './chrome.mjs';
42
+ import { argReader, isMain } from './args.mjs';
43
+ import { injectBeforeBodyEnd, sectionBodies } from './deck-html.mjs';
44
+ import { serveForRender } from '../cli/present.mjs';
45
+
46
+ const run = promisify(execFile);
47
+
48
+ /** Every slide breathes before the next one starts talking. */
49
+ export const TAIL_SECONDS = 0.4;
50
+
51
+ const HELP = `decklight video <deck.html> [options] — render the deck to a narrated mp4
52
+
53
+ -o, --out <file> output mp4 (default: <deck>.mp4 next to the deck)
54
+ --narration <dir> narration dir (default: <deckdir>/voiceover if it has a
55
+ manifest.json; otherwise the deck renders silent)
56
+ --size <WxH> frame size (default 1280x720; both must be even)
57
+ --fps <n> video frame rate (default 30)
58
+ --hold <s> seconds a slide without narration holds (default 5;
59
+ per-slide override: data-video-hold="8" on the section)
60
+ --build-hold <s> seconds each build-up frame holds on a silent slide
61
+ (default: the slide's own hold, so builds move at the
62
+ pace the deck does)
63
+ --theme <name> render with themes/<name>.css instead of the deck's theme
64
+ --slides <a-b> only this slide range (1-based, inclusive)
65
+ --voiceover run the voiceover batch (tools/voiceover.mjs) first
66
+
67
+ Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s and show
68
+ fully built; slides without hold --hold seconds over silence and BUILD as they
69
+ go, one frame per step, so the audio track stays continuous either way.
70
+ Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
71
+ `;
72
+
73
+ /** '1280x720' → { w, h }. Both even — libx264 yuv420p refuses odd dimensions. */
74
+ export function parseSize(s) {
75
+ const m = /^(\d+)x(\d+)$/.exec(s ?? '');
76
+ if (!m) throw new Error(`--size must be WxH, e.g. 1280x720 (got "${s}")`);
77
+ const w = Number(m[1]); const h = Number(m[2]);
78
+ if (w % 2 || h % 2) throw new Error(`--size must be even in both dimensions (yuv420p), got ${w}x${h}`);
79
+ return { w, h };
80
+ }
81
+
82
+ /** '2-5' or '3' → { from, to } (1-based, inclusive), validated against the deck. */
83
+ export function parseSlideRange(s, total) {
84
+ if (!s) return { from: 1, to: total };
85
+ const m = /^(\d+)(?:-(\d+))?$/.exec(s);
86
+ if (!m) throw new Error(`--slides must be a-b or a single slide number (got "${s}")`);
87
+ const from = Number(m[1]); const to = m[2] ? Number(m[2]) : from;
88
+ if (from < 1 || to > total || from > to) {
89
+ throw new Error(`--slides ${s} is outside this deck (${total} slide${total === 1 ? '' : 's'})`);
90
+ }
91
+ return { from, to };
92
+ }
93
+
94
+ /** Per-slide hold seconds: data-video-hold="8" on the section, else the default. */
95
+ export function extractHolds(html, defaultHold) {
96
+ return sectionBodies(html).map((sec) => {
97
+ const tag = sec.slice(0, sec.indexOf('>'));
98
+ const m = tag.match(/data-video-hold="([\d.]+)"/);
99
+ return m ? Number(m[1]) : defaultHold;
100
+ });
101
+ }
102
+
103
+ /**
104
+ * An oversized step: the engine clamps it to the slide's last build, so this
105
+ * always renders a slide fully built however many steps it turns out to have.
106
+ * Every slide's FINAL frame is captured here rather than at a counted step, so
107
+ * a miscount can shorten the build-up but can never lose the finished slide.
108
+ */
109
+ export const LAST_STEP = 999;
110
+
111
+ const round = (s) => Math.round(s * 1000) / 1000;
112
+
113
+ /**
114
+ * The schedule: which frame of which slide is on screen, under what audio, for
115
+ * how long.
116
+ *
117
+ * ONE ENTRY PER FRAME, not per slide. A silent slide with builds is a sequence
118
+ * — the slide bare, then each build revealed — because a video of a built slide
119
+ * that opens fully built has thrown away the thing the builds were for. A
120
+ * NARRATED slide stays one fully-built still: splitting its audio across builds
121
+ * needs the ⟨CLICK⟩ markers to map to real timestamps, which is its own
122
+ * feature, and guessing at it would put words under the wrong build.
123
+ *
124
+ * Timing, for a silent slide with `b` build steps (so `b + 1` frames): EVERY
125
+ * frame holds for the slide's hold, so a build lands at the pace the rest of
126
+ * the deck moves at and the deck gets longer the more it builds. Splitting the
127
+ * hold across the frames instead — keeping the deck's length fixed — was tried
128
+ * first and reads far too fast: the more a slide has to say, the less time each
129
+ * beat of it got, which is exactly backwards. `buildHold` overrides the
130
+ * build-up frames alone, for a deck that wants its builds quicker (or slower)
131
+ * than its slides.
132
+ *
133
+ * @param {Array|null} manifest manifest.slides from tools/voiceover.mjs
134
+ * ({ file } per slide, null for silent slides) —
135
+ * or null for a fully silent deck
136
+ * @param {object} durations audio file → real (ffprobe) seconds
137
+ * @param {number[]} holds per-slide hold seconds (one per section)
138
+ * @param {{from,to}} [range] 1-based inclusive slide range
139
+ * @param {object} [opts] steps: per-slide build-step counts (null ⇒ one
140
+ * frame per slide); buildHold: seconds per
141
+ * build-up frame (null ⇒ the slide's own hold)
142
+ * @returns {Array<{slide, step, audio, duration}>} audio null ⇒ silent hold
143
+ */
144
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null } = {}) {
145
+ const from = range?.from ?? 1;
146
+ const to = range?.to ?? holds.length;
147
+ const plan = [];
148
+ for (let n = from; n <= to; n++) {
149
+ const file = manifest?.[n - 1]?.file ?? null;
150
+ const dur = file ? durations?.[file] : null;
151
+ if (Number.isFinite(dur)) {
152
+ plan.push({ slide: n, step: LAST_STEP, audio: file, duration: round(dur + TAIL_SECONDS) });
153
+ continue;
154
+ }
155
+ const hold = holds[n - 1];
156
+ const builds = steps?.[n - 1] ?? 0;
157
+ if (!builds) { plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold }); continue; }
158
+ const each = buildHold ?? hold;
159
+ for (let k = 0; k < builds; k++) plan.push({ slide: n, step: k, audio: null, duration: each });
160
+ plan.push({ slide: n, step: LAST_STEP, audio: null, duration: hold });
161
+ }
162
+ return plan;
163
+ }
164
+
165
+ /**
166
+ * ffmpeg argv for one slide's segment: the still looped at --fps under its
167
+ * audio. Narrated slides pad the audio with the tail and stop there; silent
168
+ * slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
169
+ * carries an audio stream and the concat-demuxer's `-c copy` audio track never
170
+ * goes discontinuous. -t bounds both the infinite loop and the infinite
171
+ * anullsrc (-shortest can't end a segment whose streams are both endless).
172
+ */
173
+ export function segmentArgs({ frame, audio, duration, fps, out }) {
174
+ return [
175
+ '-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
176
+ ...(audio
177
+ ? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
178
+ : ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
179
+ '-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
180
+ '-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
181
+ '-t', Number(duration).toFixed(3), '-movflags', '+faststart', out,
182
+ ];
183
+ }
184
+
185
+ /** The concat-demuxer list: one `file '…'` line per segment, quotes escaped. */
186
+ export function concatList(segments) {
187
+ return segments.map((s) => `file '${s.replaceAll("'", "'\\''")}'`).join('\n') + '\n';
188
+ }
189
+
190
+ /** ffmpeg argv joining the segments into the output without re-encoding. */
191
+ export function concatArgs(listFile, out) {
192
+ return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy',
193
+ '-movflags', '+faststart', out];
194
+ }
195
+
196
+ /** ffprobe argv for a file's real duration in seconds (prints one number). */
197
+ export function ffprobeArgs(file) {
198
+ return ['-v', 'error', '-show_entries', 'format=duration',
199
+ '-of', 'default=noprint_wrappers=1:nokey=1', file];
200
+ }
201
+
202
+ /**
203
+ * Where the narration lives: --narration <dir> (its manifest is then required)
204
+ * → <deckdir>/voiceover/manifest.json → null (a silent deck).
205
+ * @returns {{ dir, slides }|null}
206
+ */
207
+ export function resolveNarration(deckPath, narrationDir) {
208
+ const load = (dir, required) => {
209
+ const path = join(dir, 'manifest.json');
210
+ if (!existsSync(path)) {
211
+ if (required) {
212
+ throw new Error(`--narration: no manifest.json in ${dir} — `
213
+ + 'run tools/voiceover.mjs (or decklight video --voiceover) first');
214
+ }
215
+ return null;
216
+ }
217
+ const m = JSON.parse(readFileSync(path, 'utf8'));
218
+ if (!Array.isArray(m?.slides)) {
219
+ throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
220
+ }
221
+ return { dir, slides: m.slides };
222
+ };
223
+ if (narrationDir) return load(resolve(narrationDir), true);
224
+ return load(join(resolve(deckPath, '..'), 'voiceover'), false);
225
+ }
226
+
227
+ const have = (bin) => {
228
+ try { execFileSync(bin, ['-version'], { stdio: 'ignore' }); return true; }
229
+ catch (e) { return e?.code !== 'ENOENT'; }
230
+ };
231
+
232
+ /**
233
+ * The probe that answers "how many build steps does each slide have?".
234
+ *
235
+ * Asked of the DECK, in a browser, because that is the only place the answer
236
+ * exists: grouping is the runtime's (`src/core/builds.js` — `data-build-stay`,
237
+ * `data-build-self`, nesting, ⟨CLICK⟩ markers), and a second counter written in
238
+ * Node would be a copy that drifts. It reads the count the same way the capture
239
+ * URLs do: `goto(n, LAST_STEP)` clamps, so the resulting `state.step` IS the
240
+ * slide's last step.
241
+ *
242
+ * Injected only for this one load, never for the frame captures — a probe that
243
+ * called `goto` during a screenshot would photograph the wrong slide.
244
+ */
245
+ const STEP_PROBE = `<script>
246
+ (function () {
247
+ function report() {
248
+ var d = window.__decklightProbe, out = [];
249
+ try {
250
+ for (var i = 1; i <= d.state.totalSlides; i++) { d.goto(i, ${LAST_STEP}); out.push(d.state.step); }
251
+ } catch (e) { out = ['err', String(e && e.message)]; }
252
+ var pre = document.createElement('pre');
253
+ pre.textContent = 'DECKLIGHT-BUILD-STEPS ' + JSON.stringify(out);
254
+ document.body.appendChild(pre);
255
+ }
256
+ if (document.readyState === 'complete') setTimeout(report, 30);
257
+ else window.addEventListener('load', function () { setTimeout(report, 30); });
258
+ })();
259
+ </script>`;
260
+
261
+ /** Make the deck's instance reachable, the way test/import-render.mjs does. */
262
+ const exposeInstance = (html) => html.replace(/\bDecklight\s*\.\s*init\s*\(/, 'window.__decklightProbe = Decklight.init(');
263
+
264
+ /** Parse the probe's answer out of a dumped DOM; null when it did not report. */
265
+ export function parseBuildSteps(dom, slides) {
266
+ const m = /DECKLIGHT-BUILD-STEPS (\[[^\]]*\])/.exec(dom);
267
+ if (!m) return null;
268
+ let counts;
269
+ try { counts = JSON.parse(m[1]); } catch { return null; }
270
+ if (!Array.isArray(counts) || counts.some((c) => !Number.isInteger(c) || c < 0)) return null;
271
+ return counts.length === slides ? counts : null;
272
+ }
273
+
274
+ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
275
+ const { opt } = argReader(argv);
276
+ const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
277
+ // Two different situations, and the stream and the exit code follow WHICH
278
+ // one happened rather than whether a deck was named. Asking for help is not
279
+ // a failure: it goes to stdout and exits 0, the way every other command
280
+ // answers `--help`. Naming no deck IS a failure: stderr, exit 1.
281
+ const wantsHelp = argv.includes('--help') || argv.includes('-h');
282
+ if (wantsHelp || !deckArg) {
283
+ (wantsHelp ? process.stdout : process.stderr).write(HELP);
284
+ process.exit(wantsHelp ? 0 : 1);
285
+ }
286
+ const deck = resolve(deckArg);
287
+ if (!existsSync(deck)) { console.error(`decklight video: no such deck: ${deck}`); process.exit(1); }
288
+
289
+ // The served root is the directory you run from — the deck must sit inside it
290
+ // so its relative assets (`../dist/decklight.js`, `themes/…`) resolve as URLs
291
+ // off the loopback origin the frames are captured against. This is `present`'s
292
+ // rule, for the same reason (#229): the deck runs under the CSP, and a read
293
+ // cannot escape the served tree. `cd` to a directory containing the deck.
294
+ const root = process.cwd();
295
+ if (deck !== root && !deck.startsWith(root + sep)) {
296
+ console.error(`decklight video: the deck must live under the current directory (${root}) — cd there first`);
297
+ process.exit(1);
298
+ }
299
+
300
+ // the voiceover encoder-detection policy: a missing tool is a hard, friendly
301
+ // error naming what to install — not a stack trace three steps later
302
+ if (!have('ffmpeg') || !have('ffprobe')) {
303
+ console.error('decklight video needs ffmpeg and ffprobe — install ffmpeg '
304
+ + '(apt install ffmpeg / brew install ffmpeg)');
305
+ process.exit(1);
306
+ }
307
+
308
+ let out; let plan; let narration;
309
+ try {
310
+ out = resolve(opt('-o', opt('--out', deck.replace(/\.html?$/i, '.mp4'))));
311
+ const { w, h } = parseSize(opt('--size', '1280x720'));
312
+ const fps = Number(opt('--fps', '30'));
313
+ const hold = Number(opt('--hold', '5'));
314
+ const buildHoldArg = opt('--build-hold');
315
+ const buildHold = buildHoldArg === undefined ? null : Number(buildHoldArg);
316
+ if (!Number.isFinite(fps) || fps <= 0) throw new Error(`--fps must be a positive number`);
317
+ if (!Number.isFinite(hold) || hold <= 0) throw new Error(`--hold must be positive seconds`);
318
+ if (buildHold !== null && (!Number.isFinite(buildHold) || buildHold <= 0)) {
319
+ throw new Error(`--build-hold must be positive seconds`);
320
+ }
321
+ const theme = opt('--theme');
322
+
323
+ const html = readFileSync(deck, 'utf8');
324
+ const holds = extractHolds(html, hold);
325
+ if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
326
+ const range = parseSlideRange(opt('--slides'), holds.length);
327
+
328
+ if (argv.includes('--voiceover')) {
329
+ const vo = [fileURLToPath(new URL('./voiceover.mjs', import.meta.url)), deck];
330
+ const nd = opt('--narration');
331
+ if (nd) vo.push('-o', resolve(nd));
332
+ const r = spawnSync(process.execPath, vo, { stdio: 'inherit' });
333
+ if (r.status !== 0) throw new Error('voiceover batch failed — see its output above');
334
+ }
335
+
336
+ narration = resolveNarration(deck, opt('--narration'));
337
+
338
+ // real durations, not the manifest's word count: ffprobe each audio file
339
+ const durations = {};
340
+ for (let n = range.from; n <= range.to; n++) {
341
+ const file = narration?.slides?.[n - 1]?.file;
342
+ if (!file || durations[file] != null) continue;
343
+ const path = join(narration.dir, file);
344
+ if (!existsSync(path)) {
345
+ console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk — holding ${holds[n - 1]}s of silence`);
346
+ continue;
347
+ }
348
+ durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
349
+ }
350
+
351
+
352
+ // --theme rides on the deck's response in memory (no temp file): only the
353
+ // deck itself gets the injected link; every other html asset under the root
354
+ // is served untouched. Over the loopback origin `themes/…` resolves exactly
355
+ // as the sibling-copy path used to, so a themed render is unchanged.
356
+ let probing = false;
357
+ const inject = (text, file) => {
358
+ if (resolve(file) !== deck) return text;
359
+ let out = theme
360
+ ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
361
+ : text;
362
+ if (probing) out = injectBeforeBodyEnd(exposeInstance(out), STEP_PROBE) ?? out;
363
+ return out;
364
+ };
365
+ const deckPath = '/' + relative(root, deck).split(sep).join('/');
366
+
367
+ const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
368
+ const server = await serveForRender(root, { html: inject });
369
+ try {
370
+ const chrome = chromeBin('video');
371
+
372
+ // Ask the deck how far each slide builds, in one extra load, before any
373
+ // frame is captured. A deck that will not answer is not an error: the
374
+ // plan falls back to one fully-built still per slide, which is what this
375
+ // command did before builds had frames of their own.
376
+ probing = true;
377
+ let steps = null;
378
+ try {
379
+ const dom = await exec(chrome, chromeArgs(
380
+ '--hide-scrollbars', `--window-size=${w},${h}`,
381
+ '--virtual-time-budget=2500', '--dump-dom', `${server.origin}${deckPath}`,
382
+ ), { maxBuffer: 64 * 1024 * 1024 });
383
+ steps = parseBuildSteps(dom.stdout, holds.length);
384
+ } catch { /* fall through to one frame per slide */ }
385
+ probing = false;
386
+ if (!steps) console.warn(' builds: the deck did not report its build steps — one still per slide');
387
+
388
+ plan = planTimeline(narration?.slides ?? null, durations, holds, range, { steps, buildHold });
389
+ const slideCount = new Set(plan.map((p) => p.slide)).size;
390
+ log(`${basename(deck)}: ${slideCount} slide${slideCount === 1 ? '' : 's'}, `
391
+ + `${plan.filter((p) => p.audio).length} narrated`
392
+ + (plan.length > slideCount ? `, ${plan.length} frames` : '')
393
+ + (narration ? ` (${narration.dir})` : ' (silent)'));
394
+
395
+ const segments = [];
396
+ let f = 0;
397
+ for (const p of plan) {
398
+ const nn = String(p.slide).padStart(2, '0');
399
+ const id = `${nn}-${String(f++).padStart(3, '0')}`;
400
+ const frame = join(work, `frame-${id}.png`);
401
+ // one one-shot Chrome per frame; LAST_STEP clamps to the last build
402
+ await exec(chrome, chromeArgs(
403
+ '--hide-scrollbars',
404
+ '--autoplay-policy=no-user-gesture-required',
405
+ `--window-size=${w},${h}`,
406
+ '--virtual-time-budget=1500',
407
+ `--screenshot=${frame}`,
408
+ `${server.origin}${deckPath}#/${p.slide}/${p.step}`,
409
+ ));
410
+ if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
411
+ const seg = join(work, `seg-${id}.mp4`);
412
+ await exec('ffmpeg', segmentArgs({
413
+ frame, duration: p.duration, fps, out: seg,
414
+ audio: p.audio ? join(narration.dir, p.audio) : null,
415
+ }));
416
+ segments.push(seg);
417
+ const where = p.step === LAST_STEP ? '' : ` · build ${p.step}`;
418
+ log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
419
+ }
420
+
421
+ const list = join(work, 'concat.txt');
422
+ writeFileSync(list, concatList(segments));
423
+ await exec('ffmpeg', concatArgs(list, out));
424
+ } finally {
425
+ await server.close();
426
+ rmSync(work, { recursive: true, force: true });
427
+ }
428
+
429
+ const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
430
+ log(`done → ${out} (${total.toFixed(1)}s)`);
431
+ } catch (e) {
432
+ console.error(`decklight video: ${e.message}`);
433
+ process.exit(1);
434
+ }
435
+ }
436
+
437
+ // direct execution still works: node tools/video.mjs deck.html -o deck.mp4
438
+ if (isMain(import.meta.url)) {
439
+ await videoMain(process.argv.slice(2));
440
+ }