trace-avatar-render 0.1.6 → 0.1.7

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/dist/cli.js CHANGED
@@ -4,12 +4,13 @@ import {
4
4
  RenderError,
5
5
  brandFile,
6
6
  canvasOf,
7
+ checkCatalogue,
7
8
  providerOf,
8
9
  render,
9
10
  suggestScript,
10
11
  voiceOf,
11
12
  watermarkOf
12
- } from "./chunk-ZNHFXKD3.js";
13
+ } from "./chunk-PPVNEPXF.js";
13
14
 
14
15
  // src/cli.ts
15
16
  import { existsSync, readFileSync, writeFileSync } from "fs";
@@ -85,6 +86,11 @@ Suggestions for a person to accept (the renderer never changes a trace):
85
86
  trace-avatar-render suggest <trace.json> --task captions|title|waits|narration --ai <provider> [--tone friendly|terse|formal]
86
87
  [--hints hints.json] [--out suggestions.json]
87
88
  trace-avatar-render apply <trace.json> <suggestions.json> --accept 1,3|all --out <new.trace.json>
89
+
90
+ A clip catalogue (trace-avatar-catalogue/1, schemas/catalogue-1.json):
91
+ trace-avatar-render catalogue check <file.json|https://\u2026> [--fetch] [--json]
92
+ --fetch: fetch every link too (reachable, its type, captions within the video, mp4 head)
93
+ --allow-http: accept http:// links (a local test server)
88
94
  `;
89
95
  function parse(argv) {
90
96
  const extra = {};
@@ -296,9 +302,9 @@ function reportOf(err, traceFile, repairFile) {
296
302
  var UsageError = class extends Error {
297
303
  };
298
304
  async function main(argv, io = { log: console.log, error: console.error }) {
299
- if (argv[0] === "suggest" || argv[0] === "apply") {
305
+ if (argv[0] === "suggest" || argv[0] === "apply" || argv[0] === "catalogue") {
300
306
  try {
301
- return await (argv[0] === "suggest" ? suggestCmd(argv.slice(1), io) : applyCmd(argv.slice(1), io));
307
+ return await (argv[0] === "suggest" ? suggestCmd(argv.slice(1), io) : argv[0] === "apply" ? applyCmd(argv.slice(1), io) : catalogueCmd(argv.slice(1), io));
302
308
  } catch (e) {
303
309
  io.error(`trace-avatar-render ${argv[0]}: ${e.message}`);
304
310
  if (e instanceof UsageError) io.error(USAGE);
@@ -415,6 +421,29 @@ async function applyCmd(argv, io) {
415
421
  io.log(`applied ${ids.length} of ${all.length} to ${values.out}`);
416
422
  return 0;
417
423
  }
424
+ async function catalogueCmd(argv, io) {
425
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { fetch: { type: "boolean" }, json: { type: "boolean" }, "allow-http": { type: "boolean" } } });
426
+ const [sub, where] = positionals;
427
+ if (sub !== "check" || !where) throw new UsageError("catalogue check needs a file or a link");
428
+ let doc;
429
+ if (/^https?:\/\//.test(where)) {
430
+ const res = await fetch(where);
431
+ if (!res.ok) throw new Error(`${where} answered ${res.status}`);
432
+ doc = await res.json();
433
+ } else {
434
+ if (!existsSync(where)) throw new UsageError(`no file ${where}`);
435
+ doc = readJson(where);
436
+ }
437
+ const r = await checkCatalogue(doc, { fetch: !!values.fetch, allowHttp: !!values["allow-http"] });
438
+ if (values.json) {
439
+ io.log(JSON.stringify(r, null, 2));
440
+ return r.ok ? 0 : 1;
441
+ }
442
+ for (const p of r.problems) io.error(`\u2717 ${p}`);
443
+ for (const w of r.warnings) io.log(`warning: ${w}`);
444
+ io.log(`${where}: ${r.videos} video${r.videos === 1 ? "" : "s"}${values.fetch ? `, ${r.fetched} link${r.fetched === 1 ? "" : "s"} fetched` : ""} \u2014 ${r.ok ? "keeps trace-avatar-catalogue/1" : `${r.problems.length} problem${r.problems.length === 1 ? "" : "s"}`}${r.warnings.length ? `, ${r.warnings.length} warning${r.warnings.length === 1 ? "" : "s"}` : ""}`);
445
+ return r.ok ? 0 : 1;
446
+ }
418
447
  var isMain = import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith("/trace-avatar-render") || process.argv[1]?.endsWith("/cli.js");
419
448
  if (isMain) void main(process.argv.slice(2)).then((code) => {
420
449
  process.exitCode = code;
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * trace-avatar-render invoice.trace.json --url http://localhost:3000/app --out invoice.gif --out invoice.mp4\n *\n * Exit codes: 0 rendered, 1 the render failed (a stalled guide, an error in the app), 2 wrong usage.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { apply as applySuggestions, suggest } from 'trace-avatar/assist';\nimport type { Suggestion } from 'trace-avatar/assist';\nimport { providerOf } from './ai';\nimport { suggestScript } from './narration';\nimport { voiceOf } from './voice';\nimport { parseArgs } from 'node:util';\nimport { RenderError } from './capture';\nimport { render } from './render';\nimport { brandFile, canvasOf, CORNERS, watermarkOf } from './brand';\nimport type { Corner, Watermark } from './brand';\n\nexport const USAGE = `Usage: trace-avatar-render <trace.json> --url <page> --out <file.gif|file.mp4> [options]\n\n --url <url> the page the guide starts on (required)\n --out <file> .gif or .mp4; repeat for several (required). <file>@<shape> gives that output its own\n canvas (e.g. --out wide.mp4@16:9 --out square.mp4@1:1): several shapes from one capture\n --mode <overlay|perform> Show me (default) or Do it for me\n --allow-perform needed for perform: it clicks and types for real (use a sandbox account)\n --width <px> output width (GIF default 800, MP4 the capture's)\n --fps <n> frames per second (GIF default 12, MP4 30)\n --viewport <WxH> default: the trace's meta.viewport, else 1280x800\n --scale <n> device pixel ratio of the capture (2 for crisp video)\n --storage-state <file> a signed-in Playwright session\n --max-wait <ms> waits longer than this are cut to it (default 800, 0 keeps them)\n --hide <selector> hidden before capture; repeatable\n --blur <selector> blurred before capture (as well as [data-trace-blur]); repeatable\n --allow-stall render a stalled guide anyway instead of failing\n --navigate a step on another page: load that page, as the app's router would (without it, a\n Show me guide that crosses pages waits on \"Open … to continue\")\n --security [guards] perform: leave these to the viewer (a hand-off): all, or secrets,money,files\n --value <name=text> perform: a value to type, by name or field label (e.g. password=demo-pass); repeatable\n --player <file> the trace-perform.min.js to use (default: the installed trace-avatar)\n --timeline <file> write the timeline and the cuts as JSON\n --timeout <ms> give up after this long (default 120000)\n --report <file> write what happened as JSON: { outcome: passed|stalled|failed, step, reason, message }\n (for CI: one result per guide, whatever the exit code)\n --headed show the browser\n\n Polish (all off by default):\n --frame <none|browser> a browser window around the app, on a background\n --background <css> the background behind the window and on the cards\n --camera zoom in on each action and pan between close ones\n --zoom <n> how far the camera goes in (default 1.6; implies --camera)\n --captions <burn|vtt|both> burn the steps' words in, write <out>.vtt + <out>.chapters.vtt, or both\n --captions-at <top|bottom> where burned-in captions sit (default bottom; top when the app's own UI is low)\n --poster [file] a PNG at the first click (default <out>.png)\n --title-card [title] a 1.5 s card first (default: the trace's title)\n --end-card [title] a 2 s card last (default: \"Done\")\n --canvas <shape> compose onto 9:16 (1080x1920), 4:5, 1:1, 16:9 or WxH: the app between safe margins on the\n background, for Reels, Stories and feeds (--width scales the whole canvas)\n --watermark <text> a small badge on every frame, cards too, e.g. \"Created with TraceAvatar · traceavatar.com\"\n --watermark-at <corner> top-left, top-right, bottom-left or bottom-right (default)\n --brand <file.json> the look in one file: canvas, watermark, frame, background, camera, captions, captionsAt,\n titleCard, endCard ({ title, url, logo, color }); flags given here win over it\n\n AI (nothing calls a model without --ai):\n --ai <provider> gateway: our AI gateway (AI_GATEWAY_URL, AI_GATEWAY_KEY), DeepSeek first, then Gemini,\n then OpenAI; or gateway:<provider>[/<model>][,<provider>…]; openai:<model> (OPENAI_API_KEY,\n OPENAI_BASE_URL for any OpenAI-compatible server); or ./provider.js\n --ai-vision <model> the model for --qa's frames (gateway's DeepSeek default: deepseek-flash)\n --qa [strict] send a frame per step to the AI to look for errors, empty states, a stall, personal\n data; strict exits 1 when anything is flagged (needs a vision model)\n --alt write <out>.alt.txt; with --captions vtt, AI names the chapters\n --repair when a step can't find its element, or a wait's text never shows, propose a fix in\n <out>.repair.json (verified by playing again); still exits 1. With --ai, unsure\n cases are asked (DeepSeek first)\n --repair-vision with --repair and --ai: send a screenshot of the stalled page too (elements only)\n\n Narration (MP4 only; nothing speaks without --voice):\n --voice <voice> gateway (our AI gateway: Gemini speech, AI_GATEWAY_URL/KEY), gateway:gemini/<model>:<voice>,\n openai:<model>[:<voice>] (OPENAI_API_KEY / OPENAI_BASE_URL), say[:<voice>] (macOS, offline),\n or ./voice.js. Each step's caption is spoken; the video holds where a line runs long\n --script <file.json> the spoken lines instead: { \"lines\": [{ \"n\": 1, \"text\": \"…\" }] }\n --voice-out <file.wav> also write the narration track\n --voice-strict fail when a line needs a hold longer than 8 s\n --no-voice-cache don't keep spoken lines in .trace-avatar-cache/voice\n\nSuggestions for a person to accept (the renderer never changes a trace):\n trace-avatar-render suggest <trace.json> --task captions|title|waits|narration --ai <provider> [--tone friendly|terse|formal]\n [--hints hints.json] [--out suggestions.json]\n trace-avatar-render apply <trace.json> <suggestions.json> --accept 1,3|all --out <new.trace.json>\n`;\n\nexport interface Parsed { /** --report */ report?: string; trace: string; options: Parameters<typeof render>[0]; /** --ai, made into a provider by main(). */ ai?: string; /** --ai-vision */ aiVision?: string; /** --voice, made into a Voice by main() */ voice?: string; /** --no-voice-cache */ noVoiceCache?: boolean; /** --qa strict */ strict?: boolean }\n\n/** Parse the command line. Throws a usage message (exit 2) on mistakes. Exported for tests. */\nexport function parse(argv: string[]): Parsed {\n // --poster, --title-card and --end-card take an optional value: take it here when one follows (a\n // following *.json is the trace, not the value).\n const extra: { poster?: string | true; title?: string | true; end?: string | true; qa?: string | true } = {};\n const flags: Record<string, 'poster' | 'title' | 'end' | 'qa'> = { '--poster': 'poster', '--title-card': 'title', '--end-card': 'end', '--qa': 'qa' };\n const rest: string[] = [];\n for (let k = 0; k < argv.length; k += 1) {\n const a = argv[k];\n const eq = a.indexOf('=');\n const name = eq > 0 ? a.slice(0, eq) : a;\n if (flags[name]) {\n if (eq > 0) extra[flags[name]] = a.slice(eq + 1);\n else if (argv[k + 1] !== undefined && !argv[k + 1].startsWith('-') && !/\\.json$/i.test(argv[k + 1]) && (flags[name] !== 'qa' || argv[k + 1] === 'strict')) { extra[flags[name]] = argv[k + 1]; k += 1; }\n else extra[flags[name]] = true;\n continue;\n }\n rest.push(a);\n }\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n url: { type: 'string' }, out: { type: 'string', multiple: true }, mode: { type: 'string' },\n 'allow-perform': { type: 'boolean' }, width: { type: 'string' }, fps: { type: 'string' },\n viewport: { type: 'string' }, scale: { type: 'string' }, 'storage-state': { type: 'string' },\n 'max-wait': { type: 'string' }, hide: { type: 'string', multiple: true }, blur: { type: 'string', multiple: true },\n 'allow-stall': { type: 'boolean' }, navigate: { type: 'boolean' }, security: { type: 'string' }, value: { type: 'string', multiple: true }, player: { type: 'string' }, timeline: { type: 'string' },\n timeout: { type: 'string' }, headed: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },\n frame: { type: 'string' }, background: { type: 'string' }, camera: { type: 'boolean' }, zoom: { type: 'string' },\n captions: { type: 'string' }, 'captions-at': { type: 'string' }, ai: { type: 'string' }, 'ai-vision': { type: 'string' }, alt: { type: 'boolean' },\n voice: { type: 'string' }, script: { type: 'string' }, 'voice-out': { type: 'string' }, 'voice-strict': { type: 'boolean' }, 'no-voice-cache': { type: 'boolean' },\n repair: { type: 'boolean' }, 'repair-vision': { type: 'boolean' }, report: { type: 'string' },\n canvas: { type: 'string' }, watermark: { type: 'string' }, 'watermark-at': { type: 'string' }, brand: { type: 'string' },\n },\n });\n if (values.help) throw new UsageError('');\n const trace = positionals[0];\n if (!trace) throw new UsageError('a trace file is needed');\n if (positionals.length > 1) throw new UsageError(`one trace at a time (got ${positionals.join(', ')})`);\n if (!values.url) throw new UsageError('--url is needed');\n if (!values.out?.length) throw new UsageError('--out is needed');\n const num = (name: string, v: string | undefined, min = 0) => {\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isFinite(n) || n < min) throw new UsageError(`--${name} must be a number ≥ ${min}`);\n return n;\n };\n const mode = values.mode ?? 'overlay';\n if (mode !== 'overlay' && mode !== 'perform') throw new UsageError('--mode is overlay or perform');\n let viewport: { w: number; h: number } | undefined;\n if (values.viewport) {\n const m = /^(\\d+)x(\\d+)$/i.exec(values.viewport);\n if (!m) throw new UsageError('--viewport is WIDTHxHEIGHT, e.g. 1280x800');\n viewport = { w: Number(m[1]), h: Number(m[2]) };\n }\n if (values.frame && values.frame !== 'none' && values.frame !== 'browser') throw new UsageError('--frame is none or browser');\n const captions = values.captions;\n if (captions !== undefined && captions !== 'burn' && captions !== 'vtt' && captions !== 'both') throw new UsageError('--captions is burn, vtt or both');\n const captionsAt = values['captions-at'];\n if (captionsAt !== undefined && captionsAt !== 'top' && captionsAt !== 'bottom') throw new UsageError('--captions-at is top or bottom');\n const zoom = num('zoom', values.zoom, 1);\n if (extra.qa !== undefined && extra.qa !== true && extra.qa !== 'strict') throw new UsageError('--qa takes nothing or strict');\n if ((extra.qa !== undefined || values.alt || values['ai-vision']) && !values.ai) throw new UsageError('--qa, --alt and --ai-vision need --ai');\n if (values['repair-vision'] && !(values.repair && values.ai)) throw new UsageError('--repair-vision needs --repair and --ai');\n if ((values.script || values['voice-out'] || values['voice-strict'] || values['no-voice-cache']) && !values.voice) throw new UsageError('--script, --voice-out, --voice-strict and --no-voice-cache need --voice');\n if (values.voice && !values.out.some((f) => /\\.mp4(@.*)?$/i.test(f))) throw new UsageError('--voice needs an .mp4 output (a GIF has no sound)');\n let security: boolean | string[] | undefined;\n if (values.security !== undefined) {\n const s = values.security.trim().toLowerCase();\n const guards = s === '' || s === 'all' || s === 'true' ? true : s.split(/[\\s,]+/).filter(Boolean);\n if (Array.isArray(guards) && guards.some((g) => !['secrets', 'money', 'files'].includes(g))) throw new UsageError('--security is all, or a list of secrets, money, files');\n security = guards;\n }\n const typed: Record<string, string> = {};\n for (const v of values.value ?? []) {\n const k = v.indexOf('=');\n if (k < 1) throw new UsageError('--value is name=text, e.g. password=demo-pass');\n typed[v.slice(0, k)] = v.slice(k + 1);\n }\n if ((security !== undefined || values.value?.length) && mode !== 'perform') throw new UsageError('--security and --value are for --mode perform');\n const tryUsage = <T>(f: () => T): T => { try { return f(); } catch (e) { throw new UsageError((e as Error).message); } };\n if (values.canvas !== undefined) tryUsage(() => canvasOf(values.canvas!));\n for (const o of values.out ?? []) { const m = /^.+\\.(?:gif|mp4)@(.+)$/i.exec(o); if (m) tryUsage(() => canvasOf(m[1])); }\n const at = values['watermark-at'];\n if (at !== undefined && !CORNERS.includes(at as Corner)) throw new UsageError(`--watermark-at is ${CORNERS.join(', ')}`);\n const brand = values.brand !== undefined ? tryUsage(() => brandFile(values.brand!)) : {};\n let watermark: string | Watermark | undefined = values.watermark !== undefined ? tryUsage(() => watermarkOf(values.watermark!)) : brand.watermark;\n if (at !== undefined) {\n if (watermark === undefined) throw new UsageError('--watermark-at needs a watermark (--watermark, or one in --brand)');\n watermark = { ...(typeof watermark === 'string' ? { text: watermark } : watermark), at: at as Corner };\n }\n const width = num('width', values.width, 16);\n const fps = num('fps', values.fps, 1);\n const maxWait = num('max-wait', values['max-wait']);\n return {\n trace,\n options: {\n // The brand first: the flags below win over it.\n ...brand,\n trace,\n url: values.url,\n mode,\n allowPerform: !!values['allow-perform'],\n out: values.out.map((spec) => {\n const m = /^(.+\\.(?:gif|mp4))@(.+)$/i.exec(spec);\n const file = m ? m[1] : spec;\n return { file, ...(width ? { width } : {}), ...(fps ? { fps } : {}), ...(m ? { canvas: m[2] } : {}) };\n }),\n ...(viewport ? { viewport } : {}),\n ...(values.scale ? { scale: num('scale', values.scale, 1) } : {}),\n ...(values['storage-state'] ? { storageState: values['storage-state'] } : {}),\n ...(maxWait !== undefined ? { cuts: { maxWaitMs: maxWait } } : {}),\n ...(values.hide ? { hide: values.hide } : {}),\n ...(values.blur ? { blur: values.blur } : {}),\n allowStall: !!values['allow-stall'],\n ...(values.navigate ? { navigate: true } : {}),\n ...(security !== undefined ? { security } : {}),\n ...(values.value?.length ? { values: typed } : {}),\n ...(values.player ? { player: values.player } : {}),\n ...(values.timeline ? { timeline: values.timeline } : {}),\n ...(values.timeout ? { timeoutMs: num('timeout', values.timeout, 1) } : {}),\n headless: !values.headed,\n ...(values.frame ? { frame: values.frame as 'none' | 'browser' } : {}),\n ...(values.background ? { background: values.background } : {}),\n ...(zoom ? { camera: { zoom } } : values.camera ? { camera: true } : {}),\n ...(captions ? { captions } : {}),\n ...(captionsAt ? { captionsAt: captionsAt as 'top' | 'bottom' } : {}),\n ...(extra.poster !== undefined ? { poster: extra.poster } : {}),\n ...(extra.title !== undefined ? { titleCard: extra.title } : {}),\n ...(extra.end !== undefined ? { endCard: extra.end } : {}),\n ...(values.canvas !== undefined ? { canvas: values.canvas } : {}),\n ...(watermark !== undefined ? { watermark } : {}),\n ...(extra.qa !== undefined ? { qa: true } : {}),\n ...(values.alt ? { alt: true } : {}),\n ...(values.script ? { script: values.script } : {}),\n ...(values['voice-out'] ? { voiceOut: values['voice-out'] } : {}),\n ...(values['voice-strict'] ? { voiceStrict: true } : {}),\n ...(values.repair ? { repair: true } : {}),\n ...(values['repair-vision'] ? { repairVision: true } : {}),\n },\n ...(values.ai ? { ai: values.ai } : {}),\n ...(values['ai-vision'] ? { aiVision: values['ai-vision'] } : {}),\n ...(values.voice ? { voice: values.voice } : {}),\n ...(values['no-voice-cache'] ? { noVoiceCache: true } : {}),\n ...(extra.qa === 'strict' ? { strict: true } : {}),\n ...(values.report ? { report: values.report } : {}),\n };\n}\n\n/** What --report writes: one guide's outcome, for CI. */\nexport interface Report {\n outcome: 'passed' | 'stalled' | 'failed';\n /** The stalled step (from 0); null otherwise. */\n step: number | null;\n reason: 'not-found' | 'until-timeout' | null;\n /** The stalled step's caption, or the error. */\n message: string | null;\n /** The repair file, when --repair wrote one. */\n repair?: string;\n}\n\n/** The report for a render's outcome (exported for tests). */\nexport function reportOf(err: unknown, traceFile: string, repairFile?: string): Report {\n if (!err) return { outcome: 'passed', step: null, reason: null, message: null };\n const stall = err instanceof RenderError ? err.stall : undefined;\n if (stall && Number.isInteger(stall.index)) {\n let say: string | null = null;\n try { say = ((JSON.parse(readFileSync(traceFile, 'utf8')) as { steps?: Array<{ say?: string }> }).steps?.[stall.index]?.say) ?? null; } catch { /* the error is enough */ }\n return {\n outcome: 'stalled', step: stall.index, reason: stall.reason === 'until-timeout' ? 'until-timeout' : 'not-found',\n message: say ?? (err as Error).message, ...(repairFile && existsSync(repairFile) ? { repair: repairFile } : {}),\n };\n }\n return { outcome: 'failed', step: null, reason: null, message: (err as Error)?.message ?? String(err) };\n}\n\nexport class UsageError extends Error {}\n\nexport async function main(argv: string[], io = { log: console.log, error: console.error }): Promise<number> {\n if (argv[0] === 'suggest' || argv[0] === 'apply') {\n try { return await (argv[0] === 'suggest' ? suggestCmd(argv.slice(1), io) : applyCmd(argv.slice(1), io)); } catch (e) {\n io.error(`trace-avatar-render ${argv[0]}: ${(e as Error).message}`);\n if (e instanceof UsageError) io.error(USAGE);\n return e instanceof UsageError ? 2 : 1;\n }\n }\n let p: Parsed;\n try { p = parse(argv); } catch (e) {\n const msg = (e as Error).message;\n if (msg) io.error(`trace-avatar-render: ${msg}\\n`);\n io.error(USAGE);\n return e instanceof UsageError && !msg ? 0 : 2;\n }\n try {\n if (p.ai) p.options.ai = await providerOf(p.ai, process.env, p.aiVision ? { vision: p.aiVision } : {});\n if (p.voice) p.options.voice = await voiceOf(p.voice, process.env, p.noVoiceCache ? { cacheDir: null } : {});\n const r = await render(p.options);\n for (const o of r.outputs) io.log(`${o.file} ${o.width}×${o.height} ${o.fps} fps ${(r.durationMs / 1000).toFixed(1)} s ${(o.bytes / 1024).toFixed(0)} KB`);\n if (r.rawMs > r.durationMs + 50) io.log(`cut ${((r.rawMs - r.durationMs) / 1000).toFixed(1)} s of waiting`);\n for (const f of [r.poster, r.vtt, r.chapters, r.alt]) if (f) io.log(f);\n if (r.narration) {\n io.log(`narration: ${r.narration.lines.length} line${r.narration.lines.length === 1 ? '' : 's'}${r.narration.holdMs ? `, the video holds ${(r.narration.holdMs / 1000).toFixed(1)} s for them` : ''} ${r.narration.text}`);\n if (r.narration.wav) io.log(r.narration.wav);\n }\n for (const w of r.warnings ?? []) io.error(`warning: ${w}`);\n if (p.report) writeFileSync(p.report, `${JSON.stringify(reportOf(null, p.trace), null, 2)}\\n`);\n if (r.qa) {\n if (!r.qa.length) io.log('qa: nothing flagged');\n for (const f of r.qa) io.log(`qa: ${(f.at / 1000).toFixed(1)} s ${f.kind} ${f.note}`);\n if (p.strict && r.qa.length) { io.error(`trace-avatar-render: qa flagged ${r.qa.length} problem${r.qa.length > 1 ? 's' : ''} (--qa strict)`); return 1; }\n }\n return 0;\n } catch (e) {\n io.error(`trace-avatar-render: ${(e as Error).message}`);\n if (p.report) {\n const first = p.options.out[0];\n const base = (typeof first === 'string' ? first : first.file).replace(/\\.[^./]+$/, '');\n writeFileSync(p.report, `${JSON.stringify(reportOf(e, p.trace, `${base}.repair.json`), null, 2)}\\n`);\n }\n if (e instanceof RenderError && e.screenshot) {\n const first = p.options.out[0];\n const shot = `${(typeof first === 'string' ? first : first.file).replace(/\\.[^./]+$/, '')}.failure.png`;\n writeFileSync(shot, e.screenshot);\n io.error(`the page at that moment: ${shot}`);\n }\n return 1;\n }\n}\n\nconst readJson = (file: string): unknown => {\n try { return JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`could not read ${file}: ${(e as Error).message}`); }\n};\n\n/** suggest <trace.json> --task … --ai …: suggestions, numbered, as JSON (stdout or --out). */\nasync function suggestCmd(argv: string[], io: { log: (m: string) => void }): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {\n task: { type: 'string' }, ai: { type: 'string' }, tone: { type: 'string' }, hints: { type: 'string' }, out: { type: 'string' }, 'send-typed': { type: 'boolean' },\n } });\n const [file] = positionals;\n if (!file) throw new UsageError('suggest needs a trace file');\n const task = values.task;\n if (task !== 'captions' && task !== 'title' && task !== 'waits' && task !== 'narration') throw new UsageError('--task is captions, title, waits or narration');\n if (!values.ai) throw new UsageError('suggest needs --ai');\n if (task === 'narration') {\n // A script file for --script: a person edits it before rendering.\n const r = await suggestScript(await providerOf(values.ai), readJson(file) as Parameters<typeof suggestScript>[1]);\n const out = JSON.stringify({ ...r.script, ...(r.dropped.length ? { dropped: r.dropped } : {}) }, null, 2);\n if (values.out) { writeFileSync(values.out, `${out}\\n`); io.log(`${r.script.lines.length} line${r.script.lines.length === 1 ? '' : 's'} in ${values.out}: edit them, then --script ${values.out}`); } else io.log(out);\n return 0;\n }\n const tone = values.tone;\n if (tone !== undefined && tone !== 'friendly' && tone !== 'terse' && tone !== 'formal') throw new UsageError('--tone is friendly, terse or formal');\n const trace = readJson(file) as Parameters<typeof suggest>[1];\n const hints = values.hints ? (readJson(values.hints) as Parameters<typeof suggest>[2]['hints']) : undefined;\n const r = await suggest(task, trace, { ai: await providerOf(values.ai), ...(hints ? { hints } : {}), ...(tone ? { tone } : {}), ...(values['send-typed'] ? { sendTyped: true } : {}) });\n const out = JSON.stringify({ task, suggestions: r.suggestions.map((sg, k) => ({ id: k + 1, ...sg })), dropped: r.dropped }, null, 2);\n if (values.out) { writeFileSync(values.out, `${out}\\n`); io.log(`${r.suggestions.length} suggestion${r.suggestions.length === 1 ? '' : 's'} in ${values.out}`); } else io.log(out);\n return 0;\n}\n\n/** apply <trace.json> <suggestions.json> --accept 1,3|all --out new.trace.json */\nasync function applyCmd(argv: string[], io: { log: (m: string) => void }): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { accept: { type: 'string' }, out: { type: 'string' } } });\n const [file, sugFile] = positionals;\n if (!file || !sugFile) throw new UsageError('apply needs a trace file and a suggestions file');\n if (!values.accept) throw new UsageError('apply needs --accept 1,3 (or all): a person picks what goes in');\n if (!values.out) throw new UsageError('apply needs --out for the new trace');\n const all = (readJson(sugFile) as { suggestions?: Array<Suggestion & { id: number }> }).suggestions ?? [];\n const ids = values.accept === 'all' ? all.map((x) => x.id) : values.accept.split(',').map((x) => Number(x.trim()));\n const missing = ids.filter((id) => !all.some((x) => x.id === id));\n if (missing.length) throw new UsageError(`no suggestion ${missing.join(', ')} in ${sugFile}`);\n const next = applySuggestions(readJson(file) as Parameters<typeof applySuggestions>[0], all.filter((x) => ids.includes(x.id)));\n writeFileSync(values.out, `${JSON.stringify(next, null, 2)}\\n`);\n io.log(`applied ${ids.length} of ${all.length} to ${values.out}`);\n return 0;\n}\n\nconst isMain = import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('/trace-avatar-render') || process.argv[1]?.endsWith('/cli.js');\nif (isMain) void main(process.argv.slice(2)).then((code) => { process.exitCode = code; });\n"],"mappings":";;;;;;;;;;;;;;AAOA,SAAS,YAAY,cAAc,qBAAqB;AACxD,SAAS,SAAS,kBAAkB,eAAe;AAKnD,SAAS,iBAAiB;AAMnB,IAAM,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2Ed,SAAS,MAAM,MAAwB;AAG5C,QAAM,QAAoG,CAAC;AAC3G,QAAM,QAA2D,EAAE,YAAY,UAAU,gBAAgB,SAAS,cAAc,OAAO,QAAQ,KAAK;AACpJ,QAAM,OAAiB,CAAC;AACxB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK,GAAG;AACvC,UAAM,IAAI,KAAK,CAAC;AAChB,UAAM,KAAK,EAAE,QAAQ,GAAG;AACxB,UAAM,OAAO,KAAK,IAAI,EAAE,MAAM,GAAG,EAAE,IAAI;AACvC,QAAI,MAAM,IAAI,GAAG;AACf,UAAI,KAAK,EAAG,OAAM,MAAM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AAC7F,MAAI,CAAC,OAAO,OAAQ,OAAM,IAAI,WAAW,gEAAgE;AACzG,MAAI,CAAC,OAAO,IAAK,OAAM,IAAI,WAAW,qCAAqC;AAC3E,QAAM,MAAO,SAAS,OAAO,EAA2D,eAAe,CAAC;AACxG,QAAM,MAAM,OAAO,WAAW,QAAQ,IAAI,IAAI,CAAC,MAAM,EAAE,EAAE,IAAI,OAAO,OAAO,MAAM,GAAG,EAAE,IAAI,CAAC,MAAM,OAAO,EAAE,KAAK,CAAC,CAAC;AACjH,QAAM,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;AAChE,MAAI,QAAQ,OAAQ,OAAM,IAAI,WAAW,iBAAiB,QAAQ,KAAK,IAAI,CAAC,OAAO,OAAO,EAAE;AAC5F,QAAM,OAAO,iBAAiB,SAAS,IAAI,GAA6C,IAAI,OAAO,CAAC,MAAM,IAAI,SAAS,EAAE,EAAE,CAAC,CAAC;AAC7H,gBAAc,OAAO,KAAK,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA,CAAI;AAC9D,KAAG,IAAI,WAAW,IAAI,MAAM,OAAO,IAAI,MAAM,OAAO,OAAO,GAAG,EAAE;AAChE,SAAO;AACT;AAEA,IAAM,SAAS,YAAY,QAAQ,UAAU,QAAQ,KAAK,CAAC,CAAC,MAAM,QAAQ,KAAK,CAAC,GAAG,SAAS,sBAAsB,KAAK,QAAQ,KAAK,CAAC,GAAG,SAAS,SAAS;AAC1J,IAAI,OAAQ,MAAK,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,SAAS;AAAE,UAAQ,WAAW;AAAM,CAAC;","names":["r","out"]}
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * trace-avatar-render invoice.trace.json --url http://localhost:3000/app --out invoice.gif --out invoice.mp4\n *\n * Exit codes: 0 rendered, 1 the render failed (a stalled guide, an error in the app), 2 wrong usage.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { apply as applySuggestions, suggest } from 'trace-avatar/assist';\nimport type { Suggestion } from 'trace-avatar/assist';\nimport { providerOf } from './ai';\nimport { suggestScript } from './narration';\nimport { voiceOf } from './voice';\nimport { parseArgs } from 'node:util';\nimport { RenderError } from './capture';\nimport { render } from './render';\nimport { brandFile, canvasOf, CORNERS, watermarkOf } from './brand';\nimport { checkCatalogue } from './catalogue';\nimport type { Corner, Watermark } from './brand';\n\nexport const USAGE = `Usage: trace-avatar-render <trace.json> --url <page> --out <file.gif|file.mp4> [options]\n\n --url <url> the page the guide starts on (required)\n --out <file> .gif or .mp4; repeat for several (required). <file>@<shape> gives that output its own\n canvas (e.g. --out wide.mp4@16:9 --out square.mp4@1:1): several shapes from one capture\n --mode <overlay|perform> Show me (default) or Do it for me\n --allow-perform needed for perform: it clicks and types for real (use a sandbox account)\n --width <px> output width (GIF default 800, MP4 the capture's)\n --fps <n> frames per second (GIF default 12, MP4 30)\n --viewport <WxH> default: the trace's meta.viewport, else 1280x800\n --scale <n> device pixel ratio of the capture (2 for crisp video)\n --storage-state <file> a signed-in Playwright session\n --max-wait <ms> waits longer than this are cut to it (default 800, 0 keeps them)\n --hide <selector> hidden before capture; repeatable\n --blur <selector> blurred before capture (as well as [data-trace-blur]); repeatable\n --allow-stall render a stalled guide anyway instead of failing\n --navigate a step on another page: load that page, as the app's router would (without it, a\n Show me guide that crosses pages waits on \"Open … to continue\")\n --security [guards] perform: leave these to the viewer (a hand-off): all, or secrets,money,files\n --value <name=text> perform: a value to type, by name or field label (e.g. password=demo-pass); repeatable\n --player <file> the trace-perform.min.js to use (default: the installed trace-avatar)\n --timeline <file> write the timeline and the cuts as JSON\n --timeout <ms> give up after this long (default 120000)\n --report <file> write what happened as JSON: { outcome: passed|stalled|failed, step, reason, message }\n (for CI: one result per guide, whatever the exit code)\n --headed show the browser\n\n Polish (all off by default):\n --frame <none|browser> a browser window around the app, on a background\n --background <css> the background behind the window and on the cards\n --camera zoom in on each action and pan between close ones\n --zoom <n> how far the camera goes in (default 1.6; implies --camera)\n --captions <burn|vtt|both> burn the steps' words in, write <out>.vtt + <out>.chapters.vtt, or both\n --captions-at <top|bottom> where burned-in captions sit (default bottom; top when the app's own UI is low)\n --poster [file] a PNG at the first click (default <out>.png)\n --title-card [title] a 1.5 s card first (default: the trace's title)\n --end-card [title] a 2 s card last (default: \"Done\")\n --canvas <shape> compose onto 9:16 (1080x1920), 4:5, 1:1, 16:9 or WxH: the app between safe margins on the\n background, for Reels, Stories and feeds (--width scales the whole canvas)\n --watermark <text> a small badge on every frame, cards too, e.g. \"Created with TraceAvatar · traceavatar.com\"\n --watermark-at <corner> top-left, top-right, bottom-left or bottom-right (default)\n --brand <file.json> the look in one file: canvas, watermark, frame, background, camera, captions, captionsAt,\n titleCard, endCard ({ title, url, logo, color }); flags given here win over it\n\n AI (nothing calls a model without --ai):\n --ai <provider> gateway: our AI gateway (AI_GATEWAY_URL, AI_GATEWAY_KEY), DeepSeek first, then Gemini,\n then OpenAI; or gateway:<provider>[/<model>][,<provider>…]; openai:<model> (OPENAI_API_KEY,\n OPENAI_BASE_URL for any OpenAI-compatible server); or ./provider.js\n --ai-vision <model> the model for --qa's frames (gateway's DeepSeek default: deepseek-flash)\n --qa [strict] send a frame per step to the AI to look for errors, empty states, a stall, personal\n data; strict exits 1 when anything is flagged (needs a vision model)\n --alt write <out>.alt.txt; with --captions vtt, AI names the chapters\n --repair when a step can't find its element, or a wait's text never shows, propose a fix in\n <out>.repair.json (verified by playing again); still exits 1. With --ai, unsure\n cases are asked (DeepSeek first)\n --repair-vision with --repair and --ai: send a screenshot of the stalled page too (elements only)\n\n Narration (MP4 only; nothing speaks without --voice):\n --voice <voice> gateway (our AI gateway: Gemini speech, AI_GATEWAY_URL/KEY), gateway:gemini/<model>:<voice>,\n openai:<model>[:<voice>] (OPENAI_API_KEY / OPENAI_BASE_URL), say[:<voice>] (macOS, offline),\n or ./voice.js. Each step's caption is spoken; the video holds where a line runs long\n --script <file.json> the spoken lines instead: { \"lines\": [{ \"n\": 1, \"text\": \"…\" }] }\n --voice-out <file.wav> also write the narration track\n --voice-strict fail when a line needs a hold longer than 8 s\n --no-voice-cache don't keep spoken lines in .trace-avatar-cache/voice\n\nSuggestions for a person to accept (the renderer never changes a trace):\n trace-avatar-render suggest <trace.json> --task captions|title|waits|narration --ai <provider> [--tone friendly|terse|formal]\n [--hints hints.json] [--out suggestions.json]\n trace-avatar-render apply <trace.json> <suggestions.json> --accept 1,3|all --out <new.trace.json>\n\nA clip catalogue (trace-avatar-catalogue/1, schemas/catalogue-1.json):\n trace-avatar-render catalogue check <file.json|https://…> [--fetch] [--json]\n --fetch: fetch every link too (reachable, its type, captions within the video, mp4 head)\n --allow-http: accept http:// links (a local test server)\n`;\n\nexport interface Parsed { /** --report */ report?: string; trace: string; options: Parameters<typeof render>[0]; /** --ai, made into a provider by main(). */ ai?: string; /** --ai-vision */ aiVision?: string; /** --voice, made into a Voice by main() */ voice?: string; /** --no-voice-cache */ noVoiceCache?: boolean; /** --qa strict */ strict?: boolean }\n\n/** Parse the command line. Throws a usage message (exit 2) on mistakes. Exported for tests. */\nexport function parse(argv: string[]): Parsed {\n // --poster, --title-card and --end-card take an optional value: take it here when one follows (a\n // following *.json is the trace, not the value).\n const extra: { poster?: string | true; title?: string | true; end?: string | true; qa?: string | true } = {};\n const flags: Record<string, 'poster' | 'title' | 'end' | 'qa'> = { '--poster': 'poster', '--title-card': 'title', '--end-card': 'end', '--qa': 'qa' };\n const rest: string[] = [];\n for (let k = 0; k < argv.length; k += 1) {\n const a = argv[k];\n const eq = a.indexOf('=');\n const name = eq > 0 ? a.slice(0, eq) : a;\n if (flags[name]) {\n if (eq > 0) extra[flags[name]] = a.slice(eq + 1);\n else if (argv[k + 1] !== undefined && !argv[k + 1].startsWith('-') && !/\\.json$/i.test(argv[k + 1]) && (flags[name] !== 'qa' || argv[k + 1] === 'strict')) { extra[flags[name]] = argv[k + 1]; k += 1; }\n else extra[flags[name]] = true;\n continue;\n }\n rest.push(a);\n }\n const { values, positionals } = parseArgs({\n args: rest,\n allowPositionals: true,\n options: {\n url: { type: 'string' }, out: { type: 'string', multiple: true }, mode: { type: 'string' },\n 'allow-perform': { type: 'boolean' }, width: { type: 'string' }, fps: { type: 'string' },\n viewport: { type: 'string' }, scale: { type: 'string' }, 'storage-state': { type: 'string' },\n 'max-wait': { type: 'string' }, hide: { type: 'string', multiple: true }, blur: { type: 'string', multiple: true },\n 'allow-stall': { type: 'boolean' }, navigate: { type: 'boolean' }, security: { type: 'string' }, value: { type: 'string', multiple: true }, player: { type: 'string' }, timeline: { type: 'string' },\n timeout: { type: 'string' }, headed: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },\n frame: { type: 'string' }, background: { type: 'string' }, camera: { type: 'boolean' }, zoom: { type: 'string' },\n captions: { type: 'string' }, 'captions-at': { type: 'string' }, ai: { type: 'string' }, 'ai-vision': { type: 'string' }, alt: { type: 'boolean' },\n voice: { type: 'string' }, script: { type: 'string' }, 'voice-out': { type: 'string' }, 'voice-strict': { type: 'boolean' }, 'no-voice-cache': { type: 'boolean' },\n repair: { type: 'boolean' }, 'repair-vision': { type: 'boolean' }, report: { type: 'string' },\n canvas: { type: 'string' }, watermark: { type: 'string' }, 'watermark-at': { type: 'string' }, brand: { type: 'string' },\n },\n });\n if (values.help) throw new UsageError('');\n const trace = positionals[0];\n if (!trace) throw new UsageError('a trace file is needed');\n if (positionals.length > 1) throw new UsageError(`one trace at a time (got ${positionals.join(', ')})`);\n if (!values.url) throw new UsageError('--url is needed');\n if (!values.out?.length) throw new UsageError('--out is needed');\n const num = (name: string, v: string | undefined, min = 0) => {\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isFinite(n) || n < min) throw new UsageError(`--${name} must be a number ≥ ${min}`);\n return n;\n };\n const mode = values.mode ?? 'overlay';\n if (mode !== 'overlay' && mode !== 'perform') throw new UsageError('--mode is overlay or perform');\n let viewport: { w: number; h: number } | undefined;\n if (values.viewport) {\n const m = /^(\\d+)x(\\d+)$/i.exec(values.viewport);\n if (!m) throw new UsageError('--viewport is WIDTHxHEIGHT, e.g. 1280x800');\n viewport = { w: Number(m[1]), h: Number(m[2]) };\n }\n if (values.frame && values.frame !== 'none' && values.frame !== 'browser') throw new UsageError('--frame is none or browser');\n const captions = values.captions;\n if (captions !== undefined && captions !== 'burn' && captions !== 'vtt' && captions !== 'both') throw new UsageError('--captions is burn, vtt or both');\n const captionsAt = values['captions-at'];\n if (captionsAt !== undefined && captionsAt !== 'top' && captionsAt !== 'bottom') throw new UsageError('--captions-at is top or bottom');\n const zoom = num('zoom', values.zoom, 1);\n if (extra.qa !== undefined && extra.qa !== true && extra.qa !== 'strict') throw new UsageError('--qa takes nothing or strict');\n if ((extra.qa !== undefined || values.alt || values['ai-vision']) && !values.ai) throw new UsageError('--qa, --alt and --ai-vision need --ai');\n if (values['repair-vision'] && !(values.repair && values.ai)) throw new UsageError('--repair-vision needs --repair and --ai');\n if ((values.script || values['voice-out'] || values['voice-strict'] || values['no-voice-cache']) && !values.voice) throw new UsageError('--script, --voice-out, --voice-strict and --no-voice-cache need --voice');\n if (values.voice && !values.out.some((f) => /\\.mp4(@.*)?$/i.test(f))) throw new UsageError('--voice needs an .mp4 output (a GIF has no sound)');\n let security: boolean | string[] | undefined;\n if (values.security !== undefined) {\n const s = values.security.trim().toLowerCase();\n const guards = s === '' || s === 'all' || s === 'true' ? true : s.split(/[\\s,]+/).filter(Boolean);\n if (Array.isArray(guards) && guards.some((g) => !['secrets', 'money', 'files'].includes(g))) throw new UsageError('--security is all, or a list of secrets, money, files');\n security = guards;\n }\n const typed: Record<string, string> = {};\n for (const v of values.value ?? []) {\n const k = v.indexOf('=');\n if (k < 1) throw new UsageError('--value is name=text, e.g. password=demo-pass');\n typed[v.slice(0, k)] = v.slice(k + 1);\n }\n if ((security !== undefined || values.value?.length) && mode !== 'perform') throw new UsageError('--security and --value are for --mode perform');\n const tryUsage = <T>(f: () => T): T => { try { return f(); } catch (e) { throw new UsageError((e as Error).message); } };\n if (values.canvas !== undefined) tryUsage(() => canvasOf(values.canvas!));\n for (const o of values.out ?? []) { const m = /^.+\\.(?:gif|mp4)@(.+)$/i.exec(o); if (m) tryUsage(() => canvasOf(m[1])); }\n const at = values['watermark-at'];\n if (at !== undefined && !CORNERS.includes(at as Corner)) throw new UsageError(`--watermark-at is ${CORNERS.join(', ')}`);\n const brand = values.brand !== undefined ? tryUsage(() => brandFile(values.brand!)) : {};\n let watermark: string | Watermark | undefined = values.watermark !== undefined ? tryUsage(() => watermarkOf(values.watermark!)) : brand.watermark;\n if (at !== undefined) {\n if (watermark === undefined) throw new UsageError('--watermark-at needs a watermark (--watermark, or one in --brand)');\n watermark = { ...(typeof watermark === 'string' ? { text: watermark } : watermark), at: at as Corner };\n }\n const width = num('width', values.width, 16);\n const fps = num('fps', values.fps, 1);\n const maxWait = num('max-wait', values['max-wait']);\n return {\n trace,\n options: {\n // The brand first: the flags below win over it.\n ...brand,\n trace,\n url: values.url,\n mode,\n allowPerform: !!values['allow-perform'],\n out: values.out.map((spec) => {\n const m = /^(.+\\.(?:gif|mp4))@(.+)$/i.exec(spec);\n const file = m ? m[1] : spec;\n return { file, ...(width ? { width } : {}), ...(fps ? { fps } : {}), ...(m ? { canvas: m[2] } : {}) };\n }),\n ...(viewport ? { viewport } : {}),\n ...(values.scale ? { scale: num('scale', values.scale, 1) } : {}),\n ...(values['storage-state'] ? { storageState: values['storage-state'] } : {}),\n ...(maxWait !== undefined ? { cuts: { maxWaitMs: maxWait } } : {}),\n ...(values.hide ? { hide: values.hide } : {}),\n ...(values.blur ? { blur: values.blur } : {}),\n allowStall: !!values['allow-stall'],\n ...(values.navigate ? { navigate: true } : {}),\n ...(security !== undefined ? { security } : {}),\n ...(values.value?.length ? { values: typed } : {}),\n ...(values.player ? { player: values.player } : {}),\n ...(values.timeline ? { timeline: values.timeline } : {}),\n ...(values.timeout ? { timeoutMs: num('timeout', values.timeout, 1) } : {}),\n headless: !values.headed,\n ...(values.frame ? { frame: values.frame as 'none' | 'browser' } : {}),\n ...(values.background ? { background: values.background } : {}),\n ...(zoom ? { camera: { zoom } } : values.camera ? { camera: true } : {}),\n ...(captions ? { captions } : {}),\n ...(captionsAt ? { captionsAt: captionsAt as 'top' | 'bottom' } : {}),\n ...(extra.poster !== undefined ? { poster: extra.poster } : {}),\n ...(extra.title !== undefined ? { titleCard: extra.title } : {}),\n ...(extra.end !== undefined ? { endCard: extra.end } : {}),\n ...(values.canvas !== undefined ? { canvas: values.canvas } : {}),\n ...(watermark !== undefined ? { watermark } : {}),\n ...(extra.qa !== undefined ? { qa: true } : {}),\n ...(values.alt ? { alt: true } : {}),\n ...(values.script ? { script: values.script } : {}),\n ...(values['voice-out'] ? { voiceOut: values['voice-out'] } : {}),\n ...(values['voice-strict'] ? { voiceStrict: true } : {}),\n ...(values.repair ? { repair: true } : {}),\n ...(values['repair-vision'] ? { repairVision: true } : {}),\n },\n ...(values.ai ? { ai: values.ai } : {}),\n ...(values['ai-vision'] ? { aiVision: values['ai-vision'] } : {}),\n ...(values.voice ? { voice: values.voice } : {}),\n ...(values['no-voice-cache'] ? { noVoiceCache: true } : {}),\n ...(extra.qa === 'strict' ? { strict: true } : {}),\n ...(values.report ? { report: values.report } : {}),\n };\n}\n\n/** What --report writes: one guide's outcome, for CI. */\nexport interface Report {\n outcome: 'passed' | 'stalled' | 'failed';\n /** The stalled step (from 0); null otherwise. */\n step: number | null;\n reason: 'not-found' | 'until-timeout' | null;\n /** The stalled step's caption, or the error. */\n message: string | null;\n /** The repair file, when --repair wrote one. */\n repair?: string;\n}\n\n/** The report for a render's outcome (exported for tests). */\nexport function reportOf(err: unknown, traceFile: string, repairFile?: string): Report {\n if (!err) return { outcome: 'passed', step: null, reason: null, message: null };\n const stall = err instanceof RenderError ? err.stall : undefined;\n if (stall && Number.isInteger(stall.index)) {\n let say: string | null = null;\n try { say = ((JSON.parse(readFileSync(traceFile, 'utf8')) as { steps?: Array<{ say?: string }> }).steps?.[stall.index]?.say) ?? null; } catch { /* the error is enough */ }\n return {\n outcome: 'stalled', step: stall.index, reason: stall.reason === 'until-timeout' ? 'until-timeout' : 'not-found',\n message: say ?? (err as Error).message, ...(repairFile && existsSync(repairFile) ? { repair: repairFile } : {}),\n };\n }\n return { outcome: 'failed', step: null, reason: null, message: (err as Error)?.message ?? String(err) };\n}\n\nexport class UsageError extends Error {}\n\nexport async function main(argv: string[], io = { log: console.log, error: console.error }): Promise<number> {\n if (argv[0] === 'suggest' || argv[0] === 'apply' || argv[0] === 'catalogue') {\n try { return await (argv[0] === 'suggest' ? suggestCmd(argv.slice(1), io) : argv[0] === 'apply' ? applyCmd(argv.slice(1), io) : catalogueCmd(argv.slice(1), io)); } catch (e) {\n io.error(`trace-avatar-render ${argv[0]}: ${(e as Error).message}`);\n if (e instanceof UsageError) io.error(USAGE);\n return e instanceof UsageError ? 2 : 1;\n }\n }\n let p: Parsed;\n try { p = parse(argv); } catch (e) {\n const msg = (e as Error).message;\n if (msg) io.error(`trace-avatar-render: ${msg}\\n`);\n io.error(USAGE);\n return e instanceof UsageError && !msg ? 0 : 2;\n }\n try {\n if (p.ai) p.options.ai = await providerOf(p.ai, process.env, p.aiVision ? { vision: p.aiVision } : {});\n if (p.voice) p.options.voice = await voiceOf(p.voice, process.env, p.noVoiceCache ? { cacheDir: null } : {});\n const r = await render(p.options);\n for (const o of r.outputs) io.log(`${o.file} ${o.width}×${o.height} ${o.fps} fps ${(r.durationMs / 1000).toFixed(1)} s ${(o.bytes / 1024).toFixed(0)} KB`);\n if (r.rawMs > r.durationMs + 50) io.log(`cut ${((r.rawMs - r.durationMs) / 1000).toFixed(1)} s of waiting`);\n for (const f of [r.poster, r.vtt, r.chapters, r.alt]) if (f) io.log(f);\n if (r.narration) {\n io.log(`narration: ${r.narration.lines.length} line${r.narration.lines.length === 1 ? '' : 's'}${r.narration.holdMs ? `, the video holds ${(r.narration.holdMs / 1000).toFixed(1)} s for them` : ''} ${r.narration.text}`);\n if (r.narration.wav) io.log(r.narration.wav);\n }\n for (const w of r.warnings ?? []) io.error(`warning: ${w}`);\n if (p.report) writeFileSync(p.report, `${JSON.stringify(reportOf(null, p.trace), null, 2)}\\n`);\n if (r.qa) {\n if (!r.qa.length) io.log('qa: nothing flagged');\n for (const f of r.qa) io.log(`qa: ${(f.at / 1000).toFixed(1)} s ${f.kind} ${f.note}`);\n if (p.strict && r.qa.length) { io.error(`trace-avatar-render: qa flagged ${r.qa.length} problem${r.qa.length > 1 ? 's' : ''} (--qa strict)`); return 1; }\n }\n return 0;\n } catch (e) {\n io.error(`trace-avatar-render: ${(e as Error).message}`);\n if (p.report) {\n const first = p.options.out[0];\n const base = (typeof first === 'string' ? first : first.file).replace(/\\.[^./]+$/, '');\n writeFileSync(p.report, `${JSON.stringify(reportOf(e, p.trace, `${base}.repair.json`), null, 2)}\\n`);\n }\n if (e instanceof RenderError && e.screenshot) {\n const first = p.options.out[0];\n const shot = `${(typeof first === 'string' ? first : first.file).replace(/\\.[^./]+$/, '')}.failure.png`;\n writeFileSync(shot, e.screenshot);\n io.error(`the page at that moment: ${shot}`);\n }\n return 1;\n }\n}\n\nconst readJson = (file: string): unknown => {\n try { return JSON.parse(readFileSync(file, 'utf8')); } catch (e) { throw new Error(`could not read ${file}: ${(e as Error).message}`); }\n};\n\n/** suggest <trace.json> --task … --ai …: suggestions, numbered, as JSON (stdout or --out). */\nasync function suggestCmd(argv: string[], io: { log: (m: string) => void }): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {\n task: { type: 'string' }, ai: { type: 'string' }, tone: { type: 'string' }, hints: { type: 'string' }, out: { type: 'string' }, 'send-typed': { type: 'boolean' },\n } });\n const [file] = positionals;\n if (!file) throw new UsageError('suggest needs a trace file');\n const task = values.task;\n if (task !== 'captions' && task !== 'title' && task !== 'waits' && task !== 'narration') throw new UsageError('--task is captions, title, waits or narration');\n if (!values.ai) throw new UsageError('suggest needs --ai');\n if (task === 'narration') {\n // A script file for --script: a person edits it before rendering.\n const r = await suggestScript(await providerOf(values.ai), readJson(file) as Parameters<typeof suggestScript>[1]);\n const out = JSON.stringify({ ...r.script, ...(r.dropped.length ? { dropped: r.dropped } : {}) }, null, 2);\n if (values.out) { writeFileSync(values.out, `${out}\\n`); io.log(`${r.script.lines.length} line${r.script.lines.length === 1 ? '' : 's'} in ${values.out}: edit them, then --script ${values.out}`); } else io.log(out);\n return 0;\n }\n const tone = values.tone;\n if (tone !== undefined && tone !== 'friendly' && tone !== 'terse' && tone !== 'formal') throw new UsageError('--tone is friendly, terse or formal');\n const trace = readJson(file) as Parameters<typeof suggest>[1];\n const hints = values.hints ? (readJson(values.hints) as Parameters<typeof suggest>[2]['hints']) : undefined;\n const r = await suggest(task, trace, { ai: await providerOf(values.ai), ...(hints ? { hints } : {}), ...(tone ? { tone } : {}), ...(values['send-typed'] ? { sendTyped: true } : {}) });\n const out = JSON.stringify({ task, suggestions: r.suggestions.map((sg, k) => ({ id: k + 1, ...sg })), dropped: r.dropped }, null, 2);\n if (values.out) { writeFileSync(values.out, `${out}\\n`); io.log(`${r.suggestions.length} suggestion${r.suggestions.length === 1 ? '' : 's'} in ${values.out}`); } else io.log(out);\n return 0;\n}\n\n/** apply <trace.json> <suggestions.json> --accept 1,3|all --out new.trace.json */\nasync function applyCmd(argv: string[], io: { log: (m: string) => void }): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { accept: { type: 'string' }, out: { type: 'string' } } });\n const [file, sugFile] = positionals;\n if (!file || !sugFile) throw new UsageError('apply needs a trace file and a suggestions file');\n if (!values.accept) throw new UsageError('apply needs --accept 1,3 (or all): a person picks what goes in');\n if (!values.out) throw new UsageError('apply needs --out for the new trace');\n const all = (readJson(sugFile) as { suggestions?: Array<Suggestion & { id: number }> }).suggestions ?? [];\n const ids = values.accept === 'all' ? all.map((x) => x.id) : values.accept.split(',').map((x) => Number(x.trim()));\n const missing = ids.filter((id) => !all.some((x) => x.id === id));\n if (missing.length) throw new UsageError(`no suggestion ${missing.join(', ')} in ${sugFile}`);\n const next = applySuggestions(readJson(file) as Parameters<typeof applySuggestions>[0], all.filter((x) => ids.includes(x.id)));\n writeFileSync(values.out, `${JSON.stringify(next, null, 2)}\\n`);\n io.log(`applied ${ids.length} of ${all.length} to ${values.out}`);\n return 0;\n}\n\n/** catalogue check <file|url> [--fetch] [--json]: 0 it keeps the spec, 1 it doesn't. */\nasync function catalogueCmd(argv: string[], io: { log: (m: string) => void; error: (m: string) => void }): Promise<number> {\n const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { fetch: { type: 'boolean' }, json: { type: 'boolean' }, 'allow-http': { type: 'boolean' } } });\n const [sub, where] = positionals;\n if (sub !== 'check' || !where) throw new UsageError('catalogue check needs a file or a link');\n let doc: unknown;\n if (/^https?:\\/\\//.test(where)) {\n const res = await fetch(where);\n if (!res.ok) throw new Error(`${where} answered ${res.status}`);\n doc = await res.json();\n } else {\n if (!existsSync(where)) throw new UsageError(`no file ${where}`);\n doc = readJson(where);\n }\n const r = await checkCatalogue(doc, { fetch: !!values.fetch, allowHttp: !!values['allow-http'] });\n if (values.json) { io.log(JSON.stringify(r, null, 2)); return r.ok ? 0 : 1; }\n for (const p of r.problems) io.error(`✗ ${p}`);\n for (const w of r.warnings) io.log(`warning: ${w}`);\n io.log(`${where}: ${r.videos} video${r.videos === 1 ? '' : 's'}${values.fetch ? `, ${r.fetched} link${r.fetched === 1 ? '' : 's'} fetched` : ''} — ${r.ok ? 'keeps trace-avatar-catalogue/1' : `${r.problems.length} problem${r.problems.length === 1 ? '' : 's'}`}${r.warnings.length ? `, ${r.warnings.length} warning${r.warnings.length === 1 ? '' : 's'}` : ''}`);\n return r.ok ? 0 : 1;\n}\n\nconst isMain = import.meta.url === `file://${process.argv[1]}` || process.argv[1]?.endsWith('/trace-avatar-render') || process.argv[1]?.endsWith('/cli.js');\nif (is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enderError;
956
956
  }): Promise<RepairOutcome>;
