decklight 0.9.0 → 0.11.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 (133) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +61 -3
  3. package/README.md +58 -28
  4. package/SPEC.md +1326 -85
  5. package/cli/agent-review.mjs +5 -4
  6. package/cli/agents.mjs +148 -18
  7. package/cli/bundle-audio.mjs +10 -3
  8. package/cli/bundle-module.mjs +95 -0
  9. package/cli/bundle.mjs +125 -7
  10. package/cli/cast.mjs +86 -19
  11. package/cli/check-fixes.mjs +194 -0
  12. package/cli/check-watch.mjs +151 -0
  13. package/cli/check.mjs +491 -75
  14. package/cli/code-editor.mjs +287 -0
  15. package/cli/commands.mjs +13 -2
  16. package/cli/commit-flow.mjs +7 -3
  17. package/cli/commit-message.mjs +35 -8
  18. package/cli/commit-split.mjs +125 -25
  19. package/cli/deck-refs.mjs +8 -3
  20. package/cli/decklight.mjs +11 -1
  21. package/cli/design-system-edit.mjs +37 -1
  22. package/cli/design-system-refs.mjs +263 -6
  23. package/cli/design-system.mjs +82 -14
  24. package/cli/edit-address.mjs +184 -0
  25. package/cli/edit-git.mjs +23 -6
  26. package/cli/edit-handover.mjs +257 -40
  27. package/cli/edit-look.mjs +293 -6
  28. package/cli/edit-open.mjs +143 -0
  29. package/cli/edit-slides.mjs +1043 -67
  30. package/cli/edit-translate.mjs +243 -0
  31. package/cli/edit.mjs +3680 -319
  32. package/cli/editor-support.mjs +286 -0
  33. package/cli/enhance.mjs +157 -27
  34. package/cli/find-replace.mjs +142 -0
  35. package/cli/fix-review.mjs +368 -0
  36. package/cli/git.mjs +13 -0
  37. package/cli/init.mjs +101 -22
  38. package/cli/keep-awake.mjs +68 -0
  39. package/cli/marketplace-autocheck.mjs +200 -0
  40. package/cli/marketplace.mjs +250 -13
  41. package/cli/migrate-writing.mjs +214 -0
  42. package/cli/narrate.mjs +121 -5
  43. package/cli/open.mjs +53 -15
  44. package/cli/outside-edit.mjs +257 -0
  45. package/cli/paste.mjs +92 -0
  46. package/cli/pdf.mjs +88 -10
  47. package/cli/pptx-export.mjs +10 -5
  48. package/cli/publish.mjs +24 -3
  49. package/cli/record.mjs +86 -15
  50. package/cli/remote.mjs +32 -6
  51. package/cli/rewrite.mjs +265 -0
  52. package/cli/runtime-link.mjs +218 -17
  53. package/cli/serve.mjs +9 -6
  54. package/cli/setup.mjs +2 -2
  55. package/cli/skill-content.mjs +251 -10
  56. package/cli/skills/slide-writing.md +333 -0
  57. package/cli/skills/voiceover.md +423 -0
  58. package/cli/skills.mjs +282 -15
  59. package/cli/starter-full.mjs +353 -0
  60. package/cli/supervise.mjs +14 -0
  61. package/cli/theme-refs.mjs +14 -2
  62. package/cli/theme.mjs +3 -2
  63. package/cli/translate-core.mjs +466 -0
  64. package/cli/translate-files.mjs +149 -0
  65. package/cli/translate.mjs +458 -0
  66. package/cli/units.mjs +75 -7
  67. package/cli/util.mjs +25 -0
  68. package/cli/vocabulary-docs.mjs +138 -0
  69. package/dist/decklight.css +2506 -113
  70. package/dist/decklight.js +385 -175
  71. package/dist/decklight.js.map +4 -4
  72. package/docs/GLOSSARY.md +9 -2
  73. package/docs/WRITING_RESEARCH.md +327 -0
  74. package/package.json +5 -3
  75. package/themes/coastal.css +3 -0
  76. package/themes/metropolis.css +2 -0
  77. package/themes/reveal-blood.css +3 -0
  78. package/themes/reveal-league.css +2 -0
  79. package/themes/reveal-moon.css +2 -0
  80. package/themes/reveal-serif.css +1 -0
  81. package/themes/reveal-sky.css +1 -0
  82. package/themes/reveal-solarized.css +4 -0
  83. package/tools/brand-palette.mjs +6 -1
  84. package/tools/build-groups.mjs +28 -8
  85. package/tools/cdp.mjs +176 -0
  86. package/tools/chart-spec.mjs +242 -0
  87. package/tools/click-match.mjs +70 -0
  88. package/tools/code-options.mjs +174 -0
  89. package/tools/conversation.mjs +49 -0
  90. package/tools/deck-family.mjs +101 -0
  91. package/tools/deck-html.mjs +212 -15
  92. package/tools/design-system-format.mjs +40 -1
  93. package/tools/design-system-migrations.mjs +207 -0
  94. package/tools/diagram-shapes.mjs +221 -0
  95. package/tools/elevenlabs-tts.mjs +62 -53
  96. package/tools/exec.mjs +10 -2
  97. package/tools/face-clip.mjs +96 -0
  98. package/tools/face-layout.mjs +94 -0
  99. package/tools/gemini-tts.mjs +1 -1
  100. package/tools/invisible-in-print.mjs +27 -0
  101. package/tools/lipsync-auto.mjs +197 -0
  102. package/tools/lipsync-config.mjs +16 -0
  103. package/tools/lipsync-engines.mjs +22 -4
  104. package/tools/lipsync-server.mjs +8 -5
  105. package/tools/lipsync.mjs +122 -30
  106. package/tools/local-voice.mjs +1 -1
  107. package/tools/mouth-file.mjs +26 -0
  108. package/tools/mouth.mjs +320 -0
  109. package/tools/narration-manifest.mjs +100 -6
  110. package/tools/narration-synth.mjs +96 -76
  111. package/tools/recording-impact.mjs +16 -1
  112. package/tools/sentences.mjs +7 -1
  113. package/tools/site-clip.mjs +114 -0
  114. package/tools/starters.mjs +402 -0
  115. package/tools/steps.mjs +118 -0
  116. package/tools/take-check.mjs +146 -0
  117. package/tools/template-theme.mjs +3 -1
  118. package/tools/test-impact.mjs +36 -12
  119. package/tools/theme-check.mjs +196 -1
  120. package/tools/tone-cue.mjs +108 -0
  121. package/tools/tts-cache.mjs +9 -3
  122. package/tools/tts-engines.mjs +100 -11
  123. package/tools/video-cache.mjs +93 -0
  124. package/tools/video-live.mjs +349 -0
  125. package/tools/video-options.mjs +11 -0
  126. package/tools/video.mjs +825 -117
  127. package/tools/viseme-fit.mjs +27 -0
  128. package/tools/viseme-match.mjs +77 -0
  129. package/tools/vocabulary.mjs +397 -0
  130. package/tools/voice-renumber.mjs +605 -0
  131. package/tools/voiceover-server.mjs +42 -11
  132. package/tools/voiceover.mjs +48 -20
  133. package/dist/build-info.json +0 -1
