decklight 0.10.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 (117) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +17 -0
  3. package/README.md +53 -25
  4. package/SPEC.md +1239 -67
  5. package/cli/agents.mjs +139 -15
  6. package/cli/bundle.mjs +68 -2
  7. package/cli/cast.mjs +45 -14
  8. package/cli/check-fixes.mjs +12 -4
  9. package/cli/check-watch.mjs +151 -0
  10. package/cli/check.mjs +460 -71
  11. package/cli/code-editor.mjs +287 -0
  12. package/cli/commands.mjs +13 -2
  13. package/cli/commit-message.mjs +34 -7
  14. package/cli/commit-split.mjs +123 -23
  15. package/cli/decklight.mjs +11 -1
  16. package/cli/design-system-edit.mjs +37 -1
  17. package/cli/edit-address.mjs +184 -0
  18. package/cli/edit-git.mjs +21 -4
  19. package/cli/edit-handover.mjs +136 -25
  20. package/cli/edit-look.mjs +45 -1
  21. package/cli/edit-open.mjs +143 -0
  22. package/cli/edit-slides.mjs +1043 -67
  23. package/cli/edit-translate.mjs +243 -0
  24. package/cli/edit.mjs +3182 -267
  25. package/cli/editor-support.mjs +286 -0
  26. package/cli/enhance.mjs +148 -20
  27. package/cli/find-replace.mjs +142 -0
  28. package/cli/fix-review.mjs +368 -0
  29. package/cli/init.mjs +93 -19
  30. package/cli/keep-awake.mjs +68 -0
  31. package/cli/migrate-writing.mjs +214 -0
  32. package/cli/narrate.mjs +51 -10
  33. package/cli/open.mjs +29 -9
  34. package/cli/outside-edit.mjs +257 -0
  35. package/cli/paste.mjs +92 -0
  36. package/cli/pdf.mjs +61 -2
  37. package/cli/pptx-export.mjs +3 -1
  38. package/cli/publish.mjs +24 -3
  39. package/cli/record.mjs +19 -8
  40. package/cli/rewrite.mjs +265 -0
  41. package/cli/runtime-link.mjs +218 -17
  42. package/cli/serve.mjs +7 -4
  43. package/cli/setup.mjs +2 -2
  44. package/cli/skill-content.mjs +212 -8
  45. package/cli/skills/slide-writing.md +333 -0
  46. package/cli/skills/voiceover.md +423 -0
  47. package/cli/skills.mjs +36 -13
  48. package/cli/starter-full.mjs +353 -0
  49. package/cli/supervise.mjs +14 -0
  50. package/cli/theme.mjs +3 -2
  51. package/cli/translate-core.mjs +466 -0
  52. package/cli/translate-files.mjs +149 -0
  53. package/cli/translate.mjs +458 -0
  54. package/cli/util.mjs +25 -0
  55. package/cli/vocabulary-docs.mjs +138 -0
  56. package/dist/decklight.css +2087 -91
  57. package/dist/decklight.js +367 -203
  58. package/dist/decklight.js.map +4 -4
  59. package/docs/GLOSSARY.md +9 -2
  60. package/docs/WRITING_RESEARCH.md +327 -0
  61. package/package.json +5 -3
  62. package/themes/coastal.css +3 -0
  63. package/themes/metropolis.css +2 -0
  64. package/themes/reveal-blood.css +3 -0
  65. package/themes/reveal-league.css +2 -0
  66. package/themes/reveal-moon.css +2 -0
  67. package/themes/reveal-serif.css +1 -0
  68. package/themes/reveal-sky.css +1 -0
  69. package/themes/reveal-solarized.css +4 -0
  70. package/tools/brand-palette.mjs +6 -1
  71. package/tools/build-groups.mjs +28 -8
  72. package/tools/cdp.mjs +176 -0
  73. package/tools/chart-spec.mjs +242 -0
  74. package/tools/click-match.mjs +70 -0
  75. package/tools/code-options.mjs +174 -0
  76. package/tools/conversation.mjs +49 -0
  77. package/tools/deck-family.mjs +101 -0
  78. package/tools/deck-html.mjs +212 -15
  79. package/tools/design-system-format.mjs +15 -1
  80. package/tools/diagram-shapes.mjs +221 -0
  81. package/tools/elevenlabs-tts.mjs +62 -53
  82. package/tools/face-clip.mjs +96 -0
  83. package/tools/face-layout.mjs +94 -0
  84. package/tools/gemini-tts.mjs +1 -1
  85. package/tools/invisible-in-print.mjs +27 -0
  86. package/tools/lipsync-auto.mjs +197 -0
  87. package/tools/lipsync-config.mjs +16 -0
  88. package/tools/lipsync-engines.mjs +22 -4
  89. package/tools/lipsync-server.mjs +8 -5
  90. package/tools/lipsync.mjs +122 -30
  91. package/tools/local-voice.mjs +1 -1
  92. package/tools/mouth-file.mjs +26 -0
  93. package/tools/mouth.mjs +320 -0
  94. package/tools/narration-manifest.mjs +24 -4
  95. package/tools/narration-synth.mjs +96 -76
  96. package/tools/recording-impact.mjs +16 -1
  97. package/tools/sentences.mjs +7 -1
  98. package/tools/starters.mjs +402 -0
  99. package/tools/steps.mjs +118 -0
  100. package/tools/take-check.mjs +146 -0
  101. package/tools/template-theme.mjs +3 -1
  102. package/tools/test-impact.mjs +36 -12
  103. package/tools/theme-check.mjs +196 -1
  104. package/tools/tone-cue.mjs +108 -0
  105. package/tools/tts-cache.mjs +9 -3
  106. package/tools/tts-engines.mjs +100 -11
  107. package/tools/video-cache.mjs +93 -0
  108. package/tools/video-live.mjs +349 -0
  109. package/tools/video-options.mjs +11 -0
  110. package/tools/video.mjs +772 -127
  111. package/tools/viseme-fit.mjs +27 -0
  112. package/tools/viseme-match.mjs +77 -0
  113. package/tools/vocabulary.mjs +397 -0
  114. package/tools/voice-renumber.mjs +605 -0
  115. package/tools/voiceover-server.mjs +42 -11
  116. package/tools/voiceover.mjs +48 -20
  117. package/dist/build-info.json +0 -1
