decklight 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tools/pptx.mjs CHANGED
@@ -170,6 +170,67 @@ const GRAPHIC = {
170
170
  diagram: 'SmartArt dropped — rebuild as an SVG diagram (SPEC SVG_DIAGRAMS)',
171
171
  };
172
172
 
173
+ /** OOXML chart element → data-chart type. Anything else is still a drop. */
174
+ const CHART_TYPES = {
175
+ 'c:barChart': 'bar', 'c:bar3DChart': 'bar',
176
+ 'c:lineChart': 'line', 'c:line3DChart': 'line',
177
+ 'c:areaChart': 'area', 'c:area3DChart': 'area',
178
+ 'c:pieChart': 'pie', 'c:pie3DChart': 'pie',
179
+ 'c:doughnutChart': 'donut',
180
+ };
181
+
182
+ /** The `c:pt` values of a cache, in index order; numbers where they parse. */
183
+ function cachePoints(node, numeric) {
184
+ const pts = findAll(node, 'c:pt').map((pt) => [Number(pt.attrs.idx ?? 0), textOf(find(pt, 'c:v') ?? pt).trim()]);
185
+ pts.sort((a, b) => a[0] - b[0]);
186
+ return pts.map(([, v]) => (numeric ? Number(v) : v));
187
+ }
188
+
189
+ /**
190
+ * A PowerPoint chart, as data-chart's JSON.
191
+ *
192
+ * The chart part carries the data in caches — `c:numCache` and `c:strCache`
193
+ * are the values as last calculated, so nothing here needs the workbook the
194
+ * chart was drawn from. This was the single most common rebuild in a business
195
+ * deck, and every byte it needed was already in the file.
196
+ *
197
+ * Returns null for a chart kind decklight has no native answer for (scatter,
198
+ * radar, stock…); the caller then drops it by name, as before.
199
+ */
200
+ export function parseChart(xml) {
201
+ const doc = parseXml(xml ?? '');
202
+ const plot = find(doc, 'c:plotArea');
203
+ if (!plot) return null;
204
+ // `children(node, name)` filters by ONE name; the plot area's first chart
205
+ // element is whichever of the known kinds is there, so walk its kids directly
206
+ const kindNode = (plot.children ?? []).find((n) => CHART_TYPES[n.name]);
207
+ if (!kindNode) return null;
208
+ const type = CHART_TYPES[kindNode.name];
209
+ const series = findAll(kindNode, 'c:ser').map((ser, i) => {
210
+ const tx = find(ser, 'c:tx');
211
+ const name = tx ? textOf(tx).trim() : `series ${i + 1}`;
212
+ const cat = find(ser, 'c:cat');
213
+ const val = find(ser, 'c:val');
214
+ return {
215
+ name: name || `series ${i + 1}`,
216
+ labels: cat ? cachePoints(cat, false) : [],
217
+ data: val ? cachePoints(val, true).map((n) => (Number.isFinite(n) ? n : 0)) : [],
218
+ };
219
+ }).filter((sr) => sr.data.length);
220
+ if (!series.length) return null;
221
+ const labels = series.find((sr) => sr.labels.length)?.labels ?? series[0].data.map((_, i) => String(i + 1));
222
+ const titleNode = find(doc, 'c:title');
223
+ const title = titleNode ? findAll(titleNode, 'a:t').map((t) => textOf(t)).join('').trim() : '';
224
+ return {
225
+ type,
226
+ title,
227
+ labels,
228
+ // a pie is one series in decklight; PowerPoint allows more but draws one
229
+ series: (type === 'pie' || type === 'donut' ? series.slice(0, 1) : series)
230
+ .map(({ name, data }) => ({ name, data })),
231
+ };
232
+ }
233
+
173
234
  /**
174
235
  * One slide, as the pieces a `<section>` needs.
175
236
  *
@@ -177,7 +238,7 @@ const GRAPHIC = {
177
238
  * order the slide did. Groups are walked into: a shape inside a group is still
178
239
  * content, and skipping groups loses whole slides' worth of text.
179
240
  */
