vizmatic 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,21 +1,601 @@
1
1
  #!/usr/bin/env node
2
- import {
3
- renderAnimatedGif,
4
- renderToPng
5
- } from "./chunk-SGIYXUY3.js";
6
2
 
7
3
  // src/cli.ts
8
- import { mkdir, readFile, readdir, writeFile } from "fs/promises";
9
- import { basename, extname, join, relative, resolve } from "path";
10
- import { pathToFileURL } from "url";
4
+ import { existsSync as existsSync2 } from "fs";
5
+ import { mkdir as mkdir3, readFile as readFile2, readdir, writeFile as writeFile3 } from "fs/promises";
6
+ import { createRequire, Module } from "module";
7
+ import { basename, dirname as dirname3, extname, join as join2, relative, resolve } from "path";
8
+ import { fileURLToPath, pathToFileURL } from "url";
11
9
  import { isValidElement } from "react";
10
+
11
+ // src/animate.ts
12
+ import satori2 from "satori";
13
+ import { Resvg as Resvg2 } from "@resvg/resvg-js";
14
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
15
+ import { dirname as dirname2 } from "path";
16
+ import * as gifenc from "gifenc";
17
+
18
+ // src/brand.ts
19
+ import React from "react";
20
+ var DEFAULT_WATERMARK_TEXT = "Vizmatic";
21
+ var WATERMARK_COLOR_DARK = "#a78bfa";
22
+ var WATERMARK_COLOR_LIGHT = "#7c3aed";
23
+ function VizmaticIcon({ size = 14, color }) {
24
+ return React.createElement(
25
+ "svg",
26
+ {
27
+ xmlns: "http://www.w3.org/2000/svg",
28
+ width: size,
29
+ height: size,
30
+ viewBox: "0 0 28 28",
31
+ fill: "none"
32
+ },
33
+ React.createElement("rect", { x: 2.5, y: 2.5, width: 23, height: 23, rx: 6.5, stroke: color, strokeWidth: 2, opacity: 0.54 }),
34
+ React.createElement("rect", { x: 7, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.35 }),
35
+ React.createElement("rect", { x: 15.5, y: 7, width: 5.5, height: 5.5, rx: 1.8, fill: color }),
36
+ React.createElement("rect", { x: 7, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, fill: color, opacity: 0.82 }),
37
+ React.createElement("rect", { x: 15.5, y: 15.5, width: 5.5, height: 5.5, rx: 1.8, stroke: color, strokeWidth: 1.5, opacity: 0.72 }),
38
+ React.createElement("path", { d: "M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5", stroke: color, strokeWidth: 1.6, strokeLinecap: "round", opacity: 0.88 })
39
+ );
40
+ }
41
+ function normalizeWatermark(watermark) {
42
+ if (watermark == null || watermark === false) return void 0;
43
+ if (watermark === true) return {};
44
+ if (typeof watermark === "string") return { text: watermark };
45
+ if (React.isValidElement(watermark)) {
46
+ if (watermark.type !== Watermark) return { element: watermark };
47
+ const { children, ...props } = watermark.props;
48
+ return {
49
+ ...props,
50
+ element: children ?? props.element
51
+ };
52
+ }
53
+ return watermark;
54
+ }
55
+ function Watermark(_props) {
56
+ return null;
57
+ }
58
+ function positionStyle(position) {
59
+ switch (position) {
60
+ case "top-left":
61
+ return { top: 8, left: 10 };
62
+ case "bottom-left":
63
+ return { bottom: 8, left: 10 };
64
+ case "bottom-right":
65
+ return { bottom: 8, right: 10 };
66
+ case "top-right":
67
+ default:
68
+ return { top: 8, right: 10 };
69
+ }
70
+ }
71
+ function imageNode(image) {
72
+ if (!image) return void 0;
73
+ const imageOptions = typeof image === "string" ? { src: image } : image;
74
+ return React.createElement("img", {
75
+ src: imageOptions.src,
76
+ alt: imageOptions.alt ?? "",
77
+ width: imageOptions.width ?? 14,
78
+ height: imageOptions.height ?? 14,
79
+ style: {
80
+ display: "block",
81
+ width: imageOptions.width ?? 14,
82
+ height: imageOptions.height ?? 14,
83
+ objectFit: "contain"
84
+ }
85
+ });
86
+ }
87
+ function iconNode(icon, color) {
88
+ if (icon === false) return void 0;
89
+ if (icon == null) return React.createElement(VizmaticIcon, { size: 13, color });
90
+ if (typeof icon !== "string") return icon;
91
+ return React.createElement("div", {
92
+ style: {
93
+ minWidth: 13,
94
+ height: 13,
95
+ display: "flex",
96
+ alignItems: "center",
97
+ justifyContent: "center",
98
+ color,
99
+ fontSize: icon.length > 2 ? 8 : 10,
100
+ fontWeight: 800,
101
+ fontFamily: "Inter",
102
+ lineHeight: 1
103
+ }
104
+ }, icon);
105
+ }
106
+ function wrapWithWatermark(element, width, height, theme = "dark", watermark = true) {
107
+ const isDark = theme === "dark";
108
+ const options = normalizeWatermark(watermark);
109
+ const color = options?.color ?? (isDark ? WATERMARK_COLOR_DARK : WATERMARK_COLOR_LIGHT);
110
+ const position = options?.position ?? "top-right";
111
+ const opacity = options?.opacity ?? (isDark ? 0.55 : 0.4);
112
+ const icon = options ? imageNode(options.image) ?? iconNode(options.icon, color) : void 0;
113
+ const text = options?.text ?? DEFAULT_WATERMARK_TEXT;
114
+ const content = options?.element ?? [
115
+ icon,
116
+ text !== false && text && React.createElement("div", {
117
+ key: "text",
118
+ style: {
119
+ fontSize: 11,
120
+ fontWeight: 600,
121
+ color,
122
+ fontFamily: "Inter",
123
+ letterSpacing: 0.3
124
+ }
125
+ }, text)
126
+ ];
127
+ return React.createElement(
128
+ "div",
129
+ {
130
+ style: {
131
+ width,
132
+ height,
133
+ display: "flex",
134
+ position: "relative"
135
+ }
136
+ },
137
+ element,
138
+ options && React.createElement(
139
+ "div",
140
+ {
141
+ style: {
142
+ position: "absolute",
143
+ ...positionStyle(position),
144
+ display: "flex",
145
+ alignItems: "center",
146
+ gap: 5,
147
+ opacity
148
+ }
149
+ },
150
+ content
151
+ )
152
+ );
153
+ }
154
+
155
+ // src/render.ts
156
+ import satori from "satori";
157
+ import { Resvg } from "@resvg/resvg-js";
158
+ import { homedir } from "os";
159
+ import { readFile, writeFile, mkdir } from "fs/promises";
160
+ import { dirname, join } from "path";
161
+ import { existsSync } from "fs";
162
+
163
+ // src/autocrop.ts
164
+ function detectBackgroundColor(pixels) {
165
+ const r = pixels[0];
166
+ const g = pixels[1];
167
+ const b = pixels[2];
168
+ const a = pixels[3];
169
+ if (a < 10) {
170
+ return "#000000";
171
+ }
172
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
173
+ }
174
+ function parseHexColor(hex) {
175
+ const h = hex.startsWith("#") ? hex.slice(1) : hex;
176
+ return [
177
+ parseInt(h.slice(0, 2), 16),
178
+ parseInt(h.slice(2, 4), 16),
179
+ parseInt(h.slice(4, 6), 16)
180
+ ];
181
+ }
182
+ function isBackground(r, g, b, a, bgR, bgG, bgB, tolerance = 6) {
183
+ if (a < 10) return true;
184
+ return Math.abs(r - bgR) <= tolerance && Math.abs(g - bgG) <= tolerance && Math.abs(b - bgB) <= tolerance;
185
+ }
186
+ function detectContentBounds(pixels, width, height, bgColor, padding = 20) {
187
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
188
+ let minX = width;
189
+ let minY = height;
190
+ let maxX = 0;
191
+ let maxY = 0;
192
+ for (let y = 0; y < height; y++) {
193
+ for (let x = 0; x < width; x++) {
194
+ const idx = (y * width + x) * 4;
195
+ const r = pixels[idx];
196
+ const g = pixels[idx + 1];
197
+ const b = pixels[idx + 2];
198
+ const a = pixels[idx + 3];
199
+ if (!isBackground(r, g, b, a, bgR, bgG, bgB)) {
200
+ if (x < minX) minX = x;
201
+ if (x > maxX) maxX = x;
202
+ if (y < minY) minY = y;
203
+ if (y > maxY) maxY = y;
204
+ }
205
+ }
206
+ }
207
+ if (minX > maxX || minY > maxY) {
208
+ return { x: 0, y: 0, width, height };
209
+ }
210
+ const cropX = Math.max(0, minX - padding);
211
+ const cropY = Math.max(0, minY - padding);
212
+ const cropRight = Math.min(width, maxX + 1 + padding);
213
+ const cropBottom = Math.min(height, maxY + 1 + padding);
214
+ return {
215
+ x: cropX,
216
+ y: cropY,
217
+ width: cropRight - cropX,
218
+ height: cropBottom - cropY
219
+ };
220
+ }
221
+ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDensity = 0.05, alphaThreshold = 128) {
222
+ const [bgR, bgG, bgB] = parseHexColor(bgColor);
223
+ function isContentPixel(x, y) {
224
+ const idx = (y * width + x) * 4;
225
+ const a = pixels[idx + 3];
226
+ if (a < alphaThreshold) return false;
227
+ return !isBackground(
228
+ pixels[idx],
229
+ pixels[idx + 1],
230
+ pixels[idx + 2],
231
+ a,
232
+ bgR,
233
+ bgG,
234
+ bgB
235
+ );
236
+ }
237
+ function checkEdge(scanFn, length) {
238
+ for (let offset = 0; offset < edgeTolerance; offset++) {
239
+ let contentCount = 0;
240
+ for (let i = 0; i < length; i++) {
241
+ const [x, y] = scanFn(i, offset);
242
+ if (x >= 0 && x < width && y >= 0 && y < height && isContentPixel(x, y)) {
243
+ contentCount++;
244
+ }
245
+ }
246
+ if (contentCount / length >= minDensity) {
247
+ return true;
248
+ }
249
+ }
250
+ return false;
251
+ }
252
+ const bottom = checkEdge((i, off) => [i, height - 1 - off], width);
253
+ const right = checkEdge((i, off) => [width - 1 - off, i], height);
254
+ const top = checkEdge((i, off) => [i, off], width);
255
+ const left = checkEdge((i, off) => [off, i], height);
256
+ const overflowEdges = [];
257
+ if (top) overflowEdges.push("top");
258
+ if (right) overflowEdges.push("right");
259
+ if (bottom) overflowEdges.push("bottom");
260
+ if (left) overflowEdges.push("left");
261
+ const overflows = overflowEdges.length > 0;
262
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
263
+ return {
264
+ overflows,
265
+ edges: { top, right, bottom, left },
266
+ message
267
+ };
268
+ }
269
+
270
+ // src/render.ts
271
+ var FONT_DIR = process.env.VIZMATIC_FONT_DIR ?? join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "vizmatic", "fonts");
272
+ var FONT_URLS = {
273
+ interRegular: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",
274
+ interSemiBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",
275
+ interBold: "https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",
276
+ jetbrainsMono: "https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",
277
+ // Noto Sans (544KB from gstatic): fallback for Phonetic Extensions
278
+ // (ᵀ U+1D40, ᵢ U+1D62) and extended Latin/Greek not covered by Inter.
279
+ notoSans: "https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",
280
+ // Noto Sans Math (766KB from gstatic): math operators (√, ∞, ≠, ×, ≫),
281
+ // Greek letters (τ, Σ), and arrows (→, ←)
282
+ notoSansMath: "https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"
283
+ };
284
+ async function ensureFont(filename, url) {
285
+ const localPath = join(FONT_DIR, filename);
286
+ if (existsSync(localPath)) {
287
+ return readFile(localPath);
288
+ }
289
+ console.log(` \u2193 Downloading font: ${filename}`);
290
+ const response = await fetch(url);
291
+ if (!response.ok) {
292
+ throw new Error(`Failed to download font ${filename}: ${response.statusText}`);
293
+ }
294
+ const buffer = Buffer.from(await response.arrayBuffer());
295
+ await mkdir(FONT_DIR, { recursive: true });
296
+ await writeFile(localPath, buffer);
297
+ return buffer;
298
+ }
299
+ function toArrayBuffer(buffer) {
300
+ return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
301
+ }
302
+ async function loadFonts() {
303
+ await mkdir(FONT_DIR, { recursive: true });
304
+ const fonts = [];
305
+ try {
306
+ const [regular, semiBold, bold] = await Promise.all([
307
+ ensureFont("Inter-Regular.ttf", FONT_URLS.interRegular),
308
+ ensureFont("Inter-SemiBold.ttf", FONT_URLS.interSemiBold),
309
+ ensureFont("Inter-Bold.ttf", FONT_URLS.interBold)
310
+ ]);
311
+ fonts.push(
312
+ { name: "Inter", data: toArrayBuffer(regular), weight: 400, style: "normal" },
313
+ { name: "Inter", data: toArrayBuffer(semiBold), weight: 600, style: "normal" },
314
+ { name: "Inter", data: toArrayBuffer(bold), weight: 700, style: "normal" }
315
+ );
316
+ } catch (e) {
317
+ console.warn("Warning: Could not load Inter font:", e);
318
+ }
319
+ try {
320
+ const jetbrains = await ensureFont("JetBrainsMono-Regular.ttf", FONT_URLS.jetbrainsMono);
321
+ fonts.push({ name: "JetBrains Mono", data: toArrayBuffer(jetbrains), weight: 400, style: "normal" });
322
+ } catch (e) {
323
+ console.warn("Warning: Could not load JetBrains Mono font:", e);
324
+ }
325
+ try {
326
+ const notoSans = await ensureFont("NotoSans-Regular.ttf", FONT_URLS.notoSans);
327
+ fonts.push(
328
+ { name: "Noto Sans", data: toArrayBuffer(notoSans), weight: 400, style: "normal" }
329
+ );
330
+ } catch (e) {
331
+ console.warn("Warning: Could not load Noto Sans font:", e);
332
+ }
333
+ try {
334
+ const notoMath = await ensureFont("NotoSansMath-Regular.ttf", FONT_URLS.notoSansMath);
335
+ fonts.push(
336
+ { name: "Noto Sans Math", data: toArrayBuffer(notoMath), weight: 400, style: "normal" }
337
+ );
338
+ } catch (e) {
339
+ console.warn("Warning: Could not load Noto Sans Math font:", e);
340
+ }
341
+ return fonts;
342
+ }
343
+ var EMOJI_CACHE_DIR = join(FONT_DIR, "emoji");
344
+ async function loadEmoji(segment) {
345
+ const codepoints = [...segment].map((c) => c.codePointAt(0).toString(16)).filter((cp) => cp !== "fe0f").join("-");
346
+ const filename = `${codepoints}.svg`;
347
+ const localPath = join(EMOJI_CACHE_DIR, filename);
348
+ if (existsSync(localPath)) {
349
+ const svgData = await readFile(localPath, "utf8");
350
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
351
+ }
352
+ const url = `https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/svg/${codepoints}.svg`;
353
+ try {
354
+ console.log(` \u2193 Downloading emoji: ${filename}`);
355
+ const response = await fetch(url);
356
+ if (!response.ok) {
357
+ console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);
358
+ return "";
359
+ }
360
+ const svgData = await response.text();
361
+ await mkdir(EMOJI_CACHE_DIR, { recursive: true });
362
+ await writeFile(localPath, svgData);
363
+ return `data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`;
364
+ } catch (e) {
365
+ console.warn(`Warning: Could not fetch emoji ${filename}:`, e);
366
+ return "";
367
+ }
368
+ }
369
+ async function loadAdditionalAsset(code, segment) {
370
+ if (code === "emoji") {
371
+ return loadEmoji(segment);
372
+ }
373
+ return [];
374
+ }
375
+ var cachedFonts = null;
376
+ async function getFonts() {
377
+ if (!cachedFonts) {
378
+ cachedFonts = await loadFonts();
379
+ }
380
+ return cachedFonts;
381
+ }
382
+ function sanitizeSvg(svg) {
383
+ return svg.replace(/width="0"/g, 'width="1"').replace(/height="0"/g, 'height="1"');
384
+ }
385
+ var AUTOCROP_PADDING = 24;
386
+ var CROP_THRESHOLD_PERCENT = 10;
387
+ function resolveWatermark(options) {
388
+ return options.watermark ?? options.brand;
389
+ }
390
+ async function renderToPng(element, options, createFn, theme) {
391
+ const fonts = await getFonts();
392
+ let svg = await satori(element, {
393
+ width: options.width,
394
+ height: options.height,
395
+ fonts,
396
+ loadAdditionalAsset
397
+ });
398
+ svg = sanitizeSvg(svg);
399
+ const detectResvg = new Resvg(svg, {
400
+ fitTo: { mode: "width", value: options.width },
401
+ background: "rgba(0, 0, 0, 0)"
402
+ });
403
+ const detectResult = detectResvg.render();
404
+ const detectPixels = detectResult.pixels;
405
+ const pixelData = new Uint8Array(detectPixels.buffer);
406
+ const detectedBg = detectBackgroundColor(pixelData);
407
+ const bounds = detectContentBounds(
408
+ pixelData,
409
+ options.width,
410
+ detectResult.height,
411
+ detectedBg,
412
+ AUTOCROP_PADDING
413
+ );
414
+ const overflow = detectOverflow(
415
+ pixelData,
416
+ options.width,
417
+ detectResult.height,
418
+ detectedBg
419
+ );
420
+ if (overflow.overflows) {
421
+ throw new Error(
422
+ `Canvas overflow detected (${options.width}\xD7${options.height}): ${overflow.message}`
423
+ );
424
+ }
425
+ const finalWidth = options.width;
426
+ let finalHeight = options.height;
427
+ let finalElement = element;
428
+ const heightSaved = options.height - bounds.height;
429
+ const heightSavedPercent = heightSaved / options.height * 100;
430
+ if (options.crop !== false && heightSavedPercent >= CROP_THRESHOLD_PERCENT) {
431
+ finalHeight = bounds.height;
432
+ if (createFn && theme) {
433
+ finalElement = createFn(theme);
434
+ }
435
+ }
436
+ const watermark = resolveWatermark(options);
437
+ const outputElement = watermark ? wrapWithWatermark(
438
+ finalElement,
439
+ finalWidth,
440
+ finalHeight,
441
+ theme || "dark",
442
+ watermark
443
+ ) : finalElement;
444
+ let finalSvg = await satori(outputElement, {
445
+ width: finalWidth,
446
+ height: finalHeight,
447
+ fonts,
448
+ loadAdditionalAsset
449
+ });
450
+ finalSvg = sanitizeSvg(finalSvg);
451
+ const resvg = new Resvg(finalSvg, {
452
+ fitTo: {
453
+ mode: "width",
454
+ value: finalWidth * (options.scale ?? 2)
455
+ },
456
+ background: "rgba(0, 0, 0, 0)"
457
+ });
458
+ const pngData = resvg.render();
459
+ const pngBuffer = pngData.asPng();
460
+ await mkdir(dirname(options.outputPath), { recursive: true });
461
+ await writeFile(options.outputPath, pngBuffer);
462
+ }
463
+
464
+ // src/animate.ts
465
+ function resolveGifenc(api) {
466
+ if (typeof api.GIFEncoder === "function" && typeof api.applyPalette === "function" && typeof api.quantize === "function") {
467
+ return api;
468
+ }
469
+ const fallback = api.default;
470
+ if (fallback && typeof fallback.GIFEncoder === "function" && typeof fallback.applyPalette === "function" && typeof fallback.quantize === "function") {
471
+ return fallback;
472
+ }
473
+ throw new Error("gifenc exports could not be resolved");
474
+ }
475
+ var { GIFEncoder, applyPalette, quantize } = resolveGifenc(gifenc);
476
+ async function renderToPixels(element, width, height, scale) {
477
+ const fonts = await getFonts();
478
+ const svg = await satori2(element, {
479
+ width,
480
+ height,
481
+ fonts,
482
+ loadAdditionalAsset
483
+ });
484
+ const resvg = new Resvg2(svg, {
485
+ fitTo: { mode: "width", value: width * scale },
486
+ background: "rgba(0, 0, 0, 0)"
487
+ });
488
+ const rendered = resvg.render();
489
+ return {
490
+ pixels: rendered.pixels,
491
+ width: rendered.width,
492
+ height: rendered.height
493
+ };
494
+ }
495
+ function blendPixels(base, overlay, opacity) {
496
+ const result = new Uint8Array(base.length);
497
+ const inverse = 1 - opacity;
498
+ for (let index = 0; index < base.length; index += 4) {
499
+ result[index] = Math.round(base[index] * inverse + overlay[index] * opacity);
500
+ result[index + 1] = Math.round(base[index + 1] * inverse + overlay[index + 1] * opacity);
501
+ result[index + 2] = Math.round(base[index + 2] * inverse + overlay[index + 2] * opacity);
502
+ result[index + 3] = 255;
503
+ }
504
+ return result;
505
+ }
506
+ function backgroundPixels(width, height, theme) {
507
+ const buffer = new Uint8Array(width * height * 4);
508
+ const color = theme === "light" ? { r: 245, g: 247, b: 250 } : { r: 21, g: 22, b: 32 };
509
+ for (let index = 0; index < buffer.length; index += 4) {
510
+ buffer[index] = color.r;
511
+ buffer[index + 1] = color.g;
512
+ buffer[index + 2] = color.b;
513
+ buffer[index + 3] = 255;
514
+ }
515
+ return buffer;
516
+ }
517
+ function encodeGif(frames, loop) {
518
+ if (frames.length === 0) throw new Error("No GIF frames to encode");
519
+ const firstFrame = frames[0];
520
+ const gif = GIFEncoder();
521
+ for (const frame of frames) {
522
+ const palette = quantize(frame.pixels, 256, { format: "rgba4444" });
523
+ const index = applyPalette(frame.pixels, palette, "rgba4444");
524
+ gif.writeFrame(index, firstFrame.width, firstFrame.height, {
525
+ palette,
526
+ delay: Math.max(2, Math.round(frame.delay / 10)),
527
+ repeat: loop
528
+ });
529
+ }
530
+ gif.finish();
531
+ return gif.bytes();
532
+ }
533
+ var TRANSITION_FPS = 15;
534
+ var MIN_TRANSITION_FRAMES = 3;
535
+ async function scenesToFrames(scenes, options) {
536
+ if (scenes.length === 0) throw new Error("Animated GIF requires at least one scene");
537
+ const renderedScenes = [];
538
+ for (const scene of scenes) {
539
+ const watermark = options.watermark ?? options.brand;
540
+ const element = watermark ? wrapWithWatermark(scene.element, options.width, options.height, options.theme, watermark) : scene.element;
541
+ renderedScenes.push(await renderToPixels(element, options.width, options.height, options.scale));
542
+ }
543
+ const frames = [];
544
+ const scaledWidth = options.width * options.scale;
545
+ const scaledHeight = options.height * options.scale;
546
+ for (let index = 0; index < scenes.length; index += 1) {
547
+ const scene = scenes[index];
548
+ const current = renderedScenes[index];
549
+ const transition = scene.transition ?? "none";
550
+ const transitionDuration = scene.transitionDuration ?? 400;
551
+ if (index > 0 && transition !== "none") {
552
+ const previous = renderedScenes[index - 1];
553
+ const transitionFrames = Math.max(
554
+ MIN_TRANSITION_FRAMES,
555
+ Math.round(transitionDuration / 1e3 * TRANSITION_FPS)
556
+ );
557
+ const frameDelay = transitionDuration / transitionFrames;
558
+ for (let frameIndex = 0; frameIndex < transitionFrames; frameIndex += 1) {
559
+ const amount = (frameIndex + 1) / transitionFrames;
560
+ const pixels = transition === "fade" ? blendPixels(previous.pixels, current.pixels, amount) : blendPixels(backgroundPixels(scaledWidth, scaledHeight, options.theme), current.pixels, amount);
561
+ frames.push({ pixels, delay: frameDelay, width: scaledWidth, height: scaledHeight });
562
+ }
563
+ }
564
+ frames.push({
565
+ pixels: current.pixels,
566
+ delay: scene.duration,
567
+ width: scaledWidth,
568
+ height: scaledHeight
569
+ });
570
+ }
571
+ return frames;
572
+ }
573
+ async function renderAnimatedGif(scenes, options) {
574
+ const normalized = {
575
+ ...options,
576
+ loop: options.loop ?? 0,
577
+ scale: options.scale ?? 1,
578
+ theme: options.theme ?? "dark"
579
+ };
580
+ await mkdir2(dirname2(options.outputPath), { recursive: true });
581
+ const frames = await scenesToFrames(scenes, normalized);
582
+ const bytes = encodeGif(frames, normalized.loop);
583
+ await writeFile2(options.outputPath, bytes);
584
+ }
585
+
586
+ // src/cli.ts
12
587
  var RENDER_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".mjs", ".ts", ".tsx"]);
