decklight 0.9.0 → 0.10.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 (48) hide show
  1. package/PLATFORM.md +44 -3
  2. package/README.md +7 -5
  3. package/SPEC.md +100 -31
  4. package/cli/agent-review.mjs +5 -4
  5. package/cli/agents.mjs +11 -5
  6. package/cli/bundle-audio.mjs +10 -3
  7. package/cli/bundle-module.mjs +95 -0
  8. package/cli/bundle.mjs +58 -6
  9. package/cli/cast.mjs +41 -5
  10. package/cli/check-fixes.mjs +186 -0
  11. package/cli/check.mjs +32 -5
  12. package/cli/commit-flow.mjs +7 -3
  13. package/cli/commit-message.mjs +1 -1
  14. package/cli/commit-split.mjs +2 -2
  15. package/cli/deck-refs.mjs +8 -3
  16. package/cli/design-system-refs.mjs +263 -6
  17. package/cli/design-system.mjs +82 -14
  18. package/cli/edit-git.mjs +2 -2
  19. package/cli/edit-handover.mjs +129 -23
  20. package/cli/edit-look.mjs +248 -5
  21. package/cli/edit.mjs +504 -58
  22. package/cli/enhance.mjs +12 -10
  23. package/cli/git.mjs +13 -0
  24. package/cli/init.mjs +8 -3
  25. package/cli/marketplace-autocheck.mjs +200 -0
  26. package/cli/marketplace.mjs +250 -13
  27. package/cli/narrate.mjs +78 -3
  28. package/cli/open.mjs +24 -6
  29. package/cli/pdf.mjs +27 -8
  30. package/cli/pptx-export.mjs +7 -4
  31. package/cli/record.mjs +73 -13
  32. package/cli/remote.mjs +32 -6
  33. package/cli/serve.mjs +2 -2
  34. package/cli/skill-content.mjs +40 -3
  35. package/cli/skills.mjs +247 -3
  36. package/cli/theme-refs.mjs +14 -2
  37. package/cli/units.mjs +75 -7
  38. package/dist/build-info.json +1 -1
  39. package/dist/decklight.css +429 -32
  40. package/dist/decklight.js +169 -123
  41. package/dist/decklight.js.map +4 -4
  42. package/package.json +1 -1
  43. package/tools/design-system-format.mjs +25 -0
  44. package/tools/design-system-migrations.mjs +207 -0
  45. package/tools/exec.mjs +10 -2
  46. package/tools/narration-manifest.mjs +77 -3
  47. package/tools/site-clip.mjs +114 -0
  48. package/tools/video.mjs +69 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "decklight",
3
- "version": "0.9.0",
3
+ "version": "0.10.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",
@@ -26,6 +26,7 @@
26
26
  // references, and the CSS reaches nothing outside its own package.
27
27
 
28
28
  import { SEMVER_RE } from './semver.mjs';
29
+ import { migrationShapeProblems, migrationNameProblems, migrationsOf, RENAME_KINDS } from './design-system-migrations.mjs';
29
30
  import { readScales, expandThemes, paletteEntries, offPaletteTokens, offRoleColours, nearestRole, roleToken, COLOUR_TOKENS, WEIGHTS } from './brand-palette.mjs';
30
31
 
31
32
  /**
@@ -199,6 +200,8 @@ export function readManifest(raw) {
199
200
  if (m.recommendedFonts !== undefined && (!Array.isArray(m.recommendedFonts) || !m.recommendedFonts.every((t) => typeof t === 'string'))) {
200
201
  at('manifest-field', 'recommendedFonts', 'recommendedFonts must be an array of font names — a font package (name or name@marketplace) or a font-picker stack');
201
202
  }
203
+ // what a major version renamed (SPEC DESIGN_SYSTEM_MIGRATIONS): its shape here, its names in checkPackage
204
+ for (const p of migrationShapeProblems(m)) at('migration', 'migrations', p.msg);
202
205
  return { manifest: m, problems };
203
206
  }
204
207
 
@@ -209,6 +212,8 @@ function parseThemeTokens(css) {
209
212
  return out;
210
213
  }
211
214
 
215
+ const isObjLike = (v) => v && typeof v === 'object' && !Array.isArray(v);
216
+
212
217
  /** The token prefix a manifest holds its CSS to. */
213
218
  export const tokenPrefixOf = (manifest) => manifest?.tokenPrefix ?? `--${manifest?.name ?? ''}-`;
214
219
 
