decklight 0.3.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "A presentation library designed to be authored by AI agents and humans alike: single-file decks, Keynote-style builds, theme-aware SVG diagrams, and truthful terminal recordings.",
5
5
  "type": "module",
6
6
  "main": "dist/decklight.js",
@@ -36,8 +36,9 @@
36
36
  "scripts": {
37
37
  "build": "node build.mjs",
38
38
  "prepare": "npm run build",
39
- "test": "node --test test/*.test.mjs",
40
- "verify": "npm run build && node test/verify.mjs"
39
+ "test": "node test/run.mjs",
40
+ "verify": "npm run build && node test/verify.mjs",
41
+ "soak": "node test/soak.mjs"
41
42
  },
42
43
  "engines": {
43
44
  "node": ">=20"
package/tools/chrome.mjs CHANGED
@@ -8,27 +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
+ ]);
18
41
 
19
- /** The browser to drive: $CHROME wins, else the first one installed. */
20
42
  /**
21
- * Where Chrome is, or null — the non-fatal half. `decklight report-bug` needs
22
- * to REPORT that a machine has no Chrome, which it cannot do if merely asking
23
- * exits the process.
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.
24
50
  */
25
- export function findChrome() {
26
- return process.env.CHROME || process.env.DECKLIGHT_CHROME
27
- || CANDIDATES.find((p) => existsSync(p)) || null;
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;
28
54
  }
29
55
 
