vizmatic 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/PROMPT.md +28 -8
  2. package/README.md +14 -2
  3. package/dist/cli.js +192 -49
  4. package/dist/index.cjs +85 -27
  5. package/dist/index.d.cts +10 -6
  6. package/dist/index.d.ts +10 -6
  7. package/dist/index.js +85 -27
  8. package/docs/PROMPT.md +28 -8
  9. package/docs/assets/examples/agent-pipeline_dark.png +0 -0
  10. package/docs/assets/examples/agent-pipeline_light.png +0 -0
  11. package/docs/assets/examples/animated-pipeline_dark.png +0 -0
  12. package/docs/assets/examples/animated-pipeline_light.png +0 -0
  13. package/docs/assets/examples/attention-head_dark.png +0 -0
  14. package/docs/assets/examples/attention-head_light.png +0 -0
  15. package/docs/assets/examples/embedding-map_dark.png +0 -0
  16. package/docs/assets/examples/embedding-map_light.png +0 -0
  17. package/docs/assets/examples/eval-dashboard_dark.png +0 -0
  18. package/docs/assets/examples/eval-dashboard_light.png +0 -0
  19. package/docs/assets/examples/manifest.json +16 -0
  20. package/docs/assets/examples/model-router_dark.png +0 -0
  21. package/docs/assets/examples/model-router_light.png +0 -0
  22. package/docs/assets/examples/presentation-frame_dark.png +0 -0
  23. package/docs/assets/examples/presentation-frame_light.png +0 -0
  24. package/docs/assets/examples/rag-graph_dark.png +0 -0
  25. package/docs/assets/examples/rag-graph_light.png +0 -0
  26. package/docs/assets/examples/release-card_dark.png +0 -0
  27. package/docs/assets/examples/release-card_light.png +0 -0
  28. package/docs/assets/examples/research-landscape_dark.png +0 -0
  29. package/docs/assets/examples/research-landscape_light.png +0 -0
  30. package/docs/assets/examples/sources.json +26 -6
  31. package/docs/assets/examples/spec-anatomy_dark.png +0 -0
  32. package/docs/assets/examples/spec-anatomy_light.png +0 -0
  33. package/docs/assets/examples/theme-background_dark.png +0 -0
  34. package/docs/assets/examples/theme-background_light.png +0 -0
  35. package/docs/assets/examples/theme-system_dark.png +0 -0
  36. package/docs/assets/examples/theme-system_light.png +0 -0
  37. package/docs/assets/examples/token-matrix_dark.png +0 -0
  38. package/docs/assets/examples/token-matrix_light.png +0 -0
  39. package/docs/assets/examples/transparent-badge_dark.png +0 -0
  40. package/docs/assets/examples/transparent-badge_light.png +0 -0
  41. package/examples/README.md +2 -0
  42. package/examples/model-router.tsx +1 -1
  43. package/examples/research-landscape.tsx +1 -1
  44. package/examples/theme-background.tsx +15 -0
  45. package/examples/transparent-badge.tsx +15 -0
  46. package/examples/vizmatic-bare.d.ts +1 -0
  47. package/package.json +1 -1
package/PROMPT.md CHANGED
@@ -105,7 +105,23 @@ Render it:
105
105
  vizmatic frames --out public/vizmatic --theme dark,light --watermark "Your Product" --watermark-image ./logo.svg --watermark-position top-right
