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/cli.js CHANGED
@@ -7,13 +7,13 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/cli.ts
9
9
  import { existsSync as existsSync2 } from "fs";
10
- import { mkdir as mkdir3, mkdtemp, readFile as readFile2, readdir, rm, writeFile as writeFile3 } from "fs/promises";
10
+ import { mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile2, readdir, rm as rm2, writeFile as writeFile3 } from "fs/promises";
11
11
  import { randomUUID } from "crypto";
12
12
  import { createRequire, Module } from "module";
13
- import { tmpdir } from "os";
14
- import { basename, dirname as dirname3, extname, isAbsolute, join as join2, relative, resolve, sep } from "path";
13
+ import { tmpdir as tmpdir2 } from "os";
14
+ import { basename, dirname as dirname3, extname, isAbsolute, join as join3, relative, resolve, sep } from "path";
15
15
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "url";
16
- import React13, { isValidElement as isValidElement2 } from "react";
16
+ import React13, { isValidElement as isValidElement3 } from "react";
17
17
 
18
18
  // src/index.ts
19
19
  var index_exports = {};
@@ -25,6 +25,7 @@ __export(index_exports, {
25
25
  BadgePill: () => BadgePill,
26
26
  BarChart: () => BarChart,
27
27
  Box: () => Box,
28
+ CHECK_DIAGNOSTIC_CODES: () => CHECK_DIAGNOSTIC_CODES,
28
29
  CalloutCard: () => CalloutCard,
29
30
  Canvas: () => Canvas,
30
31
  CanvasOverflowError: () => CanvasOverflowError,
@@ -92,6 +93,7 @@ __export(index_exports, {
92
93
  WindowFrame: () => WindowFrame,
93
94
  analyzeAnimationCadence: () => analyzeAnimationCadence,
94
95
  canvas: () => canvas,
96
+ checkFrame: () => checkFrame,
95
97
  colors: () => colors,
96
98
  createPlotArea: () => createPlotArea,
97
99
  cropPixels: () => cropPixels,
@@ -118,6 +120,8 @@ __export(index_exports, {
118
120
  gradients: () => gradients,
119
121
  heatColor: () => heatColor,
120
122
  hold: () => hold,
123
+ importD2Graph: () => importD2Graph,
124
+ importMermaidGraph: () => importMermaidGraph,
121
125
  keyframe: () => keyframe,
122
126
  loadAdditionalAsset: () => loadAdditionalAsset,
123
127
  normalizeWatermark: () => normalizeWatermark,
@@ -340,7 +344,7 @@ function getToneColor(tone, c) {
340
344
  dark: c.textSecondary
341
345
  }[tone];
342
346
  }
343
- function getReadableToneColor(tone, c, background = c.bgCard) {
347
+ function getReadableToneColor(tone, c, background = c.bgCard, backdrop = c.bgCard) {
344
348
  const semanticColor = {
345
349
  blue: "secondary",
346
350
  purple: "primary",
@@ -356,7 +360,7 @@ function getReadableToneColor(tone, c, background = c.bgCard) {
356
360
  dark: "neutral"
357
361
  };
358
362
  const color = getReadableColor(semanticColor[tone], c);
359
- return colorContrast(color, background, c.bgCard) >= 4.5 ? color : getReadableTextColor(background, c);
363
+ return colorContrast(color, background, backdrop) >= 4.5 ? color : getReadableTextColor(background, c, backdrop);
360
364
  }
361
365
  function getToneFill(tone, c) {
362
366
  if (c.preset !== "engineering") return `${getToneColor(tone, c)}16`;
@@ -519,12 +523,12 @@ function colorContrast(left, right, rightBackdrop) {
519
523
  if (leftLuminance == null || rightLuminance == null) return 0;
520
524
  return (Math.max(leftLuminance, rightLuminance) + 0.05) / (Math.min(leftLuminance, rightLuminance) + 0.05);
521
525
  }
522
- function getReadableTextColor(background, c) {
523
- if (colorLuminance(background, c.bgCard) == null) return c.textPrimary;
526
+ function getReadableTextColor(background, c, backdrop = c.bgCard) {
527
+ if (colorLuminance(background, backdrop) == null) return c.textPrimary;
524
528
  const candidates = [c.textPrimary, c.textOnColor, c.bg, "#000000"];
525
- const readable = candidates.find((candidate) => colorContrast(candidate, background, c.bgCard) >= 4.5);
529
+ const readable = candidates.find((candidate) => colorContrast(candidate, background, backdrop) >= 4.5);
526
530
  if (readable) return readable;
527
- return candidates.reduce((best, candidate) => colorContrast(candidate, background, c.bgCard) > colorContrast(best, background, c.bgCard) ? candidate : best);
531
+ return candidates.reduce((best, candidate) => colorContrast(candidate, background, backdrop) > colorContrast(best, background, backdrop) ? candidate : best);
528
532
  }
529
533
  function getGradient(name) {
530
534
  const map = {
@@ -566,6 +570,89 @@ function lerpColor(a, b, t) {
566
570
  return `#${(rr << 16 | rg << 8 | rb).toString(16).padStart(6, "0")}`;
567
571
  }
568
572
 
573
+ // src/primitives.ts
574
+ var primitives_exports = {};
575
+ __export(primitives_exports, {
576
+ Arrow: () => Arrow,
577
+ ArrowMarkerDef: () => ArrowMarkerDef,
578
+ AxisPlot: () => AxisPlot,
579
+ Badge: () => Badge,
580
+ BadgePill: () => BadgePill,
581
+ BarChart: () => BarChart,
582
+ Box: () => Box,
583
+ CalloutCard: () => CalloutCard,
584
+ Canvas: () => Canvas,
585
+ Card: () => Card,
586
+ ChartFrame: () => ChartFrame,
587
+ CodeBlock: () => CodeBlock,
588
+ Column: () => Column,
589
+ Comparison: () => Comparison,
590
+ Connector: () => Connector,
591
+ DashedLine: () => DashedLine,
592
+ DataTable: () => DataTable,
593
+ DataflowDiagram: () => DataflowDiagram,
594
+ DeploymentDiagram: () => DeploymentDiagram,
595
+ DetailList: () => DetailList,
596
+ DonutChart: () => DonutChart,
597
+ DotPoint: () => DotPoint,
598
+ EquationCard: () => EquationCard,
599
+ Flow: () => Flow,
600
+ FlowArrow: () => FlowArrow,
601
+ GradientChip: () => GradientChip,
602
+ GraphDiagram: () => GraphDiagram,
603
+ Grid: () => Grid,
604
+ Heatmap: () => Heatmap,
605
+ Icon: () => Icon,
606
+ IntervalPlot: () => IntervalPlot,
607
+ KeyValueList: () => KeyValueList,
608
+ LayeredNetwork: () => LayeredNetwork,
609
+ Legend: () => Legend,
610
+ LineChart: () => LineChart,
611
+ MathText: () => MathText,
612
+ Matrix: () => Matrix,
613
+ MetricCard: () => MetricCard,
614
+ MiniBarChart: () => MiniBarChart,
615
+ Panel: () => Panel,
616
+ ParetoChart: () => ParetoChart,
617
+ Pipeline: () => Pipeline,
618
+ ProgressList: () => ProgressList,
619
+ ProgressRow: () => ProgressRow,
620
+ QuadrantChart: () => QuadrantChart,
621
+ Row: () => Row,
622
+ ScatterPlot: () => ScatterPlot,
623
+ Scene: () => Scene,
624
+ SequenceDiagram: () => SequenceDiagram,
625
+ Stack: () => Stack,
626
+ StackedBar: () => StackedBar,
627
+ StatusList: () => StatusList,
628
+ StatusRow: () => StatusRow,
629
+ StepCard: () => StepCard,
630
+ SvgFrame: () => SvgFrame,
631
+ SvgMathText: () => SvgMathText,
632
+ SvgPoint: () => SvgPoint,
633
+ TextLabel: () => TextLabel,
634
+ Tile: () => Tile,
635
+ TileGrid: () => TileGrid,
636
+ TiledMatrix: () => TiledMatrix,
637
+ Timeline: () => Timeline,
638
+ TitleBar: () => TitleBar,
639
+ ToneStrip: () => ToneStrip,
640
+ TransformerTopology: () => TransformerTopology,
641
+ TreeDiagram: () => TreeDiagram,
642
+ ValuePill: () => ValuePill,
643
+ VectorArrow: () => VectorArrow,
644
+ VectorSegment: () => VectorSegment,
645
+ WindowFrame: () => WindowFrame,
646
+ createPlotArea: () => createPlotArea,
647
+ defineDiagramIcon: () => defineDiagramIcon,
648
+ defineIconRegistry: () => defineIconRegistry,
649
+ defineIllustration: () => defineIllustration,
650
+ formatMathText: () => formatMathText,
651
+ formatTensorShape: () => formatTensorShape,
652
+ getToneColor: () => getToneColor,
653
+ getToneGradient: () => getToneGradient
654
+ });
655
+
569
656
  // src/primitives/layout.ts
570
657
  import React from "react";
571
658
 
@@ -2252,6 +2339,7 @@ function MiniBarChart({
2252
2339
  ...compactChildren([
2253
2340
  showValues && React4.createElement("div", {
2254
2341
  style: {
2342
+ display: "flex",
2255
2343
  color: getReadableToneColor(tone, c),
2256
2344
  fontFamily: "JetBrains Mono",
2257
2345
  fontSize,
@@ -2271,6 +2359,7 @@ function MiniBarChart({
2271
2359
  }),
2272
2360
  React4.createElement("div", {
2273
2361
  style: {
2362
+ display: "flex",
2274
2363
  color: c.textMuted,
2275
2364
  fontFamily: "JetBrains Mono",
2276
2365
  fontSize,
@@ -2917,7 +3006,11 @@ function StatusRow({
2917
3006
  }) {
2918
3007
  const resolvedTone = tone ?? statusTones[status];
2919
3008
  const accent = getToneColor(resolvedTone, c);
2920
- const accentText = getReadableToneColor(resolvedTone, c);
3009
+ const markerAlpha = 38 / 255;
3010
+ const rowAlpha = boxed ? 18 / 255 : 0;
3011
+ const markerBackgroundAlpha = Math.round((rowAlpha + markerAlpha * (1 - rowAlpha)) * 255);
3012
+ const markerBackground = `${accent}${markerBackgroundAlpha.toString(16).padStart(2, "0")}`;
3013
+ const accentText = getReadableToneColor(resolvedTone, c, markerBackground, c.bgCard);
2921
3014
  const glyph = statusGlyphs[status];
2922
3015
  const marker = React5.createElement("div", {
2923
3016
  style: {
@@ -3339,6 +3432,200 @@ function Flow({
3339
3432
  // src/primitives/diagrams.ts
3340
3433
  import React6 from "react";
3341
3434
  import dagre from "@dagrejs/dagre";
3435
+
3436
+ // src/svg-accessibility.ts
3437
+ import { cloneElement, isValidElement } from "react";
3438
+ var SVG_ACCESSIBILITY_COMPONENT = /* @__PURE__ */ Symbol.for("vizmatic.svgAccessibilityComponent");
3439
+ function componentHasSvgMetadata(type) {
3440
+ return typeof type === "function" && type[SVG_ACCESSIBILITY_COMPONENT] === true;
3441
+ }
3442
+ function svgToken(value) {
3443
+ if (value.length === 0) return "empty";
3444
+ return Array.from(value, (character) => {
3445
+ const codePoint = character.codePointAt(0) ?? 0;
3446
+ return /^[A-Za-z0-9.-]$/.test(character) ? character : `_u${codePoint.toString(16)}_`;
3447
+ }).join("");
3448
+ }
3449
+ function textProperty(props, name) {
3450
+ const value = props[name];
3451
+ return typeof value === "string" ? value : "";
3452
+ }
3453
+ function encodedTextProperty(props, name) {
3454
+ const value = textProperty(props, name);
3455
+ try {
3456
+ return decodeURIComponent(value);
3457
+ } catch {
3458
+ return value;
3459
+ }
3460
+ }
3461
+ function prepareAccessibleSvg(element) {
3462
+ const graphs = [];
3463
+ const explicitIds = /* @__PURE__ */ new Set();
3464
+ const visit = (node, graph) => {
3465
+ if (Array.isArray(node)) return node.map((child) => visit(child, graph));
3466
+ if (!isValidElement(node)) return node;
3467
+ const component = node.type;
3468
+ if (componentHasSvgMetadata(component)) {
3469
+ return visit(component(node.props), graph);
3470
+ }
3471
+ const props = node.props;
3472
+ const title = textProperty(props, "data-vizmatic-svg-title");
3473
+ const isGraphRoot = title.length > 0;
3474
+ let activeGraph = graph;
3475
+ let elementKey = node.key;
3476
+ if (isGraphRoot) {
3477
+ const explicitId = textProperty(props, "data-vizmatic-svg-id");
3478
+ if (explicitId) {
3479
+ if (explicitIds.has(explicitId)) {
3480
+ throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`);
3481
+ }
3482
+ explicitIds.add(explicitId);
3483
+ }
3484
+ const index = graphs.length;
3485
+ const token = explicitId ? `id-${svgToken(explicitId)}` : `index-${index}`;
3486
+ activeGraph = {
3487
+ index,
3488
+ token,
3489
+ detectionKey: `vizmatic-graph-${index}`,
3490
+ title,
3491
+ description: textProperty(props, "data-vizmatic-svg-description"),
3492
+ nodes: [],
3493
+ edges: []
3494
+ };
3495
+ graphs.push(activeGraph);
3496
+ elementKey = activeGraph.detectionKey;
3497
+ }
3498
+ let nextProps;
3499
+ if (activeGraph && Object.hasOwn(props, "data-vizmatic-graph-node-id")) {
3500
+ const id = textProperty(props, "data-vizmatic-graph-node-id");
3501
+ const label = textProperty(props, "data-vizmatic-graph-node-label") || id;
3502
+ const detail = textProperty(props, "data-vizmatic-graph-node-detail");
3503
+ activeGraph.nodes.push({
3504
+ id,
3505
+ label,
3506
+ detail,
3507
+ title: textProperty(props, "data-vizmatic-graph-node-title") || label,
3508
+ href: textProperty(props, "data-vizmatic-graph-node-href") || void 0
3509
+ });
3510
+ elementKey = `${activeGraph.detectionKey}-node-${svgToken(id)}`;
3511
+ } else if (activeGraph && textProperty(props, "data-vizmatic-graph-edge-id")) {
3512
+ const id = encodedTextProperty(props, "data-vizmatic-graph-edge-id");
3513
+ activeGraph.edges.push({
3514
+ id,
3515
+ from: encodedTextProperty(props, "data-vizmatic-graph-edge-from"),
3516
+ to: encodedTextProperty(props, "data-vizmatic-graph-edge-to"),
3517
+ label: encodedTextProperty(props, "data-vizmatic-graph-edge-label"),
3518
+ title: encodedTextProperty(props, "data-vizmatic-graph-edge-title"),
3519
+ path: textProperty(props, "d"),
3520
+ href: encodedTextProperty(props, "data-vizmatic-graph-edge-href") || void 0
3521
+ });
3522
+ elementKey = `${activeGraph.detectionKey}-edge-${svgToken(id)}`;
3523
+ }
3524
+ const children = props.children;
3525
+ if (children === void 0) {
3526
+ if (isGraphRoot) {
3527
+ nextProps = { ...props, "data-vizmatic-svg-instance": activeGraph?.token };
3528
+ return cloneElement(node, { ...nextProps, key: elementKey });
3529
+ }
3530
+ return node;
3531
+ }
3532
+ const preparedChildren = visit(children, activeGraph);
3533
+ nextProps = isGraphRoot ? { ...props, "data-vizmatic-svg-instance": activeGraph?.token } : { ...props };
3534
+ return cloneElement(
3535
+ node,
3536
+ { ...nextProps, key: elementKey },
3537
+ preparedChildren
3538
+ );
3539
+ };
3540
+ return { element: visit(element), graphs };
3541
+ }
3542
+ function escapeXml(value) {
3543
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3544
+ }
3545
+ function attribute(name, value) {
3546
+ return `${name}="${escapeXml(value)}"`;
3547
+ }
3548
+ function graphBaseId(graph) {
3549
+ return `vizmatic-graph-${graph.token}`;
3550
+ }
3551
+ function nodeId(graph, node) {
3552
+ return `${graphBaseId(graph)}-node-${svgToken(node.id)}`;
3553
+ }
3554
+ function edgeId(graph, edge) {
3555
+ return `${graphBaseId(graph)}-edge-${svgToken(edge.id)}`;
3556
+ }
3557
+ function labelForEdge(graph, edge) {
3558
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
3559
+ const from = nodes.get(edge.from) ?? edge.from;
3560
+ const to = nodes.get(edge.to) ?? edge.to;
3561
+ return edge.title || (edge.label ? `${from} to ${to}: ${edge.label}` : `${from} to ${to}`);
3562
+ }
3563
+ function descriptionForEdge(graph, edge) {
3564
+ const nodes = new Map(graph.nodes.map((node) => [node.id, node.label]));
3565
+ const from = nodes.get(edge.from) ?? edge.from;
3566
+ const to = nodes.get(edge.to) ?? edge.to;
3567
+ return `Relationship from ${from} to ${to}${edge.label ? `, labeled ${edge.label}` : ""}.`;
3568
+ }
3569
+ function nodeGroup(graph, node, layout) {
3570
+ const id = nodeId(graph, node);
3571
+ const label = node.detail ? `${node.label}: ${node.detail}` : node.label;
3572
+ const description = node.detail || node.label;
3573
+ const titleId = `${id}-title`;
3574
+ const descriptionId = `${id}-description`;
3575
+ 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>`;
3576
+ if (!layout) return `${accessible}</g>`;
3577
+ const rect = `<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;
3578
+ const hitTarget = node.href ? `<a ${attribute("href", node.href)} role="link" tabindex="0" ${attribute("aria-label", label)}>${rect}</a>` : rect;
3579
+ return `${accessible}${hitTarget}</g>`;
3580
+ }
3581
+ function edgeGroup(graph, edge, root) {
3582
+ const id = edgeId(graph, edge);
3583
+ const title = labelForEdge(graph, edge);
3584
+ const titleId = `${id}-title`;
3585
+ const descriptionId = `${id}-description`;
3586
+ 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>`;
3587
+ if (!root || !edge.path) return `${accessible}</g>`;
3588
+ 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"/>`;
3589
+ const hitTarget = edge.href ? `<a ${attribute("href", edge.href)} role="link" tabindex="0" ${attribute("aria-label", title)}>${path}</a>` : path;
3590
+ return `${accessible}${hitTarget}</g>`;
3591
+ }
3592
+ function addSvgAccessibility(svg, graphs, layoutNodes) {
3593
+ if (graphs.length === 0) return svg;
3594
+ const title = graphs.map((graph) => graph.title).join(". ");
3595
+ const description = graphs.map((graph) => `${graph.title}. ${graph.description}`).join(" ");
3596
+ const hasLinks = graphs.some(
3597
+ (graph) => graph.nodes.some((node) => node.href) || graph.edges.some((edge) => edge.href)
3598
+ );
3599
+ const rootTitleId = "vizmatic-svg-title";
3600
+ const rootDescriptionId = "vizmatic-svg-description";
3601
+ const groupMarkup = graphs.map((graph) => {
3602
+ const baseId = graphBaseId(graph);
3603
+ const titleId = `${baseId}-title`;
3604
+ const descriptionId = `${baseId}-description`;
3605
+ const root = layoutNodes.find((node) => node.key === graph.detectionKey);
3606
+ const nodes = graph.nodes.map((item) => {
3607
+ const layout = layoutNodes.find((node) => node.key === `${graph.detectionKey}-node-${svgToken(item.id)}`);
3608
+ if (item.href && !layout) {
3609
+ throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`);
3610
+ }
3611
+ return nodeGroup(graph, item, layout);
3612
+ }).join("");
3613
+ const edges = graph.edges.map((item) => {
3614
+ if (item.href && !root) {
3615
+ throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`);
3616
+ }
3617
+ return edgeGroup(graph, item, root);
3618
+ }).join("");
3619
+ 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>`;
3620
+ }).join("");
3621
+ const metadata = `<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;
3622
+ return svg.replace(
3623
+ /^<svg\b([^>]*)>/,
3624
+ (_match, attrs) => `<svg${attrs} role="${hasLinks ? "group" : "img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`
3625
+ ).replace(/<\/svg>\s*$/, `${groupMarkup}</svg>`);
3626
+ }
3627
+
3628
+ // src/primitives/diagrams.ts
3342
3629
  function distributeValues(count, start, end) {
3343
3630
  if (count <= 0) return [];
3344
3631
  if (count === 1) return [(start + end) / 2];
@@ -3708,15 +3995,53 @@ function validateGraphDiagramSpec(nodes, edges, groups, layoutMode) {
3708
3995
  for (const group of groups) {
3709
3996
  if (!occupiedGroups.has(group.id)) throw new Error(`GraphDiagram group "${group.id}" contains no nodes.`);
3710
3997
  }
3998
+ const edgeIds = /* @__PURE__ */ new Set();
3711
3999
  for (const edge of edges) {
3712
4000
  if (!nodeIds.has(edge.from) || !nodeIds.has(edge.to)) {
3713
4001
  throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`);
3714
4002
  }
4003
+ if (edge.id != null) {
4004
+ if (edgeIds.has(edge.id)) throw new Error(`GraphDiagram received duplicate edge id "${edge.id}".`);
4005
+ edgeIds.add(edge.id);
4006
+ }
4007
+ validateDiagramHref(edge.href, `edge "${edge.id ?? `${edge.from}" -> "${edge.to}`}"`);
4008
+ }
4009
+ for (const node of nodes) {
4010
+ validateDiagramHref(node.href, `node "${node.id}"`);
3715
4011
  }
3716
4012
  if (groups.length > 0 && layoutMode === "manual") {
3717
4013
  throw new Error('GraphDiagram groups require automatic layout; omit node coordinates and layout="manual".');
3718
4014
  }
3719
4015
  }
4016
+ function validateDiagramHref(href, owner) {
4017
+ if (href == null) return;
4018
+ const normalized = href.trim().replace(/[\u0000-\u0020\u007f]/g, "");
4019
+ const scheme = /^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1]?.toLowerCase();
4020
+ if (scheme && !["http", "https", "mailto", "tel"].includes(scheme)) {
4021
+ throw new Error(`GraphDiagram ${owner} has an unsupported link scheme "${scheme}:".`);
4022
+ }
4023
+ }
4024
+ function graphAccessibleText(value) {
4025
+ if (typeof value === "string" || typeof value === "number") return String(value).trim();
4026
+ if (Array.isArray(value)) return value.map(graphAccessibleText).filter(Boolean).join(" ");
4027
+ if (React6.isValidElement(value)) {
4028
+ const props = value.props;
4029
+ return graphAccessibleText(props.children);
4030
+ }
4031
+ return "";
4032
+ }
4033
+ function graphDescription(nodes, edges) {
4034
+ const labels = new Map(nodes.map((node) => [node.id, graphAccessibleText(node.label) || node.id]));
4035
+ const parts = [`${nodes.length} nodes and ${edges.length} relationships.`];
4036
+ const relationships = edges.slice(0, 8).map((edge) => {
4037
+ const from = labels.get(edge.from) ?? edge.from;
4038
+ const to = labels.get(edge.to) ?? edge.to;
4039
+ return edge.label ? `${from} ${edge.label} ${to}` : `${from} to ${to}`;
4040
+ });
4041
+ if (relationships.length) parts.push(relationships.join("; "));
4042
+ if (edges.length > relationships.length) parts.push(`${edges.length - relationships.length} more relationships`);
4043
+ return parts.join(" ");
4044
+ }
3720
4045
  function graphGroupDepth(group, groupsById) {
3721
4046
  let depth = 0;
3722
4047
  let parent = group.parent;
@@ -3756,8 +4081,12 @@ function GraphDiagram({
3756
4081
  edgeGap = 14,
3757
4082
  sizing = "content",
3758
4083
  iconSize = 20,
3759
- ariaLabel
4084
+ id,
4085
+ ariaLabel,
4086
+ title,
4087
+ description
3760
4088
  }) {
4089
+ if (id != null && id.trim().length === 0) throw new Error("GraphDiagram id must not be empty.");
3761
4090
  const fullyPositioned = nodes.filter((node) => node.x != null && node.y != null).length;
3762
4091
  const partiallyPositioned = nodes.some((node) => node.x == null !== (node.y == null));
3763
4092
  if (partiallyPositioned || fullyPositioned > 0 && fullyPositioned < nodes.length) {
@@ -3768,6 +4097,19 @@ function GraphDiagram({
3768
4097
  throw new Error('GraphDiagram layout="manual" requires x and y on every node.');
3769
4098
  }
3770
4099
  validateGraphDiagramSpec(nodes, edges, groups, layoutMode);
4100
+ const edgeOccurrences = /* @__PURE__ */ new Map();
4101
+ const stableEdgeIds = edges.map((edge) => {
4102
+ if (edge.id != null) return `custom-${edge.id}`;
4103
+ const route = `${edge.from}\0${edge.to}`;
4104
+ const occurrence = edgeOccurrences.get(route) ?? 0;
4105
+ edgeOccurrences.set(route, occurrence + 1);
4106
+ return `route-${edge.from}-to-${edge.to}-${occurrence}`;
4107
+ });
4108
+ if (new Set(stableEdgeIds).size !== stableEdgeIds.length) {
4109
+ throw new Error("GraphDiagram edge ids must not collide with generated relationship ids.");
4110
+ }
4111
+ const svgTitle = title?.trim() || ariaLabel?.trim() || "Graph diagram";
4112
+ const svgDescription = description ?? graphDescription(nodes, edges);
3771
4113
  let resolvedWidth = width ?? 520;
3772
4114
  let resolvedHeight = height ?? 420;
3773
4115
  let layout;
@@ -3879,6 +4221,7 @@ function GraphDiagram({
3879
4221
  return [{
3880
4222
  ...edge,
3881
4223
  index,
4224
+ stableId: stableEdgeIds[index],
3882
4225
  color,
3883
4226
  markerId,
3884
4227
  points,
@@ -3945,8 +4288,12 @@ function GraphDiagram({
3945
4288
  return React6.createElement(
3946
4289
  "div",
3947
4290
  {
4291
+ key: "vizmatic-graph-root",
3948
4292
  role: "img",
3949
- "aria-label": ariaLabel ?? "Graph diagram",
4293
+ "aria-label": ariaLabel ?? svgTitle,
4294
+ "data-vizmatic-svg-title": svgTitle,
4295
+ "data-vizmatic-svg-description": svgDescription,
4296
+ "data-vizmatic-svg-id": id,
3950
4297
  "data-vizmatic-connector-crossings": crossings,
3951
4298
  "data-vizmatic-connector-label-collisions": labelCollisions,
3952
4299
  "data-vizmatic-crowded-connector-endpoints": crowdedEndpoints,
@@ -3980,6 +4327,12 @@ function GraphDiagram({
3980
4327
  ),
3981
4328
  ...edgeLayouts.map((edge) => React6.createElement("path", {
3982
4329
  key: `graph-edge-${edge.index}`,
4330
+ "data-vizmatic-graph-edge-id": encodeURIComponent(edge.stableId),
4331
+ "data-vizmatic-graph-edge-from": encodeURIComponent(edge.from),
4332
+ "data-vizmatic-graph-edge-to": encodeURIComponent(edge.to),
4333
+ "data-vizmatic-graph-edge-label": encodeURIComponent(edge.label ?? ""),
4334
+ "data-vizmatic-graph-edge-title": encodeURIComponent(edge.title ?? ""),
4335
+ "data-vizmatic-graph-edge-href": edge.href == null ? void 0 : encodeURIComponent(edge.href),
3983
4336
  d: edgePath(edge.points),
3984
4337
  fill: "none",
3985
4338
  stroke: edge.color,
@@ -4018,7 +4371,8 @@ function GraphDiagram({
4018
4371
  ] : []),
4019
4372
  ...Array.from(layout.values()).map((node) => {
4020
4373
  const accent = node.muted ? c.textMuted : getToneColor(node.tone ?? "blue", c);
4021
- const accentText = node.muted ? c.textMuted : getReadableToneColor(node.tone ?? "blue", c);
4374
+ const fill = getToneFill(node.tone ?? "blue", c);
4375
+ const accentText = node.muted ? c.textMuted : getReadableToneColor(node.tone ?? "blue", c, fill, c.bg);
4022
4376
  const resolvedIconSize = clamp(
4023
4377
  node.iconSize ?? iconSize,
4024
4378
  8,
@@ -4042,6 +4396,11 @@ function GraphDiagram({
4042
4396
  "div",
4043
4397
  {
4044
4398
  key: `graph-node-${node.id}`,
4399
+ "data-vizmatic-graph-node-id": node.id,
4400
+ "data-vizmatic-graph-node-label": graphAccessibleText(node.label) || node.id,
4401
+ "data-vizmatic-graph-node-detail": graphAccessibleText(node.detail),
4402
+ "data-vizmatic-graph-node-title": node.title ?? "",
4403
+ "data-vizmatic-graph-node-href": node.href,
4045
4404
  style: {
4046
4405
  position: "absolute",
4047
4406
  left: node.cx - node.width / 2,
@@ -4056,7 +4415,7 @@ function GraphDiagram({
4056
4415
  padding: "8px 10px",
4057
4416
  boxSizing: "border-box",
4058
4417
  borderRadius: c.preset === "engineering" ? 5 : 10,
4059
- backgroundColor: node.muted ? c.bgSubtle : getToneFill(node.tone ?? "blue", c),
4418
+ backgroundColor: node.muted ? c.bgSubtle : fill,
4060
4419
  border: `${c.preset === "engineering" ? 1.25 : 1.5}px solid ${node.muted ? c.borderLight : `${accent}${c.preset === "engineering" ? "" : "88"}`}`,
4061
4420
  ...!node.muted && c.preset !== "engineering" ? { boxShadow: `0 8px 18px ${c.shadow}` } : {},
4062
4421
  opacity: node.muted ? 0.62 : 1,
@@ -4098,6 +4457,7 @@ function GraphDiagram({
4098
4457
  })
4099
4458
  );
4100
4459
  }
4460
+ Object.defineProperty(GraphDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
4101
4461
  function countTreeLeaves(node) {
4102
4462
  if (!node.children?.length) return 1;
4103
4463
  return node.children.reduce((sum, child) => sum + countTreeLeaves(child), 0);
@@ -5140,6 +5500,8 @@ function compileDataflow(spec) {
5140
5500
  id: node.id,
5141
5501
  label: node.label,
5142
5502
  detail: detailWithSchema(node.detail, node.schema),
5503
+ href: node.href,
5504
+ title: node.title,
5143
5505
  tone: node.tone ?? defaultNodeTones[kind],
5144
5506
  icon: node.icon ?? defaultNodeIcons[kind],
5145
5507
  muted: node.muted,
@@ -5152,9 +5514,12 @@ function compileDataflow(spec) {
5152
5514
  const mode = edgeMode(edge);
5153
5515
  const schema = schemaLabel(edge.schema);
5154
5516
  return {
5517
+ id: edge.id,
5155
5518
  from: edge.from,
5156
5519
  to: edge.to,
5157
5520
  label: edge.label ?? schema ?? mode,
5521
+ href: edge.href,
5522
+ title: edge.title,
5158
5523
  tone: edge.tone ?? (mode === "stream" ? "cyan" : "blue"),
5159
5524
  muted: edge.muted,
5160
5525
  kind: mode === "stream" ? "async" : "data",
@@ -5175,6 +5540,9 @@ function DataflowDiagram({
5175
5540
  edges,
5176
5541
  boundaries,
5177
5542
  ariaLabel,
5543
+ id,
5544
+ title,
5545
+ description,
5178
5546
  width,
5179
5547
  height,
5180
5548
  nodeWidth = 158,
@@ -5197,6 +5565,9 @@ function DataflowDiagram({
5197
5565
  edges: compiled.edges,
5198
5566
  groups: compiled.groups,
5199
5567
  ariaLabel: compiled.ariaLabel,
5568
+ id,
5569
+ title,
5570
+ description,
5200
5571
  width,
5201
5572
  height,
5202
5573
  nodeWidth,
@@ -5213,6 +5584,7 @@ function DataflowDiagram({
5213
5584
  iconSize
5214
5585
  });
5215
5586
  }
5587
+ Object.defineProperty(DataflowDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5216
5588
 
5217
5589
  // src/primitives/deployment.ts
5218
5590
  var boundaryKindLabels = {
@@ -5425,10 +5797,10 @@ function validateDeploymentSpec(boundaries, nodes, connections) {
5425
5797
  for (const side of ["from", "to"]) {
5426
5798
  const reference = connectionPortReference(connection, side);
5427
5799
  if (reference == null) continue;
5428
- const nodeId = side === "from" ? connection.from : connection.to;
5429
- const ports = portsByNode.get(nodeId);
5800
+ const nodeId2 = side === "from" ? connection.from : connection.to;
5801
+ const ports = portsByNode.get(nodeId2);
5430
5802
  if (ports != null && ports.size > 0 && !ports.has(String(reference))) {
5431
- throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId}".`);
5803
+ throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId2}".`);
5432
5804
  }
5433
5805
  }
5434
5806
  }
@@ -5463,6 +5835,8 @@ function compileDeployment(spec) {
5463
5835
  id: node.id,
5464
5836
  label: node.label,
5465
5837
  detail: node.detail ?? generatedDetail,
5838
+ href: node.href,
5839
+ title: node.title,
5466
5840
  x: node.x,
5467
5841
  y: node.y,
5468
5842
  tone: node.tone,
@@ -5485,6 +5859,7 @@ function compileDeployment(spec) {
5485
5859
  const fallbackFromPort = fromReference != null && !sourceNode?.ports?.length ? fromReference : void 0;
5486
5860
  const fallbackToPort = toReference != null && !targetNode?.ports?.length ? toReference : void 0;
5487
5861
  return {
5862
+ id: connection.id,
5488
5863
  from: connection.from,
5489
5864
  to: connection.to,
5490
5865
  tone: connection.tone ?? connectionTones[kind],
@@ -5492,7 +5867,9 @@ function compileDeployment(spec) {
5492
5867
  kind: graphConnectionKind(kind),
5493
5868
  style: connection.style ?? graphConnectionStyle(kind),
5494
5869
  arrow: connection.arrow ?? "forward",
5495
- label: connectionLabel(connection, sourcePort ?? fallbackFromPort, targetPort ?? fallbackToPort)
5870
+ label: connectionLabel(connection, sourcePort ?? fallbackFromPort, targetPort ?? fallbackToPort),
5871
+ href: connection.href,
5872
+ title: connection.title
5496
5873
  };
5497
5874
  });
5498
5875
  return {
@@ -5520,6 +5897,7 @@ function DeploymentDiagram({
5520
5897
  ariaLabel: compiled.ariaLabel
5521
5898
  });
5522
5899
  }
5900
+ Object.defineProperty(DeploymentDiagram, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5523
5901
 
5524
5902
  // src/primitives/transformer.ts
5525
5903
  var blockLabels = {
@@ -5718,6 +6096,8 @@ function compileTransformer(spec) {
5718
6096
  id,
5719
6097
  label,
5720
6098
  detail: repetitionDetail,
6099
+ href: block.href,
6100
+ title: block.title,
5721
6101
  x: block.x,
5722
6102
  y: block.y,
5723
6103
  tone: block.tone ?? blockTones[kind],
@@ -5732,8 +6112,10 @@ function compileTransformer(spec) {
5732
6112
  const edges = [];
5733
6113
  for (const route of routes) {
5734
6114
  const kind = resolveRouteKind(route);
5735
- for (const endpoint of expandedRouteEndpoints(route, repeatCounts, expandRepeats)) {
6115
+ const endpoints = expandedRouteEndpoints(route, repeatCounts, expandRepeats);
6116
+ for (const [index, endpoint] of endpoints.entries()) {
5736
6117
  edges.push({
6118
+ id: route.id == null ? void 0 : endpoints.length === 1 ? route.id : `${route.id}-${index + 1}`,
5737
6119
  from: endpoint.from,
5738
6120
  to: endpoint.to,
5739
6121
  tone: route.tone ?? routeTones[kind],
@@ -5741,7 +6123,9 @@ function compileTransformer(spec) {
5741
6123
  kind: graphRouteKind(kind),
5742
6124
  style: route.style ?? graphRouteStyle(kind),
5743
6125
  arrow: route.arrow ?? (kind === "residual" ? "both" : "forward"),
5744
- label: routeLabel(route, kind)
6126
+ label: routeLabel(route, kind),
6127
+ href: route.href,
6128
+ title: route.title
5745
6129
  });
5746
6130
  }
5747
6131
  }
@@ -5773,6 +6157,7 @@ function TransformerTopology({
5773
6157
  ariaLabel: compiled.ariaLabel
5774
6158
  });
5775
6159
  }
6160
+ Object.defineProperty(TransformerTopology, SVG_ACCESSIBILITY_COMPONENT, { value: true });
5776
6161
 
5777
6162
  // src/primitives/data.ts
5778
6163
  import React9 from "react";
@@ -6142,8 +6527,9 @@ function Grid({
6142
6527
  const cellStyle = (cell, rowIndex, colIndex) => {
6143
6528
  const config = isGridCell(cell) ? cell : {};
6144
6529
  const toneColor = config.tone ? getToneColor(config.tone, c) : void 0;
6145
- const toneTextColor = config.tone ? getReadableToneColor(config.tone, c) : void 0;
6146
6530
  const isHeader = rowIndex < headerRows || colIndex < headerCols;
6531
+ const backgroundColor = config.backgroundColor ?? (toneColor ? `${toneColor}22` : isHeader ? c.bgSubtle : c.bgHover);
6532
+ const toneTextColor = config.tone ? getReadableToneColor(config.tone, c, backgroundColor, c.bgHover) : void 0;
6147
6533
  return {
6148
6534
  width: cellWidth,
6149
6535
  height: cellHeight,
@@ -6151,7 +6537,7 @@ function Grid({
6151
6537
  alignItems: "center",
6152
6538
  justifyContent: "center",
6153
6539
  borderRadius: radius,
6154
- backgroundColor: config.backgroundColor ?? (toneColor ? `${toneColor}22` : isHeader ? c.bgSubtle : c.bgHover),
6540
+ backgroundColor,
6155
6541
  border: `1px solid ${config.borderColor ?? (toneColor ? `${toneColor}55` : c.borderSubtle)}`,
6156
6542
  color: config.color ?? (toneTextColor ?? (isHeader ? c.textPrimary : c.textSecondary)),
6157
6543
  ...config.opacity !== void 0 ? { opacity: config.opacity } : {},
@@ -8210,13 +8596,13 @@ function detectOverflow(pixels, width, height, bgColor, edgeTolerance = 3, minDe
8210
8596
  const right = checkEdge((i, off) => [width - 1 - off, i], height);
8211
8597
  const top = checkEdge((i, off) => [i, off], width);
8212
8598
  const left = checkEdge((i, off) => [off, i], height);
8213
- const overflowEdges2 = [];
8214
- if (top) overflowEdges2.push("top");
8215
- if (right) overflowEdges2.push("right");
8216
- if (bottom) overflowEdges2.push("bottom");
8217
- if (left) overflowEdges2.push("left");
8218
- const overflows = overflowEdges2.length > 0;
8219
- const message = overflows ? `Content overflows canvas at: ${overflowEdges2.join(", ")}. Increase the illustration dimensions.` : "";
8599
+ const overflowEdges3 = [];
8600
+ if (top) overflowEdges3.push("top");
8601
+ if (right) overflowEdges3.push("right");
8602
+ if (bottom) overflowEdges3.push("bottom");
8603
+ if (left) overflowEdges3.push("left");
8604
+ const overflows = overflowEdges3.length > 0;
8605
+ const message = overflows ? `Content overflows canvas at: ${overflowEdges3.join(", ")}. Increase the illustration dimensions.` : "";
8220
8606
  return {
8221
8607
  overflows,
8222
8608
  edges: { top, right, bottom, left },
@@ -8685,14 +9071,19 @@ async function renderToSvgInContext(element, width, height, options) {
8685
9071
  options.theme ?? "dark",
8686
9072
  watermark
8687
9073
  ) : element;
8688
- const svg = await satori(outputElement, {
9074
+ const prepared = prepareAccessibleSvg(outputElement);
9075
+ const layoutNodes = [];
9076
+ const svg = await satori(prepared.element, {
8689
9077
  width,
8690
9078
  height,
8691
9079
  fonts,
8692
9080
  loadAdditionalAsset,
8693
- onNodeDetected: options.onNodeDetected
9081
+ onNodeDetected: (node) => {
9082
+ layoutNodes.push(node);
9083
+ options.onNodeDetected?.(node);
9084
+ }
8694
9085
  });
8695
- return sanitizeSvg(svg);
9086
+ return addSvgAccessibility(sanitizeSvg(svg), prepared.graphs, layoutNodes);
8696
9087
  }
8697
9088
 
8698
9089
  // src/animate.ts
@@ -9474,152 +9865,586 @@ async function renderAnimationGifWithOutput(animation, options) {
9474
9865
  };
9475
9866
  }
9476
9867
 
9477
- // src/bare-source.ts
9478
- function readJsxTag(source, start) {
9479
- if (source.startsWith("<>", start)) return { closing: false, end: start + 2, selfClosing: false };
9480
- if (source.startsWith("</>", start)) return { closing: true, end: start + 3, selfClosing: false };
9481
- const head = source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);
9482
- if (!head) return void 0;
9483
- const closing = Boolean(head[1]);
9484
- let quote;
9485
- let braces = 0;
9868
+ // src/import-types.ts
9869
+ function graphImportResult(source, graph, diagnostics) {
9870
+ if (graph.nodes.length === 0 && diagnostics.every(({ severity }) => severity !== "error")) {
9871
+ diagnostics.push({
9872
+ code: "import.empty",
9873
+ severity: "error",
9874
+ message: "The source contains no graph nodes to import.",
9875
+ line: 1,
9876
+ column: 1,
9877
+ excerpt: ""
9878
+ });
9879
+ }
9880
+ const ok = diagnostics.every(({ severity }) => severity !== "error");
9881
+ return ok ? { source, ok, graph, diagnostics } : { source, ok, diagnostics };
9882
+ }
9883
+ function addImportDiagnostic(diagnostics, sourceLines, line, code, severity, message, column = 1) {
9884
+ diagnostics.push({
9885
+ code,
9886
+ severity,
9887
+ message,
9888
+ line,
9889
+ column,
9890
+ excerpt: (sourceLines[line - 1] ?? "").trim().slice(0, 180)
9891
+ });
9892
+ }
9893
+
9894
+ // src/import-mermaid.ts
9895
+ var ID_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]*/;
9896
+ var CONNECTORS = ["-.->", "-->", "---"];
9897
+ function skipWhitespace(line, index) {
9898
+ while (index < line.length && /\s/.test(line[index] ?? "")) index++;
9899
+ return index;
9900
+ }
9901
+ function readDelimited(line, start, close) {
9902
+ let inDoubleQuote = false;
9486
9903
  let escaped = false;
9487
- for (let index = start + head[0].length; index < source.length; index += 1) {
9488
- const character = source[index];
9489
- if (quote) {
9904
+ for (let index = start; index < line.length; index++) {
9905
+ const character = line[index];
9906
+ if (inDoubleQuote) {
9490
9907
  if (escaped) escaped = false;
9491
9908
  else if (character === "\\") escaped = true;
9492
- else if (character === quote) quote = void 0;
9909
+ else if (character === '"') inDoubleQuote = false;
9493
9910
  continue;
9494
9911
  }
9495
- if (character === '"' || character === "'" || character === "`") {
9496
- quote = character;
9912
+ if (character === '"') {
9913
+ inDoubleQuote = true;
9497
9914
  continue;
9498
9915
  }
9499
- if (character === "{") {
9500
- braces += 1;
9501
- continue;
9916
+ if (line.startsWith(close, index)) {
9917
+ return { value: line.slice(start, index), next: index + close.length };
9502
9918
  }
9503
- if (character === "}") {
9504
- braces = Math.max(0, braces - 1);
9505
- continue;
9919
+ }
9920
+ return void 0;
9921
+ }
9922
+ function decodeLabel(raw) {
9923
+ const value = raw.trim();
9924
+ if (!value.startsWith('"')) return value;
9925
+ if (!value.endsWith('"')) return void 0;
9926
+ try {
9927
+ const decoded = JSON.parse(value);
9928
+ return typeof decoded === "string" ? decoded : void 0;
9929
+ } catch {
9930
+ return void 0;
9931
+ }
9932
+ }
9933
+ function labelHasUnsupportedMarkup(label) {
9934
+ return /<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label);
9935
+ }
9936
+ function readEndpoint(line, from) {
9937
+ let index = skipWhitespace(line, from);
9938
+ const id = line.slice(index).match(ID_PATTERN)?.[0];
9939
+ if (!id) return void 0;
9940
+ index += id.length;
9941
+ const afterId = skipWhitespace(line, index);
9942
+ if (afterId >= line.length) return { id, label: id, shape: "rectangle", next: afterId };
9943
+ const rest = line.slice(afterId);
9944
+ const delimiters = [
9945
+ { open: "[(", close: ")]", lossy: true },
9946
+ { open: "([", close: "])", lossy: true },
9947
+ { open: "((", close: "))", lossy: true },
9948
+ { open: "{{", close: "}}", lossy: true },
9949
+ { open: "[", close: "]", lossy: false },
9950
+ { open: "(", close: ")", lossy: true },
9951
+ { open: "{", close: "}", lossy: true }
9952
+ ];
9953
+ const delimiter = delimiters.find(({ open }) => rest.startsWith(open));
9954
+ if (!delimiter) return { id, label: id, shape: "rectangle", next: index };
9955
+ const content = readDelimited(line, afterId + delimiter.open.length, delimiter.close);
9956
+ if (!content) return void 0;
9957
+ const label = decodeLabel(content.value);
9958
+ if (label === void 0) return void 0;
9959
+ return {
9960
+ id,
9961
+ label,
9962
+ shape: delimiter.lossy ? "lossy" : "rectangle",
9963
+ next: content.next
9964
+ };
9965
+ }
9966
+ function addNode(state, endpoint, groupId, line, sourceLines, diagnostics, explicitlyDeclared) {
9967
+ if (state.groupIds.has(endpoint.id)) {
9968
+ addImportDiagnostic(
9969
+ diagnostics,
9970
+ sourceLines,
9971
+ line,
9972
+ "import.unsupported_semantics",
9973
+ "error",
9974
+ `Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`
9975
+ );
9976
+ return false;
9977
+ }
9978
+ if (labelHasUnsupportedMarkup(endpoint.label)) {
9979
+ addImportDiagnostic(
9980
+ diagnostics,
9981
+ sourceLines,
9982
+ line,
9983
+ "import.unsupported_semantics",
9984
+ "error",
9985
+ `Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`
9986
+ );
9987
+ return false;
9988
+ }
9989
+ const existingIndex = state.nodeIndexes.get(endpoint.id);
9990
+ if (existingIndex !== void 0) {
9991
+ const existing = state.nodes[existingIndex];
9992
+ if (!existing) return false;
9993
+ if (groupId && existing.group && existing.group !== groupId) {
9994
+ addImportDiagnostic(
9995
+ diagnostics,
9996
+ sourceLines,
9997
+ line,
9998
+ "import.unsupported_semantics",
9999
+ "error",
10000
+ `Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`
10001
+ );
10002
+ return false;
10003
+ }
10004
+ if (groupId && !existing.group) {
10005
+ addImportDiagnostic(
10006
+ diagnostics,
10007
+ sourceLines,
10008
+ line,
10009
+ "import.unsupported_semantics",
10010
+ "error",
10011
+ `Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`
10012
+ );
10013
+ return false;
9506
10014
  }
9507
- if (character !== ">" || braces > 0) continue;
9508
- const beforeClose = source.slice(start, index).trimEnd();
9509
- return {
9510
- closing,
9511
- end: index + 1,
9512
- selfClosing: !closing && beforeClose.endsWith("/")
10015
+ if (explicitlyDeclared) existing.label = endpoint.label;
10016
+ } else {
10017
+ state.nodeIndexes.set(endpoint.id, state.nodes.length);
10018
+ state.nodes.push({
10019
+ id: endpoint.id,
10020
+ label: endpoint.label,
10021
+ ...groupId ? { group: groupId } : {}
10022
+ });
10023
+ }
10024
+ if (endpoint.shape === "lossy" && !state.warnedShapes.has(endpoint.id)) {
10025
+ state.warnedShapes.add(endpoint.id);
10026
+ addImportDiagnostic(
10027
+ diagnostics,
10028
+ sourceLines,
10029
+ line,
10030
+ "import.lossy_semantics",
10031
+ "warning",
10032
+ `Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`
10033
+ );
10034
+ }
10035
+ return true;
10036
+ }
10037
+ function parseNodeOrEdgeLine(line, groupId, lineNumber, sourceLines, state, diagnostics) {
10038
+ const first = readEndpoint(line, 0);
10039
+ if (!first) {
10040
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Could not parse this Mermaid node or edge statement.");
10041
+ return;
10042
+ }
10043
+ const connectorStart = skipWhitespace(line, first.next);
10044
+ const hasConnector = CONNECTORS.some((connector) => line.startsWith(connector, connectorStart));
10045
+ if (!addNode(state, first, groupId, lineNumber, sourceLines, diagnostics, !hasConnector)) return;
10046
+ let previous = first;
10047
+ let cursor = first.next;
10048
+ while (true) {
10049
+ cursor = skipWhitespace(line, cursor);
10050
+ if (cursor >= line.length) return;
10051
+ const connector = CONNECTORS.find((candidate) => line.startsWith(candidate, cursor));
10052
+ if (!connector) {
10053
+ addImportDiagnostic(
10054
+ diagnostics,
10055
+ sourceLines,
10056
+ lineNumber,
10057
+ "import.unsupported_syntax",
10058
+ "error",
10059
+ "Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",
10060
+ cursor + 1
10061
+ );
10062
+ return;
10063
+ }
10064
+ cursor += connector.length;
10065
+ cursor = skipWhitespace(line, cursor);
10066
+ let edgeLabel;
10067
+ if (line[cursor] === "|") {
10068
+ const end = line.indexOf("|", cursor + 1);
10069
+ if (end < 0) {
10070
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid edge label is missing its closing |.", cursor + 1);
10071
+ return;
10072
+ }
10073
+ edgeLabel = line.slice(cursor + 1, end).trim();
10074
+ cursor = skipWhitespace(line, end + 1);
10075
+ if (labelHasUnsupportedMarkup(edgeLabel)) {
10076
+ addImportDiagnostic(
10077
+ diagnostics,
10078
+ sourceLines,
10079
+ lineNumber,
10080
+ "import.unsupported_semantics",
10081
+ "error",
10082
+ "Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",
10083
+ cursor + 1
10084
+ );
10085
+ return;
10086
+ }
10087
+ }
10088
+ const next = readEndpoint(line, cursor);
10089
+ if (!next) {
10090
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid connection has no supported target node.", cursor + 1);
10091
+ return;
10092
+ }
10093
+ if (!addNode(state, next, groupId, lineNumber, sourceLines, diagnostics, false)) return;
10094
+ const edge = {
10095
+ from: previous.id,
10096
+ to: next.id,
10097
+ ...edgeLabel !== void 0 ? { label: edgeLabel } : {},
10098
+ ...connector === "---" ? { arrow: "none" } : connector === "-.->" ? { arrow: "forward", style: "dotted" } : { arrow: "forward" }
9513
10099
  };
10100
+ state.edges.push(edge);
10101
+ state.edgeReferences.push({ id: previous.id, line: lineNumber }, { id: next.id, line: lineNumber });
10102
+ previous = next;
10103
+ cursor = next.next;
9514
10104
  }
9515
- return void 0;
9516
10105
  }
9517
- function skipJsxExpression(source, start) {
9518
- let depth = 0;
9519
- let quote;
9520
- let escaped = false;
9521
- let blockComment = false;
9522
- let lineComment = false;
9523
- for (let index = start; index < source.length; index += 1) {
9524
- const character = source[index];
9525
- const next = source[index + 1];
9526
- if (lineComment) {
9527
- if (character === "\n") lineComment = false;
10106
+ function importMermaidGraph(source) {
10107
+ const sourceLines = source.split(/\r?\n/);
10108
+ const diagnostics = [];
10109
+ const state = {
10110
+ nodes: [],
10111
+ nodeIndexes: /* @__PURE__ */ new Map(),
10112
+ groups: [],
10113
+ groupIds: /* @__PURE__ */ new Set(),
10114
+ edges: [],
10115
+ edgeReferences: [],
10116
+ warnedShapes: /* @__PURE__ */ new Set()
10117
+ };
10118
+ let direction = "TB";
10119
+ let currentGroup;
10120
+ let sawHeader = false;
10121
+ for (let index = 0; index < sourceLines.length; index++) {
10122
+ const lineNumber = index + 1;
10123
+ const rawLine = sourceLines[index] ?? "";
10124
+ const line = rawLine.trim();
10125
+ if (!line) continue;
10126
+ if (line.startsWith("%%{")) {
10127
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Mermaid directives and embedded configuration are not imported.");
9528
10128
  continue;
9529
10129
  }
9530
- if (blockComment) {
9531
- if (character === "*" && next === "/") {
9532
- blockComment = false;
9533
- index += 1;
10130
+ if (line.startsWith("%%")) continue;
10131
+ if (!sawHeader) {
10132
+ const header = line.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);
10133
+ if (!header) {
10134
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", 'Expected a Mermaid flowchart or graph header such as "flowchart LR".');
10135
+ sawHeader = true;
10136
+ continue;
9534
10137
  }
10138
+ sawHeader = true;
10139
+ const sourceDirection = header[1]?.toUpperCase();
10140
+ direction = sourceDirection === "TD" ? "TB" : sourceDirection ?? "TB";
9535
10141
  continue;
9536
10142
  }
9537
- if (quote) {
9538
- if (escaped) escaped = false;
9539
- else if (character === "\\") escaped = true;
9540
- else if (character === quote) quote = void 0;
10143
+ const subgraph = line.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);
10144
+ if (subgraph) {
10145
+ if (currentGroup) {
10146
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Nested Mermaid subgraphs are not imported.");
10147
+ continue;
10148
+ }
10149
+ const id = subgraph[1];
10150
+ if (!id) continue;
10151
+ if (state.groupIds.has(id) || state.nodeIndexes.has(id)) {
10152
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", `Mermaid subgraph id "${id}" conflicts with an existing group or node.`);
10153
+ continue;
10154
+ }
10155
+ const rawLabel = subgraph[2];
10156
+ const label = rawLabel === void 0 ? id : decodeLabel(rawLabel);
10157
+ if (label === void 0 || labelHasUnsupportedMarkup(label)) {
10158
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", `Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);
10159
+ continue;
10160
+ }
10161
+ currentGroup = id;
10162
+ state.groupIds.add(id);
10163
+ state.groups.push({ id, label });
9541
10164
  continue;
9542
10165
  }
9543
- if (character === "/" && next === "/") {
9544
- lineComment = true;
9545
- index += 1;
10166
+ if (/^subgraph\b/i.test(line)) {
10167
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_syntax", "error", "Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");
9546
10168
  continue;
9547
10169
  }
9548
- if (character === "/" && next === "*") {
9549
- blockComment = true;
9550
- index += 1;
10170
+ if (/^end\s*$/i.test(line)) {
10171
+ if (!currentGroup) addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.parse_error", "error", "Mermaid end has no matching subgraph.");
10172
+ else currentGroup = void 0;
9551
10173
  continue;
9552
10174
  }
9553
- if (character === '"' || character === "'" || character === "`") {
9554
- quote = character;
10175
+ if (/^direction\b/i.test(line)) {
10176
+ addImportDiagnostic(
10177
+ diagnostics,
10178
+ sourceLines,
10179
+ lineNumber,
10180
+ currentGroup ? "import.unsupported_semantics" : "import.parse_error",
10181
+ "error",
10182
+ currentGroup ? "Per-subgraph Mermaid direction cannot be represented by GraphDiagram." : "Set Mermaid graph direction in the flowchart or graph header."
10183
+ );
9555
10184
  continue;
9556
10185
  }
9557
- if (character === "{") depth += 1;
9558
- else if (character === "}" && --depth === 0) return index + 1;
9559
- }
9560
- return void 0;
9561
- }
9562
- function findJsxEnd(source, start) {
9563
- let depth = 0;
9564
- for (let index = start; index < source.length; index += 1) {
9565
- if (source[index] === "{") {
9566
- const expressionEnd = skipJsxExpression(source, index);
9567
- if (expressionEnd == null) return void 0;
9568
- index = expressionEnd - 1;
10186
+ if (/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line)) {
10187
+ addImportDiagnostic(diagnostics, sourceLines, lineNumber, "import.unsupported_semantics", "error", "Mermaid classes, styling, accessibility directives, and click actions are not imported.");
9569
10188
  continue;
9570
10189
  }
9571
- if (source[index] !== "<") continue;
9572
- const tag = readJsxTag(source, index);
9573
- if (!tag) continue;
9574
- if (tag.closing) depth -= 1;
9575
- else if (!tag.selfClosing) depth += 1;
9576
- index = tag.end - 1;
9577
- if (depth === 0) return tag.end;
10190
+ parseNodeOrEdgeLine(line, currentGroup, lineNumber, sourceLines, state, diagnostics);
9578
10191
  }
9579
- return void 0;
10192
+ if (!sawHeader) {
10193
+ addImportDiagnostic(diagnostics, sourceLines, 1, "import.parse_error", "error", "Missing Mermaid flowchart or graph header.");
10194
+ }
10195
+ if (currentGroup) {
10196
+ addImportDiagnostic(diagnostics, sourceLines, sourceLines.length, "import.parse_error", "error", `Mermaid subgraph "${currentGroup}" has no matching end.`);
10197
+ }
10198
+ for (const reference of state.edgeReferences) {
10199
+ if (state.groupIds.has(reference.id)) {
10200
+ addImportDiagnostic(
10201
+ diagnostics,
10202
+ sourceLines,
10203
+ reference.line,
10204
+ "import.unsupported_semantics",
10205
+ "error",
10206
+ `Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`
10207
+ );
10208
+ }
10209
+ }
10210
+ const graph = {
10211
+ nodes: state.nodes,
10212
+ edges: state.edges,
10213
+ groups: state.groups,
10214
+ direction
10215
+ };
10216
+ return graphImportResult("mermaid", graph, diagnostics);
9580
10217
  }
9581
- function hasOnlyTrailingSyntax(source) {
9582
- let index = 0;
9583
- while (index < source.length) {
9584
- const rest = source.slice(index);
9585
- const whitespace = rest.match(/^[\s;)]*/)?.[0].length ?? 0;
9586
- index += whitespace;
9587
- if (source.startsWith("//", index)) {
9588
- const newline = source.indexOf("\n", index + 2);
9589
- index = newline < 0 ? source.length : newline + 1;
9590
- continue;
10218
+
10219
+ // src/import-d2.ts
10220
+ function decodeD2Label(raw) {
10221
+ const value = raw.trim();
10222
+ if (value.startsWith('"')) {
10223
+ if (!value.endsWith('"')) return void 0;
10224
+ try {
10225
+ const decoded = JSON.parse(value);
10226
+ return typeof decoded === "string" ? decoded : void 0;
10227
+ } catch {
10228
+ return void 0;
9591
10229
  }
9592
- if (source.startsWith("/*", index)) {
9593
- const end = source.indexOf("*/", index + 2);
9594
- if (end < 0) return false;
9595
- index = end + 2;
10230
+ }
10231
+ if (value.startsWith("'")) {
10232
+ if (!value.endsWith("'")) return void 0;
10233
+ return value.slice(1, -1).replace(/\\(['\\])/g, "$1");
10234
+ }
10235
+ return value;
10236
+ }
10237
+ function hasMarkdownFormatting(label) {
10238
+ return /<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label);
10239
+ }
10240
+ function hasUnquotedHash(line) {
10241
+ let quote;
10242
+ let escaped = false;
10243
+ for (const character of line) {
10244
+ if (quote) {
10245
+ if (escaped) escaped = false;
10246
+ else if (character === "\\") escaped = true;
10247
+ else if (character === quote) quote = void 0;
9596
10248
  continue;
9597
10249
  }
9598
- return index >= source.length;
10250
+ if (character === '"' || character === "'") quote = character;
10251
+ else if (character === "#") return true;
10252
+ }
10253
+ return false;
10254
+ }
10255
+ function addNode2(nodes, id, label, line, sourceLines, diagnostics, explicitLabel) {
10256
+ if (hasMarkdownFormatting(label)) {
10257
+ addImportDiagnostic(
10258
+ diagnostics,
10259
+ sourceLines,
10260
+ line,
10261
+ "import.unsupported_semantics",
10262
+ "error",
10263
+ `D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`
10264
+ );
10265
+ return false;
10266
+ }
10267
+ const existing = nodes.get(id);
10268
+ if (existing) {
10269
+ if (explicitLabel) {
10270
+ existing.node.label = label;
10271
+ }
10272
+ } else {
10273
+ nodes.set(id, { node: { id, label } });
9599
10274
  }
9600
10275
  return true;
9601
10276
  }
9602
- function extractRootJsx(source) {
9603
- const body = source.replace(/^(?:\s*\()+\s*/, "");
9604
- const end = findJsxEnd(body, 0);
9605
- return (end == null ? body : body.slice(0, end)).trim();
10277
+ function reportUnsupported(diagnostics, sourceLines, line, message, code = "import.unsupported_syntax", column = 1) {
10278
+ addImportDiagnostic(diagnostics, sourceLines, line, code, "error", message, column);
9606
10279
  }
9607
- function findBareRootJsxStart(source) {
9608
- const candidates = source.matchAll(/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);
9609
- for (const candidate of candidates) {
9610
- if (candidate.index == null) continue;
9611
- const lineStart = candidate.index + (candidate[1]?.length ?? 0);
9612
- const expressionStart = lineStart + (candidate[2]?.length ?? 0);
9613
- const jsxStart = candidate.index + candidate[0].lastIndexOf(candidate[3] ?? "<");
9614
- const jsxEnd = findJsxEnd(source, jsxStart);
9615
- if (jsxEnd != null && hasOnlyTrailingSyntax(source.slice(jsxEnd))) return expressionStart;
10280
+ function importD2Graph(source) {
10281
+ const sourceLines = source.split(/\r?\n/);
10282
+ const diagnostics = [];
10283
+ const nodesById = /* @__PURE__ */ new Map();
10284
+ const edges = [];
10285
+ const shapes = /* @__PURE__ */ new Map();
10286
+ let direction = "TB";
10287
+ let containerDepth = 0;
10288
+ for (let index = 0; index < sourceLines.length; index++) {
10289
+ const lineNumber = index + 1;
10290
+ const rawLine = sourceLines[index] ?? "";
10291
+ const line = rawLine.trim();
10292
+ if (!line) continue;
10293
+ if (containerDepth > 0) {
10294
+ const opens = (rawLine.match(/\{/g) ?? []).length;
10295
+ const closes = (rawLine.match(/\}/g) ?? []).length;
10296
+ containerDepth = Math.max(0, containerDepth + opens - closes);
10297
+ continue;
10298
+ }
10299
+ if (line.startsWith("#")) continue;
10300
+ if (hasUnquotedHash(line)) {
10301
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");
10302
+ continue;
10303
+ }
10304
+ if (line.includes(";")) {
10305
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 semicolon-separated statements are not supported; place one statement on each line.");
10306
+ continue;
10307
+ }
10308
+ if (line.includes("{") || line.includes("}")) {
10309
+ reportUnsupported(
10310
+ diagnostics,
10311
+ sourceLines,
10312
+ lineNumber,
10313
+ "D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.",
10314
+ "import.unsupported_semantics"
10315
+ );
10316
+ const opens = (rawLine.match(/\{/g) ?? []).length;
10317
+ const closes = (rawLine.match(/\}/g) ?? []).length;
10318
+ containerDepth = Math.max(0, opens - closes);
10319
+ continue;
10320
+ }
10321
+ const directionMatch = line.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);
10322
+ if (directionMatch) {
10323
+ const value = directionMatch[1]?.toLowerCase();
10324
+ direction = value === "left" ? "RL" : value === "down" ? "TB" : value === "up" ? "BT" : "LR";
10325
+ continue;
10326
+ }
10327
+ if (/^direction\b/i.test(line)) {
10328
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 direction must be right, left, down, or up.", "import.parse_error");
10329
+ continue;
10330
+ }
10331
+ const shapeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);
10332
+ if (shapeMatch) {
10333
+ const id = shapeMatch[1];
10334
+ const shape = decodeD2Label(shapeMatch[2] ?? "");
10335
+ if (!id || shape === void 0 || shape === "") {
10336
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 shape declaration needs a simple identifier and a shape value.", "import.parse_error");
10337
+ continue;
10338
+ }
10339
+ if (!nodesById.has(id)) addNode2(nodesById, id, id, lineNumber, sourceLines, diagnostics, false);
10340
+ shapes.set(id, { value: shape, line: lineNumber });
10341
+ continue;
10342
+ }
10343
+ const edgeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);
10344
+ if (edgeMatch) {
10345
+ const from = edgeMatch[1];
10346
+ const connector = edgeMatch[2];
10347
+ const to = edgeMatch[3];
10348
+ const rawLabel = edgeMatch[4];
10349
+ if (!from || !connector || !to) continue;
10350
+ let label;
10351
+ if (rawLabel !== void 0) {
10352
+ label = decodeD2Label(rawLabel);
10353
+ if (label === void 0) {
10354
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 connection label has invalid quotes.", "import.parse_error");
10355
+ continue;
10356
+ }
10357
+ if (hasMarkdownFormatting(label)) {
10358
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.", "import.unsupported_semantics");
10359
+ continue;
10360
+ }
10361
+ }
10362
+ addNode2(nodesById, from, from, lineNumber, sourceLines, diagnostics, false);
10363
+ addNode2(nodesById, to, to, lineNumber, sourceLines, diagnostics, false);
10364
+ edges.push({
10365
+ from,
10366
+ to,
10367
+ ...label !== void 0 ? { label } : {},
10368
+ arrow: connector === "<->" ? "both" : connector === "<-" ? "backward" : connector === "--" ? "none" : "forward"
10369
+ });
10370
+ continue;
10371
+ }
10372
+ const nodeMatch = line.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);
10373
+ if (nodeMatch) {
10374
+ const id = nodeMatch[1];
10375
+ const rawLabel = nodeMatch[2];
10376
+ if (!id) continue;
10377
+ let label = id;
10378
+ let explicitLabel = false;
10379
+ if (rawLabel !== void 0) {
10380
+ const decoded = decodeD2Label(rawLabel);
10381
+ if (decoded === void 0) {
10382
+ reportUnsupported(diagnostics, sourceLines, lineNumber, `D2 label for "${id}" has invalid quotes.`, "import.parse_error");
10383
+ continue;
10384
+ }
10385
+ label = decoded;
10386
+ explicitLabel = true;
10387
+ }
10388
+ addNode2(nodesById, id, label, lineNumber, sourceLines, diagnostics, explicitLabel);
10389
+ continue;
10390
+ }
10391
+ if (line.includes(".style") || line.includes(".width") || line.includes(".height") || line.includes(".near")) {
10392
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 styling, sizing, and positioning fields are not imported.", "import.unsupported_semantics");
10393
+ } else if (/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line)) {
10394
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.");
10395
+ } else if (/(?:<->|->|<-|--)/.test(line)) {
10396
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.");
10397
+ } else {
10398
+ reportUnsupported(diagnostics, sourceLines, lineNumber, "Could not parse this D2 statement in the supported subset.", "import.parse_error");
10399
+ }
9616
10400
  }
9617
- return -1;
10401
+ if (containerDepth > 0) {
10402
+ reportUnsupported(diagnostics, sourceLines, sourceLines.length, "D2 object-property block has no matching closing brace.", "import.parse_error");
10403
+ }
10404
+ for (const [id, { value, line }] of shapes) {
10405
+ if (value.toLowerCase() === "rectangle") continue;
10406
+ addImportDiagnostic(
10407
+ diagnostics,
10408
+ sourceLines,
10409
+ line,
10410
+ "import.lossy_semantics",
10411
+ "warning",
10412
+ `D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`
10413
+ );
10414
+ }
10415
+ return graphImportResult("d2", {
10416
+ nodes: [...nodesById.values()].map(({ node }) => node),
10417
+ edges,
10418
+ groups: [],
10419
+ direction
10420
+ }, diagnostics);
9618
10421
  }
9619
10422
 
10423
+ // src/check.ts
10424
+ import { mkdtemp, rm } from "fs/promises";
10425
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
10426
+ import { tmpdir } from "os";
10427
+ import { join as join2 } from "path";
10428
+
9620
10429
  // src/diagnostics.ts
9621
10430
  import parseCssColor3 from "parse-css-color";
9622
- import { Children, isValidElement } from "react";
10431
+ import { Children, isValidElement as isValidElement2 } from "react";
10432
+ var CHECK_DIAGNOSTIC_CODES = [
10433
+ "accessibility.low_contrast",
10434
+ "api.unsupported_prop",
10435
+ "asset.warning",
10436
+ "frame.load_error",
10437
+ "frame.unknown_preset",
10438
+ "layout.auto_size",
10439
+ "layout.connector_congestion",
10440
+ "layout.overflow",
10441
+ "layout.text_overlap",
10442
+ "layout.whitespace_imbalance",
10443
+ "readability.small_text",
10444
+ "render.error",
10445
+ "render.warning",
10446
+ "style.unsupported"
10447
+ ];
9623
10448
  var MAX_CONTRAST_NODES = 5e3;
9624
10449
  var MAX_DIAGNOSTICS_PER_RULE = 12;
9625
10450
  var MIN_TEXT_SIZE = 11;
@@ -9643,7 +10468,7 @@ function hslToRgb2(hue, saturation, lightness) {
9643
10468
  function colorFromCss(value) {
9644
10469
  if (typeof value !== "string") return void 0;
9645
10470
  const parsed = parseCssColor3(value);
9646
- if (!parsed || parsed.values.length < 3 || parsed.alpha < 0.95) return void 0;
10471
+ if (!parsed || parsed.values.length < 3) return void 0;
9647
10472
  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];
9648
10473
  return {
9649
10474
  r,
@@ -9652,6 +10477,21 @@ function colorFromCss(value) {
9652
10477
  alpha: parsed.alpha
9653
10478
  };
9654
10479
  }
10480
+ function compositeOver(foreground, background) {
10481
+ if (foreground.alpha >= 1 || !background) return foreground;
10482
+ const alpha = foreground.alpha + background.alpha * (1 - foreground.alpha);
10483
+ if (alpha <= 0) return { r: 0, g: 0, b: 0, alpha: 0 };
10484
+ return {
10485
+ r: (foreground.r * foreground.alpha + background.r * background.alpha * (1 - foreground.alpha)) / alpha,
10486
+ g: (foreground.g * foreground.alpha + background.g * background.alpha * (1 - foreground.alpha)) / alpha,
10487
+ b: (foreground.b * foreground.alpha + background.b * background.alpha * (1 - foreground.alpha)) / alpha,
10488
+ alpha
10489
+ };
10490
+ }
10491
+ function isUnresolvedColor(value) {
10492
+ if (typeof value !== "string" || value.trim() === "" || colorFromCss(value)) return false;
10493
+ return !["inherit", "initial", "revert", "unset"].includes(value.trim().toLowerCase());
10494
+ }
9655
10495
  function channelLuminance(value) {
9656
10496
  const normalized = value / 255;
9657
10497
  return normalized <= 0.04045 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
@@ -9694,8 +10534,12 @@ function styleRecord(value) {
9694
10534
  function hasDirectText(children) {
9695
10535
  return Children.toArray(children).some((child) => typeof child === "string" || typeof child === "number");
9696
10536
  }
10537
+ function elementId(props) {
10538
+ const value = props.id ?? props["data-vizmatic-id"];
10539
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
10540
+ }
9697
10541
  function resolveFunctionComponent(node, trustedComponents) {
9698
- if (!isValidElement(node) || typeof node.type !== "function" || trustedComponents.has(node.type)) return void 0;
10542
+ if (!isValidElement2(node) || typeof node.type !== "function" || trustedComponents.has(node.type)) return void 0;
9699
10543
  const component = node.type;
9700
10544
  if (component.__vizmaticPrimitive) return void 0;
9701
10545
  if (component.prototype?.isReactComponent) return void 0;
@@ -9705,12 +10549,12 @@ function resolveFunctionComponent(node, trustedComponents) {
9705
10549
  return void 0;
9706
10550
  }
9707
10551
  }
9708
- function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new Set(), rootBackground) {
10552
+ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new Set(), rootBackground2) {
9709
10553
  const diagnostics = [];
9710
10554
  const seen = /* @__PURE__ */ new Set();
9711
10555
  let visited = 0;
9712
10556
  function visit(node, inherited, path) {
9713
- if (visited++ >= MAX_CONTRAST_NODES || !isValidElement(node)) return;
10557
+ if (visited++ >= MAX_CONTRAST_NODES || !isValidElement2(node)) return;
9714
10558
  const resolved = resolveFunctionComponent(node, trustedComponents);
9715
10559
  if (resolved !== void 0) {
9716
10560
  visit(resolved, inherited, path);
@@ -9719,14 +10563,20 @@ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new
9719
10563
  const props = node.props;
9720
10564
  const style = typeof node.type === "string" ? styleRecord(props.style) : {};
9721
10565
  const backgroundImage = typeof style.backgroundImage === "string" ? style.backgroundImage.trim().toLowerCase() : "";
9722
- const hasUnresolvedBackground = backgroundImage !== "" && backgroundImage !== "none" || typeof style.background === "string" && style.background.includes("gradient(");
9723
- const background = hasUnresolvedBackground ? void 0 : colorFromCss(style.backgroundColor) ?? colorFromCss(style.background) ?? inherited.background;
9724
- const color = colorFromCss(style.color) ?? inherited.color;
10566
+ const backgroundShorthand = typeof style.background === "string" ? style.background.trim() : "";
10567
+ const isBackgroundWrapper = typeof node.type === "function" && (trustedComponents.has(node.type) || Boolean(node.type.__vizmaticPrimitive));
10568
+ const wrapperBackground = isBackgroundWrapper ? props.background : void 0;
10569
+ const hasUnresolvedBackground = backgroundImage !== "" && backgroundImage !== "none" || isUnresolvedColor(style.backgroundColor) || backgroundShorthand !== "" && backgroundShorthand.toLowerCase() !== "none" && !colorFromCss(backgroundShorthand) || isUnresolvedColor(wrapperBackground);
10570
+ const ownBackground = colorFromCss(style.backgroundColor) ?? colorFromCss(style.background) ?? colorFromCss(wrapperBackground);
10571
+ const baseBackground = path === "root" && isBackgroundWrapper && colorFromCss(wrapperBackground) ? void 0 : inherited.background;
10572
+ const background = hasUnresolvedBackground ? void 0 : ownBackground ? compositeOver(ownBackground, baseBackground) : baseBackground;
10573
+ const color = typeof style.color === "string" && style.color.trim().toLowerCase() === "currentcolor" ? inherited.color : isUnresolvedColor(style.color) ? void 0 : colorFromCss(style.color) ?? inherited.color;
9725
10574
  const fontSize = fontSizePixels(style.fontSize, inherited.fontSize);
9726
10575
  const fontWeight = numericFontWeight(style.fontWeight) ?? inherited.fontWeight;
9727
10576
  const context = { background, color, fontSize, fontWeight };
9728
- if (typeof node.type === "string" && hasDirectText(props.children) && color && background) {
9729
- const ratio = contrastRatio(color, background);
10577
+ if (typeof node.type === "string" && hasDirectText(props.children) && color && background !== void 0 && background.alpha >= 1) {
10578
+ const renderedColor = compositeOver(color, background);
10579
+ const ratio = contrastRatio(renderedColor, background);
9730
10580
  const required = requiredContrast(context);
9731
10581
  if (ratio < required) {
9732
10582
  const rounded = Math.round(ratio * 100) / 100;
@@ -9738,14 +10588,16 @@ function analyzeContrast(element, theme, trustedComponents = /* @__PURE__ */ new
9738
10588
  severity: "warning",
9739
10589
  theme,
9740
10590
  message: `Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,
9741
- suggestion: "Use a stronger text or background color token."
10591
+ suggestion: "Use a stronger text or background color token.",
10592
+ elementId: elementId(props),
10593
+ location: { path }
9742
10594
  });
9743
10595
  }
9744
10596
  }
9745
10597
  }
9746
10598
  Children.forEach(props.children, (child, index) => visit(child, context, `${path}.${index}`));
9747
10599
  }
9748
- visit(element, { background: colorFromCss(rootBackground) }, "root");
10600
+ visit(element, { background: colorFromCss(rootBackground2) }, "root");
9749
10601
  return diagnostics;
9750
10602
  }
9751
10603
  function containsLayoutNode(parent, child) {
@@ -9778,6 +10630,7 @@ function renderedTextNodes(nodes) {
9778
10630
  const horizontalInset = textAlign === "center" ? (node.width - paintWidth) / 2 : textAlign === "right" || textAlign === "end" ? node.width - paintWidth : 0;
9779
10631
  textNodes.push({
9780
10632
  text,
10633
+ elementId: elementId(node.props),
9781
10634
  left: node.left,
9782
10635
  top: node.top,
9783
10636
  width: node.width,
@@ -9855,7 +10708,9 @@ function analyzeRenderedLayout(nodes, theme) {
9855
10708
  severity: "warning",
9856
10709
  theme,
9857
10710
  message: `Text "${excerpt}" renders at ${node.fontSize}px.`,
9858
- suggestion: `Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`
10711
+ suggestion: `Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,
10712
+ elementId: node.elementId,
10713
+ location: { x: node.left, y: node.top, width: node.width, height: node.height }
9859
10714
  });
9860
10715
  smallTextCount += 1;
9861
10716
  if (smallTextCount >= MAX_DIAGNOSTICS_PER_RULE) break;
@@ -9866,51 +10721,66 @@ function analyzeRenderedLayout(nodes, theme) {
9866
10721
  severity: "warning",
9867
10722
  theme,
9868
10723
  message: `Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,
9869
- suggestion: "Increase spacing or canvas size, shorten labels, or move one label."
10724
+ suggestion: "Increase spacing or canvas size, shorten labels, or move one label.",
10725
+ elementId: left.elementId,
10726
+ relatedElementIds: right.elementId ? [right.elementId] : void 0,
10727
+ location: { x: left.left, y: left.top, width: left.width, height: left.height }
9870
10728
  });
9871
10729
  }
9872
- const maxDataNumber = (attribute) => Math.max(0, ...nodes.map((node) => {
9873
- const value = node.props[attribute];
10730
+ const maxDataNumber = (attribute2) => Math.max(0, ...nodes.map((node) => {
10731
+ const value = node.props[attribute2];
9874
10732
  return typeof value === "number" ? value : Number(value) || 0;
9875
10733
  }));
9876
10734
  const connectorCrossings2 = maxDataNumber("data-vizmatic-connector-crossings");
9877
10735
  if (connectorCrossings2 > 0) {
10736
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-connector-crossings"]) > 0);
9878
10737
  diagnostics.push({
9879
10738
  code: "layout.connector_congestion",
9880
10739
  severity: "warning",
9881
10740
  theme,
9882
10741
  message: `${connectorCrossings2} connector crossing${connectorCrossings2 === 1 ? "" : "s"} detected.`,
9883
- suggestion: "Use automatic layout, change graph direction, or simplify the edge set."
10742
+ suggestion: "Use automatic layout, change graph direction, or simplify the edge set.",
10743
+ elementId: source ? elementId(source.props) : void 0,
10744
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
9884
10745
  });
9885
10746
  }
9886
10747
  const labelCollisions = maxDataNumber("data-vizmatic-connector-label-collisions");
9887
10748
  if (labelCollisions > 0) {
10749
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-connector-label-collisions"]) > 0);
9888
10750
  diagnostics.push({
9889
10751
  code: "layout.connector_congestion",
9890
10752
  severity: "warning",
9891
10753
  theme,
9892
10754
  message: `${labelCollisions} connector label collision${labelCollisions === 1 ? "" : "s"} detected.`,
9893
- suggestion: "Change graph direction or spacing, shorten edge labels, or remove nonessential labels."
10755
+ suggestion: "Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",
10756
+ elementId: source ? elementId(source.props) : void 0,
10757
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
9894
10758
  });
9895
10759
  }
9896
10760
  const crowdedEndpoints = maxDataNumber("data-vizmatic-crowded-connector-endpoints");
9897
10761
  if (crowdedEndpoints > 0) {
10762
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-crowded-connector-endpoints"]) > 0);
9898
10763
  diagnostics.push({
9899
10764
  code: "layout.connector_congestion",
9900
10765
  severity: "warning",
9901
10766
  theme,
9902
10767
  message: `${crowdedEndpoints} node${crowdedEndpoints === 1 ? "" : "s"} connect more than four edges.`,
9903
- suggestion: "Group related branches, add an intermediate hub, or change graph direction."
10768
+ suggestion: "Group related branches, add an intermediate hub, or change graph direction.",
10769
+ elementId: source ? elementId(source.props) : void 0,
10770
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
9904
10771
  });
9905
10772
  }
9906
10773
  const parallelGroups = maxDataNumber("data-vizmatic-parallel-connector-groups");
9907
10774
  if (parallelGroups > 0) {
10775
+ const source = nodes.find((node) => Number(node.props["data-vizmatic-parallel-connector-groups"]) > 0);
9908
10776
  diagnostics.push({
9909
10777
  code: "layout.connector_congestion",
9910
10778
  severity: "warning",
9911
10779
  theme,
9912
10780
  message: `${parallelGroups} connector route${parallelGroups === 1 ? "" : "s"} contain parallel edges.`,
9913
- suggestion: "Merge duplicate relationships, label one combined edge, or separate the routes."
10781
+ suggestion: "Merge duplicate relationships, label one combined edge, or separate the routes.",
10782
+ elementId: source ? elementId(source.props) : void 0,
10783
+ location: source ? { x: source.left, y: source.top, width: source.width, height: source.height } : void 0
9914
10784
  });
9915
10785
  }
9916
10786
  let whitespaceCount = 0;
@@ -9932,7 +10802,9 @@ function analyzeRenderedLayout(nodes, theme) {
9932
10802
  severity: "warning",
9933
10803
  theme,
9934
10804
  message: `Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,
9935
- suggestion: "Reduce the panel height, distribute its contents, or avoid stretching it beside taller content."
10805
+ suggestion: "Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",
10806
+ elementId: elementId(container.props),
10807
+ location: { x: container.left, y: container.top, width: container.width, height: container.height }
9936
10808
  });
9937
10809
  whitespaceCount += 1;
9938
10810
  if (whitespaceCount >= MAX_DIAGNOSTICS_PER_RULE) break;
@@ -9955,7 +10827,8 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
9955
10827
  severity: "warning",
9956
10828
  theme,
9957
10829
  message: `Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,
9958
- suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally."
10830
+ suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
10831
+ location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
9959
10832
  });
9960
10833
  }
9961
10834
  if (verticalDifference > 48 && verticalDifference / height > 0.12) {
@@ -9964,7 +10837,8 @@ function analyzeWhitespaceBalance(bounds, width, height, theme) {
9964
10837
  severity: "warning",
9965
10838
  theme,
9966
10839
  message: `Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,
9967
- suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally."
10840
+ suggestion: "Recenter the composition, crop the canvas, or use the open space intentionally.",
10841
+ location: { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height }
9968
10842
  });
9969
10843
  }
9970
10844
  return diagnostics;
@@ -10014,12 +10888,443 @@ function diagnosticFromMessage(message, severity, theme) {
10014
10888
  };
10015
10889
  }
10016
10890
 
10891
+ // src/check.ts
10892
+ var DEFAULT_WIDTH = 960;
10893
+ var DEFAULT_HEIGHT = 540;
10894
+ var MAX_WIDTH = 1920;
10895
+ var MAX_HEIGHT = 1440;
10896
+ var GROWTH = 1.25;
10897
+ var MAX_AUTO_SIZE_ATTEMPTS = 6;
10898
+ var TRUSTED_COMPONENTS = new Set(Object.values(primitives_exports));
10899
+ var consoleCaptureContext = new AsyncLocalStorage2();
10900
+ var activeConsoleCaptures = 0;
10901
+ var originalConsoleMethods;
10902
+ function formatConsoleArgs(args) {
10903
+ return args.map((value) => {
10904
+ if (value instanceof Error) return value.message;
10905
+ if (typeof value === "string") return value;
10906
+ try {
10907
+ return JSON.stringify(value);
10908
+ } catch {
10909
+ return String(value);
10910
+ }
10911
+ }).join(" ");
10912
+ }
10913
+ function installConsoleCapture() {
10914
+ if (activeConsoleCaptures === 0) {
10915
+ originalConsoleMethods = {
10916
+ debug: console.debug,
10917
+ error: console.error,
10918
+ info: console.info,
10919
+ log: console.log,
10920
+ warn: console.warn
10921
+ };
10922
+ const original = originalConsoleMethods;
10923
+ const intercept = (method, severity) => (...args) => {
10924
+ const messages = consoleCaptureContext.getStore();
10925
+ if (messages) {
10926
+ if (severity) messages.push({ severity, message: formatConsoleArgs(args) });
10927
+ return;
10928
+ }
10929
+ Reflect.apply(original[method], console, args);
10930
+ };
10931
+ console.debug = intercept("debug");
10932
+ console.error = intercept("error", "error");
10933
+ console.info = intercept("info");
10934
+ console.log = intercept("log");
10935
+ console.warn = intercept("warn", "warning");
10936
+ }
10937
+ activeConsoleCaptures += 1;
10938
+ let restored = false;
10939
+ return () => {
10940
+ if (restored) return;
10941
+ restored = true;
10942
+ activeConsoleCaptures -= 1;
10943
+ if (activeConsoleCaptures === 0 && originalConsoleMethods) {
10944
+ console.debug = originalConsoleMethods.debug;
10945
+ console.error = originalConsoleMethods.error;
10946
+ console.info = originalConsoleMethods.info;
10947
+ console.log = originalConsoleMethods.log;
10948
+ console.warn = originalConsoleMethods.warn;
10949
+ originalConsoleMethods = void 0;
10950
+ }
10951
+ };
10952
+ }
10953
+ async function captureConsole(run) {
10954
+ const messages = [];
10955
+ const uninstall = installConsoleCapture();
10956
+ try {
10957
+ const value = await consoleCaptureContext.run(messages, run);
10958
+ return { value, messages };
10959
+ } catch (error) {
10960
+ return { error, messages };
10961
+ } finally {
10962
+ uninstall();
10963
+ }
10964
+ }
10965
+ function normalizeAutoSize(value, defaults) {
10966
+ if (value === true) return { width: true, height: true };
10967
+ if (value === false) return { width: false, height: false };
10968
+ if (value) return { width: value.width ?? defaults.width, height: value.height ?? defaults.height };
10969
+ return defaults;
10970
+ }
10971
+ function overflowEdges(error) {
10972
+ if (!(error instanceof CanvasOverflowError)) return void 0;
10973
+ return Object.entries(error.overflow.edges).filter(([, overflows]) => overflows).map(([edge]) => edge);
10974
+ }
10975
+ function nextDimension(value, maximum) {
10976
+ return Math.min(maximum, Math.ceil(value * GROWTH / 10) * 10);
10977
+ }
10978
+ function nextAutoSize(width, height, autoSize, edges) {
10979
+ const growWidth = autoSize.width && (edges.includes("left") || edges.includes("right"));
10980
+ const growHeight = autoSize.height && (edges.includes("top") || edges.includes("bottom"));
10981
+ const nextWidth = growWidth ? nextDimension(width, MAX_WIDTH) : width;
10982
+ const nextHeight = growHeight ? nextDimension(height, MAX_HEIGHT) : height;
10983
+ if (nextWidth === width && nextHeight === height) return void 0;
10984
+ return { width: nextWidth, height: nextHeight };
10985
+ }
10986
+ async function renderFrame(create, theme, options) {
10987
+ let width = options.width;
10988
+ let height = options.height;
10989
+ for (let attempt = 0; attempt < MAX_AUTO_SIZE_ATTEMPTS; attempt += 1) {
10990
+ try {
10991
+ const layoutNodes = [];
10992
+ const output = await renderToPngWithOutput(create(theme), {
10993
+ width,
10994
+ height,
10995
+ outputPath: options.outputPath,
10996
+ crop: true,
10997
+ scale: 1,
10998
+ background: options.background,
10999
+ onNodeDetected: (node) => layoutNodes.push(node)
11000
+ }, create, theme);
11001
+ return {
11002
+ width,
11003
+ height,
11004
+ outputWidth: output.pixelWidth,
11005
+ outputHeight: output.pixelHeight,
11006
+ logicalOutputWidth: output.width,
11007
+ logicalOutputHeight: output.height,
11008
+ contentBounds: output.contentBounds,
11009
+ layoutNodes
11010
+ };
11011
+ } catch (error) {
11012
+ const edges = overflowEdges(error);
11013
+ const next = edges ? nextAutoSize(width, height, options.autoSize, edges) : void 0;
11014
+ if (!next || attempt === MAX_AUTO_SIZE_ATTEMPTS - 1) throw error;
11015
+ width = next.width;
11016
+ height = next.height;
11017
+ }
11018
+ }
11019
+ return {
11020
+ width,
11021
+ height,
11022
+ outputWidth: width,
11023
+ outputHeight: height,
11024
+ logicalOutputWidth: width,
11025
+ logicalOutputHeight: height,
11026
+ layoutNodes: []
11027
+ };
11028
+ }
11029
+ function counts(themes) {
11030
+ const diagnostics = themes.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
11031
+ return {
11032
+ errors: diagnostics.filter(({ severity }) => severity === "error").length,
11033
+ warnings: diagnostics.filter(({ severity }) => severity === "warning").length,
11034
+ info: diagnostics.filter(({ severity }) => severity === "info").length
11035
+ };
11036
+ }
11037
+ function fails(diagnostics, policy) {
11038
+ if (policy === "never") return false;
11039
+ const threshold = { error: 0, warning: 1, info: 2 }[policy];
11040
+ const levels = { error: 0, warning: 1, info: 2 };
11041
+ return diagnostics.some(({ severity }) => levels[severity] <= threshold);
11042
+ }
11043
+ function messageDiagnostics(messages, theme) {
11044
+ return messages.map(({ message, severity }) => diagnosticFromMessage(message, severity, theme));
11045
+ }
11046
+ function rootBackground(background, theme) {
11047
+ if (background === "theme") return getThemeColors(theme).bg;
11048
+ if (background === "transparent" || background === void 0) return void 0;
11049
+ return background;
11050
+ }
11051
+ async function checkFrame(input, options = {}) {
11052
+ const themes = options.themes ?? ["dark", "light"];
11053
+ if (themes.length === 0) throw new TypeError("checkFrame requires at least one theme");
11054
+ const width = input.width ?? DEFAULT_WIDTH;
11055
+ const height = input.height ?? DEFAULT_HEIGHT;
11056
+ if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
11057
+ throw new TypeError("checkFrame width and height must be positive finite numbers");
11058
+ }
11059
+ const autoSize = normalizeAutoSize(input.autoSize, {
11060
+ width: input.width == null,
11061
+ height: input.height == null
11062
+ });
11063
+ const create = input.create ?? (() => input.scene);
11064
+ const failOn = options.failOn ?? "error";
11065
+ const tempDir = await mkdtemp(join2(tmpdir(), "vizmatic-check-"));
11066
+ const reports = [];
11067
+ try {
11068
+ for (const [themeIndex, theme] of themes.entries()) {
11069
+ const inputDimensions = { width, height };
11070
+ const diagnostics2 = [];
11071
+ const prepared = await captureConsole(async () => {
11072
+ const element = create(theme);
11073
+ const background = rootBackground(options.background, theme);
11074
+ return analyzeContrast(element, theme, TRUSTED_COMPONENTS, background);
11075
+ });
11076
+ diagnostics2.push(...messageDiagnostics(prepared.messages, theme));
11077
+ if (!prepared.value) {
11078
+ diagnostics2.push(diagnosticFromMessage(
11079
+ prepared.error instanceof Error ? prepared.error.message : String(prepared.error),
11080
+ "error",
11081
+ theme
11082
+ ));
11083
+ reports.push({
11084
+ theme,
11085
+ ok: !fails(diagnostics2, failOn),
11086
+ dimensions: { input: inputDimensions },
11087
+ diagnostics: diagnostics2
11088
+ });
11089
+ continue;
11090
+ }
11091
+ diagnostics2.push(...prepared.value);
11092
+ const rendered = await captureConsole(() => renderFrame(create, theme, {
11093
+ width,
11094
+ height,
11095
+ autoSize,
11096
+ background: options.background,
11097
+ outputPath: join2(tempDir, `${themeIndex}.png`)
11098
+ }));
11099
+ diagnostics2.push(...messageDiagnostics(rendered.messages, theme));
11100
+ if (rendered.value) {
11101
+ diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes, theme));
11102
+ if (rendered.value.contentBounds) {
11103
+ diagnostics2.push(...analyzeWhitespaceBalance(
11104
+ rendered.value.contentBounds,
11105
+ rendered.value.logicalOutputWidth,
11106
+ rendered.value.logicalOutputHeight,
11107
+ theme
11108
+ ));
11109
+ }
11110
+ if (rendered.value.width !== width || rendered.value.height !== height) {
11111
+ diagnostics2.push({
11112
+ code: "layout.auto_size",
11113
+ severity: "info",
11114
+ theme,
11115
+ message: `Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,
11116
+ suggestedDimensions: { width: rendered.value.width, height: rendered.value.height }
11117
+ });
11118
+ }
11119
+ reports.push({
11120
+ theme,
11121
+ ok: !fails(diagnostics2, failOn),
11122
+ dimensions: {
11123
+ input: inputDimensions,
11124
+ resolved: { width: rendered.value.width, height: rendered.value.height },
11125
+ output: { width: rendered.value.outputWidth, height: rendered.value.outputHeight }
11126
+ },
11127
+ diagnostics: diagnostics2
11128
+ });
11129
+ continue;
11130
+ }
11131
+ const edges = overflowEdges(rendered.error);
11132
+ if (edges) {
11133
+ const suggestion = await captureConsole(() => renderFrame(create, theme, {
11134
+ width,
11135
+ height,
11136
+ autoSize: { width: true, height: true },
11137
+ background: options.background,
11138
+ outputPath: join2(tempDir, `${themeIndex}-suggestion.png`)
11139
+ }));
11140
+ const suggestedDimensions = suggestion.value ? { width: suggestion.value.width, height: suggestion.value.height } : void 0;
11141
+ diagnostics2.push({
11142
+ code: "layout.overflow",
11143
+ severity: "error",
11144
+ theme,
11145
+ edges,
11146
+ message: rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11147
+ 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.",
11148
+ suggestedDimensions
11149
+ });
11150
+ } else {
11151
+ diagnostics2.push(diagnosticFromMessage(
11152
+ rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11153
+ "error",
11154
+ theme
11155
+ ));
11156
+ }
11157
+ reports.push({
11158
+ theme,
11159
+ ok: !fails(diagnostics2, failOn),
11160
+ dimensions: { input: inputDimensions },
11161
+ diagnostics: diagnostics2
11162
+ });
11163
+ }
11164
+ } finally {
11165
+ await rm(tempDir, { recursive: true, force: true });
11166
+ }
11167
+ const summary = counts(reports);
11168
+ const diagnostics = reports.flatMap(({ diagnostics: themeDiagnostics }) => themeDiagnostics);
11169
+ return {
11170
+ schemaVersion: 1,
11171
+ source: input.source,
11172
+ ok: !fails(diagnostics, failOn),
11173
+ rendered: reports.every(({ dimensions }) => dimensions.resolved !== void 0),
11174
+ autoSize,
11175
+ themes: reports,
11176
+ summary
11177
+ };
11178
+ }
11179
+
11180
+ // src/bare-source.ts
11181
+ function readJsxTag(source, start) {
11182
+ if (source.startsWith("<>", start)) return { closing: false, end: start + 2, selfClosing: false };
11183
+ if (source.startsWith("</>", start)) return { closing: true, end: start + 3, selfClosing: false };
11184
+ const head = source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);
11185
+ if (!head) return void 0;
11186
+ const closing = Boolean(head[1]);
11187
+ let quote;
11188
+ let braces = 0;
11189
+ let escaped = false;
11190
+ for (let index = start + head[0].length; index < source.length; index += 1) {
11191
+ const character = source[index];
11192
+ if (quote) {
11193
+ if (escaped) escaped = false;
11194
+ else if (character === "\\") escaped = true;
11195
+ else if (character === quote) quote = void 0;
11196
+ continue;
11197
+ }
11198
+ if (character === '"' || character === "'" || character === "`") {
11199
+ quote = character;
11200
+ continue;
11201
+ }
11202
+ if (character === "{") {
11203
+ braces += 1;
11204
+ continue;
11205
+ }
11206
+ if (character === "}") {
11207
+ braces = Math.max(0, braces - 1);
11208
+ continue;
11209
+ }
11210
+ if (character !== ">" || braces > 0) continue;
11211
+ const beforeClose = source.slice(start, index).trimEnd();
11212
+ return {
11213
+ closing,
11214
+ end: index + 1,
11215
+ selfClosing: !closing && beforeClose.endsWith("/")
11216
+ };
11217
+ }
11218
+ return void 0;
11219
+ }
11220
+ function skipJsxExpression(source, start) {
11221
+ let depth = 0;
11222
+ let quote;
11223
+ let escaped = false;
11224
+ let blockComment = false;
11225
+ let lineComment = false;
11226
+ for (let index = start; index < source.length; index += 1) {
11227
+ const character = source[index];
11228
+ const next = source[index + 1];
11229
+ if (lineComment) {
11230
+ if (character === "\n") lineComment = false;
11231
+ continue;
11232
+ }
11233
+ if (blockComment) {
11234
+ if (character === "*" && next === "/") {
11235
+ blockComment = false;
11236
+ index += 1;
11237
+ }
11238
+ continue;
11239
+ }
11240
+ if (quote) {
11241
+ if (escaped) escaped = false;
11242
+ else if (character === "\\") escaped = true;
11243
+ else if (character === quote) quote = void 0;
11244
+ continue;
11245
+ }
11246
+ if (character === "/" && next === "/") {
11247
+ lineComment = true;
11248
+ index += 1;
11249
+ continue;
11250
+ }
11251
+ if (character === "/" && next === "*") {
11252
+ blockComment = true;
11253
+ index += 1;
11254
+ continue;
11255
+ }
11256
+ if (character === '"' || character === "'" || character === "`") {
11257
+ quote = character;
11258
+ continue;
11259
+ }
11260
+ if (character === "{") depth += 1;
11261
+ else if (character === "}" && --depth === 0) return index + 1;
11262
+ }
11263
+ return void 0;
11264
+ }
11265
+ function findJsxEnd(source, start) {
11266
+ let depth = 0;
11267
+ for (let index = start; index < source.length; index += 1) {
11268
+ if (source[index] === "{") {
11269
+ const expressionEnd = skipJsxExpression(source, index);
11270
+ if (expressionEnd == null) return void 0;
11271
+ index = expressionEnd - 1;
11272
+ continue;
11273
+ }
11274
+ if (source[index] !== "<") continue;
11275
+ const tag = readJsxTag(source, index);
11276
+ if (!tag) continue;
11277
+ if (tag.closing) depth -= 1;
11278
+ else if (!tag.selfClosing) depth += 1;
11279
+ index = tag.end - 1;
11280
+ if (depth === 0) return tag.end;
11281
+ }
11282
+ return void 0;
11283
+ }
11284
+ function hasOnlyTrailingSyntax(source) {
11285
+ let index = 0;
11286
+ while (index < source.length) {
11287
+ const rest = source.slice(index);
11288
+ const whitespace = rest.match(/^[\s;)]*/)?.[0].length ?? 0;
11289
+ index += whitespace;
11290
+ if (source.startsWith("//", index)) {
11291
+ const newline = source.indexOf("\n", index + 2);
11292
+ index = newline < 0 ? source.length : newline + 1;
11293
+ continue;
11294
+ }
11295
+ if (source.startsWith("/*", index)) {
11296
+ const end = source.indexOf("*/", index + 2);
11297
+ if (end < 0) return false;
11298
+ index = end + 2;
11299
+ continue;
11300
+ }
11301
+ return index >= source.length;
11302
+ }
11303
+ return true;
11304
+ }
11305
+ function extractRootJsx(source) {
11306
+ const body = source.replace(/^(?:\s*\()+\s*/, "");
11307
+ const end = findJsxEnd(body, 0);
11308
+ return (end == null ? body : body.slice(0, end)).trim();
11309
+ }
11310
+ function findBareRootJsxStart(source) {
11311
+ const candidates = source.matchAll(/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);
11312
+ for (const candidate of candidates) {
11313
+ if (candidate.index == null) continue;
11314
+ const lineStart = candidate.index + (candidate[1]?.length ?? 0);
11315
+ const expressionStart = lineStart + (candidate[2]?.length ?? 0);
11316
+ const jsxStart = candidate.index + candidate[0].lastIndexOf(candidate[3] ?? "<");
11317
+ const jsxEnd = findJsxEnd(source, jsxStart);
11318
+ if (jsxEnd != null && hasOnlyTrailingSyntax(source.slice(jsxEnd))) return expressionStart;
11319
+ }
11320
+ return -1;
11321
+ }
11322
+
10017
11323
  // src/cli.ts
10018
11324
  var RENDER_EXTENSIONS = /* @__PURE__ */ new Set([".js", ".jsx", ".mjs", ".ts", ".tsx"]);
10019
11325
  var IMPORT_RESOLUTION_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".json"];
10020
11326
  var DEFAULT_FRAME_WIDTH = 960;
10021
11327
  var DEFAULT_FRAME_HEIGHT = 540;
10022
- var CONTRAST_TRUSTED_COMPONENTS = new Set(Object.values(index_exports));
10023
11328
  var AUTO_SIZE_MAX_WIDTH = 1920;
10024
11329
  var AUTO_SIZE_MAX_HEIGHT = 1440;
10025
11330
  var AUTO_SIZE_GROWTH = 1.25;
@@ -10041,7 +11346,8 @@ var BARE_FRAME_EXTRA_EXPORTS = /* @__PURE__ */ new Set([
10041
11346
  "heatColor",
10042
11347
  "styles",
10043
11348
  "toneGradients",
10044
- "typography"
11349
+ "typography",
11350
+ "wrapWithWatermark"
10045
11351
  ]);
10046
11352
  var BARE_FRAME_EXPORTS = Object.keys(index_exports).filter((name) => /^[A-Za-z_$][\w$]*$/.test(name)).filter((name) => /^[A-Z]/.test(name) || BARE_FRAME_EXTRA_EXPORTS.has(name)).sort();
10047
11353
  var framesNeedingGlobalReact = /* @__PURE__ */ new WeakSet();
@@ -10091,7 +11397,7 @@ async function imageSourceToDataUri(source) {
10091
11397
  }
10092
11398
  async function resolveWatermarkAssets(watermark) {
10093
11399
  if (watermark == null || typeof watermark !== "object") return watermark;
10094
- if (isValidElement2(watermark) || !("image" in watermark) || !watermark.image) return watermark;
11400
+ if (isValidElement3(watermark) || !("image" in watermark) || !watermark.image) return watermark;
10095
11401
  if (typeof watermark.image === "string") {
10096
11402
  return {
10097
11403
  ...watermark,
@@ -10108,9 +11414,9 @@ async function resolveWatermarkAssets(watermark) {
10108
11414
  }
10109
11415
  function resolveSelfEntry() {
10110
11416
  const moduleDir = dirname3(fileURLToPath2(import.meta.url));
10111
- const bundledEntry = join2(moduleDir, "index.cjs");
11417
+ const bundledEntry = join3(moduleDir, "index.cjs");
10112
11418
  if (existsSync2(bundledEntry)) return bundledEntry;
10113
- const sourceEntry = join2(moduleDir, "index.ts");
11419
+ const sourceEntry = join3(moduleDir, "index.ts");
10114
11420
  if (existsSync2(sourceEntry)) return sourceEntry;
10115
11421
  try {
10116
11422
  return cliRequire.resolve("vizmatic");
@@ -10120,9 +11426,9 @@ function resolveSelfEntry() {
10120
11426
  }
10121
11427
  function resolveSelfImportEntry() {
10122
11428
  const moduleDir = dirname3(fileURLToPath2(import.meta.url));
10123
- const bundledEntry = join2(moduleDir, "index.js");
11429
+ const bundledEntry = join3(moduleDir, "index.js");
10124
11430
  if (existsSync2(bundledEntry)) return bundledEntry;
10125
- const sourceEntry = join2(moduleDir, "index.ts");
11431
+ const sourceEntry = join3(moduleDir, "index.ts");
10126
11432
  if (existsSync2(sourceEntry)) return sourceEntry;
10127
11433
  return void 0;
10128
11434
  }
@@ -10305,7 +11611,7 @@ function resolveRelativeImportSpecifier(frameDir, specifier) {
10305
11611
  if (existsSync2(candidate)) return candidate;
10306
11612
  }
10307
11613
  for (const extension of IMPORT_RESOLUTION_EXTENSIONS) {
10308
- const candidate = join2(absolute, `index${extension}`);
11614
+ const candidate = join3(absolute, `index${extension}`);
10309
11615
  if (existsSync2(candidate)) return candidate;
10310
11616
  }
10311
11617
  return absolute;
@@ -10355,7 +11661,7 @@ function bareFrameExportsForSource(source) {
10355
11661
  return BARE_FRAME_EXPORTS.filter((name) => {
10356
11662
  if (name === "getThemeColors") return true;
10357
11663
  const escapedName = escapeRegExp(name);
10358
- if (/^[A-Z]/.test(name)) return new RegExp(`<\\/?${escapedName}(?:\\s|>|/)`).test(source);
11664
+ if (/^[A-Z]/.test(name)) return new RegExp(`<\\/?${escapedName}(?:\\s|>|/)|\\b${escapedName}\\s*\\(`).test(source);
10359
11665
  return new RegExp(`\\b${escapedName}\\b`).test(source);
10360
11666
  });
10361
11667
  }
@@ -10367,6 +11673,8 @@ ${specifiers}
10367
11673
  }
10368
11674
  function buildAutoImportDeclarations(names) {
10369
11675
  return names.map((name) => {
11676
+ if (name === "Watermark" || name === "MathText") return `const ${name} = ${bareFrameAlias(name)};`;
11677
+ if (name === "DotPoint" || name === "DashedLine") return `const ${name} = __withTheme(${bareFrameAlias(name)}, true);`;
10370
11678
  if (/^[A-Z]/.test(name)) return `const ${name} = __withTheme(${bareFrameAlias(name)});`;
10371
11679
  return `const ${name} = ${bareFrameAlias(name)};`;
10372
11680
  }).join("\n");
@@ -10448,9 +11756,12 @@ ${buildAutoImportStatement(autoImports)}
10448
11756
  ${imports.join("\n")}
10449
11757
 
10450
11758
  let __theme = __Vizmatic_getThemeColors('dark', ${JSON.stringify(preset)})
10451
- function __withTheme(Component) {
11759
+ function __withTheme(Component, returnsArray = false) {
10452
11760
  function VizmaticAutoTheme(props) {
10453
- return React.createElement(Component, props?.c ? props : { ...props, c: __theme })
11761
+ const themedProps = props?.c ? props : { ...props, c: __theme }
11762
+ return returnsArray
11763
+ ? React.createElement(React.Fragment, null, Component(themedProps))
11764
+ : React.createElement(Component, themedProps)
10454
11765
  }
10455
11766
  VizmaticAutoTheme.__vizmaticPrimitive = true
10456
11767
  return VizmaticAutoTheme
@@ -10485,9 +11796,9 @@ async function importBareFrame(filePath, source) {
10485
11796
  source ??= await readFile2(filePath, "utf8");
10486
11797
  const moduleSource = buildBareFrameModule(filePath, source);
10487
11798
  if (!moduleSource) return void 0;
10488
- const tempDir = await mkdtemp(join2(tmpdir(), "vizmatic-frame-"));
10489
- const tempPath = join2(tempDir, `${basename(filePath).replace(/\.[^.]+$/, "")}.generated.tsx`);
10490
- await writeFile3(join2(tempDir, "package.json"), '{"type":"module"}\n');
11799
+ const tempDir = await mkdtemp2(join3(tmpdir2(), "vizmatic-frame-"));
11800
+ const tempPath = join3(tempDir, `${basename(filePath).replace(/\.[^.]+$/, "")}.generated.tsx`);
11801
+ await writeFile3(join3(tempDir, "package.json"), '{"type":"module"}\n');
10491
11802
  await writeFile3(tempPath, `${moduleSource}
10492
11803
  `);
10493
11804
  try {
@@ -10495,18 +11806,18 @@ async function importBareFrame(filePath, source) {
10495
11806
  framesNeedingGlobalReact.add(mod);
10496
11807
  return mod;
10497
11808
  } finally {
10498
- await rm(tempDir, { recursive: true, force: true });
11809
+ await rm2(tempDir, { recursive: true, force: true });
10499
11810
  }
10500
11811
  }
10501
11812
  async function importRewrittenFrame(filePath, source) {
10502
11813
  const extension = extname(filePath);
10503
11814
  const stem = basename(filePath, extension);
10504
- const tempPath = join2(dirname3(filePath), `.${stem}.vizmatic-${randomUUID()}${extension}`);
11815
+ const tempPath = join3(dirname3(filePath), `.${stem}.vizmatic-${randomUUID()}${extension}`);
10505
11816
  await writeFile3(tempPath, rewriteFrameModuleImports(source));
10506
11817
  try {
10507
11818
  return await importWithTsx(pathToFileURL(tempPath).href);
10508
11819
  } finally {
10509
- await rm(tempPath, { force: true });
11820
+ await rm2(tempPath, { force: true });
10510
11821
  }
10511
11822
  }
10512
11823
  function parseRenderArgs(argv) {
@@ -10521,7 +11832,7 @@ function parseRenderArgs(argv) {
10521
11832
  let background;
10522
11833
  function mutableWatermark() {
10523
11834
  if (!watermarkOptions) {
10524
- watermarkOptions = typeof watermark === "object" && watermark !== null && !isValidElement2(watermark) ? { ...watermark } : {};
11835
+ watermarkOptions = typeof watermark === "object" && watermark !== null && !isValidElement3(watermark) ? { ...watermark } : {};
10525
11836
  if (typeof watermark === "string") watermarkOptions.text = watermark;
10526
11837
  watermark = watermarkOptions;
10527
11838
  }
@@ -10657,7 +11968,7 @@ async function findFrameFiles(inputs) {
10657
11968
  return;
10658
11969
  }
10659
11970
  for (const entry of entries) {
10660
- const next = join2(resolved, entry.name);
11971
+ const next = join3(resolved, entry.name);
10661
11972
  if (entry.isDirectory()) {
10662
11973
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name.startsWith("_")) continue;
10663
11974
  await walk(next);
@@ -10751,7 +12062,7 @@ async function importFrame(filePath) {
10751
12062
  }
10752
12063
  throw loadError ?? new Error(`Unable to load frame ${filePath}`);
10753
12064
  }
10754
- function normalizeAutoSize(value, defaults) {
12065
+ function normalizeAutoSize2(value, defaults) {
10755
12066
  if (value === true) return { width: true, height: true };
10756
12067
  if (value === false) return { width: false, height: false };
10757
12068
  if (value && typeof value === "object") {
@@ -10763,13 +12074,13 @@ function normalizeAutoSize(value, defaults) {
10763
12074
  return defaults;
10764
12075
  }
10765
12076
  function normalizeFrameModule(mod) {
10766
- const defaultObject = typeof mod.default === "object" && mod.default && !isValidElement2(mod.default) && ("create" in mod.default || "createAnimation" in mod.default || "default" in mod.default) ? mod.default : void 0;
12077
+ const defaultObject = typeof mod.default === "object" && mod.default && !isValidElement3(mod.default) && ("create" in mod.default || "createAnimation" in mod.default || "default" in mod.default) ? mod.default : void 0;
10767
12078
  const hasAutoSizeSetting = mod.autoSize != null || mod.__vizmaticAutoSize != null;
10768
12079
  const hasWidth = mod.width != null || defaultObject?.width != null;
10769
12080
  const hasHeight = mod.height != null || defaultObject?.height != null;
10770
12081
  const width = mod.width ?? defaultObject?.width ?? DEFAULT_FRAME_WIDTH;
10771
12082
  const height = mod.height ?? defaultObject?.height ?? DEFAULT_FRAME_HEIGHT;
10772
- const autoSize = normalizeAutoSize(mod.autoSize ?? mod.__vizmaticAutoSize, {
12083
+ const autoSize = normalizeAutoSize2(mod.autoSize ?? mod.__vizmaticAutoSize, {
10773
12084
  width: !hasWidth || !hasAutoSizeSetting && width === DEFAULT_FRAME_WIDTH,
10774
12085
  height: !hasHeight || !hasAutoSizeSetting && height === DEFAULT_FRAME_HEIGHT
10775
12086
  });
@@ -10794,7 +12105,7 @@ function frameElement(mod, theme) {
10794
12105
  throw new Error("frame module must export create(theme) or default React element");
10795
12106
  });
10796
12107
  }
10797
- function overflowEdges(error) {
12108
+ function overflowEdges2(error) {
10798
12109
  if (error instanceof CanvasOverflowError) {
10799
12110
  return Object.entries(error.overflow.edges).filter(([, overflows]) => overflows).map(([edge]) => edge);
10800
12111
  }
@@ -10810,7 +12121,7 @@ function overflowEdges(error) {
10810
12121
  function growDimension(value, max) {
10811
12122
  return Math.min(max, Math.ceil(value * AUTO_SIZE_GROWTH / 10) * 10);
10812
12123
  }
10813
- function nextAutoSize(width, height, autoSize, edges) {
12124
+ function nextAutoSize2(width, height, autoSize, edges) {
10814
12125
  const growWidth = autoSize.width && (edges.includes("left") || edges.includes("right"));
10815
12126
  const growHeight = autoSize.height && (edges.includes("top") || edges.includes("bottom"));
10816
12127
  const nextWidth = growWidth ? growDimension(width, AUTO_SIZE_MAX_WIDTH) : width;
@@ -10843,8 +12154,8 @@ async function renderFrameToPng(mod, theme, options) {
10843
12154
  layoutNodes
10844
12155
  };
10845
12156
  } catch (error) {
10846
- const edges = overflowEdges(error);
10847
- const next = edges ? nextAutoSize(width, height, mod.autoSize, edges) : void 0;
12157
+ const edges = overflowEdges2(error);
12158
+ const next = edges ? nextAutoSize2(width, height, mod.autoSize, edges) : void 0;
10848
12159
  if (!next || attempt === AUTO_SIZE_ATTEMPTS - 1) throw error;
10849
12160
  width = next.width;
10850
12161
  height = next.height;
@@ -10873,7 +12184,7 @@ async function renderCommand(argv) {
10873
12184
  let outputHeight = 0;
10874
12185
  for (const theme of args.themes) {
10875
12186
  const outputName = `${name}_${theme}.png`;
10876
- const outputPath = join2(args.outDir, outputName);
12187
+ const outputPath = join3(args.outDir, outputName);
10877
12188
  const rendered = await renderFrameToPng(mod, theme, {
10878
12189
  width: renderWidth,
10879
12190
  height: renderHeight,
@@ -10907,10 +12218,10 @@ async function renderCommand(argv) {
10907
12218
  outputDetails
10908
12219
  });
10909
12220
  }
10910
- await writeFile3(join2(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
12221
+ await writeFile3(join3(args.outDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
10911
12222
  `);
10912
12223
  }
10913
- function formatConsoleArgs(args) {
12224
+ function formatConsoleArgs2(args) {
10914
12225
  return args.map((value) => {
10915
12226
  if (value instanceof Error) return value.message;
10916
12227
  if (typeof value === "string") return value;
@@ -10921,7 +12232,7 @@ function formatConsoleArgs(args) {
10921
12232
  }
10922
12233
  }).join(" ");
10923
12234
  }
10924
- async function captureConsole(run) {
12235
+ async function captureConsole2(run) {
10925
12236
  const messages = [];
10926
12237
  const original = {
10927
12238
  debug: console.debug,
@@ -10933,8 +12244,8 @@ async function captureConsole(run) {
10933
12244
  console.debug = () => void 0;
10934
12245
  console.log = () => void 0;
10935
12246
  console.info = () => void 0;
10936
- console.warn = (...args) => messages.push({ severity: "warning", message: formatConsoleArgs(args) });
10937
- console.error = (...args) => messages.push({ severity: "error", message: formatConsoleArgs(args) });
12247
+ console.warn = (...args) => messages.push({ severity: "warning", message: formatConsoleArgs2(args) });
12248
+ console.error = (...args) => messages.push({ severity: "error", message: formatConsoleArgs2(args) });
10938
12249
  try {
10939
12250
  return { value: await run(), messages };
10940
12251
  } catch (error) {
@@ -11010,132 +12321,42 @@ async function checkCommand(argv) {
11010
12321
  async function checkCommandWithArgs(args) {
11011
12322
  const files = await findFrameFiles(args.inputs);
11012
12323
  if (files.length === 0) throw new Error("no frame files found");
11013
- const tempDir = await mkdtemp(join2(tmpdir(), "vizmatic-check-"));
11014
12324
  const reports = [];
11015
- try {
11016
- for (const [fileIndex, file] of files.entries()) {
11017
- const source = relative(process.cwd(), file);
11018
- const imported = await captureConsole(() => importFrame(file));
11019
- const diagnostics = imported.messages.map(
11020
- (message) => diagnosticFromMessage(message.message, message.severity)
11021
- );
11022
- if (!imported.value) {
11023
- diagnostics.push({
11024
- code: "frame.load_error",
11025
- severity: "error",
11026
- message: imported.error instanceof Error ? imported.error.message : String(imported.error)
11027
- });
11028
- reports.push({ source, ok: false, diagnostics, themes: [] });
11029
- continue;
11030
- }
11031
- const mod = normalizeFrameModule(imported.value);
11032
- const themes = [];
11033
- for (const [themeIndex, theme] of args.themes.entries()) {
11034
- const input = { width: mod.width, height: mod.height };
11035
- const themeDiagnostics = [];
11036
- const prepared = await captureConsole(async () => {
11037
- const element = frameElement(mod, theme);
11038
- const rootBackground = args.background === "theme" ? getThemeColors(theme).bg : args.background === "transparent" ? void 0 : args.background;
11039
- return analyzeContrast(element, theme, CONTRAST_TRUSTED_COMPONENTS, rootBackground);
11040
- });
11041
- themeDiagnostics.push(...prepared.messages.map(
11042
- (message) => diagnosticFromMessage(message.message, message.severity, theme)
11043
- ));
11044
- if (!prepared.value) {
11045
- themeDiagnostics.push(diagnosticFromMessage(
11046
- prepared.error instanceof Error ? prepared.error.message : String(prepared.error),
11047
- "error",
11048
- theme
11049
- ));
11050
- themes.push({ theme, ok: false, dimensions: { input }, diagnostics: themeDiagnostics });
11051
- continue;
11052
- }
11053
- themeDiagnostics.push(...prepared.value);
11054
- const outputPath = join2(tempDir, `${fileIndex}-${themeIndex}.png`);
11055
- const rendered = await captureConsole(() => renderFrameToPng(mod, theme, {
11056
- ...input,
11057
- outputPath,
11058
- crop: true,
11059
- scale: 1,
11060
- background: args.background,
11061
- inspectLayout: true
11062
- }));
11063
- themeDiagnostics.push(...rendered.messages.map(
11064
- (message) => diagnosticFromMessage(message.message, message.severity, theme)
11065
- ));
11066
- if (rendered.value) {
11067
- themeDiagnostics.push(...analyzeRenderedLayout(rendered.value.layoutNodes, theme));
11068
- if (rendered.value.contentBounds) {
11069
- themeDiagnostics.push(...analyzeWhitespaceBalance(
11070
- rendered.value.contentBounds,
11071
- rendered.value.logicalOutputWidth,
11072
- rendered.value.logicalOutputHeight,
11073
- theme
11074
- ));
11075
- }
11076
- if (rendered.value.width !== input.width || rendered.value.height !== input.height) {
11077
- themeDiagnostics.push({
11078
- code: "layout.auto_size",
11079
- severity: "info",
11080
- theme,
11081
- message: `Canvas auto-sized from ${input.width}\xD7${input.height} to ${rendered.value.width}\xD7${rendered.value.height}.`,
11082
- suggestedDimensions: {
11083
- width: rendered.value.width,
11084
- height: rendered.value.height
11085
- }
11086
- });
11087
- }
11088
- themes.push({
11089
- theme,
11090
- ok: !themeDiagnostics.some((diagnostic) => diagnostic.severity === "error"),
11091
- dimensions: {
11092
- input,
11093
- resolved: { width: rendered.value.width, height: rendered.value.height },
11094
- output: { width: rendered.value.outputWidth, height: rendered.value.outputHeight }
11095
- },
11096
- diagnostics: themeDiagnostics
11097
- });
11098
- continue;
11099
- }
11100
- const edges = overflowEdges(rendered.error);
11101
- if (edges) {
11102
- const suggestionMod = { ...mod, autoSize: { width: true, height: true } };
11103
- const suggestion = await captureConsole(() => renderFrameToPng(suggestionMod, theme, {
11104
- ...input,
11105
- outputPath: join2(tempDir, `${fileIndex}-${themeIndex}-suggestion.png`),
11106
- crop: true,
11107
- scale: 1,
11108
- background: args.background
11109
- }));
11110
- const suggestedDimensions = suggestion.value ? { width: suggestion.value.width, height: suggestion.value.height } : void 0;
11111
- themeDiagnostics.push({
11112
- code: "layout.overflow",
11113
- severity: "error",
11114
- theme,
11115
- edges,
11116
- message: rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11117
- 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.",
11118
- suggestedDimensions
11119
- });
11120
- } else {
11121
- themeDiagnostics.push(diagnosticFromMessage(
11122
- rendered.error instanceof Error ? rendered.error.message : String(rendered.error),
11123
- "error",
11124
- theme
11125
- ));
11126
- }
11127
- themes.push({
11128
- theme,
11129
- ok: false,
11130
- dimensions: { input },
11131
- diagnostics: themeDiagnostics
11132
- });
11133
- }
11134
- const ok = !diagnostics.some((diagnostic) => diagnostic.severity === "error") && themes.every((theme) => theme.ok);
11135
- reports.push({ source, ok, autoSize: mod.autoSize, diagnostics, themes });
12325
+ for (const file of files) {
12326
+ const source = relative(process.cwd(), file);
12327
+ const imported = await captureConsole2(() => importFrame(file));
12328
+ const diagnostics = imported.messages.map(
12329
+ (message) => diagnosticFromMessage(message.message, message.severity)
12330
+ );
12331
+ if (!imported.value) {
12332
+ diagnostics.push({
12333
+ code: "frame.load_error",
12334
+ severity: "error",
12335
+ message: imported.error instanceof Error ? imported.error.message : String(imported.error)
12336
+ });
12337
+ reports.push({ source, ok: false, diagnostics, themes: [] });
12338
+ continue;
11136
12339
  }
11137
- } finally {
11138
- await rm(tempDir, { recursive: true, force: true });
12340
+ const mod = normalizeFrameModule(imported.value);
12341
+ const checked = await checkFrame({
12342
+ source,
12343
+ width: mod.width,
12344
+ height: mod.height,
12345
+ autoSize: mod.autoSize,
12346
+ create: (theme) => frameElement(mod, theme)
12347
+ }, {
12348
+ themes: args.themes,
12349
+ background: args.background,
12350
+ failOn: "error"
12351
+ });
12352
+ const ok = !diagnostics.some((diagnostic) => diagnostic.severity === "error") && checked.themes.every((theme) => theme.ok);
12353
+ reports.push({
12354
+ source,
12355
+ ok,
12356
+ autoSize: mod.autoSize,
12357
+ diagnostics,
12358
+ themes: checked.themes
12359
+ });
11139
12360
  }
11140
12361
  const summary = checkDiagnosticCounts(reports);
11141
12362
  const report = {
@@ -11178,7 +12399,7 @@ async function gifCommand(argv) {
11178
12399
  }
11179
12400
  for (const theme of args.themes) {
11180
12401
  const outputName = `${name}_${theme}.gif`;
11181
- const outputPath = join2(args.outDir, outputName);
12402
+ const outputPath = join3(args.outDir, outputName);
11182
12403
  const commonOptions = {
11183
12404
  width: mod.width,
11184
12405
  height: mod.height,
@@ -11219,7 +12440,7 @@ async function gifCommand(argv) {
11219
12440
  outputDetails
11220
12441
  });
11221
12442
  }
11222
- await writeFile3(join2(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
12443
+ await writeFile3(join3(args.outDir, "gif-manifest.json"), `${JSON.stringify(manifest, null, 2)}
11223
12444
  `);
11224
12445
  }
11225
12446
  async function main() {