@@ -0,0 +1,402 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // What the editing bar's Add menu and the New slide kinds put into a deck
5
+ // (SPEC PRESENTING_EDITING): a closed set of starters, each idiomatic
6
+ // Decklight, and the one transform that writes one onto a slide.
7
+ //
8
+ // The SERVER owns this markup, not the page. A page that posted the HTML it
9
+ // wanted would make the route a second "write any markup" door beside the
10
+ // content editor, and two pages of different versions would add two
11
+ // different lists. Here a kind is a name, an unknown name is refused, and
12
+ // the answer carries the markup the file got, so the page shows exactly that.
13
+ //
14
+ // Every starter is written at zero indentation; `insertElement` and
15
+ // `insertSectionsAfter` move it to where it lands. The placeholder words are
16
+ // obviously placeholders, so nobody presents one by mistake.
17
+
18
+ import {
19
+ locateSlide, sectionChildRanges, splitOpenTag, readAttrs, setSectionAttrs,
20
+ insertElement, insertInElement, wrapInDiv, insertSectionsAfter,
21
+ } from './deck-html.mjs';
22
+
23
+ /** The kinds of element Add offers, in its order (Picture is the page's file chooser, not a starter). */
24
+ export const ELEMENT_KINDS = ['heading', 'text', 'bullets', 'numbered', 'quote', 'figure', 'conversation', 'table', 'code', 'formula', 'columns', 'diagram', 'chart', 'video', 'terminal', 'webpage'];
25
+
26
+ /** The kinds of slide New slide offers; no kind is today's blank slide (`BLANK_SLIDE`). */
27
+ export const SLIDE_KINDS = ['bullets', 'text', 'columns', 'section', 'big-number', 'blank'];
28
+
29
+ /** A refusal the route answers with its own status: 400 for a kind outside the set, 409 for a slide that cannot take it. */
30
+ class StarterError extends Error {
31
+ constructor(message, status) { super(message); this.status = status; }
32
+ }
33
+
34
+ // a figure (DECK_ANATOMY): one large value over what it counts, with a line of context
35
+ const FIGURE = `<div class="figure">
36
+ <p data-figure>42%</p>
37
+ <p>What the number counts</p>
38
+ <small>One line of context</small>
39
+ </div>`;
40
+
41
+ // a conversation (DECK_ANATOMY): a user, an agent and its tool, one turn a click
42
+ const CONVERSATION = `<div class="conversation" data-build>
43
+ <p data-role="user">A question the user asks</p>
44
+ <p data-role="agent" data-kind="tool-call">look_up("the question")</p>
45
+ <p data-role="tool" data-name="look_up">{ "answer": "what the tool found" }</p>
46
+ <p data-role="agent">The agent's answer</p>
47
+ </div>`;
48
+
49
+ // one column of a comparison slide (COMPARISON_SLIDES): a heading over its points
50
+ const COLUMN = (name) => `<div>
51
+ <h3>${name}</h3>
52
+ <ul>
53
+ <li>New point</li>
54
+ <li>Another point</li>
55
+ </ul>
56
+ </div>`;
57
+
58
+ /**
59
+ * A file a starter points at (a video, a recording): a path beside the deck,
60
+ * written relative (no scheme, not absolute, no `..`), matching `exts`.
61
+ */
62
+ const besideDeck = (src, exts) => typeof src === 'string' && src.length <= 300 && !!src.trim()
63
+ && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(src) && !/^[/\\]/.test(src) && !src.split(/[/\\]/).includes('..')
64
+ && !/["<>\u0000-\u001f]/.test(src) && exts.test(src);
65
+ /** A web page a frame shows: an https address, one line, no quote or bracket that could leave the attribute. */
66
+ export const webAddress = (url) => typeof url === 'string' && url.length <= 2000 && /^https:\/\/[^\s"'<>`]+$/i.test(url)
67
+ && (() => { try { return new URL(url).protocol === 'https:'; } catch { return false; } })();
68
+ const attrText = (v) => String(v).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
69
+
70
+ /**
71
+ * The starter for `kind`. `ctx.titled` says the slide already has its title
72
+ * (a heading added then is a subheading, h3, rather than a second title);
73
+ * `ctx.wire` is an arrowhead id no other element of the deck uses.
74
+ */
75
+ function elementStarter(kind, { titled = true, wire = 'dl-wire-1', src = null, cast = null, url = null, title = null } = {}) {
76
+ switch (kind) {
77
+ case 'heading': return titled ? '<h3>Heading</h3>' : '<h2>Heading</h2>';
78
+ case 'text': return '<p>New text</p>';
79
+ case 'bullets': return '<ul>\n <li>New point</li>\n <li>Another point</li>\n</ul>';
80
+ case 'numbered': return '<ol>\n <li>First step</li>\n <li>Next step</li>\n</ol>';
81
+ case 'quote': return '<blockquote>A quote worth repeating</blockquote>';
82
+ case 'figure': return FIGURE;
83
+ case 'conversation': return CONVERSATION;
84
+ case 'table': return `<table>
85
+ <thead>
86
+ <tr><th>Column</th><th>Column</th></tr>
87
+ </thead>
88
+ <tbody>
89
+ <tr><td>Value</td><td>Value</td></tr>
90
+ <tr><td>Value</td><td>Value</td></tr>
91
+ </tbody>
92
+ </table>`;
93
+ // CODE_AND_MATH: a language class for the highlighter; the code's own
94
+ // lines start at the margin, since inside <pre> every space is shown
95
+ case 'code': return `<pre><code class="language-js">// New code
96
+ const answer = 42;</code></pre>`;
97
+ // CODE_AND_MATH: a display formula in a paragraph, typed as its TeX
98
+ // source; the route marks the slide for math in the same write
99
+ case 'formula': return '<p>$$e^{i\\pi} + 1 = 0$$</p>';
100
+ // COMPARISON_SLIDES: two sibling blocks under a split layout (the route
101
+ // sets the layout), never a column flexbox of our own
102
+ case 'columns': return `${COLUMN('Column')}\n${COLUMN('Column')}`;
103
+ // SVG_DIAGRAMS: two labelled boxes and a wire, theme tokens only, the
104
+ // arrowhead the shipped size, built (a diagram arrives in parts)
105
+ case 'diagram': return `<svg viewBox="0 0 640 200" width="640" data-build="draw" role="img" aria-label="New diagram">
106
+ <defs><marker id="${wire}" markerWidth="6" markerHeight="4" refX="5" refY="2" orient="auto"><polygon points="0 0, 6 2, 0 4" style="fill: var(--d-stroke)"/></marker></defs>
107
+ <g>
108
+ <rect x="40" y="56" width="200" height="88" rx="10" style="fill: var(--d-fill-1); stroke: var(--d-stroke)" stroke-width="2"/>
109
+ <text x="140" y="106" text-anchor="middle" font-size="20" style="font-family: var(--font-body); fill: var(--d-text)">Box A</text>
110
+ </g>
111
+ <line x1="244" y1="100" x2="392" y2="100" stroke-width="2" style="stroke: var(--d-stroke)" marker-end="url(#${wire})"/>
112
+ <g>
113
+ <rect x="400" y="56" width="200" height="88" rx="10" style="fill: var(--d-fill-2); stroke: var(--d-stroke)" stroke-width="2"/>
114
+ <text x="500" y="106" text-anchor="middle" font-size="20" style="font-family: var(--font-body); fill: var(--d-text)">Box B</text>
115
+ </g>
116
+ </svg>`;
117
+ // CHARTS: inline JSON the engine draws, its colours the theme's
118
+ case 'chart': return `<div class="chart" data-chart="bar" data-title="New chart" data-aspect="2:1">
119
+ <script type="application/json">
120
+ { "labels": ["A", "B", "C"],
121
+ "series": [ { "name": "Series", "data": [3, 5, 2] } ] }
122
+ </script>
123
+ </div>`;
124
+ // DECK_ANATOMY: a video beside the deck, with its controls; the engine
125
+ // plays it only on its slide (slide-media.js), and loads its first frame
126
+ case 'video': return `<video src="${attrText(src)}" controls playsinline preload="metadata"></video>`;
127
+ // TERMINAL_PLAYER: a recording beside the deck, played a command a click
128
+ // a framed web page: https only, a title for a screen reader, loaded as it
129
+ // comes near; blank in no-trust mode, a video export and offline (Check deck says so)
130
+ case 'webpage': return `<iframe src="${attrText(url)}" title="${attrText(title || `Web page: ${new URL(url).host}`)}" loading="lazy"></iframe>`;
131
+ case 'terminal': return `<div class="terminal" data-cast="${attrText(cast)}" data-mode="step"></div>`;
132
+ default: return null;
133
+ }
134
+ }
135
+
136
+ /** The section a New slide of `kind` inserts, or null for a kind outside the set. */
137
+ export function slideStarter(kind) {
138
+ const notes = ' <aside class="notes"></aside>';
139
+ switch (kind) {
140
+ case 'bullets': return `<section>\n <h2>Slide title</h2>\n <ul>\n <li>New point</li>\n <li>Another point</li>\n </ul>\n${notes}\n</section>`;
141
+ case 'text': return `<section>\n <h2>Slide title</h2>\n <p>New text</p>\n${notes}\n</section>`;
142
+ case 'columns': return `<section data-layout="split">\n <h2>Slide title</h2>\n${[COLUMN('Column'), COLUMN('Column')].map((c) => c.replace(/^/gm, ' ')).join('\n')}\n${notes}\n</section>`;
143
+ // a title card: the engine keeps a slide with nothing past its subtitle centred
144
+ case 'section': return `<section>\n <h1>Section title</h1>\n <p>What this part is about</p>\n${notes}\n</section>`;
145
+ // the number is the slide: a figure alone, centred, its value typed first
146
+ case 'big-number': return `<section>\n${FIGURE.replace(/^/gm, ' ')}\n${notes}\n</section>`;
147
+ case 'blank': return `<section>\n${notes}\n</section>`;
148
+ default: return null;
149
+ }
150
+ }
151
+
152
+ /** A deck with a new slide of `kind` after slide `after`; throws a 400 for a kind outside the set. */
153
+ export function insertSlideOfKind(html, after, kind) {
154
+ const section = slideStarter(kind);
155
+ if (!section) throw new StarterError(`no slide kind "${kind}" (one of: ${SLIDE_KINDS.join(', ')})`, 400);
156
+ return insertSectionsAfter(String(html ?? ''), after, [section]);
157
+ }
158
+
159
+ const openTagOf = (el) => {
160
+ const m = /^<([A-Za-z][\w:-]*)/.exec(el);
161
+ return readAttrs(splitOpenTag(el.slice(m ? m[0].length : 0)).attrs);
162
+ };
163
+
164
+ /**
165
+ * A slide's header and content blocks the way a split layout counts them:
166
+ * `title` and `subtitle` (raw child indices, or null), and `blocks`, the
167
+ * indices past them, never an aside, a script, a style or the slide's
168
+ * background (the engine's `splitContent`, read from the file).
169
+ */
170
+ function slideBlocks(seg) {
171
+ const subtitleOff = readAttrs(splitOpenTag(seg).attrs)['data-subtitle'] === 'none';
172
+ const kids = sectionChildRanges(seg).map((r, i) => ({ ...r, i, attrs: openTagOf(seg.slice(r.start, r.end)) }))
173
+ .filter((k) => !['aside', 'script', 'style'].includes(k.tag) && !/\bslide-bg\b/.test(k.attrs.class ?? ''));
174
+ let from = 0; let title = null; let subtitle = null;
175
+ if (kids[0] && (kids[0].tag === 'h1' || kids[0].tag === 'h2')) {
176
+ from = 1; title = kids[0].i;
177
+ if (!subtitleOff && kids[1]?.tag === 'p') { from = 2; subtitle = kids[1].i; }
178
+ }
179
+ return { title, subtitle, blocks: kids.slice(from).map((k) => k.i) };
180
+ }
181
+ const contentBlocks = (seg) => slideBlocks(seg).blocks;
182
+
183
+ /**
184
+ * The raw indices of a split slide's two columns (COMPARISON_SLIDES), or null
185
+ * when the slide is not split, follows a template (the engine does not split
186
+ * those), or has no pair yet (a lone list splits across two CSS columns and
187
+ * is not a column itself).
188
+ */
189
+ export function splitColumns(seg) {
190
+ const attrs = readAttrs(splitOpenTag(seg).attrs);
191
+ if (!/^split/.test(attrs['data-layout'] ?? '') || attrs['data-template']) return null;
192
+ const { blocks } = slideBlocks(seg);
193
+ return blocks.length >= 2 ? [blocks[0], blocks[1]] : null;
194
+ }
195
+
196
+ /**
197
+ * Where a new block lands on slide `seg` when the page asks for "after
198
+ * top-level child `index`, or after the node at `path` below it"
199
+ * (PRESENTING_EDITING, Adding content). The one rule every way of adding
200
+ * shares (Add, the Picture button, a dropped picture, a paste), so that none
201
+ * of them can break the slide's shape:
202
+ *
203
+ * - the title selected on a slide with a subtitle: after the subtitle, not
204
+ * between the two (a block there would become the subtitle);
205
+ * - a column of a split slide selected, or anything inside it: inside that
206
+ * column, after the column's own child the selection is in, or at the
207
+ * column's end. Beside it, the block would become a column itself and the
208
+ * real second column drop underneath as a footer;
209
+ * - the header of a split slide selected: first in the left column, for the
210
+ * same reason.
211
+ *
212
+ * Returns `{ index }` for a top-level landing (null: after the last content
213
+ * child, before the asides), or `{ index, into: true, after }` for one inside
214
+ * column `index`: after its element child `after`, first for -1, last for null.
215
+ * `column` says a column was what was selected; `header`, the header child a
216
+ * landing in the left column was moved from.
217
+ */
218
+ export function whereNewBlockLands(seg, index, path = null) {
219
+ if (index === null || index === undefined) return { index: null };
220
+ const { title, subtitle } = slideBlocks(seg);
221
+ const i = index === title && subtitle !== null ? subtitle : index;
222
+ const pair = splitColumns(seg);
223
+ if (pair?.includes(i)) {
224
+ const inside = i === index && Array.isArray(path) && Number.isInteger(path[0]) ? path[0] : null;
225
+ return { index: i, into: true, after: inside, column: true };
226
+ }
227
+ if (pair && (i === title || i === subtitle)) return { index: pair[0], into: true, after: -1, header: i };
228
+ return { index: i };
229
+ }
230
+
231
+ /** Is a column's source a plain wrapper a block can go into, rather than one block of its own (a list, a picture, a chart)? */
232
+ const isWrapper = (src) => {
233
+ if (!/^<div\b/i.test(src)) return false;
234
+ const attrs = openTagOf(src);
235
+ return !/\b(?:chart|terminal|figures?|conversation)\b/.test(attrs.class ?? '') && !('data-chart' in attrs) && !('data-cast' in attrs);
236
+ };
237
+
238
+ /**
239
+ * A deck with `markup` (one element) added to slide `slide` where
240
+ * `whereNewBlockLands` says. Returns `{ html, index, path, wrapped }`: the
241
+ * top-level child it is, or is in, and its `path` below that (`[]` on the
242
+ * slide itself). A column that is a single bare block is wrapped in a
243
+ * `<div>` in the same write (`wrapped`), so the new block has somewhere to go.
244
+ */
245
+ export function insertBlock(html, slide, index, markup, { path = null } = {}) {
246
+ const deck = String(html ?? '');
247
+ const { parts, idx } = locateSlide(deck, slide);
248
+ const seg = parts[idx];
249
+ if (index !== null && index !== undefined && !sectionChildRanges(seg)[index]) {
250
+ const n = sectionChildRanges(seg).length;
251
+ throw Object.assign(new Error(`slide ${slide}: no element at index ${index} (has ${n})`), { status: 404 });
252
+ }
253
+ const land = whereNewBlockLands(seg, index, path);
254
+ if (!land.into) {
255
+ const out = insertElement(deck, slide, land.index, markup);
256
+ return { html: out.html, index: out.index, path: [], wrapped: false };
257
+ }
258
+ const r = sectionChildRanges(seg)[land.index];
259
+ let next = deck; let after = land.after; let wrapped = false;
260
+ if (!isWrapper(seg.slice(r.start, r.end))) {
261
+ next = wrapInDiv(deck, slide, land.index);
262
+ after = after === -1 ? -1 : 0; // the bare block is the wrapper's one child
263
+ wrapped = true;
264
+ }
265
+ const out = insertInElement(next, slide, land.index, { markup, after });
266
+ return { html: out.html, index: land.index, path: out.path, wrapped };
267
+ }
268
+
269
+ /** An arrowhead id no element of the deck carries yet. */
270
+ function freeWireId(html) {
271
+ for (let n = 1; ; n++) if (!new RegExp(`\\bid=["']dl-wire-${n}["']`).test(html)) return `dl-wire-${n}`;
272
+ }
273
+
274
+ // ── words pasted from another app (PRESENTING_EDITING, the clipboard) ─────
275
+ // A paste outside typing adds a paragraph or a list of the clipboard's words.
276
+ // The page cleans them (`pastedWords`, src/core/list-edit.js) and sends one
277
+ // line of inline words per paragraph or point; the server builds the block
278
+ // around them, as it builds every starter, and takes the words only when each
279
+ // is plain text and the editor's own emphasis: a page or a forged request
280
+ // cannot make this route a door for any other markup.
281
+
282
+ /** The kinds words can be pasted as. */
283
+ export const WORDS_KINDS = ['text', 'bullets', 'numbered'];
284
+ const INLINE_TAGS = new Set(['strong', 'em', 'code', 'mark', 's', 'sup', 'sub']);
285
+ // the web, mail or a slide; else a path, which may name no scheme, not even
286
+ // one spelled with a character reference (`javascript&#58;`), and so holds none
287
+ const SAFE_HREF = /^(?:https?:\/\/|mailto:|#)[^"<>\s]*$|^(?![a-z][a-z0-9+.-]*:)(?!.*&(?:#|colon;))[^"<>\s:]+$/i;
288
+
289
+ /**
290
+ * `words` if it is one line of inline words the file may take as they are:
291
+ * text with its `<`, `>` and `&` escaped, the emphasis tags with no
292
+ * attributes, and `<a href>` to the web, mail, a slide or a path, every tag
293
+ * closed in order. Anything else throws a 400.
294
+ */
295
+ export function inlineWords(words) {
296
+ const src = String(words ?? '');
297
+ if (!src.trim() || src.length > 2000 || /[\n\r]/.test(src)) throw new StarterError('a pasted line must be one line of words', 400);
298
+ const open = [];
299
+ const re = /<(\/?)([a-z]+)((?:\s+href="[^"]*")?)>|&(?:[a-z]+|#\d+|#x[0-9a-f]+);|[<>&]/gi;
300
+ for (const m of src.matchAll(re)) {
301
+ if (m[0][0] === '&' && m[0].length > 1) continue; // an entity
302
+ const [, close, name, attrs] = m;
303
+ const tag = name?.toLowerCase();
304
+ const ok = tag && (INLINE_TAGS.has(tag) ? !attrs : tag === 'a' && (close ? !attrs : SAFE_HREF.test(attrs.replace(/^\s+href="|"$/g, ''))));
305
+ if (!ok) throw new StarterError(`a pasted line may hold words and emphasis only, not "${m[0].slice(0, 40)}"`, 400);
306
+ if (close) { if (open.pop() !== tag) throw new StarterError('a pasted line\'s tags must close in order', 400); }
307
+ else open.push(tag);
308
+ }
309
+ if (open.length) throw new StarterError('a pasted line\'s tags must close in order', 400);
310
+ return src;
311
+ }
312
+
313
+ /** The block pasted `words` make: a paragraph of one line, a list of several. */
314
+ function wordsMarkup(kind, words) {
315
+ if (!WORDS_KINDS.includes(kind)) throw new StarterError(`words are pasted as ${WORDS_KINDS.join(', ')}, not "${kind}"`, 400);
316
+ if (!Array.isArray(words) || !words.length || words.length > 30) throw new StarterError('words come as one to thirty lines', 400);
317
+ const lines = words.map(inlineWords);
318
+ if (kind === 'text') {
319
+ if (lines.length !== 1) throw new StarterError('a paragraph is one line of words', 400);
320
+ return `<p>${lines[0]}</p>`;
321
+ }
322
+ const tag = kind === 'numbered' ? 'ol' : 'ul';
323
+ return `<${tag}>\n${lines.map((l) => ` <li>${l}</li>`).join('\n')}\n</${tag}>`;
324
+ }
325
+
326
+ /**
327
+ * A deck with a starter of `kind` on slide `slide`, after top-level child
328
+ * `index` or the node at `path` below it (`index: null`: after the last
329
+ * content child, before the asides, as a dropped picture lands), placed by
330
+ * the one rule every add follows (`whereNewBlockLands`). Returns `{ html,
331
+ * index, path, wrapped, count, markup, layout }`: the first new element's
332
+ * top-level index and its path below it (`[]` on the slide itself, one step
333
+ * inside a column), whether its column was wrapped to take it, how many
334
+ * siblings went in (two columns are two), the markup exactly as written
335
+ * (unindented), the layout the slide was given, when one was (`split`,
336
+ * for two columns), and the attributes its `<section>` was given (`section`,
337
+ * `{ 'data-math': '' }` for a formula on a slide not yet marked for math).
338
+ *
339
+ * Refused (thrown, with the status the route answers): a kind outside the set
340
+ * (400); a slide that follows a design system's slide template (409), whose
341
+ * content goes in its slots and nowhere beside them (DESIGN_SYSTEMS), the
342
+ * same reason an edit may never drop a slot; two columns where the slide
343
+ * already has content before them (409): a split layout makes its first two
344
+ * blocks the columns, so the columns go first under the title; and two
345
+ * columns asked for inside a column (409).
346
+ */
347
+ export function insertStarter(html, slide, index, kind, { path = null, words = null, with: given = {} } = {}) {
348
+ const deck = String(html ?? '');
349
+ if (!ELEMENT_KINDS.includes(kind)) {
350
+ throw new StarterError(`no kind "${kind}" to add (one of: ${ELEMENT_KINDS.join(', ')})`, 400);
351
+ }
352
+ // a kind that carries a file is given its path, and only one beside the deck
353
+ if (kind === 'video' && !besideDeck(given?.src, /\.(mp4|webm)$/i)) {
354
+ throw new StarterError('a video is an mp4 or a webm beside the deck, given by its relative path (assets/clip.mp4)', 400);
355
+ }
356
+ if (kind === 'webpage' && !webAddress(given?.url)) {
357
+ throw new StarterError('a web page is an https address (https://example.com/page)', 400);
358
+ }
359
+ if (kind === 'webpage' && given?.title != null && (typeof given.title !== 'string' || given.title.length > 120 || /[\u0000-\u001f]/.test(given.title))) {
360
+ throw new StarterError('a web page’s title is one line of at most 120 characters', 400);
361
+ }
362
+ if (kind === 'terminal' && !besideDeck(given?.cast, /\.cast(\.json)?$/i)) {
363
+ throw new StarterError('a terminal recording is a .cast.json (or an asciicast .cast) beside the deck, given by its relative path (casts/demo.cast.json)', 400);
364
+ }
365
+ const { parts, idx } = locateSlide(deck, slide);
366
+ const seg = parts[idx];
367
+ const sectionAttrs = readAttrs(splitOpenTag(seg).attrs);
368
+ const template = sectionAttrs['data-template'];
369
+ if (template) {
370
+ throw new StarterError(`slide ${slide} follows the "${template}" slide template: what it says goes in the template's slots, so nothing is added beside them. Edit a slot's words, or take the slide out of the template (Use slide template…) to add freely`, 409);
371
+ }
372
+ const titled = sectionChildRanges(seg).some((r) => r.tag === 'h1' || r.tag === 'h2');
373
+ // words pasted from another app: their block around them, else the kind's starter
374
+ const markup = words !== null ? wordsMarkup(kind, words) : elementStarter(kind, { titled, wire: kind === 'diagram' ? freeWireId(deck) : undefined, src: given?.src ?? null, cast: given?.cast ?? null, url: given?.url ?? null, title: given?.title ?? null });
375
+ const count = kind === 'columns' ? 2 : 1;
376
+ let layout = null;
377
+ let out;
378
+ if (kind === 'columns') {
379
+ // two siblings, never inside a column: a slide has one pair
380
+ const land = whereNewBlockLands(seg, index, path);
381
+ if (land.column) {
382
+ throw new StarterError(`two columns do not go inside a column: slide ${slide} already has its pair, and a third column would drop underneath as a footer. Add a new slide in two columns instead (Slide ▾, New slide)`, 409);
383
+ }
384
+ out = { ...insertElement(deck, slide, land.into ? land.header : land.index, markup), path: [], wrapped: false };
385
+ const after = locateSlide(out.html, slide);
386
+ const blocks = contentBlocks(after.parts[after.idx]);
387
+ if (blocks[0] !== out.index || blocks[1] !== out.index + 1) {
388
+ throw new StarterError(`two columns go first under the title (a split layout makes the slide's first two blocks its columns), and slide ${slide} already has content there: select the title and add them right under it, or add a new slide in two columns (Slide ▾, New slide)`, 409);
389
+ }
390
+ if (!/^split/.test(sectionAttrs['data-layout'] ?? '')) {
391
+ out.html = setSectionAttrs(out.html, slide, { set: { 'data-layout': 'split' } }).html;
392
+ layout = 'split';
393
+ }
394
+ } else out = insertBlock(deck, slide, index, markup, { path });
395
+ // a formula renders only on a slide marked for math: marked in the same write, one undo for both
396
+ let section = null;
397
+ if (kind === 'formula' && !Object.hasOwn(sectionAttrs, 'data-math')) {
398
+ out.html = setSectionAttrs(out.html, slide, { set: { 'data-math': '' } }).html;
399
+ section = { 'data-math': '' };
400
+ }
401
+ return { html: out.html, index: out.index, path: out.path, wrapped: out.wrapped, count, markup, layout, section };
402
+ }
@@ -0,0 +1,118 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // A run of slides that shows where it is (SPEC DECK_ANATOMY, #1188): "step 3
5
+ // of 7", with the group it belongs to. The author marks the run once, on the
6
+ // slide that starts it, and each slide after it says which group it is in, or
7
+ // continues the one before:
8
+ //
9
+ // <section data-steps="Foundation, Fresh context, Tools, The agent" data-steps-count>
10
+ // <section> (still Foundation)
11
+ // <section data-step="Fresh context">
12
+ //
13
+ // The groups may also be a list, `<nav class="steps"><ol><li>Foundation</li>…`,
14
+ // on that first slide. A run ends at the next chapter marker (`data-module`),
15
+ // at the next run, or at a slide marked `data-steps-end`, which is the first
16
+ // slide after it.
17
+ //
18
+ // Pure and shared: the runtime draws the strip from it (src/core/steps.js),
19
+ // `decklight check` names a `data-step` that is no group of its run, and the
20
+ // slide finder folds a run's slides under its group names. One reading, so
21
+ // the strip, the finder and the check can never disagree about a slide.
22
+
23
+ /** The longest group name the strip draws, and the most groups a run takes. */
24
+ export const STEP_NAME_MAX = 60;
25
+ export const STEP_GROUPS_MAX = 12;
26
+
27
+ /** Words on one line, as a group is written: inner runs of space made one, trimmed. */
28
+ const clean = (s) => String(s ?? '').replace(/\s+/g, ' ').trim();
29
+
30
+ /** A group name as it is compared: case and spacing are no difference. */
31
+ export const stepKey = (s) => clean(s).toLowerCase();
32
+
33
+ /**
34
+ * The groups `data-steps="A, B, C"` names, in order: empty names dropped, a
35
+ * name written twice kept once, at most STEP_GROUPS_MAX of them.
36
+ */
37
+ export function parseSteps(text) {
38
+ const out = [];
39
+ for (const part of String(text ?? '').split(',')) {
40
+ const name = clean(part).slice(0, STEP_NAME_MAX);
41
+ if (name && !out.some((g) => stepKey(g) === stepKey(name))) out.push(name);
42
+ }
43
+ return out.slice(0, STEP_GROUPS_MAX);
44
+ }
45
+
46
+ /** The groups a `<nav class="steps">` list holds, its items' words in order (parseSteps' rules). */
47
+ export const listSteps = (items) => parseSteps((items ?? []).map((t) => clean(t).replace(/,/g, ' ')).join(','));
48
+
49
+ /**
50
+ * Every run in a deck, and where each slide stands in its own.
51
+ *
52
+ * `slides` is the deck in order, one `{ steps, list, step, module, end,
53
+ * count, hidden }` a slide: `steps` its `data-steps` (null when absent),
54
+ * `list` the items of its `<nav class="steps">` (null when it has none),
55
+ * `step` its `data-step`, `module` whether it starts a chapter, `end` whether
56
+ * it carries `data-steps-end`, `count` whether it carries `data-steps-count`,
57
+ * `hidden` whether it is hidden when presenting.
58
+ *
59
+ * Returns `{ runs, at, unknown }`:
60
+ * runs `[{ start, end, groups, count, slides }]`, slide numbers from 1,
61
+ * `end` the run's last slide, `slides` how many of them are shown;
62
+ * at one entry a slide (index 0 is slide 1): null outside a run, else
63
+ * `{ run, group, n, of }`, `group` the index of its group, `n` its
64
+ * place among the run's shown slides (null when it is hidden, or
65
+ * the run is not counted) and `of` how many there are;
66
+ * unknown `[{ slide, step, groups }]`: a `data-step` that names no group of
67
+ * its run (`groups` null when the slide is in no run at all). Such
68
+ * a slide continues the group before it, as an absent one does.
69
+ */
70
+ export function stepRuns(slides) {
71
+ const list = Array.isArray(slides) ? slides : [];
72
+ const runs = [];
73
+ const at = list.map(() => null);
74
+ const unknown = [];
75
+ let run = null;
76
+ let group = 0;
77
+ list.forEach((s, i) => {
78
+ const slide = i + 1;
79
+ const declared = s?.steps != null ? parseSteps(s.steps) : s?.list ? listSteps(s.list) : null;
80
+ // a chapter, a marked end, or a new run closes the one before
81
+ if (run && (s?.module || s?.end || declared)) run = null;
82
+ if (declared && declared.length) {
83
+ run = { start: slide, end: slide, groups: declared, count: !!s.count, slides: 0 };
84
+ runs.push(run);
85
+ group = 0;
86
+ }
87
+ if (s?.step != null && String(s.step).trim() !== '') {
88
+ const k = run ? run.groups.findIndex((g) => stepKey(g) === stepKey(s.step)) : -1;
89
+ if (k >= 0) group = k;
90
+ else unknown.push({ slide, step: clean(s.step), groups: run ? [...run.groups] : null });
91
+ }
92
+ if (!run) return;
93
+ run.end = slide;
94
+ at[i] = { run: runs.length - 1, group, n: null, of: 0, hidden: !!s?.hidden };
95
+ });
96
+ // numbered over the slides an audience sees: a hidden one keeps its group, not a number
97
+ for (const r of runs) {
98
+ let n = 0;
99
+ for (let i = r.start - 1; i < r.end; i++) if (!at[i].hidden) at[i].n = ++n;
100
+ r.slides = n;
101
+ for (let i = r.start - 1; i < r.end; i++) {
102
+ at[i].of = n;
103
+ if (!r.count) at[i].n = null;
104
+ delete at[i].hidden;
105
+ }
106
+ }
107
+ return { runs, at, unknown };
108
+ }
109
+
110
+ /**
111
+ * The sentence a strip says for one slide, as a screen reader and a tooltip
112
+ * read it: `Step 3 of 7: Fresh context` when the run is counted, else
113
+ * `Fresh context, 2 of 4` (the group's place among the groups).
114
+ */
115
+ export function stepLabel(run, where) {
116
+ const name = run.groups[where.group] ?? '';
117
+ return where.n != null ? `Step ${where.n} of ${where.of}: ${name}` : `${name}, ${where.group + 1} of ${run.groups.length}`;
118
+ }
@@ -0,0 +1,146 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Does a take's length fit its text?
5
+ //
6
+ // A generative voice is a sample, and now and then a bad one: ElevenLabs once
7
+ // read "You ask, it answers." as "You ask, you ask, it answers", 3.28 s where
8
+ // the sentence runs 2.16 s, and the cache kept it, so every pass over that
9
+ // slide said it that way (#1005). A take far longer than its text's pace is
10
+ // the shape of a repeated phrase, and one far shorter of a dropped one. Both
11
+ // are cheap to see from the WAV header and cheap to fix with one more sample.
12
+ //
13
+ // Only engines that sample are checked. piper, chirp and the system voices
14
+ // say a sentence the same way every time, so a retry would buy the same take.
15
+
16
+ import { spawnSync } from 'node:child_process';
17
+ import { readFileSync, readdirSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { stripAudioTags } from './sentences.mjs';
20
+ import { wavSeconds } from './face-clip.mjs';
21
+ import { PROBE_MS } from './exec.mjs';
22
+
23
+ /**
24
+ * Characters a second, per engine, for ordinary narration. Wide on purpose:
25
+ * the band around it is a factor of two either way, so this only has to be
26
+ * the right order, not a measurement of any one voice.
27
+ */
28
+ export const PACE = { elevenlabs: 14, gemini: 13 };
29
+
30
+ /** A take inside [LOW × expected, HIGH × expected] fits. */
31
+ export const BAND = [0.5, 2];
32
+
33
+ // A short sentence's take carries the voice's breath in and out, which no
34
+ // pace accounts for: below a second of speech the factor alone would flag
35
+ // "Yes." for running 0.7 s. So the top of the band is never under expected + 1 s.
36
+ const SLACK = 1;
37
+ // an audio tag ([sighs], [pause]) is a beat of its own, said or held
38
+ const PER_TAG = 1;
39
+
40
+ const TAG = /\[[^[\]]{1,40}\]/g;
41
+
42
+ /**
43
+ * The seconds a text should take on this engine, or null when the engine is
44
+ * not checked (it does not sample, or has no pace on record).
45
+ */
46
+ export function expectedSeconds(engineName, text) {
47
+ const pace = PACE[engineName];
48
+ if (!pace) return null;
49
+ const chars = stripAudioTags(text).replace(/\s+/g, ' ').trim().length;
50
+ return chars ? chars / pace : null;
51
+ }
52
+
53
+ /**
54
+ * `{ seconds, expected, ok }` for a take of `text`, or null when it cannot be
55
+ * judged: an engine that is not checked, or audio that is not a WAV (mp3
56
+ * carries no length in a header we read).
57
+ */
58
+ export function judgeTake(engineName, text, seconds) {
59
+ const expected = expectedSeconds(engineName, text);
60
+ if (expected == null || !(seconds > 0)) return null;
61
+ const tags = (String(text).match(TAG) ?? []).length;
62
+ const low = BAND[0] * expected;
63
+ const high = Math.max(BAND[1] * expected, expected + SLACK) + tags * PER_TAG;
64
+ return { seconds, expected, ok: seconds >= low && seconds <= high };
65
+ }
66
+
67
+ /** {@link judgeTake} of a WAV. */
68
+ export const judgeWav = (engineName, text, wav) => judgeTake(engineName, text, wavSeconds(wav));
69
+
70
+ // how far a take is from its text's pace, either way
71
+ const miss = (j) => Math.abs(Math.log(j.seconds / j.expected));
72
+
73
+ /**
74
+ * `engine.synth(text, opts)`, with a take whose length does not fit its text
75
+ * synthesized once more. When the second fits, it is the take; when it does
76
+ * not either, the one nearer the expected length is kept, which for a repeated
77
+ * phrase is the shorter. Either way the result carries `take`:
78
+ * `{ seconds: [first, second], expected, fits }`, `fits` false when neither
79
+ * did. Usage is the sum of both requests: both were billed.
80
+ */
81
+ export async function checkedSynth(engine, text, opts = {}) {
82
+ const first = await engine.synth(text, opts);
83
+ const a = judgeWav(engine.name, text, first.wav);
84
+ if (!a || a.ok) return first;
85
+ const second = await engine.synth(text, opts);
86
+ const b = judgeWav(engine.name, text, second.wav);
87
+ const keep = !b || b.ok || miss(b) < miss(a) ? second : first;
88
+ const usage = { ...keep.usage };
89
+ for (const k of ['chars', 'cost']) {
90
+ const sum = (first.usage?.[k] ?? 0) + (second.usage?.[k] ?? 0);
91
+ if (typeof first.usage?.[k] === 'number' || typeof second.usage?.[k] === 'number') usage[k] = sum;
92
+ }
93
+ return {
94
+ ...keep,
95
+ usage,
96
+ take: { seconds: [a.seconds, b?.seconds ?? null], expected: a.expected, fits: !b || b.ok },
97
+ };
98
+ }
99
+
100
+ const s = (n) => (n == null ? '?' : `${n.toFixed(2)} s`);
101
+
102
+ /** One line for a retried take: what it was, what came back, what was kept. */
103
+ export function takeLine(text, take) {
104
+ const [a, b] = take.seconds;
105
+ const said = String(text).length > 70 ? `${String(text).slice(0, 67)}…` : String(text);
106
+ return `“${said}” ran ${s(a)} against ~${s(take.expected)}; the retry ran ${s(b)}`
107
+ + (take.fits ? ' and is kept' : ', also outside — kept the nearer, worth a listen');
108
+ }
109
+
110
+ /** A file's seconds: a WAV from its header, anything else by ffprobe; null when neither can say. */
111
+ function fileSeconds(path) {
112
+ let buf;
113
+ try { buf = readFileSync(path); } catch { return null; }
114
+ const wav = wavSeconds(buf);
115
+ if (wav != null) return wav;
116
+ const r = spawnSync('ffprobe', ['-v', 'error', '-show_entries', 'format=duration',
117
+ '-of', 'default=noprint_wrappers=1:nokey=1', path], { encoding: 'utf8', timeout: PROBE_MS });
118
+ const n = Number(String(r.stdout ?? '').trim());
119
+ return r.status === 0 && n > 0 ? n : null;
120
+ }
121
+
122
+ /**
123
+ * The clips of a recorded track whose length does not fit their text: every
124
+ * `slide-NN[-KK].{wav,m4a,mp3}` with its `.txt` beside it, judged at the
125
+ * engine's pace. `[{ file, seconds, expected }]`, in file order; empty for an
126
+ * engine that is not checked. A clip with no script, or one nothing can
127
+ * measure (no ffprobe for an m4a), is not judged rather than guessed at.
128
+ */
129
+ export function auditTrack(dir, engineName) {
130
+ if (!PACE[engineName]) return [];
131
+ let names;
132
+ try { names = readdirSync(dir).sort(); } catch { return []; }
133
+ const out = [];
134
+ for (const file of names) {
135
+ const m = /^(slide-\d+(?:-\d+)?)\.(wav|m4a|mp3)$/.exec(file);
136
+ if (!m) continue;
137
+ // a slide cut into beats is judged beat by beat: its whole file is the
138
+ // beats joined, and would name the same bad take twice
139
+ if (m[1].split('-').length === 2 && names.some((n) => n.startsWith(`${m[1]}-`))) continue;
140
+ let text;
141
+ try { text = readFileSync(join(dir, `${m[1]}.txt`), 'utf8'); } catch { continue; }
142
+ const j = judgeTake(engineName, text, fileSeconds(join(dir, file)));
143
+ if (j && !j.ok) out.push({ file, seconds: j.seconds, expected: j.expected });
144
+ }
145
+ return out;
146
+ }