106
106
  ```
107
107
 
108
- For direct CLI frames, skip imports, `defineIllustration`, and `c` props by default. The CLI injects Vizmatic primitives and theme colors. Use the full module form when you need custom dependencies, direct renderer APIs, advanced reusable JSX helpers, or animation exports.
108
+ PNG and SVG renders use alpha-transparent canvas backgrounds by default. Use the actual theme background when the host needs a full-frame image:
109
+
110
+ ```bash
111
+ vizmatic frames --out public/vizmatic --theme dark,light --background theme
112
+ ```
113
+
114
+ Or set it in the frame:
115
+
116
+ ```tsx
117
+ <Scene background={c.bg} title="Opaque article figure">
118
+ <Flow stages={[{ title: "Theme fill", tone: "purple" }]} />
119
+ </Scene>
120
+ ```
121
+
122
+ If a direct CLI frame omits `width` or `height`, Vizmatic starts at `960x540` and grows omitted axes when overflow is detected. Explicit dimensions stay strict and should be used when exact output size matters.
123
+
124
+ For direct CLI frames, skip imports, `defineIllustration`, and `c` props by default. The CLI injects Vizmatic primitives and theme colors. Reference `c` only when you need explicit theme tokens such as `background={c.bg}`. Use the full module form when you need custom dependencies, direct renderer APIs, advanced reusable JSX helpers, or animation exports.
109
125
 
110
126
  Frame modules can also export a watermark element when code-owned branding is clearer than CLI flags:
111
127
 
@@ -204,16 +220,18 @@ Shared values:
204
220
  - `ColorName`: `"primary" | "secondary" | "positive" | "warning" | "critical" | "info" | "accent" | "neutral"`.
205
221
  - `FlexAlign`: `"start" | "center" | "end" | "stretch"`.
206
222
  - `FlexJustify`: `"start" | "center" | "end" | "space-between" | "space-around"`.
207
- - In bare CLI frames, omit `c`; the CLI injects theme colors into Vizmatic components.
223
+ - In bare CLI frames, omit `c` props; the CLI injects theme colors into Vizmatic components. The local `c` token object is still available for explicit values like `background={c.bg}`.
208
224
  - In full modules, most visual components require `c: ThemeColors`; inside `defineIllustration((c) => ...)`, pass that same `c` down.
225
+ - PNG/SVG renders are alpha-transparent by default. Use `--background theme`, `background: "theme"`, or `<Scene background={c.bg}>` for opaque theme fill.
226
+ - Omitted CLI dimensions auto-grow on overflow. Explicit `width` / `height` remain fixed and fail on clipping.
209
227
 
210
228
  ## Component API
211
229
 
212
230
  Frame helpers:
213
231
 
214
232
  - `defineIllustration(build, defaultTheme?)`: `build: (c: ThemeColors) => ReactElement`, `defaultTheme?: ThemeMode = "dark"`. Returns `{ create(theme), default }`.
215
- - `Canvas`: `children?`, `c`, `padding?: number = 40`, `justify?: "center" | "flex-start" | "space-between" | "space-around" = "center"`, `background?: string`.
216
- - `Scene`: `c`, `children`, `title?`, `subtitle?`, `padding?: number = 40`, `gap?: number = 24`, `justify?: Canvas.justify = "flex-start"`, `align?: FlexAlign = "stretch"`, `contentWidth?: number | string = "100%"`, `background?`, `contentStyle?: React.CSSProperties`.
233
+ - `Canvas`: `children?`, `c`, `padding?: number = 40`, `justify?: "center" | "flex-start" | "space-between" | "space-around" = "center"`, `background?: string`. Default root background is alpha-transparent during PNG/SVG rendering.
234
+ - `Scene`: `c`, `children`, `title?`, `subtitle?`, `padding?: number = 40`, `gap?: number = 24`, `justify?: Canvas.justify = "flex-start"`, `align?: FlexAlign = "stretch"`, `contentWidth?: number | string = "100%"`, `background?`, `contentStyle?: React.CSSProperties`. Use `background={c.bg}` for an opaque theme frame.
217
235
  - `TitleBar`: `title`, `subtitle?`, `c`.
218
236
 
219
237
  Layout primitives:
@@ -315,12 +333,12 @@ Theme and render APIs:
315
333
  - `WatermarkInput`: `boolean | string | WatermarkOptions | ReactElement<WatermarkElementProps>`. `true` uses Vizmatic defaults. A string sets the watermark text. A React element can be `<Watermark>...</Watermark>` or any custom element.
316
334
  - `WatermarkImageOptions`: `src`, `width?: number`, `height?: number`, `alt?: string`. Programmatic `src` should be a URL or data URI. CLI `--watermark-image` accepts URL, data URI, or local path.
317
335
  - `WatermarkOptions`: `text?: string | false`, `image?: string | WatermarkImageOptions`, `icon?: ReactNode | string | false`, `element?: ReactNode`, `position?: "top-left" | "top-right" | "bottom-left" | "bottom-right" = "top-right"`, `opacity?: number`, `color?: string`.
318
- - `RenderOptions`: `width`, `height`, `outputPath`, `watermark?: WatermarkInput`, `brand?: boolean | string` as a compatibility alias, `crop?: boolean = true`, `scale?: number = 2`.
319
- - `renderToBuffer(element, width, height, options?)`: `options` supports `watermark?`, `brand?`, `scale?`.
320
- - `renderToSvg(element, width, height, options?)`: `options` supports `watermark?`, `brand?`.
336
+ - `RenderOptions`: `width`, `height`, `outputPath`, `background?: "transparent" | "theme" | CSS color = "transparent"`, `watermark?: WatermarkInput`, `brand?: boolean | string` as a compatibility alias, `crop?: boolean = true`, `scale?: number = 2`.
337
+ - `renderToBuffer(element, width, height, options?)`: `options` supports `background?`, `watermark?`, `brand?`, `scale?`.
338
+ - `renderToSvg(element, width, height, options?)`: `options` supports `background?`, `watermark?`, `brand?`.
321
339
  - `renderAnimatedGif(scenes, options)`: `scenes: AnimatedScene[]`, `options: AnimationOptions`.
322
340
  - `AnimatedScene`: `element`, `duration` in ms, `transition?: "none" | "fade" | "appear"`, `transitionDuration?`, `label?`.
323
- - `AnimationOptions`: `width`, `height`, `outputPath`, `loop?: number = 0`, `scale?: number = 1`, `watermark?: WatermarkInput`, `brand?: boolean | string` as a compatibility alias, `theme?: "dark" | "light" = "dark"`.
341
+ - `AnimationOptions`: `width`, `height`, `outputPath`, `loop?: number = 0`, `scale?: number = 1`, `background?: "theme" | "transparent" | CSS color = "theme"` for GIF reliability, `watermark?: WatermarkInput`, `brand?: boolean | string` as a compatibility alias, `theme?: "dark" | "light" = "dark"`.
324
342
 
325
343
  ## Prop-aware examples
326
344
 
@@ -400,6 +418,8 @@ height = 560;
400
418
 
401
419
  - Use semantic tones, not hard-coded colors: `blue`, `purple`, `green`, `warm`, `cyan`, `pink`, `critical`, `ocean`, `neutral`.
402
420
  - Keep canvas sizes explicit. Good defaults: `1040x560` for article figures, `1280x720` for slide frames, `900x520` for compact diagrams.
421
+ - For exploratory direct CLI frames, dimensions may be omitted; Vizmatic auto-grows omitted axes if content overflows.
422
+ - Prefer alpha-transparent PNG/SVG backgrounds for blog embeds and docs cards. Use theme backgrounds only when the host surface is unknown or needs full-frame fill.
403
423
  - Use `width`, `minWidth`, `height`, `minHeight`, `gap`, and `padding` props to stabilize layout.
404
424
  - Keep text short. Use `TextLabel`, `Panel`, `StepCard`, `MetricCard`, `DataTable`, and `Grid` for wrapping-safe labels.
405
425
  - Render both dark and light when shipping reusable assets: `--theme dark,light`.
package/README.md CHANGED
@@ -44,6 +44,14 @@ Then render any frame directly:
44
44
  vizmatic ./frame.tsx --out ./dist/frames --theme dark,light
45
45
  ```