@@ -749,5 +754,25 @@ export function checkPackage(pkg) {
749
754
  : summary.brand ? `${summary.brand.scales.length} colours, ${summary.brand.palette.length} swatches${summary.brand.palette.some((e) => e.derived) ? ` (${summary.brand.palette.filter((e) => e.derived).length} derived)` : ''}` : 0;
750
755
  summary.recommendedThemes = manifest.recommendedThemes ?? [];
751
756
  summary.recommendedFonts = manifest.recommendedFonts ?? [];
757
+
758
+ // every name a migration renamed is gone from this version, every successor
759
+ // here (SPEC DESIGN_SYSTEM_MIGRATIONS) — held only once the files they are
760
+ // read from were readable, and the shape itself passed
761
+ if (manifest.migrations !== undefined && stylesRead && !mp.some((p) => p.rule === 'migration')) {
762
+ const css = files.get(stylesPath)?.text ?? '';
763
+ const templatesText = (templatesPath && files.get(templatesPath)?.text) || '';
764
+ const classes = new Set();
765
+ for (const c of css.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\{[^{}]*\}/g, '{}').matchAll(/\.(-?[A-Za-z_][A-Za-z0-9_-]*)/g)) classes.add(c[1]);
766
+ for (const a of templatesText.matchAll(/\bclass\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)) for (const c of (a[1] ?? a[2]).split(/\s+/)) if (c) classes.add(c);
767
+ const roleIds = isObjLike(manifest.roles) ? Object.keys(manifest.roles) : [];
768
+ const has = {
769
+ roles: new Set(roleIds),
770
+ tokens: new Set([...summary.tokens, ...(summary.brand?.palette ?? []).map((e) => e.token), ...roleIds.map((id) => roleToken(prefix ?? '', id))]),
771
+ classes,
772
+ themes: new Set([...(summary.brand?.themes ?? []).map((t) => t.name), ...(Array.isArray(manifest.recommendedThemes) ? manifest.recommendedThemes.map((t) => String(t).split('@')[0]) : [])]),
773
+ };
774
+ for (const p of migrationNameProblems(manifest, has)) problems.push({ file: 'design-system.json', line: keyLine(pkg.manifest, 'migrations'), rule: 'migration', msg: p.msg });
775
+ }
776
+ summary.migrations = migrationsOf(manifest).map((m) => ({ version: m.version, skill: m.skill, renames: RENAME_KINDS.reduce((n, k) => n + Object.keys(m[k]).length, 0) }));
752
777
  return { ok: problems.length === 0, problems, warnings, summary };
753
778
  }
