vizmatic 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};import{existsSync as existsSync2}from"fs";import{mkdir as mkdir3,mkdtemp as mkdtemp2,readFile as readFile2,readdir,rm as rm2,writeFile as writeFile3}from"fs/promises";import{randomUUID}from"crypto";import{createRequire,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename,dirname as dirname3,extname,isAbsolute,join as join3,relative,resolve,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React15,{isValidElement as isValidElement4}from"react";import{Resvg as Resvg3}from"@resvg/resvg-js";var index_exports={};__export(index_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AxisPlot:()=>AxisPlot,Badge:()=>Badge,BadgePill:()=>BadgePill,BarChart:()=>BarChart,Board:()=>Board,Box:()=>Box,CANVAS_ITEM_COMPONENT:()=>CANVAS_ITEM_COMPONENT,CHECK_DIAGNOSTIC_CODES:()=>CHECK_DIAGNOSTIC_CODES,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,CanvasOverflowError:()=>CanvasOverflowError,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,EquationCard:()=>EquationCard,Flow:()=>Flow,FlowArrow:()=>FlowArrow,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MiniBarChart:()=>MiniBarChart,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,Row:()=>Row,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TextLabel:()=>TextLabel,Tile:()=>Tile,TileGrid:()=>TileGrid,TiledMatrix:()=>TiledMatrix,Timeline:()=>Timeline,TitleBar:()=>TitleBar,ToneStrip:()=>ToneStrip,TransformerTopology:()=>TransformerTopology,TreeDiagram:()=>TreeDiagram,ValuePill:()=>ValuePill,VectorArrow:()=>VectorArrow,VectorSegment:()=>VectorSegment,Watermark:()=>Watermark,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,canvas:()=>canvas,checkFrame:()=>checkFrame,colors:()=>colors,createPlotArea:()=>createPlotArea,cropPixels:()=>cropPixels,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectOverflow:()=>detectOverflow,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,keyframe:()=>keyframe,loadAdditionalAsset:()=>loadAdditionalAsset,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,sampleAnimation:()=>sampleAnimation,sampleAnimationFrames:()=>sampleAnimationFrames,styles:()=>styles,toneGradients:()=>toneGradients,tween:()=>tween,typography:()=>typography,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import parseCssColor from"parse-css-color";var darkColors={bg:"#151620",bgCard:"#1a1b26",bgCardAlt:"#1e2030",bgHover:"#24253a",bgSubtle:"#151620",primary:"#7c3aed",primaryLight:"#a78bfa",primaryDark:"#6d28d9",secondary:"#2563eb",secondaryLight:"#60a5fa",secondaryDark:"#1d4ed8",positive:"#059669",positiveLight:"#34d399",positiveDark:"#047857",warning:"#d97706",warningLight:"#fbbf24",warningDark:"#b45309",critical:"#dc2626",criticalLight:"#f87171",criticalDark:"#b91c1c",info:"#06b6d4",infoLight:"#22d3ee",infoDark:"#0891b2",accent:"#f472b6",accentLight:"#f9a8d4",neutral:"#334155",neutralLight:"#475569",neutralDark:"#1e293b",textPrimary:"#f1f5f9",textSecondary:"#94a3b8",textMuted:"#8493a8",textOnColor:"#ffffff",border:"#334155",borderSubtle:"#1e293b",borderLight:"#475569",shadow:"rgba(0, 0, 0, 0.24)"};var lightColors={bg:"#f5f7fa",bgCard:"#f8fafc",bgCardAlt:"#f1f5f9",bgHover:"#e2e8f0",bgSubtle:"#f5f7fa",primary:"#7c3aed",primaryLight:"#8b5cf6",primaryDark:"#6d28d9",secondary:"#2563eb",secondaryLight:"#3b82f6",secondaryDark:"#1d4ed8",positive:"#059669",positiveLight:"#10b981",positiveDark:"#047857",warning:"#d97706",warningLight:"#f59e0b",warningDark:"#b45309",critical:"#dc2626",criticalLight:"#ef4444",criticalDark:"#b91c1c",info:"#0891b2",infoLight:"#06b6d4",infoDark:"#0e7490",accent:"#ec4899",accentLight:"#f472b6",neutral:"#cbd5e1",neutralLight:"#94a3b8",neutralDark:"#e2e8f0",textPrimary:"#0f172a",textSecondary:"#475569",textMuted:"#5b677a",textOnColor:"#ffffff",border:"#e2e8f0",borderSubtle:"#e2e8f0",borderLight:"#cbd5e1",shadow:"rgba(15, 23, 42, 0.12)"};var defaultStyleTokens={preset:"default",fontSans:"Inter",fontMono:"JetBrains Mono"};var engineeringColors={...lightColors,bg:"#f4f4f5",bgCard:"#ffffff",bgCardAlt:"#ececee",bgHover:"#e4e4e7",bgSubtle:"#eeeeef",primary:"#632ca6",primaryLight:"#6d28d9",primaryDark:"#4c1d95",secondary:"#124fc7",secondaryLight:"#1556d1",secondaryDark:"#123d96",positive:"#087a55",positiveLight:"#0a8060",positiveDark:"#05543c",warning:"#c96c00",warningLight:"#d97800",warningDark:"#9a4f00",critical:"#b83232",criticalLight:"#c43d3d",criticalDark:"#8f2626",info:"#0b7185",infoLight:"#0d7d92",infoDark:"#075565",accent:"#a83c76",accentLight:"#b74583",neutral:"#52525b",neutralLight:"#71717a",neutralDark:"#3f3f46",textPrimary:"#101012",textSecondary:"#3f3f46",textMuted:"#68686f",textOnColor:"#ffffff",border:"#3f3f46",borderSubtle:"#d4d4d8",borderLight:"#a1a1aa",shadow:"rgba(0, 0, 0, 0)"};function getThemeColors(mode,preset="default"){if(preset==="engineering"){return{...engineeringColors,preset,fontSans:"Inter",fontMono:"JetBrains Mono"}}return{...mode==="light"?lightColors:darkColors,...defaultStyleTokens}}var colors={...darkColors,...defaultStyleTokens};var gradients={purple:"linear-gradient(135deg, #7c3aed, #a855f7)",blue:"linear-gradient(135deg, #2563eb, #60a5fa)",green:"linear-gradient(135deg, #059669, #34d399)",warm:"linear-gradient(135deg, #f59e0b, #ef4444)",cyan:"linear-gradient(135deg, #06b6d4, #22d3ee)",pink:"linear-gradient(135deg, #ec4899, #f472b6)",sunset:"linear-gradient(135deg, #f97316, #db2777)",ocean:"linear-gradient(135deg, #0284c7, #7c3aed)",dark:"linear-gradient(180deg, #0f1117, #1a1b26)"};var toneGradients={blue:gradients.blue,purple:gradients.purple,green:gradients.green,warm:gradients.warm,cyan:gradients.cyan,pink:gradients.pink,red:gradients.warm,critical:gradients.warm,neutral:gradients.dark,sunset:gradients.sunset,ocean:gradients.ocean,dark:gradients.dark};function getToneGradient(tone){return toneGradients[tone]}function getToneColor(tone,c){return{blue:c.secondaryLight,purple:c.primaryLight,green:c.positiveLight,warm:c.warningLight,cyan:c.infoLight,pink:c.accentLight,red:c.criticalLight,critical:c.criticalLight,neutral:c.textSecondary,sunset:c.warningLight,ocean:c.infoLight,dark:c.textSecondary}[tone]}function getReadableToneColor(tone,c,background=c.bgCard,backdrop=c.bgCard){const semanticColor={blue:"secondary",purple:"primary",green:"positive",warm:"warning",cyan:"info",pink:"accent",red:"critical",critical:"critical",neutral:"neutral",sunset:"warning",ocean:"info",dark:"neutral"};const color=getReadableColor(semanticColor[tone],c);return colorContrast(color,background,backdrop)>=4.5?color:getReadableTextColor(background,c,backdrop)}function getToneFill(tone,c){if(c.preset!=="engineering")return`${getToneColor(tone,c)}16`;return{blue:"#cddcfa",purple:"#dfcff8",green:"#d5ede4",warm:"#fde7ce",cyan:"#d7edf1",pink:"#f3d9e7",red:"#f4d7d7",critical:"#f4d7d7",neutral:"#e4e4e7",sunset:"#fde1d6",ocean:"#d8e2f6",dark:"#dedee2"}[tone]}var typography={title:{fontSize:28,fontWeight:700,fontFamily:"Inter"},subtitle:{fontSize:20,fontWeight:600,fontFamily:"Inter"},label:{fontSize:16,fontWeight:600,fontFamily:"Inter"},body:{fontSize:14,fontWeight:400,fontFamily:"Inter"},small:{fontSize:12,fontWeight:500,fontFamily:"Inter"},tiny:{fontSize:11,fontWeight:500,fontFamily:"Inter"},code:{fontSize:13,fontWeight:400,fontFamily:"JetBrains Mono"},annotation:{fontSize:12,fontWeight:500,fontFamily:"Inter",fontStyle:"italic"}};var canvas={standard:{width:800,height:500},wide:{width:1e3,height:400},square:{width:600,height:600},tall:{width:600,height:800}};function getStyles(c){return{canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:c.bg,fontFamily:c.fontSans,padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:c.bgCard,borderRadius:8,border:`1px solid ${c.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}}}var styles={canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:colors.bg,fontFamily:"Inter",padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:colors.bgCard,borderRadius:8,border:`1px solid ${colors.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}};function getColor(name,c){if(c)return c[name];return colors[name]}function getReadableColor(name,c){const variants={primary:[c.primaryLight,c.primary,c.primaryDark],secondary:[c.secondaryLight,c.secondary,c.secondaryDark],positive:[c.positiveLight,c.positive,c.positiveDark],warning:[c.warningLight,c.warning,c.warningDark],critical:[c.criticalLight,c.critical,c.criticalDark],info:[c.infoLight,c.info,c.infoDark],accent:[c.accentLight,c.accent,"#be185d"],neutral:[c.textSecondary,c.neutralLight,c.neutral,c.neutralDark]};return variants[name].reduce((best,candidate)=>colorContrast(candidate,c.bgCard)>colorContrast(best,c.bgCard)?candidate:best)}function parseColor(color){const parsed=parseCssColor(color);if(!parsed||parsed.values.length<3)return void 0;if(parsed.type!=="hsl"){return{channels:[parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0],alpha:parsed.alpha}}const hue=((parsed.values[0]??0)%360+360)%360;const saturation=(parsed.values[1]??0)/100;const lightness=(parsed.values[2]??0)/100;const chroma=(1-Math.abs(2*lightness-1))*saturation;const segment=hue/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=lightness-chroma/2;return{channels:channels.map(channel=>Math.round((channel+offset)*255)),alpha:parsed.alpha}}function colorLuminance(color,backdrop){const parsed=parseColor(color);if(!parsed)return void 0;let channels=parsed.channels;if(parsed.alpha<1){const backdropColor=backdrop?parseColor(backdrop):void 0;if(!backdropColor)return void 0;channels=channels.map((channel,index)=>Math.round(channel*parsed.alpha+backdropColor.channels[index]*(1-parsed.alpha)))}const[r,g,b]=channels.map(channel=>{const normalized=channel/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4});return .2126*r+.7152*g+.0722*b}function colorContrast(left,right,rightBackdrop){const leftLuminance=colorLuminance(left);const rightLuminance=colorLuminance(right,rightBackdrop);if(leftLuminance==null||rightLuminance==null)return 0;return(Math.max(leftLuminance,rightLuminance)+.05)/(Math.min(leftLuminance,rightLuminance)+.05)}function getReadableTextColor(background,c,backdrop=c.bgCard){if(colorLuminance(background,backdrop)==null)return c.textPrimary;const candidates=[c.textPrimary,c.textOnColor,c.bg,"#000000"];const readable=candidates.find(candidate=>colorContrast(candidate,background,backdrop)>=4.5);if(readable)return readable;return candidates.reduce((best,candidate)=>colorContrast(candidate,background,backdrop)>colorContrast(best,background,backdrop)?candidate:best)}function getGradient(name){const map={primary:gradients.purple,secondary:gradients.blue,positive:gradients.green,warning:gradients.warm,critical:gradients.warm,info:gradients.cyan,accent:gradients.pink,neutral:gradients.dark};return map[name]}function heatColor(value){const v=Math.max(0,Math.min(1,value));if(v<.25){const t=v/.25;return lerpColor("#1e293b","#0891b2",t)}else if(v<.5){const t=(v-.25)/.25;return lerpColor("#0891b2","#059669",t)}else if(v<.75){const t=(v-.5)/.25;return lerpColor("#059669","#d97706",t)}else{const t=(v-.75)/.25;return lerpColor("#d97706","#dc2626",t)}}function lerpColor(a,b,t){const ah=parseInt(a.slice(1),16);const bh=parseInt(b.slice(1),16);const ar=ah>>16&255,ag=ah>>8&255,ab=ah&255;const br=bh>>16&255,bg=bh>>8&255,bb=bh&255;const rr=Math.round(ar+(br-ar)*t);const rg=Math.round(ag+(bg-ag)*t);const rb=Math.round(ab+(bb-ab)*t);return`#${(rr<<16|rg<<8|rb).toString(16).padStart(6,"0")}`}var primitives_exports={};__export(primitives_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AxisPlot:()=>AxisPlot,Badge:()=>Badge,BadgePill:()=>BadgePill,BarChart:()=>BarChart,Board:()=>Board,Box:()=>Box,CANVAS_ITEM_COMPONENT:()=>CANVAS_ITEM_COMPONENT,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,EquationCard:()=>EquationCard,Flow:()=>Flow,FlowArrow:()=>FlowArrow,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MiniBarChart:()=>MiniBarChart,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,Row:()=>Row,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TextLabel:()=>TextLabel,Tile:()=>Tile,TileGrid:()=>TileGrid,TiledMatrix:()=>TiledMatrix,Timeline:()=>Timeline,TitleBar:()=>TitleBar,ToneStrip:()=>ToneStrip,TransformerTopology:()=>TransformerTopology,TreeDiagram:()=>TreeDiagram,ValuePill:()=>ValuePill,VectorArrow:()=>VectorArrow,VectorSegment:()=>VectorSegment,WindowFrame:()=>WindowFrame,createPlotArea:()=>createPlotArea,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,getToneColor:()=>getToneColor,getToneGradient:()=>getToneGradient});import React from"react";import{AsyncLocalStorage}from"async_hooks";var RENDER_CONTEXT_KEY=Symbol.for("vizmatic.renderContext");var globalRenderContext=globalThis;var renderContext=globalRenderContext[RENDER_CONTEXT_KEY]??=new AsyncLocalStorage;function getRenderBackground(){return renderContext.getStore()?.background??"transparent"}async function withRenderContext(context,render){const parent=renderContext.getStore();return renderContext.run({...parent,...context},render)}function defineIllustration(build,defaultTheme="dark"){return{create(theme){return build(getThemeColors(theme))},default:build(getThemeColors(defaultTheme))}}function Canvas({children,c,padding=40,justify="center",background}){const renderBackground=getRenderBackground();const canvasBackground=background??(renderBackground==="theme"?c.bg:renderBackground);return React.createElement("div",{style:{width:"100%",height:"100%",boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:justify,backgroundColor:canvasBackground,fontFamily:c.fontSans,padding}},children)}function TitleBar({title,subtitle,c}){const engineering=c.preset==="engineering";return React.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:engineering?"flex-start":"center",gap:6,...engineering?{width:"100%"}:{},marginBottom:engineering?20:24}},React.createElement("div",{style:{...typography.title,fontFamily:c.fontSans,fontSize:engineering?34:typography.title.fontSize,fontWeight:700,...engineering?{lineHeight:1.12}:{},color:c.textPrimary}},title),subtitle&&React.createElement("div",{style:{...typography.body,color:c.textSecondary,fontFamily:c.fontMono,fontSize:engineering?14:typography.body.fontSize,lineHeight:1.35}},subtitle))}function flexAlign(align){return{start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"}[align]}function flexJustify(justify){return{start:"flex-start",center:"center",end:"flex-end","space-between":"space-between","space-around":"space-around"}[justify]}function textFitStyle(align="left"){return{minWidth:0,maxWidth:"100%",whiteSpace:"normal",overflowWrap:"break-word",textAlign:align}}function compactChildren(children){return children.filter(child=>child!==void 0&&child!==null&&child!==false)}function Scene({c,children,title,subtitle,padding=40,gap=24,justify="flex-start",align="stretch",contentWidth="100%",background,contentStyle}){return React.createElement(Canvas,{c,padding,justify,background},...compactChildren([title&&React.createElement(TitleBar,{c,title,subtitle}),React.createElement("div",{style:{width:contentWidth,display:"flex",flexDirection:"column",alignItems:flexAlign(align),gap,...contentStyle}},children)]))}function flexBox(direction,{children,gap=12,align="center",justify="center",wrap=false,width,height,style}){return React.createElement("div",{style:{display:"flex",flexDirection:direction,alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...wrap?{flexWrap:"wrap"}:{},...width!=null?{width}:{},...height!=null?{height}:{},...style}},children)}function Row(props){return flexBox("row",props)}function Column(props){return flexBox("column",props)}function ToneStrip({tone,width=34,height=4}){return React.createElement("span",{style:{display:"flex",width,height,borderRadius:999,backgroundImage:getToneGradient(tone),flexShrink:0}},"")}var iconShapes={agent:[{tag:"rect",attrs:{x:5,y:7,width:14,height:12,rx:4}},{tag:"path",attrs:{d:"M12 7V4"}},{tag:"circle",attrs:{cx:12,cy:3,r:1}},{tag:"circle",attrs:{cx:9,cy:13,r:1}},{tag:"circle",attrs:{cx:15,cy:13,r:1}},{tag:"path",attrs:{d:"M9 17h6"}}],bucket:[{tag:"path",attrs:{d:"M5 7c0-2 14-2 14 0s-14 2-14 0Z"}},{tag:"path",attrs:{d:"M6 7l1 13h10l1-13"}}],browser:[{tag:"rect",attrs:{x:3,y:4,width:18,height:16,rx:2}},{tag:"path",attrs:{d:"M3 8h18"}},{tag:"circle",attrs:{cx:7,cy:6,r:.75}},{tag:"circle",attrs:{cx:10,cy:6,r:.75}},{tag:"circle",attrs:{cx:13,cy:6,r:.75}}],cache:[{tag:"rect",attrs:{x:5,y:4,width:14,height:16,rx:3}},{tag:"path",attrs:{d:"M8 9h8"}},{tag:"path",attrs:{d:"M8 13h8"}},{tag:"path",attrs:{d:"M8 17h5"}}],chart:[{tag:"path",attrs:{d:"M4 19V5"}},{tag:"path",attrs:{d:"M4 19h16"}},{tag:"polyline",attrs:{points:"7 15 11 11 14 13 19 7"}}],check:[{tag:"polyline",attrs:{points:"20 6 9 17 4 12"}}],cluster:[{tag:"path",attrs:{d:"M12 8v4M10 13l-4 2M14 13l4 2"}},{tag:"circle",attrs:{cx:12,cy:5,r:3}},{tag:"circle",attrs:{cx:6,cy:17,r:3}},{tag:"circle",attrs:{cx:18,cy:17,r:3}}],code:[{tag:"polyline",attrs:{points:"8 9 4 12 8 15"}},{tag:"polyline",attrs:{points:"16 9 20 12 16 15"}},{tag:"path",attrs:{d:"M13 5l-2 14"}}],cloud:[{tag:"path",attrs:{d:"M7 18h11a4 4 0 0 0 .5-7.97A6.5 6.5 0 0 0 6.2 8.5 4.8 4.8 0 0 0 7 18Z"}}],container:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:1}},{tag:"path",attrs:{d:"M8 5v14M16 5v14"}}],database:[{tag:"path",attrs:{d:"M4 7c0-2 16-2 16 0s-16 2-16 0Z"}},{tag:"path",attrs:{d:"M4 7v5c0 2 16 2 16 0V7"}},{tag:"path",attrs:{d:"M4 12v5c0 2 16 2 16 0v-5"}}],file:[{tag:"path",attrs:{d:"M6 3h8l4 4v14H6Z"}},{tag:"path",attrs:{d:"M14 3v5h5"}},{tag:"path",attrs:{d:"M9 13h6"}},{tag:"path",attrs:{d:"M9 17h4"}}],firewall:[{tag:"path",attrs:{d:"M5 4h14v16H5Z"}},{tag:"path",attrs:{d:"M5 9h14M5 14h14"}},{tag:"path",attrs:{d:"M9 4v5M15 4v5M12 9v5M8 14v6M17 14v6"}}],gateway:[{tag:"path",attrs:{d:"M4 20V5h16v15"}},{tag:"path",attrs:{d:"M8 20v-7h8v7"}},{tag:"polyline",attrs:{points:"9 9 12 6 15 9"}},{tag:"path",attrs:{d:"M12 6v7"}}],git:[{tag:"circle",attrs:{cx:6,cy:6,r:2}},{tag:"circle",attrs:{cx:18,cy:18,r:2}},{tag:"circle",attrs:{cx:6,cy:18,r:2}},{tag:"path",attrs:{d:"M8 6h3a5 5 0 0 1 5 5v5"}},{tag:"path",attrs:{d:"M6 8v8"}}],globe:[{tag:"circle",attrs:{cx:12,cy:12,r:9}},{tag:"path",attrs:{d:"M3 12h18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 1 0 18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 0 0 18"}}],image:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:3}},{tag:"circle",attrs:{cx:9,cy:10,r:1.5}},{tag:"polyline",attrs:{points:"7 17 11 13 14 16 16 14 20 18"}}],layers:[{tag:"path",attrs:{d:"M12 3 3 8l9 5 9-5Z"}},{tag:"path",attrs:{d:"m3 13 9 5 9-5"}},{tag:"path",attrs:{d:"m3 18 9 5 9-5"}}],lock:[{tag:"rect",attrs:{x:5,y:10,width:14,height:10,rx:2}},{tag:"path",attrs:{d:"M8 10V7a4 4 0 0 1 8 0v3"}}],"load-balancer":[{tag:"rect",attrs:{x:8,y:8,width:8,height:8,rx:2}},{tag:"path",attrs:{d:"M4 12h4M16 7h4M16 12h4M16 17h4"}},{tag:"polyline",attrs:{points:"6 10 4 12 6 14"}}],mobile:[{tag:"rect",attrs:{x:6,y:2,width:12,height:20,rx:2}},{tag:"path",attrs:{d:"M10 5h4"}},{tag:"circle",attrs:{cx:12,cy:18,r:1}}],monitor:[{tag:"rect",attrs:{x:3,y:4,width:18,height:13,rx:2}},{tag:"path",attrs:{d:"M8 21h8M12 17v4"}}],network:[{tag:"path",attrs:{d:"M7 10l3-3M14 7l3 3M17 14l-3 3M10 17l-3-3M7 12h10M12 7v10"}},{tag:"circle",attrs:{cx:5,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:5,r:2}},{tag:"circle",attrs:{cx:19,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:19,r:2}}],play:[{tag:"path",attrs:{d:"M8 5v14l11-7Z"}}],queue:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:2}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:12,cy:12,r:1}},{tag:"circle",attrs:{cx:16,cy:12,r:1}}],server:[{tag:"rect",attrs:{x:4,y:4,width:16,height:16,rx:2}},{tag:"path",attrs:{d:"M4 9h16M4 15h16"}},{tag:"circle",attrs:{cx:8,cy:7,r:1}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:8,cy:18,r:1}}],spark:[{tag:"path",attrs:{d:"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8Z"}},{tag:"path",attrs:{d:"M5 16l.8 2.2L8 19l-2.2.8L5 22l-.8-2.2L2 19l2.2-.8Z"}}],storage:[{tag:"rect",attrs:{x:4,y:6,width:16,height:12,rx:2}},{tag:"circle",attrs:{cx:12,cy:12,r:3}},{tag:"path",attrs:{d:"M7 18h10"}}],stream:[{tag:"path",attrs:{d:"M4 7h13"}},{tag:"polyline",attrs:{points:"14 4 17 7 14 10"}},{tag:"path",attrs:{d:"M20 17H7"}},{tag:"polyline",attrs:{points:"10 14 7 17 10 20"}}],terminal:[{tag:"polyline",attrs:{points:"5 7 10 12 5 17"}},{tag:"path",attrs:{d:"M12 17h7"}}],tool:[{tag:"path",attrs:{d:"M14 6a5 5 0 0 0 6 6L11 21l-6-6 9-9Z"}},{tag:"path",attrs:{d:"M8 18l-2-2"}}],user:[{tag:"circle",attrs:{cx:12,cy:7,r:3.5}},{tag:"path",attrs:{d:"M5 20a7 7 0 0 1 14 0"}}],warning:[{tag:"path",attrs:{d:"M12 4 22 20H2Z"}},{tag:"path",attrs:{d:"M12 9v5"}},{tag:"path",attrs:{d:"M12 17h.01"}}]};function Icon({c,name,tone="blue",color,size=24,strokeWidth=2,label,muted=false}){const stroke=muted?c.textMuted:color??getToneColor(tone,c);const shapes=iconShapes[name];return React.createElement("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke,strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",role:label?"img":void 0,"aria-hidden":label?void 0:"true","aria-label":label,style:{flex:`0 0 ${size}px`}},shapes.map((shape,index)=>React.createElement(shape.tag,{key:`${name}-${index}`,...shape.attrs})))}function Panel({title,c,children,subtitle,tone="blue",footer,width,minWidth,height,minHeight,padding=14,radius=8,gap=10,align="stretch",justify="start",shadow=true,background,borderColor,titleFontSize,accentWidth=34,accentHeight=4,bodyStyle}){const engineering=c.preset==="engineering";return React.createElement("div",{"data-vizmatic-layout-container":"panel",style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:radius,border:`1px solid ${borderColor??c.borderSubtle}`,backgroundColor:background??c.bgCard,...shadow&&!engineering?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap:subtitle?5:0}},...compactChildren([React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,...typography.small,fontFamily:c.fontSans,...textFitStyle(),fontSize:titleFontSize??typography.small.fontSize,fontWeight:900,lineHeight:1.2}},ToneStrip({tone,width:accentWidth,height:accentHeight}),title),subtitle&&React.createElement("div",{style:{display:"flex",color:c.textSecondary,...typography.tiny,fontFamily:engineering?c.fontMono:typography.tiny.fontFamily,...textFitStyle(),lineHeight:1.35}},subtitle)])),React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap,...bodyStyle}},children),footer&&React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",color:c.textMuted,...typography.tiny,...textFitStyle()}},footer)]))}function readScriptValue(text,start){if(text[start]==="{"){const end=text.indexOf("}",start+1);if(end!==-1)return{value:text.slice(start+1,end),next:end+1}}let next=start;while(next<text.length&&/[A-Za-z0-9+\-]/.test(text[next]))next+=1;if(next===start)next+=1;return{value:text.slice(start,next),next}}function parseMathText(text){const parts=[];let buffer="";let index=0;while(index<text.length){const char=text[index];if((char==="_"||char==="^")&&index+1<text.length){if(buffer){parts.push({kind:"text",value:buffer});buffer=""}const script=readScriptValue(text,index+1);parts.push({kind:char==="_"?"sub":"sup",value:script.value});index=script.next;continue}buffer+=char;index+=1}if(buffer)parts.push({kind:"text",value:buffer});return parts}var subscriptChars={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var superscriptChars={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"};var superscriptWords={alpha:"\u1D45",beta:"\u1D5D",gamma:"\u1D5E",theta:"\u1DBF"};function scriptText(value,kind){const words=kind==="sup"?superscriptWords:{};const chars=kind==="sub"?subscriptChars:superscriptChars;if(words[value])return words[value];if((value.startsWith("-")||value.startsWith("+"))&&words[value.slice(1)]){return`${chars[value[0]]}${words[value.slice(1)]}`}return Array.from(value).map(char=>chars[char]??char).join("")}function formatMathText(text){return parseMathText(text).map(part=>part.kind==="text"?part.value:scriptText(part.value,part.kind)).join("")}function MathText({text}){return formatMathText(text)}function TextLabel({text,c,variant="body",color,fontSize,fontWeight,width,align="left",math=false,mono=false}){const base=typography[variant];return React.createElement("div",{style:{display:"flex",...width!==void 0?{width}:{},...base,...textFitStyle(align),color:color??c.textSecondary,fontSize:fontSize??base.fontSize,fontWeight:fontWeight??base.fontWeight,fontFamily:mono?"JetBrains Mono":base.fontFamily,justifyContent:align==="right"?"flex-end":align==="center"?"center":"flex-start",lineHeight:1.35}},math?formatMathText(text):text)}function svgMathTextBaselineOffset(dominantBaseline){switch(dominantBaseline.toLowerCase()){case"hanging":case"text-before-edge":case"before-edge":case"top":return"0";case"text-after-edge":case"after-edge":case"bottom":case"alphabetic":case"baseline":case"ideographic":case"auto":return"-100%";default:return"-50%"}}function SvgMathText({text,x,y,fill,fontSize=13,fontFamily="JetBrains Mono",fontWeight=800,textAnchor="middle",dominantBaseline="middle",opacity=1}){const anchorOffset=textAnchor==="start"?"0":textAnchor==="end"?"-100%":"-50%";const baselineOffset=svgMathTextBaselineOffset(dominantBaseline);return React.createElement("div",{"data-vizmatic-svg-math-text":true,style:{position:"absolute",left:x,top:y,display:"flex",color:fill,fontSize,fontFamily,fontWeight,lineHeight:1,whiteSpace:"nowrap",pointerEvents:"none",opacity,transform:`translate(${anchorOffset}, ${baselineOffset})`}},formatMathText(text))}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}import React2 from"react";function Box({label,c,color="primary",width,height,fontSize=14,gradient=false,sublabel,icon,radius=8,outlined=false}){const solidColor=getColor(color,c);const gradientBg=getGradient(color);const solidTextColor=getReadableTextColor(solidColor,c);const style={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:radius,padding:"12px 20px",gap:4,...width?{width}:{},...height?{height}:{}};if(outlined){style.border=`2px solid ${solidColor}`;style.backgroundColor="transparent"}else if(gradient){style.backgroundImage=gradientBg;style.boxShadow=`0 4px 20px ${solidColor}30`}else{style.backgroundColor=solidColor;style.boxShadow=`0 4px 20px ${solidColor}30`}return React2.createElement("div",{style},icon&&React2.createElement("div",{style:{fontSize:fontSize+4}},icon),React2.createElement("div",{style:{fontSize,fontWeight:700,color:outlined?solidColor:gradient?c.textOnColor:solidTextColor,fontFamily:c.fontSans,textAlign:"center",lineHeight:1.3}},label),sublabel&&React2.createElement("div",{style:{fontSize:fontSize-2,fontWeight:400,color:outlined?c.textMuted:gradient?`${c.textOnColor}b3`:solidTextColor,fontFamily:c.fontMono,textAlign:"center"}},sublabel))}function Arrow({direction="down",label,length=40,c,color}){const arrowColor=color||c.textMuted;const isVertical=direction==="down"||direction==="up";const arrowHead={down:{width:14,height:10,points:"0,0 14,0 7,10"},up:{width:14,height:10,points:"0,10 14,10 7,0"},right:{width:10,height:14,points:"0,0 10,7 0,14"},left:{width:10,height:14,points:"10,0 0,7 10,14"}}[direction];const line=React2.createElement("div",{style:{...isVertical?{width:2,flexGrow:1,minHeight:1}:{height:2,flexGrow:1,minWidth:1},backgroundColor:arrowColor}});const head=React2.createElement("svg",{width:arrowHead.width,height:arrowHead.height,viewBox:`0 0 ${arrowHead.width} ${arrowHead.height}`,style:{flexShrink:0}},React2.createElement("polygon",{points:arrowHead.points,fill:arrowColor}));return React2.createElement("div",{style:{position:"relative",display:"flex",flexDirection:isVertical?"column":"row",alignItems:"center",justifyContent:"center",gap:0,...isVertical?{height:length}:{width:length}}},...direction==="up"||direction==="left"?[head,line]:[line,head],label&&React2.createElement("div",{style:{fontSize:11,color:c.textMuted,fontFamily:c.fontSans,fontWeight:500,position:"absolute",...isVertical?{left:8}:{bottom:12}}},label))}function FlowArrow({direction="right",label,length=40,c,tone="blue",color}){return Arrow({direction,label,length,c,color:color??getToneColor(tone,c)})}function Connector(props){return FlowArrow(props)}function VectorArrow({key,x1,y1,x2,y2,color,strokeWidth=2,arrowSize=2.2,opacity=1}){const dx=x2-x1;const dy=y2-y1;const len=Math.sqrt(dx*dx+dy*dy);if(len<.001){return React2.createElement("g",null)}const ux=dx/len;const uy=dy/len;const px=-uy;const py=ux;const headLen=strokeWidth*arrowSize;const headWidth=headLen*.6;const backX=x2-ux*headLen;const backY=y2-uy*headLen;const points=`${x2},${y2} ${backX+px*headWidth/2},${backY+py*headWidth/2} ${backX-px*headWidth/2},${backY-py*headWidth/2}`;return React2.createElement("g",{key,opacity},React2.createElement("line",{x1,y1,x2:backX,y2:backY,stroke:color,strokeWidth,strokeLinecap:"round"}),React2.createElement("polygon",{points,fill:color}))}function VectorSegment({key,x1,y1,x2,y2,color,strokeWidth=4,opacity=1,showStartDot=false,showEndDot=true,dotRadius=4.5}){return React2.createElement("g",{key,opacity},React2.createElement("line",{x1,y1,x2,y2,stroke:color,strokeWidth,strokeLinecap:"round"}),showStartDot&&React2.createElement("circle",{cx:x1,cy:y1,r:dotRadius,fill:color}),showEndDot&&React2.createElement("circle",{cx:x2,cy:y2,r:dotRadius,fill:color}))}function SvgFrame({key,x=0,y=0,width,height,c,rx=8,fill,stroke,strokeWidth=1,opacity}){return React2.createElement("rect",{key,x,y,width,height,rx,fill:fill??c.bgSubtle,stroke:stroke??c.borderSubtle,strokeWidth,...opacity!==void 0?{opacity}:{}})}function SvgPoint({key,cx,cy,r=5,fill,stroke,strokeWidth,opacity}){return React2.createElement("circle",{key,cx,cy,r,fill,...stroke?{stroke}:{},...strokeWidth?{strokeWidth}:{},...opacity!==void 0?{opacity}:{}})}function ArrowMarkerDef({id,color,size=5}){return React2.createElement("marker",{id,viewBox:"0 0 10 10",refX:9.5,refY:5,markerWidth:size,markerHeight:size,orient:"auto-start-reverse"},React2.createElement("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:color}))}import React3 from"react";function Stack({direction="vertical",gap=12,align="center",wrap=false,children}){const alignMap={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"};return React3.createElement("div",{style:{display:"flex",flexDirection:direction==="vertical"?"column":"row",alignItems:alignMap[align],gap,...wrap?{flexWrap:"wrap"}:{}}},children)}function Card({children,c,title,subtitle,tone,footer,width,minWidth,height,minHeight,padding=20,radius=8,gap,align="stretch",justify="start",shadow=false,background,borderColor,bodyStyle}){const hasHeader=title||subtitle||tone;const engineering=c.preset==="engineering";return React3.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap:gap??(hasHeader||footer?10:0),backgroundColor:background??c.bgCard,borderRadius:engineering?Math.min(radius,5):radius,border:`1px solid ${borderColor??c.borderSubtle}`,padding,...width!==void 0?{width}:{},...minWidth!==void 0?{minWidth}:{},...height!==void 0?{height}:{},...minHeight!==void 0?{minHeight}:{},...shadow&&!engineering?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([hasHeader&&React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:subtitle?5:0}},...compactChildren([(title||tone)&&React3.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,...typography.small,fontFamily:c.fontSans,...textFitStyle(),fontWeight:900,lineHeight:1.2}},tone&&ToneStrip({tone,width:30,height:4}),title),subtitle&&React3.createElement("div",{style:{display:"flex",color:c.textSecondary,...typography.tiny,fontFamily:c.fontSans,...textFitStyle(),lineHeight:1.35}},subtitle)])),React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",...bodyStyle}},children),footer&&React3.createElement("div",{style:{width:"100%",display:"flex",color:c.textMuted,...typography.tiny,fontFamily:c.fontSans,...textFitStyle()}},footer)]))}function renderMaybeMath(node,math){return math&&typeof node==="string"?formatMathText(node):node}function ValuePill({label,value,c,tone="blue",detail,width=112,math=false}){const accent=getReadableToneColor(tone,c);return Card({c,tone,width,padding:12,radius:10,shadow:true,title:React3.createElement("span",{style:{textTransform:"uppercase",letterSpacing:"0.05em"}},renderMaybeMath(label,math)),children:React3.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4}},React3.createElement("div",{style:{color:accent,fontFamily:c.fontMono,fontSize:24,fontWeight:900,lineHeight:1}},renderMaybeMath(value,math)),detail&&React3.createElement("div",{style:{color:c.textSecondary,...typography.tiny,lineHeight:1.3}},renderMaybeMath(detail,math)))})}function EquationCard({title,formula,c,tone="purple",result,detail,width=190,height,math=false,align="left"}){const accent=getReadableToneColor(tone,c);const textAlign=align;return Card({c,tone,width,height,padding:16,radius:10,shadow:true,title,children:React3.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,alignItems:align==="center"?"center":"flex-start"}},React3.createElement("div",{style:{color:c.textPrimary,fontFamily:c.fontMono,fontSize:15,fontWeight:800,lineHeight:1.3,textAlign}},renderMaybeMath(formula,math)),result&&React3.createElement("div",{style:{color:accent,fontFamily:c.fontMono,fontSize:28,fontWeight:900,lineHeight:1,textAlign}},renderMaybeMath(result,math)),detail&&React3.createElement("div",{style:{color:c.textSecondary,...typography.tiny,lineHeight:1.35,textAlign}},renderMaybeMath(detail,math)))})}function BadgePill({text,c,tone="blue",width,minWidth=34,height=20,padding="0 8px",radius=6,fontSize=11,mono=true,filled=false,math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";return React3.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},padding,borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c)}:filled?{backgroundImage:getToneGradient(tone)}:{backgroundColor:`${accent}18`},border:`1px solid ${engineering?accent:filled?`${accent}00`:`${accent}55`}`,color:engineering?c.textPrimary:filled?c.textOnColor:accentText,fontSize,fontWeight:800,lineHeight:1,fontFamily:mono?c.fontMono:c.fontSans,boxSizing:"border-box",whiteSpace:"nowrap"}},renderMaybeMath(text,math))}function GradientChip({title,c,subtitle,tone="blue",gradient,width,minWidth,height,minHeight=78,padding="0 18px",radius=8,shadow=true,align="left",subtitleMono=true,math=false}){const textAlign=align;const engineering=c.preset==="engineering"&&gradient==null;const textColor=engineering?c.textPrimary:c.textOnColor;const accent=getToneColor(tone,c);return React3.createElement("div",{style:{...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},boxSizing:"border-box",borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c),border:`1px solid ${accent}`}:{backgroundImage:gradient??getToneGradient(tone)},color:textColor,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:5,padding,...shadow&&!engineering?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},React3.createElement("div",{style:{...typography.label,color:textColor,fontFamily:c.fontSans,fontWeight:900,lineHeight:1.1,textAlign}},renderMaybeMath(title,math)),subtitle&&React3.createElement("div",{style:{fontSize:11,color:engineering?c.textSecondary:"rgba(255,255,255,0.86)",lineHeight:1.2,textAlign,fontFamily:subtitleMono?c.fontMono:c.fontSans}},renderMaybeMath(subtitle,math)))}function StepCard({title,c,subtitle,eyebrow,tone="blue",width=210,minWidth,minHeight=74,padding="12px 14px",radius=8,shadow=true,align="center",math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";const textAlign=align;return Card({c,width,minWidth,minHeight,padding,radius:engineering?5:radius,shadow:engineering?false:shadow,background:engineering?getToneFill(tone,c):void 0,borderColor:engineering?accent:`${accent}88`,children:React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:subtitle?5:2}},eyebrow&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontMono,color:c.textMuted,fontWeight:engineering?400:800,textTransform:"uppercase",letterSpacing:"0.05em",...textFitStyle(textAlign),lineHeight:1.2}},renderMaybeMath(eyebrow,math)),React3.createElement("div",{style:{...typography.label,fontFamily:c.fontSans,color:engineering?c.textPrimary:accentText,fontWeight:700,lineHeight:1.15,...textFitStyle(textAlign)}},renderMaybeMath(title,math)),subtitle&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontMono,color:c.textMuted,lineHeight:1.25,...textFitStyle(textAlign)}},renderMaybeMath(subtitle,math)))})}function MetricCard({label,value,c,tone="blue",detail,width,minWidth,minHeight=74,padding="10px 12px",radius=8,shadow=true,align="center",math=false,valueMono=true,valueFontSize=22,valueColor}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const textAlign=align;return Card({c,width,minWidth,minHeight,padding,radius,shadow,borderColor:`${accent}66`,children:React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:3}},...compactChildren([React3.createElement("div",{style:{fontSize:11,fontWeight:800,color:accentText,fontFamily:c.fontSans,lineHeight:1.1,...textFitStyle(textAlign)}},renderMaybeMath(label,math)),React3.createElement("div",{style:{fontSize:valueFontSize,fontWeight:700,color:valueColor??c.textPrimary,lineHeight:1.15,...textFitStyle(textAlign),fontFamily:valueMono?c.fontMono:c.fontSans}},renderMaybeMath(value,math)),detail&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontSans,color:c.textMuted,lineHeight:1.2,...textFitStyle(textAlign)}},renderMaybeMath(detail,math))]))})}import React4 from"react";function ProgressRow({label,value,valueLabel,tone="blue",muted=false,c,labelWidth=42,valueWidth=38,barHeight=8,fontSize=11}){const accent=muted?c.textMuted:getToneColor(tone,c);const accentText=muted?c.textMuted:getReadableToneColor(tone,c);const pct=Math.round(Math.max(0,Math.min(1,value))*100);return React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%"}},React4.createElement("div",{style:{width:labelWidth,color:muted?c.textMuted:c.textPrimary,fontSize,fontWeight:800,lineHeight:1}},label),React4.createElement("div",{style:{display:"flex",flex:1,height:barHeight,borderRadius:999,backgroundColor:c.bgSubtle,border:`1px solid ${c.borderSubtle}`,overflow:"hidden"}},React4.createElement("div",{style:{width:`${pct}%`,height:"100%",borderRadius:999,backgroundColor:accent,opacity:muted?.62:1}})),React4.createElement("div",{style:{width:valueWidth,color:accentText,fontSize,fontWeight:800,fontFamily:"JetBrains Mono",lineHeight:1,textAlign:"right"}},valueLabel??`${pct}%`))}function ProgressList({rows,c,gap=8,labelWidth,valueWidth,barHeight,fontSize}){return Column({gap,align:"stretch",children:rows.map((row,index)=>React4.createElement(React4.Fragment,{key:`progress-${index}`},ProgressRow({...row,c,labelWidth,valueWidth,barHeight,fontSize})))})}function MiniBarChart({data,c,max,minBarHeight=8,height=92,barWidth=22,gap=10,radius=7,fontSize=11,showValues=false}){const requestedMax=max!=null&&max>0?max:void 0;const safeMax=requestedMax??Math.max(1,...data.map(item=>Math.max(0,item.value)));const barMaxHeight=Math.max(minBarHeight,height-(showValues?34:20));return React4.createElement("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"center",gap,height,width:"100%",padding:"0 4px",boxSizing:"border-box"}},...data.map((item,index)=>{const tone=item.tone??"blue";const barHeight=Math.max(minBarHeight,Math.round(Math.max(0,item.value)/safeMax*barMaxHeight));const fill=item.color??getToneGradient(tone);return React4.createElement("div",{key:`mini-bar-${index}-${String(item.label)}`,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-end",gap:5,height:"100%",minWidth:barWidth}},...compactChildren([showValues&&React4.createElement("div",{style:{display:"flex",color:getReadableToneColor(tone,c),fontFamily:"JetBrains Mono",fontSize,fontWeight:800,lineHeight:1}},item.valueLabel??item.value),React4.createElement("div",{style:{display:"flex",width:barWidth,height:barHeight,borderRadius:`${radius}px ${radius}px 4px 4px`,...fill.startsWith("linear-gradient")?{backgroundImage:fill}:{backgroundColor:fill},opacity:item.opacity??.92}}),React4.createElement("div",{style:{display:"flex",color:c.textMuted,fontFamily:"JetBrains Mono",fontSize,fontWeight:700,lineHeight:1,minHeight:fontSize+2}},item.label)]))}))}function DetailList({items,c,tone,gap=7,padding="7px 8px",fontSize=11,mono=false,math=false}){const accent=tone?getToneColor(tone,c):c.borderSubtle;return Column({gap,align:"stretch",children:items.map((item,index)=>React4.createElement("div",{key:`detail-${index}`,style:{padding,borderRadius:8,backgroundColor:c.bgSubtle,border:`1px solid ${tone?`${accent}44`:c.borderSubtle}`,color:c.textSecondary,fontSize,lineHeight:1.3,fontFamily:mono?"JetBrains Mono":"Inter"}},renderMaybeMath(item,math)))})}function Tile({title,subtitle,eyebrow,icon,tone="blue",lines,children,width,minHeight=84,c,align="center",padding="14px 16px",radius=10,shadow=true,math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const textAlign=align;const crossAlign=align==="center"?"center":"flex-start";const detailLines=(lines??[]).map((line,index)=>React4.createElement("div",{key:`tile-line-${index}`,style:{display:"flex",alignItems:"center",justifyContent:align==="center"?"center":"flex-start",gap:6,...typography.tiny,color:c.textSecondary,lineHeight:1.3,textAlign}},React4.createElement("span",{style:{display:"flex",width:4,height:4,borderRadius:999,backgroundColor:accent,flexShrink:0}}),renderMaybeMath(line,math)));return Card({c,width,minHeight,padding,radius,shadow,borderColor:`${accent}88`,children:React4.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:crossAlign,gap:5}},...compactChildren([icon!=null&&React4.createElement("div",{style:{display:"flex",fontSize:22,lineHeight:1}},icon),eyebrow!=null&&React4.createElement("div",{style:{...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",lineHeight:1.2,textAlign}},renderMaybeMath(eyebrow,math)),React4.createElement("div",{style:{...typography.label,color:accentText,fontWeight:800,lineHeight:1.15,textAlign}},renderMaybeMath(title,math)),subtitle!=null&&React4.createElement("div",{style:{...typography.tiny,color:c.textSecondary,lineHeight:1.3,textAlign}},renderMaybeMath(subtitle,math)),detailLines.length>0&&React4.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:4,marginTop:2}},...detailLines),children]))})}function TileGrid({tiles,c,columns,gap=12,tileWidth,minHeight,align="center",math=false}){const renderTile=(tile,index)=>React4.createElement(React4.Fragment,{key:`tile-${index}`},Tile({...tile,c,align,math,width:tile.width??tileWidth,minHeight:tile.minHeight??minHeight}));if(!columns||columns>=tiles.length){return Row({gap,align:"stretch",justify:"center",wrap:true,children:tiles.map(renderTile)})}const rows=[];for(let i=0;i<tiles.length;i+=columns){rows.push(tiles.slice(i,i+columns))}return Column({gap,align:"stretch",children:rows.map((rowTiles,rowIndex)=>React4.createElement(React4.Fragment,{key:`tile-row-${rowIndex}`},Row({gap,align:"stretch",justify:"center",children:rowTiles.map((tile,colIndex)=>renderTile(tile,rowIndex*columns+colIndex))})))})}function isCodeLineSpec(line){return typeof line==="object"&&line!==null&&!React4.isValidElement(line)&&"text"in line}function CodeBlock({lines,c,title,tone,width,minWidth,fontSize=12,showLineNumbers=false,padding=14,radius=10,background,shadow=false,math=false}){const headerAccent=tone?getToneColor(tone,c):c.textMuted;const numberWidth=String(lines.length).length*(fontSize*.62)+8;const lineElements=lines.map((line,index)=>{const spec=isCodeLineSpec(line)?line:{text:line};const accent=spec.tone?getToneColor(spec.tone,c):void 0;const accentText=spec.tone?getReadableToneColor(spec.tone,c):void 0;const textColor=spec.dim?c.textMuted:accentText??c.textSecondary;return React4.createElement("div",{key:`code-line-${index}`,style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:accent?"3px 7px":"1px 0",borderRadius:accent?5:0,...accent?{backgroundColor:`${accent}1f`}:{},boxSizing:"border-box"}},...compactChildren([showLineNumbers&&React4.createElement("div",{style:{display:"flex",width:numberWidth,flexShrink:0,justifyContent:"flex-end",color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:fontSize-1,lineHeight:1.5,opacity:.7}},String(index+1)),spec.prefix!=null&&React4.createElement("div",{style:{display:"flex",flexShrink:0,color:accentText??c.textMuted,fontFamily:"JetBrains Mono",fontWeight:800,fontSize,lineHeight:1.5}},spec.prefix),React4.createElement("div",{style:{display:"flex",flex:1,color:textColor,fontFamily:"JetBrains Mono",fontWeight:accent?700:500,fontSize,lineHeight:1.5,whiteSpace:"pre-wrap"}},math&&typeof spec.text==="string"?formatMathText(spec.text):spec.text)]))});return React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},padding,borderRadius:radius,backgroundColor:background??c.bgSubtle,border:`1px solid ${tone?`${headerAccent}44`:c.borderSubtle}`,boxSizing:"border-box",...shadow?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([title!=null&&React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:fontSize-1,fontWeight:800,letterSpacing:"0.02em"}},React4.createElement("span",{style:{display:"flex",width:8,height:8,borderRadius:999,backgroundColor:headerAccent,flexShrink:0}}),renderMaybeMath(title,math)),React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2,width:"100%"}},...lineElements)]))}function renderComparisonDivider(divider,c,key){const label=divider===true?"vs":divider;return React4.createElement("div",{key,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",alignSelf:"stretch",flexShrink:0}},React4.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minWidth:30,height:30,padding:"0 8px",borderRadius:999,backgroundColor:c.bgCard,border:`1px solid ${c.borderLight}`,color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.06em",boxShadow:`0 4px 12px ${c.shadow}`}},label))}function Comparison({sides:sides2,c,divider=false,gap=14,sideWidth,minHeight,align="stretch",math=false}){const children=sides2.flatMap((side,index)=>{const tone=side.tone??"blue";const panel=React4.createElement(React4.Fragment,{key:`comparison-side-${index}`},Panel({c,tone,title:side.title,subtitle:side.subtitle,footer:side.footer,width:side.width??sideWidth,minHeight,bodyStyle:{gap:8},children:side.eyebrow!=null?React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8}},React4.createElement("div",{style:{...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em"}},renderMaybeMath(side.eyebrow,math)),side.children??DetailList({items:side.lines??[],c,tone,math})):side.children??DetailList({items:side.lines??[],c,tone,math})}));if(divider&&index<sides2.length-1){return[panel,renderComparisonDivider(divider,c,`comparison-divider-${index}`)]}return[panel]});return Row({gap,align,justify:"center",children})}function KeyValueList({rows,c,title,width,minWidth,keyWidth,gap=0,fontSize=11,divider=true,keyMono=false,math=false}){const rowElements=rows.map((row,index)=>{const accent=row.tone?getReadableToneColor(row.tone,c):void 0;const isLast=index===rows.length-1;const valueMono=row.valueMono??true;return React4.createElement("div",{key:`kv-row-${index}`,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:14,width:"100%",padding:divider?"7px 0":"4px 0",...divider&&!isLast?{borderBottom:`1px solid ${c.borderSubtle}`}:{},boxSizing:"border-box"}},React4.createElement("div",{style:{display:"flex",...keyWidth!=null?{width:keyWidth,flexShrink:0}:{},color:c.textSecondary,fontFamily:keyMono?"JetBrains Mono":"Inter",fontSize,fontWeight:600,lineHeight:1.3}},renderMaybeMath(row.key,math)),React4.createElement("div",{style:{display:"flex",flex:1,justifyContent:"flex-end",textAlign:"right",color:accent??c.textPrimary,fontFamily:valueMono?"JetBrains Mono":"Inter",fontSize,fontWeight:800,lineHeight:1.3}},renderMaybeMath(row.value,math)))});return React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{}}},...compactChildren([title!=null&&React4.createElement("div",{style:{display:"flex",...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",paddingBottom:4}},renderMaybeMath(title,math)),...rowElements]))}function WindowFrame({c,children,title,variant="window",tone="blue",dots=true,width,minWidth,height,minHeight,padding=16,radius=10,shadow=true,background,bodyStyle}){const isTerminal=variant==="terminal";const surface=background??(isTerminal?c.bgSubtle:c.bgCard);const titleColor=isTerminal?getReadableToneColor(tone,c,c.bgHover):c.textSecondary;const trafficDot=(color,key)=>React4.createElement("span",{key,style:{display:"flex",width:10,height:10,borderRadius:999,backgroundColor:color}});const titleBar=React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"8px 12px",backgroundColor:isTerminal?c.bg==="transparent"?c.bgHover:c.bgHover:c.bgSubtle,borderBottom:`1px solid ${c.borderSubtle}`,boxSizing:"border-box"}},...compactChildren([dots&&React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0}},trafficDot(c.criticalLight,"dot-r"),trafficDot(c.warningLight,"dot-y"),trafficDot(c.positiveLight,"dot-g")),title!=null&&(variant==="browser"?React4.createElement("div",{style:{display:"flex",flex:1,alignItems:"center",height:22,padding:"0 12px",borderRadius:999,backgroundColor:c.bgCard,border:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:600,lineHeight:1}},title):React4.createElement("div",{style:{display:"flex",flex:1,justifyContent:dots?"center":"flex-start",color:titleColor,fontFamily:isTerminal?"JetBrains Mono":"Inter",fontSize:12,fontWeight:700,lineHeight:1}},title)),dots&&title!=null&&variant!=="browser"&&React4.createElement("div",{style:{display:"flex",width:52,flexShrink:0}},"")]));return React4.createElement("div",{style:{display:"flex",flexDirection:"column",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},borderRadius:radius,border:`1px solid ${c.borderSubtle}`,backgroundColor:surface,overflow:"hidden",boxSizing:"border-box",...shadow?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},titleBar,React4.createElement("div",{style:{display:"flex",flexDirection:"column",width:"100%",padding,boxSizing:"border-box",...isTerminal?{fontFamily:"JetBrains Mono",color:c.textSecondary}:{},...bodyStyle}},children))}import React5 from"react";var statusGlyphs={check:"\u2713",cross:"\u2717",warn:"!",info:"i",pending:"\u2013",dot:""};var statusTones={check:"green",cross:"red",warn:"warm",info:"blue",pending:"neutral",dot:"blue"};function StatusRow({label,detail,status="check",tone,c,boxed=true,fontSize=11,width,math=false}){const resolvedTone=tone??statusTones[status];const accent=getToneColor(resolvedTone,c);const markerAlpha=38/255;const rowAlpha=boxed?18/255:0;const markerBackgroundAlpha=Math.round((rowAlpha+markerAlpha*(1-rowAlpha))*255);const markerBackground=`${accent}${markerBackgroundAlpha.toString(16).padStart(2,"0")}`;const accentText=getReadableToneColor(resolvedTone,c,markerBackground,c.bgCard);const glyph=statusGlyphs[status];const marker=React5.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,flexShrink:0,borderRadius:999,backgroundColor:status==="dot"?accent:`${accent}26`,border:`1px solid ${accent}`,color:accentText,fontFamily:"Inter",fontSize:status==="warn"||status==="info"?12:11,fontWeight:900,lineHeight:1}},glyph);return React5.createElement("div",{style:{display:"flex",alignItems:"center",gap:9,width:width??"100%",boxSizing:"border-box",...boxed?{padding:"7px 10px",borderRadius:8,backgroundColor:`${accent}12`,border:`1px solid ${accent}3a`}:{padding:"3px 0"}}},marker,React5.createElement("div",{style:{display:"flex",flex:1,color:c.textPrimary,fontFamily:"Inter",fontSize,fontWeight:600,lineHeight:1.3}},renderMaybeMath(label,math)),detail!=null&&React5.createElement("div",{style:{display:"flex",flexShrink:0,color:c.textSecondary,fontFamily:"Inter",fontSize:fontSize-1,lineHeight:1.3,textAlign:"right"}},renderMaybeMath(detail,math)))}function StatusList({rows,c,gap=7,boxed=true,fontSize,width,math=false}){return Column({gap,align:"stretch",...width!=null?{width}:{},children:rows.map((row,index)=>React5.createElement(React5.Fragment,{key:`status-${index}`},StatusRow({...row,c,boxed,fontSize,math})))})}function renderTimelineCard(event,c,math,width){const resolvedTone=event.tone??statusTones[event.status??"dot"];const accent=getToneColor(resolvedTone,c);const accentText=getReadableToneColor(resolvedTone,c);const resolvedWidth=event.width??width;return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:5,...resolvedWidth!=null?{width:resolvedWidth}:{},...typeof resolvedWidth==="string"?{minWidth:0}:{},padding:"10px 12px",borderRadius:8,border:`1px solid ${accent}44`,backgroundColor:c.bgCard,boxShadow:`0 7px 18px ${c.shadow}`,boxSizing:"border-box"}},...compactChildren([event.time!=null&&React5.createElement("div",{style:{display:"flex",color:accentText,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:900,lineHeight:1.15,textTransform:"uppercase",letterSpacing:"0.04em"}},renderMaybeMath(event.time,math)),React5.createElement("div",{style:{display:"flex",color:c.textPrimary,fontFamily:"Inter",fontSize:14,fontWeight:900,lineHeight:1.18,...textFitStyle()}},renderMaybeMath(event.title,math)),event.detail!=null&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35,...textFitStyle()}},renderMaybeMath(event.detail,math))]))}function Timeline({events,c,title,subtitle,direction="vertical",width,eventWidth,gap=12,markerSize=14,math=false}){const header=(title!=null||subtitle!=null)&&React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:"100%"}},...compactChildren([title!=null&&React5.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,fontFamily:"Inter",fontSize:16,fontWeight:900,lineHeight:1.2}},ToneStrip({tone:events[0]?.tone??"blue"}),renderMaybeMath(title,math)),subtitle!=null&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));if(direction==="horizontal"){return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React5.createElement("div",{style:{display:"flex",alignItems:"stretch",gap:0,width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React5.createElement("div",{key:`timeline-h-${index}`,style:{display:"flex",flexDirection:"column",gap:8,...eventWidth==null?{flex:1}:{},...(event.width??eventWidth)!=null?{width:event.width??eventWidth}:{},minWidth:0}},React5.createElement("div",{style:{display:"flex",alignItems:"center",width:"100%"}},React5.createElement("div",{style:{display:"flex",flex:1,height:2,backgroundColor:c.borderLight,opacity:index===0?0:1}}),React5.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,border:`3px solid ${c.bg}`,boxShadow:`0 0 0 1px ${accent}`,flexShrink:0}}),React5.createElement("div",{style:{display:"flex",flex:1,height:2,backgroundColor:c.borderLight,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math,eventWidth))}))]))}return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React5.createElement("div",{key:`timeline-v-${index}`,style:{display:"flex",alignItems:"stretch",gap:11,width:"100%"}},React5.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:markerSize+8,flexShrink:0}},React5.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:2,backgroundColor:c.borderLight,opacity:index===0?0:1}}),React5.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,border:`3px solid ${c.bg}`,boxShadow:`0 0 0 1px ${accent}`,flexShrink:0}}),React5.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:2,backgroundColor:c.borderLight,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math))}))]))}function renderFlowStage(stage,c,math){const tone=stage.tone??"blue";const hasDetails=Boolean(stage.children||stage.lines?.length);if(!hasDetails){return StepCard({title:stage.title,subtitle:stage.subtitle,eyebrow:stage.eyebrow,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding,math})}return Panel({title:stage.title,subtitle:stage.subtitle,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding??12,bodyStyle:{gap:8},children:stage.children??DetailList({items:stage.lines??[],c,tone,math})})}function Flow({stages,c,direction="horizontal",gap=10,connectorLength=28,connectorTone="neutral",align="center",math=false}){const isHorizontal=direction==="horizontal";const children=stages.flatMap((stage,index)=>{const elements=[React5.createElement(React5.Fragment,{key:`stage-${index}`},renderFlowStage(stage,c,math))];if(index<stages.length-1){elements.push(React5.createElement(React5.Fragment,{key:`connector-${index}`},FlowArrow({direction:isHorizontal?"right":"down",length:connectorLength,c,tone:connectorTone})))}return elements});return(isHorizontal?Row:Column)({gap,align,justify:"center",children})}import React6 from"react";import dagre from"@dagrejs/dagre";import{cloneElement,isValidElement}from"react";var SVG_ACCESSIBILITY_COMPONENT=Symbol.for("vizmatic.svgAccessibilityComponent");function componentHasSvgMetadata(type){return typeof type==="function"&&type[SVG_ACCESSIBILITY_COMPONENT]===true}function svgToken(value){if(value.length===0)return"empty";return Array.from(value,character=>{const codePoint=character.codePointAt(0)??0;return/^[A-Za-z0-9.-]$/.test(character)?character:`_u${codePoint.toString(16)}_`}).join("")}function textProperty(props,name){const value=props[name];return typeof value==="string"?value:""}function encodedTextProperty(props,name){const value=textProperty(props,name);try{return decodeURIComponent(value)}catch{return value}}function prepareAccessibleSvg(element){const graphs=[];const explicitIds=new Set;const visit=(node,graph)=>{if(Array.isArray(node))return node.map(child=>visit(child,graph));if(!isValidElement(node))return node;const component=node.type;if(componentHasSvgMetadata(component)){return visit(component(node.props),graph)}const props=node.props;const title=textProperty(props,"data-vizmatic-svg-title");const isGraphRoot=title.length>0;let activeGraph=graph;let elementKey=node.key;if(isGraphRoot){const explicitId=textProperty(props,"data-vizmatic-svg-id");if(explicitId){if(explicitIds.has(explicitId)){throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`)}explicitIds.add(explicitId)}const index=graphs.length;const token=explicitId?`id-${svgToken(explicitId)}`:`index-${index}`;activeGraph={index,token,detectionKey:`vizmatic-graph-${index}`,title,description:textProperty(props,"data-vizmatic-svg-description"),nodes:[],edges:[]};graphs.push(activeGraph);elementKey=activeGraph.detectionKey}let nextProps;if(activeGraph&&Object.hasOwn(props,"data-vizmatic-graph-node-id")){const id=textProperty(props,"data-vizmatic-graph-node-id");const label=textProperty(props,"data-vizmatic-graph-node-label")||id;const detail=textProperty(props,"data-vizmatic-graph-node-detail");activeGraph.nodes.push({id,label,detail,title:textProperty(props,"data-vizmatic-graph-node-title")||label,href:textProperty(props,"data-vizmatic-graph-node-href")||void 0});elementKey=`${activeGraph.detectionKey}-node-${svgToken(id)}`}else if(activeGraph&&textProperty(props,"data-vizmatic-graph-edge-id")){const id=encodedTextProperty(props,"data-vizmatic-graph-edge-id");activeGraph.edges.push({id,from:encodedTextProperty(props,"data-vizmatic-graph-edge-from"),to:encodedTextProperty(props,"data-vizmatic-graph-edge-to"),label:encodedTextProperty(props,"data-vizmatic-graph-edge-label"),title:encodedTextProperty(props,"data-vizmatic-graph-edge-title"),path:textProperty(props,"d"),href:encodedTextProperty(props,"data-vizmatic-graph-edge-href")||void 0});elementKey=`${activeGraph.detectionKey}-edge-${svgToken(id)}`}const children=props.children;if(children===void 0){if(isGraphRoot){nextProps={...props,"data-vizmatic-svg-instance":activeGraph?.token};return cloneElement(node,{...nextProps,key:elementKey})}return node}const preparedChildren=visit(children,activeGraph);nextProps=isGraphRoot?{...props,"data-vizmatic-svg-instance":activeGraph?.token}:{...props};return cloneElement(node,{...nextProps,key:elementKey},preparedChildren)};return{element:visit(element),graphs}}function escapeXml(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function attribute(name,value){return`${name}="${escapeXml(value)}"`}function graphBaseId(graph){return`vizmatic-graph-${graph.token}`}function nodeId(graph,node){return`${graphBaseId(graph)}-node-${svgToken(node.id)}`}function edgeId(graph,edge){return`${graphBaseId(graph)}-edge-${svgToken(edge.id)}`}function labelForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return edge.title||(edge.label?`${from} to ${to}: ${edge.label}`:`${from} to ${to}`)}function descriptionForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return`Relationship from ${from} to ${to}${edge.label?`, labeled ${edge.label}`:""}.`}function nodeGroup(graph,node,layout){const id=nodeId(graph,node);const label=node.detail?`${node.label}: ${node.detail}`:node.label;const description=node.detail||node.label;const titleId=`${id}-title`;const descriptionId=`${id}-description`;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>`;if(!layout)return`${accessible}</g>`;const rect=`<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;const hitTarget=node.href?`<a ${attribute("href",node.href)} role="link" tabindex="0" ${attribute("aria-label",label)}>${rect}</a>`:rect;return`${accessible}${hitTarget}</g>`}function edgeGroup(graph,edge,root){const id=edgeId(graph,edge);const title=labelForEdge(graph,edge);const titleId=`${id}-title`;const descriptionId=`${id}-description`;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>`;if(!root||!edge.path)return`${accessible}</g>`;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"/>`;const hitTarget=edge.href?`<a ${attribute("href",edge.href)} role="link" tabindex="0" ${attribute("aria-label",title)}>${path}</a>`:path;return`${accessible}${hitTarget}</g>`}function addSvgAccessibility(svg,graphs,layoutNodes){if(graphs.length===0)return svg;const title=graphs.map(graph=>graph.title).join(". ");const description=graphs.map(graph=>`${graph.title}. ${graph.description}`).join(" ");const hasLinks=graphs.some(graph=>graph.nodes.some(node=>node.href)||graph.edges.some(edge=>edge.href));const rootTitleId="vizmatic-svg-title";const rootDescriptionId="vizmatic-svg-description";const groupMarkup=graphs.map(graph=>{const baseId=graphBaseId(graph);const titleId=`${baseId}-title`;const descriptionId=`${baseId}-description`;const root=layoutNodes.find(node=>node.key===graph.detectionKey);const nodes=graph.nodes.map(item=>{const layout=layoutNodes.find(node=>node.key===`${graph.detectionKey}-node-${svgToken(item.id)}`);if(item.href&&!layout){throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`)}return nodeGroup(graph,item,layout)}).join("");const edges=graph.edges.map(item=>{if(item.href&&!root){throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`)}return edgeGroup(graph,item,root)}).join("");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>`}).join("");const metadata=`<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>`<svg${attrs} role="${hasLinks?"group":"img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`).replace(/<\/svg>\s*$/,`${groupMarkup}</svg>`)}var EPSILON=.001;var MAX_GRID_POINTS=18e3;var MAX_SEARCH_STATES=54e3;var MAX_TOTAL_SEARCH_STATES=16e4;var MAX_ROUTED_EDGES=256;var MAX_OBSTACLES=64;var sides=["right","bottom","left","top"];function box(node,clearance=0){return{left:node.cx-node.width/2-clearance,right:node.cx+node.width/2+clearance,top:node.cy-node.height/2-clearance,bottom:node.cy+node.height/2+clearance}}function inside(point,obstacle){return point.x>obstacle.left+EPSILON&&point.x<obstacle.right-EPSILON&&point.y>obstacle.top+EPSILON&&point.y<obstacle.bottom-EPSILON}function routingSegmentBlocked(a,b,obstacle){if(Math.abs(a.y-b.y)<EPSILON){return a.y>obstacle.top+EPSILON&&a.y<obstacle.bottom-EPSILON&&Math.max(a.x,b.x)>obstacle.left+EPSILON&&Math.min(a.x,b.x)<obstacle.right-EPSILON}if(Math.abs(a.x-b.x)<EPSILON){return a.x>obstacle.left+EPSILON&&a.x<obstacle.right-EPSILON&&Math.max(a.y,b.y)>obstacle.top+EPSILON&&Math.min(a.y,b.y)<obstacle.bottom-EPSILON}return true}function preferredSide(from,to){if(Math.abs(to.cx-from.cx)>=Math.abs(to.cy-from.cy))return to.cx>=from.cx?"right":"left";return to.cy>=from.cy?"bottom":"top"}function routingAnchor(node,side,offset=.5){const bounds=box(node);if(side==="left"||side==="right")return{x:bounds[side],y:bounds.top+node.height*offset};return{x:bounds.left+node.width*offset,y:bounds[side]}}function outward(point,side,distance){return{x:point.x+(side==="right"?distance:side==="left"?-distance:0),y:point.y+(side==="bottom"?distance:side==="top"?-distance:0)}}function simplify(points){const result=[];for(const point of points){const last=result[result.length-1];if(last&&Math.abs(last.x-point.x)<EPSILON&&Math.abs(last.y-point.y)<EPSILON)continue;const previous=result[result.length-2];if(previous&&last&&(previous.x===last.x&&last.x===point.x||previous.y===last.y&&last.y===point.y)){result[result.length-1]=point}else result.push(point)}return result}function overlappingLength(a,b,c,d){if(a.y===b.y&&c.y===d.y&&Math.abs(a.y-c.y)<EPSILON){return Math.max(0,Math.min(Math.max(a.x,b.x),Math.max(c.x,d.x))-Math.max(Math.min(a.x,b.x),Math.min(c.x,d.x)))}if(a.x===b.x&&c.x===d.x&&Math.abs(a.x-c.x)<EPSILON){return Math.max(0,Math.min(Math.max(a.y,b.y),Math.max(c.y,d.y))-Math.max(Math.min(a.y,b.y),Math.min(c.y,d.y)))}return 0}var MinQueue=class{items=[];get length(){return this.items.length}push(value){const items=this.items;items.push(value);let index=items.length-1;while(index>0){const parent=index-1>>1;if(items[parent].priority<=value.priority)break;items[index]=items[parent];index=parent}items[index]=value}pop(){const items=this.items;const first=items[0];const last=items.pop();if(items.length===0)return first;let index=0;while(index*2+1<items.length){const left=index*2+1;const right=left+1;const child=right<items.length&&items[right].priority<items[left].priority?right:left;if(items[child].priority>=last.priority)break;items[index]=items[child];index=child}items[index]=last;return first}};function findPath(start,end,obstacles,width,height,previousRoutes,gap,budget){const within=point=>point.x>=0&&point.x<=width&&point.y>=0&&point.y<=height;if(!within(start)||!within(end)||obstacles.some(obstacle=>inside(start,obstacle)||inside(end,obstacle))){return{reason:"an endpoint has no clear exit inside the canvas"}}const xs=new Set([0,width,start.x,end.x]);const ys=new Set([0,height,start.y,end.y]);for(const obstacle of obstacles){if(obstacle.left>=0&&obstacle.left<=width)xs.add(obstacle.left);if(obstacle.right>=0&&obstacle.right<=width)xs.add(obstacle.right);if(obstacle.top>=0&&obstacle.top<=height)ys.add(obstacle.top);if(obstacle.bottom>=0&&obstacle.bottom<=height)ys.add(obstacle.bottom)}for(const route of previousRoutes.slice(-8))for(const point of route){for(const offset of[-gap,gap]){if(point.x+offset>=0&&point.x+offset<=width)xs.add(point.x+offset);if(point.y+offset>=0&&point.y+offset<=height)ys.add(point.y+offset)}}const xValues=[...xs].sort((a,b)=>a-b);const yValues=[...ys].sort((a,b)=>a-b);const columns=xValues.length;const gridSize=columns*yValues.length;if(gridSize>MAX_GRID_POINTS)return{reason:`routing grid exceeds ${MAX_GRID_POINTS} points; simplify the graph`};const startIndex=yValues.indexOf(start.y)*columns+xValues.indexOf(start.x);const endIndex=yValues.indexOf(end.y)*columns+xValues.indexOf(end.x);const pointAt=index=>({x:xValues[index%columns],y:yValues[Math.floor(index/columns)]});const costs=new Float64Array(gridSize*3).fill(Infinity);const parents=new Int32Array(gridSize*3).fill(-1);const queue=new MinQueue;costs[startIndex*3]=0;queue.push({state:startIndex*3,cost:0,priority:0});let visits=0;while(queue.length>0){if(--budget.remaining<0)return{reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`};if(++visits>MAX_SEARCH_STATES)return{reason:`routing search exceeds ${MAX_SEARCH_STATES} states; simplify the graph`};const current=queue.pop();if(current.cost!==costs[current.state])continue;const index=Math.floor(current.state/3);const axis=current.state%3;if(index===endIndex){const points=[];for(let state=current.state;state>=0;state=parents[state])points.push(pointAt(Math.floor(state/3)));return{points:simplify(points.reverse())}}const a=pointAt(index);const column=index%columns;const row=Math.floor(index/columns);const neighbors=[column>0?index-1:-1,column<columns-1?index+1:-1,row>0?index-columns:-1,row<yValues.length-1?index+columns:-1];for(const neighbor of neighbors){if(neighbor<0)continue;const b=pointAt(neighbor);if(obstacles.some(obstacle=>routingSegmentBlocked(a,b,obstacle)))continue;const nextAxis=a.y===b.y?1:2;const state=neighbor*3+nextAxis;let overlap=0;for(const route of previousRoutes)for(let i=1;i<route.length;i++)overlap+=overlappingLength(a,b,route[i-1],route[i]);const cost=current.cost+Math.abs(b.x-a.x)+Math.abs(b.y-a.y)+(axis!==0&&axis!==nextAxis?18:0)+overlap*5;if(cost>=costs[state])continue;costs[state]=cost;parents[state]=current.state;queue.push({state,cost,priority:cost+Math.abs(end.x-b.x)+Math.abs(end.y-b.y)})}}return{reason:"no obstacle-free route exists inside the canvas"}}function endpoint(node,other,portId,requestedSide,selfLoop,target,ordinal,count,gap){const port=node.ports?.find(candidate=>candidate.id===portId);const side=port?.side??requestedSide??(selfLoop?target?"top":"right":preferredSide(node,other));const length=side==="left"||side==="right"?node.height:node.width;const separation=count>1?Math.min(gap,length*.7/(count-1)):0;const offset=port?port.offset??.5:.5+(ordinal-(count-1)/2)*separation/length;return{side,anchor:routingAnchor(node,side,offset),explicit:portId!=null||requestedSide!=null}}function straightGraphRoute(from,to,edge){return[endpoint(from,to,edge.fromPort,edge.fromSide,false,false,0,1,0).anchor,endpoint(to,from,edge.toPort,edge.toSide,false,true,0,1,0).anchor]}function routeOrthogonalGraph(nodes,edges,width,height,clearance=12,gap=14,extraObstacles=[]){const routes=new Map;const failures=[];const byId=new Map(nodes.map(node=>[node.id,node]));const obstacles=[...nodes.map(node=>box(node,clearance)),...extraObstacles.map(obstacle=>({left:obstacle.left-clearance,right:obstacle.right+clearance,top:obstacle.top-clearance,bottom:obstacle.bottom+clearance}))];const routeKey=edge=>[edge.from,edge.to].sort().join("\0");const counts2=new Map;for(const edge of edges)counts2.set(routeKey(edge),(counts2.get(routeKey(edge))??0)+1);const occurrences=new Map;const previous=new Map;const budget={remaining:MAX_TOTAL_SEARCH_STATES};edges.forEach((edge,index)=>{if(index>=MAX_ROUTED_EDGES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_ROUTED_EDGES} edges per diagram`});return}if(obstacles.length>MAX_OBSTACLES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_OBSTACLES} node and header obstacles per diagram`});return}if(budget.remaining<0){failures.push({index,reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`});return}const from=byId.get(edge.from);const to=byId.get(edge.to);const key=routeKey(edge);const ordinal=occurrences.get(key)??0;occurrences.set(key,ordinal+1);const count=counts2.get(key)??1;const source=endpoint(from,to,edge.fromPort,edge.fromSide,from===to,false,ordinal,count,gap);const target=endpoint(to,from,edge.toPort,edge.toSide,from===to,true,ordinal,count,gap);const sourceSides=source.explicit?[source.side]:[source.side,...sides.filter(side=>side!==source.side)];const targetSides=target.explicit?[target.side]:[target.side,...sides.filter(side=>side!==target.side)];let failure="no obstacle-free route exists inside the canvas";for(const sourceSide of sourceSides){for(const targetSide of targetSides){const start=sourceSide===source.side?source.anchor:routingAnchor(from,sourceSide);const end=targetSide===target.side?target.anchor:routingAnchor(to,targetSide);if(from===to&&start.x===end.x&&start.y===end.y){failure="a self-loop requires distinct endpoint anchors";continue}const leadStart=outward(start,sourceSide,clearance);const leadEnd=outward(end,targetSide,clearance);if(obstacles.some((obstacle,obstacleIndex)=>obstacleIndex!==nodes.indexOf(from)&&routingSegmentBlocked(start,leadStart,obstacle)||obstacleIndex!==nodes.indexOf(to)&&routingSegmentBlocked(leadEnd,end,obstacle))){failure="another obstacle blocks an endpoint exit";continue}const result=findPath(leadStart,leadEnd,obstacles,width,height,previous.get(key)??[],Math.max(1,gap),budget);if(!result.points){failure=result.reason;if(/routing (grid|search|budget)/.test(failure)){failures.push({index,reason:failure});return}continue}const points=simplify([start,...result.points,end]);if(points.length<2)continue;const repeated=(previous.get(key)??[]).some(route=>route.length===points.length&&(route.every((point,position)=>point.x===points[position].x&&point.y===points[position].y)||route.every((point,position)=>point.x===points[points.length-1-position].x&&point.y===points[points.length-1-position].y)));if(repeated){failure="parallel connectors have no separate lane at the requested clearance";continue}routes.set(index,points);previous.set(key,[...previous.get(key)??[],points]);return}}failures.push({index,reason:failure})});return{routes,failures}}function routingLabelPosition(points){let longest=0;let position=points[0];for(let i=1;i<points.length;i++){const a=points[i-1];const b=points[i];const length=Math.abs(a.x-b.x)+Math.abs(a.y-b.y);if(length>longest){longest=length;position={x:(a.x+b.x)/2,y:(a.y+b.y)/2}}}return position}function distributeValues(count,start,end){if(count<=0)return[];if(count===1)return[(start+end)/2];const step=(end-start)/(count-1);return Array.from({length:count},(_,index)=>start+index*step)}function LayeredNetwork({c,layers,ariaLabel="Layered network diagram",activePath=[],annotations=[],formula,legend="highlighted path",width=900,height=400,nodeSize=56,showFormula=true}){const radius=nodeSize/2;const top=82;const bottom=showFormula||formula?height-118:height-42;const layerXs=distributeValues(layers.length,82,width-82);const nodeLayout=layers.map((layer,layerIndex)=>({...layer,x:layerXs[layerIndex],ys:distributeValues(layer.nodes.length,top,bottom),tone:layer.tone??"purple"}));const connectionElements=nodeLayout.slice(0,-1).flatMap((from,layerIndex)=>{const to=nodeLayout[layerIndex+1];return from.ys.flatMap((fromY,fromIndex)=>to.ys.map((toY,toIndex)=>{const active=activePath[layerIndex]===fromIndex&&activePath[layerIndex+1]===toIndex;return React6.createElement("line",{key:`connection-${layerIndex}-${fromIndex}-${toIndex}`,x1:from.x+radius+4,y1:fromY,x2:to.x-radius-4,y2:toY,stroke:active?c.warningLight:c.borderLight,strokeWidth:active?3.6:1.2,strokeOpacity:active?.98:.42,strokeLinecap:"round"})}))});const label=(key,text,x,y,labelWidth,color,fontSize=13,fontWeight=800,fontFamily="Inter")=>React6.createElement("div",{key,style:{position:"absolute",left:x-labelWidth/2,top:y,width:labelWidth,display:"flex",justifyContent:"center",color,fontSize,fontWeight,fontFamily,lineHeight:1.15,textAlign:"center"}},formatMathText(text));const titleElements=nodeLayout.map(layer=>label(`title-${layer.title}`,layer.title,layer.x,20,120,getReadableToneColor(layer.tone,c),16,900));const nodeElements=nodeLayout.flatMap((layer,layerIndex)=>layer.ys.flatMap((y,nodeIndex)=>{const active=activePath[layerIndex]===nodeIndex;const color=getToneColor(layer.tone,c);return[active&&React6.createElement("div",{key:`halo-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius-14,top:y-radius-14,width:nodeSize+28,height:nodeSize+28,borderRadius:999,backgroundColor:`${c.warningLight}2e`,border:`4px solid ${c.warningLight}`,boxSizing:"border-box",boxShadow:`0 0 18px ${c.warningLight}66`}}),React6.createElement("div",{key:`node-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius,top:y-radius,width:nodeSize,height:nodeSize,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,color:getReadableTextColor(color,c),border:active?`3px solid ${c.warningLight}`:`1.5px solid ${color}`,boxSizing:"border-box",boxShadow:active?`0 0 16px ${c.warningLight}70`:`0 8px 14px ${c.shadow}`,fontFamily:"JetBrains Mono",fontSize:16,fontWeight:900,lineHeight:1}},formatMathText(layer.nodes[nodeIndex]))]}).filter(Boolean));const annotationY=showFormula||formula?height-84:height-26;const annotationElements=annotations.slice(0,Math.max(0,layerXs.length-1)).map((annotation,index)=>label(`annotation-${index}`,annotation,(layerXs[index]+layerXs[index+1])/2,annotationY,132,c.textMuted,13,800,"JetBrains Mono"));const formulaElement=(showFormula||formula)&&formula?React6.createElement("div",{key:"formula-wrap",style:{position:"absolute",left:width/2-244,top:height-52,width:488,height:44,borderRadius:10,border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard,display:"flex",alignItems:"center",justifyContent:"center",color:c.textPrimary,fontFamily:"Inter",fontSize:15,fontWeight:850,boxShadow:`0 8px 18px ${c.shadow}`}},formatMathText(formula)):null;const legendElement=(showFormula||formula)&&formula?React6.createElement("div",{key:"legend-wrap",style:{position:"absolute",left:width-184,top:height-43,width:160,display:"flex",alignItems:"center",gap:14,color:c.textSecondary,fontFamily:"Inter",fontSize:12,fontWeight:800}},React6.createElement("div",{style:{width:42,height:5,borderRadius:999,backgroundColor:c.warningLight}}),legend):null;return React6.createElement("div",{role:"img","aria-label":ariaLabel,style:{width,height,maxWidth:"100%",position:"relative",display:"flex",alignSelf:"center",flexShrink:0}},React6.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,style:{position:"absolute",inset:0,overflow:"visible"}},...connectionElements),...titleElements,...nodeElements,...annotationElements,formulaElement,legendElement)}function defineDiagramIcon(id,render){return{id,render}}function defineIconRegistry(icons){return icons}function manualGraphLayout(nodes,width,height,nodeWidth,nodeHeight,padding){return new Map(nodes.map(node=>{const resolvedWidth=node.width??nodeWidth;const resolvedHeight=node.height??nodeHeight;const minCx=resolvedWidth/2;const maxCx=width-resolvedWidth/2;const minCy=resolvedHeight/2;const maxCy=height-resolvedHeight/2;const requestedCx=padding+clamp(node.x??.5,0,1)*(width-padding*2);const requestedCy=padding+clamp(node.y??.5,0,1)*(height-padding*2);return[node.id,{...node,width:resolvedWidth,height:resolvedHeight,cx:minCx<=maxCx?clamp(requestedCx,minCx,maxCx):width/2,cy:minCy<=maxCy?clamp(requestedCy,minCy,maxCy):height/2}]}))}function segmentCrosses(a1,a2,b1,b2){const cross=(origin,first,second)=>(first.x-origin.x)*(second.y-origin.y)-(first.y-origin.y)*(second.x-origin.x);const d1=cross(a1,a2,b1);const d2=cross(a1,a2,b2);const d3=cross(b1,b2,a1);const d4=cross(b1,b2,a2);const epsilon=.01;return d1*d2<-epsilon&&d3*d4<-epsilon}function connectorCrossings(edges){let crossings=0;for(let leftIndex=0;leftIndex<edges.length;leftIndex+=1){const left=edges[leftIndex];for(let rightIndex=leftIndex+1;rightIndex<edges.length;rightIndex+=1){const right=edges[rightIndex];if(left.from===right.from||left.from===right.to||left.to===right.from||left.to===right.to)continue;let crosses=false;for(let leftSegment=0;leftSegment<left.points.length-1&&!crosses;leftSegment+=1){for(let rightSegment=0;rightSegment<right.points.length-1;rightSegment+=1){if(segmentCrosses(left.points[leftSegment],left.points[leftSegment+1],right.points[rightSegment],right.points[rightSegment+1])){crosses=true;break}}}if(crosses)crossings+=1}}return crossings}function rectanglesOverlap(left,right,padding=0){return left.left<right.right+padding&&left.right>right.left-padding&&left.top<right.bottom+padding&&left.bottom>right.top-padding}function connectorLabelCollisions(edges,nodes,groups=[]){const labels=edges.flatMap(edge=>edge.label?[{bounds:{left:edge.labelX-estimatedEdgeLabelWidth(edge.label)/2,right:edge.labelX+estimatedEdgeLabelWidth(edge.label)/2,top:edge.labelY-10,bottom:edge.labelY+10}}]:[]);let collisions=0;for(let index=0;index<labels.length;index+=1){for(let otherIndex=index+1;otherIndex<labels.length;otherIndex+=1){if(rectanglesOverlap(labels[index].bounds,labels[otherIndex].bounds,4))collisions+=1}for(const node of nodes.values()){const bounds={left:node.cx-node.width/2,right:node.cx+node.width/2,top:node.cy-node.height/2,bottom:node.cy+node.height/2};if(rectanglesOverlap(labels[index].bounds,bounds))collisions+=1}for(const group of groups){const headerBounds={left:group.cx-group.width/2,right:group.cx+group.width/2,top:group.cy-group.height/2,bottom:group.cy-group.height/2+26};if(rectanglesOverlap(labels[index].bounds,headerBounds))collisions+=1}}return collisions}function crowdedConnectorEndpoints(edges){const degrees=new Map;for(const edge of edges){degrees.set(edge.from,(degrees.get(edge.from)??0)+1);degrees.set(edge.to,(degrees.get(edge.to)??0)+1)}return Array.from(degrees.values()).filter(degree=>degree>4).length}function parallelConnectorGroups(edges){const routes=new Map;for(const edge of edges){const key=`${edge.from}\0${edge.to}`;routes.set(key,(routes.get(key)??0)+1)}return Array.from(routes.values()).filter(count=>count>1).length}function edgePath(points){return points.map((point,index)=>`${index===0?"M":"L"} ${point.x} ${point.y}`).join(" ")}function estimatedEdgeLabelWidth(label){const units=Array.from(label.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0);return Math.max(28,Math.ceil(units*6+14))}function validateGraphDiagramSpec(nodes,edges,groups,layoutMode){const nodeIds=new Set;for(const node of nodes){if(nodeIds.has(node.id))throw new Error(`GraphDiagram received duplicate node id "${node.id}".`);nodeIds.add(node.id);const portIds=new Set;for(const port of node.ports??[]){if(typeof port.id!=="string"||port.id.trim().length===0){throw new Error(`GraphDiagram node "${node.id}" port id must be a non-empty string.`)}if(portIds.has(port.id))throw new Error(`GraphDiagram node "${node.id}" received duplicate port "${port.id}".`);portIds.add(port.id);if(!["top","right","bottom","left"].includes(port.side)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" must use side "top", "right", "bottom", or "left".`)}if(port.offset!=null&&(!Number.isFinite(port.offset)||port.offset<0||port.offset>1)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" offset must be between 0 and 1.`)}}}const groupsById=new Map;for(const group of groups){if(nodeIds.has(group.id)||groupsById.has(group.id)){throw new Error(`GraphDiagram node and group ids must be unique; received duplicate id "${group.id}".`)}groupsById.set(group.id,group)}for(const group of groups){if(group.parent!=null&&!groupsById.has(group.parent)){throw new Error(`GraphDiagram group "${group.id}" references missing parent group "${group.parent}".`)}const visited=new Set([group.id]);let parent=group.parent;while(parent!=null){if(visited.has(parent))throw new Error(`GraphDiagram groups contain a parent cycle at "${parent}".`);visited.add(parent);parent=groupsById.get(parent)?.parent}}const occupiedGroups=new Set;for(const node of nodes){if(node.group!=null&&!groupsById.has(node.group)){throw new Error(`GraphDiagram node "${node.id}" references missing group "${node.group}".`)}let groupId=node.group;while(groupId!=null){occupiedGroups.add(groupId);groupId=groupsById.get(groupId)?.parent}}for(const group of groups){if(!occupiedGroups.has(group.id))throw new Error(`GraphDiagram group "${group.id}" contains no nodes.`)}const edgeIds=new Set;for(const edge of edges){if(!nodeIds.has(edge.from)||!nodeIds.has(edge.to)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}if(edge.id!=null){if(edgeIds.has(edge.id))throw new Error(`GraphDiagram received duplicate edge id "${edge.id}".`);edgeIds.add(edge.id)}for(const side of["from","to"]){const reference=side==="from"?edge.fromPort:edge.toPort;const endpointSide=side==="from"?edge.fromSide:edge.toSide;const node=nodes.find(candidate=>candidate.id===edge[side]);if(reference!=null&&!node.ports?.some(port=>port.id===reference)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references missing ${side} port "${reference}" on node "${node.id}".`)}if(endpointSide!=null&&!["top","right","bottom","left"].includes(endpointSide)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" ${side}Side must be "top", "right", "bottom", or "left".`)}if(reference!=null&&endpointSide!=null){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" cannot combine ${side}Port and ${side}Side.`)}}validateDiagramHref(edge.href,`edge "${edge.id??`${edge.from}" -> "${edge.to}`}"`)}for(const node of nodes){validateDiagramHref(node.href,`node "${node.id}"`)}if(groups.length>0&&layoutMode==="manual"){throw new Error('GraphDiagram groups require automatic layout; omit node coordinates and layout="manual".')}}function validateDiagramHref(href,owner){if(href==null)return;const normalized=href.trim().replace(/[\u0000-\u0020\u007f]/g,"");const scheme=/^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1]?.toLowerCase();if(scheme&&!["http","https","mailto","tel"].includes(scheme)){throw new Error(`GraphDiagram ${owner} has an unsupported link scheme "${scheme}:".`)}}function graphAccessibleText(value){if(typeof value==="string"||typeof value==="number")return String(value).trim();if(Array.isArray(value))return value.map(graphAccessibleText).filter(Boolean).join(" ");if(React6.isValidElement(value)){const props=value.props;return graphAccessibleText(props.children)}return""}function graphDescription(nodes,edges){const labels=new Map(nodes.map(node=>[node.id,graphAccessibleText(node.label)||node.id]));const parts=[`${nodes.length} nodes and ${edges.length} relationships.`];const relationships=edges.slice(0,8).map(edge=>{const from=labels.get(edge.from)??edge.from;const to=labels.get(edge.to)??edge.to;return edge.label?`${from} ${edge.label} ${to}`:`${from} to ${to}`});if(relationships.length)parts.push(relationships.join("; "));if(edges.length>relationships.length)parts.push(`${edges.length-relationships.length} more relationships`);return parts.join(" ")}function graphGroupDepth(group,groupsById){let depth=0;let parent=group.parent;while(parent!=null){depth+=1;parent=groupsById.get(parent)?.parent}return depth}function resolvedGraphEdgeStyle(edge){if(edge.style)return edge.style;if(edge.dashed)return"dashed";if(edge.kind==="async"||edge.kind==="dependency")return"dashed";if(edge.kind==="event")return"dotted";return"solid"}function resolvedGraphEdgeArrow(edge){return edge.arrow??(edge.kind==="association"?"none":"forward")}function GraphDiagram({nodes,edges,groups=[],c,width,height,nodeWidth=150,nodeHeight=66,labelFontSize=14,detailFontSize=11,arrowSize=5,padding=28,layout:requestedLayout,direction="LR",nodeGap=34,rankGap=64,edgeGap=14,routing="dagre",routingClearance=12,sizing="content",iconSize=20,id,ariaLabel,title,description}){if(id!=null&&id.trim().length===0)throw new Error("GraphDiagram id must not be empty.");if(!["dagre","straight","orthogonal"].includes(routing))throw new Error('GraphDiagram routing must be "dagre", "straight", or "orthogonal".');if(!Number.isFinite(routingClearance)||routingClearance<=0)throw new Error("GraphDiagram routingClearance must be a finite positive number.");const fullyPositioned=nodes.filter(node=>node.x!=null&&node.y!=null).length;const partiallyPositioned=nodes.some(node=>node.x==null!==(node.y==null));if(partiallyPositioned||fullyPositioned>0&&fullyPositioned<nodes.length){throw new Error("GraphDiagram nodes must either all define both x and y, or all omit coordinates for automatic layout.")}const layoutMode=requestedLayout??(fullyPositioned===nodes.length?"manual":"auto");if(layoutMode==="manual"&&fullyPositioned!==nodes.length){throw new Error('GraphDiagram layout="manual" requires x and y on every node.')}validateGraphDiagramSpec(nodes,edges,groups,layoutMode);const edgeOccurrences=new Map;const stableEdgeIds=edges.map(edge=>{if(edge.id!=null)return`custom-${edge.id}`;const route=`${edge.from}\0${edge.to}`;const occurrence=edgeOccurrences.get(route)??0;edgeOccurrences.set(route,occurrence+1);return`route-${edge.from}-to-${edge.to}-${occurrence}`});if(new Set(stableEdgeIds).size!==stableEdgeIds.length){throw new Error("GraphDiagram edge ids must not collide with generated relationship ids.")}const svgTitle=title?.trim()||ariaLabel?.trim()||"Graph diagram";const svgDescription=description??graphDescription(nodes,edges);let resolvedWidth=width??520;let resolvedHeight=height??420;let layout;let groupLayout=[];let autoEdgePoints=new Map;if(layoutMode==="auto"){const compoundGap=groups.length>0?34:0;const graph=new dagre.graphlib.Graph({multigraph:true,compound:groups.length>0}).setGraph({rankdir:direction,nodesep:Math.max(nodeGap,compoundGap),ranksep:Math.max(rankGap,compoundGap),edgesep:edgeGap,marginx:padding,marginy:padding}).setDefaultEdgeLabel(()=>({}));for(const group of groups)graph.setNode(group.id,{width:0,height:0});for(const node of nodes){graph.setNode(node.id,{width:node.width??nodeWidth,height:node.height??nodeHeight})}for(const group of groups){if(group.parent!=null)graph.setParent(group.id,group.parent)}for(const node of nodes){if(node.group!=null)graph.setParent(node.id,node.group)}edges.forEach((edge,index)=>{const labelWidth=edge.label?estimatedEdgeLabelWidth(edge.label):0;graph.setEdge(edge.from,edge.to,{width:labelWidth,height:edge.label?18:0},`edge-${index}`)});dagre.layout(graph);const graphSize=graph.graph();if(sizing==="content"){resolvedWidth=Math.max(width??520,Math.ceil(graphSize.width??0));resolvedHeight=Math.max(height??420,Math.ceil(graphSize.height??0))}const offsetX=(resolvedWidth-(graphSize.width??resolvedWidth))/2;const offsetY=(resolvedHeight-(graphSize.height??resolvedHeight))/2;layout=new Map(nodes.map(node=>{const position=graph.node(node.id);return[node.id,{...node,width:node.width??nodeWidth,height:node.height??nodeHeight,cx:(position?.x??resolvedWidth/2)+offsetX,cy:(position?.y??resolvedHeight/2)+offsetY}]}));const groupsById=new Map(groups.map(group=>[group.id,group]));groupLayout=groups.map(group=>{const position=graph.node(group.id);return{...group,width:position?.width??0,height:position?.height??0,cx:(position?.x??resolvedWidth/2)+offsetX,cy:(position?.y??resolvedHeight/2)+offsetY,depth:graphGroupDepth(group,groupsById)}}).sort((left,right)=>left.depth-right.depth);autoEdgePoints=new Map(edges.map((edge,index)=>{const placed=graph.edge({v:edge.from,w:edge.to,name:`edge-${index}`});const points=(placed?.points??[]).map(point=>({x:point.x+offsetX,y:point.y+offsetY}));return[index,{points,labelX:placed?.x!=null?placed.x+offsetX:points[Math.floor(points.length/2)]?.x??resolvedWidth/2,labelY:placed?.y!=null?placed.y+offsetY:points[Math.floor(points.length/2)]?.y??resolvedHeight/2}]}))}else{layout=manualGraphLayout(nodes,resolvedWidth,resolvedHeight,nodeWidth,nodeHeight,padding)}const anchored=edge=>edge.fromPort!=null||edge.toPort!=null||edge.fromSide!=null||edge.toSide!=null;const orthogonalEdges=edges.flatMap((edge,index)=>routing==="orthogonal"||routing==="dagre"&&anchored(edge)||routing==="straight"&&edge.from===edge.to?[{edge,index}]:[]);const routed=routeOrthogonalGraph(Array.from(layout.values()),orthogonalEdges.map(({edge})=>edge),resolvedWidth,resolvedHeight,routingClearance,edgeGap,groupLayout.map(group=>({left:group.cx-group.width/2,right:group.cx+group.width/2,top:group.cy-group.height/2,bottom:group.cy-group.height/2+26})));const orthogonalPoints=new Map(Array.from(routed.routes,([index,points])=>[orthogonalEdges[index].index,points]));const failedIndexes=new Set(routed.failures.map(failure=>orthogonalEdges[failure.index].index));const routingFailures=routed.failures.map(failure=>{const{edge}=orthogonalEdges[failure.index];return`Connector "${edge.from}" -> "${edge.to}" was not drawn: ${failure.reason}.`});const edgeLayouts=edges.flatMap((edge,index)=>{if(failedIndexes.has(index))return[];const from=layout.get(edge.from);const to=layout.get(edge.to);if(!from||!to)return[];const automatic=autoEdgePoints.get(index);const selfLoop=edge.from===edge.to;if(!selfLoop&&from.cx===to.cx&&from.cy===to.cy&&!automatic?.points.length)return[];const dx=to.cx-from.cx;const dy=to.cy-from.cy;const absDx=Math.abs(dx);const absDy=Math.abs(dy);const fromScale=Math.min(absDx>0?from.width/2/absDx:Infinity,absDy>0?from.height/2/absDy:Infinity);const toScale=Math.min(absDx>0?to.width/2/absDx:Infinity,absDy>0?to.height/2/absDy:Infinity);const color=edge.muted?c.textMuted:c.preset==="engineering"&&edge.tone==null?c.textSecondary:getToneColor(edge.tone??"blue",c);const markerId=`graph-arrow-${edge.from}-${edge.to}-${index}-${arrowSize}-${color}`.replace(/[^a-zA-Z0-9_-]/g,"-");const loopClearance=Math.max(24,arrowSize*5);const manualLoopPoints=selfLoop?[{x:from.cx+from.width/2,y:from.cy-8},{x:from.cx+from.width/2+loopClearance,y:from.cy-8},{x:from.cx+from.width/2+loopClearance,y:from.cy-from.height/2-loopClearance},{x:from.cx+10,y:from.cy-from.height/2-loopClearance},{x:from.cx+10,y:from.cy-from.height/2}]:void 0;const routedPoints=orthogonalPoints.get(index);const points=routedPoints??(routing==="straight"?straightGraphRoute(from,to,edge):automatic?.points.length?automatic.points:manualLoopPoints??[{x:from.cx+dx*fromScale,y:from.cy+dy*fromScale},{x:to.cx-dx*toScale,y:to.cy-dy*toScale}]);const manualLoopLabel=manualLoopPoints?{x:from.cx+from.width/2+loopClearance,y:from.cy-from.height/2-loopClearance/2}:void 0;const routedLabel=routedPoints||routing==="straight"?routingLabelPosition(points):void 0;return[{...edge,index,stableId:stableEdgeIds[index],color,markerId,points,labelX:routedLabel?.x??automatic?.labelX??manualLoopLabel?.x??(points[0].x+points[points.length-1].x)/2,labelY:routedLabel?.y??automatic?.labelY??manualLoopLabel?.y??(points[0].y+points[points.length-1].y)/2}]});const crossings=connectorCrossings(edgeLayouts);const labelCollisions=connectorLabelCollisions(edgeLayouts,layout,groupLayout);const crowdedEndpoints=crowdedConnectorEndpoints(edgeLayouts);const parallelGroups=parallelConnectorGroups(edgeLayouts.filter(edge=>!orthogonalPoints.has(edge.index)));const groupElements=groupLayout.map(group=>{const accent=group.muted?c.textMuted:getToneColor(group.tone??"blue",c);return React6.createElement("div",{key:`graph-group-${group.id}`,"data-vizmatic-graph-group":group.id,style:{position:"absolute",left:group.cx-group.width/2,top:group.cy-group.height/2,width:group.width,height:group.height,display:"flex",boxSizing:"border-box",borderRadius:c.preset==="engineering"?6:12,border:`${c.preset==="engineering"?1.25:1.5}px ${group.muted?"dashed":"solid"} ${accent}${group.muted?"55":"77"}`,backgroundColor:`${accent}${c.preset==="engineering"?"08":"0d"}`,opacity:group.muted?.68:1}},React6.createElement("div",{style:{position:"absolute",left:10,top:5,display:"flex",alignItems:"baseline",gap:7,width:Math.max(0,group.width-20),overflow:"hidden",color:group.muted?c.textMuted:getReadableToneColor(group.tone??"blue",c),fontFamily:c.fontSans,lineHeight:1,whiteSpace:"nowrap"}},React6.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",fontSize:12,fontWeight:800}},group.label),group.detail&&React6.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",color:c.textMuted,fontFamily:c.fontMono,fontSize:11,fontWeight:500}},group.detail)))});return React6.createElement("div",{key:"vizmatic-graph-root",role:"img","aria-label":ariaLabel??svgTitle,"data-vizmatic-svg-title":svgTitle,"data-vizmatic-svg-description":svgDescription,"data-vizmatic-svg-id":id,"data-vizmatic-connector-crossings":crossings,"data-vizmatic-connector-label-collisions":labelCollisions,"data-vizmatic-crowded-connector-endpoints":crowdedEndpoints,"data-vizmatic-parallel-connector-groups":parallelGroups,"data-vizmatic-unrouted-connectors":routingFailures.length,"data-vizmatic-routing-failures":routingFailures.length?JSON.stringify(routingFailures):void 0,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},...groupElements,React6.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React6.createElement("defs",{},...edgeLayouts.map(edge=>ArrowMarkerDef({id:edge.markerId,color:edge.color,size:arrowSize}))),...edgeLayouts.map(edge=>React6.createElement("path",{key:`graph-edge-${edge.index}`,"data-vizmatic-graph-edge-id":encodeURIComponent(edge.stableId),"data-vizmatic-graph-edge-from":encodeURIComponent(edge.from),"data-vizmatic-graph-edge-to":encodeURIComponent(edge.to),"data-vizmatic-graph-edge-label":encodeURIComponent(edge.label??""),"data-vizmatic-graph-edge-title":encodeURIComponent(edge.title??""),"data-vizmatic-graph-edge-href":edge.href==null?void 0:encodeURIComponent(edge.href),d:edgePath(edge.points),fill:"none",stroke:edge.color,strokeWidth:edge.muted?1.4:c.preset==="engineering"?1.7:2.8,strokeDasharray:resolvedGraphEdgeStyle(edge)==="dashed"?"7 6":resolvedGraphEdgeStyle(edge)==="dotted"?"2 6":void 0,strokeLinecap:"round",opacity:edge.muted?.48:.9,markerStart:resolvedGraphEdgeArrow(edge)==="backward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerId})`:void 0,markerEnd:resolvedGraphEdgeArrow(edge)==="forward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerId})`:void 0}))),...edgeLayouts.flatMap(edge=>edge.label?[React6.createElement("div",{key:`graph-edge-label-${edge.index}`,style:{position:"absolute",left:edge.labelX,top:edge.labelY,transform:"translate(-50%, -50%)",padding:c.preset==="engineering"?"3px 5px":"3px 7px",borderRadius:c.preset==="engineering"?0:999,backgroundColor:c.preset==="engineering"?c.bg:c.bgCard,border:c.preset==="engineering"?"none":`1px solid ${c.borderSubtle}`,color:edge.muted?c.textMuted:c.preset==="engineering"?c.textSecondary:getReadableToneColor(edge.tone??"blue",c),fontFamily:c.fontMono,fontSize:11,fontWeight:c.preset==="engineering"?400:800,lineHeight:1,...c.preset==="engineering"?{textTransform:"uppercase",letterSpacing:"0.02em"}:{},whiteSpace:"nowrap"}},edge.label)]:[]),...Array.from(layout.values()).map(node=>{const accent=node.muted?c.textMuted:getToneColor(node.tone??"blue",c);const fill=getToneFill(node.tone??"blue",c);const accentText=node.muted?c.textMuted:getReadableToneColor(node.tone??"blue",c,fill,c.bg);const resolvedIconSize=clamp(node.iconSize??iconSize,8,Math.max(8,Math.min(node.width,node.height)-16));const iconLabel=typeof node.label==="string"?`${node.label} icon`:void 0;const iconElement=typeof node.icon==="string"?Icon({c,name:node.icon,color:accent,size:resolvedIconSize,label:iconLabel,muted:node.muted}):React6.isValidElement(node.icon)?node.icon:node.icon?.render({c,color:accent,size:resolvedIconSize,label:iconLabel});const icon=iconElement&&React6.createElement("div",{"data-vizmatic-graph-icon":node.id,style:{width:resolvedIconSize,height:resolvedIconSize,display:"flex",alignItems:"center",justifyContent:"center",flex:`0 0 ${resolvedIconSize}px`,overflow:"hidden"}},iconElement);return React6.createElement("div",{key:`graph-node-${node.id}`,"data-vizmatic-graph-node-id":node.id,"data-vizmatic-graph-node-label":graphAccessibleText(node.label)||node.id,"data-vizmatic-graph-node-detail":graphAccessibleText(node.detail),"data-vizmatic-graph-node-title":node.title??"","data-vizmatic-graph-node-href":node.href,style:{position:"absolute",left:node.cx-node.width/2,top:node.cy-node.height/2,width:node.width,height:node.height,display:"flex",flexDirection:icon?"row":"column",alignItems:"center",justifyContent:"center",gap:icon?9:node.detail?5:0,padding:"8px 10px",boxSizing:"border-box",borderRadius:c.preset==="engineering"?5:10,backgroundColor:node.muted?c.bgSubtle:fill,border:`${c.preset==="engineering"?1.25:1.5}px solid ${node.muted?c.borderLight:`${accent}${c.preset==="engineering"?"":"88"}`}`,...!node.muted&&c.preset!=="engineering"?{boxShadow:`0 8px 18px ${c.shadow}`}:{},opacity:node.muted?.62:1,color:c.preset==="engineering"?c.textPrimary:accentText,textAlign:icon?"left":"center"}},icon,React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:icon?"flex-start":"center",gap:node.detail?5:0,minWidth:0}},React6.createElement("div",{style:{fontFamily:c.fontSans,fontSize:labelFontSize,fontWeight:c.preset==="engineering"?700:900,lineHeight:1.15}},node.label),node.detail&&React6.createElement("div",{style:{color:c.textMuted,fontFamily:c.fontMono,fontSize:detailFontSize,fontWeight:c.preset==="engineering"?400:650,lineHeight:1.2}},node.detail)))}))}Object.defineProperty(GraphDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});function countTreeLeaves(node){if(!node.children?.length)return 1;return node.children.reduce((sum,child)=>sum+countTreeLeaves(child),0)}function maxTreeDepth(node){if(!node.children?.length)return 0;return 1+Math.max(...node.children.map(maxTreeDepth))}function TreeDiagram({root,c,ariaLabel,title,subtitle,width,height,nodeWidth=156,nodeHeight=64,levelGap=58,siblingGap=24,padding=28,math=false}){const explicitIds=new Set;const validateIds=node=>{if(node.id){if(explicitIds.has(node.id))throw new Error(`TreeDiagram received duplicate node id "${node.id}".`);explicitIds.add(node.id)}node.children?.forEach(validateIds)};validateIds(root);const leafCount=Math.max(1,countTreeLeaves(root));const depthCount=maxTreeDepth(root);const resolvedWidth=width??Math.max(520,padding*2+leafCount*nodeWidth+Math.max(0,leafCount-1)*siblingGap);const resolvedHeight=height??padding*2+(depthCount+1)*nodeHeight+depthCount*levelGap;const levelStep=depthCount===0?0:Math.max(nodeHeight+18,(resolvedHeight-padding*2-nodeHeight)/depthCount);const usableWidth=Math.max(0,resolvedWidth-padding*2-nodeWidth);const leafStep=leafCount<=1?0:usableWidth/(leafCount-1);const positioned=[];const edges=[];let nextLeaf=0;const placeWithEdges=(node,depth,path)=>{const children=node.children??[];let centerIndex;const childPlacements=[];if(!children.length){centerIndex=nextLeaf;nextLeaf+=1}else{for(let index=0;index<children.length;index+=1){const child=children[index];childPlacements.push({node:child,index,center:placeWithEdges(child,depth+1,`${path}-${index}`)})}centerIndex=childPlacements.reduce((sum,child)=>sum+child.center,0)/childPlacements.length}const placed={...node,key:node.id??path,depth,cx:leafCount<=1?resolvedWidth/2:padding+nodeWidth/2+centerIndex*leafStep,cy:padding+nodeHeight/2+depth*levelStep};positioned.push(placed);for(const childPlacement of childPlacements){const childKey=childPlacement.node.id??`${path}-${childPlacement.index}`;const childNode=positioned.find(candidate=>candidate.key===childKey);if(childNode)edges.push({key:`${placed.key}-${childNode.key}`,from:placed,to:childNode})}return centerIndex};placeWithEdges(root,0,"root");const header=(title!=null||subtitle!=null)&&React6.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:resolvedWidth,maxWidth:"100%"}},...compactChildren([title!=null&&React6.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,fontFamily:"Inter",fontSize:16,fontWeight:900,lineHeight:1.2}},ToneStrip({tone:root.tone??"blue"}),renderMaybeMath(title,math)),subtitle!=null&&React6.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));return React6.createElement("div",{style:{display:"flex",flexDirection:"column",gap:header?10:0,width:resolvedWidth,maxWidth:"100%"}},...compactChildren([header,React6.createElement("div",{role:"img","aria-label":ariaLabel??(typeof title==="string"?title:"Tree diagram"),style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},React6.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},...edges.map(edge=>{const tone=edge.to.muted?"neutral":edge.to.tone??edge.from.tone??"blue";const color=edge.to.muted?c.textMuted:getToneColor(tone,c);const startY=edge.from.cy+nodeHeight/2;const endY=edge.to.cy-nodeHeight/2;const midY=startY+(endY-startY)/2;return React6.createElement("path",{key:`tree-edge-${edge.key}`,d:`M ${edge.from.cx} ${startY} C ${edge.from.cx} ${midY}, ${edge.to.cx} ${midY}, ${edge.to.cx} ${endY}`,fill:"none",stroke:color,strokeWidth:edge.to.muted?1.4:2.4,strokeLinecap:"round",opacity:edge.to.muted?.4:.74})})),...positioned.map(node=>{const accent=node.muted?c.textMuted:getToneColor(node.tone??"blue",c);const accentText=node.muted?c.textMuted:getReadableToneColor(node.tone??"blue",c);return React6.createElement("div",{key:`tree-node-${node.key}`,style:{position:"absolute",left:node.cx-nodeWidth/2,top:node.cy-nodeHeight/2,width:nodeWidth,height:nodeHeight,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:node.detail?4:0,padding:"8px 10px",boxSizing:"border-box",borderRadius:8,backgroundColor:node.muted?c.bgSubtle:c.bgCard,border:`1.5px solid ${node.muted?c.borderLight:`${accent}88`}`,...!node.muted?{boxShadow:`0 8px 18px ${c.shadow}`}:{},opacity:node.muted?.62:1,color:accentText,textAlign:"center"}},React6.createElement("div",{style:{color:accentText,fontFamily:"Inter",fontSize:13,fontWeight:900,lineHeight:1.15,...textFitStyle("center")}},renderMaybeMath(node.label,math)),node.detail!=null&&React6.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:650,lineHeight:1.2,...textFitStyle("center")}},renderMaybeMath(node.detail,math)))}))]))}function CalloutCard({c,children,title,detail,tone="blue",width,minHeight,padding=12,titleFontSize,detailFontSize,filled=true,align="center"}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";const textAlign=align;return React6.createElement("div",{style:{...width!=null?{width}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:10,boxSizing:"border-box",...engineering?{backgroundColor:getToneFill(tone,c),color:c.textPrimary,border:`1px solid ${accent}`}:filled?{backgroundImage:getToneGradient(tone),color:c.textOnColor,border:`1px solid ${accent}00`}:{backgroundColor:c.bgCard,color:c.textPrimary,border:`1px solid ${accent}66`},display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",justifyContent:"center",gap:detail?5:0,...!engineering?{boxShadow:`0 10px 24px ${c.shadow}`}:{},textAlign}},...compactChildren([title&&React6.createElement("div",{style:{...typography.small,...titleFontSize!=null?{fontSize:titleFontSize}:{},color:engineering?c.textPrimary:filled?c.textOnColor:accentText,fontFamily:c.fontSans,fontWeight:900,lineHeight:1.2,textAlign}},title),detail&&React6.createElement("div",{style:{...typography.tiny,...detailFontSize!=null?{fontSize:detailFontSize}:{},color:engineering?c.textSecondary:filled?"rgba(255,255,255,0.84)":c.textSecondary,fontFamily:engineering?c.fontMono:typography.tiny.fontFamily,lineHeight:1.3,textAlign}},detail),children&&React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",fontSize:12,fontWeight:700,lineHeight:1.3,textAlign}},children)]))}function Pipeline({stages,c,title}){return React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:20}},title&&React6.createElement("div",{style:{...typography.label,color:c.textPrimary}},title),React6.createElement("div",{style:{display:"flex",alignItems:"center",gap:0}},...stages.flatMap((stage,i)=>{const elements=[];elements.push(Box({label:stage.label,sublabel:stage.sublabel,icon:stage.icon,color:stage.color||"primary",gradient:true,c,fontSize:13}));if(i<stages.length-1){elements.push(Arrow({direction:"right",length:36,c}))}return elements})))}import React7 from"react";var sequenceFragmentKinds=["alt","loop","parallel"];var sequenceMessageKinds=["sync","async","return"];function isFragment(item){return!("from"in item)&&(!("type"in item)||item.type!=="note"&&item.type!=="activation")}function isActivation(item){return"type"in item&&item.type==="activation"}function isNote(item){return"type"in item&&item.type==="note"}function sequenceFragmentKind(fragment){const kind=fragment.kind;if(kind==null||!sequenceFragmentKinds.includes(kind)){throw new Error(`SequenceDiagram fragment must define kind as "alt", "loop", or "parallel".`)}return kind}function sequenceMessageKind(message){const kind=message.kind;if(kind==null)return"sync";if(!sequenceMessageKinds.includes(kind)){throw new Error(`SequenceDiagram message kind must be "sync", "async", or "return".`)}return kind}function sequenceNoteText(note){return note.text}function sequenceContainerItems(container){if(container.items)return container.items;return[...container.messages??[],...container.notes??[],...container.fragments??[]]}function participantReferences(note){const references=note.over??[];if(note.participant&&!references.includes(note.participant))return[note.participant,...references];return references}function validateSequenceItems(items,participantIds,path){for(let index=0;index<items.length;index+=1){const item=items[index];const itemPath=`${path}[${index}]`;if(isFragment(item)){const kind=sequenceFragmentKind(item);const branches=item.branches??[];if((kind==="alt"||kind==="parallel")&&branches.length<2){throw new Error(`SequenceDiagram ${kind} fragment at ${itemPath} requires at least two branches.`)}if(branches.some(branch=>!branch||typeof branch!=="object")){throw new Error(`SequenceDiagram fragment at ${itemPath} contains an invalid branch.`)}for(let branchIndex=0;branchIndex<branches.length;branchIndex+=1){validateSequenceItems(sequenceContainerItems(branches[branchIndex]),participantIds,`${itemPath}.branches[${branchIndex}]`)}if(!branches.length){validateSequenceItems(sequenceContainerItems(item),participantIds,`${itemPath}.items`)}continue}if(isActivation(item)){if(!participantIds.has(item.participant)){throw new Error(`SequenceDiagram activation references missing participant "${item.participant}".`)}continue}if(isNote(item)){for(const participant of participantReferences(item)){if(!participantIds.has(participant)){throw new Error(`SequenceDiagram note references missing participant "${participant}".`)}}continue}if(!participantIds.has(item.from)||!participantIds.has(item.to)){throw new Error(`SequenceDiagram message "${item.from}" -> "${item.to}" references a missing participant.`)}sequenceMessageKind(item)}}function validateSequenceSpec(participants,items){const ids=new Set;for(const participant of participants){if(!participant.id.trim())throw new Error("SequenceDiagram participant ids must not be empty.");if(ids.has(participant.id))throw new Error(`SequenceDiagram received duplicate participant id "${participant.id}".`);ids.add(participant.id)}validateSequenceItems(items,ids,"items")}function branchLabel(branch,index){return branch.label??(index===0?"case":"else")}function flattenSequenceItems(items){const rows=[];const spans=[];const appendItems=(nextItems,depth,path)=>{nextItems.forEach((item,index)=>{if(!isFragment(item)){rows.push({key:item.id??`${path}-${index}`,item,depth});return}const fragmentId=item.id??`${path}-fragment-${index}`;const start=rows.length;const branchStarts=[];const branches=item.branches??[];if(branches.length){branches.forEach((branch,branchIndex)=>{const row=rows.length;branchStarts.push({row,label:branchLabel(branch,branchIndex)});rows.push({key:`${fragmentId}-branch-${branchIndex}`,marker:{fragment:item,branch,branchIndex},depth});appendItems(sequenceContainerItems(branch),depth+1,`${fragmentId}-branch-${branchIndex}`)})}else{rows.push({key:`${fragmentId}-start`,marker:{fragment:item},depth});appendItems(sequenceContainerItems(item),depth+1,fragmentId)}if(rows.length===start)rows.push({key:`${fragmentId}-empty`,marker:{fragment:item},depth});spans.push({id:fragmentId,start,end:Math.max(start,rows.length-1),depth,fragment:item,branchStarts})})};appendItems(items,0,"sequence");return{rows,spans}}function readableNodeText(value){if(typeof value==="string"||typeof value==="number")return String(value);return""}function sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop){if(!selfLoop)return`M ${fromX} ${y} L ${toX} ${y}`;const loopWidth=34;const right=fromX+loopWidth;const bottom=y+rowHeight*.52;return`M ${fromX} ${y} L ${right} ${y} L ${right} ${bottom} L ${fromX+10} ${bottom} L ${fromX+10} ${y+1}`}function sequenceNoteBounds(note,xs,chartWidth,noteWidth,padding){const references=participantReferences(note).filter(id=>xs.has(id));if(references.length>=2||note.side==="over"){const values=references.map(id=>xs.get(id)??chartWidth/2);const left2=Math.max(padding,Math.min(...values)-noteWidth/2);const right=Math.min(chartWidth-padding,Math.max(...values)+noteWidth/2);return{left:left2,width:Math.max(82,right-left2)}}const anchor=references.length?xs.get(references[0])??chartWidth/2:chartWidth/2;const left=note.side==="left"?anchor-noteWidth-18:note.side==="right"?anchor+18:anchor-noteWidth/2;return{left:Math.max(padding,Math.min(chartWidth-padding-noteWidth,left)),width:noteWidth}}function activationReference(value,rows,fallback,end){if(value==null)return fallback;if(typeof value==="number"){if(!Number.isInteger(value)||value<0||value>=Math.max(rows.length,1)){throw new Error(`SequenceDiagram activation row reference ${value} is outside rendered rows.`)}return value}const index=rows.findIndex(row=>row.key===value||row.item!=null&&row.item.id===value);if(index<0)throw new Error(`SequenceDiagram activation references missing row "${value}".`);return end?index:index}function SequenceDiagram({c,participants,messages=[],notes=[],activations=[],fragments=[],items,title,subtitle,ariaLabel,width,height,padding=24,participantWidth=132,participantGap=42,rowHeight=56,fragmentIndent=12,noteWidth=156,lifelineDash="5 5"}){const orderedItems=items??sequenceContainerItems({messages,notes,fragments});validateSequenceSpec(participants,activations.length?[...orderedItems,...activations]:orderedItems);const flattened=flattenSequenceItems(orderedItems);const rows=flattened.rows.length?flattened.rows:[{key:"sequence-empty",depth:0}];const minimumWidth=padding*2+participantWidth*participants.length+participantGap*Math.max(0,participants.length-1);const resolvedWidth=width??Math.max(560,minimumWidth);if(width!=null&&width<minimumWidth){throw new Error(`SequenceDiagram width ${width} is too small for ${participants.length} participants; use at least ${minimumWidth}.`)}const headerHeight=92;const minimumHeight=padding+headerHeight+rows.length*rowHeight+padding;const resolvedHeight=height??minimumHeight;if(height!=null&&height<minimumHeight){throw new Error(`SequenceDiagram height ${height} is too small for ${rows.length} rows; use at least ${minimumHeight}.`)}const availableParticipantWidth=resolvedWidth-padding*2;const step=participants.length>1?(availableParticipantWidth-participantWidth)/(participants.length-1):0;const firstX=participants.length>1?padding+participantWidth/2:resolvedWidth/2;const participantXs=new Map(participants.map((participant,index)=>[participant.id,firstX+index*step]));const bodyTop=padding+headerHeight;const rowCenter=index=>bodyTop+index*rowHeight+rowHeight/2;const labelText=ariaLabel??readableNodeText(title)??"Sequence diagram";const accessibleLabel=labelText||"Sequence diagram";const markerDefinitions=participants.flatMap((participant,participantIndex)=>{const color=getToneColor(participant.tone??"blue",c);return sequenceMessageKindsForMarkers(orderedItems).map(kind=>ArrowMarkerDef({id:`sequence-arrow-${participantIndex}-${kind}`,color,size:5}))});const fragmentElements=flattened.spans.map(span=>{const tone=span.fragment.tone??(span.fragment.kind==="loop"?"purple":span.fragment.kind==="parallel"?"cyan":"warm");const accent=span.fragment.muted?c.textMuted:getToneColor(tone,c);const top=bodyTop+span.start*rowHeight+4;const spanHeight=Math.max(rowHeight-8,(span.end-span.start+1)*rowHeight-8);const left=padding+span.depth*fragmentIndent;const fragmentWidth=Math.max(0,resolvedWidth-left-padding-span.depth*fragmentIndent);return React7.createElement("div",{key:`sequence-fragment-${span.id}`,"data-vizmatic-sequence-fragment":span.id,style:{position:"absolute",left,top,width:fragmentWidth,height:spanHeight,display:"flex",boxSizing:"border-box",border:`1.25px ${span.fragment.muted?"dotted":"dashed"} ${accent}${span.fragment.muted?"55":"99"}`,backgroundColor:`${accent}0b`,borderRadius:c.preset==="engineering"?4:8,pointerEvents:"none"}},React7.createElement("div",{style:{position:"absolute",left:8,top:-9,display:"flex",alignItems:"center",gap:5,padding:"1px 5px",backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:11,fontWeight:800,lineHeight:1.1,textTransform:"uppercase"}},span.fragment.kind,span.fragment.label),...span.branchStarts.map(branch=>React7.createElement("div",{key:`sequence-branch-${span.id}-${branch.row}`,style:{position:"absolute",left:Math.max(8,span.depth*fragmentIndent),top:branch.row*rowHeight-span.start*rowHeight+5,padding:"2px 5px",backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:11,fontWeight:700,lineHeight:1.1}},branch.label)))});const lifelineElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;return React7.createElement("line",{key:`sequence-lifeline-${participant.id}`,x1:x,y1:bodyTop-14,x2:x,y2:bodyTop+rows.length*rowHeight,stroke:participant.muted?c.textMuted:c.borderLight,strokeWidth:participant.muted?1:1.35,strokeDasharray:lifelineDash,opacity:participant.muted?.46:.8})});const activationElements=[...activations,...orderedItems.filter(isActivation)].map((activation,index)=>{const participantX=participantXs.get(activation.participant);if(participantX==null)return null;const startValue=activation.start??activation.fromMessage;const endValue=activation.end??activation.toMessage;const start=activationReference(startValue,rows,0,false);const end=activationReference(endValue,rows,rows.length-1,true);if(end<start)throw new Error(`SequenceDiagram activation for "${activation.participant}" ends before it starts.`);const depth=Math.max(0,activation.depth??0);const accent=activation.muted?c.textMuted:getToneColor(activation.tone??"blue",c);const top=rowCenter(start)-rowHeight/2+5;const activationHeight=Math.max(14,(end-start+1)*rowHeight-10);return React7.createElement("div",{key:`sequence-activation-${activation.id??index}`,"data-vizmatic-sequence-activation":activation.participant,style:{position:"absolute",left:participantX-5+depth*7,top,width:10,height:activationHeight,boxSizing:"border-box",borderRadius:3,backgroundColor:getToneFill(activation.tone??"blue",c),border:`1.5px solid ${accent}`,opacity:activation.muted?.52:.94,pointerEvents:"none"}})}).filter(Boolean);const messageElements=rows.map((row,rowIndex)=>{if(!row.item||isFragment(row.item)||isActivation(row.item)||isNote(row.item))return null;const message=row.item;const fromX=participantXs.get(message.from)??resolvedWidth/2;const toX=participantXs.get(message.to)??resolvedWidth/2;const kind=sequenceMessageKind(message);const tone=message.tone??(kind==="return"?"neutral":kind==="async"?"cyan":"blue");const color=message.muted?c.textMuted:getToneColor(tone,c);const markerId=`sequence-arrow-${participants.findIndex(participant=>participant.id===message.to)}-${kind}`;const y=rowCenter(rowIndex);const selfLoop=message.from===message.to;return React7.createElement(React7.Fragment,{key:`sequence-message-${message.id??row.key}`},React7.createElement("path",{d:sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop),fill:"none",stroke:color,strokeWidth:message.muted?1.25:2,strokeDasharray:kind==="sync"?void 0:"7 5",strokeLinecap:"round",opacity:message.muted?.48:.9,markerEnd:`url(#${markerId})`}),message.label!=null&&React7.createElement("div",{style:{position:"absolute",left:selfLoop?fromX+34:(fromX+toX)/2,top:y-18,transform:"translate(-50%, -50%)",maxWidth:Math.max(74,Math.abs(toX-fromX)-28),padding:"2px 5px",backgroundColor:c.bg,color:message.muted?c.textMuted:c.textPrimary,fontFamily:c.fontMono,fontSize:11,fontWeight:650,lineHeight:1.1,whiteSpace:"nowrap",...textFitStyle("center")}},message.label))}).filter(Boolean);const noteElements=rows.map((row,rowIndex)=>{if(!row.item||!isNote(row.item))return null;const note=row.item;const bounds=sequenceNoteBounds(note,participantXs,resolvedWidth,noteWidth,padding);const tone=note.tone??"warm";const accent=note.muted?c.textMuted:getToneColor(tone,c);return React7.createElement("div",{key:`sequence-note-${note.id??row.key}`,"data-vizmatic-sequence-note":note.id??row.key,style:{position:"absolute",left:bounds.left,top:rowCenter(rowIndex)-17,width:bounds.width,minHeight:34,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",padding:"6px 9px",borderRadius:c.preset==="engineering"?3:7,backgroundColor:note.muted?c.bgSubtle:getToneFill(tone,c),border:`1px solid ${accent}${note.muted?"66":"99"}`,color:note.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),fontFamily:c.fontSans,fontSize:11,fontWeight:700,lineHeight:1.2,textAlign:"center",...textFitStyle("center")}},sequenceNoteText(note))}).filter(Boolean);const participantElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;const tone=participant.tone??"blue";const accent=participant.muted?c.textMuted:getToneColor(tone,c);const icon=participant.icon&&Icon({c,name:participant.icon,color:accent,size:16,muted:participant.muted,label:readableNodeText(participant.label)?`${readableNodeText(participant.label)} icon`:void 0});return React7.createElement("div",{key:`sequence-participant-${participant.id}`,"data-vizmatic-sequence-participant":participant.id,style:{position:"absolute",left:x-participantWidth/2,top:padding,width:participantWidth,minHeight:54,boxSizing:"border-box",display:"flex",flexDirection:icon?"row":"column",alignItems:"center",justifyContent:"center",gap:icon?7:participant.detail?3:0,padding:"7px 8px",borderRadius:c.preset==="engineering"?4:8,backgroundColor:participant.muted?c.bgSubtle:getToneFill(tone,c),border:`1.25px solid ${participant.muted?c.borderLight:accent}`,color:participant.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),opacity:participant.muted?.62:1,textAlign:icon?"left":"center"}},icon,React7.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:icon?"flex-start":"center",minWidth:0,gap:participant.detail?3:0}},React7.createElement("div",{style:{fontFamily:c.fontSans,fontSize:12,fontWeight:850,lineHeight:1.15,...textFitStyle(icon?"left":"center")}},participant.label),participant.detail!=null&&React7.createElement("div",{style:{color:c.textMuted,fontFamily:c.fontMono,fontSize:11,fontWeight:550,lineHeight:1.1,...textFitStyle(icon?"left":"center")}},participant.detail)))});return React7.createElement("div",{role:"img","aria-label":accessibleLabel,"data-vizmatic-sequence-row-count":rows.length,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},...fragmentElements,React7.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React7.createElement("defs",{},...markerDefinitions),...lifelineElements,...messageElements),...activationElements,...noteElements,...participantElements,title!=null&&React7.createElement("div",{style:{position:"absolute",left:padding,top:2,color:c.textPrimary,fontFamily:c.fontSans,fontSize:14,fontWeight:850}},title),subtitle!=null&&React7.createElement("div",{style:{position:"absolute",left:padding,top:20,color:c.textSecondary,fontFamily:c.fontSans,fontSize:11,fontWeight:550}},subtitle))}function sequenceMessageKindsForMarkers(items){const kinds=new Set;const visit=nextItems=>{for(const item of nextItems){if(isFragment(item)){if(item.branches)item.branches.forEach(branch=>visit(sequenceContainerItems(branch)));else visit(sequenceContainerItems(item))}else if(!isNote(item)&&!isActivation(item)){kinds.add(sequenceMessageKind(item))}}};visit(items);if(!kinds.size)kinds.add("sync");return Array.from(kinds)}import React8 from"react";var nodeKinds=["source","transform","store","sink"];var edgeModes=["batch","stream"];var defaultNodeTones={source:"blue",transform:"purple",store:"green",sink:"warm"};var defaultNodeIcons={source:"file",transform:"tool",store:"database",sink:"bucket"};function nodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds.includes(kind)){throw new Error(`DataflowDiagram node "${node.id}" must define kind as "source", "transform", "store", or "sink".`)}return kind}function edgeMode(edge){const mode=edge.mode??"batch";if(!edgeModes.includes(mode)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" must use mode "batch" or "stream".`)}return mode}function validateSchema(schema,owner){if(schema==null||typeof schema==="string")return;const fields=new Set;const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));for(const field of fieldList){if(!field.name.trim())throw new Error(`DataflowDiagram schema for "${owner}" contains an empty field name.`);if(fields.has(field.name))throw new Error(`DataflowDiagram schema for "${owner}" contains duplicate field "${field.name}".`);fields.add(field.name)}}function schemaLabel(schema){if(schema==null)return void 0;if(typeof schema==="string")return schema;const prefix=[schema.name,schema.version].filter(Boolean).join(" ");const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));const fields=fieldList.map(field=>`${field.name}${field.type?`: ${field.type}`:""}${field.required?" *":""}`).join(", ");return[prefix,fields?`{ ${fields} }`:void 0].filter(Boolean).join(" ")}function detailWithSchema(detail,schema){const renderedSchema=schemaLabel(schema);if(!renderedSchema)return detail;if(detail==null)return renderedSchema;if(typeof detail==="string"||typeof detail==="number")return`${detail} \xB7 ${renderedSchema}`;return React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap:3,minWidth:0}},React8.createElement("div",null,detail),React8.createElement("div",{style:{fontFamily:"inherit",fontSize:"inherit",fontWeight:"inherit"}},renderedSchema))}function validateDataflowSpec(spec){const boundaries=spec.boundaries??[];const ids=new Set;for(const node of spec.nodes){if(!node.id.trim())throw new Error("DataflowDiagram node ids must not be empty.");if(ids.has(node.id))throw new Error(`DataflowDiagram received duplicate id "${node.id}".`);ids.add(node.id);nodeKind(node);validateSchema(node.schema,node.id)}for(const boundary of boundaries){if(!boundary.id.trim())throw new Error("DataflowDiagram boundary ids must not be empty.");if(ids.has(boundary.id))throw new Error(`DataflowDiagram received duplicate id "${boundary.id}".`);ids.add(boundary.id)}const boundariesById=new Map(boundaries.map(boundary=>[boundary.id,boundary]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundariesById.has(boundary.parent)){throw new Error(`DataflowDiagram boundary "${boundary.id}" references missing parent "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DataflowDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundariesById.get(parent)?.parent}}for(const node of spec.nodes){const boundary=node.boundary;if(boundary!=null&&!boundariesById.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}}for(const edge of spec.edges){if(!ids.has(edge.from)||!ids.has(edge.to)||!spec.nodes.some(node=>node.id===edge.from)||!spec.nodes.some(node=>node.id===edge.to)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}edgeMode(edge);validateSchema(edge.schema,`${edge.from} -> ${edge.to}`)}const occupied=new Set;for(const node of spec.nodes){let boundary=node.boundary;while(boundary!=null){occupied.add(boundary);boundary=boundariesById.get(boundary)?.parent}}for(const boundary of boundaries){if(!occupied.has(boundary.id))throw new Error(`DataflowDiagram boundary "${boundary.id}" contains no nodes.`)}return{boundaries}}function compileDataflow(spec){const{boundaries}=validateDataflowSpec(spec);const boundaryIds=new Set(boundaries.map(boundary=>boundary.id));const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail,parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=nodeKind(node);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}return{id:node.id,label:node.label,detail:detailWithSchema(node.detail,node.schema),href:node.href,title:node.title,tone:node.tone??defaultNodeTones[kind],icon:node.icon??defaultNodeIcons[kind],muted:node.muted,group:boundary,width:node.width,height:node.height}});const edges=spec.edges.map(edge=>{const mode=edgeMode(edge);const schema=schemaLabel(edge.schema);return{id:edge.id,from:edge.from,to:edge.to,label:edge.label??schema??mode,href:edge.href,title:edge.title,tone:edge.tone??(mode==="stream"?"cyan":"blue"),muted:edge.muted,kind:mode==="stream"?"async":"data",style:mode==="stream"?"dashed":"solid",arrow:"forward"}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Dataflow diagram"}}function DataflowDiagram({c,nodes,edges,boundaries,ariaLabel,id,title,description,width,height,nodeWidth=158,nodeHeight=70,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize}){const compiled=compileDataflow({nodes,edges,boundaries,ariaLabel});return GraphDiagram({c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel,id,title,description,width,height,nodeWidth,nodeHeight,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize})}Object.defineProperty(DataflowDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var boundaryKindLabels={region:"REGION",zone:"ZONE",vpc:"VPC",subnet:"SUBNET",namespace:"NAMESPACE",host:"HOST",cluster:"CLUSTER",trust:"TRUST"};var nodeKindLabels={user:"USER",client:"CLIENT",external:"EXTERNAL",gateway:"GATEWAY","load-balancer":"LOAD BALANCER",service:"SERVICE",api:"API",function:"FUNCTION",lambda:"LAMBDA",worker:"WORKER",container:"CONTAINER",pod:"POD",host:"HOST",vm:"VM",cluster:"CLUSTER",database:"DATABASE",cache:"CACHE",queue:"QUEUE",storage:"STORAGE","object-store":"OBJECT STORE",registry:"REGISTRY","message-broker":"MESSAGE BROKER",firewall:"FIREWALL",network:"NETWORK",internet:"INTERNET",device:"DEVICE",custom:"NODE"};var nodeKindIcons={user:"user",client:"browser",external:"globe",gateway:"gateway","load-balancer":"load-balancer",service:"container",api:"gateway",function:"agent",lambda:"agent",worker:"agent",container:"container",pod:"cluster",host:"server",vm:"server",cluster:"cluster",database:"database",cache:"cache",queue:"queue",storage:"storage","object-store":"bucket",registry:"storage","message-broker":"queue",firewall:"firewall",network:"network",internet:"globe",device:"mobile"};var connectionTones={ingress:"cyan",egress:"warm",internal:"blue","cross-boundary":"purple"};var boundaryKinds=["region","zone","vpc","subnet","namespace","host","cluster","trust"];var nodeKinds2=["user","client","external","gateway","load-balancer","service","api","function","lambda","worker","container","pod","host","vm","cluster","database","cache","queue","storage","object-store","registry","message-broker","firewall","network","internet","device","custom"];var connectionKinds=["ingress","egress","internal","cross-boundary"];function assertIdentifier(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`DeploymentDiagram ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier(id,seen,what){assertIdentifier(id,what);if(seen.has(id))throw new Error(`DeploymentDiagram received duplicate ${what} id "${id}".`);seen.add(id)}function portIdentity(port){if(typeof port==="string"||typeof port==="number")return String(port);return port.id}function portText(port){if(typeof port==="string"||typeof port==="number")return String(port);if(port.label)return port.label;const endpoint2=port.port??port.id;return[port.protocol,endpoint2==null?void 0:String(endpoint2)].filter(Boolean).join("/")||port.direction||"port"}function portForReference(node,reference){if(reference==null)return void 0;return node.ports?.find(port=>portIdentity(port)===String(reference))}function resolveConnectionKind(connection){const kind=connection.kind??"internal";if(!connectionKinds.includes(kind)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" must use kind "ingress", "egress", "internal", or "cross-boundary".`)}return kind}function resolveBoundaryKind(boundary){const kind=boundary.kind;if(kind==null||!boundaryKinds.includes(kind)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" must define kind as "region", "zone", "vpc", "subnet", "namespace", "host", "cluster", or "trust".`)}return kind}function resolveNodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds2.includes(kind)){throw new Error(`DeploymentDiagram node "${node.id}" must define kind as a supported deployment node kind.`)}return kind}function connectionPortReference(connection,side){return side==="from"?connection.fromPort:connection.toPort}function connectionLabel(connection,sourcePort,targetPort){if(connection.label!=null)return connection.label;const declaredPort=connection.port;const portLabel=declaredPort!=null?portText(declaredPort):sourcePort!=null?portText(sourcePort):targetPort!=null?portText(targetPort):void 0;const protocol=connection.protocol??(typeof sourcePort==="object"&&sourcePort!=null?sourcePort.protocol:void 0)??(typeof targetPort==="object"&&targetPort!=null?targetPort.protocol:void 0);if(protocol&&portLabel&&!portLabel.toLowerCase().startsWith(protocol.toLowerCase())){return`${protocol}/${portLabel}`}return protocol??portLabel}function validateDeploymentSpec(boundaries,nodes,connections){const ids=new Set;const boundaryIds=new Set;for(const boundary of boundaries){assertUniqueIdentifier(boundary.id,ids,"boundary");resolveBoundaryKind(boundary);boundaryIds.add(boundary.id)}const nodeIds=new Set;const portsByNode=new Map;for(const node of nodes){assertUniqueIdentifier(node.id,ids,"node");nodeIds.add(node.id);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DeploymentDiagram node "${node.id}" references missing boundary "${boundary}".`)}const ports=new Map;node.ports?.forEach(port=>{const identity=portIdentity(port);if(ports.has(identity))throw new Error(`DeploymentDiagram node "${node.id}" received duplicate port "${identity}".`);ports.set(identity,port)});portsByNode.set(node.id,ports)}const boundaryParents=new Map(boundaries.map(boundary=>[boundary.id,boundary.parent]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundaryIds.has(boundary.parent)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" references missing parent boundary "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DeploymentDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundaryParents.get(parent)}}const connectionIds=new Set;for(const connection of connections){if(connection.id!=null)assertUniqueIdentifier(connection.id,connectionIds,"connection");if(!nodeIds.has(connection.from)||!nodeIds.has(connection.to)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references a missing node.`)}resolveConnectionKind(connection);for(const side of["from","to"]){const reference=connectionPortReference(connection,side);if(reference==null)continue;const nodeId2=side==="from"?connection.from:connection.to;const ports=portsByNode.get(nodeId2);if(ports!=null&&ports.size>0&&!ports.has(String(reference))){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId2}".`)}}}}function graphConnectionKind(kind){if(kind==="internal")return"data";if(kind==="ingress")return"sync";return"dependency"}function graphConnectionStyle(kind){if(kind==="cross-boundary")return"dotted";if(kind==="egress")return"dashed";return"solid"}function compileDeployment(spec){const boundaries=spec.boundaries??[];const connections=spec.connections??[];validateDeploymentSpec(boundaries,spec.nodes,connections);const anchorPorts=spec.routing!=null&&spec.routing!=="dagre";const incomingSide=spec.direction==="TB"?"top":spec.direction==="BT"?"bottom":spec.direction==="RL"?"right":"left";const outgoingSide=spec.direction==="TB"?"bottom":spec.direction==="BT"?"top":spec.direction==="RL"?"left":"right";const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail??boundaryKindLabels[resolveBoundaryKind(boundary)],parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=resolveNodeKind(node);const nodePorts=node.ports??[];const generatedDetail=nodePorts.length>0?`ports: ${nodePorts.map(portText).join(", ")}`:nodeKindLabels[kind];return{id:node.id,label:node.label,detail:node.detail??generatedDetail,href:node.href,title:node.title,x:node.x,y:node.y,tone:node.tone,muted:node.muted,width:node.width,height:node.height,group:node.boundary,icon:node.icon??nodeKindIcons[kind],iconSize:node.iconSize,ports:anchorPorts?nodePorts.map((port,index)=>{const incoming=typeof port==="object"?port.direction==="ingress":false;const targetOnly=connections.some(connection=>connection.to===node.id&&String(connection.toPort)===portIdentity(port))&&!connections.some(connection=>connection.from===node.id&&String(connection.fromPort)===portIdentity(port));return{id:portIdentity(port),side:typeof port==="object"&&port.side!=null?port.side:incoming||targetOnly?incomingSide:outgoingSide,offset:typeof port==="object"&&port.offset!=null?port.offset:(index+1)/(nodePorts.length+1)}}):void 0}});const edges=connections.map(connection=>{const kind=resolveConnectionKind(connection);const fromReference=connectionPortReference(connection,"from");const toReference=connectionPortReference(connection,"to");const sourceNode=spec.nodes.find(node=>node.id===connection.from);const targetNode=spec.nodes.find(node=>node.id===connection.to);const sourcePort=sourceNode?portForReference(sourceNode,fromReference):void 0;const targetPort=targetNode?portForReference(targetNode,toReference):void 0;const fallbackFromPort=fromReference!=null&&!sourceNode?.ports?.length?fromReference:void 0;const fallbackToPort=toReference!=null&&!targetNode?.ports?.length?toReference:void 0;return{id:connection.id,from:connection.from,to:connection.to,tone:connection.tone??connectionTones[kind],muted:connection.muted,kind:graphConnectionKind(kind),style:connection.style??graphConnectionStyle(kind),arrow:connection.arrow??"forward",label:connectionLabel(connection,sourcePort??fallbackFromPort,targetPort??fallbackToPort),href:connection.href,title:connection.title,fromPort:anchorPorts&&fromReference!=null?String(fromReference):void 0,toPort:anchorPorts&&toReference!=null?String(toReference):void 0,fromSide:connection.fromSide,toSide:connection.toSide}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Deployment diagram"}}function DeploymentDiagram({c,boundaries,nodes,connections,ariaLabel="Deployment diagram",...graphProps}){const compiled=compileDeployment({nodes,boundaries,connections,ariaLabel,direction:graphProps.direction,routing:graphProps.routing});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel})}Object.defineProperty(DeploymentDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var blockLabels={embedding:"Embedding",attention:"Attention",norm:"Norm",mlp:"MLP",residual:"Residual",router:"Router",output:"Output",custom:"Block"};var blockTones={embedding:"cyan",attention:"purple",norm:"neutral",mlp:"blue",residual:"warm",router:"pink",output:"green",custom:"ocean"};var blockIcons={embedding:"layers",attention:"network",norm:"tool",mlp:"code",residual:"git",router:"gateway",output:"check",custom:"spark"};var routeTones={activation:"blue",residual:"warm","kv-cache":"cyan",expert:"pink",collective:"purple"};var blockKinds=["embedding","attention","norm","mlp","residual","router","output","custom"];var routeKinds=["activation","residual","kv-cache","expert","collective"];function assertIdentifier2(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`TransformerTopology ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier2(id,seen,what){assertIdentifier2(id,what);if(seen.has(id))throw new Error(`TransformerTopology received duplicate ${what} id "${id}".`);seen.add(id)}function isTensorShapeArray(shape){return Array.isArray(shape)}function formatTensorShape(shape){if(shape==null)return void 0;if(typeof shape==="string")return shape;const dimensions=isTensorShapeArray(shape)?shape:shape.dims;const label=isTensorShapeArray(shape)?void 0:shape.label;const formatted=dimensions?.length?`[${dimensions.join(" \xD7 ")}]`:void 0;const base=label??formatted;if(!base)return void 0;const metadata=!isTensorShapeArray(shape)?[shape.dtype,shape.layout].filter(Boolean).join(" \xB7 "):"";return metadata?`${base} \xB7 ${metadata}`:base}function resolveBlockKind(block){const kind=block.kind;if(kind==null||!blockKinds.includes(kind)){throw new Error(`TransformerTopology block "${block.id}" must define kind as "embedding", "attention", "norm", "mlp", "residual", "router", "output", or "custom".`)}return kind}function resolveRouteKind(route){const kind=route.kind??"activation";if(!routeKinds.includes(kind)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" must use kind "activation", "residual", "kv-cache", "expert", or "collective".`)}return kind}function resolveRepeat(block){const repeat=block.repeat??1;if(!Number.isInteger(repeat)||repeat<1){throw new Error(`TransformerTopology block "${block.id}" repeat must be a positive integer.`)}return repeat}function blockShapeText(block){const shape=block.shape;const input=formatTensorShape(block.inputShape);const output=formatTensorShape(block.outputShape);const primary=formatTensorShape(shape);if(input||output){return[input,output&&input?`\u2192 ${output}`:output].filter(Boolean).join(" ")}return primary}function blockDetail(block,kind,repeat){const shape=blockShapeText(block);const repetition=repeat>1?`\xD7${repeat}`:void 0;if(block.detail!=null){if(typeof block.detail==="string"){return[block.detail,repetition,shape].filter(Boolean).join(" \xB7 ")}return block.detail}return[repetition,shape,repeat===1?blockLabels[kind].toUpperCase():void 0].filter(Boolean).join(" \xB7 ")||void 0}function routeShapeText(route){return formatTensorShape(route.shape)}function routeLabel(route,kind){if(route.label!=null)return route.label;const kindLabel=kind==="kv-cache"?"KV cache":kind;const qualifiers=[kindLabel,route.expert==null?void 0:`expert ${route.expert}`,route.collective,routeShapeText(route)].filter(Boolean);return qualifiers.join(" \xB7 ")}function graphRouteKind(kind){if(kind==="activation"||kind==="expert")return"data";if(kind==="kv-cache")return"event";return"dependency"}function graphRouteStyle(kind){if(kind==="kv-cache")return"dotted";if(kind==="residual"||kind==="collective")return"dashed";return"solid"}function validateTransformerSpec(blocks,routes,expandRepeats){const blockIds=new Set;const repeatCounts=new Map;for(const block of blocks){assertUniqueIdentifier2(block.id,blockIds,"block");resolveBlockKind(block);repeatCounts.set(block.id,resolveRepeat(block))}const routeIds=new Set;const graphIds=new Set(blockIds);if(expandRepeats){for(const block of blocks){const repeat=repeatCounts.get(block.id)??1;if(repeat===1)continue;for(let index=1;index<=repeat;index+=1){const expandedId=`${block.id}-${index}`;if(graphIds.has(expandedId)){throw new Error(`TransformerTopology repeated block "${block.id}" generates duplicate node id "${expandedId}".`)}graphIds.add(expandedId)}}}for(const route of routes){if(route.id!=null)assertUniqueIdentifier2(route.id,routeIds,"route");if(!blockIds.has(route.from)||!blockIds.has(route.to)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" references a missing block.`)}resolveRouteKind(route)}return repeatCounts}function expandedNodeId(id,repeat,index){return repeat>1?`${id}-${index+1}`:id}function expandedRouteEndpoints(route,repeatCounts,expandRepeats){if(!expandRepeats)return[{from:route.from,to:route.to}];const fromRepeat=repeatCounts.get(route.from)??1;const toRepeat=repeatCounts.get(route.to)??1;if(route.from===route.to&&fromRepeat>1){return Array.from({length:fromRepeat-1},(_,index)=>({from:expandedNodeId(route.from,fromRepeat,index),to:expandedNodeId(route.to,toRepeat,index+1)}))}return[{from:expandedNodeId(route.from,fromRepeat,fromRepeat-1),to:expandedNodeId(route.to,toRepeat,0)}]}function compileTransformer(spec){const routes=spec.routes??[];const expandRepeats=spec.expandRepeats??false;const repeatCounts=validateTransformerSpec(spec.blocks,routes,expandRepeats);const nodes=[];for(const block of spec.blocks){const kind=resolveBlockKind(block);const repeat=repeatCounts.get(block.id)??1;const count=expandRepeats?repeat:1;for(let index=0;index<count;index+=1){const id=expandRepeats?expandedNodeId(block.id,repeat,index):block.id;const label=block.label??blockLabels[kind];const repetitionDetail=expandRepeats&&repeat>1?[blockDetail(block,kind,repeat),`${index+1}/${repeat}`].filter(Boolean).join(" \xB7 "):blockDetail(block,kind,repeat);nodes.push({id,label,detail:repetitionDetail,href:block.href,title:block.title,x:block.x,y:block.y,tone:block.tone??blockTones[kind],muted:block.muted,width:block.width,height:block.height,icon:block.icon??blockIcons[kind],iconSize:block.iconSize})}}const edges=[];for(const route of routes){const kind=resolveRouteKind(route);const endpoints=expandedRouteEndpoints(route,repeatCounts,expandRepeats);for(const[index,endpoint2]of endpoints.entries()){edges.push({id:route.id==null?void 0:endpoints.length===1?route.id:`${route.id}-${index+1}`,from:endpoint2.from,to:endpoint2.to,tone:route.tone??routeTones[kind],muted:route.muted,kind:graphRouteKind(kind),style:route.style??graphRouteStyle(kind),arrow:route.arrow??(kind==="residual"?"both":"forward"),label:routeLabel(route,kind),href:route.href,title:route.title})}}return{nodes,edges,ariaLabel:spec.ariaLabel??"Transformer topology diagram"}}function TransformerTopology({c,blocks,routes,expandRepeats=false,ariaLabel="Transformer topology diagram",...graphProps}){const compiled=compileTransformer({blocks,routes,expandRepeats,ariaLabel});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,ariaLabel:compiled.ariaLabel})}Object.defineProperty(TransformerTopology,SVG_ACCESSIBILITY_COMPONENT,{value:true});import React9 from"react";function Matrix({data,c,rowLabels,colLabels,labels,title,cellSize=48,cellWidth,cellHeight,rowLabelWidth,format="decimal",colorize=true,colorScale="heat"}){const resolvedCellWidth=cellWidth??cellSize;const resolvedCellHeight=cellHeight??cellSize;const resolvedRowLabelWidth=rowLabelWidth??cellSize;const formatValue=v=>{if(format==="percent")return`${Math.round(v*100)}%`;if(format==="integer")return`${Math.round(v)}`;return v.toFixed(2)};const cellColor=value=>{if(colorScale==="heat")return heatColor(value);if(value<.34)return c.bgHover;if(value<.67)return c.infoDark;return c.positiveDark};return React9.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:12}},title&&React9.createElement("div",{style:{...typography.label,color:c.textPrimary}},title),React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},colLabels&&React9.createElement("div",{style:{display:"flex",gap:2,marginLeft:rowLabels?resolvedRowLabelWidth+4:0}},...colLabels.map((label,i)=>React9.createElement("div",{key:`col-${i}`,style:{width:resolvedCellWidth,textAlign:"center",fontSize:11,fontWeight:600,color:c.textSecondary,fontFamily:"JetBrains Mono"}},label))),...data.map((row,ri)=>React9.createElement("div",{key:`row-${ri}`,style:{display:"flex",gap:2,alignItems:"center"}},rowLabels&&React9.createElement("div",{style:{width:resolvedRowLabelWidth,textAlign:"right",paddingRight:4,fontSize:11,fontWeight:600,color:c.textSecondary,fontFamily:"JetBrains Mono"}},rowLabels[ri]),...row.map((value,ci)=>{const backgroundColor=colorize?cellColor(value):c.bgCard;return React9.createElement("div",{key:`cell-${ri}-${ci}`,style:{width:resolvedCellWidth,height:resolvedCellHeight,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor,borderRadius:6,fontSize:11,fontWeight:600,color:colorize?getReadableTextColor(backgroundColor,c):c.textPrimary,fontFamily:"JetBrains Mono"}},labels?.[ri]?.[ci]??formatValue(value))})))))}function Heatmap({data,xLabels,yLabels,c,labels,title,cellSize=52,cellWidth,cellHeight,rowLabelWidth,colorScale}){return Matrix({data,colLabels:xLabels,rowLabels:yLabels,c,labels,title,colorize:true,cellSize,cellWidth,cellHeight,rowLabelWidth,colorScale})}function TiledMatrix({rows,cols,c,ariaLabel,regions=[],title,subtitle,cellSize=24,gap=3,tone="blue",muted=false,crossedOut=false}){const safeRows=Math.max(1,Math.floor(rows));const safeCols=Math.max(1,Math.floor(cols));const baseAccent=getToneColor(tone,c);const cellRows=Array.from({length:safeRows},(_,row)=>React9.createElement("div",{key:`tiled-matrix-row-${row}`,style:{display:"flex",gap}},...Array.from({length:safeCols},(_2,col)=>{const regionIndex=regions.findIndex(region2=>row>=region2.rowStart&&row<region2.rowEnd&&col>=region2.colStart&&col<region2.colEnd);const region=regionIndex>=0?regions[regionIndex]:void 0;const accent=getToneColor(region?.tone??tone,c);return React9.createElement("div",{key:`tiled-matrix-cell-${row}-${col}`,"data-region":regionIndex>=0?regionIndex:void 0,style:{width:cellSize,height:cellSize,boxSizing:"border-box",borderRadius:Math.max(2,Math.min(6,Math.round(cellSize*.18))),backgroundColor:region?`${accent}42`:muted?c.bgSubtle:`${baseAccent}0f`,border:`1px solid ${region?`${accent}aa`:c.borderSubtle}`,opacity:muted?.55:1}})})));const grid=React9.createElement("div",{"data-crossed-out":crossedOut?"true":void 0,style:{position:"relative",display:"flex",flexDirection:"column",gap,padding:gap,borderRadius:10,backgroundColor:c.bgSubtle,border:`1px solid ${c.borderLight}`,boxShadow:`0 8px 18px ${c.shadow}`,overflow:"hidden"}},...cellRows,...crossedOut?[React9.createElement("div",{key:"cross-forward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}}),React9.createElement("div",{key:"cross-backward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(-36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}})]:[]);return React9.createElement("div",{role:"img","aria-label":ariaLabel??(typeof title==="string"?title:"Tiled matrix"),style:{display:"flex",flexDirection:"column",alignItems:"center",gap:7}},...compactChildren([title&&React9.createElement("div",{style:{color:muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:"Inter",fontSize:13,fontWeight:900,lineHeight:1.1,textAlign:"center"}},title),subtitle&&React9.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:700,lineHeight:1.1,textAlign:"center"}},subtitle),grid]))}function DataTable({rows,c,cellWidth=54,firstColWidth=cellWidth,cellHeight=28,gap=5,headerRows=1,headerCols=1,fontSize=11,math=false}){const renderCell=cell=>math&&typeof cell==="string"?formatMathText(cell):cell;return React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap,alignItems:"center"}},...rows.map((row,rowIndex)=>React9.createElement("div",{key:`${rowIndex}-${row.map(String).join("|")}`,style:{display:"flex",gap}},...row.map((cell,colIndex)=>{const isHeaderRow=rowIndex<headerRows;const isHeaderCol=colIndex<headerCols;return React9.createElement("div",{key:`${rowIndex}-${colIndex}-${String(cell)}`,style:{width:colIndex===0?firstColWidth:cellWidth,height:cellHeight,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:7,backgroundColor:isHeaderRow?c.bgSubtle:c.bgHover,color:isHeaderCol?c.textPrimary:c.textSecondary,fontFamily:"JetBrains Mono",fontSize,fontWeight:isHeaderCol?850:650,lineHeight:1.15,...textFitStyle("center")}},renderCell(cell))}))))}function isGridCell(cell){return typeof cell==="object"&&cell!==null&&!React9.isValidElement(cell)&&("label"in cell||"tone"in cell||"color"in cell||"backgroundColor"in cell||"borderColor"in cell||"opacity"in cell)}function Grid({rows,c,cellWidth=34,cellHeight=30,gap=5,radius=7,fontSize=11,math=false,headerRows=0,headerCols=0}){const renderCellLabel=cell=>{const label=isGridCell(cell)?cell.label:cell;return math&&typeof label==="string"?formatMathText(label):label};const cellStyle=(cell,rowIndex,colIndex)=>{const config=isGridCell(cell)?cell:{};const toneColor=config.tone?getToneColor(config.tone,c):void 0;const isHeader=rowIndex<headerRows||colIndex<headerCols;const backgroundColor=config.backgroundColor??(toneColor?`${toneColor}22`:isHeader?c.bgSubtle:c.bgHover);const toneTextColor=config.tone?getReadableToneColor(config.tone,c,backgroundColor,c.bgHover):void 0;return{width:cellWidth,height:cellHeight,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:radius,backgroundColor,border:`1px solid ${config.borderColor??(toneColor?`${toneColor}55`:c.borderSubtle)}`,color:config.color??(toneTextColor??(isHeader?c.textPrimary:c.textSecondary)),...config.opacity!==void 0?{opacity:config.opacity}:{},fontFamily:"JetBrains Mono",fontSize,fontWeight:isHeader||toneColor?850:650,lineHeight:1.15,...textFitStyle("center")}};return React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap,alignItems:"center"}},...rows.map((row,rowIndex)=>React9.createElement("div",{key:`grid-row-${rowIndex}`,style:{display:"flex",gap}},...row.map((cell,colIndex)=>React9.createElement("div",{key:`grid-cell-${rowIndex}-${colIndex}`,style:cellStyle(cell,rowIndex,colIndex)},renderCellLabel(cell))))))}function AxisPlot({c,width,height,xMin=-1,xMax=1,yMin=-1,yMax=1,padding=18,showFrame=true,showAxes=true,showGrid=false,gridCount=5,frameRx=8,frameFill,frameStroke,axisColor,points=[],vectors=[],paths=[],xAxisLabel,yAxisLabel,children}){const innerWidth=Math.max(1,width-padding*2);const innerHeight=Math.max(1,height-padding*2);const xRange=xMax===xMin?1:xMax-xMin;const yRange=yMax===yMin?1:yMax-yMin;const sx=x=>padding+(x-xMin)/xRange*innerWidth;const sy=y=>padding+innerHeight-(y-yMin)/yRange*innerHeight;const xAxisY=yMin<=0&&yMax>=0?sy(0):padding+innerHeight/2;const yAxisX=xMin<=0&&xMax>=0?sx(0):padding+innerWidth/2;const axisStroke=axisColor??c.borderLight;const gridIndexes=Array.from({length:Math.max(0,gridCount)},(_,index)=>index+1);const elements=[];if(showFrame){elements.push(SvgFrame({key:"axis-frame",x:padding/2,y:padding/2,width:width-padding,height:height-padding,rx:frameRx,c,fill:frameFill,stroke:frameStroke}))}if(showGrid&&gridCount>0){elements.push(...gridIndexes.flatMap(index=>{const x=padding+innerWidth*index/(gridCount+1);const y=padding+innerHeight*index/(gridCount+1);return[React9.createElement("line",{key:`axis-grid-x-${index}`,x1:x,y1:padding,x2:x,y2:padding+innerHeight,stroke:c.borderSubtle,strokeWidth:1,opacity:.75}),React9.createElement("line",{key:`axis-grid-y-${index}`,x1:padding,y1:y,x2:padding+innerWidth,y2:y,stroke:c.borderSubtle,strokeWidth:1,opacity:.75})]}))}if(showAxes){elements.push(React9.createElement("line",{key:"axis-x",x1:padding,y1:xAxisY,x2:padding+innerWidth,y2:xAxisY,stroke:axisStroke,strokeWidth:1.6,opacity:.85}),React9.createElement("line",{key:"axis-y",x1:yAxisX,y1:padding,x2:yAxisX,y2:padding+innerHeight,stroke:axisStroke,strokeWidth:1.6,opacity:.85}))}elements.push(...paths.flatMap((path,index)=>{if(path.points.length<2)return[];const[first,...rest]=path.points;const commands=[`M ${sx(first.x)} ${sy(first.y)}`];for(const point of rest){if(path.interpolation==="step-after"){commands.push(`H ${sx(point.x)} V ${sy(point.y)}`)}else{commands.push(`L ${sx(point.x)} ${sy(point.y)}`)}}return[React9.createElement("path",{key:`axis-path-${index}`,d:commands.join(" "),fill:"none",stroke:path.color??getToneColor(path.tone??"blue",c),strokeWidth:path.strokeWidth??3,strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:path.dashed?"8 7":void 0,opacity:path.opacity??1})]}));elements.push(...vectors.map((vector,index)=>{const color=vector.color??getToneColor(vector.tone??"blue",c);const x1=sx(vector.x1);const y1=sy(vector.y1);const x2=sx(vector.x2);const y2=sy(vector.y2);if(vector.arrow){return VectorArrow({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,arrowSize:vector.arrowSize,opacity:vector.opacity})}return VectorSegment({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,opacity:vector.opacity,showStartDot:vector.showStartDot,showEndDot:vector.showEndDot,dotRadius:vector.dotRadius})}));elements.push(...points.map((point,index)=>SvgPoint({key:`axis-point-${index}`,cx:sx(point.x),cy:sy(point.y),r:point.r??5,fill:point.fill??getToneColor(point.tone??"blue",c),stroke:point.stroke,strokeWidth:point.strokeWidth,opacity:point.opacity})));elements.push(...React9.Children.toArray(children).filter(React9.isValidElement));const svg=React9.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...elements);if(!xAxisLabel&&!yAxisLabel)return svg;return React9.createElement("div",{style:{position:"relative",width,height,display:"flex"}},svg,xAxisLabel&&React9.createElement("div",{key:"axis-x-label",style:{position:"absolute",left:width/2,bottom:0,width:width-padding*2,transform:"translateX(-50%)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:750}},xAxisLabel),yAxisLabel&&React9.createElement("div",{key:"axis-y-label",style:{position:"absolute",left:0,top:height/2,width:height-padding*2,transform:"translate(-50%, -50%) rotate(-90deg)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:750}},yAxisLabel))}import React11 from"react";import React10,{isValidElement as isValidElement2}from"react";var CANVAS_CHART_COMPONENT=Symbol.for("vizmatic.canvasChartComponent");var CHART_FRAME_COMPONENT=Symbol.for("vizmatic.chartFrameComponent");var FIT_PROP="__vizmaticCanvasChartFit";var SCOPE_PROP="data-vizmatic-chart-fit-scope";var VIEWPORT_PROP="data-vizmatic-chart-fit-viewport";function isCanvasChart(component){return typeof component==="function"&&Boolean(component[CANVAS_CHART_COMPONENT])}function CanvasChartFit({children,width,height}){let chart=children;for(let depth=0;isValidElement2(chart)&&typeof chart.type==="function"&&depth<16;depth+=1){if(chart.type[CHART_FRAME_COMPONENT]){const props=chart.props;const padding=typeof props.padding==="number"?props.padding:16;chart=React10.cloneElement(chart,{...props,width:typeof props.width==="number"?props.width+2*(padding+1):props.width,height:void 0});break}chart=chart.type(chart.props)}return React10.createElement("div",{[FIT_PROP]:{width,height},style:{position:"relative",display:"flex",width,height,flexShrink:0}},React10.createElement("div",{style:{position:"absolute",left:0,top:0,display:"flex",alignItems:"flex-start"}},chart))}function prepareChartFits(element){const sizes=new Map;const visit=(node,scope)=>{if(Array.isArray(node))return node.map(child=>visit(child,scope));if(!isValidElement2(node))return node;if(typeof node.type==="function"){const resolved=visit(node.type(node.props),scope);return node.key!=null&&isValidElement2(resolved)?React10.cloneElement(resolved,{key:node.key}):resolved}const size=node.props[FIT_PROP];const props={...node.props};delete props[FIT_PROP];if(size){const id=String(sizes.size);sizes.set(id,size);props[VIEWPORT_PROP]=id;return React10.cloneElement(node,props,visit(node.props.children,id))}if(scope!==void 0&&typeof node.type==="string")props[SCOPE_PROP]=scope;const children=node.props.children;return children===void 0?React10.cloneElement(node,props):React10.cloneElement(node,props,visit(children,scope))};return{element:visit(element),sizes}}function fittedTree(element,geometry){if(Array.isArray(element))return element.map(child=>fittedTree(child,geometry));if(!isValidElement2(element))return element;const id=element.props[VIEWPORT_PROP];const children=element.props.children;if(typeof id==="string"){const fit=geometry.get(id);const content=React10.Children.only(children);return React10.cloneElement(element,{},React10.cloneElement(content,{style:{...content.props.style,left:fit.left,top:fit.top,transform:`scale(${fit.scale})`,transformOrigin:"top left"}}))}return children===void 0?element:React10.cloneElement(element,{},fittedTree(children,geometry))}async function renderWithCanvasChartFit(render,element,options){const prepared=prepareChartFits(element);if(!prepared.sizes.size)return render(prepared.element,options);const viewports=new Map;const bounds=new Map;await render(prepared.element,{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")viewports.set(viewport,node);const id=node.props[SCOPE_PROP];if(typeof id!=="string"||node.width<=0||node.height<=0)return;const prior=bounds.get(id);bounds.set(id,{left:Math.min(prior?.left??Infinity,node.left),top:Math.min(prior?.top??Infinity,node.top),right:Math.max(prior?.right??-Infinity,node.left+node.width),bottom:Math.max(prior?.bottom??-Infinity,node.top+node.height)})}});const geometry=new Map;for(const[id,size]of prepared.sizes){const viewport=viewports.get(id);const measured=bounds.get(id);if(!viewport||!measured)throw new Error("Could not measure the chart inside CanvasItem.");const width=measured.right-measured.left,height=measured.bottom-measured.top;const scale=Math.min(size.width/width,size.height/height);if(!Number.isFinite(scale)||scale<=0)throw new Error("CanvasItem charts require positive, finite dimensions.");geometry.set(id,{...size,scale,left:(size.width-width*scale)/2-(measured.left-viewport.left)*scale,top:(size.height-height*scale)/2-(measured.top-viewport.top)*scale})}const finalViewports=new Map;return render(fittedTree(prepared.element,geometry),{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")finalViewports.set(viewport,node);const id=node.props[SCOPE_PROP];const fit=typeof id==="string"?geometry.get(id):void 0;const origin=typeof id==="string"?finalViewports.get(id):void 0;if(fit&&origin){const left=origin.left+fit.left,top=origin.top+fit.top;const style=node.props.style??{};options.onNodeDetected?.({...node,left:left+(node.left-left)*fit.scale,top:top+(node.top-top)*fit.scale,width:node.width*fit.scale,height:node.height*fit.scale,props:{...node.props,style:{...style,...typeof style.fontSize==="number"?{fontSize:style.fontSize*fit.scale}:{}}}})}else options.onNodeDetected?.(node)}})}var chartPalette=["primary","secondary","positive","warning","info","accent","critical"];function isColorName(value){return chartPalette.includes(value)||value==="neutral"}function chartColor(color,c,index=0){const resolved=color??chartPalette[index%chartPalette.length];if(!isColorName(resolved))return resolved;return getReadableColor(resolved,c)}function formatChartValue(value,format="decimal"){if(typeof format==="function")return format(value);if(format==="percent")return`${Math.round(value*100)}%`;if(format==="integer")return`${Math.round(value)}`;if(format==="compact"){const magnitude=Math.abs(value);if(magnitude>=999950)return`${(value/1e6).toFixed(1)}M`;if(magnitude>=999.95)return`${(value/1e3).toFixed(1)}k`;return`${Math.round(value)}`}return Number.isInteger(value)?`${value}`:value.toFixed(2)}function chartDomain(values,min,max){const rawMin=min??Math.min(0,...values);const rawMax=max??Math.max(...values,1);const range=rawMax===rawMin?1:rawMax-rawMin;return{min:rawMin,max:rawMax,range}}function chartTicks(min,max,count=4){if(count<=1||max===min)return[min];const step=(max-min)/(count-1);return Array.from({length:count},(_,index)=>min+step*index)}function axisTextStyle(c){return{fontFamily:"JetBrains Mono",fontSize:11,fontWeight:600,color:c.textMuted,lineHeight:1}}function createPlotArea(width,height,margin){const innerWidth=Math.max(1,width-margin.left-margin.right);const innerHeight=Math.max(1,height-margin.top-margin.bottom);return{width,height,margin,x:margin.left,y:margin.top,right:width-margin.right,bottom:height-margin.bottom,innerWidth,innerHeight}}function scaleToRange(value,min,range,outputStart,outputLength){return outputStart+(value-min)/range*outputLength}function xInPlot(value,domain,plot){return scaleToRange(value,domain.min,domain.range,plot.x,plot.innerWidth)}function yInPlot(value,domain,plot){return plot.y+plot.innerHeight-(value-domain.min)/domain.range*plot.innerHeight}function chartLabel(key,text,x,y,c,options={}){const align=options.align??"center";const width=options.width??72;const fontSize=options.fontSize??11;const labelHeight=options.height??Math.ceil(fontSize*1.4);let left=x;let top=y;let transform=options.transform??(align==="center"?"translate(-50%, -50%)":align==="right"?"translate(-100%, -50%)":"translate(0, -50%)");if(options.bounds){const padding=options.bounds.padding??4;const idealLeft=align==="center"?x-width/2:align==="right"?x-width:x;const idealTop=y-labelHeight/2;left=clamp(idealLeft,options.bounds.x+padding,options.bounds.x+options.bounds.width-width-padding);top=clamp(idealTop,options.bounds.y+padding,options.bounds.y+options.bounds.height-labelHeight-padding);transform=void 0}return React11.createElement("div",{key,style:{position:"absolute",left,top,width,...transform!==void 0?{transform}:{},display:"flex",justifyContent:align==="right"?"flex-end":align==="left"?"flex-start":"center",...textFitStyle(align),pointerEvents:"none",...axisTextStyle(c),color:options.color??c.textMuted,fontFamily:options.fontFamily??"JetBrains Mono",fontWeight:options.fontWeight??600,fontSize,lineHeight:1.15}},text)}function pointLabelPlacement(x,y,plot,index,width=70){const nearTop=y<plot.y+58;const nearBottom=y>plot.bottom-34;const nearLeft=x<plot.x+76;const nearRight=x>plot.right-76;const align=nearLeft?"left":nearRight?"right":"center";const verticalOffset=nearTop?18:nearBottom?-18:index%2===0?-16:18;return{x,y:y+verticalOffset,align,width,bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:6}}}function ChartFrame(props){return React11.createElement(ChartFrameContent,props)}function ChartFrameContent({children,c,title,subtitle,legend,footer,width="100%",height,padding=16}){return React11.createElement("div",{style:{width,...height?{height}:{},boxSizing:"border-box",display:"flex",flexDirection:"column",gap:12,padding,borderRadius:8,border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard,boxShadow:`0 9px 24px ${c.shadow}`}},(title||subtitle)&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,maxWidth:"100%"}},title&&React11.createElement("div",{style:{...typography.small,...textFitStyle(),color:c.textPrimary,fontWeight:900}},title),subtitle&&React11.createElement("div",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,lineHeight:1.35}},subtitle)),children,(legend||footer)&&React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:legend?"space-between":"center",gap:12,minHeight:18}},legend&&React11.createElement("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",minWidth:0}},...legend.map((item,index)=>React11.createElement("div",{key:`${item.label}-${index}`,style:{display:"flex",alignItems:"center",gap:6,minWidth:0}},React11.createElement("span",{style:{width:14,height:3,borderRadius:999,backgroundColor:chartColor(item.color,c,index),display:"flex"}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary}},item.label)))),footer&&React11.createElement("div",{style:{...typography.tiny,...textFitStyle("right"),color:c.textMuted}},footer)))}Object.defineProperty(ChartFrameContent,CHART_FRAME_COMPONENT,{value:true});function polarPoint(cx,cy,radius,angleDegrees){const radians=angleDegrees*Math.PI/180;return{x:cx+radius*Math.cos(radians),y:cy+radius*Math.sin(radians)}}function donutArcPath(cx,cy,outerRadius,innerRadius,startAngle,endAngle){const span=Math.min(359.99,Math.max(.01,endAngle-startAngle));const safeEnd=startAngle+span;const outerStart=polarPoint(cx,cy,outerRadius,startAngle);const outerEnd=polarPoint(cx,cy,outerRadius,safeEnd);const innerEnd=polarPoint(cx,cy,innerRadius,safeEnd);const innerStart=polarPoint(cx,cy,innerRadius,startAngle);const largeArc=span>180?1:0;return[`M ${outerStart.x} ${outerStart.y}`,`A ${outerRadius} ${outerRadius} 0 ${largeArc} 1 ${outerEnd.x} ${outerEnd.y}`,`L ${innerEnd.x} ${innerEnd.y}`,`A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}`,"Z"].join(" ")}function validateNonNegativeSegments(segments,chartName){let total=0;for(const segment of segments){if(!Number.isFinite(segment.value)||segment.value<0){throw new RangeError(`${chartName} values must be finite, non-negative numbers.`)}total+=segment.value;if(!Number.isFinite(total)){throw new RangeError(`${chartName} total must be finite.`)}}return total}function pieSectorPath(cx,cy,radius,startAngle,endAngle){const span=endAngle-startAngle;const start=polarPoint(cx,cy,radius,startAngle);if(span>=359.999){const opposite=polarPoint(cx,cy,radius,startAngle+180);return[`M ${cx} ${cy}`,`L ${start.x} ${start.y}`,`A ${radius} ${radius} 0 1 1 ${opposite.x} ${opposite.y}`,`A ${radius} ${radius} 0 1 1 ${start.x} ${start.y}`,"Z"].join(" ")}const end=polarPoint(cx,cy,radius,endAngle);const largeArc=span>180?1:0;return`M ${cx} ${cy} L ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArc} 1 ${end.x} ${end.y} Z`}function PieChart({segments,c,title,subtitle,width=360,height=240,size,format="decimal",showLegend=true,footer}){const total=validateNonNegativeSegments(segments,"PieChart");const positiveSegments=segments.filter(segment=>segment.value>0);const resolvedSize=size??Math.min(184,Math.max(132,height-44),Math.max(132,width*.5));const radius=resolvedSize/2-2;const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const paths=positiveSegments.map((segment,index)=>{const span=total>0?segment.value/total*360:0;const start=cursor;const end=index===positiveSegments.length-1?270:cursor+span;cursor+=span;return React11.createElement("path",{key:`pie-segment-${segment.label}-${index}`,d:pieSectorPath(cx,cy,radius,start,end),fill:chartColor(segment.color,c,index),stroke:c.bgCard,strokeWidth:positiveSegments.length>1?2:0,"data-pie-label":segment.label,"data-pie-value":segment.value,"data-pie-share":total>0?segment.value/total:0})});const legend=showLegend&&positiveSegments.length>0&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>{const formattedValue=formatChartValue(segment.value,format);const share=formatChartValue(segment.value/total,"percent");const label=segment.valueLabel??(format==="percent"?formattedValue:`${formattedValue} \xB7 ${share}`);return React11.createElement("div",{key:`pie-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:8,minWidth:0}},React11.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:3,backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React11.createElement("span",{style:{...typography.tiny,color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:850,flexShrink:0}},label))}));return ChartFrame({c,title,subtitle,footer,width,children:React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:18,minHeight:resolvedSize,width:"100%"}},React11.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`,role:"img","aria-label":title??"Pie chart"},positiveSegments.length===0?React11.createElement("circle",{cx,cy,r:radius,fill:"none",stroke:c.borderLight,strokeWidth:2}):paths),legend)})}function DonutChart({segments,c,title,subtitle,width=360,height=230,size,thickness,format="decimal",centerLabel,centerValue,showLegend=true,footer}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);const resolvedSize=size??Math.min(162,Math.max(128,height-44),Math.max(128,width*.48));const resolvedThickness=thickness??Math.max(20,Math.round(resolvedSize*.18));const outerRadius=resolvedSize/2-2;const innerRadius=Math.max(18,outerRadius-resolvedThickness);const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const resolvedCenterValue=centerValue??(centerLabel!=null?formatChartValue(total,format):void 0);const paths=positiveSegments.map((segment,index)=>{const rawSpan=total>0?segment.value/total*360:0;const gap=positiveSegments.length>1?Math.min(1.5,rawSpan*.28):0;const start=cursor+gap/2;const end=cursor+rawSpan-gap/2;cursor+=rawSpan;if(end<=start)return null;return React11.createElement("path",{key:`donut-segment-${segment.label}-${index}`,d:donutArcPath(cx,cy,outerRadius,innerRadius,start,end),fill:chartColor(segment.color,c,index)})}).filter(Boolean);const legend=showLegend&&positiveSegments.length>0&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>React11.createElement("div",{key:`donut-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:8,minWidth:0}},React11.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:3,backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React11.createElement("span",{style:{...typography.tiny,color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:850,flexShrink:0}},segment.valueLabel??formatChartValue(segment.value,format)))));return ChartFrame({c,title,subtitle,footer,width,height,padding:16,children:React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:18,minHeight:resolvedSize,width:"100%"}},React11.createElement("div",{style:{position:"relative",display:"flex",width:resolvedSize,height:resolvedSize,flexShrink:0}},React11.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`},positiveSegments.length===0?React11.createElement("circle",{cx,cy,r:(outerRadius+innerRadius)/2,fill:"none",stroke:c.borderLight,strokeWidth:resolvedThickness}):paths),(centerLabel!=null||resolvedCenterValue!=null)&&React11.createElement("div",{style:{position:"absolute",top:resolvedThickness,left:resolvedThickness,width:Math.max(0,resolvedSize-resolvedThickness*2),height:Math.max(0,resolvedSize-resolvedThickness*2),display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:3,textAlign:"center"}},resolvedCenterValue!=null&&React11.createElement("div",{style:{...typography.small,color:c.textPrimary,fontFamily:"JetBrains Mono",fontSize:18,fontWeight:900,lineHeight:1.05,...textFitStyle("center")}},resolvedCenterValue),centerLabel!=null&&React11.createElement("div",{style:{...typography.tiny,color:c.textMuted,lineHeight:1.2,...textFitStyle("center")}},centerLabel))),legend)})}function StackedBar({segments,c,width=480,height=68,title,subtitle,showLegend=true}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);return React11.createElement("div",{style:{width,display:"flex",flexDirection:"column",gap:10}},(title||subtitle)&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:3}},title&&React11.createElement("div",{style:{...typography.label,color:c.textPrimary,fontWeight:850}},title),subtitle&&React11.createElement("div",{style:{...typography.tiny,color:c.textSecondary}},subtitle)),React11.createElement("div",{style:{width,height,display:"flex",overflow:"hidden",borderRadius:14,border:`1px solid ${c.borderLight}`,backgroundColor:c.bgCard,boxShadow:`0 8px 22px ${c.shadow}`}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;const segmentWidth=width*share;const color=chartColor(segment.color,c,index);return React11.createElement("div",{key:`${segment.label}-${index}`,style:{width:`${share*100}%`,height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,...index<positiveSegments.length-1?{borderRight:`2px solid ${c.bgSubtle}`}:{}}},segmentWidth>=64&&React11.createElement("span",{style:{...typography.small,color:getReadableTextColor(color,c),fontWeight:900,whiteSpace:"nowrap"}},segment.valueLabel??formatChartValue(share,"percent")))})),showLegend&&React11.createElement("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;return React11.createElement("div",{key:`legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:7}},React11.createElement("span",{style:{width:12,height:12,borderRadius:4,display:"flex",backgroundColor:chartColor(segment.color,c,index)}}),React11.createElement("span",{style:{...typography.tiny,color:c.textSecondary}},`${segment.label} ${segment.valueLabel??formatChartValue(share,"percent")}`))})))}function BarChart({data,c,title,subtitle,width=320,height=220,min,max,format="decimal",showGrid=true,showValues=true,yAxisLabel,footer}){const margin={top:18,right:38,bottom:40,left:yAxisLabel?52:38};const plot=createPlotArea(width,height,margin);const domain=chartDomain(data.map(item=>item.value),min,max);const ticks=chartTicks(domain.min,domain.max,4);const barSlot=plot.innerWidth/Math.max(data.length,1);const barWidth=Math.max(8,Math.min(76,barSlot*.72));const zeroY=yInPlot(0,domain,plot);const baselineY=clamp(zeroY,plot.y,plot.bottom);const barGeometries=data.map((item,index)=>{const x=plot.x+index*barSlot+(barSlot-barWidth)/2;const valueY=clamp(yInPlot(item.value,domain,plot),plot.y,plot.bottom);const distance=Math.abs(baselineY-valueY);const barHeight=Math.min(plot.innerHeight,Math.max(4,distance));const growsUp=valueY<baselineY||valueY===baselineY&&item.value>=0;const y=growsUp?Math.max(plot.y,baselineY-barHeight):Math.min(plot.bottom-barHeight,baselineY);return{item,index,x,y,barHeight,valueY,color:chartColor(item.color,c,index)}});return ChartFrame({c,title,subtitle,width,footer,children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React11.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React11.createElement("line",{key:`tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.y,x2:plot.x,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.x,y1:baselineY,x2:plot.right,y2:baselineY,stroke:c.borderLight,strokeWidth:1.2}),...barGeometries.map(({item,index,x,y,barHeight,color})=>React11.createElement("rect",{key:`${item.label}-${index}`,x,y,width:barWidth,height:barHeight,rx:5,fill:color,opacity:.92}))),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`tick-label-${tick}`,formatChartValue(tick,format),plot.x-8,y,c,{align:"right",width:36})}),yAxisLabel&&chartLabel("y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...barGeometries.flatMap(({item,index,x,y,barHeight,valueY})=>[...showValues?[chartLabel(`bar-value-${index}`,item.valueLabel??formatChartValue(item.value,format),x+barWidth/2,item.value<0?y+barHeight+12:clamp(valueY-8,10,height-28),c,{color:c.textPrimary,fontWeight:800,width:54,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]:[],chartLabel(`bar-label-${index}`,item.label,x+barWidth/2,height-16,c,{width:54})]))})}function ParetoBarChart({data,c,title,subtitle,width=520,height=300,format="integer",showGrid=true,showValues=true,footer}){let total=0;for(const item of data){if(!Number.isFinite(item.value)||item.value<0){throw new RangeError("ParetoBarChart values must be finite, non-negative numbers.")}total+=item.value;if(!Number.isFinite(total)){throw new RangeError("ParetoBarChart total must be finite.")}}const sorted=data.map((item,index)=>({item,index})).sort((left,right)=>right.item.value-left.item.value||left.index-right.index);const maximum=Math.max(1,...sorted.map(({item})=>item.value));const margin={top:24,right:48,bottom:48,left:48};const plot=createPlotArea(width,height,margin);const valueDomain={min:0,range:maximum>Number.MAX_VALUE/1.16?maximum:maximum*1.16};const countTicks=chartTicks(0,maximum,4);const slot=plot.innerWidth/Math.max(sorted.length,1);const barWidth=Math.max(6,Math.min(68,slot*.68));let accumulated=0;const bars=sorted.map(({item,index},order)=>{accumulated+=item.value;const cumulative=total===0?0:order===sorted.length-1?1:accumulated/total;const x=plot.x+order*slot+(slot-barWidth)/2;const top=yInPlot(item.value,valueDomain,plot);return{item,sourceIndex:index,order,x,y:top,height:Math.max(0,plot.bottom-top),color:chartColor(item.color,c,order),centerX:x+barWidth/2,cumulative,cumulativeY:plot.bottom-cumulative*plot.innerHeight}});const cumulativePath=bars.map(({centerX,cumulativeY},index)=>`${index===0?"M":"L"} ${centerX.toFixed(1)} ${cumulativeY.toFixed(1)}`).join(" ");return ChartFrame({c,title,subtitle,width,footer,children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,role:"img","aria-label":title??"Pareto bar chart"},showGrid&&React11.createElement("g",{},...countTicks.map(tick=>{const y=yInPlot(tick,valueDomain,plot);return React11.createElement("line",{key:`pareto-count-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.right,y1:plot.y,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...bars.map(({item,order,x,y,height:barHeight,color})=>React11.createElement("rect",{key:`pareto-bar-${item.label}-${order}`,x,y,width:barWidth,height:barHeight,rx:4,fill:color,opacity:.86,"data-pareto-bar":item.label,"data-pareto-value":item.value,"data-pareto-order":order})),cumulativePath&&React11.createElement("path",{d:cumulativePath,fill:"none",stroke:chartColor("critical",c),strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round","data-pareto-cumulative-line":true}),...bars.map(({item,sourceIndex,centerX,cumulativeY,cumulative,order})=>React11.createElement("circle",{key:`pareto-cumulative-point-${order}`,cx:centerX,cy:cumulativeY,r:4,fill:chartColor("critical",c),stroke:c.bgCard,strokeWidth:2,"data-pareto-category":item.label,"data-pareto-source-index":sourceIndex,"data-pareto-cumulative-percent":cumulative*100}))),...countTicks.map(tick=>chartLabel(`pareto-count-label-${tick}`,formatChartValue(tick,format),plot.x-7,yInPlot(tick,valueDomain,plot),c,{align:"right",width:36})),...[0,.5,1].map(share=>chartLabel(`pareto-percent-label-${share}`,`${Math.round(share*100)}%`,plot.right+7,plot.bottom-share*plot.innerHeight,c,{align:"left",width:38})),...bars.flatMap(({item,order,centerX,y})=>[...showValues?[chartLabel(`pareto-value-${order}`,item.valueLabel??formatChartValue(item.value,format),centerX,clamp(y-8,plot.y+8,plot.bottom-12),c,{color:c.textPrimary,fontWeight:800,width:Math.min(slot,64),bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight}})]:[],chartLabel(`pareto-category-${order}`,item.label,centerX,height-17,c,{width:Math.max(1,Math.min(96,slot-2)),bounds:{x:plot.x,y:plot.bottom+1,width:plot.innerWidth,height:Math.max(1,height-plot.bottom-2),padding:0}})]))})}function LineChart({series,c,title,subtitle,width=420,height=240,labels,min,max,format="decimal",showGrid=true,showPoints=true,yAxisLabel,footer}){const margin={top:18,right:20,bottom:labels?36:24,left:yAxisLabel?54:40};const plot=createPlotArea(width,height,margin);const allValues=series.flatMap(item=>item.points);const domain=chartDomain(allValues,min,max);const maxPoints=Math.max(labels?.length??0,...series.map(item=>item.points.length),1);const xInset=maxPoints<=1?0:Math.min(26,Math.max(14,plot.innerWidth*.06));const xStart=maxPoints<=1?plot.x+plot.innerWidth/2:plot.x+xInset;const xSpan=maxPoints<=1?0:Math.max(1,plot.innerWidth-xInset*2);const xStep=maxPoints<=1?0:xSpan/(maxPoints-1);const ticks=chartTicks(domain.min,domain.max,4);const pointFor=(value,index)=>{const x=xStart+index*xStep;const markerInset=showPoints?6.5:2;const y=clamp(yInPlot(value,domain,plot),plot.y+markerInset,plot.bottom-markerInset);return{x,y}};const pathFor=points=>points.map((value,index)=>{const point=pointFor(value,index);return`${index===0?"M":"L"} ${point.x.toFixed(1)} ${point.y.toFixed(1)}`}).join(" ");return ChartFrame({c,title,subtitle,width,footer,legend:series.map((item,index)=>({label:item.name,color:item.color??chartPalette[index%chartPalette.length]})),children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React11.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React11.createElement("line",{key:`line-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.y,x2:plot.x,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...series.flatMap((item,seriesIndex)=>{if(item.points.length===0)return[];const color=chartColor(item.color,c,seriesIndex);const linePath=pathFor(item.points);let areaPath="";if(item.area&&item.points.length>1){const firstPoint=pointFor(item.points[0],0);const lastPoint=pointFor(item.points[item.points.length-1],item.points.length-1);areaPath=`${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`}const elements=[];if(areaPath){elements.push(React11.createElement("path",{key:`${item.name}-area`,d:areaPath,fill:color,opacity:.12}))}elements.push(React11.createElement("path",{key:`${item.name}-line`,d:linePath,fill:"none",stroke:color,strokeWidth:4,strokeLinecap:"round",strokeLinejoin:"round"}));if(showPoints){elements.push(...item.points.map((value,index)=>{const point=pointFor(value,index);return React11.createElement("circle",{key:`${item.name}-point-${index}`,cx:point.x,cy:point.y,r:5,fill:c.bgCard,stroke:color,strokeWidth:3})}))}return elements})),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`line-tick-label-${tick}`,formatChartValue(tick,format),plot.x-8,y,c,{align:"right",width:36})}),yAxisLabel&&chartLabel("line-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...(labels??[]).map((label,index)=>{const x=xStart+index*xStep;return chartLabel(`line-x-${label}`,label,x,height-14,c,{width:72})}))})}for(const chart of[PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}import React12 from"react";for(const chart of[ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}function xTickLabelAlign(index,count){if(index===0)return"left";if(index===count-1)return"right";return"center"}function ScatterPlot({points,c,title,subtitle,width=380,height=260,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,footer}){const margin={top:20,right:24,bottom:xAxisLabel?46:34,left:yAxisLabel?54:42};const plot=createPlotArea(width,height,margin);const xDomain=chartDomain(points.map(item=>item.x),xMin,xMax);const yDomain=chartDomain(points.map(item=>item.y),yMin,yMax);const xTicks=chartTicks(xDomain.min,xDomain.max,4);const yTicks=chartTicks(yDomain.min,yDomain.max,4);const pointFor=(xValue,yValue)=>({x:xInPlot(xValue,xDomain,plot),y:yInPlot(yValue,yDomain,plot)});const pointGeometries=points.map((item,index)=>{const point=pointFor(item.x,item.y);return{item,index,point,color:chartColor(item.color,c,index)}});return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`x-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`y-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),...pointGeometries.map(({item,index,point,color})=>React12.createElement("circle",{key:`${item.label??"point"}-${index}`,cx:point.x,cy:point.y,r:item.size??7,fill:color,opacity:.92,stroke:c.bgCard,strokeWidth:2}))),...xTicks.map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:44})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:36})}),xAxisLabel&&chartLabel("scatter-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("scatter-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({item,index,point,color})=>{if(!item.label)return[];const placement=pointLabelPlacement(point.x,point.y,plot,index);return[chartLabel(`scatter-point-label-${index}`,item.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color,fontWeight:800})]}))})}function pointDominates(candidate,point,xObjective,yObjective){const xNoWorse=xObjective==="minimize"?candidate.x<=point.x:candidate.x>=point.x;const yNoWorse=yObjective==="minimize"?candidate.y<=point.y:candidate.y>=point.y;const xBetter=xObjective==="minimize"?candidate.x<point.x:candidate.x>point.x;const yBetter=yObjective==="minimize"?candidate.y<point.y:candidate.y>point.y;return xNoWorse&&yNoWorse&&(xBetter||yBetter)}function paretoFrontierIndices(points,xObjective,yObjective){const frontier=new Set;for(const candidate of points){const dominated=points.some(({point})=>pointDominates(point,candidate.point,xObjective,yObjective));if(!dominated)frontier.add(candidate.index)}return frontier}function positiveLogDomain(values,min,max){const positiveValues=values.filter(value=>Number.isFinite(value)&&value>0);const positiveMin=min!==void 0&&Number.isFinite(min)&&min>0?min:Math.min(...positiveValues,1);const fallbackMax=Math.max(...positiveValues,positiveMin*10);const positiveMax=max!==void 0&&Number.isFinite(max)&&max>0?max:fallbackMax;const safeMin=Math.max(Number.MIN_VALUE,positiveMin);const safeMax=positiveMax>safeMin?positiveMax:safeMin*10;return{min:safeMin,max:safeMax,range:Math.log(safeMax)-Math.log(safeMin)}}function logChartTicks(min,max,count=5){if(!(min>0)||!(max>min)||count<=1)return[min];const startPower=Math.ceil(Math.log10(min));const endPower=Math.floor(Math.log10(max));const powers=Array.from({length:Math.max(0,endPower-startPower+1)},(_,index)=>10**(startPower+index)).filter(value=>value>=min&&value<=max);if(powers.length>=4)return powers;return Array.from({length:count},(_,index)=>min*(max/min)**(index/(count-1)))}function ParetoChart({points,c,title,subtitle,width=640,height=360,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,xScale="linear",xObjective="minimize",yObjective="maximize",frontierColor,showGoal=true,goalLabel,footer}){const margin={top:22,right:26,bottom:xAxisLabel?48:36,left:yAxisLabel?56:44};const plot=createPlotArea(width,height,margin);const validPoints=points.map((point,index)=>({point,index})).filter(({point})=>Number.isFinite(point.x)&&Number.isFinite(point.y)&&(xScale!=="log"||point.x>0));const frontierIndices=paretoFrontierIndices(validPoints,xObjective,yObjective);const xDomain=xScale==="log"?positiveLogDomain(validPoints.map(({point})=>point.x),xMin,xMax):chartDomain(validPoints.map(({point})=>point.x),xMin,xMax);const yDomain=chartDomain(validPoints.map(({point})=>point.y),yMin,yMax);const xTicks=xScale==="log"?logChartTicks(xDomain.min,xDomain.max):chartTicks(xDomain.min,xDomain.max,5);const yTicks=chartTicks(yDomain.min,yDomain.max,5);const frontier=chartColor(frontierColor??"positive",c,0);const pointFor=(xValue,yValue)=>{const x=xScale==="log"?plot.x+(Math.log(xValue>0?xValue:xDomain.min)-Math.log(xDomain.min))/xDomain.range*plot.innerWidth:xInPlot(xValue,xDomain,plot);return{x:clamp(x,plot.x,plot.right),y:clamp(yInPlot(yValue,yDomain,plot),plot.y,plot.bottom)}};const pointGeometries=validPoints.map(({point,index})=>{const pointPosition=pointFor(point.x,point.y);const isFrontier=frontierIndices.has(index);return{point,index,x:pointPosition.x,y:pointPosition.y,color:chartColor(point.color??(isFrontier?frontier:"neutral"),c,index),frontier:isFrontier}});const frontierGeometries=pointGeometries.filter(geometry=>geometry.frontier).sort((left,right)=>left.point.x-right.point.x);const frontierPath=frontierGeometries.length>1?frontierGeometries.map((geometry,index)=>`${index===0?"M":"L"} ${geometry.x.toFixed(1)} ${geometry.y.toFixed(1)}`).join(" "):void 0;const goalText=goalLabel??`goal: ${xObjective==="minimize"?"lower x":"higher x"} \xB7 ${yObjective==="maximize"?"higher y":"lower y"}`;const goalXStart=plot.right-72;const goalY=plot.y+18;const goalXEnd=xObjective==="minimize"?goalXStart-26:goalXStart+26;const goalYStart=plot.y+52;const goalYEnd=yObjective==="maximize"?goalYStart-26:goalYStart+26;const arrowSize=5;return ChartFrame({c,title,subtitle,width,footer,legend:[{label:"Pareto frontier",color:frontier},{label:"dominated",color:"neutral"}],children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=pointFor(tick,yDomain.min).x;return React12.createElement("line",{key:`pareto-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`pareto-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),showGoal&&React12.createElement("g",{"data-pareto-goal":true,stroke:frontier,fill:"none",strokeWidth:2,strokeLinecap:"round"},React12.createElement("line",{x1:goalXStart,y1:goalY,x2:goalXEnd,y2:goalY}),React12.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY-arrowSize}),React12.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY+arrowSize}),React12.createElement("line",{x1:goalXStart,y1:goalYStart,x2:goalXStart,y2:goalYEnd}),React12.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart-arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)}),React12.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart+arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)})),frontierPath&&React12.createElement("path",{"data-pareto-frontier":true,d:frontierPath,fill:"none",stroke:frontier,strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"}),...pointGeometries.filter(geometry=>!geometry.frontier).concat(pointGeometries.filter(geometry=>geometry.frontier)).map(({point,index,x,y,color,frontier:isFrontier})=>React12.createElement("circle",{key:`pareto-point-${point.label??"point"}-${index}`,"data-pareto-status":isFrontier?"frontier":"dominated",cx:x,cy:y,r:Math.max(4,Math.min(20,point.size??(isFrontier?8:7))),fill:color,opacity:isFrontier?1:.38,stroke:isFrontier?frontier:c.bgCard,strokeWidth:isFrontier?3:2}))),...xTicks.map((tick,index)=>{const x=pointFor(tick,yDomain.min).x;return chartLabel(`pareto-x-tick-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:52})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`pareto-y-tick-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:42})}),showGoal&&chartLabel("pareto-goal-label",goalText,plot.right-2,plot.y+9,c,{align:"right",width:170,color:frontier,fontWeight:850,fontSize:11,bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:4}}),xAxisLabel&&chartLabel("pareto-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("pareto-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({point,index,x,y,color,frontier:isFrontier})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`pareto-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color:isFrontier?color:c.textMuted,fontWeight:isFrontier?850:600})]}))})}function QuadrantChart({points,regions,c,title,subtitle,width=700,height=360,xMin,xMax,yMin,yMax,xThreshold,yThreshold,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showTicks=false,showGrid=false,footer}){const margin={top:18,right:20,bottom:xAxisLabel?showTicks?58:46:showTicks?36:24,left:yAxisLabel?showTicks?72:54:showTicks?48:24};const plot=createPlotArea(width,height,margin);const xDomain=xMin===void 0&&xMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.x),xMin,xMax);const yDomain=yMin===void 0&&yMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.y),yMin,yMax);const resolvedXThreshold=clamp(xThreshold??xDomain.min+xDomain.range/2,xDomain.min,xDomain.max);const resolvedYThreshold=clamp(yThreshold??yDomain.min+yDomain.range/2,yDomain.min,yDomain.max);const midX=xInPlot(resolvedXThreshold,xDomain,plot);const midY=yInPlot(resolvedYThreshold,yDomain,plot);const xTicks=showTicks||showGrid?chartTicks(xDomain.min,xDomain.max,5):[];const yTicks=showTicks||showGrid?chartTicks(yDomain.min,yDomain.max,5):[];const regionEntries=[{key:"top-left",region:regions.topLeft,x:plot.x,y:plot.y,width:midX-plot.x,height:midY-plot.y},{key:"top-right",region:regions.topRight,x:midX,y:plot.y,width:plot.right-midX,height:midY-plot.y},{key:"bottom-left",region:regions.bottomLeft,x:plot.x,y:midY,width:midX-plot.x,height:plot.bottom-midY},{key:"bottom-right",region:regions.bottomRight,x:midX,y:midY,width:plot.right-midX,height:plot.bottom-midY}];const pointGeometries=points.map((point,index)=>({point,index,x:xInPlot(clamp(point.x,xDomain.min,xDomain.max),xDomain,plot),y:yInPlot(clamp(point.y,yDomain.min,yDomain.max),yDomain,plot),color:chartColor(point.color,c,index)}));return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...regionEntries.map(({key,region,x,y,width:regionWidth,height:regionHeight},index)=>{const color=chartColor(region.color,c,index);const emphasized=region.emphasis===true;return React12.createElement("rect",{key:`quadrant-${key}`,x,y,width:regionWidth,height:regionHeight,fill:color,opacity:emphasized?.2:.1,stroke:emphasized?color:"transparent",strokeWidth:emphasized?2:0})}),showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`quadrant-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`quadrant-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:8}),React12.createElement("line",{x1:midX,y1:plot.y,x2:midX,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.4}),React12.createElement("line",{x1:plot.x,y1:midY,x2:plot.right,y2:midY,stroke:c.borderLight,strokeWidth:1.4}),...(showTicks?xTicks:[]).map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`quadrant-x-tick-${tick}`,x1:x,y1:plot.bottom,x2:x,y2:plot.bottom+5,stroke:c.textMuted,strokeWidth:1.2})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`quadrant-y-tick-${tick}`,x1:plot.x-5,y1:y,x2:plot.x,y2:y,stroke:c.textMuted,strokeWidth:1.2})}),...pointGeometries.map(({point,index,x,y,color})=>React12.createElement("circle",{key:`quadrant-point-${point.label??index}`,cx:x,cy:y,r:point.size??8,fill:color,stroke:c.bgCard,strokeWidth:3}))),...regionEntries.flatMap(({key,region,x,y,width:regionWidth},index)=>{const color=chartColor(region.color,c,index);return[chartLabel(`quadrant-label-${key}`,region.label,x+regionWidth/2,y+18,c,{width:Math.max(1,regionWidth-24),color,fontFamily:"Inter",fontWeight:900,fontSize:11}),...region.detail?[chartLabel(`quadrant-detail-${key}`,region.detail,x+regionWidth/2,y+34,c,{width:Math.max(1,regionWidth-24),color:c.textMuted,fontSize:11})]:[]]}),...(showTicks?xTicks:[]).map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`quadrant-x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:54})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`quadrant-y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-9,y,c,{align:"right",width:48})}),...pointGeometries.flatMap(({point,index,x,y,color})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`quadrant-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:110,bounds:placement.bounds,color,fontFamily:"Inter",fontWeight:850,fontSize:11})]}),xAxisLabel&&chartLabel("quadrant-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("quadrant-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}))})}function IntervalPlot({data,c,title,subtitle,width=640,height=220,min,max,format="decimal",axisLabel,footer}){const margin={top:22,right:28,bottom:axisLabel?44:30,left:96};const plot=createPlotArea(width,height,margin);const rowGap=data.length<=1?0:plot.innerHeight/data.length;const domain=chartDomain(data.flatMap(item=>[item.low,item.mid,item.high]),min,max);const ticks=chartTicks(domain.min,domain.max,5);const scaleX=value=>xInPlot(value,domain,plot);const rows=data.map((item,index)=>{const y=data.length<=1?plot.y+plot.innerHeight/2:plot.y+rowGap*index+rowGap/2;return{item,index,y,color:chartColor(item.color,c,index),lowX:scaleX(item.low),midX:scaleX(item.mid),highX:scaleX(item.high)}});return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...ticks.map(tick=>{const x=scaleX(tick);return React12.createElement("line",{key:`interval-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),React12.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...rows.flatMap(({item,index,y,color,lowX,midX,highX})=>[React12.createElement("line",{key:`${item.label}-range-${index}`,x1:lowX,y1:y,x2:highX,y2:y,stroke:color,strokeWidth:9,strokeLinecap:"round",opacity:.9}),React12.createElement("circle",{key:`${item.label}-mid-${index}`,cx:midX,cy:y,r:10,fill:c.bgCard,stroke:color,strokeWidth:4})])),...ticks.map((tick,index)=>{const x=scaleX(tick);return chartLabel(`interval-tick-label-${tick}`,formatChartValue(tick,format),x,height-margin.bottom+17,c,{align:xTickLabelAlign(index,ticks.length),width:48})}),axisLabel&&chartLabel("interval-axis-label",axisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),...rows.flatMap(({item,index,y,lowX,midX,highX})=>[chartLabel(`interval-row-label-${index}`,item.label,plot.x-12,y,c,{align:"right",width:84,color:c.textPrimary,fontFamily:"Inter",fontWeight:900}),chartLabel(`interval-low-${index}`,item.lowLabel??formatChartValue(item.low,format),lowX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}}),chartLabel(`interval-mid-${index}`,item.midLabel??formatChartValue(item.mid,format),midX,y-16,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height},color:c.textPrimary,fontWeight:900}),chartLabel(`interval-high-${index}`,item.highLabel??formatChartValue(item.high,format),highX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]))})}function Badge({label,c,color="primary"}){const solidColor=getReadableColor(color,c);return React12.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:`${solidColor}20`,color:solidColor,borderRadius:999,padding:"4px 12px",fontSize:11,fontWeight:600,fontFamily:"Inter",border:`1px solid ${solidColor}40`}},label)}function DotPoint({x,y,label,color,c,size=12,labelOffset}){const offX=labelOffset?.x??0;const offY=labelOffset?.y??-22;return[React12.createElement("div",{key:`dot-${label}`,style:{position:"absolute",left:x-size/2,top:y-size/2,width:size,height:size,borderRadius:"50%",backgroundColor:color,boxShadow:`0 0 14px ${color}50`,display:"flex"}}),React12.createElement("div",{key:`label-${label}`,style:{position:"absolute",left:x+offX-30,top:y+offY,fontSize:13,fontWeight:600,color:c.textPrimary,fontFamily:"JetBrains Mono",textAlign:"center",width:60}},label)]}function DashedLine({x1,y1,x2,y2,color,dotSpacing=8,dotSize=2}){const dx=x2-x1;const dy=y2-y1;const length=Math.sqrt(dx*dx+dy*dy);const numDots=Math.max(1,Math.floor(length/dotSpacing));const dots=[];for(let i=0;i<numDots;i++){if(i%2===1)continue;const t=i/numDots;dots.push(React12.createElement("div",{key:`dash-${i}`,style:{position:"absolute",left:x1+t*dx-dotSize/2,top:y1+t*dy-dotSize/2,width:dotSize,height:dotSize,borderRadius:"50%",backgroundColor:color}}))}return dots}function Legend({items,c,title}){return React12.createElement("div",{style:{display:"flex",flexDirection:"column",gap:10,backgroundColor:c.bgCard,borderRadius:8,border:`1px solid ${c.borderSubtle}`,padding:"14px 16px"}},title&&React12.createElement("div",{style:{fontSize:11,fontWeight:700,color:c.textSecondary,textTransform:"uppercase",letterSpacing:1,fontFamily:"Inter"}},title),...items.map((item,i)=>React12.createElement("div",{key:`legend-${i}`,style:{display:"flex",alignItems:"center",gap:8}},React12.createElement("div",{style:{width:16,height:item.style==="dashed"?0:2,backgroundColor:item.color,...item.style==="dashed"?{borderTop:`2px dashed ${item.color}`}:{}}}),React12.createElement("div",{style:{fontSize:11,color:c.textMuted,fontFamily:"Inter"}},item.label))))}import React13 from"react";var CANVAS_ITEM_COMPONENT=Symbol.for("vizmatic.canvas-item");function dimension(value,name){if(value!==void 0&&(!Number.isFinite(value)||value<=0||value>8192)){throw new Error(`${name} must be a finite number greater than 0 and at most 8192.`)}return value}function Board({children,c,width=960,height=540,background}){return React13.createElement("div",{style:{display:"flex",position:"relative",width:dimension(width,"Board width"),height:dimension(height,"Board height"),overflow:"hidden",backgroundColor:background??"transparent",color:c.textPrimary}},children)}function CanvasItem({children,x,y,width,height}){if(!Number.isFinite(x)||!Number.isFinite(y))throw new Error("CanvasItem x and y must be finite numbers.");const sizedChildren=React13.Children.map(children,child=>{if(!React13.isValidElement(child))return child;const sized=React13.cloneElement(child,{...width!==void 0?{width}:{},...height!==void 0?{height}:{}});return width!==void 0&&height!==void 0&&isCanvasChart(child.type)?React13.createElement(CanvasChartFit,{width,height,__vizmaticTextScope:child.props.__vizmaticTextScope},sized):sized});return React13.createElement("div",{style:{display:"flex",position:"absolute",left:x,top:y,width:dimension(width,"CanvasItem width"),height:dimension(height,"CanvasItem height"),alignItems:"stretch"}},sizedChildren)}Object.defineProperty(CanvasItem,CANVAS_ITEM_COMPONENT,{value:true});import{Resvg}from"@resvg/resvg-js";import{homedir}from"os";import{readFile,writeFile,mkdir}from"fs/promises";import{dirname,join}from"path";import{existsSync}from"fs";import{fileURLToPath}from"url";import{brotliDecompressSync}from"zlib";import React14 from"react";var DEFAULT_WATERMARK_TEXT="Vizmatic";var WATERMARK_COLOR_DARK="#a78bfa";var WATERMARK_COLOR_LIGHT="#7c3aed";function VizmaticIcon({size=14,color}){return React14.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:size,height:size,viewBox:"0 0 28 28",fill:"none"},React14.createElement("rect",{x:2.5,y:2.5,width:23,height:23,rx:6.5,stroke:color,strokeWidth:2,opacity:.54}),React14.createElement("rect",{x:7,y:7,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.35}),React14.createElement("rect",{x:15.5,y:7,width:5.5,height:5.5,rx:1.8,fill:color}),React14.createElement("rect",{x:7,y:15.5,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.82}),React14.createElement("rect",{x:15.5,y:15.5,width:5.5,height:5.5,rx:1.8,stroke:color,strokeWidth:1.5,opacity:.72}),React14.createElement("path",{d:"M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5",stroke:color,strokeWidth:1.6,strokeLinecap:"round",opacity:.88}))}function normalizeWatermark(watermark){if(watermark==null||watermark===false)return void 0;if(watermark===true)return{};if(typeof watermark==="string")return{text:watermark};if(React14.isValidElement(watermark)){if(watermark.type!==Watermark)return{element:watermark};const{children,...props}=watermark.props;return{...props,element:children??props.element}}return watermark}function Watermark(_props){return null}function positionStyle(position){switch(position){case"top-left":return{top:8,left:10};case"bottom-left":return{bottom:8,left:10};case"bottom-right":return{bottom:8,right:10};case"top-right":default:return{top:8,right:10}}}function imageNode(image){if(!image)return void 0;const imageOptions=typeof image==="string"?{src:image}:image;return React14.createElement("img",{src:imageOptions.src,alt:imageOptions.alt??"",width:imageOptions.width??14,height:imageOptions.height??14,style:{display:"block",width:imageOptions.width??14,height:imageOptions.height??14,objectFit:"contain"}})}function iconNode(icon,color){if(icon===false)return void 0;if(icon==null)return React14.createElement(VizmaticIcon,{size:13,color});if(typeof icon!=="string")return icon;return React14.createElement("div",{style:{minWidth:13,height:13,display:"flex",alignItems:"center",justifyContent:"center",color,fontSize:icon.length>2?8:10,fontWeight:800,fontFamily:"Inter",lineHeight:1}},icon)}function wrapWithWatermark(element,width,height,theme="dark",watermark=true){const isDark=theme==="dark";const options=normalizeWatermark(watermark);const color=options?.color??(isDark?WATERMARK_COLOR_DARK:WATERMARK_COLOR_LIGHT);const position=options?.position??"top-right";const opacity=options?.opacity??(isDark?.55:.4);const icon=options?imageNode(options.image)??iconNode(options.icon,color):void 0;const text=options?.text??DEFAULT_WATERMARK_TEXT;const content=options?.element??[icon,text!==false&&text&&React14.createElement("div",{key:"text",style:{fontSize:11,fontWeight:600,color,fontFamily:"Inter",letterSpacing:.3}},text)];return React14.createElement("div",{style:{width,height,display:"flex",position:"relative"}},element,options&&React14.createElement("div",{style:{position:"absolute",...positionStyle(position),display:"flex",alignItems:"center",gap:5,opacity}},content))}function wrapWithBrand(element,width,height,theme="dark",label=DEFAULT_WATERMARK_TEXT){return wrapWithWatermark(element,width,height,theme,label)}function detectBackgroundColor(pixels){const r=pixels[0];const g=pixels[1];const b=pixels[2];const a=pixels[3];if(a<10){return"transparent"}return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}function parseHexColor(hex){const h=hex.startsWith("#")?hex.slice(1):hex;return[parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]}function createBackgroundMatcher(bgColor,tolerance=6){if(bgColor==="transparent"){return(_r,_g,_b,a)=>a<10}const[bgR,bgG,bgB]=parseHexColor(bgColor);return(r,g,b,a)=>{if(a<10)return true;return Math.abs(r-bgR)<=tolerance&&Math.abs(g-bgG)<=tolerance&&Math.abs(b-bgB)<=tolerance}}function detectContentBounds(pixels,width,height,bgColor,padding=20){const isBackground=createBackgroundMatcher(bgColor);let minX=width;let minY=height;let maxX=0;let maxY=0;for(let y=0;y<height;y++){for(let x=0;x<width;x++){const idx=(y*width+x)*4;const r=pixels[idx];const g=pixels[idx+1];const b=pixels[idx+2];const a=pixels[idx+3];if(!isBackground(r,g,b,a)){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;if(y>maxY)maxY=y}}}if(minX>maxX||minY>maxY){return{x:0,y:0,width,height}}const cropX=Math.max(0,minX-padding);const cropY=Math.max(0,minY-padding);const cropRight=Math.min(width,maxX+1+padding);const cropBottom=Math.min(height,maxY+1+padding);return{x:cropX,y:cropY,width:cropRight-cropX,height:cropBottom-cropY}}function cropPixels(pixels,srcWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const srcOffset=((region.y+y)*srcWidth+region.x)*4;const dstOffset=y*region.width*4;out.set(pixels.subarray(srcOffset,srcOffset+region.width*4),dstOffset)}return out}function detectOverflow(pixels,width,height,bgColor,edgeTolerance=3,minDensity=.05,alphaThreshold=10){const isBackground=createBackgroundMatcher(bgColor);function isContentPixel(x,y){const idx=(y*width+x)*4;const a=pixels[idx+3];if(a<alphaThreshold)return false;return!isBackground(pixels[idx],pixels[idx+1],pixels[idx+2],a)}function checkEdge(scanFn,length){for(let offset=0;offset<edgeTolerance;offset++){let contentCount=0;for(let i=0;i<length;i++){const[x,y]=scanFn(i,offset);if(x>=0&&x<width&&y>=0&&y<height&&isContentPixel(x,y)){contentCount++}}if(contentCount/length>=minDensity){return true}}return false}const bottom=checkEdge((i,off)=>[i,height-1-off],width);const right=checkEdge((i,off)=>[width-1-off,i],height);const top=checkEdge((i,off)=>[i,off],width);const left=checkEdge((i,off)=>[off,i],height);const overflowEdges3=[];if(top)overflowEdges3.push("top");if(right)overflowEdges3.push("right");if(bottom)overflowEdges3.push("bottom");if(left)overflowEdges3.push("left");const overflows=overflowEdges3.length>0;const message=overflows?`Content overflows canvas at: ${overflowEdges3.join(", ")}. Increase the illustration dimensions.`:"";return{overflows,edges:{top,right,bottom,left},message}}import*as satoriModule from"satori";function resolveSatori(api){if(typeof api==="function")return api;if(api&&typeof api==="object"){const fallback=api.default;if(typeof fallback==="function")return fallback;if(fallback&&typeof fallback==="object"){const nestedFallback=fallback.default;if(typeof nestedFallback==="function")return nestedFallback}}throw new Error("satori export could not be resolved")}var renderSatori=resolveSatori(satoriModule);var satori=(element,options)=>renderWithCanvasChartFit(renderSatori,element,options);var FONT_CACHE_DIR=process.env.VIZMATIC_FONT_DIR??join(process.env.XDG_CACHE_HOME??join(homedir(),".cache"),"vizmatic","fonts");var NETWORK_FALLBACK_DISABLED=process.env.VIZMATIC_DISABLE_NETWORK==="1"||process.env.VIZMATIC_OFFLINE==="1";function moduleDirectory(){if(typeof __dirname!=="undefined")return __dirname;return dirname(fileURLToPath(import.meta.url))}function unique(values){return[...new Set(values.filter(value=>Boolean(value)))]}function resolveAssetDir(){const moduleDir=moduleDirectory();const candidates=unique([process.env.VIZMATIC_ASSET_DIR,join(moduleDir,"..","assets"),join(moduleDir,"assets"),join(process.cwd(),"assets")]);return candidates.find(candidate=>existsSync(candidate))}var ASSET_DIR=resolveAssetDir();var VENDORED_FONT_DIR=ASSET_DIR?join(ASSET_DIR,"fonts"):void 0;var VENDORED_EMOJI_DIR=ASSET_DIR?join(ASSET_DIR,"emoji"):void 0;var VENDORED_EMOJI_BUNDLE=ASSET_DIR?join(ASSET_DIR,"emoji.json.br"):void 0;var FONT_URLS={interRegular:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",interSemiBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",interBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",jetbrainsMono:"https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",notoSans:"https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",notoSansMath:"https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"};function fontReadPaths(filename){return unique([process.env.VIZMATIC_FONT_DIR?join(process.env.VIZMATIC_FONT_DIR,filename):void 0,VENDORED_FONT_DIR?join(VENDORED_FONT_DIR,filename):void 0,join(FONT_CACHE_DIR,filename)])}async function ensureFont(filename,url){for(const localPath of fontReadPaths(filename)){if(existsSync(localPath))return readFile(localPath)}if(NETWORK_FALLBACK_DISABLED){throw new Error(`Font ${filename} was not found in local Vizmatic assets and network fallback is disabled`)}console.log(` \u2193 Downloading font: ${filename}`);const response=await fetch(url);if(!response.ok){throw new Error(`Failed to download font ${filename}: ${response.statusText}`)}const buffer=Buffer.from(await response.arrayBuffer());await mkdir(FONT_CACHE_DIR,{recursive:true});await writeFile(join(FONT_CACHE_DIR,filename),buffer);return buffer}function toArrayBuffer(buffer){return buffer.buffer.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)}async function loadFonts(){await mkdir(FONT_CACHE_DIR,{recursive:true});const fonts=[];try{const[regular,semiBold,bold]=await Promise.all([ensureFont("Inter-Regular.ttf",FONT_URLS.interRegular),ensureFont("Inter-SemiBold.ttf",FONT_URLS.interSemiBold),ensureFont("Inter-Bold.ttf",FONT_URLS.interBold)]);fonts.push({name:"Inter",data:toArrayBuffer(regular),weight:400,style:"normal"},{name:"Inter",data:toArrayBuffer(semiBold),weight:600,style:"normal"},{name:"Inter",data:toArrayBuffer(bold),weight:700,style:"normal"})}catch(e){console.warn("Warning: Could not load Inter font:",e)}try{const jetbrains=await ensureFont("JetBrainsMono-Regular.ttf",FONT_URLS.jetbrainsMono);fonts.push({name:"JetBrains Mono",data:toArrayBuffer(jetbrains),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load JetBrains Mono font:",e)}try{const notoSans=await ensureFont("NotoSans-Regular.ttf",FONT_URLS.notoSans);fonts.push({name:"Noto Sans",data:toArrayBuffer(notoSans),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans font:",e)}try{const notoMath=await ensureFont("NotoSansMath-Regular.ttf",FONT_URLS.notoSansMath);fonts.push({name:"Noto Sans Math",data:toArrayBuffer(notoMath),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans Math font:",e)}return fonts}var EMOJI_CACHE_DIR=join(FONT_CACHE_DIR,"emoji");function emojiCodepoints(segment){return[...segment].map(c=>c.codePointAt(0).toString(16))}function emojiFilenames(segment){const codepoints=emojiCodepoints(segment);const full=codepoints.join("-");const withoutVariationSelectors=codepoints.filter(cp=>cp!=="fe0f").join("-");return unique([full,withoutVariationSelectors]).map(codepoints2=>`${codepoints2}.svg`)}async function svgFileToDataUri(path){const svgData=await readFile(path,"utf8");return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}var bundledEmoji;async function loadBundledEmoji(filename){if(!VENDORED_EMOJI_BUNDLE||!existsSync(VENDORED_EMOJI_BUNDLE))return void 0;bundledEmoji??=JSON.parse(brotliDecompressSync(await readFile(VENDORED_EMOJI_BUNDLE)).toString("utf8"));const svg=bundledEmoji[filename];return svg?`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`:void 0}async function loadEmoji(segment){const filenames=emojiFilenames(segment);for(const filename2 of filenames){const paths=unique([VENDORED_EMOJI_DIR?join(VENDORED_EMOJI_DIR,filename2):void 0,join(EMOJI_CACHE_DIR,filename2)]);for(const localPath of paths){if(existsSync(localPath))return svgFileToDataUri(localPath)}const bundled=await loadBundledEmoji(filename2);if(bundled)return bundled}if(NETWORK_FALLBACK_DISABLED){console.warn(`Warning: Emoji asset not found locally: ${filenames.join(" or ")}`);return""}const filename=filenames[0];if(!filename)return"";const url=`https://cdn.jsdelivr.net/npm/@twemoji/svg@15.0.0/${filename}`;try{console.log(` \u2193 Downloading emoji: ${filename}`);const response=await fetch(url);if(!response.ok){console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);return""}const svgData=await response.text();await mkdir(EMOJI_CACHE_DIR,{recursive:true});await writeFile(join(EMOJI_CACHE_DIR,filename),svgData);return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}catch(e){console.warn(`Warning: Could not fetch emoji ${filename}:`,e);return""}}async function loadAdditionalAsset(code,segment){if(code==="emoji"){return loadEmoji(segment)}return[]}var cachedFonts=null;async function getFonts(){if(!cachedFonts){cachedFonts=await loadFonts()}return cachedFonts}function sanitizeSvg(svg){return svg.replace(/width="0"/g,'width="1"').replace(/height="0"/g,'height="1"')}var AUTOCROP_PADDING=24;var CROP_THRESHOLD_PERCENT=10;function replaceSvgAttribute(attrs,name,value){const pattern=new RegExp(`\\s${name}="[^"]*"`);if(pattern.test(attrs))return attrs.replace(pattern,` ${name}="${value}"`);return`${attrs} ${name}="${value}"`}function cropSvgViewport(svg,region){const x=Math.max(0,Math.floor(region.x));const y=Math.max(0,Math.floor(region.y));const width=Math.max(1,Math.ceil(region.width));const height=Math.max(1,Math.ceil(region.height));return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>{let nextAttrs=attrs;nextAttrs=replaceSvgAttribute(nextAttrs,"width",String(width));nextAttrs=replaceSvgAttribute(nextAttrs,"height",String(height));nextAttrs=replaceSvgAttribute(nextAttrs,"viewBox",`${x} ${y} ${width} ${height}`);return`<svg${nextAttrs}>`})}function cropLayoutNodes(nodes,region){return nodes.flatMap(node=>{const left=Math.max(node.left,region.x);const top=Math.max(node.top,region.y);const right=Math.min(node.left+node.width,region.x+region.width);const bottom=Math.min(node.top+node.height,region.y+region.height);if(right<=left||bottom<=top)return[];return[{...node,left:left-region.x,top:top-region.y,width:right-left,height:bottom-top}]})}function cropSavesEnough(source,target){if(source<=0||target>=source)return false;return(source-target)/source*100>=CROP_THRESHOLD_PERCENT}var CanvasOverflowError=class extends Error{width;height;overflow;animation;constructor(width,height,overflow,animation){const position=animation?[animation.sceneIndex!=null?`scene ${animation.sceneIndex+1}`:void 0,animation.frameIndex!=null?`frame ${animation.frameIndex+1}${animation.frameCount?`/${animation.frameCount}`:""}`:void 0,animation.time!=null?`${Math.round(animation.time)}ms`:void 0,animation.label?JSON.stringify(animation.label):void 0].filter(Boolean).join(", "):"";super(`Canvas overflow detected (${width}\xD7${height})${position?` at ${position}`:""}: ${overflow.message}`);this.name="CanvasOverflowError";this.width=width;this.height=height;this.overflow=overflow;this.animation=animation}};function resolveWatermark(options){return options.watermark??options.brand}function shouldCropHeight(crop){return crop!==false}function shouldCropViewport(crop){return crop!==false&&crop!=="height"}async function renderToPng(element,options,createFn,theme){await renderToPngWithOutput(element,options,createFn,theme)}async function renderToPngWithOutput(element,options,createFn,theme){return withRenderContext({background:options.background??"transparent"},()=>renderToPngInContext(element,options,createFn,theme))}async function renderToPngInContext(element,options,createFn,theme){const fonts=await getFonts();const renderTheme=options.theme??theme??"dark";let svg=await satori(element,{width:options.width,height:options.height,fonts,loadAdditionalAsset});svg=sanitizeSvg(svg);const detectResvg=new Resvg(svg,{fitTo:{mode:"width",value:options.width},background:"rgba(0, 0, 0, 0)"});const detectResult=detectResvg.render();const detectPixels=detectResult.pixels;const pixelData=new Uint8Array(detectPixels.buffer);const detectedBg=detectBackgroundColor(pixelData);const bounds=detectContentBounds(pixelData,options.width,detectResult.height,detectedBg,AUTOCROP_PADDING);const overflow=detectOverflow(pixelData,options.width,detectResult.height,detectedBg);if(overflow.overflows){throw new CanvasOverflowError(options.width,options.height,overflow)}let finalWidth=options.width;let finalHeight=options.height;let finalElement=element;const croppedHeight=bounds.y+bounds.height;const heightSaved=options.height-croppedHeight;const heightSavedPercent=heightSaved/options.height*100;if(shouldCropHeight(options.crop)&&heightSavedPercent>=CROP_THRESHOLD_PERCENT){finalHeight=croppedHeight;if(createFn&&theme){finalElement=createFn(theme)}}const watermark=resolveWatermark(options);const renderFinalSvg=async(targetElement,targetWidth,targetHeight)=>{const layoutNodes=[];const outputElement=watermark?wrapWithWatermark(targetElement,targetWidth,targetHeight,renderTheme,watermark):targetElement;const renderedSvg=await satori(outputElement,{width:targetWidth,height:targetHeight,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected?node=>layoutNodes.push(node):void 0});return{svg:sanitizeSvg(renderedSvg),layoutNodes}};let finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);let finalSvg=finalRender.svg;if(finalHeight<options.height){const cropCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const cropPixels2=new Uint8Array(cropCheck.pixels.buffer);const cropBg=detectBackgroundColor(cropPixels2);const cropOverflow=detectOverflow(cropPixels2,finalWidth,cropCheck.height,cropBg);if(cropOverflow.overflows){finalHeight=options.height;finalElement=element;finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);finalSvg=finalRender.svg}}if(shouldCropViewport(options.crop)){const viewportCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const viewportPixels=new Uint8Array(viewportCheck.pixels.buffer);const viewportBg=detectBackgroundColor(viewportPixels);const viewportBounds=detectContentBounds(viewportPixels,finalWidth,viewportCheck.height,viewportBg,AUTOCROP_PADDING);if(cropSavesEnough(finalWidth,viewportBounds.width)||cropSavesEnough(viewportCheck.height,viewportBounds.height)){finalSvg=cropSvgViewport(finalSvg,viewportBounds);finalRender.layoutNodes=cropLayoutNodes(finalRender.layoutNodes,viewportBounds);finalWidth=viewportBounds.width;finalHeight=viewportBounds.height}}if(options.onNodeDetected){finalRender.layoutNodes.forEach(options.onNodeDetected)}const resvg=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();const outputPixels=new Uint8Array(pngData.pixels.buffer);const outputBackground=detectBackgroundColor(outputPixels);const physicalContentBounds=detectContentBounds(outputPixels,pngData.width,pngData.height,outputBackground,0);const outputScale=pngData.width/finalWidth;const contentBounds={x:physicalContentBounds.x/outputScale,y:physicalContentBounds.y/outputScale,width:physicalContentBounds.width/outputScale,height:physicalContentBounds.height/outputScale};const pngBuffer=pngData.asPng();await mkdir(dirname(options.outputPath),{recursive:true});await writeFile(options.outputPath,pngBuffer);return{width:finalWidth,height:finalHeight,pixelWidth:pngData.width,pixelHeight:pngData.height,contentBounds}}async function renderToBuffer(element,width,height,options={}){return withRenderContext({background:options.background??"transparent"},()=>renderToBufferInContext(element,width,height,options))}async function renderToBufferInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;let svg=await satori(outputElement,{width,height,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected});svg=sanitizeSvg(svg);const resvg=new Resvg(svg,{fitTo:{mode:"width",value:width*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();return Buffer.from(pngData.asPng())}async function renderToSvg(element,width,height,options={}){return withRenderContext({background:options.background??"transparent"},()=>renderToSvgInContext(element,width,height,options))}async function renderToSvgInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;const prepared=prepareAccessibleSvg(outputElement);const layoutNodes=[];const svg=await satori(prepared.element,{width,height,fonts,loadAdditionalAsset,onNodeDetected:node=>{layoutNodes.push(node);options.onNodeDetected?.(node)}});return addSvgAccessibility(sanitizeSvg(svg),prepared.graphs,layoutNodes)}import{Resvg as Resvg2}from"@resvg/resvg-js";import{mkdir as mkdir2,writeFile as writeFile2}from"fs/promises";import{dirname as dirname2}from"path";import*as gifenc from"gifenc";import parseCssColor2 from"parse-css-color";var MIN_FPS=1;var MAX_FPS=50;var DEFAULT_FPS=20;function assertDuration(duration,context){if(!Number.isFinite(duration)||duration<=0){throw new Error(`${context} duration must be a positive finite number`)}}function assertFps(fps){if(!Number.isFinite(fps)||!Number.isInteger(fps)||fps<MIN_FPS||fps>MAX_FPS){throw new Error(`Animation fps must be an integer from ${MIN_FPS} to ${MAX_FPS}`)}}function clampProgress(progress){return Math.max(0,Math.min(1,progress))}function easingValue(easing="linear",progress){const amount=clampProgress(progress);let result;if(typeof easing==="function"){result=easing(amount)}else if(easing==="ease-in"){result=amount*amount*amount}else if(easing==="ease-out"){result=1-(1-amount)**3}else if(easing==="ease-in-out"){result=amount<.5?4*amount*amount*amount:1-(-2*amount+2)**3/2}else if(easing==="linear"){result=amount}else{throw new Error(`Unknown animation easing: ${String(easing)}`)}if(!Number.isFinite(result))throw new Error("Animation easing must return a finite number");return clampProgress(result)}function hold(duration,label){return{type:"hold",duration,label}}function keyframe(value,label){return{type:"keyframe",value,label}}function tween(to,options){return{type:"tween",to,...options}}function parallel(tracks,label){return{type:"parallel",tracks,label}}function propertyStepDuration(step){return step.type==="keyframe"?0:step.duration}function parallelDuration(step){return Math.max(0,...Object.values(step.tracks).map(track=>track?.reduce((total,item)=>total+propertyStepDuration(item),0)??0))}function timelineStepDuration(step){if(step.type==="keyframe")return 0;if(step.type==="parallel")return parallelDuration(step);return step.duration}function validatePropertySteps(steps,context){for(const step of steps){if(step.type!=="keyframe")assertDuration(step.duration,context);if(step.type==="tween")easingValue(step.easing,.5)}}function validateTimeline(timeline){if(timeline.length===0)throw new Error("Animation timeline requires at least one step");let duration=0;timeline.forEach((step,index)=>{if(step.type==="parallel"){const tracks=Object.entries(step.tracks);if(tracks.length===0)throw new Error(`Animation parallel step ${index} requires at least one track`);tracks.forEach(([name,track])=>{if(!track)return;validatePropertySteps(track,`Animation parallel track ${JSON.stringify(name)}`)});assertDuration(parallelDuration(step),`Animation parallel step ${index}`)}else if(step.type!=="keyframe"){assertDuration(step.duration,`Animation step ${index}`);if(step.type==="tween")easingValue(step.easing,.5)}duration+=timelineStepDuration(step)});if(duration<=0)throw new Error("Animation timeline requires at least one timed step");return duration}function defineAnimation(definition){const fps=definition.fps??DEFAULT_FPS;assertFps(fps);const duration=validateTimeline(definition.timeline);validateAnimationValues(definition.initial,definition.timeline);return{...definition,kind:"vizmatic.animation",duration,fps}}function interpolateValue(from,to,progress,interpolate){if(interpolate)return interpolate(from,to,progress);if(typeof from==="number"&&typeof to==="number"&&Number.isFinite(from)&&Number.isFinite(to)){return from+(to-from)*progress}throw new Error("Animation tweens require finite numeric values or a custom interpolate function")}function validatePropertyInterpolation(initial,steps){let value=initial;for(const step of steps){if(step.type==="keyframe")value=step.value;if(step.type==="tween"){interpolateValue(value,step.to,.5,step.interpolate);value=step.to}}return value}function validateAnimationValues(initial,timeline){let state={...initial};for(const step of timeline){if(step.type==="keyframe"){state={...state,...step.value}}else if(step.type==="tween"){interpolateState(state,step,.5);state={...state,...step.to}}else if(step.type==="parallel"){const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)result[key]=validatePropertyInterpolation(state[key],track)}state=result}}}function interpolateState(from,step,progress){if(step.interpolate){const fromPatch=Object.fromEntries(Object.keys(step.to).map(key=>[key,from[key]]));return{...from,...step.interpolate(fromPatch,step.to,progress)}}const patch={};for(const key of Object.keys(step.to)){const target=step.to[key];if(target===void 0)continue;patch[key]=interpolateValue(from[key],target,progress)}return{...from,...patch}}function finalState(state,step){if(step.type==="keyframe")return{...state,...step.value};if(step.type==="tween")return{...state,...step.to};if(step.type!=="parallel")return state;const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(!track)continue;let value=state[key];for(const item of track){if(item.type==="keyframe"||item.type==="tween")value=item.type==="keyframe"?item.value:item.to}result[key]=value}return result}function evaluatePropertyTrack(initial,steps,time){let value=initial;let cursor=0;for(const step of steps){if(step.type==="keyframe"){value=step.value;continue}const end=cursor+step.duration;if(time<end){if(step.type==="hold")return value;const progress=easingValue(step.easing,(time-cursor)/step.duration);return interpolateValue(value,step.to,progress,step.interpolate)}if(step.type==="tween")value=step.to;cursor=end}return value}function evaluateAnimation(animation,requestedTime){const time=Math.max(0,Math.min(animation.duration,requestedTime));let state={...animation.initial};let cursor=0;for(let index=0;index<animation.timeline.length;index+=1){const step=animation.timeline[index];if(step.type==="keyframe"){state={...state,...step.value};continue}const duration=timelineStepDuration(step);const end=cursor+duration;if(time<end){const rawProgress=(time-cursor)/duration;if(step.type==="hold"){return{state,step:index,stepProgress:rawProgress,label:step.label}}if(step.type==="tween"){const progress=easingValue(step.easing,rawProgress);return{state:interpolateState(state,step,progress),step:index,stepProgress:rawProgress,label:step.label}}const parallelState={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)parallelState[key]=evaluatePropertyTrack(state[key],track,time-cursor)}return{state:parallelState,step:index,stepProgress:rawProgress,label:step.label}}state=finalState(state,step);cursor=end}const lastIndex=animation.timeline.length-1;return{state,step:lastIndex,stepProgress:1,label:animation.timeline[lastIndex]?.label}}function sampleAnimation(animation,time){if(!Number.isFinite(time))throw new Error("Animation sample time must be finite");return evaluateAnimation(animation,time).state}function animationCadence(duration,fps){const interval=1e3/fps;const times=[0];for(let time=interval;time<duration;time+=interval)times.push(time);if(times.at(-1)!==duration)times.push(duration);const boundaries=times.map(time=>Math.round(time/10)*10);const delays=times.map((_,index)=>index===times.length-1?20:Math.max(20,boundaries[index+1]-boundaries[index]));const targetDuration=Math.max(Math.round(duration/10)*10,delays.length*20);let excess=delays.reduce((total,delay)=>total+delay,0)-targetDuration;for(let index=delays.length-2;index>=0&&excess>0;index-=1){const reduction=Math.min(excess,delays[index]-20);delays[index]-=reduction;excess-=reduction}return{times,delays}}function analyzeAnimationCadence(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);return{fps,duration:animation.duration,frameCount:cadence.times.length,encodedDuration:cadence.delays.reduce((total,delay)=>total+delay,0),targetInterval:1e3/fps,minDelay:Math.min(...cadence.delays),maxDelay:Math.max(...cadence.delays)}}function sampleAnimationFrames(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);const count=cadence.times.length;return cadence.times.map((time,index)=>{const evaluated=evaluateAnimation(animation,time);return{state:evaluated.state,frame:{index,count,time,duration:animation.duration,delay:cadence.delays[index],progress:time/animation.duration,step:evaluated.step,stepProgress:evaluated.stepProgress,label:evaluated.label,fps}}})}function resolveGifenc(api){if(typeof api.GIFEncoder==="function"&&typeof api.applyPalette==="function"&&typeof api.quantize==="function"){return api}const fallback=api.default;if(fallback&&typeof fallback.GIFEncoder==="function"&&typeof fallback.applyPalette==="function"&&typeof fallback.quantize==="function"){return fallback}throw new Error("gifenc exports could not be resolved")}var{GIFEncoder,applyPalette,quantize}=resolveGifenc(gifenc);var MAX_PALETTE_SAMPLE_PIXELS=1e6;var MAX_TIMELINE_PALETTE_FRAMES=24;async function renderToPixels(element,width,height,scale,theme,background,overflowContext){const fonts=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg2(svg,{fitTo:{mode:"width",value:width*scale},background:rasterBackground(background,theme)});const rendered=resvg.render();const output={pixels:rendered.pixels,width:rendered.width,height:rendered.height};if(overflowContext){const overflow=detectLayoutOverflow(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow(nodes,width,height){const epsilon=.5;const edges={top:nodes.some(node=>node.top<-epsilon),right:nodes.some(node=>node.left+node.width>width+epsilon),bottom:nodes.some(node=>node.top+node.height>height+epsilon),left:nodes.some(node=>node.left<-epsilon)};const names=Object.entries(edges).filter(([,overflows])=>overflows).map(([edge])=>edge);return{overflows:names.length>0,edges,message:names.length?`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`:""}}function blendPixels(base,overlay,opacity){const result=new Uint8Array(base.length);const inverse=1-opacity;for(let index=0;index<base.length;index+=4){const baseAlpha=base[index+3]/255*inverse;const overlayAlpha=overlay[index+3]/255*opacity;const outputAlpha=baseAlpha+overlayAlpha;if(outputAlpha===0)continue;result[index]=Math.round((base[index]*baseAlpha+overlay[index]*overlayAlpha)/outputAlpha);result[index+1]=Math.round((base[index+1]*baseAlpha+overlay[index+1]*overlayAlpha)/outputAlpha);result[index+2]=Math.round((base[index+2]*baseAlpha+overlay[index+2]*overlayAlpha)/outputAlpha);result[index+3]=Math.round(outputAlpha*255)}return result}function hslToRgb(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=l-chroma/2;return[Math.round((channels[0]+offset)*255),Math.round((channels[1]+offset)*255),Math.round((channels[2]+offset)*255)]}function colorForBackground(background,theme){const value=background==="theme"?getThemeColors(theme).bg:background;const parsed=parseCssColor2(value);if(!parsed)throw new Error(`Invalid animation background color: ${value}`);const[r,g,b]=parsed.type==="hsl"?hslToRgb(parsed.values[0],parsed.values[1],parsed.values[2]):[parsed.values[0],parsed.values[1],parsed.values[2]];return{r,g,b,a:Math.round(parsed.alpha*255)}}function rasterBackground(background,theme){const{r,g,b,a}=colorForBackground(background,theme);return`rgba(${r}, ${g}, ${b}, ${a/255})`}function backgroundPixels(width,height,theme,background){const buffer=new Uint8Array(width*height*4);const color=colorForBackground(background,theme);for(let index=0;index<buffer.length;index+=4){buffer[index]=color.r;buffer[index+1]=color.g;buffer[index+2]=color.b;buffer[index+3]=color.a}return buffer}function samplePixels(pixels,limit){const pixelCount=pixels.length/4;if(pixelCount<=limit)return pixels.slice();const sample=new Uint8Array(limit*4);for(let index=0;index<limit;index+=1){const sourcePixel=Math.floor((index+.5)*pixelCount/limit);sample.set(pixels.subarray(sourcePixel*4,sourcePixel*4+4),index*4)}return sample}function sharedPalette(frames){if(frames.length===0)throw new Error("No GIF frames to quantize");const pixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/frames.length));const samples=frames.map(frame=>samplePixels(frame.pixels,pixelsPerFrame));const length=samples.reduce((total,sample)=>total+sample.length,0);const combined=new Uint8Array(length);let offset=0;for(const sample of samples){combined.set(sample,offset);offset+=sample.length}return quantize(combined,256,{format:"rgba4444",oneBitAlpha:true})}function changedBounds(previous,current,width,height){let minX=width;let minY=height;let maxX=-1;let maxY=-1;for(let index=0;index<current.length;index+=4){if(previous[index]===current[index]&&previous[index+1]===current[index+1]&&previous[index+2]===current[index+2]&&previous[index+3]===current[index+3])continue;const pixel=index/4;const x=pixel%width;const y=Math.floor(pixel/width);minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y)}return maxX<minX?void 0:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropFramePixels(pixels,canvasWidth,region){const output=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y+=1){const source=((region.y+y)*canvasWidth+region.x)*4;output.set(pixels.subarray(source,source+region.width*4),y*region.width*4)}return output}function deltaPixelFrame(frame,previous,enabled){if(!enabled||!previous)return frame;const bounds=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds||bounds.width===frame.width&&bounds.height===frame.height)return frame;return{...frame,x:bounds.x,y:bounds.y,delta:true,width:bounds.width,height:bounds.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds)}}function encodeGif(frames,loop,deltaFrames){if(frames.length===0)throw new Error("No GIF frames to encode");const firstFrame=frames[0];const gif=GIFEncoder();const palette=sharedPalette(frames);let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;let pending;for(const frame of frames){if(frame.width!==firstFrame.width||frame.height!==firstFrame.height){throw new Error("All GIF frames must have matching dimensions")}if(pending&&pixelsEqual(pending.pixels,frame.pixels)){pending.delay+=frame.delay;continue}if(pending){const encoded=deltaPixelFrame(pending,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending={...frame}}if(pending){const encoded=deltaPixelFrame(pending,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1}gif.finish();return{bytes:gif.bytes(),encodedFrameCount,deltaFrameCount}}var DEFAULT_TRANSITION_FPS=20;var MIN_TRANSITION_FRAMES=3;function sceneTransitionFps(fps){const resolved=fps??DEFAULT_TRANSITION_FPS;if(!Number.isInteger(resolved)||resolved<1||resolved>50){throw new Error("Animation fps must be an integer from 1 to 50")}return resolved}function transitionFrameDelays(duration,count){const totalCentiseconds=Math.max(count*2,Math.round(duration/10));let previous=0;return Array.from({length:count},(_,index)=>{const cumulative=Math.round((index+1)/count*totalCentiseconds);const delay=(cumulative-previous)*10;previous=cumulative;return delay})}async function scenesToFrames(scenes,options){if(scenes.length===0)throw new Error("Animated GIF requires at least one scene");for(const[index,scene]of scenes.entries()){if(!Number.isFinite(scene.duration)||scene.duration<=0){throw new Error(`Animated scene ${index+1} duration must be a positive finite number`)}if(scene.transition!=null&&!["none","fade","appear"].includes(scene.transition)){throw new Error(`Animated scene ${index+1} has unknown transition "${scene.transition}"`)}if(scene.transitionDuration!=null&&(!Number.isFinite(scene.transitionDuration)||scene.transitionDuration<=0)){throw new Error(`Animated scene ${index+1} transitionDuration must be a positive finite number`)}}const fps=sceneTransitionFps(options.fps);const renderedScenes=await Promise.all(scenes.map((scene,sceneIndex)=>{const watermark=options.watermark??options.brand;const element=watermark?wrapWithWatermark(scene.element,options.width,options.height,options.theme,watermark):scene.element;return renderToPixels(element,options.width,options.height,options.scale,options.theme,options.background,{sceneIndex,label:scene.label})}));const frames=[];const scaledWidth=renderedScenes[0].width;const scaledHeight=renderedScenes[0].height;for(let index=0;index<scenes.length;index+=1){const scene=scenes[index];const current=renderedScenes[index];const transition=scene.transition??"none";const transitionDuration=scene.transitionDuration??400;if(transition!=="none"){const previous=index>0?renderedScenes[index-1]:{pixels:backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),width:scaledWidth,height:scaledHeight};const transitionFrames=Math.max(MIN_TRANSITION_FRAMES,Math.round(transitionDuration/1e3*fps));const frameDelays=transitionFrameDelays(transitionDuration,transitionFrames);for(let frameIndex=0;frameIndex<transitionFrames;frameIndex+=1){const amount=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount);frames.push({pixels,delay:frameDelays[frameIndex],width:scaledWidth,height:scaledHeight})}}frames.push({pixels:current.pixels,delay:scene.duration,width:scaledWidth,height:scaledHeight})}return frames}async function renderAnimatedGif(scenes,options){if(!Array.isArray(scenes)){await renderAnimationGifWithOutput(scenes,options)}else{await renderAnimatedGifWithOutput(scenes,options)}}async function renderAnimatedGifWithOutput(scenes,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};await mkdir2(dirname2(options.outputPath),{recursive:true});const frames=await scenesToFrames(scenes,normalized);const encoded=encodeGif(frames,normalized.loop,normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255);await writeFile2(options.outputPath,encoded.bytes);return{width:frames[0].width,height:frames[0].height,frameCount:frames.length,encodedFrameCount:encoded.encodedFrameCount,deltaFrameCount:encoded.deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.delay,0),bytes:encoded.bytes.length}}function pixelsEqual(left,right){if(left.length!==right.length)return false;for(let index=0;index<left.length;index+=1){if(left[index]!==right[index])return false}return true}function writeGifFrame(gif,frame,loop,palette,first,delta){const index=applyPalette(frame.pixels,palette,"rgba4444");const transparentIndex=palette.findIndex(color=>color[3]===0);let remainingDelay=frame.delay;let includePalette=first;do{const delay=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay),repeat:loop,transparent:transparentIndex>=0,transparentIndex,dispose:delta&&frame.delta?1:void 0});if((frame.x??0)!==0||(frame.y??0)!==0){const bytes=gif.bytesView();const descriptor=frameStart+8;if(bytes[descriptor]!==44)throw new Error("GIF image descriptor was not written");const x=frame.x??0;const y=frame.y??0;bytes[descriptor+1]=x&255;bytes[descriptor+2]=x>>8&255;bytes[descriptor+3]=y&255;bytes[descriptor+4]=y>>8&255}includePalette=false;remainingDelay-=delay}while(remainingDelay>0)}function representativeFrameIndexes(frameCount){const count=Math.min(frameCount,MAX_TIMELINE_PALETTE_FRAMES);if(count===frameCount)return Array.from({length:count},(_,index)=>index);return Array.from({length:count},(_,index)=>Math.round(index*(frameCount-1)/(count-1)))}async function renderAnimationGif(animation,options){await renderAnimationGifWithOutput(animation,options)}async function renderAnimationGifWithOutput(animation,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};const frames=sampleAnimationFrames(animation,{fps:options.fps});const paletteFrames=[];const paletteIndexes=representativeFrameIndexes(frames.length);const palettePixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/paletteIndexes.length));for(const index of paletteIndexes){const sampled=frames[index];const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background);paletteFrames.push({...rendered,pixels:samplePixels(rendered.pixels,palettePixelsPerFrame),delay:sampled.frame.delay})}const palette=sharedPalette(paletteFrames);const gif=GIFEncoder();let pending;let dimensions;let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;const useDeltaFrames=normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255;for(const sampled of frames){const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background,{frameIndex:sampled.frame.index,frameCount:sampled.frame.count,time:sampled.frame.time,label:sampled.frame.label});dimensions??={width:rendered.width,height:rendered.height};if(rendered.width!==dimensions.width||rendered.height!==dimensions.height){throw new Error("All GIF frames must have matching dimensions")}if(pending&&pixelsEqual(pending.pixels,rendered.pixels)){pending.delay+=sampled.frame.delay;continue}if(pending){const encoded2=deltaPixelFrame(pending,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending={...rendered,delay:sampled.frame.delay}}if(!pending||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir2(dirname2(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile2(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}function graphImportResult(source,graph,diagnostics){if(graph.nodes.length===0&&diagnostics.every(({severity})=>severity!=="error")){diagnostics.push({code:"import.empty",severity:"error",message:"The source contains no graph nodes to import.",line:1,column:1,excerpt:""})}const ok=diagnostics.every(({severity})=>severity!=="error");return ok?{source,ok,graph,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line,code,severity,message,column=1){diagnostics.push({code,severity,message,line,column,excerpt:(sourceLines[line-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line,index){while(index<line.length&&/\s/.test(line[index]??""))index++;return index}function readDelimited(line,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line.length;index++){const character=line[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line.startsWith(close,index)){return{value:line.slice(start,index),next:index+close.length}}}return void 0}function decodeLabel(raw){const value=raw.trim();if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}function labelHasUnsupportedMarkup(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label)}function readEndpoint(line,from){let index=skipWhitespace(line,from);const id=line.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line,index);if(afterId>=line.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line.slice(afterId);const delimiters=[{open:"[(",close:")]",lossy:true},{open:"([",close:"])",lossy:true},{open:"((",close:"))",lossy:true},{open:"{{",close:"}}",lossy:true},{open:"[",close:"]",lossy:false},{open:"(",close:")",lossy:true},{open:"{",close:"}",lossy:true}];const delimiter=delimiters.find(({open})=>rest.startsWith(open));if(!delimiter)return{id,label:id,shape:"rectangle",next:index};const content=readDelimited(line,afterId+delimiter.open.length,delimiter.close);if(!content)return void 0;const label=decodeLabel(content.value);if(label===void 0)return void 0;return{id,label,shape:delimiter.lossy?"lossy":"rectangle",next:content.next}}function addNode(state,endpoint2,groupId,line,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint2.id)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid id "${endpoint2.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint2.label)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint2.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint2.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid node "${endpoint2.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid node "${endpoint2.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint2.label}else{state.nodeIndexes.set(endpoint2.id,state.nodes.length);state.nodes.push({id:endpoint2.id,label:endpoint2.label,...groupId?{group:groupId}:{}})}if(endpoint2.shape==="lossy"&&!state.warnedShapes.has(endpoint2.id)){state.warnedShapes.add(endpoint2.id);addImportDiagnostic(diagnostics,sourceLines,line,"import.lossy_semantics","warning",`Mermaid node "${endpoint2.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line,first.next);const hasConnector=CONNECTORS.some(connector=>line.startsWith(connector,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line,cursor);if(cursor>=line.length)return;const connector=CONNECTORS.find(candidate=>line.startsWith(candidate,cursor));if(!connector){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",cursor+1);return}cursor+=connector.length;cursor=skipWhitespace(line,cursor);let edgeLabel;if(line[cursor]==="|"){const end=line.indexOf("|",cursor+1);if(end<0){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid edge label is missing its closing |.",cursor+1);return}edgeLabel=line.slice(cursor+1,end).trim();cursor=skipWhitespace(line,end+1);if(labelHasUnsupportedMarkup(edgeLabel)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",cursor+1);return}}const next=readEndpoint(line,cursor);if(!next){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid connection has no supported target node.",cursor+1);return}if(!addNode(state,next,groupId,lineNumber,sourceLines,diagnostics,false))return;const edge={from:previous.id,to:next.id,...edgeLabel!==void 0?{label:edgeLabel}:{},...connector==="---"?{arrow:"none"}:connector==="-.->"?{arrow:"forward",style:"dotted"}:{arrow:"forward"}};state.edges.push(edge);state.edgeReferences.push({id:previous.id,line:lineNumber},{id:next.id,line:lineNumber});previous=next;cursor=next.next}}function importMermaidGraph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const state={nodes:[],nodeIndexes:new Map,groups:[],groupIds:new Set,edges:[],edgeReferences:[],warnedShapes:new Set};let direction="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line=rawLine.trim();if(!line)continue;if(line.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line.startsWith("%%"))continue;if(!sawHeader){const header=line.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);if(!header){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error",'Expected a Mermaid flowchart or graph header such as "flowchart LR".');sawHeader=true;continue}sawHeader=true;const sourceDirection=header[1]?.toUpperCase();direction=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);if(subgraph){if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Nested Mermaid subgraphs are not imported.");continue}const id=subgraph[1];if(!id)continue;if(state.groupIds.has(id)||state.nodeIndexes.has(id)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph id "${id}" conflicts with an existing group or node.`);continue}const rawLabel=subgraph[2];const label=rawLabel===void 0?id:decodeLabel(rawLabel);if(label===void 0||labelHasUnsupportedMarkup(label)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);continue}currentGroup=id;state.groupIds.add(id);state.groups.push({id,label});continue}if(/^subgraph\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");continue}if(/^end\s*$/i.test(line)){if(!currentGroup)addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid end has no matching subgraph.");else currentGroup=void 0;continue}if(/^direction\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,currentGroup?"import.unsupported_semantics":"import.parse_error","error",currentGroup?"Per-subgraph Mermaid direction cannot be represented by GraphDiagram.":"Set Mermaid graph direction in the flowchart or graph header.");continue}if(/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line,currentGroup,lineNumber,sourceLines,state,diagnostics)}if(!sawHeader){addImportDiagnostic(diagnostics,sourceLines,1,"import.parse_error","error","Missing Mermaid flowchart or graph header.")}if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,sourceLines.length,"import.parse_error","error",`Mermaid subgraph "${currentGroup}" has no matching end.`)}for(const reference of state.edgeReferences){if(state.groupIds.has(reference.id)){addImportDiagnostic(diagnostics,sourceLines,reference.line,"import.unsupported_semantics","error",`Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`)}}const graph={nodes:state.nodes,edges:state.edges,groups:state.groups,direction};return graphImportResult("mermaid",graph,diagnostics)}function decodeD2Label(raw){const value=raw.trim();if(value.startsWith('"')){if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}if(value.startsWith("'")){if(!value.endsWith("'"))return void 0;return value.slice(1,-1).replace(/\\(['\\])/g,"$1")}return value}function hasMarkdownFormatting(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label)}function hasUnquotedHash(line){let quote;let escaped=false;for(const character of line){if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'")quote=character;else if(character==="#")return true}return false}function addNode2(nodes,id,label,line,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`);return false}const existing=nodes.get(id);if(existing){if(explicitLabel){existing.node.label=label}}else{nodes.set(id,{node:{id,label}})}return true}function reportUnsupported(diagnostics,sourceLines,line,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line,code,"error",message,column)}function importD2Graph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const nodesById=new Map;const edges=[];const shapes=new Map;let direction="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line=rawLine.trim();if(!line)continue;if(containerDepth>0){const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,containerDepth+opens-closes);continue}if(line.startsWith("#"))continue;if(hasUnquotedHash(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line.includes("{")||line.includes("}")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.","import.unsupported_semantics");const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,opens-closes);continue}const directionMatch=line.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape=decodeD2Label(shapeMatch[2]??"");if(!id||shape===void 0||shape===""){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 shape declaration needs a simple identifier and a shape value.","import.parse_error");continue}if(!nodesById.has(id))addNode2(nodesById,id,id,lineNumber,sourceLines,diagnostics,false);shapes.set(id,{value:shape,line:lineNumber});continue}const edgeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);if(edgeMatch){const from=edgeMatch[1];const connector=edgeMatch[2];const to=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector||!to)continue;let label;if(rawLabel!==void 0){label=decodeD2Label(rawLabel);if(label===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection label has invalid quotes.","import.parse_error");continue}if(hasMarkdownFormatting(label)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.","import.unsupported_semantics");continue}}addNode2(nodesById,from,from,lineNumber,sourceLines,diagnostics,false);addNode2(nodesById,to,to,lineNumber,sourceLines,diagnostics,false);edges.push({from,to,...label!==void 0?{label}:{},arrow:connector==="<->"?"both":connector==="<-"?"backward":connector==="--"?"none":"forward"});continue}const nodeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);if(nodeMatch){const id=nodeMatch[1];const rawLabel=nodeMatch[2];if(!id)continue;let label=id;let explicitLabel=false;if(rawLabel!==void 0){const decoded=decodeD2Label(rawLabel);if(decoded===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,`D2 label for "${id}" has invalid quotes.`,"import.parse_error");continue}label=decoded;explicitLabel=true}addNode2(nodesById,id,label,lineNumber,sourceLines,diagnostics,explicitLabel);continue}if(line.includes(".style")||line.includes(".width")||line.includes(".height")||line.includes(".near")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 styling, sizing, and positioning fields are not imported.","import.unsupported_semantics")}else if(/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.")}else{reportUnsupported(diagnostics,sourceLines,lineNumber,"Could not parse this D2 statement in the supported subset.","import.parse_error")}}if(containerDepth>0){reportUnsupported(diagnostics,sourceLines,sourceLines.length,"D2 object-property block has no matching closing brace.","import.parse_error")}for(const[id,{value,line}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line,"import.lossy_semantics","warning",`D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`)}return graphImportResult("d2",{nodes:[...nodesById.values()].map(({node})=>node),edges,groups:[],direction},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";import{tmpdir}from"os";import{join as join2}from"path";import parseCssColor3 from"parse-css-color";import{Children,isValidElement as isValidElement3}from"react";var CHECK_DIAGNOSTIC_CODES=["accessibility.low_contrast","api.unsupported_prop","asset.warning","frame.load_error","frame.unknown_preset","layout.auto_size","layout.connector_congestion","layout.connector_unroutable","layout.overflow","layout.text_overlap","layout.whitespace_imbalance","readability.small_text","render.error","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=11;function hslToRgb2(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=l-chroma/2;return channels.map(channel=>Math.round((channel+offset)*255))}function colorFromCss(value){if(typeof value!=="string")return void 0;const parsed=parseCssColor3(value);if(!parsed||parsed.values.length<3)return void 0;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];return{r,g,b,alpha:parsed.alpha}}function compositeOver(foreground,background){if(foreground.alpha>=1||!background)return foreground;const alpha=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha,alpha}}function isUnresolvedColor(value){if(typeof value!=="string"||value.trim()===""||colorFromCss(value))return false;return!["inherit","initial","revert","unset"].includes(value.trim().toLowerCase())}function channelLuminance(value){const normalized=value/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4}function relativeLuminance(color){return .2126*channelLuminance(color.r)+.7152*channelLuminance(color.g)+.0722*channelLuminance(color.b)}function contrastRatio(foreground,background){const lighter=Math.max(relativeLuminance(foreground),relativeLuminance(background));const darker=Math.min(relativeLuminance(foreground),relativeLuminance(background));return(lighter+.05)/(darker+.05)}function numericFontWeight(value){if(typeof value==="number")return value;if(value==="bold")return 700;if(typeof value==="string"&&/^\d+$/.test(value))return Number(value);return void 0}function fontSizePixels(value,inherited){if(typeof value==="number")return value;if(typeof value!=="string")return inherited;const match=value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);if(!match?.[1])return inherited;const amount=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount*4/3;if(unit==="rem")return amount*16;if(unit==="em")return amount*(inherited??16);if(unit==="%")return amount/100*(inherited??16);return amount}function requiredContrast(context){const large=(context.fontSize??16)>=24||(context.fontSize??16)>=18.66&&(context.fontWeight??400)>=700;return large?3:4.5}function styleRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return value}function hasDirectText(children){return Children.toArray(children).some(child=>typeof child==="string"||typeof child==="number")}function elementId(props){const value=props.id??props["data-vizmatic-id"];return typeof value==="string"&&value.trim()!==""?value.trim():void 0}function resolveFunctionComponent(node,trustedComponents){if(!isValidElement3(node)||typeof node.type!=="function"||trustedComponents.has(node.type))return void 0;const component=node.type;if(component.__vizmaticPrimitive)return void 0;if(component.prototype?.isReactComponent)return void 0;try{return component(node.props)}catch{return void 0}}function analyzeContrast(element,theme,trustedComponents=new Set,rootBackground2){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path){if(visited++>=MAX_CONTRAST_NODES||!isValidElement3(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path);return}const props=node.props;const style=typeof node.type==="string"?styleRecord(props.style):{};const backgroundImage=typeof style.backgroundImage==="string"?style.backgroundImage.trim().toLowerCase():"";const backgroundShorthand=typeof style.background==="string"?style.background.trim():"";const isBackgroundWrapper=typeof node.type==="function"&&(trustedComponents.has(node.type)||Boolean(node.type.__vizmaticPrimitive));const wrapperBackground=isBackgroundWrapper?props.background:void 0;const hasUnresolvedBackground=backgroundImage!==""&&backgroundImage!=="none"||isUnresolvedColor(style.backgroundColor)||backgroundShorthand!==""&&backgroundShorthand.toLowerCase()!=="none"&&!colorFromCss(backgroundShorthand)||isUnresolvedColor(wrapperBackground);const ownBackground=colorFromCss(style.backgroundColor)??colorFromCss(style.background)??colorFromCss(wrapperBackground);const baseBackground=path==="root"&&isBackgroundWrapper&&colorFromCss(wrapperBackground)?void 0:inherited.background;const background=hasUnresolvedBackground?void 0:ownBackground?compositeOver(ownBackground,baseBackground):baseBackground;const color=typeof style.color==="string"&&style.color.trim().toLowerCase()==="currentcolor"?inherited.color:isUnresolvedColor(style.color)?void 0:colorFromCss(style.color)??inherited.color;const fontSize=fontSizePixels(style.fontSize,inherited.fontSize);const fontWeight=numericFontWeight(style.fontWeight)??inherited.fontWeight;const context={background,color,fontSize,fontWeight};if(typeof node.type==="string"&&hasDirectText(props.children)&&color&&background!==void 0&&background.alpha>=1){const renderedColor=compositeOver(color,background);const ratio=contrastRatio(renderedColor,background);const required=requiredContrast(context);if(ratio<required){const rounded=Math.round(ratio*100)/100;const key=`${rounded}:${required}:${path}`;if(!seen.has(key)){seen.add(key);diagnostics.push({code:"accessibility.low_contrast",severity:"warning",theme,message:`Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,suggestion:"Use a stronger text or background color token.",elementId:elementId(props),location:{path}})}}}Children.forEach(props.children,(child,index)=>visit(child,context,`${path}.${index}`))}visit(element,{background:colorFromCss(rootBackground2)},"root");return diagnostics}function containsLayoutNode(parent,child){const epsilon=.5;return child.left>=parent.left-epsilon&&child.top>=parent.top-epsilon&&child.left+child.width<=parent.left+parent.width+epsilon&&child.top+child.height<=parent.top+parent.height+epsilon}function textUnits(text){return Array.from(text.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0)}function renderedTextNodes(nodes){const textNodes=[];const ancestors=[];for(const node of nodes){while(ancestors.length>0&&!containsLayoutNode(ancestors[ancestors.length-1].node,node)){ancestors.pop()}const inherited=ancestors[ancestors.length-1];const style=styleRecord(node.props.style);const fontSize=fontSizePixels(style.fontSize,inherited?.fontSize)??16;const textAlign=typeof style.textAlign==="string"?style.textAlign:inherited?.textAlign??"left";const text=node.textContent?.trim();if(text&&node.width>0&&node.height>0){const estimatedLines=Math.max(1,Math.round(node.height/Math.max(fontSize*1.5,1)));const paintHeight=Math.min(node.height,fontSize*.9+(estimatedLines-1)*fontSize*1.25);const unwrappedWidth=textUnits(text)*fontSize*.56;const paintWidth=Math.min(node.width,unwrappedWidth);const horizontalInset=textAlign==="center"?(node.width-paintWidth)/2:textAlign==="right"||textAlign==="end"?node.width-paintWidth:0;textNodes.push({text,elementId:elementId(node.props),left:node.left,top:node.top,width:node.width,height:node.height,paintLeft:node.left+horizontalInset,paintTop:node.top+(node.height-paintHeight)/2,paintWidth,paintHeight,fontSize})}else if(node.width>0&&node.height>0){ancestors.push({node,fontSize,textAlign})}}return textNodes}function textExcerpt(text){const normalized=text.replace(/\s+/g," ").trim();return normalized.length>40?`${normalized.slice(0,37)}...`:normalized}function meaningfulOverlap(a,b){const width=Math.min(a.paintLeft+a.paintWidth,b.paintLeft+b.paintWidth)-Math.max(a.paintLeft,b.paintLeft);const height=Math.min(a.paintTop+a.paintHeight,b.paintTop+b.paintHeight)-Math.max(a.paintTop,b.paintTop);if(width<2||height<2)return false;if(a.text===b.text&&a.left===b.left&&a.top===b.top&&a.width===b.width&&a.height===b.height)return false;const overlapArea=width*height;const smallerArea=Math.min(a.paintWidth*a.paintHeight,b.paintWidth*b.paintHeight);return overlapArea/smallerArea>=.08}function overlapCandidates(nodes){const cellSize=96;const buckets=new Map;const pairs=[];for(let index=0;index<nodes.length&&pairs.length<MAX_DIAGNOSTICS_PER_RULE;index+=1){const node=nodes[index];const minX=Math.floor(node.paintLeft/cellSize);const maxX=Math.floor((node.paintLeft+node.paintWidth)/cellSize);const minY=Math.floor(node.paintTop/cellSize);const maxY=Math.floor((node.paintTop+node.paintHeight)/cellSize);const candidates=new Set;for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const bucket=buckets.get(`${x}:${y}`);bucket?.forEach(candidate=>candidates.add(candidate))}}for(const candidate of candidates){if(meaningfulOverlap(nodes[candidate],node))pairs.push([nodes[candidate],node]);if(pairs.length>=MAX_DIAGNOSTICS_PER_RULE)break}for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const key=`${x}:${y}`;const bucket=buckets.get(key)??[];bucket.push(index);buckets.set(key,bucket)}}}return pairs}function analyzeRenderedLayout(nodes,theme){const diagnostics=[];const textNodes=renderedTextNodes(nodes);const seenSmallText=new Set;let smallTextCount=0;for(const node of textNodes){if(node.fontSize>=MIN_TEXT_SIZE)continue;const excerpt=textExcerpt(node.text);const key=`${excerpt}:${node.fontSize}`;if(seenSmallText.has(key))continue;seenSmallText.add(key);diagnostics.push({code:"readability.small_text",severity:"warning",theme,message:`Text "${excerpt}" renders at ${node.fontSize}px.`,suggestion:`Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,elementId:node.elementId,location:{x:node.left,y:node.top,width:node.width,height:node.height}});smallTextCount+=1;if(smallTextCount>=MAX_DIAGNOSTICS_PER_RULE)break}for(const[left,right]of overlapCandidates(textNodes)){diagnostics.push({code:"layout.text_overlap",severity:"warning",theme,message:`Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,suggestion:"Increase spacing or canvas size, shorten labels, or move one label.",elementId:left.elementId,relatedElementIds:right.elementId?[right.elementId]:void 0,location:{x:left.left,y:left.top,width:left.width,height:left.height}})}const maxDataNumber=attribute2=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute2];return typeof value==="number"?value:Number(value)||0}));for(const source of nodes.filter(node=>Number(node.props["data-vizmatic-unrouted-connectors"])>0)){const messages=JSON.parse(String(source.props["data-vizmatic-routing-failures"]));for(const message of messages.slice(0,MAX_DIAGNOSTICS_PER_RULE))diagnostics.push({code:"layout.connector_unroutable",severity:"error",theme,message,suggestion:"Increase canvas size or spacing, reduce routingClearance, or choose a different endpoint side or port.",elementId:elementId(source.props),location:{x:source.left,y:source.top,width:source.width,height:source.height}})}const connectorCrossings2=maxDataNumber("data-vizmatic-connector-crossings");if(connectorCrossings2>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings2} connector crossing${connectorCrossings2===1?"":"s"} detected.`,suggestion:"Use automatic layout, change graph direction, or simplify the edge set.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const labelCollisions=maxDataNumber("data-vizmatic-connector-label-collisions");if(labelCollisions>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-collisions"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${labelCollisions} connector label collision${labelCollisions===1?"":"s"} detected.`,suggestion:"Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crowdedEndpoints=maxDataNumber("data-vizmatic-crowded-connector-endpoints");if(crowdedEndpoints>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-crowded-connector-endpoints"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${crowdedEndpoints} node${crowdedEndpoints===1?"":"s"} connect more than four edges.`,suggestion:"Group related branches, add an intermediate hub, or change graph direction.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const parallelGroups=maxDataNumber("data-vizmatic-parallel-connector-groups");if(parallelGroups>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-parallel-connector-groups"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${parallelGroups} connector route${parallelGroups===1?"":"s"} contain parallel edges.`,suggestion:"Merge duplicate relationships, label one combined edge, or separate the routes.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}let whitespaceCount=0;for(const container of nodes.filter(node=>node.props["data-vizmatic-layout-container"]==="panel")){const contentNodes=nodes.filter(node=>node.props["data-vizmatic-layout-content"]==="panel"&&node.width>0&&node.height>0&&node.left>=container.left&&node.top>=container.top&&node.left+node.width<=container.left+container.width&&node.top+node.height<=container.top+container.height);if(contentNodes.length===0)continue;const contentTop=Math.min(...contentNodes.map(node=>node.top));const contentBottom=Math.max(...contentNodes.map(node=>node.top+node.height));const topGutter=contentTop-container.top;const bottomGutter=container.top+container.height-contentBottom;const difference=Math.abs(bottomGutter-topGutter);if(difference<=48||difference/container.height<=.18)continue;const largerSide=bottomGutter>topGutter?"below":"above";const smallerSide=largerSide==="below"?"above":"below";diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,suggestion:"Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",elementId:elementId(container.props),location:{x:container.left,y:container.top,width:container.width,height:container.height}});whitespaceCount+=1;if(whitespaceCount>=MAX_DIAGNOSTICS_PER_RULE)break}return diagnostics}function analyzeWhitespaceBalance(bounds,width,height,theme){const gutters={left:bounds.x,right:width-bounds.x-bounds.width,top:bounds.y,bottom:height-bounds.y-bounds.height};const diagnostics=[];const horizontalDifference=Math.abs(gutters.left-gutters.right);const verticalDifference=Math.abs(gutters.top-gutters.bottom);if(horizontalDifference>48&&horizontalDifference/width>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds.x,y:bounds.y,width:bounds.width,height:bounds.height}})}if(verticalDifference>48&&verticalDifference/height>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds.x,y:bounds.y,width:bounds.width,height:bounds.height}})}return diagnostics}function diagnosticFromMessage(message,severity,theme){if(/unknown preset/i.test(message)){return{code:"frame.unknown_preset",severity,theme,message,suggestion:'Use "default" or "engineering".'}}if(/unsupported prop|unknown prop|does not recognize (?:the )?.* prop/i.test(message)){return{code:"api.unsupported_prop",severity,theme,message,suggestion:"Remove the prop or use one documented for this Vizmatic primitive."}}if(/invalid value for css property|unsupported (?:css|style)|not supported.*css/i.test(message)){return{code:"style.unsupported",severity,theme,message,suggestion:"Use CSS supported by Satori or a Vizmatic primitive."}}if(/font|emoji|image asset|failed to (?:download|fetch)|asset .*not found/i.test(message)){return{code:"asset.warning",severity,theme,message,suggestion:"Use a reachable asset or install it locally before rendering offline."}}return{code:severity==="error"?"render.error":"render.warning",severity,theme,message}}var DEFAULT_WIDTH=960;var DEFAULT_HEIGHT=540;var MAX_WIDTH=1920;var MAX_HEIGHT=1440;var GROWTH=1.25;var MAX_AUTO_SIZE_ATTEMPTS=6;var TRUSTED_COMPONENTS=new Set(Object.values(primitives_exports));var consoleCaptureContext=new AsyncLocalStorage2;var activeConsoleCaptures=0;var originalConsoleMethods;function formatConsoleArgs(args){return args.map(value=>{if(value instanceof Error)return value.message;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}).join(" ")}function installConsoleCapture(){if(activeConsoleCaptures===0){originalConsoleMethods={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};const original=originalConsoleMethods;const intercept=(method,severity)=>(...args)=>{const messages=consoleCaptureContext.getStore();if(messages){if(severity)messages.push({severity,message:formatConsoleArgs(args)});return}Reflect.apply(original[method],console,args)};console.debug=intercept("debug");console.error=intercept("error","error");console.info=intercept("info");console.log=intercept("log");console.warn=intercept("warn","warning")}activeConsoleCaptures+=1;let restored=false;return()=>{if(restored)return;restored=true;activeConsoleCaptures-=1;if(activeConsoleCaptures===0&&originalConsoleMethods){console.debug=originalConsoleMethods.debug;console.error=originalConsoleMethods.error;console.info=originalConsoleMethods.info;console.log=originalConsoleMethods.log;console.warn=originalConsoleMethods.warn;originalConsoleMethods=void 0}}}async function captureConsole(run){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run);return{value,messages}}catch(error){return{error,messages}}finally{uninstall()}}function normalizeAutoSize(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value)return{width:value.width??defaults.width,height:value.height??defaults.height};return defaults}function overflowEdges(error){if(!(error instanceof CanvasOverflowError))return void 0;return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}function nextDimension(value,maximum){return Math.min(maximum,Math.ceil(value*GROWTH/10)*10)}function nextAutoSize(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?nextDimension(width,MAX_WIDTH):width;const nextHeight=growHeight?nextDimension(height,MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrame(create,theme,options){let width=options.width;let height=options.height;for(let attempt=0;attempt<MAX_AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const output=await renderToPngWithOutput(create(theme),{width,height,outputPath:options.outputPath,crop:true,scale:1,background:options.background,onNodeDetected:node=>layoutNodes.push(node)},create,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges(error);const next=edges?nextAutoSize(width,height,options.autoSize,edges):void 0;if(!next||attempt===MAX_AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function counts(themes){const diagnostics=themes.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{errors:diagnostics.filter(({severity})=>severity==="error").length,warnings:diagnostics.filter(({severity})=>severity==="warning").length,info:diagnostics.filter(({severity})=>severity==="info").length}}function fails(diagnostics,policy){if(policy==="never")return false;const threshold={error:0,warning:1,info:2}[policy];const levels={error:0,warning:1,info:2};return diagnostics.some(({severity})=>levels[severity]<=threshold)}function messageDiagnostics(messages,theme){return messages.map(({message,severity})=>diagnosticFromMessage(message,severity,theme))}function rootBackground(background,theme){if(background==="theme")return getThemeColors(theme).bg;if(background==="transparent"||background===void 0)return void 0;return background}async function checkFrame(input,options={}){const themes=options.themes??["dark","light"];if(themes.length===0)throw new TypeError("checkFrame requires at least one theme");const width=input.width??DEFAULT_WIDTH;const height=input.height??DEFAULT_HEIGHT;if(!Number.isFinite(width)||width<=0||!Number.isFinite(height)||height<=0){throw new TypeError("checkFrame width and height must be positive finite numbers")}const autoSize=normalizeAutoSize(input.autoSize,{width:input.width==null,height:input.height==null});const create=input.create??(()=>input.scene);const failOn=options.failOn??"error";const tempDir=await mkdtemp(join2(tmpdir(),"vizmatic-check-"));const reports=[];try{for(const[themeIndex,theme]of themes.entries()){const inputDimensions={width,height};const diagnostics2=[];const prepared=await captureConsole(async()=>{const element=create(theme);const background=rootBackground(options.background,theme);return analyzeContrast(element,theme,TRUSTED_COMPONENTS,background)});diagnostics2.push(...messageDiagnostics(prepared.messages,theme));if(!prepared.value){diagnostics2.push(diagnosticFromMessage(prepared.error instanceof Error?prepared.error.message:String(prepared.error),"error",theme));reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2});continue}diagnostics2.push(...prepared.value);const rendered=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize,background:options.background,outputPath:join2(tempDir,`${themeIndex}.png`)}));diagnostics2.push(...messageDiagnostics(rendered.messages,theme));if(rendered.value){diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes,theme));if(rendered.value.contentBounds){diagnostics2.push(...analyzeWhitespaceBalance(rendered.value.contentBounds,rendered.value.logicalOutputWidth,rendered.value.logicalOutputHeight,theme))}if(rendered.value.width!==width||rendered.value.height!==height){diagnostics2.push({code:"layout.auto_size",severity:"info",theme,message:`Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,suggestedDimensions:{width:rendered.value.width,height:rendered.value.height}})}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions,resolved:{width:rendered.value.width,height:rendered.value.height},output:{width:rendered.value.outputWidth,height:rendered.value.outputHeight}},diagnostics:diagnostics2});continue}const edges=overflowEdges(rendered.error);if(edges){const suggestion=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize:{width:true,height:true},background:options.background,outputPath:join2(tempDir,`${themeIndex}-suggestion.png`)}));const suggestedDimensions=suggestion.value?{width:suggestion.value.width,height:suggestion.value.height}:void 0;diagnostics2.push({code:"layout.overflow",severity:"error",theme,edges,message:rendered.error instanceof Error?rendered.error.message:String(rendered.error),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.",suggestedDimensions})}else{diagnostics2.push(diagnosticFromMessage(rendered.error instanceof Error?rendered.error.message:String(rendered.error),"error",theme))}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2})}}finally{await rm(tempDir,{recursive:true,force:true})}const summary=counts(reports);const diagnostics=reports.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{schemaVersion:1,source:input.source,ok:!fails(diagnostics,failOn),rendered:reports.every(({dimensions})=>dimensions.resolved!==void 0),autoSize,themes:reports,summary}}function readJsxTag(source,start){if(source.startsWith("<>",start))return{closing:false,end:start+2,selfClosing:false};if(source.startsWith("</>",start))return{closing:true,end:start+3,selfClosing:false};const head=source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);if(!head)return void 0;const closing=Boolean(head[1]);let quote;let braces=0;let escaped=false;for(let index=start+head[0].length;index<source.length;index+=1){const character=source[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{"){braces+=1;continue}if(character==="}"){braces=Math.max(0,braces-1);continue}if(character!==">"||braces>0)continue;const beforeClose=source.slice(start,index).trimEnd();return{closing,end:index+1,selfClosing:!closing&&beforeClose.endsWith("/")}}return void 0}function skipJsxExpression(source,start){let depth=0;let quote;let escaped=false;let blockComment=false;let lineComment=false;for(let index=start;index<source.length;index+=1){const character=source[index];const next=source[index+1];if(lineComment){if(character==="\n")lineComment=false;continue}if(blockComment){if(character==="*"&&next==="/"){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==="/"&&next==="/"){lineComment=true;index+=1;continue}if(character==="/"&&next==="*"){blockComment=true;index+=1;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{")depth+=1;else if(character==="}"&&--depth===0)return index+1}return void 0}function findJsxEnd(source,start){let depth=0;for(let index=start;index<source.length;index+=1){if(source[index]==="{"){const expressionEnd=skipJsxExpression(source,index);if(expressionEnd==null)return void 0;index=expressionEnd-1;continue}if(source[index]!=="<")continue;const tag=readJsxTag(source,index);if(!tag)continue;if(tag.closing)depth-=1;else if(!tag.selfClosing)depth+=1;index=tag.end-1;if(depth===0)return tag.end}return void 0}function hasOnlyTrailingSyntax(source){let index=0;while(index<source.length){const rest=source.slice(index);const whitespace=rest.match(/^[\s;)]*/)?.[0].length??0;index+=whitespace;if(source.startsWith("//",index)){const newline=source.indexOf("\n",index+2);index=newline<0?source.length:newline+1;continue}if(source.startsWith("/*",index)){const end=source.indexOf("*/",index+2);if(end<0)return false;index=end+2;continue}return index>=source.length}return true}function extractRootJsx(source){const body=source.replace(/^(?:\s*\()+\s*/,"");const end=findJsxEnd(body,0);return(end==null?body:body.slice(0,end)).trim()}function findBareRootJsxStart(source){const candidates=source.matchAll(/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);for(const candidate of candidates){if(candidate.index==null)continue;const lineStart=candidate.index+(candidate[1]?.length??0);const expressionStart=lineStart+(candidate[2]?.length??0);const jsxStart=candidate.index+candidate[0].lastIndexOf(candidate[3]??"<");const jsxEnd=findJsxEnd(source,jsxStart);if(jsxEnd!=null&&hasOnlyTrailingSyntax(source.slice(jsxEnd)))return expressionStart}return-1}function validatePlaygroundAnimation(animation){if(!Number.isFinite(animation.duration)||animation.duration<=0||animation.duration>10){throw new Error("animationDuration must be greater than 0 and at most 10 seconds.")}if(!Number.isInteger(animation.fps)||animation.fps<1||animation.fps>30){throw new Error("animationFps must be an integer from 1 to 30.")}return{duration:animation.duration,fps:animation.fps}}function readAnimationLine(line){const match=line.match(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?(animationDuration|animationFps)\s*[:=]\s*(.*?)\s*;?\s*(?:\/\/.*)?$/);if(!match)return void 0;const expression=match[2].replace(/;\s*$/,"").trim();if(!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(expression)){throw new Error(`${match[1]} must be a numeric literal.`)}return{name:match[1],value:Number(expression)}}var RENDER_EXTENSIONS=new Set([".js",".jsx",".mjs",".ts",".tsx"]);var IMPORT_RESOLUTION_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"];var DEFAULT_FRAME_WIDTH=960;var DEFAULT_FRAME_HEIGHT=540;var AUTO_SIZE_MAX_WIDTH=1920;var AUTO_SIZE_MAX_HEIGHT=1440;var AUTO_SIZE_GROWTH=1.25;var AUTO_SIZE_ATTEMPTS=6;var SVG_AUTOCROP_PADDING=24;var SVG_CROP_THRESHOLD_PERCENT=10;var cliRequire=createRequire(import.meta.url);var frameDependencyAliasesInstalled=false;var BARE_FRAME_EXTRA_EXPORTS=new Set(["canvas","colors","defineIllustration","defineAnimation","getColor","getGradient","getReadableTextColor","getReadableToneColor","getStyles","getThemeColors","getToneFill","getToneColor","getToneGradient","gradients","heatColor","hold","keyframe","sampleAnimationFrames","styles","toneGradients","tween","typography","wrapWithWatermark"]);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();var framesNeedingGlobalReact=new WeakSet;function usageText(){return`Usage:
2
+ var __defProp=Object.defineProperty;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true})};import{existsSync as existsSync2}from"fs";import{mkdir as mkdir3,mkdtemp as mkdtemp2,readFile as readFile2,readdir,rm as rm2,writeFile as writeFile3}from"fs/promises";import{randomUUID}from"crypto";import{createRequire,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename,dirname as dirname3,extname,isAbsolute,join as join3,relative,resolve,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React15,{isValidElement as isValidElement4}from"react";import{Resvg as Resvg3}from"@resvg/resvg-js";var index_exports={};__export(index_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AxisPlot:()=>AxisPlot,Badge:()=>Badge,BadgePill:()=>BadgePill,BarChart:()=>BarChart,Board:()=>Board,Box:()=>Box,CANVAS_ITEM_COMPONENT:()=>CANVAS_ITEM_COMPONENT,CHECK_DIAGNOSTIC_CODES:()=>CHECK_DIAGNOSTIC_CODES,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,CanvasOverflowError:()=>CanvasOverflowError,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,EquationCard:()=>EquationCard,Flow:()=>Flow,FlowArrow:()=>FlowArrow,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MiniBarChart:()=>MiniBarChart,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,Row:()=>Row,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TextLabel:()=>TextLabel,Tile:()=>Tile,TileGrid:()=>TileGrid,TiledMatrix:()=>TiledMatrix,Timeline:()=>Timeline,TitleBar:()=>TitleBar,ToneStrip:()=>ToneStrip,TransformerTopology:()=>TransformerTopology,TreeDiagram:()=>TreeDiagram,ValuePill:()=>ValuePill,VectorArrow:()=>VectorArrow,VectorSegment:()=>VectorSegment,Watermark:()=>Watermark,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,canvas:()=>canvas,checkFrame:()=>checkFrame,colors:()=>colors,createPlotArea:()=>createPlotArea,cropPixels:()=>cropPixels,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectOverflow:()=>detectOverflow,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,keyframe:()=>keyframe,loadAdditionalAsset:()=>loadAdditionalAsset,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,sampleAnimation:()=>sampleAnimation,sampleAnimationFrames:()=>sampleAnimationFrames,styles:()=>styles,toneGradients:()=>toneGradients,tween:()=>tween,typography:()=>typography,withColorAlpha:()=>withColorAlpha,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import parseCssColor from"parse-css-color";var darkColors={bg:"#151620",bgCard:"#1a1b26",bgCardAlt:"#1e2030",bgHover:"#24253a",bgSubtle:"#151620",primary:"#7c3aed",primaryLight:"#a78bfa",primaryDark:"#6d28d9",secondary:"#2563eb",secondaryLight:"#60a5fa",secondaryDark:"#1d4ed8",positive:"#059669",positiveLight:"#34d399",positiveDark:"#047857",warning:"#d97706",warningLight:"#fbbf24",warningDark:"#b45309",critical:"#dc2626",criticalLight:"#f87171",criticalDark:"#b91c1c",info:"#06b6d4",infoLight:"#22d3ee",infoDark:"#0891b2",accent:"#f472b6",accentLight:"#f9a8d4",neutral:"#334155",neutralLight:"#475569",neutralDark:"#1e293b",textPrimary:"#f1f5f9",textSecondary:"#94a3b8",textMuted:"#8493a8",textOnColor:"#ffffff",border:"#334155",borderSubtle:"#1e293b",borderLight:"#475569",shadow:"rgba(0, 0, 0, 0.24)"};var lightColors={bg:"#f5f7fa",bgCard:"#f8fafc",bgCardAlt:"#f1f5f9",bgHover:"#e2e8f0",bgSubtle:"#f5f7fa",primary:"#7c3aed",primaryLight:"#8b5cf6",primaryDark:"#6d28d9",secondary:"#2563eb",secondaryLight:"#3b82f6",secondaryDark:"#1d4ed8",positive:"#059669",positiveLight:"#10b981",positiveDark:"#047857",warning:"#d97706",warningLight:"#f59e0b",warningDark:"#b45309",critical:"#dc2626",criticalLight:"#ef4444",criticalDark:"#b91c1c",info:"#0891b2",infoLight:"#06b6d4",infoDark:"#0e7490",accent:"#ec4899",accentLight:"#f472b6",neutral:"#cbd5e1",neutralLight:"#94a3b8",neutralDark:"#e2e8f0",textPrimary:"#0f172a",textSecondary:"#475569",textMuted:"#5b677a",textOnColor:"#ffffff",border:"#e2e8f0",borderSubtle:"#e2e8f0",borderLight:"#cbd5e1",shadow:"rgba(15, 23, 42, 0.12)"};var defaultStyleTokens={preset:"default",fontSans:"Inter",fontMono:"JetBrains Mono"};var engineeringColors={...lightColors,bg:"#f4f4f5",bgCard:"#ffffff",bgCardAlt:"#ececee",bgHover:"#e4e4e7",bgSubtle:"#eeeeef",primary:"#632ca6",primaryLight:"#6d28d9",primaryDark:"#4c1d95",secondary:"#124fc7",secondaryLight:"#1556d1",secondaryDark:"#123d96",positive:"#087a55",positiveLight:"#0a8060",positiveDark:"#05543c",warning:"#c96c00",warningLight:"#d97800",warningDark:"#9a4f00",critical:"#b83232",criticalLight:"#c43d3d",criticalDark:"#8f2626",info:"#0b7185",infoLight:"#0d7d92",infoDark:"#075565",accent:"#a83c76",accentLight:"#b74583",neutral:"#52525b",neutralLight:"#71717a",neutralDark:"#3f3f46",textPrimary:"#101012",textSecondary:"#3f3f46",textMuted:"#68686f",textOnColor:"#ffffff",border:"#3f3f46",borderSubtle:"#d4d4d8",borderLight:"#a1a1aa",shadow:"rgba(0, 0, 0, 0)"};function getThemeColors(mode,preset="default"){if(preset==="engineering"){return{...engineeringColors,preset,fontSans:"Inter",fontMono:"JetBrains Mono"}}return{...mode==="light"?lightColors:darkColors,...defaultStyleTokens}}var colors={...darkColors,...defaultStyleTokens};var gradients={purple:"linear-gradient(135deg, #7c3aed, #a855f7)",blue:"linear-gradient(135deg, #2563eb, #60a5fa)",green:"linear-gradient(135deg, #059669, #34d399)",warm:"linear-gradient(135deg, #f59e0b, #ef4444)",cyan:"linear-gradient(135deg, #06b6d4, #22d3ee)",pink:"linear-gradient(135deg, #ec4899, #f472b6)",sunset:"linear-gradient(135deg, #f97316, #db2777)",ocean:"linear-gradient(135deg, #0284c7, #7c3aed)",dark:"linear-gradient(180deg, #0f1117, #1a1b26)"};var toneGradients={blue:gradients.blue,purple:gradients.purple,green:gradients.green,warm:gradients.warm,cyan:gradients.cyan,pink:gradients.pink,red:gradients.warm,critical:gradients.warm,neutral:gradients.dark,sunset:gradients.sunset,ocean:gradients.ocean,dark:gradients.dark};function getToneGradient(tone){return toneGradients[tone]}function getToneColor(tone,c){return{blue:c.secondaryLight,purple:c.primaryLight,green:c.positiveLight,warm:c.warningLight,cyan:c.infoLight,pink:c.accentLight,red:c.criticalLight,critical:c.criticalLight,neutral:c.textSecondary,sunset:c.warningLight,ocean:c.infoLight,dark:c.textSecondary}[tone]}function getReadableToneColor(tone,c,background=c.bgCard,backdrop=c.bgCard){const semanticColor={blue:"secondary",purple:"primary",green:"positive",warm:"warning",cyan:"info",pink:"accent",red:"critical",critical:"critical",neutral:"neutral",sunset:"warning",ocean:"info",dark:"neutral"};const color=getReadableColor(semanticColor[tone],c);return colorContrast(color,background,backdrop)>=4.5?color:getReadableTextColor(background,c,backdrop)}function getToneFill(tone,c){if(c.preset!=="engineering")return withColorAlpha(getToneColor(tone,c),22/255);return{blue:"#cddcfa",purple:"#dfcff8",green:"#d5ede4",warm:"#fde7ce",cyan:"#d7edf1",pink:"#f3d9e7",red:"#f4d7d7",critical:"#f4d7d7",neutral:"#e4e4e7",sunset:"#fde1d6",ocean:"#d8e2f6",dark:"#dedee2"}[tone]}var typography={title:{fontSize:28,fontWeight:700,fontFamily:"Inter"},subtitle:{fontSize:20,fontWeight:600,fontFamily:"Inter"},label:{fontSize:16,fontWeight:600,fontFamily:"Inter"},body:{fontSize:14,fontWeight:400,fontFamily:"Inter"},small:{fontSize:12,fontWeight:500,fontFamily:"Inter"},tiny:{fontSize:11,fontWeight:500,fontFamily:"Inter"},code:{fontSize:13,fontWeight:400,fontFamily:"JetBrains Mono"},annotation:{fontSize:12,fontWeight:500,fontFamily:"Inter",fontStyle:"italic"}};var canvas={standard:{width:800,height:500},wide:{width:1e3,height:400},square:{width:600,height:600},tall:{width:600,height:800}};function getStyles(c){return{canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:c.bg,fontFamily:c.fontSans,padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:c.bgCard,borderRadius:8,border:`1px solid ${c.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}}}var styles={canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:colors.bg,fontFamily:"Inter",padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:colors.bgCard,borderRadius:8,border:`1px solid ${colors.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}};function getColor(name,c){if(c)return c[name];return colors[name]}function getReadableColor(name,c){const variants={primary:[c.primaryLight,c.primary,c.primaryDark],secondary:[c.secondaryLight,c.secondary,c.secondaryDark],positive:[c.positiveLight,c.positive,c.positiveDark],warning:[c.warningLight,c.warning,c.warningDark],critical:[c.criticalLight,c.critical,c.criticalDark],info:[c.infoLight,c.info,c.infoDark],accent:[c.accentLight,c.accent,"#be185d"],neutral:[c.textSecondary,c.neutralLight,c.neutral,c.neutralDark]};return variants[name].reduce((best,candidate)=>colorContrast(candidate,c.bgCard)>colorContrast(best,c.bgCard)?candidate:best)}function parseColor(color){const parsed=parseCssColor(color);if(!parsed||parsed.values.length<3)return void 0;if(parsed.type!=="hsl"){return{channels:[parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0],alpha:parsed.alpha}}const hue=((parsed.values[0]??0)%360+360)%360;const saturation=(parsed.values[1]??0)/100;const lightness=(parsed.values[2]??0)/100;const chroma=(1-Math.abs(2*lightness-1))*saturation;const segment=hue/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=lightness-chroma/2;return{channels:channels.map(channel=>Math.round((channel+offset)*255)),alpha:parsed.alpha}}function withColorAlpha(color,opacity){if(typeof color!=="string"||!Number.isFinite(opacity))return"transparent";const parsed=parseColor(color);if(!parsed)return"transparent";const alpha=Math.min(1,Math.max(0,parsed.alpha*Math.min(1,Math.max(0,opacity))));const hex=color.trim();if(/^#[\da-f]{6}$/i.test(hex)){return`${hex}${Math.round(alpha*255).toString(16).padStart(2,"0")}`}return`rgba(${parsed.channels.join(", ")}, ${Number(alpha.toFixed(6))})`}function colorLuminance(color,backdrop){const parsed=parseColor(color);if(!parsed)return void 0;let channels=parsed.channels;if(parsed.alpha<1){const backdropColor=backdrop?parseColor(backdrop):void 0;if(!backdropColor)return void 0;channels=channels.map((channel,index)=>Math.round(channel*parsed.alpha+backdropColor.channels[index]*(1-parsed.alpha)))}const[r,g,b]=channels.map(channel=>{const normalized=channel/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4});return .2126*r+.7152*g+.0722*b}function colorContrast(left,right,rightBackdrop){const leftLuminance=colorLuminance(left);const rightLuminance=colorLuminance(right,rightBackdrop);if(leftLuminance==null||rightLuminance==null)return 0;return(Math.max(leftLuminance,rightLuminance)+.05)/(Math.min(leftLuminance,rightLuminance)+.05)}function getReadableTextColor(background,c,backdrop=c.bgCard){if(colorLuminance(background,backdrop)==null)return c.textPrimary;const candidates=[c.textPrimary,c.textOnColor,c.bg,"#000000"];const readable=candidates.find(candidate=>colorContrast(candidate,background,backdrop)>=4.5);if(readable)return readable;return candidates.reduce((best,candidate)=>colorContrast(candidate,background,backdrop)>colorContrast(best,background,backdrop)?candidate:best)}function getGradient(name){const map={primary:gradients.purple,secondary:gradients.blue,positive:gradients.green,warning:gradients.warm,critical:gradients.warm,info:gradients.cyan,accent:gradients.pink,neutral:gradients.dark};return map[name]}function heatColor(value){const v=Math.max(0,Math.min(1,value));if(v<.25){const t=v/.25;return lerpColor("#1e293b","#0891b2",t)}else if(v<.5){const t=(v-.25)/.25;return lerpColor("#0891b2","#059669",t)}else if(v<.75){const t=(v-.5)/.25;return lerpColor("#059669","#d97706",t)}else{const t=(v-.75)/.25;return lerpColor("#d97706","#dc2626",t)}}function lerpColor(a,b,t){const ah=parseInt(a.slice(1),16);const bh=parseInt(b.slice(1),16);const ar=ah>>16&255,ag=ah>>8&255,ab=ah&255;const br=bh>>16&255,bg=bh>>8&255,bb=bh&255;const rr=Math.round(ar+(br-ar)*t);const rg=Math.round(ag+(bg-ag)*t);const rb=Math.round(ab+(bb-ab)*t);return`#${(rr<<16|rg<<8|rb).toString(16).padStart(6,"0")}`}var primitives_exports={};__export(primitives_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AxisPlot:()=>AxisPlot,Badge:()=>Badge,BadgePill:()=>BadgePill,BarChart:()=>BarChart,Board:()=>Board,Box:()=>Box,CANVAS_ITEM_COMPONENT:()=>CANVAS_ITEM_COMPONENT,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,EquationCard:()=>EquationCard,Flow:()=>Flow,FlowArrow:()=>FlowArrow,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MiniBarChart:()=>MiniBarChart,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,Row:()=>Row,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TextLabel:()=>TextLabel,Tile:()=>Tile,TileGrid:()=>TileGrid,TiledMatrix:()=>TiledMatrix,Timeline:()=>Timeline,TitleBar:()=>TitleBar,ToneStrip:()=>ToneStrip,TransformerTopology:()=>TransformerTopology,TreeDiagram:()=>TreeDiagram,ValuePill:()=>ValuePill,VectorArrow:()=>VectorArrow,VectorSegment:()=>VectorSegment,WindowFrame:()=>WindowFrame,createPlotArea:()=>createPlotArea,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,getToneColor:()=>getToneColor,getToneGradient:()=>getToneGradient});import React from"react";import{AsyncLocalStorage}from"async_hooks";var RENDER_CONTEXT_KEY=Symbol.for("vizmatic.renderContext");var globalRenderContext=globalThis;var renderContext=globalRenderContext[RENDER_CONTEXT_KEY]??=new AsyncLocalStorage;function getRenderBackground(){return renderContext.getStore()?.background??"transparent"}async function withRenderContext(context,render){const parent=renderContext.getStore();return renderContext.run({...parent,...context},render)}function defineIllustration(build,defaultTheme="dark"){return{create(theme){return build(getThemeColors(theme))},default:build(getThemeColors(defaultTheme))}}function Canvas({children,c,padding=40,justify="center",background}){const renderBackground=getRenderBackground();const canvasBackground=background??(renderBackground==="theme"?c.bg:renderBackground);return React.createElement("div",{style:{width:"100%",height:"100%",boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:justify,backgroundColor:canvasBackground,fontFamily:c.fontSans,padding}},children)}function TitleBar({title,subtitle,c}){const engineering=c.preset==="engineering";return React.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:engineering?"flex-start":"center",gap:6,...engineering?{width:"100%"}:{},marginBottom:engineering?20:24}},React.createElement("div",{style:{...typography.title,fontFamily:c.fontSans,fontSize:engineering?34:typography.title.fontSize,fontWeight:700,...engineering?{lineHeight:1.12}:{},color:c.textPrimary}},title),subtitle&&React.createElement("div",{style:{...typography.body,color:c.textSecondary,fontFamily:c.fontMono,fontSize:engineering?14:typography.body.fontSize,lineHeight:1.35}},subtitle))}function flexAlign(align){return{start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"}[align]}function flexJustify(justify){return{start:"flex-start",center:"center",end:"flex-end","space-between":"space-between","space-around":"space-around"}[justify]}function textFitStyle(align="left"){return{minWidth:0,maxWidth:"100%",whiteSpace:"normal",overflowWrap:"break-word",textAlign:align}}function compactChildren(children){return children.filter(child=>child!==void 0&&child!==null&&child!==false)}function Scene({c,children,title,subtitle,padding=40,gap=24,justify="flex-start",align="stretch",contentWidth="100%",background,contentStyle}){return React.createElement(Canvas,{c,padding,justify,background},...compactChildren([title&&React.createElement(TitleBar,{c,title,subtitle}),React.createElement("div",{style:{width:contentWidth,display:"flex",flexDirection:"column",alignItems:flexAlign(align),gap,...contentStyle}},children)]))}function flexBox(direction,{children,gap=12,align="center",justify="center",wrap=false,width,height,style}){return React.createElement("div",{style:{display:"flex",flexDirection:direction,alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...wrap?{flexWrap:"wrap"}:{},...width!=null?{width}:{},...height!=null?{height}:{},...style}},children)}function Row(props){return flexBox("row",props)}function Column(props){return flexBox("column",props)}function ToneStrip({tone,width=34,height=4}){return React.createElement("span",{style:{display:"flex",width,height,borderRadius:999,backgroundImage:getToneGradient(tone),flexShrink:0}},"")}var iconShapes={agent:[{tag:"rect",attrs:{x:5,y:7,width:14,height:12,rx:4}},{tag:"path",attrs:{d:"M12 7V4"}},{tag:"circle",attrs:{cx:12,cy:3,r:1}},{tag:"circle",attrs:{cx:9,cy:13,r:1}},{tag:"circle",attrs:{cx:15,cy:13,r:1}},{tag:"path",attrs:{d:"M9 17h6"}}],bucket:[{tag:"path",attrs:{d:"M5 7c0-2 14-2 14 0s-14 2-14 0Z"}},{tag:"path",attrs:{d:"M6 7l1 13h10l1-13"}}],browser:[{tag:"rect",attrs:{x:3,y:4,width:18,height:16,rx:2}},{tag:"path",attrs:{d:"M3 8h18"}},{tag:"circle",attrs:{cx:7,cy:6,r:.75}},{tag:"circle",attrs:{cx:10,cy:6,r:.75}},{tag:"circle",attrs:{cx:13,cy:6,r:.75}}],cache:[{tag:"rect",attrs:{x:5,y:4,width:14,height:16,rx:3}},{tag:"path",attrs:{d:"M8 9h8"}},{tag:"path",attrs:{d:"M8 13h8"}},{tag:"path",attrs:{d:"M8 17h5"}}],chart:[{tag:"path",attrs:{d:"M4 19V5"}},{tag:"path",attrs:{d:"M4 19h16"}},{tag:"polyline",attrs:{points:"7 15 11 11 14 13 19 7"}}],check:[{tag:"polyline",attrs:{points:"20 6 9 17 4 12"}}],cluster:[{tag:"path",attrs:{d:"M12 8v4M10 13l-4 2M14 13l4 2"}},{tag:"circle",attrs:{cx:12,cy:5,r:3}},{tag:"circle",attrs:{cx:6,cy:17,r:3}},{tag:"circle",attrs:{cx:18,cy:17,r:3}}],code:[{tag:"polyline",attrs:{points:"8 9 4 12 8 15"}},{tag:"polyline",attrs:{points:"16 9 20 12 16 15"}},{tag:"path",attrs:{d:"M13 5l-2 14"}}],cloud:[{tag:"path",attrs:{d:"M7 18h11a4 4 0 0 0 .5-7.97A6.5 6.5 0 0 0 6.2 8.5 4.8 4.8 0 0 0 7 18Z"}}],container:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:1}},{tag:"path",attrs:{d:"M8 5v14M16 5v14"}}],database:[{tag:"path",attrs:{d:"M4 7c0-2 16-2 16 0s-16 2-16 0Z"}},{tag:"path",attrs:{d:"M4 7v5c0 2 16 2 16 0V7"}},{tag:"path",attrs:{d:"M4 12v5c0 2 16 2 16 0v-5"}}],file:[{tag:"path",attrs:{d:"M6 3h8l4 4v14H6Z"}},{tag:"path",attrs:{d:"M14 3v5h5"}},{tag:"path",attrs:{d:"M9 13h6"}},{tag:"path",attrs:{d:"M9 17h4"}}],firewall:[{tag:"path",attrs:{d:"M5 4h14v16H5Z"}},{tag:"path",attrs:{d:"M5 9h14M5 14h14"}},{tag:"path",attrs:{d:"M9 4v5M15 4v5M12 9v5M8 14v6M17 14v6"}}],gateway:[{tag:"path",attrs:{d:"M4 20V5h16v15"}},{tag:"path",attrs:{d:"M8 20v-7h8v7"}},{tag:"polyline",attrs:{points:"9 9 12 6 15 9"}},{tag:"path",attrs:{d:"M12 6v7"}}],git:[{tag:"circle",attrs:{cx:6,cy:6,r:2}},{tag:"circle",attrs:{cx:18,cy:18,r:2}},{tag:"circle",attrs:{cx:6,cy:18,r:2}},{tag:"path",attrs:{d:"M8 6h3a5 5 0 0 1 5 5v5"}},{tag:"path",attrs:{d:"M6 8v8"}}],globe:[{tag:"circle",attrs:{cx:12,cy:12,r:9}},{tag:"path",attrs:{d:"M3 12h18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 1 0 18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 0 0 18"}}],image:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:3}},{tag:"circle",attrs:{cx:9,cy:10,r:1.5}},{tag:"polyline",attrs:{points:"7 17 11 13 14 16 16 14 20 18"}}],layers:[{tag:"path",attrs:{d:"M12 3 3 8l9 5 9-5Z"}},{tag:"path",attrs:{d:"m3 13 9 5 9-5"}},{tag:"path",attrs:{d:"m3 18 9 5 9-5"}}],lock:[{tag:"rect",attrs:{x:5,y:10,width:14,height:10,rx:2}},{tag:"path",attrs:{d:"M8 10V7a4 4 0 0 1 8 0v3"}}],"load-balancer":[{tag:"rect",attrs:{x:8,y:8,width:8,height:8,rx:2}},{tag:"path",attrs:{d:"M4 12h4M16 7h4M16 12h4M16 17h4"}},{tag:"polyline",attrs:{points:"6 10 4 12 6 14"}}],mobile:[{tag:"rect",attrs:{x:6,y:2,width:12,height:20,rx:2}},{tag:"path",attrs:{d:"M10 5h4"}},{tag:"circle",attrs:{cx:12,cy:18,r:1}}],monitor:[{tag:"rect",attrs:{x:3,y:4,width:18,height:13,rx:2}},{tag:"path",attrs:{d:"M8 21h8M12 17v4"}}],network:[{tag:"path",attrs:{d:"M7 10l3-3M14 7l3 3M17 14l-3 3M10 17l-3-3M7 12h10M12 7v10"}},{tag:"circle",attrs:{cx:5,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:5,r:2}},{tag:"circle",attrs:{cx:19,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:19,r:2}}],play:[{tag:"path",attrs:{d:"M8 5v14l11-7Z"}}],queue:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:2}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:12,cy:12,r:1}},{tag:"circle",attrs:{cx:16,cy:12,r:1}}],server:[{tag:"rect",attrs:{x:4,y:4,width:16,height:16,rx:2}},{tag:"path",attrs:{d:"M4 9h16M4 15h16"}},{tag:"circle",attrs:{cx:8,cy:7,r:1}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:8,cy:18,r:1}}],spark:[{tag:"path",attrs:{d:"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8Z"}},{tag:"path",attrs:{d:"M5 16l.8 2.2L8 19l-2.2.8L5 22l-.8-2.2L2 19l2.2-.8Z"}}],storage:[{tag:"rect",attrs:{x:4,y:6,width:16,height:12,rx:2}},{tag:"circle",attrs:{cx:12,cy:12,r:3}},{tag:"path",attrs:{d:"M7 18h10"}}],stream:[{tag:"path",attrs:{d:"M4 7h13"}},{tag:"polyline",attrs:{points:"14 4 17 7 14 10"}},{tag:"path",attrs:{d:"M20 17H7"}},{tag:"polyline",attrs:{points:"10 14 7 17 10 20"}}],terminal:[{tag:"polyline",attrs:{points:"5 7 10 12 5 17"}},{tag:"path",attrs:{d:"M12 17h7"}}],tool:[{tag:"path",attrs:{d:"M14 6a5 5 0 0 0 6 6L11 21l-6-6 9-9Z"}},{tag:"path",attrs:{d:"M8 18l-2-2"}}],user:[{tag:"circle",attrs:{cx:12,cy:7,r:3.5}},{tag:"path",attrs:{d:"M5 20a7 7 0 0 1 14 0"}}],warning:[{tag:"path",attrs:{d:"M12 4 22 20H2Z"}},{tag:"path",attrs:{d:"M12 9v5"}},{tag:"path",attrs:{d:"M12 17h.01"}}]};function Icon({c,name,tone="blue",color,size=24,strokeWidth=2,label,muted=false}){const stroke=muted?c.textMuted:color??getToneColor(tone,c);const shapes=iconShapes[name];return React.createElement("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke,strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",role:label?"img":void 0,"aria-hidden":label?void 0:"true","aria-label":label,style:{flex:`0 0 ${size}px`}},shapes.map((shape,index)=>React.createElement(shape.tag,{key:`${name}-${index}`,...shape.attrs})))}function Panel({title,c,children,subtitle,tone="blue",footer,width,minWidth,height,minHeight,padding=14,radius=8,gap=10,align="stretch",justify="start",shadow=true,background,borderColor,titleFontSize,accentWidth=34,accentHeight=4,bodyStyle}){const engineering=c.preset==="engineering";return React.createElement("div",{"data-vizmatic-layout-container":"panel",style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:radius,border:`1px solid ${borderColor??c.borderSubtle}`,backgroundColor:background??c.bgCard,...shadow&&!engineering?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap:subtitle?5:0}},...compactChildren([React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,...typography.small,fontFamily:c.fontSans,...textFitStyle(),fontSize:titleFontSize??typography.small.fontSize,fontWeight:900,lineHeight:1.2}},ToneStrip({tone,width:accentWidth,height:accentHeight}),title),subtitle&&React.createElement("div",{style:{display:"flex",color:c.textSecondary,...typography.tiny,fontFamily:engineering?c.fontMono:typography.tiny.fontFamily,...textFitStyle(),lineHeight:1.35}},subtitle)])),React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap,...bodyStyle}},children),footer&&React.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",color:c.textMuted,...typography.tiny,...textFitStyle()}},footer)]))}function readScriptValue(text,start){if(text[start]==="{"){const end=text.indexOf("}",start+1);if(end!==-1)return{value:text.slice(start+1,end),next:end+1}}let next=start;while(next<text.length&&/[A-Za-z0-9+\-]/.test(text[next]))next+=1;if(next===start)next+=1;return{value:text.slice(start,next),next}}function parseMathText(text){const parts=[];let buffer="";let index=0;while(index<text.length){const char=text[index];if((char==="_"||char==="^")&&index+1<text.length){if(buffer){parts.push({kind:"text",value:buffer});buffer=""}const script=readScriptValue(text,index+1);parts.push({kind:char==="_"?"sub":"sup",value:script.value});index=script.next;continue}buffer+=char;index+=1}if(buffer)parts.push({kind:"text",value:buffer});return parts}var subscriptChars={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var superscriptChars={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"};var superscriptWords={alpha:"\u1D45",beta:"\u1D5D",gamma:"\u1D5E",theta:"\u1DBF"};function scriptText(value,kind){const words=kind==="sup"?superscriptWords:{};const chars=kind==="sub"?subscriptChars:superscriptChars;if(words[value])return words[value];if((value.startsWith("-")||value.startsWith("+"))&&words[value.slice(1)]){return`${chars[value[0]]}${words[value.slice(1)]}`}return Array.from(value).map(char=>chars[char]??char).join("")}function formatMathText(text){return parseMathText(text).map(part=>part.kind==="text"?part.value:scriptText(part.value,part.kind)).join("")}function MathText({text}){return formatMathText(text)}function TextLabel({text,c,variant="body",color,fontSize,fontWeight,width,align="left",math=false,mono=false}){const base=typography[variant];return React.createElement("div",{style:{display:"flex",...width!==void 0?{width}:{},...base,...textFitStyle(align),color:color??c.textSecondary,fontSize:fontSize??base.fontSize,fontWeight:fontWeight??base.fontWeight,fontFamily:mono?"JetBrains Mono":base.fontFamily,justifyContent:align==="right"?"flex-end":align==="center"?"center":"flex-start",lineHeight:1.35}},math?formatMathText(text):text)}function svgMathTextBaselineOffset(dominantBaseline){switch(dominantBaseline.toLowerCase()){case"hanging":case"text-before-edge":case"before-edge":case"top":return"0";case"text-after-edge":case"after-edge":case"bottom":case"alphabetic":case"baseline":case"ideographic":case"auto":return"-100%";default:return"-50%"}}function SvgMathText({text,x,y,fill,fontSize=13,fontFamily="JetBrains Mono",fontWeight=800,textAnchor="middle",dominantBaseline="middle",opacity=1}){const anchorOffset=textAnchor==="start"?"0":textAnchor==="end"?"-100%":"-50%";const baselineOffset=svgMathTextBaselineOffset(dominantBaseline);return React.createElement("div",{"data-vizmatic-svg-math-text":true,style:{position:"absolute",left:x,top:y,display:"flex",color:fill,fontSize,fontFamily,fontWeight,lineHeight:1,whiteSpace:"nowrap",pointerEvents:"none",opacity,transform:`translate(${anchorOffset}, ${baselineOffset})`}},formatMathText(text))}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}import React2 from"react";function Box({label,c,color="primary",width,height,fontSize=14,gradient=false,sublabel,icon,radius=8,outlined=false}){const solidColor=getColor(color,c);const gradientBg=getGradient(color);const solidTextColor=getReadableTextColor(solidColor,c);const style={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:radius,padding:"12px 20px",gap:4,...width?{width}:{},...height?{height}:{}};if(outlined){style.border=`2px solid ${solidColor}`;style.backgroundColor="transparent"}else if(gradient){style.backgroundImage=gradientBg;style.boxShadow=`0 4px 20px ${withColorAlpha(solidColor,48/255)}`}else{style.backgroundColor=solidColor;style.boxShadow=`0 4px 20px ${withColorAlpha(solidColor,48/255)}`}return React2.createElement("div",{style},icon&&React2.createElement("div",{style:{fontSize:fontSize+4}},icon),React2.createElement("div",{style:{fontSize,fontWeight:700,color:outlined?solidColor:gradient?c.textOnColor:solidTextColor,fontFamily:c.fontSans,textAlign:"center",lineHeight:1.3}},label),sublabel&&React2.createElement("div",{style:{fontSize:fontSize-2,fontWeight:400,color:outlined?c.textMuted:gradient?withColorAlpha(c.textOnColor,179/255):solidTextColor,fontFamily:c.fontMono,textAlign:"center"}},sublabel))}function Arrow({direction="down",label,length=40,c,color}){const arrowColor=color||c.textMuted;const isVertical=direction==="down"||direction==="up";const arrowHead={down:{width:14,height:10,points:"0,0 14,0 7,10"},up:{width:14,height:10,points:"0,10 14,10 7,0"},right:{width:10,height:14,points:"0,0 10,7 0,14"},left:{width:10,height:14,points:"10,0 0,7 10,14"}}[direction];const line=React2.createElement("div",{style:{...isVertical?{width:2,flexGrow:1,minHeight:1}:{height:2,flexGrow:1,minWidth:1},backgroundColor:arrowColor}});const head=React2.createElement("svg",{width:arrowHead.width,height:arrowHead.height,viewBox:`0 0 ${arrowHead.width} ${arrowHead.height}`,style:{flexShrink:0}},React2.createElement("polygon",{points:arrowHead.points,fill:arrowColor}));return React2.createElement("div",{style:{position:"relative",display:"flex",flexDirection:isVertical?"column":"row",alignItems:"center",justifyContent:"center",gap:0,...isVertical?{height:length}:{width:length}}},...direction==="up"||direction==="left"?[head,line]:[line,head],label&&React2.createElement("div",{style:{fontSize:11,color:c.textMuted,fontFamily:c.fontSans,fontWeight:500,position:"absolute",...isVertical?{left:8}:{bottom:12}}},label))}function FlowArrow({direction="right",label,length=40,c,tone="blue",color}){return Arrow({direction,label,length,c,color:color??getToneColor(tone,c)})}function Connector(props){return FlowArrow(props)}function VectorArrow({key,x1,y1,x2,y2,color,strokeWidth=2,arrowSize=2.2,opacity=1}){const dx=x2-x1;const dy=y2-y1;const len=Math.sqrt(dx*dx+dy*dy);if(len<.001){return React2.createElement("g",null)}const ux=dx/len;const uy=dy/len;const px=-uy;const py=ux;const headLen=strokeWidth*arrowSize;const headWidth=headLen*.6;const backX=x2-ux*headLen;const backY=y2-uy*headLen;const points=`${x2},${y2} ${backX+px*headWidth/2},${backY+py*headWidth/2} ${backX-px*headWidth/2},${backY-py*headWidth/2}`;return React2.createElement("g",{key,opacity},React2.createElement("line",{x1,y1,x2:backX,y2:backY,stroke:color,strokeWidth,strokeLinecap:"round"}),React2.createElement("polygon",{points,fill:color}))}function VectorSegment({key,x1,y1,x2,y2,color,strokeWidth=4,opacity=1,showStartDot=false,showEndDot=true,dotRadius=4.5}){return React2.createElement("g",{key,opacity},React2.createElement("line",{x1,y1,x2,y2,stroke:color,strokeWidth,strokeLinecap:"round"}),showStartDot&&React2.createElement("circle",{cx:x1,cy:y1,r:dotRadius,fill:color}),showEndDot&&React2.createElement("circle",{cx:x2,cy:y2,r:dotRadius,fill:color}))}function SvgFrame({key,x=0,y=0,width,height,c,rx=8,fill,stroke,strokeWidth=1,opacity}){return React2.createElement("rect",{key,x,y,width,height,rx,fill:fill??c.bgSubtle,stroke:stroke??c.borderSubtle,strokeWidth,...opacity!==void 0?{opacity}:{}})}function SvgPoint({key,cx,cy,r=5,fill,stroke,strokeWidth,opacity}){return React2.createElement("circle",{key,cx,cy,r,fill,...stroke?{stroke}:{},...strokeWidth?{strokeWidth}:{},...opacity!==void 0?{opacity}:{}})}function ArrowMarkerDef({id,color,size=5}){return React2.createElement("marker",{id,viewBox:"0 0 10 10",refX:9.5,refY:5,markerWidth:size,markerHeight:size,orient:"auto-start-reverse"},React2.createElement("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:color}))}import React3 from"react";function Stack({direction="vertical",gap=12,align="center",wrap=false,children}){const alignMap={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"};return React3.createElement("div",{style:{display:"flex",flexDirection:direction==="vertical"?"column":"row",alignItems:alignMap[align],gap,...wrap?{flexWrap:"wrap"}:{}}},children)}function Card({children,c,title,subtitle,tone,footer,width,minWidth,height,minHeight,padding=20,radius=8,gap,align="stretch",justify="start",shadow=false,background,borderColor,bodyStyle}){const hasHeader=title||subtitle||tone;const engineering=c.preset==="engineering";return React3.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap:gap??(hasHeader||footer?10:0),backgroundColor:background??c.bgCard,borderRadius:engineering?Math.min(radius,5):radius,border:`1px solid ${borderColor??c.borderSubtle}`,padding,...width!==void 0?{width}:{},...minWidth!==void 0?{minWidth}:{},...height!==void 0?{height}:{},...minHeight!==void 0?{minHeight}:{},...shadow&&!engineering?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([hasHeader&&React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:subtitle?5:0}},...compactChildren([(title||tone)&&React3.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,...typography.small,fontFamily:c.fontSans,...textFitStyle(),fontWeight:900,lineHeight:1.2}},tone&&ToneStrip({tone,width:30,height:4}),title),subtitle&&React3.createElement("div",{style:{display:"flex",color:c.textSecondary,...typography.tiny,fontFamily:c.fontSans,...textFitStyle(),lineHeight:1.35}},subtitle)])),React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",...bodyStyle}},children),footer&&React3.createElement("div",{style:{width:"100%",display:"flex",color:c.textMuted,...typography.tiny,fontFamily:c.fontSans,...textFitStyle()}},footer)]))}function renderMaybeMath(node,math){return math&&typeof node==="string"?formatMathText(node):node}function ValuePill({label,value,c,tone="blue",detail,width=112,math=false}){const accent=getReadableToneColor(tone,c);return Card({c,tone,width,padding:12,radius:10,shadow:true,title:React3.createElement("span",{style:{textTransform:"uppercase",letterSpacing:"0.05em"}},renderMaybeMath(label,math)),children:React3.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4}},React3.createElement("div",{style:{color:accent,fontFamily:c.fontMono,fontSize:24,fontWeight:900,lineHeight:1}},renderMaybeMath(value,math)),detail&&React3.createElement("div",{style:{color:c.textSecondary,...typography.tiny,lineHeight:1.3}},renderMaybeMath(detail,math)))})}function EquationCard({title,formula,c,tone="purple",result,detail,width=190,height,math=false,align="left"}){const accent=getReadableToneColor(tone,c);const textAlign=align;return Card({c,tone,width,height,padding:16,radius:10,shadow:true,title,children:React3.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,alignItems:align==="center"?"center":"flex-start"}},React3.createElement("div",{style:{color:c.textPrimary,fontFamily:c.fontMono,fontSize:15,fontWeight:800,lineHeight:1.3,textAlign}},renderMaybeMath(formula,math)),result&&React3.createElement("div",{style:{color:accent,fontFamily:c.fontMono,fontSize:28,fontWeight:900,lineHeight:1,textAlign}},renderMaybeMath(result,math)),detail&&React3.createElement("div",{style:{color:c.textSecondary,...typography.tiny,lineHeight:1.35,textAlign}},renderMaybeMath(detail,math)))})}function BadgePill({text,c,tone="blue",width,minWidth=34,height=20,padding="0 8px",radius=6,fontSize=11,mono=true,filled=false,math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";return React3.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},padding,borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c)}:filled?{backgroundImage:getToneGradient(tone)}:{backgroundColor:withColorAlpha(accent,24/255)},border:`1px solid ${engineering?accent:filled?withColorAlpha(accent,0):withColorAlpha(accent,85/255)}`,color:engineering?c.textPrimary:filled?c.textOnColor:accentText,fontSize,fontWeight:800,lineHeight:1,fontFamily:mono?c.fontMono:c.fontSans,boxSizing:"border-box",whiteSpace:"nowrap"}},renderMaybeMath(text,math))}function GradientChip({title,c,subtitle,tone="blue",gradient,width,minWidth,height,minHeight=78,padding="0 18px",radius=8,shadow=true,align="left",subtitleMono=true,math=false}){const textAlign=align;const engineering=c.preset==="engineering"&&gradient==null;const textColor=engineering?c.textPrimary:c.textOnColor;const accent=getToneColor(tone,c);return React3.createElement("div",{style:{...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},boxSizing:"border-box",borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c),border:`1px solid ${accent}`}:{backgroundImage:gradient??getToneGradient(tone)},color:textColor,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:5,padding,...shadow&&!engineering?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},React3.createElement("div",{style:{...typography.label,color:textColor,fontFamily:c.fontSans,fontWeight:900,lineHeight:1.1,textAlign}},renderMaybeMath(title,math)),subtitle&&React3.createElement("div",{style:{fontSize:11,color:engineering?c.textSecondary:"rgba(255,255,255,0.86)",lineHeight:1.2,textAlign,fontFamily:subtitleMono?c.fontMono:c.fontSans}},renderMaybeMath(subtitle,math)))}function StepCard({title,c,subtitle,eyebrow,tone="blue",width=210,minWidth,minHeight=74,padding="12px 14px",radius=8,shadow=true,align="center",math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";const textAlign=align;return Card({c,width,minWidth,minHeight,padding,radius:engineering?5:radius,shadow:engineering?false:shadow,background:engineering?getToneFill(tone,c):void 0,borderColor:engineering?accent:withColorAlpha(accent,136/255),children:React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:subtitle?5:2}},eyebrow&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontMono,color:c.textMuted,fontWeight:engineering?400:800,textTransform:"uppercase",letterSpacing:"0.05em",...textFitStyle(textAlign),lineHeight:1.2}},renderMaybeMath(eyebrow,math)),React3.createElement("div",{style:{...typography.label,fontFamily:c.fontSans,color:engineering?c.textPrimary:accentText,fontWeight:700,lineHeight:1.15,...textFitStyle(textAlign)}},renderMaybeMath(title,math)),subtitle&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontMono,color:c.textMuted,lineHeight:1.25,...textFitStyle(textAlign)}},renderMaybeMath(subtitle,math)))})}function MetricCard({label,value,c,tone="blue",detail,width,minWidth,minHeight=74,padding="10px 12px",radius=8,shadow=true,align="center",math=false,valueMono=true,valueFontSize=22,valueColor}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const textAlign=align;return Card({c,width,minWidth,minHeight,padding,radius,shadow,borderColor:withColorAlpha(accent,102/255),children:React3.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:3}},...compactChildren([React3.createElement("div",{style:{fontSize:11,fontWeight:800,color:accentText,fontFamily:c.fontSans,lineHeight:1.1,...textFitStyle(textAlign)}},renderMaybeMath(label,math)),React3.createElement("div",{style:{fontSize:valueFontSize,fontWeight:700,color:valueColor??c.textPrimary,lineHeight:1.15,...textFitStyle(textAlign),fontFamily:valueMono?c.fontMono:c.fontSans}},renderMaybeMath(value,math)),detail&&React3.createElement("div",{style:{...typography.tiny,fontFamily:c.fontSans,color:c.textMuted,lineHeight:1.2,...textFitStyle(textAlign)}},renderMaybeMath(detail,math))]))})}import React4 from"react";function ProgressRow({label,value,valueLabel,tone="blue",muted=false,c,labelWidth=42,valueWidth=38,barHeight=8,fontSize=11}){const accent=muted?c.textMuted:getToneColor(tone,c);const accentText=muted?c.textMuted:getReadableToneColor(tone,c);const pct=Math.round(Math.max(0,Math.min(1,value))*100);return React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,width:"100%"}},React4.createElement("div",{style:{width:labelWidth,color:muted?c.textMuted:c.textPrimary,fontSize,fontWeight:800,lineHeight:1}},label),React4.createElement("div",{style:{display:"flex",flex:1,height:barHeight,borderRadius:999,backgroundColor:c.bgSubtle,border:`1px solid ${c.borderSubtle}`,overflow:"hidden"}},React4.createElement("div",{style:{width:`${pct}%`,height:"100%",borderRadius:999,backgroundColor:accent,opacity:muted?.62:1}})),React4.createElement("div",{style:{width:valueWidth,color:accentText,fontSize,fontWeight:800,fontFamily:"JetBrains Mono",lineHeight:1,textAlign:"right"}},valueLabel??`${pct}%`))}function ProgressList({rows,c,gap=8,labelWidth,valueWidth,barHeight,fontSize}){return Column({gap,align:"stretch",children:rows.map((row,index)=>React4.createElement(React4.Fragment,{key:`progress-${index}`},ProgressRow({...row,c,labelWidth,valueWidth,barHeight,fontSize})))})}function MiniBarChart({data,c,max,minBarHeight=8,height=92,barWidth=22,gap=10,radius=7,fontSize=11,showValues=false}){const requestedMax=max!=null&&max>0?max:void 0;const safeMax=requestedMax??Math.max(1,...data.map(item=>Math.max(0,item.value)));const barMaxHeight=Math.max(minBarHeight,height-(showValues?34:20));return React4.createElement("div",{style:{display:"flex",alignItems:"flex-end",justifyContent:"center",gap,height,width:"100%",padding:"0 4px",boxSizing:"border-box"}},...data.map((item,index)=>{const tone=item.tone??"blue";const barHeight=Math.max(minBarHeight,Math.round(Math.max(0,item.value)/safeMax*barMaxHeight));const fill=item.color??getToneGradient(tone);return React4.createElement("div",{key:`mini-bar-${index}-${String(item.label)}`,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-end",gap:5,height:"100%",minWidth:barWidth}},...compactChildren([showValues&&React4.createElement("div",{style:{display:"flex",color:getReadableToneColor(tone,c),fontFamily:"JetBrains Mono",fontSize,fontWeight:800,lineHeight:1}},item.valueLabel??item.value),React4.createElement("div",{style:{display:"flex",width:barWidth,height:barHeight,borderRadius:`${radius}px ${radius}px 4px 4px`,...fill.startsWith("linear-gradient")?{backgroundImage:fill}:{backgroundColor:fill},opacity:item.opacity??.92}}),React4.createElement("div",{style:{display:"flex",color:c.textMuted,fontFamily:"JetBrains Mono",fontSize,fontWeight:700,lineHeight:1,minHeight:fontSize+2}},item.label)]))}))}function DetailList({items,c,tone,gap=7,padding="7px 8px",fontSize=11,mono=false,math=false}){const accent=tone?getToneColor(tone,c):c.borderSubtle;return Column({gap,align:"stretch",children:items.map((item,index)=>React4.createElement("div",{key:`detail-${index}`,style:{padding,borderRadius:8,backgroundColor:c.bgSubtle,border:`1px solid ${tone?withColorAlpha(accent,68/255):c.borderSubtle}`,color:c.textSecondary,fontSize,lineHeight:1.3,fontFamily:mono?"JetBrains Mono":"Inter"}},renderMaybeMath(item,math)))})}function Tile({title,subtitle,eyebrow,icon,tone="blue",lines,children,width,minHeight=84,c,align="center",padding="14px 16px",radius=10,shadow=true,math=false}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const textAlign=align;const crossAlign=align==="center"?"center":"flex-start";const detailLines=(lines??[]).map((line,index)=>React4.createElement("div",{key:`tile-line-${index}`,style:{display:"flex",alignItems:"center",justifyContent:align==="center"?"center":"flex-start",gap:6,...typography.tiny,color:c.textSecondary,lineHeight:1.3,textAlign}},React4.createElement("span",{style:{display:"flex",width:4,height:4,borderRadius:999,backgroundColor:accent,flexShrink:0}}),renderMaybeMath(line,math)));return Card({c,width,minHeight,padding,radius,shadow,borderColor:withColorAlpha(accent,136/255),children:React4.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:crossAlign,gap:5}},...compactChildren([icon!=null&&React4.createElement("div",{style:{display:"flex",fontSize:22,lineHeight:1}},icon),eyebrow!=null&&React4.createElement("div",{style:{...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",lineHeight:1.2,textAlign}},renderMaybeMath(eyebrow,math)),React4.createElement("div",{style:{...typography.label,color:accentText,fontWeight:800,lineHeight:1.15,textAlign}},renderMaybeMath(title,math)),subtitle!=null&&React4.createElement("div",{style:{...typography.tiny,color:c.textSecondary,lineHeight:1.3,textAlign}},renderMaybeMath(subtitle,math)),detailLines.length>0&&React4.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:4,marginTop:2}},...detailLines),children]))})}function TileGrid({tiles,c,columns,gap=12,tileWidth,minHeight,align="center",math=false}){const renderTile=(tile,index)=>React4.createElement(React4.Fragment,{key:`tile-${index}`},Tile({...tile,c,align,math,width:tile.width??tileWidth,minHeight:tile.minHeight??minHeight}));if(!columns||columns>=tiles.length){return Row({gap,align:"stretch",justify:"center",wrap:true,children:tiles.map(renderTile)})}const rows=[];for(let i=0;i<tiles.length;i+=columns){rows.push(tiles.slice(i,i+columns))}return Column({gap,align:"stretch",children:rows.map((rowTiles,rowIndex)=>React4.createElement(React4.Fragment,{key:`tile-row-${rowIndex}`},Row({gap,align:"stretch",justify:"center",children:rowTiles.map((tile,colIndex)=>renderTile(tile,rowIndex*columns+colIndex))})))})}function isCodeLineSpec(line){return typeof line==="object"&&line!==null&&!React4.isValidElement(line)&&"text"in line}function CodeBlock({lines,c,title,tone,width,minWidth,fontSize=12,showLineNumbers=false,padding=14,radius=10,background,shadow=false,math=false}){const headerAccent=tone?getToneColor(tone,c):c.textMuted;const numberWidth=String(lines.length).length*(fontSize*.62)+8;const lineElements=lines.map((line,index)=>{const spec=isCodeLineSpec(line)?line:{text:line};const accent=spec.tone?getToneColor(spec.tone,c):void 0;const accentText=spec.tone?getReadableToneColor(spec.tone,c):void 0;const textColor=spec.dim?c.textMuted:accentText??c.textSecondary;return React4.createElement("div",{key:`code-line-${index}`,style:{display:"flex",alignItems:"flex-start",gap:8,width:"100%",padding:accent?"3px 7px":"1px 0",borderRadius:accent?5:0,...accent?{backgroundColor:withColorAlpha(accent,31/255)}:{},boxSizing:"border-box"}},...compactChildren([showLineNumbers&&React4.createElement("div",{style:{display:"flex",width:numberWidth,flexShrink:0,justifyContent:"flex-end",color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:fontSize-1,lineHeight:1.5,opacity:.7}},String(index+1)),spec.prefix!=null&&React4.createElement("div",{style:{display:"flex",flexShrink:0,color:accentText??c.textMuted,fontFamily:"JetBrains Mono",fontWeight:800,fontSize,lineHeight:1.5}},spec.prefix),React4.createElement("div",{style:{display:"flex",flex:1,color:textColor,fontFamily:"JetBrains Mono",fontWeight:accent?700:500,fontSize,lineHeight:1.5,whiteSpace:"pre-wrap"}},math&&typeof spec.text==="string"?formatMathText(spec.text):spec.text)]))});return React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},padding,borderRadius:radius,backgroundColor:background??c.bgSubtle,border:`1px solid ${tone?withColorAlpha(headerAccent,68/255):c.borderSubtle}`,boxSizing:"border-box",...shadow?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([title!=null&&React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:fontSize-1,fontWeight:800,letterSpacing:"0.02em"}},React4.createElement("span",{style:{display:"flex",width:8,height:8,borderRadius:999,backgroundColor:headerAccent,flexShrink:0}}),renderMaybeMath(title,math)),React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2,width:"100%"}},...lineElements)]))}function renderComparisonDivider(divider,c,key){const label=divider===true?"vs":divider;return React4.createElement("div",{key,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",alignSelf:"stretch",flexShrink:0}},React4.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minWidth:30,height:30,padding:"0 8px",borderRadius:999,backgroundColor:c.bgCard,border:`1px solid ${c.borderLight}`,color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.06em",boxShadow:`0 4px 12px ${c.shadow}`}},label))}function Comparison({sides:sides2,c,divider=false,gap=14,sideWidth,minHeight,align="stretch",math=false}){const children=sides2.flatMap((side,index)=>{const tone=side.tone??"blue";const panel=React4.createElement(React4.Fragment,{key:`comparison-side-${index}`},Panel({c,tone,title:side.title,subtitle:side.subtitle,footer:side.footer,width:side.width??sideWidth,minHeight,bodyStyle:{gap:8},children:side.eyebrow!=null?React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8}},React4.createElement("div",{style:{...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em"}},renderMaybeMath(side.eyebrow,math)),side.children??DetailList({items:side.lines??[],c,tone,math})):side.children??DetailList({items:side.lines??[],c,tone,math})}));if(divider&&index<sides2.length-1){return[panel,renderComparisonDivider(divider,c,`comparison-divider-${index}`)]}return[panel]});return Row({gap,align,justify:"center",children})}function KeyValueList({rows,c,title,width,minWidth,keyWidth,gap=0,fontSize=11,divider=true,keyMono=false,math=false}){const rowElements=rows.map((row,index)=>{const accent=row.tone?getReadableToneColor(row.tone,c):void 0;const isLast=index===rows.length-1;const valueMono=row.valueMono??true;return React4.createElement("div",{key:`kv-row-${index}`,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:14,width:"100%",padding:divider?"7px 0":"4px 0",...divider&&!isLast?{borderBottom:`1px solid ${c.borderSubtle}`}:{},boxSizing:"border-box"}},React4.createElement("div",{style:{display:"flex",...keyWidth!=null?{width:keyWidth,flexShrink:0}:{},color:c.textSecondary,fontFamily:keyMono?"JetBrains Mono":"Inter",fontSize,fontWeight:600,lineHeight:1.3}},renderMaybeMath(row.key,math)),React4.createElement("div",{style:{display:"flex",flex:1,justifyContent:"flex-end",textAlign:"right",color:accent??c.textPrimary,fontFamily:valueMono?"JetBrains Mono":"Inter",fontSize,fontWeight:800,lineHeight:1.3}},renderMaybeMath(row.value,math)))});return React4.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{}}},...compactChildren([title!=null&&React4.createElement("div",{style:{display:"flex",...typography.tiny,color:c.textMuted,fontWeight:800,textTransform:"uppercase",letterSpacing:"0.05em",paddingBottom:4}},renderMaybeMath(title,math)),...rowElements]))}function WindowFrame({c,children,title,variant="window",tone="blue",dots=true,width,minWidth,height,minHeight,padding=16,radius=10,shadow=true,background,bodyStyle}){const isTerminal=variant==="terminal";const surface=background??(isTerminal?c.bgSubtle:c.bgCard);const titleColor=isTerminal?getReadableToneColor(tone,c,c.bgHover):c.textSecondary;const trafficDot=(color,key)=>React4.createElement("span",{key,style:{display:"flex",width:10,height:10,borderRadius:999,backgroundColor:color}});const titleBar=React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"8px 12px",backgroundColor:isTerminal?c.bg==="transparent"?c.bgHover:c.bgHover:c.bgSubtle,borderBottom:`1px solid ${c.borderSubtle}`,boxSizing:"border-box"}},...compactChildren([dots&&React4.createElement("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0}},trafficDot(c.criticalLight,"dot-r"),trafficDot(c.warningLight,"dot-y"),trafficDot(c.positiveLight,"dot-g")),title!=null&&(variant==="browser"?React4.createElement("div",{style:{display:"flex",flex:1,alignItems:"center",height:22,padding:"0 12px",borderRadius:999,backgroundColor:c.bgCard,border:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:600,lineHeight:1}},title):React4.createElement("div",{style:{display:"flex",flex:1,justifyContent:dots?"center":"flex-start",color:titleColor,fontFamily:isTerminal?"JetBrains Mono":"Inter",fontSize:12,fontWeight:700,lineHeight:1}},title)),dots&&title!=null&&variant!=="browser"&&React4.createElement("div",{style:{display:"flex",width:52,flexShrink:0}},"")]));return React4.createElement("div",{style:{display:"flex",flexDirection:"column",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},borderRadius:radius,border:`1px solid ${c.borderSubtle}`,backgroundColor:surface,overflow:"hidden",boxSizing:"border-box",...shadow?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},titleBar,React4.createElement("div",{style:{display:"flex",flexDirection:"column",width:"100%",padding,boxSizing:"border-box",...isTerminal?{fontFamily:"JetBrains Mono",color:c.textSecondary}:{},...bodyStyle}},children))}import React5 from"react";var statusGlyphs={check:"\u2713",cross:"\u2717",warn:"!",info:"i",pending:"\u2013",dot:""};var statusTones={check:"green",cross:"red",warn:"warm",info:"blue",pending:"neutral",dot:"blue"};function StatusRow({label,detail,status="check",tone,c,boxed=true,fontSize=11,width,math=false}){const resolvedTone=tone??statusTones[status];const accent=getToneColor(resolvedTone,c);const markerAlpha=38/255;const rowAlpha=boxed?18/255:0;const markerBackgroundAlpha=Math.round((rowAlpha+markerAlpha*(1-rowAlpha))*255);const markerBackground=withColorAlpha(accent,markerBackgroundAlpha/255);const accentText=getReadableToneColor(resolvedTone,c,markerBackground,c.bgCard);const glyph=statusGlyphs[status];const marker=React5.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:18,height:18,flexShrink:0,borderRadius:999,backgroundColor:status==="dot"?accent:withColorAlpha(accent,38/255),border:`1px solid ${accent}`,color:accentText,fontFamily:"Inter",fontSize:status==="warn"||status==="info"?12:11,fontWeight:900,lineHeight:1}},glyph);return React5.createElement("div",{style:{display:"flex",alignItems:"center",gap:9,width:width??"100%",boxSizing:"border-box",...boxed?{padding:"7px 10px",borderRadius:8,backgroundColor:withColorAlpha(accent,18/255),border:`1px solid ${withColorAlpha(accent,58/255)}`}:{padding:"3px 0"}}},marker,React5.createElement("div",{style:{display:"flex",flex:1,color:c.textPrimary,fontFamily:"Inter",fontSize,fontWeight:600,lineHeight:1.3}},renderMaybeMath(label,math)),detail!=null&&React5.createElement("div",{style:{display:"flex",flexShrink:0,color:c.textSecondary,fontFamily:"Inter",fontSize:fontSize-1,lineHeight:1.3,textAlign:"right"}},renderMaybeMath(detail,math)))}function StatusList({rows,c,gap=7,boxed=true,fontSize,width,math=false}){return Column({gap,align:"stretch",...width!=null?{width}:{},children:rows.map((row,index)=>React5.createElement(React5.Fragment,{key:`status-${index}`},StatusRow({...row,c,boxed,fontSize,math})))})}function renderTimelineCard(event,c,math,width){const resolvedTone=event.tone??statusTones[event.status??"dot"];const accent=getToneColor(resolvedTone,c);const accentText=getReadableToneColor(resolvedTone,c);const resolvedWidth=event.width??width;return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:5,...resolvedWidth!=null?{width:resolvedWidth}:{},...typeof resolvedWidth==="string"?{minWidth:0}:{},padding:"10px 12px",borderRadius:8,border:`1px solid ${withColorAlpha(accent,68/255)}`,backgroundColor:c.bgCard,boxShadow:`0 7px 18px ${c.shadow}`,boxSizing:"border-box"}},...compactChildren([event.time!=null&&React5.createElement("div",{style:{display:"flex",color:accentText,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:900,lineHeight:1.15,textTransform:"uppercase",letterSpacing:"0.04em"}},renderMaybeMath(event.time,math)),React5.createElement("div",{style:{display:"flex",color:c.textPrimary,fontFamily:"Inter",fontSize:14,fontWeight:900,lineHeight:1.18,...textFitStyle()}},renderMaybeMath(event.title,math)),event.detail!=null&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35,...textFitStyle()}},renderMaybeMath(event.detail,math))]))}function Timeline({events,c,title,subtitle,direction="vertical",width,eventWidth,gap=12,markerSize=14,math=false}){const header=(title!=null||subtitle!=null)&&React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:"100%"}},...compactChildren([title!=null&&React5.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,fontFamily:"Inter",fontSize:16,fontWeight:900,lineHeight:1.2}},ToneStrip({tone:events[0]?.tone??"blue"}),renderMaybeMath(title,math)),subtitle!=null&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));if(direction==="horizontal"){return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React5.createElement("div",{style:{display:"flex",alignItems:"stretch",gap:0,width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React5.createElement("div",{key:`timeline-h-${index}`,style:{display:"flex",flexDirection:"column",gap:8,...eventWidth==null?{flex:1}:{},...(event.width??eventWidth)!=null?{width:event.width??eventWidth}:{},minWidth:0}},React5.createElement("div",{style:{display:"flex",alignItems:"center",width:"100%"}},React5.createElement("div",{style:{display:"flex",flex:1,height:2,backgroundColor:c.borderLight,opacity:index===0?0:1}}),React5.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,border:`3px solid ${c.bg}`,boxShadow:`0 0 0 1px ${accent}`,flexShrink:0}}),React5.createElement("div",{style:{display:"flex",flex:1,height:2,backgroundColor:c.borderLight,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math,eventWidth))}))]))}return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap,width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React5.createElement("div",{key:`timeline-v-${index}`,style:{display:"flex",alignItems:"stretch",gap:11,width:"100%"}},React5.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:markerSize+8,flexShrink:0}},React5.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:2,backgroundColor:c.borderLight,opacity:index===0?0:1}}),React5.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,border:`3px solid ${c.bg}`,boxShadow:`0 0 0 1px ${accent}`,flexShrink:0}}),React5.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:2,backgroundColor:c.borderLight,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math))}))]))}function renderFlowStage(stage,c,math){const tone=stage.tone??"blue";const hasDetails=Boolean(stage.children||stage.lines?.length);if(!hasDetails){return StepCard({title:stage.title,subtitle:stage.subtitle,eyebrow:stage.eyebrow,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding,math})}return Panel({title:stage.title,subtitle:stage.subtitle,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding??12,bodyStyle:{gap:8},children:stage.children??DetailList({items:stage.lines??[],c,tone,math})})}function Flow({stages,c,direction="horizontal",gap=10,connectorLength=28,connectorTone="neutral",align="center",math=false}){const isHorizontal=direction==="horizontal";const children=stages.flatMap((stage,index)=>{const elements=[React5.createElement(React5.Fragment,{key:`stage-${index}`},renderFlowStage(stage,c,math))];if(index<stages.length-1){elements.push(React5.createElement(React5.Fragment,{key:`connector-${index}`},FlowArrow({direction:isHorizontal?"right":"down",length:connectorLength,c,tone:connectorTone})))}return elements});return(isHorizontal?Row:Column)({gap,align,justify:"center",children})}import React6 from"react";import dagre from"@dagrejs/dagre";import{cloneElement,isValidElement}from"react";var SVG_ACCESSIBILITY_COMPONENT=Symbol.for("vizmatic.svgAccessibilityComponent");function componentHasSvgMetadata(type){return typeof type==="function"&&type[SVG_ACCESSIBILITY_COMPONENT]===true}function svgToken(value){if(value.length===0)return"empty";return Array.from(value,character=>{const codePoint=character.codePointAt(0)??0;return/^[A-Za-z0-9.-]$/.test(character)?character:`_u${codePoint.toString(16)}_`}).join("")}function textProperty(props,name){const value=props[name];return typeof value==="string"?value:""}function encodedTextProperty(props,name){const value=textProperty(props,name);try{return decodeURIComponent(value)}catch{return value}}function prepareAccessibleSvg(element){const graphs=[];const explicitIds=new Set;const visit=(node,graph)=>{if(Array.isArray(node))return node.map(child=>visit(child,graph));if(!isValidElement(node))return node;const component=node.type;if(componentHasSvgMetadata(component)){return visit(component(node.props),graph)}const props=node.props;const title=textProperty(props,"data-vizmatic-svg-title");const isGraphRoot=title.length>0;let activeGraph=graph;let elementKey=node.key;if(isGraphRoot){const explicitId=textProperty(props,"data-vizmatic-svg-id");if(explicitId){if(explicitIds.has(explicitId)){throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`)}explicitIds.add(explicitId)}const index=graphs.length;const token=explicitId?`id-${svgToken(explicitId)}`:`index-${index}`;activeGraph={index,token,detectionKey:`vizmatic-graph-${index}`,title,description:textProperty(props,"data-vizmatic-svg-description"),nodes:[],edges:[]};graphs.push(activeGraph);elementKey=activeGraph.detectionKey}let nextProps;if(activeGraph&&Object.hasOwn(props,"data-vizmatic-graph-node-id")){const id=textProperty(props,"data-vizmatic-graph-node-id");const label=textProperty(props,"data-vizmatic-graph-node-label")||id;const detail=textProperty(props,"data-vizmatic-graph-node-detail");activeGraph.nodes.push({id,label,detail,title:textProperty(props,"data-vizmatic-graph-node-title")||label,href:textProperty(props,"data-vizmatic-graph-node-href")||void 0});elementKey=`${activeGraph.detectionKey}-node-${svgToken(id)}`}else if(activeGraph&&textProperty(props,"data-vizmatic-graph-edge-id")){const id=encodedTextProperty(props,"data-vizmatic-graph-edge-id");activeGraph.edges.push({id,from:encodedTextProperty(props,"data-vizmatic-graph-edge-from"),to:encodedTextProperty(props,"data-vizmatic-graph-edge-to"),label:encodedTextProperty(props,"data-vizmatic-graph-edge-label"),title:encodedTextProperty(props,"data-vizmatic-graph-edge-title"),path:textProperty(props,"d"),href:encodedTextProperty(props,"data-vizmatic-graph-edge-href")||void 0});elementKey=`${activeGraph.detectionKey}-edge-${svgToken(id)}`}const children=props.children;if(children===void 0){if(isGraphRoot){nextProps={...props,"data-vizmatic-svg-instance":activeGraph?.token};return cloneElement(node,{...nextProps,key:elementKey})}return node}const preparedChildren=visit(children,activeGraph);nextProps=isGraphRoot?{...props,"data-vizmatic-svg-instance":activeGraph?.token}:{...props};return cloneElement(node,{...nextProps,key:elementKey},preparedChildren)};return{element:visit(element),graphs}}function escapeXml(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function attribute(name,value){return`${name}="${escapeXml(value)}"`}function graphBaseId(graph){return`vizmatic-graph-${graph.token}`}function nodeId(graph,node){return`${graphBaseId(graph)}-node-${svgToken(node.id)}`}function edgeId(graph,edge){return`${graphBaseId(graph)}-edge-${svgToken(edge.id)}`}function labelForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return edge.title||(edge.label?`${from} to ${to}: ${edge.label}`:`${from} to ${to}`)}function descriptionForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return`Relationship from ${from} to ${to}${edge.label?`, labeled ${edge.label}`:""}.`}function nodeGroup(graph,node,layout){const id=nodeId(graph,node);const label=node.detail?`${node.label}: ${node.detail}`:node.label;const description=node.detail||node.label;const titleId=`${id}-title`;const descriptionId=`${id}-description`;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>`;if(!layout)return`${accessible}</g>`;const rect=`<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;const hitTarget=node.href?`<a ${attribute("href",node.href)} role="link" tabindex="0" ${attribute("aria-label",label)}>${rect}</a>`:rect;return`${accessible}${hitTarget}</g>`}function edgeGroup(graph,edge,root){const id=edgeId(graph,edge);const title=labelForEdge(graph,edge);const titleId=`${id}-title`;const descriptionId=`${id}-description`;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>`;if(!root||!edge.path)return`${accessible}</g>`;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"/>`;const hitTarget=edge.href?`<a ${attribute("href",edge.href)} role="link" tabindex="0" ${attribute("aria-label",title)}>${path}</a>`:path;return`${accessible}${hitTarget}</g>`}function addSvgAccessibility(svg,graphs,layoutNodes){if(graphs.length===0)return svg;const title=graphs.map(graph=>graph.title).join(". ");const description=graphs.map(graph=>`${graph.title}. ${graph.description}`).join(" ");const hasLinks=graphs.some(graph=>graph.nodes.some(node=>node.href)||graph.edges.some(edge=>edge.href));const rootTitleId="vizmatic-svg-title";const rootDescriptionId="vizmatic-svg-description";const groupMarkup=graphs.map(graph=>{const baseId=graphBaseId(graph);const titleId=`${baseId}-title`;const descriptionId=`${baseId}-description`;const root=layoutNodes.find(node=>node.key===graph.detectionKey);const nodes=graph.nodes.map(item=>{const layout=layoutNodes.find(node=>node.key===`${graph.detectionKey}-node-${svgToken(item.id)}`);if(item.href&&!layout){throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`)}return nodeGroup(graph,item,layout)}).join("");const edges=graph.edges.map(item=>{if(item.href&&!root){throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`)}return edgeGroup(graph,item,root)}).join("");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>`}).join("");const metadata=`<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>`<svg${attrs} role="${hasLinks?"group":"img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`).replace(/<\/svg>\s*$/,`${groupMarkup}</svg>`)}var EPSILON=.001;var MAX_GRID_POINTS=18e3;var MAX_SEARCH_STATES=54e3;var MAX_TOTAL_SEARCH_STATES=16e4;var MAX_ROUTED_EDGES=256;var MAX_OBSTACLES=64;var sides=["right","bottom","left","top"];function box(node,clearance=0){return{left:node.cx-node.width/2-clearance,right:node.cx+node.width/2+clearance,top:node.cy-node.height/2-clearance,bottom:node.cy+node.height/2+clearance}}function inside(point,obstacle){return point.x>obstacle.left+EPSILON&&point.x<obstacle.right-EPSILON&&point.y>obstacle.top+EPSILON&&point.y<obstacle.bottom-EPSILON}function routingSegmentBlocked(a,b,obstacle){if(Math.abs(a.y-b.y)<EPSILON){return a.y>obstacle.top+EPSILON&&a.y<obstacle.bottom-EPSILON&&Math.max(a.x,b.x)>obstacle.left+EPSILON&&Math.min(a.x,b.x)<obstacle.right-EPSILON}if(Math.abs(a.x-b.x)<EPSILON){return a.x>obstacle.left+EPSILON&&a.x<obstacle.right-EPSILON&&Math.max(a.y,b.y)>obstacle.top+EPSILON&&Math.min(a.y,b.y)<obstacle.bottom-EPSILON}return true}function preferredSide(from,to){if(Math.abs(to.cx-from.cx)>=Math.abs(to.cy-from.cy))return to.cx>=from.cx?"right":"left";return to.cy>=from.cy?"bottom":"top"}function routingAnchor(node,side,offset=.5){const bounds=box(node);if(side==="left"||side==="right")return{x:bounds[side],y:bounds.top+node.height*offset};return{x:bounds.left+node.width*offset,y:bounds[side]}}function outward(point,side,distance){return{x:point.x+(side==="right"?distance:side==="left"?-distance:0),y:point.y+(side==="bottom"?distance:side==="top"?-distance:0)}}function simplify(points){const result=[];for(const point of points){const last=result[result.length-1];if(last&&Math.abs(last.x-point.x)<EPSILON&&Math.abs(last.y-point.y)<EPSILON)continue;const previous=result[result.length-2];if(previous&&last&&(previous.x===last.x&&last.x===point.x||previous.y===last.y&&last.y===point.y)){result[result.length-1]=point}else result.push(point)}return result}function overlappingLength(a,b,c,d){if(a.y===b.y&&c.y===d.y&&Math.abs(a.y-c.y)<EPSILON){return Math.max(0,Math.min(Math.max(a.x,b.x),Math.max(c.x,d.x))-Math.max(Math.min(a.x,b.x),Math.min(c.x,d.x)))}if(a.x===b.x&&c.x===d.x&&Math.abs(a.x-c.x)<EPSILON){return Math.max(0,Math.min(Math.max(a.y,b.y),Math.max(c.y,d.y))-Math.max(Math.min(a.y,b.y),Math.min(c.y,d.y)))}return 0}var MinQueue=class{items=[];get length(){return this.items.length}push(value){const items=this.items;items.push(value);let index=items.length-1;while(index>0){const parent=index-1>>1;if(items[parent].priority<=value.priority)break;items[index]=items[parent];index=parent}items[index]=value}pop(){const items=this.items;const first=items[0];const last=items.pop();if(items.length===0)return first;let index=0;while(index*2+1<items.length){const left=index*2+1;const right=left+1;const child=right<items.length&&items[right].priority<items[left].priority?right:left;if(items[child].priority>=last.priority)break;items[index]=items[child];index=child}items[index]=last;return first}};function findPath(start,end,obstacles,width,height,previousRoutes,gap,budget){const within=point=>point.x>=0&&point.x<=width&&point.y>=0&&point.y<=height;if(!within(start)||!within(end)||obstacles.some(obstacle=>inside(start,obstacle)||inside(end,obstacle))){return{reason:"an endpoint has no clear exit inside the canvas"}}const xs=new Set([0,width,start.x,end.x]);const ys=new Set([0,height,start.y,end.y]);for(const obstacle of obstacles){if(obstacle.left>=0&&obstacle.left<=width)xs.add(obstacle.left);if(obstacle.right>=0&&obstacle.right<=width)xs.add(obstacle.right);if(obstacle.top>=0&&obstacle.top<=height)ys.add(obstacle.top);if(obstacle.bottom>=0&&obstacle.bottom<=height)ys.add(obstacle.bottom)}for(const route of previousRoutes.slice(-8))for(const point of route){for(const offset of[-gap,gap]){if(point.x+offset>=0&&point.x+offset<=width)xs.add(point.x+offset);if(point.y+offset>=0&&point.y+offset<=height)ys.add(point.y+offset)}}const xValues=[...xs].sort((a,b)=>a-b);const yValues=[...ys].sort((a,b)=>a-b);const columns=xValues.length;const gridSize=columns*yValues.length;if(gridSize>MAX_GRID_POINTS)return{reason:`routing grid exceeds ${MAX_GRID_POINTS} points; simplify the graph`};const startIndex=yValues.indexOf(start.y)*columns+xValues.indexOf(start.x);const endIndex=yValues.indexOf(end.y)*columns+xValues.indexOf(end.x);const pointAt=index=>({x:xValues[index%columns],y:yValues[Math.floor(index/columns)]});const costs=new Float64Array(gridSize*3).fill(Infinity);const parents=new Int32Array(gridSize*3).fill(-1);const queue=new MinQueue;costs[startIndex*3]=0;queue.push({state:startIndex*3,cost:0,priority:0});let visits=0;while(queue.length>0){if(--budget.remaining<0)return{reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`};if(++visits>MAX_SEARCH_STATES)return{reason:`routing search exceeds ${MAX_SEARCH_STATES} states; simplify the graph`};const current=queue.pop();if(current.cost!==costs[current.state])continue;const index=Math.floor(current.state/3);const axis=current.state%3;if(index===endIndex){const points=[];for(let state=current.state;state>=0;state=parents[state])points.push(pointAt(Math.floor(state/3)));return{points:simplify(points.reverse())}}const a=pointAt(index);const column=index%columns;const row=Math.floor(index/columns);const neighbors=[column>0?index-1:-1,column<columns-1?index+1:-1,row>0?index-columns:-1,row<yValues.length-1?index+columns:-1];for(const neighbor of neighbors){if(neighbor<0)continue;const b=pointAt(neighbor);if(obstacles.some(obstacle=>routingSegmentBlocked(a,b,obstacle)))continue;const nextAxis=a.y===b.y?1:2;const state=neighbor*3+nextAxis;let overlap=0;for(const route of previousRoutes)for(let i=1;i<route.length;i++)overlap+=overlappingLength(a,b,route[i-1],route[i]);const cost=current.cost+Math.abs(b.x-a.x)+Math.abs(b.y-a.y)+(axis!==0&&axis!==nextAxis?18:0)+overlap*5;if(cost>=costs[state])continue;costs[state]=cost;parents[state]=current.state;queue.push({state,cost,priority:cost+Math.abs(end.x-b.x)+Math.abs(end.y-b.y)})}}return{reason:"no obstacle-free route exists inside the canvas"}}function endpoint(node,other,portId,requestedSide,selfLoop,target,ordinal,count,gap){const port=node.ports?.find(candidate=>candidate.id===portId);const side=port?.side??requestedSide??(selfLoop?target?"top":"right":preferredSide(node,other));const length=side==="left"||side==="right"?node.height:node.width;const separation=count>1?Math.min(gap,length*.7/(count-1)):0;const offset=port?port.offset??.5:.5+(ordinal-(count-1)/2)*separation/length;return{side,anchor:routingAnchor(node,side,offset),explicit:portId!=null||requestedSide!=null}}function straightGraphRoute(from,to,edge){return[endpoint(from,to,edge.fromPort,edge.fromSide,false,false,0,1,0).anchor,endpoint(to,from,edge.toPort,edge.toSide,false,true,0,1,0).anchor]}function routeOrthogonalGraph(nodes,edges,width,height,clearance=12,gap=14,extraObstacles=[]){const routes=new Map;const failures=[];const byId=new Map(nodes.map(node=>[node.id,node]));const obstacles=[...nodes.map(node=>box(node,clearance)),...extraObstacles.map(obstacle=>({left:obstacle.left-clearance,right:obstacle.right+clearance,top:obstacle.top-clearance,bottom:obstacle.bottom+clearance}))];const routeKey=edge=>[edge.from,edge.to].sort().join("\0");const counts2=new Map;for(const edge of edges)counts2.set(routeKey(edge),(counts2.get(routeKey(edge))??0)+1);const occurrences=new Map;const previous=new Map;const budget={remaining:MAX_TOTAL_SEARCH_STATES};edges.forEach((edge,index)=>{if(index>=MAX_ROUTED_EDGES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_ROUTED_EDGES} edges per diagram`});return}if(obstacles.length>MAX_OBSTACLES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_OBSTACLES} node and header obstacles per diagram`});return}if(budget.remaining<0){failures.push({index,reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`});return}const from=byId.get(edge.from);const to=byId.get(edge.to);const key=routeKey(edge);const ordinal=occurrences.get(key)??0;occurrences.set(key,ordinal+1);const count=counts2.get(key)??1;const source=endpoint(from,to,edge.fromPort,edge.fromSide,from===to,false,ordinal,count,gap);const target=endpoint(to,from,edge.toPort,edge.toSide,from===to,true,ordinal,count,gap);const sourceSides=source.explicit?[source.side]:[source.side,...sides.filter(side=>side!==source.side)];const targetSides=target.explicit?[target.side]:[target.side,...sides.filter(side=>side!==target.side)];let failure="no obstacle-free route exists inside the canvas";for(const sourceSide of sourceSides){for(const targetSide of targetSides){const start=sourceSide===source.side?source.anchor:routingAnchor(from,sourceSide);const end=targetSide===target.side?target.anchor:routingAnchor(to,targetSide);if(from===to&&start.x===end.x&&start.y===end.y){failure="a self-loop requires distinct endpoint anchors";continue}const leadStart=outward(start,sourceSide,clearance);const leadEnd=outward(end,targetSide,clearance);if(obstacles.some((obstacle,obstacleIndex)=>obstacleIndex!==nodes.indexOf(from)&&routingSegmentBlocked(start,leadStart,obstacle)||obstacleIndex!==nodes.indexOf(to)&&routingSegmentBlocked(leadEnd,end,obstacle))){failure="another obstacle blocks an endpoint exit";continue}const result=findPath(leadStart,leadEnd,obstacles,width,height,previous.get(key)??[],Math.max(1,gap),budget);if(!result.points){failure=result.reason;if(/routing (grid|search|budget)/.test(failure)){failures.push({index,reason:failure});return}continue}const points=simplify([start,...result.points,end]);if(points.length<2)continue;const repeated=(previous.get(key)??[]).some(route=>route.length===points.length&&(route.every((point,position)=>point.x===points[position].x&&point.y===points[position].y)||route.every((point,position)=>point.x===points[points.length-1-position].x&&point.y===points[points.length-1-position].y)));if(repeated){failure="parallel connectors have no separate lane at the requested clearance";continue}routes.set(index,points);previous.set(key,[...previous.get(key)??[],points]);return}}failures.push({index,reason:failure})});return{routes,failures}}function routingLabelPosition(points){let longest=0;let position=points[0];for(let i=1;i<points.length;i++){const a=points[i-1];const b=points[i];const length=Math.abs(a.x-b.x)+Math.abs(a.y-b.y);if(length>longest){longest=length;position={x:(a.x+b.x)/2,y:(a.y+b.y)/2}}}return position}function distributeValues(count,start,end){if(count<=0)return[];if(count===1)return[(start+end)/2];const step=(end-start)/(count-1);return Array.from({length:count},(_,index)=>start+index*step)}function LayeredNetwork({c,layers,ariaLabel="Layered network diagram",activePath=[],annotations=[],formula,legend="highlighted path",width=900,height=400,nodeSize=56,showFormula=true}){const radius=nodeSize/2;const top=82;const bottom=showFormula||formula?height-118:height-42;const layerXs=distributeValues(layers.length,82,width-82);const nodeLayout=layers.map((layer,layerIndex)=>({...layer,x:layerXs[layerIndex],ys:distributeValues(layer.nodes.length,top,bottom),tone:layer.tone??"purple"}));const connectionElements=nodeLayout.slice(0,-1).flatMap((from,layerIndex)=>{const to=nodeLayout[layerIndex+1];return from.ys.flatMap((fromY,fromIndex)=>to.ys.map((toY,toIndex)=>{const active=activePath[layerIndex]===fromIndex&&activePath[layerIndex+1]===toIndex;return React6.createElement("line",{key:`connection-${layerIndex}-${fromIndex}-${toIndex}`,x1:from.x+radius+4,y1:fromY,x2:to.x-radius-4,y2:toY,stroke:active?c.warningLight:c.borderLight,strokeWidth:active?3.6:1.2,strokeOpacity:active?.98:.42,strokeLinecap:"round"})}))});const label=(key,text,x,y,labelWidth,color,fontSize=13,fontWeight=800,fontFamily="Inter")=>React6.createElement("div",{key,style:{position:"absolute",left:x-labelWidth/2,top:y,width:labelWidth,display:"flex",justifyContent:"center",color,fontSize,fontWeight,fontFamily,lineHeight:1.15,textAlign:"center"}},formatMathText(text));const titleElements=nodeLayout.map(layer=>label(`title-${layer.title}`,layer.title,layer.x,20,120,getReadableToneColor(layer.tone,c),16,900));const nodeElements=nodeLayout.flatMap((layer,layerIndex)=>layer.ys.flatMap((y,nodeIndex)=>{const active=activePath[layerIndex]===nodeIndex;const color=getToneColor(layer.tone,c);return[active&&React6.createElement("div",{key:`halo-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius-14,top:y-radius-14,width:nodeSize+28,height:nodeSize+28,borderRadius:999,backgroundColor:withColorAlpha(c.warningLight,46/255),border:`4px solid ${c.warningLight}`,boxSizing:"border-box",boxShadow:`0 0 18px ${withColorAlpha(c.warningLight,102/255)}`}}),React6.createElement("div",{key:`node-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius,top:y-radius,width:nodeSize,height:nodeSize,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,color:getReadableTextColor(color,c),border:active?`3px solid ${c.warningLight}`:`1.5px solid ${color}`,boxSizing:"border-box",boxShadow:active?`0 0 16px ${withColorAlpha(c.warningLight,112/255)}`:`0 8px 14px ${c.shadow}`,fontFamily:"JetBrains Mono",fontSize:16,fontWeight:900,lineHeight:1}},formatMathText(layer.nodes[nodeIndex]))]}).filter(Boolean));const annotationY=showFormula||formula?height-84:height-26;const annotationElements=annotations.slice(0,Math.max(0,layerXs.length-1)).map((annotation,index)=>label(`annotation-${index}`,annotation,(layerXs[index]+layerXs[index+1])/2,annotationY,132,c.textMuted,13,800,"JetBrains Mono"));const formulaElement=(showFormula||formula)&&formula?React6.createElement("div",{key:"formula-wrap",style:{position:"absolute",left:width/2-244,top:height-52,width:488,height:44,borderRadius:10,border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard,display:"flex",alignItems:"center",justifyContent:"center",color:c.textPrimary,fontFamily:"Inter",fontSize:15,fontWeight:850,boxShadow:`0 8px 18px ${c.shadow}`}},formatMathText(formula)):null;const legendElement=(showFormula||formula)&&formula?React6.createElement("div",{key:"legend-wrap",style:{position:"absolute",left:width-184,top:height-43,width:160,display:"flex",alignItems:"center",gap:14,color:c.textSecondary,fontFamily:"Inter",fontSize:12,fontWeight:800}},React6.createElement("div",{style:{width:42,height:5,borderRadius:999,backgroundColor:c.warningLight}}),legend):null;return React6.createElement("div",{role:"img","aria-label":ariaLabel,style:{width,height,maxWidth:"100%",position:"relative",display:"flex",alignSelf:"center",flexShrink:0}},React6.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,style:{position:"absolute",inset:0,overflow:"visible"}},...connectionElements),...titleElements,...nodeElements,...annotationElements,formulaElement,legendElement)}function defineDiagramIcon(id,render){return{id,render}}function defineIconRegistry(icons){return icons}function manualGraphLayout(nodes,width,height,nodeWidth,nodeHeight,padding){return new Map(nodes.map(node=>{const resolvedWidth=node.width??nodeWidth;const resolvedHeight=node.height??nodeHeight;const minCx=resolvedWidth/2;const maxCx=width-resolvedWidth/2;const minCy=resolvedHeight/2;const maxCy=height-resolvedHeight/2;const requestedCx=padding+clamp(node.x??.5,0,1)*(width-padding*2);const requestedCy=padding+clamp(node.y??.5,0,1)*(height-padding*2);return[node.id,{...node,width:resolvedWidth,height:resolvedHeight,cx:minCx<=maxCx?clamp(requestedCx,minCx,maxCx):width/2,cy:minCy<=maxCy?clamp(requestedCy,minCy,maxCy):height/2}]}))}function segmentCrosses(a1,a2,b1,b2){const cross=(origin,first,second)=>(first.x-origin.x)*(second.y-origin.y)-(first.y-origin.y)*(second.x-origin.x);const d1=cross(a1,a2,b1);const d2=cross(a1,a2,b2);const d3=cross(b1,b2,a1);const d4=cross(b1,b2,a2);const epsilon=.01;return d1*d2<-epsilon&&d3*d4<-epsilon}function connectorCrossings(edges){let crossings=0;for(let leftIndex=0;leftIndex<edges.length;leftIndex+=1){const left=edges[leftIndex];for(let rightIndex=leftIndex+1;rightIndex<edges.length;rightIndex+=1){const right=edges[rightIndex];if(left.from===right.from||left.from===right.to||left.to===right.from||left.to===right.to)continue;let crosses=false;for(let leftSegment=0;leftSegment<left.points.length-1&&!crosses;leftSegment+=1){for(let rightSegment=0;rightSegment<right.points.length-1;rightSegment+=1){if(segmentCrosses(left.points[leftSegment],left.points[leftSegment+1],right.points[rightSegment],right.points[rightSegment+1])){crosses=true;break}}}if(crosses)crossings+=1}}return crossings}function rectanglesOverlap(left,right,padding=0){return left.left<right.right+padding&&left.right>right.left-padding&&left.top<right.bottom+padding&&left.bottom>right.top-padding}function connectorLabelCollisions(edges,nodes,groups=[]){const labels=edges.flatMap(edge=>edge.label?[{bounds:{left:edge.labelX-estimatedEdgeLabelWidth(edge.label)/2,right:edge.labelX+estimatedEdgeLabelWidth(edge.label)/2,top:edge.labelY-10,bottom:edge.labelY+10}}]:[]);let collisions=0;for(let index=0;index<labels.length;index+=1){for(let otherIndex=index+1;otherIndex<labels.length;otherIndex+=1){if(rectanglesOverlap(labels[index].bounds,labels[otherIndex].bounds,4))collisions+=1}for(const node of nodes.values()){const bounds={left:node.cx-node.width/2,right:node.cx+node.width/2,top:node.cy-node.height/2,bottom:node.cy+node.height/2};if(rectanglesOverlap(labels[index].bounds,bounds))collisions+=1}for(const group of groups){const headerBounds={left:group.cx-group.width/2,right:group.cx+group.width/2,top:group.cy-group.height/2,bottom:group.cy-group.height/2+26};if(rectanglesOverlap(labels[index].bounds,headerBounds))collisions+=1}}return collisions}function crowdedConnectorEndpoints(edges){const degrees=new Map;for(const edge of edges){degrees.set(edge.from,(degrees.get(edge.from)??0)+1);degrees.set(edge.to,(degrees.get(edge.to)??0)+1)}return Array.from(degrees.values()).filter(degree=>degree>4).length}function parallelConnectorGroups(edges){const routes=new Map;for(const edge of edges){const key=`${edge.from}\0${edge.to}`;routes.set(key,(routes.get(key)??0)+1)}return Array.from(routes.values()).filter(count=>count>1).length}function edgePath(points){return points.map((point,index)=>`${index===0?"M":"L"} ${point.x} ${point.y}`).join(" ")}function estimatedEdgeLabelWidth(label){const units=Array.from(label.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0);return Math.max(28,Math.ceil(units*6+14))}function validateGraphDiagramSpec(nodes,edges,groups,layoutMode){const nodeIds=new Set;for(const node of nodes){if(nodeIds.has(node.id))throw new Error(`GraphDiagram received duplicate node id "${node.id}".`);nodeIds.add(node.id);const portIds=new Set;for(const port of node.ports??[]){if(typeof port.id!=="string"||port.id.trim().length===0){throw new Error(`GraphDiagram node "${node.id}" port id must be a non-empty string.`)}if(portIds.has(port.id))throw new Error(`GraphDiagram node "${node.id}" received duplicate port "${port.id}".`);portIds.add(port.id);if(!["top","right","bottom","left"].includes(port.side)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" must use side "top", "right", "bottom", or "left".`)}if(port.offset!=null&&(!Number.isFinite(port.offset)||port.offset<0||port.offset>1)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" offset must be between 0 and 1.`)}}}const groupsById=new Map;for(const group of groups){if(nodeIds.has(group.id)||groupsById.has(group.id)){throw new Error(`GraphDiagram node and group ids must be unique; received duplicate id "${group.id}".`)}groupsById.set(group.id,group)}for(const group of groups){if(group.parent!=null&&!groupsById.has(group.parent)){throw new Error(`GraphDiagram group "${group.id}" references missing parent group "${group.parent}".`)}const visited=new Set([group.id]);let parent=group.parent;while(parent!=null){if(visited.has(parent))throw new Error(`GraphDiagram groups contain a parent cycle at "${parent}".`);visited.add(parent);parent=groupsById.get(parent)?.parent}}const occupiedGroups=new Set;for(const node of nodes){if(node.group!=null&&!groupsById.has(node.group)){throw new Error(`GraphDiagram node "${node.id}" references missing group "${node.group}".`)}let groupId=node.group;while(groupId!=null){occupiedGroups.add(groupId);groupId=groupsById.get(groupId)?.parent}}for(const group of groups){if(!occupiedGroups.has(group.id))throw new Error(`GraphDiagram group "${group.id}" contains no nodes.`)}const edgeIds=new Set;for(const edge of edges){if(!nodeIds.has(edge.from)||!nodeIds.has(edge.to)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}if(edge.id!=null){if(edgeIds.has(edge.id))throw new Error(`GraphDiagram received duplicate edge id "${edge.id}".`);edgeIds.add(edge.id)}for(const side of["from","to"]){const reference=side==="from"?edge.fromPort:edge.toPort;const endpointSide=side==="from"?edge.fromSide:edge.toSide;const node=nodes.find(candidate=>candidate.id===edge[side]);if(reference!=null&&!node.ports?.some(port=>port.id===reference)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references missing ${side} port "${reference}" on node "${node.id}".`)}if(endpointSide!=null&&!["top","right","bottom","left"].includes(endpointSide)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" ${side}Side must be "top", "right", "bottom", or "left".`)}if(reference!=null&&endpointSide!=null){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" cannot combine ${side}Port and ${side}Side.`)}}validateDiagramHref(edge.href,`edge "${edge.id??`${edge.from}" -> "${edge.to}`}"`)}for(const node of nodes){validateDiagramHref(node.href,`node "${node.id}"`)}if(groups.length>0&&layoutMode==="manual"){throw new Error('GraphDiagram groups require automatic layout; omit node coordinates and layout="manual".')}}function validateDiagramHref(href,owner){if(href==null)return;const normalized=href.trim().replace(/[\u0000-\u0020\u007f]/g,"");const scheme=/^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1]?.toLowerCase();if(scheme&&!["http","https","mailto","tel"].includes(scheme)){throw new Error(`GraphDiagram ${owner} has an unsupported link scheme "${scheme}:".`)}}function graphAccessibleText(value){if(typeof value==="string"||typeof value==="number")return String(value).trim();if(Array.isArray(value))return value.map(graphAccessibleText).filter(Boolean).join(" ");if(React6.isValidElement(value)){const props=value.props;return graphAccessibleText(props.children)}return""}function graphDescription(nodes,edges){const labels=new Map(nodes.map(node=>[node.id,graphAccessibleText(node.label)||node.id]));const parts=[`${nodes.length} nodes and ${edges.length} relationships.`];const relationships=edges.slice(0,8).map(edge=>{const from=labels.get(edge.from)??edge.from;const to=labels.get(edge.to)??edge.to;return edge.label?`${from} ${edge.label} ${to}`:`${from} to ${to}`});if(relationships.length)parts.push(relationships.join("; "));if(edges.length>relationships.length)parts.push(`${edges.length-relationships.length} more relationships`);return parts.join(" ")}function graphGroupDepth(group,groupsById){let depth=0;let parent=group.parent;while(parent!=null){depth+=1;parent=groupsById.get(parent)?.parent}return depth}function resolvedGraphEdgeStyle(edge){if(edge.style)return edge.style;if(edge.dashed)return"dashed";if(edge.kind==="async"||edge.kind==="dependency")return"dashed";if(edge.kind==="event")return"dotted";return"solid"}function resolvedGraphEdgeArrow(edge){return edge.arrow??(edge.kind==="association"?"none":"forward")}function GraphDiagram({nodes,edges,groups=[],c,width,height,nodeWidth=150,nodeHeight=66,labelFontSize=14,detailFontSize=11,arrowSize=5,padding=28,layout:requestedLayout,direction="LR",nodeGap=34,rankGap=64,edgeGap=14,routing="dagre",routingClearance=12,sizing="content",iconSize=20,id,ariaLabel,title,description}){if(id!=null&&id.trim().length===0)throw new Error("GraphDiagram id must not be empty.");if(!["dagre","straight","orthogonal"].includes(routing))throw new Error('GraphDiagram routing must be "dagre", "straight", or "orthogonal".');if(!Number.isFinite(routingClearance)||routingClearance<=0)throw new Error("GraphDiagram routingClearance must be a finite positive number.");const fullyPositioned=nodes.filter(node=>node.x!=null&&node.y!=null).length;const partiallyPositioned=nodes.some(node=>node.x==null!==(node.y==null));if(partiallyPositioned||fullyPositioned>0&&fullyPositioned<nodes.length){throw new Error("GraphDiagram nodes must either all define both x and y, or all omit coordinates for automatic layout.")}const layoutMode=requestedLayout??(fullyPositioned===nodes.length?"manual":"auto");if(layoutMode==="manual"&&fullyPositioned!==nodes.length){throw new Error('GraphDiagram layout="manual" requires x and y on every node.')}validateGraphDiagramSpec(nodes,edges,groups,layoutMode);const edgeOccurrences=new Map;const stableEdgeIds=edges.map(edge=>{if(edge.id!=null)return`custom-${edge.id}`;const route=`${edge.from}\0${edge.to}`;const occurrence=edgeOccurrences.get(route)??0;edgeOccurrences.set(route,occurrence+1);return`route-${edge.from}-to-${edge.to}-${occurrence}`});if(new Set(stableEdgeIds).size!==stableEdgeIds.length){throw new Error("GraphDiagram edge ids must not collide with generated relationship ids.")}const svgTitle=title?.trim()||ariaLabel?.trim()||"Graph diagram";const svgDescription=description??graphDescription(nodes,edges);let resolvedWidth=width??520;let resolvedHeight=height??420;let layout;let groupLayout=[];let autoEdgePoints=new Map;if(layoutMode==="auto"){const compoundGap=groups.length>0?34:0;const graph=new dagre.graphlib.Graph({multigraph:true,compound:groups.length>0}).setGraph({rankdir:direction,nodesep:Math.max(nodeGap,compoundGap),ranksep:Math.max(rankGap,compoundGap),edgesep:edgeGap,marginx:padding,marginy:padding}).setDefaultEdgeLabel(()=>({}));for(const group of groups)graph.setNode(group.id,{width:0,height:0});for(const node of nodes){graph.setNode(node.id,{width:node.width??nodeWidth,height:node.height??nodeHeight})}for(const group of groups){if(group.parent!=null)graph.setParent(group.id,group.parent)}for(const node of nodes){if(node.group!=null)graph.setParent(node.id,node.group)}edges.forEach((edge,index)=>{const labelWidth=edge.label?estimatedEdgeLabelWidth(edge.label):0;graph.setEdge(edge.from,edge.to,{width:labelWidth,height:edge.label?18:0},`edge-${index}`)});dagre.layout(graph);const graphSize=graph.graph();if(sizing==="content"){resolvedWidth=Math.max(width??520,Math.ceil(graphSize.width??0));resolvedHeight=Math.max(height??420,Math.ceil(graphSize.height??0))}const offsetX=(resolvedWidth-(graphSize.width??resolvedWidth))/2;const offsetY=(resolvedHeight-(graphSize.height??resolvedHeight))/2;layout=new Map(nodes.map(node=>{const position=graph.node(node.id);return[node.id,{...node,width:node.width??nodeWidth,height:node.height??nodeHeight,cx:(position?.x??resolvedWidth/2)+offsetX,cy:(position?.y??resolvedHeight/2)+offsetY}]}));const groupsById=new Map(groups.map(group=>[group.id,group]));groupLayout=groups.map(group=>{const position=graph.node(group.id);return{...group,width:position?.width??0,height:position?.height??0,cx:(position?.x??resolvedWidth/2)+offsetX,cy:(position?.y??resolvedHeight/2)+offsetY,depth:graphGroupDepth(group,groupsById)}}).sort((left,right)=>left.depth-right.depth);autoEdgePoints=new Map(edges.map((edge,index)=>{const placed=graph.edge({v:edge.from,w:edge.to,name:`edge-${index}`});const points=(placed?.points??[]).map(point=>({x:point.x+offsetX,y:point.y+offsetY}));return[index,{points,labelX:placed?.x!=null?placed.x+offsetX:points[Math.floor(points.length/2)]?.x??resolvedWidth/2,labelY:placed?.y!=null?placed.y+offsetY:points[Math.floor(points.length/2)]?.y??resolvedHeight/2}]}))}else{layout=manualGraphLayout(nodes,resolvedWidth,resolvedHeight,nodeWidth,nodeHeight,padding)}const anchored=edge=>edge.fromPort!=null||edge.toPort!=null||edge.fromSide!=null||edge.toSide!=null;const orthogonalEdges=edges.flatMap((edge,index)=>routing==="orthogonal"||routing==="dagre"&&anchored(edge)||routing==="straight"&&edge.from===edge.to?[{edge,index}]:[]);const routed=routeOrthogonalGraph(Array.from(layout.values()),orthogonalEdges.map(({edge})=>edge),resolvedWidth,resolvedHeight,routingClearance,edgeGap,groupLayout.map(group=>({left:group.cx-group.width/2,right:group.cx+group.width/2,top:group.cy-group.height/2,bottom:group.cy-group.height/2+26})));const orthogonalPoints=new Map(Array.from(routed.routes,([index,points])=>[orthogonalEdges[index].index,points]));const failedIndexes=new Set(routed.failures.map(failure=>orthogonalEdges[failure.index].index));const routingFailures=routed.failures.map(failure=>{const{edge}=orthogonalEdges[failure.index];return`Connector "${edge.from}" -> "${edge.to}" was not drawn: ${failure.reason}.`});const edgeLayouts=edges.flatMap((edge,index)=>{if(failedIndexes.has(index))return[];const from=layout.get(edge.from);const to=layout.get(edge.to);if(!from||!to)return[];const automatic=autoEdgePoints.get(index);const selfLoop=edge.from===edge.to;if(!selfLoop&&from.cx===to.cx&&from.cy===to.cy&&!automatic?.points.length)return[];const dx=to.cx-from.cx;const dy=to.cy-from.cy;const absDx=Math.abs(dx);const absDy=Math.abs(dy);const fromScale=Math.min(absDx>0?from.width/2/absDx:Infinity,absDy>0?from.height/2/absDy:Infinity);const toScale=Math.min(absDx>0?to.width/2/absDx:Infinity,absDy>0?to.height/2/absDy:Infinity);const color=edge.muted?c.textMuted:c.preset==="engineering"&&edge.tone==null?c.textSecondary:getToneColor(edge.tone??"blue",c);const markerId=`graph-arrow-${edge.from}-${edge.to}-${index}-${arrowSize}-${color}`.replace(/[^a-zA-Z0-9_-]/g,"-");const loopClearance=Math.max(24,arrowSize*5);const manualLoopPoints=selfLoop?[{x:from.cx+from.width/2,y:from.cy-8},{x:from.cx+from.width/2+loopClearance,y:from.cy-8},{x:from.cx+from.width/2+loopClearance,y:from.cy-from.height/2-loopClearance},{x:from.cx+10,y:from.cy-from.height/2-loopClearance},{x:from.cx+10,y:from.cy-from.height/2}]:void 0;const routedPoints=orthogonalPoints.get(index);const points=routedPoints??(routing==="straight"?straightGraphRoute(from,to,edge):automatic?.points.length?automatic.points:manualLoopPoints??[{x:from.cx+dx*fromScale,y:from.cy+dy*fromScale},{x:to.cx-dx*toScale,y:to.cy-dy*toScale}]);const manualLoopLabel=manualLoopPoints?{x:from.cx+from.width/2+loopClearance,y:from.cy-from.height/2-loopClearance/2}:void 0;const routedLabel=routedPoints||routing==="straight"?routingLabelPosition(points):void 0;return[{...edge,index,stableId:stableEdgeIds[index],color,markerId,points,labelX:routedLabel?.x??automatic?.labelX??manualLoopLabel?.x??(points[0].x+points[points.length-1].x)/2,labelY:routedLabel?.y??automatic?.labelY??manualLoopLabel?.y??(points[0].y+points[points.length-1].y)/2}]});const crossings=connectorCrossings(edgeLayouts);const labelCollisions=connectorLabelCollisions(edgeLayouts,layout,groupLayout);const crowdedEndpoints=crowdedConnectorEndpoints(edgeLayouts);const parallelGroups=parallelConnectorGroups(edgeLayouts.filter(edge=>!orthogonalPoints.has(edge.index)));const groupElements=groupLayout.map(group=>{const accent=group.muted?c.textMuted:getToneColor(group.tone??"blue",c);return React6.createElement("div",{key:`graph-group-${group.id}`,"data-vizmatic-graph-group":group.id,style:{position:"absolute",left:group.cx-group.width/2,top:group.cy-group.height/2,width:group.width,height:group.height,display:"flex",boxSizing:"border-box",borderRadius:c.preset==="engineering"?6:12,border:`${c.preset==="engineering"?1.25:1.5}px ${group.muted?"dashed":"solid"} ${withColorAlpha(accent,(group.muted?85:119)/255)}`,backgroundColor:withColorAlpha(accent,(c.preset==="engineering"?8:13)/255),opacity:group.muted?.68:1}},React6.createElement("div",{style:{position:"absolute",left:10,top:5,display:"flex",alignItems:"baseline",gap:7,width:Math.max(0,group.width-20),overflow:"hidden",color:group.muted?c.textMuted:getReadableToneColor(group.tone??"blue",c),fontFamily:c.fontSans,lineHeight:1,whiteSpace:"nowrap"}},React6.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",fontSize:12,fontWeight:800}},group.label),group.detail&&React6.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",color:c.textMuted,fontFamily:c.fontMono,fontSize:11,fontWeight:500}},group.detail)))});return React6.createElement("div",{key:"vizmatic-graph-root",role:"img","aria-label":ariaLabel??svgTitle,"data-vizmatic-svg-title":svgTitle,"data-vizmatic-svg-description":svgDescription,"data-vizmatic-svg-id":id,"data-vizmatic-connector-crossings":crossings,"data-vizmatic-connector-label-collisions":labelCollisions,"data-vizmatic-crowded-connector-endpoints":crowdedEndpoints,"data-vizmatic-parallel-connector-groups":parallelGroups,"data-vizmatic-unrouted-connectors":routingFailures.length,"data-vizmatic-routing-failures":routingFailures.length?JSON.stringify(routingFailures):void 0,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},...groupElements,React6.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React6.createElement("defs",{},...edgeLayouts.map(edge=>ArrowMarkerDef({id:edge.markerId,color:edge.color,size:arrowSize}))),...edgeLayouts.map(edge=>React6.createElement("path",{key:`graph-edge-${edge.index}`,"data-vizmatic-graph-edge-id":encodeURIComponent(edge.stableId),"data-vizmatic-graph-edge-from":encodeURIComponent(edge.from),"data-vizmatic-graph-edge-to":encodeURIComponent(edge.to),"data-vizmatic-graph-edge-label":encodeURIComponent(edge.label??""),"data-vizmatic-graph-edge-title":encodeURIComponent(edge.title??""),"data-vizmatic-graph-edge-href":edge.href==null?void 0:encodeURIComponent(edge.href),d:edgePath(edge.points),fill:"none",stroke:edge.color,strokeWidth:edge.muted?1.4:c.preset==="engineering"?1.7:2.8,strokeDasharray:resolvedGraphEdgeStyle(edge)==="dashed"?"7 6":resolvedGraphEdgeStyle(edge)==="dotted"?"2 6":void 0,strokeLinecap:"round",opacity:edge.muted?.48:.9,markerStart:resolvedGraphEdgeArrow(edge)==="backward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerId})`:void 0,markerEnd:resolvedGraphEdgeArrow(edge)==="forward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerId})`:void 0}))),...edgeLayouts.flatMap(edge=>edge.label?[React6.createElement("div",{key:`graph-edge-label-${edge.index}`,style:{position:"absolute",left:edge.labelX,top:edge.labelY,transform:"translate(-50%, -50%)",padding:c.preset==="engineering"?"3px 5px":"3px 7px",borderRadius:c.preset==="engineering"?0:999,backgroundColor:c.preset==="engineering"?c.bg:c.bgCard,border:c.preset==="engineering"?"none":`1px solid ${c.borderSubtle}`,color:edge.muted?c.textMuted:c.preset==="engineering"?c.textSecondary:getReadableToneColor(edge.tone??"blue",c),fontFamily:c.fontMono,fontSize:11,fontWeight:c.preset==="engineering"?400:800,lineHeight:1,...c.preset==="engineering"?{textTransform:"uppercase",letterSpacing:"0.02em"}:{},whiteSpace:"nowrap"}},edge.label)]:[]),...Array.from(layout.values()).map(node=>{const accent=node.muted?c.textMuted:getToneColor(node.tone??"blue",c);const fill=getToneFill(node.tone??"blue",c);const accentText=node.muted?c.textMuted:getReadableToneColor(node.tone??"blue",c,fill,c.bg);const resolvedIconSize=clamp(node.iconSize??iconSize,8,Math.max(8,Math.min(node.width,node.height)-16));const iconLabel=typeof node.label==="string"?`${node.label} icon`:void 0;const iconElement=typeof node.icon==="string"?Icon({c,name:node.icon,color:accent,size:resolvedIconSize,label:iconLabel,muted:node.muted}):React6.isValidElement(node.icon)?node.icon:node.icon?.render({c,color:accent,size:resolvedIconSize,label:iconLabel});const icon=iconElement&&React6.createElement("div",{"data-vizmatic-graph-icon":node.id,style:{width:resolvedIconSize,height:resolvedIconSize,display:"flex",alignItems:"center",justifyContent:"center",flex:`0 0 ${resolvedIconSize}px`,overflow:"hidden"}},iconElement);return React6.createElement("div",{key:`graph-node-${node.id}`,"data-vizmatic-graph-node-id":node.id,"data-vizmatic-graph-node-label":graphAccessibleText(node.label)||node.id,"data-vizmatic-graph-node-detail":graphAccessibleText(node.detail),"data-vizmatic-graph-node-title":node.title??"","data-vizmatic-graph-node-href":node.href,style:{position:"absolute",left:node.cx-node.width/2,top:node.cy-node.height/2,width:node.width,height:node.height,display:"flex",flexDirection:icon?"row":"column",alignItems:"center",justifyContent:"center",gap:icon?9:node.detail?5:0,padding:"8px 10px",boxSizing:"border-box",borderRadius:c.preset==="engineering"?5:10,backgroundColor:node.muted?c.bgSubtle:fill,border:`${c.preset==="engineering"?1.25:1.5}px solid ${node.muted?c.borderLight:c.preset==="engineering"?accent:withColorAlpha(accent,136/255)}`,...!node.muted&&c.preset!=="engineering"?{boxShadow:`0 8px 18px ${c.shadow}`}:{},opacity:node.muted?.62:1,color:c.preset==="engineering"?c.textPrimary:accentText,textAlign:icon?"left":"center"}},icon,React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:icon?"flex-start":"center",gap:node.detail?5:0,minWidth:0}},React6.createElement("div",{style:{fontFamily:c.fontSans,fontSize:labelFontSize,fontWeight:c.preset==="engineering"?700:900,lineHeight:1.15}},node.label),node.detail&&React6.createElement("div",{style:{color:c.textMuted,fontFamily:c.fontMono,fontSize:detailFontSize,fontWeight:c.preset==="engineering"?400:650,lineHeight:1.2}},node.detail)))}))}Object.defineProperty(GraphDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});function countTreeLeaves(node){if(!node.children?.length)return 1;return node.children.reduce((sum,child)=>sum+countTreeLeaves(child),0)}function maxTreeDepth(node){if(!node.children?.length)return 0;return 1+Math.max(...node.children.map(maxTreeDepth))}function TreeDiagram({root,c,ariaLabel,title,subtitle,width,height,nodeWidth=156,nodeHeight=64,levelGap=58,siblingGap=24,padding=28,math=false}){const explicitIds=new Set;const validateIds=node=>{if(node.id){if(explicitIds.has(node.id))throw new Error(`TreeDiagram received duplicate node id "${node.id}".`);explicitIds.add(node.id)}node.children?.forEach(validateIds)};validateIds(root);const leafCount=Math.max(1,countTreeLeaves(root));const depthCount=maxTreeDepth(root);const resolvedWidth=width??Math.max(520,padding*2+leafCount*nodeWidth+Math.max(0,leafCount-1)*siblingGap);const resolvedHeight=height??padding*2+(depthCount+1)*nodeHeight+depthCount*levelGap;const levelStep=depthCount===0?0:Math.max(nodeHeight+18,(resolvedHeight-padding*2-nodeHeight)/depthCount);const usableWidth=Math.max(0,resolvedWidth-padding*2-nodeWidth);const leafStep=leafCount<=1?0:usableWidth/(leafCount-1);const positioned=[];const edges=[];let nextLeaf=0;const placeWithEdges=(node,depth,path)=>{const children=node.children??[];let centerIndex;const childPlacements=[];if(!children.length){centerIndex=nextLeaf;nextLeaf+=1}else{for(let index=0;index<children.length;index+=1){const child=children[index];childPlacements.push({node:child,index,center:placeWithEdges(child,depth+1,`${path}-${index}`)})}centerIndex=childPlacements.reduce((sum,child)=>sum+child.center,0)/childPlacements.length}const placed={...node,key:node.id??path,depth,cx:leafCount<=1?resolvedWidth/2:padding+nodeWidth/2+centerIndex*leafStep,cy:padding+nodeHeight/2+depth*levelStep};positioned.push(placed);for(const childPlacement of childPlacements){const childKey=childPlacement.node.id??`${path}-${childPlacement.index}`;const childNode=positioned.find(candidate=>candidate.key===childKey);if(childNode)edges.push({key:`${placed.key}-${childNode.key}`,from:placed,to:childNode})}return centerIndex};placeWithEdges(root,0,"root");const header=(title!=null||subtitle!=null)&&React6.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:resolvedWidth,maxWidth:"100%"}},...compactChildren([title!=null&&React6.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:c.textPrimary,fontFamily:"Inter",fontSize:16,fontWeight:900,lineHeight:1.2}},ToneStrip({tone:root.tone??"blue"}),renderMaybeMath(title,math)),subtitle!=null&&React6.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:11,fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));return React6.createElement("div",{style:{display:"flex",flexDirection:"column",gap:header?10:0,width:resolvedWidth,maxWidth:"100%"}},...compactChildren([header,React6.createElement("div",{role:"img","aria-label":ariaLabel??(typeof title==="string"?title:"Tree diagram"),style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},React6.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},...edges.map(edge=>{const tone=edge.to.muted?"neutral":edge.to.tone??edge.from.tone??"blue";const color=edge.to.muted?c.textMuted:getToneColor(tone,c);const startY=edge.from.cy+nodeHeight/2;const endY=edge.to.cy-nodeHeight/2;const midY=startY+(endY-startY)/2;return React6.createElement("path",{key:`tree-edge-${edge.key}`,d:`M ${edge.from.cx} ${startY} C ${edge.from.cx} ${midY}, ${edge.to.cx} ${midY}, ${edge.to.cx} ${endY}`,fill:"none",stroke:color,strokeWidth:edge.to.muted?1.4:2.4,strokeLinecap:"round",opacity:edge.to.muted?.4:.74})})),...positioned.map(node=>{const accent=node.muted?c.textMuted:getToneColor(node.tone??"blue",c);const accentText=node.muted?c.textMuted:getReadableToneColor(node.tone??"blue",c);return React6.createElement("div",{key:`tree-node-${node.key}`,style:{position:"absolute",left:node.cx-nodeWidth/2,top:node.cy-nodeHeight/2,width:nodeWidth,height:nodeHeight,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:node.detail?4:0,padding:"8px 10px",boxSizing:"border-box",borderRadius:8,backgroundColor:node.muted?c.bgSubtle:c.bgCard,border:`1.5px solid ${node.muted?c.borderLight:withColorAlpha(accent,136/255)}`,...!node.muted?{boxShadow:`0 8px 18px ${c.shadow}`}:{},opacity:node.muted?.62:1,color:accentText,textAlign:"center"}},React6.createElement("div",{style:{color:accentText,fontFamily:"Inter",fontSize:13,fontWeight:900,lineHeight:1.15,...textFitStyle("center")}},renderMaybeMath(node.label,math)),node.detail!=null&&React6.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:650,lineHeight:1.2,...textFitStyle("center")}},renderMaybeMath(node.detail,math)))}))]))}function CalloutCard({c,children,title,detail,tone="blue",width,minHeight,padding=12,titleFontSize,detailFontSize,filled=true,align="center"}){const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";const textAlign=align;return React6.createElement("div",{style:{...width!=null?{width}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:10,boxSizing:"border-box",...engineering?{backgroundColor:getToneFill(tone,c),color:c.textPrimary,border:`1px solid ${accent}`}:filled?{backgroundImage:getToneGradient(tone),color:c.textOnColor,border:`1px solid ${withColorAlpha(accent,0)}`}:{backgroundColor:c.bgCard,color:c.textPrimary,border:`1px solid ${withColorAlpha(accent,102/255)}`},display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",justifyContent:"center",gap:detail?5:0,...!engineering?{boxShadow:`0 10px 24px ${c.shadow}`}:{},textAlign}},...compactChildren([title&&React6.createElement("div",{style:{...typography.small,...titleFontSize!=null?{fontSize:titleFontSize}:{},color:engineering?c.textPrimary:filled?c.textOnColor:accentText,fontFamily:c.fontSans,fontWeight:900,lineHeight:1.2,textAlign}},title),detail&&React6.createElement("div",{style:{...typography.tiny,...detailFontSize!=null?{fontSize:detailFontSize}:{},color:engineering?c.textSecondary:filled?"rgba(255,255,255,0.84)":c.textSecondary,fontFamily:engineering?c.fontMono:typography.tiny.fontFamily,lineHeight:1.3,textAlign}},detail),children&&React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",fontSize:12,fontWeight:700,lineHeight:1.3,textAlign}},children)]))}function Pipeline({stages,c,title}){return React6.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:20}},title&&React6.createElement("div",{style:{...typography.label,color:c.textPrimary}},title),React6.createElement("div",{style:{display:"flex",alignItems:"center",gap:0}},...stages.flatMap((stage,i)=>{const elements=[];elements.push(Box({label:stage.label,sublabel:stage.sublabel,icon:stage.icon,color:stage.color||"primary",gradient:true,c,fontSize:13}));if(i<stages.length-1){elements.push(Arrow({direction:"right",length:36,c}))}return elements})))}import React7 from"react";var sequenceFragmentKinds=["alt","loop","parallel"];var sequenceMessageKinds=["sync","async","return"];function isFragment(item){return!("from"in item)&&(!("type"in item)||item.type!=="note"&&item.type!=="activation")}function isActivation(item){return"type"in item&&item.type==="activation"}function isNote(item){return"type"in item&&item.type==="note"}function sequenceFragmentKind(fragment){const kind=fragment.kind;if(kind==null||!sequenceFragmentKinds.includes(kind)){throw new Error(`SequenceDiagram fragment must define kind as "alt", "loop", or "parallel".`)}return kind}function sequenceMessageKind(message){const kind=message.kind;if(kind==null)return"sync";if(!sequenceMessageKinds.includes(kind)){throw new Error(`SequenceDiagram message kind must be "sync", "async", or "return".`)}return kind}function sequenceNoteText(note){return note.text}function sequenceContainerItems(container){if(container.items)return container.items;return[...container.messages??[],...container.notes??[],...container.fragments??[]]}function participantReferences(note){const references=note.over??[];if(note.participant&&!references.includes(note.participant))return[note.participant,...references];return references}function validateSequenceItems(items,participantIds,path){for(let index=0;index<items.length;index+=1){const item=items[index];const itemPath=`${path}[${index}]`;if(isFragment(item)){const kind=sequenceFragmentKind(item);const branches=item.branches??[];if((kind==="alt"||kind==="parallel")&&branches.length<2){throw new Error(`SequenceDiagram ${kind} fragment at ${itemPath} requires at least two branches.`)}if(branches.some(branch=>!branch||typeof branch!=="object")){throw new Error(`SequenceDiagram fragment at ${itemPath} contains an invalid branch.`)}for(let branchIndex=0;branchIndex<branches.length;branchIndex+=1){validateSequenceItems(sequenceContainerItems(branches[branchIndex]),participantIds,`${itemPath}.branches[${branchIndex}]`)}if(!branches.length){validateSequenceItems(sequenceContainerItems(item),participantIds,`${itemPath}.items`)}continue}if(isActivation(item)){if(!participantIds.has(item.participant)){throw new Error(`SequenceDiagram activation references missing participant "${item.participant}".`)}continue}if(isNote(item)){for(const participant of participantReferences(item)){if(!participantIds.has(participant)){throw new Error(`SequenceDiagram note references missing participant "${participant}".`)}}continue}if(!participantIds.has(item.from)||!participantIds.has(item.to)){throw new Error(`SequenceDiagram message "${item.from}" -> "${item.to}" references a missing participant.`)}sequenceMessageKind(item)}}function validateSequenceSpec(participants,items){const ids=new Set;for(const participant of participants){if(!participant.id.trim())throw new Error("SequenceDiagram participant ids must not be empty.");if(ids.has(participant.id))throw new Error(`SequenceDiagram received duplicate participant id "${participant.id}".`);ids.add(participant.id)}validateSequenceItems(items,ids,"items")}function branchLabel(branch,index){return branch.label??(index===0?"case":"else")}function flattenSequenceItems(items){const rows=[];const spans=[];const appendItems=(nextItems,depth,path)=>{nextItems.forEach((item,index)=>{if(!isFragment(item)){rows.push({key:item.id??`${path}-${index}`,item,depth});return}const fragmentId=item.id??`${path}-fragment-${index}`;const start=rows.length;const branchStarts=[];const branches=item.branches??[];if(branches.length){branches.forEach((branch,branchIndex)=>{const row=rows.length;branchStarts.push({row,label:branchLabel(branch,branchIndex)});rows.push({key:`${fragmentId}-branch-${branchIndex}`,marker:{fragment:item,branch,branchIndex},depth});appendItems(sequenceContainerItems(branch),depth+1,`${fragmentId}-branch-${branchIndex}`)})}else{rows.push({key:`${fragmentId}-start`,marker:{fragment:item},depth});appendItems(sequenceContainerItems(item),depth+1,fragmentId)}if(rows.length===start)rows.push({key:`${fragmentId}-empty`,marker:{fragment:item},depth});spans.push({id:fragmentId,start,end:Math.max(start,rows.length-1),depth,fragment:item,branchStarts})})};appendItems(items,0,"sequence");return{rows,spans}}function readableNodeText(value){if(typeof value==="string"||typeof value==="number")return String(value);return""}function sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop){if(!selfLoop)return`M ${fromX} ${y} L ${toX} ${y}`;const loopWidth=34;const right=fromX+loopWidth;const bottom=y+rowHeight*.52;return`M ${fromX} ${y} L ${right} ${y} L ${right} ${bottom} L ${fromX+10} ${bottom} L ${fromX+10} ${y+1}`}function sequenceNoteBounds(note,xs,chartWidth,noteWidth,padding){const references=participantReferences(note).filter(id=>xs.has(id));if(references.length>=2||note.side==="over"){const values=references.map(id=>xs.get(id)??chartWidth/2);const left2=Math.max(padding,Math.min(...values)-noteWidth/2);const right=Math.min(chartWidth-padding,Math.max(...values)+noteWidth/2);return{left:left2,width:Math.max(82,right-left2)}}const anchor=references.length?xs.get(references[0])??chartWidth/2:chartWidth/2;const left=note.side==="left"?anchor-noteWidth-18:note.side==="right"?anchor+18:anchor-noteWidth/2;return{left:Math.max(padding,Math.min(chartWidth-padding-noteWidth,left)),width:noteWidth}}function activationReference(value,rows,fallback,end){if(value==null)return fallback;if(typeof value==="number"){if(!Number.isInteger(value)||value<0||value>=Math.max(rows.length,1)){throw new Error(`SequenceDiagram activation row reference ${value} is outside rendered rows.`)}return value}const index=rows.findIndex(row=>row.key===value||row.item!=null&&row.item.id===value);if(index<0)throw new Error(`SequenceDiagram activation references missing row "${value}".`);return end?index:index}function SequenceDiagram({c,participants,messages=[],notes=[],activations=[],fragments=[],items,title,subtitle,ariaLabel,width,height,padding=24,participantWidth=132,participantGap=42,rowHeight=56,fragmentIndent=12,noteWidth=156,lifelineDash="5 5"}){const orderedItems=items??sequenceContainerItems({messages,notes,fragments});validateSequenceSpec(participants,activations.length?[...orderedItems,...activations]:orderedItems);const flattened=flattenSequenceItems(orderedItems);const rows=flattened.rows.length?flattened.rows:[{key:"sequence-empty",depth:0}];const minimumWidth=padding*2+participantWidth*participants.length+participantGap*Math.max(0,participants.length-1);const resolvedWidth=width??Math.max(560,minimumWidth);if(width!=null&&width<minimumWidth){throw new Error(`SequenceDiagram width ${width} is too small for ${participants.length} participants; use at least ${minimumWidth}.`)}const headerHeight=92;const minimumHeight=padding+headerHeight+rows.length*rowHeight+padding;const resolvedHeight=height??minimumHeight;if(height!=null&&height<minimumHeight){throw new Error(`SequenceDiagram height ${height} is too small for ${rows.length} rows; use at least ${minimumHeight}.`)}const availableParticipantWidth=resolvedWidth-padding*2;const step=participants.length>1?(availableParticipantWidth-participantWidth)/(participants.length-1):0;const firstX=participants.length>1?padding+participantWidth/2:resolvedWidth/2;const participantXs=new Map(participants.map((participant,index)=>[participant.id,firstX+index*step]));const bodyTop=padding+headerHeight;const rowCenter=index=>bodyTop+index*rowHeight+rowHeight/2;const labelText=ariaLabel??readableNodeText(title)??"Sequence diagram";const accessibleLabel=labelText||"Sequence diagram";const markerDefinitions=participants.flatMap((participant,participantIndex)=>{const color=getToneColor(participant.tone??"blue",c);return sequenceMessageKindsForMarkers(orderedItems).map(kind=>ArrowMarkerDef({id:`sequence-arrow-${participantIndex}-${kind}`,color,size:5}))});const fragmentElements=flattened.spans.map(span=>{const tone=span.fragment.tone??(span.fragment.kind==="loop"?"purple":span.fragment.kind==="parallel"?"cyan":"warm");const accent=span.fragment.muted?c.textMuted:getToneColor(tone,c);const top=bodyTop+span.start*rowHeight+4;const spanHeight=Math.max(rowHeight-8,(span.end-span.start+1)*rowHeight-8);const left=padding+span.depth*fragmentIndent;const fragmentWidth=Math.max(0,resolvedWidth-left-padding-span.depth*fragmentIndent);return React7.createElement("div",{key:`sequence-fragment-${span.id}`,"data-vizmatic-sequence-fragment":span.id,style:{position:"absolute",left,top,width:fragmentWidth,height:spanHeight,display:"flex",boxSizing:"border-box",border:`1.25px ${span.fragment.muted?"dotted":"dashed"} ${withColorAlpha(accent,(span.fragment.muted?85:153)/255)}`,backgroundColor:withColorAlpha(accent,11/255),borderRadius:c.preset==="engineering"?4:8,pointerEvents:"none"}},React7.createElement("div",{style:{position:"absolute",left:8,top:-9,display:"flex",alignItems:"center",gap:5,padding:"1px 5px",backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:11,fontWeight:800,lineHeight:1.1,textTransform:"uppercase"}},span.fragment.kind,span.fragment.label),...span.branchStarts.map(branch=>React7.createElement("div",{key:`sequence-branch-${span.id}-${branch.row}`,style:{position:"absolute",left:Math.max(8,span.depth*fragmentIndent),top:branch.row*rowHeight-span.start*rowHeight+5,padding:"2px 5px",backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:11,fontWeight:700,lineHeight:1.1}},branch.label)))});const lifelineElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;return React7.createElement("line",{key:`sequence-lifeline-${participant.id}`,x1:x,y1:bodyTop-14,x2:x,y2:bodyTop+rows.length*rowHeight,stroke:participant.muted?c.textMuted:c.borderLight,strokeWidth:participant.muted?1:1.35,strokeDasharray:lifelineDash,opacity:participant.muted?.46:.8})});const activationElements=[...activations,...orderedItems.filter(isActivation)].map((activation,index)=>{const participantX=participantXs.get(activation.participant);if(participantX==null)return null;const startValue=activation.start??activation.fromMessage;const endValue=activation.end??activation.toMessage;const start=activationReference(startValue,rows,0,false);const end=activationReference(endValue,rows,rows.length-1,true);if(end<start)throw new Error(`SequenceDiagram activation for "${activation.participant}" ends before it starts.`);const depth=Math.max(0,activation.depth??0);const accent=activation.muted?c.textMuted:getToneColor(activation.tone??"blue",c);const top=rowCenter(start)-rowHeight/2+5;const activationHeight=Math.max(14,(end-start+1)*rowHeight-10);return React7.createElement("div",{key:`sequence-activation-${activation.id??index}`,"data-vizmatic-sequence-activation":activation.participant,style:{position:"absolute",left:participantX-5+depth*7,top,width:10,height:activationHeight,boxSizing:"border-box",borderRadius:3,backgroundColor:getToneFill(activation.tone??"blue",c),border:`1.5px solid ${accent}`,opacity:activation.muted?.52:.94,pointerEvents:"none"}})}).filter(Boolean);const messageElements=rows.map((row,rowIndex)=>{if(!row.item||isFragment(row.item)||isActivation(row.item)||isNote(row.item))return null;const message=row.item;const fromX=participantXs.get(message.from)??resolvedWidth/2;const toX=participantXs.get(message.to)??resolvedWidth/2;const kind=sequenceMessageKind(message);const tone=message.tone??(kind==="return"?"neutral":kind==="async"?"cyan":"blue");const color=message.muted?c.textMuted:getToneColor(tone,c);const markerId=`sequence-arrow-${participants.findIndex(participant=>participant.id===message.to)}-${kind}`;const y=rowCenter(rowIndex);const selfLoop=message.from===message.to;return React7.createElement(React7.Fragment,{key:`sequence-message-${message.id??row.key}`},React7.createElement("path",{d:sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop),fill:"none",stroke:color,strokeWidth:message.muted?1.25:2,strokeDasharray:kind==="sync"?void 0:"7 5",strokeLinecap:"round",opacity:message.muted?.48:.9,markerEnd:`url(#${markerId})`}),message.label!=null&&React7.createElement("div",{style:{position:"absolute",left:selfLoop?fromX+34:(fromX+toX)/2,top:y-18,transform:"translate(-50%, -50%)",maxWidth:Math.max(74,Math.abs(toX-fromX)-28),padding:"2px 5px",backgroundColor:c.bg,color:message.muted?c.textMuted:c.textPrimary,fontFamily:c.fontMono,fontSize:11,fontWeight:650,lineHeight:1.1,whiteSpace:"nowrap",...textFitStyle("center")}},message.label))}).filter(Boolean);const noteElements=rows.map((row,rowIndex)=>{if(!row.item||!isNote(row.item))return null;const note=row.item;const bounds=sequenceNoteBounds(note,participantXs,resolvedWidth,noteWidth,padding);const tone=note.tone??"warm";const accent=note.muted?c.textMuted:getToneColor(tone,c);return React7.createElement("div",{key:`sequence-note-${note.id??row.key}`,"data-vizmatic-sequence-note":note.id??row.key,style:{position:"absolute",left:bounds.left,top:rowCenter(rowIndex)-17,width:bounds.width,minHeight:34,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",padding:"6px 9px",borderRadius:c.preset==="engineering"?3:7,backgroundColor:note.muted?c.bgSubtle:getToneFill(tone,c),border:`1px solid ${withColorAlpha(accent,(note.muted?102:153)/255)}`,color:note.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),fontFamily:c.fontSans,fontSize:11,fontWeight:700,lineHeight:1.2,textAlign:"center",...textFitStyle("center")}},sequenceNoteText(note))}).filter(Boolean);const participantElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;const tone=participant.tone??"blue";const accent=participant.muted?c.textMuted:getToneColor(tone,c);const icon=participant.icon&&Icon({c,name:participant.icon,color:accent,size:16,muted:participant.muted,label:readableNodeText(participant.label)?`${readableNodeText(participant.label)} icon`:void 0});return React7.createElement("div",{key:`sequence-participant-${participant.id}`,"data-vizmatic-sequence-participant":participant.id,style:{position:"absolute",left:x-participantWidth/2,top:padding,width:participantWidth,minHeight:54,boxSizing:"border-box",display:"flex",flexDirection:icon?"row":"column",alignItems:"center",justifyContent:"center",gap:icon?7:participant.detail?3:0,padding:"7px 8px",borderRadius:c.preset==="engineering"?4:8,backgroundColor:participant.muted?c.bgSubtle:getToneFill(tone,c),border:`1.25px solid ${participant.muted?c.borderLight:accent}`,color:participant.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),opacity:participant.muted?.62:1,textAlign:icon?"left":"center"}},icon,React7.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:icon?"flex-start":"center",minWidth:0,gap:participant.detail?3:0}},React7.createElement("div",{style:{fontFamily:c.fontSans,fontSize:12,fontWeight:850,lineHeight:1.15,...textFitStyle(icon?"left":"center")}},participant.label),participant.detail!=null&&React7.createElement("div",{style:{color:c.textMuted,fontFamily:c.fontMono,fontSize:11,fontWeight:550,lineHeight:1.1,...textFitStyle(icon?"left":"center")}},participant.detail)))});return React7.createElement("div",{role:"img","aria-label":accessibleLabel,"data-vizmatic-sequence-row-count":rows.length,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},...fragmentElements,React7.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React7.createElement("defs",{},...markerDefinitions),...lifelineElements,...messageElements),...activationElements,...noteElements,...participantElements,title!=null&&React7.createElement("div",{style:{position:"absolute",left:padding,top:2,color:c.textPrimary,fontFamily:c.fontSans,fontSize:14,fontWeight:850}},title),subtitle!=null&&React7.createElement("div",{style:{position:"absolute",left:padding,top:20,color:c.textSecondary,fontFamily:c.fontSans,fontSize:11,fontWeight:550}},subtitle))}function sequenceMessageKindsForMarkers(items){const kinds=new Set;const visit=nextItems=>{for(const item of nextItems){if(isFragment(item)){if(item.branches)item.branches.forEach(branch=>visit(sequenceContainerItems(branch)));else visit(sequenceContainerItems(item))}else if(!isNote(item)&&!isActivation(item)){kinds.add(sequenceMessageKind(item))}}};visit(items);if(!kinds.size)kinds.add("sync");return Array.from(kinds)}import React8 from"react";var nodeKinds=["source","transform","store","sink"];var edgeModes=["batch","stream"];var defaultNodeTones={source:"blue",transform:"purple",store:"green",sink:"warm"};var defaultNodeIcons={source:"file",transform:"tool",store:"database",sink:"bucket"};function nodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds.includes(kind)){throw new Error(`DataflowDiagram node "${node.id}" must define kind as "source", "transform", "store", or "sink".`)}return kind}function edgeMode(edge){const mode=edge.mode??"batch";if(!edgeModes.includes(mode)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" must use mode "batch" or "stream".`)}return mode}function validateSchema(schema,owner){if(schema==null||typeof schema==="string")return;const fields=new Set;const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));for(const field of fieldList){if(!field.name.trim())throw new Error(`DataflowDiagram schema for "${owner}" contains an empty field name.`);if(fields.has(field.name))throw new Error(`DataflowDiagram schema for "${owner}" contains duplicate field "${field.name}".`);fields.add(field.name)}}function schemaLabel(schema){if(schema==null)return void 0;if(typeof schema==="string")return schema;const prefix=[schema.name,schema.version].filter(Boolean).join(" ");const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));const fields=fieldList.map(field=>`${field.name}${field.type?`: ${field.type}`:""}${field.required?" *":""}`).join(", ");return[prefix,fields?`{ ${fields} }`:void 0].filter(Boolean).join(" ")}function detailWithSchema(detail,schema){const renderedSchema=schemaLabel(schema);if(!renderedSchema)return detail;if(detail==null)return renderedSchema;if(typeof detail==="string"||typeof detail==="number")return`${detail} \xB7 ${renderedSchema}`;return React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap:3,minWidth:0}},React8.createElement("div",null,detail),React8.createElement("div",{style:{fontFamily:"inherit",fontSize:"inherit",fontWeight:"inherit"}},renderedSchema))}function validateDataflowSpec(spec){const boundaries=spec.boundaries??[];const ids=new Set;for(const node of spec.nodes){if(!node.id.trim())throw new Error("DataflowDiagram node ids must not be empty.");if(ids.has(node.id))throw new Error(`DataflowDiagram received duplicate id "${node.id}".`);ids.add(node.id);nodeKind(node);validateSchema(node.schema,node.id)}for(const boundary of boundaries){if(!boundary.id.trim())throw new Error("DataflowDiagram boundary ids must not be empty.");if(ids.has(boundary.id))throw new Error(`DataflowDiagram received duplicate id "${boundary.id}".`);ids.add(boundary.id)}const boundariesById=new Map(boundaries.map(boundary=>[boundary.id,boundary]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundariesById.has(boundary.parent)){throw new Error(`DataflowDiagram boundary "${boundary.id}" references missing parent "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DataflowDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundariesById.get(parent)?.parent}}for(const node of spec.nodes){const boundary=node.boundary;if(boundary!=null&&!boundariesById.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}}for(const edge of spec.edges){if(!ids.has(edge.from)||!ids.has(edge.to)||!spec.nodes.some(node=>node.id===edge.from)||!spec.nodes.some(node=>node.id===edge.to)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}edgeMode(edge);validateSchema(edge.schema,`${edge.from} -> ${edge.to}`)}const occupied=new Set;for(const node of spec.nodes){let boundary=node.boundary;while(boundary!=null){occupied.add(boundary);boundary=boundariesById.get(boundary)?.parent}}for(const boundary of boundaries){if(!occupied.has(boundary.id))throw new Error(`DataflowDiagram boundary "${boundary.id}" contains no nodes.`)}return{boundaries}}function compileDataflow(spec){const{boundaries}=validateDataflowSpec(spec);const boundaryIds=new Set(boundaries.map(boundary=>boundary.id));const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail,parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=nodeKind(node);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}return{id:node.id,label:node.label,detail:detailWithSchema(node.detail,node.schema),href:node.href,title:node.title,tone:node.tone??defaultNodeTones[kind],icon:node.icon??defaultNodeIcons[kind],muted:node.muted,group:boundary,width:node.width,height:node.height}});const edges=spec.edges.map(edge=>{const mode=edgeMode(edge);const schema=schemaLabel(edge.schema);return{id:edge.id,from:edge.from,to:edge.to,label:edge.label??schema??mode,href:edge.href,title:edge.title,tone:edge.tone??(mode==="stream"?"cyan":"blue"),muted:edge.muted,kind:mode==="stream"?"async":"data",style:mode==="stream"?"dashed":"solid",arrow:"forward"}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Dataflow diagram"}}function DataflowDiagram({c,nodes,edges,boundaries,ariaLabel,id,title,description,width,height,nodeWidth=158,nodeHeight=70,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize}){const compiled=compileDataflow({nodes,edges,boundaries,ariaLabel});return GraphDiagram({c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel,id,title,description,width,height,nodeWidth,nodeHeight,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize})}Object.defineProperty(DataflowDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var boundaryKindLabels={region:"REGION",zone:"ZONE",vpc:"VPC",subnet:"SUBNET",namespace:"NAMESPACE",host:"HOST",cluster:"CLUSTER",trust:"TRUST"};var nodeKindLabels={user:"USER",client:"CLIENT",external:"EXTERNAL",gateway:"GATEWAY","load-balancer":"LOAD BALANCER",service:"SERVICE",api:"API",function:"FUNCTION",lambda:"LAMBDA",worker:"WORKER",container:"CONTAINER",pod:"POD",host:"HOST",vm:"VM",cluster:"CLUSTER",database:"DATABASE",cache:"CACHE",queue:"QUEUE",storage:"STORAGE","object-store":"OBJECT STORE",registry:"REGISTRY","message-broker":"MESSAGE BROKER",firewall:"FIREWALL",network:"NETWORK",internet:"INTERNET",device:"DEVICE",custom:"NODE"};var nodeKindIcons={user:"user",client:"browser",external:"globe",gateway:"gateway","load-balancer":"load-balancer",service:"container",api:"gateway",function:"agent",lambda:"agent",worker:"agent",container:"container",pod:"cluster",host:"server",vm:"server",cluster:"cluster",database:"database",cache:"cache",queue:"queue",storage:"storage","object-store":"bucket",registry:"storage","message-broker":"queue",firewall:"firewall",network:"network",internet:"globe",device:"mobile"};var connectionTones={ingress:"cyan",egress:"warm",internal:"blue","cross-boundary":"purple"};var boundaryKinds=["region","zone","vpc","subnet","namespace","host","cluster","trust"];var nodeKinds2=["user","client","external","gateway","load-balancer","service","api","function","lambda","worker","container","pod","host","vm","cluster","database","cache","queue","storage","object-store","registry","message-broker","firewall","network","internet","device","custom"];var connectionKinds=["ingress","egress","internal","cross-boundary"];function assertIdentifier(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`DeploymentDiagram ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier(id,seen,what){assertIdentifier(id,what);if(seen.has(id))throw new Error(`DeploymentDiagram received duplicate ${what} id "${id}".`);seen.add(id)}function portIdentity(port){if(typeof port==="string"||typeof port==="number")return String(port);return port.id}function portText(port){if(typeof port==="string"||typeof port==="number")return String(port);if(port.label)return port.label;const endpoint2=port.port??port.id;return[port.protocol,endpoint2==null?void 0:String(endpoint2)].filter(Boolean).join("/")||port.direction||"port"}function portForReference(node,reference){if(reference==null)return void 0;return node.ports?.find(port=>portIdentity(port)===String(reference))}function resolveConnectionKind(connection){const kind=connection.kind??"internal";if(!connectionKinds.includes(kind)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" must use kind "ingress", "egress", "internal", or "cross-boundary".`)}return kind}function resolveBoundaryKind(boundary){const kind=boundary.kind;if(kind==null||!boundaryKinds.includes(kind)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" must define kind as "region", "zone", "vpc", "subnet", "namespace", "host", "cluster", or "trust".`)}return kind}function resolveNodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds2.includes(kind)){throw new Error(`DeploymentDiagram node "${node.id}" must define kind as a supported deployment node kind.`)}return kind}function connectionPortReference(connection,side){return side==="from"?connection.fromPort:connection.toPort}function connectionLabel(connection,sourcePort,targetPort){if(connection.label!=null)return connection.label;const declaredPort=connection.port;const portLabel=declaredPort!=null?portText(declaredPort):sourcePort!=null?portText(sourcePort):targetPort!=null?portText(targetPort):void 0;const protocol=connection.protocol??(typeof sourcePort==="object"&&sourcePort!=null?sourcePort.protocol:void 0)??(typeof targetPort==="object"&&targetPort!=null?targetPort.protocol:void 0);if(protocol&&portLabel&&!portLabel.toLowerCase().startsWith(protocol.toLowerCase())){return`${protocol}/${portLabel}`}return protocol??portLabel}function validateDeploymentSpec(boundaries,nodes,connections){const ids=new Set;const boundaryIds=new Set;for(const boundary of boundaries){assertUniqueIdentifier(boundary.id,ids,"boundary");resolveBoundaryKind(boundary);boundaryIds.add(boundary.id)}const nodeIds=new Set;const portsByNode=new Map;for(const node of nodes){assertUniqueIdentifier(node.id,ids,"node");nodeIds.add(node.id);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DeploymentDiagram node "${node.id}" references missing boundary "${boundary}".`)}const ports=new Map;node.ports?.forEach(port=>{const identity=portIdentity(port);if(ports.has(identity))throw new Error(`DeploymentDiagram node "${node.id}" received duplicate port "${identity}".`);ports.set(identity,port)});portsByNode.set(node.id,ports)}const boundaryParents=new Map(boundaries.map(boundary=>[boundary.id,boundary.parent]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundaryIds.has(boundary.parent)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" references missing parent boundary "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DeploymentDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundaryParents.get(parent)}}const connectionIds=new Set;for(const connection of connections){if(connection.id!=null)assertUniqueIdentifier(connection.id,connectionIds,"connection");if(!nodeIds.has(connection.from)||!nodeIds.has(connection.to)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references a missing node.`)}resolveConnectionKind(connection);for(const side of["from","to"]){const reference=connectionPortReference(connection,side);if(reference==null)continue;const nodeId2=side==="from"?connection.from:connection.to;const ports=portsByNode.get(nodeId2);if(ports!=null&&ports.size>0&&!ports.has(String(reference))){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId2}".`)}}}}function graphConnectionKind(kind){if(kind==="internal")return"data";if(kind==="ingress")return"sync";return"dependency"}function graphConnectionStyle(kind){if(kind==="cross-boundary")return"dotted";if(kind==="egress")return"dashed";return"solid"}function compileDeployment(spec){const boundaries=spec.boundaries??[];const connections=spec.connections??[];validateDeploymentSpec(boundaries,spec.nodes,connections);const anchorPorts=spec.routing!=null&&spec.routing!=="dagre";const incomingSide=spec.direction==="TB"?"top":spec.direction==="BT"?"bottom":spec.direction==="RL"?"right":"left";const outgoingSide=spec.direction==="TB"?"bottom":spec.direction==="BT"?"top":spec.direction==="RL"?"left":"right";const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail??boundaryKindLabels[resolveBoundaryKind(boundary)],parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=resolveNodeKind(node);const nodePorts=node.ports??[];const generatedDetail=nodePorts.length>0?`ports: ${nodePorts.map(portText).join(", ")}`:nodeKindLabels[kind];return{id:node.id,label:node.label,detail:node.detail??generatedDetail,href:node.href,title:node.title,x:node.x,y:node.y,tone:node.tone,muted:node.muted,width:node.width,height:node.height,group:node.boundary,icon:node.icon??nodeKindIcons[kind],iconSize:node.iconSize,ports:anchorPorts?nodePorts.map((port,index)=>{const incoming=typeof port==="object"?port.direction==="ingress":false;const targetOnly=connections.some(connection=>connection.to===node.id&&String(connection.toPort)===portIdentity(port))&&!connections.some(connection=>connection.from===node.id&&String(connection.fromPort)===portIdentity(port));return{id:portIdentity(port),side:typeof port==="object"&&port.side!=null?port.side:incoming||targetOnly?incomingSide:outgoingSide,offset:typeof port==="object"&&port.offset!=null?port.offset:(index+1)/(nodePorts.length+1)}}):void 0}});const edges=connections.map(connection=>{const kind=resolveConnectionKind(connection);const fromReference=connectionPortReference(connection,"from");const toReference=connectionPortReference(connection,"to");const sourceNode=spec.nodes.find(node=>node.id===connection.from);const targetNode=spec.nodes.find(node=>node.id===connection.to);const sourcePort=sourceNode?portForReference(sourceNode,fromReference):void 0;const targetPort=targetNode?portForReference(targetNode,toReference):void 0;const fallbackFromPort=fromReference!=null&&!sourceNode?.ports?.length?fromReference:void 0;const fallbackToPort=toReference!=null&&!targetNode?.ports?.length?toReference:void 0;return{id:connection.id,from:connection.from,to:connection.to,tone:connection.tone??connectionTones[kind],muted:connection.muted,kind:graphConnectionKind(kind),style:connection.style??graphConnectionStyle(kind),arrow:connection.arrow??"forward",label:connectionLabel(connection,sourcePort??fallbackFromPort,targetPort??fallbackToPort),href:connection.href,title:connection.title,fromPort:anchorPorts&&fromReference!=null?String(fromReference):void 0,toPort:anchorPorts&&toReference!=null?String(toReference):void 0,fromSide:connection.fromSide,toSide:connection.toSide}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Deployment diagram"}}function DeploymentDiagram({c,boundaries,nodes,connections,ariaLabel="Deployment diagram",...graphProps}){const compiled=compileDeployment({nodes,boundaries,connections,ariaLabel,direction:graphProps.direction,routing:graphProps.routing});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel})}Object.defineProperty(DeploymentDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var blockLabels={embedding:"Embedding",attention:"Attention",norm:"Norm",mlp:"MLP",residual:"Residual",router:"Router",output:"Output",custom:"Block"};var blockTones={embedding:"cyan",attention:"purple",norm:"neutral",mlp:"blue",residual:"warm",router:"pink",output:"green",custom:"ocean"};var blockIcons={embedding:"layers",attention:"network",norm:"tool",mlp:"code",residual:"git",router:"gateway",output:"check",custom:"spark"};var routeTones={activation:"blue",residual:"warm","kv-cache":"cyan",expert:"pink",collective:"purple"};var blockKinds=["embedding","attention","norm","mlp","residual","router","output","custom"];var routeKinds=["activation","residual","kv-cache","expert","collective"];function assertIdentifier2(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`TransformerTopology ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier2(id,seen,what){assertIdentifier2(id,what);if(seen.has(id))throw new Error(`TransformerTopology received duplicate ${what} id "${id}".`);seen.add(id)}function isTensorShapeArray(shape){return Array.isArray(shape)}function formatTensorShape(shape){if(shape==null)return void 0;if(typeof shape==="string")return shape;const dimensions=isTensorShapeArray(shape)?shape:shape.dims;const label=isTensorShapeArray(shape)?void 0:shape.label;const formatted=dimensions?.length?`[${dimensions.join(" \xD7 ")}]`:void 0;const base=label??formatted;if(!base)return void 0;const metadata=!isTensorShapeArray(shape)?[shape.dtype,shape.layout].filter(Boolean).join(" \xB7 "):"";return metadata?`${base} \xB7 ${metadata}`:base}function resolveBlockKind(block){const kind=block.kind;if(kind==null||!blockKinds.includes(kind)){throw new Error(`TransformerTopology block "${block.id}" must define kind as "embedding", "attention", "norm", "mlp", "residual", "router", "output", or "custom".`)}return kind}function resolveRouteKind(route){const kind=route.kind??"activation";if(!routeKinds.includes(kind)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" must use kind "activation", "residual", "kv-cache", "expert", or "collective".`)}return kind}function resolveRepeat(block){const repeat=block.repeat??1;if(!Number.isInteger(repeat)||repeat<1){throw new Error(`TransformerTopology block "${block.id}" repeat must be a positive integer.`)}return repeat}function blockShapeText(block){const shape=block.shape;const input=formatTensorShape(block.inputShape);const output=formatTensorShape(block.outputShape);const primary=formatTensorShape(shape);if(input||output){return[input,output&&input?`\u2192 ${output}`:output].filter(Boolean).join(" ")}return primary}function blockDetail(block,kind,repeat){const shape=blockShapeText(block);const repetition=repeat>1?`\xD7${repeat}`:void 0;if(block.detail!=null){if(typeof block.detail==="string"){return[block.detail,repetition,shape].filter(Boolean).join(" \xB7 ")}return block.detail}return[repetition,shape,repeat===1?blockLabels[kind].toUpperCase():void 0].filter(Boolean).join(" \xB7 ")||void 0}function routeShapeText(route){return formatTensorShape(route.shape)}function routeLabel(route,kind){if(route.label!=null)return route.label;const kindLabel=kind==="kv-cache"?"KV cache":kind;const qualifiers=[kindLabel,route.expert==null?void 0:`expert ${route.expert}`,route.collective,routeShapeText(route)].filter(Boolean);return qualifiers.join(" \xB7 ")}function graphRouteKind(kind){if(kind==="activation"||kind==="expert")return"data";if(kind==="kv-cache")return"event";return"dependency"}function graphRouteStyle(kind){if(kind==="kv-cache")return"dotted";if(kind==="residual"||kind==="collective")return"dashed";return"solid"}function validateTransformerSpec(blocks,routes,expandRepeats){const blockIds=new Set;const repeatCounts=new Map;for(const block of blocks){assertUniqueIdentifier2(block.id,blockIds,"block");resolveBlockKind(block);repeatCounts.set(block.id,resolveRepeat(block))}const routeIds=new Set;const graphIds=new Set(blockIds);if(expandRepeats){for(const block of blocks){const repeat=repeatCounts.get(block.id)??1;if(repeat===1)continue;for(let index=1;index<=repeat;index+=1){const expandedId=`${block.id}-${index}`;if(graphIds.has(expandedId)){throw new Error(`TransformerTopology repeated block "${block.id}" generates duplicate node id "${expandedId}".`)}graphIds.add(expandedId)}}}for(const route of routes){if(route.id!=null)assertUniqueIdentifier2(route.id,routeIds,"route");if(!blockIds.has(route.from)||!blockIds.has(route.to)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" references a missing block.`)}resolveRouteKind(route)}return repeatCounts}function expandedNodeId(id,repeat,index){return repeat>1?`${id}-${index+1}`:id}function expandedRouteEndpoints(route,repeatCounts,expandRepeats){if(!expandRepeats)return[{from:route.from,to:route.to}];const fromRepeat=repeatCounts.get(route.from)??1;const toRepeat=repeatCounts.get(route.to)??1;if(route.from===route.to&&fromRepeat>1){return Array.from({length:fromRepeat-1},(_,index)=>({from:expandedNodeId(route.from,fromRepeat,index),to:expandedNodeId(route.to,toRepeat,index+1)}))}return[{from:expandedNodeId(route.from,fromRepeat,fromRepeat-1),to:expandedNodeId(route.to,toRepeat,0)}]}function compileTransformer(spec){const routes=spec.routes??[];const expandRepeats=spec.expandRepeats??false;const repeatCounts=validateTransformerSpec(spec.blocks,routes,expandRepeats);const nodes=[];for(const block of spec.blocks){const kind=resolveBlockKind(block);const repeat=repeatCounts.get(block.id)??1;const count=expandRepeats?repeat:1;for(let index=0;index<count;index+=1){const id=expandRepeats?expandedNodeId(block.id,repeat,index):block.id;const label=block.label??blockLabels[kind];const repetitionDetail=expandRepeats&&repeat>1?[blockDetail(block,kind,repeat),`${index+1}/${repeat}`].filter(Boolean).join(" \xB7 "):blockDetail(block,kind,repeat);nodes.push({id,label,detail:repetitionDetail,href:block.href,title:block.title,x:block.x,y:block.y,tone:block.tone??blockTones[kind],muted:block.muted,width:block.width,height:block.height,icon:block.icon??blockIcons[kind],iconSize:block.iconSize})}}const edges=[];for(const route of routes){const kind=resolveRouteKind(route);const endpoints=expandedRouteEndpoints(route,repeatCounts,expandRepeats);for(const[index,endpoint2]of endpoints.entries()){edges.push({id:route.id==null?void 0:endpoints.length===1?route.id:`${route.id}-${index+1}`,from:endpoint2.from,to:endpoint2.to,tone:route.tone??routeTones[kind],muted:route.muted,kind:graphRouteKind(kind),style:route.style??graphRouteStyle(kind),arrow:route.arrow??(kind==="residual"?"both":"forward"),label:routeLabel(route,kind),href:route.href,title:route.title})}}return{nodes,edges,ariaLabel:spec.ariaLabel??"Transformer topology diagram"}}function TransformerTopology({c,blocks,routes,expandRepeats=false,ariaLabel="Transformer topology diagram",...graphProps}){const compiled=compileTransformer({blocks,routes,expandRepeats,ariaLabel});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,ariaLabel:compiled.ariaLabel})}Object.defineProperty(TransformerTopology,SVG_ACCESSIBILITY_COMPONENT,{value:true});import React9 from"react";function Matrix({data,c,rowLabels,colLabels,labels,title,cellSize=48,cellWidth,cellHeight,rowLabelWidth,format="decimal",colorize=true,colorScale="heat"}){const resolvedCellWidth=cellWidth??cellSize;const resolvedCellHeight=cellHeight??cellSize;const resolvedRowLabelWidth=rowLabelWidth??cellSize;const formatValue=v=>{if(format==="percent")return`${Math.round(v*100)}%`;if(format==="integer")return`${Math.round(v)}`;return v.toFixed(2)};const cellColor=value=>{if(colorScale==="heat")return heatColor(value);if(value<.34)return c.bgHover;if(value<.67)return c.infoDark;return c.positiveDark};return React9.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:12}},title&&React9.createElement("div",{style:{...typography.label,color:c.textPrimary}},title),React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},colLabels&&React9.createElement("div",{style:{display:"flex",gap:2,marginLeft:rowLabels?resolvedRowLabelWidth+4:0}},...colLabels.map((label,i)=>React9.createElement("div",{key:`col-${i}`,style:{width:resolvedCellWidth,textAlign:"center",fontSize:11,fontWeight:600,color:c.textSecondary,fontFamily:"JetBrains Mono"}},label))),...data.map((row,ri)=>React9.createElement("div",{key:`row-${ri}`,style:{display:"flex",gap:2,alignItems:"center"}},rowLabels&&React9.createElement("div",{style:{width:resolvedRowLabelWidth,textAlign:"right",paddingRight:4,fontSize:11,fontWeight:600,color:c.textSecondary,fontFamily:"JetBrains Mono"}},rowLabels[ri]),...row.map((value,ci)=>{const backgroundColor=colorize?cellColor(value):c.bgCard;return React9.createElement("div",{key:`cell-${ri}-${ci}`,style:{width:resolvedCellWidth,height:resolvedCellHeight,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor,borderRadius:6,fontSize:11,fontWeight:600,color:colorize?getReadableTextColor(backgroundColor,c):c.textPrimary,fontFamily:"JetBrains Mono"}},labels?.[ri]?.[ci]??formatValue(value))})))))}function Heatmap({data,xLabels,yLabels,c,labels,title,cellSize=52,cellWidth,cellHeight,rowLabelWidth,colorScale}){return Matrix({data,colLabels:xLabels,rowLabels:yLabels,c,labels,title,colorize:true,cellSize,cellWidth,cellHeight,rowLabelWidth,colorScale})}function TiledMatrix({rows,cols,c,ariaLabel,regions=[],title,subtitle,cellSize=24,gap=3,tone="blue",muted=false,crossedOut=false}){const safeRows=Math.max(1,Math.floor(rows));const safeCols=Math.max(1,Math.floor(cols));const baseAccent=getToneColor(tone,c);const cellRows=Array.from({length:safeRows},(_,row)=>React9.createElement("div",{key:`tiled-matrix-row-${row}`,style:{display:"flex",gap}},...Array.from({length:safeCols},(_2,col)=>{const regionIndex=regions.findIndex(region2=>row>=region2.rowStart&&row<region2.rowEnd&&col>=region2.colStart&&col<region2.colEnd);const region=regionIndex>=0?regions[regionIndex]:void 0;const accent=getToneColor(region?.tone??tone,c);return React9.createElement("div",{key:`tiled-matrix-cell-${row}-${col}`,"data-region":regionIndex>=0?regionIndex:void 0,style:{width:cellSize,height:cellSize,boxSizing:"border-box",borderRadius:Math.max(2,Math.min(6,Math.round(cellSize*.18))),backgroundColor:region?withColorAlpha(accent,66/255):muted?c.bgSubtle:withColorAlpha(baseAccent,15/255),border:`1px solid ${region?withColorAlpha(accent,170/255):c.borderSubtle}`,opacity:muted?.55:1}})})));const grid=React9.createElement("div",{"data-crossed-out":crossedOut?"true":void 0,style:{position:"relative",display:"flex",flexDirection:"column",gap,padding:gap,borderRadius:10,backgroundColor:c.bgSubtle,border:`1px solid ${c.borderLight}`,boxShadow:`0 8px 18px ${c.shadow}`,overflow:"hidden"}},...cellRows,...crossedOut?[React9.createElement("div",{key:"cross-forward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}}),React9.createElement("div",{key:"cross-backward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(-36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}})]:[]);return React9.createElement("div",{role:"img","aria-label":ariaLabel??(typeof title==="string"?title:"Tiled matrix"),style:{display:"flex",flexDirection:"column",alignItems:"center",gap:7}},...compactChildren([title&&React9.createElement("div",{style:{color:muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:"Inter",fontSize:13,fontWeight:900,lineHeight:1.1,textAlign:"center"}},title),subtitle&&React9.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:11,fontWeight:700,lineHeight:1.1,textAlign:"center"}},subtitle),grid]))}function DataTable({rows,c,cellWidth=54,firstColWidth=cellWidth,cellHeight=28,gap=5,headerRows=1,headerCols=1,fontSize=11,math=false}){const renderCell=cell=>math&&typeof cell==="string"?formatMathText(cell):cell;return React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap,alignItems:"center"}},...rows.map((row,rowIndex)=>React9.createElement("div",{key:`${rowIndex}-${row.map(String).join("|")}`,style:{display:"flex",gap}},...row.map((cell,colIndex)=>{const isHeaderRow=rowIndex<headerRows;const isHeaderCol=colIndex<headerCols;return React9.createElement("div",{key:`${rowIndex}-${colIndex}-${String(cell)}`,style:{width:colIndex===0?firstColWidth:cellWidth,height:cellHeight,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:7,backgroundColor:isHeaderRow?c.bgSubtle:c.bgHover,color:isHeaderCol?c.textPrimary:c.textSecondary,fontFamily:"JetBrains Mono",fontSize,fontWeight:isHeaderCol?850:650,lineHeight:1.15,...textFitStyle("center")}},renderCell(cell))}))))}function isGridCell(cell){return typeof cell==="object"&&cell!==null&&!React9.isValidElement(cell)&&("label"in cell||"tone"in cell||"color"in cell||"backgroundColor"in cell||"borderColor"in cell||"opacity"in cell)}function Grid({rows,c,cellWidth=34,cellHeight=30,gap=5,radius=7,fontSize=11,math=false,headerRows=0,headerCols=0}){const renderCellLabel=cell=>{const label=isGridCell(cell)?cell.label:cell;return math&&typeof label==="string"?formatMathText(label):label};const cellStyle=(cell,rowIndex,colIndex)=>{const config=isGridCell(cell)?cell:{};const toneColor=config.tone?getToneColor(config.tone,c):void 0;const isHeader=rowIndex<headerRows||colIndex<headerCols;const backgroundColor=config.backgroundColor??(toneColor?withColorAlpha(toneColor,34/255):isHeader?c.bgSubtle:c.bgHover);const toneTextColor=config.tone?getReadableToneColor(config.tone,c,backgroundColor,c.bgHover):void 0;return{width:cellWidth,height:cellHeight,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:radius,backgroundColor,border:`1px solid ${config.borderColor??(toneColor?withColorAlpha(toneColor,85/255):c.borderSubtle)}`,color:config.color??(toneTextColor??(isHeader?c.textPrimary:c.textSecondary)),...config.opacity!==void 0?{opacity:config.opacity}:{},fontFamily:"JetBrains Mono",fontSize,fontWeight:isHeader||toneColor?850:650,lineHeight:1.15,...textFitStyle("center")}};return React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap,alignItems:"center"}},...rows.map((row,rowIndex)=>React9.createElement("div",{key:`grid-row-${rowIndex}`,style:{display:"flex",gap}},...row.map((cell,colIndex)=>React9.createElement("div",{key:`grid-cell-${rowIndex}-${colIndex}`,style:cellStyle(cell,rowIndex,colIndex)},renderCellLabel(cell))))))}function AxisPlot({c,width,height,xMin=-1,xMax=1,yMin=-1,yMax=1,padding=18,showFrame=true,showAxes=true,showGrid=false,gridCount=5,frameRx=8,frameFill,frameStroke,axisColor,points=[],vectors=[],paths=[],xAxisLabel,yAxisLabel,children}){const innerWidth=Math.max(1,width-padding*2);const innerHeight=Math.max(1,height-padding*2);const xRange=xMax===xMin?1:xMax-xMin;const yRange=yMax===yMin?1:yMax-yMin;const sx=x=>padding+(x-xMin)/xRange*innerWidth;const sy=y=>padding+innerHeight-(y-yMin)/yRange*innerHeight;const xAxisY=yMin<=0&&yMax>=0?sy(0):padding+innerHeight/2;const yAxisX=xMin<=0&&xMax>=0?sx(0):padding+innerWidth/2;const axisStroke=axisColor??c.borderLight;const gridIndexes=Array.from({length:Math.max(0,gridCount)},(_,index)=>index+1);const elements=[];if(showFrame){elements.push(SvgFrame({key:"axis-frame",x:padding/2,y:padding/2,width:width-padding,height:height-padding,rx:frameRx,c,fill:frameFill,stroke:frameStroke}))}if(showGrid&&gridCount>0){elements.push(...gridIndexes.flatMap(index=>{const x=padding+innerWidth*index/(gridCount+1);const y=padding+innerHeight*index/(gridCount+1);return[React9.createElement("line",{key:`axis-grid-x-${index}`,x1:x,y1:padding,x2:x,y2:padding+innerHeight,stroke:c.borderSubtle,strokeWidth:1,opacity:.75}),React9.createElement("line",{key:`axis-grid-y-${index}`,x1:padding,y1:y,x2:padding+innerWidth,y2:y,stroke:c.borderSubtle,strokeWidth:1,opacity:.75})]}))}if(showAxes){elements.push(React9.createElement("line",{key:"axis-x",x1:padding,y1:xAxisY,x2:padding+innerWidth,y2:xAxisY,stroke:axisStroke,strokeWidth:1.6,opacity:.85}),React9.createElement("line",{key:"axis-y",x1:yAxisX,y1:padding,x2:yAxisX,y2:padding+innerHeight,stroke:axisStroke,strokeWidth:1.6,opacity:.85}))}elements.push(...paths.flatMap((path,index)=>{if(path.points.length<2)return[];const[first,...rest]=path.points;const commands=[`M ${sx(first.x)} ${sy(first.y)}`];for(const point of rest){if(path.interpolation==="step-after"){commands.push(`H ${sx(point.x)} V ${sy(point.y)}`)}else{commands.push(`L ${sx(point.x)} ${sy(point.y)}`)}}return[React9.createElement("path",{key:`axis-path-${index}`,d:commands.join(" "),fill:"none",stroke:path.color??getToneColor(path.tone??"blue",c),strokeWidth:path.strokeWidth??3,strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:path.dashed?"8 7":void 0,opacity:path.opacity??1})]}));elements.push(...vectors.map((vector,index)=>{const color=vector.color??getToneColor(vector.tone??"blue",c);const x1=sx(vector.x1);const y1=sy(vector.y1);const x2=sx(vector.x2);const y2=sy(vector.y2);if(vector.arrow){return VectorArrow({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,arrowSize:vector.arrowSize,opacity:vector.opacity})}return VectorSegment({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,opacity:vector.opacity,showStartDot:vector.showStartDot,showEndDot:vector.showEndDot,dotRadius:vector.dotRadius})}));elements.push(...points.map((point,index)=>SvgPoint({key:`axis-point-${index}`,cx:sx(point.x),cy:sy(point.y),r:point.r??5,fill:point.fill??getToneColor(point.tone??"blue",c),stroke:point.stroke,strokeWidth:point.strokeWidth,opacity:point.opacity})));elements.push(...React9.Children.toArray(children).filter(React9.isValidElement));const svg=React9.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...elements);if(!xAxisLabel&&!yAxisLabel)return svg;return React9.createElement("div",{style:{position:"relative",width,height,display:"flex"}},svg,xAxisLabel&&React9.createElement("div",{key:"axis-x-label",style:{position:"absolute",left:width/2,bottom:0,width:width-padding*2,transform:"translateX(-50%)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:750}},xAxisLabel),yAxisLabel&&React9.createElement("div",{key:"axis-y-label",style:{position:"absolute",left:0,top:height/2,width:height-padding*2,transform:"translate(-50%, -50%) rotate(-90deg)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:11,fontWeight:750}},yAxisLabel))}import React11 from"react";import React10,{isValidElement as isValidElement2}from"react";var CANVAS_CHART_COMPONENT=Symbol.for("vizmatic.canvasChartComponent");var CHART_FRAME_COMPONENT=Symbol.for("vizmatic.chartFrameComponent");var FIT_PROP="__vizmaticCanvasChartFit";var SCOPE_PROP="data-vizmatic-chart-fit-scope";var VIEWPORT_PROP="data-vizmatic-chart-fit-viewport";function isCanvasChart(component){return typeof component==="function"&&Boolean(component[CANVAS_CHART_COMPONENT])}function CanvasChartFit({children,width,height}){let chart=children;for(let depth=0;isValidElement2(chart)&&typeof chart.type==="function"&&depth<16;depth+=1){if(chart.type[CHART_FRAME_COMPONENT]){const props=chart.props;const padding=typeof props.padding==="number"?props.padding:16;chart=React10.cloneElement(chart,{...props,width:typeof props.width==="number"?props.width+2*(padding+1):props.width,height:void 0});break}chart=chart.type(chart.props)}return React10.createElement("div",{[FIT_PROP]:{width,height},style:{position:"relative",display:"flex",width,height,flexShrink:0}},React10.createElement("div",{style:{position:"absolute",left:0,top:0,display:"flex",alignItems:"flex-start"}},chart))}function prepareChartFits(element){const sizes=new Map;const visit=(node,scope)=>{if(Array.isArray(node))return node.map(child=>visit(child,scope));if(!isValidElement2(node))return node;if(typeof node.type==="function"){const resolved=visit(node.type(node.props),scope);return node.key!=null&&isValidElement2(resolved)?React10.cloneElement(resolved,{key:node.key}):resolved}const size=node.props[FIT_PROP];const props={...node.props};delete props[FIT_PROP];if(size){const id=String(sizes.size);sizes.set(id,size);props[VIEWPORT_PROP]=id;return React10.cloneElement(node,props,visit(node.props.children,id))}if(scope!==void 0&&typeof node.type==="string")props[SCOPE_PROP]=scope;const children=node.props.children;return children===void 0?React10.cloneElement(node,props):React10.cloneElement(node,props,visit(children,scope))};return{element:visit(element),sizes}}function fittedTree(element,geometry){if(Array.isArray(element))return element.map(child=>fittedTree(child,geometry));if(!isValidElement2(element))return element;const id=element.props[VIEWPORT_PROP];const children=element.props.children;if(typeof id==="string"){const fit=geometry.get(id);const content=React10.Children.only(children);return React10.cloneElement(element,{},React10.cloneElement(content,{style:{...content.props.style,left:fit.left,top:fit.top,transform:`scale(${fit.scale})`,transformOrigin:"top left"}}))}return children===void 0?element:React10.cloneElement(element,{},fittedTree(children,geometry))}async function renderWithCanvasChartFit(render,element,options){const prepared=prepareChartFits(element);if(!prepared.sizes.size)return render(prepared.element,options);const viewports=new Map;const bounds=new Map;await render(prepared.element,{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")viewports.set(viewport,node);const id=node.props[SCOPE_PROP];if(typeof id!=="string"||node.width<=0||node.height<=0)return;const prior=bounds.get(id);bounds.set(id,{left:Math.min(prior?.left??Infinity,node.left),top:Math.min(prior?.top??Infinity,node.top),right:Math.max(prior?.right??-Infinity,node.left+node.width),bottom:Math.max(prior?.bottom??-Infinity,node.top+node.height)})}});const geometry=new Map;for(const[id,size]of prepared.sizes){const viewport=viewports.get(id);const measured=bounds.get(id);if(!viewport||!measured)throw new Error("Could not measure the chart inside CanvasItem.");const width=measured.right-measured.left,height=measured.bottom-measured.top;const scale=Math.min(size.width/width,size.height/height);if(!Number.isFinite(scale)||scale<=0)throw new Error("CanvasItem charts require positive, finite dimensions.");geometry.set(id,{...size,scale,left:(size.width-width*scale)/2-(measured.left-viewport.left)*scale,top:(size.height-height*scale)/2-(measured.top-viewport.top)*scale})}const finalViewports=new Map;return render(fittedTree(prepared.element,geometry),{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")finalViewports.set(viewport,node);const id=node.props[SCOPE_PROP];const fit=typeof id==="string"?geometry.get(id):void 0;const origin=typeof id==="string"?finalViewports.get(id):void 0;if(fit&&origin){const left=origin.left+fit.left,top=origin.top+fit.top;const style=node.props.style??{};options.onNodeDetected?.({...node,left:left+(node.left-left)*fit.scale,top:top+(node.top-top)*fit.scale,width:node.width*fit.scale,height:node.height*fit.scale,props:{...node.props,style:{...style,...typeof style.fontSize==="number"?{fontSize:style.fontSize*fit.scale}:{}}}})}else options.onNodeDetected?.(node)}})}var chartPalette=["primary","secondary","positive","warning","info","accent","critical"];function isColorName(value){return chartPalette.includes(value)||value==="neutral"}function chartColor(color,c,index=0){const resolved=color??chartPalette[index%chartPalette.length];if(!isColorName(resolved))return resolved;return getReadableColor(resolved,c)}function formatChartValue(value,format="decimal"){if(typeof format==="function")return format(value);if(format==="percent")return`${Math.round(value*100)}%`;if(format==="integer")return`${Math.round(value)}`;if(format==="compact"){const magnitude=Math.abs(value);if(magnitude>=999950)return`${(value/1e6).toFixed(1)}M`;if(magnitude>=999.95)return`${(value/1e3).toFixed(1)}k`;return`${Math.round(value)}`}return Number.isInteger(value)?`${value}`:value.toFixed(2)}function chartDomain(values,min,max){const rawMin=min??Math.min(0,...values);const rawMax=max??Math.max(...values,1);const range=rawMax===rawMin?1:rawMax-rawMin;return{min:rawMin,max:rawMax,range}}function chartTicks(min,max,count=4){if(count<=1||max===min)return[min];const step=(max-min)/(count-1);return Array.from({length:count},(_,index)=>min+step*index)}function axisTextStyle(c){return{fontFamily:"JetBrains Mono",fontSize:11,fontWeight:600,color:c.textMuted,lineHeight:1}}function createPlotArea(width,height,margin){const innerWidth=Math.max(1,width-margin.left-margin.right);const innerHeight=Math.max(1,height-margin.top-margin.bottom);return{width,height,margin,x:margin.left,y:margin.top,right:width-margin.right,bottom:height-margin.bottom,innerWidth,innerHeight}}function scaleToRange(value,min,range,outputStart,outputLength){return outputStart+(value-min)/range*outputLength}function xInPlot(value,domain,plot){return scaleToRange(value,domain.min,domain.range,plot.x,plot.innerWidth)}function yInPlot(value,domain,plot){return plot.y+plot.innerHeight-(value-domain.min)/domain.range*plot.innerHeight}function chartLabel(key,text,x,y,c,options={}){const align=options.align??"center";const width=options.width??72;const fontSize=options.fontSize??11;const labelHeight=options.height??Math.ceil(fontSize*1.4);let left=x;let top=y;let transform=options.transform??(align==="center"?"translate(-50%, -50%)":align==="right"?"translate(-100%, -50%)":"translate(0, -50%)");if(options.bounds){const padding=options.bounds.padding??4;const idealLeft=align==="center"?x-width/2:align==="right"?x-width:x;const idealTop=y-labelHeight/2;left=clamp(idealLeft,options.bounds.x+padding,options.bounds.x+options.bounds.width-width-padding);top=clamp(idealTop,options.bounds.y+padding,options.bounds.y+options.bounds.height-labelHeight-padding);transform=void 0}return React11.createElement("div",{key,style:{position:"absolute",left,top,width,...transform!==void 0?{transform}:{},display:"flex",justifyContent:align==="right"?"flex-end":align==="left"?"flex-start":"center",...textFitStyle(align),pointerEvents:"none",...axisTextStyle(c),color:options.color??c.textMuted,fontFamily:options.fontFamily??"JetBrains Mono",fontWeight:options.fontWeight??600,fontSize,lineHeight:1.15}},text)}function pointLabelPlacement(x,y,plot,index,width=70){const nearTop=y<plot.y+58;const nearBottom=y>plot.bottom-34;const nearLeft=x<plot.x+76;const nearRight=x>plot.right-76;const align=nearLeft?"left":nearRight?"right":"center";const verticalOffset=nearTop?18:nearBottom?-18:index%2===0?-16:18;return{x,y:y+verticalOffset,align,width,bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:6}}}function ChartFrame(props){return React11.createElement(ChartFrameContent,props)}function ChartFrameContent({children,c,title,subtitle,legend,footer,width="100%",height,padding=16}){return React11.createElement("div",{style:{width,...height?{height}:{},boxSizing:"border-box",display:"flex",flexDirection:"column",gap:12,padding,borderRadius:8,border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard,boxShadow:`0 9px 24px ${c.shadow}`}},(title||subtitle)&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,maxWidth:"100%"}},title&&React11.createElement("div",{style:{...typography.small,...textFitStyle(),color:c.textPrimary,fontWeight:900}},title),subtitle&&React11.createElement("div",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,lineHeight:1.35}},subtitle)),children,(legend||footer)&&React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:legend?"space-between":"center",gap:12,minHeight:18}},legend&&React11.createElement("div",{style:{display:"flex",alignItems:"center",gap:12,flexWrap:"wrap",minWidth:0}},...legend.map((item,index)=>React11.createElement("div",{key:`${item.label}-${index}`,style:{display:"flex",alignItems:"center",gap:6,minWidth:0}},React11.createElement("span",{style:{width:14,height:3,borderRadius:999,backgroundColor:chartColor(item.color,c,index),display:"flex"}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary}},item.label)))),footer&&React11.createElement("div",{style:{...typography.tiny,...textFitStyle("right"),color:c.textMuted}},footer)))}Object.defineProperty(ChartFrameContent,CHART_FRAME_COMPONENT,{value:true});function polarPoint(cx,cy,radius,angleDegrees){const radians=angleDegrees*Math.PI/180;return{x:cx+radius*Math.cos(radians),y:cy+radius*Math.sin(radians)}}function donutArcPath(cx,cy,outerRadius,innerRadius,startAngle,endAngle){const span=Math.min(359.99,Math.max(.01,endAngle-startAngle));const safeEnd=startAngle+span;const outerStart=polarPoint(cx,cy,outerRadius,startAngle);const outerEnd=polarPoint(cx,cy,outerRadius,safeEnd);const innerEnd=polarPoint(cx,cy,innerRadius,safeEnd);const innerStart=polarPoint(cx,cy,innerRadius,startAngle);const largeArc=span>180?1:0;return[`M ${outerStart.x} ${outerStart.y}`,`A ${outerRadius} ${outerRadius} 0 ${largeArc} 1 ${outerEnd.x} ${outerEnd.y}`,`L ${innerEnd.x} ${innerEnd.y}`,`A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}`,"Z"].join(" ")}function validateNonNegativeSegments(segments,chartName){let total=0;for(const segment of segments){if(!Number.isFinite(segment.value)||segment.value<0){throw new RangeError(`${chartName} values must be finite, non-negative numbers.`)}total+=segment.value;if(!Number.isFinite(total)){throw new RangeError(`${chartName} total must be finite.`)}}return total}function pieSectorPath(cx,cy,radius,startAngle,endAngle){const span=endAngle-startAngle;const start=polarPoint(cx,cy,radius,startAngle);if(span>=359.999){const opposite=polarPoint(cx,cy,radius,startAngle+180);return[`M ${cx} ${cy}`,`L ${start.x} ${start.y}`,`A ${radius} ${radius} 0 1 1 ${opposite.x} ${opposite.y}`,`A ${radius} ${radius} 0 1 1 ${start.x} ${start.y}`,"Z"].join(" ")}const end=polarPoint(cx,cy,radius,endAngle);const largeArc=span>180?1:0;return`M ${cx} ${cy} L ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArc} 1 ${end.x} ${end.y} Z`}function PieChart({segments,c,title,subtitle,width=360,height=240,size,format="decimal",showLegend=true,footer}){const total=validateNonNegativeSegments(segments,"PieChart");const positiveSegments=segments.filter(segment=>segment.value>0);const resolvedSize=size??Math.min(184,Math.max(132,height-44),Math.max(132,width*.5));const radius=resolvedSize/2-2;const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const paths=positiveSegments.map((segment,index)=>{const span=total>0?segment.value/total*360:0;const start=cursor;const end=index===positiveSegments.length-1?270:cursor+span;cursor+=span;return React11.createElement("path",{key:`pie-segment-${segment.label}-${index}`,d:pieSectorPath(cx,cy,radius,start,end),fill:chartColor(segment.color,c,index),stroke:c.bgCard,strokeWidth:positiveSegments.length>1?2:0,"data-pie-label":segment.label,"data-pie-value":segment.value,"data-pie-share":total>0?segment.value/total:0})});const legend=showLegend&&positiveSegments.length>0&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>{const formattedValue=formatChartValue(segment.value,format);const share=formatChartValue(segment.value/total,"percent");const label=segment.valueLabel??(format==="percent"?formattedValue:`${formattedValue} \xB7 ${share}`);return React11.createElement("div",{key:`pie-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:8,minWidth:0}},React11.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:3,backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React11.createElement("span",{style:{...typography.tiny,color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:850,flexShrink:0}},label))}));return ChartFrame({c,title,subtitle,footer,width,children:React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:18,minHeight:resolvedSize,width:"100%"}},React11.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`,role:"img","aria-label":title??"Pie chart"},positiveSegments.length===0?React11.createElement("circle",{cx,cy,r:radius,fill:"none",stroke:c.borderLight,strokeWidth:2}):paths),legend)})}function DonutChart({segments,c,title,subtitle,width=360,height=230,size,thickness,format="decimal",centerLabel,centerValue,showLegend=true,footer}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);const resolvedSize=size??Math.min(162,Math.max(128,height-44),Math.max(128,width*.48));const resolvedThickness=thickness??Math.max(20,Math.round(resolvedSize*.18));const outerRadius=resolvedSize/2-2;const innerRadius=Math.max(18,outerRadius-resolvedThickness);const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const resolvedCenterValue=centerValue??(centerLabel!=null?formatChartValue(total,format):void 0);const paths=positiveSegments.map((segment,index)=>{const rawSpan=total>0?segment.value/total*360:0;const gap=positiveSegments.length>1?Math.min(1.5,rawSpan*.28):0;const start=cursor+gap/2;const end=cursor+rawSpan-gap/2;cursor+=rawSpan;if(end<=start)return null;return React11.createElement("path",{key:`donut-segment-${segment.label}-${index}`,d:donutArcPath(cx,cy,outerRadius,innerRadius,start,end),fill:chartColor(segment.color,c,index)})}).filter(Boolean);const legend=showLegend&&positiveSegments.length>0&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8,flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>React11.createElement("div",{key:`donut-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:8,minWidth:0}},React11.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:3,backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React11.createElement("span",{style:{...typography.tiny,...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React11.createElement("span",{style:{...typography.tiny,color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:850,flexShrink:0}},segment.valueLabel??formatChartValue(segment.value,format)))));return ChartFrame({c,title,subtitle,footer,width,height,padding:16,children:React11.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:18,minHeight:resolvedSize,width:"100%"}},React11.createElement("div",{style:{position:"relative",display:"flex",width:resolvedSize,height:resolvedSize,flexShrink:0}},React11.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`},positiveSegments.length===0?React11.createElement("circle",{cx,cy,r:(outerRadius+innerRadius)/2,fill:"none",stroke:c.borderLight,strokeWidth:resolvedThickness}):paths),(centerLabel!=null||resolvedCenterValue!=null)&&React11.createElement("div",{style:{position:"absolute",top:resolvedThickness,left:resolvedThickness,width:Math.max(0,resolvedSize-resolvedThickness*2),height:Math.max(0,resolvedSize-resolvedThickness*2),display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:3,textAlign:"center"}},resolvedCenterValue!=null&&React11.createElement("div",{style:{...typography.small,color:c.textPrimary,fontFamily:"JetBrains Mono",fontSize:18,fontWeight:900,lineHeight:1.05,...textFitStyle("center")}},resolvedCenterValue),centerLabel!=null&&React11.createElement("div",{style:{...typography.tiny,color:c.textMuted,lineHeight:1.2,...textFitStyle("center")}},centerLabel))),legend)})}function StackedBar({segments,c,width=480,height=68,title,subtitle,showLegend=true}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);return React11.createElement("div",{style:{width,display:"flex",flexDirection:"column",gap:10}},(title||subtitle)&&React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:3}},title&&React11.createElement("div",{style:{...typography.label,color:c.textPrimary,fontWeight:850}},title),subtitle&&React11.createElement("div",{style:{...typography.tiny,color:c.textSecondary}},subtitle)),React11.createElement("div",{style:{width,height,display:"flex",overflow:"hidden",borderRadius:14,border:`1px solid ${c.borderLight}`,backgroundColor:c.bgCard,boxShadow:`0 8px 22px ${c.shadow}`}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;const segmentWidth=width*share;const color=chartColor(segment.color,c,index);return React11.createElement("div",{key:`${segment.label}-${index}`,style:{width:`${share*100}%`,height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,...index<positiveSegments.length-1?{borderRight:`2px solid ${c.bgSubtle}`}:{}}},segmentWidth>=64&&React11.createElement("span",{style:{...typography.small,color:getReadableTextColor(color,c),fontWeight:900,whiteSpace:"nowrap"}},segment.valueLabel??formatChartValue(share,"percent")))})),showLegend&&React11.createElement("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap"}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;return React11.createElement("div",{key:`legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:7}},React11.createElement("span",{style:{width:12,height:12,borderRadius:4,display:"flex",backgroundColor:chartColor(segment.color,c,index)}}),React11.createElement("span",{style:{...typography.tiny,color:c.textSecondary}},`${segment.label} ${segment.valueLabel??formatChartValue(share,"percent")}`))})))}function BarChart({data,c,title,subtitle,width=320,height=220,min,max,format="decimal",showGrid=true,showValues=true,yAxisLabel,footer}){const margin={top:18,right:38,bottom:40,left:yAxisLabel?52:38};const plot=createPlotArea(width,height,margin);const domain=chartDomain(data.map(item=>item.value),min,max);const ticks=chartTicks(domain.min,domain.max,4);const barSlot=plot.innerWidth/Math.max(data.length,1);const barWidth=Math.max(8,Math.min(76,barSlot*.72));const zeroY=yInPlot(0,domain,plot);const baselineY=clamp(zeroY,plot.y,plot.bottom);const barGeometries=data.map((item,index)=>{const x=plot.x+index*barSlot+(barSlot-barWidth)/2;const valueY=clamp(yInPlot(item.value,domain,plot),plot.y,plot.bottom);const distance=Math.abs(baselineY-valueY);const barHeight=Math.min(plot.innerHeight,Math.max(4,distance));const growsUp=valueY<baselineY||valueY===baselineY&&item.value>=0;const y=growsUp?Math.max(plot.y,baselineY-barHeight):Math.min(plot.bottom-barHeight,baselineY);return{item,index,x,y,barHeight,valueY,color:chartColor(item.color,c,index)}});return ChartFrame({c,title,subtitle,width,footer,children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React11.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React11.createElement("line",{key:`tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.y,x2:plot.x,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.x,y1:baselineY,x2:plot.right,y2:baselineY,stroke:c.borderLight,strokeWidth:1.2}),...barGeometries.map(({item,index,x,y,barHeight,color})=>React11.createElement("rect",{key:`${item.label}-${index}`,x,y,width:barWidth,height:barHeight,rx:5,fill:color,opacity:.92}))),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`tick-label-${tick}`,formatChartValue(tick,format),plot.x-8,y,c,{align:"right",width:36})}),yAxisLabel&&chartLabel("y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...barGeometries.flatMap(({item,index,x,y,barHeight,valueY})=>[...showValues?[chartLabel(`bar-value-${index}`,item.valueLabel??formatChartValue(item.value,format),x+barWidth/2,item.value<0?y+barHeight+12:clamp(valueY-8,10,height-28),c,{color:c.textPrimary,fontWeight:800,width:54,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]:[],chartLabel(`bar-label-${index}`,item.label,x+barWidth/2,height-16,c,{width:54})]))})}function ParetoBarChart({data,c,title,subtitle,width=520,height=300,format="integer",showGrid=true,showValues=true,footer}){let total=0;for(const item of data){if(!Number.isFinite(item.value)||item.value<0){throw new RangeError("ParetoBarChart values must be finite, non-negative numbers.")}total+=item.value;if(!Number.isFinite(total)){throw new RangeError("ParetoBarChart total must be finite.")}}const sorted=data.map((item,index)=>({item,index})).sort((left,right)=>right.item.value-left.item.value||left.index-right.index);const maximum=Math.max(1,...sorted.map(({item})=>item.value));const margin={top:24,right:48,bottom:48,left:48};const plot=createPlotArea(width,height,margin);const valueDomain={min:0,range:maximum>Number.MAX_VALUE/1.16?maximum:maximum*1.16};const countTicks=chartTicks(0,maximum,4);const slot=plot.innerWidth/Math.max(sorted.length,1);const barWidth=Math.max(6,Math.min(68,slot*.68));let accumulated=0;const bars=sorted.map(({item,index},order)=>{accumulated+=item.value;const cumulative=total===0?0:order===sorted.length-1?1:accumulated/total;const x=plot.x+order*slot+(slot-barWidth)/2;const top=yInPlot(item.value,valueDomain,plot);return{item,sourceIndex:index,order,x,y:top,height:Math.max(0,plot.bottom-top),color:chartColor(item.color,c,order),centerX:x+barWidth/2,cumulative,cumulativeY:plot.bottom-cumulative*plot.innerHeight}});const cumulativePath=bars.map(({centerX,cumulativeY},index)=>`${index===0?"M":"L"} ${centerX.toFixed(1)} ${cumulativeY.toFixed(1)}`).join(" ");return ChartFrame({c,title,subtitle,width,footer,children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,role:"img","aria-label":title??"Pareto bar chart"},showGrid&&React11.createElement("g",{},...countTicks.map(tick=>{const y=yInPlot(tick,valueDomain,plot);return React11.createElement("line",{key:`pareto-count-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.right,y1:plot.y,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...bars.map(({item,order,x,y,height:barHeight,color})=>React11.createElement("rect",{key:`pareto-bar-${item.label}-${order}`,x,y,width:barWidth,height:barHeight,rx:4,fill:color,opacity:.86,"data-pareto-bar":item.label,"data-pareto-value":item.value,"data-pareto-order":order})),cumulativePath&&React11.createElement("path",{d:cumulativePath,fill:"none",stroke:chartColor("critical",c),strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round","data-pareto-cumulative-line":true}),...bars.map(({item,sourceIndex,centerX,cumulativeY,cumulative,order})=>React11.createElement("circle",{key:`pareto-cumulative-point-${order}`,cx:centerX,cy:cumulativeY,r:4,fill:chartColor("critical",c),stroke:c.bgCard,strokeWidth:2,"data-pareto-category":item.label,"data-pareto-source-index":sourceIndex,"data-pareto-cumulative-percent":cumulative*100}))),...countTicks.map(tick=>chartLabel(`pareto-count-label-${tick}`,formatChartValue(tick,format),plot.x-7,yInPlot(tick,valueDomain,plot),c,{align:"right",width:36})),...[0,.5,1].map(share=>chartLabel(`pareto-percent-label-${share}`,`${Math.round(share*100)}%`,plot.right+7,plot.bottom-share*plot.innerHeight,c,{align:"left",width:38})),...bars.flatMap(({item,order,centerX,y})=>[...showValues?[chartLabel(`pareto-value-${order}`,item.valueLabel??formatChartValue(item.value,format),centerX,clamp(y-8,plot.y+8,plot.bottom-12),c,{color:c.textPrimary,fontWeight:800,width:Math.min(slot,64),bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight}})]:[],chartLabel(`pareto-category-${order}`,item.label,centerX,height-17,c,{width:Math.max(1,Math.min(96,slot-2)),bounds:{x:plot.x,y:plot.bottom+1,width:plot.innerWidth,height:Math.max(1,height-plot.bottom-2),padding:0}})]))})}function LineChart({series,c,title,subtitle,width=420,height=240,labels,min,max,format="decimal",showGrid=true,showPoints=true,yAxisLabel,footer}){const margin={top:18,right:20,bottom:labels?36:24,left:yAxisLabel?54:40};const plot=createPlotArea(width,height,margin);const allValues=series.flatMap(item=>item.points);const domain=chartDomain(allValues,min,max);const maxPoints=Math.max(labels?.length??0,...series.map(item=>item.points.length),1);const xInset=maxPoints<=1?0:Math.min(26,Math.max(14,plot.innerWidth*.06));const xStart=maxPoints<=1?plot.x+plot.innerWidth/2:plot.x+xInset;const xSpan=maxPoints<=1?0:Math.max(1,plot.innerWidth-xInset*2);const xStep=maxPoints<=1?0:xSpan/(maxPoints-1);const ticks=chartTicks(domain.min,domain.max,4);const pointFor=(value,index)=>{const x=xStart+index*xStep;const markerInset=showPoints?6.5:2;const y=clamp(yInPlot(value,domain,plot),plot.y+markerInset,plot.bottom-markerInset);return{x,y}};const pathFor=points=>points.map((value,index)=>{const point=pointFor(value,index);return`${index===0?"M":"L"} ${point.x.toFixed(1)} ${point.y.toFixed(1)}`}).join(" ");return ChartFrame({c,title,subtitle,width,footer,legend:series.map((item,index)=>({label:item.name,color:item.color??chartPalette[index%chartPalette.length]})),children:React11.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React11.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React11.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React11.createElement("line",{key:`line-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React11.createElement("line",{x1:plot.x,y1:plot.y,x2:plot.x,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),React11.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...series.flatMap((item,seriesIndex)=>{if(item.points.length===0)return[];const color=chartColor(item.color,c,seriesIndex);const linePath=pathFor(item.points);let areaPath="";if(item.area&&item.points.length>1){const firstPoint=pointFor(item.points[0],0);const lastPoint=pointFor(item.points[item.points.length-1],item.points.length-1);areaPath=`${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`}const elements=[];if(areaPath){elements.push(React11.createElement("path",{key:`${item.name}-area`,d:areaPath,fill:color,opacity:.12}))}elements.push(React11.createElement("path",{key:`${item.name}-line`,d:linePath,fill:"none",stroke:color,strokeWidth:4,strokeLinecap:"round",strokeLinejoin:"round"}));if(showPoints){elements.push(...item.points.map((value,index)=>{const point=pointFor(value,index);return React11.createElement("circle",{key:`${item.name}-point-${index}`,cx:point.x,cy:point.y,r:5,fill:c.bgCard,stroke:color,strokeWidth:3})}))}return elements})),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`line-tick-label-${tick}`,formatChartValue(tick,format),plot.x-8,y,c,{align:"right",width:36})}),yAxisLabel&&chartLabel("line-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...(labels??[]).map((label,index)=>{const x=xStart+index*xStep;return chartLabel(`line-x-${label}`,label,x,height-14,c,{width:72})}))})}for(const chart of[PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}import React12 from"react";for(const chart of[ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}function xTickLabelAlign(index,count){if(index===0)return"left";if(index===count-1)return"right";return"center"}function ScatterPlot({points,c,title,subtitle,width=380,height=260,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,footer}){const margin={top:20,right:24,bottom:xAxisLabel?46:34,left:yAxisLabel?54:42};const plot=createPlotArea(width,height,margin);const xDomain=chartDomain(points.map(item=>item.x),xMin,xMax);const yDomain=chartDomain(points.map(item=>item.y),yMin,yMax);const xTicks=chartTicks(xDomain.min,xDomain.max,4);const yTicks=chartTicks(yDomain.min,yDomain.max,4);const pointFor=(xValue,yValue)=>({x:xInPlot(xValue,xDomain,plot),y:yInPlot(yValue,yDomain,plot)});const pointGeometries=points.map((item,index)=>{const point=pointFor(item.x,item.y);return{item,index,point,color:chartColor(item.color,c,index)}});return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`x-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`y-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),...pointGeometries.map(({item,index,point,color})=>React12.createElement("circle",{key:`${item.label??"point"}-${index}`,cx:point.x,cy:point.y,r:item.size??7,fill:color,opacity:.92,stroke:c.bgCard,strokeWidth:2}))),...xTicks.map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:44})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:36})}),xAxisLabel&&chartLabel("scatter-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("scatter-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({item,index,point,color})=>{if(!item.label)return[];const placement=pointLabelPlacement(point.x,point.y,plot,index);return[chartLabel(`scatter-point-label-${index}`,item.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color,fontWeight:800})]}))})}function pointDominates(candidate,point,xObjective,yObjective){const xNoWorse=xObjective==="minimize"?candidate.x<=point.x:candidate.x>=point.x;const yNoWorse=yObjective==="minimize"?candidate.y<=point.y:candidate.y>=point.y;const xBetter=xObjective==="minimize"?candidate.x<point.x:candidate.x>point.x;const yBetter=yObjective==="minimize"?candidate.y<point.y:candidate.y>point.y;return xNoWorse&&yNoWorse&&(xBetter||yBetter)}function paretoFrontierIndices(points,xObjective,yObjective){const frontier=new Set;for(const candidate of points){const dominated=points.some(({point})=>pointDominates(point,candidate.point,xObjective,yObjective));if(!dominated)frontier.add(candidate.index)}return frontier}function positiveLogDomain(values,min,max){const positiveValues=values.filter(value=>Number.isFinite(value)&&value>0);const positiveMin=min!==void 0&&Number.isFinite(min)&&min>0?min:Math.min(...positiveValues,1);const fallbackMax=Math.max(...positiveValues,positiveMin*10);const positiveMax=max!==void 0&&Number.isFinite(max)&&max>0?max:fallbackMax;const safeMin=Math.max(Number.MIN_VALUE,positiveMin);const safeMax=positiveMax>safeMin?positiveMax:safeMin*10;return{min:safeMin,max:safeMax,range:Math.log(safeMax)-Math.log(safeMin)}}function logChartTicks(min,max,count=5){if(!(min>0)||!(max>min)||count<=1)return[min];const startPower=Math.ceil(Math.log10(min));const endPower=Math.floor(Math.log10(max));const powers=Array.from({length:Math.max(0,endPower-startPower+1)},(_,index)=>10**(startPower+index)).filter(value=>value>=min&&value<=max);if(powers.length>=4)return powers;return Array.from({length:count},(_,index)=>min*(max/min)**(index/(count-1)))}function ParetoChart({points,c,title,subtitle,width=640,height=360,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,xScale="linear",xObjective="minimize",yObjective="maximize",frontierColor,showGoal=true,goalLabel,footer}){const margin={top:22,right:26,bottom:xAxisLabel?48:36,left:yAxisLabel?56:44};const plot=createPlotArea(width,height,margin);const validPoints=points.map((point,index)=>({point,index})).filter(({point})=>Number.isFinite(point.x)&&Number.isFinite(point.y)&&(xScale!=="log"||point.x>0));const frontierIndices=paretoFrontierIndices(validPoints,xObjective,yObjective);const xDomain=xScale==="log"?positiveLogDomain(validPoints.map(({point})=>point.x),xMin,xMax):chartDomain(validPoints.map(({point})=>point.x),xMin,xMax);const yDomain=chartDomain(validPoints.map(({point})=>point.y),yMin,yMax);const xTicks=xScale==="log"?logChartTicks(xDomain.min,xDomain.max):chartTicks(xDomain.min,xDomain.max,5);const yTicks=chartTicks(yDomain.min,yDomain.max,5);const frontier=chartColor(frontierColor??"positive",c,0);const pointFor=(xValue,yValue)=>{const x=xScale==="log"?plot.x+(Math.log(xValue>0?xValue:xDomain.min)-Math.log(xDomain.min))/xDomain.range*plot.innerWidth:xInPlot(xValue,xDomain,plot);return{x:clamp(x,plot.x,plot.right),y:clamp(yInPlot(yValue,yDomain,plot),plot.y,plot.bottom)}};const pointGeometries=validPoints.map(({point,index})=>{const pointPosition=pointFor(point.x,point.y);const isFrontier=frontierIndices.has(index);return{point,index,x:pointPosition.x,y:pointPosition.y,color:chartColor(point.color??(isFrontier?frontier:"neutral"),c,index),frontier:isFrontier}});const frontierGeometries=pointGeometries.filter(geometry=>geometry.frontier).sort((left,right)=>left.point.x-right.point.x);const frontierPath=frontierGeometries.length>1?frontierGeometries.map((geometry,index)=>`${index===0?"M":"L"} ${geometry.x.toFixed(1)} ${geometry.y.toFixed(1)}`).join(" "):void 0;const goalText=goalLabel??`goal: ${xObjective==="minimize"?"lower x":"higher x"} \xB7 ${yObjective==="maximize"?"higher y":"lower y"}`;const goalXStart=plot.right-72;const goalY=plot.y+18;const goalXEnd=xObjective==="minimize"?goalXStart-26:goalXStart+26;const goalYStart=plot.y+52;const goalYEnd=yObjective==="maximize"?goalYStart-26:goalYStart+26;const arrowSize=5;return ChartFrame({c,title,subtitle,width,footer,legend:[{label:"Pareto frontier",color:frontier},{label:"dominated",color:"neutral"}],children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=pointFor(tick,yDomain.min).x;return React12.createElement("line",{key:`pareto-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`pareto-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),showGoal&&React12.createElement("g",{"data-pareto-goal":true,stroke:frontier,fill:"none",strokeWidth:2,strokeLinecap:"round"},React12.createElement("line",{x1:goalXStart,y1:goalY,x2:goalXEnd,y2:goalY}),React12.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY-arrowSize}),React12.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY+arrowSize}),React12.createElement("line",{x1:goalXStart,y1:goalYStart,x2:goalXStart,y2:goalYEnd}),React12.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart-arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)}),React12.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart+arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)})),frontierPath&&React12.createElement("path",{"data-pareto-frontier":true,d:frontierPath,fill:"none",stroke:frontier,strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"}),...pointGeometries.filter(geometry=>!geometry.frontier).concat(pointGeometries.filter(geometry=>geometry.frontier)).map(({point,index,x,y,color,frontier:isFrontier})=>React12.createElement("circle",{key:`pareto-point-${point.label??"point"}-${index}`,"data-pareto-status":isFrontier?"frontier":"dominated",cx:x,cy:y,r:Math.max(4,Math.min(20,point.size??(isFrontier?8:7))),fill:color,opacity:isFrontier?1:.38,stroke:isFrontier?frontier:c.bgCard,strokeWidth:isFrontier?3:2}))),...xTicks.map((tick,index)=>{const x=pointFor(tick,yDomain.min).x;return chartLabel(`pareto-x-tick-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:52})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`pareto-y-tick-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:42})}),showGoal&&chartLabel("pareto-goal-label",goalText,plot.right-2,plot.y+9,c,{align:"right",width:170,color:frontier,fontWeight:850,fontSize:11,bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:4}}),xAxisLabel&&chartLabel("pareto-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("pareto-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({point,index,x,y,color,frontier:isFrontier})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`pareto-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color:isFrontier?color:c.textMuted,fontWeight:isFrontier?850:600})]}))})}function QuadrantChart({points,regions,c,title,subtitle,width=700,height=360,xMin,xMax,yMin,yMax,xThreshold,yThreshold,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showTicks=false,showGrid=false,footer}){const margin={top:18,right:20,bottom:xAxisLabel?showTicks?58:46:showTicks?36:24,left:yAxisLabel?showTicks?72:54:showTicks?48:24};const plot=createPlotArea(width,height,margin);const xDomain=xMin===void 0&&xMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.x),xMin,xMax);const yDomain=yMin===void 0&&yMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.y),yMin,yMax);const resolvedXThreshold=clamp(xThreshold??xDomain.min+xDomain.range/2,xDomain.min,xDomain.max);const resolvedYThreshold=clamp(yThreshold??yDomain.min+yDomain.range/2,yDomain.min,yDomain.max);const midX=xInPlot(resolvedXThreshold,xDomain,plot);const midY=yInPlot(resolvedYThreshold,yDomain,plot);const xTicks=showTicks||showGrid?chartTicks(xDomain.min,xDomain.max,5):[];const yTicks=showTicks||showGrid?chartTicks(yDomain.min,yDomain.max,5):[];const regionEntries=[{key:"top-left",region:regions.topLeft,x:plot.x,y:plot.y,width:midX-plot.x,height:midY-plot.y},{key:"top-right",region:regions.topRight,x:midX,y:plot.y,width:plot.right-midX,height:midY-plot.y},{key:"bottom-left",region:regions.bottomLeft,x:plot.x,y:midY,width:midX-plot.x,height:plot.bottom-midY},{key:"bottom-right",region:regions.bottomRight,x:midX,y:midY,width:plot.right-midX,height:plot.bottom-midY}];const pointGeometries=points.map((point,index)=>({point,index,x:xInPlot(clamp(point.x,xDomain.min,xDomain.max),xDomain,plot),y:yInPlot(clamp(point.y,yDomain.min,yDomain.max),yDomain,plot),color:chartColor(point.color,c,index)}));return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...regionEntries.map(({key,region,x,y,width:regionWidth,height:regionHeight},index)=>{const color=chartColor(region.color,c,index);const emphasized=region.emphasis===true;return React12.createElement("rect",{key:`quadrant-${key}`,x,y,width:regionWidth,height:regionHeight,fill:color,opacity:emphasized?.2:.1,stroke:emphasized?color:"transparent",strokeWidth:emphasized?2:0})}),showGrid&&React12.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`quadrant-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`quadrant-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React12.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:8}),React12.createElement("line",{x1:midX,y1:plot.y,x2:midX,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.4}),React12.createElement("line",{x1:plot.x,y1:midY,x2:plot.right,y2:midY,stroke:c.borderLight,strokeWidth:1.4}),...(showTicks?xTicks:[]).map(tick=>{const x=xInPlot(tick,xDomain,plot);return React12.createElement("line",{key:`quadrant-x-tick-${tick}`,x1:x,y1:plot.bottom,x2:x,y2:plot.bottom+5,stroke:c.textMuted,strokeWidth:1.2})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return React12.createElement("line",{key:`quadrant-y-tick-${tick}`,x1:plot.x-5,y1:y,x2:plot.x,y2:y,stroke:c.textMuted,strokeWidth:1.2})}),...pointGeometries.map(({point,index,x,y,color})=>React12.createElement("circle",{key:`quadrant-point-${point.label??index}`,cx:x,cy:y,r:point.size??8,fill:color,stroke:c.bgCard,strokeWidth:3}))),...regionEntries.flatMap(({key,region,x,y,width:regionWidth},index)=>{const color=chartColor(region.color,c,index);return[chartLabel(`quadrant-label-${key}`,region.label,x+regionWidth/2,y+18,c,{width:Math.max(1,regionWidth-24),color,fontFamily:"Inter",fontWeight:900,fontSize:11}),...region.detail?[chartLabel(`quadrant-detail-${key}`,region.detail,x+regionWidth/2,y+34,c,{width:Math.max(1,regionWidth-24),color:c.textMuted,fontSize:11})]:[]]}),...(showTicks?xTicks:[]).map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`quadrant-x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:54})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`quadrant-y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-9,y,c,{align:"right",width:48})}),...pointGeometries.flatMap(({point,index,x,y,color})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`quadrant-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:110,bounds:placement.bounds,color,fontFamily:"Inter",fontWeight:850,fontSize:11})]}),xAxisLabel&&chartLabel("quadrant-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("quadrant-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}))})}function IntervalPlot({data,c,title,subtitle,width=640,height=220,min,max,format="decimal",axisLabel,footer}){const margin={top:22,right:28,bottom:axisLabel?44:30,left:96};const plot=createPlotArea(width,height,margin);const rowGap=data.length<=1?0:plot.innerHeight/data.length;const domain=chartDomain(data.flatMap(item=>[item.low,item.mid,item.high]),min,max);const ticks=chartTicks(domain.min,domain.max,5);const scaleX=value=>xInPlot(value,domain,plot);const rows=data.map((item,index)=>{const y=data.length<=1?plot.y+plot.innerHeight/2:plot.y+rowGap*index+rowGap/2;return{item,index,y,color:chartColor(item.color,c,index),lowX:scaleX(item.low),midX:scaleX(item.mid),highX:scaleX(item.high)}});return ChartFrame({c,title,subtitle,width,footer,children:React12.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React12.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...ticks.map(tick=>{const x=scaleX(tick);return React12.createElement("line",{key:`interval-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),React12.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...rows.flatMap(({item,index,y,color,lowX,midX,highX})=>[React12.createElement("line",{key:`${item.label}-range-${index}`,x1:lowX,y1:y,x2:highX,y2:y,stroke:color,strokeWidth:9,strokeLinecap:"round",opacity:.9}),React12.createElement("circle",{key:`${item.label}-mid-${index}`,cx:midX,cy:y,r:10,fill:c.bgCard,stroke:color,strokeWidth:4})])),...ticks.map((tick,index)=>{const x=scaleX(tick);return chartLabel(`interval-tick-label-${tick}`,formatChartValue(tick,format),x,height-margin.bottom+17,c,{align:xTickLabelAlign(index,ticks.length),width:48})}),axisLabel&&chartLabel("interval-axis-label",axisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),...rows.flatMap(({item,index,y,lowX,midX,highX})=>[chartLabel(`interval-row-label-${index}`,item.label,plot.x-12,y,c,{align:"right",width:84,color:c.textPrimary,fontFamily:"Inter",fontWeight:900}),chartLabel(`interval-low-${index}`,item.lowLabel??formatChartValue(item.low,format),lowX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}}),chartLabel(`interval-mid-${index}`,item.midLabel??formatChartValue(item.mid,format),midX,y-16,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height},color:c.textPrimary,fontWeight:900}),chartLabel(`interval-high-${index}`,item.highLabel??formatChartValue(item.high,format),highX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]))})}function Badge({label,c,color="primary"}){const solidColor=getReadableColor(color,c);return React12.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:withColorAlpha(solidColor,32/255),color:solidColor,borderRadius:999,padding:"4px 12px",fontSize:11,fontWeight:600,fontFamily:"Inter",border:`1px solid ${withColorAlpha(solidColor,64/255)}`}},label)}function DotPoint({x,y,label,color,c,size=12,labelOffset}){const offX=labelOffset?.x??0;const offY=labelOffset?.y??-22;return[React12.createElement("div",{key:`dot-${label}`,style:{position:"absolute",left:x-size/2,top:y-size/2,width:size,height:size,borderRadius:"50%",backgroundColor:color,boxShadow:`0 0 14px ${withColorAlpha(color,80/255)}`,display:"flex"}}),React12.createElement("div",{key:`label-${label}`,style:{position:"absolute",left:x+offX-30,top:y+offY,fontSize:13,fontWeight:600,color:c.textPrimary,fontFamily:"JetBrains Mono",textAlign:"center",width:60}},label)]}function DashedLine({x1,y1,x2,y2,color,dotSpacing=8,dotSize=2}){const dx=x2-x1;const dy=y2-y1;const length=Math.sqrt(dx*dx+dy*dy);const numDots=Math.max(1,Math.floor(length/dotSpacing));const dots=[];for(let i=0;i<numDots;i++){if(i%2===1)continue;const t=i/numDots;dots.push(React12.createElement("div",{key:`dash-${i}`,style:{position:"absolute",left:x1+t*dx-dotSize/2,top:y1+t*dy-dotSize/2,width:dotSize,height:dotSize,borderRadius:"50%",backgroundColor:color}}))}return dots}function Legend({items,c,title}){return React12.createElement("div",{style:{display:"flex",flexDirection:"column",gap:10,backgroundColor:c.bgCard,borderRadius:8,border:`1px solid ${c.borderSubtle}`,padding:"14px 16px"}},title&&React12.createElement("div",{style:{fontSize:11,fontWeight:700,color:c.textSecondary,textTransform:"uppercase",letterSpacing:1,fontFamily:"Inter"}},title),...items.map((item,i)=>React12.createElement("div",{key:`legend-${i}`,style:{display:"flex",alignItems:"center",gap:8}},React12.createElement("div",{style:{width:16,height:item.style==="dashed"?0:2,backgroundColor:item.color,...item.style==="dashed"?{borderTop:`2px dashed ${item.color}`}:{}}}),React12.createElement("div",{style:{fontSize:11,color:c.textMuted,fontFamily:"Inter"}},item.label))))}import React13 from"react";var CANVAS_ITEM_COMPONENT=Symbol.for("vizmatic.canvas-item");function dimension(value,name){if(value!==void 0&&(!Number.isFinite(value)||value<=0||value>8192)){throw new Error(`${name} must be a finite number greater than 0 and at most 8192.`)}return value}function Board({children,c,width=960,height=540,background}){return React13.createElement("div",{style:{display:"flex",position:"relative",width:dimension(width,"Board width"),height:dimension(height,"Board height"),overflow:"hidden",backgroundColor:background??"transparent",color:c.textPrimary}},children)}function CanvasItem({children,x,y,width,height}){if(!Number.isFinite(x)||!Number.isFinite(y))throw new Error("CanvasItem x and y must be finite numbers.");const sizedChildren=React13.Children.map(children,child=>{if(!React13.isValidElement(child))return child;const sized=React13.cloneElement(child,{...width!==void 0?{width}:{},...height!==void 0?{height}:{}});return width!==void 0&&height!==void 0&&isCanvasChart(child.type)?React13.createElement(CanvasChartFit,{width,height,__vizmaticTextScope:child.props.__vizmaticTextScope},sized):sized});return React13.createElement("div",{style:{display:"flex",position:"absolute",left:x,top:y,width:dimension(width,"CanvasItem width"),height:dimension(height,"CanvasItem height"),alignItems:"stretch"}},sizedChildren)}Object.defineProperty(CanvasItem,CANVAS_ITEM_COMPONENT,{value:true});import{Resvg}from"@resvg/resvg-js";import{homedir}from"os";import{readFile,writeFile,mkdir}from"fs/promises";import{dirname,join}from"path";import{existsSync}from"fs";import{fileURLToPath}from"url";import{brotliDecompressSync}from"zlib";import React14 from"react";var DEFAULT_WATERMARK_TEXT="Vizmatic";var WATERMARK_COLOR_DARK="#a78bfa";var WATERMARK_COLOR_LIGHT="#7c3aed";function VizmaticIcon({size=14,color}){return React14.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:size,height:size,viewBox:"0 0 28 28",fill:"none"},React14.createElement("rect",{x:2.5,y:2.5,width:23,height:23,rx:6.5,stroke:color,strokeWidth:2,opacity:.54}),React14.createElement("rect",{x:7,y:7,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.35}),React14.createElement("rect",{x:15.5,y:7,width:5.5,height:5.5,rx:1.8,fill:color}),React14.createElement("rect",{x:7,y:15.5,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.82}),React14.createElement("rect",{x:15.5,y:15.5,width:5.5,height:5.5,rx:1.8,stroke:color,strokeWidth:1.5,opacity:.72}),React14.createElement("path",{d:"M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5",stroke:color,strokeWidth:1.6,strokeLinecap:"round",opacity:.88}))}function normalizeWatermark(watermark){if(watermark==null||watermark===false)return void 0;if(watermark===true)return{};if(typeof watermark==="string")return{text:watermark};if(React14.isValidElement(watermark)){if(watermark.type!==Watermark)return{element:watermark};const{children,...props}=watermark.props;return{...props,element:children??props.element}}return watermark}function Watermark(_props){return null}function positionStyle(position){switch(position){case"top-left":return{top:8,left:10};case"bottom-left":return{bottom:8,left:10};case"bottom-right":return{bottom:8,right:10};case"top-right":default:return{top:8,right:10}}}function imageNode(image){if(!image)return void 0;const imageOptions=typeof image==="string"?{src:image}:image;return React14.createElement("img",{src:imageOptions.src,alt:imageOptions.alt??"",width:imageOptions.width??14,height:imageOptions.height??14,style:{display:"block",width:imageOptions.width??14,height:imageOptions.height??14,objectFit:"contain"}})}function iconNode(icon,color){if(icon===false)return void 0;if(icon==null)return React14.createElement(VizmaticIcon,{size:13,color});if(typeof icon!=="string")return icon;return React14.createElement("div",{style:{minWidth:13,height:13,display:"flex",alignItems:"center",justifyContent:"center",color,fontSize:icon.length>2?8:10,fontWeight:800,fontFamily:"Inter",lineHeight:1}},icon)}function wrapWithWatermark(element,width,height,theme="dark",watermark=true){const isDark=theme==="dark";const options=normalizeWatermark(watermark);const color=options?.color??(isDark?WATERMARK_COLOR_DARK:WATERMARK_COLOR_LIGHT);const position=options?.position??"top-right";const opacity=options?.opacity??(isDark?.55:.4);const icon=options?imageNode(options.image)??iconNode(options.icon,color):void 0;const text=options?.text??DEFAULT_WATERMARK_TEXT;const content=options?.element??[icon,text!==false&&text&&React14.createElement("div",{key:"text",style:{fontSize:11,fontWeight:600,color,fontFamily:"Inter",letterSpacing:.3}},text)];return React14.createElement("div",{style:{width,height,display:"flex",position:"relative"}},element,options&&React14.createElement("div",{style:{position:"absolute",...positionStyle(position),display:"flex",alignItems:"center",gap:5,opacity}},content))}function wrapWithBrand(element,width,height,theme="dark",label=DEFAULT_WATERMARK_TEXT){return wrapWithWatermark(element,width,height,theme,label)}function detectBackgroundColor(pixels){const r=pixels[0];const g=pixels[1];const b=pixels[2];const a=pixels[3];if(a<10){return"transparent"}return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}function parseHexColor(hex){const h=hex.startsWith("#")?hex.slice(1):hex;return[parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]}function createBackgroundMatcher(bgColor,tolerance=6){if(bgColor==="transparent"){return(_r,_g,_b,a)=>a<10}const[bgR,bgG,bgB]=parseHexColor(bgColor);return(r,g,b,a)=>{if(a<10)return true;return Math.abs(r-bgR)<=tolerance&&Math.abs(g-bgG)<=tolerance&&Math.abs(b-bgB)<=tolerance}}function detectContentBounds(pixels,width,height,bgColor,padding=20){const isBackground=createBackgroundMatcher(bgColor);let minX=width;let minY=height;let maxX=0;let maxY=0;for(let y=0;y<height;y++){for(let x=0;x<width;x++){const idx=(y*width+x)*4;const r=pixels[idx];const g=pixels[idx+1];const b=pixels[idx+2];const a=pixels[idx+3];if(!isBackground(r,g,b,a)){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;if(y>maxY)maxY=y}}}if(minX>maxX||minY>maxY){return{x:0,y:0,width,height}}const cropX=Math.max(0,minX-padding);const cropY=Math.max(0,minY-padding);const cropRight=Math.min(width,maxX+1+padding);const cropBottom=Math.min(height,maxY+1+padding);return{x:cropX,y:cropY,width:cropRight-cropX,height:cropBottom-cropY}}function cropPixels(pixels,srcWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const srcOffset=((region.y+y)*srcWidth+region.x)*4;const dstOffset=y*region.width*4;out.set(pixels.subarray(srcOffset,srcOffset+region.width*4),dstOffset)}return out}function detectOverflow(pixels,width,height,bgColor,edgeTolerance=3,minDensity=.05,alphaThreshold=10){const isBackground=createBackgroundMatcher(bgColor);function isContentPixel(x,y){const idx=(y*width+x)*4;const a=pixels[idx+3];if(a<alphaThreshold)return false;return!isBackground(pixels[idx],pixels[idx+1],pixels[idx+2],a)}function checkEdge(scanFn,length){for(let offset=0;offset<edgeTolerance;offset++){let contentCount=0;for(let i=0;i<length;i++){const[x,y]=scanFn(i,offset);if(x>=0&&x<width&&y>=0&&y<height&&isContentPixel(x,y)){contentCount++}}if(contentCount/length>=minDensity){return true}}return false}const bottom=checkEdge((i,off)=>[i,height-1-off],width);const right=checkEdge((i,off)=>[width-1-off,i],height);const top=checkEdge((i,off)=>[i,off],width);const left=checkEdge((i,off)=>[off,i],height);const overflowEdges3=[];if(top)overflowEdges3.push("top");if(right)overflowEdges3.push("right");if(bottom)overflowEdges3.push("bottom");if(left)overflowEdges3.push("left");const overflows=overflowEdges3.length>0;const message=overflows?`Content overflows canvas at: ${overflowEdges3.join(", ")}. Increase the illustration dimensions.`:"";return{overflows,edges:{top,right,bottom,left},message}}import*as satoriModule from"satori";function resolveSatori(api){if(typeof api==="function")return api;if(api&&typeof api==="object"){const fallback=api.default;if(typeof fallback==="function")return fallback;if(fallback&&typeof fallback==="object"){const nestedFallback=fallback.default;if(typeof nestedFallback==="function")return nestedFallback}}throw new Error("satori export could not be resolved")}var renderSatori=resolveSatori(satoriModule);var satori=(element,options)=>renderWithCanvasChartFit(renderSatori,element,options);var FONT_CACHE_DIR=process.env.VIZMATIC_FONT_DIR??join(process.env.XDG_CACHE_HOME??join(homedir(),".cache"),"vizmatic","fonts");var NETWORK_FALLBACK_DISABLED=process.env.VIZMATIC_DISABLE_NETWORK==="1"||process.env.VIZMATIC_OFFLINE==="1";function moduleDirectory(){if(typeof __dirname!=="undefined")return __dirname;return dirname(fileURLToPath(import.meta.url))}function unique(values){return[...new Set(values.filter(value=>Boolean(value)))]}function resolveAssetDir(){const moduleDir=moduleDirectory();const candidates=unique([process.env.VIZMATIC_ASSET_DIR,join(moduleDir,"..","assets"),join(moduleDir,"assets"),join(process.cwd(),"assets")]);return candidates.find(candidate=>existsSync(candidate))}var ASSET_DIR=resolveAssetDir();var VENDORED_FONT_DIR=ASSET_DIR?join(ASSET_DIR,"fonts"):void 0;var VENDORED_EMOJI_DIR=ASSET_DIR?join(ASSET_DIR,"emoji"):void 0;var VENDORED_EMOJI_BUNDLE=ASSET_DIR?join(ASSET_DIR,"emoji.json.br"):void 0;var FONT_URLS={interRegular:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",interSemiBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",interBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",jetbrainsMono:"https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",notoSans:"https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",notoSansMath:"https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf"};function fontReadPaths(filename){return unique([process.env.VIZMATIC_FONT_DIR?join(process.env.VIZMATIC_FONT_DIR,filename):void 0,VENDORED_FONT_DIR?join(VENDORED_FONT_DIR,filename):void 0,join(FONT_CACHE_DIR,filename)])}async function ensureFont(filename,url){for(const localPath of fontReadPaths(filename)){if(existsSync(localPath))return readFile(localPath)}if(NETWORK_FALLBACK_DISABLED){throw new Error(`Font ${filename} was not found in local Vizmatic assets and network fallback is disabled`)}console.log(` \u2193 Downloading font: ${filename}`);const response=await fetch(url);if(!response.ok){throw new Error(`Failed to download font ${filename}: ${response.statusText}`)}const buffer=Buffer.from(await response.arrayBuffer());await mkdir(FONT_CACHE_DIR,{recursive:true});await writeFile(join(FONT_CACHE_DIR,filename),buffer);return buffer}function toArrayBuffer(buffer){return buffer.buffer.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)}async function loadFonts(){await mkdir(FONT_CACHE_DIR,{recursive:true});const fonts=[];try{const[regular,semiBold,bold]=await Promise.all([ensureFont("Inter-Regular.ttf",FONT_URLS.interRegular),ensureFont("Inter-SemiBold.ttf",FONT_URLS.interSemiBold),ensureFont("Inter-Bold.ttf",FONT_URLS.interBold)]);fonts.push({name:"Inter",data:toArrayBuffer(regular),weight:400,style:"normal"},{name:"Inter",data:toArrayBuffer(semiBold),weight:600,style:"normal"},{name:"Inter",data:toArrayBuffer(bold),weight:700,style:"normal"})}catch(e){console.warn("Warning: Could not load Inter font:",e)}try{const jetbrains=await ensureFont("JetBrainsMono-Regular.ttf",FONT_URLS.jetbrainsMono);fonts.push({name:"JetBrains Mono",data:toArrayBuffer(jetbrains),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load JetBrains Mono font:",e)}try{const notoSans=await ensureFont("NotoSans-Regular.ttf",FONT_URLS.notoSans);fonts.push({name:"Noto Sans",data:toArrayBuffer(notoSans),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans font:",e)}try{const notoMath=await ensureFont("NotoSansMath-Regular.ttf",FONT_URLS.notoSansMath);fonts.push({name:"Noto Sans Math",data:toArrayBuffer(notoMath),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans Math font:",e)}return fonts}var EMOJI_CACHE_DIR=join(FONT_CACHE_DIR,"emoji");function emojiCodepoints(segment){return[...segment].map(c=>c.codePointAt(0).toString(16))}function emojiFilenames(segment){const codepoints=emojiCodepoints(segment);const full=codepoints.join("-");const withoutVariationSelectors=codepoints.filter(cp=>cp!=="fe0f").join("-");return unique([full,withoutVariationSelectors]).map(codepoints2=>`${codepoints2}.svg`)}async function svgFileToDataUri(path){const svgData=await readFile(path,"utf8");return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}var bundledEmoji;async function loadBundledEmoji(filename){if(!VENDORED_EMOJI_BUNDLE||!existsSync(VENDORED_EMOJI_BUNDLE))return void 0;bundledEmoji??=JSON.parse(brotliDecompressSync(await readFile(VENDORED_EMOJI_BUNDLE)).toString("utf8"));const svg=bundledEmoji[filename];return svg?`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`:void 0}async function loadEmoji(segment){const filenames=emojiFilenames(segment);for(const filename2 of filenames){const paths=unique([VENDORED_EMOJI_DIR?join(VENDORED_EMOJI_DIR,filename2):void 0,join(EMOJI_CACHE_DIR,filename2)]);for(const localPath of paths){if(existsSync(localPath))return svgFileToDataUri(localPath)}const bundled=await loadBundledEmoji(filename2);if(bundled)return bundled}if(NETWORK_FALLBACK_DISABLED){console.warn(`Warning: Emoji asset not found locally: ${filenames.join(" or ")}`);return""}const filename=filenames[0];if(!filename)return"";const url=`https://cdn.jsdelivr.net/npm/@twemoji/svg@15.0.0/${filename}`;try{console.log(` \u2193 Downloading emoji: ${filename}`);const response=await fetch(url);if(!response.ok){console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);return""}const svgData=await response.text();await mkdir(EMOJI_CACHE_DIR,{recursive:true});await writeFile(join(EMOJI_CACHE_DIR,filename),svgData);return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}catch(e){console.warn(`Warning: Could not fetch emoji ${filename}:`,e);return""}}async function loadAdditionalAsset(code,segment){if(code==="emoji"){return loadEmoji(segment)}return[]}var cachedFonts=null;async function getFonts(){if(!cachedFonts){cachedFonts=await loadFonts()}return cachedFonts}function sanitizeSvg(svg){return svg.replace(/width="0"/g,'width="1"').replace(/height="0"/g,'height="1"')}var AUTOCROP_PADDING=24;var CROP_THRESHOLD_PERCENT=10;function replaceSvgAttribute(attrs,name,value){const pattern=new RegExp(`\\s${name}="[^"]*"`);if(pattern.test(attrs))return attrs.replace(pattern,` ${name}="${value}"`);return`${attrs} ${name}="${value}"`}function cropSvgViewport(svg,region){const x=Math.max(0,Math.floor(region.x));const y=Math.max(0,Math.floor(region.y));const width=Math.max(1,Math.ceil(region.width));const height=Math.max(1,Math.ceil(region.height));return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>{let nextAttrs=attrs;nextAttrs=replaceSvgAttribute(nextAttrs,"width",String(width));nextAttrs=replaceSvgAttribute(nextAttrs,"height",String(height));nextAttrs=replaceSvgAttribute(nextAttrs,"viewBox",`${x} ${y} ${width} ${height}`);return`<svg${nextAttrs}>`})}function cropLayoutNodes(nodes,region){return nodes.flatMap(node=>{const left=Math.max(node.left,region.x);const top=Math.max(node.top,region.y);const right=Math.min(node.left+node.width,region.x+region.width);const bottom=Math.min(node.top+node.height,region.y+region.height);if(right<=left||bottom<=top)return[];return[{...node,left:left-region.x,top:top-region.y,width:right-left,height:bottom-top}]})}function cropSavesEnough(source,target){if(source<=0||target>=source)return false;return(source-target)/source*100>=CROP_THRESHOLD_PERCENT}var CanvasOverflowError=class extends Error{width;height;overflow;animation;constructor(width,height,overflow,animation){const position=animation?[animation.sceneIndex!=null?`scene ${animation.sceneIndex+1}`:void 0,animation.frameIndex!=null?`frame ${animation.frameIndex+1}${animation.frameCount?`/${animation.frameCount}`:""}`:void 0,animation.time!=null?`${Math.round(animation.time)}ms`:void 0,animation.label?JSON.stringify(animation.label):void 0].filter(Boolean).join(", "):"";super(`Canvas overflow detected (${width}\xD7${height})${position?` at ${position}`:""}: ${overflow.message}`);this.name="CanvasOverflowError";this.width=width;this.height=height;this.overflow=overflow;this.animation=animation}};function resolveWatermark(options){return options.watermark??options.brand}function shouldCropHeight(crop){return crop!==false}function shouldCropViewport(crop){return crop!==false&&crop!=="height"}async function renderToPng(element,options,createFn,theme){await renderToPngWithOutput(element,options,createFn,theme)}async function renderToPngWithOutput(element,options,createFn,theme){return withRenderContext({background:options.background??"transparent"},()=>renderToPngInContext(element,options,createFn,theme))}async function renderToPngInContext(element,options,createFn,theme){const fonts=await getFonts();const renderTheme=options.theme??theme??"dark";let svg=await satori(element,{width:options.width,height:options.height,fonts,loadAdditionalAsset});svg=sanitizeSvg(svg);const detectResvg=new Resvg(svg,{fitTo:{mode:"width",value:options.width},background:"rgba(0, 0, 0, 0)"});const detectResult=detectResvg.render();const detectPixels=detectResult.pixels;const pixelData=new Uint8Array(detectPixels.buffer);const detectedBg=detectBackgroundColor(pixelData);const bounds=detectContentBounds(pixelData,options.width,detectResult.height,detectedBg,AUTOCROP_PADDING);const overflow=detectOverflow(pixelData,options.width,detectResult.height,detectedBg);if(overflow.overflows){throw new CanvasOverflowError(options.width,options.height,overflow)}let finalWidth=options.width;let finalHeight=options.height;let finalElement=element;const croppedHeight=bounds.y+bounds.height;const heightSaved=options.height-croppedHeight;const heightSavedPercent=heightSaved/options.height*100;if(shouldCropHeight(options.crop)&&heightSavedPercent>=CROP_THRESHOLD_PERCENT){finalHeight=croppedHeight;if(createFn&&theme){finalElement=createFn(theme)}}const watermark=resolveWatermark(options);const renderFinalSvg=async(targetElement,targetWidth,targetHeight)=>{const layoutNodes=[];const outputElement=watermark?wrapWithWatermark(targetElement,targetWidth,targetHeight,renderTheme,watermark):targetElement;const renderedSvg=await satori(outputElement,{width:targetWidth,height:targetHeight,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected?node=>layoutNodes.push(node):void 0});return{svg:sanitizeSvg(renderedSvg),layoutNodes}};let finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);let finalSvg=finalRender.svg;if(finalHeight<options.height){const cropCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const cropPixels2=new Uint8Array(cropCheck.pixels.buffer);const cropBg=detectBackgroundColor(cropPixels2);const cropOverflow=detectOverflow(cropPixels2,finalWidth,cropCheck.height,cropBg);if(cropOverflow.overflows){finalHeight=options.height;finalElement=element;finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);finalSvg=finalRender.svg}}if(shouldCropViewport(options.crop)){const viewportCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const viewportPixels=new Uint8Array(viewportCheck.pixels.buffer);const viewportBg=detectBackgroundColor(viewportPixels);const viewportBounds=detectContentBounds(viewportPixels,finalWidth,viewportCheck.height,viewportBg,AUTOCROP_PADDING);if(cropSavesEnough(finalWidth,viewportBounds.width)||cropSavesEnough(viewportCheck.height,viewportBounds.height)){finalSvg=cropSvgViewport(finalSvg,viewportBounds);finalRender.layoutNodes=cropLayoutNodes(finalRender.layoutNodes,viewportBounds);finalWidth=viewportBounds.width;finalHeight=viewportBounds.height}}if(options.onNodeDetected){finalRender.layoutNodes.forEach(options.onNodeDetected)}const resvg=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();const outputPixels=new Uint8Array(pngData.pixels.buffer);const outputBackground=detectBackgroundColor(outputPixels);const physicalContentBounds=detectContentBounds(outputPixels,pngData.width,pngData.height,outputBackground,0);const outputScale=pngData.width/finalWidth;const contentBounds={x:physicalContentBounds.x/outputScale,y:physicalContentBounds.y/outputScale,width:physicalContentBounds.width/outputScale,height:physicalContentBounds.height/outputScale};const pngBuffer=pngData.asPng();await mkdir(dirname(options.outputPath),{recursive:true});await writeFile(options.outputPath,pngBuffer);return{width:finalWidth,height:finalHeight,pixelWidth:pngData.width,pixelHeight:pngData.height,contentBounds}}async function renderToBuffer(element,width,height,options={}){return withRenderContext({background:options.background??"transparent"},()=>renderToBufferInContext(element,width,height,options))}async function renderToBufferInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;let svg=await satori(outputElement,{width,height,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected});svg=sanitizeSvg(svg);const resvg=new Resvg(svg,{fitTo:{mode:"width",value:width*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();return Buffer.from(pngData.asPng())}async function renderToSvg(element,width,height,options={}){return withRenderContext({background:options.background??"transparent"},()=>renderToSvgInContext(element,width,height,options))}async function renderToSvgInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;const prepared=prepareAccessibleSvg(outputElement);const layoutNodes=[];const svg=await satori(prepared.element,{width,height,fonts,loadAdditionalAsset,onNodeDetected:node=>{layoutNodes.push(node);options.onNodeDetected?.(node)}});return addSvgAccessibility(sanitizeSvg(svg),prepared.graphs,layoutNodes)}import{Resvg as Resvg2}from"@resvg/resvg-js";import{mkdir as mkdir2,writeFile as writeFile2}from"fs/promises";import{dirname as dirname2}from"path";import*as gifenc from"gifenc";import parseCssColor2 from"parse-css-color";var MIN_FPS=1;var MAX_FPS=50;var DEFAULT_FPS=20;function assertDuration(duration,context){if(!Number.isFinite(duration)||duration<=0){throw new Error(`${context} duration must be a positive finite number`)}}function assertFps(fps){if(!Number.isFinite(fps)||!Number.isInteger(fps)||fps<MIN_FPS||fps>MAX_FPS){throw new Error(`Animation fps must be an integer from ${MIN_FPS} to ${MAX_FPS}`)}}function clampProgress(progress){return Math.max(0,Math.min(1,progress))}function easingValue(easing="linear",progress){const amount=clampProgress(progress);let result;if(typeof easing==="function"){result=easing(amount)}else if(easing==="ease-in"){result=amount*amount*amount}else if(easing==="ease-out"){result=1-(1-amount)**3}else if(easing==="ease-in-out"){result=amount<.5?4*amount*amount*amount:1-(-2*amount+2)**3/2}else if(easing==="linear"){result=amount}else{throw new Error(`Unknown animation easing: ${String(easing)}`)}if(!Number.isFinite(result))throw new Error("Animation easing must return a finite number");return clampProgress(result)}function hold(duration,label){return{type:"hold",duration,label}}function keyframe(value,label){return{type:"keyframe",value,label}}function tween(to,options){return{type:"tween",to,...options}}function parallel(tracks,label){return{type:"parallel",tracks,label}}function propertyStepDuration(step){return step.type==="keyframe"?0:step.duration}function parallelDuration(step){return Math.max(0,...Object.values(step.tracks).map(track=>track?.reduce((total,item)=>total+propertyStepDuration(item),0)??0))}function timelineStepDuration(step){if(step.type==="keyframe")return 0;if(step.type==="parallel")return parallelDuration(step);return step.duration}function validatePropertySteps(steps,context){for(const step of steps){if(step.type!=="keyframe")assertDuration(step.duration,context);if(step.type==="tween")easingValue(step.easing,.5)}}function validateTimeline(timeline){if(timeline.length===0)throw new Error("Animation timeline requires at least one step");let duration=0;timeline.forEach((step,index)=>{if(step.type==="parallel"){const tracks=Object.entries(step.tracks);if(tracks.length===0)throw new Error(`Animation parallel step ${index} requires at least one track`);tracks.forEach(([name,track])=>{if(!track)return;validatePropertySteps(track,`Animation parallel track ${JSON.stringify(name)}`)});assertDuration(parallelDuration(step),`Animation parallel step ${index}`)}else if(step.type!=="keyframe"){assertDuration(step.duration,`Animation step ${index}`);if(step.type==="tween")easingValue(step.easing,.5)}duration+=timelineStepDuration(step)});if(duration<=0)throw new Error("Animation timeline requires at least one timed step");return duration}function defineAnimation(definition){const fps=definition.fps??DEFAULT_FPS;assertFps(fps);const duration=validateTimeline(definition.timeline);validateAnimationValues(definition.initial,definition.timeline);return{...definition,kind:"vizmatic.animation",duration,fps}}function interpolateValue(from,to,progress,interpolate){if(interpolate)return interpolate(from,to,progress);if(typeof from==="number"&&typeof to==="number"&&Number.isFinite(from)&&Number.isFinite(to)){return from+(to-from)*progress}throw new Error("Animation tweens require finite numeric values or a custom interpolate function")}function validatePropertyInterpolation(initial,steps){let value=initial;for(const step of steps){if(step.type==="keyframe")value=step.value;if(step.type==="tween"){interpolateValue(value,step.to,.5,step.interpolate);value=step.to}}return value}function validateAnimationValues(initial,timeline){let state={...initial};for(const step of timeline){if(step.type==="keyframe"){state={...state,...step.value}}else if(step.type==="tween"){interpolateState(state,step,.5);state={...state,...step.to}}else if(step.type==="parallel"){const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)result[key]=validatePropertyInterpolation(state[key],track)}state=result}}}function interpolateState(from,step,progress){if(step.interpolate){const fromPatch=Object.fromEntries(Object.keys(step.to).map(key=>[key,from[key]]));return{...from,...step.interpolate(fromPatch,step.to,progress)}}const patch={};for(const key of Object.keys(step.to)){const target=step.to[key];if(target===void 0)continue;patch[key]=interpolateValue(from[key],target,progress)}return{...from,...patch}}function finalState(state,step){if(step.type==="keyframe")return{...state,...step.value};if(step.type==="tween")return{...state,...step.to};if(step.type!=="parallel")return state;const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(!track)continue;let value=state[key];for(const item of track){if(item.type==="keyframe"||item.type==="tween")value=item.type==="keyframe"?item.value:item.to}result[key]=value}return result}function evaluatePropertyTrack(initial,steps,time){let value=initial;let cursor=0;for(const step of steps){if(step.type==="keyframe"){value=step.value;continue}const end=cursor+step.duration;if(time<end){if(step.type==="hold")return value;const progress=easingValue(step.easing,(time-cursor)/step.duration);return interpolateValue(value,step.to,progress,step.interpolate)}if(step.type==="tween")value=step.to;cursor=end}return value}function evaluateAnimation(animation,requestedTime){const time=Math.max(0,Math.min(animation.duration,requestedTime));let state={...animation.initial};let cursor=0;for(let index=0;index<animation.timeline.length;index+=1){const step=animation.timeline[index];if(step.type==="keyframe"){state={...state,...step.value};continue}const duration=timelineStepDuration(step);const end=cursor+duration;if(time<end){const rawProgress=(time-cursor)/duration;if(step.type==="hold"){return{state,step:index,stepProgress:rawProgress,label:step.label}}if(step.type==="tween"){const progress=easingValue(step.easing,rawProgress);return{state:interpolateState(state,step,progress),step:index,stepProgress:rawProgress,label:step.label}}const parallelState={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)parallelState[key]=evaluatePropertyTrack(state[key],track,time-cursor)}return{state:parallelState,step:index,stepProgress:rawProgress,label:step.label}}state=finalState(state,step);cursor=end}const lastIndex=animation.timeline.length-1;return{state,step:lastIndex,stepProgress:1,label:animation.timeline[lastIndex]?.label}}function sampleAnimation(animation,time){if(!Number.isFinite(time))throw new Error("Animation sample time must be finite");return evaluateAnimation(animation,time).state}function animationCadence(duration,fps){const interval=1e3/fps;const times=[0];for(let time=interval;time<duration;time+=interval)times.push(time);if(times.at(-1)!==duration)times.push(duration);const boundaries=times.map(time=>Math.round(time/10)*10);const delays=times.map((_,index)=>index===times.length-1?20:Math.max(20,boundaries[index+1]-boundaries[index]));const targetDuration=Math.max(Math.round(duration/10)*10,delays.length*20);let excess=delays.reduce((total,delay)=>total+delay,0)-targetDuration;for(let index=delays.length-2;index>=0&&excess>0;index-=1){const reduction=Math.min(excess,delays[index]-20);delays[index]-=reduction;excess-=reduction}return{times,delays}}function analyzeAnimationCadence(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);return{fps,duration:animation.duration,frameCount:cadence.times.length,encodedDuration:cadence.delays.reduce((total,delay)=>total+delay,0),targetInterval:1e3/fps,minDelay:Math.min(...cadence.delays),maxDelay:Math.max(...cadence.delays)}}function sampleAnimationFrames(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);const count=cadence.times.length;return cadence.times.map((time,index)=>{const evaluated=evaluateAnimation(animation,time);return{state:evaluated.state,frame:{index,count,time,duration:animation.duration,delay:cadence.delays[index],progress:time/animation.duration,step:evaluated.step,stepProgress:evaluated.stepProgress,label:evaluated.label,fps}}})}function resolveGifenc(api){if(typeof api.GIFEncoder==="function"&&typeof api.applyPalette==="function"&&typeof api.quantize==="function"){return api}const fallback=api.default;if(fallback&&typeof fallback.GIFEncoder==="function"&&typeof fallback.applyPalette==="function"&&typeof fallback.quantize==="function"){return fallback}throw new Error("gifenc exports could not be resolved")}var{GIFEncoder,applyPalette,quantize}=resolveGifenc(gifenc);var MAX_PALETTE_SAMPLE_PIXELS=1e6;var MAX_TIMELINE_PALETTE_FRAMES=24;async function renderToPixels(element,width,height,scale,theme,background,overflowContext){const fonts=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg2(svg,{fitTo:{mode:"width",value:width*scale},background:rasterBackground(background,theme)});const rendered=resvg.render();const output={pixels:rendered.pixels,width:rendered.width,height:rendered.height};if(overflowContext){const overflow=detectLayoutOverflow(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow(nodes,width,height){const epsilon=.5;const edges={top:nodes.some(node=>node.top<-epsilon),right:nodes.some(node=>node.left+node.width>width+epsilon),bottom:nodes.some(node=>node.top+node.height>height+epsilon),left:nodes.some(node=>node.left<-epsilon)};const names=Object.entries(edges).filter(([,overflows])=>overflows).map(([edge])=>edge);return{overflows:names.length>0,edges,message:names.length?`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`:""}}function blendPixels(base,overlay,opacity){const result=new Uint8Array(base.length);const inverse=1-opacity;for(let index=0;index<base.length;index+=4){const baseAlpha=base[index+3]/255*inverse;const overlayAlpha=overlay[index+3]/255*opacity;const outputAlpha=baseAlpha+overlayAlpha;if(outputAlpha===0)continue;result[index]=Math.round((base[index]*baseAlpha+overlay[index]*overlayAlpha)/outputAlpha);result[index+1]=Math.round((base[index+1]*baseAlpha+overlay[index+1]*overlayAlpha)/outputAlpha);result[index+2]=Math.round((base[index+2]*baseAlpha+overlay[index+2]*overlayAlpha)/outputAlpha);result[index+3]=Math.round(outputAlpha*255)}return result}function hslToRgb(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=l-chroma/2;return[Math.round((channels[0]+offset)*255),Math.round((channels[1]+offset)*255),Math.round((channels[2]+offset)*255)]}function colorForBackground(background,theme){const value=background==="theme"?getThemeColors(theme).bg:background;const parsed=parseCssColor2(value);if(!parsed)throw new Error(`Invalid animation background color: ${value}`);const[r,g,b]=parsed.type==="hsl"?hslToRgb(parsed.values[0],parsed.values[1],parsed.values[2]):[parsed.values[0],parsed.values[1],parsed.values[2]];return{r,g,b,a:Math.round(parsed.alpha*255)}}function rasterBackground(background,theme){const{r,g,b,a}=colorForBackground(background,theme);return`rgba(${r}, ${g}, ${b}, ${a/255})`}function backgroundPixels(width,height,theme,background){const buffer=new Uint8Array(width*height*4);const color=colorForBackground(background,theme);for(let index=0;index<buffer.length;index+=4){buffer[index]=color.r;buffer[index+1]=color.g;buffer[index+2]=color.b;buffer[index+3]=color.a}return buffer}function samplePixels(pixels,limit){const pixelCount=pixels.length/4;if(pixelCount<=limit)return pixels.slice();const sample=new Uint8Array(limit*4);for(let index=0;index<limit;index+=1){const sourcePixel=Math.floor((index+.5)*pixelCount/limit);sample.set(pixels.subarray(sourcePixel*4,sourcePixel*4+4),index*4)}return sample}function sharedPalette(frames){if(frames.length===0)throw new Error("No GIF frames to quantize");const pixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/frames.length));const samples=frames.map(frame=>samplePixels(frame.pixels,pixelsPerFrame));const length=samples.reduce((total,sample)=>total+sample.length,0);const combined=new Uint8Array(length);let offset=0;for(const sample of samples){combined.set(sample,offset);offset+=sample.length}return quantize(combined,256,{format:"rgba4444",oneBitAlpha:true})}function changedBounds(previous,current,width,height){let minX=width;let minY=height;let maxX=-1;let maxY=-1;for(let index=0;index<current.length;index+=4){if(previous[index]===current[index]&&previous[index+1]===current[index+1]&&previous[index+2]===current[index+2]&&previous[index+3]===current[index+3])continue;const pixel=index/4;const x=pixel%width;const y=Math.floor(pixel/width);minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y)}return maxX<minX?void 0:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropFramePixels(pixels,canvasWidth,region){const output=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y+=1){const source=((region.y+y)*canvasWidth+region.x)*4;output.set(pixels.subarray(source,source+region.width*4),y*region.width*4)}return output}function deltaPixelFrame(frame,previous,enabled){if(!enabled||!previous)return frame;const bounds=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds||bounds.width===frame.width&&bounds.height===frame.height)return frame;return{...frame,x:bounds.x,y:bounds.y,delta:true,width:bounds.width,height:bounds.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds)}}function encodeGif(frames,loop,deltaFrames){if(frames.length===0)throw new Error("No GIF frames to encode");const firstFrame=frames[0];const gif=GIFEncoder();const palette=sharedPalette(frames);let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;let pending;for(const frame of frames){if(frame.width!==firstFrame.width||frame.height!==firstFrame.height){throw new Error("All GIF frames must have matching dimensions")}if(pending&&pixelsEqual(pending.pixels,frame.pixels)){pending.delay+=frame.delay;continue}if(pending){const encoded=deltaPixelFrame(pending,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending={...frame}}if(pending){const encoded=deltaPixelFrame(pending,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1}gif.finish();return{bytes:gif.bytes(),encodedFrameCount,deltaFrameCount}}var DEFAULT_TRANSITION_FPS=20;var MIN_TRANSITION_FRAMES=3;function sceneTransitionFps(fps){const resolved=fps??DEFAULT_TRANSITION_FPS;if(!Number.isInteger(resolved)||resolved<1||resolved>50){throw new Error("Animation fps must be an integer from 1 to 50")}return resolved}function transitionFrameDelays(duration,count){const totalCentiseconds=Math.max(count*2,Math.round(duration/10));let previous=0;return Array.from({length:count},(_,index)=>{const cumulative=Math.round((index+1)/count*totalCentiseconds);const delay=(cumulative-previous)*10;previous=cumulative;return delay})}async function scenesToFrames(scenes,options){if(scenes.length===0)throw new Error("Animated GIF requires at least one scene");for(const[index,scene]of scenes.entries()){if(!Number.isFinite(scene.duration)||scene.duration<=0){throw new Error(`Animated scene ${index+1} duration must be a positive finite number`)}if(scene.transition!=null&&!["none","fade","appear"].includes(scene.transition)){throw new Error(`Animated scene ${index+1} has unknown transition "${scene.transition}"`)}if(scene.transitionDuration!=null&&(!Number.isFinite(scene.transitionDuration)||scene.transitionDuration<=0)){throw new Error(`Animated scene ${index+1} transitionDuration must be a positive finite number`)}}const fps=sceneTransitionFps(options.fps);const renderedScenes=await Promise.all(scenes.map((scene,sceneIndex)=>{const watermark=options.watermark??options.brand;const element=watermark?wrapWithWatermark(scene.element,options.width,options.height,options.theme,watermark):scene.element;return renderToPixels(element,options.width,options.height,options.scale,options.theme,options.background,{sceneIndex,label:scene.label})}));const frames=[];const scaledWidth=renderedScenes[0].width;const scaledHeight=renderedScenes[0].height;for(let index=0;index<scenes.length;index+=1){const scene=scenes[index];const current=renderedScenes[index];const transition=scene.transition??"none";const transitionDuration=scene.transitionDuration??400;if(transition!=="none"){const previous=index>0?renderedScenes[index-1]:{pixels:backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),width:scaledWidth,height:scaledHeight};const transitionFrames=Math.max(MIN_TRANSITION_FRAMES,Math.round(transitionDuration/1e3*fps));const frameDelays=transitionFrameDelays(transitionDuration,transitionFrames);for(let frameIndex=0;frameIndex<transitionFrames;frameIndex+=1){const amount=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount);frames.push({pixels,delay:frameDelays[frameIndex],width:scaledWidth,height:scaledHeight})}}frames.push({pixels:current.pixels,delay:scene.duration,width:scaledWidth,height:scaledHeight})}return frames}async function renderAnimatedGif(scenes,options){if(!Array.isArray(scenes)){await renderAnimationGifWithOutput(scenes,options)}else{await renderAnimatedGifWithOutput(scenes,options)}}async function renderAnimatedGifWithOutput(scenes,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};await mkdir2(dirname2(options.outputPath),{recursive:true});const frames=await scenesToFrames(scenes,normalized);const encoded=encodeGif(frames,normalized.loop,normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255);await writeFile2(options.outputPath,encoded.bytes);return{width:frames[0].width,height:frames[0].height,frameCount:frames.length,encodedFrameCount:encoded.encodedFrameCount,deltaFrameCount:encoded.deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.delay,0),bytes:encoded.bytes.length}}function pixelsEqual(left,right){if(left.length!==right.length)return false;for(let index=0;index<left.length;index+=1){if(left[index]!==right[index])return false}return true}function writeGifFrame(gif,frame,loop,palette,first,delta){const index=applyPalette(frame.pixels,palette,"rgba4444");const transparentIndex=palette.findIndex(color=>color[3]===0);let remainingDelay=frame.delay;let includePalette=first;do{const delay=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay),repeat:loop,transparent:transparentIndex>=0,transparentIndex,dispose:delta&&frame.delta?1:void 0});if((frame.x??0)!==0||(frame.y??0)!==0){const bytes=gif.bytesView();const descriptor=frameStart+8;if(bytes[descriptor]!==44)throw new Error("GIF image descriptor was not written");const x=frame.x??0;const y=frame.y??0;bytes[descriptor+1]=x&255;bytes[descriptor+2]=x>>8&255;bytes[descriptor+3]=y&255;bytes[descriptor+4]=y>>8&255}includePalette=false;remainingDelay-=delay}while(remainingDelay>0)}function representativeFrameIndexes(frameCount){const count=Math.min(frameCount,MAX_TIMELINE_PALETTE_FRAMES);if(count===frameCount)return Array.from({length:count},(_,index)=>index);return Array.from({length:count},(_,index)=>Math.round(index*(frameCount-1)/(count-1)))}async function renderAnimationGif(animation,options){await renderAnimationGifWithOutput(animation,options)}async function renderAnimationGifWithOutput(animation,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};const frames=sampleAnimationFrames(animation,{fps:options.fps});const paletteFrames=[];const paletteIndexes=representativeFrameIndexes(frames.length);const palettePixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/paletteIndexes.length));for(const index of paletteIndexes){const sampled=frames[index];const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background);paletteFrames.push({...rendered,pixels:samplePixels(rendered.pixels,palettePixelsPerFrame),delay:sampled.frame.delay})}const palette=sharedPalette(paletteFrames);const gif=GIFEncoder();let pending;let dimensions;let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;const useDeltaFrames=normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255;for(const sampled of frames){const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background,{frameIndex:sampled.frame.index,frameCount:sampled.frame.count,time:sampled.frame.time,label:sampled.frame.label});dimensions??={width:rendered.width,height:rendered.height};if(rendered.width!==dimensions.width||rendered.height!==dimensions.height){throw new Error("All GIF frames must have matching dimensions")}if(pending&&pixelsEqual(pending.pixels,rendered.pixels)){pending.delay+=sampled.frame.delay;continue}if(pending){const encoded2=deltaPixelFrame(pending,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending={...rendered,delay:sampled.frame.delay}}if(!pending||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir2(dirname2(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile2(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}function graphImportResult(source,graph,diagnostics){if(graph.nodes.length===0&&diagnostics.every(({severity})=>severity!=="error")){diagnostics.push({code:"import.empty",severity:"error",message:"The source contains no graph nodes to import.",line:1,column:1,excerpt:""})}const ok=diagnostics.every(({severity})=>severity!=="error");return ok?{source,ok,graph,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line,code,severity,message,column=1){diagnostics.push({code,severity,message,line,column,excerpt:(sourceLines[line-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line,index){while(index<line.length&&/\s/.test(line[index]??""))index++;return index}function readDelimited(line,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line.length;index++){const character=line[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line.startsWith(close,index)){return{value:line.slice(start,index),next:index+close.length}}}return void 0}function decodeLabel(raw){const value=raw.trim();if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}function labelHasUnsupportedMarkup(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label)}function readEndpoint(line,from){let index=skipWhitespace(line,from);const id=line.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line,index);if(afterId>=line.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line.slice(afterId);const delimiters=[{open:"[(",close:")]",lossy:true},{open:"([",close:"])",lossy:true},{open:"((",close:"))",lossy:true},{open:"{{",close:"}}",lossy:true},{open:"[",close:"]",lossy:false},{open:"(",close:")",lossy:true},{open:"{",close:"}",lossy:true}];const delimiter=delimiters.find(({open})=>rest.startsWith(open));if(!delimiter)return{id,label:id,shape:"rectangle",next:index};const content=readDelimited(line,afterId+delimiter.open.length,delimiter.close);if(!content)return void 0;const label=decodeLabel(content.value);if(label===void 0)return void 0;return{id,label,shape:delimiter.lossy?"lossy":"rectangle",next:content.next}}function addNode(state,endpoint2,groupId,line,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint2.id)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid id "${endpoint2.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint2.label)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint2.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint2.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid node "${endpoint2.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`Mermaid node "${endpoint2.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint2.label}else{state.nodeIndexes.set(endpoint2.id,state.nodes.length);state.nodes.push({id:endpoint2.id,label:endpoint2.label,...groupId?{group:groupId}:{}})}if(endpoint2.shape==="lossy"&&!state.warnedShapes.has(endpoint2.id)){state.warnedShapes.add(endpoint2.id);addImportDiagnostic(diagnostics,sourceLines,line,"import.lossy_semantics","warning",`Mermaid node "${endpoint2.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line,first.next);const hasConnector=CONNECTORS.some(connector=>line.startsWith(connector,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line,cursor);if(cursor>=line.length)return;const connector=CONNECTORS.find(candidate=>line.startsWith(candidate,cursor));if(!connector){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",cursor+1);return}cursor+=connector.length;cursor=skipWhitespace(line,cursor);let edgeLabel;if(line[cursor]==="|"){const end=line.indexOf("|",cursor+1);if(end<0){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid edge label is missing its closing |.",cursor+1);return}edgeLabel=line.slice(cursor+1,end).trim();cursor=skipWhitespace(line,end+1);if(labelHasUnsupportedMarkup(edgeLabel)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",cursor+1);return}}const next=readEndpoint(line,cursor);if(!next){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid connection has no supported target node.",cursor+1);return}if(!addNode(state,next,groupId,lineNumber,sourceLines,diagnostics,false))return;const edge={from:previous.id,to:next.id,...edgeLabel!==void 0?{label:edgeLabel}:{},...connector==="---"?{arrow:"none"}:connector==="-.->"?{arrow:"forward",style:"dotted"}:{arrow:"forward"}};state.edges.push(edge);state.edgeReferences.push({id:previous.id,line:lineNumber},{id:next.id,line:lineNumber});previous=next;cursor=next.next}}function importMermaidGraph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const state={nodes:[],nodeIndexes:new Map,groups:[],groupIds:new Set,edges:[],edgeReferences:[],warnedShapes:new Set};let direction="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line=rawLine.trim();if(!line)continue;if(line.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line.startsWith("%%"))continue;if(!sawHeader){const header=line.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);if(!header){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error",'Expected a Mermaid flowchart or graph header such as "flowchart LR".');sawHeader=true;continue}sawHeader=true;const sourceDirection=header[1]?.toUpperCase();direction=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);if(subgraph){if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Nested Mermaid subgraphs are not imported.");continue}const id=subgraph[1];if(!id)continue;if(state.groupIds.has(id)||state.nodeIndexes.has(id)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph id "${id}" conflicts with an existing group or node.`);continue}const rawLabel=subgraph[2];const label=rawLabel===void 0?id:decodeLabel(rawLabel);if(label===void 0||labelHasUnsupportedMarkup(label)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);continue}currentGroup=id;state.groupIds.add(id);state.groups.push({id,label});continue}if(/^subgraph\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");continue}if(/^end\s*$/i.test(line)){if(!currentGroup)addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid end has no matching subgraph.");else currentGroup=void 0;continue}if(/^direction\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,currentGroup?"import.unsupported_semantics":"import.parse_error","error",currentGroup?"Per-subgraph Mermaid direction cannot be represented by GraphDiagram.":"Set Mermaid graph direction in the flowchart or graph header.");continue}if(/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line,currentGroup,lineNumber,sourceLines,state,diagnostics)}if(!sawHeader){addImportDiagnostic(diagnostics,sourceLines,1,"import.parse_error","error","Missing Mermaid flowchart or graph header.")}if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,sourceLines.length,"import.parse_error","error",`Mermaid subgraph "${currentGroup}" has no matching end.`)}for(const reference of state.edgeReferences){if(state.groupIds.has(reference.id)){addImportDiagnostic(diagnostics,sourceLines,reference.line,"import.unsupported_semantics","error",`Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`)}}const graph={nodes:state.nodes,edges:state.edges,groups:state.groups,direction};return graphImportResult("mermaid",graph,diagnostics)}function decodeD2Label(raw){const value=raw.trim();if(value.startsWith('"')){if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}if(value.startsWith("'")){if(!value.endsWith("'"))return void 0;return value.slice(1,-1).replace(/\\(['\\])/g,"$1")}return value}function hasMarkdownFormatting(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label)}function hasUnquotedHash(line){let quote;let escaped=false;for(const character of line){if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'")quote=character;else if(character==="#")return true}return false}function addNode2(nodes,id,label,line,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line,"import.unsupported_semantics","error",`D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`);return false}const existing=nodes.get(id);if(existing){if(explicitLabel){existing.node.label=label}}else{nodes.set(id,{node:{id,label}})}return true}function reportUnsupported(diagnostics,sourceLines,line,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line,code,"error",message,column)}function importD2Graph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const nodesById=new Map;const edges=[];const shapes=new Map;let direction="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line=rawLine.trim();if(!line)continue;if(containerDepth>0){const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,containerDepth+opens-closes);continue}if(line.startsWith("#"))continue;if(hasUnquotedHash(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line.includes("{")||line.includes("}")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.","import.unsupported_semantics");const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,opens-closes);continue}const directionMatch=line.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape=decodeD2Label(shapeMatch[2]??"");if(!id||shape===void 0||shape===""){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 shape declaration needs a simple identifier and a shape value.","import.parse_error");continue}if(!nodesById.has(id))addNode2(nodesById,id,id,lineNumber,sourceLines,diagnostics,false);shapes.set(id,{value:shape,line:lineNumber});continue}const edgeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);if(edgeMatch){const from=edgeMatch[1];const connector=edgeMatch[2];const to=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector||!to)continue;let label;if(rawLabel!==void 0){label=decodeD2Label(rawLabel);if(label===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection label has invalid quotes.","import.parse_error");continue}if(hasMarkdownFormatting(label)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.","import.unsupported_semantics");continue}}addNode2(nodesById,from,from,lineNumber,sourceLines,diagnostics,false);addNode2(nodesById,to,to,lineNumber,sourceLines,diagnostics,false);edges.push({from,to,...label!==void 0?{label}:{},arrow:connector==="<->"?"both":connector==="<-"?"backward":connector==="--"?"none":"forward"});continue}const nodeMatch=line.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);if(nodeMatch){const id=nodeMatch[1];const rawLabel=nodeMatch[2];if(!id)continue;let label=id;let explicitLabel=false;if(rawLabel!==void 0){const decoded=decodeD2Label(rawLabel);if(decoded===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,`D2 label for "${id}" has invalid quotes.`,"import.parse_error");continue}label=decoded;explicitLabel=true}addNode2(nodesById,id,label,lineNumber,sourceLines,diagnostics,explicitLabel);continue}if(line.includes(".style")||line.includes(".width")||line.includes(".height")||line.includes(".near")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 styling, sizing, and positioning fields are not imported.","import.unsupported_semantics")}else if(/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line)){reportUnsupported(diagnostics,sourceLines,lineNumber,"Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.")}else{reportUnsupported(diagnostics,sourceLines,lineNumber,"Could not parse this D2 statement in the supported subset.","import.parse_error")}}if(containerDepth>0){reportUnsupported(diagnostics,sourceLines,sourceLines.length,"D2 object-property block has no matching closing brace.","import.parse_error")}for(const[id,{value,line}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line,"import.lossy_semantics","warning",`D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`)}return graphImportResult("d2",{nodes:[...nodesById.values()].map(({node})=>node),edges,groups:[],direction},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage as AsyncLocalStorage2}from"async_hooks";import{tmpdir}from"os";import{join as join2}from"path";import parseCssColor3 from"parse-css-color";import{Children,isValidElement as isValidElement3}from"react";var CHECK_DIAGNOSTIC_CODES=["accessibility.low_contrast","api.unsupported_prop","asset.warning","frame.load_error","frame.unknown_preset","layout.auto_size","layout.connector_congestion","layout.connector_unroutable","layout.overflow","layout.text_overlap","layout.whitespace_imbalance","readability.small_text","render.error","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=11;function hslToRgb2(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=l-chroma/2;return channels.map(channel=>Math.round((channel+offset)*255))}function colorFromCss(value){if(typeof value!=="string")return void 0;const parsed=parseCssColor3(value);if(!parsed||parsed.values.length<3)return void 0;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];return{r,g,b,alpha:parsed.alpha}}function compositeOver(foreground,background){if(foreground.alpha>=1||!background)return foreground;const alpha=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha,alpha}}function isUnresolvedColor(value){if(typeof value!=="string"||value.trim()===""||colorFromCss(value))return false;return!["inherit","initial","revert","unset"].includes(value.trim().toLowerCase())}function channelLuminance(value){const normalized=value/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4}function relativeLuminance(color){return .2126*channelLuminance(color.r)+.7152*channelLuminance(color.g)+.0722*channelLuminance(color.b)}function contrastRatio(foreground,background){const lighter=Math.max(relativeLuminance(foreground),relativeLuminance(background));const darker=Math.min(relativeLuminance(foreground),relativeLuminance(background));return(lighter+.05)/(darker+.05)}function numericFontWeight(value){if(typeof value==="number")return value;if(value==="bold")return 700;if(typeof value==="string"&&/^\d+$/.test(value))return Number(value);return void 0}function fontSizePixels(value,inherited){if(typeof value==="number")return value;if(typeof value!=="string")return inherited;const match=value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);if(!match?.[1])return inherited;const amount=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount*4/3;if(unit==="rem")return amount*16;if(unit==="em")return amount*(inherited??16);if(unit==="%")return amount/100*(inherited??16);return amount}function requiredContrast(context){const large=(context.fontSize??16)>=24||(context.fontSize??16)>=18.66&&(context.fontWeight??400)>=700;return large?3:4.5}function styleRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return value}function hasDirectText(children){return Children.toArray(children).some(child=>typeof child==="string"||typeof child==="number")}function elementId(props){const value=props.id??props["data-vizmatic-id"];return typeof value==="string"&&value.trim()!==""?value.trim():void 0}function resolveFunctionComponent(node,trustedComponents){if(!isValidElement3(node)||typeof node.type!=="function"||trustedComponents.has(node.type))return void 0;const component=node.type;if(component.__vizmaticPrimitive)return void 0;if(component.prototype?.isReactComponent)return void 0;try{return component(node.props)}catch{return void 0}}function analyzeContrast(element,theme,trustedComponents=new Set,rootBackground2){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path){if(visited++>=MAX_CONTRAST_NODES||!isValidElement3(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path);return}const props=node.props;const style=typeof node.type==="string"?styleRecord(props.style):{};const backgroundImage=typeof style.backgroundImage==="string"?style.backgroundImage.trim().toLowerCase():"";const backgroundShorthand=typeof style.background==="string"?style.background.trim():"";const isBackgroundWrapper=typeof node.type==="function"&&(trustedComponents.has(node.type)||Boolean(node.type.__vizmaticPrimitive));const wrapperBackground=isBackgroundWrapper?props.background:void 0;const hasUnresolvedBackground=backgroundImage!==""&&backgroundImage!=="none"||isUnresolvedColor(style.backgroundColor)||backgroundShorthand!==""&&backgroundShorthand.toLowerCase()!=="none"&&!colorFromCss(backgroundShorthand)||isUnresolvedColor(wrapperBackground);const ownBackground=colorFromCss(style.backgroundColor)??colorFromCss(style.background)??colorFromCss(wrapperBackground);const baseBackground=path==="root"&&isBackgroundWrapper&&colorFromCss(wrapperBackground)?void 0:inherited.background;const background=hasUnresolvedBackground?void 0:ownBackground?compositeOver(ownBackground,baseBackground):baseBackground;const color=typeof style.color==="string"&&style.color.trim().toLowerCase()==="currentcolor"?inherited.color:isUnresolvedColor(style.color)?void 0:colorFromCss(style.color)??inherited.color;const fontSize=fontSizePixels(style.fontSize,inherited.fontSize);const fontWeight=numericFontWeight(style.fontWeight)??inherited.fontWeight;const context={background,color,fontSize,fontWeight};if(typeof node.type==="string"&&hasDirectText(props.children)&&color&&background!==void 0&&background.alpha>=1){const renderedColor=compositeOver(color,background);const ratio=contrastRatio(renderedColor,background);const required=requiredContrast(context);if(ratio<required){const rounded=Math.round(ratio*100)/100;const key=`${rounded}:${required}:${path}`;if(!seen.has(key)){seen.add(key);diagnostics.push({code:"accessibility.low_contrast",severity:"warning",theme,message:`Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,suggestion:"Use a stronger text or background color token.",elementId:elementId(props),location:{path}})}}}Children.forEach(props.children,(child,index)=>visit(child,context,`${path}.${index}`))}visit(element,{background:colorFromCss(rootBackground2)},"root");return diagnostics}function containsLayoutNode(parent,child){const epsilon=.5;return child.left>=parent.left-epsilon&&child.top>=parent.top-epsilon&&child.left+child.width<=parent.left+parent.width+epsilon&&child.top+child.height<=parent.top+parent.height+epsilon}function textUnits(text){return Array.from(text.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0)}function renderedTextNodes(nodes){const textNodes=[];const ancestors=[];for(const node of nodes){while(ancestors.length>0&&!containsLayoutNode(ancestors[ancestors.length-1].node,node)){ancestors.pop()}const inherited=ancestors[ancestors.length-1];const style=styleRecord(node.props.style);const fontSize=fontSizePixels(style.fontSize,inherited?.fontSize)??16;const textAlign=typeof style.textAlign==="string"?style.textAlign:inherited?.textAlign??"left";const text=node.textContent?.trim();if(text&&node.width>0&&node.height>0){const estimatedLines=Math.max(1,Math.round(node.height/Math.max(fontSize*1.5,1)));const paintHeight=Math.min(node.height,fontSize*.9+(estimatedLines-1)*fontSize*1.25);const unwrappedWidth=textUnits(text)*fontSize*.56;const paintWidth=Math.min(node.width,unwrappedWidth);const horizontalInset=textAlign==="center"?(node.width-paintWidth)/2:textAlign==="right"||textAlign==="end"?node.width-paintWidth:0;textNodes.push({text,elementId:elementId(node.props),left:node.left,top:node.top,width:node.width,height:node.height,paintLeft:node.left+horizontalInset,paintTop:node.top+(node.height-paintHeight)/2,paintWidth,paintHeight,fontSize})}else if(node.width>0&&node.height>0){ancestors.push({node,fontSize,textAlign})}}return textNodes}function textExcerpt(text){const normalized=text.replace(/\s+/g," ").trim();return normalized.length>40?`${normalized.slice(0,37)}...`:normalized}function meaningfulOverlap(a,b){const width=Math.min(a.paintLeft+a.paintWidth,b.paintLeft+b.paintWidth)-Math.max(a.paintLeft,b.paintLeft);const height=Math.min(a.paintTop+a.paintHeight,b.paintTop+b.paintHeight)-Math.max(a.paintTop,b.paintTop);if(width<2||height<2)return false;if(a.text===b.text&&a.left===b.left&&a.top===b.top&&a.width===b.width&&a.height===b.height)return false;const overlapArea=width*height;const smallerArea=Math.min(a.paintWidth*a.paintHeight,b.paintWidth*b.paintHeight);return overlapArea/smallerArea>=.08}function overlapCandidates(nodes){const cellSize=96;const buckets=new Map;const pairs=[];for(let index=0;index<nodes.length&&pairs.length<MAX_DIAGNOSTICS_PER_RULE;index+=1){const node=nodes[index];const minX=Math.floor(node.paintLeft/cellSize);const maxX=Math.floor((node.paintLeft+node.paintWidth)/cellSize);const minY=Math.floor(node.paintTop/cellSize);const maxY=Math.floor((node.paintTop+node.paintHeight)/cellSize);const candidates=new Set;for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const bucket=buckets.get(`${x}:${y}`);bucket?.forEach(candidate=>candidates.add(candidate))}}for(const candidate of candidates){if(meaningfulOverlap(nodes[candidate],node))pairs.push([nodes[candidate],node]);if(pairs.length>=MAX_DIAGNOSTICS_PER_RULE)break}for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const key=`${x}:${y}`;const bucket=buckets.get(key)??[];bucket.push(index);buckets.set(key,bucket)}}}return pairs}function analyzeRenderedLayout(nodes,theme){const diagnostics=[];const textNodes=renderedTextNodes(nodes);const seenSmallText=new Set;let smallTextCount=0;for(const node of textNodes){if(node.fontSize>=MIN_TEXT_SIZE)continue;const excerpt=textExcerpt(node.text);const key=`${excerpt}:${node.fontSize}`;if(seenSmallText.has(key))continue;seenSmallText.add(key);diagnostics.push({code:"readability.small_text",severity:"warning",theme,message:`Text "${excerpt}" renders at ${node.fontSize}px.`,suggestion:`Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,elementId:node.elementId,location:{x:node.left,y:node.top,width:node.width,height:node.height}});smallTextCount+=1;if(smallTextCount>=MAX_DIAGNOSTICS_PER_RULE)break}for(const[left,right]of overlapCandidates(textNodes)){diagnostics.push({code:"layout.text_overlap",severity:"warning",theme,message:`Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,suggestion:"Increase spacing or canvas size, shorten labels, or move one label.",elementId:left.elementId,relatedElementIds:right.elementId?[right.elementId]:void 0,location:{x:left.left,y:left.top,width:left.width,height:left.height}})}const maxDataNumber=attribute2=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute2];return typeof value==="number"?value:Number(value)||0}));for(const source of nodes.filter(node=>Number(node.props["data-vizmatic-unrouted-connectors"])>0)){const messages=JSON.parse(String(source.props["data-vizmatic-routing-failures"]));for(const message of messages.slice(0,MAX_DIAGNOSTICS_PER_RULE))diagnostics.push({code:"layout.connector_unroutable",severity:"error",theme,message,suggestion:"Increase canvas size or spacing, reduce routingClearance, or choose a different endpoint side or port.",elementId:elementId(source.props),location:{x:source.left,y:source.top,width:source.width,height:source.height}})}const connectorCrossings2=maxDataNumber("data-vizmatic-connector-crossings");if(connectorCrossings2>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings2} connector crossing${connectorCrossings2===1?"":"s"} detected.`,suggestion:"Use automatic layout, change graph direction, or simplify the edge set.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const labelCollisions=maxDataNumber("data-vizmatic-connector-label-collisions");if(labelCollisions>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-collisions"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${labelCollisions} connector label collision${labelCollisions===1?"":"s"} detected.`,suggestion:"Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crowdedEndpoints=maxDataNumber("data-vizmatic-crowded-connector-endpoints");if(crowdedEndpoints>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-crowded-connector-endpoints"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${crowdedEndpoints} node${crowdedEndpoints===1?"":"s"} connect more than four edges.`,suggestion:"Group related branches, add an intermediate hub, or change graph direction.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const parallelGroups=maxDataNumber("data-vizmatic-parallel-connector-groups");if(parallelGroups>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-parallel-connector-groups"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${parallelGroups} connector route${parallelGroups===1?"":"s"} contain parallel edges.`,suggestion:"Merge duplicate relationships, label one combined edge, or separate the routes.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}let whitespaceCount=0;for(const container of nodes.filter(node=>node.props["data-vizmatic-layout-container"]==="panel")){const contentNodes=nodes.filter(node=>node.props["data-vizmatic-layout-content"]==="panel"&&node.width>0&&node.height>0&&node.left>=container.left&&node.top>=container.top&&node.left+node.width<=container.left+container.width&&node.top+node.height<=container.top+container.height);if(contentNodes.length===0)continue;const contentTop=Math.min(...contentNodes.map(node=>node.top));const contentBottom=Math.max(...contentNodes.map(node=>node.top+node.height));const topGutter=contentTop-container.top;const bottomGutter=container.top+container.height-contentBottom;const difference=Math.abs(bottomGutter-topGutter);if(difference<=48||difference/container.height<=.18)continue;const largerSide=bottomGutter>topGutter?"below":"above";const smallerSide=largerSide==="below"?"above":"below";diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,suggestion:"Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",elementId:elementId(container.props),location:{x:container.left,y:container.top,width:container.width,height:container.height}});whitespaceCount+=1;if(whitespaceCount>=MAX_DIAGNOSTICS_PER_RULE)break}return diagnostics}function analyzeWhitespaceBalance(bounds,width,height,theme){const gutters={left:bounds.x,right:width-bounds.x-bounds.width,top:bounds.y,bottom:height-bounds.y-bounds.height};const diagnostics=[];const horizontalDifference=Math.abs(gutters.left-gutters.right);const verticalDifference=Math.abs(gutters.top-gutters.bottom);if(horizontalDifference>48&&horizontalDifference/width>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds.x,y:bounds.y,width:bounds.width,height:bounds.height}})}if(verticalDifference>48&&verticalDifference/height>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds.x,y:bounds.y,width:bounds.width,height:bounds.height}})}return diagnostics}function diagnosticFromMessage(message,severity,theme){if(/unknown preset/i.test(message)){return{code:"frame.unknown_preset",severity,theme,message,suggestion:'Use "default" or "engineering".'}}if(/unsupported prop|unknown prop|does not recognize (?:the )?.* prop/i.test(message)){return{code:"api.unsupported_prop",severity,theme,message,suggestion:"Remove the prop or use one documented for this Vizmatic primitive."}}if(/invalid value for css property|unsupported (?:css|style)|not supported.*css/i.test(message)){return{code:"style.unsupported",severity,theme,message,suggestion:"Use CSS supported by Satori or a Vizmatic primitive."}}if(/font|emoji|image asset|failed to (?:download|fetch)|asset .*not found/i.test(message)){return{code:"asset.warning",severity,theme,message,suggestion:"Use a reachable asset or install it locally before rendering offline."}}return{code:severity==="error"?"render.error":"render.warning",severity,theme,message}}var DEFAULT_WIDTH=960;var DEFAULT_HEIGHT=540;var MAX_WIDTH=1920;var MAX_HEIGHT=1440;var GROWTH=1.25;var MAX_AUTO_SIZE_ATTEMPTS=6;var TRUSTED_COMPONENTS=new Set(Object.values(primitives_exports));var consoleCaptureContext=new AsyncLocalStorage2;var activeConsoleCaptures=0;var originalConsoleMethods;function formatConsoleArgs(args){return args.map(value=>{if(value instanceof Error)return value.message;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}).join(" ")}function installConsoleCapture(){if(activeConsoleCaptures===0){originalConsoleMethods={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};const original=originalConsoleMethods;const intercept=(method,severity)=>(...args)=>{const messages=consoleCaptureContext.getStore();if(messages){if(severity)messages.push({severity,message:formatConsoleArgs(args)});return}Reflect.apply(original[method],console,args)};console.debug=intercept("debug");console.error=intercept("error","error");console.info=intercept("info");console.log=intercept("log");console.warn=intercept("warn","warning")}activeConsoleCaptures+=1;let restored=false;return()=>{if(restored)return;restored=true;activeConsoleCaptures-=1;if(activeConsoleCaptures===0&&originalConsoleMethods){console.debug=originalConsoleMethods.debug;console.error=originalConsoleMethods.error;console.info=originalConsoleMethods.info;console.log=originalConsoleMethods.log;console.warn=originalConsoleMethods.warn;originalConsoleMethods=void 0}}}async function captureConsole(run){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run);return{value,messages}}catch(error){return{error,messages}}finally{uninstall()}}function normalizeAutoSize(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value)return{width:value.width??defaults.width,height:value.height??defaults.height};return defaults}function overflowEdges(error){if(!(error instanceof CanvasOverflowError))return void 0;return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}function nextDimension(value,maximum){return Math.min(maximum,Math.ceil(value*GROWTH/10)*10)}function nextAutoSize(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?nextDimension(width,MAX_WIDTH):width;const nextHeight=growHeight?nextDimension(height,MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrame(create,theme,options){let width=options.width;let height=options.height;for(let attempt=0;attempt<MAX_AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const output=await renderToPngWithOutput(create(theme),{width,height,outputPath:options.outputPath,crop:true,scale:1,background:options.background,onNodeDetected:node=>layoutNodes.push(node)},create,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges(error);const next=edges?nextAutoSize(width,height,options.autoSize,edges):void 0;if(!next||attempt===MAX_AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function counts(themes){const diagnostics=themes.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{errors:diagnostics.filter(({severity})=>severity==="error").length,warnings:diagnostics.filter(({severity})=>severity==="warning").length,info:diagnostics.filter(({severity})=>severity==="info").length}}function fails(diagnostics,policy){if(policy==="never")return false;const threshold={error:0,warning:1,info:2}[policy];const levels={error:0,warning:1,info:2};return diagnostics.some(({severity})=>levels[severity]<=threshold)}function messageDiagnostics(messages,theme){return messages.map(({message,severity})=>diagnosticFromMessage(message,severity,theme))}function rootBackground(background,theme){if(background==="theme")return getThemeColors(theme).bg;if(background==="transparent"||background===void 0)return void 0;return background}async function checkFrame(input,options={}){const themes=options.themes??["dark","light"];if(themes.length===0)throw new TypeError("checkFrame requires at least one theme");const width=input.width??DEFAULT_WIDTH;const height=input.height??DEFAULT_HEIGHT;if(!Number.isFinite(width)||width<=0||!Number.isFinite(height)||height<=0){throw new TypeError("checkFrame width and height must be positive finite numbers")}const autoSize=normalizeAutoSize(input.autoSize,{width:input.width==null,height:input.height==null});const create=input.create??(()=>input.scene);const failOn=options.failOn??"error";const tempDir=await mkdtemp(join2(tmpdir(),"vizmatic-check-"));const reports=[];try{for(const[themeIndex,theme]of themes.entries()){const inputDimensions={width,height};const diagnostics2=[];const prepared=await captureConsole(async()=>{const element=create(theme);const background=rootBackground(options.background,theme);return analyzeContrast(element,theme,TRUSTED_COMPONENTS,background)});diagnostics2.push(...messageDiagnostics(prepared.messages,theme));if(!prepared.value){diagnostics2.push(diagnosticFromMessage(prepared.error instanceof Error?prepared.error.message:String(prepared.error),"error",theme));reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2});continue}diagnostics2.push(...prepared.value);const rendered=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize,background:options.background,outputPath:join2(tempDir,`${themeIndex}.png`)}));diagnostics2.push(...messageDiagnostics(rendered.messages,theme));if(rendered.value){diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes,theme));if(rendered.value.contentBounds){diagnostics2.push(...analyzeWhitespaceBalance(rendered.value.contentBounds,rendered.value.logicalOutputWidth,rendered.value.logicalOutputHeight,theme))}if(rendered.value.width!==width||rendered.value.height!==height){diagnostics2.push({code:"layout.auto_size",severity:"info",theme,message:`Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,suggestedDimensions:{width:rendered.value.width,height:rendered.value.height}})}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions,resolved:{width:rendered.value.width,height:rendered.value.height},output:{width:rendered.value.outputWidth,height:rendered.value.outputHeight}},diagnostics:diagnostics2});continue}const edges=overflowEdges(rendered.error);if(edges){const suggestion=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize:{width:true,height:true},background:options.background,outputPath:join2(tempDir,`${themeIndex}-suggestion.png`)}));const suggestedDimensions=suggestion.value?{width:suggestion.value.width,height:suggestion.value.height}:void 0;diagnostics2.push({code:"layout.overflow",severity:"error",theme,edges,message:rendered.error instanceof Error?rendered.error.message:String(rendered.error),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.",suggestedDimensions})}else{diagnostics2.push(diagnosticFromMessage(rendered.error instanceof Error?rendered.error.message:String(rendered.error),"error",theme))}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2})}}finally{await rm(tempDir,{recursive:true,force:true})}const summary=counts(reports);const diagnostics=reports.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{schemaVersion:1,source:input.source,ok:!fails(diagnostics,failOn),rendered:reports.every(({dimensions})=>dimensions.resolved!==void 0),autoSize,themes:reports,summary}}function readJsxTag(source,start){if(source.startsWith("<>",start))return{closing:false,end:start+2,selfClosing:false};if(source.startsWith("</>",start))return{closing:true,end:start+3,selfClosing:false};const head=source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);if(!head)return void 0;const closing=Boolean(head[1]);let quote;let braces=0;let escaped=false;for(let index=start+head[0].length;index<source.length;index+=1){const character=source[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{"){braces+=1;continue}if(character==="}"){braces=Math.max(0,braces-1);continue}if(character!==">"||braces>0)continue;const beforeClose=source.slice(start,index).trimEnd();return{closing,end:index+1,selfClosing:!closing&&beforeClose.endsWith("/")}}return void 0}function skipJsxExpression(source,start){let depth=0;let quote;let escaped=false;let blockComment=false;let lineComment=false;for(let index=start;index<source.length;index+=1){const character=source[index];const next=source[index+1];if(lineComment){if(character==="\n")lineComment=false;continue}if(blockComment){if(character==="*"&&next==="/"){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==="/"&&next==="/"){lineComment=true;index+=1;continue}if(character==="/"&&next==="*"){blockComment=true;index+=1;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{")depth+=1;else if(character==="}"&&--depth===0)return index+1}return void 0}function findJsxEnd(source,start){let depth=0;for(let index=start;index<source.length;index+=1){if(source[index]==="{"){const expressionEnd=skipJsxExpression(source,index);if(expressionEnd==null)return void 0;index=expressionEnd-1;continue}if(source[index]!=="<")continue;const tag=readJsxTag(source,index);if(!tag)continue;if(tag.closing)depth-=1;else if(!tag.selfClosing)depth+=1;index=tag.end-1;if(depth===0)return tag.end}return void 0}function hasOnlyTrailingSyntax(source){let index=0;while(index<source.length){const rest=source.slice(index);const whitespace=rest.match(/^[\s;)]*/)?.[0].length??0;index+=whitespace;if(source.startsWith("//",index)){const newline=source.indexOf("\n",index+2);index=newline<0?source.length:newline+1;continue}if(source.startsWith("/*",index)){const end=source.indexOf("*/",index+2);if(end<0)return false;index=end+2;continue}return index>=source.length}return true}function extractRootJsx(source){const body=source.replace(/^(?:\s*\()+\s*/,"");const end=findJsxEnd(body,0);return(end==null?body:body.slice(0,end)).trim()}function findBareRootJsxStart(source){const candidates=source.matchAll(/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);for(const candidate of candidates){if(candidate.index==null)continue;const lineStart=candidate.index+(candidate[1]?.length??0);const expressionStart=lineStart+(candidate[2]?.length??0);const jsxStart=candidate.index+candidate[0].lastIndexOf(candidate[3]??"<");const jsxEnd=findJsxEnd(source,jsxStart);if(jsxEnd!=null&&hasOnlyTrailingSyntax(source.slice(jsxEnd)))return expressionStart}return-1}import parseCssColor4 from"parse-css-color";var themeColorKeys=Object.freeze(Object.keys(getThemeColors("dark")).filter(key=>key!=="preset"&&key!=="fontSans"&&key!=="fontMono"));var themeColorKeySet=new Set(themeColorKeys);function validatePlaygroundThemeColors(value){if(value==null||typeof value!=="object"||Array.isArray(value)){throw new Error("themeColors must be a JSON object of CSS colors.")}const colors2={};for(const[key,color]of Object.entries(value)){if(!themeColorKeySet.has(key)){throw new Error(`Unknown themeColors key ${JSON.stringify(key)}.`)}if(typeof color!=="string"||!parseCssColor4(color.trim())){throw new Error(`themeColors.${key} must be a valid CSS color.`)}colors2[key]=color.trim()}return colors2}function parseThemeColorsMetadataLine(line){const withoutComment=stripTrailingLineComment(line.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error("themeColors must be a single-line JSON object of CSS colors.");let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error("themeColors must be a single-line JSON object of CSS colors.")}return validatePlaygroundThemeColors(parsed)}function parseBackgroundMetadataLine(line){const withoutComment=stripTrailingLineComment(line.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.');let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.')}return validatePlaygroundBackground(parsed)}function isBackgroundMetadataLine(line){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]/.test(line)}function validatePlaygroundBackground(value){if(typeof value!=="string"){throw new Error('background must be "theme", "transparent", or a valid CSS color.')}const background=value.trim();if(background==="theme"||background==="transparent"||parseCssColor4(background))return background;throw new Error('background must be "theme", "transparent", or a valid CSS color.')}function isThemeColorsMetadataLine(line){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]/.test(line)}function mergePlaygroundThemeColors(mode,preset,overrides){return{...getThemeColors(mode,preset),...overrides}}function stripTrailingLineComment(line){let quoted=false;let escaped=false;for(let index=0;index<line.length-1;index+=1){const character=line[index];if(quoted){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')quoted=false;continue}if(character==='"')quoted=true;else if(character==="/"&&line[index+1]==="/")return line.slice(0,index)}return line}function readPresetLine(line){const candidate=stripLineComment(line.replace(/^\s*\/\/\s*/,"")).trim();const match=candidate.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?preset(?:\s*:\s*ThemePreset)?\s*[:=]\s*(.+)$/i);if(!match?.[1])return void 0;const expression=match[1].trim().replace(/;\s*$/,"").trim();const quoted=expression.match(/^(['"])(.*)\1$/);const requested=(quoted?.[2]??expression).trim();const normalized=requested.toLowerCase();const preset=quoted&&(normalized==="default"||normalized==="engineering")?normalized:void 0;return{preset,requested}}function readAnimationLine(line){const match=line.match(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?(animationDuration|animationFps)\s*[:=]\s*(.*?)\s*;?\s*(?:\/\/.*)?$/);if(!match)return void 0;const expression=match[2].replace(/;\s*$/,"").trim();if(!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(expression)){throw new Error(`${match[1]} must be a numeric literal.`)}return{name:match[1],value:Number(expression)}}function stripLineComment(line){let quote;let escaped=false;for(let index=0;index<line.length-1;index+=1){const character=line[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0}else if(character==='"'||character==="'")quote=character;else if(character==="/"&&line[index+1]==="/")return line.slice(0,index)}return line}import parseCssColor5 from"parse-css-color";function validatePlaygroundAnimation(animation){if(!Number.isFinite(animation.duration)||animation.duration<=0||animation.duration>10){throw new Error("animationDuration must be greater than 0 and at most 10 seconds.")}if(!Number.isInteger(animation.fps)||animation.fps<1||animation.fps>30){throw new Error("animationFps must be an integer from 1 to 30.")}return{duration:animation.duration,fps:animation.fps}}var RENDER_EXTENSIONS=new Set([".js",".jsx",".mjs",".ts",".tsx"]);var IMPORT_RESOLUTION_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".json"];var DEFAULT_FRAME_WIDTH=960;var DEFAULT_FRAME_HEIGHT=540;var AUTO_SIZE_MAX_WIDTH=1920;var AUTO_SIZE_MAX_HEIGHT=1440;var AUTO_SIZE_GROWTH=1.25;var AUTO_SIZE_ATTEMPTS=6;var SVG_AUTOCROP_PADDING=24;var SVG_CROP_THRESHOLD_PERCENT=10;var cliRequire=createRequire(import.meta.url);var frameDependencyAliasesInstalled=false;var BARE_FRAME_EXTRA_EXPORTS=new Set(["canvas","colors","defineIllustration","defineAnimation","getColor","getGradient","getReadableTextColor","getReadableToneColor","getStyles","getThemeColors","getToneFill","getToneColor","getToneGradient","gradients","heatColor","hold","keyframe","sampleAnimationFrames","styles","toneGradients","tween","typography","wrapWithWatermark"]);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();var framesNeedingGlobalReact=new WeakSet;function usageText(){return`Usage:
3
3
  vizmatic <file-or-directory...> [--out <dir>] [--theme dark,light] [--background transparent|theme|color] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop]
4
4
  vizmatic render <file-or-directory...> [--out <dir>] [--theme dark,light] [--background transparent|theme|color] [--watermark Label] [--watermark-image path-or-url] [--watermark-position top-right] [--no-crop] [--format png|svg|both]
5
5
  vizmatic check <file-or-directory...> [--theme dark,light] [--background transparent|theme|color] [--json]
@@ -15,9 +15,9 @@ Examples:
15
15
  vizmatic render examples --out docs/assets/examples --theme dark --watermark Vizmatic
16
16
  vizmatic render frames/attention.tsx --out dist/frames --theme dark,light
17
17
  vizmatic gif examples/animated-pipeline.tsx --out docs/assets/examples --theme dark --watermark Vizmatic`}function usage(){console.error(usageText());process.exit(1)}function help(){console.log(usageText());process.exit(0)}var WATERMARK_POSITIONS=new Set(["top-left","top-right","bottom-left","bottom-right"]);var IMAGE_MIME_BY_EXT={".apng":"image/apng",".avif":"image/avif",".gif":"image/gif",".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".svg":"image/svg+xml",".webp":"image/webp"};function imageMime(source){return IMAGE_MIME_BY_EXT[extname(source).toLowerCase()]??"application/octet-stream"}async function imageSourceToDataUri(source){if(/^(data:|https?:\/\/)/i.test(source))return source;const filePath=resolve(source);const data=await readFile2(filePath);return`data:${imageMime(filePath)};base64,${data.toString("base64")}`}async function resolveWatermarkAssets(watermark){if(watermark==null||typeof watermark!=="object")return watermark;if(isValidElement4(watermark)||!("image"in watermark)||!watermark.image)return watermark;if(typeof watermark.image==="string"){return{...watermark,image:await imageSourceToDataUri(watermark.image)}}return{...watermark,image:{...watermark.image,src:await imageSourceToDataUri(watermark.image.src)}}}function resolveSelfEntry(){const moduleDir=dirname3(fileURLToPath2(import.meta.url));const bundledEntry=join3(moduleDir,"index.cjs");if(existsSync2(bundledEntry))return bundledEntry;const sourceEntry=join3(moduleDir,"index.ts");if(existsSync2(sourceEntry))return sourceEntry;try{return cliRequire.resolve("vizmatic")}catch{return void 0}}function resolveSelfImportEntry(){const moduleDir=dirname3(fileURLToPath2(import.meta.url));const bundledEntry=join3(moduleDir,"index.js");if(existsSync2(bundledEntry))return bundledEntry;const sourceEntry=join3(moduleDir,"index.ts");if(existsSync2(sourceEntry))return sourceEntry;return void 0}function resolveSelfImportSpecifier(){const entry=resolveSelfImportEntry();return entry?pathToFileURL(entry).href:"vizmatic"}function resolveReactImportSpecifier(){const entry=resolveFrameDependency("react")??"react";return isAbsolute(entry)?pathToFileURL(entry).href:entry}function resolveFrameDependency(request){try{if(request==="vizmatic")return resolveSelfEntry();if(request==="react"||request.startsWith("react/"))return cliRequire.resolve(request)}catch{return void 0}return void 0}function installFrameDependencyAliases(){if(frameDependencyAliasesInstalled)return;frameDependencyAliasesInstalled=true;const moduleWithResolver=Module;const resolveFilename=moduleWithResolver._resolveFilename;moduleWithResolver._resolveFilename=function resolveFrameDependencyAlias(request,parent,isMain,options){return resolveFrameDependency(request)??resolveFilename.call(this,request,parent,isMain,options)}}function maskStringsAndComments(source){const masked=source.split("");let mode="code";let quote;let escaped=false;for(let index=0;index<source.length;index+=1){const character=source[index];const next=source[index+1];if(mode==="line-comment"){if(character==="\n")mode="code";else masked[index]=" ";continue}if(mode==="block-comment"){if(character!=="\n")masked[index]=" ";if(character==="*"&&next==="/"){masked[index+1]=" ";index+=1;mode="code"}continue}if(mode==="string"){if(character!=="\n")masked[index]=" ";if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote){quote=void 0;mode="code"}continue}if(character==="/"&&next==="/"){masked[index]=" ";masked[index+1]=" ";index+=1;mode="line-comment";continue}if(character==="/"&&next==="*"){masked[index]=" ";masked[index+1]=" ";index+=1;mode="block-comment";continue}if(character==='"'||character==="'"||character==="`"){masked[index]=" ";quote=character;mode="string"}}return masked.join("")}function rewriteStaticModuleSpecifier(statement,specifier,replacement){const escaped=escapeRegExp(specifier);const fromPattern=new RegExp(`(\\bfrom\\s+)(["'])${escaped}\\2`);const sideEffectPattern=new RegExp(`(^\\s*import\\s+)(["'])${escaped}\\2`,"m");return statement.replace(fromPattern,(_match,before)=>`${before}${replacement}`).replace(sideEffectPattern,(_match,before)=>`${before}${replacement}`)}function rewriteRelativeImports(statement,framePath){const specifier=staticImportSource(statement);if(!specifier?.match(/^\.{1,2}\//))return statement;const replacement=JSON.stringify(resolveRelativeImportSpecifier(dirname3(framePath),specifier));return rewriteStaticModuleSpecifier(statement,specifier,replacement)}var REACT_IMPORT_BINDING=/^\s*import\s+(?:React(?:\s*,|\s+from)|\*\s+as\s+React\s+from|\{[^}]*\bdefault\s+as\s+React\b[^}]*\}\s+from)/m;function hasReactImportBinding(source){return REACT_IMPORT_BINDING.test(maskStringsAndComments(source))}function containsJsx(source){return/<[A-Za-z][A-Za-z0-9.:-]*(\s|\/|>)/.test(source)}function installTemporaryGlobalReactBinding(){const globalScope=globalThis;const hadOwnBinding=Object.prototype.hasOwnProperty.call(globalScope,"React");const previousBinding=globalScope.React;globalScope.React=React15;return()=>{if(hadOwnBinding)globalScope.React=previousBinding;else Reflect.deleteProperty(globalScope,"React")}}async function withTemporaryGlobalReact(callback){const restore=installTemporaryGlobalReactBinding();try{return await callback()}finally{restore()}}function withTemporaryGlobalReactSync(callback){const restore=installTemporaryGlobalReactBinding();try{return callback()}finally{restore()}}var tsxLoaderRegistered=false;function needsRegisteredTsxLoader(){const[nodeMajor,nodeMinor]=process.versions.node.split(".").map(Number);return nodeMajor===22&&nodeMinor>=23}async function importWithTsx(url){if(needsRegisteredTsxLoader()){if(!tsxLoaderRegistered){const{register}=await import("tsx/esm/api");register();tsxLoaderRegistered=true}return await import(url)}const{tsImport}=await import("tsx/esm/api");return await tsImport(url,import.meta.url)}function rewritePackageImports(source,packageName,replacement){const lines=source.split("\n");const maskedLines=maskStringsAndComments(source).split("\n");const rewritten=[];for(let index=0;index<lines.length;index+=1){const startsStaticModuleStatement=/^\s*import(?:\s|[{'"*])/.test(maskedLines[index]??"")||/^\s*export\s*(?:\{|\*)/.test(maskedLines[index]??"");if(!startsStaticModuleStatement){rewritten.push(lines[index]);continue}const imported=readStaticImport(lines,index);const specifier=staticImportSource(imported.statement);rewritten.push(specifier===packageName?rewriteStaticModuleSpecifier(imported.statement,specifier,replacement):imported.statement);index=imported.end}return rewritten.join("\n")}function rewriteFrameModuleImports(source){const selfImport=JSON.stringify(resolveSelfImportSpecifier());const reactImport=JSON.stringify(resolveReactImportSpecifier());const rewritten=rewritePackageImports(rewritePackageImports(source,"vizmatic",selfImport),"react",reactImport);const hasReactBinding=hasReactImportBinding(rewritten);return`/** @jsxRuntime classic */
18
- ${hasReactBinding?"":"const React = globalThis.React\n"}${rewritten}`}function resolveRelativeImportSpecifier(frameDir,specifier){const absolute=resolve(frameDir,specifier);if(existsSync2(absolute))return absolute;for(const extension of IMPORT_RESOLUTION_EXTENSIONS){const candidate=`${absolute}${extension}`;if(existsSync2(candidate))return candidate}for(const extension of IMPORT_RESOLUTION_EXTENSIONS){const candidate=join3(absolute,`index${extension}`);if(existsSync2(candidate))return candidate}return absolute}function readDimensionLine(line){const match=line.match(/^\s*(?:(?:\/\/\s*)?)(?:export\s+)?(?:(?:const|let|var)\s+)?(width|height)\s*[:=]\s*(\d+)\s*;?\s*$/i);if(!match?.[1]||!match[2])return void 0;return{name:match[1].toLowerCase(),value:Number(match[2])}}function readPresetLine(line){const withoutComment=line.replace(/\s*\/\/.*$/,"").trim();const match=withoutComment.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?preset(?:\s*:\s*ThemePreset)?\s*[:=]\s*(.+)$/i);if(!match?.[1])return void 0;const expression=match[1].trim().replace(/;\s*$/,"").trim();const quoted=expression.match(/^(["'])(.*)\1$/);const requested=(quoted?.[2]??expression).trim();const normalized=requested.toLowerCase();const preset=quoted&&(normalized==="default"||normalized==="engineering")?normalized:void 0;return{preset,requested}}function readFrameDimension(jsx,name){const frameOpen=jsx.match(/<Frame\b[^>]*>/)?.[0];const value=frameOpen?.match(new RegExp(`${name}\\s*=\\s*(?:{(\\d+)}|"(\\d+)"|'(\\d+)'|(\\d+))`));const raw=value?.[1]??value?.[2]??value?.[3]??value?.[4];return raw?Number(raw):void 0}function staticImportSource(statement){const match=statement.trim().match(/(?:\bfrom\s+)?(["'])([^"']+)\1\s*;?(?:\s*\/\/.*)?$/s);return match?.[2]}function readStaticImport(lines,start){const statement=[lines[start]];let end=start;while(staticImportSource(statement.join("\n"))==null&&end+1<lines.length){end+=1;statement.push(lines[end])}return{statement:statement.join("\n"),end}}function bareFrameAlias(name){return`__Vizmatic_${name}`}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bareFrameExportsForSource(source){return BARE_FRAME_EXPORTS.filter(name=>{if(name==="getThemeColors")return true;const escapedName=escapeRegExp(name);if(/^[A-Z]/.test(name))return new RegExp(`<\\/?${escapedName}(?:\\s|>|/)|\\b${escapedName}\\s*\\(`).test(source);return new RegExp(`\\b${escapedName}\\b`).test(source)})}function buildAutoImportStatement(names){const specifiers=names.map(name=>` ${name} as ${bareFrameAlias(name)}`).join(",\n");return`import {
18
+ ${hasReactBinding?"":"const React = globalThis.React\n"}${rewritten}`}function resolveRelativeImportSpecifier(frameDir,specifier){const absolute=resolve(frameDir,specifier);if(existsSync2(absolute))return absolute;for(const extension of IMPORT_RESOLUTION_EXTENSIONS){const candidate=`${absolute}${extension}`;if(existsSync2(candidate))return candidate}for(const extension of IMPORT_RESOLUTION_EXTENSIONS){const candidate=join3(absolute,`index${extension}`);if(existsSync2(candidate))return candidate}return absolute}function readDimensionLine(line){const candidate=line.replace(/^\s*\/\/\s*/,"").replace(/\s*\/\/.*$/,"");const match=candidate.match(/^\s*(?:export\s+)?(?:(?:const|let|var)\s+)?(width|height)\s*[:=]\s*(\d+)\s*;?\s*$/i);if(!match?.[1]||!match[2])return void 0;return{name:match[1].toLowerCase(),value:Number(match[2])}}function readPresetLine2(line){return readPresetLine(line)}function readFrameDimension(jsx,name){const frameOpen=jsx.match(/<Frame\b[^>]*>/)?.[0];const value=frameOpen?.match(new RegExp(`${name}\\s*=\\s*(?:{(\\d+)}|"(\\d+)"|'(\\d+)'|(\\d+))`));const raw=value?.[1]??value?.[2]??value?.[3]??value?.[4];return raw?Number(raw):void 0}function staticImportSource(statement){const match=statement.trim().match(/(?:\bfrom\s+)?(["'])([^"']+)\1\s*;?(?:\s*\/\/.*)?$/s);return match?.[2]}function readStaticImport(lines,start){const statement=[lines[start]];let end=start;while(staticImportSource(statement.join("\n"))==null&&end+1<lines.length){end+=1;statement.push(lines[end])}return{statement:statement.join("\n"),end}}function bareFrameAlias(name){return`__Vizmatic_${name}`}function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bareFrameExportsForSource(source){return BARE_FRAME_EXPORTS.filter(name=>{if(name==="getThemeColors")return true;const escapedName=escapeRegExp(name);if(/^[A-Z]/.test(name))return new RegExp(`<\\/?${escapedName}(?:\\s|>|/)|\\b${escapedName}\\s*\\(`).test(source);return new RegExp(`\\b${escapedName}\\b`).test(source)})}function buildAutoImportStatement(names){const specifiers=names.map(name=>` ${name} as ${bareFrameAlias(name)}`).join(",\n");return`import {
19
19
  ${specifiers}
20
- } from ${JSON.stringify(resolveSelfImportSpecifier())}`}function buildAutoImportDeclarations(names){return names.map(name=>{if(name==="Watermark"||name==="MathText")return`const ${name} = ${bareFrameAlias(name)};`;if(name==="DotPoint"||name==="DashedLine")return`const ${name} = __withTheme(${bareFrameAlias(name)}, true);`;if(/^[A-Z]/.test(name))return`const ${name} = __withTheme(${bareFrameAlias(name)});`;return`const ${name} = ${bareFrameAlias(name)};`}).join("\n")}function buildBareFrameModule(framePath,source){const imports=[];const bodyLines=[];let width;let height;let preset="default";let animationDuration;let animationFps;const lines=source.split(/\r?\n/);const maskedLines=maskStringsAndComments(source).split(/\r?\n/);for(let index=0;index<lines.length;index+=1){const line=lines[index];const trimmed=maskedLines[index]?.trim()??"";if(trimmed==="import"||trimmed.startsWith("import ")){const imported=readStaticImport(lines,index);const specifier=staticImportSource(imported.statement);if(specifier!=="react"&&specifier!=="vizmatic"){imports.push(rewriteRelativeImports(imported.statement,framePath))}index=imported.end;continue}bodyLines.push(line)}const body=bodyLines.join("\n");const jsxStart=findBareRootJsxStart(body);if(jsxStart<0)return void 0;const setupLines=[];let metadataPreamble=true;let metadataBlockComment=false;for(const line of body.slice(0,jsxStart).split(/\r?\n/)){const trimmed=line.trim();if(metadataBlockComment){if(trimmed.includes("*/"))metadataBlockComment=false;setupLines.push(line);continue}if(trimmed.startsWith("/*")){metadataBlockComment=!trimmed.slice(2).includes("*/");setupLines.push(line);continue}const dimension2=metadataPreamble?readDimensionLine(line):void 0;if(dimension2){if(dimension2.name==="width")width=dimension2.value;if(dimension2.name==="height")height=dimension2.value;continue}const framePreset=metadataPreamble?readPresetLine(line):void 0;if(framePreset){if(framePreset.preset)preset=framePreset.preset;else{console.warn(`warning: Unknown preset ${JSON.stringify(framePreset.requested)}; using "default". Available presets: "default", "engineering".`)}continue}const animationLine=metadataPreamble?readAnimationLine(line):void 0;if(animationLine){if(animationLine.name==="animationDuration")animationDuration=animationLine.value;else animationFps=animationLine.value;continue}if(trimmed&&!trimmed.startsWith("//"))metadataPreamble=false;setupLines.push(line)}const setup=setupLines.join("\n").replace(/^\s*export\s+/gm,"");if(animationFps!==void 0&&animationDuration===void 0){throw new Error("animationFps requires animationDuration in the metadata preamble.")}const hasAnimationMetadata=animationDuration!==void 0;if(animationDuration!==void 0){validatePlaygroundAnimation({duration:animationDuration,fps:animationFps??10})}const jsx=extractRootJsx(body.slice(jsxStart).trim().replace(/^export\s+default\s+/,""));const declaresThemeColors=/\b(?:const|let|var)\s+c\b/.test(setup);const frameWidth=readFrameDimension(jsx,"width");const frameHeight=readFrameDimension(jsx,"height");const autoSize={width:width==null&&frameWidth==null,height:height==null&&frameHeight==null};width??=frameWidth??DEFAULT_FRAME_WIDTH;height??=frameHeight??DEFAULT_FRAME_HEIGHT;const autoImports=bareFrameExportsForSource(body);const createBody=hasAnimationMetadata?` const c = __theme
20
+ } from ${JSON.stringify(resolveSelfImportSpecifier())}`}function buildAutoImportDeclarations(names,preset){return names.map(name=>{if(name==="getThemeColors"){return`const getThemeColors = (theme, requestedPreset = ${JSON.stringify(preset)}) => __getTheme(theme, requestedPreset);`}if(name==="Watermark"||name==="MathText")return`const ${name} = ${bareFrameAlias(name)};`;if(name==="DotPoint"||name==="DashedLine")return`const ${name} = __withTheme(${bareFrameAlias(name)}, true);`;if(/^[A-Z]/.test(name))return`const ${name} = __withTheme(${bareFrameAlias(name)});`;return`const ${name} = ${bareFrameAlias(name)};`}).join("\n")}function buildBareFrameModule(framePath,source){const imports=[];const bodyLines=[];let width;let height;let preset="default";let animationDuration;let animationFps;let themeColors={};let sourceBackground;const lines=source.split(/\r?\n/);const maskedLines=maskStringsAndComments(source).split(/\r?\n/);for(let index=0;index<lines.length;index+=1){const line=lines[index];const trimmed=maskedLines[index]?.trim()??"";if(trimmed==="import"||trimmed.startsWith("import ")){const imported=readStaticImport(lines,index);const specifier=staticImportSource(imported.statement);if(specifier!=="react"&&specifier!=="vizmatic"){imports.push(rewriteRelativeImports(imported.statement,framePath))}index=imported.end;continue}bodyLines.push(line)}const body=bodyLines.join("\n");const jsxStart=findBareRootJsxStart(body);if(jsxStart<0)return void 0;const setupLines=[];let metadataPreamble=true;let metadataBlockComment=false;for(const line of body.slice(0,jsxStart).split(/\r?\n/)){const trimmed=line.trim();if(metadataBlockComment){if(trimmed.includes("*/"))metadataBlockComment=false;setupLines.push(line);continue}if(trimmed.startsWith("/*")){metadataBlockComment=!trimmed.slice(2).includes("*/");setupLines.push(line);continue}const dimension2=metadataPreamble?readDimensionLine(line):void 0;if(dimension2){if(dimension2.name==="width")width=dimension2.value;if(dimension2.name==="height")height=dimension2.value;continue}const framePreset=metadataPreamble?readPresetLine2(line):void 0;if(framePreset){if(framePreset.preset)preset=framePreset.preset;else{console.warn(`warning: Unknown preset ${JSON.stringify(framePreset.requested)}; using "default". Available presets: "default", "engineering".`)}continue}const animationLine=metadataPreamble?readAnimationLine(line):void 0;if(animationLine){if(animationLine.name==="animationDuration")animationDuration=animationLine.value;else animationFps=animationLine.value;continue}if(metadataPreamble&&isThemeColorsMetadataLine(line)){themeColors=parseThemeColorsMetadataLine(line)??{};continue}if(metadataPreamble&&isBackgroundMetadataLine(line)){sourceBackground=parseBackgroundMetadataLine(line);continue}if(trimmed&&!trimmed.startsWith("//"))metadataPreamble=false;setupLines.push(line)}const setup=setupLines.join("\n").replace(/^\s*export\s+/gm,"");if(animationFps!==void 0&&animationDuration===void 0){throw new Error("animationFps requires animationDuration in the metadata preamble.")}const hasAnimationMetadata=animationDuration!==void 0;if(animationDuration!==void 0){validatePlaygroundAnimation({duration:animationDuration,fps:animationFps??10})}const jsx=extractRootJsx(body.slice(jsxStart).trim().replace(/^export\s+default\s+/,""));const rootComponent=jsx.match(/^\s*<([A-Za-z][\w.]*)\b/)?.[1];const declaresThemeColors=/\b(?:const|let|var)\s+c\b/.test(setup);const frameWidth=readFrameDimension(jsx,"width");const frameHeight=readFrameDimension(jsx,"height");const autoSize={width:width==null&&frameWidth==null,height:height==null&&frameHeight==null};width??=frameWidth??DEFAULT_FRAME_WIDTH;height??=frameHeight??DEFAULT_FRAME_HEIGHT;const autoImports=bareFrameExportsForSource(body);const createBody=hasAnimationMetadata?` const c = __theme
21
21
  const t = 0
22
22
  return (() => {
23
23
  ${setup}
@@ -32,7 +32,10 @@ const React = globalThis.React
32
32
  ${buildAutoImportStatement(autoImports)}
33
33
  ${imports.join("\n")}
34
34
 
35
- let __theme = __Vizmatic_getThemeColors('dark', ${JSON.stringify(preset)})
35
+ function __getTheme(theme, requestedPreset = ${JSON.stringify(preset)}) {
36
+ return { ...__Vizmatic_getThemeColors(theme, requestedPreset), ...${JSON.stringify(themeColors)} }
37
+ }
38
+ let __theme = __getTheme('dark')
36
39
  function __withTheme(Component, returnsArray = false) {
37
40
  function VizmaticAutoTheme(props) {
38
41
  const themedProps = props?.c ? props : { ...props, c: __theme }
@@ -44,20 +47,24 @@ function __withTheme(Component, returnsArray = false) {
44
47
  return VizmaticAutoTheme
45
48
  }
46
49
  const Frame = ({ children }) => React.createElement(React.Fragment, null, children)
47
- ${buildAutoImportDeclarations(autoImports)}
50
+ ${buildAutoImportDeclarations(autoImports,preset)}
48
51
 
49
52
  export const width = ${width}
50
53
  export const height = ${height}
51
54
  export const __vizmaticAutoSize = ${JSON.stringify(autoSize)}
55
+ export const __vizmaticThemeColors = ${JSON.stringify(themeColors)}
56
+ export const __vizmaticBackground = ${JSON.stringify(sourceBackground)}
57
+ export const __vizmaticPreset = ${JSON.stringify(preset)}
58
+ export const __vizmaticRootComponent = ${JSON.stringify(rootComponent)}
52
59
 
53
60
  export function create(theme = 'dark') {
54
- __theme = __Vizmatic_getThemeColors(theme, ${JSON.stringify(preset)})
61
+ __theme = __getTheme(theme)
55
62
  ${createBody}
56
63
  }
57
64
 
58
65
  export default { create, width, height }
59
- `}function hasAnimationMetadataPreamble(source){let metadataPreamble=true;let metadataBlockComment=false;const lines=source.split(/\r?\n/);const maskedLines=maskStringsAndComments(source).split(/\r?\n/);for(let index=0;index<lines.length&&metadataPreamble;index+=1){const line=lines[index]??"";const trimmed=maskedLines[index]?.trim()??"";if(metadataBlockComment){if(trimmed.includes("*/"))metadataBlockComment=false;continue}if(trimmed.startsWith("/*")){metadataBlockComment=!trimmed.slice(2).includes("*/");continue}if(readDimensionLine(line)||readPresetLine(line))continue;try{if(readAnimationLine(line))return true}catch{if(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?animation(?:Duration|Fps)\s*[:=]/.test(line))return true}if(trimmed&&!trimmed.startsWith("//"))metadataPreamble=false}return false}function isBareFrameSource(source){const rootJsxStart=findBareRootJsxStart(source);if(rootJsxStart<0)return false;if(hasAnimationMetadataPreamble(source.slice(0,rootJsxStart))){const maskedSource=maskStringsAndComments(source);const exportsFrameFactory=/\bexport\s+(?:(?:async\s+)?function\s+(?:create|createScenes|createAnimation)\b|(?:const|let|var)\s+(?:create|createScenes|createAnimation)\b)/.test(maskedSource)||/\bexport\s*\{[^}]*\b(?:create|createScenes|createAnimation)\b[^}]*\}/s.test(maskedSource)||/\bexport\s+default\s+(?:(?:async\s+)?function\s+(?:create|createScenes|createAnimation)\b|(?:create|createScenes|createAnimation)\b|\{[^}]*\b(?:create|createScenes|createAnimation)\b[^}]*\})/s.test(maskedSource);if(!exportsFrameFactory&&!/\bdefineIllustration\s*\(|\bcreateScenes\s*\(/.test(maskedSource))return true}if(/\bdefineIllustration\s*\(/.test(source))return false;if(/\bcreateScenes\s*\(/.test(source))return false;if(/\bcreateAnimation\s*\(/.test(source))return false;if(/\bexport\s+(?:const|function)\s+create\b/.test(source))return false;return true}async function importBareFrame(filePath,source){source??=await readFile2(filePath,"utf8");const moduleSource=buildBareFrameModule(filePath,source);if(!moduleSource)return void 0;const tempDir=await mkdtemp2(join3(tmpdir2(),"vizmatic-frame-"));const tempPath=join3(tempDir,`${basename(filePath).replace(/\.[^.]+$/,"")}.generated.tsx`);await writeFile3(join3(tempDir,"package.json"),'{"type":"module"}\n');await writeFile3(tempPath,`${moduleSource}
60
- `);try{const mod=await withTemporaryGlobalReact(()=>importWithTsx(pathToFileURL(tempPath).href));framesNeedingGlobalReact.add(mod);return mod}finally{await rm2(tempDir,{recursive:true,force:true})}}async function importRewrittenFrame(filePath,source){const extension=extname(filePath);const stem=basename(filePath,extension);const tempPath=join3(dirname3(filePath),`.${stem}.vizmatic-${randomUUID()}${extension}`);await writeFile3(tempPath,rewriteFrameModuleImports(source));try{return await importWithTsx(pathToFileURL(tempPath).href)}finally{await rm2(tempPath,{force:true})}}function parseRenderArgs(argv){const inputs=[];let outDir="dist/frames";let themes=["dark","light"];let watermark;let watermarkOptions;let crop=true;let scale;let fps;let background;let format="png";function mutableWatermark(){if(!watermarkOptions){watermarkOptions=typeof watermark==="object"&&watermark!==null&&!isValidElement4(watermark)?{...watermark}:{};if(typeof watermark==="string")watermarkOptions.text=watermark;watermark=watermarkOptions}return watermarkOptions}function readOptionalValue(index){const next=argv[index+1];if(!next||next.startsWith("-"))return void 0;return next}function setWatermarkImageSource(src){const current=mutableWatermark().image;if(current&&typeof current==="object"){current.src=src}else{mutableWatermark().image=src}}function mutableWatermarkImage(){const watermarkConfig=mutableWatermark();if(!watermarkConfig.image||typeof watermarkConfig.image==="string"){watermarkConfig.image={src:watermarkConfig.image??""}}return watermarkConfig.image}for(let index=0;index<argv.length;index+=1){const arg=argv[index];if(!arg)continue;if(arg==="--out"){outDir=argv[++index]??usage()}else if(arg==="--theme"){const raw=argv[++index]??usage();themes=raw.split(",").map(theme=>theme.trim()).filter(Boolean);if(themes.length===0||themes.some(theme=>theme!=="dark"&&theme!=="light"))usage()}else if(arg==="--brand"){const label=readOptionalValue(index);mutableWatermark().text=label??"Vizmatic";if(label)index+=1}else if(arg==="--watermark"){const label=readOptionalValue(index);if(label){mutableWatermark().text=label;index+=1}else{watermark=true;watermarkOptions=void 0}}else if(arg==="--watermark-text"){const rawText=argv[++index]??usage();mutableWatermark().text=rawText==="false"||rawText==="none"?false:rawText}else if(arg==="--watermark-icon"){const rawIcon=argv[++index]??usage();mutableWatermark().icon=rawIcon==="false"||rawIcon==="none"?false:rawIcon}else if(arg==="--watermark-image"){setWatermarkImageSource(argv[++index]??usage())}else if(arg==="--watermark-image-width"){const width=Number(argv[++index]);if(!Number.isFinite(width)||width<=0)usage();mutableWatermarkImage().width=width}else if(arg==="--watermark-image-height"){const height=Number(argv[++index]);if(!Number.isFinite(height)||height<=0)usage();mutableWatermarkImage().height=height}else if(arg==="--watermark-position"){const position=argv[++index];if(!position||!WATERMARK_POSITIONS.has(position))usage();mutableWatermark().position=position}else if(arg==="--no-brand"){watermark=false;watermarkOptions=void 0}else if(arg==="--no-watermark"){watermark=false;watermarkOptions=void 0}else if(arg==="--no-crop"){crop=false}else if(arg==="--transparent"||arg==="--transparent-background"){background="transparent"}else if(arg==="--background"){background=argv[++index]??usage()}else if(arg==="--scale"){const rawScale=Number(argv[++index]);if(!Number.isFinite(rawScale)||rawScale<=0)usage();scale=rawScale}else if(arg==="--fps"){const rawFps=Number(argv[++index]);if(!Number.isInteger(rawFps)||rawFps<1||rawFps>50)usage();fps=rawFps}else if(arg==="--format"){const rawFormat=argv[++index];if(rawFormat!=="png"&&rawFormat!=="svg"&&rawFormat!=="both")usage();format=rawFormat}else if(arg.startsWith("-")){usage()}else{inputs.push(arg)}}if(inputs.length===0)usage();return{inputs,outDir,themes,watermark,crop,scale,fps,background,format}}function parseCheckArgs(argv){const inputs=[];let themes=["dark","light"];let background;let json=false;for(let index=0;index<argv.length;index+=1){const arg=argv[index];if(!arg)continue;if(arg==="--theme"){const raw=argv[++index]??usage();themes=raw.split(",").map(theme=>theme.trim()).filter(Boolean);if(themes.length===0||themes.some(theme=>theme!=="dark"&&theme!=="light"))usage()}else if(arg==="--transparent"||arg==="--transparent-background"){background="transparent"}else if(arg==="--background"){background=argv[++index]??usage()}else if(arg==="--json"){json=true}else if(arg.startsWith("-")){usage()}else{inputs.push(arg)}}if(inputs.length===0)usage();return{inputs,themes,background,json}}async function findFrameFiles(inputs){const files=new Set;async function walk(path){const resolved=resolve(path);const entries=await readdir(resolved,{withFileTypes:true}).catch(()=>void 0);if(!entries){if(RENDER_EXTENSIONS.has(extname(resolved))&&!resolved.endsWith(".d.ts")){files.add(resolved)}return}for(const entry of entries){const next=join3(resolved,entry.name);if(entry.isDirectory()){if(entry.name==="node_modules"||entry.name==="dist"||entry.name.startsWith("_"))continue;await walk(next)}else if(RENDER_EXTENSIONS.has(extname(entry.name))&&!entry.name.endsWith(".d.ts")){files.add(next)}}}for(const input of inputs){await walk(input)}return[...files].sort()}function commonDirectory(paths){let candidate=dirname3(paths[0]??process.cwd());while(!paths.every(path=>{const rel=relative(candidate,path);return rel===""||!rel.startsWith(`..${sep}`)&&rel!==".."&&!isAbsolute(rel)})){const parent=dirname3(candidate);if(parent===candidate)return candidate;candidate=parent}return candidate}function outputStems(files){const basenameCounts=new Map;for(const file of files){const name=basename(file,extname(file));basenameCounts.set(name,(basenameCounts.get(name)??0)+1)}const root=commonDirectory(files);const stems=new Map;const used=new Map;for(const file of files){const base=basename(file,extname(file));const stem=basenameCounts.get(base)===1?base:relative(root,file).slice(0,-extname(file).length).split(sep).join("__");const previous=used.get(stem);if(previous){throw new Error(`output name collision for ${relative(process.cwd(),previous)} and ${relative(process.cwd(),file)}: ${stem}`)}used.set(stem,file);stems.set(file,stem)}return stems}async function importFrame(filePath){installFrameDependencyAliases();const url=pathToFileURL(filePath).href;if(!RENDER_EXTENSIONS.has(extname(filePath)))return await import(url);const source=await readFile2(filePath,"utf8");const isBareFrame=isBareFrameSource(source);const preferBareFrame=isBareFrame&&!/\bexport\s+default\b/.test(source);const needsGlobalReactBinding=!hasReactImportBinding(source)&&containsJsx(source);async function importWithOptionalReactBinding(loader){const mod=needsGlobalReactBinding?await withTemporaryGlobalReact(loader):await loader();if(needsGlobalReactBinding){framesNeedingGlobalReact.add(mod)}return mod}let loadError;const cliRunsFromTypeScript=extname(fileURLToPath2(import.meta.url))===".ts";if(!needsRegisteredTsxLoader()||cliRunsFromTypeScript){try{const mod=await importWithOptionalReactBinding(()=>import(url));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(nativeError){loadError=nativeError}}try{const mod=await importWithOptionalReactBinding(()=>importWithTsx(url));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(tsxError){loadError=tsxError}if(preferBareFrame){const bareFrame=await importBareFrame(filePath,source);if(bareFrame)return bareFrame}try{const mod=await importWithOptionalReactBinding(()=>importRewrittenFrame(filePath,source));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(rewrittenError){if(!isBareFrame)throw rewrittenError}if(!preferBareFrame){const bareFrame=await importBareFrame(filePath,source);if(bareFrame)return bareFrame}throw loadError??new Error(`Unable to load frame ${filePath}`)}function normalizeAutoSize2(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value&&typeof value==="object"){return{width:value.width??defaults.width,height:value.height??defaults.height}}return defaults}function normalizeFrameModule(mod){const defaultObject=typeof mod.default==="object"&&mod.default&&!isValidElement4(mod.default)&&("create"in mod.default||"createAnimation"in mod.default||"default"in mod.default)?mod.default:void 0;const hasAutoSizeSetting=mod.autoSize!=null||mod.__vizmaticAutoSize!=null;const hasWidth=mod.width!=null||defaultObject?.width!=null;const hasHeight=mod.height!=null||defaultObject?.height!=null;const width=mod.width??defaultObject?.width??DEFAULT_FRAME_WIDTH;const height=mod.height??defaultObject?.height??DEFAULT_FRAME_HEIGHT;const autoSize=normalizeAutoSize2(mod.autoSize??mod.__vizmaticAutoSize,{width:!hasWidth||!hasAutoSizeSetting&&width===DEFAULT_FRAME_WIDTH,height:!hasHeight||!hasAutoSizeSetting&&height===DEFAULT_FRAME_HEIGHT});const normalized={...mod,...defaultObject??{},width,height,autoSize};if(framesNeedingGlobalReact.has(mod))framesNeedingGlobalReact.add(normalized);return normalized}function withFrameReactBinding(mod,callback){const needsGlobalReactBinding=framesNeedingGlobalReact.has(mod);return needsGlobalReactBinding?withTemporaryGlobalReactSync(callback):callback()}function frameElement(mod,theme){return withFrameReactBinding(mod,()=>{if(mod.create)return mod.create(theme);if(mod.default&&!(typeof mod.default==="object"&&"create"in mod.default))return mod.default;throw new Error("frame module must export create(theme) or default React element")})}function overflowEdges2(error){if(error instanceof CanvasOverflowError){return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}const message=error instanceof Error?error.message:String(error);const match=message.match(/Content overflows canvas at: ([^.]+)/);if(!match?.[1])return void 0;const edges=match[1].split(",").map(edge=>edge.trim()).filter(Boolean);if(edges.some(edge=>edge!=="top"&&edge!=="right"&&edge!=="bottom"&&edge!=="left")){return void 0}return edges}function growDimension(value,max){return Math.min(max,Math.ceil(value*AUTO_SIZE_GROWTH/10)*10)}function nextAutoSize2(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?growDimension(width,AUTO_SIZE_MAX_WIDTH):width;const nextHeight=growHeight?growDimension(height,AUTO_SIZE_MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrameToPng(mod,theme,options){let width=options.width;let height=options.height;const{inspectLayout,...renderOptions}=options;for(let attempt=0;attempt<AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const recreate=mod.create?nextTheme=>withFrameReactBinding(mod,()=>mod.create(nextTheme)):void 0;const output=await renderToPngWithOutput(frameElement(mod,theme),{...renderOptions,width,height,onNodeDetected:inspectLayout?node=>layoutNodes.push(node):void 0},recreate,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges2(error);const next=edges?nextAutoSize2(width,height,mod.autoSize,edges):void 0;if(!next||attempt===AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function rasterizeSvgForBounds(svg,width){return new Resvg3(svg,{fitTo:{mode:"width",value:width},background:"rgba(0, 0, 0, 0)"}).render()}function replaceSvgRootAttribute(attributes,name,value){const pattern=new RegExp(`\\s${name}="[^"]*"`);return pattern.test(attributes)?attributes.replace(pattern,` ${name}="${value}"`):`${attributes} ${name}="${value}"`}function cropSvgToRegion(svg,region){const x=Math.max(0,Math.floor(region.x));const y=Math.max(0,Math.floor(region.y));const width=Math.max(1,Math.ceil(region.width));const height=Math.max(1,Math.ceil(region.height));const cropped=svg.replace(/^<svg\b([^>]*)>/,(_match,attributes)=>{let next=replaceSvgRootAttribute(attributes,"width",String(width));next=replaceSvgRootAttribute(next,"height",String(height));next=replaceSvgRootAttribute(next,"viewBox",`${x} ${y} ${width} ${height}`);return`<svg${next}>`});return{svg:cropped,width,height}}function cropSavesEnough2(source,target){return source>target&&(source-target)/source*100>=SVG_CROP_THRESHOLD_PERCENT}async function renderFrameToSvg(mod,theme,options){let width=options.width;let height=options.height;let originalElement=frameElement(mod,theme);let originalSvg="";let initialBounds;for(let attempt=0;attempt<AUTO_SIZE_ATTEMPTS;attempt+=1){originalElement=frameElement(mod,theme);try{originalSvg=await renderToSvg(originalElement,width,height,{background:options.background,theme})}catch(error){const edges=overflowEdges2(error);const next=edges?nextAutoSize2(width,height,mod.autoSize,edges):void 0;if(!next||attempt===AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height;continue}const initialRaster=rasterizeSvgForBounds(originalSvg,width);const pixels=new Uint8Array(initialRaster.pixels.buffer);const background=detectBackgroundColor(pixels);const overflow=detectOverflow(pixels,initialRaster.width,initialRaster.height,background);if(overflow.overflows){const edges=Object.entries(overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge);const next=nextAutoSize2(width,height,mod.autoSize,edges);if(!next||attempt===AUTO_SIZE_ATTEMPTS-1){throw new CanvasOverflowError(width,height,overflow)}width=next.width;height=next.height;continue}initialBounds=detectContentBounds(pixels,initialRaster.width,initialRaster.height,background,SVG_AUTOCROP_PADDING);break}if(!initialBounds)throw new Error("unable to measure SVG content bounds");let finalWidth=width;let finalHeight=height;let finalElement=originalElement;let finalSvg=originalSvg;const croppedHeight=initialBounds.y+initialBounds.height;const heightSavedPercent=(height-croppedHeight)/height*100;if(options.crop&&heightSavedPercent>=SVG_CROP_THRESHOLD_PERCENT){finalHeight=croppedHeight;finalElement=mod.create?frameElement(mod,theme):originalElement}const renderFinalSvg=(element,targetWidth,targetHeight)=>renderToSvg(element,targetWidth,targetHeight,{watermark:options.watermark,background:options.background,theme});finalSvg=await renderFinalSvg(finalElement,finalWidth,finalHeight);if(finalHeight<height){const cropRaster=rasterizeSvgForBounds(finalSvg,finalWidth);const cropPixels2=new Uint8Array(cropRaster.pixels.buffer);const cropBackground=detectBackgroundColor(cropPixels2);const cropOverflow=detectOverflow(cropPixels2,cropRaster.width,cropRaster.height,cropBackground);if(cropOverflow.overflows){finalHeight=height;finalElement=originalElement;finalSvg=await renderFinalSvg(finalElement,finalWidth,finalHeight)}}if(options.crop){const viewportRaster=rasterizeSvgForBounds(finalSvg,finalWidth);const viewportPixels=new Uint8Array(viewportRaster.pixels.buffer);const viewportBackground=detectBackgroundColor(viewportPixels);const viewportBounds=detectContentBounds(viewportPixels,viewportRaster.width,viewportRaster.height,viewportBackground,SVG_AUTOCROP_PADDING);if(cropSavesEnough2(finalWidth,viewportBounds.width)||cropSavesEnough2(viewportRaster.height,viewportBounds.height)){const cropped=cropSvgToRegion(finalSvg,viewportBounds);finalSvg=cropped.svg;finalWidth=cropped.width;finalHeight=cropped.height}}return{width,height,outputWidth:finalWidth,outputHeight:finalHeight,svg:finalSvg}}async function renderCommand(argv){const args=parseRenderArgs(argv);const cliWatermark=await resolveWatermarkAssets(args.watermark);const files=await findFrameFiles(args.inputs);if(files.length===0)throw new Error("no frame files found");const stems=outputStems(files);await mkdir3(args.outDir,{recursive:true});const manifest=[];for(const file of files){const rawMod=await importFrame(file);const mod=normalizeFrameModule(rawMod);const name=stems.get(file)??basename(file).replace(/\.[^.]+$/,"");const outputs=[];const outputDetails=[];const moduleWatermark=await resolveWatermarkAssets(mod.watermark??mod.brand);let renderWidth=mod.width;let renderHeight=mod.height;let outputWidth=0;let outputHeight=0;for(const theme of args.themes){const inputWidth=renderWidth;const inputHeight=renderHeight;let themeWidth=inputWidth;let themeHeight=inputHeight;if(args.format==="png"||args.format==="both"){const outputName=`${name}_${theme}.png`;const outputPath=join3(args.outDir,outputName);const rendered=await renderFrameToPng(mod,theme,{width:inputWidth,height:inputHeight,outputPath,watermark:cliWatermark??moduleWatermark,crop:args.crop,scale:args.scale,background:args.background});themeWidth=rendered.width;themeHeight=rendered.height;outputWidth=Math.max(outputWidth,rendered.outputWidth);outputHeight=Math.max(outputHeight,rendered.outputHeight);outputs.push(outputName);outputDetails.push({theme,format:"png",path:outputName,width:rendered.outputWidth,height:rendered.outputHeight});console.log(`rendered ${relative(process.cwd(),outputPath)}`)}if(args.format==="svg"||args.format==="both"){const outputName=`${name}_${theme}.svg`;const outputPath=join3(args.outDir,outputName);const rendered=await renderFrameToSvg(mod,theme,{width:inputWidth,height:inputHeight,watermark:cliWatermark??moduleWatermark,crop:args.crop,background:args.background});await writeFile3(outputPath,rendered.svg);themeWidth=rendered.width;themeHeight=rendered.height;outputWidth=Math.max(outputWidth,rendered.outputWidth);outputHeight=Math.max(outputHeight,rendered.outputHeight);outputs.push(outputName);outputDetails.push({theme,format:"svg",path:outputName,width:rendered.outputWidth,height:rendered.outputHeight});console.log(`rendered ${relative(process.cwd(),outputPath)}`)}renderWidth=themeWidth;renderHeight=themeHeight}manifest.push({name,source:relative(process.cwd(),file),width:renderWidth,height:renderHeight,outputWidth,outputHeight,outputs,outputDetails})}await writeFile3(join3(args.outDir,"manifest.json"),`${JSON.stringify(manifest,null,2)}
66
+ `}function hasAnimationMetadataPreamble(source){let metadataPreamble=true;let metadataBlockComment=false;const lines=source.split(/\r?\n/);const maskedLines=maskStringsAndComments(source).split(/\r?\n/);for(let index=0;index<lines.length&&metadataPreamble;index+=1){const line=lines[index]??"";const trimmed=maskedLines[index]?.trim()??"";if(metadataBlockComment){if(trimmed.includes("*/"))metadataBlockComment=false;continue}if(trimmed.startsWith("/*")){metadataBlockComment=!trimmed.slice(2).includes("*/");continue}if(readDimensionLine(line)||readPresetLine2(line))continue;try{if(readAnimationLine(line))return true}catch{if(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?animation(?:Duration|Fps)\s*[:=]/.test(line))return true}if(trimmed&&!trimmed.startsWith("//"))metadataPreamble=false}return false}function isBareFrameSource(source){const rootJsxStart=findBareRootJsxStart(source);if(rootJsxStart<0)return false;if(hasAnimationMetadataPreamble(source.slice(0,rootJsxStart))){const maskedSource=maskStringsAndComments(source);const exportsFrameFactory=/\bexport\s+(?:(?:async\s+)?function\s+(?:create|createScenes|createAnimation)\b|(?:const|let|var)\s+(?:create|createScenes|createAnimation)\b)/.test(maskedSource)||/\bexport\s*\{[^}]*\b(?:create|createScenes|createAnimation)\b[^}]*\}/s.test(maskedSource)||/\bexport\s+default\s+(?:(?:async\s+)?function\s+(?:create|createScenes|createAnimation)\b|(?:create|createScenes|createAnimation)\b|\{[^}]*\b(?:create|createScenes|createAnimation)\b[^}]*\})/s.test(maskedSource);if(!exportsFrameFactory&&!/\bdefineIllustration\s*\(|\bcreateScenes\s*\(/.test(maskedSource))return true}if(/\bdefineIllustration\s*\(/.test(source))return false;if(/\bcreateScenes\s*\(/.test(source))return false;if(/\bcreateAnimation\s*\(/.test(source))return false;if(/\bexport\s+(?:const|function)\s+create\b/.test(source))return false;return true}async function importBareFrame(filePath,source){source??=await readFile2(filePath,"utf8");const moduleSource=buildBareFrameModule(filePath,source);if(!moduleSource)return void 0;const tempDir=await mkdtemp2(join3(tmpdir2(),"vizmatic-frame-"));const tempPath=join3(tempDir,`${basename(filePath).replace(/\.[^.]+$/,"")}.generated.tsx`);await writeFile3(join3(tempDir,"package.json"),'{"type":"module"}\n');await writeFile3(tempPath,`${moduleSource}
67
+ `);try{const mod=await withTemporaryGlobalReact(()=>importWithTsx(pathToFileURL(tempPath).href));framesNeedingGlobalReact.add(mod);return mod}finally{await rm2(tempDir,{recursive:true,force:true})}}async function importRewrittenFrame(filePath,source){const extension=extname(filePath);const stem=basename(filePath,extension);const tempPath=join3(dirname3(filePath),`.${stem}.vizmatic-${randomUUID()}${extension}`);await writeFile3(tempPath,rewriteFrameModuleImports(source));try{return await importWithTsx(pathToFileURL(tempPath).href)}finally{await rm2(tempPath,{force:true})}}function parseRenderArgs(argv){const inputs=[];let outDir="dist/frames";let themes=["dark","light"];let watermark;let watermarkOptions;let crop=true;let scale;let fps;let background;let format="png";function mutableWatermark(){if(!watermarkOptions){watermarkOptions=typeof watermark==="object"&&watermark!==null&&!isValidElement4(watermark)?{...watermark}:{};if(typeof watermark==="string")watermarkOptions.text=watermark;watermark=watermarkOptions}return watermarkOptions}function readOptionalValue(index){const next=argv[index+1];if(!next||next.startsWith("-"))return void 0;return next}function setWatermarkImageSource(src){const current=mutableWatermark().image;if(current&&typeof current==="object"){current.src=src}else{mutableWatermark().image=src}}function mutableWatermarkImage(){const watermarkConfig=mutableWatermark();if(!watermarkConfig.image||typeof watermarkConfig.image==="string"){watermarkConfig.image={src:watermarkConfig.image??""}}return watermarkConfig.image}for(let index=0;index<argv.length;index+=1){const arg=argv[index];if(!arg)continue;if(arg==="--out"){outDir=argv[++index]??usage()}else if(arg==="--theme"){const raw=argv[++index]??usage();themes=raw.split(",").map(theme=>theme.trim()).filter(Boolean);if(themes.length===0||themes.some(theme=>theme!=="dark"&&theme!=="light"))usage()}else if(arg==="--brand"){const label=readOptionalValue(index);mutableWatermark().text=label??"Vizmatic";if(label)index+=1}else if(arg==="--watermark"){const label=readOptionalValue(index);if(label){mutableWatermark().text=label;index+=1}else{watermark=true;watermarkOptions=void 0}}else if(arg==="--watermark-text"){const rawText=argv[++index]??usage();mutableWatermark().text=rawText==="false"||rawText==="none"?false:rawText}else if(arg==="--watermark-icon"){const rawIcon=argv[++index]??usage();mutableWatermark().icon=rawIcon==="false"||rawIcon==="none"?false:rawIcon}else if(arg==="--watermark-image"){setWatermarkImageSource(argv[++index]??usage())}else if(arg==="--watermark-image-width"){const width=Number(argv[++index]);if(!Number.isFinite(width)||width<=0)usage();mutableWatermarkImage().width=width}else if(arg==="--watermark-image-height"){const height=Number(argv[++index]);if(!Number.isFinite(height)||height<=0)usage();mutableWatermarkImage().height=height}else if(arg==="--watermark-position"){const position=argv[++index];if(!position||!WATERMARK_POSITIONS.has(position))usage();mutableWatermark().position=position}else if(arg==="--no-brand"){watermark=false;watermarkOptions=void 0}else if(arg==="--no-watermark"){watermark=false;watermarkOptions=void 0}else if(arg==="--no-crop"){crop=false}else if(arg==="--transparent"||arg==="--transparent-background"){background="transparent"}else if(arg==="--background"){background=argv[++index]??usage()}else if(arg==="--scale"){const rawScale=Number(argv[++index]);if(!Number.isFinite(rawScale)||rawScale<=0)usage();scale=rawScale}else if(arg==="--fps"){const rawFps=Number(argv[++index]);if(!Number.isInteger(rawFps)||rawFps<1||rawFps>50)usage();fps=rawFps}else if(arg==="--format"){const rawFormat=argv[++index];if(rawFormat!=="png"&&rawFormat!=="svg"&&rawFormat!=="both")usage();format=rawFormat}else if(arg.startsWith("-")){usage()}else{inputs.push(arg)}}if(inputs.length===0)usage();return{inputs,outDir,themes,watermark,crop,scale,fps,background,format}}function parseCheckArgs(argv){const inputs=[];let themes=["dark","light"];let background;let json=false;for(let index=0;index<argv.length;index+=1){const arg=argv[index];if(!arg)continue;if(arg==="--theme"){const raw=argv[++index]??usage();themes=raw.split(",").map(theme=>theme.trim()).filter(Boolean);if(themes.length===0||themes.some(theme=>theme!=="dark"&&theme!=="light"))usage()}else if(arg==="--transparent"||arg==="--transparent-background"){background="transparent"}else if(arg==="--background"){background=argv[++index]??usage()}else if(arg==="--json"){json=true}else if(arg.startsWith("-")){usage()}else{inputs.push(arg)}}if(inputs.length===0)usage();return{inputs,themes,background,json}}async function findFrameFiles(inputs){const files=new Set;async function walk(path){const resolved=resolve(path);const entries=await readdir(resolved,{withFileTypes:true}).catch(()=>void 0);if(!entries){if(RENDER_EXTENSIONS.has(extname(resolved))&&!resolved.endsWith(".d.ts")){files.add(resolved)}return}for(const entry of entries){const next=join3(resolved,entry.name);if(entry.isDirectory()){if(entry.name==="node_modules"||entry.name==="dist"||entry.name.startsWith("_"))continue;await walk(next)}else if(RENDER_EXTENSIONS.has(extname(entry.name))&&!entry.name.endsWith(".d.ts")){files.add(next)}}}for(const input of inputs){await walk(input)}return[...files].sort()}function commonDirectory(paths){let candidate=dirname3(paths[0]??process.cwd());while(!paths.every(path=>{const rel=relative(candidate,path);return rel===""||!rel.startsWith(`..${sep}`)&&rel!==".."&&!isAbsolute(rel)})){const parent=dirname3(candidate);if(parent===candidate)return candidate;candidate=parent}return candidate}function outputStems(files){const basenameCounts=new Map;for(const file of files){const name=basename(file,extname(file));basenameCounts.set(name,(basenameCounts.get(name)??0)+1)}const root=commonDirectory(files);const stems=new Map;const used=new Map;for(const file of files){const base=basename(file,extname(file));const stem=basenameCounts.get(base)===1?base:relative(root,file).slice(0,-extname(file).length).split(sep).join("__");const previous=used.get(stem);if(previous){throw new Error(`output name collision for ${relative(process.cwd(),previous)} and ${relative(process.cwd(),file)}: ${stem}`)}used.set(stem,file);stems.set(file,stem)}return stems}async function importFrame(filePath){installFrameDependencyAliases();const url=pathToFileURL(filePath).href;if(!RENDER_EXTENSIONS.has(extname(filePath)))return await import(url);const source=await readFile2(filePath,"utf8");const isBareFrame=isBareFrameSource(source);const preferBareFrame=isBareFrame&&!/\bexport\s+default\b/.test(source);const needsGlobalReactBinding=!hasReactImportBinding(source)&&containsJsx(source);async function importWithOptionalReactBinding(loader){const mod=needsGlobalReactBinding?await withTemporaryGlobalReact(loader):await loader();if(needsGlobalReactBinding){framesNeedingGlobalReact.add(mod)}return mod}let loadError;const cliRunsFromTypeScript=extname(fileURLToPath2(import.meta.url))===".ts";if(!needsRegisteredTsxLoader()||cliRunsFromTypeScript){try{const mod=await importWithOptionalReactBinding(()=>import(url));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(nativeError){loadError=nativeError}}try{const mod=await importWithOptionalReactBinding(()=>importWithTsx(url));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(tsxError){loadError=tsxError}if(preferBareFrame){const bareFrame=await importBareFrame(filePath,source);if(bareFrame)return bareFrame}try{const mod=await importWithOptionalReactBinding(()=>importRewrittenFrame(filePath,source));if(!isBareFrame||mod.create||mod.default||mod.createScenes||mod.createAnimation)return mod}catch(rewrittenError){if(!isBareFrame)throw rewrittenError}if(!preferBareFrame){const bareFrame=await importBareFrame(filePath,source);if(bareFrame)return bareFrame}throw loadError??new Error(`Unable to load frame ${filePath}`)}function normalizeAutoSize2(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value&&typeof value==="object"){return{width:value.width??defaults.width,height:value.height??defaults.height}}return defaults}function normalizeFrameModule(mod){const defaultObject=typeof mod.default==="object"&&mod.default&&!isValidElement4(mod.default)&&("create"in mod.default||"createAnimation"in mod.default||"default"in mod.default)?mod.default:void 0;const hasAutoSizeSetting=mod.autoSize!=null||mod.__vizmaticAutoSize!=null;const hasWidth=mod.width!=null||defaultObject?.width!=null;const hasHeight=mod.height!=null||defaultObject?.height!=null;const width=mod.width??defaultObject?.width??DEFAULT_FRAME_WIDTH;const height=mod.height??defaultObject?.height??DEFAULT_FRAME_HEIGHT;const autoSize=normalizeAutoSize2(mod.autoSize??mod.__vizmaticAutoSize,{width:!hasWidth||!hasAutoSizeSetting&&width===DEFAULT_FRAME_WIDTH,height:!hasHeight||!hasAutoSizeSetting&&height===DEFAULT_FRAME_HEIGHT});const normalized={...mod,...defaultObject??{},width,height,autoSize};if(framesNeedingGlobalReact.has(mod))framesNeedingGlobalReact.add(normalized);return normalized}function withFrameReactBinding(mod,callback){const needsGlobalReactBinding=framesNeedingGlobalReact.has(mod);return needsGlobalReactBinding?withTemporaryGlobalReactSync(callback):callback()}function frameElement(mod,theme,background){const element=withFrameReactBinding(mod,()=>{if(mod.create)return mod.create(theme);if(mod.default&&!(typeof mod.default==="object"&&"create"in mod.default))return mod.default;throw new Error("frame module must export create(theme) or default React element")});if(!background||mod.__vizmaticRootComponent!=="Board"&&mod.__vizmaticRootComponent!=="Scene"||!isValidElement4(element)||Object.hasOwn(element.props,"background"))return element;return React15.cloneElement(element,{background})}function sourceFrameBackground(mod,theme,requested){const background=requested??mod.__vizmaticBackground;if(background==null)return void 0;if(background==="theme"){if(mod.__vizmaticRootComponent==null&&mod.__vizmaticBackground==null)return"theme";return mergePlaygroundThemeColors(theme,mod.__vizmaticPreset??"default",mod.__vizmaticThemeColors).bg}return background}function overflowEdges2(error){if(error instanceof CanvasOverflowError){return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}const message=error instanceof Error?error.message:String(error);const match=message.match(/Content overflows canvas at: ([^.]+)/);if(!match?.[1])return void 0;const edges=match[1].split(",").map(edge=>edge.trim()).filter(Boolean);if(edges.some(edge=>edge!=="top"&&edge!=="right"&&edge!=="bottom"&&edge!=="left")){return void 0}return edges}function growDimension(value,max){return Math.min(max,Math.ceil(value*AUTO_SIZE_GROWTH/10)*10)}function nextAutoSize2(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?growDimension(width,AUTO_SIZE_MAX_WIDTH):width;const nextHeight=growHeight?growDimension(height,AUTO_SIZE_MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrameToPng(mod,theme,options){let width=options.width;let height=options.height;const{inspectLayout,...renderOptions}=options;const background=sourceFrameBackground(mod,theme,options.background);for(let attempt=0;attempt<AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const recreate=mod.create?nextTheme=>frameElement(mod,nextTheme,background):void 0;const output=await renderToPngWithOutput(frameElement(mod,theme,background),{...renderOptions,background,width,height,onNodeDetected:inspectLayout?node=>layoutNodes.push(node):void 0},recreate,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges2(error);const next=edges?nextAutoSize2(width,height,mod.autoSize,edges):void 0;if(!next||attempt===AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function rasterizeSvgForBounds(svg,width){return new Resvg3(svg,{fitTo:{mode:"width",value:width},background:"rgba(0, 0, 0, 0)"}).render()}function replaceSvgRootAttribute(attributes,name,value){const pattern=new RegExp(`\\s${name}="[^"]*"`);return pattern.test(attributes)?attributes.replace(pattern,` ${name}="${value}"`):`${attributes} ${name}="${value}"`}function cropSvgToRegion(svg,region){const x=Math.max(0,Math.floor(region.x));const y=Math.max(0,Math.floor(region.y));const width=Math.max(1,Math.ceil(region.width));const height=Math.max(1,Math.ceil(region.height));const cropped=svg.replace(/^<svg\b([^>]*)>/,(_match,attributes)=>{let next=replaceSvgRootAttribute(attributes,"width",String(width));next=replaceSvgRootAttribute(next,"height",String(height));next=replaceSvgRootAttribute(next,"viewBox",`${x} ${y} ${width} ${height}`);return`<svg${next}>`});return{svg:cropped,width,height}}function cropSavesEnough2(source,target){return source>target&&(source-target)/source*100>=SVG_CROP_THRESHOLD_PERCENT}async function renderFrameToSvg(mod,theme,options){let width=options.width;let height=options.height;const frameBackground=sourceFrameBackground(mod,theme,options.background);let originalElement=frameElement(mod,theme,frameBackground);let originalSvg="";let initialBounds;for(let attempt=0;attempt<AUTO_SIZE_ATTEMPTS;attempt+=1){originalElement=frameElement(mod,theme,frameBackground);try{originalSvg=await renderToSvg(originalElement,width,height,{background:frameBackground,theme})}catch(error){const edges=overflowEdges2(error);const next=edges?nextAutoSize2(width,height,mod.autoSize,edges):void 0;if(!next||attempt===AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height;continue}const initialRaster=rasterizeSvgForBounds(originalSvg,width);const pixels=new Uint8Array(initialRaster.pixels.buffer);const background=detectBackgroundColor(pixels);const overflow=detectOverflow(pixels,initialRaster.width,initialRaster.height,background);if(overflow.overflows){const edges=Object.entries(overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge);const next=nextAutoSize2(width,height,mod.autoSize,edges);if(!next||attempt===AUTO_SIZE_ATTEMPTS-1){throw new CanvasOverflowError(width,height,overflow)}width=next.width;height=next.height;continue}initialBounds=detectContentBounds(pixels,initialRaster.width,initialRaster.height,background,SVG_AUTOCROP_PADDING);break}if(!initialBounds)throw new Error("unable to measure SVG content bounds");let finalWidth=width;let finalHeight=height;let finalElement=originalElement;let finalSvg=originalSvg;const croppedHeight=initialBounds.y+initialBounds.height;const heightSavedPercent=(height-croppedHeight)/height*100;if(options.crop&&heightSavedPercent>=SVG_CROP_THRESHOLD_PERCENT){finalHeight=croppedHeight;finalElement=mod.create?frameElement(mod,theme,frameBackground):originalElement}const renderFinalSvg=(element,targetWidth,targetHeight)=>renderToSvg(element,targetWidth,targetHeight,{watermark:options.watermark,background:frameBackground,theme});finalSvg=await renderFinalSvg(finalElement,finalWidth,finalHeight);if(finalHeight<height){const cropRaster=rasterizeSvgForBounds(finalSvg,finalWidth);const cropPixels2=new Uint8Array(cropRaster.pixels.buffer);const cropBackground=detectBackgroundColor(cropPixels2);const cropOverflow=detectOverflow(cropPixels2,cropRaster.width,cropRaster.height,cropBackground);if(cropOverflow.overflows){finalHeight=height;finalElement=originalElement;finalSvg=await renderFinalSvg(finalElement,finalWidth,finalHeight)}}if(options.crop){const viewportRaster=rasterizeSvgForBounds(finalSvg,finalWidth);const viewportPixels=new Uint8Array(viewportRaster.pixels.buffer);const viewportBackground=detectBackgroundColor(viewportPixels);const viewportBounds=detectContentBounds(viewportPixels,viewportRaster.width,viewportRaster.height,viewportBackground,SVG_AUTOCROP_PADDING);if(cropSavesEnough2(finalWidth,viewportBounds.width)||cropSavesEnough2(viewportRaster.height,viewportBounds.height)){const cropped=cropSvgToRegion(finalSvg,viewportBounds);finalSvg=cropped.svg;finalWidth=cropped.width;finalHeight=cropped.height}}return{width,height,outputWidth:finalWidth,outputHeight:finalHeight,svg:finalSvg}}async function renderCommand(argv){const args=parseRenderArgs(argv);const cliWatermark=await resolveWatermarkAssets(args.watermark);const files=await findFrameFiles(args.inputs);if(files.length===0)throw new Error("no frame files found");const stems=outputStems(files);await mkdir3(args.outDir,{recursive:true});const manifest=[];for(const file of files){const rawMod=await importFrame(file);const mod=normalizeFrameModule(rawMod);const name=stems.get(file)??basename(file).replace(/\.[^.]+$/,"");const outputs=[];const outputDetails=[];const moduleWatermark=await resolveWatermarkAssets(mod.watermark??mod.brand);let renderWidth=mod.width;let renderHeight=mod.height;let outputWidth=0;let outputHeight=0;for(const theme of args.themes){const inputWidth=renderWidth;const inputHeight=renderHeight;let themeWidth=inputWidth;let themeHeight=inputHeight;if(args.format==="png"||args.format==="both"){const outputName=`${name}_${theme}.png`;const outputPath=join3(args.outDir,outputName);const rendered=await renderFrameToPng(mod,theme,{width:inputWidth,height:inputHeight,outputPath,watermark:cliWatermark??moduleWatermark,crop:args.crop,scale:args.scale,background:args.background});themeWidth=rendered.width;themeHeight=rendered.height;outputWidth=Math.max(outputWidth,rendered.outputWidth);outputHeight=Math.max(outputHeight,rendered.outputHeight);outputs.push(outputName);outputDetails.push({theme,format:"png",path:outputName,width:rendered.outputWidth,height:rendered.outputHeight});console.log(`rendered ${relative(process.cwd(),outputPath)}`)}if(args.format==="svg"||args.format==="both"){const outputName=`${name}_${theme}.svg`;const outputPath=join3(args.outDir,outputName);const rendered=await renderFrameToSvg(mod,theme,{width:inputWidth,height:inputHeight,watermark:cliWatermark??moduleWatermark,crop:args.crop,background:args.background});await writeFile3(outputPath,rendered.svg);themeWidth=rendered.width;themeHeight=rendered.height;outputWidth=Math.max(outputWidth,rendered.outputWidth);outputHeight=Math.max(outputHeight,rendered.outputHeight);outputs.push(outputName);outputDetails.push({theme,format:"svg",path:outputName,width:rendered.outputWidth,height:rendered.outputHeight});console.log(`rendered ${relative(process.cwd(),outputPath)}`)}renderWidth=themeWidth;renderHeight=themeHeight}manifest.push({name,source:relative(process.cwd(),file),width:renderWidth,height:renderHeight,outputWidth,outputHeight,outputs,outputDetails})}await writeFile3(join3(args.outDir,"manifest.json"),`${JSON.stringify(manifest,null,2)}
61
68
  `)}function formatConsoleArgs2(args){return args.map(value=>{if(value instanceof Error)return value.message;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}).join(" ")}async function captureConsole2(run){const messages=[];const original={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};console.debug=()=>void 0;console.log=()=>void 0;console.info=()=>void 0;console.warn=(...args)=>messages.push({severity:"warning",message:formatConsoleArgs2(args)});console.error=(...args)=>messages.push({severity:"error",message:formatConsoleArgs2(args)});try{return{value:await run(),messages}}catch(error){return{error,messages}}finally{console.debug=original.debug;console.error=original.error;console.info=original.info;console.log=original.log;console.warn=original.warn}}function suppressConsoleOutput(){const original={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};console.debug=()=>void 0;console.error=()=>void 0;console.info=()=>void 0;console.log=()=>void 0;console.warn=()=>void 0;return()=>{console.debug=original.debug;console.error=original.error;console.info=original.info;console.log=original.log;console.warn=original.warn}}function checkDiagnosticCounts(files){const diagnostics=files.flatMap(file=>[...file.diagnostics,...file.themes.flatMap(theme=>theme.diagnostics)]);return{errors:diagnostics.filter(diagnostic=>diagnostic.severity==="error").length,warnings:diagnostics.filter(diagnostic=>diagnostic.severity==="warning").length,info:diagnostics.filter(diagnostic=>diagnostic.severity==="info").length}}function printCheckReport(files){for(const file of files){console.log(`${file.ok?"ok":"error"} ${file.source}`);for(const theme of file.themes){const resolved=theme.dimensions.resolved??theme.dimensions.input;const output=theme.dimensions.output;const outputLabel=output?` -> ${output.width}\xD7${output.height}`:"";console.log(` ${theme.ok?"ok":"error"} ${theme.theme} ${resolved.width}\xD7${resolved.height}${outputLabel}`);for(const diagnostic of theme.diagnostics){console.log(` ${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}`);if(diagnostic.suggestion)console.log(` ${diagnostic.suggestion}`)}}for(const diagnostic of file.diagnostics){console.log(` ${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}`)}}}async function checkCommand(argv){const args=parseCheckArgs(argv);const restoreConsole=args.json?suppressConsoleOutput():void 0;try{await checkCommandWithArgs(args)}catch(error){restoreConsole?.();throw error}}async function checkCommandWithArgs(args){const files=await findFrameFiles(args.inputs);if(files.length===0)throw new Error("no frame files found");const reports=[];for(const file of files){const source=relative(process.cwd(),file);const imported=await captureConsole2(()=>importFrame(file));const diagnostics=imported.messages.map(message=>diagnosticFromMessage(message.message,message.severity));if(!imported.value){diagnostics.push({code:"frame.load_error",severity:"error",message:imported.error instanceof Error?imported.error.message:String(imported.error)});reports.push({source,ok:false,diagnostics,themes:[]});continue}const mod=normalizeFrameModule(imported.value);const checked=await checkFrame({source,width:mod.width,height:mod.height,autoSize:mod.autoSize,create:theme=>frameElement(mod,theme)},{themes:args.themes,background:args.background,failOn:"error"});const ok=!diagnostics.some(diagnostic=>diagnostic.severity==="error")&&checked.themes.every(theme=>theme.ok);reports.push({source,ok,autoSize:mod.autoSize,diagnostics,themes:checked.themes})}const summary=checkDiagnosticCounts(reports);const report={schemaVersion:1,command:"check",ok:summary.errors===0,files:reports,summary:{files:reports.length,...summary}};if(args.json){process.stdout.write(`${JSON.stringify(report,null,2)}
62
69
  `)}else{printCheckReport(reports);console.log(`checked ${report.summary.files} file(s): ${summary.errors} error(s), ${summary.warnings} warning(s), ${summary.info} info`)}if(!report.ok)process.exitCode=1}async function gifCommand(argv){const args=parseRenderArgs(argv);if(args.format!=="png"){throw new Error("--format applies to static rendering only; gif always writes GIF output")}const cliWatermark=await resolveWatermarkAssets(args.watermark);const files=await findFrameFiles(args.inputs);if(files.length===0)throw new Error("no frame files found");const stems=outputStems(files);await mkdir3(args.outDir,{recursive:true});const manifest=[];for(const file of files){const rawMod=await importFrame(file);const mod=normalizeFrameModule(rawMod);const name=stems.get(file)??basename(file).replace(/\.[^.]+$/,"");const outputs=[];const outputDetails=[];const moduleWatermark=await resolveWatermarkAssets(mod.watermark??mod.brand);const outputScale=args.scale??1;if(!mod.createAnimation&&!mod.createScenes){throw new Error(`${relative(process.cwd(),file)} must export createAnimation(theme) or createScenes(theme) for GIF rendering`)}for(const theme of args.themes){const outputName=`${name}_${theme}.gif`;const outputPath=join3(args.outDir,outputName);const commonOptions={width:mod.width,height:mod.height,outputPath,watermark:cliWatermark??moduleWatermark,scale:outputScale,theme,background:args.background,fps:args.fps};const rendered=mod.createAnimation?await renderAnimationGifWithOutput(withFrameReactBinding(mod,()=>mod.createAnimation(theme)),commonOptions):await renderAnimatedGifWithOutput(withFrameReactBinding(mod,()=>mod.createScenes(theme)),commonOptions);outputs.push(outputName);outputDetails.push({theme,path:outputName,width:rendered.width,height:rendered.height,frameCount:rendered.frameCount,encodedFrameCount:rendered.encodedFrameCount,deltaFrameCount:rendered.deltaFrameCount,duration:rendered.duration,bytes:rendered.bytes});console.log(`rendered ${relative(process.cwd(),outputPath)}`)}manifest.push({name,source:relative(process.cwd(),file),width:mod.width,height:mod.height,outputs,outputDetails})}await writeFile3(join3(args.outDir,"gif-manifest.json"),`${JSON.stringify(manifest,null,2)}
63
70
  `)}async function main(){const args=process.argv.slice(2);const[command,...rest]=args;if(command==="render"){await renderCommand(rest)}else if(command==="check"){await checkCommand(rest)}else if(command==="gif"){await gifCommand(rest)}else if(!command||command==="help"||command==="--help"||command==="-h"){help()}else if(!command.startsWith("-")){await renderCommand(args)}else{usage()}}main().catch(error=>{if(process.env.VIZMATIC_DEBUG==="1"&&error instanceof Error){console.error(error.stack??error.message)}else{console.error(error instanceof Error?error.message:String(error))}process.exit(1)});