180
- export function parseSlide(xml, { rels, mediaOf, slideNo = 0 } = {}) {
241
+ export function parseSlide(xml, { rels, mediaOf, chartOf, slideNo = 0 } = {}) {
181
242
  const doc = parseXml(xml);
182
243
  const sld = find(doc, 'p:sld');
183
244
  const hidden = sld?.attrs.show === '0';
@@ -250,6 +311,15 @@ export function parseSlide(xml, { rels, mediaOf, slideNo = 0 } = {}) {
250
311
  if (tbl) blocks.push({ kind: 'table', node: tbl });
251
312
  continue;
252
313
  }
314
+ if (kind === 'chart') {
315
+ // the frame holds only a relationship; the data is in its own part
316
+ const rid = find(node, 'c:chart')?.attrs['r:id'];
317
+ const rel = rid && rels?.get(rid);
318
+ const chart = rel && chartOf ? parseChart(chartOf(rel.target)) : null;
319
+ if (chart) { blocks.push({ kind: 'chart', ...chart }); continue; }
320
+ drop(GRAPHIC.chart);
321
+ continue;
322
+ }
253
323
  drop(GRAPHIC[kind] ?? `an embedded ${kind || 'object'} was dropped`);
254
324
  continue;
255
325
  }
@@ -280,6 +350,13 @@ export function notesText(xml, { rels } = {}) {
280
350
  }
281
351
 
282
352
  /** A parsed slide as the `<section>` markup, plus what its report line says. */
353
+ /** A chart block as SPEC CHARTS markup — JSON in a script tag, so `</` must not end it early. */
354
+ export function chartHtml({ type, title, labels, series }) {
355
+ const json = JSON.stringify({ labels, series }).replace(/<\//g, '<\\/');
356
+ const attrs = [`class="chart"`, `data-chart="${type}"`, title ? `data-title="${escapeHtml(title)}"` : null].filter(Boolean);
357
+ return `<div ${attrs.join(' ')}>\n <script type="application/json">${json}</script>\n </div>`;
358
+ }
359
+
283
360
  export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
284
361
  const parts = [];
285
362
  const did = [];
@@ -303,6 +380,9 @@ export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
303
380
  const cols = rows.length ? children(rows[0], 'a:tc').length : 0;
304
381
  did.push(`table ${rows.length}×${cols}`);
305
382
  parts.push(` ${tableHtml(b.node)}`);
383
+ } else if (b.kind === 'chart') {
384
+ did.push(`chart (${b.type}, ${b.series.length} series × ${b.labels.length})`);
385
+ parts.push(` ${chartHtml(b)}`);
306
386
  } else if (b.kind === 'image') {
307
387
  did.push(`image inlined (${Math.round(b.bytes.length / 1024)} KB)`);
308
388
  parts.push(` <img src="data:${b.mime};base64,${b.bytes.toString('base64')}"`
@@ -316,5 +396,5 @@ export function slideSection(slide, notes = [], { build = 'auto' } = {}) {
316
396
  for (const line of notes) parts.push(` <p>${line}</p>`);
317
397
  parts.push(' </aside>');
318
398
  }
319
- return { html: ` <section>\n${parts.join('\n')}\n </section>`, did };
399
+ return { html: ` <section${slide.hidden ? ' data-hidden' : ''}>\n${parts.join('\n')}\n </section>`, did };
320
400
  }
@@ -14,10 +14,10 @@
14
14
  // Requires gh (authenticated) on PATH.
15
15
 
16
16
  import { readFileSync, readdirSync, existsSync } from 'node:fs';
17
- import { execFileSync } from 'node:child_process';
18
17
  import { join } from 'node:path';
19
18
  import { createHash } from 'node:crypto';
20
19
  import { argReader } from './args.mjs';
20
+ import { run, NETWORK_MS } from './exec.mjs';
21
21
 
22
22
  const args = process.argv.slice(2);
23
23
  const { opt } = argReader(args);
@@ -25,7 +25,7 @@ const REPO = opt('--repo', 'decklight/decklight.github.io');
25
25
  const STAGING = 'demo/voiceover-site';
26
26
 
27
27
  const gh = (argv, input) =>
28
- JSON.parse(execFileSync('gh', ['api', ...argv], { encoding: 'utf8', input, maxBuffer: 1 << 28 }));
28
+ JSON.parse(run('gh', ['api', ...argv], { encoding: 'utf8', input, maxBuffer: 1 << 28, timeout: NETWORK_MS, why: 'gh is waiting on the network or a login — run: gh auth status' }));
29
29
 
30
30
  // git blob sha1: sha1("blob <len>\0" + content)
31
31
  const blobSha = (buf) =>
@@ -33,9 +33,11 @@
33
33
  */
34
34
 
35
35
  import { zipSync } from '../cli/zip.mjs';
36
+ import * as fsSync from 'node:fs';
37
+ import * as pathMod from 'node:path';
36
38
  import { validateSchema } from '../cli/wizard.mjs';
37
39
 
38
- export const TARGETS = ['netlify', 'vercel'];
40
+ export const TARGETS = ['netlify', 'vercel', 'folder'];
39
41
 
40
42
  // Raw schemas, in the ENGINES#WIZARD shape (cli/wizard.mjs FIELD_TYPES) — the same
41
43
  // vocabulary a marketplace-declared engine is limited to, so a hand-authored schema
@@ -58,12 +60,26 @@ const RAW_SCHEMAS = {
58
60
  { name: 'teamId', label: 'Team ID', type: 'text' },
59
61
  ],
60
62
  },
63
+ // The target with no provider: the same files the others upload, written
64
+ // into a directory, for whatever serves it — an S3 sync, an rsync to a VPS,
65
+ // a Dropbox folder, a corporate intranet share. "Send me a link" is the
66
+ // reflex of everyone coming from Google Slides, and a link needs a host
67
+ // that is not GitHub. No credential, because the folder IS the credential.
68
+ folder: {
69
+ engine: 'folder',
70
+ title: 'A folder — any static host',
71
+ fields: [
72
+ { name: 'dir', label: 'Directory to write the site into', type: 'text', required: true },
73
+ { name: 'url', label: 'Public URL that directory is served at (printed as the deck link)', type: 'text' },
74
+ ],
75
+ },
61
76
  };