package/cli/check.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  /**
6
6
  * decklight check — one headless lint of one deck, with one exit code.
7
7
  *
8
- * decklight check <deck.html> [--no-render] [--json] [--wait <ms>]
8
+ * decklight check <deck.html> [--no-render] [--json] [--wait <ms>] [--watch | --fix]
9
9
  *
10
10
  * The promise this repo makes (README, SPEC PRESENTING: the overflow guardrail
11
11
  * is assertable headlessly) is that an agent can verify its own work without
@@ -18,8 +18,7 @@
18
18
  *
19
19
  * So this is the one command whose whole job is to REPORT, per slide, what an
20
20
  * author or an agent would otherwise only find by looking — and to exit 1 when
21
- * something is actually wrong. Nothing here writes a file, starts a server, or
22
- * changes the deck.
21
+ * something is actually wrong. Only an explicit --fix can change the deck.
23
22
  *
24
23
  * TWO HALVES, AND WHY THEY ARE SEPARATE FUNCTIONS. `staticFindings` is pure
25
24
  * over the file text (with `exists` injected, it touches no disk at all) and
@@ -47,6 +46,9 @@ import {
47
46
  sectionInner, slideHeading, splitOpenTag,
48
47
  } from '../tools/deck-html.mjs';
49
48
  import { CLICK_MARK } from '../tools/sentences.mjs';
49
+ import { parseChart } from '../tools/chart-spec.mjs';
50
+ import { calloutBlocks, calloutSteps, calloutsOf, stepsOf as lineStepsOf } from '../tools/code-options.mjs';
51
+ import { clickMismatch, clickMismatchText, readClickMismatch } from '../tools/click-match.mjs';
50
52
  import { isTemplateRef, parseTemplateRef } from '../tools/design-system-format.mjs';
51
53
  import { auditDeck } from './audit.mjs';
52
54
  import {
@@ -56,15 +58,94 @@ import { composeRenames, migrationsOf } from '../tools/design-system-migrations.
56
58
  import { markedSources } from './theme-refs.mjs';
57
59
  import { parseColor, toOklab } from '../tools/color.mjs';
58
60
  import { ON_PALETTE_DISTANCE, offRoleColours, nearestRole, resolveTokenColours } from '../tools/brand-palette.mjs';
59
- import { printUrl } from './pdf.mjs';
61
+ import { printUrl, invisibleSaid } from './pdf.mjs';
62
+ import { invisibleMessage } from '../tools/invisible-in-print.mjs';
63
+ import { configBlock, hasDoctype, isDeck } from './runtime-link.mjs';
64
+ import { attributeFindings, configFindings } from '../tools/vocabulary.mjs';
65
+ import { stepRuns } from '../tools/steps.mjs';
60
66
  import { runMain } from './util.mjs';
67
+ import { translationFindings } from './translate-files.mjs';
68
+ import { legacyWriting, migrateWriting } from './migrate-writing.mjs';
61
69
 
62
70
  /**
63
71
  * One finding. `slide` is null for anything outside a section (the head), and
64
72
  * `rule` is there for the `--json` reader: an agent filters on a stable name,
65
73
  * never on the wording of a message a human reads.
74
+ *
75
+ * A finding about ONE element carries its address, `at: { path, tag }`: the
76
+ * element-child path below the slide's `<section>` (its first step is the
77
+ * raw index among the section's children, the edit routes' `index`; the rest
78
+ * is their `path`), and the tag found there. The panel's Fix it hands it to
79
+ * the agent, and a row's hover outlines the element on the stage.
80
+ */
81
+ const finding = (level, rule, slide, title, message, at = null) => ({ level, rule, slide, title, message, ...(at ? { at } : {}) });
82
+
83
+ /** `n` as an ordinal: 1st, 2nd, 3rd, 11th, 22nd. */
84
+ const ordinal = (n) => `${n}${[11, 12, 13].includes(n % 100) ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' }[n % 10] ?? 'th')}`;
85
+
86
+ /**
87
+ * How a finding names one element: its tag, what tells it apart from its
88
+ * neighbours (its class, else its id, else its data-node), then the
89
+ * attributes the finding is about. `<rect class="cm-grow" data-concept="full">`.
90
+ */
91
+ function elementName(node, shown) {
92
+ const a = readAttrs(node.attrs);
93
+ const cls = String(a.class ?? '').trim().replace(/\s+/g, ' ');
94
+ const own = cls ? ['class', cls] : a.id ? ['id', a.id] : a['data-node'] && !('data-node' in shown) ? ['data-node', a['data-node']] : null;
95
+ const parts = [own, ...Object.entries(shown)].filter(Boolean).map(([k, v]) => `${k}="${v}"`);
96
+ return `<${node.tag}${parts.length ? ` ${parts.join(' ')}` : ''}>`;
97
+ }
98
+
99
+ /**
100
+ * Names for `nodes` that tell them apart: each one's `elementName`, and where
101
+ * two of them would read alike, its place among those that do
102
+ * (`<rect data-concept="full"> (2nd of 3)`), in document order. Two findings
103
+ * about two elements never read as one.
104
+ */
105
+ function namesApart(nodes, shown) {
106
+ const named = nodes.map((n) => [n, elementName(n, shown(n))]);
107
+ const alike = new Map();
108
+ for (const [, name] of named) alike.set(name, (alike.get(name) ?? 0) + 1);
109
+ const seen = new Map();
110
+ return new Map(named.map(([n, name]) => {
111
+ const total = alike.get(name);
112
+ if (total === 1) return [n, name];
113
+ const i = (seen.get(name) ?? 0) + 1;
114
+ seen.set(name, i);
115
+ return [n, `${name} (${ordinal(i)} of ${total})`];
116
+ }));
117
+ }
118
+
119
+ /** Every node under `root` mapped to its element-child path from it, `[2, 0]`. */
120
+ function pathsBelow(root) {
121
+ const out = new Map();
122
+ const walk = (node, path) => node.children.forEach((c, i) => {
123
+ const p = [...path, i];
124
+ out.set(c, p);
125
+ walk(c, p);
126
+ });
127
+ walk(root, []);
128
+ return out;
129
+ }
130
+
131
+ /**
132
+ * Findings that would read as the same row (same level, rule, slide and
133
+ * message) folded into one, which says how many it stands for (`count`) and
134
+ * carries every element's address (`ats`) when they had one.
66
135
  */
67
- const finding = (level, rule, slide, title, message) => ({ level, rule, slide, title, message });
136
+ export function foldRepeats(findings) {
137
+ const out = [];
138
+ const byKey = new Map();
139
+ for (const f of findings) {
140
+ const key = JSON.stringify([f.level, f.rule, f.slide, f.message]);
141
+ const first = byKey.get(key);
142
+ if (!first) { byKey.set(key, f); out.push(f); continue; }
143
+ first.count = (first.count ?? 1) + 1;
144
+ if (f.at) first.ats = [...(first.ats ?? (first.at ? [first.at] : [])), f.at];
145
+ }
146
+ for (const f of out) if (f.count > 1) f.message = `${f.message} (${f.count} alike here)`;
147
+ return out;
148
+ }
68
149
 
69
150
  // ── a deck as a tree, just enough of one ─────────────────────────────────────
70
151
  // Both static halves need the same two things — which element carries which
