vizmatic 0.1.42 → 0.2.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.
package/dist/index.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/theme.ts
2
8
  import parseCssColor from "parse-css-color";
3
9
  var darkColors = {
@@ -198,7 +204,7 @@ function getToneColor(tone, c) {
198
204
  dark: c.textSecondary
199
205
  }[tone];
200
206
  }
201
- function getReadableToneColor(tone, c, background = c.bgCard) {
207
+ function getReadableToneColor(tone, c, background = c.bgCard, backdrop = c.bgCard) {
202
208
  const semanticColor = {
203
209
  blue: "secondary",
204
210
  purple: "primary",
@@ -214,7 +220,7 @@ function getReadableToneColor(tone, c, background = c.bgCard) {
214
220
  dark: "neutral"
215
221
  };
216
222
  const color = getReadableColor(semanticColor[tone], c);
217
- return colorContrast(color, background, c.bgCard) >= 4.5 ? color : getReadableTextColor(background, c);
223
+ return colorContrast(color, background, backdrop) >= 4.5 ? color : getReadableTextColor(background, c, backdrop);
218
224
  }
219
225
  function getToneFill(tone, c) {
220
226
  if (c.preset !== "engineering") return `${getToneColor(tone, c)}16`;
@@ -377,12 +383,12 @@ function colorContrast(left, right, rightBackdrop) {
377
383
  if (leftLuminance == null || rightLuminance == null) return 0;
378
384
  return (Math.max(leftLuminance, rightLuminance) + 0.05) / (Math.min(leftLuminance, rightLuminance) + 0.05);
379
385
  }
380
- function getReadableTextColor(background, c) {
381
- if (colorLuminance(background, c.bgCard) == null) return c.textPrimary;
386
+ function getReadableTextColor(background, c, backdrop = c.bgCard) {
387
+ if (colorLuminance(background, backdrop) == null) return c.textPrimary;
382
388
  const candidates = [c.textPrimary, c.textOnColor, c.bg, "#000000"];
383
- const readable = candidates.find((candidate) => colorContrast(candidate, background, c.bgCard) >= 4.5);
389
+ const readable = candidates.find((candidate) => colorContrast(candidate, background, backdrop) >= 4.5);
384
390
  if (readable) return readable;
385
- return candidates.reduce((best, candidate) => colorContrast(candidate, background, c.bgCard) > colorContrast(best, background, c.bgCard) ? candidate : best);
391
+ return candidates.reduce((best, candidate) => colorContrast(candidate, background, backdrop) > colorContrast(best, background, backdrop) ? candidate : best);
386
392
  }
387
393
  function getGradient(name) {
388
394
  const map = {
@@ -424,6 +430,89 @@ function lerpColor(a, b, t) {
424
430
  return `#${(rr << 16 | rg << 8 | rb).toString(16).padStart(6, "0")}`;
425
431
  }
426
432
 
433
+ // src/primitives.ts
434
+ var primitives_exports = {};
435
+ __export(primitives_exports, {
436
+ Arrow: () => Arrow,
437
+ ArrowMarkerDef: () => ArrowMarkerDef,
438
+ AxisPlot: () => AxisPlot,
439
+ Badge: () => Badge,
440
+ BadgePill: () => BadgePill,
441
+ BarChart: () => BarChart,
442
+ Box: () => Box,
443
+ CalloutCard: () => CalloutCard,
444
+ Canvas: () => Canvas,
445
+ Card: () => Card,
446
+ ChartFrame: () => ChartFrame,
447
+ CodeBlock: () => CodeBlock,
448
+ Column: () => Column,
449
+ Comparison: () => Comparison,
450
+ Connector: () => Connector,
451
+ DashedLine: () => DashedLine,
452
+ DataTable: () => DataTable,
453
+ DataflowDiagram: () => DataflowDiagram,
454
+ DeploymentDiagram: () => DeploymentDiagram,
455
+ DetailList: () => DetailList,
456
+ DonutChart: () => DonutChart,
457
+ DotPoint: () => DotPoint,
458
+ EquationCard: () => EquationCard,
459
+ Flow: () => Flow,
460
+ FlowArrow: () => FlowArrow,
461
+ GradientChip: () => GradientChip,
462
+ GraphDiagram: () => GraphDiagram,
463
+ Grid: () => Grid,
464
+ Heatmap: () => Heatmap,
465
+ Icon: () => Icon,
466
+ IntervalPlot: () => IntervalPlot,
467
+ KeyValueList: () => KeyValueList,
468
+ LayeredNetwork: () => LayeredNetwork,
469
+ Legend: () => Legend,
470
+ LineChart: () => LineChart,
471
+ MathText: () => MathText,
472
+ Matrix: () => Matrix,
473
+ MetricCard: () => MetricCard,
474
+ MiniBarChart: () => MiniBarChart,
475
+ Panel: () => Panel,
476
+ ParetoChart: () => ParetoChart,
477
+ Pipeline: () => Pipeline,
478
+ ProgressList: () => ProgressList,
479
+ ProgressRow: () => ProgressRow,
480
+ QuadrantChart: () => QuadrantChart,
481
+ Row: () => Row,
482
+ ScatterPlot: () => ScatterPlot,
483
+ Scene: () => Scene,
484
+ SequenceDiagram: () => SequenceDiagram,
485
+ Stack: () => Stack,
486
+ StackedBar: () => StackedBar,
487
+ StatusList: () => StatusList,
488
+ StatusRow: () => StatusRow,
489
+ StepCard: () => StepCard,
490
+ SvgFrame: () => SvgFrame,
491
+ SvgMathText: () => SvgMathText,
492
+ SvgPoint: () => SvgPoint,
493
+ TextLabel: () => TextLabel,
494
+ Tile: () => Tile,
495
+ TileGrid: () => TileGrid,
496
+ TiledMatrix: () => TiledMatrix,
497
+ Timeline: () => Timeline,
498
+ TitleBar: () => TitleBar,
499
+ ToneStrip: () => ToneStrip,
500
+ TransformerTopology: () => TransformerTopology,
501
+ TreeDiagram: () => TreeDiagram,
502
+ ValuePill: () => ValuePill,
503
+ VectorArrow: () => VectorArrow,
504
+ VectorSegment: () => VectorSegment,
505
+ WindowFrame: () => WindowFrame,
506
+ createPlotArea: () => createPlotArea,
507
+ defineDiagramIcon: () => defineDiagramIcon,
508
+ defineIconRegistry: () => defineIconRegistry,
509
+ defineIllustration: () => defineIllustration,
510
+ formatMathText: () => formatMathText,
511
+ formatTensorShape: () => formatTensorShape,
512
+ getToneColor: () => getToneColor,
513
+ getToneGradient: () => getToneGradient
514
+ });
515
+
427
516
  // src/primitives/layout.ts
428
517
  import React from "react";
429
518
 
@@ -2110,6 +2199,7 @@ function MiniBarChart({
2110
2199
  ...compactChildren([
2111
2200
  showValues && React4.createElement("div", {
2112
2201
  style: {
2202
+ display: "flex",
2113
2203
  color: getReadableToneColor(tone, c),
2114
2204
  fontFamily: "JetBrains Mono",
2115
2205
  fontSize,
@@ -2129,6 +2219,7 @@ function MiniBarChart({
2129
2219
  }),
2130
2220
  React4.createElement("div", {
2131
2221
  style: {
2222
+ display: "flex",
2132
2223
  color: c.textMuted,
2133
2224
  fontFamily: "JetBrains Mono",
2134
2225
  fontSize,
@@ -2775,7 +2866,11 @@ function StatusRow({
2775
2866
  }) {
2776
2867
  const resolvedTone = tone ?? statusTones[status];
2777
2868
  const accent = getToneColor(resolvedTone, c);
2778
- const accentText = getReadableToneColor(resolvedTone, c);
2869
+ const markerAlpha = 38 / 255;
2870
+ const rowAlpha = boxed ? 18 / 255 : 0;
2871
+ const markerBackgroundAlpha = Math.round((rowAlpha + markerAlpha * (1 - rowAlpha)) * 255);
2872
+ const markerBackground = `${accent}${markerBackgroundAlpha.toString(16).padStart(2, "0")}`;
2873
+ const accentText = getReadableToneColor(resolvedTone, c, markerBackground, c.bgCard);
2779
2874
  const glyph = statusGlyphs[status];
2780
2875
  const marker = React5.createElement("div", {
2781
2876
  style: {
@@ -3197,6 +3292,200 @@ function Flow({
3197
3292
  // src/primitives/diagrams.ts
3198
3293
  import React6 from "react";
3199
3294
  import dagre from "@dagrejs/dagre";
3295
+
3296
+ // src/svg-accessibility.ts
3297
+ import { cloneElement, isValidElement } from "react";
3298
+ var SVG_ACCESSIBILITY_COMPONENT = /* @__PURE__ */ Symbol.for("vizmatic.svgAccessibilityComponent");
3299
+ function componentHasSvgMetadata(type) {
3300
+ return typeof type === "function" && type[SVG_ACCESSIBILITY_COMPONENT] === true;
3301
+ }
3302
+ function svgToken(value) {
3303
+ if (value.length === 0) return "empty";
3304
+ return Array.from(value, (character) => {
3305
+ const codePoint = character.codePointAt(0) ?? 0;
3306
+ return /^[A-Za-z0-9.-]$/.test(character) ? character : `_u${codePoint.toString(16)}_`;
3307
+ }).join("");
3308
+ }
3309
+ function textProperty(props, name) {
3310
+ const value = props[name];
3311
+ return typeof value === "string" ? value : "";
3312
+ }
3313
+ function encodedTextProperty(props, name) {
3314
+ const value = textProperty(props, name);
3315
+ try {
3316
+ return decodeURIComponent(value);
3317
+ } catch {
3318
+ return value;
3319
+ }
3320
+ }
3321
+ function prepareAccessibleSvg(element) {
3322
+ const graphs = [];
3323
+ const explicitIds = /* @__PURE__ */ new Set();
3324
+ const visit = (node, graph) => {
3325
+ if (Array.isArray(node)) return node.map((child) => visit(child, graph));
3326
+ if (!isValidElement(node)) return node;
3327
+ const component = node.type;
3328
+ if (componentHasSvgMetadata(component)) {
3329
+ return visit(component(node.props), graph);
3330
+ }
3331
+ const props = node.props;
3332
+ const title = textProperty(props, "data-vizmatic-svg-title");
3333
+ const isGraphRoot = title.length > 0;
3334
+ let activeGraph = graph;
3335
+ let elementKey = node.key;
3336
+ if (isGraphRoot) {
3337
+ const explicitId = textProperty(props, "data-vizmatic-svg-id");
3338
+ if (explicitId) {
3339
+ if (explicitIds.has(explicitId)) {
3340
+ throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`);
3341
+ }
3342
+ explicitIds.add(explicitId);
3343
+ }
3344
+ const index = graphs.length;
3345
+ const token = explicitId ? `id-${svgToken(explicitId)}` : `index-${index}`;
3346
+ activeGraph = {
3347
+ index,
3348
+ token,
3349
+ detectionKey: `vizmatic-graph-${index}`,
3350
+ title,
3351
+ description: textProperty(props, "data-vizmatic-svg-description"),
3352
+ nodes: [],
3353
+ edges: []
3354
+ };
3355
+ graphs.push(activeGraph);
3356
+ elementKey = activeGraph.detectionKey;
3357
+ }
3358
+ let nextProps;
3359
+ if (activeGraph && Object.hasOwn(props, "data-vizmatic-graph-node-id")) {
3360
+ const id = textProperty(props, "data-vizmatic-graph-node-id");
3361
+ const label = textProperty(props, "data-vizmatic-graph-node-label") || id;
3362
+ const detail = textProperty(props, "data-vizmatic-graph-node-detail");
3363
+ activeGraph.nodes.push({
3364
+ id,
3365
+ label,
3366
+ detail,
3367
+ title: textProperty(props, "data-vizmatic-graph-node-title") || label,
3368
+ href: textProperty(props, "data-vizmatic-graph-node-href") || void 0
3369
+ });
3370
+ elementKey = `${activeGraph.detectionKey}-node-${svgToken(id)}`;
3371
+ } else if (activeGraph && textProperty(props, "data-vizmatic-graph-edge-id")) {
3372
+ const id = encodedTextProperty(props, "data-vizmatic-graph-edge-id");
3373
+ activeGraph.edges.push({
3374
+ id,
3375
+ from: encodedTextProperty(props, "data-vizmatic-graph-edge-from"),
3376
+ to: encodedTextProperty(props, "data-vizmatic-graph-edge-to"),
3377
+ label: encodedTextProperty(props, "data-vizmatic-graph-edge-label"),
3378
+ title: encodedTextProperty(props, "data-vizmatic-graph-edge-title"),
3379
+ path: textProperty(props, "d"),
3380
+ href: encodedTextProperty(props, "data-vizmatic-graph-edge-href") || void 0
3381
+ });
3382
+ elementKey = `${activeGraph.detectionKey}-edge-${svgToken(id)}`;
3383
+ }
3384
+ const children = props.children;
3385
+ if (children === void 0) {
3386
+ if (isGraphRoot) {
3387
+ nextProps = { ...props, "data-vizmatic-svg-instance": activeGraph?.token };
3388
+ return cloneElement(node, { ...nextProps, key: elementKey });
3389
+ }
3390
+ return node;
3391
+ }
3392
+ const preparedChildren = visit(children, activeGraph);
3393
+ nextProps = isGraphRoot ? { ...props, "data-vizmatic-svg-instance": activeGraph?.token } : { ...props };
3394
+ return cloneElement(
3395
+ node,
3396
+ { ...nextProps, key: elementKey },
3397
+ preparedChildren
3398
+ );
3399
+ };
3400
+ return { element: visit(element), graphs };
3401
+ }
3402
+ function escapeXml(value) {
3403
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3404
+ }
3405
+ function attribute(name, value) {
3406
+ return `${name}="${escapeXml(value)}"`;
3407
+ }
3408
+ function graphBaseId(graph) {
3409
+ return `vizmatic-graph-${graph.token}`;
3410
+ }
3411
+ function nodeId(graph, node) {
3412
+ return `${graphBaseId(graph)}-node-${svgToken(node.id)}`;
3413
+ }
3414
+ function edgeId(graph, edge) {
3415
+ return `${graphBaseId(graph)}-edge-${svgToken(edge.id)}`;
3416
+ }
3417
+ function labelForEdge(graph, edge) {
3418
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
3419
+ const from = nodes.get(edge.from) ?? edge.from;
3420
+ const to = nodes.get(edge.to) ?? edge.to;
3421
+ return edge.title || (edge.label ? `${from} to ${to}: ${edge.label}` : `${from} to ${to}`);
3422
+ }
3423
+ function descriptionForEdge(graph, edge) {
3424
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
3425
+ const from = nodes.get(edge.from) ?? edge.from;
3426
+ const to = nodes.get(edge.to) ?? edge.to;
3427
+ return `Relationship from ${from} to ${to}${edge.label ? `, labeled ${edge.label}` : ""}.`;
3428
+ }
3429
+ function nodeGroup(graph, node, layout) {
3430
+ const id = nodeId(graph, node);
3431
+ const label = node.detail ? `${node.label}: ${node.detail}` : node.label;
3432
+ const description = node.detail || node.label;
3433
+ const titleId = `${id}-title`;
3434
+ const descriptionId = `${id}-description`;
3435
+ const accessible = `<g ${attribute("id", id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(node.title || node.label)}</title><desc id="${descriptionId}">${escapeXml(description)}</desc>`;
3436
+ if (!layout) return `${accessible}</g>`;
3437
+ const rect = `<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;
3438
+ const hitTarget = node.href ? `<a ${attribute("href", node.href)} role="link" tabindex="0" ${attribute("aria-label", label)}>${rect}</a>` : rect;
3439
+ return `${accessible}${hitTarget}</g>`;
3440
+ }
3441
+ function edgeGroup(graph, edge, root) {
3442
+ const id = edgeId(graph, edge);
3443
+ const title = labelForEdge(graph, edge);
3444
+ const titleId = `${id}-title`;
3445
+ const descriptionId = `${id}-description`;
3446
+ const accessible = `<g ${attribute("id", id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(title)}</title><desc id="${descriptionId}">${escapeXml(descriptionForEdge(graph, edge))}</desc>`;
3447
+ if (!root || !edge.path) return `${accessible}</g>`;
3448
+ const path = `<path d="${escapeXml(edge.path)}" transform="translate(${root.left} ${root.top})" fill="none" stroke="transparent" stroke-width="14" stroke-linecap="round" pointer-events="stroke"/>`;
3449
+ const hitTarget = edge.href ? `<a ${attribute("href", edge.href)} role="link" tabindex="0" ${attribute("aria-label", title)}>${path}</a>` : path;
3450
+ return `${accessible}${hitTarget}</g>`;
3451
+ }
3452
+ function addSvgAccessibility(svg, graphs, layoutNodes) {
3453
+ if (graphs.length === 0) return svg;
3454
+ const title = graphs.map((graph) => graph.title).join(". ");
3455
+ const description = graphs.map((graph) => `${graph.title}. ${graph.description}`).join(" ");
3456
+ const hasLinks = graphs.some(
3457
+ (graph) => graph.nodes.some((node) => node.href) || graph.edges.some((edge) => edge.href)
3458
+ );
3459
+ const rootTitleId = "vizmatic-svg-title";
3460
+ const rootDescriptionId = "vizmatic-svg-description";
3461
+ const groupMarkup = graphs.map((graph) => {
3462
+ const baseId = graphBaseId(graph);
3463
+ const titleId = `${baseId}-title`;
3464
+ const descriptionId = `${baseId}-description`;
3465
+ const root = layoutNodes.find((node) => node.key === graph.detectionKey);
3466
+ const nodes = graph.nodes.map((item) => {
3467
+ const layout = layoutNodes.find((node) => node.key === `${graph.detectionKey}-node-${svgToken(item.id)}`);
3468
+ if (item.href && !layout) {
3469
+ throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`);
3470
+ }
3471
+ return nodeGroup(graph, item, layout);
3472
+ }).join("");
3473
+ const edges = graph.edges.map((item) => {
3474
+ if (item.href && !root) {
3475
+ throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`);
3476
+ }
3477
+ return edgeGroup(graph, item, root);
3478
+ }).join("");
3479
+ return `<g ${attribute("id", baseId)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(graph.title)}</title><desc id="${descriptionId}">${escapeXml(graph.description)}</desc>${nodes}${edges}</g>`;
3480
+ }).join("");
3481
+ const metadata = `<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;
3482
+ return svg.replace(
3483
+ /^<svg\b([^>]*)>/,
3484
+ (_match, attrs) => `<svg${attrs} role="${hasLinks ? "group" : "img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`
3485
+ ).replace(/<\/svg>\s*$/, `${groupMarkup}</svg>`);
3486
+ }
3487
+
3488
+ // src/primitives/diagrams.ts
3200
3489
  function distributeValues(count, start, end) {
3201
3490
  if (count <= 0) return [];
3202
3491
  if (count === 1) return [(start + end) / 2];
@@ -3566,15 +3855,53 @@ function validateGraphDiagramSpec(nodes, edges, groups, layoutMode) {
3566
3855
  for (const group of groups) {
3567
3856
  if (!occupiedGroups.has(group.id)) throw new Error(`GraphDiagram group "${group.id}" contains no nodes.`);
3568
3857
  }
3858
+ const edgeIds = /* @__PURE__ */ new Set();
3569
3859
  for (const edge of edges) {
3570
3860
  if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) {
3571
3861
  throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`);
3572
3862
  }
3863
+ if (edge.id != null) {
3864
+ if (edgeIds.has(edge.id)) throw new Error(`GraphDiagram received duplicate edge id "${edge.id}".`);
3865
+ edgeIds.add(edge.id);
3866
+ }
3867
+ validateDiagramHref(edge.href, `edge "${edge.id ?? `${edge.from}" -> "${edge.to}`}"`);
3868
+ }
3869
+ for (const node of nodes) {
3870
+ validateDiagramHref(node.href, `node "${node.id}"`);
3573
3871
  }
3574
3872
  if (groups.length > 0 && layoutMode === "manual") {
3575
3873
  throw new Error('GraphDiagram groups require automatic layout; omit node coordinates and layout="manual".');
3576
3874
  }
3577
3875
  }
3876
+ function validateDiagramHref(href, owner) {
3877
+ if (href == null) return;
3878
+ const normalized = href.trim().replace(/[\u0000-\u0020\u007f]/g, "");
3879
+ const scheme = /^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1]?.toLowerCase();
3880
+ if (scheme && !["http", "https", "mailto", "tel"].includes(scheme)) {
3881
+ throw new Error(`GraphDiagram ${owner} has an unsupported link scheme "${scheme}:".`);
3882
+ }
3883
+ }
3884
+ function graphAccessibleText(value) {
3885
+ if (typeof value === "string" || typeof value === "number") return String(value).trim();
3886
+ if (Array.isArray(value)) return value.map(graphAccessibleText).filter(Boolean).join(" ");
3887
+ if (React6.isValidElement(value)) {
3888
+ const props = value.props;
3889
+ return graphAccessibleText(props.children);
3890
+ }
3891
+ return "";
3892
+ }
3893
+ function graphDescription(nodes, edges) {
3894
+ const labels = new Map(nodes.map((node) => [node.id, graphAccessibleText(node.label) || node.id]));
3895
+ const parts = [`${nodes.length} nodes and ${edges.length} relationships.`];
3896
+ const relationships = edges.slice(0, 8).map((edge) => {
3897
+ const from = labels.get(edge.from) ?? edge.from;
3898
+ const to = labels.get(edge.to) ?? edge.to;
3899
+ return edge.label ? `${from} ${edge.label} ${to}` : `${from} to ${to}`;
3900
+ });
3901
+ if (relationships.length) parts.push(relationships.join("; "));
3902
+ if (edges.length > relationships.length) parts.push(`${edges.length - relationships.length} more relationships`);
3903
+ return parts.join(" ");
3904
+ }
3578
3905
  function graphGroupDepth(group, groupsById) {
3579
3906
  let depth = 0;
3580
3907
  let parent = group.parent;
@@ -3614,8 +3941,12 @@ function GraphDiagram({
3614
3941
  edgeGap = 14,
3615
3942
  sizing = "content",
3616
3943
  iconSize = 20,
3617
- ariaLabel
3944
+ id,
3945
+ ariaLabel,
3946
+ title,
3947
+ description
3618
3948
  }) {
3949
+ if (id != null && id.trim().length === 0) throw new Error("GraphDiagram id must not be empty.");
3619
3950
  const fullyPositioned = nodes.filter((node) => node.x != null && node.y != null).length;
3620
3951
  const partiallyPositioned = nodes.some((node) => node.x == null !== (node.y == null));
3621
3952
  if (partiallyPositioned || fullyPositioned > 0 && fullyPositioned < nodes.length) {
@@ -3626,6 +3957,19 @@ function GraphDiagram({
3626
3957
  throw new Error('GraphDiagram layout="manual" requires x and y on every node.');
3627
3958
  }
3628
3959
  validateGraphDiagramSpec(nodes, edges, groups, layoutMode);
3960
+ const edgeOccurrences = /* @__PURE__ */ new Map();
3961
+ const stableEdgeIds = edges.map((edge) => {
3962
+ if (edge.id != null) return `custom-${edge.id}`;
3963
+ const route = `${edge.from}\0${edge.to}`;
3964
+ const occurrence = edgeOccurrences.get(route) ?? 0;
3965
+ edgeOccurrences.set(route, occurrence + 1);
3966
+ return `route-${edge.from}-to-${edge.to}-${occurrence}`;
3967
+ });
3968
+ if (new Set(stableEdgeIds).size !== stableEdgeIds.length) {
3969
+ throw new Error("GraphDiagram edge ids must not collide with generated relationship ids.");
3970
+ }
3971
+ const svgTitle = title?.trim() || ariaLabel?.trim() || "Graph diagram";
3972
+ const svgDescription = description ?? graphDescription(nodes, edges);
3629
3973
  let resolvedWidth = width ?? 520;
3630
3974
  let resolvedHeight = height ?? 420;
3631
3975
  let layout;
@@ -3737,6 +4081,7 @@ function GraphDiagram({
3737
4081
  return [{
3738
4082
  ...edge,
3739
4083
  index,
4084
+ stableId: stableEdgeIds[index],
3740
4085
  color,
3741
4086
  markerId,
3742
4087
  points,
@@ -3803,8 +4148,12 @@ function GraphDiagram({
3803
4148
  return React6.createElement(
3804
4149
  "div",
3805
4150
  {
4151
+ key: "vizmatic-graph-root",
3806
4152
  role: "img",
3807
- "aria-label": ariaLabel ?? "Graph diagram",
4153
+ "aria-label": ariaLabel ?? svgTitle,
4154
+ "data-vizmatic-svg-title": svgTitle,
4155
+ "data-vizmatic-svg-description": svgDescription,
4156
+ "data-vizmatic-svg-id": id,
3808
4157
  "data-vizmatic-connector-crossings": crossings,
3809
4158
  "data-vizmatic-connector-label-collisions": labelCollisions,
3810
4159
  "data-vizmatic-crowded-connector-endpoints": crowdedEndpoints,
@@ -3838,6 +4187,12 @@ function GraphDiagram({
3838
4187
  ),
3839
4188
  ...edgeLayouts.map((edge) => React6.createElement("path", {
3840
4189
  key: `graph-edge-${edge.index}`,
4190
+ "data-vizmatic-graph-edge-id": encodeURIComponent(edge.stableId),
4191
+ "data-vizmatic-graph-edge-from": encodeURIComponent(edge.from),
4192
+ "data-vizmatic-graph-edge-to": encodeURIComponent(edge.to),
4193
+ "data-vizmatic-graph-edge-label": encodeURIComponent(edge.label ?? ""),
4194
+ "data-vizmatic-graph-edge-title": encodeURIComponent(edge.title ?? ""),
4195
+ "data-vizmatic-graph-edge-href": edge.href == null ? void 0 : encodeURIComponent(edge.href),
3841
4196
  d: edgePath(edge.points),
3842
4197
  fill: "none",
3843
4198
  stroke: edge.color,
@@ -3876,7 +4231,8 @@ function GraphDiagram({
3876
4231
  ] : []),
3877
4232
  ...Array.from(layout.values()).map((node) => {
3878
4233
  const accent = node.muted ? c.textMuted : getToneColor(node.tone ?? "blue", c);
3879
- const accentText = node.muted ? c.textMuted : getReadableToneColor(node.tone ?? "blue", c);
4234
+ const fill = getToneFill(node.tone ?? "blue", c);
4235
+ const accentText = node.muted ? c.textMuted : getReadableToneColor(node.tone ?? "blue", c, fill, c.bg);
3880
4236
  const resolvedIconSize = clamp(
3881
4237
  node.iconSize ?? iconSize,
3882
4238
  8,
@@ -3900,6 +4256,11 @@ function GraphDiagram({
3900
4256
  "div",
3901
4257
  {
3902
4258
  key: `graph-node-${node.id}`,
4259
+ "data-vizmatic-graph-node-id": node.id,
4260
+ "data-vizmatic-graph-node-label": graphAccessibleText(node.label) || node.id,
4261
+ "data-vizmatic-graph-node-detail": graphAccessibleText(node.detail),
4262
+ "data-vizmatic-graph-node-title": node.title ?? "",
4263
+ "data-vizmatic-graph-node-href": node.href,
3903
4264
  style: {
3904
4265
  position: "absolute",
3905
4266
  left: node.cx - node.width / 2,
@@ -3914,7 +4275,7 @@ function GraphDiagram({
3914
4275
  padding: "8px 10px",
3915
4276
  boxSizing: "border-box",
3916
4277
  borderRadius: c.preset === "engineering" ? 5 : 10,
3917
- backgroundColor: node.muted ? c.bgSubtle : getToneFill(node.tone ?? "blue", c),
4278
+ backgroundColor: node.muted ? c.bgSubtle : fill,
3918
4279
  border: `${c.preset === "engineering" ? 1.25 : 1.5}px solid ${node.muted ? c.borderLight : `${accent}${c.preset === "engineering" ? "" : "88"}`}`,
3919
4280
  ...!node.muted && c.preset !== "engineering" ? { boxShadow: `0 8px 18px ${c.shadow}` } : {},
3920
4281
  opacity: node.muted ? 0.62 : 1,
@@ -3956,6 +4317,7 @@ function GraphDiagram({
3956
4317
  })
3957
4318
  );
3958
4319
  }
4320
+ Object.defineProperty(GraphDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
3959
4321
  function countTreeLeaves(node) {
3960
4322
  if (!node.children?.length) return 1;
3961
4323
  return node.children.reduce((sum, child) => sum + countTreeLeaves(child), 0);
@@ -4998,6 +5360,8 @@ function compileDataflow(spec) {
4998
5360
  id: node.id,
4999
5361
  label: node.label,
5000
5362
  detail: detailWithSchema(node.detail, node.schema),
5363
+ href: node.href,
5364
+ title: node.title,
5001
5365
  tone: node.tone ?? defaultNodeTones[kind],
5002
5366
  icon: node.icon ?? defaultNodeIcons[kind],
5003
5367
  muted: node.muted,
@@ -5010,9 +5374,12 @@ function compileDataflow(spec) {
5010
5374
  const mode = edgeMode(edge);
5011
5375
  const schema = schemaLabel(edge.schema);
5012
5376
  return {
5377
+ id: edge.id,
5013
5378
  from: edge.from,
5014
5379
  to: edge.to,
5015
5380
  label: edge.label ?? schema ?? mode,
5381
+ href: edge.href,
5382
+ title: edge.title,
5016
5383
  tone: edge.tone ?? (mode === "stream" ? "cyan" : "blue"),
5017
5384
  muted: edge.muted,
5018
5385
  kind: mode === "stream" ? "async" : "data",
@@ -5033,6 +5400,9 @@ function DataflowDiagram({
5033
5400
  edges,
5034
5401
  boundaries,
5035
5402
  ariaLabel,
5403
+ id,
5404
+ title,
5405
+ description,
5036
5406
  width,
5037
5407
  height,
5038
5408
  nodeWidth = 158,
@@ -5055,6 +5425,9 @@ function DataflowDiagram({
5055
5425
  edges: compiled.edges,
5056
5426
  groups: compiled.groups,
5057
5427
  ariaLabel: compiled.ariaLabel,
5428
+ id,
5429
+ title,
5430
+ description,
5058
5431
  width,
5059
5432
  height,
5060
5433
  nodeWidth,
@@ -5071,6 +5444,7 @@ function DataflowDiagram({
5071
5444
  iconSize
5072
5445
  });
5073
5446
  }
5447
+ Object.defineProperty(DataflowDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5074
5448
 
5075
5449
  // src/primitives/deployment.ts
5076
5450
  var boundaryKindLabels = {
@@ -5283,10 +5657,10 @@ function validateDeploymentSpec(boundaries, nodes, connections) {
5283
5657
  for (const side of ["from", "to"]) {
5284
5658
  const reference = connectionPortReference(connection, side);
5285
5659
  if (reference == null) continue;
5286
- const nodeId = side === "from" ? connection.from : connection.to;
5287
- const ports = portsByNode.get(nodeId);
5660
+ const nodeId2 = side === "from" ? connection.from : connection.to;
5661
+ const ports = portsByNode.get(nodeId2);
5288
5662
  if (ports != null && ports.size > 0 && !ports.has(String(reference))) {
5289
- throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId}".`);
5663
+ throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId2}".`);
5290
5664
  }
5291
5665
  }
5292
5666
  }
@@ -5321,6 +5695,8 @@ function compileDeployment(spec) {
5321
5695
  id: node.id,
5322
5696
  label: node.label,
5323
5697
  detail: node.detail ?? generatedDetail,
5698
+ href: node.href,
5699
+ title: node.title,
5324
5700
  x: node.x,
5325
5701
  y: node.y,
5326
5702
  tone: node.tone,
@@ -5343,6 +5719,7 @@ function compileDeployment(spec) {
5343
5719
  const fallbackFromPort = fromReference != null && !sourceNode?.ports?.length ? fromReference : void 0;
5344
5720
  const fallbackToPort = toReference != null && !targetNode?.ports?.length ? toReference : void 0;
5345
5721
  return {
5722
+ id: connection.id,
5346
5723
  from: connection.from,
5347
5724
  to: connection.to,
5348
5725
  tone: connection.tone ?? connectionTones[kind],
@@ -5350,7 +5727,9 @@ function compileDeployment(spec) {
5350
5727
  kind: graphConnectionKind(kind),
5351
5728
  style: connection.style ?? graphConnectionStyle(kind),
5352
5729
  arrow: connection.arrow ?? "forward",
5353
- label: connectionLabel(connection, sourcePort ?? fallbackFromPort, targetPort ?? fallbackToPort)
5730
+ label: connectionLabel(connection, sourcePort ?? fallbackFromPort, targetPort ?? fallbackToPort),
5731
+ href: connection.href,
5732
+ title: connection.title
5354
5733
  };
5355
5734
  });
5356
5735
  return {
@@ -5378,6 +5757,7 @@ function DeploymentDiagram({
5378
5757
  ariaLabel: compiled.ariaLabel
5379
5758
  });
5380
5759
  }
5760
+ Object.defineProperty(DeploymentDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5381
5761
 
5382
5762
  // src/primitives/transformer.ts
5383
5763
  var blockLabels = {
@@ -5576,6 +5956,8 @@ function compileTransformer(spec) {
5576
5956
  id,
5577
5957
  label,
5578
5958
  detail: repetitionDetail,
5959
+ href: block.href,
5960
+ title: block.title,
5579
5961
  x: block.x,
5580
5962
  y: block.y,
5581
5963
  tone: block.tone ?? blockTones[kind],
@@ -5590,8 +5972,10 @@ function compileTransformer(spec) {
5590
5972
  const edges = [];
5591
5973
  for (const route of routes) {
5592
5974
  const kind = resolveRouteKind(route);
5593
- for (const endpoint of expandedRouteEndpoints(route, repeatCounts, expandRepeats)) {
5975
+ const endpoints = expandedRouteEndpoints(route, repeatCounts, expandRepeats);
5976
+ for (const [index, endpoint] of endpoints.entries()) {
5594
5977
  edges.push({
5978
+ id: route.id == null ? void 0 : endpoints.length === 1 ? route.id : `${route.id}-${index + 1}`,
5595
5979
  from: endpoint.from,
5596
5980
  to: endpoint.to,
5597
5981
  tone: route.tone ?? routeTones[kind],
@@ -5599,7 +5983,9 @@ function compileTransformer(spec) {
5599
5983
  kind: graphRouteKind(kind),
5600
5984
  style: route.style ?? graphRouteStyle(kind),
5601
5985
  arrow: route.arrow ?? (kind === "residual" ? "both" : "forward"),
5602
- label: routeLabel(route, kind)
5986
+ label: routeLabel(route, kind),
5987
+ href: route.href,
5988
+ title: route.title
5603
5989
  });
5604
5990
  }
5605
5991
  }
@@ -5631,6 +6017,7 @@ function TransformerTopology({
5631
6017
  ariaLabel: compiled.ariaLabel
5632
6018
  });
5633
6019
  }
6020
+ Object.defineProperty(TransformerTopology, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5634
6021
 
5635
6022
  // src/primitives/data.ts
5636
6023
  import React9 from "react";
@@ -6000,8 +6387,9 @@ function Grid({
6000
6387
  const cellStyle = (cell, rowIndex, colIndex) => {
6001
6388
  const config = isGridCell(cell) ? cell : {};
6002
6389
  const toneColor = config.tone ? getToneColor(config.tone, c) : void 0;
6003
- const toneTextColor = config.tone ? getReadableToneColor(config.tone, c) : void 0;
6004
6390
  const isHeader = rowIndex < headerRows || colIndex < headerCols;
6391
+ const backgroundColor = config.backgroundColor ?? (toneColor ? `${toneColor}22` : isHeader ? c.bgSubtle : c.bgHover);
6392
+ const toneTextColor = config.tone ? getReadableToneColor(config.tone, c, backgroundColor, c.bgHover) : void 0;
6005
6393
  return {
6006
6394
  width: cellWidth,
6007
6395
  height: cellHeight,
@@ -6009,7 +6397,7 @@ function Grid({
6009
6397
  alignItems: "center",
6010
6398
  justifyContent: "center",
6011
6399
  borderRadius: radius,
6012
- backgroundColor: config.backgroundColor ?? (toneColor ? `${toneColor}22` : isHeader ? c.bgSubtle : c.bgHover),
6400
+ backgroundColor,
6013
6401
  border: `1px solid ${config.borderColor ?? (toneColor ? `${toneColor}55` : c.borderSubtle)}`,
6014
6402
  color: config.color ?? (toneTextColor ?? (isHeader ? c.textPrimary : c.textSecondary)),
6015
6403
  ...config.opacity !== void 0 ? { opacity: config.opacity } : {},
@@ -8068,13 +8456,13 @@ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDe
8068
8456
  const right = checkEdge((i, off) => [width - 1 - off, i], height);
8069
8457
  const top = checkEdge((i, off) => [i, off], width);
8070
8458
  const left = checkEdge((i, off) => [off, i], height);
8071
- const overflowEdges = [];
8072
- if (top) overflowEdges.push("top");
8073
- if (right) overflowEdges.push("right");
8074
- if (bottom) overflowEdges.push("bottom");
8075
- if (left) overflowEdges.push("left");
8076
- const overflows = overflowEdges.length > 0;
8077
- const message = overflows ? `Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.` : "";
8459
+ const overflowEdges2 = [];
8460
+ if (top) overflowEdges2.push("top");
8461
+ if (right) overflowEdges2.push("right");
8462
+ if (bottom) overflowEdges2.push("bottom");
8463
+ if (left) overflowEdges2.push("left");
8464
+ const overflows = overflowEdges2.length > 0;
8465
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges2.join(", ")}. Increase the illustration dimensions.` : "";
8078
8466
  return {
8079
8467
  overflows,
8080
8468
  edges: { top, right, bottom, left },
@@ -8543,14 +8931,19 @@ async function renderToSvgInContext(element, width, height, options) {
8543
8931
  options.theme ?? "dark",
8544
8932
  watermark
8545
8933
  ) : element;
8546
- const svg = await satori(outputElement, {
8934
+ const prepared = prepareAccessibleSvg(outputElement);
8935
+ const layoutNodes = [];
8936
+ const svg = await satori(prepared.element, {
8547
8937
  width,
8548
8938
  height,
8549
8939
  fonts,
8550
8940
  loadAdditionalAsset,
8551
- onNodeDetected: options.onNodeDetected
8941
+ onNodeDetected: (node) => {
8942
+ layoutNodes.push(node);
8943
+ options.onNodeDetected?.(node);
8944
+ }
8552
8945
  });
8553
- return sanitizeSvg(svg);
8946
+ return addSvgAccessibility(sanitizeSvg(svg), prepared.graphs, layoutNodes);
8554
8947
  }
8555
8948
 
8556
8949
  // src/animate.ts
@@ -9331,6 +9724,1318 @@ async function renderAnimationGifWithOutput(animation, options) {
9331
9724
  bytes: bytes.length
9332
9725
  };
9333
9726
  }
9727
+
9728
+ // src/import-types.ts
9729
+ function graphImportResult(source, graph, diagnostics) {
9730
+ if (graph.nodes.length === 0 && diagnostics.every(({ severity }) => severity !== "error")) {
9731
+ diagnostics.push({
9732
+ code: "import.empty",
9733
+ severity: "error",
9734
+ message: "The source contains no graph nodes to import.",
9735
+ line: 1,
9736
+ column: 1,
9737
+ excerpt: ""
9738
+ });
9739
+ }
9740
+ const ok = diagnostics.every(({ severity }) => severity !== "error");
9741
+ return ok ? { source, ok, graph, diagnostics } : { source, ok, diagnostics };
9742
+ }
9743
+ function addImportDiagnostic(diagnostics, sourceLines, line, code, severity, message, column = 1) {
9744
+ diagnostics.push({
9745
+ code,
9746
+ severity,
9747
+ message,
9748
+ line,
9749
+ column,
9750
+ excerpt: (sourceLines[line - 1] ?? "").trim().slice(0, 180)
9751
+ });
9752
+ }
9753
+
9754
+ // src/import-mermaid.ts
9755
+ var ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*/;
9756
+ var CONNECTORS = ["-.->", "-->", "---"];
9757
+ function skipWhitespace(line, index) {
9758
+ while (index < line.length && /\s/.test(line[index] ?? "")) index++;
9759
+ return index;
9760
+ }
9761
+ function readDelimited(line, start, close) {
9762
+ let inDoubleQuote = false;
9763
+ let escaped = false;
9764
+ for (let index = start; index < line.length; index++) {
9765
+ const character = line[index];
9766
+ if (inDoubleQuote) {
9767
+ if (escaped) escaped = false;
9768
+ else if (character === "\\") escaped = true;
9769
+ else if (character === '"') inDoubleQuote = false;
9770
+ continue;
9771
+ }
9772
+ if (character === '"') {
9773
+ inDoubleQuote = true;
9774
+ continue;
9775
+ }
9776
+ if (line.startsWith(close, index)) {
9777
+ return { value: line.slice(start, index), next: index + close.length };
9778
+ }
9779
+ }
9780
+ return void 0;
9781
+ }
9782
+ function decodeLabel(raw) {
9783
+ const value = raw.trim();
9784
+ if (!value.startsWith('"')) return value;
9785
+ if (!value.endsWith('"')) return void 0;
9786
+ try {
9787
+ const decoded = JSON.parse(value);
9788
+ return typeof decoded === "string" ? decoded : void 0;
9789
+ } catch {
9790
+ return void 0;
9791
+ }
9792
+ }
9793
+ function labelHasUnsupportedMarkup(label) {
9794
+ return /<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label);
9795
+ }
9796
+ function readEndpoint(line, from) {
9797
+ let index = skipWhitespace(line, from);
9798
+ const id = line.slice(index).match(ID_PATTERN)?.[0];
9799
+ if (!id) return void 0;
9800
+ index += id.length;
9801
+ const afterId = skipWhitespace(line, index);
9802
+ if (afterId >= line.length) return { id, label: id, shape: "rectangle", next: afterId };
9803
+ const rest = line.slice(afterId);
9804
+ const delimiters = [
9805
+ { open: "[(", close: ")]", lossy: true },
9806
+ { open: "([", close: "])", lossy: true },
9807
+ { open: "((", close: "))", lossy: true },
9808
+ { open: "{{", close: "}}", lossy: true },
9809
+ { open: "[", close: "]", lossy: false },
9810
+ { open: "(", close: ")", lossy: true },
9811
+ { open: "{", close: "}", lossy: true }
9812
+ ];
9813
+ const delimiter = delimiters.find(({ open }) => rest.startsWith(open));
9814
+ if (!delimiter) return { id, label: id, shape: "rectangle", next: index };
9815
+ const content = readDelimited(line, afterId + delimiter.open.length, delimiter.close);
9816
+ if (!content) return void 0;
9817
+ const label = decodeLabel(content.value);
9818
+ if (label === void 0) return void 0;
9819
+ return {
9820
+ id,
9821
+ label,
9822
+ shape: delimiter.lossy ? "lossy" : "rectangle",
9823
+ next: content.next
9824
+ };
9825
+ }
9826
+ function addNode(state, endpoint, groupId, line, sourceLines, diagnostics, explicitlyDeclared) {
9827
+ if (state.groupIds.has(endpoint.id)) {
9828
+ addImportDiagnostic(
9829
+ diagnostics,
9830
+ sourceLines,
9831
+ line,
9832
+ "import.unsupported_semantics",
9833
+ "error",
9834
+ `Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`
9835
+ );
9836
+ return false;
9837
+ }
9838
+ if (labelHasUnsupportedMarkup(endpoint.label)) {
9839
+ addImportDiagnostic(
9840
+ diagnostics,
9841
+ sourceLines,
9842
+ line,
9843
+ "import.unsupported_semantics",
9844
+ "error",
9845
+ `Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`
9846
+ );
9847
+ return false;
9848
+ }
9849
+ const existingIndex = state.nodeIndexes.get(endpoint.id);
9850
+ if (existingIndex !== void 0) {
9851
+ const existing = state.nodes[existingIndex];
9852
+ if (!existing) return false;
9853
+ if (groupId && existing.group && existing.group !== groupId) {
9854
+ addImportDiagnostic(
9855
+ diagnostics,
9856
+ sourceLines,
9857
+ line,
9858
+ "import.unsupported_semantics",
9859
+ "error",
9860
+ `Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`
9861
+ );
9862
+ return false;
9863
+ }
9864
+ if (groupId && !existing.group) {
9865
+ addImportDiagnostic(
9866
+ diagnostics,
9867
+ sourceLines,
9868
+ line,
9869
+ "import.unsupported_semantics",
9870
+ "error",
9871
+ `Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`
9872
+ );
9873
+ return false;
9874
+ }
9875
+ if (explicitlyDeclared) existing.label = endpoint.label;
9876
+ } else {
9877
+ state.nodeIndexes.set(endpoint.id, state.nodes.length);
9878
+ state.nodes.push({
9879
+ id: endpoint.id,
9880
+ label: endpoint.label,
9881
+ ...groupId ? { group: groupId } : {}
9882
+ });
9883
+ }
9884
+ if (endpoint.shape === "lossy" && !state.warnedShapes.has(endpoint.id)) {
9885
+ state.warnedShapes.add(endpoint.id);
9886
+ addImportDiagnostic(
9887
+ diagnostics,
9888
+ sourceLines,
9889
+ line,
9890
+ "import.lossy_semantics",
9891
+ "warning",
9892
+ `Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`
9893
+ );
9894
+ }
9895
+ return true;
9896
+ }
9897
+ function parseNodeOrEdgeLine(line, groupId, lineNumber, sourceLines, state, diagnostics) {
9898
+ const first = readEndpoint(line, 0);
9899
+ if (!first) {
9900
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Could not parse this Mermaid node or edge statement.");
9901
+ return;
9902
+ }
9903
+ const connectorStart = skipWhitespace(line, first.next);
9904
+ const hasConnector = CONNECTORS.some((connector) => line.startsWith(connector, connectorStart));
9905
+ if (!addNode(state, first, groupId, lineNumber, sourceLines, diagnostics, !hasConnector)) return;
9906
+ let previous = first;
9907
+ let cursor = first.next;
9908
+ while (true) {
9909
+ cursor = skipWhitespace(line, cursor);
9910
+ if (cursor >= line.length) return;
9911
+ const connector = CONNECTORS.find((candidate) => line.startsWith(candidate, cursor));
9912
+ if (!connector) {
9913
+ addImportDiagnostic(
9914
+ diagnostics,
9915
+ sourceLines,
9916
+ lineNumber,
9917
+ "import.unsupported_syntax",
9918
+ "error",
9919
+ "Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",
9920
+ cursor + 1
9921
+ );
9922
+ return;
9923
+ }
9924
+ cursor += connector.length;
9925
+ cursor = skipWhitespace(line, cursor);
9926
+ let edgeLabel;
9927
+ if (line[cursor] === "|") {
9928
+ const end = line.indexOf("|", cursor + 1);
9929
+ if (end < 0) {
9930
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid edge label is missing its closing |.", cursor + 1);
9931
+ return;
9932
+ }
9933
+ edgeLabel = line.slice(cursor + 1, end).trim();
9934
+ cursor = skipWhitespace(line, end + 1);
9935
+ if (labelHasUnsupportedMarkup(edgeLabel)) {
9936
+ addImportDiagnostic(
9937
+ diagnostics,
9938
+ sourceLines,
9939
+ lineNumber,
9940
+ "import.unsupported_semantics",
9941
+ "error",
9942
+ "Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",
9943
+ cursor + 1
9944
+ );
9945
+ return;
9946
+ }
9947
+ }
9948
+ const next = readEndpoint(line, cursor);
9949
+ if (!next) {
9950
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid connection has no supported target node.", cursor + 1);
9951
+ return;
9952
+ }
9953
+ if (!addNode(state, next, groupId, lineNumber, sourceLines, diagnostics, false)) return;
9954
+ const edge = {
9955
+ from: previous.id,
9956
+ to: next.id,
9957
+ ...edgeLabel !== void 0 ? { label: edgeLabel } : {},
9958
+ ...connector === "---" ? { arrow: "none" } : connector === "-.->" ? { arrow: "forward", style: "dotted" } : { arrow: "forward" }
9959
+ };
9960
+ state.edges.push(edge);
9961
+ state.edgeReferences.push({ id: previous.id, line: lineNumber }, { id: next.id, line: lineNumber });
9962
+ previous = next;
9963
+ cursor = next.next;
9964
+ }
9965
+ }
9966
+ function importMermaidGraph(source) {
9967
+ const sourceLines = source.split(/\r?\n/);
9968
+ const diagnostics = [];
9969
+ const state = {
9970
+ nodes: [],
9971
+ nodeIndexes: /* @__PURE__ */ new Map(),
9972
+ groups: [],
9973
+ groupIds: /* @__PURE__ */ new Set(),
9974
+ edges: [],
9975
+ edgeReferences: [],
9976
+ warnedShapes: /* @__PURE__ */ new Set()
9977
+ };
9978
+ let direction = "TB";
9979
+ let currentGroup;
9980
+ let sawHeader = false;
9981
+ for (let index = 0; index < sourceLines.length; index++) {
9982
+ const lineNumber = index + 1;
9983
+ const rawLine = sourceLines[index] ?? "";
9984
+ const line = rawLine.trim();
9985
+ if (!line) continue;
9986
+ if (line.startsWith("%%{")) {
9987
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Mermaid directives and embedded configuration are not imported.");
9988
+ continue;
9989
+ }
9990
+ if (line.startsWith("%%")) continue;
9991
+ if (!sawHeader) {
9992
+ const header = line.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);
9993
+ if (!header) {
9994
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", 'Expected a Mermaid flowchart or graph header such as "flowchart LR".');
9995
+ sawHeader = true;
9996
+ continue;
9997
+ }
9998
+ sawHeader = true;
9999
+ const sourceDirection = header[1]?.toUpperCase();
10000
+ direction = sourceDirection === "TD" ? "TB" : sourceDirection ?? "TB";
10001
+ continue;
10002
+ }
10003
+ const subgraph = line.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);
10004
+ if (subgraph) {
10005
+ if (currentGroup) {
10006
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Nested Mermaid subgraphs are not imported.");
10007
+ continue;
10008
+ }
10009
+ const id = subgraph[1];
10010
+ if (!id) continue;
10011
+ if (state.groupIds.has(id) || state.nodeIndexes.has(id)) {
10012
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", `Mermaid subgraph id "${id}" conflicts with an existing group or node.`);
10013
+ continue;
10014
+ }
10015
+ const rawLabel = subgraph[2];
10016
+ const label = rawLabel === void 0 ? id : decodeLabel(rawLabel);
10017
+ if (label === void 0 || labelHasUnsupportedMarkup(label)) {
10018
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", `Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);
10019
+ continue;
10020
+ }
10021
+ currentGroup = id;
10022
+ state.groupIds.add(id);
10023
+ state.groups.push({ id, label });
10024
+ continue;
10025
+ }
10026
+ if (/^subgraph\b/i.test(line)) {
10027
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_syntax", "error", "Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");
10028
+ continue;
10029
+ }
10030
+ if (/^end\s*$/i.test(line)) {
10031
+ if (!currentGroup) addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid end has no matching subgraph.");
10032
+ else currentGroup = void 0;
10033
+ continue;
10034
+ }
10035
+ if (/^direction\b/i.test(line)) {
10036
+ addImportDiagnostic(
10037
+ diagnostics,
10038
+ sourceLines,
10039
+ lineNumber,
10040
+ currentGroup ? "import.unsupported_semantics" : "import.parse_error",
10041
+ "error",
10042
+ currentGroup ? "Per-subgraph Mermaid direction cannot be represented by GraphDiagram." : "Set Mermaid graph direction in the flowchart or graph header."
10043
+ );
10044
+ continue;
10045
+ }
10046
+ if (/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line)) {
10047
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Mermaid classes, styling, accessibility directives, and click actions are not imported.");
10048
+ continue;
10049
+ }
10050
+ parseNodeOrEdgeLine(line, currentGroup, lineNumber, sourceLines, state, diagnostics);
10051
+ }
10052
+ if (!sawHeader) {
10053
+ addImportDiagnostic(diagnostics, sourceLines, 1, "import.parse_error", "error", "Missing Mermaid flowchart or graph header.");
10054
+ }
10055
+ if (currentGroup) {
10056
+ addImportDiagnostic(diagnostics, sourceLines, sourceLines.length, "import.parse_error", "error", `Mermaid subgraph "${currentGroup}" has no matching end.`);
10057
+ }
10058
+ for (const reference of state.edgeReferences) {
10059
+ if (state.groupIds.has(reference.id)) {
10060
+ addImportDiagnostic(
10061
+ diagnostics,
10062
+ sourceLines,
10063
+ reference.line,
10064
+ "import.unsupported_semantics",
10065
+ "error",
10066
+ `Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`
10067
+ );
10068
+ }
10069
+ }
10070
+ const graph = {
10071
+ nodes: state.nodes,
10072
+ edges: state.edges,
10073
+ groups: state.groups,
10074
+ direction
10075
+ };
10076
+ return graphImportResult("mermaid", graph, diagnostics);
10077
+ }
10078
+
10079
+ // src/import-d2.ts
10080
+ function decodeD2Label(raw) {
10081
+ const value = raw.trim();
10082
+ if (value.startsWith('"')) {
10083
+ if (!value.endsWith('"')) return void 0;
10084
+ try {
10085
+ const decoded = JSON.parse(value);
10086
+ return typeof decoded === "string" ? decoded : void 0;
10087
+ } catch {
10088
+ return void 0;
10089
+ }
10090
+ }
10091
+ if (value.startsWith("'")) {
10092
+ if (!value.endsWith("'")) return void 0;
10093
+ return value.slice(1, -1).replace(/\\(['\\])/g, "$1");
10094
+ }
10095
+ return value;
10096
+ }
10097
+ function hasMarkdownFormatting(label) {
10098
+ return /<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label);
10099
+ }
10100
+ function hasUnquotedHash(line) {
10101
+ let quote;
10102
+ let escaped = false;
10103
+ for (const character of line) {
10104
+ if (quote) {
10105
+ if (escaped) escaped = false;
10106
+ else if (character === "\\") escaped = true;
10107
+ else if (character === quote) quote = void 0;
10108
+ continue;
10109
+ }
10110
+ if (character === '"' || character === "'") quote = character;
10111
+ else if (character === "#") return true;
10112
+ }
10113
+ return false;
10114
+ }
10115
+ function addNode2(nodes, id, label, line, sourceLines, diagnostics, explicitLabel) {
10116
+ if (hasMarkdownFormatting(label)) {
10117
+ addImportDiagnostic(
10118
+ diagnostics,
10119
+ sourceLines,
10120
+ line,
10121
+ "import.unsupported_semantics",
10122
+ "error",
10123
+ `D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`
10124
+ );
10125
+ return false;
10126
+ }
10127
+ const existing = nodes.get(id);
10128
+ if (existing) {
10129
+ if (explicitLabel) {
10130
+ existing.node.label = label;
10131
+ }
10132
+ } else {
10133
+ nodes.set(id, { node: { id, label } });
10134
+ }
10135
+ return true;
10136
+ }
10137
+ function reportUnsupported(diagnostics, sourceLines, line, message, code = "import.unsupported_syntax", column = 1) {
10138
+ addImportDiagnostic(diagnostics, sourceLines, line, code, "error", message, column);
10139
+ }
10140
+ function importD2Graph(source) {
10141
+ const sourceLines = source.split(/\r?\n/);
10142
+ const diagnostics = [];
10143
+ const nodesById = /* @__PURE__ */ new Map();
10144
+ const edges = [];
10145
+ const shapes = /* @__PURE__ */ new Map();
10146
+ let direction = "TB";
10147
+ let containerDepth = 0;
10148
+ for (let index = 0; index < sourceLines.length; index++) {
10149
+ const lineNumber = index + 1;
10150
+ const rawLine = sourceLines[index] ?? "";
10151
+ const line = rawLine.trim();
10152
+ if (!line) continue;
10153
+ if (containerDepth > 0) {
10154
+ const opens = (rawLine.match(/\{/g) ?? []).length;
10155
+ const closes = (rawLine.match(/\}/g) ?? []).length;
10156
+ containerDepth = Math.max(0, containerDepth + opens - closes);
10157
+ continue;
10158
+ }
10159
+ if (line.startsWith("#")) continue;
10160
+ if (hasUnquotedHash(line)) {
10161
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");
10162
+ continue;
10163
+ }
10164
+ if (line.includes(";")) {
10165
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 semicolon-separated statements are not supported; place one statement on each line.");
10166
+ continue;
10167
+ }
10168
+ if (line.includes("{") || line.includes("}")) {
10169
+ reportUnsupported(
10170
+ diagnostics,
10171
+ sourceLines,
10172
+ lineNumber,
10173
+ "D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.",
10174
+ "import.unsupported_semantics"
10175
+ );
10176
+ const opens = (rawLine.match(/\{/g) ?? []).length;
10177
+ const closes = (rawLine.match(/\}/g) ?? []).length;
10178
+ containerDepth = Math.max(0, opens - closes);
10179
+ continue;
10180
+ }
10181
+ const directionMatch = line.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);
10182
+ if (directionMatch) {
10183
+ const value = directionMatch[1]?.toLowerCase();
10184
+ direction = value === "left" ? "RL" : value === "down" ? "TB" : value === "up" ? "BT" : "LR";
10185
+ continue;
10186
+ }
10187
+ if (/^direction\b/i.test(line)) {
10188
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 direction must be right, left, down, or up.", "import.parse_error");
10189
+ continue;
10190
+ }
10191
+ const shapeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);
10192
+ if (shapeMatch) {
10193
+ const id = shapeMatch[1];
10194
+ const shape = decodeD2Label(shapeMatch[2] ?? "");
10195
+ if (!id || shape === void 0 || shape === "") {
10196
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 shape declaration needs a simple identifier and a shape value.", "import.parse_error");
10197
+ continue;
10198
+ }
10199
+ if (!nodesById.has(id)) addNode2(nodesById, id, id, lineNumber, sourceLines, diagnostics, false);
10200
+ shapes.set(id, { value: shape, line: lineNumber });
10201
+ continue;
10202
+ }
10203
+ const edgeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);
10204
+ if (edgeMatch) {
10205
+ const from = edgeMatch[1];
10206
+ const connector = edgeMatch[2];
10207
+ const to = edgeMatch[3];
10208
+ const rawLabel = edgeMatch[4];
10209
+ if (!from || !connector || !to) continue;
10210
+ let label;
10211
+ if (rawLabel !== void 0) {
10212
+ label = decodeD2Label(rawLabel);
10213
+ if (label === void 0) {
10214
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 connection label has invalid quotes.", "import.parse_error");
10215
+ continue;
10216
+ }
10217
+ if (hasMarkdownFormatting(label)) {
10218
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.", "import.unsupported_semantics");
10219
+ continue;
10220
+ }
10221
+ }
10222
+ addNode2(nodesById, from, from, lineNumber, sourceLines, diagnostics, false);
10223
+ addNode2(nodesById, to, to, lineNumber, sourceLines, diagnostics, false);
10224
+ edges.push({
10225
+ from,
10226
+ to,
10227
+ ...label !== void 0 ? { label } : {},
10228
+ arrow: connector === "<->" ? "both" : connector === "<-" ? "backward" : connector === "--" ? "none" : "forward"
10229
+ });
10230
+ continue;
10231
+ }
10232
+ const nodeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);
10233
+ if (nodeMatch) {
10234
+ const id = nodeMatch[1];
10235
+ const rawLabel = nodeMatch[2];
10236
+ if (!id) continue;
10237
+ let label = id;
10238
+ let explicitLabel = false;
10239
+ if (rawLabel !== void 0) {
10240
+ const decoded = decodeD2Label(rawLabel);
10241
+ if (decoded === void 0) {
10242
+ reportUnsupported(diagnostics, sourceLines, lineNumber, `D2 label for "${id}" has invalid quotes.`, "import.parse_error");
10243
+ continue;
10244
+ }
10245
+ label = decoded;
10246
+ explicitLabel = true;
10247
+ }
10248
+ addNode2(nodesById, id, label, lineNumber, sourceLines, diagnostics, explicitLabel);
10249
+ continue;
10250
+ }
10251
+ if (line.includes(".style") || line.includes(".width") || line.includes(".height") || line.includes(".near")) {
10252
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 styling, sizing, and positioning fields are not imported.", "import.unsupported_semantics");
10253
+ } else if (/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line)) {
10254
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.");
10255
+ } else if (/(?:<->|->|<-|--)/.test(line)) {
10256
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.");
10257
+ } else {
10258
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "Could not parse this D2 statement in the supported subset.", "import.parse_error");
10259
+ }
10260
+ }
10261
+ if (containerDepth > 0) {
10262
+ reportUnsupported(diagnostics, sourceLines, sourceLines.length, "D2 object-property block has no matching closing brace.", "import.parse_error");
10263
+ }
10264
+ for (const [id, { value, line }] of shapes) {
10265
+ if (value.toLowerCase() === "rectangle") continue;
10266
+ addImportDiagnostic(
10267
+ diagnostics,
10268
+ sourceLines,
10269
+ line,
10270
+ "import.lossy_semantics",
10271
+ "warning",
10272
+ `D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`
10273
+ );
10274
+ }
10275
+ return graphImportResult("d2", {
10276
+ nodes: [...nodesById.values()].map(({ node }) => node),
10277
+ edges,
10278
+ groups: [],
10279
+ direction
10280
+ }, diagnostics);
10281
+ }
10282
+
10283
+ // src/check.ts
10284
+ import { mkdtemp, rm } from "fs/promises";
10285
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
10286
+ import { tmpdir } from "os";
10287
+ import { join as join2 } from "path";
10288
+
10289
+ // src/diagnostics.ts
10290
+ import parseCssColor3 from "parse-css-color";
10291
+ import { Children, isValidElement as isValidElement2 } from "react";
10292
+ var CHECK_DIAGNOSTIC_CODES = [
10293
+ "accessibility.low_contrast",
10294
+ "api.unsupported_prop",
10295
+ "asset.warning",
10296
+ "frame.load_error",
10297
+ "frame.unknown_preset",
10298
+ "layout.auto_size",
10299
+ "layout.connector_congestion",
10300
+ "layout.overflow",
10301
+ "layout.text_overlap",
10302
+ "layout.whitespace_imbalance",
10303
+ "readability.small_text",
10304
+ "render.error",
10305
+ "render.warning",
10306
+ "style.unsupported"
10307
+ ];
10308
+ var MAX_CONTRAST_NODES = 5e3;
10309
+ var MAX_DIAGNOSTICS_PER_RULE = 12;
10310
+ var MIN_TEXT_SIZE = 11;
10311
+ function hslToRgb2(hue, saturation, lightness) {
10312
+ const h = (hue % 360 + 360) % 360;
10313
+ const s = saturation / 100;
10314
+ const l = lightness / 100;
10315
+ const chroma = (1 - Math.abs(2 * l - 1)) * s;
10316
+ const segment = h / 60;
10317
+ const intermediate = chroma * (1 - Math.abs(segment % 2 - 1));
10318
+ let channels;
10319
+ if (segment < 1) channels = [chroma, intermediate, 0];
10320
+ else if (segment < 2) channels = [intermediate, chroma, 0];
10321
+ else if (segment < 3) channels = [0, chroma, intermediate];
10322
+ else if (segment < 4) channels = [0, intermediate, chroma];
10323
+ else if (segment < 5) channels = [intermediate, 0, chroma];
10324
+ else channels = [chroma, 0, intermediate];
10325
+ const offset = l - chroma / 2;
10326
+ return channels.map((channel) => Math.round((channel + offset) * 255));
10327
+ }
10328
+ function colorFromCss(value) {
10329
+ if (typeof value !== "string") return void 0;
10330
+ const parsed = parseCssColor3(value);
10331
+ if (!parsed || parsed.values.length < 3) return void 0;
10332
+ const [r, g, b] = parsed.type === "hsl" ? hslToRgb2(parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0) : [parsed.values[0] ?? 0, parsed.values[1] ?? 0, parsed.values[2] ?? 0];
10333
+ return {
10334
+ r,
10335
+ g,
10336
+ b,
10337
+ alpha: parsed.alpha
10338
+ };
10339
+ }
10340
+ function compositeOver(foreground, background) {
10341
+ if (foreground.alpha >= 1 || !background) return foreground;
10342
+ const alpha = foreground.alpha + background.alpha * (1 - foreground.alpha);
10343
+ if (alpha <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
10344
+ return {
10345
+ r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha,
10346
+ g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha,
10347
+ b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha,
10348
+ alpha
10349
+ };
10350
+ }
10351
+ function isUnresolvedColor(value) {
10352
+ if (typeof value !== "string" || value.trim() === "" || colorFromCss(value)) return false;
10353
+ return !["inherit", "initial", "revert", "unset"].includes(value.trim().toLowerCase());
10354
+ }
10355
+ function channelLuminance(value) {
10356
+ const normalized = value / 255;
10357
+ return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
10358
+ }
10359
+ function relativeLuminance(color) {
10360
+ return 0.2126 * channelLuminance(color.r) + 0.7152 * channelLuminance(color.g) + 0.0722 * channelLuminance(color.b);
10361
+ }
10362
+ function contrastRatio(foreground, background) {
10363
+ const lighter = Math.max(relativeLuminance(foreground), relativeLuminance(background));
10364
+ const darker = Math.min(relativeLuminance(foreground), relativeLuminance(background));
10365
+ return (lighter + 0.05) / (darker + 0.05);
10366
+ }
10367
+ function numericFontWeight(value) {
10368
+ if (typeof value === "number") return value;
10369
+ if (value === "bold") return 700;
10370
+ if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
10371
+ return void 0;
10372
+ }
10373
+ function fontSizePixels(value, inherited) {
10374
+ if (typeof value === "number") return value;
10375
+ if (typeof value !== "string") return inherited;
10376
+ const match = value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);
10377
+ if (!match?.[1]) return inherited;
10378
+ const amount = Number(match[1]);
10379
+ const unit = match[2] ?? "px";
10380
+ if (unit === "pt") return amount * 4 / 3;
10381
+ if (unit === "rem") return amount * 16;
10382
+ if (unit === "em") return amount * (inherited ?? 16);
10383
+ if (unit === "%") return amount / 100 * (inherited ?? 16);
10384
+ return amount;
10385
+ }
10386
+ function requiredContrast(context) {
10387
+ const large = (context.fontSize ?? 16) >= 24 || (context.fontSize ?? 16) >= 18.66 && (context.fontWeight ?? 400) >= 700;
10388
+ return large ? 3 : 4.5;
10389
+ }
10390
+ function styleRecord(value) {
10391
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
10392
+ return value;
10393
+ }
10394
+ function hasDirectText(children) {
10395
+ return Children.toArray(children).some((child) => typeof child === "string" || typeof child === "number");
10396
+ }
10397
+ function elementId(props) {
10398
+ const value = props.id ?? props["data-vizmatic-id"];
10399
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
10400
+ }
10401
+ function resolveFunctionComponent(node, trustedComponents) {
10402
+ if (!isValidElement2(node) || typeof node.type !== "function" || trustedComponents.has(node.type)) return void 0;
10403
+ const component = node.type;
10404
+ if (component.__vizmaticPrimitive) return void 0;
10405
+ if (component.prototype?.isReactComponent) return void 0;
10406
+ try {
10407
+ return component(node.props);
10408
+ } catch {
10409
+ return void 0;
10410
+ }
10411
+ }
10412
+ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new Set(), rootBackground2) {
10413
+ const diagnostics = [];
10414
+ const seen = /* @__PURE__ */ new Set();
10415
+ let visited = 0;
10416
+ function visit(node, inherited, path) {
10417
+ if (visited++ >= MAX_CONTRAST_NODES || !isValidElement2(node)) return;
10418
+ const resolved = resolveFunctionComponent(node, trustedComponents);
10419
+ if (resolved !== void 0) {
10420
+ visit(resolved, inherited, path);
10421
+ return;
10422
+ }
10423
+ const props = node.props;
10424
+ const style = typeof node.type === "string" ? styleRecord(props.style) : {};
10425
+ const backgroundImage = typeof style.backgroundImage === "string" ? style.backgroundImage.trim().toLowerCase() : "";
10426
+ const backgroundShorthand = typeof style.background === "string" ? style.background.trim() : "";
10427
+ const isBackgroundWrapper = typeof node.type === "function" && (trustedComponents.has(node.type) || Boolean(node.type.__vizmaticPrimitive));
10428
+ const wrapperBackground = isBackgroundWrapper ? props.background : void 0;
10429
+ const hasUnresolvedBackground = backgroundImage !== "" && backgroundImage !== "none" || isUnresolvedColor(style.backgroundColor) || backgroundShorthand !== "" && backgroundShorthand.toLowerCase() !== "none" && !colorFromCss(backgroundShorthand) || isUnresolvedColor(wrapperBackground);
10430
+ const ownBackground = colorFromCss(style.backgroundColor) ?? colorFromCss(style.background) ?? colorFromCss(wrapperBackground);
10431
+ const baseBackground = path === "root" && isBackgroundWrapper && colorFromCss(wrapperBackground) ? void 0 : inherited.background;
10432
+ const background = hasUnresolvedBackground ? void 0 : ownBackground ? compositeOver(ownBackground, baseBackground) : baseBackground;
10433
+ const color = typeof style.color === "string" && style.color.trim().toLowerCase() === "currentcolor" ? inherited.color : isUnresolvedColor(style.color) ? void 0 : colorFromCss(style.color) ?? inherited.color;
10434
+ const fontSize = fontSizePixels(style.fontSize, inherited.fontSize);
10435
+ const fontWeight = numericFontWeight(style.fontWeight) ?? inherited.fontWeight;
10436
+ const context = { background, color, fontSize, fontWeight };
10437
+ if (typeof node.type === "string" && hasDirectText(props.children) && color && background !== void 0 && background.alpha >= 1) {
10438
+ const renderedColor = compositeOver(color, background);
10439
+ const ratio = contrastRatio(renderedColor, background);
10440
+ const required = requiredContrast(context);
10441
+ if (ratio < required) {
10442
+ const rounded = Math.round(ratio * 100) / 100;
10443
+ const key = `${rounded}:${required}:${path}`;
10444
+ if (!seen.has(key)) {
10445
+ seen.add(key);
10446
+ diagnostics.push({
10447
+ code: "accessibility.low_contrast",
10448
+ severity: "warning",
10449
+ theme,
10450
+ message: `Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,
10451
+ suggestion: "Use a stronger text or background color token.",
10452
+ elementId: elementId(props),
10453
+ location: { path }
10454
+ });
10455
+ }
10456
+ }
10457
+ }
10458
+ Children.forEach(props.children, (child, index) => visit(child, context, `${path}.${index}`));
10459
+ }
10460
+ visit(element, { background: colorFromCss(rootBackground2) }, "root");
10461
+ return diagnostics;
10462
+ }
10463
+ function containsLayoutNode(parent, child) {
10464
+ const epsilon = 0.5;
10465
+ return child.left >= parent.left - epsilon && child.top >= parent.top - epsilon && child.left + child.width <= parent.left + parent.width + epsilon && child.top + child.height <= parent.top + parent.height + epsilon;
10466
+ }
10467
+ function textUnits(text) {
10468
+ return Array.from(text.normalize("NFC")).reduce((sum, character) => sum + ((character.codePointAt(0) ?? 0) > 255 ? 1.7 : 1), 0);
10469
+ }
10470
+ function renderedTextNodes(nodes) {
10471
+ const textNodes = [];
10472
+ const ancestors = [];
10473
+ for (const node of nodes) {
10474
+ while (ancestors.length > 0 && !containsLayoutNode(ancestors[ancestors.length - 1].node, node)) {
10475
+ ancestors.pop();
10476
+ }
10477
+ const inherited = ancestors[ancestors.length - 1];
10478
+ const style = styleRecord(node.props.style);
10479
+ const fontSize = fontSizePixels(style.fontSize, inherited?.fontSize) ?? 16;
10480
+ const textAlign = typeof style.textAlign === "string" ? style.textAlign : inherited?.textAlign ?? "left";
10481
+ const text = node.textContent?.trim();
10482
+ if (text && node.width > 0 && node.height > 0) {
10483
+ const estimatedLines = Math.max(1, Math.round(node.height / Math.max(fontSize * 1.5, 1)));
10484
+ const paintHeight = Math.min(
10485
+ node.height,
10486
+ fontSize * 0.9 + (estimatedLines - 1) * fontSize * 1.25
10487
+ );
10488
+ const unwrappedWidth = textUnits(text) * fontSize * 0.56;
10489
+ const paintWidth = Math.min(node.width, unwrappedWidth);
10490
+ const horizontalInset = textAlign === "center" ? (node.width - paintWidth) / 2 : textAlign === "right" || textAlign === "end" ? node.width - paintWidth : 0;
10491
+ textNodes.push({
10492
+ text,
10493
+ elementId: elementId(node.props),
10494
+ left: node.left,
10495
+ top: node.top,
10496
+ width: node.width,
10497
+ height: node.height,
10498
+ paintLeft: node.left + horizontalInset,
10499
+ paintTop: node.top + (node.height - paintHeight) / 2,
10500
+ paintWidth,
10501
+ paintHeight,
10502
+ fontSize
10503
+ });
10504
+ } else if (node.width > 0 && node.height > 0) {
10505
+ ancestors.push({ node, fontSize, textAlign });
10506
+ }
10507
+ }
10508
+ return textNodes;
10509
+ }
10510
+ function textExcerpt(text) {
10511
+ const normalized = text.replace(/\s+/g, " ").trim();
10512
+ return normalized.length > 40 ? `${normalized.slice(0, 37)}...` : normalized;
10513
+ }
10514
+ function meaningfulOverlap(a, b) {
10515
+ const width = Math.min(a.paintLeft + a.paintWidth, b.paintLeft + b.paintWidth) - Math.max(a.paintLeft, b.paintLeft);
10516
+ const height = Math.min(a.paintTop + a.paintHeight, b.paintTop + b.paintHeight) - Math.max(a.paintTop, b.paintTop);
10517
+ if (width < 2 || height < 2) return false;
10518
+ if (a.text === b.text && a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height) return false;
10519
+ const overlapArea = width * height;
10520
+ const smallerArea = Math.min(a.paintWidth * a.paintHeight, b.paintWidth * b.paintHeight);
10521
+ return overlapArea / smallerArea >= 0.08;
10522
+ }
10523
+ function overlapCandidates(nodes) {
10524
+ const cellSize = 96;
10525
+ const buckets = /* @__PURE__ */ new Map();
10526
+ const pairs = [];
10527
+ for (let index = 0; index < nodes.length && pairs.length < MAX_DIAGNOSTICS_PER_RULE; index += 1) {
10528
+ const node = nodes[index];
10529
+ const minX = Math.floor(node.paintLeft / cellSize);
10530
+ const maxX = Math.floor((node.paintLeft + node.paintWidth) / cellSize);
10531
+ const minY = Math.floor(node.paintTop / cellSize);
10532
+ const maxY = Math.floor((node.paintTop + node.paintHeight) / cellSize);
10533
+ const candidates = /* @__PURE__ */ new Set();
10534
+ for (let x = minX; x <= maxX; x += 1) {
10535
+ for (let y = minY; y <= maxY; y += 1) {
10536
+ const bucket = buckets.get(`${x}:${y}`);
10537
+ bucket?.forEach((candidate) => candidates.add(candidate));
10538
+ }
10539
+ }
10540
+ for (const candidate of candidates) {
10541
+ if (meaningfulOverlap(nodes[candidate], node)) pairs.push([nodes[candidate], node]);
10542
+ if (pairs.length >= MAX_DIAGNOSTICS_PER_RULE) break;
10543
+ }
10544
+ for (let x = minX; x <= maxX; x += 1) {
10545
+ for (let y = minY; y <= maxY; y += 1) {
10546
+ const key = `${x}:${y}`;
10547
+ const bucket = buckets.get(key) ?? [];
10548
+ bucket.push(index);
10549
+ buckets.set(key, bucket);
10550
+ }
10551
+ }
10552
+ }
10553
+ return pairs;
10554
+ }
10555
+ function analyzeRenderedLayout(nodes, theme) {
10556
+ const diagnostics = [];
10557
+ const textNodes = renderedTextNodes(nodes);
10558
+ const seenSmallText = /* @__PURE__ */ new Set();
10559
+ let smallTextCount = 0;
10560
+ for (const node of textNodes) {
10561
+ if (node.fontSize >= MIN_TEXT_SIZE) continue;
10562
+ const excerpt = textExcerpt(node.text);
10563
+ const key = `${excerpt}:${node.fontSize}`;
10564
+ if (seenSmallText.has(key)) continue;
10565
+ seenSmallText.add(key);
10566
+ diagnostics.push({
10567
+ code: "readability.small_text",
10568
+ severity: "warning",
10569
+ theme,
10570
+ message: `Text "${excerpt}" renders at ${node.fontSize}px.`,
10571
+ suggestion: `Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,
10572
+ elementId: node.elementId,
10573
+ location: { x: node.left, y: node.top, width: node.width, height: node.height }
10574
+ });
10575
+ smallTextCount += 1;
10576
+ if (smallTextCount >= MAX_DIAGNOSTICS_PER_RULE) break;
10577
+ }
10578
+ for (const [left, right] of overlapCandidates(textNodes)) {
10579
+ diagnostics.push({
10580
+ code: "layout.text_overlap",
10581
+ severity: "warning",
10582
+ theme,
10583
+ message: `Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,
10584
+ suggestion: "Increase spacing or canvas size, shorten labels, or move one label.",
10585
+ elementId: left.elementId,
10586
+ relatedElementIds: right.elementId ? [right.elementId] : void 0,
10587
+ location: { x: left.left, y: left.top, width: left.width, height: left.height }
10588
+ });
10589
+ }
10590
+ const maxDataNumber = (attribute2) => Math.max(0, ...nodes.map((node) => {
10591
+ const value = node.props[attribute2];
10592
+ return typeof value === "number" ? value : Number(value) || 0;
10593
+ }));
10594
+ const connectorCrossings2 = maxDataNumber("data-vizmatic-connector-crossings");
10595
+ if (connectorCrossings2 > 0) {
10596
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-connector-crossings"]) > 0);
10597
+ diagnostics.push({
10598
+ code: "layout.connector_congestion",
10599
+ severity: "warning",
10600
+ theme,
10601
+ message: `${connectorCrossings2} connector crossing${connectorCrossings2 === 1 ? "" : "s"} detected.`,
10602
+ suggestion: "Use automatic layout, change graph direction, or simplify the edge set.",
10603
+ elementId: source ? elementId(source.props) : void 0,
10604
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
10605
+ });
10606
+ }
10607
+ const labelCollisions = maxDataNumber("data-vizmatic-connector-label-collisions");
10608
+ if (labelCollisions > 0) {
10609
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-connector-label-collisions"]) > 0);
10610
+ diagnostics.push({
10611
+ code: "layout.connector_congestion",
10612
+ severity: "warning",
10613
+ theme,
10614
+ message: `${labelCollisions} connector label collision${labelCollisions === 1 ? "" : "s"} detected.`,
10615
+ suggestion: "Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",
10616
+ elementId: source ? elementId(source.props) : void 0,
10617
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
10618
+ });
10619
+ }
10620
+ const crowdedEndpoints = maxDataNumber("data-vizmatic-crowded-connector-endpoints");
10621
+ if (crowdedEndpoints > 0) {
10622
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-crowded-connector-endpoints"]) > 0);
10623
+ diagnostics.push({
10624
+ code: "layout.connector_congestion",
10625
+ severity: "warning",
10626
+ theme,
10627
+ message: `${crowdedEndpoints} node${crowdedEndpoints === 1 ? "" : "s"} connect more than four edges.`,
10628
+ suggestion: "Group related branches, add an intermediate hub, or change graph direction.",
10629
+ elementId: source ? elementId(source.props) : void 0,
10630
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
10631
+ });
10632
+ }
10633
+ const parallelGroups = maxDataNumber("data-vizmatic-parallel-connector-groups");
10634
+ if (parallelGroups > 0) {
10635
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-parallel-connector-groups"]) > 0);
10636
+ diagnostics.push({
10637
+ code: "layout.connector_congestion",
10638
+ severity: "warning",
10639
+ theme,
10640
+ message: `${parallelGroups} connector route${parallelGroups === 1 ? "" : "s"} contain parallel edges.`,
10641
+ suggestion: "Merge duplicate relationships, label one combined edge, or separate the routes.",
10642
+ elementId: source ? elementId(source.props) : void 0,
10643
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
10644
+ });
10645
+ }
10646
+ let whitespaceCount = 0;
10647
+ for (const container of nodes.filter((node) => node.props["data-vizmatic-layout-container"] === "panel")) {
10648
+ const contentNodes = nodes.filter(
10649
+ (node) => node.props["data-vizmatic-layout-content"] === "panel" && node.width > 0 && node.height > 0 && node.left >= container.left && node.top >= container.top && node.left + node.width <= container.left + container.width && node.top + node.height <= container.top + container.height
10650
+ );
10651
+ if (contentNodes.length === 0) continue;
10652
+ const contentTop = Math.min(...contentNodes.map((node) => node.top));
10653
+ const contentBottom = Math.max(...contentNodes.map((node) => node.top + node.height));
10654
+ const topGutter = contentTop - container.top;
10655
+ const bottomGutter = container.top + container.height - contentBottom;
10656
+ const difference = Math.abs(bottomGutter - topGutter);
10657
+ if (difference <= 48 || difference / container.height <= 0.18) continue;
10658
+ const largerSide = bottomGutter > topGutter ? "below" : "above";
10659
+ const smallerSide = largerSide === "below" ? "above" : "below";
10660
+ diagnostics.push({
10661
+ code: "layout.whitespace_imbalance",
10662
+ severity: "warning",
10663
+ theme,
10664
+ message: `Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,
10665
+ suggestion: "Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",
10666
+ elementId: elementId(container.props),
10667
+ location: { x: container.left, y: container.top, width: container.width, height: container.height }
10668
+ });
10669
+ whitespaceCount += 1;
10670
+ if (whitespaceCount >= MAX_DIAGNOSTICS_PER_RULE) break;
10671
+ }
10672
+ return diagnostics;
10673
+ }
10674
+ function analyzeWhitespaceBalance(bounds, width, height, theme) {
10675
+ const gutters = {
10676
+ left: bounds.x,
10677
+ right: width - bounds.x - bounds.width,
10678
+ top: bounds.y,
10679
+ bottom: height - bounds.y - bounds.height
10680
+ };
10681
+ const diagnostics = [];
10682
+ const horizontalDifference = Math.abs(gutters.left - gutters.right);
10683
+ const verticalDifference = Math.abs(gutters.top - gutters.bottom);
10684
+ if (horizontalDifference > 48 && horizontalDifference / width > 0.12) {
10685
+ diagnostics.push({
10686
+ code: "layout.whitespace_imbalance",
10687
+ severity: "warning",
10688
+ theme,
10689
+ message: `Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,
10690
+ suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
10691
+ location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
10692
+ });
10693
+ }
10694
+ if (verticalDifference > 48 && verticalDifference / height > 0.12) {
10695
+ diagnostics.push({
10696
+ code: "layout.whitespace_imbalance",
10697
+ severity: "warning",
10698
+ theme,
10699
+ message: `Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,
10700
+ suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
10701
+ location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
10702
+ });
10703
+ }
10704
+ return diagnostics;
10705
+ }
10706
+ function diagnosticFromMessage(message, severity, theme) {
10707
+ if (/unknown preset/i.test(message)) {
10708
+ return {
10709
+ code: "frame.unknown_preset",
10710
+ severity,
10711
+ theme,
10712
+ message,
10713
+ suggestion: 'Use "default" or "engineering".'
10714
+ };
10715
+ }
10716
+ if (/unsupported prop|unknown prop|does not recognize (?:the )?.* prop/i.test(message)) {
10717
+ return {
10718
+ code: "api.unsupported_prop",
10719
+ severity,
10720
+ theme,
10721
+ message,
10722
+ suggestion: "Remove the prop or use one documented for this Vizmatic primitive."
10723
+ };
10724
+ }
10725
+ if (/invalid value for css property|unsupported (?:css|style)|not supported.*css/i.test(message)) {
10726
+ return {
10727
+ code: "style.unsupported",
10728
+ severity,
10729
+ theme,
10730
+ message,
10731
+ suggestion: "Use CSS supported by Satori or a Vizmatic primitive."
10732
+ };
10733
+ }
10734
+ if (/font|emoji|image asset|failed to (?:download|fetch)|asset .*not found/i.test(message)) {
10735
+ return {
10736
+ code: "asset.warning",
10737
+ severity,
10738
+ theme,
10739
+ message,
10740
+ suggestion: "Use a reachable asset or install it locally before rendering offline."
10741
+ };
10742
+ }
10743
+ return {
10744
+ code: severity === "error" ? "render.error" : "render.warning",
10745
+ severity,
10746
+ theme,
10747
+ message
10748
+ };
10749
+ }
10750
+
10751
+ // src/check.ts
10752
+ var DEFAULT_WIDTH = 960;
10753
+ var DEFAULT_HEIGHT = 540;
10754
+ var MAX_WIDTH = 1920;
10755
+ var MAX_HEIGHT = 1440;
10756
+ var GROWTH = 1.25;
10757
+ var MAX_AUTO_SIZE_ATTEMPTS = 6;
10758
+ var TRUSTED_COMPONENTS = new Set(Object.values(primitives_exports));
10759
+ var consoleCaptureContext = new AsyncLocalStorage2();
10760
+ var activeConsoleCaptures = 0;
10761
+ var originalConsoleMethods;
10762
+ function formatConsoleArgs(args) {
10763
+ return args.map((value) => {
10764
+ if (value instanceof Error) return value.message;
10765
+ if (typeof value === "string") return value;
10766
+ try {
10767
+ return JSON.stringify(value);
10768
+ } catch {
10769
+ return String(value);
10770
+ }
10771
+ }).join(" ");
10772
+ }
10773
+ function installConsoleCapture() {
10774
+ if (activeConsoleCaptures === 0) {
10775
+ originalConsoleMethods = {
10776
+ debug: console.debug,
10777
+ error: console.error,
10778
+ info: console.info,
10779
+ log: console.log,
10780
+ warn: console.warn
10781
+ };
10782
+ const original = originalConsoleMethods;
10783
+ const intercept = (method, severity) => (...args) => {
10784
+ const messages = consoleCaptureContext.getStore();
10785
+ if (messages) {
10786
+ if (severity) messages.push({ severity, message: formatConsoleArgs(args) });
10787
+ return;
10788
+ }
10789
+ Reflect.apply(original[method], console, args);
10790
+ };
10791
+ console.debug = intercept("debug");
10792
+ console.error = intercept("error", "error");
10793
+ console.info = intercept("info");
10794
+ console.log = intercept("log");
10795
+ console.warn = intercept("warn", "warning");
10796
+ }
10797
+ activeConsoleCaptures += 1;
10798
+ let restored = false;
10799
+ return () => {
10800
+ if (restored) return;
10801
+ restored = true;
10802
+ activeConsoleCaptures -= 1;
10803
+ if (activeConsoleCaptures === 0 && originalConsoleMethods) {
10804
+ console.debug = originalConsoleMethods.debug;
10805
+ console.error = originalConsoleMethods.error;
10806
+ console.info = originalConsoleMethods.info;
10807
+ console.log = originalConsoleMethods.log;
10808
+ console.warn = originalConsoleMethods.warn;
10809
+ originalConsoleMethods = void 0;
10810
+ }
10811
+ };
10812
+ }
10813
+ async function captureConsole(run) {
10814
+ const messages = [];
10815
+ const uninstall = installConsoleCapture();
10816
+ try {
10817
+ const value = await consoleCaptureContext.run(messages, run);
10818
+ return { value, messages };
10819
+ } catch (error) {
10820
+ return { error, messages };
10821
+ } finally {
10822
+ uninstall();
10823
+ }
10824
+ }
10825
+ function normalizeAutoSize(value, defaults) {
10826
+ if (value === true) return { width: true, height: true };
10827
+ if (value === false) return { width: false, height: false };
10828
+ if (value) return { width: value.width ?? defaults.width, height: value.height ?? defaults.height };
10829
+ return defaults;
10830
+ }
10831
+ function overflowEdges(error) {
10832
+ if (!(error instanceof CanvasOverflowError)) return void 0;
10833
+ return Object.entries(error.overflow.edges).filter(([, overflows]) => overflows).map(([edge]) => edge);
10834
+ }
10835
+ function nextDimension(value, maximum) {
10836
+ return Math.min(maximum, Math.ceil(value * GROWTH / 10) * 10);
10837
+ }
10838
+ function nextAutoSize(width, height, autoSize, edges) {
10839
+ const growWidth = autoSize.width && (edges.includes("left") || edges.includes("right"));
10840
+ const growHeight = autoSize.height && (edges.includes("top") || edges.includes("bottom"));
10841
+ const nextWidth = growWidth ? nextDimension(width, MAX_WIDTH) : width;
10842
+ const nextHeight = growHeight ? nextDimension(height, MAX_HEIGHT) : height;
10843
+ if (nextWidth === width && nextHeight === height) return void 0;
10844
+ return { width: nextWidth, height: nextHeight };
10845
+ }
10846
+ async function renderFrame(create, theme, options) {
10847
+ let width = options.width;
10848
+ let height = options.height;
10849
+ for (let attempt = 0; attempt < MAX_AUTO_SIZE_ATTEMPTS; attempt += 1) {
10850
+ try {
10851
+ const layoutNodes = [];
10852
+ const output = await renderToPngWithOutput(create(theme), {
10853
+ width,
10854
+ height,
10855
+ outputPath: options.outputPath,
10856
+ crop: true,
10857
+ scale: 1,
10858
+ background: options.background,
10859
+ onNodeDetected: (node) => layoutNodes.push(node)
10860
+ }, create, theme);
10861
+ return {
10862
+ width,
10863
+ height,
10864
+ outputWidth: output.pixelWidth,
10865
+ outputHeight: output.pixelHeight,
10866
+ logicalOutputWidth: output.width,
10867
+ logicalOutputHeight: output.height,
10868
+ contentBounds: output.contentBounds,
10869
+ layoutNodes
10870
+ };
10871
+ } catch (error) {
10872
+ const edges = overflowEdges(error);
10873
+ const next = edges ? nextAutoSize(width, height, options.autoSize, edges) : void 0;
10874
+ if (!next || attempt === MAX_AUTO_SIZE_ATTEMPTS - 1) throw error;
10875
+ width = next.width;
10876
+ height = next.height;
10877
+ }
10878
+ }
10879
+ return {
10880
+ width,
10881
+ height,
10882
+ outputWidth: width,
10883
+ outputHeight: height,
10884
+ logicalOutputWidth: width,
10885
+ logicalOutputHeight: height,
10886
+ layoutNodes: []
10887
+ };
10888
+ }
10889
+ function counts(themes) {
10890
+ const diagnostics = themes.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
10891
+ return {
10892
+ errors: diagnostics.filter(({ severity }) => severity === "error").length,
10893
+ warnings: diagnostics.filter(({ severity }) => severity === "warning").length,
10894
+ info: diagnostics.filter(({ severity }) => severity === "info").length
10895
+ };
10896
+ }
10897
+ function fails(diagnostics, policy) {
10898
+ if (policy === "never") return false;
10899
+ const threshold = { error: 0, warning: 1, info: 2 }[policy];
10900
+ const levels = { error: 0, warning: 1, info: 2 };
10901
+ return diagnostics.some(({ severity }) => levels[severity] <= threshold);
10902
+ }
10903
+ function messageDiagnostics(messages, theme) {
10904
+ return messages.map(({ message, severity }) => diagnosticFromMessage(message, severity, theme));
10905
+ }
10906
+ function rootBackground(background, theme) {
10907
+ if (background === "theme") return getThemeColors(theme).bg;
10908
+ if (background === "transparent" || background === void 0) return void 0;
10909
+ return background;
10910
+ }
10911
+ async function checkFrame(input, options = {}) {
10912
+ const themes = options.themes ?? ["dark", "light"];
10913
+ if (themes.length === 0) throw new TypeError("checkFrame requires at least one theme");
10914
+ const width = input.width ?? DEFAULT_WIDTH;
10915
+ const height = input.height ?? DEFAULT_HEIGHT;
10916
+ if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
10917
+ throw new TypeError("checkFrame width and height must be positive finite numbers");
10918
+ }
10919
+ const autoSize = normalizeAutoSize(input.autoSize, {
10920
+ width: input.width == null,
10921
+ height: input.height == null
10922
+ });
10923
+ const create = input.create ?? (() => input.scene);
10924
+ const failOn = options.failOn ?? "error";
10925
+ const tempDir = await mkdtemp(join2(tmpdir(), "vizmatic-check-"));
10926
+ const reports = [];
10927
+ try {
10928
+ for (const [themeIndex, theme] of themes.entries()) {
10929
+ const inputDimensions = { width, height };
10930
+ const diagnostics2 = [];
10931
+ const prepared = await captureConsole(async () => {
10932
+ const element = create(theme);
10933
+ const background = rootBackground(options.background, theme);
10934
+ return analyzeContrast(element, theme, TRUSTED_COMPONENTS, background);
10935
+ });
10936
+ diagnostics2.push(...messageDiagnostics(prepared.messages, theme));
10937
+ if (!prepared.value) {
10938
+ diagnostics2.push(diagnosticFromMessage(
10939
+ prepared.error instanceof Error ? prepared.error.message : String(prepared.error),
10940
+ "error",
10941
+ theme
10942
+ ));
10943
+ reports.push({
10944
+ theme,
10945
+ ok: !fails(diagnostics2, failOn),
10946
+ dimensions: { input: inputDimensions },
10947
+ diagnostics: diagnostics2
10948
+ });
10949
+ continue;
10950
+ }
10951
+ diagnostics2.push(...prepared.value);
10952
+ const rendered = await captureConsole(() => renderFrame(create, theme, {
10953
+ width,
10954
+ height,
10955
+ autoSize,
10956
+ background: options.background,
10957
+ outputPath: join2(tempDir, `${themeIndex}.png`)
10958
+ }));
10959
+ diagnostics2.push(...messageDiagnostics(rendered.messages, theme));
10960
+ if (rendered.value) {
10961
+ diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes, theme));
10962
+ if (rendered.value.contentBounds) {
10963
+ diagnostics2.push(...analyzeWhitespaceBalance(
10964
+ rendered.value.contentBounds,
10965
+ rendered.value.logicalOutputWidth,
10966
+ rendered.value.logicalOutputHeight,
10967
+ theme
10968
+ ));
10969
+ }
10970
+ if (rendered.value.width !== width || rendered.value.height !== height) {
10971
+ diagnostics2.push({
10972
+ code: "layout.auto_size",
10973
+ severity: "info",
10974
+ theme,
10975
+ message: `Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,
10976
+ suggestedDimensions: { width: rendered.value.width, height: rendered.value.height }
10977
+ });
10978
+ }
10979
+ reports.push({
10980
+ theme,
10981
+ ok: !fails(diagnostics2, failOn),
10982
+ dimensions: {
10983
+ input: inputDimensions,
10984
+ resolved: { width: rendered.value.width, height: rendered.value.height },
10985
+ output: { width: rendered.value.outputWidth, height: rendered.value.outputHeight }
10986
+ },
10987
+ diagnostics: diagnostics2
10988
+ });
10989
+ continue;
10990
+ }
10991
+ const edges = overflowEdges(rendered.error);
10992
+ if (edges) {
10993
+ const suggestion = await captureConsole(() => renderFrame(create, theme, {
10994
+ width,
10995
+ height,
10996
+ autoSize: { width: true, height: true },
10997
+ background: options.background,
10998
+ outputPath: join2(tempDir, `${themeIndex}-suggestion.png`)
10999
+ }));
11000
+ const suggestedDimensions = suggestion.value ? { width: suggestion.value.width, height: suggestion.value.height } : void 0;
11001
+ diagnostics2.push({
11002
+ code: "layout.overflow",
11003
+ severity: "error",
11004
+ theme,
11005
+ edges,
11006
+ message: rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11007
+ suggestion: suggestedDimensions ? `Increase the canvas to at least ${suggestedDimensions.width}\xD7${suggestedDimensions.height}, or remove fixed dimensions to enable auto-sizing.` : "Increase the canvas dimensions or remove fixed dimensions to enable auto-sizing.",
11008
+ suggestedDimensions
11009
+ });
11010
+ } else {
11011
+ diagnostics2.push(diagnosticFromMessage(
11012
+ rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11013
+ "error",
11014
+ theme
11015
+ ));
11016
+ }
11017
+ reports.push({
11018
+ theme,
11019
+ ok: !fails(diagnostics2, failOn),
11020
+ dimensions: { input: inputDimensions },
11021
+ diagnostics: diagnostics2
11022
+ });
11023
+ }
11024
+ } finally {
11025
+ await rm(tempDir, { recursive: true, force: true });
11026
+ }
11027
+ const summary = counts(reports);
11028
+ const diagnostics = reports.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
11029
+ return {
11030
+ schemaVersion: 1,
11031
+ source: input.source,
11032
+ ok: !fails(diagnostics, failOn),
11033
+ rendered: reports.every(({ dimensions }) => dimensions.resolved !== void 0),
11034
+ autoSize,
11035
+ themes: reports,
11036
+ summary
11037
+ };
11038
+ }
9334
11039
  export {
9335
11040
  Arrow,
9336
11041
  ArrowMarkerDef,
@@ -9339,6 +11044,7 @@ export {
9339
11044
  BadgePill,
9340
11045
  BarChart,
9341
11046
  Box,
11047
+ CHECK_DIAGNOSTIC_CODES,
9342
11048
  CalloutCard,
9343
11049
  Canvas,
9344
11050
  CanvasOverflowError,
@@ -9406,6 +11112,7 @@ export {
9406
11112
  WindowFrame,
9407
11113
  analyzeAnimationCadence,
9408
11114
  canvas,
11115
+ checkFrame,
9409
11116
  colors,
9410
11117
  createPlotArea,
9411
11118
  cropPixels,
@@ -9432,6 +11139,8 @@ export {
9432
11139
  gradients,
9433
11140
  heatColor,
9434
11141
  hold,
11142
+ importD2Graph,
11143
+ importMermaidGraph,
9435
11144
  keyframe,
9436
11145
  loadAdditionalAsset,
9437
11146
  normalizeWatermark,