@@ -0,0 +1,207 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * A design system's declared migrations (SPEC DESIGN_SYSTEM_MIGRATIONS): what
6
+ * a major version renamed, so decklight knows a deck is behind without
7
+ * guessing, says it once, and can apply the renames itself.
8
+ *
9
+ * "migrations": {
10
+ * "6.0.0": {
11
+ * "skill": "acme-migrate",
12
+ * "roles": { "text-diagram-blue": "text-diagram-default" },
13
+ * "tokens": { "--acme-font-size-body-lg": "--acme-font-size-body-xl" },
14
+ * "classes": { "acme-tile--zest": "acme-tile--secondary-3" },
15
+ * "themes": { "acme-devrel": "acme-dark" }
16
+ * }
17
+ * }
18
+ *
19
+ * A key is the version that made the change. Every rename is a WHOLE name:
20
+ * a role id (the slide writes its token, `--<prefix>color-<role>`), a custom
21
+ * property, a class, a theme. Pure — no file is read here; the gate, `check`,
22
+ * the servers and `design-system migrate` hand in the text.
23
+ */
24
+
25
+ import { SEMVER_RE, semverCompare } from './semver.mjs';
26
+
27
+ /** The four kinds of name a migration renames, in the order they are said. */
28
+ export const RENAME_KINDS = ['roles', 'tokens', 'classes', 'themes'];
29
+ const ONE = { roles: 'role', tokens: 'token', classes: 'class', themes: 'theme' };
30
+
31
+ const ID_RE = /^[a-z][a-z0-9-]*$/;
32
+ const SHAPES = {
33
+ roles: [ID_RE, 'a role id (a lowercase word, e.g. "text-heading-main")'],
34
+ tokens: [/^--[A-Za-z0-9_-]+$/, 'a custom property, "--…"'],
35
+ classes: [/^-?[A-Za-z_][A-Za-z0-9_-]*$/, 'a class name, without the dot'],
36
+ themes: [ID_RE, 'a theme name'],
37
+ };
38
+
39
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
40
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
41
+ /** A name as a whole word of CSS or HTML: not inside a longer identifier. */
42
+ const whole = (name) => new RegExp(`(?<![\\w-])${escapeRe(name)}(?![\\w-])`, 'g');
43
+
44
+ /** The major of a semver version, or null. */
45
+ export const majorOf = (v) => (SEMVER_RE.test(String(v ?? '')) ? Number(String(v).split('.')[0]) : null);
46
+
47
+ /**
48
+ * What is wrong with a manifest's `migrations`, as `[{ msg }]` — its shape
49
+ * only: every key a semver version no later than the package's own, every
50
+ * value `{ skill?, roles?, tokens?, classes?, themes? }` of whole names.
51
+ */
52
+ export function migrationShapeProblems(m) {
53
+ const out = [];
54
+ if (m.migrations === undefined) return out;
55
+ if (!isObj(m.migrations)) return [{ msg: 'migrations must be { "<version>": { "roles": { "<old>": "<new>" }, … } }, one entry per version that renamed something' }];
56
+ for (const [version, mig] of Object.entries(m.migrations)) {
57
+ if (!SEMVER_RE.test(version)) { out.push({ msg: `migrations: "${version}" is not a semver version — key each migration by the version that made it` }); continue; }
58
+ if (SEMVER_RE.test(String(m.version ?? '')) && semverCompare(version, m.version) > 0) {
59
+ out.push({ msg: `migrations: ${version} is later than this package's version ${m.version}` });
60
+ }
61
+ if (!isObj(mig)) { out.push({ msg: `migrations: ${version} must be { "skill"?, "roles"?, "tokens"?, "classes"?, "themes"? }` }); continue; }
62
+ for (const key of Object.keys(mig)) {
63
+ if (key !== 'skill' && !RENAME_KINDS.includes(key)) out.push({ msg: `migrations: ${version} has "${key}" — a migration renames roles, tokens, classes and themes, and may name a skill` });
64
+ }
65
+ if (mig.skill !== undefined && (typeof mig.skill !== 'string' || !ID_RE.test(mig.skill))) {
66
+ out.push({ msg: `migrations: ${version}.skill ${JSON.stringify(mig.skill)} — the name of a marketplace skill (decklight library add skill <name>)` });
67
+ }
68
+ for (const kind of RENAME_KINDS) {
69
+ if (mig[kind] === undefined) continue;
70
+ if (!isObj(mig[kind])) { out.push({ msg: `migrations: ${version}.${kind} must be { "<old>": "<new>" }` }); continue; }
71
+ const [re, what] = SHAPES[kind];
72
+ for (const [from, to] of Object.entries(mig[kind])) {
73
+ if (!re.test(from) || typeof to !== 'string' || !re.test(to)) out.push({ msg: `migrations: ${version}.${kind} "${from}" → ${JSON.stringify(to)} — each side is ${what}` });
74
+ else if (from === to) out.push({ msg: `migrations: ${version}.${kind} renames "${from}" to itself` });
75
+ }
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /** The migrations in version order, each `{ version, skill, roles, tokens, classes, themes }` — only well-formed ones. */
82
+ export function migrationsOf(manifest) {
83
+ const all = isObj(manifest?.migrations) ? manifest.migrations : {};
84
+ return Object.entries(all)
85
+ .filter(([v, mig]) => SEMVER_RE.test(v) && isObj(mig))
86
+ .map(([version, mig]) => ({
87
+ version,
88
+ skill: typeof mig.skill === 'string' ? mig.skill : null,
89
+ ...Object.fromEntries(RENAME_KINDS.map((k) => [k, isObj(mig[k]) ? Object.fromEntries(Object.entries(mig[k]).filter(([, to]) => typeof to === 'string')) : {}])),
90
+ }))
91
+ .sort((a, b) => semverCompare(a.version, b.version));
92
+ }
93
+
94
+ /**
95
+ * The migrations a deck written for `from` has still to take, up to the
96
+ * package's own version: every one after `from`, or every one when the deck
97
+ * records no version.
98
+ */
99
+ export function pendingMigrations(manifest, from = null) {
100
+ return migrationsOf(manifest).filter((m) => (!from || !SEMVER_RE.test(from) || semverCompare(m.version, from) > 0)
101
+ && (!SEMVER_RE.test(String(manifest?.version ?? '')) || semverCompare(m.version, manifest.version) <= 0));
102
+ }
103
+
104
+ /**
105
+ * The renames of several migrations as one map per kind, chains followed: a
106
+ * name renamed in 5.0.0 and its successor again in 6.0.0 goes straight to the
107
+ * last one, so a deck two majors behind is moved in one pass. Each value is
108
+ * `{ to, version }` — the version of the LAST rename on the way.
109
+ */
110
+ export function composeRenames(migrations) {
111
+ const out = Object.fromEntries(RENAME_KINDS.map((k) => [k, {}]));
112
+ for (const m of migrations) {
113
+ for (const kind of RENAME_KINDS) {
114
+ const map = out[kind];
115
+ for (const [from, to] of Object.entries(m[kind])) {
116
+ for (const r of Object.values(map)) if (r.to === from) { r.to = to; r.version = m.version; }
117
+ if (!map[from]) map[from] = { to, version: m.version };
118
+ }
119
+ }
120
+ }
121
+ return out;
122
+ }
123
+
124
+ /** A role id's token, as a slide writes it — the shape `roleToken` gives (SPEC DESIGN_SYSTEM_ROLES). */
125
+ const roleTokenOf = (prefix, id) => `${prefix}color-${id}`;
126
+
127
+ /**
128
+ * Every renamed name the texts still use: `[{ kind, from, to, version, as }]`,
129
+ * `as` the spelling found (a role is found as its token). Classes are looked
130
+ * for in `class` attributes and in CSS selectors, themes as the configured
131
+ * `"theme"`; roles and tokens anywhere, as whole names.
132
+ */
133
+ export function findRenamed(texts, renames, prefix) {
134
+ const found = [];
135
+ const body = [].concat(texts).join('\n');
136
+ const classAttrs = [...body.matchAll(/\bclass\s*=\s*(?:"([^"]*)"|'([^']*)')/gi)].map((m) => ` ${m[1] ?? m[2]} `).join(' ');
137
+ for (const [from, r] of Object.entries(renames.roles ?? {})) {
138
+ const as = roleTokenOf(prefix, from);
139
+ if (whole(as).test(body)) found.push({ kind: 'roles', from, to: r.to, version: r.version, as });
140
+ }
141
+ for (const [from, r] of Object.entries(renames.tokens ?? {})) {
142
+ if (whole(from).test(body)) found.push({ kind: 'tokens', from, to: r.to, version: r.version, as: from });
143
+ }
144
+ for (const [from, r] of Object.entries(renames.classes ?? {})) {
145
+ if (whole(from).test(classAttrs) || new RegExp(`\\.${escapeRe(from)}(?![\\w-])`).test(body)) found.push({ kind: 'classes', from, to: r.to, version: r.version, as: from });
146
+ }
147
+ for (const [from, r] of Object.entries(renames.themes ?? {})) {
148
+ if (new RegExp(`"theme"\\s*:\\s*"${escapeRe(from)}"`).test(body)) found.push({ kind: 'themes', from, to: r.to, version: r.version, as: from });
149
+ }
150
+ return found;
151
+ }
152
+
153
+ /**
154
+ * The renames applied to one text: roles (as tokens) and tokens wherever they
155
+ * stand as whole names, classes in `class` attributes and in selectors, and
156
+ * — when `config` is true, for the deck — the configured `"theme"`. Nothing
157
+ * else changes, byte for byte. Returns `{ text, count }`.
158
+ */
159
+ export function applyRenames(text, renames, prefix, { config = false } = {}) {
160
+ let count = 0;
161
+ let out = String(text);
162
+ const swap = (re, to) => { out = out.replace(re, () => { count++; return to; }); };
163
+ for (const [from, r] of Object.entries(renames.roles ?? {})) swap(whole(roleTokenOf(prefix, from)), roleTokenOf(prefix, r.to));
164
+ for (const [from, r] of Object.entries(renames.tokens ?? {})) swap(whole(from), r.to);
165
+ const classes = Object.entries(renames.classes ?? {});
166
+ if (classes.length) {
167
+ out = out.replace(/(\bclass\s*=\s*)(?:"([^"]*)"|'([^']*)')/gi, (all, lead, dq, sq) => {
168
+ const q = dq !== undefined ? '"' : "'";
169
+ let v = dq ?? sq;
170
+ for (const [from, r] of classes) v = v.replace(whole(from), () => { count++; return r.to; });
171
+ return `${lead}${q}${v}${q}`;
172
+ });
173
+ for (const [from, r] of classes) swap(new RegExp(`\\.${escapeRe(from)}(?![\\w-])`, 'g'), `.${r.to}`);
174
+ }
175
+ if (config) {
176
+ for (const [from, r] of Object.entries(renames.themes ?? {})) {
177
+ out = out.replace(new RegExp(`("theme"\\s*:\\s*")${escapeRe(from)}"`, 'g'), (all, lead) => { count++; return `${lead}${r.to}"`; });
178
+ }
179
+ }
180
+ return { text: out, count };
181
+ }
182
+
183
+ /**
184
+ * The gate's half (DESIGN_SYSTEM_MIGRATIONS): a migration's names, against
185
+ * the package as it now is. Every old name must be gone — a rename that
186
+ * leaves it is not one — and every new name present, unless a later
187
+ * migration renamed it again. `has` is `{ roles, tokens, classes, themes }`,
188
+ * each a Set of what the package defines. Returns `[{ msg }]`.
189
+ */
190
+ export function migrationNameProblems(manifest, has) {
191
+ const out = [];
192
+ const migrations = migrationsOf(manifest);
193
+ migrations.forEach((m, i) => {
194
+ const later = migrations.slice(i + 1);
195
+ for (const kind of RENAME_KINDS) {
196
+ const set = has[kind];
197
+ if (!set) continue;
198
+ for (const [from, to] of Object.entries(m[kind])) {
199
+ if (set.has(from)) out.push({ msg: `migrations: ${m.version} renames ${ONE[kind]} "${from}", which this version still defines — a renamed name is gone from the new version` });
200
+ if (!set.has(to) && !later.some((n) => Object.hasOwn(n[kind], to))) {
201
+ out.push({ msg: `migrations: ${m.version} renames ${ONE[kind]} "${from}" to "${to}", which this version does not define` });
202
+ }
203
+ }
204
+ }
205
+ });
206
+ return out;
207
+ }
package/tools/exec.mjs CHANGED
@@ -69,11 +69,19 @@ export function run(bin, args, { timeout = NETWORK_MS, why = '', ...opts } = {})
69
69
  *
70
70
  * Use this — never `run` — whenever the process that spawns the child is also
71
71
  * serving it (tools/shot.mjs, tools/video.mjs, cli/pptx-export.mjs).
72
+ *
73
+ * A `signal` stops the child (SIGKILL, like the timeout) and rejects with the
74
+ * AbortError itself, so a caller can tell "stopped" from "hung".
72
75
  */
73
- export function runAsync(bin, args, { timeout = NETWORK_MS, why = '', ...opts } = {}) {
76
+ export function runAsync(bin, args, { timeout = NETWORK_MS, why = '', signal = null, ...opts } = {}) {
74
77
  return new Promise((resolve, reject) => {
75
- execFile(bin, args, { ...opts, timeout, killSignal: 'SIGKILL' }, (e, stdout, stderr) => {
78
+ // execFile throws on `signal: null`, which is what a caller with nothing
79
+ // that could stop it (the command line) passes along
80
+ execFile(bin, args, { ...opts, ...(signal ? { signal } : {}), timeout, killSignal: 'SIGKILL' }, (e, stdout, stderr) => {
76
81
  if (!e) return resolve(stdout);
82
+ // `signal` aborted: somebody STOPPED it (the edit server's stop routes),
83
+ // which is not a hang and must not read as one
84
+ if (e.name === 'AbortError') return reject(e);
77
85
  if (e.killed || e.code === 'ETIMEDOUT' || (e.signal === 'SIGKILL' && e.status == null)) {
78
86
  const err = new Error(`${bin} hung for ${Math.round(timeout / 1000)}s and was killed`
79
87
  + (why ? ` — ${why}` : ''));
@@ -19,7 +19,7 @@
19
19
  import { createHash } from 'node:crypto';
20
20
  import { cacheKey } from './tts-cache.mjs';
21
21
  import { readsAudioTags } from './elevenlabs-tts.mjs';
22
- import { sectionBodies, NOTES_ASIDE, cleanNotes, readNotes, isHiddenSection } from './deck-html.mjs';
22
+ import { sectionBodies, NOTES_ASIDE, cleanNotes, readNotes, isHiddenSection, notesSegments } from './deck-html.mjs';
23
23
  import { deckConfig } from '../cli/runtime-link.mjs';
24
24
  import { PAUSE_MARK } from './sentences.mjs';
25
25
 
@@ -170,6 +170,77 @@ export function staleSlides(manifest, texts, range = null, prior = null) {
170
170
  return out;
171
171
  }
172
172
 
173
+ /**
174
+ * Each slide's beats as a reader is shown them: the ⟨CLICK⟩ segments with
175
+ * words, ⟨PAUSE⟩ kept, or the whole slide as one beat when it is not
176
+ * segmented; [] for a slide with nothing to say. Index i is slide i+1.
177
+ *
178
+ * What your own voice's manifest records per slide (#850). A hash says THAT
179
+ * the notes moved; this says how: a recorded beat is cut where you pressed →,
180
+ * so moving a ⟨CLICK⟩ changes nothing you hear, and the one fix is to read
181
+ * those beats again. A synthesized track is re-voiced from the notes, so
182
+ * its hash is all it needs.
183
+ */
184
+ export const slideBeats = (html) => slideNotes(html).map((raw) => {
185
+ if (!raw) return [];
186
+ const segs = notesSegments(raw, { marks: true });
187
+ if (segs) return segs;
188
+ const text = cleanNotes(raw, { marks: true });
189
+ return text ? [text] : [];
190
+ });
191
+
192
+ /**
193
+ * How a slide recorded in your own voice differs from its notes now: null in
194
+ * step; `{ why: 'text' }` when the words moved; `{ why: 'clicks', was, now }`
195
+ * when the words are the same and only the ⟨CLICK⟩ split moved (`was`/`now`
196
+ * the beat counts). `undefined` when the entry carries no record of what was
197
+ * read (anything recorded before #850): unknown, which is never a verdict.
198
+ */
199
+ export function scriptDrift(entry, beats) {
200
+ if (!Array.isArray(entry?.beats)) return undefined;
201
+ const was = entry.beats.map(String);
202
+ const now = (beats ?? []).map(String);
203
+ if (was.length === now.length && was.every((b, k) => b === now[k])) return null;
204
+ const words = (list) => list.join(' ').replace(/\s+/g, ' ').trim();
205
+ if (words(was) === words(now)) return { why: 'clicks', was: was.length, now: now.length };
206
+ return { why: 'text' };
207
+ }
208
+
209
+ /**
210
+ * Every slide of `manifest` out of step with the deck: `drift` lists
211
+ * `{ slide, why, was?, now? }`, from the beats a take of your own voice
212
+ * recorded, else from the notes hash; `unknown` counts the slides that carry
213
+ * neither (recorded by hand before either existed), which are left alone.
214
+ */
215
+ export function trackDrift(manifest, html) {
216
+ const out = { drift: [], unknown: 0 };
217
+ const beats = slideBeats(html);
218
+ const texts = slideTexts(html);
219
+ const prior = priorSlideTexts(html);
220
+ const slides = manifest?.slides ?? [];
221
+ for (let i = 0; i < slides.length; i++) {
222
+ const entry = slides[i];
223
+ if (!entry) continue;
224
+ const d = scriptDrift(entry, beats[i]);
225
+ if (d) { out.drift.push({ slide: i + 1, ...d }); continue; }
226
+ if (d === null) continue;
227
+ if (!entry.hash) { out.unknown++; continue; }
228
+ if (entryMatches(manifest, entry, texts[i] ?? '')) continue;
229
+ if (manifest.recorder === 'deck' && prior[i] && entryMatches(manifest, entry, prior[i])) continue;
230
+ out.drift.push({ slide: i + 1, why: 'text' });
231
+ }
232
+ return out;
233
+ }
234
+
235
+ /**
236
+ * What a re-record of `slides` takes, as a line to paste: your own voice at
237
+ * the microphone, or the track's engine from the notes.
238
+ */
239
+ export function rerecordLine(deck, dir, slides, { mine = false } = {}) {
240
+ const range = slides.length === 1 ? String(slides[0]) : `${Math.min(...slides)}-${Math.max(...slides)}`;
241
+ return `decklight narrate ${deck}${mine ? ' --mic' : ''} --slides ${range} --dir ${dir}`;
242
+ }
243
+
173
244
  /**
174
245
  * The manifest the deck recorder writes, after each slide of a take (#535):
175
246
  * `recorded` maps slide number → its beat file numbers; every slide inside
@@ -177,7 +248,7 @@ export function staleSlides(manifest, texts, range = null, prior = null) {
177
248
  * `prev`'s entry — a ranged re-record is a surgical redo, the same promise
178
249
  * `voiceover --slides` makes. Files are wav: the recorder stitches WAV.
179
250
  */
180
- export function recorderManifest({ prev, header, texts, range, recorded }) {
251
+ export function recorderManifest({ prev, header, texts, range, recorded, recorder = 'deck', beats = null }) {
181
252
  const total = Math.max(texts.length, prev?.slides?.length ?? 0);
182
253
  const slides = [];
183
254
  for (let i = 0; i < total; i++) {
@@ -189,8 +260,11 @@ export function recorderManifest({ prev, header, texts, range, recorded }) {
189
260
  const entry = { file: `slide-${nn}.wav`, hash: manifestHash(header, texts[i] ?? '') };
190
261
  const segs = (take.segments ?? []).filter((k) => Number.isInteger(k) && k > 0);
191
262
  if (segs.length) entry.segments = segs.map((k) => ({ file: `slide-${nn}-${String(k).padStart(2, '0')}.wav` }));
263
+ // your own voice: the beats as you read them, which is what tells a moved
264
+ // ⟨CLICK⟩ from changed words (scriptDrift)
265
+ if (beats) entry.beats = beats[i] ?? [];
192
266
  slides.push(entry);
193
267
  }
194
268
  const { engine, model, voice, style } = header;
195
- return { engine, model, voice, style, recorder: 'deck', slides };
269
+ return { engine, model, voice, style, recorder, slides };
196
270
  }
@@ -0,0 +1,114 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The narration clip on decklight.io: one showcase slide, narrated by the
5
+ // site's own voice track with captions on, its builds stepping with the voice.
6
+ // It is a RECORDING of the live deck, not a `decklight video` render: a render
7
+ // is one still per build step, so the strokes drawing in and the caption bar
8
+ // following the voice would never be in it.
9
+ //
10
+ // node tools/site-voices.mjs pull the voice track → site/voices/ (once)
11
+ // node tools/site-clip.mjs re-record site/img/narration.{webm,mp4,jpg}
12
+ //
13
+ // It bundles the showcase the way the site deploy does, with the voice track's
14
+ // per-beat clips switched on (segments), serves it on 127.0.0.1, plays the
15
+ // slide in Chrome (Playwright) and keeps the stretch from the first build to
16
+ // the last one plus a short hold, muted, as VP9 WebM, an H.264 MP4 for older
17
+ // Safari, and a poster frame. Re-run it when the slide or its notes change.
18
+ // Needs Playwright, Chrome and ffmpeg; never runs in CI.
19
+
20
+ import fs from 'node:fs';
21
+ import http from 'node:http';
22
+ import os from 'node:os';
23
+ import path from 'node:path';
24
+ import { execFileSync } from 'node:child_process';
25
+ import { fileURLToPath } from 'node:url';
26
+
27
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
28
+ const args = process.argv.slice(2);
29
+ const opt = (name, fallback) => { const i = args.indexOf(name); return i === -1 ? fallback : args[i + 1]; };
30
+ const SLIDE = Number(opt('--slide', 7));
31
+ const OUT = path.resolve(ROOT, opt('--out', 'site/img/narration'));
32
+ const HOLD_MS = Number(opt('--hold', 2500));
33
+ const LIMIT_MS = 90_000;
34
+
35
+ const cfg = JSON.parse(fs.readFileSync(path.join(ROOT, 'site/voices.json'), 'utf8'));
36
+ const voices = path.join(ROOT, cfg.dir);
37
+ if (!fs.existsSync(path.join(voices, path.basename(cfg.voices[0].dir), 'manifest.json'))) {
38
+ console.error(`no voice track in ${cfg.dir}/ — run: node tools/site-voices.mjs pull`);
39
+ process.exit(1);
40
+ }
41
+
42
+ // ── the showcase, bundled with its voice, as the deploy does ─────────────────
43
+ const work = fs.mkdtempSync(path.join(os.tmpdir(), 'decklight-site-clip-'));
44
+ const site = path.join(work, 'site');
45
+ fs.mkdirSync(site);
46
+ fs.cpSync(voices, path.join(site, 'voices'), { recursive: true });
47
+ execFileSync(process.execPath, [path.join(ROOT, 'cli/decklight.mjs'), 'bundle', path.join(ROOT, cfg.deck),
48
+ '--themes', 'all', '-o', path.join(site, 'showcase.html')], { stdio: 'ignore' });
49
+ {
50
+ // segments: the per-beat clips drive the builds, one beat per [click]
51
+ const files = cfg.voices.map((v) => `{ label: ${JSON.stringify(v.label)}, dir: ${JSON.stringify(v.dir)}, segments: true }`).join(', ');
52
+ const p = path.join(site, 'showcase.html');
53
+ const html = fs.readFileSync(p, 'utf8');
54
+ const out = html.replace('Decklight.init({', `Decklight.init({\n narration: { files: [${files}] },`);
55
+ if (out === html) throw new Error('init config anchor not found in the bundled showcase');
56
+ fs.writeFileSync(p, out);
57
+ }
58
+
59
+ const TYPES = { '.html': 'text/html', '.m4a': 'audio/mp4', '.json': 'application/json', '.txt': 'text/plain' };
60
+ const server = http.createServer((req, res) => {
61
+ const rel = decodeURIComponent(new URL(req.url, 'http://x').pathname);
62
+ const file = path.join(site, rel);
63
+ if (!file.startsWith(site) || !fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404).end(); return; }
64
+ res.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream' });
65
+ fs.createReadStream(file).pipe(res);
66
+ });
67
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
68
+ const base = `http://127.0.0.1:${server.address().port}`;
69
+
70
+ // ── play the slide and record it ─────────────────────────────────────────────
71
+ const { chromium } = await import('playwright');
72
+ const browser = await chromium.launch({ channel: 'chrome', args: ['--autoplay-policy=no-user-gesture-required'] });
73
+ const videoDir = path.join(work, 'video');
74
+ const ctx = await browser.newContext({ viewport: { width: 1280, height: 720 }, recordVideo: { dir: videoDir, size: { width: 1280, height: 720 } } });
75
+ const recordingFrom = Date.now();
76
+ const page = await ctx.newPage();
77
+ // ?embedded hides the controls and saves nothing; &captions shows the caption bar
78
+ await page.goto(`${base}/showcase.html?embedded&captions&voiceover#/${SLIDE}/0`, { waitUntil: 'networkidle' });
79
+ await page.evaluate(() => {
80
+ // the engine dispatches on the deck's root, and the event does not bubble
81
+ window.__steps = [];
82
+ document.querySelector('.decklight').addEventListener('decklight:build',
83
+ (e) => window.__steps.push({ at: Date.now(), index: e.detail.index, total: e.detail.total }));
84
+ });
85
+ await page.waitForTimeout(500);
86
+ await page.keyboard.press('Shift'); // the gesture ?voiceover waits for, without moving the deck
87
+ const deadline = Date.now() + LIMIT_MS;
88
+ let steps = [];
89
+ while (Date.now() < deadline) {
90
+ steps = await page.evaluate(() => window.__steps);
91
+ if (steps.length && steps.at(-1).index >= steps.at(-1).total) break;
92
+ await page.waitForTimeout(250);
93
+ }
94
+ if (!steps.length) throw new Error(`slide ${SLIDE} never stepped: is the voice track playing?`);
95
+ await page.waitForTimeout(HOLD_MS);
96
+ const video = await page.video().path();
97
+ await ctx.close();
98
+ await browser.close();
99
+ server.close();
100
+
101
+ // ── cut from just before the first build to the hold after the last ──────────
102
+ const from = Math.max(0, (steps[0].at - recordingFrom) / 1000 - 0.8);
103
+ const to = (steps.at(-1).at - recordingFrom + HOLD_MS) / 1000;
104
+ const ff = (...a) => execFileSync('ffmpeg', ['-loglevel', 'error', '-y', ...a], { stdio: 'inherit' });
105
+ const cut = ['-ss', from.toFixed(2), '-to', to.toFixed(2), '-i', video, '-vf', 'scale=960:-2', '-an'];
106
+ fs.mkdirSync(path.dirname(OUT), { recursive: true });
107
+ ff(...cut, '-c:v', 'libvpx-vp9', '-crf', '34', '-b:v', '0', '-row-mt', '1', `${OUT}.webm`);
108
+ ff(...cut, '-c:v', 'libx264', '-crf', '26', '-preset', 'slow', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', `${OUT}.mp4`);
109
+ ff('-sseof', '-0.3', '-i', `${OUT}.mp4`, '-frames:v', '1', '-q:v', '4', `${OUT}.jpg`);
110
+ fs.rmSync(work, { recursive: true, force: true });
111
+
112
+ const kb = (f) => `${Math.round(fs.statSync(f).size / 1024)} KB`;
113
+ console.log(`slide ${SLIDE}: ${steps.length} builds, ${(to - from).toFixed(1)}s`
114
+ + ` → ${path.relative(ROOT, OUT)}.webm (${kb(`${OUT}.webm`)}), .mp4 (${kb(`${OUT}.mp4`)}), .jpg (${kb(`${OUT}.jpg`)})`);
package/tools/video.mjs CHANGED
@@ -33,7 +33,7 @@
33
33
  // written here would be a copy that drifts.
34
34
 
35
35
  import { execFile, spawnSync } from 'node:child_process';
36
- import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
36
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
37
37
  import { tmpdir } from 'node:os';
38
38
  import { basename, join, relative, resolve, sep } from 'node:path';
39
39
  import { promisify } from 'node:util';
@@ -549,8 +549,48 @@ export function ffprobeArgs(file) {
549
549
  }
550
550
 
551
551
  /**
552
- * Where the narration lives: --narration <dir> (its manifest is then required)
553
- * → <deckdir>/voiceover/manifest.json → null (a silent deck).
552
+ * A folder recorded by hand, read off the disk: what a manifest would say
553
+ * about its files, and nothing it would say about the notes. Your own voice
554
+ * (`narrate --mic`) wrote no manifest, and a folder of `slide-NN.wav` with its
555
+ * `slide-NN-KK.wav` beats is everything a render plays; with no hash per
556
+ * slide, the freshness check counts it as hand-recorded and says so.
557
+ * Null when the folder holds no whole-slide audio at all.
558
+ */
559
+ export function folderNarration(dir) {
560
+ let names;
561
+ try { names = readdirSync(dir); } catch { return null; }
562
+ const EXT = ['wav', 'm4a', 'mp3']; // a folder holding two, the recorder's first
563
+ const whole = new Map();
564
+ const beats = new Map();
565
+ for (const f of names) {
566
+ const m = /^slide-(\d+)(?:-(\d+))?\.(wav|m4a|mp3)$/.exec(f);
567
+ if (!m) continue;
568
+ const n = Number(m[1]);
569
+ if (m[2] == null) {
570
+ const had = whole.get(n);
571
+ if (!had || EXT.indexOf(m[3]) < EXT.indexOf(had.split('.').pop())) whole.set(n, f);
572
+ } else {
573
+ if (!beats.has(n)) beats.set(n, new Map());
574
+ const k = Number(m[2]);
575
+ const had = beats.get(n).get(k);
576
+ if (!had || EXT.indexOf(m[3]) < EXT.indexOf(had.split('.').pop())) beats.get(n).set(k, f);
577
+ }
578
+ }
579
+ if (!whole.size) return null;
580
+ const slides = [];
581
+ for (let n = 1; n <= Math.max(...whole.keys()); n++) {
582
+ const file = whole.get(n);
583
+ if (!file) { slides.push(null); continue; }
584
+ const segs = [...(beats.get(n) ?? new Map()).entries()].sort((a, b) => a[0] - b[0]).map(([, f]) => ({ file: f }));
585
+ slides.push(segs.length ? { file, segments: segs } : { file });
586
+ }
587
+ return { dir, slides, engine: undefined, model: undefined, voice: undefined, style: undefined };
588
+ }
589
+
590
+ /**
591
+ * Where the narration lives: --narration <dir> (its manifest, else the audio
592
+ * files in it, recorded by hand) → <deckdir>/voiceover/manifest.json → null
593
+ * (a silent deck).
554
594
  * @returns {{ dir, slides }|null}
555
595
  */
556
596
  export function resolveNarration(deckPath, narrationDir) {
@@ -558,8 +598,10 @@ export function resolveNarration(deckPath, narrationDir) {
558
598
  const path = join(dir, 'manifest.json');
559
599
  if (!existsSync(path)) {
560
600
  if (required) {
561
- throw new Error(`--narration: no manifest.json in ${dir} — `
562
- + 'run tools/voiceover.mjs (or decklight video --voiceover) first');
601
+ const byHand = folderNarration(dir);
602
+ if (byHand) return byHand;
603
+ throw new Error(`--narration: no manifest.json and no slide-NN audio in ${dir} — `
604
+ + 'record it first (decklight narrate, or decklight video --voiceover)');
563
605
  }
564
606
  return null;
565
607
  }
@@ -703,7 +745,7 @@ export function parseBuildSteps(dom, slides) {
703
745
  return counts.length === slides ? counts : null;
704
746
  }
705
747
 
706
- export async function videoMain(argv, { exec = run, log = console.log } = {}) {
748
+ export async function videoMain(argv, { exec: execRaw = run, log = console.log } = {}) {
707
749
  const { opt } = argReader(argv);
708
750
  const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
709
751
  // Two different situations, and the stream and the exit code follow WHICH
@@ -737,6 +779,20 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
737
779
  process.exit(1);
738
780
  }
739
781
 
782
+ // Stopped part-way — the edit server's stop route sends SIGTERM. Every Chrome
783
+ // and ffmpeg in flight is killed through this signal and the next one never
784
+ // starts; the `finally` below takes the scratch frames, and the catch takes a
785
+ // file ffmpeg had begun writing, because a half-written video looks exactly
786
+ // like a finished one in a file browser. Anything not waiting on a child
787
+ // (re-voicing over the network) gets a moment, then the process goes anyway.
788
+ const stopping = new AbortController();
789
+ process.once('SIGTERM', () => {
790
+ stopping.abort();
791
+ setTimeout(() => process.exit(143), 3000).unref();
792
+ });
793
+ const exec = (bin, args, opts = {}) => execRaw(bin, args, { ...opts, signal: stopping.signal });
794
+ let writing = false;
795
+
740
796
  let out; let plan; let narration;
741
797
  try {
742
798
  const named = opt('-o', opt('--out'));
@@ -929,7 +985,9 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
929
985
 
930
986
  const list = join(work, 'concat.txt');
931
987
  writeFileSync(list, concatList(segments));
988
+ writing = true;
932
989
  await exec('ffmpeg', concatArgs(list, out, { format, subtitles: embedded }));
990
+ writing = false;
933
991
  } finally {
934
992
  await server.close();
935
993
  rmSync(work, { recursive: true, force: true });
@@ -938,6 +996,11 @@ export async function videoMain(argv, { exec = run, log = console.log } = {}) {
938
996
  const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
939
997
  log(`done → ${out} (${total.toFixed(1)}s)`);
940
998
  } catch (e) {
999
+ if (stopping.signal.aborted) {
1000
+ if (writing) rmSync(out, { force: true });
1001
+ console.error('decklight video: stopped — no video written');
1002
+ process.exit(143);
1003
+ }
941
1004
  console.error(`decklight video: ${e.message}`);
942
1005
  process.exit(1);
943
1006
  }