@@ -95,7 +176,9 @@ const IMPLIED_CLOSE = {
95
176
  const TAG = /<!--[\s\S]*?-->|<(\/)?([a-zA-Z][\w:.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*)>/g;
96
177
 
97
178
  /**
98
- * `html` as a tree of `{ tag, attrs, start, children }`, best-effort.
179
+ * `html` as a tree of `{ tag, attrs, start, end, children }`, best-effort:
180
+ * `end` is where the node's content stops (its close tag, or the end of the
181
+ * document for one never closed), so its text is `html.slice(start, end)`.
99
182
  *
100
183
  * Best-effort is the contract: this reads a file somebody is mid-edit on, so a
101
184
  * stray `</div>` is ignored rather than thrown on, and an unclosed tag simply
@@ -113,19 +196,22 @@ export function parseTree(html) {
113
196
  const tag = rawName.toLowerCase();
114
197
  if (closing) {
115
198
  const at = stack.findLastIndex((n) => n.tag === tag);
116
- if (at > 0) stack.length = at; // a close with no open is somebody's typo, not a nesting level
199
+ if (at > 0) { // a close with no open is somebody's typo, not a nesting level
200
+ for (const open of stack.slice(at)) open.end = m.index;
201
+ stack.length = at;
202
+ }
117
203
  continue;
118
204
  }
119
205
  const selfClosed = /\/\s*$/.test(rawAttrs);
120
- const node = { tag, attrs: rawAttrs.replace(/\/\s*$/, ''), start: m.index, children: [] };
206
+ const node = { tag, attrs: rawAttrs.replace(/\/\s*$/, ''), start: m.index, end: html.length, children: [] };
121
207
  for (const implied of IMPLIED_CLOSE[tag] ?? []) {
122
208
  if (stack.at(-1).tag === implied) stack.pop();
123
209
  }
124
210
  stack.at(-1).children.push(node);
125
- if (selfClosed || VOID_ELEMENTS.has(tag)) continue;
211
+ if (selfClosed || VOID_ELEMENTS.has(tag)) { node.end = re.lastIndex; continue; }
126
212
  if (OPAQUE_ELEMENTS.has(tag)) {
127
213
  const close = indexOfCI(html, `</${tag}`, re.lastIndex);
128
- re.lastIndex = close === -1 ? html.length : close;
214
+ re.lastIndex = node.end = close === -1 ? html.length : close;
129
215
  continue;
130
216
  }
131
217
  stack.push(node);
@@ -231,7 +317,7 @@ function assetReferences(tree) {
231
317
  return out;
232
318
  }
233
319
 
234
- // ── ⟨CLICK⟩ segments vs build steps ──────────────────────────────────────────
320
+ // ── [click] markers vs build clicks ──────────────────────────────────────────
235
321
 
236
322
  const SVG_SKIP = new Set(['defs', 'title', 'desc', 'style', 'metadata']);
237
323
  const CONTAINER_TAGS = new Set(['ul', 'ol', 'table', 'tbody', 'dl', 'svg']);
@@ -251,6 +337,8 @@ function eligibleChildren(node) {
251
337
  function isContainer(node) {
252
338
  if ('data-build-self' in readAttrs(node.attrs)) return false;
253
339
  if (CONTAINER_TAGS.has(node.tag)) return true;
340
+ // a figure (DECK_ANATOMY) is one step, its value and label together
341
+ if (node.tag === 'div' && /(^|\s)figure(\s|$)/.test(readAttrs(node.attrs).class ?? '')) return false;
254
342
  if (node.tag === 'div' || node.tag === 'g') return eligibleChildren(node).length >= 2;
255
343
  return false;
256
344
  }
@@ -273,6 +361,8 @@ function stepSource(node) {
273
361
  * read a cast or parsed `data-lines`, and no file reader can count those.
274
362
  * `hasProvider` below is why the caller does not compare on such a slide at
275
363
  * all: a guess against a number nobody can know is a warning about nothing.
364
+ * The render half counts them (engine.js `markClickMismatch`), and when it
365
+ * runs its answer replaces this one (#929).
276
366
  */
277
367
  export function buildSteps(node) {
278
368
  return buildItems(node).length;
@@ -288,24 +378,32 @@ export function buildSteps(node) {
288
378
  function buildItems(node) {
289
379
  const items = [];
290
380
  let auto = 0;
291
- const push = (orderAttr) => { items.push(orderItem(orderAttr, auto)); auto++; };
381
+ const push = (orderAttr, n, withPrev = false) => { items.push({ ...orderItem(orderAttr, auto, withPrev), node: n }); auto++; };
292
382
  const stops = (n) => parseDrawStops(readAttrs(n.attrs)['data-draw-stops']).length;
293
383
  const stepsOf = (n) => {
294
384
  const attrs = readAttrs(n.attrs);
295
385
  if ('data-draw-stops' in attrs && stops(n)) {
296
386
  // its stops count up from its data-build-order, when it has one (#524)
297
387
  const base = parseInt(attrs['data-build-order'] ?? '', 10);
298
- for (let i = 0; i < stops(n); i++) push(Number.isFinite(base) ? String(base + i) : null);
388
+ for (let i = 0; i < stops(n); i++) push(Number.isFinite(base) ? String(base + i) : null, n);
299
389
  return;
300
390
  }
301
- push(attrs['data-build-order']);
391
+ push(attrs['data-build-order'], n, 'data-build-with' in attrs);
392
+ };
393
+ // a diagram's group that builds (builds.js isBuildingGroup): its members are steps of their own
394
+ const stepsIn = (container) => {
395
+ for (const c of stepSource(container)) {
396
+ const a = readAttrs(c.attrs);
397
+ if (c.tag === 'g' && 'data-group' in a && 'data-build' in a && isContainer(c)) stepsIn(c);
398
+ else stepsOf(c);
399
+ }
302
400
  };
303
401
  const walk = (parent) => {
304
402
  for (const child of parent.children) {
305
403
  if (child.tag === 'aside' || OPAQUE_ELEMENTS.has(child.tag)) continue;
306
404
  const attrs = readAttrs(child.attrs);
307
405
  if ('data-build' in attrs) {
308
- if (isContainer(child)) { for (const c of stepSource(child)) stepsOf(c); continue; }
406
+ if (isContainer(child)) { stepsIn(child); continue; }
309
407
  stepsOf(child); // a leaf is one step, and the engine keeps walking into it
310
408
  } else if ('data-draw-stops' in attrs && stops(child)) {
311
409
  stepsOf(child); // a staged stroke outside any build container is its own provider
@@ -328,6 +426,24 @@ export function buildClicks(node) {
328
426
  return computeGroups(buildItems(node)).length;
329
427
  }
330
428
 
429
+ // What paints, for a build step read from the file: words, or one of these.
430
+ const PAINTS = new Set(['img', 'picture', 'video', 'canvas', 'iframe', 'object', 'embed', 'path', 'rect', 'circle',
431
+ 'ellipse', 'line', 'polyline', 'polygon', 'text', 'image', 'use', 'foreignobject']);
432
+
433
+ /**
434
+ * Is one click of this slide's builds a reveal of nothing: a group whose every
435
+ * step has no words and nothing that paints? The commonest cause of a
436
+ * [click] count that is one short (#929): a `<g data-build-order>` left
437
+ * behind when its graphic was removed. `html` is the text `node` was parsed from.
438
+ */
439
+ export function emptyBuildClick(node, html) {
440
+ const items = buildItems(node);
441
+ // a token along a wire is an empty <g> the runtime draws in: its click shows the token, never nothing
442
+ const blank = (n) => readAttrs(n.attrs)['data-build'] !== 'travel' && !PAINTS.has(n.tag) && ![...descendants(n)].some((d) => PAINTS.has(d.tag))
443
+ && !html.slice(n.start, n.end).replace(/<[^>]*>/g, '').replace(/&nbsp;|&#160;/g, ' ').trim();
444
+ return computeGroups(items).some((g) => g.length && g.every((k) => blank(items[k].node)));
445
+ }
446
+
331
447
  /** The stop count a `data-draw-stops` attribute declares (the runtime's `parseDrawStops`, without a length to clamp to). */
332
448
  function parseDrawStops(attr) {
333
449
  const raw = String(attr ?? '').trim().split(/[\s,]+/).filter(Boolean);
@@ -535,6 +651,13 @@ function designSystemFindings(value, tree, systems, configured, push) {
535
651
 
536
652
  // ── whether a slide's diagram builds ─────────────────────────────────────────
537
653
 
654
+ /** The longest a figure's value reads as one (DECK_ANATOMY): `$12.5M`, `1,500`, `-12.5%`. */
655
+ export const FIGURE_MAX_CHARS = 8;
656
+ /** A figure's value as a reader sees it, from its source: tags out, the common entities read, spaces folded. */
657
+ const figureText = (src) => src.replace(/^<[^>]*>/, '').replace(/<[^>]*>/g, '')
658
+ .replace(/&nbsp;|&#160;/g, ' ').replace(/&times;/g, '×').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&[a-z]+;|&#\d+;/gi, '·')
659
+ .replace(/\s+/g, ' ').trim();
660
+
538
661
  const hasClass = (node, cls) => new RegExp(`(?:^|\\s)${cls}(?:\\s|$)`).test(readAttrs(node.attrs).class ?? '');
539
662
  /** Generated, not drawn: a chart or a terminal cast has nothing an author would build. */
540
663
  const generated = (node) => hasClass(node, 'chart') || hasClass(node, 'terminal');
@@ -584,6 +707,14 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
584
707
  const systems = configured.length ? designSystems(src) : new Map();
585
708
  const hold = brandHold(src, systems);
586
709
  const roles = roleHold(src, systems);
710
+ // A file with no doctype (#1190): every server and render puts one in front,
711
+ // but a browser opening the file itself lays it out in quirks mode, where a
712
+ // table loses the theme's text colour. A hint: Decklight's own paths are fine.
713
+ if (isDeck(src) && !hasDoctype(src)) {
714
+ out.push(finding('hint', 'no-doctype', null, 'head',
715
+ 'no <!doctype html> at the top of the file — Decklight adds it when it serves or renders the deck, '
716
+ + 'but a browser opening the file itself lays it out in quirks mode: put <!doctype html> on its first line'));
717
+ }
587
718
  const offBrand = themeOffBrand(src, systems);
588
719
  if (offBrand) {
589
720
  out.push(finding('warn', 'theme-off-brand', null, 'head',
@@ -625,6 +756,8 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
625
756
  return { slide, title: title(slide) };
626
757
  };
627
758
 
759
+ // a run of slides (DECK_ANATOMY, #1188), read slide by slide below, judged once the deck is read
760
+ const stepSlides = [];
628
761
  for (const range of ranges) {
629
762
  const { slide, body } = range;
630
763
  const attrs = readAttrs(splitOpenTag(body).attrs);
@@ -649,19 +782,130 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
649
782
  }
650
783
 
651
784
  const tree = parseTree(inner);
652
- const push = (rule, message) => out.push(finding('warn', rule, slide, head, message));
785
+ const stepsNav = [...descendants(tree)].find((n) => n.tag === 'nav' && hasClass(n, 'steps'));
786
+ stepSlides.push({
787
+ // an attribute's value as the page reads it: its entities decoded (`Ship &amp; tell`)
788
+ steps: attrs['data-steps'] == null ? null : figureText(attrs['data-steps']),
789
+ list: stepsNav ? [...descendants(stepsNav)].filter((n) => n.tag === 'li').map((n) => figureText(inner.slice(n.start, n.end))) : null,
790
+ step: attrs['data-step'] == null ? null : figureText(attrs['data-step']),
791
+ module: 'data-module' in attrs,
792
+ end: 'data-steps-end' in attrs,
793
+ count: 'data-steps-count' in attrs,
794
+ hidden: 'data-hidden' in attrs,
795
+ });
796
+ const pathOf = pathsBelow(tree);
797
+ const addressOf = (node) => ({ path: pathOf.get(node), tag: node.tag });
798
+ const push = (rule, message, node = null) => out.push(finding('warn', rule, slide, head, message, node && addressOf(node)));
653
799
  // a slashed data-layout was how a slide named a template before 0.9.0
654
800
  if (isTemplateRef(attrs['data-layout'])) {
655
801
  push('ds-layout-attr', `data-layout="${attrs['data-layout']}" — a slide template is named by data-template now: write data-template="${attrs['data-layout']}" (data-layout is for the built-in layouts, L)`);
656
802
  }
803
+ // a framed web page (Add ▾ › Web page): someone else's page, fetched as
804
+ // the slide shows, so wherever the deck cannot reach it the frame is blank
805
+ for (const node of descendants(tree)) {
806
+ if (node.tag !== 'iframe') continue;
807
+ const at = readAttrs(node.attrs).src ?? '';
808
+ if (!/^https?:\/\//i.test(at)) continue;
809
+ let host = at;
810
+ try { host = new URL(at).host; } catch { /* said as written */ }
811
+ push('web-page', `the web page from ${host} is blank in no-trust mode, in a video export and offline: the frame fetches it as the slide shows, so present it where it can be reached, or show a picture of it`, node);
812
+ }
813
+ // a figure's value (DECK_ANATOMY): a number and its unit, a few
814
+ // characters set several times the body size; a sentence there is not a
815
+ // figure, and is shrunk to fit its column until it is no longer large
816
+ for (const node of descendants(tree)) {
817
+ if (!('data-figure' in readAttrs(node.attrs))) continue;
818
+ const text = figureText(inner.slice(node.start, node.end));
819
+ if ([...text].length > FIGURE_MAX_CHARS) {
820
+ push('figure-long', `the figure's value "${text.length > 40 ? `${text.slice(0, 40)}…` : text}" is ${[...text].length} characters — a figure is a number and its unit (94%, $1.2M, 3×), at most ${FIGURE_MAX_CHARS}: put the words in its label, the <p> under it`, node);
821
+ }
822
+ }
823
+ // a chart's JSON (CHARTS), read as the runtime reads it: what it refuses
824
+ // is the error box on the slide, and what it draws without (a band
825
+ // shorter than the labels, a dashFrom naming no label) is said here only
826
+ for (const node of descendants(tree)) {
827
+ const a = readAttrs(node.attrs);
828
+ if (!('data-chart' in a)) continue;
829
+ const body = /<script\b[^>]*\btype\s*=\s*["']?application\/json["']?[^>]*>([\s\S]*?)<\/script\s*>/i.exec(inner.slice(node.start, node.end));
830
+ let spec = null;
831
+ try {
832
+ spec = parseChart(body ? body[1] : null, { type: a['data-chart'] || undefined, title: a['data-title'] || undefined, aspect: a['data-aspect'] || undefined });
833
+ } catch (e) {
834
+ out.push(finding('error', 'chart', slide, head, `the chart shows an error box instead of a chart: ${e.message}`, addressOf(node)));
835
+ continue;
836
+ }
837
+ for (const note of spec.notes) push('chart', `the chart: ${note}`, node);
838
+ }
839
+ // code sized by hand (CODE_AND_MATH, #1185): a font-size on a <pre>, or on
840
+ // a section that holds one, is right for one layout and clipped or tiny
841
+ // after the next edit; data-fit sizes the code to the room instead
842
+ const sizeOf = (a) => /(?:^|;)\s*font-size\s*:\s*([^;]+)/i.exec(a.style ?? '')?.[1].trim();
843
+ const pres = [...descendants(tree)].filter((n) => n.tag === 'pre');
844
+ if (pres.length && sizeOf(attrs)) {
845
+ push('code-font-size', `the slide sets font-size: ${sizeOf(attrs)} and holds code — a size set by hand is right for one layout and clipped or tiny after the next edit: take it off and mark the code data-fit (data-fit="fill" to grow short code into the room)`);
846
+ }
847
+ for (const node of pres) {
848
+ const size = sizeOf(readAttrs(node.attrs));
849
+ if (size) push('code-font-size', `<pre> sets font-size: ${size} — a size set by hand is right for one layout and clipped or tiny after the next edit: take it off and mark the block data-fit (data-fit="fill" to grow short code into the room)`, node);
850
+ }
851
+ // a line walk's callouts (CODE_AND_MATH, #1182): a label a step, and a
852
+ // label past the last step is never shown. They cost no click of their own.
853
+ const stepped = pres.filter((n) => readAttrs(n.attrs)['data-lines'] !== undefined);
854
+ const steps = (n) => lineStepsOf(readAttrs(n.attrs)['data-lines']).length;
855
+ const tooMany = (have, n) => `${have} callout${have === 1 ? '' : 's'} for ${n} line step${n === 1 ? '' : 's'}`;
856
+ for (const node of pres) {
857
+ const a = readAttrs(node.attrs);
858
+ if (a['data-callouts'] === undefined) continue;
859
+ const have = calloutsOf(a['data-callouts']).length;
860
+ const n = a['data-lines'] === undefined ? 0 : steps(node);
861
+ if (have > n) push('code-callouts', `<pre> has ${tooMany(have, n)} — ${n ? `a label past step ${n} is never shown: one label a step, | between them, in step order` : 'callouts label line steps: give the block data-lines'}`, node);
862
+ }
863
+ const asides = [...descendants(tree)].filter((n) => n.tag === 'aside' && /(^|\s)callouts(\s|$)/.test(readAttrs(n.attrs).class ?? ''));
864
+ const tied = calloutBlocks(stepped.map((n) => ({ id: readAttrs(n.attrs).id })), asides.map((n) => ({ for: readAttrs(n.attrs)['data-for'] })));
865
+ asides.forEach((node, k) => {
866
+ const entries = node.children.filter((c) => c.tag);
867
+ const last = Math.max(0, ...calloutSteps(entries.map((c) => readAttrs(c.attrs)['data-step'])));
868
+ const block = stepped[tied[k]];
869
+ if (!block) {
870
+ const f = readAttrs(node.attrs)['data-for'];
871
+ push('code-callouts', f ? `the callouts aside is for "${f}", and no block with data-lines on this slide has that id` : 'the callouts aside has no block with data-lines on this slide to label', node);
872
+ } else if (last > steps(block)) push('code-callouts', `the callouts aside labels step ${last}, and its block has ${steps(block)} line step${steps(block) === 1 ? '' : 's'}: one label a step`, node);
873
+ });
657
874
  // a concept shape with its own fill (SVG_DIAGRAMS, #718): the concept
658
875
  // repaints the fill on every load, so the hand-set one is never seen
659
- for (const node of descendants(tree)) {
660
- if (!SHAPE_TAGS.has(node.tag)) continue;
876
+ // — each named apart from the slide's other concept shapes, quoting the fill it found
877
+ const conceptShapes = [...descendants(tree)].filter((n) => SHAPE_TAGS.has(n.tag) && readAttrs(n.attrs)['data-concept']);
878
+ const conceptNames = namesApart(conceptShapes, (n) => ({ 'data-concept': readAttrs(n.attrs)['data-concept'] }));
879
+ for (const node of conceptShapes) {
661
880
  const a = readAttrs(node.attrs);
662
- if (!a['data-concept']) continue;
663
- const own = a.fill && a.fill !== 'none' ? `fill="${a.fill}"` : /(?:^|;)\s*fill\s*:\s*(?!none\b)[^;]+/i.test(a.style ?? '') ? 'a fill in its style' : null;
664
- if (own) push('concept-fill', `<${node.tag} data-concept="${a['data-concept']}"> also carries ${own} — the concept colours it, and the fill is painted over; pin the concept's slot (Concept colors…) or take the concept off (Colors… → Detach from concept)`);
881
+ const styled = /(?:^|;)\s*fill\s*:\s*(?!none\b)([^;]+)/i.exec(a.style ?? '');
882
+ const own = a.fill && a.fill !== 'none' ? `fill="${a.fill}"` : styled ? `fill: ${styled[1].trim()} in its style` : null;
883
+ if (own) push('concept-fill', `${conceptNames.get(node)} also carries ${own} — the concept colours it, and the fill is painted over; pin the concept's slot (Concept colors…) or take the concept off (Colors… → Detach from concept)`, node);
884
+ }
885
+ // a connector naming a node its svg does not have (SVG_DIAGRAMS): the
886
+ // runtime leaves it where the file draws it, attached to nothing
887
+ for (const svg of descendants(tree)) {
888
+ if (svg.tag !== 'svg') continue;
889
+ const inside = [...descendants(svg)];
890
+ const names = new Set(inside.map((n) => readAttrs(n.attrs)['data-node']).filter(Boolean));
891
+ for (const end of ['data-from', 'data-to']) {
892
+ const wires = inside.filter((n) => readAttrs(n.attrs)[end] !== undefined);
893
+ const called = namesApart(wires, (n) => ({ [end]: readAttrs(n.attrs)[end] }));
894
+ for (const n of wires) {
895
+ const value = readAttrs(n.attrs)[end];
896
+ if (names.has(value)) continue;
897
+ push('connector-node', `${called.get(n)} names no data-node in its svg — the wire stays where the file draws it, joined to nothing: give the shape it joins data-node="${value}", or take ${end} off`, n);
898
+ }
899
+ }
900
+ // a token along a wire (BUILD_ENTRANCES, travel) naming a wire its svg does not have: its click shows nothing
901
+ const wires = new Set(inside.filter((n) => /^(line|path|polyline)$/.test(n.tag)).map((n) => readAttrs(n.attrs)['data-wire']).filter(Boolean));
902
+ const tokens = inside.filter((n) => readAttrs(n.attrs)['data-along-wire'] !== undefined);
903
+ const tokenNames = namesApart(tokens, (n) => ({ 'data-along-wire': readAttrs(n.attrs)['data-along-wire'] }));
904
+ for (const n of tokens) {
905
+ const value = readAttrs(n.attrs)['data-along-wire'];
906
+ if (wires.has(value)) continue;
907
+ push('travel-wire', `${tokenNames.get(n)} names no data-wire in its svg — its click sends nothing along anything: name the wire data-wire="${value}" (Wire ▸ Send a token along it does), or point it at one the svg has${wires.size ? ` (${[...wires].slice(0, 4).join(', ')})` : ''}`, n);
908
+ }
665
909
  }
666
910
  // a deck on a design system with roles: every colour its slides name is a role (SPEC DESIGN_SYSTEM_ROLES)
667
911
  if (roles) {
@@ -725,18 +969,19 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
725
969
  designSystemFindings(attrs['data-template'], tree, systems, configured.map((r) => r.ref),
726
970
  (rule, message) => out.push(finding('warn', rule, slide, head, message)));
727
971
  }
728
- const segments = clickSegments(NOTES_ASIDE.exec(inner)?.[1]);
729
- const steps = buildSteps(tree);
730
- const clicks = buildClicks(tree);
731
- // segments = clicks + 1, so a slide with one segment has no ⟨CLICK⟩ at all
732
- // and is making no claim about the builds.
733
- if (segments > 1 && segments - 1 !== clicks && !hasProvider(tree)) {
734
- const tied = clicks !== steps ? ` (${steps} build steps, tied by data-build-order)` : '';
735
- out.push(finding('warn', 'clicks-vs-builds', slide, head,
736
- `${segments} [click] segment${segments === 1 ? '' : 's'} but ${clicks} build click${clicks === 1 ? '' : 's'}${tied}`
737
- + ` — ${clicks} click${clicks === 1 ? '' : 's'} take${clicks === 1 ? 's' : ''} ${clicks} [click] marker${clicks === 1 ? '' : 's'}`
738
- + ` in the notes (${clicks + 1} segments: one before the first click, one per click), and this slide has`
739
- + ` ${segments - 1}, so the narration and the builds drift apart here`));
972
+ // ⟨CLICK⟩ markers against build clicks (tools/click-match.mjs, #929), as
973
+ // far as the file can count them: a provider's steps exist only once the
974
+ // runtime has read them, so such a slide is left to the render half,
975
+ // which counts them in the browser and replaces this estimate when it runs.
976
+ const notesHtml = NOTES_ASIDE.exec(inner)?.[1];
977
+ const segments = clickSegments(notesHtml);
978
+ if (segments > 1 && !hasProvider(tree)) {
979
+ const lead = !cleanNotes(readNotes(notesHtml).split(CLICK_MARK)[0]);
980
+ const m = clickMismatch({
981
+ markers: segments - 1, clicks: buildClicks(tree),
982
+ cause: emptyBuildClick(tree, inner) ? 'empty-build' : lead ? 'lead-click' : null,
983
+ });
984
+ if (m) out.push(finding('warn', 'clicks-vs-builds', slide, head, clickMismatchText(m, { steps: buildSteps(tree) })));
740
985
  }
741
986
 
742
987
 
@@ -754,10 +999,35 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
754
999
  }
755
1000
  }
756
1001
 
1002
+ // A slide's group that is none of its run's (DECK_ANATOMY, #1188): the strip
1003
+ // cannot light it, and shows the slide as still in the group before.
1004
+ for (const u of stepRuns(stepSlides).unknown) {
1005
+ out.push(finding('warn', 'step-group', u.slide, title(u.slide), u.groups
1006
+ ? `data-step="${u.step}" is not one of its run's groups (${u.groups.join(', ')}) — the strip shows the slide as still in the group before: name one of them, or add it to data-steps on the slide the run starts on`
1007
+ : `data-step="${u.step}" is on a slide in no run — a run starts on a slide with data-steps="…" and ends at the next chapter or data-steps-end: start one, or take data-step off`));
1008
+ }
1009
+
1010
+ const tree = parseTree(src);
1011
+
1012
+ // A word Decklight does not know (tools/vocabulary.mjs): `data-buld`, a
1013
+ // build effect spelled `fade-upp`, a configuration key typed `trasition`
1014
+ // all render as if absent, and nothing else would ever say so.
1015
+ const titles = new Map();
1016
+ const titled = (slide) => {
1017
+ if (!titles.has(slide)) titles.set(slide, title(slide));
1018
+ return titles.get(slide);
1019
+ };
1020
+ out.push(...attributeFindings([...descendants(tree)].map((n) => {
1021
+ const slide = slideAt(ranges, n.start);
1022
+ return { slide, title: titled(slide), attrs: readAttrs(n.attrs) };
1023
+ })));
1024
+ const block = configBlock(src);
1025
+ if (block) out.push(...configFindings(block.inner, { line: src.slice(0, block.innerStart).split('\n').length }));
1026
+
757
1027
  // An asset that is not on disk is the failure with no symptom: the deck
758
1028
  // renders, the image is a blank box, and whoever exported the PDF finds out
759
1029
  // afterwards. Resolved the way the browser would, against the deck's folder.
760
- for (const ref of assetReferences(parseTree(src))) {
1030
+ for (const ref of assetReferences(tree)) {
761
1031
  if (exists(resolve(dir, ref.path))) continue;
762
1032
  const where = at(ref.at);
763
1033
  out.push(finding('error', 'missing-asset', where.slide, where.title,
@@ -782,7 +1052,7 @@ export function staticFindings(html, { dir = '.', exists = existsSync, designSys
782
1052
  `line ${h.line}: ${h.kind} on <${h.tag}> (${h.attr}) — --no-trust --strict would strip this`));
783
1053
  }
784
1054
 
785
- return sortFindings(out);
1055
+ return foldRepeats(sortFindings(out));
786
1056
  }
787
1057
 
788
1058
  /** Head first, then slides in order; within a slide, the order they were found. */
@@ -837,14 +1107,17 @@ export function renderFindings(domHtml, { slides = 0 } = {}) {
837
1107
  const head = slideHeading(sectionInner(bodies[i] ?? ''), i);
838
1108
  const attrs = readAttrs(m[0].slice('<section'.length).replace(/>$/, ''));
839
1109
  if ('data-overflow' in attrs) {
840
- // The guardrail is a boolean today (engine.js `checkOverflow` toggles the
841
- // attribute), so the px figure is reported only if a future one writes it
842
- // — better than printing a number this file made up.
1110
+ // The guardrail names what is cut and by how much (engine.js
1111
+ // `checkOverflow`: data-overflow="a diagram", data-overflow-by, #1183);
1112
+ // a deck on an older runtime carries a bare attribute, and is told only
1113
+ // that it is clipped, rather than a figure this file made up.
1114
+ const what = attrs['data-overflow'];
843
1115
  const by = Number(attrs['data-overflow-by']);
1116
+ const over = Number.isFinite(by) && by > 0;
844
1117
  out.push(finding('error', 'overflow', slide, head,
845
- Number.isFinite(by) && by > 0
846
- ? `content is clipped (${Math.round(by)} px over)`
847
- : 'content is clipped — it does not fit the slide, and the audience never sees the rest'));
1118
+ what && over ? `content is clipped: ${what} runs ${Math.round(by)}px past what the slide shows, and the audience never sees the rest`
1119
+ : over ? `content is clipped (${Math.round(by)} px over)`
1120
+ : 'content is clipped — it does not fit the slide, and the audience never sees the rest'));
848
1121
  }
849
1122
  // crowded past SLIDE_DENSITY: the runtime counts it as it lays the deck
850
1123
  // out (src/core/density.js) and marks the section, like data-overflow
@@ -853,6 +1126,17 @@ export function renderFindings(domHtml, { slides = 0 } = {}) {
853
1126
  `crowded: ${attrs['data-dense']} (~3–4 bullets or ~2 short paragraphs per column, SPEC SLIDE_DENSITY)`
854
1127
  + ' — split the slide rather than shrink it, or mark it data-dense-ok if it is meant'));
855
1128
  }
1129
+ // content the print render does not show, once builds are complete and the
1130
+ // deck's own animations finished (src/core/print-visibility.js, #1184): a
1131
+ // hole in the PDF. A warning, not an error: the runtime cannot read intent.
1132
+ const invisible = invisibleSaid(m[0]);
1133
+ if (invisible) {
1134
+ out.push(finding('warn', 'invisible-in-print', slide, head, invisibleMessage(invisible)));
1135
+ }
1136
+ // [click] markers against build clicks, counted by the engine itself
1137
+ // (engine.js markClickMismatch): providers included, which the file cannot do
1138
+ const clicks = readClickMismatch(attrs['data-click-mismatch']);
1139
+ if (clicks) out.push(finding('warn', 'clicks-vs-builds', slide, head, clickMismatchText(clicks)));
856
1140
  if ('data-split-conflict' in attrs) {
857
1141
  out.push(finding('warn', 'split-conflict', slide, head,
858
1142
  'data-layout="split" is fighting this slide\'s own column flexbox — two layout systems, '
@@ -908,34 +1192,101 @@ export function formatFindings(findings, { color = false, slides = 0 } = {}) {
908
1192
  return lines;
909
1193
  }
910
1194
 
911
- const USAGE = `usage: decklight check <deck.html> [--no-render] [--json] [--wait <ms>]
1195
+ const USAGE = `usage: decklight check <deck.html> [--no-render] [--json] [--wait <ms>] [--watch | --fix]
912
1196
  lints one deck and says, per slide, what you would otherwise only find by
913
1197
  looking — for an AI agent after every edit, and for a human before a talk
914
1198
 
915
1199
  what it reports
916
1200
  from the file a <section> that is never closed · an image, video, cast
917
1201
  or stylesheet that is not on disk · a data-markdown slide
918
- (removed in 0.3.0) · [click] segments that do not line up
919
- with the slide's build steps · script blocks and inline
920
- handlers --no-trust --strict would strip
921
- from a render slides the overflow guardrail measured as clipped, slides
1202
+ (removed in 0.3.0) · script blocks and inline handlers
1203
+ --no-trust --strict would strip · a misspelled data-*
1204
+ attribute, build effect, layout or other value, and a
1205
+ configuration block that is not JSON or has a key
1206
+ Decklight does not read, each with what was meant
1207
+ (an attribute close to nothing Decklight reads is yours,
1208
+ and left alone)
1209
+ its languages on a translation (talk.fr.html): a piece translated from
1210
+ words the source no longer has, or not translated, a
1211
+ slide changed in more than its words, a <html lang> that
1212
+ is not the record's. On the source, a warning per
1213
+ language behind. decklight translate fixes the first two
1214
+ from a render slides the overflow guardrail measured as clipped, slides
922
1215
  crowded past SLIDE_DENSITY (~3–4 bullets or ~2 short
923
1216
  paragraphs per column; a warning, and data-dense-ok on a
924
1217
  section says it is meant), split layouts fighting their
925
- own flexbox, and a deck whose runtime never mounted
1218
+ own flexbox, [click] markers that do not match the
1219
+ slide's build clicks (counted by the runtime, code
1220
+ stepping and terminals included; from the file alone
1221
+ under --no-render, which skips those), and a deck whose
1222
+ runtime never mounted
926
1223
  hints the same words on boxes on several slides in different
927
1224
  colours: one idea, worth one concept (SVG_DIAGRAMS) · an
928
1225
  SVG diagram with no build, landing all at once
929
- (data-static-ok says it is meant)
1226
+ (data-static-ok says it is meant) · a file with no
1227
+ <!doctype html>, which a browser opening it directly
1228
+ lays out in quirks mode
930
1229
 
931
1230
  --no-render the file half only — no Chrome, no render (a machine without
932
1231
  Chrome skips that half by itself, and says so)
933
1232
  --json the findings as a JSON array: level, rule, slide, title, message
1233
+ --fix migrate split-letter titles and their translation records to data-write
934
1234
  --wait <ms> render budget for heavy decks [8000]
1235
+ --watch check, then check again each time the deck is saved: the
1236
+ screen is cleared and the fresh findings printed under the
1237
+ time, one Chrome kept open for the whole session. For a
1238
+ terminal beside your editor; not with --json
935
1239
 
936
- exit 1 if anything is an error, 0 otherwise — warnings and hints never fail the run`;
1240
+ exit 1 if anything is an error, 0 otherwise — warnings and hints never fail the run.
1241
+ --watch runs until Ctrl-C and then exits 0, whatever it found`;
937
1242
 
938
- export async function checkMain(args = []) {
1243
+ /**
1244
+ * One check of the deck at `src`: both halves, the render through `render`
1245
+ * (`(url, wait) => dom`), or the file half alone when `render` is null.
1246
+ * Returns the findings in order and the slide count; `null` when the deck is
1247
+ * not there to read (a watch catches it mid-save).
1248
+ */
1249
+ export async function checkOnce(src, deck, { render, wait }) {
1250
+ let html;
1251
+ try { html = readFileSync(src, 'utf8'); } catch { return null; }
1252
+ const bodies = sectionBodies(html);
1253
+ const slides = bodies.length;
1254
+ const findings = staticFindings(html, { dir: dirname(src), deck });
1255
+ bodies.forEach((body, i) => {
1256
+ const title = legacyWriting(body)[0];
1257
+ if (title) findings.push(finding('warn', 'legacy-write', i + 1, title,
1258
+ 'the title is stored letter by letter. Run decklight check --fix to convert it and its translations to plain text'));
1259
+ });
1260
+ // a deck's languages (SPEC TRANSLATION_RECORD): string comparison, no model
1261
+ try { findings.push(...translationFindings(src, html, { finding })); } catch { /* a record that cannot be read says so itself */ }
1262
+ if (render) {
1263
+ try {
1264
+ const dom = await render(printUrl(src), wait);
1265
+ // the browser counted the [click]s against the builds, providers and
1266
+ // all: its answer replaces the file's estimate rather than joining it
1267
+ const rendered = renderFindings(dom, { slides });
1268
+ if (!rendered.some((f) => f.rule === 'not-rendered')) {
1269
+ findings.splice(0, findings.length, ...findings.filter((f) => f.rule !== 'clicks-vs-builds'));
1270
+ }
1271
+ findings.push(...rendered);
1272
+ } catch (e) {
1273
+ findings.push(finding('error', 'render-failed', null, 'head',
1274
+ `the deck could not be rendered — ${String(e.message ?? e).split('\n')[0]}`));
1275
+ }
1276
+ }
1277
+ return { findings: sortFindings(findings), slides };
1278
+ }
1279
+
1280
+ /** A one-shot Chrome per render: `--dump-dom` under a virtual-time budget. */
1281
+ export const oneShot = (bin) => (url, wait) => runAsync(bin, [
1282
+ ...chromeArgs('--allow-file-access-from-files', `--virtual-time-budget=${wait}`),
1283
+ '--dump-dom', url,
1284
+ ], {
1285
+ encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: CODEC_MS,
1286
+ why: 'Chrome did not finish rendering — a slide is probably waiting on a resource it cannot reach',
1287
+ });
1288
+
1289
+ export async function checkMain(args = [], { watchOpts = {} } = {}) {
939
1290
  if (args.includes('--help') || args.includes('-h')) { console.log(USAGE); return 0; }
940
1291
  const { opt } = argReader(args);
941
1292
  const deck = firstPositional(args, ['--wait']);
@@ -943,37 +1294,36 @@ export async function checkMain(args = []) {
943
1294
  const src = resolve(deck);
944
1295
  if (!existsSync(src)) { console.error(`decklight check: no such deck: ${deck}`); return 1; }
945
1296
 
946
- const html = readFileSync(src, 'utf8');
947
- const slides = sectionBodies(html).length;
948
- const findings = staticFindings(html, { dir: dirname(src), deck });
949
-
950
1297
  // The render half is skipped rather than failed when there is no browser:
951
1298
  // `findChrome` and never `chromeBin`, which exits the process — half a lint
952
1299
  // is the useful answer on a machine that cannot run the other half.
953
1300
  const json = args.includes('--json');
1301
+ const watching = args.includes('--watch');
1302
+ if (args.includes('--fix')) {
1303
+ if (watching) { console.error('decklight check: --fix and --watch cannot be combined'); return 1; }
1304
+ try {
1305
+ const count = migrateWriting(src);
1306
+ if (count) console.error(`check: converted ${count} split-letter title${count === 1 ? '' : 's'} to plain text`);
1307
+ } catch (e) { console.error(`decklight check: could not migrate split-letter titles: ${e.message}`); return 1; }
1308
+ }
1309
+ // a stream of JSON arrays over a cleared screen is nobody's input: an agent
1310
+ // checks once per edit, and a watch is a screen for a person
1311
+ if (watching && json) {
1312
+ console.error('decklight check: --watch is for a person at a terminal, and --json is for a program: '
1313
+ + 'run `decklight check <deck> --json` once per edit instead');
1314
+ return 1;
1315
+ }
954
1316
  const bin = args.includes('--no-render') ? null : findChrome();
955
1317
  const notes = [];
956
1318
  if (args.includes('--no-render')) notes.push('check: --no-render — the file half only, nothing was rendered');
957
1319
  else if (!bin) notes.push('check: no Chrome found — the file half only; clipped slides go unreported (point $CHROME at one)');
1320
+ const wait = Number(opt('--wait', 8000));
958
1321
 
959
- if (bin) {
960
- const wait = Number(opt('--wait', 8000));
961
- try {
962
- const dom = await runAsync(bin, [
963
- ...chromeArgs('--allow-file-access-from-files', `--virtual-time-budget=${wait}`),
964
- '--dump-dom', printUrl(src),
965
- ], {
966
- encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: CODEC_MS,
967
- why: 'Chrome did not finish rendering — a slide is probably waiting on a resource it cannot reach',
968
- });
969
- findings.push(...renderFindings(dom, { slides }));
970
- } catch (e) {
971
- findings.push(finding('error', 'render-failed', null, 'head',
972
- `the deck could not be rendered — ${String(e.message ?? e).split('\n')[0]}`));
973
- }
974
- }
1322
+ if (watching) return watchCheck(src, deck, { bin, wait, notes, ...watchOpts });
975
1323
 
976
- const ordered = sortFindings(findings);
1324
+ const once = await checkOnce(src, deck, { render: bin ? oneShot(bin) : null, wait });
1325
+ if (!once) { console.error(`decklight check: could not read ${deck}`); return 1; }
1326
+ const { findings: ordered, slides } = once;
977
1327
  const errors = ordered.filter((f) => f.level === 'error').length;
978
1328
  if (json) {
979
1329
  console.log(JSON.stringify(ordered, null, 2));
@@ -985,4 +1335,43 @@ export async function checkMain(args = []) {
985
1335
  return errors ? 1 : 0;
986
1336
  }
987
1337
 
1338
+ /**
1339
+ * `--watch`: check, then check again on every save, until Ctrl-C.
1340
+ *
1341
+ * One Chrome for the whole session (persistentRenderer), the screen cleared
1342
+ * and the fresh report printed under a timestamp each time. It runs until
1343
+ * it is interrupted and then exits 0: the findings decide nothing here, a
1344
+ * person reads them. `signals` and `out` are injectable for a test.
1345
+ */
1346
+ async function watchCheck(src, deck, { bin, wait, notes, signals = process, out = process.stdout, debounceMs = 150 }) {
1347
+ const { watchDeck, persistentRenderer, watchHeader } = await import('./check-watch.mjs');
1348
+ const renderer = bin ? persistentRenderer(bin) : null;
1349
+ const tty = !!out.isTTY;
1350
+ const print = (lines) => out.write(`${tty ? '\x1b[2J\x1b[3J\x1b[H' : ''}${lines.join('\n')}\n`);
1351
+ let stopping = false;
1352
+ const run = async () => {
1353
+ const r = await checkOnce(src, deck, { render: renderer ? (url, w) => renderer.render(url, w) : null, wait });
1354
+ if (stopping) return; // Ctrl-C mid-run: the browser it was using is gone, and so is the reader
1355
+ const dim = (x) => (tty ? `\x1b[2m${x}\x1b[0m` : x);
1356
+ if (!r) { print([dim(watchHeader(basename(src), 0)), '', `${deck} is not there right now; waiting for it to be saved again`]); return; }
1357
+ print([dim(watchHeader(basename(src), r.slides)), ...notes.map(dim), '',
1358
+ ...formatFindings(r.findings, { color: tty, slides: r.slides })]);
1359
+ };
1360
+ const watcher = watchDeck({ file: src, run, debounceMs, onError: (e) => out.write(`check: ${e.message ?? e}\n`) });
1361
+ return new Promise((done) => {
1362
+ const stop = async () => {
1363
+ if (stopping) return;
1364
+ stopping = true;
1365
+ signals.off?.('SIGINT', stop);
1366
+ signals.off?.('SIGTERM', stop);
1367
+ watcher.close();
1368
+ await renderer?.close(); // first: a run still rendering fails at once rather than finishing
1369
+ await watcher.settled().catch(() => {});
1370
+ done(0);
1371
+ };
1372
+ signals.once('SIGINT', stop);
1373
+ signals.once('SIGTERM', stop);
1374
+ });
1375
+ }
1376
+
988
1377
  if (isMain(import.meta.url)) process.exit(await runMain('check', () => checkMain(process.argv.slice(2))));