46
46
 
47
+ PNG and SVG renders use an alpha-transparent canvas by default. Add `--background theme` when the output needs the actual dark/light theme fill:
48
+
49
+ ```bash
50
+ vizmatic ./frame.tsx --out ./dist/frames --theme dark,light --background theme
51
+ ```
52
+
53
+ If a CLI frame omits `width` or `height`, Vizmatic starts at `960x540` and grows omitted axes when overflow is detected. Explicit dimensions stay strict and fail on clipping.
54
+
47
55
  Bare CLI frames auto-import Vizmatic primitives and inject theme colors. Use normal imports when a frame needs helpers, data loading, custom dependencies, or direct renderer APIs.
48
56
 
49
57
  Install it in the project when you want scripts, editor types, or direct renderer APIs:
@@ -151,6 +159,8 @@ Render it:
151
159
  vizmatic ./frame.tsx --out ./dist/frames --theme dark,light --watermark "Acme" --watermark-image ./logo.svg
152
160
  ```
153
161
 
162
+ The PNG canvas is alpha-transparent by default. Use `--background theme` for an opaque theme-colored frame, or set `background={c.bg}` on `Scene` / `Canvas`.
163
+
154
164
  Render an animation:
155
165
 
156
166
  ```bash
@@ -167,6 +177,7 @@ await renderToPng(create("dark"), {
167
177
  width,
168
178
  height,
169
179
  outputPath: "dist/agent-pipeline.png",
180
+ background: "theme", // omit for alpha-transparent output
170
181
  watermark: { text: "Acme", image: "data:image/svg+xml;base64,...", position: "top-right" },
171
182
  })
172
183
  ```
@@ -452,7 +463,7 @@ Vizmatic exports a fairly complete visual kit. Common cases should use these pri
452
463
  | Component | Use |
453
464
  |---|---|
454
465
  | `defineIllustration` | Wraps a theme-aware frame builder and exports `create(theme)` plus a default element. |
455
- | `Canvas` | Low-level full-frame root with background, padding, and vertical alignment. |
466
+ | `Canvas` | Low-level full-frame root with alpha-transparent default background, optional background fill, padding, and vertical alignment. |
456
467
  | `Scene` | Standard frame wrapper with title, subtitle, content column, and theme-aware typography. |
457
468
  | `TitleBar` | Shared title/subtitle block used by `Scene`. |
458
469
  | `Row` / `Column` | Flex layout primitives with gap, alignment, wrapping, width, and height props. |
@@ -558,13 +569,14 @@ Vizmatic exports a fairly complete visual kit. Common cases should use these pri
558
569
  import { renderAnimatedGif, renderToPng, renderToBuffer, renderToSvg } from "vizmatic"
559
570
  ```
560
571
 
561
- `renderToPng` renders at 2x scale by default, checks for clipped content, crops extra vertical whitespace, and can apply an optional watermark. Use `watermark.image` for a URL or data URI; the CLI also accepts local image paths through `--watermark-image`. For frame-owned branding, export `watermark = <Watermark>...</Watermark>` from the frame module. `brand` still works as a compatibility alias.
572
+ `renderToPng` renders at 2x scale by default, uses alpha transparency unless `background` is set, checks for clipped content, crops extra vertical whitespace, and can apply an optional watermark. Use `background: "theme"` to paint `c.bg`, or any CSS color string for a fixed fill. Use `watermark.image` for a URL or data URI; the CLI also accepts local image paths through `--watermark-image`. For frame-owned branding, export `watermark = <Watermark>...</Watermark>` from the frame module. `brand` still works as a compatibility alias.
562
573
 