957
957
 
958
- export { type Action, type Brand, CANVASES, CORNERS, type CameraOptions, type Canvas, type CanvasSpec, type Capture, type CaptureOptions, type CapturedFrame, type CardOptions, type Corner, type Cue, DEFAULT_BACKGROUND, DEFAULT_MAX_WAIT_MS, type EditOptions, type FinishOptions, type FrameStyle, GEMINI_TTS, type GifOptions, type GifResult, type GifWriter, type Image, type Layers, type Layout, type NarrationPlan, type OutFormat, type OutSpec, type Pcm, type Phase, type PlanOptions, type PlannedLine, type Rect, RenderError, type RenderOptions, type RenderOutput, type RenderResult, type RepairOutcome, type RepairSuggestion, type Script, type Segment, type Span, TRACK_RATE, type TimelineEvent, type Unresolved, type Voice, type Watermark, ZOOM_KINDS, actionsOf, badgeAt, blank, brandFile, brandOf, cached, cameraKeys, cameraPath, canvasOf, captionCues, capture, cardFrames, cardOf, chapterCues, createGifWriter, createLayers, crop, crossfade, cueAt, dataUri, drawRegion, durationOf, editList, encodeGif, encodeMp4, findFfmpeg, findPlayer, finish, fitWidth, formatOf, frameTimes, fromS16le, fromWav, geminiVoice, layoutOf, linesOf, mix, mp4Args, msOf, narrationText, openAiVoice, outputAt, overlay, pageAt, paletteOf, parseScript, pickFrames, pixel, planNarration, providerOf, render, repairGuide, repairScriptOf, resample, resize, runQa, sayVoice, sourceAt, spansOf, stallInspector, stepCues, suggestScript, toVtt, toWav, trimSilence, voiceOf, watermarkOf, withCards, withHolds };
958
+ /**
959
+ * The clip catalogue, `trace-avatar-catalogue/1` (schemas/catalogue-1.json): a public JSON file listing a product's
960
+ * published marketing videos, one entry per file and shape, so anything (a scheduler such as DutyCaptain, a site) can
961
+ * pick a clip and write about it from the clip's own words (`says`).
962
+ *
963
+ * const r = checkCatalogue(json); // the rules a file can show by itself
964
+ * const r = await checkCatalogue(json, { fetch: true }); // …and its links: reachable, the right type, captions that
965
+ * // fit the video, an mp4 that starts playing before it has all loaded
966
+ *
967
+ * Problems break the spec; warnings are advice (a reader still works). Unknown fields are allowed.
968
+ */
969
+ declare const CATALOGUE_SPEC = "trace-avatar-catalogue/1";
970
+ declare const CATALOGUE_KINDS: readonly ["intro", "demo", "guide", "onboarding", "pitch", "whats-new", "ad", "docs-gif", "qa", "support"];
971
+ declare const CATALOGUE_SHAPES: readonly ["16:9", "1:1", "4:5", "9:16"];
972
+ declare const CATALOGUE_FORMATS: readonly ["mp4", "gif"];
973
+ /** The fields every entry has. */
974
+ declare const CATALOGUE_REQUIRED: readonly ["id", "product", "video", "kind", "preset", "shape", "format", "url", "captionsBurned", "seconds", "narrated", "alt", "site", "made"];
975
+ interface CatalogueEntry {
976
+ id: string;
977
+ product: string;
978
+ video: string;
979
+ kind: (typeof CATALOGUE_KINDS)[number];
980
+ preset: string;
981
+ shape: (typeof CATALOGUE_SHAPES)[number] | null;
982
+ format: (typeof CATALOGUE_FORMATS)[number];
983
+ url: string;
984
+ poster?: string;
985
+ captions?: string;
986
+ /** Two letters; `en` when absent. */
987
+ language?: string;
988
+ captionsBurned: boolean;
989
+ seconds: number;
990
+ narrated: boolean;
991
+ title?: string | null;
992
+ alt: string;
993
+ /** The video's own words, in order: its captions (the spoken lines when narrated) and its cards' lines. */
994
+ says?: string[];
995
+ site: string;
996
+ endsWith?: string;
997
+ made: string;
998
+ [more: string]: unknown;
999
+ }
1000
+ interface Catalogue {
1001
+ spec: typeof CATALOGUE_SPEC;
1002
+ updated: string;
1003
+ videos: CatalogueEntry[];
1004
+ [more: string]: unknown;
1005
+ }
1006
+ interface CatalogueCheck {
1007
+ ok: boolean;
1008
+ problems: string[];
1009
+ warnings: string[];
1010
+ /** Entries checked. */
1011
+ videos: number;
1012
+ /** Links fetched (with `fetch`). */
1013
+ fetched: number;
1014
+ }
1015
+ /** An entry's id as the spec recommends: <product>/<video>/<preset>/<shape|gif>. Stable across re-renders. */
1016
+ declare function catalogueId(e: Pick<CatalogueEntry, 'product' | 'video' | 'preset' | 'shape' | 'format'>): string;
1017
+ /** WebVTT cue end times, in seconds. Throws when it is not WebVTT. */
1018
+ declare function vttEnds(text: string): number[];
1019
+ /**
1020
+ * An mp4's top-level boxes from its first bytes: whether `moov` (what a player needs first) comes before `mdat` (the
1021
+ * media), and, when moov is all there, which codecs it names.
1022
+ */
1023
+ declare function mp4Head(bytes: Uint8Array): {
1024
+ faststart: boolean | null;
1025
+ codecs: string[] | null;
1026
+ };
1027
+ interface CheckOptions {
1028
+ /** Fetch every link too (no cookies): reachable, its type, the captions' length, the mp4's head. */
1029
+ fetch?: boolean;
1030
+ /** The fetch to use (tests). */
1031
+ fetcher?: typeof fetch;
1032
+ /** Links fetched at once (default 6). */
1033
+ concurrency?: number;
1034
+ /** Allow http:// links (a local test server); the spec wants https. */
1035
+ allowHttp?: boolean;
1036
+ }
1037
+ /** Check a catalogue against trace-avatar-catalogue/1. With `fetch`, its links too. */
1038
+ declare function checkCatalogue(doc: unknown, o?: CheckOptions): Promise<CatalogueCheck>;
1039
+
1040
+ export { type Action, type Brand, CANVASES, CATALOGUE_FORMATS, CATALOGUE_KINDS, CATALOGUE_REQUIRED, CATALOGUE_SHAPES, CATALOGUE_SPEC, CORNERS, type CameraOptions, type Canvas, type CanvasSpec, type Capture, type CaptureOptions, type CapturedFrame, type CardOptions, type Catalogue, type CatalogueCheck, type CatalogueEntry, type CheckOptions, type Corner, type Cue, DEFAULT_BACKGROUND, DEFAULT_MAX_WAIT_MS, type EditOptions, type FinishOptions, type FrameStyle, GEMINI_TTS, type GifOptions, type GifResult, type GifWriter, type Image, type Layers, type Layout, type NarrationPlan, type OutFormat, type OutSpec, type Pcm, type Phase, type PlanOptions, type PlannedLine, type Rect, RenderError, type RenderOptions, type RenderOutput, type RenderResult, type RepairOutcome, type RepairSuggestion, type Script, type Segment, type Span, TRACK_RATE, type TimelineEvent, type Unresolved, type Voice, type Watermark, ZOOM_KINDS, actionsOf, badgeAt, blank, brandFile, brandOf, cached, cameraKeys, cameraPath, canvasOf, captionCues, capture, cardFrames, cardOf, catalogueId, chapterCues, checkCatalogue, createGifWriter, createLayers, crop, crossfade, cueAt, dataUri, drawRegion, durationOf, editList, encodeGif, encodeMp4, findFfmpeg, findPlayer, finish, fitWidth, formatOf, frameTimes, fromS16le, fromWav, geminiVoice, layoutOf, linesOf, mix, mp4Args, mp4Head, msOf, narrationText, openAiVoice, outputAt, overlay, pageAt, paletteOf, parseScript, pickFrames, pixel, planNarration, providerOf, render, repairGuide, repairScriptOf, resample, resize, runQa, sayVoice, sourceAt, spansOf, stallInspector, stepCues, suggestScript, toVtt, toWav, trimSilence, voiceOf, vttEnds, watermarkOf, withCards, withHolds };
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import {
2
2
  CANVASES,
3
+ CATALOGUE_FORMATS,
4
+ CATALOGUE_KINDS,
5
+ CATALOGUE_REQUIRED,
6
+ CATALOGUE_SHAPES,
7
+ CATALOGUE_SPEC,
3
8
  CORNERS,
4
9
  DEFAULT_BACKGROUND,
5
10
  DEFAULT_MAX_WAIT_MS,
@@ -20,7 +25,9 @@ import {
20
25
  capture,
21
26
  cardFrames,
22
27
  cardOf,
28
+ catalogueId,
23
29
  chapterCues,
30
+ checkCatalogue,
24
31
  createGifWriter,
25
32
  createLayers,
26
33
  crop,
@@ -45,6 +52,7 @@ import {
45
52
  linesOf,
46
53
  mix,
47
54
  mp4Args,
55
+ mp4Head,
48
56
  msOf,
49
57
  narrationText,
50
58
  openAiVoice,
@@ -73,12 +81,18 @@ import {
73
81
  toWav,
74
82
  trimSilence,
75
83
  voiceOf,
84
+ vttEnds,
76
85
  watermarkOf,
77
86
  withCards,
78
87
  withHolds
79
- } from "./chunk-ZNHFXKD3.js";
88
+ } from "./chunk-PPVNEPXF.js";
80
89
  export {
81
90
  CANVASES,
91
+ CATALOGUE_FORMATS,
92
+ CATALOGUE_KINDS,
93
+ CATALOGUE_REQUIRED,
94
+ CATALOGUE_SHAPES,
95
+ CATALOGUE_SPEC,
82
96
  CORNERS,
83
97
  DEFAULT_BACKGROUND,
84
98
  DEFAULT_MAX_WAIT_MS,
@@ -99,7 +113,9 @@ export {
99
113
  capture,
100
114
  cardFrames,
101
115
  cardOf,
116
+ catalogueId,
102
117
  chapterCues,
118
+ checkCatalogue,
103
119
  createGifWriter,
104
120
  createLayers,
105
121
  crop,
@@ -124,6 +140,7 @@ export {
124
140
  linesOf,
125
141
  mix,
126
142
  mp4Args,
143
+ mp4Head,
127
144
  msOf,
128
145
  narrationText,
129
146
  openAiVoice,
@@ -152,6 +169,7 @@ export {
152
169
  toWav,
153
170
  trimSilence,
154
171
  voiceOf,
172
+ vttEnds,
155
173
  watermarkOf,
156
174
  withCards,
157
175
  withHolds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trace-avatar-render",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "description": "Render a trace-avatar guide to a GIF or MP4 by playing it on your real app in headless Chromium.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,10 +13,12 @@
13
13
  "types": "./dist/index.d.ts",
14
14
  "import": "./dist/index.js"
15
15
  },
16
- "./package.json": "./package.json"
16
+ "./package.json": "./package.json",
17
+ "./schemas/catalogue-1.json": "./schemas/catalogue-1.json"
17
18
  },
18
19
  "files": [
19
20
  "dist",
21
+ "schemas",
20
22
  "README.md",
21
23
  "CHANGELOG.md",
22
24
  "LICENSE"
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://traceavatar.com/schemas/catalogue-1.json",
4
+ "title": "trace-avatar-catalogue/1",
5
+ "description": "A product's published marketing videos: one entry per file and shape. `trace-avatar-render catalogue check` checks this and the rules a schema can't (unique ids, captions that fit the video, links that answer).",
6
+ "type": "object",
7
+ "required": ["spec", "updated", "videos"],
8
+ "properties": {
9
+ "spec": { "const": "trace-avatar-catalogue/1" },
10
+ "updated": { "type": "string", "format": "date-time" },
11
+ "videos": { "type": "array", "items": { "$ref": "#/$defs/entry" } }
12
+ },
13
+ "$defs": {
14
+ "word": { "type": "string", "pattern": "^\\S+$" },
15
+ "https": { "type": "string", "format": "uri", "pattern": "^https://" },
16
+ "entry": {
17
+ "type": "object",
18
+ "required": ["id", "product", "video", "kind", "preset", "shape", "format", "url", "captionsBurned", "seconds", "narrated", "alt", "site", "made"],
19
+ "properties": {
20
+ "id": { "$ref": "#/$defs/word", "description": "Stable across re-renders: <product>/<video>/<preset>/<shape|gif>." },
21
+ "product": { "$ref": "#/$defs/word", "description": "The product it promotes." },
22
+ "video": { "$ref": "#/$defs/word", "description": "The video it is a cut of; its shapes share it." },
23
+ "kind": { "enum": ["intro", "demo", "guide", "onboarding", "pitch", "whats-new", "ad", "docs-gif", "qa", "support"] },
24
+ "preset": { "$ref": "#/$defs/word", "description": "The look: product (its own brand) or another." },
25
+ "shape": { "enum": ["16:9", "1:1", "4:5", "9:16", null], "description": "The canvas; null for a GIF." },
26
+ "format": { "enum": ["mp4", "gif"] },
27
+ "url": { "$ref": "#/$defs/https", "description": "The file. Content-addressed and cached forever is recommended." },
28
+ "poster": { "$ref": "#/$defs/https" },
29
+ "captions": { "$ref": "#/$defs/https", "description": "WebVTT, when the captions are not burned in." },
30
+ "language": { "type": "string", "pattern": "^[a-z]{2}$", "description": "The captions' and narration's language; en when absent." },
31
+ "captionsBurned": { "type": "boolean" },
32
+ "seconds": { "type": "number", "exclusiveMinimum": 0 },
33
+ "narrated": { "type": "boolean" },
34
+ "title": { "type": ["string", "null"] },
35
+ "alt": { "type": "string", "minLength": 1, "description": "What it shows, plainly." },
36
+ "says": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 }, "description": "The video's own words, in order: its captions (the spoken lines when narrated) and its cards' lines." },
37
+ "site": { "$ref": "#/$defs/https" },
38
+ "endsWith": { "type": "string", "description": "What its last card says." },
39
+ "made": { "type": "string", "format": "date-time" }
40
+ },
41
+ "allOf": [
42
+ { "if": { "properties": { "format": { "const": "gif" } } }, "then": { "properties": { "shape": { "const": null } } } },
43
+ { "if": { "properties": { "format": { "const": "mp4" } } }, "then": { "properties": { "shape": { "enum": ["16:9", "1:1", "4:5", "9:16"] } } } },
44
+ { "if": { "properties": { "captionsBurned": { "const": true } }, "required": ["captionsBurned"] }, "then": { "not": { "required": ["captions"] } } }
45
+ ]
46
+ }
47
+ }
48
+ }