trace-avatar-render 0.1.3 → 0.1.5

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/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.5 (unreleased)
4
+
5
+ - **Several shapes from one capture**: `--out file.mp4@1:1` (`OutSpec.canvas` in `render()` and `finish()`) gives
6
+ that output its own canvas, over `--canvas`. A 16:9, a 1:1 and a 4:5 cut of one run need one capture, not three
7
+ (found making SpeedyMessaging's campaign videos: three captures took three times as long, and a Do it for me run
8
+ sent three test messages).
9
+
10
+ ## 0.1.4 (11 Nov 2026)
11
+
12
+ - `--canvas 9:16|4:5|1:1|16:9|WxH` (`canvas` in `render()` and `finish()`): the app is composed onto a picture of that
13
+ shape, between safe margins on the background, for Reels, Stories and feeds.
14
+ - `--width` scales the whole canvas.
15
+ - A phone capture is scaled up to fill a tall canvas, so capture it at `--scale 2`.
16
+ - Burned-in captions are sized to the canvas and sit below the app (above it with `--captions-at top`).
17
+ - `--watermark <text>` and `--watermark-at <corner>` (`watermark: text | { text, at, opacity, logo }`): a small
18
+ badge on every frame, the title and end cards included.
19
+ - It is drawn after the camera, so it never zooms.
20
+ - A burned-in caption that would touch it moves clear of it.
21
+ - **Cards** take `url` (large, in the card's colour) and `logo` (an image file above the title), e.g.
22
+ `{ "title": "For more info visit", "url": "naijaprices.com" }`.
23
+ - `--brand <file.json>` (`brandOf`, `brandFile`): the look in one checked file.
24
+ - It covers canvas, watermark, frame, background, camera, captions, captionsAt, titleCard and endCard.
25
+ - Logo paths resolve beside the file.
26
+ - Flags given on the command line win over it.
27
+
3
28
  ## 0.1.3 (11 Nov 2026)
4
29
 
5
30
  - `--captions-at top|bottom` (`captionsAt` in `render()` and `finish()`): burned-in captions can sit at the top. At
package/README.md CHANGED
@@ -31,7 +31,7 @@ Because the guide is known before it plays, the render can do what a screen reco
31
31
  | | |
32
32
  |---|---|
33
33
  | `--url <url>` | the page the guide starts on (required) |
34
- | `--out <file>` | `.gif` or `.mp4`, repeatable (required) |
34
+ | `--out <file>` | `.gif` or `.mp4`, repeatable (required); `<file>@<shape>` gives that output its own canvas (see `--canvas`), so one capture makes several shapes |
35
35
  | `--mode overlay\|perform` | Show me (default) or Do it for me |
36
36
  | `--allow-perform` | needed for Do it for me: it clicks and types in the app for real. **Use a sandbox account.** |
37
37
  | `--width <px>` | output width (GIF default 800, MP4 the capture's) |
@@ -64,12 +64,39 @@ Because the guide is known before it plays, the render can do what a screen reco
64
64
  | `--poster [file]` | a PNG at the first click (default `<out>.png`) |
65
65
  | `--title-card [title]` | 1.5 s first: the trace's title and the avatar, or your title; fades into the guide |
66
66
  | `--end-card [title]` | 2 s last: "Done", or your text (e.g. a URL) |
67
+ | `--canvas <shape>` | compose onto `9:16` (1080×1920), `4:5`, `1:1`, `16:9` or `WxH`: the app between safe margins on the background, captions sized to the canvas and below the app; `--width` scales the canvas. For a phone-shaped clip, capture at `--viewport 390x844 --scale 2` |
68
+ | `--watermark <text>` | a small badge on every frame, cards included (never zoomed by the camera; captions keep clear of it) |
69
+ | `--watermark-at <corner>` | `top-left`, `top-right`, `bottom-left` or `bottom-right` (default) |
70
+ | `--brand <file.json>` | the look in one file (below); flags given on the command line win over it |
67
71
 
68
72
  ```sh
69
73
  trace-avatar-render invoice.trace.json --url http://localhost:3000/app --out invoice.mp4 \
70
74
  --scale 2 --frame browser --camera --captions both --poster --title-card --end-card "acme.com/invoices"
71
75
  ```
72
76
 
77
+ **A brand** keeps every clip of a product looking the same, in every shape:
78
+
79
+ ```json
80
+ {
81
+ "frame": "browser",
82
+ "background": "linear-gradient(135deg, #e6eefc, #e9f6f1)",
83
+ "watermark": { "text": "Made by Acme", "at": "bottom-right", "logo": "acme-mark.svg" },
84
+ "endCard": { "title": "For more info visit", "url": "acme.com", "logo": "acme-logo.png", "color": "#2456d8" }
85
+ }
86
+ ```
87
+
88
+ ```sh
89
+ trace-avatar-render invoice.trace.json --url http://localhost:3000/app --brand acme.json --canvas 9:16 \
90
+ --viewport 390x844 --scale 2 --captions burn --out invoice-reel.mp4
91
+ ```
92
+
93
+ One capture, several feed shapes:
94
+
95
+ ```sh
96
+ trace-avatar-render invoice.trace.json --url http://localhost:3000/app --brand acme.json --scale 2 \
97
+ --out invoice-wide.mp4@16:9 --out invoice-square.mp4@1:1 --out invoice-feed.mp4@4:5
98
+ ```
99
+
73
100
  Exit codes: 0 rendered, 1 the render failed, 2 wrong usage.
74
101
 
75
102
  **MP4 needs ffmpeg** on the PATH (or `FFMPEG=/path/to/ffmpeg`): `brew install ffmpeg`, `apt install ffmpeg`. GIF
@@ -283,9 +283,9 @@ async function findPlayer(explicit, env = process.env) {
283
283
  if (explicit) return explicit;
284
284
  if (env.TRACE_AVATAR_PLAYER) return env.TRACE_AVATAR_PLAYER;
285
285
  const { createRequire } = await import("module");
286
- const { dirname: dirname3, join: join4 } = await import("path");
286
+ const { dirname: dirname4, join: join4 } = await import("path");
287
287
  const req = createRequire(import.meta.url);
288
- return join4(dirname3(req.resolve("trace-avatar/package.json")), "dist", "trace-perform.min.js");
288
+ return join4(dirname4(req.resolve("trace-avatar/package.json")), "dist", "trace-perform.min.js");
289
289
  }
290
290
 
291
291
  // src/compose.ts
@@ -467,7 +467,16 @@ function same(a, b) {
467
467
  }
468
468
 
469
469
  // src/layers.ts
470
+ import { readFileSync as readFileSync2 } from "fs";
471
+ import { extname } from "path";
470
472
  import { PNG } from "pngjs";
473
+ var MIME = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".svg": "image/svg+xml", ".webp": "image/webp", ".gif": "image/gif" };
474
+ function dataUri(file) {
475
+ if (/^data:/.test(file)) return file;
476
+ const type = MIME[extname(file).toLowerCase()];
477
+ if (!type) throw new Error(`a logo is a PNG, JPEG, SVG, WebP or GIF file (got ${file})`);
478
+ return `data:${type};base64,${readFileSync2(file).toString("base64")}`;
479
+ }
471
480
  var DEFAULT_BACKGROUND = "linear-gradient(135deg, #dfe7fb 0%, #eef0f6 50%, #f6e9f1 100%)";
472
481
  var esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
473
482
  var FONT = "system-ui,-apple-system,'Segoe UI',Roboto,sans-serif";
@@ -491,6 +500,7 @@ async function createLayers(browser) {
491
500
  const bar = l.bar;
492
501
  const r = Math.round(l.width * 0.012);
493
502
  const dot = bar ? Math.round(bar.h * 0.36) : 0;
503
+ const plate = !bar && l.canvas ? `<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>` : "";
494
504
  const chrome = bar ? `
495
505
  <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>
496
506
  <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">
@@ -500,7 +510,7 @@ async function createLayers(browser) {
500
510
  <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>
501
511
  <span style="flex:none;max-width:22%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-weight:600">${esc(o.title ?? "")}</span>
502
512
  </div>` : "";
503
- return shoot(l.width, l.height, `<div style="position:relative;width:100%;height:100%;background:${o.background}">${chrome}</div>`);
513
+ return shoot(l.width, l.height, `<div style="position:relative;width:100%;height:100%;background:${o.background}">${plate}${chrome}</div>`);
504
514
  },
505
515
  async caption(text, o) {
506
516
  const pad = Math.round(o.fontPx * 0.6);
@@ -511,11 +521,18 @@ async function createLayers(browser) {
511
521
  const initial = esc((o.sub ?? o.title).trim().charAt(0).toUpperCase() || "\u2022");
512
522
  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}">
513
523
  <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">
524
+ ${o.logo ? `<img src="${dataUri(o.logo)}" alt="" style="max-height:${Math.round(s * 2)}px;max-width:${Math.round(l.width * 0.4)}px">` : ""}
514
525
  <div style="font:700 ${s}px/1.2 ${FONT}">${esc(o.title)}</div>
526
+ ${o.url ? `<div style="font:800 ${Math.round(s * 0.9)}px/1.15 ${FONT};color:${o.color ?? "#2456d8"};overflow-wrap:anywhere">${esc(o.url)}</div>` : ""}
515
527
  ${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>` : ""}
516
528
  </div>
517
529
  </div>`);
518
530
  },
531
+ async badge(text, o) {
532
+ const f = o.fontPx;
533
+ const logo = o.logo ? `<img src="${dataUri(o.logo)}" alt="" style="height:${Math.round(f * 1.25)}px;width:auto;flex:none">` : "";
534
+ return shoot(f * 40, f * 4, `<div style="display:flex"><div id="b" style="display:inline-flex;align-items:center;gap:${Math.round(f * 0.45)}px;padding:${Math.round(f * 0.4)}px ${Math.round(f * 0.7)}px;border-radius:${Math.round(f * 0.6)}px;background:rgb(15 23 42/.72);color:#fff;font:600 ${f}px/1.1 ${FONT};white-space:nowrap">${logo}<span>${esc(text)}</span></div></div>`, true, "#b");
535
+ },
519
536
  close: () => ctx.close()
520
537
  };
