vizmatic 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,930 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/scene-runtime.ts
31
+ var scene_runtime_exports = {};
32
+ __export(scene_runtime_exports, {
33
+ SCENE_COMPONENT_NAMES: () => SCENE_COMPONENT_NAMES,
34
+ SCENE_DOM_TAGS: () => SCENE_DOM_TAGS,
35
+ SCENE_LIMITS: () => SCENE_LIMITS,
36
+ SCENE_RUNTIME_VERSION: () => SCENE_RUNTIME_VERSION,
37
+ evaluateSceneSource: () => evaluateSceneSource,
38
+ prepareScene: () => prepareScene,
39
+ prepareSceneSource: () => prepareSceneSource,
40
+ validateSceneGraph: () => validateSceneGraph
41
+ });
42
+ module.exports = __toCommonJS(scene_runtime_exports);
43
+ var import_quickjs_emscripten = require("quickjs-emscripten");
44
+ var import_sucrase = require("sucrase");
45
+
46
+ // src/bare-source.ts
47
+ function readJsxTag(source, start) {
48
+ if (source.startsWith("<>", start)) return { closing: false, end: start + 2, selfClosing: false };
49
+ if (source.startsWith("</>", start)) return { closing: true, end: start + 3, selfClosing: false };
50
+ const head = source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);
51
+ if (!head) return void 0;
52
+ const closing = Boolean(head[1]);
53
+ let quote;
54
+ let braces = 0;
55
+ let escaped = false;
56
+ for (let index = start + head[0].length; index < source.length; index += 1) {
57
+ const character = source[index];
58
+ if (quote) {
59
+ if (escaped) escaped = false;
60
+ else if (character === "\\") escaped = true;
61
+ else if (character === quote) quote = void 0;
62
+ continue;
63
+ }
64
+ if (character === '"' || character === "'" || character === "`") {
65
+ quote = character;
66
+ continue;
67
+ }
68
+ if (character === "{") {
69
+ braces += 1;
70
+ continue;
71
+ }
72
+ if (character === "}") {
73
+ braces = Math.max(0, braces - 1);
74
+ continue;
75
+ }
76
+ if (character !== ">" || braces > 0) continue;
77
+ const beforeClose = source.slice(start, index).trimEnd();
78
+ return {
79
+ closing,
80
+ end: index + 1,
81
+ selfClosing: !closing && beforeClose.endsWith("/")
82
+ };
83
+ }
84
+ return void 0;
85
+ }
86
+ function skipJsxExpression(source, start) {
87
+ let depth = 0;
88
+ let quote;
89
+ let escaped = false;
90
+ let blockComment = false;
91
+ let lineComment = false;
92
+ for (let index = start; index < source.length; index += 1) {
93
+ const character = source[index];
94
+ const next = source[index + 1];
95
+ if (lineComment) {
96
+ if (character === "\n") lineComment = false;
97
+ continue;
98
+ }
99
+ if (blockComment) {
100
+ if (character === "*" && next === "/") {
101
+ blockComment = false;
102
+ index += 1;
103
+ }
104
+ continue;
105
+ }
106
+ if (quote) {
107
+ if (escaped) escaped = false;
108
+ else if (character === "\\") escaped = true;
109
+ else if (character === quote) quote = void 0;
110
+ continue;
111
+ }
112
+ if (character === "/" && next === "/") {
113
+ lineComment = true;
114
+ index += 1;
115
+ continue;
116
+ }
117
+ if (character === "/" && next === "*") {
118
+ blockComment = true;
119
+ index += 1;
120
+ continue;
121
+ }
122
+ if (character === '"' || character === "'" || character === "`") {
123
+ quote = character;
124
+ continue;
125
+ }
126
+ if (character === "{") depth += 1;
127
+ else if (character === "}" && --depth === 0) return index + 1;
128
+ }
129
+ return void 0;
130
+ }
131
+ function findJsxEnd(source, start) {
132
+ let depth = 0;
133
+ for (let index = start; index < source.length; index += 1) {
134
+ if (source[index] === "{") {
135
+ const expressionEnd = skipJsxExpression(source, index);
136
+ if (expressionEnd == null) return void 0;
137
+ index = expressionEnd - 1;
138
+ continue;
139
+ }
140
+ if (source[index] !== "<") continue;
141
+ const tag = readJsxTag(source, index);
142
+ if (!tag) continue;
143
+ if (tag.closing) depth -= 1;
144
+ else if (!tag.selfClosing) depth += 1;
145
+ index = tag.end - 1;
146
+ if (depth === 0) return tag.end;
147
+ }
148
+ return void 0;
149
+ }
150
+ function hasOnlyTrailingSyntax(source) {
151
+ let index = 0;
152
+ while (index < source.length) {
153
+ const rest = source.slice(index);
154
+ const whitespace = rest.match(/^[\s;)]*/)?.[0].length ?? 0;
155
+ index += whitespace;
156
+ if (source.startsWith("//", index)) {
157
+ const newline = source.indexOf("\n", index + 2);
158
+ index = newline < 0 ? source.length : newline + 1;
159
+ continue;
160
+ }
161
+ if (source.startsWith("/*", index)) {
162
+ const end = source.indexOf("*/", index + 2);
163
+ if (end < 0) return false;
164
+ index = end + 2;
165
+ continue;
166
+ }
167
+ return index >= source.length;
168
+ }
169
+ return true;
170
+ }
171
+ function extractRootJsx(source) {
172
+ const body = source.replace(/^(?:\s*\()+\s*/, "");
173
+ const end = findJsxEnd(body, 0);
174
+ return (end == null ? body : body.slice(0, end)).trim();
175
+ }
176
+ function findBareRootJsxStart(source, allowNativeTags = false) {
177
+ const candidates = source.matchAll(allowNativeTags ? /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Za-z]|>))/g : /(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);
178
+ for (const candidate of candidates) {
179
+ if (candidate.index == null) continue;
180
+ const lineStart = candidate.index + (candidate[1]?.length ?? 0);
181
+ const expressionStart = lineStart + (candidate[2]?.length ?? 0);
182
+ const jsxStart = candidate.index + candidate[0].lastIndexOf(candidate[3] ?? "<");
183
+ const jsxEnd = findJsxEnd(source, jsxStart);
184
+ if (jsxEnd != null && hasOnlyTrailingSyntax(source.slice(jsxEnd))) return expressionStart;
185
+ }
186
+ return -1;
187
+ }
188
+
189
+ // src/theme.ts
190
+ var import_parse_css_color = __toESM(require("parse-css-color"), 1);
191
+ var darkColors = {
192
+ // Canvas backgrounds
193
+ bg: "#151620",
194
+ bgCard: "#1a1b26",
195
+ bgCardAlt: "#1e2030",
196
+ bgHover: "#24253a",
197
+ bgSubtle: "#151620",
198
+ // Brand / semantic colors (matches Mermaid palette)
199
+ primary: "#7c3aed",
200
+ // Purple — key/highlighted components
201
+ primaryLight: "#a78bfa",
202
+ primaryDark: "#6d28d9",
203
+ secondary: "#2563eb",
204
+ // Blue — supporting elements
205
+ secondaryLight: "#60a5fa",
206
+ secondaryDark: "#1d4ed8",
207
+ positive: "#059669",
208
+ // Green — output/success
209
+ positiveLight: "#34d399",
210
+ positiveDark: "#047857",
211
+ warning: "#d97706",
212
+ // Amber — warnings
213
+ warningLight: "#fbbf24",
214
+ warningDark: "#b45309",
215
+ critical: "#dc2626",
216
+ // Red — errors/bottlenecks
217
+ criticalLight: "#f87171",
218
+ criticalDark: "#b91c1c",
219
+ info: "#06b6d4",
220
+ // Cyan — informational
221
+ infoLight: "#22d3ee",
222
+ infoDark: "#0891b2",
223
+ accent: "#f472b6",
224
+ // Pink — accents
225
+ accentLight: "#f9a8d4",
226
+ neutral: "#334155",
227
+ // Slate — infrastructure/background
228
+ neutralLight: "#475569",
229
+ neutralDark: "#1e293b",
230
+ // Text
231
+ textPrimary: "#f1f5f9",
232
+ textSecondary: "#94a3b8",
233
+ textMuted: "#8493a8",
234
+ textOnColor: "#ffffff",
235
+ // Borders
236
+ border: "#334155",
237
+ borderSubtle: "#1e293b",
238
+ borderLight: "#475569",
239
+ shadow: "rgba(0, 0, 0, 0.24)"
240
+ };
241
+ var lightColors = {
242
+ // Canvas backgrounds
243
+ bg: "#f5f7fa",
244
+ bgCard: "#f8fafc",
245
+ bgCardAlt: "#f1f5f9",
246
+ bgHover: "#e2e8f0",
247
+ bgSubtle: "#f5f7fa",
248
+ // Brand / semantic colors (same hues, adjusted for light bg)
249
+ primary: "#7c3aed",
250
+ primaryLight: "#8b5cf6",
251
+ primaryDark: "#6d28d9",
252
+ secondary: "#2563eb",
253
+ secondaryLight: "#3b82f6",
254
+ secondaryDark: "#1d4ed8",
255
+ positive: "#059669",
256
+ positiveLight: "#10b981",
257
+ positiveDark: "#047857",
258
+ warning: "#d97706",
259
+ warningLight: "#f59e0b",
260
+ warningDark: "#b45309",
261
+ critical: "#dc2626",
262
+ criticalLight: "#ef4444",
263
+ criticalDark: "#b91c1c",
264
+ info: "#0891b2",
265
+ infoLight: "#06b6d4",
266
+ infoDark: "#0e7490",
267
+ accent: "#ec4899",
268
+ accentLight: "#f472b6",
269
+ neutral: "#cbd5e1",
270
+ neutralLight: "#94a3b8",
271
+ neutralDark: "#e2e8f0",
272
+ // Text
273
+ textPrimary: "#0f172a",
274
+ textSecondary: "#475569",
275
+ textMuted: "#5b677a",
276
+ textOnColor: "#ffffff",
277
+ // Borders
278
+ border: "#e2e8f0",
279
+ borderSubtle: "#e2e8f0",
280
+ borderLight: "#cbd5e1",
281
+ shadow: "rgba(15, 23, 42, 0.12)"
282
+ };
283
+ var defaultStyleTokens = {
284
+ preset: "default",
285
+ fontSans: "Inter",
286
+ fontMono: "JetBrains Mono"
287
+ };
288
+ var engineeringColors = {
289
+ ...lightColors,
290
+ bg: "#f4f4f5",
291
+ bgCard: "#ffffff",
292
+ bgCardAlt: "#ececee",
293
+ bgHover: "#e4e4e7",
294
+ bgSubtle: "#eeeeef",
295
+ primary: "#632ca6",
296
+ primaryLight: "#6d28d9",
297
+ primaryDark: "#4c1d95",
298
+ secondary: "#124fc7",
299
+ secondaryLight: "#1556d1",
300
+ secondaryDark: "#123d96",
301
+ positive: "#087a55",
302
+ positiveLight: "#0a8060",
303
+ positiveDark: "#05543c",
304
+ warning: "#c96c00",
305
+ warningLight: "#d97800",
306
+ warningDark: "#9a4f00",
307
+ critical: "#b83232",
308
+ criticalLight: "#c43d3d",
309
+ criticalDark: "#8f2626",
310
+ info: "#0b7185",
311
+ infoLight: "#0d7d92",
312
+ infoDark: "#075565",
313
+ accent: "#a83c76",
314
+ accentLight: "#b74583",
315
+ neutral: "#52525b",
316
+ neutralLight: "#71717a",
317
+ neutralDark: "#3f3f46",
318
+ textPrimary: "#101012",
319
+ textSecondary: "#3f3f46",
320
+ textMuted: "#68686f",
321
+ textOnColor: "#ffffff",
322
+ border: "#3f3f46",
323
+ borderSubtle: "#d4d4d8",
324
+ borderLight: "#a1a1aa",
325
+ shadow: "rgba(0, 0, 0, 0)"
326
+ };
327
+ function getThemeColors(mode, preset = "default") {
328
+ if (preset === "engineering") {
329
+ return {
330
+ ...engineeringColors,
331
+ preset,
332
+ fontSans: "Inter",
333
+ fontMono: "JetBrains Mono"
334
+ };
335
+ }
336
+ return {
337
+ ...mode === "light" ? lightColors : darkColors,
338
+ ...defaultStyleTokens
339
+ };
340
+ }
341
+ var colors = {
342
+ ...darkColors,
343
+ ...defaultStyleTokens
344
+ };
345
+ var gradients = {
346
+ purple: "linear-gradient(135deg, #7c3aed, #a855f7)",
347
+ blue: "linear-gradient(135deg, #2563eb, #60a5fa)",
348
+ green: "linear-gradient(135deg, #059669, #34d399)",
349
+ warm: "linear-gradient(135deg, #f59e0b, #ef4444)",
350
+ cyan: "linear-gradient(135deg, #06b6d4, #22d3ee)",
351
+ pink: "linear-gradient(135deg, #ec4899, #f472b6)",
352
+ sunset: "linear-gradient(135deg, #f97316, #db2777)",
353
+ ocean: "linear-gradient(135deg, #0284c7, #7c3aed)",
354
+ dark: "linear-gradient(180deg, #0f1117, #1a1b26)"
355
+ };
356
+ var toneGradients = {
357
+ blue: gradients.blue,
358
+ purple: gradients.purple,
359
+ green: gradients.green,
360
+ warm: gradients.warm,
361
+ cyan: gradients.cyan,
362
+ pink: gradients.pink,
363
+ red: gradients.warm,
364
+ critical: gradients.warm,
365
+ neutral: gradients.dark,
366
+ sunset: gradients.sunset,
367
+ ocean: gradients.ocean,
368
+ dark: gradients.dark
369
+ };
370
+ var styles = {
371
+ canvas: {
372
+ width: "100%",
373
+ height: "100%",
374
+ display: "flex",
375
+ flexDirection: "column",
376
+ backgroundColor: colors.bg,
377
+ fontFamily: "Inter",
378
+ padding: 40
379
+ },
380
+ card: {
381
+ display: "flex",
382
+ flexDirection: "column",
383
+ backgroundColor: colors.bgCard,
384
+ borderRadius: 8,
385
+ border: `1px solid ${colors.borderSubtle}`,
386
+ padding: 20
387
+ },
388
+ pill: {
389
+ display: "flex",
390
+ alignItems: "center",
391
+ justifyContent: "center",
392
+ borderRadius: 999,
393
+ padding: "6px 16px",
394
+ fontSize: 13,
395
+ fontWeight: 600,
396
+ fontFamily: "Inter"
397
+ }
398
+ };
399
+
400
+ // src/scene-components.ts
401
+ var SCENE_COMPONENT_NAMES = Object.freeze([
402
+ "Arrow",
403
+ "ArrowMarkerDef",
404
+ "AxisPlot",
405
+ "Badge",
406
+ "BadgePill",
407
+ "BarChart",
408
+ "Board",
409
+ "Box",
410
+ "CalloutCard",
411
+ "Canvas",
412
+ "CanvasItem",
413
+ "Card",
414
+ "ChartFrame",
415
+ "CodeBlock",
416
+ "Column",
417
+ "Comparison",
418
+ "Connector",
419
+ "DashedLine",
420
+ "DataTable",
421
+ "DataflowDiagram",
422
+ "DeploymentDiagram",
423
+ "DetailList",
424
+ "DonutChart",
425
+ "DotPoint",
426
+ "EquationCard",
427
+ "Flow",
428
+ "FlowArrow",
429
+ "GradientChip",
430
+ "GraphDiagram",
431
+ "Grid",
432
+ "Heatmap",
433
+ "Icon",
434
+ "IntervalPlot",
435
+ "KeyValueList",
436
+ "LayeredNetwork",
437
+ "Legend",
438
+ "LineChart",
439
+ "MathText",
440
+ "Matrix",
441
+ "MetricCard",
442
+ "MiniBarChart",
443
+ "Panel",
444
+ "ParetoBarChart",
445
+ "ParetoChart",
446
+ "PieChart",
447
+ "Pipeline",
448
+ "ProgressList",
449
+ "ProgressRow",
450
+ "QuadrantChart",
451
+ "Row",
452
+ "ScatterPlot",
453
+ "Scene",
454
+ "SequenceDiagram",
455
+ "Stack",
456
+ "StackedBar",
457
+ "StatusList",
458
+ "StatusRow",
459
+ "StepCard",
460
+ "SvgFrame",
461
+ "SvgMathText",
462
+ "SvgPoint",
463
+ "TextLabel",
464
+ "Tile",
465
+ "TileGrid",
466
+ "TiledMatrix",
467
+ "Timeline",
468
+ "TitleBar",
469
+ "ToneStrip",
470
+ "TransformerTopology",
471
+ "TreeDiagram",
472
+ "ValuePill",
473
+ "VectorArrow",
474
+ "VectorSegment",
475
+ "WindowFrame"
476
+ ]);
477
+ var SCENE_DOM_TAGS = Object.freeze([
478
+ "div",
479
+ "span",
480
+ "p",
481
+ "strong",
482
+ "em",
483
+ "b",
484
+ "i",
485
+ "br",
486
+ "svg",
487
+ "g",
488
+ "path",
489
+ "rect",
490
+ "circle",
491
+ "ellipse",
492
+ "line",
493
+ "polyline",
494
+ "polygon",
495
+ "text",
496
+ "tspan",
497
+ "defs",
498
+ "clipPath",
499
+ "linearGradient",
500
+ "radialGradient",
501
+ "stop",
502
+ "pattern",
503
+ "marker",
504
+ "mask",
505
+ "title",
506
+ "desc",
507
+ "use"
508
+ ]);
509
+
510
+ // src/scene-contract.ts
511
+ var SCENE_RUNTIME_VERSION = "vizmatic-scene/1";
512
+ var SCENE_LIMITS = Object.freeze({
513
+ sourceBytes: 131072,
514
+ graphBytes: 2097152,
515
+ nodes: 2e3,
516
+ depth: 64,
517
+ stringLength: 65536,
518
+ canvasEdge: 1920,
519
+ canvasPixels: 2073600,
520
+ duration: 120,
521
+ frames: 3600,
522
+ memoryBytes: 64 * 1024 * 1024,
523
+ stackBytes: 256 * 1024,
524
+ evaluationMs: 250
525
+ });
526
+ var unsafeKeys = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
527
+ function isUnsafeSceneKey(key) {
528
+ return unsafeKeys.has(key);
529
+ }
530
+ function normalizeSceneRequest(request) {
531
+ if (!request || typeof request !== "object") throw new Error("A scene request is required.");
532
+ if (typeof request.source !== "string" || !request.source.trim() || new TextEncoder().encode(request.source).byteLength > SCENE_LIMITS.sourceBytes) {
533
+ throw new Error(`Scene source must contain between 1 and ${SCENE_LIMITS.sourceBytes} UTF-8 bytes.`);
534
+ }
535
+ for (const name of ["width", "height"]) {
536
+ const value = request[name];
537
+ if (!Number.isInteger(value) || value < 2 || value > SCENE_LIMITS.canvasEdge || value % 2 !== 0) {
538
+ throw new Error(`Scene ${name} must be an even integer from 2 to ${SCENE_LIMITS.canvasEdge}.`);
539
+ }
540
+ }
541
+ if (request.width * request.height > SCENE_LIMITS.canvasPixels) {
542
+ throw new Error(`Scene canvas supports at most ${SCENE_LIMITS.canvasPixels} pixels.`);
543
+ }
544
+ if (!Number.isFinite(request.duration) || request.duration <= 0 || request.duration > SCENE_LIMITS.duration) {
545
+ throw new Error(`Scene duration must be greater than 0 and at most ${SCENE_LIMITS.duration} seconds.`);
546
+ }
547
+ const fps = request.fps ?? 24;
548
+ if (!Number.isInteger(fps) || fps < 1 || fps > 60) throw new Error("Scene fps must be an integer from 1 to 60.");
549
+ const frameCount = Math.round(request.duration * fps);
550
+ if (frameCount < 1 || frameCount > SCENE_LIMITS.frames) {
551
+ throw new Error(`Scene duration must round to between 1 and ${SCENE_LIMITS.frames} frames.`);
552
+ }
553
+ const theme = request.theme ?? "dark";
554
+ if (theme !== "dark" && theme !== "light") throw new Error("Scene theme must be dark or light.");
555
+ const seed = request.seed ?? 0;
556
+ if (!Number.isInteger(seed) || seed < 0 || seed > 4294967295) throw new Error("Scene seed must be a uint32 integer.");
557
+ const cues = /* @__PURE__ */ Object.create(null);
558
+ if (request.cues !== void 0 && (!request.cues || typeof request.cues !== "object" || Array.isArray(request.cues))) {
559
+ throw new Error("Scene cues must be an object containing times in seconds.");
560
+ }
561
+ const cueEntries = Object.entries(request.cues ?? {});
562
+ if (cueEntries.length > 128) throw new Error("Scene supports at most 128 cues.");
563
+ for (const [name, time] of cueEntries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
564
+ if (!/^[A-Za-z][\w.-]{0,79}$/.test(name) || isUnsafeSceneKey(name) || !Number.isFinite(time) || time < 0 || time > request.duration) {
565
+ throw new Error(`Invalid scene cue ${JSON.stringify(name)}. Cue times must be within the requested duration.`);
566
+ }
567
+ cues[name] = time;
568
+ }
569
+ return {
570
+ source: request.source,
571
+ width: request.width,
572
+ height: request.height,
573
+ duration: request.duration,
574
+ fps,
575
+ theme,
576
+ cues,
577
+ seed,
578
+ frameCount
579
+ };
580
+ }
581
+ function normalizeSceneTime(time, duration) {
582
+ const value = time ?? 0;
583
+ if (!Number.isFinite(value) || value < 0 || value > duration) {
584
+ throw new Error("Scene time must be within its duration, in seconds.");
585
+ }
586
+ return value;
587
+ }
588
+ async function sceneSha256(value) {
589
+ const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
590
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));
591
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
592
+ }
593
+
594
+ // src/scene-prop-limits.ts
595
+ function integer(value, name, min, max) {
596
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
597
+ throw new Error(`Editable scene ${name} must be an integer from ${min} to ${max}.`);
598
+ }
599
+ return value;
600
+ }
601
+ function finite(value, name) {
602
+ if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 32768) {
603
+ throw new Error(`Editable scene ${name} must be finite and within 32768 canvas units.`);
604
+ }
605
+ return value;
606
+ }
607
+ function entries(value, name, max) {
608
+ if (value === void 0) return [];
609
+ if (!Array.isArray(value) || value.length > max) throw new Error(`Editable scene ${name} supports at most ${max} entries.`);
610
+ return value;
611
+ }
612
+ function record(value, name) {
613
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Editable scene ${name} must be an object.`);
614
+ return value;
615
+ }
616
+ function validateSceneComponentProps(name, props) {
617
+ let values = 0;
618
+ const check = (value, key) => {
619
+ if (++values > 8192) throw new Error(`Editable scene ${name} props exceed their value budget.`);
620
+ if (typeof value === "number") {
621
+ if (/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key)) finite(value, `${name}.${key}`);
622
+ if (/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key)) integer(value, `${name}.${key}`, key === "gridCount" ? 0 : 1, 2e3);
623
+ }
624
+ if (Array.isArray(value)) value.forEach((item) => check(item, ""));
625
+ else if (value && typeof value === "object") {
626
+ if (value.kind !== "vizmatic.element") Object.entries(value).forEach(([property, item]) => check(item, property));
627
+ }
628
+ };
629
+ Object.entries(props).forEach(([key, value]) => check(value, key));
630
+ if (name === "DashedLine") {
631
+ const x1 = finite(props.x1, "DashedLine.x1"), y1 = finite(props.y1, "DashedLine.y1");
632
+ const x2 = finite(props.x2, "DashedLine.x2"), y2 = finite(props.y2, "DashedLine.y2");
633
+ const spacing = props.dotSpacing ?? 8;
634
+ if (typeof spacing !== "number" || !Number.isFinite(spacing) || spacing <= 0 || Math.hypot(x2 - x1, y2 - y1) / spacing > 2e3) {
635
+ throw new Error("Editable scene DashedLine requires positive dotSpacing and at most 2000 dots.");
636
+ }
637
+ }
638
+ if (name === "TileGrid" && props.columns !== void 0) integer(props.columns, "TileGrid.columns", 1, 2e3);
639
+ if (name === "TiledMatrix") {
640
+ const rows = integer(props.rows, "TiledMatrix.rows", 1, 2e3);
641
+ const cols = integer(props.cols, "TiledMatrix.cols", 1, 2e3);
642
+ if (rows * cols > 2e3) throw new Error("Editable scene TiledMatrix supports at most 2000 cells.");
643
+ }
644
+ if (name === "AxisPlot" && props.gridCount !== void 0) integer(props.gridCount, "AxisPlot.gridCount", 0, 100);
645
+ if (["GraphDiagram", "DataflowDiagram", "DeploymentDiagram", "TransformerTopology"].includes(name)) {
646
+ for (const key of ["nodes", "groups", "boundaries", "blocks"]) entries(props[key], `${name}.${key}`, 128);
647
+ for (const key of ["edges", "connections", "routes"]) entries(props[key], `${name}.${key}`, 256);
648
+ }
649
+ if (name === "TransformerTopology" && props.expandRepeats) {
650
+ const blocks = entries(props.blocks, "TransformerTopology.blocks", 128);
651
+ const total = blocks.reduce((sum, block) => sum + integer(record(block, "Transformer block").repeat ?? 1, "Transformer block.repeat", 1, 128), 0);
652
+ if (total > 128) throw new Error("Editable scene TransformerTopology expands to at most 128 nodes.");
653
+ }
654
+ if (name === "LayeredNetwork") {
655
+ const layers = entries(props.layers, "LayeredNetwork.layers", 16);
656
+ const counts = layers.map((layer) => entries(record(layer, "Network layer").nodes, "Network layer.nodes", 32).length);
657
+ const edges = counts.reduce((sum, count, index) => sum + count * (counts[index - 1] ?? 0), 0);
658
+ if (edges > 1024) throw new Error("Editable scene LayeredNetwork supports at most 1024 connections.");
659
+ }
660
+ if (name === "TreeDiagram" && props.root !== void 0) {
661
+ let count = 0;
662
+ const tree = (node) => {
663
+ if (++count > 128) throw new Error("Editable scene TreeDiagram supports at most 128 nodes.");
664
+ entries(record(node, "Tree node").children, "Tree node.children", 128).forEach(tree);
665
+ };
666
+ tree(props.root);
667
+ }
668
+ if (name === "ParetoChart") entries(props.points, "ParetoChart.points", 512);
669
+ }
670
+
671
+ // src/scene-graph.ts
672
+ var componentNames = new Set(SCENE_COMPONENT_NAMES);
673
+ var domTags = new Set(SCENE_DOM_TAGS);
674
+ var localReference = /^#[A-Za-z_][\w:.-]*$/;
675
+ var localPaint = /^url\(\s*#[A-Za-z_][\w:.-]*\s*\)$/;
676
+ var resourceKeys = /^(?:background(?:image)?|fill|stroke|filter|clippath|mask(?:image)?|borderimage(?:source)?|liststyle(?:image)?|cursor|content)$/i;
677
+ function validateResource(value, key, inStyle) {
678
+ if (/^(?:src|href|xlinkhref|xlink:href|srcset|poster|action|formaction)$/i.test(key) && !localReference.test(value)) {
679
+ throw new Error("Scene resource references must be local SVG fragment IDs. External assets are disabled.");
680
+ }
681
+ if ((inStyle || resourceKeys.test(key) || /gradient$/i.test(key)) && (/\\|\/\*/.test(value) || /(?:https?|file|ftp|data|blob|javascript):|\/\//i.test(value) || /url\s*\(/i.test(value) && !localPaint.test(value))) {
682
+ throw new Error("Scene CSS cannot load external resources or escaped resource expressions.");
683
+ }
684
+ }
685
+ function validateSceneGraph(value) {
686
+ let nodes = 0;
687
+ const visit = (input, depth, key = "", inStyle = false) => {
688
+ if (depth > SCENE_LIMITS.depth) throw new Error(`Scene graph exceeds depth ${SCENE_LIMITS.depth}.`);
689
+ if (++nodes > SCENE_LIMITS.nodes * 32) throw new Error("Scene graph contains too many values.");
690
+ if (input === null || typeof input === "boolean") return input;
691
+ if (typeof input === "number") {
692
+ if (!Number.isFinite(input) || Math.abs(input) > 1e9) throw new Error("Scene numbers must be finite and bounded.");
693
+ return input;
694
+ }
695
+ if (typeof input === "string") {
696
+ if (input.length > SCENE_LIMITS.stringLength) throw new Error("Scene string exceeds its length limit.");
697
+ validateResource(input, key, inStyle);
698
+ return input;
699
+ }
700
+ if (Array.isArray(input)) return input.map((item) => visit(item, depth + 1, key, inStyle));
701
+ if (!input || typeof input !== "object" || Object.getPrototypeOf(input) !== Object.prototype && Object.getPrototypeOf(input) !== null) throw new Error("Scene props must be plain JSON values.");
702
+ const record2 = input;
703
+ const output = /* @__PURE__ */ Object.create(null);
704
+ for (const [property, item] of Object.entries(record2)) {
705
+ if (isUnsafeSceneKey(property) || /^on/i.test(property) || /^(?:xml:base|xmlBase)$/i.test(property) || property === "dangerouslySetInnerHTML" || property === "ref" || property === "__html") throw new Error(`Scene property ${JSON.stringify(property)} is not allowed.`);
706
+ output[property] = visit(item, depth + 1, property, inStyle || /style$/i.test(property));
707
+ }
708
+ if (record2.kind === "vizmatic.element") {
709
+ if (typeof record2.type !== "string" || !componentNames.has(record2.type) && !domTags.has(record2.type)) {
710
+ throw new Error(`Scene component ${JSON.stringify(record2.type)} is not supported.`);
711
+ }
712
+ if (!record2.props || typeof record2.props !== "object" || Array.isArray(record2.props) || !Array.isArray(record2.children) || Object.keys(record2).some((name) => !["kind", "type", "props", "children"].includes(name))) {
713
+ throw new Error("Invalid scene element.");
714
+ }
715
+ if (componentNames.has(record2.type)) validateSceneComponentProps(record2.type, output.props);
716
+ }
717
+ return output;
718
+ };
719
+ const graph = visit(value, 0);
720
+ let elementCount = 0;
721
+ const checkChildren = (child) => {
722
+ if (Array.isArray(child)) {
723
+ child.forEach(checkChildren);
724
+ return;
725
+ }
726
+ if (child === null || typeof child !== "object") return;
727
+ if (child.kind !== "vizmatic.element") throw new Error("Scene children must be JSX elements, text or numbers.");
728
+ if (++elementCount > SCENE_LIMITS.nodes) throw new Error(`Scene graph exceeds ${SCENE_LIMITS.nodes} elements.`);
729
+ const element = child;
730
+ element.children.forEach(checkChildren);
731
+ const checkProps = (prop) => {
732
+ if (Array.isArray(prop)) {
733
+ prop.forEach(checkProps);
734
+ return;
735
+ }
736
+ if (prop && typeof prop === "object") {
737
+ if (prop.kind === "vizmatic.element") checkChildren(prop);
738
+ else Object.values(prop).forEach(checkProps);
739
+ }
740
+ };
741
+ Object.values(element.props).forEach(checkProps);
742
+ };
743
+ checkChildren(graph);
744
+ return graph;
745
+ }
746
+
747
+ // src/scene-runtime.ts
748
+ var bootstrap = String.raw`
749
+ const __jsonStringify = JSON.stringify.bind(JSON);
750
+ const __objectEntries = Object.entries.bind(Object);
751
+ const __isArray = Array.isArray.bind(Array);
752
+ const __isFinite = Number.isFinite.bind(Number);
753
+ const __Error = Error;
754
+ const __ownDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
755
+ const __freeze = (value) => {
756
+ if (value && typeof value === 'object') {
757
+ for (const child of Object.values(value)) __freeze(child);
758
+ Object.freeze(value);
759
+ }
760
+ return value;
761
+ };
762
+ const clamp = (value, min = 0, max = 1) => Math.max(min, Math.min(max, value));
763
+ const lerp = (from, to, amount) => from + (to - from) * amount;
764
+ const ease = (amount) => { const x = clamp(amount); return x * x * (3 - 2 * x); };
765
+ const easeInOut = ease;
766
+ const easeOut = (amount) => 1 - Math.pow(1 - clamp(amount), 3);
767
+ const cue = (name, span = 1) => {
768
+ if (!Object.hasOwn(cues, name)) throw new __Error('Unknown scene cue: ' + name);
769
+ if (!__isFinite(span) || span <= 0) throw new __Error('Cue span must be positive seconds.');
770
+ return clamp((time - cues[name]) / span);
771
+ };
772
+ let __randomState = seed >>> 0;
773
+ Math.random = () => {
774
+ __randomState = (__randomState + 0x6D2B79F5) >>> 0;
775
+ let v = Math.imul(__randomState ^ (__randomState >>> 15), 1 | __randomState);
776
+ v ^= v + Math.imul(v ^ (v >>> 7), 61 | v);
777
+ return ((v ^ (v >>> 14)) >>> 0) / 4294967296;
778
+ };
779
+ globalThis.Date = undefined;
780
+ globalThis.performance = undefined;
781
+ const __fragment = '__vizmatic_fragment';
782
+ const __jsx = (type, props, ...children) => {
783
+ const attributes = props == null ? {} : { ...props };
784
+ const descendants = children.length ? children : Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
785
+ delete attributes.children;
786
+ if (type === __fragment) return descendants;
787
+ if (typeof type === 'function') return type({ ...attributes, children: descendants.length === 1 ? descendants[0] : descendants });
788
+ if (typeof type !== 'string') throw new __Error('Invalid scene JSX component.');
789
+ return { kind: 'vizmatic.element', type, props: attributes, children: descendants };
790
+ };
791
+ const React = __freeze({ createElement: __jsx, Fragment: __fragment });
792
+ const Fragment = __fragment;
793
+ const __primitive = (type) => (props) => {
794
+ const attributes = { ...props };
795
+ const children = Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
796
+ delete attributes.children;
797
+ return { kind: 'vizmatic.element', type, props: attributes, children };
798
+ };
799
+ const __serialize = (value) => {
800
+ let values = 0;
801
+ return __jsonStringify(value, (key, item) => {
802
+ if (++values > 64000) throw new __Error('Scene graph contains too many values.');
803
+ if (typeof item === 'function' || typeof item === 'symbol' || typeof item === 'bigint') {
804
+ throw new __Error('Scene props cannot contain functions, symbols or bigint.');
805
+ }
806
+ if (typeof item === 'number' && !__isFinite(item)) throw new __Error('Scene props must be finite.');
807
+ if (item && typeof item === 'object' && typeof item.then === 'function') throw new __Error('Async scene values are not supported.');
808
+ return item;
809
+ });
810
+ };
811
+ `;
812
+ function prepareSceneSource(source) {
813
+ if (/^\s*(?:import|export)\b|\bimport\s*(?:[('"{*]|\/\*)/m.test(source)) {
814
+ throw new Error("Editable scenes use bare TSX. Imports and exports are disabled; Vizmatic components are provided automatically.");
815
+ }
816
+ const start = findBareRootJsxStart(source, true);
817
+ if (start < 0) throw new Error("Scene source needs one root JSX element after its local declarations.");
818
+ const setup = source.slice(0, start);
819
+ const jsx = extractRootJsx(source.slice(start).trim());
820
+ return (0, import_sucrase.transform)(`(() => {
821
+ ${setup}
822
+ return (
823
+ ${jsx}
824
+ );
825
+ })()`, {
826
+ transforms: ["typescript", "jsx"],
827
+ jsxPragma: "React.createElement",
828
+ jsxFragmentPragma: "React.Fragment",
829
+ production: true,
830
+ disableESTransforms: true
831
+ }).code;
832
+ }
833
+ async function prepareScene(request) {
834
+ const normalized = Object.freeze(normalizeSceneRequest(request));
835
+ Object.freeze(normalized.cues);
836
+ const code = prepareSceneSource(normalized.source);
837
+ const sourceSha256 = await sceneSha256(normalized.source);
838
+ const inputSha256 = await sceneSha256(JSON.stringify({ runtimeVersion: SCENE_RUNTIME_VERSION, ...normalized }));
839
+ const QuickJS = await (0, import_quickjs_emscripten.getQuickJS)();
840
+ const colors2 = getThemeColors(normalized.theme);
841
+ const components = `const { ${SCENE_COMPONENT_NAMES.join(", ")} } = Object.fromEntries(${JSON.stringify(SCENE_COMPONENT_NAMES)}.map(name => [name, __primitive(name)]));`;
842
+ const evaluate = async (requestedTime) => {
843
+ const time = normalizeSceneTime(requestedTime, normalized.duration);
844
+ const runtime = QuickJS.newRuntime();
845
+ runtime.setMemoryLimit(SCENE_LIMITS.memoryBytes);
846
+ runtime.setMaxStackSize(SCENE_LIMITS.stackBytes);
847
+ const deadline = Date.now() + SCENE_LIMITS.evaluationMs;
848
+ runtime.setInterruptHandler(() => Date.now() > deadline);
849
+ runtime.removeModuleLoader();
850
+ const vm = runtime.newContext();
851
+ const context = {
852
+ width: normalized.width,
853
+ height: normalized.height,
854
+ duration: normalized.duration,
855
+ fps: normalized.fps,
856
+ time,
857
+ t: time,
858
+ progress: time / normalized.duration,
859
+ frame: Math.floor(time * normalized.fps + 1e-9),
860
+ theme: normalized.theme,
861
+ cues: normalized.cues,
862
+ seed: normalized.seed,
863
+ c: colors2
864
+ };
865
+ const declaration = `const { ${Object.keys(context).join(", ")} } = ${JSON.stringify(context)};`;
866
+ try {
867
+ const result = vm.evalCode(`(() => { 'use strict';
868
+ ${declaration}
869
+ ${bootstrap}
870
+ __freeze(c); __freeze(cues);
871
+ ${components}
872
+ try { return __serialize(${code}); } catch (error) {
873
+ if (typeof error === 'string') throw error.slice(0, 1024);
874
+ const message = error && typeof error === 'object' ? __ownDescriptor(error, 'message')?.value : undefined;
875
+ throw typeof message === 'string' ? message.slice(0, 1024) : 'Scene evaluation failed.';
876
+ }
877
+ })()`, "scene.tsx");
878
+ if (result.error) {
879
+ const error = result.error;
880
+ try {
881
+ const message = vm.typeof(error) === "string" ? vm.getString(error) : "Scene evaluation failed or exceeded its CPU, stack or memory limit.";
882
+ throw new Error(message.slice(0, 1024));
883
+ } finally {
884
+ error.dispose();
885
+ }
886
+ }
887
+ const handle = result.value;
888
+ try {
889
+ if (vm.typeof(handle) !== "string") throw new Error("Scene source must return synchronous JSX.");
890
+ const length = vm.getProp(handle, "length");
891
+ try {
892
+ if (vm.getNumber(length) > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
893
+ } finally {
894
+ length.dispose();
895
+ }
896
+ const json = vm.getString(handle);
897
+ if (new TextEncoder().encode(json).byteLength > SCENE_LIMITS.graphBytes) throw new Error("Scene graph exceeds its serialized size limit.");
898
+ const graph = validateSceneGraph(JSON.parse(json));
899
+ return {
900
+ graph,
901
+ request: normalized,
902
+ time,
903
+ runtimeVersion: SCENE_RUNTIME_VERSION,
904
+ sourceSha256,
905
+ inputSha256: await sceneSha256(JSON.stringify({ sceneInputSha256: inputSha256, time }))
906
+ };
907
+ } finally {
908
+ handle.dispose();
909
+ }
910
+ } finally {
911
+ vm.dispose();
912
+ runtime.dispose();
913
+ }
914
+ };
915
+ return { request: normalized, sourceSha256, inputSha256, evaluate };
916
+ }
917
+ async function evaluateSceneSource(request) {
918
+ return (await prepareScene(request)).evaluate(request.time);
919
+ }
920
+ // Annotate the CommonJS export names for ESM import in node:
921
+ 0 && (module.exports = {
922
+ SCENE_COMPONENT_NAMES,
923
+ SCENE_DOM_TAGS,
924
+ SCENE_LIMITS,
925
+ SCENE_RUNTIME_VERSION,
926
+ evaluateSceneSource,
927
+ prepareScene,
928
+ prepareSceneSource,
929
+ validateSceneGraph
930
+ });