563
574
  ```ts
564
575
  await renderToPng(element, {
565
576
  width: 1040,
566
577
  height: 560,
567
578
  outputPath: "dist/frame.png",
579
+ background: "theme",
568
580
  watermark: { text: "Your Product", image: "https://example.com/logo.svg", position: "top-right" },
569
581
  crop: true,
570
582
  scale: 2,
package/dist/cli.js CHANGED
@@ -373,6 +373,21 @@ function lerpColor(a, b, t) {
373
373
 
374
374
  // src/primitives.ts
375
375
  import React from "react";
376
+
377
+ // src/renderContext.ts
378
+ import { AsyncLocalStorage } from "async_hooks";
379
+ var RENDER_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("vizmatic.renderContext");
380
+ var globalRenderContext = globalThis;
381
+ var renderContext = globalRenderContext[RENDER_CONTEXT_KEY] ??= new AsyncLocalStorage();
382
+ function getRenderBackground() {
383
+ return renderContext.getStore()?.background ?? "transparent";
384
+ }
385
+ async function withRenderContext(context, render) {
386
+ const parent = renderContext.getStore();
387
+ return renderContext.run({ ...parent, ...context }, render);
388
+ }
389
+
390
+ // src/primitives.ts
376
391
  function defineIllustration(build, defaultTheme = "dark") {
377
392
  return {
378
393
  create(theme) {
@@ -382,6 +397,8 @@ function defineIllustration(build, defaultTheme = "dark") {
382
397
  };
383
398
  }
384
399
  function Canvas({ children, c, padding = 40, justify = "center", background }) {
400
+ const renderBackground = getRenderBackground();
401
+ const canvasBackground = background ?? (renderBackground === "theme" ? c.bg : renderBackground);
385
402
  return React.createElement("div", {
386
403
  style: {
387
404
  width: "100%",
@@ -391,7 +408,7 @@ function Canvas({ children, c, padding = 40, justify = "center", background }) {
391
408
  flexDirection: "column",
392
409
  alignItems: "center",
393
410
  justifyContent: justify,
394
- backgroundColor: background ?? c.bg,
411
+ backgroundColor: canvasBackground,
395
412
  fontFamily: "Inter",
396
413
  padding
397
414
  }
@@ -4860,7 +4877,7 @@ function detectBackgroundColor(pixels) {
4860
4877
  const b = pixels[2];
4861
4878
  const a = pixels[3];
4862
4879
  if (a < 10) {
4863
- return "#000000";
4880
+ return "transparent";
4864
4881
  }
4865
4882
  return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
4866
4883
  }
@@ -4872,12 +4889,18 @@ function parseHexColor(hex) {
4872
4889
  parseInt(h.slice(4, 6), 16)
4873
4890
  ];
4874
4891
  }
4875
- function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
4876
- if (a < 10) return true;
4877
- return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4892
+ function createBackgroundMatcher(bgColor, tolerance = 6) {
4893
+ if (bgColor === "transparent") {
4894
+ return (_r, _g, _b, a) => a < 10;
4895
+ }
4896
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
4897
+ return (r, g, b, a) => {
4898
+ if (a < 10) return true;
4899
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
4900
+ };
4878
4901
  }
4879
4902
  function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4880
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4903
+ const isBackground = createBackgroundMatcher(bgColor);
4881
4904
  let minX = width;
4882
4905
  let minY = height;
4883
4906
  let maxX = 0;
@@ -4889,7 +4912,7 @@ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
4889
4912
  const g = pixels[idx + 1];
4890
4913
  const b = pixels[idx + 2];
4891
4914
  const a = pixels[idx + 3];
4892
- if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
4915
+ if (!isBackground(r, g, b, a)) {
4893
4916
  if (x < minX) minX = x;
4894
4917
  if (x > maxX) maxX = x;
4895
4918
  if (y < minY) minY = y;
@@ -4924,20 +4947,12 @@ function cropPixels(pixels, srcWidth, region) {
4924
4947
  return out;
4925
4948
  }
4926
4949
  function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
4927
- const [bgR, bgG, bgB] = parseHexColor(bgColor);
4950
+ const isBackground = createBackgroundMatcher(bgColor);
4928
4951
  function isContentPixel(x, y) {
4929
4952
  const idx = (y * width + x) * 4;
4930
4953
  const a = pixels[idx + 3];
4931
4954
  if (a < alphaThreshold) return false;
4932
- return !isBackground(
4933
- pixels[idx],
4934
- pixels[idx + 1],
4935
- pixels[idx + 2],
4936
- a,
4937
- bgR,
4938
- bgG,
4939
- bgB
4940
- );
4955
+ return !isBackground(pixels[idx], pixels[idx + 1], pixels[idx + 2], a);
4941
4956
  }
4942
4957
  function checkEdge(scanFn, length) {
4943
4958
  for (let offset = 0; offset < edgeTolerance; offset++) {
@@ -4958,13 +4973,13 @@ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDe
4958
4973
  const right = checkEdge((i, off) => [width - 1 - off, i], height);
4959
4974
  const top = checkEdge((i, off) => [i, off], width);
4960
4975
  const left = checkEdge((i, off) => [off, i], height);
4961
- const overflowEdges = [];
4962
- if (top) overflowEdges.push("top");
4963
- if (right) overflowEdges.push("right");
4964
- if (bottom) overflowEdges.push("bottom");
4965
- if (left) overflowEdges.push("left");
4966
- const overflows = overflowEdges.length > 0;
4967
- const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
4976
+ const overflowEdges2 = [];
4977
+ if (top) overflowEdges2.push("top");
4978
+ if (right) overflowEdges2.push("right");
4979
+ if (bottom) overflowEdges2.push("bottom");
4980
+ if (left) overflowEdges2.push("left");
4981
+ const overflows = overflowEdges2.length > 0;
4982
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges2.join(", ")}. Increase the illustration dimensions.` : "";
4968
4983
  return {
4969
4984
  overflows,
4970
4985
  edges: { top, right, bottom, left },
@@ -5161,6 +5176,12 @@ function resolveWatermark(options) {
5161
5176
  return options.watermark ?? options.brand;
5162
5177
  }
5163
5178
  async function renderToPng(element, options, createFn, theme) {
5179
+ return withRenderContext(
5180
+ { background: options.background ?? "transparent" },
5181
+ () => renderToPngInContext(element, options, createFn, theme)
5182
+ );
5183
+ }
5184
+ async function renderToPngInContext(element, options, createFn, theme) {
5164
5185
  const fonts = await getFonts();
5165
5186
  let svg = await satori(element, {
5166
5187
  width: options.width,
@@ -5234,6 +5255,12 @@ async function renderToPng(element, options, createFn, theme) {
5234
5255
  await writeFile(options.outputPath, pngBuffer);
5235
5256
  }
5236
5257
  async function renderToBuffer(element, width, height, options = {}) {
5258
+ return withRenderContext(
5259
+ { background: options.background ?? "transparent" },
5260
+ () => renderToBufferInContext(element, width, height, options)
5261
+ );
5262
+ }
5263
+ async function renderToBufferInContext(element, width, height, options) {
5237
5264
  const fonts = await getFonts();
5238
5265
  const watermark = resolveWatermark(options);
5239
5266
  const outputElement = watermark ? wrapWithWatermark(
@@ -5251,12 +5278,19 @@ async function renderToBuffer(element, width, height, options = {}) {
5251
5278
  });
5252
5279
  svg = sanitizeSvg(svg);
5253
5280
  const resvg = new Resvg(svg, {
5254
- fitTo: { mode: "width", value: width * (options.scale ?? 2) }
5281
+ fitTo: { mode: "width", value: width * (options.scale ?? 2) },
5282
+ background: "rgba(0, 0, 0, 0)"
5255
5283
  });
5256
5284
  const pngData = resvg.render();
5257
5285
  return Buffer.from(pngData.asPng());
5258
5286
  }
5259
5287
  async function renderToSvg(element, width, height, options = {}) {
5288
+ return withRenderContext(
5289
+ { background: options.background ?? "transparent" },
5290
+ () => renderToSvgInContext(element, width, height, options)
5291
+ );
5292
+ }
5293
+ async function renderToSvgInContext(element, width, height, options) {
5260
5294
  const fonts = await getFonts();
5261
5295
  const watermark = resolveWatermark(options);
5262
5296
  const outputElement = watermark ? wrapWithWatermark(
@@ -5291,14 +5325,14 @@ function resolveGifenc(api) {
5291
5325
  throw new Error("gifenc exports could not be resolved");
5292
5326
  }
5293
5327
  var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
5294
- async function renderToPixels(element, width, height, scale) {
5328
+ async function renderToPixels(element, width, height, scale, background) {
5295
5329
  const fonts = await getFonts();
5296
- const svg = await satori(element, {
5330
+ const svg = await withRenderContext({ background }, () => satori(element, {
5297
5331
  width,
5298
5332
  height,
5299
5333
  fonts,
5300
5334
  loadAdditionalAsset
5301
- });
5335
+ }));
5302
5336
  const resvg = new Resvg2(svg, {
5303
5337
  fitTo: { mode: "width", value: width * scale },
5304
5338
  background: "rgba(0, 0, 0, 0)"
@@ -5321,14 +5355,37 @@ function blendPixels(base, overlay, opacity) {
5321
5355
  }
5322
5356
  return result;
5323
5357
  }
5324
- function backgroundPixels(width, height, theme) {
5358
+ function colorForBackground(background, theme) {
5359
+ if (background === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
5360
+ const value = background === "theme" ? getThemeColors(theme).bg : background;
5361
+ const hex = value.match(/^#([0-9a-f]{6})$/i)?.[1];
5362
+ if (hex) {
5363
+ return {
5364
+ r: parseInt(hex.slice(0, 2), 16),
5365
+ g: parseInt(hex.slice(2, 4), 16),
5366
+ b: parseInt(hex.slice(4, 6), 16),
5367
+ a: 255
5368
+ };
5369
+ }
5370
+ const rgb = value.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([0-9.]+))?\s*\)$/i);
5371
+ if (rgb) {
5372
+ return {
5373
+ r: Number(rgb[1]),
5374
+ g: Number(rgb[2]),
5375
+ b: Number(rgb[3]),
5376
+ a: Math.round(Number(rgb[4] ?? "1") * 255)
5377
+ };
5378
+ }
5379
+ return { r: 0, g: 0, b: 0, a: 0 };
5380
+ }
5381
+ function backgroundPixels(width, height, theme, background) {
5325
5382
  const buffer = new Uint8Array(width * height * 4);
5326
- const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
5383
+ const color = colorForBackground(background, theme);
5327
5384
  for (let index = 0; index < buffer.length; index += 4) {
5328
5385
  buffer[index] = color.r;
5329
5386
  buffer[index + 1] = color.g;
5330
5387
  buffer[index + 2] = color.b;
5331
- buffer[index + 3] = 255;
5388
+ buffer[index + 3] = color.a;
5332
5389
  }
5333
5390
  return buffer;
5334
5391
  }
@@ -5356,7 +5413,7 @@ async function scenesToFrames(scenes, options) {
5356
5413
  for (const scene of scenes) {
5357
5414
  const watermark = options.watermark ?? options.brand;
5358
5415
  const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
5359
- renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
5416
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale, options.background));
5360
5417
  }
5361
5418
  const frames = [];
5362
5419
  const scaledWidth = options.width * options.scale;
@@ -5375,7 +5432,7 @@ async function scenesToFrames(scenes, options) {
5375
5432
  const frameDelay = transitionDuration / transitionFrames;
5376
5433
  for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
5377
5434
  const amount = (frameIndex + 1) / transitionFrames;
5378
- const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
5435
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme, options.background), current.pixels, amount);
5379
5436
  frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
5380
5437
  }
5381
5438
  }
@@ -5393,7 +5450,8 @@ async function renderAnimatedGif(scenes, options) {
5393
5450
  ...options,
5394
5451
  loop: options.loop ?? 0,
5395
5452
  scale: options.scale ?? 1,
5396
- theme: options.theme ?? "dark"
5453
+ theme: options.theme ?? "dark",
5454
+ background: options.background ?? "theme"
5397
5455
  };
5398
5456
  await mkdir2(dirname2(options.outputPath), { recursive: true });
5399
5457
  const frames = await scenesToFrames(scenes, normalized);
@@ -5404,6 +5462,12 @@ async function renderAnimatedGif(scenes, options) {
5404
5462
  // src/cli.ts
5405
5463
  var RENDER_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".mjs", ".ts", ".tsx"]);
5406
5464
  var IMPORT_RESOLUTION_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".json"];
5465
+ var DEFAULT_FRAME_WIDTH = 960;
5466
+ var DEFAULT_FRAME_HEIGHT = 540;
5467
+ var AUTO_SIZE_MAX_WIDTH = 1920;
5468
+ var AUTO_SIZE_MAX_HEIGHT = 1440;
5469
+ var AUTO_SIZE_GROWTH = 1.25;
5470
+ var AUTO_SIZE_ATTEMPTS = 6;
5407
5471
  var cliRequire = createRequire(import.meta.url);
5408
5472
  var frameDependencyAliasesInstalled = false;
5409
5473
  var BARE_FRAME_EXTRA_EXPORTS = /* @__PURE__ */ new Set([
@@ -5425,13 +5489,14 @@ var BARE_FRAME_EXTRA_EXPORTS = /* @__PURE__ */ new Set([
5425
5489
  var BARE_FRAME_EXPORTS = Object.keys(index_exports).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name)).filter((name) => /^[A-Z]/.test(name) || BARE_FRAME_EXTRA_EXPORTS.has(name)).sort();
5426
5490
  function usageText() {
5427
5491
  return `Usage:
5428
- vizmatic <file-or-directory...> [--out <dir>] [--theme dark,light] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
5429
- vizmatic render <file-or-directory...> [--out <dir>] [--theme dark,light] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
5492
+ vizmatic <file-or-directory...> [--out <dir>] [--theme dark,light] [--background transparent|theme|color] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
5493
+ vizmatic render <file-or-directory...> [--out <dir>] [--theme dark,light] [--background transparent|theme|color] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
5430
5494
  vizmatic gif <file-or-directory...> [--out <dir>] [--theme dark] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--scale 1]
5431
5495
 
5432
5496
  Examples:
5433
5497
  vizmatic examples/attention-head.tsx --out dist/frames --theme dark,light
5434
5498
  vizmatic ./frame.tsx --out ./dist/frames --theme dark
5499
+ vizmatic ./frame.tsx --out ./dist/frames --theme light --background theme
5435
5500
  vizmatic render examples --out docs/assets/examples --theme dark --watermark Vizmatic
5436
5501
  vizmatic render frames/attention.tsx --out dist/frames --theme dark,light
5437
5502
  vizmatic gif examples/animated-pipeline.tsx --out docs/assets/examples --theme dark --watermark Vizmatic`;
@@ -5609,8 +5674,14 @@ function buildBareFrameModule(framePath, source) {
5609
5674
  if (jsxStart < 0) return void 0;
5610
5675
  const setup = body.slice(0, jsxStart).replace(/^\s*export\s+/gm, "");
5611
5676
  const jsx = body.slice(jsxStart).trim().replace(/^export\s+default\s+/, "").replace(/;\s*$/, "");
5612
- width ??= readFrameDimension(jsx, "width") ?? 960;
5613
- height ??= readFrameDimension(jsx, "height") ?? 540;
5677
+ const frameWidth = readFrameDimension(jsx, "width");
5678
+ const frameHeight = readFrameDimension(jsx, "height");
5679
+ const autoSize = {
5680
+ width: width == null && frameWidth == null,
5681
+ height: height == null && frameHeight == null
5682
+ };
5683
+ width ??= frameWidth ?? DEFAULT_FRAME_WIDTH;
5684
+ height ??= frameHeight ?? DEFAULT_FRAME_HEIGHT;
5614
5685
  const autoImports = bareFrameExportsForSource(body);
5615
5686
  return `/** @jsxRuntime classic */
5616
5687
  import { createRequire as __createRequire } from 'module'
@@ -5630,6 +5701,7 @@ ${buildAutoImportDeclarations(autoImports)}
5630
5701
 
5631
5702
  export const width = ${width}
5632
5703
  export const height = ${height}
5704
+ export const __vizmaticAutoSize = ${JSON.stringify(autoSize)}
5633
5705
 
5634
5706
  export function create(theme = 'dark') {
5635
5707
  __theme = __Vizmatic_getThemeColors(theme)
@@ -5672,6 +5744,7 @@ function parseRenderArgs(argv) {
5672
5744
  let force = false;
5673
5745
  let crop = true;
5674
5746
  let scale;
5747
+ let background;
5675
5748
  function mutableWatermark() {
5676
5749
  if (!watermarkOptions) {
5677
5750
  watermarkOptions = typeof watermark === "object" && watermark !== null && !isValidElement(watermark) ? { ...watermark } : {};
@@ -5751,6 +5824,10 @@ function parseRenderArgs(argv) {
5751
5824
  force = true;
5752
5825
  } else if (arg === "--no-crop") {
5753
5826
  crop = false;
5827
+ } else if (arg === "--transparent" || arg === "--transparent-background") {
5828
+ background = "transparent";
5829
+ } else if (arg === "--background") {
5830
+ background = argv[++index] ?? usage();
5754
5831
  } else if (arg === "--scale") {
5755
5832
  const rawScale = Number(argv[++index]);
5756
5833
  if (!Number.isFinite(rawScale) || rawScale <= 0) usage();
@@ -5762,7 +5839,7 @@ function parseRenderArgs(argv) {
5762
5839
  }
5763
5840
  }
5764
5841
  if (inputs.length === 0) usage();
5765
- return { inputs, outDir, themes, watermark, force, crop, scale };
5842
+ return { inputs, outDir, themes, watermark, force, crop, scale, background };
5766
5843
  }
5767
5844
  async function findFrameFiles(inputs) {
5768
5845
  const files = [];
@@ -5811,13 +5888,31 @@ async function importFrame(filePath) {
5811
5888
  }
5812
5889
  }
5813
5890
  }
5891
+ function normalizeAutoSize(value, defaults) {
5892
+ if (value === true) return { width: true, height: true };
5893
+ if (value === false) return { width: false, height: false };
5894
+ if (value && typeof value === "object") {
5895
+ return {
5896
+ width: value.width ?? defaults.width,
5897
+ height: value.height ?? defaults.height
5898
+ };
5899
+ }
5900
+ return defaults;
5901
+ }
5814
5902
  function normalizeFrameModule(mod) {
5815
5903
  const defaultObject = typeof mod.default === "object" && mod.default && "create" in mod.default ? mod.default : void 0;
5904
+ const hasWidth = mod.width != null || defaultObject?.width != null;
5905
+ const hasHeight = mod.height != null || defaultObject?.height != null;
5906
+ const autoSize = normalizeAutoSize(mod.autoSize ?? mod.__vizmaticAutoSize, {
5907
+ width: !hasWidth,
5908
+ height: !hasHeight
5909
+ });
5816
5910
  return {
5817
5911
  ...mod,
5818
5912
  ...defaultObject ?? {},
5819
- width: mod.width ?? defaultObject?.width ?? 960,
5820
- height: mod.height ?? defaultObject?.height ?? 540
5913
+ width: mod.width ?? defaultObject?.width ?? DEFAULT_FRAME_WIDTH,
5914
+ height: mod.height ?? defaultObject?.height ?? DEFAULT_FRAME_HEIGHT,
5915
+ autoSize
5821
5916
  };
5822
5917
  }
5823
5918
  function frameElement(mod, theme) {
@@ -5825,6 +5920,48 @@ function frameElement(mod, theme) {
5825
5920
  if (mod.default && !(typeof mod.default === "object" && "create" in mod.default)) return mod.default;
5826
5921
  throw new Error("frame module must export create(theme) or default React element");
5827
5922
  }
5923
+ function overflowEdges(error) {
5924
+ const message = error instanceof Error ? error.message : String(error);
5925
+ const match = message.match(/Content overflows canvas at: ([^.]+)/);
5926
+ if (!match?.[1]) return void 0;
5927
+ const edges = match[1].split(",").map((edge) => edge.trim()).filter(Boolean);
5928
+ if (edges.some((edge) => edge !== "top" && edge !== "right" && edge !== "bottom" && edge !== "left")) {
5929
+ return void 0;
5930
+ }
5931
+ return edges;
5932
+ }
5933
+ function growDimension(value, max) {
5934
+ return Math.min(max, Math.ceil(value * AUTO_SIZE_GROWTH / 10) * 10);
5935
+ }
5936
+ function nextAutoSize(width, height, autoSize, edges) {
5937
+ const growWidth = autoSize.width && (edges.includes("left") || edges.includes("right"));
5938
+ const growHeight = autoSize.height && (edges.includes("top") || edges.includes("bottom"));
5939
+ const nextWidth = growWidth ? growDimension(width, AUTO_SIZE_MAX_WIDTH) : width;
5940
+ const nextHeight = growHeight ? growDimension(height, AUTO_SIZE_MAX_HEIGHT) : height;
5941
+ if (nextWidth === width && nextHeight === height) return void 0;
5942
+ return { width: nextWidth, height: nextHeight };
5943
+ }
5944
+ async function renderFrameToPng(mod, theme, options) {
5945
+ let width = options.width;
5946
+ let height = options.height;
5947
+ for (let attempt = 0; attempt < AUTO_SIZE_ATTEMPTS; attempt += 1) {
5948
+ try {
5949
+ await renderToPng(frameElement(mod, theme), {
5950
+ ...options,
5951
+ width,
5952
+ height
5953
+ }, mod.create, theme);
5954
+ return { width, height };
5955
+ } catch (error) {
5956
+ const edges = overflowEdges(error);
5957
+ const next = edges ? nextAutoSize(width, height, mod.autoSize, edges) : void 0;
5958
+ if (!next || attempt === AUTO_SIZE_ATTEMPTS - 1) throw error;
5959
+ width = next.width;
5960
+ height = next.height;
5961
+ }
5962
+ }
5963
+ return { width, height };
5964
+ }
5828
5965
  async function renderCommand(argv) {
5829
5966
  const args = parseRenderArgs(argv);
5830
5967
  const cliWatermark = await resolveWatermarkAssets(args.watermark);
@@ -5838,25 +5975,30 @@ async function renderCommand(argv) {
5838
5975
  const name = basename(file).replace(/\.[^.]+$/, "");
5839
5976
  const outputs = [];
5840
5977
  const moduleWatermark = await resolveWatermarkAssets(mod.watermark ?? mod.brand);
5978
+ let renderWidth = mod.width;
5979
+ let renderHeight = mod.height;
5841
5980
  for (const theme of args.themes) {
5842
5981
  const outputName = `${name}_${theme}.png`;
5843
5982
  const outputPath = join2(args.outDir, outputName);
5844
- await renderToPng(frameElement(mod, theme), {
5845
- width: mod.width,
5846
- height: mod.height,
5983
+ const rendered = await renderFrameToPng(mod, theme, {
5984
+ width: renderWidth,
5985
+ height: renderHeight,
5847
5986
  outputPath,
5848
5987
  watermark: cliWatermark ?? moduleWatermark,
5849
5988
  crop: args.crop,
5850
- scale: args.scale
5851
- }, mod.create, theme);
5989
+ scale: args.scale,
5990
+ background: args.background
5991
+ });
5992
+ renderWidth = rendered.width;
5993
+ renderHeight = rendered.height;
5852
5994
  outputs.push(outputName);
5853
5995
  console.log(`rendered ${relative(process.cwd(), outputPath)}`);
5854
5996
  }
5855
5997
  manifest.push({
5856
5998
  name,
5857
5999
  source: relative(process.cwd(), file),
5858
- width: mod.width,
5859
- height: mod.height,
6000
+ width: renderWidth,
6001
+ height: renderHeight,
5860
6002
  outputs
5861
6003
  });
5862
6004
  }
@@ -5888,7 +6030,8 @@ async function gifCommand(argv) {
5888
6030
  outputPath,
5889
6031
  watermark: cliWatermark ?? moduleWatermark,
5890
6032
  scale: args.scale ?? 1,
5891
- theme
6033
+ theme,
6034
+ background: args.background
5892
6035
  });
5893
6036
  outputs.push(outputName);
5894
6037
  console.log(`rendered ${relative(process.cwd(), outputPath)}`);