521
538
  }
@@ -578,7 +595,8 @@ function pixel(img, x, y) {
578
595
 
579
596
  // src/layout.ts
580
597
  var even = (n) => Math.max(2, Math.round(n / 2) * 2);
581
- function layoutOf(srcW, srcH, width, frame = "none") {
598
+ function layoutOf(srcW, srcH, width, frame = "none", canvas) {
599
+ if (canvas) return onCanvas(srcW, srcH, width, frame, canvas);
582
600
  if (frame === "none") {
583
601
  const { width: W2, height: H2 } = fitWidth(srcW, srcH, width);
584
602
  const r = { x: 0, y: 0, w: W2, h: H2 };
@@ -599,6 +617,131 @@ function layoutOf(srcW, srcH, width, frame = "none") {
599
617
  window: { x: pad, y: top, w: cw, h: barH + ch }
600
618
  };
601
619
  }
620
+ function onCanvas(srcW, srcH, width, frame, canvas) {
621
+ const W = even(width ? Math.min(width, canvas.width) : canvas.width);
622
+ const H = even(canvas.height * W / canvas.width);
623
+ const tall = H / W > 1.2;
624
+ const padX = Math.round(W * 0.05);
625
+ const top = Math.round(H * (tall ? 0.1 : 0.07));
626
+ const bottom = Math.round(H * (tall ? 0.16 : 0.09));
627
+ const boxW = W - 2 * padX;
628
+ const boxH = H - top - bottom;
629
+ const barK = frame === "browser" ? 0.039 : 0;
630
+ const cw = Math.max(2, Math.floor(Math.min(boxW, boxH / (srcH / srcW + barK))));
631
+ const ch = Math.max(2, Math.round(srcH * cw / srcW));
632
+ const barH = frame === "browser" ? Math.max(18, Math.round(cw * barK)) : 0;
633
+ const x = Math.round((W - cw) / 2);
634
+ const y = top + Math.max(0, Math.round((boxH - ch - barH) / 2));
635
+ return {
636
+ width: W,
637
+ height: H,
638
+ bar: frame === "browser" ? { x, y, w: cw, h: barH } : null,
639
+ content: { x, y: y + barH, w: cw, h: ch },
640
+ window: { x, y, w: cw, h: barH + ch },
641
+ canvas: true
642
+ };
643
+ }
644
+
645
+ // src/brand.ts
646
+ import { readFileSync as readFileSync3 } from "fs";
647
+ import { dirname, isAbsolute, resolve } from "path";
648
+ var CANVASES = {
649
+ "9:16": { width: 1080, height: 1920 },
650
+ "4:5": { width: 1080, height: 1350 },
651
+ "1:1": { width: 1080, height: 1080 },
652
+ "16:9": { width: 1920, height: 1080 }
653
+ };
654
+ var CORNERS = ["top-left", "top-right", "bottom-left", "bottom-right"];
655
+ function canvasOf(v) {
656
+ if (typeof v === "object" && v) {
657
+ if (!(Number.isInteger(v.width) && Number.isInteger(v.height) && v.width >= 16 && v.height >= 16)) throw new Error("a canvas is { width, height } in whole pixels, at least 16");
658
+ return { width: v.width, height: v.height };
659
+ }
660
+ if (CANVASES[v]) return CANVASES[v];
661
+ const m = /^(\d+)x(\d+)$/i.exec(String(v));
662
+ if (!m || Number(m[1]) < 16 || Number(m[2]) < 16) throw new Error(`a canvas is ${Object.keys(CANVASES).join(", ")} or WIDTHxHEIGHT (got ${String(v)})`);
663
+ return { width: Number(m[1]), height: Number(m[2]) };
664
+ }
665
+ function watermarkOf(v) {
666
+ const w = typeof v === "string" ? { text: v } : v;
667
+ if (!w || typeof w.text !== "string" || !w.text.trim()) throw new Error("a watermark needs its text");
668
+ if (w.at !== void 0 && !CORNERS.includes(w.at)) throw new Error(`a watermark sits at ${CORNERS.join(", ")}`);
669
+ if (w.opacity !== void 0 && !(w.opacity > 0 && w.opacity <= 1)) throw new Error("a watermark's opacity is above 0, up to 1");
670
+ return { ...w, text: w.text.trim() };
671
+ }
672
+ var KEYS = ["$comment", "name", "canvas", "watermark", "frame", "background", "camera", "captions", "captionsAt", "titleCard", "endCard"];
673
+ function brandOf(json, dir = ".") {
674
+ if (!json || typeof json !== "object" || Array.isArray(json)) throw new Error("a brand is a JSON object");
675
+ const b = json;
676
+ const problems = [];
677
+ for (const k of Object.keys(b)) if (!KEYS.includes(k)) problems.push(`unknown key ${k}`);
678
+ const out = {};
679
+ const at = (p) => p && !isAbsolute(p) && !/^data:/.test(p) ? resolve(dir, p) : p;
680
+ const card = (v, name) => {
681
+ if (typeof v === "boolean" || typeof v === "string") return v;
682
+ if (v && typeof v === "object" && typeof v.title === "string") {
683
+ const c = v;
684
+ return { ...c, ...c.logo ? { logo: at(c.logo) } : {} };
685
+ }
686
+ problems.push(`${name} is true, a title, or { title, sub?, url?, logo?, color? }`);
687
+ return void 0;
688
+ };
689
+ const tryIt = (f) => {
690
+ try {
691
+ f();
692
+ } catch (e) {
693
+ problems.push(e.message);
694
+ }
695
+ };
696
+ if (b.canvas !== void 0) tryIt(() => {
697
+ canvasOf(b.canvas);
698
+ out.canvas = b.canvas;
699
+ });
700
+ if (b.watermark !== void 0) tryIt(() => {
701
+ const w = watermarkOf(b.watermark);
702
+ out.watermark = { ...w, ...w.logo ? { logo: at(w.logo) } : {} };
703
+ });
704
+ if (b.frame !== void 0) {
705
+ if (b.frame === "none" || b.frame === "browser") out.frame = b.frame;
706
+ else problems.push("frame is none or browser");
707
+ }
708
+ if (b.background !== void 0) {
709
+ if (typeof b.background === "string") out.background = b.background;
710
+ else problems.push("background is a CSS colour or gradient");
711
+ }
712
+ if (b.camera !== void 0) {
713
+ const z = b.camera?.zoom;
714
+ if (typeof b.camera === "boolean" || typeof b.camera === "object" && b.camera && (z === void 0 || typeof z === "number" && z >= 1)) out.camera = b.camera;
715
+ else problems.push("camera is true, false or { zoom \u2265 1 }");
716
+ }
717
+ if (b.captions !== void 0) {
718
+ if (["burn", "vtt", "both"].includes(b.captions)) out.captions = b.captions;
719
+ else problems.push("captions is burn, vtt or both");
720
+ }
721
+ if (b.captionsAt !== void 0) {
722
+ if (b.captionsAt === "top" || b.captionsAt === "bottom") out.captionsAt = b.captionsAt;
723
+ else problems.push("captionsAt is top or bottom");
724
+ }
725
+ if (b.titleCard !== void 0) {
726
+ const c = card(b.titleCard, "titleCard");
727
+ if (c !== void 0) out.titleCard = c;
728
+ }
729
+ if (b.endCard !== void 0) {
730
+ const c = card(b.endCard, "endCard");
731
+ if (c !== void 0) out.endCard = c;
732
+ }
733
+ if (problems.length) throw new Error(`brand: ${problems.join("; ")}`);
734
+ return out;
735
+ }
736
+ function brandFile(file) {
737
+ let json;
738
+ try {
739
+ json = JSON.parse(readFileSync3(file, "utf8"));
740
+ } catch (e) {
741
+ throw new Error(`brand ${file}: ${e.message}`);
742
+ }
743
+ return brandOf(json, dirname(resolve(file)));
744
+ }
602
745
 
603
746
  // src/mp4.ts
604
747
  import { spawn, spawnSync } from "child_process";
@@ -652,9 +795,9 @@ async function encodeMp4(frames, o) {
652
795
  p.stderr.on("data", (d) => {
653
796
  err += String(d);
654
797
  });
655
- const done = new Promise((resolve3, reject) => {
798
+ const done = new Promise((resolve4, reject) => {
656
799
  p.on("error", reject);
657
- p.on("close", (code) => code === 0 ? resolve3() : reject(new Error(`ffmpeg exited with ${code}: ${err.trim()}`)));
800
+ p.on("close", (code) => code === 0 ? resolve4() : reject(new Error(`ffmpeg exited with ${code}: ${err.trim()}`)));
658
801
  });
659
802
  p.stdin.on("error", () => {
660
803
  });
@@ -1031,16 +1174,16 @@ async function suggestScript(ai, trace) {
1031
1174
  }
1032
1175
 
1033
1176
  // src/repair.ts
1034
- import { existsSync, readFileSync as readFileSync2 } from "fs";
1035
- import { dirname, join } from "path";
1177
+ import { existsSync, readFileSync as readFileSync4 } from "fs";
1178
+ import { dirname as dirname2, join } from "path";
1036
1179
  import { applyRaw, chooseRepair, chooseWait, guessWait, repairSuggestion, typedOf, waitSuggestion } from "trace-avatar/assist";
1037
1180
  function repairScriptOf(playerFile) {
1038
- const file = join(dirname(playerFile), "trace-repair.min.js");
1181
+ const file = join(dirname2(playerFile), "trace-repair.min.js");
1039
1182
  if (!existsSync(file)) throw new RenderError(`--repair needs trace-avatar 0.1.7 or later (no ${file})`);
1040
1183
  return file;
1041
1184
  }
1042
1185
  function stallInspector(o) {
1043
- const code = `${readFileSync2(o.script, "utf8")}
1186
+ const code = `${readFileSync4(o.script, "utf8")}
1044
1187
  ;window.__taRepair = TraceAvatarRepair;`;
1045
1188
  return async (page, stall) => {
1046
1189
  if (stall.reason === "until-timeout") return waitInspect(page, stall.index);
@@ -1164,7 +1307,7 @@ function chapterCues(starts, endMs) {
1164
1307
  }
1165
1308
 
1166
1309
  // src/ai.ts
1167
- import { resolve } from "path";
1310
+ import { resolve as resolve2 } from "path";
1168
1311
  import { pathToFileURL } from "url";
1169
1312
  import { gateway, openAiCompatible } from "trace-avatar/assist";
1170
1313
  async function providerOf(spec, env = process.env, o = {}) {
@@ -1185,7 +1328,7 @@ async function providerOf(spec, env = process.env, o = {}) {
1185
1328
  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 });
1186
1329
  }
1187
1330
  if (/\.(m?js|cjs)$/.test(spec)) {
1188
- const mod = await import(pathToFileURL(resolve(spec)).href);
1331
+ const mod = await import(pathToFileURL(resolve2(spec)).href);
1189
1332
  const fn = mod.default ?? mod.ai;
1190
1333
  if (typeof fn !== "function") throw new Error(`${spec} must export a default function (task, input, schema, { instructions, images }) \u2192 JSON`);
1191
1334
  return fn;
@@ -1221,14 +1364,14 @@ async function runQa(ai, frames, context) {
1221
1364
  }
1222
1365
 
1223
1366
  // src/render.ts
1224
- import { readFileSync as readFileSync3, writeFileSync, mkdirSync, mkdtempSync, rmSync } from "fs";
1367
+ import { readFileSync as readFileSync5, writeFileSync, mkdirSync, mkdtempSync, rmSync } from "fs";
1225
1368
  import { tmpdir } from "os";
1226
- import { dirname as dirname2, extname, join as join2 } from "path";
1369
+ import { dirname as dirname3, extname as extname2, join as join2 } from "path";
1227
1370
  import { chromium as chromium2 } from "playwright";
1228
1371
  import { PNG as PNG2 } from "pngjs";
1229
1372
  import { describe as describeGuide } from "trace-avatar/assist";
1230
1373
  var formatOf = (file) => {
1231
- const ext = extname(file).toLowerCase();
1374
+ const ext = extname2(file).toLowerCase();
1232
1375
  if (ext === ".gif") return "gif";
1233
1376
  if (ext === ".mp4") return "mp4";
1234
1377
  throw new RenderError(`unknown output "${file}": use .gif or .mp4`);
@@ -1244,7 +1387,7 @@ function cardOf(v, fallback) {
1244
1387
  return { ...fallback, ...v };
1245
1388
  }
1246
1389
  async function render(o) {
1247
- const trace = typeof o.trace === "string" ? JSON.parse(readFileSync3(o.trace, "utf8")) : o.trace;
1390
+ const trace = typeof o.trace === "string" ? JSON.parse(readFileSync5(o.trace, "utf8")) : o.trace;
1248
1391
  if (!trace || typeof trace !== "object") throw new RenderError("the trace must be an object or a .trace.json path");
1249
1392
  const mode = o.mode ?? "overlay";
1250
1393
  if (mode === "perform" && !o.allowPerform) {
@@ -1259,7 +1402,7 @@ async function render(o) {
1259
1402
  const burn = o.captions === "burn" || o.captions === "both";
1260
1403
  if ((o.qa || o.alt) && !o.ai) throw new RenderError("qa and alt need an AI: pass ai (--ai)");
1261
1404
  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)");
1262
- 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;
1405
+ const spoken = o.voice ? linesOf(trace.steps ?? [], o.script === void 0 ? void 0 : parseScript(typeof o.script === "string" ? JSON.parse(readFileSync5(o.script, "utf8")) : o.script)) : null;
1263
1406
  if (spoken && !spoken.size) throw new RenderError("nothing to say: no step has a caption (say), and no script was given");
1264
1407
  if (o.repairVision && !(o.repair && o.ai)) throw new RenderError("repairVision needs repair and an AI");
1265
1408
  const capOpts = {
@@ -1293,7 +1436,7 @@ async function render(o) {
1293
1436
  if (!(o.repair && e instanceof RenderError && e.stall)) throw e;
1294
1437
  const outcome = await repairGuide({ trace, capture: capOpts, ...o.ai ? { ai: o.ai } : {}, ...o.repairVision ? { vision: true } : {}, first: e });
1295
1438
  const file = `${base(outs[0].file)}.repair.json`;
1296
- mkdirSync(dirname2(file) || ".", { recursive: true });
1439
+ mkdirSync(dirname3(file) || ".", { recursive: true });
1297
1440
  writeFileSync(file, `${JSON.stringify({ task: "repair", suggestions: outcome.suggestions, unresolved: outcome.unresolved, passed: outcome.passed }, null, 2)}
1298
1441
  `);
1299
1442
  const n = outcome.suggestions.length;
@@ -1384,6 +1527,9 @@ async function finish(cap, outs, o = {}) {
1384
1527
  const srcH = first.height;
1385
1528
  const scale = cap.viewport ? srcW / cap.viewport.w : 1;
1386
1529
  const frameStyle = o.frame ?? "none";
1530
+ const canvas = o.canvas !== void 0 ? canvasOf(o.canvas) : void 0;
1531
+ const canvases = outs.map((x) => x.canvas !== void 0 ? canvasOf(x.canvas) : canvas);
1532
+ const mark = o.watermark !== void 0 ? watermarkOf(o.watermark) : void 0;
1387
1533
  const background = o.background ?? DEFAULT_BACKGROUND;
1388
1534
  const burn = o.captions === "burn" || o.captions === "both";
1389
1535
  const variant = (sg) => {
@@ -1402,7 +1548,7 @@ async function finish(cap, outs, o = {}) {
1402
1548
  const titleMs = o.cards?.title ? TITLE_MS : 0;
1403
1549
  const endMs = o.cards?.end ? END_MS : 0;
1404
1550
  const full = { x: 0, y: 0, w: srcW, h: srcH };
1405
- const needLayers = frameStyle !== "none" || burn && (cues.length > 0 || plain.cues.length > 0) || !!o.cards?.title || !!o.cards?.end;
1551
+ const needLayers = frameStyle !== "none" || canvases.some(Boolean) || !!mark || burn && (cues.length > 0 || plain.cues.length > 0) || !!o.cards?.title || !!o.cards?.end;
1406
1552
  const browser = needLayers ? await chromium2.launch() : null;
1407
1553
  let layers = null;
1408
1554
  const outputs = [];
@@ -1413,15 +1559,15 @@ async function finish(cap, outs, o = {}) {
1413
1559
  try {
1414
1560
  layers = browser ? await createLayers(browser) : null;
1415
1561
  for (const [n, out] of outs.entries()) {
1416
- mkdirSync(dirname2(out.file) || ".", { recursive: true });
1562
+ mkdirSync(dirname3(out.file) || ".", { recursive: true });
1417
1563
  const fps = out.fps ?? (out.format === "gif" ? 12 : 30);
1418
- const layout = layoutOf(srcW, srcH, out.width ?? (out.format === "gif" ? 800 : void 0), frameStyle);
1564
+ const layout = layoutOf(srcW, srcH, out.width ?? (out.format === "gif" ? 800 : void 0), frameStyle, canvases[n]);
1419
1565
  const v = out.format === "gif" ? plain : main;
1420
1566
  const { cam, segs: segs2, contentMs: contentMs2 } = v;
1421
1567
  const cues2 = v.cues;
1422
1568
  const times = frameTimes(segs2, fps);
1423
1569
  const picks = pickFrames(stamps, times);
1424
- 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 });
1570
+ 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, mark });
1425
1571
  const nTitle = Math.round(titleMs * fps / 1e3);
1426
1572
  const nEnd = Math.round(endMs * fps / 1e3);
1427
1573
  const nFade = Math.max(1, Math.round(FADE_MS * fps / 1e3));
@@ -1441,9 +1587,22 @@ async function finish(cap, outs, o = {}) {
1441
1587
  if (c && alpha > 0) {
1442
1588
  const img = art.captions.get(c.cue.text);
1443
1589
  const gap = Math.round(layout.content.h * 0.05);
1444
- const y = img && (o.captionsAt === "top" ? layout.content.y + gap : layout.content.y + layout.content.h - img.height - gap);
1445
- if (img && y !== void 0) overlay(dst, img, layout.content.x + (layout.content.w - img.width) / 2, y, alpha);
1590
+ let y = img && (o.captionsAt === "top" ? layout.content.y + gap : layout.content.y + layout.content.h - img.height - gap);
1591
+ if (img && layout.canvas) {
1592
+ const g2 = Math.round(layout.height * 0.02);
1593
+ const below = layout.window.y + layout.window.h + g2;
1594
+ const above = layout.window.y - g2 - img.height;
1595
+ if (o.captionsAt === "top" ? above >= g2 : below + img.height <= layout.height - g2) y = o.captionsAt === "top" ? above : below;
1596
+ }
1597
+ const x = img ? layout.canvas ? (layout.width - img.width) / 2 : layout.content.x + (layout.content.w - img.width) / 2 : 0;
1598
+ if (img && y !== void 0 && art.badge) {
1599
+ const b = art.badge;
1600
+ const touches = x < b.x + b.img.width && x + img.width > b.x && y < b.y + b.img.height && y + img.height > b.y;
1601
+ if (touches) y = b.y < layout.height / 2 ? b.y + b.img.height + Math.round(gap / 2) : b.y - img.height - Math.round(gap / 2);
1602
+ }
1603
+ if (img && y !== void 0) overlay(dst, img, x, y, alpha);
1446
1604
  }
1605
+ if (art.badge) overlay(dst, art.badge.img, art.badge.x, art.badge.y, art.badge.alpha);
1447
1606
  last = { key, img: dst };
1448
1607
  return dst;
1449
1608
  };
@@ -1475,13 +1634,13 @@ async function finish(cap, outs, o = {}) {
1475
1634
  audio = join2(tmp, `${n}.wav`);
1476
1635
  writeFileSync(audio, toWav(track, TRACK_RATE));
1477
1636
  if (narr.out && !wav) {
1478
- mkdirSync(dirname2(narr.out) || ".", { recursive: true });
1637
+ mkdirSync(dirname3(narr.out) || ".", { recursive: true });
1479
1638
  writeFileSync(narr.out, toWav(track, TRACK_RATE));
1480
1639
  wav = narr.out;
1481
1640
  }
1482
1641
  }
1483
1642
  await encodeMp4(all(), { file: out.file, fps, width: layout.width, height: layout.height, ...audio ? { audio } : {} });
1484
- 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) });
1643
+ outputs.push({ file: out.file, format: "mp4", width: layout.width, height: layout.height, fps, frames: total, bytes: readFileSync5(out.file).length, durationMs: Math.round(total * 1e3 / fps) });
1485
1644
  }
1486
1645
  if (n === 0 && o.poster) {
1487
1646
  const click = cap.events.find((e) => e.type === "step" && (e.stepType === "click" || e.stepType === "dblclick"));
@@ -1492,7 +1651,7 @@ async function finish(cap, outs, o = {}) {
1492
1651
  const png = new PNG2({ width: img.width, height: img.height });
1493
1652
  png.data.set(img.data);
1494
1653
  poster = typeof o.poster === "string" ? o.poster : `${base(out.file)}.png`;
1495
- mkdirSync(dirname2(poster) || ".", { recursive: true });
1654
+ mkdirSync(dirname3(poster) || ".", { recursive: true });
1496
1655
  writeFileSync(poster, PNG2.sync.write(png));
1497
1656
  }
1498
1657
  if (n === 0 && o.qa) {
@@ -1551,7 +1710,7 @@ async function finish(cap, outs, o = {}) {
1551
1710
  ...warnings.length ? { warnings } : {}
1552
1711
  };
1553
1712
  if (o.timeline) {
1554
- mkdirSync(dirname2(o.timeline) || ".", { recursive: true });
1713
+ mkdirSync(dirname3(o.timeline) || ".", { recursive: true });
1555
1714
  writeFileSync(o.timeline, JSON.stringify(result, null, 2));
1556
1715
  }
1557
1716
  return result;
@@ -1564,28 +1723,46 @@ function namedChapters(names, events, segs, endMs) {
1564
1723
  }).sort((a, b) => a.t - b.t);
1565
1724
  return starts.map((c, k) => ({ start: c.t, end: starts[k + 1]?.t ?? endMs, text: c.text }));
1566
1725
  }
1726
+ function badgeAt(W, H, w, h, at = "bottom-right") {
1727
+ const m = Math.round(Math.min(W, H) * 0.025);
1728
+ return { x: at.endsWith("left") ? m : W - w - m, y: at.startsWith("top") ? m : H - h - m };
1729
+ }
1567
1730
  async function artFor(layers, layout, o) {
1568
1731
  const art = { base: null, captions: /* @__PURE__ */ new Map() };
1569
1732
  if (!layers) return art;
1570
- if (o.frameStyle !== "none") {
1733
+ if (o.frameStyle !== "none" || layout.canvas) {
1571
1734
  art.base = /* @__PURE__ */ new Map();
1572
1735
  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] }));
1573
1736
  }
1574
- const fontPx = Math.max(12, Math.round(layout.content.w * 0.026));
1737
+ const fontPx = layout.canvas ? Math.max(12, Math.round(layout.width * 0.034)) : Math.max(12, Math.round(layout.content.w * 0.026));
1738
+ const maxWidth = Math.round(layout.canvas ? layout.width * 0.9 : layout.content.w * 0.8);
1575
1739
  for (const c of o.cues) {
1576
- 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 }));
1740
+ if (!art.captions.has(c.text)) art.captions.set(c.text, await layers.caption(c.text, { maxWidth, fontPx }));
1577
1741
  }
1578
1742
  if (o.cards?.title) art.title = await layers.card(layout, { ...o.cards.title, background: o.background });
1579
1743
  if (o.cards?.end) art.end = await layers.card(layout, { ...o.cards.end, background: o.background });
1744
+ if (o.mark) {
1745
+ const img = await layers.badge(o.mark.text, { fontPx: Math.max(11, Math.round(Math.min(layout.width, layout.height) * 0.024)), ...o.mark.logo ? { logo: o.mark.logo } : {} });
1746
+ const { x, y } = badgeAt(layout.width, layout.height, img.width, img.height, o.mark.at);
1747
+ art.badge = { img, x, y, alpha: o.mark.opacity ?? 0.9 };
1748
+ for (const k of ["title", "end"]) {
1749
+ const c = art[k];
1750
+ if (c) {
1751
+ const d = copy(c);
1752
+ overlay(d, img, x, y, art.badge.alpha);
1753
+ art[k] = d;
1754
+ }
1755
+ }
1756
+ }
1580
1757
  return art;
1581
1758
  }
1582
1759
 
1583
1760
  // src/voice.ts
1584
1761
  import { spawnSync as spawnSync2 } from "child_process";
1585
1762
  import { createHash } from "crypto";
1586
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync4, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1763
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, mkdtempSync as mkdtempSync2, readFileSync as readFileSync6, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";
1587
1764
  import { tmpdir as tmpdir2 } from "os";
1588
- import { join as join3, resolve as resolve2 } from "path";
1765
+ import { join as join3, resolve as resolve3 } from "path";
1589
1766
  import { pathToFileURL as pathToFileURL2 } from "url";
1590
1767
  var GEMINI_TTS = { model: "gemini-2.5-flash-preview-tts", voice: "Kore" };
1591
1768
  var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1651,7 +1828,7 @@ function sayVoice(o = {}) {
1651
1828
  const file = join3(dir, "line.wav");
1652
1829
  const r = spawnSync2("say", [...o.voice ? ["-v", o.voice] : [], "-o", file, "--file-format=WAVE", "--data-format=LEI16@24000", text], { encoding: "utf8" });
1653
1830
  if (r.error || r.status !== 0) throw new Error(`say failed${r.error ? ` (${r.error.message})` : `: ${r.stderr}`}; --voice say needs macOS`);
1654
- return fromWav(new Uint8Array(readFileSync4(file)));
1831
+ return fromWav(new Uint8Array(readFileSync6(file)));
1655
1832
  } finally {
1656
1833
  rmSync2(dir, { recursive: true, force: true });
1657
1834
  }
@@ -1663,7 +1840,7 @@ function cached(voice, id, dir) {
1663
1840
  ${text}`).digest("hex").slice(0, 32)}.wav`);
1664
1841
  if (existsSync2(file)) {
1665
1842
  v.hits += 1;
1666
- return fromWav(new Uint8Array(readFileSync4(file)));
1843
+ return fromWav(new Uint8Array(readFileSync6(file)));
1667
1844
  }
1668
1845
  const p = await voice(text);
1669
1846
  v.misses += 1;
@@ -1676,7 +1853,7 @@ ${text}`).digest("hex").slice(0, 32)}.wav`);
1676
1853
  return v;
1677
1854
  }
1678
1855
  async function voiceOf(spec, env = process.env, o = {}) {
1679
- const cacheDir = o.cacheDir === void 0 ? resolve2(".trace-avatar-cache", "voice") : o.cacheDir;
1856
+ const cacheDir = o.cacheDir === void 0 ? resolve3(".trace-avatar-cache", "voice") : o.cacheDir;
1680
1857
  const wrap = (v) => cacheDir ? cached(v, spec, cacheDir) : v;
1681
1858
  const g = /^gateway(?::gemini(?:\/([^:]+))?(?::(.+))?)?$/.exec(spec);
1682
1859
  if (g) {
@@ -1699,7 +1876,7 @@ async function voiceOf(spec, env = process.env, o = {}) {
1699
1876
  const s = /^say(?::(.+))?$/.exec(spec);
1700
1877
  if (s) return wrap(sayVoice(s[1] ? { voice: s[1] } : {}));
1701
1878
  if (/\.(m?js|cjs)$/.test(spec)) {
1702
- const mod = await import(pathToFileURL2(resolve2(spec)).href);
1879
+ const mod = await import(pathToFileURL2(resolve3(spec)).href);
1703
1880
  const fn = mod.default ?? mod.voice;
1704
1881
  if (typeof fn !== "function") throw new Error(`${spec} must export a default function (text) \u2192 { pcm: Int16Array, sampleRate }`);
1705
1882
  return wrap(fn);
@@ -1721,6 +1898,7 @@ export {
1721
1898
  paletteOf,
1722
1899
  encodeGif,
1723
1900
  createGifWriter,
1901
+ dataUri,
1724
1902
  DEFAULT_BACKGROUND,
1725
1903
  createLayers,
1726
1904
  fitWidth,
@@ -1728,6 +1906,12 @@ export {
1728
1906
  crop,
1729
1907
  pixel,
1730
1908
  layoutOf,
1909
+ CANVASES,
1910
+ CORNERS,
1911
+ canvasOf,
1912
+ watermarkOf,
1913
+ brandOf,
1914
+ brandFile,
1731
1915
  findFfmpeg,
1732
1916
  mp4Args,
1733
1917
  encodeMp4,
@@ -1769,6 +1953,7 @@ export {
1769
1953
  cardOf,
1770
1954
  render,
1771
1955
  finish,
1956
+ badgeAt,
1772
1957
  GEMINI_TTS,
1773
1958
  geminiVoice,
1774
1959
  openAiVoice,
@@ -1776,4 +1961,4 @@ export {
1776
1961
  cached,
1777
1962
  voiceOf
1778
1963
  };
1779
- //# sourceMappingURL=chunk-JVSMXA44.js.map
1964
+ //# sourceMappingURL=chunk-OYFQTEVA.js.map