588
+ var cliRequire = createRequire(import.meta.url);
589
+ var frameDependencyAliasesInstalled = false;
13
590
  function usageText() {
14
591
  return `Usage:
15
- vizmatic render <file-or-directory...> --out <dir> [--theme dark,light] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
16
- vizmatic gif <file-or-directory...> --out <dir> [--theme dark] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--scale 1]
592
+ vizmatic <file-or-directory...> [--out <dir>] [--theme dark,light] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
593
+ vizmatic render <file-or-directory...> [--out <dir>] [--theme dark,light] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--force]
594
+ vizmatic gif <file-or-directory...> [--out <dir>] [--theme dark] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--scale 1]
17
595
 
18
596
  Examples:
597
+ vizmatic examples/attention-head.tsx --out dist/frames --theme dark,light
598
+ pnpm dlx vizmatic ./frame.tsx --out ./dist/frames --theme dark
19
599
  vizmatic render examples --out docs/assets/examples --theme dark --watermark Vizmatic
20
600
  vizmatic render frames/attention.tsx --out dist/frames --theme dark,light
21
601
  vizmatic gif examples/animated-pipeline.tsx --out docs/assets/examples --theme dark --watermark Vizmatic`;
@@ -45,7 +625,7 @@ function imageMime(source) {
45
625
  async function imageSourceToDataUri(source) {
46
626
  if (/^(data:|https?:\/\/)/i.test(source)) return source;
47
627
  const filePath = resolve(source);
48
- const data = await readFile(filePath);
628
+ const data = await readFile2(filePath);
49
629
  return `data:${imageMime(filePath)};base64,${data.toString("base64")}`;
50
630
  }
51
631
  async function resolveWatermarkAssets(watermark) {
@@ -65,6 +645,36 @@ async function resolveWatermarkAssets(watermark) {
65
645
  }
66
646
  };
67
647
  }
648
+ function resolveSelfEntry() {
649
+ const moduleDir = dirname3(fileURLToPath(import.meta.url));
650
+ const bundledEntry = join2(moduleDir, "index.cjs");
651
+ if (existsSync2(bundledEntry)) return bundledEntry;
652
+ const sourceEntry = join2(moduleDir, "index.ts");
653
+ if (existsSync2(sourceEntry)) return sourceEntry;
654
+ try {
655
+ return cliRequire.resolve("vizmatic");
656
+ } catch {
657
+ return void 0;
658
+ }
659
+ }
660
+ function resolveFrameDependency(request) {
661
+ try {
662
+ if (request === "vizmatic") return resolveSelfEntry();
663
+ if (request === "react" || request.startsWith("react/")) return cliRequire.resolve(request);
664
+ } catch {
665
+ return void 0;
666
+ }
667
+ return void 0;
668
+ }
669
+ function installFrameDependencyAliases() {
670
+ if (frameDependencyAliasesInstalled) return;
671
+ frameDependencyAliasesInstalled = true;
672
+ const moduleWithResolver = Module;
673
+ const resolveFilename = moduleWithResolver._resolveFilename;
674
+ moduleWithResolver._resolveFilename = function resolveFrameDependencyAlias(request, parent, isMain, options) {
675
+ return resolveFrameDependency(request) ?? resolveFilename.call(this, request, parent, isMain, options);
676
+ };
677
+ }
68
678
  function parseRenderArgs(argv) {
69
679
  const inputs = [];
70
680
  let outDir = "dist/frames";
@@ -178,7 +788,7 @@ async function findFrameFiles(inputs) {
178
788
  return;
179
789
  }
180
790
  for (const entry of entries) {
181
- const next = join(resolved, entry.name);
791
+ const next = join2(resolved, entry.name);
182
792
  if (entry.isDirectory()) {
183
793
  if (entry.name === "node_modules" || entry.name === "dist") continue;
184
794
  await walk(next);
@@ -193,11 +803,12 @@ async function findFrameFiles(inputs) {
193
803
  return files.sort();
194
804
  }
195
805
  async function importFrame(filePath) {
806
+ installFrameDependencyAliases();
196
807
  const url = pathToFileURL(filePath).href;
197
808
  try {
198
809
  return await import(url);
199
810
  } catch (error) {
200
- if (!/\.[tj]sx?$/.test(filePath)) throw error;
811
+ if (!RENDER_EXTENSIONS.has(extname(filePath))) throw error;
201
812
  const { tsImport } = await import("tsx/esm/api");
202
813
  return await tsImport(url, import.meta.url);
203
814
  }
@@ -221,7 +832,7 @@ async function renderCommand(argv) {
221
832
  const cliWatermark = await resolveWatermarkAssets(args.watermark);
222
833
  const files = await findFrameFiles(args.inputs);
223
834
  if (files.length === 0) throw new Error("no frame files found");
224
- await mkdir(args.outDir, { recursive: true });
835
+ await mkdir3(args.outDir, { recursive: true });
225
836
  const manifest = [];
226
837
  for (const file of files) {
227
838
  const rawMod = await importFrame(file);
@@ -231,7 +842,7 @@ async function renderCommand(argv) {
231
842
  const moduleWatermark = await resolveWatermarkAssets(mod.watermark ?? mod.brand);
232
843
  for (const theme of args.themes) {
233
844
  const outputName = `${name}_${theme}.png`;
234
- const outputPath = join(args.outDir, outputName);
845
+ const outputPath = join2(args.outDir, outputName);
235
846
  await renderToPng(frameElement(mod, theme), {
236
847
  width: mod.width,
237
848
  height: mod.height,
@@ -251,7 +862,7 @@ async function renderCommand(argv) {
251
862
  outputs
252
863
  });
253
864
  }
254
- await writeFile(join(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
865
+ await writeFile3(join2(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
255
866
  `);
256
867
  }
257
868
  async function gifCommand(argv) {
@@ -259,7 +870,7 @@ async function gifCommand(argv) {
259
870
  const cliWatermark = await resolveWatermarkAssets(args.watermark);
260
871
  const files = await findFrameFiles(args.inputs);
261
872
  if (files.length === 0) throw new Error("no frame files found");
262
- await mkdir(args.outDir, { recursive: true });
873
+ await mkdir3(args.outDir, { recursive: true });
263
874
  const manifest = [];
264
875
  for (const file of files) {
265
876
  const rawMod = await importFrame(file);
@@ -272,7 +883,7 @@ async function gifCommand(argv) {
272
883
  }
273
884
  for (const theme of args.themes) {
274
885
  const outputName = `${name}_${theme}.gif`;
275
- const outputPath = join(args.outDir, outputName);
886
+ const outputPath = join2(args.outDir, outputName);
276
887
  await renderAnimatedGif(mod.createScenes(theme), {
277
888
  width: mod.width,
278
889
  height: mod.height,
@@ -292,17 +903,20 @@ async function gifCommand(argv) {
292
903
  outputs
293
904
  });
294
905
  }
295
- await writeFile(join(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
906
+ await writeFile3(join2(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
296
907
  `);
297
908
  }
298
909
  async function main() {
299
- const [command, ...rest] = process.argv.slice(2);
910
+ const args = process.argv.slice(2);
911
+ const [command, ...rest] = args;
300
912
  if (command === "render") {
301
913
  await renderCommand(rest);
302
914
  } else if (command === "gif") {
303
915
  await gifCommand(rest);
304
916
  } else if (!command || command === "help" || command === "--help" || command === "-h") {
305
917
  help();
918
+ } else if (!command.startsWith("-")) {
919
+ await renderCommand(args);
306
920
  } else {
307
921
  usage();
308
922
  }