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.
- package/LICENSE +202 -21
- package/README.md +105 -183
- package/SPEC.md +861 -74
- package/cli/agents.mjs +206 -0
- package/cli/associate.mjs +279 -0
- package/cli/audit.mjs +424 -0
- package/cli/bundle.mjs +210 -45
- package/cli/deckfile.mjs +233 -0
- package/cli/decklight.mjs +216 -5
- package/cli/dev.mjs +455 -0
- package/cli/edit.mjs +733 -63
- package/cli/extension.mjs +108 -0
- package/cli/git.mjs +141 -0
- package/cli/import.mjs +398 -0
- package/cli/init.mjs +465 -121
- package/cli/loader.mjs +263 -0
- package/cli/marketplace.mjs +730 -0
- package/cli/pdf.mjs +156 -0
- package/cli/pkg.mjs +69 -0
- package/cli/plugin.mjs +646 -0
- package/cli/port-conflict.mjs +94 -0
- package/cli/present.mjs +560 -0
- package/cli/publish.mjs +342 -0
- package/cli/qr.mjs +334 -0
- package/cli/rec.mjs +12 -8
- package/cli/remote.mjs +149 -0
- package/cli/report-bug.mjs +97 -0
- package/cli/restore.mjs +174 -0
- package/cli/serve.mjs +247 -0
- package/cli/sign.mjs +216 -0
- package/cli/skill-content.mjs +222 -0
- package/cli/skills.mjs +338 -0
- package/cli/supervise.mjs +57 -0
- package/cli/theme.mjs +201 -0
- package/cli/units.mjs +488 -0
- package/cli/upgrade.mjs +250 -0
- package/cli/util.mjs +90 -0
- package/cli/wizard.mjs +432 -0
- package/cli/zip.mjs +121 -0
- package/dist/decklight.css +949 -72
- package/dist/decklight.js +220 -103
- package/dist/decklight.js.map +4 -4
- package/docs/architecture.svg +1 -1
- package/package.json +9 -6
- package/themes/README.md +6 -4
- package/themes/aurora.css +4 -1
- package/themes/berry.css +4 -1
- package/themes/carbon.css +4 -1
- package/themes/citrus.css +4 -1
- package/themes/coastal.css +4 -1
- package/themes/cosmos.css +4 -1
- package/themes/dune.css +4 -1
- package/themes/eclipse.css +4 -1
- package/themes/ember.css +4 -1
- package/themes/fjord.css +4 -1
- package/themes/gallery.html +3 -11
- package/themes/glacier.css +4 -1
- package/themes/graphite.css +4 -1
- package/themes/harvest.css +4 -1
- package/themes/ibm-modern.css +4 -1
- package/themes/ink.css +4 -1
- package/themes/latte.css +4 -1
- package/themes/linen.css +4 -1
- package/themes/meadow.css +4 -1
- package/themes/metropolis.css +4 -1
- package/themes/midnight.css +4 -1
- package/themes/mint.css +4 -1
- package/themes/moss.css +4 -1
- package/themes/obsidian.css +4 -1
- package/themes/orchid.css +4 -1
- package/themes/packs.json +4 -31
- package/themes/paper.css +4 -1
- package/themes/peony.css +4 -1
- package/themes/porcelain.css +4 -1
- package/themes/reveal-beige.css +4 -1
- package/themes/reveal-black.css +4 -1
- package/themes/reveal-blood.css +4 -1
- package/themes/reveal-dracula.css +4 -1
- package/themes/reveal-league.css +4 -1
- package/themes/reveal-moon.css +4 -1
- package/themes/reveal-night.css +4 -1
- package/themes/reveal-serif.css +4 -1
- package/themes/reveal-simple.css +4 -1
- package/themes/reveal-sky.css +4 -1
- package/themes/reveal-solarized.css +4 -1
- package/themes/reveal-white.css +4 -1
- package/themes/sepia.css +4 -1
- package/themes/seriph.css +4 -1
- package/themes/slate.css +4 -1
- package/themes/storm.css +4 -1
- package/themes/synthwave.css +4 -1
- package/themes/velvet.css +4 -1
- package/themes/yamabuki.css +120 -0
- package/tools/args.mjs +32 -0
- package/tools/bridge.mjs +30 -0
- package/tools/chrome.mjs +52 -0
- package/tools/color.mjs +110 -0
- package/tools/deck-html.mjs +138 -0
- package/tools/elevenlabs-tts.mjs +248 -0
- package/tools/escape.mjs +40 -0
- package/tools/extension-check-runner.mjs +41 -0
- package/tools/extension-check.mjs +266 -0
- package/tools/gemini-tts.mjs +44 -4
- package/tools/lipsync-engines.mjs +81 -0
- package/tools/lipsync-server.mjs +290 -0
- package/tools/lipsync.mjs +181 -0
- package/tools/local-voice.mjs +209 -0
- package/tools/ooxml.mjs +151 -0
- package/tools/pptx.mjs +320 -0
- package/tools/publish-site-voices.mjs +5 -1
- package/tools/publish-targets.mjs +143 -0
- package/tools/publish-voices.mjs +230 -0
- package/tools/shot.mjs +129 -0
- package/tools/theme-check.mjs +139 -0
- package/tools/tts-engines.mjs +455 -0
- package/tools/tts-setup.mjs +257 -0
- package/tools/veo.mjs +204 -0
- package/tools/video.mjs +316 -0
- package/tools/visemes.mjs +26 -0
- package/tools/voiceover-server.mjs +0 -0
- package/tools/voiceover.mjs +73 -39
- package/tools/zip.mjs +143 -0
- package/docs/demo.svg +0 -124
- package/themes/aliens.css +0 -84
- package/themes/apple2.css +0 -126
- package/themes/blade-runner.css +0 -83
- package/themes/c64.css +0 -85
- package/themes/friends.css +0 -82
- package/themes/gameboy.css +0 -118
- package/themes/genesis.css +0 -84
- package/themes/godfather.css +0 -82
- package/themes/ibm-oldschool.css +0 -84
- package/themes/miami-vice.css +0 -84
- package/themes/pulp-fiction.css +0 -84
- package/themes/severance.css +0 -82
- package/themes/snes.css +0 -82
- package/themes/star-wars.css +0 -85
- package/themes/stranger-things.css +0 -84
- package/themes/terminator.css +0 -84
package/tools/video.mjs
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Copyright 2026 Gilles Philippart
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
// decklight video — render a deck to a narrated mp4.
|
|
6
|
+
//
|
|
7
|
+
// decklight video deck.html -o deck.mp4
|
|
8
|
+
// [--narration <dir>] [--size 1280x720] [--fps 30] [--hold 5]
|
|
9
|
+
// [--theme <name>] [--slides a-b] [--voiceover]
|
|
10
|
+
//
|
|
11
|
+
// One still per slide (final build state), each held for the duration of its
|
|
12
|
+
// narration audio plus a short tail, muxed with that audio into one mp4 — a
|
|
13
|
+
// deck with generated narration becomes a watchable, shareable video in one
|
|
14
|
+
// command. Narration resolves --narration <dir> → <deckdir>/voiceover/
|
|
15
|
+
// (the manifest tools/voiceover.mjs writes) → a fully silent deck where every
|
|
16
|
+
// slide holds --hold seconds (per-slide override: data-video-hold="8" on the
|
|
17
|
+
// section). Silent slides still carry a silent audio segment (anullsrc) so the
|
|
18
|
+
// concatenated audio track stays continuous.
|
|
19
|
+
//
|
|
20
|
+
// Capture is the tools/shot.mjs mechanism: one one-shot headless Chrome per
|
|
21
|
+
// frame against the deck served over http://127.0.0.1 at #/n/999 (an oversized
|
|
22
|
+
// step clamps to the last build, so every slide renders fully built). The deck
|
|
23
|
+
// is served under the `present` CSP, NOT opened over file:// with
|
|
24
|
+
// --allow-file-access-from-files (#229): that flag let a deck's own JS read any
|
|
25
|
+
// local file and exfiltrate it, and video renders decks you may not have
|
|
26
|
+
// vetted. No puppeteer, no CDP, no new deps — which is also the honest limit:
|
|
27
|
+
// frames are stills, so the character overlay appears but frozen, and timing is
|
|
28
|
+
// per-slide, not per-build-step (animated lipsync needs a CDP screencast — a
|
|
29
|
+
// Node ≥22 follow-up).
|
|
30
|
+
|
|
31
|
+
import { execFile, execFileSync, spawnSync } from 'node:child_process';
|
|
32
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
33
|
+
import { tmpdir } from 'node:os';
|
|
34
|
+
import { basename, join, relative, resolve, sep } from 'node:path';
|
|
35
|
+
import { promisify } from 'node:util';
|
|
36
|
+
import { fileURLToPath } from 'node:url';
|
|
37
|
+
import { chromeBin, chromeArgs } from './chrome.mjs';
|
|
38
|
+
import { argReader, isMain } from './args.mjs';
|
|
39
|
+
import { sectionBodies } from './deck-html.mjs';
|
|
40
|
+
import { serveForRender } from '../cli/present.mjs';
|
|
41
|
+
|
|
42
|
+
const run = promisify(execFile);
|
|
43
|
+
|
|
44
|
+
/** Every slide breathes before the next one starts talking. */
|
|
45
|
+
export const TAIL_SECONDS = 0.4;
|
|
46
|
+
|
|
47
|
+
const HELP = `decklight video <deck.html> [options] — render the deck to a narrated mp4
|
|
48
|
+
|
|
49
|
+
-o, --out <file> output mp4 (default: <deck>.mp4 next to the deck)
|
|
50
|
+
--narration <dir> narration dir (default: <deckdir>/voiceover if it has a
|
|
51
|
+
manifest.json; otherwise the deck renders silent)
|
|
52
|
+
--size <WxH> frame size (default 1280x720; both must be even)
|
|
53
|
+
--fps <n> video frame rate (default 30)
|
|
54
|
+
--hold <s> seconds a slide without narration holds (default 5;
|
|
55
|
+
per-slide override: data-video-hold="8" on the section)
|
|
56
|
+
--theme <name> render with themes/<name>.css instead of the deck's theme
|
|
57
|
+
--slides <a-b> only this slide range (1-based, inclusive)
|
|
58
|
+
--voiceover run the voiceover batch (tools/voiceover.mjs) first
|
|
59
|
+
|
|
60
|
+
Slides with narration hold for the audio's real duration + ${TAIL_SECONDS}s; slides
|
|
61
|
+
without hold --hold seconds over silence, so the audio track stays continuous.
|
|
62
|
+
Needs ffmpeg + ffprobe on PATH, and a Chrome ($CHROME or an installed one).
|
|
63
|
+
`;
|
|
64
|
+
|
|
65
|
+
/** '1280x720' → { w, h }. Both even — libx264 yuv420p refuses odd dimensions. */
|
|
66
|
+
export function parseSize(s) {
|
|
67
|
+
const m = /^(\d+)x(\d+)$/.exec(s ?? '');
|
|
68
|
+
if (!m) throw new Error(`--size must be WxH, e.g. 1280x720 (got "${s}")`);
|
|
69
|
+
const w = Number(m[1]); const h = Number(m[2]);
|
|
70
|
+
if (w % 2 || h % 2) throw new Error(`--size must be even in both dimensions (yuv420p), got ${w}x${h}`);
|
|
71
|
+
return { w, h };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** '2-5' or '3' → { from, to } (1-based, inclusive), validated against the deck. */
|
|
75
|
+
export function parseSlideRange(s, total) {
|
|
76
|
+
if (!s) return { from: 1, to: total };
|
|
77
|
+
const m = /^(\d+)(?:-(\d+))?$/.exec(s);
|
|
78
|
+
if (!m) throw new Error(`--slides must be a-b or a single slide number (got "${s}")`);
|
|
79
|
+
const from = Number(m[1]); const to = m[2] ? Number(m[2]) : from;
|
|
80
|
+
if (from < 1 || to > total || from > to) {
|
|
81
|
+
throw new Error(`--slides ${s} is outside this deck (${total} slide${total === 1 ? '' : 's'})`);
|
|
82
|
+
}
|
|
83
|
+
return { from, to };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Per-slide hold seconds: data-video-hold="8" on the section, else the default. */
|
|
87
|
+
export function extractHolds(html, defaultHold) {
|
|
88
|
+
return sectionBodies(html).map((sec) => {
|
|
89
|
+
const tag = sec.slice(0, sec.indexOf('>'));
|
|
90
|
+
const m = tag.match(/data-video-hold="([\d.]+)"/);
|
|
91
|
+
return m ? Number(m[1]) : defaultHold;
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* The per-slide schedule: which audio plays under slide n, and for how long.
|
|
97
|
+
*
|
|
98
|
+
* @param {Array|null} manifest manifest.slides from tools/voiceover.mjs
|
|
99
|
+
* ({ file } per slide, null for silent slides) —
|
|
100
|
+
* or null for a fully silent deck
|
|
101
|
+
* @param {object} durations audio file → real (ffprobe) seconds
|
|
102
|
+
* @param {number[]} holds per-slide hold seconds (one per section)
|
|
103
|
+
* @param {{from,to}} [range] 1-based inclusive slide range
|
|
104
|
+
* @returns {Array<{slide, audio, duration}>} audio null ⇒ silent hold
|
|
105
|
+
*/
|
|
106
|
+
export function planTimeline(manifest, durations, holds, range = null) {
|
|
107
|
+
const from = range?.from ?? 1;
|
|
108
|
+
const to = range?.to ?? holds.length;
|
|
109
|
+
const plan = [];
|
|
110
|
+
for (let n = from; n <= to; n++) {
|
|
111
|
+
const file = manifest?.[n - 1]?.file ?? null;
|
|
112
|
+
const dur = file ? durations?.[file] : null;
|
|
113
|
+
plan.push(Number.isFinite(dur)
|
|
114
|
+
? { slide: n, audio: file, duration: Math.round((dur + TAIL_SECONDS) * 1000) / 1000 }
|
|
115
|
+
: { slide: n, audio: null, duration: holds[n - 1] });
|
|
116
|
+
}
|
|
117
|
+
return plan;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* ffmpeg argv for one slide's segment: the still looped at --fps under its
|
|
122
|
+
* audio. Narrated slides pad the audio with the tail and stop there; silent
|
|
123
|
+
* slides synthesize the same stereo/44.1k silence (anullsrc), so every segment
|
|
124
|
+
* carries an audio stream and the concat-demuxer's `-c copy` audio track never
|
|
125
|
+
* goes discontinuous. -t bounds both the infinite loop and the infinite
|
|
126
|
+
* anullsrc (-shortest can't end a segment whose streams are both endless).
|
|
127
|
+
*/
|
|
128
|
+
export function segmentArgs({ frame, audio, duration, fps, out }) {
|
|
129
|
+
return [
|
|
130
|
+
'-y', '-loop', '1', '-framerate', String(fps), '-i', frame,
|
|
131
|
+
...(audio
|
|
132
|
+
? ['-i', audio, '-af', `apad=pad_dur=${TAIL_SECONDS}`]
|
|
133
|
+
: ['-f', 'lavfi', '-i', 'anullsrc=channel_layout=stereo:sample_rate=44100']),
|
|
134
|
+
'-c:v', 'libx264', '-tune', 'stillimage', '-pix_fmt', 'yuv420p',
|
|
135
|
+
'-c:a', 'aac', '-b:a', '128k', '-ar', '44100', '-ac', '2',
|
|
136
|
+
'-t', Number(duration).toFixed(3), '-movflags', '+faststart', out,
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** The concat-demuxer list: one `file '…'` line per segment, quotes escaped. */
|
|
141
|
+
export function concatList(segments) {
|
|
142
|
+
return segments.map((s) => `file '${s.replaceAll("'", "'\\''")}'`).join('\n') + '\n';
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** ffmpeg argv joining the segments into the output without re-encoding. */
|
|
146
|
+
export function concatArgs(listFile, out) {
|
|
147
|
+
return ['-y', '-f', 'concat', '-safe', '0', '-i', listFile, '-c', 'copy',
|
|
148
|
+
'-movflags', '+faststart', out];
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** ffprobe argv for a file's real duration in seconds (prints one number). */
|
|
152
|
+
export function ffprobeArgs(file) {
|
|
153
|
+
return ['-v', 'error', '-show_entries', 'format=duration',
|
|
154
|
+
'-of', 'default=noprint_wrappers=1:nokey=1', file];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Where the narration lives: --narration <dir> (its manifest is then required)
|
|
159
|
+
* → <deckdir>/voiceover/manifest.json → null (a silent deck).
|
|
160
|
+
* @returns {{ dir, slides }|null}
|
|
161
|
+
*/
|
|
162
|
+
export function resolveNarration(deckPath, narrationDir) {
|
|
163
|
+
const load = (dir, required) => {
|
|
164
|
+
const path = join(dir, 'manifest.json');
|
|
165
|
+
if (!existsSync(path)) {
|
|
166
|
+
if (required) {
|
|
167
|
+
throw new Error(`--narration: no manifest.json in ${dir} — `
|
|
168
|
+
+ 'run tools/voiceover.mjs (or decklight video --voiceover) first');
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
const m = JSON.parse(readFileSync(path, 'utf8'));
|
|
173
|
+
if (!Array.isArray(m?.slides)) {
|
|
174
|
+
throw new Error(`${path}: not a voiceover manifest (no slides array) — regenerate it with tools/voiceover.mjs`);
|
|
175
|
+
}
|
|
176
|
+
return { dir, slides: m.slides };
|
|
177
|
+
};
|
|
178
|
+
if (narrationDir) return load(resolve(narrationDir), true);
|
|
179
|
+
return load(join(resolve(deckPath, '..'), 'voiceover'), false);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const have = (bin) => {
|
|
183
|
+
try { execFileSync(bin, ['-version'], { stdio: 'ignore' }); return true; }
|
|
184
|
+
catch (e) { return e?.code !== 'ENOENT'; }
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
export async function videoMain(argv, { exec = run, log = console.log } = {}) {
|
|
188
|
+
const { opt } = argReader(argv);
|
|
189
|
+
const deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
|
|
190
|
+
if (argv.includes('--help') || !deckArg) {
|
|
191
|
+
(deckArg ? process.stdout : process.stderr).write(HELP);
|
|
192
|
+
process.exit(deckArg ? 0 : 1);
|
|
193
|
+
}
|
|
194
|
+
const deck = resolve(deckArg);
|
|
195
|
+
if (!existsSync(deck)) { console.error(`decklight video: no such deck: ${deck}`); process.exit(1); }
|
|
196
|
+
|
|
197
|
+
// The served root is the directory you run from — the deck must sit inside it
|
|
198
|
+
// so its relative assets (`../dist/decklight.js`, `themes/…`) resolve as URLs
|
|
199
|
+
// off the loopback origin the frames are captured against. This is `present`'s
|
|
200
|
+
// rule, for the same reason (#229): the deck runs under the CSP, and a read
|
|
201
|
+
// cannot escape the served tree. `cd` to a directory containing the deck.
|
|
202
|
+
const root = process.cwd();
|
|
203
|
+
if (deck !== root && !deck.startsWith(root + sep)) {
|
|
204
|
+
console.error(`decklight video: the deck must live under the current directory (${root}) — cd there first`);
|
|
205
|
+
process.exit(1);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// the voiceover encoder-detection policy: a missing tool is a hard, friendly
|
|
209
|
+
// error naming what to install — not a stack trace three steps later
|
|
210
|
+
if (!have('ffmpeg') || !have('ffprobe')) {
|
|
211
|
+
console.error('decklight video needs ffmpeg and ffprobe — install ffmpeg '
|
|
212
|
+
+ '(apt install ffmpeg / brew install ffmpeg)');
|
|
213
|
+
process.exit(1);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let out; let plan; let narration;
|
|
217
|
+
try {
|
|
218
|
+
out = resolve(opt('-o', opt('--out', deck.replace(/\.html?$/i, '.mp4'))));
|
|
219
|
+
const { w, h } = parseSize(opt('--size', '1280x720'));
|
|
220
|
+
const fps = Number(opt('--fps', '30'));
|
|
221
|
+
const hold = Number(opt('--hold', '5'));
|
|
222
|
+
if (!Number.isFinite(fps) || fps <= 0) throw new Error(`--fps must be a positive number`);
|
|
223
|
+
if (!Number.isFinite(hold) || hold <= 0) throw new Error(`--hold must be positive seconds`);
|
|
224
|
+
const theme = opt('--theme');
|
|
225
|
+
|
|
226
|
+
const html = readFileSync(deck, 'utf8');
|
|
227
|
+
const holds = extractHolds(html, hold);
|
|
228
|
+
if (!holds.length) throw new Error(`${basename(deck)} has no <section> slides`);
|
|
229
|
+
const range = parseSlideRange(opt('--slides'), holds.length);
|
|
230
|
+
|
|
231
|
+
if (argv.includes('--voiceover')) {
|
|
232
|
+
const vo = [fileURLToPath(new URL('./voiceover.mjs', import.meta.url)), deck];
|
|
233
|
+
const nd = opt('--narration');
|
|
234
|
+
if (nd) vo.push('-o', resolve(nd));
|
|
235
|
+
const r = spawnSync(process.execPath, vo, { stdio: 'inherit' });
|
|
236
|
+
if (r.status !== 0) throw new Error('voiceover batch failed — see its output above');
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
narration = resolveNarration(deck, opt('--narration'));
|
|
240
|
+
|
|
241
|
+
// real durations, not the manifest's word count: ffprobe each audio file
|
|
242
|
+
const durations = {};
|
|
243
|
+
for (let n = range.from; n <= range.to; n++) {
|
|
244
|
+
const file = narration?.slides?.[n - 1]?.file;
|
|
245
|
+
if (!file || durations[file] != null) continue;
|
|
246
|
+
const path = join(narration.dir, file);
|
|
247
|
+
if (!existsSync(path)) {
|
|
248
|
+
console.warn(` slide ${String(n).padStart(2, '0')}: ${file} is in the manifest but not on disk — holding ${holds[n - 1]}s of silence`);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
durations[file] = Number((await exec('ffprobe', ffprobeArgs(path))).stdout.trim());
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
plan = planTimeline(narration?.slides ?? null, durations, holds, range);
|
|
255
|
+
log(`${basename(deck)}: ${plan.length} slide${plan.length === 1 ? '' : 's'}, `
|
|
256
|
+
+ `${plan.filter((p) => p.audio).length} narrated`
|
|
257
|
+
+ (narration ? ` (${narration.dir})` : ' (silent)'));
|
|
258
|
+
|
|
259
|
+
// --theme rides on the deck's response in memory (no temp file): only the
|
|
260
|
+
// deck itself gets the injected link; every other html asset under the root
|
|
261
|
+
// is served untouched. Over the loopback origin `themes/…` resolves exactly
|
|
262
|
+
// as the sibling-copy path used to, so a themed render is unchanged.
|
|
263
|
+
const inject = theme
|
|
264
|
+
? (text, file) => (resolve(file) === deck
|
|
265
|
+
? text.replace(/(<\/head>)/i, `<link rel="stylesheet" href="themes/${theme}.css">$1`)
|
|
266
|
+
: text)
|
|
267
|
+
: null;
|
|
268
|
+
const deckPath = '/' + relative(root, deck).split(sep).join('/');
|
|
269
|
+
|
|
270
|
+
const work = mkdtempSync(join(tmpdir(), 'decklight-video-'));
|
|
271
|
+
const server = await serveForRender(root, { html: inject });
|
|
272
|
+
try {
|
|
273
|
+
const chrome = chromeBin('video');
|
|
274
|
+
const segments = [];
|
|
275
|
+
for (const p of plan) {
|
|
276
|
+
const nn = String(p.slide).padStart(2, '0');
|
|
277
|
+
const frame = join(work, `frame-${nn}.png`);
|
|
278
|
+
// one one-shot Chrome per frame; #/n/999 clamps to the last build step
|
|
279
|
+
await exec(chrome, chromeArgs(
|
|
280
|
+
'--hide-scrollbars',
|
|
281
|
+
'--autoplay-policy=no-user-gesture-required',
|
|
282
|
+
`--window-size=${w},${h}`,
|
|
283
|
+
'--virtual-time-budget=1500',
|
|
284
|
+
`--screenshot=${frame}`,
|
|
285
|
+
`${server.origin}${deckPath}#/${p.slide}/999`,
|
|
286
|
+
));
|
|
287
|
+
if (!existsSync(frame)) throw new Error(`chrome produced no frame for slide ${p.slide}`);
|
|
288
|
+
const seg = join(work, `seg-${nn}.mp4`);
|
|
289
|
+
await exec('ffmpeg', segmentArgs({
|
|
290
|
+
frame, duration: p.duration, fps, out: seg,
|
|
291
|
+
audio: p.audio ? join(narration.dir, p.audio) : null,
|
|
292
|
+
}));
|
|
293
|
+
segments.push(seg);
|
|
294
|
+
log(` slide ${nn}: ${p.duration.toFixed(1)}s ${p.audio ?? '(silence)'}`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const list = join(work, 'concat.txt');
|
|
298
|
+
writeFileSync(list, concatList(segments));
|
|
299
|
+
await exec('ffmpeg', concatArgs(list, out));
|
|
300
|
+
} finally {
|
|
301
|
+
await server.close();
|
|
302
|
+
rmSync(work, { recursive: true, force: true });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const total = Number((await exec('ffprobe', ffprobeArgs(out))).stdout.trim());
|
|
306
|
+
log(`done → ${out} (${total.toFixed(1)}s)`);
|
|
307
|
+
} catch (e) {
|
|
308
|
+
console.error(`decklight video: ${e.message}`);
|
|
309
|
+
process.exit(1);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// direct execution still works: node tools/video.mjs deck.html -o deck.mp4
|
|
314
|
+
if (isMain(import.meta.url)) {
|
|
315
|
+
await videoMain(process.argv.slice(2));
|
|
316
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// Shared viseme-timeline format (v1) — the contract between the lipsync
|
|
2
|
+
// bridge (tools/lipsync-server.mjs), the batch tool (tools/lipsync.mjs) and
|
|
3
|
+
// the player's character overlay:
|
|
4
|
+
//
|
|
5
|
+
// { v: 1, kind: 'visemes', duration: 7.42, source: 'rhubarb',
|
|
6
|
+
// cues: [ { t: 0.00, v: 'X' }, { t: 0.31, v: 'B' }, … ] }
|
|
7
|
+
//
|
|
8
|
+
// Cues carry START times only — each shape holds until the next cue, the
|
|
9
|
+
// last until `duration`. That is lossless versus Rhubarb's contiguous
|
|
10
|
+
// { start, end, value } runs and half the size on disk.
|
|
11
|
+
|
|
12
|
+
const r3 = (x) => Math.round(x * 1000) / 1000;
|
|
13
|
+
|
|
14
|
+
// Rhubarb `-f json` output → timeline v1. Collapses consecutive duplicate
|
|
15
|
+
// shapes (Rhubarb emits them across word boundaries).
|
|
16
|
+
export function normalizeRhubarb(rh) {
|
|
17
|
+
const cues = [];
|
|
18
|
+
let end = 0;
|
|
19
|
+
for (const c of rh?.mouthCues ?? []) {
|
|
20
|
+
const v = String(c.value ?? 'X').toUpperCase();
|
|
21
|
+
end = Math.max(end, c.end ?? 0);
|
|
22
|
+
if (cues.length && cues[cues.length - 1].v === v) continue;
|
|
23
|
+
cues.push({ t: r3(c.start ?? 0), v });
|
|
24
|
+
}
|
|
25
|
+
return { v: 1, kind: 'visemes', duration: r3(rh?.metadata?.duration ?? end), source: 'rhubarb', cues };
|
|
26
|
+
}
|
|
Binary file
|
package/tools/voiceover.mjs
CHANGED
|
@@ -1,23 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// Copyright 2026 Gilles Philippart
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
2
5
|
// Voice-over generator: per-slide narration audio from a deck's speaker notes.
|
|
3
6
|
//
|
|
4
|
-
// node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|gemini]
|
|
7
|
+
// node tools/voiceover.mjs <deck.html> [-o <dir>] [--engine piper|chirp|gemini|elevenlabs]
|
|
5
8
|
// [--voice <name>] [--data-dir <dir>]
|
|
6
|
-
// [--project <id>] [--location global]
|
|
9
|
+
// [--project <id>] [--location global] [--lang en-US]
|
|
7
10
|
// [--tts-model gemini-2.5-pro-tts]
|
|
8
11
|
// [--model qwen3:30b-a3b] [--no-llm] [--reuse-text]
|
|
12
|
+
// [--keep-wav] (keep the lossless intermediates —
|
|
13
|
+
// tools/lipsync.mjs consumes them)
|
|
9
14
|
//
|
|
10
|
-
// Engines (the
|
|
11
|
-
//
|
|
12
|
-
//
|
|
15
|
+
// Engines (tools/tts-engines.mjs — the same three the live bridge speaks with;
|
|
16
|
+
// the built-in macOS voices were dropped: not good enough):
|
|
17
|
+
// piper — neural local TTS, fully offline, unlimited, free. --voice takes a
|
|
18
|
+
// piper model name (default en_US-ryan-high, a natural US male):
|
|
13
19
|
// uv tool install piper-tts
|
|
14
|
-
// python -m piper.download_voices en_US-ryan-high
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
//
|
|
19
|
-
//
|
|
20
|
-
//
|
|
20
|
+
// uvx --from piper-tts python -m piper.download_voices en_US-ryan-high
|
|
21
|
+
// (into --data-dir; a plain `python -m …` only works when piper was
|
|
22
|
+
// pip-installed into the active environment, not `uv tool install`ed)
|
|
23
|
+
// chirp — Chirp 3: HD on the Cloud Text-to-Speech API. Same 30 star-named
|
|
24
|
+
// voices as gemini, ~1s a sentence, and 1M characters a month free.
|
|
25
|
+
// No --style: Chirp has no delivery-instruction channel.
|
|
26
|
+
// gemini — gemini-2.5-{pro,flash}-tts on Vertex AI. The only engine that
|
|
27
|
+
// honors --style (default: warm, welcoming battle-hardened senior
|
|
28
|
+
// engineer). No free tier, and pro is slow.
|
|
29
|
+
// elevenlabs — your ElevenLabs account's own voices, cloned ones included.
|
|
30
|
+
// --voice takes the voice's NAME (or its id); omit it and the first
|
|
31
|
+
// of YOUR voices is used, which is the point of the engine. Needs
|
|
32
|
+
// $ELEVENLABS_API_KEY. No --style. --tts-format mp3 if your plan has
|
|
33
|
+
// no PCM output — but this tool wants WAV (--keep-wav feeds
|
|
34
|
+
// tools/lipsync.mjs), so pcm is the sane choice here.
|
|
35
|
+
// Cloud engines: --project or $GOOGLE_CLOUD_PROJECT, auth via
|
|
36
|
+
// gcloud auth application-default login.
|
|
21
37
|
//
|
|
22
38
|
// Pipeline: extract each slide's notes (HTML asides or markdown Note: blocks,
|
|
23
39
|
// ⟨CLICK⟩ markers removed) → optionally rewrite into flowing narration with a
|
|
@@ -31,15 +47,20 @@ import { createHash } from 'node:crypto';
|
|
|
31
47
|
import { execFileSync } from 'node:child_process';
|
|
32
48
|
import { resolve, join, basename } from 'node:path';
|
|
33
49
|
import { homedir } from 'node:os';
|
|
34
|
-
import {
|
|
50
|
+
import { createEngine } from './tts-engines.mjs';
|
|
51
|
+
import { argReader } from './args.mjs';
|
|
52
|
+
import { sectionBodies, NOTES_ASIDE } from './deck-html.mjs';
|
|
35
53
|
|
|
36
54
|
const args = process.argv.slice(2);
|
|
37
55
|
const deckPath = args.find((a) => !a.startsWith('-'));
|
|
38
|
-
if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--engine piper|gemini] [--voice name] [--no-llm] [--reuse-text]'); process.exit(1); }
|
|
39
|
-
const
|
|
56
|
+
if (!deckPath) { console.error('usage: voiceover.mjs <deck.html> [-o dir] [--engine piper|chirp|gemini|elevenlabs] [--voice name] [--no-llm] [--reuse-text]'); process.exit(1); }
|
|
57
|
+
const { opt } = argReader(args);
|
|
40
58
|
const outDir = resolve(opt('-o', join(resolve(deckPath, '..'), 'voiceover')));
|
|
41
59
|
const engine = opt('--engine', 'piper');
|
|
42
|
-
|
|
60
|
+
// elevenlabs has no default name worth guessing: the roster is the account's,
|
|
61
|
+
// and undefined means "the first of yours", which is what you came for
|
|
62
|
+
const voice = opt('--voice', engine === 'piper' ? 'en_US-ryan-high'
|
|
63
|
+
: engine === 'elevenlabs' ? undefined : 'Alnilam');
|
|
43
64
|
const style = opt('--style',
|
|
44
65
|
'Read in a warm, welcoming tone, like a friendly battle-hardened senior ' +
|
|
45
66
|
'engineer who is still curious about new technology.');
|
|
@@ -48,24 +69,39 @@ const project = opt('--project', process.env.GOOGLE_CLOUD_PROJECT);
|
|
|
48
69
|
const model = opt('--model', 'qwen3:30b-a3b');
|
|
49
70
|
const useLlm = !args.includes('--no-llm');
|
|
50
71
|
const reuseText = args.includes('--reuse-text');
|
|
51
|
-
|
|
52
|
-
|
|
72
|
+
const keepWav = args.includes('--keep-wav');
|
|
73
|
+
|
|
74
|
+
// one factory, three engines — the same ones the live bridge speaks with
|
|
75
|
+
let tts;
|
|
76
|
+
try {
|
|
77
|
+
tts = createEngine({
|
|
78
|
+
engine, project, voice, dataDir,
|
|
79
|
+
model: opt('--tts-model'), location: opt('--location'), lang: opt('--lang'),
|
|
80
|
+
format: opt('--tts-format'),
|
|
81
|
+
});
|
|
82
|
+
} catch (e) {
|
|
83
|
+
console.error(e.message);
|
|
84
|
+
process.exit(1);
|
|
53
85
|
}
|
|
54
|
-
const synthGemini = engine === 'gemini'
|
|
55
|
-
? createSynth({ project, ttsModel: opt('--tts-model'), location: opt('--location') })
|
|
56
|
-
: null;
|
|
57
86
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
87
|
+
// WAV → AAC. ffmpeg everywhere; afconvert is Core Audio, so it only exists on
|
|
88
|
+
// macOS — probing in that order keeps this working off a Mac (as tools/lipsync.mjs
|
|
89
|
+
// already does), and both engines' output goes through here.
|
|
90
|
+
const have = (bin, flags = ['-version']) => {
|
|
91
|
+
try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
|
|
92
|
+
};
|
|
93
|
+
const encoder = have('ffmpeg') ? 'ffmpeg' : have('afconvert') ? 'afconvert' : null;
|
|
94
|
+
if (!encoder) {
|
|
95
|
+
console.error('no AAC encoder — install ffmpeg (apt install ffmpeg / brew install ffmpeg)');
|
|
63
96
|
process.exit(1);
|
|
64
97
|
}
|
|
98
|
+
const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
|
|
99
|
+
? ['-y', '-i', wav, '-c:a', 'aac', '-b:a', '128k', m4a]
|
|
100
|
+
: ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore' });
|
|
65
101
|
|
|
66
102
|
// ── extract per-slide narration text ─────────────────────────────────────────
|
|
67
103
|
const html = readFileSync(deckPath, 'utf8');
|
|
68
|
-
const sections = html
|
|
104
|
+
const sections = sectionBodies(html);
|
|
69
105
|
const clean = (s) => s
|
|
70
106
|
.replace(/⟨CLICK⟩/g, ' ')
|
|
71
107
|
.replace(/<[^>]+>/g, ' ')
|
|
@@ -73,7 +109,7 @@ const clean = (s) => s
|
|
|
73
109
|
.replace(/\s+/g, ' ')
|
|
74
110
|
.trim();
|
|
75
111
|
const slides = sections.map((sec, i) => {
|
|
76
|
-
const aside = sec.match(
|
|
112
|
+
const aside = sec.match(NOTES_ASIDE);
|
|
77
113
|
if (aside) return clean(aside[1]);
|
|
78
114
|
const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
|
|
79
115
|
if (md) return clean(md[1]);
|
|
@@ -132,17 +168,12 @@ for (let i = 0; i < slides.length; i++) {
|
|
|
132
168
|
console.log(` slide ${n}: unchanged — kept`);
|
|
133
169
|
continue;
|
|
134
170
|
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
} else {
|
|
142
|
-
execFileSync('piper', ['-m', voice, '--data-dir', dataDir, '-f', wav], { input: text });
|
|
143
|
-
}
|
|
144
|
-
execFileSync('afconvert', ['-f', 'm4af', '-d', 'aac', wav, m4a]);
|
|
145
|
-
rmSync(wav);
|
|
171
|
+
const { wav: buf, usage } = await tts.synth(text, { voice, style });
|
|
172
|
+
writeFileSync(wav, buf);
|
|
173
|
+
totalCost += usage.cost;
|
|
174
|
+
const costNote = usage.cost ? ` · ~$${usage.cost.toFixed(4)}` : '';
|
|
175
|
+
toAac(wav, m4a);
|
|
176
|
+
if (!keepWav) rmSync(wav);
|
|
146
177
|
console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}${costNote}`);
|
|
147
178
|
// crash-safe: persist progress after every slide so an interrupted run
|
|
148
179
|
// resumes incrementally instead of re-synthesizing everything
|
|
@@ -151,5 +182,8 @@ for (let i = 0; i < slides.length; i++) {
|
|
|
151
182
|
}
|
|
152
183
|
writeFileSync(join(outDir, 'manifest.json'),
|
|
153
184
|
JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
|
|
185
|
+
// piper is held resident (§ createPiper) — without this the tool prints `done`
|
|
186
|
+
// and then hangs on the live child process
|
|
187
|
+
tts.synth.close?.();
|
|
154
188
|
console.log(`done → ${outDir}${skipped ? ` (${skipped} unchanged, skipped)` : ''}`
|
|
155
189
|
+ (totalCost ? ` · estimated cost ~$${totalCost.toFixed(4)}` : ''));
|
package/tools/zip.mjs
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// Copyright 2026 Gilles Philippart
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
// Enough of the ZIP format to read an Office file, and nothing more.
|
|
5
|
+
//
|
|
6
|
+
// A .pptx is a ZIP of XML parts, so importing one means unzipping one — and
|
|
7
|
+
// the repo's rule is that the runtime has zero dependencies while the CLI may
|
|
8
|
+
// have Node-only ones. This could have been a dependency. It is ~90 lines
|
|
9
|
+
// instead, because `node:zlib` already does the only hard part (inflate) and
|
|
10
|
+
// what remains is reading a well-documented directory structure.
|
|
11
|
+
//
|
|
12
|
+
// Deliberately partial: read-only, no ZIP64, no encryption, no multi-disk, no
|
|
13
|
+
// data descriptors trusted over the central directory. Every one of those is
|
|
14
|
+
// absent from files Office and Keynote write, and each is a loud error rather
|
|
15
|
+
// than a wrong answer if it ever shows up.
|
|
16
|
+
//
|
|
17
|
+
// And deliberately bounded: everything this reads is something someone SENT —
|
|
18
|
+
// a `.pptx` on import, a `.decklight` container that `present` must unzip
|
|
19
|
+
// BEFORE it can even find the signature — so a few-KB archive that inflates to
|
|
20
|
+
// gigabytes (a zip bomb) would detonate ahead of every trust decision. Two
|
|
21
|
+
// caps, both far above anything Office or `bundle --deck` writes, and the
|
|
22
|
+
// central directory's declared size is enforced rather than merely read: an
|
|
23
|
+
// entry whose inflated bytes disagree with its declaration is hostile or
|
|
24
|
+
// corrupt, and either way the answer is a loud refusal, not an allocation.
|
|
25
|
+
|
|
26
|
+
import { inflateRawSync } from 'node:zlib';
|
|
27
|
+
|
|
28
|
+
/** The most one entry may inflate to. */
|
|
29
|
+
export const MAX_ENTRY_BYTES = 512 * 1024 * 1024;
|
|
30
|
+
/** The most a whole archive may declare, summed across its entries. */
|
|
31
|
+
export const MAX_TOTAL_BYTES = 1024 * 1024 * 1024;
|
|
32
|
+
|
|
33
|
+
const EOCD_SIG = 0x06054b50;
|
|
34
|
+
const CEN_SIG = 0x02014b50;
|
|
35
|
+
const LOC_SIG = 0x04034b50;
|
|
36
|
+
const STORED = 0;
|
|
37
|
+
const DEFLATED = 8;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The End Of Central Directory record, scanned backwards from the end.
|
|
41
|
+
*
|
|
42
|
+
* It is last in the file but variable in position, because a trailing comment
|
|
43
|
+
* may follow it — so the only way to find it is to look for its signature from
|
|
44
|
+
* the back. The comment is at most 65535 bytes, which bounds the search.
|
|
45
|
+
*/
|
|
46
|
+
function findEocd(buf) {
|
|
47
|
+
const min = Math.max(0, buf.length - 22 - 0xffff);
|
|
48
|
+
for (let i = buf.length - 22; i >= min; i -= 1) {
|
|
49
|
+
if (buf.readUInt32LE(i) === EOCD_SIG) return i;
|
|
50
|
+
}
|
|
51
|
+
return -1;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* List a ZIP's entries from its central directory.
|
|
56
|
+
*
|
|
57
|
+
* The central directory is authoritative: the per-file local headers may carry
|
|
58
|
+
* zeroed sizes (a streaming writer fills them in a trailing data descriptor
|
|
59
|
+
* instead), so sizes and offsets are taken from here and the local header is
|
|
60
|
+
* read only for where its data actually begins.
|
|
61
|
+
*/
|
|
62
|
+
export function zipEntries(buf) {
|
|
63
|
+
const eocd = findEocd(buf);
|
|
64
|
+
if (eocd < 0) throw new Error('not a zip file (no end-of-central-directory record)');
|
|
65
|
+
const count = buf.readUInt16LE(eocd + 10);
|
|
66
|
+
const start = buf.readUInt32LE(eocd + 16);
|
|
67
|
+
if (start === 0xffffffff || count === 0xffff) {
|
|
68
|
+
throw new Error('zip64 archives are not supported');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const entries = [];
|
|
72
|
+
let p = start;
|
|
73
|
+
for (let i = 0; i < count; i += 1) {
|
|
74
|
+
if (buf.readUInt32LE(p) !== CEN_SIG) throw new Error(`corrupt zip: bad central directory entry ${i}`);
|
|
75
|
+
const method = buf.readUInt16LE(p + 10);
|
|
76
|
+
const compressedSize = buf.readUInt32LE(p + 20);
|
|
77
|
+
const size = buf.readUInt32LE(p + 24);
|
|
78
|
+
const nameLen = buf.readUInt16LE(p + 28);
|
|
79
|
+
const extraLen = buf.readUInt16LE(p + 30);
|
|
80
|
+
const commentLen = buf.readUInt16LE(p + 32);
|
|
81
|
+
const offset = buf.readUInt32LE(p + 42);
|
|
82
|
+
// Office writes UTF-8 names; the flag bit that says so is set, and the
|
|
83
|
+
// legacy CP437 alternative has no characters we would read differently.
|
|
84
|
+
const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
|
|
85
|
+
entries.push({ name, method, compressedSize, size, offset });
|
|
86
|
+
p += 46 + nameLen + extraLen + commentLen;
|
|
87
|
+
}
|
|
88
|
+
return entries;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The bytes of one entry, inflated if it needs to be. */
|
|
92
|
+
export function zipRead(buf, entry) {
|
|
93
|
+
if (buf.readUInt32LE(entry.offset) !== LOC_SIG) {
|
|
94
|
+
throw new Error(`corrupt zip: ${entry.name} does not start with a local file header`);
|
|
95
|
+
}
|
|
96
|
+
if (entry.size > MAX_ENTRY_BYTES) {
|
|
97
|
+
throw new Error(`${entry.name}: declares ${entry.size} bytes inflated, past the ${MAX_ENTRY_BYTES}-byte entry cap`);
|
|
98
|
+
}
|
|
99
|
+
const nameLen = buf.readUInt16LE(entry.offset + 26);
|
|
100
|
+
const extraLen = buf.readUInt16LE(entry.offset + 28);
|
|
101
|
+
const start = entry.offset + 30 + nameLen + extraLen;
|
|
102
|
+
const raw = buf.subarray(start, start + entry.compressedSize);
|
|
103
|
+
if (entry.method === STORED) return Buffer.from(raw);
|
|
104
|
+
if (entry.method === DEFLATED) {
|
|
105
|
+
let out;
|
|
106
|
+
// maxOutputLength makes zlib stop AT the declared size instead of
|
|
107
|
+
// allocating whatever the stream expands to — the declaration is the cap.
|
|
108
|
+
// (zlib refuses a cap of 0; a genuinely empty entry still inflates to
|
|
109
|
+
// nothing under a cap of 1, and anything else fails the check below.)
|
|
110
|
+
try {
|
|
111
|
+
out = inflateRawSync(raw, { maxOutputLength: Math.max(entry.size, 1) });
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e.code !== 'ERR_BUFFER_TOO_LARGE') throw e;
|
|
114
|
+
throw new Error(`${entry.name}: inflates past the ${entry.size} bytes its central directory entry declares`);
|
|
115
|
+
}
|
|
116
|
+
if (out.length !== entry.size) {
|
|
117
|
+
throw new Error(`${entry.name}: inflates to ${out.length} bytes, not the ${entry.size} its central directory entry declares`);
|
|
118
|
+
}
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
throw new Error(`${entry.name}: unsupported compression method ${entry.method}`);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The whole archive as a name → Buffer map.
|
|
126
|
+
*
|
|
127
|
+
* An Office file is a few dozen small parts read in an order the code decides,
|
|
128
|
+
* not the archive, so holding them all beats seeking repeatedly. Directory
|
|
129
|
+
* entries (trailing slash, zero length) are dropped — they are not content.
|
|
130
|
+
*/
|
|
131
|
+
export function unzip(buf) {
|
|
132
|
+
const entries = zipEntries(buf).filter((e) => !e.name.endsWith('/'));
|
|
133
|
+
// Summed up front, from the directory alone — an archive that declares more
|
|
134
|
+
// than the cap is refused before a single entry is inflated, and zipRead
|
|
135
|
+
// holds every entry to its declaration, so the sum is a real bound.
|
|
136
|
+
const total = entries.reduce((n, e) => n + e.size, 0);
|
|
137
|
+
if (total > MAX_TOTAL_BYTES) {
|
|
138
|
+
throw new Error(`archive declares ${total} bytes inflated, past the ${MAX_TOTAL_BYTES}-byte cap`);
|
|
139
|
+
}
|
|
140
|
+
const out = new Map();
|
|
141
|
+
for (const entry of entries) out.set(entry.name, zipRead(buf, entry));
|
|
142
|
+
return out;
|
|
143
|
+
}
|