62
77
 
63
78
  /** Which environment variable answers each field — the provider's OWN CLI names. */
64
79
  const ENV_VARS = {
65
80
  netlify: { token: 'NETLIFY_AUTH_TOKEN', siteId: 'NETLIFY_SITE_ID' },
66
81
  vercel: { token: 'VERCEL_TOKEN', project: 'VERCEL_PROJECT', teamId: 'VERCEL_TEAM_ID' },
82
+ folder: { dir: 'DECKLIGHT_PUBLISH_DIR', url: 'DECKLIGHT_PUBLISH_URL' },
67
83
  };
68
84
 
69
85
  const known = (target) => {
@@ -134,7 +150,28 @@ export async function deployVercel({ token, project, teamId }, files, { fetchImp
134
150
  return { url: j.url ? `https://${j.url}` : null, id: j.id ?? j.uid ?? null };
135
151
  }
136
152
 
137
- const DEPLOYERS = { netlify: deployNetlify, vercel: deployVercel };
153
+ /**
154
+ * Write the site into a directory. Every path a target receives is relative
155
+ * and already carries `--path`'s subdirectory, so the only thing to refuse is
156
+ * a path that would climb out of the folder — which none of ours produces,
157
+ * and which this checks anyway, because the folder may be somebody's home.
158
+ */
159
+ export async function deployFolder({ dir, url }, files, { fs: fsImpl = null } = {}) {
160
+ const fs = fsImpl ?? fsSync;
161
+ const root = pathMod.resolve(dir);
162
+ for (const { path: rel, data } of files) {
163
+ const abs = pathMod.resolve(root, rel);
164
+ if (abs !== root && !abs.startsWith(root + pathMod.sep)) throw new Error(`folder: refusing to write outside ${root}: ${rel}`);
165
+ fs.mkdirSync(pathMod.dirname(abs), { recursive: true });
166
+ fs.writeFileSync(abs, data);
167
+ }
168
+ // the link is the public url plus the subdirectory the files were written under
169
+ const sub = pathMod.dirname(files[0]?.path ?? 'index.html');
170
+ const base = url ? url.replace(/\/+$/, '') : null;
171
+ return { url: base ? `${base}${sub === '.' ? '' : `/${sub}`}/` : null, id: root };
172
+ }
173
+
174
+ const DEPLOYERS = { netlify: deployNetlify, vercel: deployVercel, folder: deployFolder };
138
175
 
139
176
  /** `files` is `[{ path, data: Buffer|string }]` — the same set gh-pages commits. */
140
177
  export async function deploy(target, answers, files, opts = {}) {
@@ -20,10 +20,10 @@
20
20
  // repo tool; gcloud already owns those credentials and should keep owning them.
21
21
  // Same posture as tools/publish-site-voices.mjs shelling out to `gh`.
22
22
 
23
- import { execFileSync } from 'node:child_process';
24
23
  import { existsSync, readFileSync, writeFileSync, statSync } from 'node:fs';
25
24
  import { basename, join, resolve } from 'node:path';
26
25
  import { argReader, isMain } from './args.mjs';
26
+ import { run, NETWORK_MS } from './exec.mjs';
27
27
 
28
28
  const USAGE = `usage: node tools/publish-voices.mjs <voice-dir> --bucket gs://bucket/prefix [--sign 7d]
29
29
  uploads a recorded track's audio to Cloud Storage and writes a manifest of
@@ -177,7 +177,7 @@ export function signedUrlFrom(json) {
177
177
  return one?.signed_url ?? one?.signedUrl ?? one?.signed_uri ?? null;
178
178
  }
179
179
 
180
- const gcloud = (argv) => execFileSync('gcloud', argv, { encoding: 'utf8', maxBuffer: 1 << 26 });
180
+ const gcloud = (argv) => run('gcloud', argv, { encoding: 'utf8', maxBuffer: 1 << 26, timeout: NETWORK_MS, why: 'gcloud is waiting on a login that expired, or on the network — run: gcloud auth application-default login' });
181
181
 
182
182
  export async function publishVoicesMain(args = []) {
183
183
  if (!args.length || args.includes('--help') || args.includes('-h')) { console.log(USAGE); return args.length ? 0 : 1; }
@@ -0,0 +1,154 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * A PowerPoint template's palette and fonts, as a decklight theme.
6
+ *
7
+ * `decklight import` throws the template's LOOK away on purpose — the deck you
8
+ * get is a decklight deck, not a screenshot of the old one — and every
9
+ * imported corporate deck arrived in `midnight`, to be re-themed by hand. The
10
+ * part of the look that is a THEME rather than a layout was in the file all
11
+ * along: ppt/theme/theme1.xml carries the colour scheme (dk1, lt1, dk2, lt2,
12
+ * accent1–6, hlink) and the font scheme (a heading face and a body face). That
13
+ * is most of what a brand team means by "our template".
14
+ *
15
+ * So this reads those two schemes and derives the full SPEC THEMING token set
16
+ * from them. Derives, not copies: a template has twelve colours and a theme
17
+ * needs fifty-six tokens with contrast gates between them, so the rest is
18
+ * chosen from the twelve and then PUSHED until every gate in
19
+ * tools/theme-check.mjs clears — a link colour that reads on the slide
20
+ * background, six diagram fills a label can be read on, a code palette that
21
+ * is legible on the block. The result is validated by the same function
22
+ * `decklight theme check` runs, and if it cannot be made to pass, that is
23
+ * reported rather than shipped.
24
+ */
25
+
26
+ import { parseXml, find, findAll } from './ooxml.mjs';
27
+ import { parseColor, contrast } from './color.mjs';
28
+ import { validateTheme, GATES } from './theme-check.mjs';
29
+
30
+ const SLOTS = ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink'];
31
+
32
+ /** Windows system colours a theme may name instead of a hex value. */
33
+ const SYSTEM = { windowText: '000000', window: 'FFFFFF' };
34
+
35
+ const hex = ([r, g, b]) => '#' + [r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
36
+ const rgb = (h) => parseColor(h);
37
+ const mix = (a, b, t) => hex(rgb(a).map((v, i) => v + (rgb(b)[i] - v) * t));
38
+
39
+ /**
40
+ * The scheme, or null when the part is not a theme. Each colour slot resolves
41
+ * `a:srgbClr` or `a:sysClr` (with its lastClr, else the system default).
42
+ */
43
+ export function parseTemplateTheme(xml) {
44
+ const doc = parseXml(xml ?? '');
45
+ const scheme = find(doc, 'a:clrScheme');
46
+ if (!scheme) return null;
47
+ const colors = {};
48
+ for (const slot of SLOTS) {
49
+ const node = find(scheme, `a:${slot}`);
50
+ if (!node) continue;
51
+ const srgb = find(node, 'a:srgbClr')?.attrs.val;
52
+ const sys = find(node, 'a:sysClr');
53
+ const val = srgb ?? sys?.attrs.lastClr ?? (sys && SYSTEM[sys.attrs.val]);
54
+ if (val && /^[0-9a-f]{6}$/i.test(val)) colors[slot] = '#' + val.toLowerCase();
55
+ }
56
+ const fonts = find(doc, 'a:fontScheme');
57
+ const face = (which) => find(find(fonts, which) ?? { children: [] }, 'a:latin')?.attrs.typeface ?? null;
58
+ return {
59
+ name: scheme.attrs.name ?? find(doc, 'a:theme')?.attrs.name ?? 'template',
60
+ colors,
61
+ fonts: { heading: fonts ? face('a:majorFont') : null, body: fonts ? face('a:minorFont') : null },
62
+ };
63
+ }
64
+
65
+ /** Nudge `fg` toward black or white — whichever moves it away from `bg` — until the gate clears. */
66
+ function pushUntil(fg, bg, min) {
67
+ const dark = contrast(rgb(bg), [0, 0, 0]) > contrast(rgb(bg), [255, 255, 255]);
68
+ const target = dark ? '#000000' : '#ffffff';
69
+ let out = fg;
70
+ for (let t = 0; t <= 1.0001 && contrast(rgb(out), rgb(bg)) < min; t += 0.05) out = mix(fg, target, t);
71
+ return out;
72
+ }
73
+
74
+ /** A font stack around the template's face, with the same fallbacks the shipped themes use. */
75
+ const stack = (face, mono = false) => (mono
76
+ ? '"SF Mono", SFMono-Regular, ui-monospace, "Cascadia Code", Menlo, Consolas, monospace'
77
+ : `${face ? `"${face.replace(/"/g, '')}", ` : ''}-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`);
78
+
79
+ /**
80
+ * The full token set, derived from a scheme and pushed through the gates.
81
+ *
82
+ * Light by construction: PowerPoint templates are lt1-on-dk1 far more often
83
+ * than not, and a slide background that is the template's page colour is what
84
+ * "looks like our template" means. Returns { css, name, ok, errors }; `ok` is
85
+ * theme-check's verdict on the CSS this produced.
86
+ */
87
+ export function themeFromTemplate(parsed, { name } = {}) {
88
+ const c = parsed.colors;
89
+ const bg = c.lt1 ?? '#ffffff';
90
+ const fg = c.dk1 ?? '#1a1a1a';
91
+ const accents = [1, 2, 3, 4, 5, 6].map((i) => c[`accent${i}`] ?? mix(fg, bg, 0.3 + i * 0.08));
92
+ const tok = {};
93
+ tok.bg = bg;
94
+ tok['bg-accent'] = mix(bg, c.lt2 ?? accents[0], 0.35);
95
+ tok.fg = pushUntil(fg, bg, 4.5);
96
+ tok.muted = pushUntil(mix(c.dk2 ?? fg, bg, 0.35), bg, 3.0);
97
+ tok['font-body'] = stack(parsed.fonts.body);
98
+ tok['font-heading'] = stack(parsed.fonts.heading ?? parsed.fonts.body);
99
+ tok['font-mono'] = stack(null, true);
100
+ tok['heading-color'] = pushUntil(c.dk2 ?? accents[0], bg, 3.0);
101
+ tok['heading-weight'] = '700';
102
+ tok.link = pushUntil(c.hlink ?? accents[0], bg, 3.0);
103
+ tok.accent = accents[0];
104
+ tok['accent-contrast'] = contrast(rgb(accents[0]), rgb(bg)) >= contrast(rgb(accents[0]), rgb(fg)) ? bg : fg;
105
+ tok['accent-contrast'] = pushUntil(tok['accent-contrast'], accents[0], 4.5);
106
+ tok['block-bg'] = mix(bg, c.lt2 ?? fg, 0.08);
107
+ tok['block-border'] = `1px solid ${mix(bg, fg, 0.18)}`;
108
+ tok['block-radius'] = '10px';
109
+ tok.shadow = '0 10px 32px rgba(0, 0, 0, 0.12)';
110
+ // code: the template's secondary light on the page, ink on it
111
+ tok['code-bg'] = mix(bg, c.lt2 ?? fg, 0.12);
112
+ tok['code-fg'] = pushUntil(fg, tok['code-bg'], 4.5);
113
+ const hl = ['keyword', 'string', 'number', 'function', 'type', 'punct'];
114
+ hl.forEach((h, i) => { tok[`hl-${h}`] = pushUntil(accents[i % 6], tok['code-bg'], 4.5); });
115
+ tok['hl-comment'] = pushUntil(tok.muted, tok['code-bg'], 3.0);
116
+ // diagrams. SPEC CHARTS: the --d-fill panels sit deliberately CLOSE TO THE
117
+ // CANVAS, gated for text on them — so a fill is a pale tint of its accent,
118
+ // not the accent, and the ink on it is the page's ink. Each tint is then
119
+ // pushed toward the page until that ink clears the gate on it.
120
+ const towardBg = (fill, ink, min) => {
121
+ let out = fill;
122
+ for (let t = 0; t <= 1.0001 && contrast(rgb(ink), rgb(out)) < min; t += 0.05) out = mix(fill, bg, t);
123
+ return out;
124
+ };
125
+ tok['d-text'] = tok.fg;
126
+ accents.forEach((a, i) => { tok[`d-fill-${i + 1}`] = towardBg(mix(a, bg, 0.72), tok.fg, 3.0); });
127
+ const fills = [1, 2, 3, 4, 5, 6].map((i) => tok[`d-fill-${i}`]);
128
+ // one muted and one accent ink that read on EVERY fill: push against the hardest one
129
+ const onAllFills = (ink, min) => fills.reduce((out, f) => pushUntil(out, f, min), ink);
130
+ tok['d-muted'] = onAllFills(mix(tok.fg, bg, 0.4), 2.6);
131
+ tok['d-accent'] = onAllFills(accents[0], 2.6);
132
+ tok['d-stroke'] = pushUntil(c.dk2 ?? fg, bg, 3.0);
133
+ // terminal: the template's dark on itself — a terminal on a light theme is still dark
134
+ tok['term-bg'] = c.dk2 ?? mix(fg, '#000000', 0.2);
135
+ tok['term-fg'] = pushUntil(bg, tok['term-bg'], 3.0);
136
+ tok['term-prompt'] = pushUntil(accents[0], tok['term-bg'], 3.0);
137
+ tok['term-cursor'] = tok['term-fg'];
138
+ tok['term-selection'] = mix(tok['term-bg'], tok['term-fg'], 0.3);
139
+ const ansi = { black: mix(tok['term-bg'], tok['term-fg'], 0.45), red: accents[0], green: accents[1], yellow: accents[2], blue: accents[3], magenta: accents[4], cyan: accents[5], white: tok['term-fg'] };
140
+ for (const [k, v] of Object.entries(ansi)) {
141
+ tok[`ansi-${k}`] = pushUntil(v, tok['term-bg'], 3.0);
142
+ tok[`ansi-bright-${k}`] = pushUntil(mix(v, tok['term-fg'], 0.35), tok['term-bg'], 3.0);
143
+ }
144
+ // one last pass over EVERY gate, in case a derived token moved another's background
145
+ for (const [f, b, min] of GATES) {
146
+ if (f.startsWith('d-')) continue; // settled above, against every fill at once
147
+ if (tok[f] && tok[b] && /^#/.test(tok[f]) && /^#/.test(tok[b]) && contrast(rgb(tok[f]), rgb(tok[b])) < min) tok[f] = pushUntil(tok[f], tok[b], min);
148
+ }
149
+ const themeName = name ?? `template-${String(parsed.name).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'template'}`;
150
+ const lines = Object.entries(tok).map(([k, v]) => ` --${k}: ${v};`);
151
+ const css = `/* Decklight theme · ${themeName}\n light · derived from the PowerPoint template's colour and font schemes\n Token contract: SPEC.md THEMING */\n.decklight {\n${lines.join('\n')}\n}\n`;
152
+ const check = validateTheme(css);
153
+ return { css, name: themeName, ok: check.ok, errors: check.errors ?? [] };
154
+ }
@@ -17,7 +17,7 @@
17
17
  * enough to always be right, and being right is what a test picker is for.
18
18
  *
19
19
  * The render harnesses are the opposite: serial, minutes long, and each one
20
- * pinned to a subsystem you can name. `narration-render` alone is 65s — a third
20
+ * pinned to a subsystem you can name. The five narration groups together are ~100s — a third
21
21
  * of the suite — and a change to `cli/pdf.mjs` has no business waiting for it.
22
22
  * That is the decision worth automating, so that is the only one made here.
23
23
  *
@@ -40,9 +40,14 @@ import { isMain } from './args.mjs';
40
40
  const here = path.dirname(fileURLToPath(import.meta.url));
41
41
  const repo = path.resolve(here, '..');
42
42
 
43
+ /** narration-render's five concerns, as verify runs them (see test/verify.mjs). */
44
+ const NARRATION = ['narration-render:live', 'narration-render:picker', 'narration-render:recorded', 'narration-render:segments', 'narration-render:record'];
45
+
43
46
  /** Every harness `verify` knows, in its running order. */
44
47
  export const ALL = [
45
- 'render', 'player-render', 'narration-render', 'record-render', 'review-render',
48
+ 'render', 'player-render',
49
+ 'narration-render:live', 'narration-render:picker', 'narration-render:recorded', 'narration-render:segments', 'narration-render:record',
50
+ 'record-render', 'review-render',
46
51
  'character-render', 'engine-render', 'pin-render', 'overflow-render', 'split-render',
47
52
  'strict-render', 'shot-render', 'plugin-render', 'extension-check-render',
48
53
  'deckfile-render', 'pdf-render', 'import-render', 'contrast', 'palette-rules',
@@ -76,9 +81,9 @@ const RULES = [
76
81
  [/^package\.json$/, ALL, 'scripts, deps and packed files'],
77
82
 
78
83
  // ── subsystems, each with a harness that is about it ────────────────────
79
- [/^src\/core\/narration\.js$/, ['narration-render', 'record-render', 'character-render'],
84
+ [/^src\/core\/narration\.js$/, [...NARRATION, 'record-render', 'character-render'],
80
85
  'narration drives playback, the recorder and the character overlay'],
81
- [/^src\/core\/character\.js$/, ['character-render', 'narration-render'], 'the talking head'],
86
+ [/^src\/core\/character\.js$/, ['character-render', ...NARRATION], 'the talking head'],
82
87
  [/^src\/core\/character-art\.js$/, ['character-render'], 'the head it draws'],
83
88
  [/^src\/core\/review\.js$/, ['review-render'], 'the review overlay and its anchor resolver'],
84
89
  [/^src\/core\/overflow\.js$/, ['overflow-render', 'pin-render'], 'the overflow guardrail and the pinned-title case'],
@@ -107,7 +112,7 @@ const RULES = [
107
112
  [/^tools\/(theme-check|color)\.mjs$/, LINT, 'the theme lints'],
108
113
  [/^tools\/chrome\.mjs$/, ALL, 'every harness starts a browser through it'],
109
114
  [/^tools\/review-anchor\.mjs$/, ['review-render'], 'the anchor resolver both halves share'],
110
- [/^tools\/(tts-engines|local-voice|voiceover-server|lipsync)\.mjs$/, ['narration-render', 'record-render'],
115
+ [/^tools\/(tts-engines|local-voice|voiceover-server|lipsync)\.mjs$/, [...NARRATION, 'record-render'],
111
116
  'the voice bridge narration talks to'],
112
117
  [/^themes\//, ['render', ...LINT], 'a theme, and the gates that read every theme'],
113
118
  [/^demo\//, ['render'], 'the smoke deck itself'],
@@ -128,8 +133,9 @@ export function forPath(p) {
128
133
  // A harness fixture is about its own harness; `foo-render.mjs` / `foo.html`.
129
134
  const m = /^test\/([a-z-]+?)(?:-render)?\.(?:mjs|html)$/.exec(p);
130
135
  if (m) {
131
- const hit = ALL.find((h) => h === m[1] || h === `${m[1]}-render`);
132
- if (hit) return { harnesses: [hit], why: 'its own harness' };
136
+ // `narration.html` is the fixture for all five narration groups
137
+ const hits = ALL.filter((h) => h === m[1] || h === `${m[1]}-render` || h.startsWith(`${m[1]}-render:`));
138
+ if (hits.length) return { harnesses: hits, why: hits.length > 1 ? 'its own harnesses' : 'its own harness' };
133
139
  }
134
140
  return { harnesses: ALL, why: 'UNMAPPED — falling back to everything' };
135
141
  }
@@ -210,7 +216,8 @@ const selected = ALL.filter((h) => picked.has(h));
210
216
 
211
217
  // Measured on a laptop; a rough shape so the report can say what it saves.
212
218
  const COST = {
213
- 'narration-render': 65, 'extension-check-render': 23, 'engine-render': 17, render: 20,
219
+ 'narration-render:live': 25, 'narration-render:picker': 12, 'narration-render:recorded': 12,
220
+ 'narration-render:segments': 12, 'narration-render:record': 40, 'extension-check-render': 23, 'engine-render': 17, render: 20,
214
221
  'pdf-render': 10, 'split-render': 9, 'review-render': 8, 'pin-render': 7, 'record-render': 7,
215
222
  'strict-render': 6, 'overflow-render': 6, 'plugin-render': 6, 'deckfile-render': 4,
216
223
  'shot-render': 4, 'player-render': 3, 'character-render': 2, 'import-render': 2,
@@ -0,0 +1,191 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The synthesis cache on disk — one clip per (engine, model, format, voice,
6
+ * style, text), shared by everything that speaks.
7
+ *
8
+ * It lived inside tools/voiceover-server.mjs and served only the free local
9
+ * engines, on the argument that a cloud engine's output drifts with the
10
+ * server's model and a stale clip is worse than re-billing one preview
11
+ * sentence. That argument was answering the wrong question: it treated the
12
+ * MODEL as invisible, so the only way to avoid serving audio from last
13
+ * quarter's model was to keep no audio at all. Put the model in the key and
14
+ * the drift is not a risk, it is a cache miss — a new model is new bytes under
15
+ * a new name, and yesterday's clip is unreachable rather than wrong.
16
+ *
17
+ * What that buys is the thing the memory cache never could: the live bridge
18
+ * and `decklight voiceover` are SEPARATE PROCESSES, so a deck previewed
19
+ * sentence by sentence in the browser and then batch-recorded paid ElevenLabs
20
+ * twice for identical text. They now meet here, because the key is derived
21
+ * from what was said and how — not from who is asking.
22
+ *
23
+ * The key deliberately does NOT include the deck, the slide number or the
24
+ * output directory. The same sentence in two decks is the same audio, and a
25
+ * second take into a different `-o` should cost nothing.
26
+ *
27
+ * Nothing here throws. A cache that cannot be read is a cache miss and a cache
28
+ * that cannot be written is a cache — read-only media, a full disk and a
29
+ * locked-down $HOME all degrade to "synthesize it again", never to a failed
30
+ * talk.
31
+ */
32
+
33
+ import { createHash } from 'node:crypto';
34
+ import { mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { join } from 'node:path';
37
+
38
+ /**
39
+ * How much audio is allowed to accumulate before the oldest is dropped.
40
+ *
41
+ * A per-sentence cache grows forever, and a silent 10 GB in ~/.cache is not a
42
+ * cache, it is a leak with a euphemism.
43
+ */
44
+ export const CACHE_LIMIT = 400 * 1024 * 1024;
45
+
46
+ /** Where clips live. `$XDG_CACHE_HOME` wins, so a test never touches the real one. */
47
+ export function cacheHome(env = process.env) {
48
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'decklight', 'tts');
49
+ }
50
+
51
+ /**
52
+ * The file extension for what an engine returned.
53
+ *
54
+ * ElevenLabs' `--tts-format mp3` is the only path that is not a WAV, and
55
+ * filing an mp3 under `.wav` would make the cache dir a pile of lies — playable
56
+ * by nothing that trusts the name, prunable only by accident.
57
+ */
58
+ export function extFor(mime) {
59
+ return mime === 'audio/mpeg' ? 'mp3' : 'wav';
60
+ }
61
+
62
+ /** Every extension the cache is allowed to own, for pruning. */
63
+ export const CACHE_EXTS = ['.wav', '.mp3'];
64
+
65
+ /**
66
+ * The name a clip is filed under.
67
+ *
68
+ * Everything that changes the AUDIO is in here and nothing else is. `model` is
69
+ * the addition that lets cloud engines be cached at all; `format` is here
70
+ * because pcm and mp3 of one sentence are different bytes with the same words.
71
+ *
72
+ * NUL joins the fields so they cannot run together — a style ending in a space
73
+ * and a text starting with one must not hash like their neighbours — but
74
+ * written as an ESCAPE, not a raw byte: git calls any file with a NUL in its
75
+ * first 8 KB binary, and this file would silently become undiffable.
76
+ */
77
+ export function cacheKey({ engine, model, format, voice, style, text } = {}) {
78
+ return createHash('sha256')
79
+ .update([engine, model, format, voice, style, text].map((f) => f ?? '').join('\u0000'))
80
+ .digest('hex');
81
+ }
82
+
83
+ /**
84
+ * The key for one sentence on one ENGINE — the form both callers use.
85
+ *
86
+ * `cacheKey` above takes loose fields, which is what makes it testable; this
87
+ * takes the engine object and derives them, which is what makes the live
88
+ * bridge and `decklight voiceover` agree. They used to assemble the fields
89
+ * separately, and separately is how a cache that spans two processes quietly
90
+ * stops hitting: one of them starts sending a field the other does not, every
91
+ * lookup misses, and nothing fails — you just pay twice again.
92
+ *
93
+ * Two rules are worth naming, because both were bugs before they were rules.
94
+ *
95
+ * WHAT `model` MEANS DIFFERS BY ENGINE, and only gemini, chirp and ElevenLabs
96
+ * mean by it what the word says. For say and SAPI it is the voice the process
97
+ * booted with, while the voice that actually speaks arrives per sentence — so
98
+ * a bridge started without `--voice` and a recorder started with one hashed
99
+ * the same sentence, in the same voice, two different ways, and the batch
100
+ * recording missed every clip the browser had just filed. For piper it is the
101
+ * loaded model and the per-sentence voice is ignored entirely, which is the
102
+ * opposite mistake: keying on the request would let two runs under different
103
+ * `--voice` models collide on one key and serve the wrong voice. Each engine
104
+ * declares which it is (`modelIsDefaultVoice`, `voiceIsFixed`) rather than
105
+ * this file guessing from the name.
106
+ *
107
+ * STYLE only counts when the engine can act on it. Only gemini and ElevenLabs
108
+ * v3 read a delivery instruction; the rest are handed one and ignore it. The
109
+ * bridge gets its style from the deck (usually none) and the CLI defaults to a
110
+ * paragraph about a warm senior engineer — so keying on a style neither engine
111
+ * read would make identical audio hash two ways. `stylable` is the engine's
112
+ * own answer to "can this change the sound", and only then does it change the
113
+ * name.
114
+ */
115
+ export function clipKey(engine, { voice, style, text } = {}) {
116
+ // The voice that will SPEAK this sentence, and the model that will speak it
117
+ // — never the same axis twice, and never an axis the engine does not have.
118
+ const voiceId = engine?.voiceIsFixed ? engine?.model
119
+ : engine?.modelIsDefaultVoice ? (voice ?? engine?.model)
120
+ : voice;
121
+ const modelId = (engine?.voiceIsFixed || engine?.modelIsDefaultVoice) ? undefined : engine?.model;
122
+ return cacheKey({
123
+ engine: engine?.name,
124
+ model: modelId,
125
+ format: extFor(engine?.synth?.mimeType ?? 'audio/wav'),
126
+ voice: voiceId,
127
+ style: engine?.stylable ? style : undefined,
128
+ text,
129
+ });
130
+ }
131
+
132
+ /**
133
+ * A cache bound to a directory.
134
+ *
135
+ * `enabled: false` returns the same shape doing nothing, so a caller never
136
+ * grows an `if` around every read and write — `--no-cache` is one construction
137
+ * argument rather than a condition threaded through two files.
138
+ */
139
+ export function createTtsCache({ dir = cacheHome(), limit = CACHE_LIMIT, enabled = true } = {}) {
140
+ const path = (key, ext) => join(dir, `${key}.${ext}`);
141
+
142
+ /** The clip, or null. A miss and an unreadable file are the same answer. */
143
+ function read(key, ext = 'wav') {
144
+ if (!enabled) return null;
145
+ try {
146
+ const bytes = readFileSync(path(key, ext));
147
+ return bytes.length ? bytes : null;
148
+ } catch { return null; }
149
+ }
150
+
151
+ /** File a clip. Empty audio is never cached: it would poison the key forever. */
152
+ function write(key, bytes, ext = 'wav') {
153
+ if (!enabled || !bytes?.length) return false;
154
+ try {
155
+ mkdirSync(dir, { recursive: true });
156
+ writeFileSync(path(key, ext), bytes);
157
+ return true;
158
+ } catch { return false; }
159
+ }
160
+
161
+ /**
162
+ * Drop the oldest clips until the directory fits.
163
+ *
164
+ * Called once at startup rather than on every write: the bound is on what a
165
+ * machine keeps, not on what a single run may add, and stat-ing the whole
166
+ * directory per sentence would cost more than the synthesis it saves.
167
+ *
168
+ * Oldest-first by mtime also retires stale keys for free. Changing the key
169
+ * formula (adding `model`, say) orphans every clip filed under the old one;
170
+ * those are by definition never touched again, so they age to the front of
171
+ * this queue and leave on their own.
172
+ */
173
+ function prune() {
174
+ if (!enabled) return 0;
175
+ try {
176
+ const entries = readdirSync(dir)
177
+ .filter((f) => CACHE_EXTS.some((e) => f.endsWith(e)))
178
+ .map((f) => ({ f, ...statSync(join(dir, f)) }))
179
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
180
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
181
+ let dropped = 0;
182
+ for (const e of entries) {
183
+ if (total <= limit) break;
184
+ try { unlinkSync(join(dir, e.f)); total -= e.size; dropped++; } catch { break; }
185
+ }
186
+ return dropped;
187
+ } catch { return 0; }
188
+ }
189
+
190
+ return { dir, enabled, read, write, prune };
191
+ }