30
- export function chromeBin(who = 'chrome') {
31
- const bin = findChrome();
56
+ export function chromeBin(who = 'chrome', opts = {}) {
57
+ const bin = findChrome(opts);
32
58
  if (!bin) {
33
59
  console.error(`${who}: no Chrome found — install one, or point $CHROME at it`);
34
60
  process.exit(1);
@@ -125,7 +125,12 @@ export function validateTheme(css) {
125
125
 
126
126
  /** A theme name from a path or URL: the basename, minus .css. */
127
127
  export function themeNameFrom(source) {
128
- const last = String(source ?? '').split(/[?#]/)[0].split('/').filter(Boolean).pop() ?? '';
128
+ // Both separators, because `source` is either a URL (always `/`) or a local
129
+ // path (`\` on Windows). Splitting on `/` alone made the whole path the
130
+ // name there — `decklight theme check C:\themes\aurora.css` reported
131
+ // `✔ C:\themes\aurora`, and `theme add` would then have tried to install
132
+ // under a name validThemeName refuses, from a file that was perfectly fine.
133
+ const last = String(source ?? '').split(/[?#]/)[0].split(/[/\\]/).filter(Boolean).pop() ?? '';
129
134
  return last.replace(/\.css$/i, '');
130
135
  }
131
136
 
package/tools/video.mjs CHANGED
@@ -6,12 +6,14 @@
6
6
  //
7
7
  // decklight video deck.html -o deck.mp4
8
8
  // [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
9
- // [--theme <name>] [--slides a-b] [--voiceover]
9
+ // [--build-hold <s>] [--theme <name>] [--slides a-b] [--voiceover]
10
10
  //
11
- // One still per slide (final build state), each held for the duration of its
12
- // narration audio plus a short tail, muxed with that audio into one mp4 — a
13
- // deck with generated narration becomes a watchable, shareable video in one
14
- // command. Narration resolves --narration <dir> → <deckdir>/voiceover/
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/
15
17
  // (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
16
18
  // slide holds --hold seconds (per-slide override: data-video-hold="8" on the
17
19
  // section). Silent slides still carry a silent audio segment (anullsrc) so the
@@ -24,9 +26,11 @@
24
26
  // --allow-file-access-from-files (#229): that flag let a deck's own JS read any
25
27
  // local file and exfiltrate it, and video renders decks you may not have
26
28
  // vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
27
- // frames are stills, so the character overlay appears but frozen, and timing is
28
- // per-slide, not per-build-step (animated lipsync needs a CDP screencast — a
29
- // Node ≥22 follow-up).
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.
30
34
 
31
35
  import { execFile, execFileSync, spawnSync } from 'node:child_process';
32
36
  import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -36,7 +40,7 @@ import { promisify } from 'node:util';
36
40
  import { fileURLToPath } from 'node:url';
37
41
  import { chromeBin, chromeArgs } from './chrome.mjs';
38
42
  import { argReader, isMain } from './args.mjs';
39
- import { sectionBodies } from './deck-html.mjs';
43
+ import { injectBeforeBodyEnd, sectionBodies } from './deck-html.mjs';
40
44
  import { serveForRender } from '../cli/present.mjs';
41
45
 
42
46
  const run = promisify(execFile);
@@ -53,12 +57,16 @@ const HELP = `decklight video <deck.html> [options] — render the deck to a nar
53
57
  --fps <n> video frame rate (default 30)
54
58
  --hold <s> seconds a slide without narration holds (default 5;
55
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)
56
63
  --theme <name> render with themes/<name>.css instead of the deck's theme
57
64
  --slides <a-b> only this slide range (1-based, inclusive)
58
65
  --voiceover run the voiceover batch (tools/voiceover.mjs) first
59
66
 
60
- Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s; slides
61
- without hold --hold seconds over silence, so the audio track stays continuous.
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.
62
70
  Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
63
71
  `;
64
72
 
@@ -93,7 +101,34 @@ export function extractHolds(html, defaultHold) {
93
101
  }
94
102
 
95
103
  /**
96
- * The per-slide schedule: which audio plays under slide n, and for how long.
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.
97
132
  *
98
133
  * @param {Array|null} manifest manifest.slides from tools/voiceover.mjs
99
134
  * ({ file } per slide, null for silent slides) —
@@ -101,18 +136,28 @@ export function extractHolds(html, defaultHold) {
101
136
  * @param {object} durations audio file → real (ffprobe) seconds
102
137
  * @param {number[]} holds per-slide hold seconds (one per section)
103
138
  * @param {{from,to}} [range] 1-based inclusive slide range
104
- * @returns {Array<{slide, audio, duration}>} audio null ⇒ silent hold
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
105
143
  */
106
- export function planTimeline(manifest, durations, holds, range = null) {
144
+ export function planTimeline(manifest, durations, holds, range = null, { steps = null, buildHold = null } = {}) {
107
145
  const from = range?.from ?? 1;
108
146
  const to = range?.to ?? holds.length;
109
147
  const plan = [];
110
148
  for (let n = from; n <= to; n++) {
111
149
  const file = manifest?.[n - 1]?.file ?? null;
112
150
  const dur = file ? durations?.[file] : null;
113
- plan.push(Number.isFinite(dur)
114
- ? { slide: n, audio: file, duration: Math.round((dur + TAIL_SECONDS) * 1000) / 1000 }
115
- : { slide: n, audio: null, duration: holds[n - 1] });
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 });
116
161
  }
117
162
  return plan;
118
163
  }
@@ -184,12 +229,59 @@ const have = (bin) => {
184
229
  catch (e) { return e?.code !== 'ENOENT'; }
185
230
  };
186
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
+
187
274
  export async function videoMain(argv, { exec = run, log = console.log } = {}) {
188
275
  const { opt } = argReader(argv);
189
276
  const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
190
- if (argv.includes('--help') || !deckArg) {
191
- (deckArg ? process.stdout : process.stderr).write(HELP);
192
- process.exit(deckArg ? 0 : 1);
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);
193
285
  }
194
286
  const deck = resolve(deckArg);
195
287
  if (!existsSync(deck)) { console.error(`decklight video: no such deck: ${deck}`); process.exit(1); }
@@ -219,8 +311,13 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
219
311
  const { w, h } = parseSize(opt('--size', '1280x720'));
220
312
  const fps = Number(opt('--fps', '30'));
221
313
  const hold = Number(opt('--hold', '5'));
314
+ const buildHoldArg = opt('--build-hold');
315
+ const buildHold = buildHoldArg === undefined ? null : Number(buildHoldArg);
222
316
  if (!Number.isFinite(fps) || fps <= 0) throw new Error(`--fps must be a positive number`);
223
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
+ }
224
321
  const theme = opt('--theme');
225
322
 
226
323
  const html = readFileSync(deck, 'utf8');
@@ -251,47 +348,74 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
251
348
  durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
252
349
  }
253
350
 
254
- plan = planTimeline(narration?.slides ?? null, durations, holds, range);
255
- log(`${basename(deck)}: ${plan.length} slide${plan.length === 1 ? '' : 's'}, `
256
- + `${plan.filter((p) => p.audio).length} narrated`
257
- + (narration ? ` (${narration.dir})` : ' (silent)'));
258
351
 
259
352
  // --theme rides on the deck's response in memory (no temp file): only the
260
353
  // deck itself gets the injected link; every other html asset under the root
261
354
  // is served untouched. Over the loopback origin `themes/…` resolves exactly
262
355
  // as the sibling-copy path used to, so a themed render is unchanged.
263
- const inject = theme
264
- ? (text, file) => (resolve(file) === deck
356
+ let probing = false;
357
+ const inject = (text, file) => {
358
+ if (resolve(file) !== deck) return text;
359
+ let out = theme
265
360
  ? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
266
- : text)
267
- : null;
361
+ : text;
362
+ if (probing) out = injectBeforeBodyEnd(exposeInstance(out), STEP_PROBE) ?? out;
363
+ return out;
364
+ };
268
365
  const deckPath = '/' + relative(root, deck).split(sep).join('/');
269
366
 
270
367
  const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
271
368
  const server = await serveForRender(root, { html: inject });
272
369
  try {
273
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
+
274
395
  const segments = [];
396
+ let f = 0;
275
397
  for (const p of plan) {
276
398
  const nn = String(p.slide).padStart(2, '0');
277
- const frame = join(work, `frame-${nn}.png`);
278
- // one one-shot Chrome per frame; #/n/999 clamps to the last build step
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
279
402
  await exec(chrome, chromeArgs(
280
403
  '--hide-scrollbars',
281
404
  '--autoplay-policy=no-user-gesture-required',
282
405
  `--window-size=${w},${h}`,
283
406
  '--virtual-time-budget=1500',
284
407
  `--screenshot=${frame}`,
285
- `${server.origin}${deckPath}#/${p.slide}/999`,
408
+ `${server.origin}${deckPath}#/${p.slide}/${p.step}`,
286
409
  ));
287
410
  if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
288
- const seg = join(work, `seg-${nn}.mp4`);
411
+ const seg = join(work, `seg-${id}.mp4`);
289
412
  await exec('ffmpeg', segmentArgs({
290
413
  frame, duration: p.duration, fps, out: seg,
291
414
  audio: p.audio ? join(narration.dir, p.audio) : null,
292
415
  }));
293
416
  segments.push(seg);
294
- log(` slide ${nn}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
417
+ const where = p.step === LAST_STEP ? '' : ` · build ${p.step}`;
418
+ log(` slide ${nn}${where}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
295
419
  }
296
420
 
297
421
  const list = join(work, 'concat.txt');