decklight 0.1.0 → 0.3.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 (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
package/cli/bundle.mjs CHANGED
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
2
5
  /**
3
6
  * decklight bundle — flatten Decklight decks into ONE self-contained HTML file
4
7
  * (send it to anyone; opens from disk, no server, no sibling files).
@@ -15,7 +18,8 @@
15
18
  * inline-theme mode toggles them — picker/?theme= work).
16
19
  * - terminals : data-cast="url" casts are embedded and switched to
17
20
  * data-cast-inline (fetch is blocked on file://).
18
- * - images : <img src> → data: URIs.
21
+ * - images : <img src>, data-background-image and data-background-poster
22
+ * → data: URIs (background VIDEOS stay external, with a notice).
19
23
  *
20
24
  * MERGE mode (--all or several inputs): every module's <section>s are
21
25
  * concatenated into one deck, in order. Each module's first section gets
@@ -26,26 +30,14 @@
26
30
 
27
31
  import fs from 'node:fs';
28
32
  import path from 'node:path';
33
+ import { makeFail, scriptSafe, runMain } from './util.mjs';
34
+ import { inlineRuntime } from './pkg.mjs';
35
+ import { escapeHtml } from '../tools/escape.mjs';
36
+ import { isMain } from '../tools/args.mjs';
37
+ import { injectBeforeBodyEnd } from '../tools/deck-html.mjs';
29
38
 
30
- function fail(msg) {
31
- process.stderr.write(`decklight bundle: ${msg}\n`);
32
- process.exit(1);
33
- }
39
+ const fail = makeFail('bundle');
34
40
 
35
- // Inline <script> content must never contain "</script" (terminates the tag)
36
- // NOR "<!--" (flips the HTML tokenizer into script-data-escaped mode, after
37
- // which closers mis-parse — marked's comment regexes contain it). "\/" is an
38
- // identity escape everywhere. "<!--" is broken by rewriting the bang as a
39
- // backslash-u0021 unicode escape, NOT as backslash-bang: the latter is fine
40
- // in strings and flagless regexes but an INVALID escape inside u-flagged
41
- // regexes — highlight.js composes its XML grammar's comment regex with /imu
42
- // the first time a deck highlights language-html, which turned the old
43
- // escape into a lazy SyntaxError. The unicode escape is valid in strings,
44
- // templates, JSON, and regexes with or without the u flag.
45
- const scriptSafe = (s) => s.replace(/<\/script/gi, '<\\/script').replace(/<!--/g, '<\\u0021--');
46
- const jsonSafe = (s) => s.replace(/<\/script/gi, '<\\/script').replace(/<!--/g, '<\\u0021--');
47
-
48
- const escAttr = (s) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
49
41
 
50
42
  // Unescape a single-quoted JS string body ('·', '’', \' …).
51
43
  function unescapeJs(raw) {
@@ -124,7 +116,7 @@ function mergeDecks(jobs, baseDir, notices) {
124
116
  if (!baseBounds) fail(`no .decklight container in ${jobs[0].path}`);
125
117
 
126
118
  const markSections = (inner, title) =>
127
- inner.replace(/<section\b/, `<section data-module="${escAttr(title)}"`);
119
+ inner.replace(/<section\b/, `<section data-module="${escapeHtml(title)}"`);
128
120
 
129
121
  const castScriptRe = /<script\b[^>]*type=["']application\/json["'][^>]*id=["']([^"']+)["'][^>]*>[\s\S]*?<\/script>/gi;
130
122
 
@@ -159,7 +151,8 @@ function mergeDecks(jobs, baseDir, notices) {
159
151
  // Rebase relative asset urls onto the first deck's directory.
160
152
  if (path.resolve(modDir) !== path.resolve(baseDir)) {
161
153
  const rebase = (rel) => path.relative(baseDir, path.resolve(modDir, rel)).split(path.sep).join('/');
162
- inner = inner.replace(/\b(data-cast|src)=["'](?!#|data:|https?:|\/\/)([^"']+)["']/g,
154
+ inner = inner.replace(
155
+ /\b(data-cast|data-background-image|data-background-video|data-background-poster|src)=["'](?!#|data:|https?:|\/\/)([^"']+)["']/g,
163
156
  (t, attr, rel) => `${attr}="${rebase(rel)}"`);
164
157
  }
165
158
 
@@ -191,13 +184,14 @@ function mergeDecks(jobs, baseDir, notices) {
191
184
 
192
185
  // ---------------------------------------------------------------- arguments
193
186
 
194
- export async function bundleMain(argv = process.argv.slice(2)) {
187
+ /** `client` is the sigstore seam — see publishMain; omitted, the real one is used. */
188
+ export async function bundleMain(argv = process.argv.slice(2), { client } = {}) {
195
189
 
196
190
  if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
197
191
  process.stdout.write(`decklight bundle — flatten deck(s) into one self-contained HTML file
198
192
 
199
193
  Usage:
200
- decklight bundle <deck.html> [-o out.html] [--themes current|all|name,name,…]
194
+ decklight bundle <deck.html> [-o out.html] [--sign] [--deck] [--themes current|all|…]
201
195
  decklight bundle <deck.html> --all [-o out.html] [--title "…"] [--themes …]
202
196
  decklight bundle <a.html> <b.html> … [-o out.html] [--title "…"] [--themes …]
203
197
 
@@ -207,23 +201,44 @@ Options:
207
201
  --all follow the deck's playlist and merge EVERY module into
208
202
  one single-file presentation (in-file module menu via
209
203
  data-module markers)
204
+ --sign sign the output with Sigstore keyless and write a detached
205
+ <out>.sig beside it. There are no keys: signing mints a
206
+ short-lived certificate against an OIDC identity — the
207
+ ambient token in CI, or SIGSTORE_ID_TOKEN — and needs the
208
+ network. Plain bundle neither signs nor warns: offline-clean
209
+ by default, never silently unsigned.
210
+ --deck also write <out>.decklight — the deck, its signature and a
211
+ manifest as ONE file, which is what gets forwarded. Implies
212
+ --sign, because the container is the signed artifact. A
213
+ .decklight renamed to .html still plays in a browser: the
214
+ deck comes first in the file and the metadata is appended.
210
215
  --title <t> <title> for a merged presentation
216
+ --transform <name> run an installed build-time transform (decklight transform
217
+ add <name>) on the deck's own source before anything else
218
+ is inlined — repeatable, applied in the order given
211
219
  --themes <sel> which themes to embed:
212
220
  current just the deck's linked theme (default)
213
221
  all every theme in the deck's themes/ directory
214
222
  name,name,… an explicit list (the deck's linked theme
215
223
  stays active when included, else the first)
216
224
  `);
217
- process.exit(0);
225
+ return 0;
218
226
  }
219
227
 
220
228
  const inputs = [];
221
- let outPath = null, themesSel = 'current', all = false, mergedTitle = null;
229
+ let outPath = null, themesSel = 'current', all = false, mergedTitle = null, sign = false, deckFile = false;
230
+ const transformNames = [];
222
231
  for (let i = 0; i < argv.length; i++) {
223
232
  const a = argv[i];
224
233
  if (a === '-o') outPath = argv[++i];
225
234
  else if (a === '--themes') themesSel = argv[++i];
226
235
  else if (a === '--all') all = true;
236
+ else if (a === '--transform') transformNames.push(argv[++i]);
237
+ else if (a === '--sign') sign = true;
238
+ // --deck implies --sign rather than erroring on the pair: the container IS
239
+ // the signed artifact, so an unsigned one would be a zip wearing the name of
240
+ // an attestation. Naming the implication beats refusing the obvious command.
241
+ else if (a === '--deck') { deckFile = true; sign = true; }
227
242
  else if (a === '--title') mergedTitle = argv[++i];
228
243
  else if (!a.startsWith('-')) inputs.push(a);
229
244
  else fail(`unknown argument: ${a}`);
@@ -260,7 +275,7 @@ if (jobs) {
260
275
  html = mergeDecks(jobs, deckDir, notices);
261
276
  const t = mergedTitle ||
262
277
  (jobs[0].title || '').replace(/^\d+\s*[·.:-]\s*/, '') || 'Presentation';
263
- html = html.replace(/<title>[^<]*<\/title>/i, `<title>${escAttr(t)}</title>`);
278
+ html = html.replace(/<title>[^<]*<\/title>/i, `<title>${escapeHtml(t)}</title>`);
264
279
  outPath = path.resolve(outPath ||
265
280
  path.join(deckDir, path.basename(firstPath, '.html') + '-course.html'));
266
281
  } else {
@@ -275,11 +290,46 @@ const read = (rel) => {
275
290
  return fs.readFileSync(p, 'utf8');
276
291
  };
277
292
 
293
+ // --------------------------------------------------------------- transforms
294
+
295
+ // EXTENSIONS#LOADER. Deliberately BEFORE every other section below: a
296
+ // transform sees the deck's own source, the way the author wrote it, not
297
+ // decklight's runtime/theme/images already spliced in (SPEC
298
+ // EXTENSIONS_TRANSFORMS) — and that puts it ahead of signing for free, since
299
+ // everything in this file runs top to bottom before the sign step near the end.
300
+ if (transformNames.length) {
301
+ const { runTransform, LoaderError } = await import('./loader.mjs');
302
+ for (const name of transformNames) {
303
+ let result;
304
+ try {
305
+ result = await runTransform(name, html);
306
+ } catch (e) {
307
+ if (e instanceof LoaderError) fail(e.message);
308
+ throw e;
309
+ }
310
+ html = result.html;
311
+ notices.push(`transform ${name} applied`
312
+ + (result.checked ? '' : ' (no cached catalog entry — apiVersion not checked)'));
313
+ }
314
+ }
315
+
278
316
  // ---------------------------------------------------------- theme selection
279
317
 
280
318
  const themeLinkRe = /<link\b[^>]*rel=["']stylesheet["'][^>]*href=["']([^"']*themes\/([\w-]+)\.css)["'][^>]*>/i;
281
319
  const themeLinkM = html.match(themeLinkRe);
282
- if (!themeLinkM) fail('no theme <link> (href matching themes/<name>.css) found in the deck');
320
+ if (!themeLinkM) {
321
+ // A deck with its themes already INLINE is the common way to arrive here —
322
+ // `decklight init` scaffolds one, and the README's own quick start goes
323
+ // straight from init to bundle. Blaming a missing <link> sends that reader
324
+ // looking for markup they were never supposed to have, when the honest
325
+ // answer is that there is nothing left to flatten.
326
+ const inlined = /<style\b[^>]*\bdata-theme\b/i.test(html);
327
+ fail(inlined
328
+ ? 'this deck is already self-contained — its themes are inline <style data-theme> blocks.\n'
329
+ + ' bundle is for a deck that REFERENCES dist/ and themes/ by URL; there is nothing here to flatten.\n'
330
+ + ' to refresh its inlined runtime and themes instead: decklight upgrade <deck.html>'
331
+ : 'no theme <link> (href matching themes/<name>.css) found in the deck');
332
+ }
283
333
  const [themeLinkTag, themeHref, linkedTheme] = themeLinkM;
284
334
  const themesDir = path.resolve(deckDir, path.dirname(themeHref));
285
335
 
@@ -319,26 +369,50 @@ html = html.replace(
319
369
 
320
370
  // -------------------------------------------------------------------- images
321
371
 
372
+ const imageDataUri = (rel) => {
373
+ const p = path.resolve(deckDir, rel);
374
+ if (!fs.existsSync(p)) return null;
375
+ const ext = path.extname(p).slice(1).toLowerCase();
376
+ const mime = { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' }[ext] || 'application/octet-stream';
377
+ return `data:${mime};base64,${fs.readFileSync(p).toString('base64')}`;
378
+ };
379
+
322
380
  html = html.replace(
323
381
  /<img\b([^>]*)\bsrc=["']([^"']+)["']/gi,
324
382
  (tag, pre, src) => {
325
383
  if (/^(data:|https?:|\/\/)/.test(src)) return tag;
326
- const p = path.resolve(deckDir, src);
327
- if (!fs.existsSync(p)) { notices.push(`image not found, left as-is: ${src}`); return tag; }
328
- const ext = path.extname(p).slice(1).toLowerCase();
329
- const mime = { svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' }[ext] || 'application/octet-stream';
330
- const b64 = fs.readFileSync(p).toString('base64');
331
- return `<img${pre}src="data:${mime};base64,${b64}"`;
384
+ const uri = imageDataUri(src);
385
+ if (!uri) { notices.push(`image not found, left as-is: ${src}`); return tag; }
386
+ return `<img${pre}src="${uri}"`;
332
387
  });
333
388
 
389
+ // Background media (SPEC DECK_ANATOMY): the image and the poster inline like <img src>.
390
+ // Background VIDEOS stay external — video cannot inline sanely, the same
391
+ // posture as character MP4s — with a notice so the author ships the files.
392
+ html = html.replace(
393
+ /\b(data-background-image|data-background-poster)=["']([^"']+)["']/gi,
394
+ (tag, attr, src) => {
395
+ if (/^(data:|https?:|\/\/)/.test(src)) return tag;
396
+ const uri = imageDataUri(src);
397
+ if (!uri) { notices.push(`background image not found, left as-is: ${src}`); return tag; }
398
+ return `${attr}="${uri}"`;
399
+ });
400
+ {
401
+ const external = [...new Set([...html.matchAll(/\bdata-background-video=["']([^"']+)["']/gi)]
402
+ .map((m) => m[1]).filter((src) => !/^(data:|https?:|\/\/)/.test(src)))];
403
+ if (external.length) {
404
+ notices.push(`background video: ${external.length} file(s) stay external — ship next to the bundle:\n `
405
+ + external.join('\n '));
406
+ }
407
+ }
408
+
334
409
  // ------------------------------------------------------------ runtime script
335
410
 
336
411
  html = html.replace(
337
412
  /<script\b[^>]*src=["']([^"']+)["'][^>]*>\s*<\/script>/gi,
338
413
  (tag, src) => {
339
414
  if (/^(https?:)?\/\//.test(src)) { notices.push(`external script kept as src: ${src}`); return tag; }
340
- const js = read(src).replace(/\/\/# sourceMappingURL=.*$/m, '');
341
- return `<script>\n${scriptSafe(js)}\n</script>`;
415
+ return `<script>\n${inlineRuntime(read(src))}\n</script>`;
342
416
  });
343
417
 
344
418
  // ------------------------------------------------------------------- casts
@@ -351,20 +425,76 @@ html = html.replace(
351
425
  const m = attrs.match(/\bdata-cast=["']([^"']+)["']/);
352
426
  if (!m) return tag; // data-cast-inline (or no cast) passes through
353
427
  const id = `bundled-cast-${++castN}`;
354
- const json = jsonSafe(read(m[1]));
428
+ const json = scriptSafe(read(m[1]));
355
429
  embeds.push(`<script type="application/json" id="${id}">\n${json}\n</script>`);
356
430
  return tag.replace(m[0], `data-cast-inline="#${id}"`);
357
431
  });
358
432
 
433
+ // ---------------------------------------------- narration lip-sync sidecars
434
+
435
+ // slide-NN.visemes.json next to a narration track (tools/lipsync.mjs, or the
436
+ // ⇧V export) inlines as a data-decklight-visemes block — fetch() is blocked
437
+ // on file:// and a bundle should not depend on a sidecar folder. Per-slide
438
+ // MP4s stay external: video cannot inline sanely (a deck's worth is
439
+ // 50–150 MB), same posture as playlist links.
440
+ {
441
+ const seen = new Set();
442
+ const narrDirs = [...new Set(
443
+ [...html.matchAll(/\b(?:dir|files)\s*:\s*['"]([^'"]+)['"]/g)].map((m) => m[1]))];
444
+ for (const d of narrDirs) {
445
+ const abs = path.resolve(deckDir, d);
446
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) continue;
447
+ let mp4s = 0;
448
+ for (const f of fs.readdirSync(abs).sort()) {
449
+ const vm = f.match(/^slide-(\d+)\.visemes\.json$/);
450
+ if (vm) {
451
+ if (seen.has(vm[1])) {
452
+ notices.push(`character visemes: ${d}/${f} skipped — slide ${vm[1]} already inlined from another track`);
453
+ continue;
454
+ }
455
+ seen.add(vm[1]);
456
+ embeds.push(`<script type="application/json" data-decklight-visemes="slide-${vm[1]}">\n`
457
+ + `${scriptSafe(fs.readFileSync(path.join(abs, f), 'utf8'))}\n</script>`);
458
+ } else if (/^slide-\d+\.mp4$/.test(f)) mp4s++;
459
+ }
460
+ if (mp4s) {
461
+ notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ stay external — ship the folder next to the bundle`);
462
+ }
463
+ }
464
+ if (seen.size) notices.push(`character visemes: inlined ${seen.size} slide timeline(s)`);
465
+ }
466
+
467
+ // --------------------------------------------- narration manifest tracks
468
+
469
+ // A `manifest:` track is a fetch, and fetch is dead on file:// — so a bundle
470
+ // that kept only the path would play nothing when opened from disk, which is
471
+ // the one way bundles are most often opened. The manifest is a few KB of JSON
472
+ // naming URLs, so it inlines under its own path, exactly like the viseme
473
+ // sidecars above. The AUDIO stays in the bucket: that is the entire point of
474
+ // the manifest, and inlining it would undo the feature.
475
+ {
476
+ let n = 0;
477
+ const manifests = [...new Set(
478
+ [...html.matchAll(/\bmanifest\s*:\s*['"]([^'"]+)['"]/g)].map((m) => m[1]))];
479
+ for (const rel of manifests) {
480
+ const abs = path.resolve(deckDir, rel);
481
+ if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
482
+ notices.push(`narration manifest: ${rel} not found — the bundle will fetch it at runtime`);
483
+ continue;
484
+ }
485
+ embeds.push(`<script type="application/json" data-decklight-voices="${rel.replace(/"/g, '&quot;')}">\n`
486
+ + `${scriptSafe(fs.readFileSync(abs, 'utf8'))}\n</script>`);
487
+ n++;
488
+ }
489
+ if (n) notices.push(`narration: inlined ${n} voice manifest(s) — the audio stays in its bucket`);
490
+ }
491
+
359
492
  // -------------------------------------------------------------- assemble
360
493
 
361
- // Anchor to the LAST </body>: the inlined runtime contains the speaker-view
362
- // popup template, whose "</body></html>" string would match a first-occurrence
363
- // search and corrupt the JS mid-payload.
364
494
  if (embeds.length) {
365
- const at = html.toLowerCase().lastIndexOf('</body>');
366
- if (at === -1) fail('deck has no </body>');
367
- html = html.slice(0, at) + embeds.join('\n') + '\n' + html.slice(at);
495
+ const injected = injectBeforeBodyEnd(html, embeds.join('\n') + '\n');
496
+ if (injected === null) fail('deck has no </body>');
497
+ html = injected;
368
498
  }
369
499
 
370
500
  if (!jobs) {
@@ -376,13 +506,48 @@ if (!jobs) {
376
506
  }
377
507
  }
378
508
 
509
+ // Signing happens BEFORE the write, and that ordering is the feature
510
+ // (INTEGRITY#SIGNING): a failed signature must leave no artifact behind, or
511
+ // the unsigned file sitting there afterwards gets picked up later and sent as
512
+ // though it were finished. Bytes, not a path, for exactly this reason.
513
+ let bundleSig = null;
514
+ if (sign) {
515
+ const { signBytes } = await import('./sign.mjs');
516
+ // Through fail(), so an unsigned-because-offline bundle reads as a decision
517
+ // the tool explains rather than a stack trace the user has to interpret.
518
+ try { bundleSig = await signBytes(Buffer.from(html, 'utf8'), { client }); } catch (e) { fail(e.message); }
519
+ }
520
+
379
521
  fs.writeFileSync(outPath, html);
380
522
  const kb = (fs.statSync(outPath).size / 1024).toFixed(1);
381
523
  const what = jobs ? `${jobs.length} modules` : path.basename(firstPath);
382
524
  process.stdout.write(`bundled ${what} → ${outPath} (${kb} KB, themes: ${themeNames.join(', ')}; active: ${activeTheme})\n`);
525
+ if (bundleSig) {
526
+ const { writeSidecar, verifyBytes, formatSignature } = await import('./sign.mjs');
527
+ const sidecar = writeSidecar(outPath, bundleSig);
528
+ process.stdout.write(`signed → ${sidecar} (detached — the sidecar is the authority; send both)\n`);
529
+ // Read back what was just written the same way a recipient will. A signature
530
+ // this command cannot verify itself is not one to hand anybody.
531
+ process.stdout.write(`${formatSignature(await verifyBytes(html, bundleSig, { client }), { indent: ' ' })}\n`);
532
+
533
+ // …and the container is that pair as one artifact, because two files is one
534
+ // more than people forward (DECK_FILE).
535
+ if (deckFile) {
536
+ const { packContainer, containerFor, originOf, runtimeVersionOf } = await import('./deckfile.mjs');
537
+ const { bytes } = packContainer({
538
+ payload: html,
539
+ signature: bundleSig,
540
+ name: path.basename(outPath),
541
+ runtime: runtimeVersionOf(html),
542
+ origin: originOf(firstPath),
543
+ });
544
+ const container = containerFor(outPath);
545
+ fs.writeFileSync(container, bytes);
546
+ process.stdout.write(`packed → ${container} (${(bytes.length / 1024).toFixed(1)} KB — `
547
+ + 'the deck, its signature and a manifest in one file; rename it .html and a browser still plays it)\n');
548
+ }
549
+ }
383
550
  for (const n of notices) process.stdout.write(`note: ${n}\n`);
384
551
  }
385
552
 
386
- import { fileURLToPath } from 'node:url';
387
- const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
388
- if (isMain) bundleMain().catch((e) => fail(e.message));
553
+ if (isMain(import.meta.url)) process.exitCode = await runMain('bundle', bundleMain);
@@ -0,0 +1,233 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The `.decklight` container (MARKETPLACE.md DECK_FILE).
6
+ *
7
+ * A signed deck travels as two files — `talk.html` and `talk.html.sig` — and
8
+ * two files is one more than people forward. The container carries the pair as
9
+ * one artifact, and a double-click on it opens `decklight present` rather than
10
+ * a raw browser (DECK_FILE#ASSOC).
11
+ *
12
+ * **The extension is `.decklight`, not `.deck`** — decided after looking: `.deck`
13
+ * belongs to Decker, an active cross-platform HyperCard revival whose files are
14
+ * *also* interactive decks exported as single HTML documents, which is about as
15
+ * adjacent as a collision gets; `.dck` is Forge/XMage Magic decks. Zero-collision
16
+ * verbosity is the feature.
17
+ *
18
+ * ## The layout, and why it is this one
19
+ *
20
+ * [ the bundled deck, verbatim HTML ]\n<!--\n[ ZIP of { <deck>.sig, manifest.json } ]\n-->\n
21
+ *
22
+ * The deck comes FIRST and untouched. That ordering is what makes the last
23
+ * acceptance criterion possible — rename a `.decklight` to `.html` and a
24
+ * browser plays it — because the recipient who cannot be relied upon to have
25
+ * the tooling is the whole reason this wave exists, and a format that met them
26
+ * with a wall would be worse than the plain HTML file it replaced.
27
+ *
28
+ * **The HTML comment around the archive is not decoration.** "A parser stops
29
+ * caring after `</html>`" is a comfortable thing to assume and it is wrong:
30
+ * character tokens in the "after after body" insertion mode are reprocessed
31
+ * into the body, so a naive append puts the raw ZIP bytes on screen as text.
32
+ * (A render harness caught exactly that — `deckfile-render` still asserts no
33
+ * archive byte reaches `document.body.textContent`.) A comment token, by
34
+ * contrast, is inserted into the document and never rendered.
35
+ *
36
+ * It is still a real ZIP. Every offset a ZIP records is measured from the start
37
+ * of the FILE, so writing them with the prefix's length already added produces
38
+ * an archive `unzip` reads happily — a self-extracting archive is built exactly
39
+ * this way. And the closing `-->` lives in the archive's own **comment field**
40
+ * rather than trailing after the end record, so there are no stray bytes for a
41
+ * ZIP tool to complain about. One file, two readers, neither one lied to.
42
+ *
43
+ * The one thing that could break the wrapper is the byte sequence `-->` turning
44
+ * up inside the compressed archive, which would close the comment early. So the
45
+ * pack checks, and pads the manifest until it does not — deflate is
46
+ * deterministic, so this converges immediately and produces the same bytes
47
+ * every time.
48
+ *
49
+ * ## What the manifest is, and is not
50
+ *
51
+ * It sits OUTSIDE the payload so that editing the deck and editing its label are
52
+ * not one action. But metadata is not evidence: the manifest carries the
53
+ * payload's SHA-256, so a tamperer who edits the deck has to fix the digest
54
+ * too — and the *signature*, which they cannot, is what makes that matter. The
55
+ * manifest describes; the sidecar attests. Neither is asked to do the other's
56
+ * job.
57
+ *
58
+ * The other direction has no such guard: nothing stops a repacker from keeping
59
+ * a signed payload and rewriting the manifest around it, because the signature
60
+ * covers the payload alone. So the manifest's provenance fields (origin repo
61
+ * and commit) are recorded for tooling but never printed by `present` — see
62
+ * `formatManifest`.
63
+ */
64
+
65
+ import { readFileSync, existsSync } from 'node:fs';
66
+ import { createHash } from 'node:crypto';
67
+ import { execFileSync } from 'node:child_process';
68
+ import path from 'node:path';
69
+ import { zipSync } from './zip.mjs';
70
+ import { unzip, zipEntries } from '../tools/zip.mjs';
71
+
72
+ export const DECK_EXT = '.decklight';
73
+ export const MANIFEST = 'manifest.json';
74
+
75
+ /** The comment that hides the archive from an HTML parser. Fixed bytes, both
76
+ * ends: the opener is part of the format's structure (the reader subtracts it
77
+ * to find where the deck stops), and the closer rides in the ZIP's own
78
+ * archive-comment field so no byte trails the end record. */
79
+ export const OPEN = '\n<!--\n';
80
+ export const CLOSE = '\n-->\n';
81
+
82
+ /** Is this path a container, by name? (Contents are checked when it is read.) */
83
+ export const isContainer = (file) => path.extname(file).toLowerCase() === DECK_EXT;
84
+
85
+ /** The container `bundle -o out.html --deck` writes: out.decklight. */
86
+ export const containerFor = (file) => file.replace(/\.[^.\\/]+$/, '') + DECK_EXT;
87
+
88
+ const sha256 = (b) => createHash('sha256').update(b).digest('hex');
89
+
90
+ /**
91
+ * Where this deck came from, when the answer is knowable.
92
+ *
93
+ * Read from the deck's own repository, and omitted entirely when there isn't
94
+ * one — a manifest that guessed at provenance would be worse than one that says
95
+ * nothing, because the guess is what someone would end up quoting.
96
+ */
97
+ export function originOf(deckPath) {
98
+ const cwd = path.dirname(path.resolve(deckPath));
99
+ const git = (...args) => {
100
+ try { return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim(); }
101
+ catch { return ''; }
102
+ };
103
+ const repo = git('remote', 'get-url', 'origin');
104
+ const commit = git('rev-parse', 'HEAD');
105
+ const origin = {};
106
+ if (repo) origin.repo = repo;
107
+ if (commit) origin.commit = commit;
108
+ return Object.keys(origin).length ? origin : null;
109
+ }
110
+
111
+ /**
112
+ * Build the container bytes.
113
+ *
114
+ * `payload` is the bundled deck, `signature` its Sigstore bundle. Both are
115
+ * required: a container is the SIGNED artifact, and one without a signature
116
+ * would be a zip file wearing the name of an attestation.
117
+ */
118
+ export function packContainer({ payload, signature, name = 'deck.html', runtime = null, origin = null, extensions = [] }) {
119
+ const body = Buffer.isBuffer(payload) ? payload : Buffer.from(payload, 'utf8');
120
+ if (!signature) throw new Error('a .decklight container is the signed artifact — there is nothing to pack without a signature');
121
+ const manifest = {
122
+ decklight: 1,
123
+ payload: { name, bytes: body.length, sha256: sha256(body) },
124
+ runtime,
125
+ origin,
126
+ extensions,
127
+ signature: `${name}.sig`,
128
+ };
129
+ const open = Buffer.from(OPEN, 'utf8');
130
+
131
+ // Pad until the compressed bytes carry neither comment terminator. The pad
132
+ // is whitespace in the manifest JSON, so it changes nothing a reader parses;
133
+ // deflate is deterministic, so the same input always lands on the same
134
+ // answer and the container stays byte-reproducible.
135
+ for (let pad = 0; pad < 64; pad++) {
136
+ const zip = zipSync([
137
+ { name: `${name}.sig`, data: `${JSON.stringify(signature, null, 2)}\n` },
138
+ { name: MANIFEST, data: `${JSON.stringify(manifest, null, 2)}${' '.repeat(pad)}\n` },
139
+ ], { prefix: body.length + open.length, comment: CLOSE });
140
+ if (!/--!?>/.test(zip.toString('latin1', 0, zip.length - CLOSE.length))) {
141
+ return { bytes: Buffer.concat([body, open, zip]), manifest };
142
+ }
143
+ }
144
+ // Not reachable in practice; a loud failure beats a container that renders
145
+ // half an archive on someone's screen.
146
+ throw new Error('could not pack a container whose archive stays inside an HTML comment');
147
+ }
148
+
149
+ /**
150
+ * Split a container back into its parts.
151
+ *
152
+ * The payload's length comes from the ZIP's own first local-header offset — a
153
+ * structural fact — and not from the manifest, which is the half a tamperer
154
+ * would edit. The manifest's digest is then checked AGAINST that payload, so
155
+ * disagreement is reported rather than resolved in either side's favour.
156
+ *
157
+ * Throws for a file that is not a container at all. Returns
158
+ * `{ payload, signature, manifest, digestOk }` otherwise; `digestOk === false`
159
+ * means the label does not describe the deck it is stapled to, which the caller
160
+ * treats exactly like a signature that does not verify.
161
+ */
162
+ export function readContainer(file) {
163
+ const buf = readFileSync(file);
164
+ let entries;
165
+ try { entries = zipEntries(buf); } catch (e) {
166
+ throw new Error(`${path.basename(file)} is not a .decklight container (${e.message})`);
167
+ }
168
+ if (!entries.length) throw new Error(`${path.basename(file)} carries no container entries`);
169
+ // Where the deck stops is structural — the first local header's offset, less
170
+ // the fixed opener — and not whatever the manifest claims, because the
171
+ // manifest is the half a tamperer edits. The opener is then checked, so a
172
+ // file that merely happens to end in a ZIP is rejected rather than sliced at
173
+ // a boundary this format never wrote.
174
+ const archiveAt = Math.min(...entries.map((e) => e.offset));
175
+ const payloadEnd = archiveAt - OPEN.length;
176
+ if (payloadEnd < 0 || buf.toString('utf8', payloadEnd, archiveAt) !== OPEN) {
177
+ throw new Error(`${path.basename(file)} is not a .decklight container (its archive is not wrapped the way one is)`);
178
+ }
179
+ const payload = buf.subarray(0, payloadEnd);
180
+
181
+ const parts = unzip(buf);
182
+ const manifestRaw = parts.get(MANIFEST);
183
+ if (!manifestRaw) throw new Error(`${path.basename(file)} has no ${MANIFEST} — not a .decklight container`);
184
+ let manifest;
185
+ try { manifest = JSON.parse(manifestRaw.toString('utf8')); } catch (e) {
186
+ throw new Error(`${path.basename(file)}: ${MANIFEST} is not readable JSON (${e.message})`);
187
+ }
188
+
189
+ const sigName = typeof manifest.signature === 'string' ? manifest.signature : null;
190
+ const sigRaw = sigName ? parts.get(sigName) : null;
191
+ let signature = null;
192
+ if (sigRaw) {
193
+ try { signature = JSON.parse(sigRaw.toString('utf8')); } catch { signature = null; }
194
+ }
195
+
196
+ return {
197
+ payload,
198
+ signature,
199
+ manifest,
200
+ // Not "valid": just whether the two halves agree about what is here.
201
+ digestOk: manifest?.payload?.sha256 === sha256(payload),
202
+ };
203
+ }
204
+
205
+ /** One line naming what the container says about itself. Never a verdict. */
206
+ export function formatManifest(manifest, { indent = ' ' } = {}) {
207
+ const bits = [];
208
+ if (manifest?.runtime) bits.push(`runtime ${manifest.runtime}`);
209
+ // The manifest's origin is deliberately NOT printed. The signature covers the
210
+ // payload alone, so on a VERIFIED deck the origin is still whatever the
211
+ // packer wrote: repack an Alice-signed payload with origin.repo naming a repo
212
+ // people trust, and both the signature and the digest still pass. The runtime
213
+ // claim above survives because the ingredients label measures the embedded
214
+ // runtime independently, so a lie there prints next to its own contradiction;
215
+ // a borrowed repo name has nothing beside it but one skim between "says:
216
+ // from <repo>" and "signed by". A claim nobody vouches for gets no line
217
+ // beside one somebody did — the origin stays in the manifest for tooling to
218
+ // read, and earns this line back only if it ever comes inside the signed
219
+ // bytes.
220
+ const ext = manifest?.extensions ?? [];
221
+ bits.push(ext.length ? `declares ${ext.length} extension${ext.length === 1 ? '' : 's'}: ${ext.join(', ')}` : 'declares no extensions');
222
+ // "says" and not "is" — the manifest is the container's own claim about
223
+ // itself, and the signature is the only part of this that anyone checked.
224
+ return `${indent}container — says: ${bits.join(' · ')}`;
225
+ }
226
+
227
+ /** The deck's own runtime version claim, for the manifest. */
228
+ export function runtimeVersionOf(html) {
229
+ return /\/\*!\s*Decklight v(\d+\.\d+\.\d+[^\s*]*)/.exec(html)?.[1] ?? null;
230
+ }
231
+
232
+ /** Does a path exist and look like a container? (For the CLI's error paths.) */
233
+ export const containerExists = (file) => isContainer(file) && existsSync(file);