trace-avatar-render 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,1757 @@
1
+ // src/camera.ts
2
+ var ZOOM_KINDS = /* @__PURE__ */ new Set(["click", "dblclick", "type", "key", "hover"]);
3
+ var smooth = (u) => u * u * (3 - 2 * u);
4
+ function cameraKeys(actions, o) {
5
+ const Z = o.zoom ?? 1.6;
6
+ const lead = o.leadMs ?? 400;
7
+ const ease = o.easeMs ?? 400;
8
+ const join4 = o.joinMs ?? 2500;
9
+ const hold = o.holdMs ?? 900;
10
+ const minChange = o.minChangeMs ?? 1500;
11
+ const sorted = actions.slice().sort((a, b) => a.t - b.t);
12
+ const shots = [];
13
+ let cur = [];
14
+ for (const a of sorted) {
15
+ if (!ZOOM_KINDS.has(a.kind)) {
16
+ if (cur.length) shots.push(cur);
17
+ cur = [];
18
+ continue;
19
+ }
20
+ const last = cur[cur.length - 1];
21
+ if (last && a.t - last.t > join4) {
22
+ shots.push(cur);
23
+ cur = [];
24
+ }
25
+ cur.push(a);
26
+ }
27
+ if (cur.length) shots.push(cur);
28
+ const merged = [];
29
+ for (const s of shots) {
30
+ const prev = merged[merged.length - 1];
31
+ if (prev) {
32
+ const outAt = prev[prev.length - 1].t + hold;
33
+ const inAt = s[0].t - lead - ease;
34
+ const scrollBetween = sorted.some((a) => !ZOOM_KINDS.has(a.kind) && a.t > prev[prev.length - 1].t && a.t < s[0].t);
35
+ if (!scrollBetween && inAt - (outAt + ease) < minChange) {
36
+ prev.push(...s);
37
+ continue;
38
+ }
39
+ }
40
+ merged.push(s.slice());
41
+ }
42
+ const keys = [];
43
+ for (const s of merged) {
44
+ const first = s[0];
45
+ const inEnd = Math.max(first.t - lead, (keys[keys.length - 1]?.t ?? -Infinity) + ease);
46
+ keys.push({ t: inEnd - ease, z: 1, x: first.x, y: first.y }, { t: inEnd, z: Z, x: first.x, y: first.y });
47
+ for (let k = 1; k < s.length; k += 1) {
48
+ const a = s[k];
49
+ const prev = keys[keys.length - 1];
50
+ const arrive = Math.max(a.t - lead, prev.t + ease);
51
+ keys.push({ t: arrive - ease, z: Z, x: prev.x, y: prev.y }, { t: arrive, z: Z, x: a.x, y: a.y });
52
+ }
53
+ const last = keys[keys.length - 1];
54
+ const out = Math.max(s[s.length - 1].t + hold, last.t);
55
+ keys.push({ t: out, z: Z, x: last.x, y: last.y }, { t: out + ease, z: 1, x: last.x, y: last.y });
56
+ }
57
+ return keys;
58
+ }
59
+ function cameraPath(actions, o) {
60
+ const keys = cameraKeys(actions, o);
61
+ const full = { x: 0, y: 0, w: o.width, h: o.height };
62
+ const rectOf = (z, x, y) => {
63
+ if (z <= 1.0001) return full;
64
+ const w = o.width / z;
65
+ const h = o.height / z;
66
+ return { x: Math.min(Math.max(0, x - w / 2), o.width - w), y: Math.min(Math.max(0, y - h / 2), o.height - h), w, h };
67
+ };
68
+ return (t) => {
69
+ if (!keys.length || t <= keys[0].t || t >= keys[keys.length - 1].t) return full;
70
+ let k = 0;
71
+ while (k < keys.length - 2 && keys[k + 1].t <= t) k += 1;
72
+ const a = keys[k];
73
+ const b = keys[k + 1];
74
+ const u = b.t > a.t ? smooth(Math.min(1, Math.max(0, (t - a.t) / (b.t - a.t)))) : 1;
75
+ const za = 1 / a.z;
76
+ const zb = 1 / b.z;
77
+ const z = 1 / (za + (zb - za) * u);
78
+ return rectOf(z, a.x + (b.x - a.x) * u, a.y + (b.y - a.y) * u);
79
+ };
80
+ }
81
+
82
+ // src/capture.ts
83
+ import { readFileSync } from "fs";
84
+ import { chromium } from "playwright";
85
+ var RenderError = class extends Error {
86
+ constructor(message, screenshot) {
87
+ super(message);
88
+ this.screenshot = screenshot;
89
+ this.name = "RenderError";
90
+ }
91
+ screenshot;
92
+ /** A stall: which step, why, and what onStall found on the page. */
93
+ stall;
94
+ };
95
+ function bootstrap(cfg) {
96
+ if (window.top !== window || location.protocol === "about:") return;
97
+ const w = window;
98
+ const send = (e) => {
99
+ try {
100
+ w.__taEvent({ ...e, t: Date.now(), url: location.pathname, title: document.title });
101
+ } catch {
102
+ }
103
+ };
104
+ let c = null;
105
+ let started = false;
106
+ w.__taPlay = () => {
107
+ started = true;
108
+ send({ type: "play" });
109
+ c?.play();
110
+ };
111
+ addEventListener("pagehide", () => send({ type: "unload" }));
112
+ const go = () => {
113
+ const style = document.createElement("style");
114
+ style.setAttribute("data-trace-render", "");
115
+ style.textContent = (cfg.hide.length ? `${cfg.hide.join(",")}{visibility:hidden!important}
116
+ ` : "") + `${["[data-trace-blur]", ...cfg.blur].join(",")}{filter:blur(8px)!important}`;
117
+ (document.head || document.documentElement).append(style);
118
+ c = w.__taPlayer.createTrace({ trace: cfg.trace, mode: cfg.mode, autoplay: false, controls: false, resumeKey: cfg.key, ...cfg.rate ? { rate: cfg.rate } : {}, ...cfg.captions ? { captions: cfg.captions } : {} });
119
+ w.__taRender = c;
120
+ c.on("state", ({ phase }) => {
121
+ send({ type: "state", phase });
122
+ if (phase === "paused" && started) setTimeout(() => {
123
+ if (c.state === "paused") c.play();
124
+ }, cfg.pauseHoldMs);
125
+ });
126
+ c.on("step", (e) => {
127
+ const r = e.element?.getBoundingClientRect?.();
128
+ send({
129
+ type: "step",
130
+ index: e.index,
131
+ stepType: e.step.type,
132
+ ...r && r.width + r.height > 0 ? { rect: { x: r.x, y: r.y, w: r.width, h: r.height } } : {},
133
+ ...typeof e.step.say === "string" && e.step.say.trim() ? { say: e.step.say } : {}
134
+ });
135
+ });
136
+ c.on("stalled", (e) => {
137
+ window.__taSeen = e.seen ?? [];
138
+ send({ type: "stalled", index: e.index, reason: e.reason });
139
+ });
140
+ c.on("page", (e) => send({ type: "page", index: e.index }));
141
+ c.on("blocked", (e) => send({ type: "blocked", message: e.say }));
142
+ c.on("handoff", (e) => {
143
+ send({ type: "handoff", index: e.index });
144
+ const el = e.element;
145
+ if (el && "value" in el) {
146
+ el.focus();
147
+ el.value = e.step.text ?? "";
148
+ el.dispatchEvent(new Event("input", { bubbles: true }));
149
+ el.dispatchEvent(new Event("change", { bubbles: true }));
150
+ }
151
+ });
152
+ c.on("end", () => send({ type: "end" }));
153
+ c.on("error", (e) => send({ type: "error", message: e.message }));
154
+ c.ready.then(() => {
155
+ send({ type: "ready", phase: c.state });
156
+ if (c.state === "paused") {
157
+ started = true;
158
+ c.play();
159
+ }
160
+ }, (e) => send({ type: "error", message: String(e?.message ?? e) }));
161
+ };
162
+ if (document.readyState === "loading") addEventListener("DOMContentLoaded", go, { once: true });
163
+ else go();
164
+ }
165
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
166
+ async function capture(o) {
167
+ const timeout = o.timeoutMs ?? 12e4;
168
+ const cfg = {
169
+ trace: o.trace,
170
+ mode: o.mode,
171
+ key: "trace-avatar-render",
172
+ hide: o.hide ?? [],
173
+ blur: o.blur ?? [],
174
+ ...o.rate ? { rate: o.rate } : {},
175
+ pauseHoldMs: o.pauseHoldMs ?? 1200,
176
+ ...o.captions ? { captions: o.captions } : {}
177
+ };
178
+ const content = `${readFileSync(o.playerFile, "utf8")}
179
+ ;window.__taPlayer = TraceAvatar;
180
+ (${bootstrap.toString()})(${JSON.stringify(cfg)});`;
181
+ const browser = await chromium.launch({ headless: o.headless !== false });
182
+ try {
183
+ const context = await browser.newContext({
184
+ viewport: { width: o.viewport.w, height: o.viewport.h },
185
+ deviceScaleFactor: o.scale ?? 1,
186
+ ...o.storageState ? { storageState: o.storageState } : {}
187
+ });
188
+ const events = [];
189
+ let wake = () => {
190
+ };
191
+ await context.exposeBinding("__taEvent", (_src, e) => {
192
+ events.push(e);
193
+ wake();
194
+ });
195
+ await context.addInitScript({ content });
196
+ const page = await context.newPage();
197
+ const cdp = await context.newCDPSession(page);
198
+ const frames = [];
199
+ let capturing = false;
200
+ cdp.on("Page.screencastFrame", (f) => {
201
+ frames.push({ t: (f.metadata.timestamp ?? Date.now() / 1e3) * 1e3, png: Buffer.from(f.data, "base64") });
202
+ cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => {
203
+ });
204
+ });
205
+ const startCast = () => cdp.send("Page.startScreencast", { format: "png", everyNthFrame: 1 }).catch(() => {
206
+ });
207
+ page.on("load", () => {
208
+ if (capturing) void startCast();
209
+ });
210
+ page.on("request", (r) => {
211
+ if (capturing && r.isNavigationRequest() && r.frame() === page.mainFrame()) {
212
+ events.push({ t: Date.now(), type: "unload", url: new URL(r.url()).pathname });
213
+ wake();
214
+ }
215
+ });
216
+ const until = async (test, what, ms = timeout) => {
217
+ const deadline = Date.now() + ms;
218
+ for (; ; ) {
219
+ const v = test();
220
+ if (v) return v;
221
+ const left = deadline - Date.now();
222
+ if (left <= 0) throw new RenderError(`timed out after ${ms} ms waiting for ${what}`, await page.screenshot().catch(() => void 0));
223
+ await new Promise((r) => {
224
+ wake = r;
225
+ setTimeout(r, Math.min(left, 250));
226
+ });
227
+ }
228
+ };
229
+ const failure = () => events.find((e) => e.type === "error" || e.type === "blocked");
230
+ const opened = Date.now();
231
+ await page.goto(o.url, { waitUntil: "load", timeout });
232
+ const first = await until(() => events.find((e) => e.type === "ready" && e.t >= opened) ?? failure(), "the player");
233
+ if (first.type !== "ready") throw new RenderError(`the guide could not start: ${first.message ?? first.type}`);
234
+ capturing = true;
235
+ await startCast();
236
+ await sleep(o.leadMs ?? 500);
237
+ const playAt = Date.now();
238
+ await page.evaluate(() => window.__taPlay());
239
+ const done = await until(() => events.find((e) => e.type === "end" || e.type === "stalled") ?? failure(), "the guide to end");
240
+ if (done.type === "error" || done.type === "blocked") throw new RenderError(`the guide stopped: ${done.message ?? done.type}`, await page.screenshot().catch(() => void 0));
241
+ if (done.type === "stalled") {
242
+ const why = `step ${(done.index ?? 0) + 1} stalled (${done.reason}) on ${done.url ?? "the page"}`;
243
+ const stall = { index: done.index ?? 0, reason: done.reason ?? "not-found" };
244
+ const data = o.onStall ? await o.onStall(page, stall) : void 0;
245
+ if (!o.allowStall) {
246
+ const err = new RenderError(`${why}: the app no longer matches the guide. Pass allowStall (--allow-stall) to render it anyway.`, await page.screenshot().catch(() => void 0));
247
+ err.stall = { ...stall, ...data !== void 0 ? { data } : {} };
248
+ throw err;
249
+ }
250
+ await sleep(3e3);
251
+ } else await sleep(o.holdEndMs ?? 1500);
252
+ const stopAt = Date.now();
253
+ capturing = false;
254
+ await cdp.send("Page.stopScreencast").catch(() => {
255
+ });
256
+ if (!frames.length) throw new RenderError("no frames were captured");
257
+ const titles = {};
258
+ for (const e of events) if (e.url && e.title && !titles[e.url]) titles[e.url] = e.title;
259
+ for (const e of events) delete e.title;
260
+ return { frames, events, playAt, stopAt, endAt: done.type === "end" ? done.t : null, viewport: { ...o.viewport, scale: o.scale ?? 1 }, titles };
261
+ } finally {
262
+ await browser.close();
263
+ }
264
+ }
265
+ async function findPlayer(explicit, env = process.env) {
266
+ if (explicit) return explicit;
267
+ if (env.TRACE_AVATAR_PLAYER) return env.TRACE_AVATAR_PLAYER;
268
+ const { createRequire } = await import("module");
269
+ const { dirname: dirname3, join: join4 } = await import("path");
270
+ const req = createRequire(import.meta.url);
271
+ return join4(dirname3(req.resolve("trace-avatar/package.json")), "dist", "trace-perform.min.js");
272
+ }
273
+
274
+ // src/compose.ts
275
+ function drawRegion(dst, to, src, from) {
276
+ const W = Math.round(to.w);
277
+ const H = Math.round(to.h);
278
+ const X0 = Math.round(to.x);
279
+ const Y0 = Math.round(to.y);
280
+ const sx = from.w / W;
281
+ const sy = from.h / H;
282
+ const s = src.data;
283
+ const d = dst.data;
284
+ const maxX = src.width - 1;
285
+ const maxY = src.height - 1;
286
+ for (let Y = 0; Y < H; Y += 1) {
287
+ const dy = Y0 + Y;
288
+ if (dy < 0 || dy >= dst.height) continue;
289
+ for (let X = 0; X < W; X += 1) {
290
+ const dx = X0 + X;
291
+ if (dx < 0 || dx >= dst.width) continue;
292
+ let r = 0;
293
+ let g = 0;
294
+ let b = 0;
295
+ if (sx > 1 || sy > 1) {
296
+ const x0 = from.x + X * sx;
297
+ const x1 = x0 + sx;
298
+ const y0 = from.y + Y * sy;
299
+ const y1 = y0 + sy;
300
+ let wsum = 0;
301
+ for (let y = Math.floor(y0); y < Math.min(src.height, Math.ceil(y1)); y += 1) {
302
+ const wy = Math.min(y + 1, y1) - Math.max(y, y0);
303
+ for (let x = Math.floor(x0); x < Math.min(src.width, Math.ceil(x1)); x += 1) {
304
+ const wt = wy * (Math.min(x + 1, x1) - Math.max(x, x0));
305
+ const i = (y * src.width + x) * 4;
306
+ r += s[i] * wt;
307
+ g += s[i + 1] * wt;
308
+ b += s[i + 2] * wt;
309
+ wsum += wt;
310
+ }
311
+ }
312
+ r /= wsum;
313
+ g /= wsum;
314
+ b /= wsum;
315
+ } else {
316
+ const fx = Math.min(maxX, Math.max(0, from.x + (X + 0.5) * sx - 0.5));
317
+ const fy = Math.min(maxY, Math.max(0, from.y + (Y + 0.5) * sy - 0.5));
318
+ const x0 = Math.floor(fx);
319
+ const y0 = Math.floor(fy);
320
+ const x1 = Math.min(maxX, x0 + 1);
321
+ const y1 = Math.min(maxY, y0 + 1);
322
+ const ax = fx - x0;
323
+ const ay = fy - y0;
324
+ const i00 = (y0 * src.width + x0) * 4;
325
+ const i10 = (y0 * src.width + x1) * 4;
326
+ const i01 = (y1 * src.width + x0) * 4;
327
+ const i11 = (y1 * src.width + x1) * 4;
328
+ for (let c = 0; c < 3; c += 1) {
329
+ const v = (s[i00 + c] * (1 - ax) + s[i10 + c] * ax) * (1 - ay) + (s[i01 + c] * (1 - ax) + s[i11 + c] * ax) * ay;
330
+ if (c === 0) r = v;
331
+ else if (c === 1) g = v;
332
+ else b = v;
333
+ }
334
+ }
335
+ const o = (dy * dst.width + dx) * 4;
336
+ d[o] = Math.round(r);
337
+ d[o + 1] = Math.round(g);
338
+ d[o + 2] = Math.round(b);
339
+ d[o + 3] = 255;
340
+ }
341
+ }
342
+ }
343
+ function overlay(dst, img, x, y, alpha = 1) {
344
+ if (alpha <= 0) return;
345
+ const X0 = Math.round(x);
346
+ const Y0 = Math.round(y);
347
+ for (let Y = 0; Y < img.height; Y += 1) {
348
+ const dy = Y0 + Y;
349
+ if (dy < 0 || dy >= dst.height) continue;
350
+ for (let X = 0; X < img.width; X += 1) {
351
+ const dx = X0 + X;
352
+ if (dx < 0 || dx >= dst.width) continue;
353
+ const i = (Y * img.width + X) * 4;
354
+ const a = img.data[i + 3] / 255 * alpha;
355
+ if (a <= 0) continue;
356
+ const o = (dy * dst.width + dx) * 4;
357
+ for (let c = 0; c < 3; c += 1) dst.data[o + c] = Math.round(dst.data[o + c] * (1 - a) + img.data[i + c] * a);
358
+ dst.data[o + 3] = 255;
359
+ }
360
+ }
361
+ }
362
+ function crossfade(a, b, u) {
363
+ const out = new Uint8Array(a.data.length);
364
+ for (let i = 0; i < out.length; i += 1) out[i] = Math.round(a.data[i] * (1 - u) + b.data[i] * u);
365
+ return { width: a.width, height: a.height, data: out };
366
+ }
367
+ var blank = (width, height, rgb = [255, 255, 255]) => {
368
+ const data = new Uint8Array(width * height * 4);
369
+ for (let i = 0; i < width * height; i += 1) data.set([rgb[0], rgb[1], rgb[2], 255], i * 4);
370
+ return { width, height, data };
371
+ };
372
+ var copy = (img) => ({ width: img.width, height: img.height, data: img.data.slice() });
373
+
374
+ // src/gif.ts
375
+ import * as gifencNs from "gifenc";
376
+ var lib = gifencNs.quantize ? gifencNs : gifencNs.default;
377
+ var { GIFEncoder, quantize: quantize2, applyPalette } = lib;
378
+ var CLEAR = 255;
379
+ function paletteOf(frames, samples = 12) {
380
+ const pick = Math.min(samples, frames.length);
381
+ const chosen = Array.from({ length: pick }, (_, k) => frames[Math.floor(k * frames.length / pick)]);
382
+ const per = chosen.map((f) => Math.ceil(f.width * f.height / 3));
383
+ const all = new Uint8Array(per.reduce((a, b) => a + b, 0) * 4);
384
+ let o = 0;
385
+ for (const f of chosen) {
386
+ for (let p = 0; p < f.width * f.height; p += 3) {
387
+ all[o] = f.data[p * 4];
388
+ all[o + 1] = f.data[p * 4 + 1];
389
+ all[o + 2] = f.data[p * 4 + 2];
390
+ all[o + 3] = 255;
391
+ o += 4;
392
+ }
393
+ }
394
+ return quantize2(all.subarray(0, o), CLEAR);
395
+ }
396
+ function encodeGif(frames, o) {
397
+ if (!frames.length) throw new Error("no frames to encode");
398
+ const w = createGifWriter({ width: frames[0].width, height: frames[0].height, fps: o.fps, repeat: o.repeat, palette: paletteOf(frames, o.paletteSamples) });
399
+ for (const f of frames) w.add(f);
400
+ return w.finish();
401
+ }
402
+ function createGifWriter(o) {
403
+ const { width, height, palette } = o;
404
+ const step = 1e3 / o.fps;
405
+ const full = [...palette, ...Array.from({ length: CLEAR + 1 - palette.length }, () => [0, 0, 0])];
406
+ const gif = GIFEncoder();
407
+ let prev = null;
408
+ let pending = null;
409
+ let shown = 0;
410
+ let count = 0;
411
+ const flush = () => {
412
+ if (!pending) return;
413
+ const { index, ms } = pending;
414
+ const delay = Math.max(20, Math.round((shown + ms) / 10) * 10 - Math.round(shown / 10) * 10);
415
+ shown += ms;
416
+ if (!prev) {
417
+ gif.writeFrame(index, width, height, { palette: full, delay, repeat: o.repeat ?? 0 });
418
+ } else {
419
+ const diff = new Uint8Array(index.length);
420
+ for (let i = 0; i < index.length; i += 1) diff[i] = index[i] === prev[i] ? CLEAR : index[i];
421
+ gif.writeFrame(diff, width, height, { delay, transparent: true, transparentIndex: CLEAR, dispose: 1 });
422
+ }
423
+ prev = index;
424
+ count += 1;
425
+ pending = null;
426
+ };
427
+ return {
428
+ add(f) {
429
+ if (f.width !== width || f.height !== height) throw new Error("every frame must be the same size");
430
+ const index = applyPalette(f.data, palette);
431
+ if (pending && same(pending.index, index)) {
432
+ pending.ms += step;
433
+ return;
434
+ }
435
+ flush();
436
+ pending = { index, ms: step };
437
+ },
438
+ finish() {
439
+ flush();
440
+ if (!count) throw new Error("no frames to encode");
441
+ gif.finish();
442
+ return { bytes: gif.bytes(), frames: count, durationMs: Math.round(shown) };
443
+ }
444
+ };
445
+ }
446
+ function same(a, b) {
447
+ if (a.length !== b.length) return false;
448
+ for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
449
+ return true;
450
+ }
451
+
452
+ // src/layers.ts
453
+ import { PNG } from "pngjs";
454
+ var DEFAULT_BACKGROUND = "linear-gradient(135deg, #dfe7fb 0%, #eef0f6 50%, #f6e9f1 100%)";
455
+ var esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
456
+ var FONT = "system-ui,-apple-system,'Segoe UI',Roboto,sans-serif";
457
+ var decode = (buf) => {
458
+ const p = PNG.sync.read(buf);
459
+ return { width: p.width, height: p.height, data: new Uint8Array(p.data.buffer, p.data.byteOffset, p.data.length) };
460
+ };
461
+ async function createLayers(browser) {
462
+ const ctx = await browser.newContext({ deviceScaleFactor: 1 });
463
+ const page = await ctx.newPage();
464
+ const shoot = async (w, h, html, transparent = false, sel) => {
465
+ await page.setViewportSize({ width: Math.max(1, Math.round(w)), height: Math.max(1, Math.round(h)) });
466
+ await page.setContent(`<!doctype html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;${transparent ? "background:transparent" : ""}}</style></head><body>${html}</body></html>`);
467
+ await page.evaluate(() => document.fonts.ready);
468
+ const buf = sel ? await page.locator(sel).screenshot({ omitBackground: transparent }) : await page.screenshot({ omitBackground: transparent, clip: { x: 0, y: 0, width: Math.round(w), height: Math.round(h) } });
469
+ return decode(buf);
470
+ };
471
+ return {
472
+ async base(l, o) {
473
+ const win = l.window;
474
+ const bar = l.bar;
475
+ const r = Math.round(l.width * 0.012);
476
+ const dot = bar ? Math.round(bar.h * 0.36) : 0;
477
+ const chrome = bar ? `
478
+ <div style="position:absolute;left:${win.x}px;top:${win.y}px;width:${win.w}px;height:${win.h}px;border-radius:${r}px;background:#fff;box-shadow:0 ${Math.round(r * 1.5)}px ${r * 5}px rgb(15 23 42/.22),0 0 0 1px rgb(15 23 42/.08)"></div>
479
+ <div style="position:absolute;left:${bar.x}px;top:${bar.y}px;width:${bar.w}px;height:${bar.h}px;border-radius:${r}px ${r}px 0 0;background:#eef0f4;border-bottom:1px solid #d9dde5;box-sizing:border-box;display:flex;align-items:center;gap:${Math.round(dot * 0.6)}px;padding:0 ${Math.round(dot * 1.2)}px;font:${Math.round(bar.h * 0.42)}px/1 ${FONT};color:#475569">
480
+ <span style="width:${dot}px;height:${dot}px;border-radius:50%;background:#ff5f57;flex:none"></span>
481
+ <span style="width:${dot}px;height:${dot}px;border-radius:50%;background:#febc2e;flex:none"></span>
482
+ <span style="width:${dot}px;height:${dot}px;border-radius:50%;background:#28c840;flex:none"></span>
483
+ <span style="flex:1;display:flex;justify-content:center;min-width:0"><span style="background:#fff;border-radius:${Math.round(bar.h * 0.3)}px;padding:${Math.round(bar.h * 0.12)}px ${Math.round(bar.h * 0.6)}px;max-width:70%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(o.path ?? "/")}</span></span>
484
+ <span style="flex:none;max-width:22%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600">${esc(o.title ?? "")}</span>
485
+ </div>` : "";
486
+ return shoot(l.width, l.height, `<div style="position:relative;width:100%;height:100%;background:${o.background}">${chrome}</div>`);
487
+ },
488
+ async caption(text, o) {
489
+ const pad = Math.round(o.fontPx * 0.6);
490
+ return shoot(o.maxWidth, o.fontPx * 8, `<div style="display:flex;justify-content:center"><div id="c" style="max-width:${o.maxWidth - 2}px;box-sizing:border-box;padding:${pad}px ${Math.round(pad * 1.5)}px;border-radius:${pad}px;background:rgb(17 24 39/.88);color:#f9fafb;font:500 ${o.fontPx}px/1.35 ${FONT};text-align:center">${esc(text)}</div></div>`, true, "#c");
491
+ },
492
+ async card(l, o) {
493
+ const s = Math.round(l.width * 0.045);
494
+ const initial = esc((o.sub ?? o.title).trim().charAt(0).toUpperCase() || "\u2022");
495
+ return shoot(l.width, l.height, `<div style="width:100%;height:100%;background:${o.background};display:flex;align-items:center;justify-content:center;font-family:${FONT}">
496
+ <div style="max-width:76%;box-sizing:border-box;padding:${Math.round(s * 0.8)}px ${Math.round(s * 1.2)}px;border-radius:${Math.round(s * 0.5)}px;background:#fff;box-shadow:0 ${Math.round(s * 0.3)}px ${s}px rgb(15 23 42/.25);display:flex;flex-direction:column;align-items:center;gap:${Math.round(s * 0.45)}px;color:#0f172a;text-align:center">
497
+ <div style="font:700 ${s}px/1.2 ${FONT}">${esc(o.title)}</div>
498
+ ${o.sub ? `<div style="display:flex;align-items:center;gap:${Math.round(s * 0.25)}px;font:500 ${Math.round(s * 0.45)}px/1 ${FONT};color:#334155"><span style="width:${Math.round(s * 0.7)}px;height:${Math.round(s * 0.7)}px;border-radius:50%;background:${o.color ?? "#2456d8"};color:#fff;display:inline-flex;align-items:center;justify-content:center;font-weight:700">${initial}</span>${esc(o.sub)}</div>` : ""}
499
+ </div>
500
+ </div>`);
501
+ },
502
+ close: () => ctx.close()
503
+ };
504
+ }
505
+
506
+ // src/image.ts
507
+ function fitWidth(w, h, width) {
508
+ if (!width || width >= w) return { width: w - w % 2, height: h - h % 2 };
509
+ const W = Math.max(2, Math.round(width / 2) * 2);
510
+ const H = Math.max(2, Math.round(h * W / w / 2) * 2);
511
+ return { width: W, height: H };
512
+ }
513
+ function resize(src, W, H) {
514
+ const { width: w, height: h, data } = src;
515
+ if (W === w && H === h) return src;
516
+ const out = new Uint8Array(W * H * 4);
517
+ const sx = w / W;
518
+ const sy = h / H;
519
+ for (let Y = 0; Y < H; Y += 1) {
520
+ const y0 = Y * sy;
521
+ const y1 = y0 + sy;
522
+ for (let X = 0; X < W; X += 1) {
523
+ const x0 = X * sx;
524
+ const x1 = x0 + sx;
525
+ let r = 0;
526
+ let g = 0;
527
+ let b = 0;
528
+ let a = 0;
529
+ let wsum = 0;
530
+ for (let y = Math.floor(y0); y < Math.min(h, Math.ceil(y1)); y += 1) {
531
+ const wy = Math.min(y + 1, y1) - Math.max(y, y0);
532
+ for (let x = Math.floor(x0); x < Math.min(w, Math.ceil(x1)); x += 1) {
533
+ const wt = wy * (Math.min(x + 1, x1) - Math.max(x, x0));
534
+ const i = (y * w + x) * 4;
535
+ r += data[i] * wt;
536
+ g += data[i + 1] * wt;
537
+ b += data[i + 2] * wt;
538
+ a += data[i + 3] * wt;
539
+ wsum += wt;
540
+ }
541
+ }
542
+ const o = (Y * W + X) * 4;
543
+ out[o] = Math.round(r / wsum);
544
+ out[o + 1] = Math.round(g / wsum);
545
+ out[o + 2] = Math.round(b / wsum);
546
+ out[o + 3] = Math.round(a / wsum);
547
+ }
548
+ }
549
+ return { width: W, height: H, data: out };
550
+ }
551
+ function crop(src, W, H) {
552
+ if (W === src.width && H === src.height) return src;
553
+ const out = new Uint8Array(W * H * 4);
554
+ for (let y = 0; y < H; y += 1) out.set(src.data.subarray(y * src.width * 4, y * src.width * 4 + W * 4), y * W * 4);
555
+ return { width: W, height: H, data: out };
556
+ }
557
+ function pixel(img, x, y) {
558
+ const i = (y * img.width + x) * 4;
559
+ return [img.data[i], img.data[i + 1], img.data[i + 2]];
560
+ }
561
+
562
+ // src/layout.ts
563
+ var even = (n) => Math.max(2, Math.round(n / 2) * 2);
564
+ function layoutOf(srcW, srcH, width, frame = "none") {
565
+ if (frame === "none") {
566
+ const { width: W2, height: H2 } = fitWidth(srcW, srcH, width);
567
+ const r = { x: 0, y: 0, w: W2, h: H2 };
568
+ return { width: W2, height: H2, content: r, bar: null, window: r };
569
+ }
570
+ const W = even(Math.min(width ?? Infinity, srcW / 0.92));
571
+ const pad = Math.round(W * 0.04);
572
+ const barH = Math.max(18, Math.round(W * 0.036));
573
+ const cw = W - 2 * pad;
574
+ const ch = Math.round(srcH * cw / srcW);
575
+ const H = even(ch + barH + 2 * pad);
576
+ const top = Math.floor((H - ch - barH) / 2);
577
+ return {
578
+ width: W,
579
+ height: H,
580
+ bar: { x: pad, y: top, w: cw, h: barH },
581
+ content: { x: pad, y: top + barH, w: cw, h: ch },
582
+ window: { x: pad, y: top, w: cw, h: barH + ch }
583
+ };
584
+ }
585
+
586
+ // src/mp4.ts
587
+ import { spawn, spawnSync } from "child_process";
588
+ function findFfmpeg(env = process.env) {
589
+ const bin = env.FFMPEG || "ffmpeg";
590
+ try {
591
+ const r = spawnSync(bin, ["-version"], { stdio: "ignore" });
592
+ return r.status === 0 ? bin : null;
593
+ } catch {
594
+ return null;
595
+ }
596
+ }
597
+ function mp4Args(file, fps, size, audio) {
598
+ return [
599
+ "-y",
600
+ "-loglevel",
601
+ "error",
602
+ "-f",
603
+ "rawvideo",
604
+ "-pix_fmt",
605
+ "rgba",
606
+ "-s",
607
+ `${size.width}x${size.height}`,
608
+ "-framerate",
609
+ String(fps),
610
+ "-i",
611
+ "-",
612
+ ...audio ? ["-i", audio, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "128k"] : [],
613
+ "-vf",
614
+ "format=yuv420p",
615
+ "-c:v",
616
+ "libx264",
617
+ "-preset",
618
+ "medium",
619
+ "-crf",
620
+ "20",
621
+ "-r",
622
+ String(fps),
623
+ ...audio ? ["-shortest"] : [],
624
+ "-movflags",
625
+ "+faststart",
626
+ file
627
+ ];
628
+ }
629
+ async function encodeMp4(frames, o) {
630
+ const bin = o.ffmpeg ?? findFfmpeg();
631
+ if (!bin) throw new Error("MP4 needs ffmpeg: install it (brew install ffmpeg, apt install ffmpeg) or set FFMPEG to its path. GIF works without it.");
632
+ if (o.width % 2 || o.height % 2) throw new Error(`MP4 needs an even size (got ${o.width}\xD7${o.height})`);
633
+ const p = spawn(bin, mp4Args(o.file, o.fps, o, o.audio), { stdio: ["pipe", "ignore", "pipe"] });
634
+ let err = "";
635
+ p.stderr.on("data", (d) => {
636
+ err += String(d);
637
+ });
638
+ const done = new Promise((resolve3, reject) => {
639
+ p.on("error", reject);
640
+ p.on("close", (code) => code === 0 ? resolve3() : reject(new Error(`ffmpeg exited with ${code}: ${err.trim()}`)));
641
+ });
642
+ p.stdin.on("error", () => {
643
+ });
644
+ for (const f of frames) {
645
+ if (p.exitCode !== null) break;
646
+ if (!p.stdin.write(f)) {
647
+ await new Promise((r) => {
648
+ const go = () => {
649
+ p.stdin.off("drain", go);
650
+ p.off("close", go);
651
+ r();
652
+ };
653
+ p.stdin.once("drain", go);
654
+ p.once("close", go);
655
+ });
656
+ }
657
+ }
658
+ p.stdin.end();
659
+ await done;
660
+ }
661
+
662
+ // src/timeline.ts
663
+ var lenOf = (s) => s.hold ? s.hold : s.to - s.from;
664
+ var DEFAULT_MAX_WAIT_MS = 800;
665
+ function spansOf(events, start, end) {
666
+ const marks = events.filter((e) => e.type === "state" && e.phase || e.type === "unload").map((e) => ({ t: e.t, phase: e.type === "unload" ? "waiting" : e.phase })).sort((a, b) => a.t - b.t);
667
+ const spans = [];
668
+ let phase = "idle";
669
+ let at = start;
670
+ for (const m of marks) {
671
+ if (m.t <= start) {
672
+ phase = m.phase;
673
+ continue;
674
+ }
675
+ if (m.t >= end) break;
676
+ if (m.t > at) spans.push({ from: at, to: m.t, phase });
677
+ phase = m.phase;
678
+ at = m.t;
679
+ }
680
+ if (end > at) spans.push({ from: at, to: end, phase });
681
+ const out = [];
682
+ for (const s of spans) {
683
+ const last = out[out.length - 1];
684
+ if (last && last.phase === s.phase && last.to === s.from) last.to = s.to;
685
+ else out.push({ ...s });
686
+ }
687
+ return out;
688
+ }
689
+ function editList(events, o) {
690
+ if (!(o.end > o.start)) return [];
691
+ const max = o.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
692
+ const cuts = [];
693
+ if (max > 0) {
694
+ for (const s of spansOf(events, o.start, o.end)) {
695
+ if (s.phase === "waiting" && s.to - s.from > max) cuts.push({ from: s.from + max / 2, to: s.to - max / 2 });
696
+ }
697
+ }
698
+ const keep = [];
699
+ let at = o.start;
700
+ for (const c of cuts) {
701
+ if (c.from > at) keep.push({ from: at, to: c.from });
702
+ at = Math.max(at, c.to);
703
+ }
704
+ if (o.end > at) keep.push({ from: at, to: o.end });
705
+ return keep;
706
+ }
707
+ var durationOf = (segs) => segs.reduce((n, s) => n + lenOf(s), 0);
708
+ function sourceAt(segs, t) {
709
+ if (!segs.length) return 0;
710
+ let left = Math.max(0, t);
711
+ for (const s of segs) {
712
+ const len = lenOf(s);
713
+ if (left < len) return s.hold ? s.from : s.from + left;
714
+ left -= len;
715
+ }
716
+ return segs[segs.length - 1].to;
717
+ }
718
+ function outputAt(segs, src) {
719
+ let out = 0;
720
+ for (const s of segs) {
721
+ if (s.hold) {
722
+ out += s.hold;
723
+ continue;
724
+ }
725
+ if (src >= s.from && src <= s.to) return out + (src - s.from);
726
+ out += s.to - s.from;
727
+ }
728
+ return null;
729
+ }
730
+ function withHolds(segs, holds) {
731
+ const marks = holds.filter((h) => h.ms > 0).map((h) => ({ src: sourceAt(segs, h.at), ms: Math.round(h.ms) })).sort((a, b) => a.src - b.src);
732
+ const out = [];
733
+ let k = 0;
734
+ for (const s of segs) {
735
+ if (s.hold) {
736
+ out.push({ ...s });
737
+ continue;
738
+ }
739
+ let from = s.from;
740
+ while (k < marks.length && marks[k].src <= s.to) {
741
+ const m = marks[k++];
742
+ const at = Math.max(from, m.src);
743
+ if (at > from) out.push({ from, to: at });
744
+ out.push({ from: at, to: at, hold: m.ms });
745
+ from = at;
746
+ }
747
+ if (s.to > from) out.push({ from, to: s.to });
748
+ }
749
+ return out;
750
+ }
751
+ function frameTimes(segs, fps) {
752
+ const n = Math.max(1, Math.round(durationOf(segs) / 1e3 * fps));
753
+ return Array.from({ length: n }, (_, k) => sourceAt(segs, k * 1e3 / fps));
754
+ }
755
+ function pickFrames(captured, want) {
756
+ return want.map((t) => {
757
+ let lo = 0;
758
+ let hi = captured.length - 1;
759
+ let best = 0;
760
+ while (lo <= hi) {
761
+ const mid = lo + hi >> 1;
762
+ if (captured[mid] <= t) {
763
+ best = mid;
764
+ lo = mid + 1;
765
+ } else hi = mid - 1;
766
+ }
767
+ return best;
768
+ });
769
+ }
770
+
771
+ // src/plan.ts
772
+ var stepsOf = (events) => events.filter((e) => e.type === "step").slice().sort((a, b) => a.t - b.t);
773
+ function actionsOf(events, segs, scale = 1) {
774
+ const out = [];
775
+ for (const e of events) {
776
+ const t = outputAt(segs, e.t);
777
+ if (t === null) continue;
778
+ if (e.type === "unload") out.push({ t, x: 0, y: 0, kind: "page" });
779
+ else if (e.type === "step" && e.rect && e.stepType) {
780
+ out.push({ t, x: (e.rect.x + e.rect.w / 2) * scale, y: (e.rect.y + e.rect.h / 2) * scale, kind: e.stepType });
781
+ }
782
+ }
783
+ return out.sort((a, b) => a.t - b.t);
784
+ }
785
+ function stepCues(events, segs, endMs, o = {}) {
786
+ const after = o.afterMs ?? 600;
787
+ const min = o.minMs ?? 1200;
788
+ const cues = [];
789
+ let prev = 0;
790
+ for (const e of stepsOf(events)) {
791
+ const t = outputAt(segs, e.t);
792
+ if (t === null) continue;
793
+ if (e.say) {
794
+ const end = Math.min(t + after, endMs);
795
+ cues.push({ start: Math.max(0, Math.min(prev, end - min)), end, text: e.say });
796
+ }
797
+ prev = t;
798
+ }
799
+ for (let k = 1; k < cues.length; k += 1) {
800
+ if (cues[k].start < cues[k - 1].end) cues[k].start = cues[k - 1].end;
801
+ }
802
+ return cues.filter((c) => c.end > c.start);
803
+ }
804
+ function pageAt(events) {
805
+ const marks = events.filter((e) => e.url && e.type !== "unload").slice().sort((a, b) => a.t - b.t);
806
+ return (src) => {
807
+ let url = marks[0]?.url ?? "/";
808
+ for (const m of marks) {
809
+ if (m.t <= src) url = m.url;
810
+ else break;
811
+ }
812
+ return url;
813
+ };
814
+ }
815
+ function cueAt(cues, t, fadeMs = 150) {
816
+ for (const c of cues) {
817
+ if (t >= c.start && t < c.end) {
818
+ const alpha = Math.min(1, (t - c.start) / fadeMs, (c.end - t) / fadeMs);
819
+ return { cue: c, alpha: Math.max(0, alpha) };
820
+ }
821
+ }
822
+ return null;
823
+ }
824
+
825
+ // src/audio.ts
826
+ var TRACK_RATE = 48e3;
827
+ function toWav(pcm, sampleRate) {
828
+ const data = pcm.length * 2;
829
+ const buf = new ArrayBuffer(44 + data);
830
+ const v = new DataView(buf);
831
+ const str = (at, s) => {
832
+ for (let i = 0; i < s.length; i += 1) v.setUint8(at + i, s.charCodeAt(i));
833
+ };
834
+ str(0, "RIFF");
835
+ v.setUint32(4, 36 + data, true);
836
+ str(8, "WAVE");
837
+ str(12, "fmt ");
838
+ v.setUint32(16, 16, true);
839
+ v.setUint16(20, 1, true);
840
+ v.setUint16(22, 1, true);
841
+ v.setUint32(24, sampleRate, true);
842
+ v.setUint32(28, sampleRate * 2, true);
843
+ v.setUint16(32, 2, true);
844
+ v.setUint16(34, 16, true);
845
+ str(36, "data");
846
+ v.setUint32(40, data, true);
847
+ for (let i = 0; i < pcm.length; i += 1) v.setInt16(44 + i * 2, pcm[i], true);
848
+ return new Uint8Array(buf);
849
+ }
850
+ function fromWav(bytes) {
851
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
852
+ const tag = (at2) => String.fromCharCode(...bytes.subarray(at2, at2 + 4));
853
+ if (bytes.length < 12 || tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error("not a WAV file");
854
+ let at = 12;
855
+ let rate = 0;
856
+ let channels = 1;
857
+ while (at + 8 <= bytes.length) {
858
+ const id = tag(at);
859
+ const size = v.getUint32(at + 4, true);
860
+ if (id === "fmt ") {
861
+ const format = v.getUint16(at + 8, true);
862
+ channels = v.getUint16(at + 10, true);
863
+ rate = v.getUint32(at + 12, true);
864
+ const bits = v.getUint16(at + 22, true);
865
+ if (format !== 1 && format !== 65534 || bits !== 16) throw new Error(`only 16-bit PCM WAV is read (format ${format}, ${bits} bits)`);
866
+ } else if (id === "data") {
867
+ if (!rate) throw new Error("a WAV data chunk before its format");
868
+ const len = size === 0 || size === 4294967295 || at + 8 + size > bytes.length ? bytes.length - at - 8 : size;
869
+ const n = Math.floor(len / 2 / channels);
870
+ const pcm = new Int16Array(n);
871
+ for (let i = 0; i < n; i += 1) {
872
+ let sum = 0;
873
+ for (let c = 0; c < channels; c += 1) sum += v.getInt16(at + 8 + (i * channels + c) * 2, true);
874
+ pcm[i] = Math.round(sum / channels);
875
+ }
876
+ return { pcm, sampleRate: rate };
877
+ }
878
+ at += 8 + size + size % 2;
879
+ }
880
+ throw new Error("a WAV file without data");
881
+ }
882
+ function fromS16le(bytes) {
883
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
884
+ const out = new Int16Array(Math.floor(bytes.length / 2));
885
+ for (let i = 0; i < out.length; i += 1) out[i] = v.getInt16(i * 2, true);
886
+ return out;
887
+ }
888
+ function resample(pcm, from, to) {
889
+ if (from === to || !pcm.length) return pcm.slice();
890
+ const n = Math.max(1, Math.round(pcm.length * to / from));
891
+ const out = new Int16Array(n);
892
+ const step = from / to;
893
+ for (let i = 0; i < n; i += 1) {
894
+ const x = i * step;
895
+ const a = Math.min(pcm.length - 1, Math.floor(x));
896
+ const b = Math.min(pcm.length - 1, a + 1);
897
+ out[i] = Math.round(pcm[a] + (pcm[b] - pcm[a]) * (x - a));
898
+ }
899
+ return out;
900
+ }
901
+ function trimSilence(p, o = {}) {
902
+ const level = o.level ?? 400;
903
+ const pad = Math.round((o.padMs ?? 40) * p.sampleRate / 1e3);
904
+ let a = 0;
905
+ while (a < p.pcm.length && Math.abs(p.pcm[a]) < level) a += 1;
906
+ if (a === p.pcm.length) return { pcm: new Int16Array(0), sampleRate: p.sampleRate };
907
+ let b = p.pcm.length - 1;
908
+ while (b > a && Math.abs(p.pcm[b]) < level) b -= 1;
909
+ return { pcm: p.pcm.slice(Math.max(0, a - pad), Math.min(p.pcm.length, b + 1 + pad)), sampleRate: p.sampleRate };
910
+ }
911
+ var msOf = (p) => p.pcm.length * 1e3 / p.sampleRate;
912
+ function mix(lines, totalMs, o = {}) {
913
+ const out = new Float64Array(Math.max(0, Math.round(totalMs * TRACK_RATE / 1e3)));
914
+ const fade = Math.round((o.fadeMs ?? 15) * TRACK_RATE / 1e3);
915
+ for (const l of lines) {
916
+ const s = resample(l.audio.pcm, l.audio.sampleRate, TRACK_RATE);
917
+ const at = Math.round(l.start * TRACK_RATE / 1e3);
918
+ const f = Math.min(fade, Math.floor(s.length / 2));
919
+ for (let i = 0; i < s.length; i += 1) {
920
+ const k = at + i;
921
+ if (k < 0) continue;
922
+ if (k >= out.length) break;
923
+ const g = f ? Math.min(1, i / f, (s.length - 1 - i) / f) : 1;
924
+ out[k] += s[i] * g;
925
+ }
926
+ }
927
+ const pcm = new Int16Array(out.length);
928
+ for (let i = 0; i < out.length; i += 1) pcm[i] = Math.max(-32768, Math.min(32767, Math.round(out[i])));
929
+ return pcm;
930
+ }
931
+
932
+ // src/narration.ts
933
+ import { preview } from "trace-avatar/assist";
934
+ function linesOf(steps, script) {
935
+ const out = /* @__PURE__ */ new Map();
936
+ steps.forEach((s, i) => {
937
+ if (s.say?.trim()) out.set(i, s.say.trim());
938
+ });
939
+ for (const l of script?.lines ?? []) {
940
+ const i = l.n - 1;
941
+ if (!Number.isInteger(i) || i < 0 || i >= steps.length) throw new Error(`the script has a line for step ${l.n}, but the trace has ${steps.length} steps`);
942
+ if (l.text.trim()) out.set(i, l.text.trim());
943
+ else out.delete(i);
944
+ }
945
+ return out;
946
+ }
947
+ function parseScript(json) {
948
+ const lines = json?.lines;
949
+ if (!Array.isArray(lines) || lines.some((l) => !l || typeof l.n !== "number" || typeof l.text !== "string")) {
950
+ throw new Error('a narration script is { "lines": [{ "n": 1, "text": "\u2026" }] }');
951
+ }
952
+ return { lines: lines.map((l) => ({ n: l.n, text: l.text })) };
953
+ }
954
+ function planNarration(acts, lines, endMs, o = {}) {
955
+ const first = o.firstMs ?? 300;
956
+ const after = o.afterActMs ?? 200;
957
+ const before = o.beforeActMs ?? 250;
958
+ const gap = o.gapMs ?? 150;
959
+ const maxHold = o.maxHoldMs ?? 8e3;
960
+ const plan = { lines: [], holds: [], long: [] };
961
+ let extra = 0;
962
+ let prevCut = null;
963
+ let prevEnd = -Infinity;
964
+ for (const a of acts.slice().sort((x, y) => x.t - y.t)) {
965
+ const line = lines.get(a.index);
966
+ const prevHeld = prevCut === null ? null : prevCut + extra;
967
+ if (line && line.ms > 0) {
968
+ const start = Math.max(prevHeld === null ? first : prevHeld + after, prevEnd + gap);
969
+ const end = start + line.ms;
970
+ const need = Math.ceil(end - (a.t + extra - before));
971
+ if (need > 0) {
972
+ plan.holds.push({ at: Math.max(0, a.t - before, prevCut ?? 0), ms: need });
973
+ extra += need;
974
+ if (need > maxHold) plan.long.push({ index: a.index, ms: need });
975
+ }
976
+ plan.lines.push({ index: a.index, text: line.text, start: Math.round(start), ms: Math.round(line.ms) });
977
+ prevEnd = end;
978
+ }
979
+ prevCut = a.t;
980
+ }
981
+ const endHoldMs = Math.max(0, Math.ceil(prevEnd + (o.tailMs ?? 400) - (endMs + extra)));
982
+ if (endHoldMs > 0) plan.holds.push({ at: endMs, ms: endHoldMs });
983
+ return { ...plan, endHoldMs };
984
+ }
985
+ function narrationText(lines, offsetMs = 0) {
986
+ const at = (ms) => {
987
+ const s = Math.round((ms + offsetMs) / 1e3);
988
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
989
+ };
990
+ return lines.map((l) => `[${at(l.start)}] ${l.text}`).join("\n") + (lines.length ? "\n" : "");
991
+ }
992
+ var SCRIPT_SCHEMA = { type: "object", properties: { lines: { type: "array", items: { type: "object", properties: { n: { type: "integer" }, text: { type: "string" } }, required: ["n", "text"] } } }, required: ["lines"] };
993
+ var SCRIPT_INSTRUCTIONS = `You write the voice-over for a short screen guide. For each step, write one line to be spoken while the cursor moves to it: a full, natural sentence in plain English, second person ("Now click Save"), at most 25 words. Spell out symbols and numbers as spoken ("twenty percent", not "20%"). Keep the meaning of the step's caption when it has one. Skip steps that need no words (return no line for them). Never invent data values. Answer with JSON: { "lines": [{ "n": <step number>, "text": "\u2026" }] }.`;
994
+ async function suggestScript(ai, trace) {
995
+ const p = preview("captions", trace);
996
+ const answer = await ai("narration", p.input, SCRIPT_SCHEMA, { instructions: SCRIPT_INSTRUCTIONS });
997
+ const steps = trace.steps?.length ?? 0;
998
+ const lines = [];
999
+ const dropped = [];
1000
+ const seen = /* @__PURE__ */ new Set();
1001
+ for (const l of answer?.lines ?? []) {
1002
+ const n = l?.n;
1003
+ const text = typeof l?.text === "string" ? l.text.trim() : "";
1004
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > steps) dropped.push({ n, why: "no such step" });
1005
+ else if (seen.has(n)) dropped.push({ n, why: "a second line for the step" });
1006
+ else if (!text) dropped.push({ n, why: "empty" });
1007
+ else if (text.length > 300) dropped.push({ n, why: "longer than 300 characters" });
1008
+ else {
1009
+ seen.add(n);
1010
+ lines.push({ n, text });
1011
+ }
1012
+ }
1013
+ return { script: { lines: lines.sort((a, b) => a.n - b.n) }, dropped };
1014
+ }
1015
+
1016
+ // src/repair.ts
1017
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
1018
+ import { dirname, join } from "path";
1019
+ import { applyRaw, chooseRepair, chooseWait, guessWait, repairSuggestion, typedOf, waitSuggestion } from "trace-avatar/assist";
1020
+ function repairScriptOf(playerFile) {
1021
+ const file = join(dirname(playerFile), "trace-repair.min.js");
1022
+ if (!existsSync(file)) throw new RenderError(`--repair needs trace-avatar 0.1.7 or later (no ${file})`);
1023
+ return file;
1024
+ }
1025
+ function stallInspector(o) {
1026
+ const code = `${readFileSync2(o.script, "utf8")}
1027
+ ;window.__taRepair = TraceAvatarRepair;`;
1028
+ return async (page, stall) => {
1029
+ if (stall.reason === "until-timeout") return waitInspect(page, stall.index);
1030
+ if (stall.reason !== "not-found") return { why: "the step timed out waiting; only a missing element or a changed text can be repaired", top: [] };
1031
+ await page.evaluate(code);
1032
+ const skip = o.skip?.length ? o.skip.join(", ") : void 0;
1033
+ const list = await page.evaluate((sk) => window.__taRepair.candidatesOf(document, sk ? { skip: sk } : {}), skip);
1034
+ const image = o.ai && o.vision ? { png: new Uint8Array(await page.screenshot()), label: "the page now" } : void 0;
1035
+ const choice = await chooseRepair(o.trace(), stall.index, list, { ...o.ai ? { ai: o.ai } : {}, ...image ? { image } : {} });
1036
+ const byId = new Map(list.map((c) => [c.id, c]));
1037
+ const top = choice.top.map((t) => {
1038
+ const { key: _k, ...c } = byId.get(t.id);
1039
+ return { ...c, score: t.score };
1040
+ });
1041
+ if (choice.id === null || choice.by === "none") return { why: choice.why ?? (o.ai ? "no element on the page fits the step" : "no clear match; pass --ai to ask, or pick one"), top };
1042
+ const r = await page.evaluate((id) => {
1043
+ const x = window.__taRepair;
1044
+ const target = x.targetFor(id);
1045
+ return { target, ok: !!target && x.resolvesTo(target, x.elementOf(id)) };
1046
+ }, choice.id);
1047
+ if (!r.ok) return { why: "the chosen element could not be told apart from others on the page", top };
1048
+ return { chosen: { target: r.target, by: choice.by, ...choice.score !== void 0 ? { score: choice.score } : {}, ...choice.why ? { why: choice.why } : {} }, top };
1049
+ };
1050
+ async function waitInspect(page, index) {
1051
+ await page.evaluate(code);
1052
+ if (!await page.evaluate(() => typeof window.__taRepair.textsOf === "function")) {
1053
+ return { why: "repairing a wait needs trace-avatar 0.1.9 or later", top: [] };
1054
+ }
1055
+ const trace = o.trace();
1056
+ const list = await page.evaluate(({ target, typed, skip }) => {
1057
+ const w = window;
1058
+ const r = w.__taRepair;
1059
+ const out = (el) => !!skip && !!el?.closest(skip);
1060
+ const seen = (w.__taSeen ?? []).filter((x) => !out(x.element));
1061
+ return r.textsOf(r.scopeFor(target ?? void 0, document), { seen, typed }).filter((c) => !out(r.elementOf(c.id))).map((c, id) => ({ ...c, id }));
1062
+ }, { target: trace.steps[index]?.target ?? null, typed: typedOf(trace), skip: o.skip?.length ? o.skip.join(", ") : "" });
1063
+ const choice = await chooseWait(trace, index, list, o.ai ? { ai: o.ai } : {});
1064
+ const top = choice.top.map((t) => {
1065
+ const { id: _i, ...c } = list[t.id];
1066
+ return { ...c, score: t.score };
1067
+ });
1068
+ const best = guessWait(choice, list);
1069
+ if (!best) return { why: choice.why ?? (o.ai ? "no text on the page fits the wait" : "no clear match; pass --ai to ask, or pick one"), top };
1070
+ const score = choice.top.find((t) => t.id === best.id)?.score;
1071
+ return { text: { value: best.text, by: best.guess ? "guess" : choice.by, ...score !== void 0 ? { score } : {}, ...choice.why && !best.guess ? { why: choice.why } : {} }, top };
1072
+ }
1073
+ }
1074
+ async function repairGuide(o) {
1075
+ let current = o.trace;
1076
+ const out = { suggestions: [], unresolved: [], passed: false };
1077
+ const inspect = stallInspector({ script: repairScriptOf(o.capture.playerFile), trace: () => current, ...o.ai ? { ai: o.ai } : {}, ...o.vision ? { vision: true } : {}, ...o.capture.hide || o.capture.blur ? { skip: [...o.capture.hide ?? [], ...o.capture.blur ?? []] } : {} });
1078
+ let pending = o.first;
1079
+ for (let round = 0; round <= (o.maxStalls ?? 5); round += 1) {
1080
+ let stall = pending;
1081
+ pending = void 0;
1082
+ if (!stall) {
1083
+ try {
1084
+ await capture({ ...o.capture, trace: current, onStall: inspect });
1085
+ const last2 = out.suggestions[out.suggestions.length - 1];
1086
+ if (last2) last2.verified = true;
1087
+ out.passed = true;
1088
+ return out;
1089
+ } catch (e) {
1090
+ if (!(e instanceof RenderError) || !e.stall) throw e;
1091
+ stall = e;
1092
+ }
1093
+ }
1094
+ const s = stall.stall;
1095
+ const last = out.suggestions[out.suggestions.length - 1];
1096
+ if (last && last.verified === void 0) {
1097
+ last.verified = s.index > last.index;
1098
+ if (!last.verified) {
1099
+ out.unresolved.push({ index: s.index, reason: s.reason, why: "the repaired step still stalls", top: [] });
1100
+ return out;
1101
+ }
1102
+ }
1103
+ const found = s.data;
1104
+ if (!found?.chosen && !found?.text) {
1105
+ out.unresolved.push({ index: s.index, reason: s.reason, why: found?.why ?? "the page could not be looked at", top: found?.top ?? [] });
1106
+ return out;
1107
+ }
1108
+ if (round === (o.maxStalls ?? 5)) {
1109
+ out.unresolved.push({ index: s.index, reason: s.reason, why: `stopped after ${o.maxStalls ?? 5} repairs`, top: found.top });
1110
+ return out;
1111
+ }
1112
+ const pick = found.chosen ?? found.text;
1113
+ const sg = found.chosen ? repairSuggestion(current, s.index, found.chosen.target, pick.why ? { why: pick.why } : {}) : waitSuggestion(current, s.index, found.text.value, pick.why ? { why: pick.why } : {});
1114
+ out.suggestions.push({ ...sg, id: out.suggestions.length + 1, by: pick.by, ...pick.score !== void 0 ? { score: pick.score } : {} });
1115
+ current = applyRaw(current, [sg]);
1116
+ }
1117
+ return out;
1118
+ }
1119
+
1120
+ // src/vtt.ts
1121
+ var stamp = (ms) => {
1122
+ const t = Math.max(0, Math.round(ms));
1123
+ const h = Math.floor(t / 36e5);
1124
+ const m = Math.floor(t % 36e5 / 6e4);
1125
+ const s = Math.floor(t % 6e4 / 1e3);
1126
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(t % 1e3).padStart(3, "0")}`;
1127
+ };
1128
+ var clean = (s) => s.replace(/-->/g, "\u2192").replace(/\r?\n\s*\r?\n/g, "\n").trim();
1129
+ function toVtt(cues) {
1130
+ return `WEBVTT
1131
+
1132
+ ${cues.filter((c) => c.end > c.start && c.text.trim()).map((c, k) => `${k + 1}
1133
+ ${stamp(c.start)} --> ${stamp(c.end)}
1134
+ ${clean(c.text)}
1135
+ `).join("\n")}`;
1136
+ }
1137
+ function captionCues(starts, endMs, maxMs = 6e3) {
1138
+ const s = starts.slice().sort((a, b) => a.t - b.t);
1139
+ return s.map((c, k) => ({ start: c.t, end: Math.min(s[k + 1]?.t ?? endMs, c.t + maxMs, endMs), text: c.text }));
1140
+ }
1141
+ function chapterCues(starts, endMs) {
1142
+ const s = starts.slice().sort((a, b) => a.t - b.t);
1143
+ return s.map((c, k) => {
1144
+ const first = c.text.split(/(?<=[.!?…])\s/)[0].trim();
1145
+ return { start: c.t, end: s[k + 1]?.t ?? endMs, text: first.length > 60 ? `${first.slice(0, 59)}\u2026` : first };
1146
+ });
1147
+ }
1148
+
1149
+ // src/ai.ts
1150
+ import { resolve } from "path";
1151
+ import { pathToFileURL } from "url";
1152
+ import { gateway, openAiCompatible } from "trace-avatar/assist";
1153
+ async function providerOf(spec, env = process.env, o = {}) {
1154
+ const vision = o.vision ? { visionModel: o.vision } : {};
1155
+ const g = /^gateway(?::([\w.-]+)(?:\/([^,]+))?((?:,[\w.-]+)*))?$/.exec(spec);
1156
+ if (g) {
1157
+ return gateway({
1158
+ ...g[1] ? { provider: [g[1], ...(g[3] ?? "").split(",").filter(Boolean)] } : {},
1159
+ ...g[2] ? { model: g[2] } : {},
1160
+ ...vision,
1161
+ url: env.AI_GATEWAY_URL,
1162
+ key: env.AI_GATEWAY_KEY
1163
+ });
1164
+ }
1165
+ const m = /^openai:(.+)$/.exec(spec);
1166
+ if (m) {
1167
+ if (!env.OPENAI_API_KEY && !env.OPENAI_BASE_URL) throw new Error("--ai openai:\u2026 needs OPENAI_API_KEY (and OPENAI_BASE_URL for another OpenAI-compatible server)");
1168
+ return openAiCompatible({ baseUrl: env.OPENAI_BASE_URL || "https://api.openai.com/v1", ...env.OPENAI_API_KEY ? { key: env.OPENAI_API_KEY } : {}, model: m[1], ...vision });
1169
+ }
1170
+ if (/\.(m?js|cjs)$/.test(spec)) {
1171
+ const mod = await import(pathToFileURL(resolve(spec)).href);
1172
+ const fn = mod.default ?? mod.ai;
1173
+ if (typeof fn !== "function") throw new Error(`${spec} must export a default function (task, input, schema, { instructions, images }) \u2192 JSON`);
1174
+ return fn;
1175
+ }
1176
+ throw new Error(`--ai is gateway, gateway:<provider>[/<model>][,<provider>\u2026], openai:<model>, or a .js file (got "${spec}")`);
1177
+ }
1178
+ var QA_KINDS = ["error", "empty", "stalled", "personal-data", "wrong-page", "other"];
1179
+ var QA_SCHEMA = {
1180
+ type: "object",
1181
+ required: ["flags"],
1182
+ properties: { flags: { type: "array", items: { type: "object", required: ["frame", "kind", "note"], properties: {
1183
+ frame: { type: "integer" },
1184
+ kind: { enum: [...QA_KINDS] },
1185
+ note: { type: "string", maxLength: 200 }
1186
+ } } } }
1187
+ };
1188
+ var QA_INSTRUCTIONS = `You check frames of a GIF/video of an on-screen guide before it is published: a cursor with a name badge walks through a web app. For each numbered frame, flag only real problems a viewer would notice: an error message or toast ("error"), an empty state or blank page where content is expected ("empty"), a "Looking for \u2026" caption meaning the guide got stuck ("stalled"), personal data such as real email addresses, phone numbers, card or account numbers ("personal-data"), or a page that does not fit the step ("wrong-page"). The cursor, the name badge, highlights and captions are part of the guide, not problems. Reply with JSON only: {"flags":[{"frame":1,"kind":"error","note":"\u2026"}]}, an empty list when all is well.`;
1189
+ async function runQa(ai, frames, context) {
1190
+ if (!frames.length) return [];
1191
+ const input = { title: context.title, steps: context.steps, frames: frames.map((f, k) => ({ frame: k + 1, at: Math.round(f.at / 100) / 10, shows: f.label })) };
1192
+ const answer = await ai("qa", input, QA_SCHEMA, { instructions: QA_INSTRUCTIONS, images: frames.map((f, k) => ({ png: f.png, label: `Frame ${k + 1}: ${f.label}` })) });
1193
+ const list = answer && typeof answer === "object" && Array.isArray(answer.flags) ? answer.flags : null;
1194
+ if (!list) throw new Error('the QA answer has no "flags" list');
1195
+ const out = [];
1196
+ for (const item of list) {
1197
+ const r = item;
1198
+ if (!Number.isInteger(r?.frame) || r.frame < 1 || r.frame > frames.length) continue;
1199
+ const kind = QA_KINDS.includes(r.kind) ? r.kind : "other";
1200
+ const note = typeof r.note === "string" ? r.note.replace(/\s+/g, " ").trim().slice(0, 200) : "";
1201
+ out.push({ at: frames[r.frame - 1].at, kind, note });
1202
+ }
1203
+ return out.sort((a, b) => a.at - b.at);
1204
+ }
1205
+
1206
+ // src/render.ts
1207
+ import { readFileSync as readFileSync3, writeFileSync, mkdirSync, mkdtempSync, rmSync } from "fs";
1208
+ import { tmpdir } from "os";
1209
+ import { dirname as dirname2, extname, join as join2 } from "path";
1210
+ import { chromium as chromium2 } from "playwright";
1211
+ import { PNG as PNG2 } from "pngjs";
1212
+ import { describe as describeGuide } from "trace-avatar/assist";
1213
+ var formatOf = (file) => {
1214
+ const ext = extname(file).toLowerCase();
1215
+ if (ext === ".gif") return "gif";
1216
+ if (ext === ".mp4") return "mp4";
1217
+ throw new RenderError(`unknown output "${file}": use .gif or .mp4`);
1218
+ };
1219
+ var LEAD_MS = 500;
1220
+ var TITLE_MS = 1500;
1221
+ var END_MS = 2e3;
1222
+ var FADE_MS = 300;
1223
+ function cardOf(v, fallback) {
1224
+ if (!v) return void 0;
1225
+ if (v === true) return fallback;
1226
+ if (typeof v === "string") return { ...fallback, title: v };
1227
+ return { ...fallback, ...v };
1228
+ }
1229
+ async function render(o) {
1230
+ const trace = typeof o.trace === "string" ? JSON.parse(readFileSync3(o.trace, "utf8")) : o.trace;
1231
+ if (!trace || typeof trace !== "object") throw new RenderError("the trace must be an object or a .trace.json path");
1232
+ const mode = o.mode ?? "overlay";
1233
+ if (mode === "perform" && !o.allowPerform) {
1234
+ throw new RenderError("Do it for me clicks and types in the app for real: pass allowPerform (--allow-perform), and render against a sandbox account.");
1235
+ }
1236
+ const outs = o.out.map((x) => typeof x === "string" ? { file: x } : x).map((x) => ({ ...x, format: formatOf(x.file) }));
1237
+ if (!outs.length) throw new RenderError("nothing to write: give at least one output (.gif or .mp4)");
1238
+ const ffmpeg = outs.some((x) => x.format === "mp4") ? findFfmpeg() : null;
1239
+ if (outs.some((x) => x.format === "mp4") && !ffmpeg) throw new RenderError("MP4 needs ffmpeg: install it (brew install ffmpeg, apt install ffmpeg) or set FFMPEG to its path. GIF works without it.");
1240
+ const t = trace;
1241
+ const viewport = o.viewport ?? t.meta?.viewport ?? { w: 1280, h: 800 };
1242
+ const burn = o.captions === "burn" || o.captions === "both";
1243
+ if ((o.qa || o.alt) && !o.ai) throw new RenderError("qa and alt need an AI: pass ai (--ai)");
1244
+ if (o.voice && !outs.some((x) => x.format === "mp4")) throw new RenderError("narration is for video: add an .mp4 output (a GIF has no sound)");
1245
+ const spoken = o.voice ? linesOf(trace.steps ?? [], o.script === void 0 ? void 0 : parseScript(typeof o.script === "string" ? JSON.parse(readFileSync3(o.script, "utf8")) : o.script)) : null;
1246
+ if (spoken && !spoken.size) throw new RenderError("nothing to say: no step has a caption (say), and no script was given");
1247
+ if (o.repairVision && !(o.repair && o.ai)) throw new RenderError("repairVision needs repair and an AI");
1248
+ const capOpts = {
1249
+ url: o.url,
1250
+ mode,
1251
+ viewport,
1252
+ scale: o.scale,
1253
+ storageState: o.storageState,
1254
+ playerFile: await findPlayer(o.player),
1255
+ hide: o.hide,
1256
+ blur: o.blur,
1257
+ rate: o.rate,
1258
+ timeoutMs: o.timeoutMs,
1259
+ headless: o.headless,
1260
+ leadMs: LEAD_MS,
1261
+ ...burn ? { captions: "none" } : {}
1262
+ };
1263
+ if (o.repair) repairScriptOf(capOpts.playerFile);
1264
+ let cap;
1265
+ try {
1266
+ cap = await capture({
1267
+ ...capOpts,
1268
+ trace,
1269
+ allowStall: o.allowStall,
1270
+ ...o.repair && !o.allowStall ? { onStall: stallInspector({ script: repairScriptOf(capOpts.playerFile), trace: () => trace, ...o.ai ? { ai: o.ai } : {}, ...o.repairVision ? { vision: true } : {}, skip: [...o.hide ?? [], ...o.blur ?? []] }) } : {}
1271
+ });
1272
+ } catch (e) {
1273
+ if (!(o.repair && e instanceof RenderError && e.stall)) throw e;
1274
+ const outcome = await repairGuide({ trace, capture: capOpts, ...o.ai ? { ai: o.ai } : {}, ...o.repairVision ? { vision: true } : {}, first: e });
1275
+ const file = `${base(outs[0].file)}.repair.json`;
1276
+ mkdirSync(dirname2(file) || ".", { recursive: true });
1277
+ writeFileSync(file, `${JSON.stringify({ task: "repair", suggestions: outcome.suggestions, unresolved: outcome.unresolved, passed: outcome.passed }, null, 2)}
1278
+ `);
1279
+ const n = outcome.suggestions.length;
1280
+ const ok = outcome.suggestions.filter((x) => x.verified).length;
1281
+ const err = new RenderError(`${e.message}
1282
+ repair: ${n ? `${n} fix${n > 1 ? "es" : ""} (${ok} verified${outcome.passed ? ", the guide now plays to the end" : ""})` : "no fix found"}${outcome.unresolved.length ? `; unresolved: step ${outcome.unresolved.map((u) => u.index + 1).join(", ")}` : ""}. See ${file}${n ? `, then: trace-avatar-render apply <trace> ${file} --accept ${outcome.suggestions.map((x) => x.id).join(",")} --out <new.trace.json>` : ""}`, e.screenshot);
1283
+ err.stall = e.stall;
1284
+ err.repair = { file, outcome };
1285
+ throw err;
1286
+ }
1287
+ const sub = t.avatar?.name ? { sub: t.avatar.name, color: t.avatar.color } : {};
1288
+ const title = cardOf(o.titleCard, { title: t.meta?.title || "How to", ...sub });
1289
+ const end = cardOf(o.endCard, { title: "Done", ...sub });
1290
+ const steps = (trace.steps ?? []).map((st, i) => ({ n: i + 1, type: st.type, ...st.say ? { say: st.say } : {} }));
1291
+ const described = o.alt ? await describeGuide(trace, { ai: o.ai }) : null;
1292
+ let narration;
1293
+ if (spoken) {
1294
+ const lines = /* @__PURE__ */ new Map();
1295
+ for (const [i, text] of spoken) {
1296
+ let audio;
1297
+ try {
1298
+ audio = trimSilence(await o.voice(text));
1299
+ } catch (e) {
1300
+ throw new RenderError(`the voice failed on step ${i + 1} ("${text}"): ${e.message}`);
1301
+ }
1302
+ if (audio.pcm.length) lines.set(i, { text, audio });
1303
+ }
1304
+ narration = { lines, ...o.voiceStrict ? { strict: true } : {}, ...o.voiceOut ? { out: o.voiceOut } : {} };
1305
+ }
1306
+ const { qa: _qa, voice: _v, script: _s, ...rest } = o;
1307
+ const r = await finish(cap, outs, {
1308
+ ...rest,
1309
+ cards: { ...title ? { title } : {}, ...end ? { end } : {} },
1310
+ ...o.qa ? { qa: { ai: o.ai, title: t.meta?.title, steps } } : {},
1311
+ ...described?.chapters.length ? { chapterNames: described.chapters } : {},
1312
+ ...narration ? { narration } : {}
1313
+ });
1314
+ if (described?.alt) {
1315
+ const file = `${base(outs[0].file)}.alt.txt`;
1316
+ writeFileSync(file, `${described.alt}
1317
+ `);
1318
+ r.alt = file;
1319
+ }
1320
+ return r;
1321
+ }
1322
+ var base = (file) => file.replace(/\.[^./]+$/, "");
1323
+ async function finish(cap, outs, o = {}) {
1324
+ const frames = cap.frames.slice().sort((a, b) => a.t - b.t);
1325
+ const start = Math.max(frames[0].t, cap.playAt - LEAD_MS);
1326
+ const end = cap.stopAt;
1327
+ const cut = editList(cap.events, { start, end, maxWaitMs: o.cuts?.maxWaitMs ?? DEFAULT_MAX_WAIT_MS });
1328
+ const stamps = frames.map((f) => f.t);
1329
+ const warnings = [];
1330
+ const narr = o.narration?.lines.size ? o.narration : null;
1331
+ let said = null;
1332
+ let held = cut;
1333
+ if (narr) {
1334
+ const seen = /* @__PURE__ */ new Set();
1335
+ const acts = cap.events.filter((e) => e.type === "step" && e.index !== void 0).sort((a, b) => a.t - b.t).flatMap((e) => {
1336
+ const t = outputAt(cut, e.t);
1337
+ if (t === null || seen.has(e.index)) return [];
1338
+ seen.add(e.index);
1339
+ return [{ index: e.index, t }];
1340
+ });
1341
+ const lines = new Map([...narr.lines].map(([i, l]) => [i, { text: l.text, ms: msOf(l.audio) }]));
1342
+ said = planNarration(acts, lines, durationOf(cut));
1343
+ for (const l of said.long) {
1344
+ const msg = `step ${l.index + 1}'s line needs the video to hold ${(l.ms / 1e3).toFixed(1)} s: shorten it (--script)`;
1345
+ if (narr.strict) throw new RenderError(msg);
1346
+ warnings.push(msg);
1347
+ }
1348
+ const missed = [...narr.lines.keys()].filter((i) => !said.lines.some((l) => l.index === i));
1349
+ if (missed.length) warnings.push(`no narration for step${missed.length > 1 ? "s" : ""} ${missed.map((i) => i + 1).join(", ")}: ${missed.length > 1 ? "they" : "it"} never played`);
1350
+ held = withHolds(cut, said.holds);
1351
+ }
1352
+ const segs = held;
1353
+ const contentMs = durationOf(segs);
1354
+ let slot = null;
1355
+ const source = (i) => {
1356
+ if (slot?.i !== i) {
1357
+ const p = PNG2.sync.read(frames[i].png);
1358
+ slot = { i, img: { width: p.width, height: p.height, data: new Uint8Array(p.data.buffer, p.data.byteOffset, p.data.length) } };
1359
+ }
1360
+ return slot.img;
1361
+ };
1362
+ const first = source(0);
1363
+ const srcW = first.width;
1364
+ const srcH = first.height;
1365
+ const scale = cap.viewport ? srcW / cap.viewport.w : 1;
1366
+ const frameStyle = o.frame ?? "none";
1367
+ const background = o.background ?? DEFAULT_BACKGROUND;
1368
+ const burn = o.captions === "burn" || o.captions === "both";
1369
+ const variant = (sg) => {
1370
+ const ms = durationOf(sg);
1371
+ return {
1372
+ segs: sg,
1373
+ contentMs: ms,
1374
+ cam: o.camera ? cameraPath(actionsOf(cap.events, sg, scale), { width: srcW, height: srcH, ...typeof o.camera === "object" && o.camera.zoom ? { zoom: o.camera.zoom } : {} }) : null,
1375
+ cues: o.captions ? stepCues(cap.events, sg, ms) : []
1376
+ };
1377
+ };
1378
+ const main = variant(segs);
1379
+ const plain = narr ? variant(cut) : main;
1380
+ const cues = main.cues;
1381
+ const page = pageAt(cap.events);
1382
+ const titleMs = o.cards?.title ? TITLE_MS : 0;
1383
+ const endMs = o.cards?.end ? END_MS : 0;
1384
+ const full = { x: 0, y: 0, w: srcW, h: srcH };
1385
+ const needLayers = frameStyle !== "none" || burn && (cues.length > 0 || plain.cues.length > 0) || !!o.cards?.title || !!o.cards?.end;
1386
+ const browser = needLayers ? await chromium2.launch() : null;
1387
+ let layers = null;
1388
+ const outputs = [];
1389
+ const qaFrames = [];
1390
+ let poster;
1391
+ let wav;
1392
+ const tmp = narr ? mkdtempSync(join2(tmpdir(), "tar-voice-")) : null;
1393
+ try {
1394
+ layers = browser ? await createLayers(browser) : null;
1395
+ for (const [n, out] of outs.entries()) {
1396
+ mkdirSync(dirname2(out.file) || ".", { recursive: true });
1397
+ const fps = out.fps ?? (out.format === "gif" ? 12 : 30);
1398
+ const layout = layoutOf(srcW, srcH, out.width ?? (out.format === "gif" ? 800 : void 0), frameStyle);
1399
+ const v = out.format === "gif" ? plain : main;
1400
+ const { cam, segs: segs2, contentMs: contentMs2 } = v;
1401
+ const cues2 = v.cues;
1402
+ const times = frameTimes(segs2, fps);
1403
+ const picks = pickFrames(stamps, times);
1404
+ const art = await artFor(layers, layout, { frameStyle, background, cues: burn ? cues2 : [], urls: [...new Set(cap.events.map((e) => e.url).filter(Boolean))], titles: cap.titles ?? {}, cards: o.cards });
1405
+ const nTitle = Math.round(titleMs * fps / 1e3);
1406
+ const nEnd = Math.round(endMs * fps / 1e3);
1407
+ const nFade = Math.max(1, Math.round(FADE_MS * fps / 1e3));
1408
+ const total = nTitle + picks.length + nEnd;
1409
+ let last = null;
1410
+ const content = (k) => {
1411
+ const t = k * 1e3 / fps;
1412
+ const i = picks[k];
1413
+ const rect = cam ? cam(t) : full;
1414
+ const url = page(times[k]);
1415
+ const c = burn ? cueAt(cues2, t) : null;
1416
+ const alpha = c ? Math.round(c.alpha * 8) / 8 : 0;
1417
+ const key = `${i}|${rect.x.toFixed(1)},${rect.y.toFixed(1)},${rect.w.toFixed(1)}|${url}|${c && alpha > 0 ? `${c.cue.text}@${alpha}` : ""}`;
1418
+ if (last?.key === key) return last.img;
1419
+ const dst = art.base ? copy(art.base.get(url) ?? art.base.values().next().value) : blank(layout.width, layout.height);
1420
+ drawRegion(dst, layout.content, source(i), rect);
1421
+ if (c && alpha > 0) {
1422
+ const img = art.captions.get(c.cue.text);
1423
+ if (img) overlay(dst, img, layout.content.x + (layout.content.w - img.width) / 2, layout.content.y + layout.content.h - img.height - Math.round(layout.content.h * 0.05), alpha);
1424
+ }
1425
+ last = { key, img: dst };
1426
+ return dst;
1427
+ };
1428
+ const frameAt = (m) => {
1429
+ if (m < nTitle) {
1430
+ const left = nTitle - m;
1431
+ return left <= nFade ? crossfade(art.title, content(0), 1 - (left - 1) / nFade) : art.title;
1432
+ }
1433
+ const k = m - nTitle;
1434
+ if (k < picks.length) return content(k);
1435
+ const e = k - picks.length;
1436
+ return e < nFade ? crossfade(content(picks.length - 1), art.end, (e + 1) / nFade) : art.end;
1437
+ };
1438
+ if (out.format === "gif") {
1439
+ const samples = Array.from({ length: Math.min(12, total) }, (_, s) => copy(frameAt(Math.floor(s * total / Math.min(12, total)))));
1440
+ last = null;
1441
+ const w = createGifWriter({ width: layout.width, height: layout.height, fps, palette: paletteOf(samples, samples.length) });
1442
+ for (let m = 0; m < total; m += 1) w.add(frameAt(m));
1443
+ const gif = w.finish();
1444
+ writeFileSync(out.file, gif.bytes);
1445
+ outputs.push({ file: out.file, format: "gif", width: layout.width, height: layout.height, fps, frames: total, bytes: gif.bytes.length, durationMs: gif.durationMs });
1446
+ } else {
1447
+ const all = function* () {
1448
+ for (let m = 0; m < total; m += 1) yield frameAt(m).data;
1449
+ };
1450
+ let audio;
1451
+ if (narr && said && tmp) {
1452
+ const track = mix(said.lines.map((l) => ({ start: l.start + titleMs, audio: narr.lines.get(l.index).audio })), total * 1e3 / fps);
1453
+ audio = join2(tmp, `${n}.wav`);
1454
+ writeFileSync(audio, toWav(track, TRACK_RATE));
1455
+ if (narr.out && !wav) {
1456
+ mkdirSync(dirname2(narr.out) || ".", { recursive: true });
1457
+ writeFileSync(narr.out, toWav(track, TRACK_RATE));
1458
+ wav = narr.out;
1459
+ }
1460
+ }
1461
+ await encodeMp4(all(), { file: out.file, fps, width: layout.width, height: layout.height, ...audio ? { audio } : {} });
1462
+ outputs.push({ file: out.file, format: "mp4", width: layout.width, height: layout.height, fps, frames: total, bytes: readFileSync3(out.file).length, durationMs: Math.round(total * 1e3 / fps) });
1463
+ }
1464
+ if (n === 0 && o.poster) {
1465
+ const click = cap.events.find((e) => e.type === "step" && (e.stepType === "click" || e.stepType === "dblclick"));
1466
+ const ct = click ? outputAt(segs2, click.t) : null;
1467
+ const k = Math.min(picks.length - 1, Math.max(0, Math.round(((ct ?? contentMs2 / 2) + (ct === null ? 0 : 300)) * fps / 1e3)));
1468
+ last = null;
1469
+ const img = content(k);
1470
+ const png = new PNG2({ width: img.width, height: img.height });
1471
+ png.data.set(img.data);
1472
+ poster = typeof o.poster === "string" ? o.poster : `${base(out.file)}.png`;
1473
+ mkdirSync(dirname2(poster) || ".", { recursive: true });
1474
+ writeFileSync(poster, PNG2.sync.write(png));
1475
+ }
1476
+ if (n === 0 && o.qa) {
1477
+ const steps = cap.events.filter((e) => e.type === "step" && e.index !== void 0);
1478
+ const pick = steps.length > 15 ? Array.from({ length: 15 }, (_, j) => steps[Math.floor(j * steps.length / 15)]) : steps;
1479
+ const at = [
1480
+ ...pick.map((e) => ({ t: outputAt(segs2, e.t), label: `after step ${e.index + 1} (${e.stepType})` })).filter((x) => x.t !== null),
1481
+ { t: contentMs2 - 1, label: "the end" }
1482
+ ];
1483
+ for (const x of at) {
1484
+ const k = Math.min(picks.length - 1, Math.max(0, Math.round((x.t + 300) * fps / 1e3)));
1485
+ last = null;
1486
+ const img = content(k);
1487
+ const small = img.width > 640 ? resize(img, 640, Math.max(2, Math.round(img.height * 640 / img.width))) : img;
1488
+ const png = new PNG2({ width: small.width, height: small.height });
1489
+ png.data.set(small.data);
1490
+ qaFrames.push({ at: Math.round(x.t + titleMs), label: x.label, png: new Uint8Array(PNG2.sync.write(png)) });
1491
+ }
1492
+ }
1493
+ }
1494
+ } finally {
1495
+ await layers?.close().catch(() => {
1496
+ });
1497
+ await browser?.close();
1498
+ if (tmp) rmSync(tmp, { recursive: true, force: true });
1499
+ }
1500
+ let vtt;
1501
+ let chapters;
1502
+ if ((o.captions === "vtt" || o.captions === "both") && cues.length) {
1503
+ const shift = (c) => ({ ...c, start: c.start + titleMs, end: c.end + titleMs });
1504
+ vtt = `${base(outs[0].file)}.vtt`;
1505
+ chapters = `${base(outs[0].file)}.chapters.vtt`;
1506
+ writeFileSync(vtt, toVtt(cues.map(shift)));
1507
+ writeFileSync(chapters, toVtt(o.chapterNames?.length ? namedChapters(o.chapterNames, cap.events, segs, contentMs).map(shift) : chapterCues(cues.map((c) => ({ t: c.start, text: c.text })), contentMs).map(shift)));
1508
+ }
1509
+ const qa = o.qa ? await runQa(o.qa.ai, qaFrames, { title: o.qa.title, steps: o.qa.steps }) : void 0;
1510
+ let narration;
1511
+ if (said) {
1512
+ const mp4 = outs.find((x) => x.format === "mp4");
1513
+ const text = `${base(mp4.file)}.narration.txt`;
1514
+ writeFileSync(text, narrationText(said.lines, titleMs));
1515
+ narration = { lines: said.lines.map((l) => ({ ...l, start: l.start + titleMs })), holdMs: said.holds.reduce((a, h) => a + h.ms, 0), text, ...wav ? { wav } : {} };
1516
+ }
1517
+ const rel = (t) => Math.round(t - start);
1518
+ const result = {
1519
+ durationMs: Math.round(contentMs + titleMs + endMs),
1520
+ offsetMs: titleMs,
1521
+ rawMs: Math.round(end - start),
1522
+ segments: segs.map((s) => ({ from: rel(s.from), to: rel(s.to), ...s.hold ? { hold: s.hold } : {} })),
1523
+ events: cap.events.map((e) => ({ ...e, t: rel(e.t) })),
1524
+ outputs,
1525
+ ...poster ? { poster } : {},
1526
+ ...vtt ? { vtt, chapters } : {},
1527
+ ...qa ? { qa } : {},
1528
+ ...narration ? { narration } : {},
1529
+ ...warnings.length ? { warnings } : {}
1530
+ };
1531
+ if (o.timeline) {
1532
+ mkdirSync(dirname2(o.timeline) || ".", { recursive: true });
1533
+ writeFileSync(o.timeline, JSON.stringify(result, null, 2));
1534
+ }
1535
+ return result;
1536
+ }
1537
+ function namedChapters(names, events, segs, endMs) {
1538
+ const starts = names.flatMap((c) => {
1539
+ const e = events.find((x) => x.type === "step" && x.index === c.index);
1540
+ const t = e ? outputAt(segs, e.t) : null;
1541
+ return t === null ? [] : [{ t: c.index === names[0].index ? 0 : t, text: c.name }];
1542
+ }).sort((a, b) => a.t - b.t);
1543
+ return starts.map((c, k) => ({ start: c.t, end: starts[k + 1]?.t ?? endMs, text: c.text }));
1544
+ }
1545
+ async function artFor(layers, layout, o) {
1546
+ const art = { base: null, captions: /* @__PURE__ */ new Map() };
1547
+ if (!layers) return art;
1548
+ if (o.frameStyle !== "none") {
1549
+ art.base = /* @__PURE__ */ new Map();
1550
+ for (const url of o.urls.length ? o.urls : ["/"]) art.base.set(url, await layers.base(layout, { background: o.background, path: url, title: o.titles[url] }));
1551
+ }
1552
+ const fontPx = Math.max(12, Math.round(layout.content.w * 0.026));
1553
+ for (const c of o.cues) {
1554
+ if (!art.captions.has(c.text)) art.captions.set(c.text, await layers.caption(c.text, { maxWidth: Math.round(layout.content.w * 0.8), fontPx }));
1555
+ }
1556
+ if (o.cards?.title) art.title = await layers.card(layout, { ...o.cards.title, background: o.background });
1557
+ if (o.cards?.end) art.end = await layers.card(layout, { ...o.cards.end, background: o.background });
1558
+ return art;
1559
+ }
1560
+
1561
+ // src/voice.ts
1562
+ import { spawnSync as spawnSync2 } from "child_process";
1563
+ import { createHash } from "crypto";
1564
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1565
+ import { tmpdir as tmpdir2 } from "os";
1566
+ import { join as join3, resolve as resolve2 } from "path";
1567
+ import { pathToFileURL as pathToFileURL2 } from "url";
1568
+ var GEMINI_TTS = { model: "gemini-2.5-flash-preview-tts", voice: "Kore" };
1569
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
1570
+ async function post(f, url, headers, body) {
1571
+ for (let n = 1; ; n += 1) {
1572
+ let res = null;
1573
+ try {
1574
+ res = await f(url, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body) });
1575
+ } catch (e) {
1576
+ if (n >= 3) throw new Error(`could not reach the voice (${e.message})`);
1577
+ }
1578
+ if (res?.ok) return res;
1579
+ if (res) {
1580
+ const text = await res.text();
1581
+ let gw = null;
1582
+ try {
1583
+ const j = JSON.parse(text);
1584
+ if (j?.error?.source === "ai-interface") gw = j.error;
1585
+ } catch {
1586
+ }
1587
+ if (gw) throw new Error(`the AI gateway refused the voice call: ${gw.message}`);
1588
+ if (!(res.status === 429 || res.status >= 500) || n >= 3) throw new Error(`the voice call failed (${res.status}): ${text.slice(0, 300)}`);
1589
+ }
1590
+ await sleep2(Math.min(400 * 2 ** (n - 1) * (0.5 + Math.random() / 2), 4e3));
1591
+ }
1592
+ }
1593
+ function geminiVoice(o) {
1594
+ const model = o.model ?? GEMINI_TTS.model;
1595
+ return async (text) => {
1596
+ const res = await post(
1597
+ o.fetch ?? fetch,
1598
+ `${o.url.replace(/\/+$/, "")}/models/${model}:generateContent`,
1599
+ { ...o.bearer ? { authorization: `Bearer ${o.key}` } : { "x-goog-api-key": o.key }, ...o.headers },
1600
+ {
1601
+ contents: [{ role: "user", parts: [{ text }] }],
1602
+ generationConfig: { responseModalities: ["AUDIO"], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: o.voice ?? GEMINI_TTS.voice } } } }
1603
+ }
1604
+ );
1605
+ const json = await res.json();
1606
+ const part = json.candidates?.[0]?.content?.parts?.find((p) => p.inlineData?.data || p.inline_data?.data);
1607
+ const data = part?.inlineData?.data ?? part?.inline_data?.data;
1608
+ if (!data) throw new Error(`${model} answered without audio`);
1609
+ const mime = part?.inlineData?.mimeType ?? part?.inline_data?.mime_type ?? "";
1610
+ const rate = Number(/rate=(\d+)/.exec(mime)?.[1] ?? 24e3);
1611
+ return { pcm: fromS16le(new Uint8Array(Buffer.from(data, "base64"))), sampleRate: rate };
1612
+ };
1613
+ }
1614
+ function openAiVoice(o) {
1615
+ return async (text) => {
1616
+ const res = await post(
1617
+ o.fetch ?? fetch,
1618
+ `${o.baseUrl.replace(/\/+$/, "")}/audio/speech`,
1619
+ o.key ? { authorization: `Bearer ${o.key}` } : {},
1620
+ { model: o.model, voice: o.voice ?? "alloy", input: text, response_format: "pcm" }
1621
+ );
1622
+ return { pcm: fromS16le(new Uint8Array(await res.arrayBuffer())), sampleRate: 24e3 };
1623
+ };
1624
+ }
1625
+ function sayVoice(o = {}) {
1626
+ return async (text) => {
1627
+ const dir = mkdtempSync2(join3(tmpdir2(), "tar-say-"));
1628
+ try {
1629
+ const file = join3(dir, "line.wav");
1630
+ const r = spawnSync2("say", [...o.voice ? ["-v", o.voice] : [], "-o", file, "--file-format=WAVE", "--data-format=LEI16@24000", text], { encoding: "utf8" });
1631
+ if (r.error || r.status !== 0) throw new Error(`say failed${r.error ? ` (${r.error.message})` : `: ${r.stderr}`}; --voice say needs macOS`);
1632
+ return fromWav(new Uint8Array(readFileSync4(file)));
1633
+ } finally {
1634
+ rmSync2(dir, { recursive: true, force: true });
1635
+ }
1636
+ };
1637
+ }
1638
+ function cached(voice, id, dir) {
1639
+ const v = (async (text) => {
1640
+ const file = join3(dir, `${createHash("sha256").update(`${id}
1641
+ ${text}`).digest("hex").slice(0, 32)}.wav`);
1642
+ if (existsSync2(file)) {
1643
+ v.hits += 1;
1644
+ return fromWav(new Uint8Array(readFileSync4(file)));
1645
+ }
1646
+ const p = await voice(text);
1647
+ v.misses += 1;
1648
+ mkdirSync2(dir, { recursive: true });
1649
+ writeFileSync2(file, toWav(p.pcm, p.sampleRate));
1650
+ return p;
1651
+ });
1652
+ v.hits = 0;
1653
+ v.misses = 0;
1654
+ return v;
1655
+ }
1656
+ async function voiceOf(spec, env = process.env, o = {}) {
1657
+ const cacheDir = o.cacheDir === void 0 ? resolve2(".trace-avatar-cache", "voice") : o.cacheDir;
1658
+ const wrap = (v) => cacheDir ? cached(v, spec, cacheDir) : v;
1659
+ const g = /^gateway(?::gemini(?:\/([^:]+))?(?::(.+))?)?$/.exec(spec);
1660
+ if (g) {
1661
+ if (!env.AI_GATEWAY_URL || !env.AI_GATEWAY_KEY) throw new Error("--voice gateway needs AI_GATEWAY_URL and AI_GATEWAY_KEY");
1662
+ return wrap(geminiVoice({
1663
+ url: `${env.AI_GATEWAY_URL.replace(/\/+$/, "")}/v1/gemini`,
1664
+ key: env.AI_GATEWAY_KEY,
1665
+ bearer: true,
1666
+ ...g[1] ? { model: g[1] } : {},
1667
+ ...g[2] ? { voice: g[2] } : {},
1668
+ headers: { "x-ai-feature": "trace-avatar-voice" },
1669
+ ...o.fetch ? { fetch: o.fetch } : {}
1670
+ }));
1671
+ }
1672
+ const m = /^openai:([^:]+)(?::(.+))?$/.exec(spec);
1673
+ if (m) {
1674
+ if (!env.OPENAI_API_KEY && !env.OPENAI_BASE_URL) throw new Error("--voice openai:\u2026 needs OPENAI_API_KEY (and OPENAI_BASE_URL for another OpenAI-compatible server)");
1675
+ return wrap(openAiVoice({ baseUrl: env.OPENAI_BASE_URL || "https://api.openai.com/v1", ...env.OPENAI_API_KEY ? { key: env.OPENAI_API_KEY } : {}, model: m[1], ...m[2] ? { voice: m[2] } : {}, ...o.fetch ? { fetch: o.fetch } : {} }));
1676
+ }
1677
+ const s = /^say(?::(.+))?$/.exec(spec);
1678
+ if (s) return wrap(sayVoice(s[1] ? { voice: s[1] } : {}));
1679
+ if (/\.(m?js|cjs)$/.test(spec)) {
1680
+ const mod = await import(pathToFileURL2(resolve2(spec)).href);
1681
+ const fn = mod.default ?? mod.voice;
1682
+ if (typeof fn !== "function") throw new Error(`${spec} must export a default function (text) \u2192 { pcm: Int16Array, sampleRate }`);
1683
+ return wrap(fn);
1684
+ }
1685
+ throw new Error(`--voice is gateway[:gemini[/<model>][:<voice>]], openai:<model>[:<voice>], say[:<voice>], or a .js file (got "${spec}")`);
1686
+ }
1687
+
1688
+ export {
1689
+ ZOOM_KINDS,
1690
+ cameraKeys,
1691
+ cameraPath,
1692
+ RenderError,
1693
+ capture,
1694
+ findPlayer,
1695
+ drawRegion,
1696
+ overlay,
1697
+ crossfade,
1698
+ blank,
1699
+ paletteOf,
1700
+ encodeGif,
1701
+ createGifWriter,
1702
+ DEFAULT_BACKGROUND,
1703
+ createLayers,
1704
+ fitWidth,
1705
+ resize,
1706
+ crop,
1707
+ pixel,
1708
+ layoutOf,
1709
+ findFfmpeg,
1710
+ mp4Args,
1711
+ encodeMp4,
1712
+ DEFAULT_MAX_WAIT_MS,
1713
+ spansOf,
1714
+ editList,
1715
+ durationOf,
1716
+ sourceAt,
1717
+ outputAt,
1718
+ withHolds,
1719
+ frameTimes,
1720
+ pickFrames,
1721
+ actionsOf,
1722
+ stepCues,
1723
+ pageAt,
1724
+ cueAt,
1725
+ TRACK_RATE,
1726
+ toWav,
1727
+ fromWav,
1728
+ fromS16le,
1729
+ resample,
1730
+ trimSilence,
1731
+ msOf,
1732
+ mix,
1733
+ linesOf,
1734
+ parseScript,
1735
+ planNarration,
1736
+ narrationText,
1737
+ suggestScript,
1738
+ repairScriptOf,
1739
+ stallInspector,
1740
+ repairGuide,
1741
+ toVtt,
1742
+ captionCues,
1743
+ chapterCues,
1744
+ providerOf,
1745
+ runQa,
1746
+ formatOf,
1747
+ cardOf,
1748
+ render,
1749
+ finish,
1750
+ GEMINI_TTS,
1751
+ geminiVoice,
1752
+ openAiVoice,
1753
+ sayVoice,
1754
+ cached,
1755
+ voiceOf
1756
+ };
1757
+ //# sourceMappingURL=chunk-PE3MNBRB.js.map