vizmatic 0.7.0 → 0.7.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/ROADMAP.md +2 -2
- package/dist/chunk-3LQLKLGH.js +79 -0
- package/dist/{chunk-CJOXWJQA.js → chunk-DTD35LPT.js} +36 -4
- package/dist/{chunk-4XE64I2U.js → chunk-DZHX76RS.js} +8 -1
- package/dist/cli.js +1 -1
- package/dist/index.cjs +1298 -730
- package/dist/index.d.cts +128 -65
- package/dist/index.d.ts +128 -65
- package/dist/index.js +869 -339
- package/dist/scene-browser.js +18 -18
- package/dist/scene-cli.js +1 -1
- package/dist/scene-runtime.cjs +8 -1
- package/dist/scene-runtime.d.cts +1 -1
- package/dist/scene-runtime.d.ts +1 -1
- package/dist/scene-runtime.js +1 -1
- package/dist/stage-export.cjs +20 -4
- package/dist/stage-export.js +1 -1
- package/examples/README.md +1 -0
- package/examples/entity-relationship.tsx +50 -0
- package/package.json +1 -1
- package/dist/chunk-MAHT32CE.js +0 -79
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Arrow,ArrowMarkerDef,AttentionMatrix,AxisPlot,Badge,BadgePill,BarChart,Board,Box,CANVAS_ITEM_COMPONENT,CalloutCard,Canvas,CanvasItem,CanvasOverflowError,Card,ChartFrame,CodeBlock,Column,Comparison,Connector,DEFAULT_DENSITY,DENSITY_NAMES,DashedLine,DataTable,DataflowDiagram,DeploymentDiagram,DetailList,DiagramLegend,DonutChart,DotPoint,ELEMENT_SYMBOLS,EquationCard,FactRows,Flow,FlowArrow,FreeBodyDiagram,GeometryDiagram,GradientChip,GraphDiagram,Grid,Heatmap,Icon,InlineBar,IntervalPlot,KeyValueList,LayeredNetwork,Legend,LineChart,MathText,Matrix,MetricCard,MetricStrip,MiniBarChart,MoleculeDiagram,NumberLine,Panel,ParetoBarChart,ParetoChart,PieChart,Pipeline,PixelGrid,ProgressList,ProgressRow,QuadrantChart,ReactionEnergyDiagram,ReactionEquation,Row,SCENE_LIMITS,SCENE_RUNTIME_VERSION,ScatterPlot,Scene,SequenceDiagram,SmallMultiples,Sparkline,Stack,StackedBar,StatusDot,StatusList,StatusRow,StepCard,SvgFrame,SvgMathText,SvgPoint,TagList,TextLabel,Tile,TileGrid,TiledMatrix,Timeline,TitleBar,ToneStrip,TransformerTopology,TreeDiagram,ValuePill,VectorArrow,VectorSegment,Watermark,WaveDiagram,WindowFrame,analyzeAnimationCadence,assertDensity,canvas,colors,compositeColor,createPlotArea,cropPixels,cropRgbImage,cropRgbRaster,crossCorrelate2d,decodeRgbPng,defineAnimation,defineDiagramIcon,defineIconRegistry,defineIllustration,densityOf,densityTokens,detectBackgroundColor,detectContentBounds,detectLayoutOverflow,detectOverflow,dotProduct,encodePng,encodeRgbPng,entropy,estimateTextWidth,evaluateSceneSource,extractRootJsx,findBareRootJsxStart,flattenRgbImage,formatMathText,formatTensorShape,gaussian,gaussianBlurRgb,gaussianKernel,geometryBounds,getColor,getFonts,getGradient,getReadableColor,getReadableTextColor,getReadableToneColor,getStyles,getThemeColors,getToneColor,getToneFill,getToneGradient,gradients,hasShadow,heatColor,hold,keyframe,lerpArray,loadAdditionalAsset,mapNumberLine,multiplyMatrices,normalizeVector,normalizeWatermark,parallel,parseDensity,pointAlongSamples,prepareScene,primitives_exports,reactionBalance,renderAnimationVideo,renderRgbaVideo,renderSceneFrame,renderSceneVideo,renderToBuffer,renderToPng,renderToPngWithOutput,renderToSvg,rgbChannel,routeOrthogonalGraph,routingSegmentBlocked,sampleAnimation,sampleAnimationFrame,sampleAnimationFrames,sampleFunction,sampleGaussian,sampleWave,satori,scaledDotProductAttention,scopeDensity,seededRandom,setDefaultDensity,setDensityResolver,stableSoftmax,statusColor,styles,sumForces,toneGradients,transposeMatrix,tween,typeOf,typography,videoFrameSchedule,waveValue,withColorAlpha,withDensity,withRenderContext,wrapWithBrand,wrapWithWatermark}from"./chunk-MAHT32CE.js";import{renderMathSvg}from"./chunk-3F2VQ7NW.js";import{__export}from"./chunk-PSBF4TEK.js";import{existsSync as existsSync2}from"fs";import{mkdir as mkdir4,mkdtemp as mkdtemp2,readFile,readdir,rm as rm2,writeFile as writeFile4}from"fs/promises";import{randomUUID}from"crypto";import{createRequire as createRequire2,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename as basename2,dirname as dirname4,extname as extname2,isAbsolute,join as join3,relative as relative2,resolve as resolve3,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React,{isValidElement as isValidElement2}from"react";import{Resvg as Resvg2}from"@resvg/resvg-js";var index_exports={};__export(index_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AttentionMatrix:()=>AttentionMatrix,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,DEFAULT_DENSITY:()=>DEFAULT_DENSITY,DENSITY_NAMES:()=>DENSITY_NAMES,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DiagramLegend:()=>DiagramLegend,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,ELEMENT_SYMBOLS:()=>ELEMENT_SYMBOLS,EquationCard:()=>EquationCard,FactRows:()=>FactRows,Flow:()=>Flow,FlowArrow:()=>FlowArrow,FreeBodyDiagram:()=>FreeBodyDiagram,GeometryDiagram:()=>GeometryDiagram,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,InlineBar:()=>InlineBar,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MetricStrip:()=>MetricStrip,MiniBarChart:()=>MiniBarChart,MoleculeDiagram:()=>MoleculeDiagram,NumberLine:()=>NumberLine,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,PixelGrid:()=>PixelGrid,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,ReactionEnergyDiagram:()=>ReactionEnergyDiagram,ReactionEquation:()=>ReactionEquation,Row:()=>Row,SCENE_LIMITS:()=>SCENE_LIMITS,SCENE_RUNTIME_VERSION:()=>SCENE_RUNTIME_VERSION,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,SmallMultiples:()=>SmallMultiples,Sparkline:()=>Sparkline,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusDot:()=>StatusDot,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TagList:()=>TagList,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,WaveDiagram:()=>WaveDiagram,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,arcSwap:()=>arcSwap,assertDensity:()=>assertDensity,assertTokenHistoryTransition:()=>assertTokenHistoryTransition,byteDifferenceState:()=>byteDifferenceState,cameraSvgTransform:()=>cameraSvgTransform,canvas:()=>canvas,categoricalSampling:()=>categoricalSampling,checkFrame:()=>checkFrame,colors:()=>colors,compareByteSequences:()=>compareByteSequences,compositeColor:()=>compositeColor,createCanvasComponents:()=>createCanvasComponents,createCueTrack:()=>createCueTrack,createFocusDirector:()=>createFocusDirector,createPlotArea:()=>createPlotArea,createPolylineMorph:()=>createPolylineMorph,createTeachingByteDifference:()=>createTeachingByteDifference,createTeachingCanvas:()=>createTeachingCanvas,createTeachingCategoricalSampling:()=>createTeachingCategoricalSampling,createTeachingFocus:()=>createTeachingFocus,createTeachingRoutedTransfer:()=>createTeachingRoutedTransfer,createTeachingTokenHistory:()=>createTeachingTokenHistory,createTeachingValueChange:()=>createTeachingValueChange,createTeachingVectorAccumulation:()=>createTeachingVectorAccumulation,cropPixels:()=>cropPixels,cropRgbImage:()=>cropRgbImage,cropRgbRaster:()=>cropRgbRaster,crossCorrelate2d:()=>crossCorrelate2d,decodeRgbPng:()=>decodeRgbPng,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,densityOf:()=>densityOf,densityTokens:()=>densityTokens,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectLayoutOverflow:()=>detectLayoutOverflow,detectOverflow:()=>detectOverflow,dotProduct:()=>dotProduct,encodeRgbPng:()=>encodeRgbPng,entropy:()=>entropy,escapedByte:()=>escapedByte,estimateTextWidth:()=>estimateTextWidth,evaluateSceneSource:()=>evaluateSceneSource,flattenRgbImage:()=>flattenRgbImage,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,gaussian:()=>gaussian,gaussianBlurRgb:()=>gaussianBlurRgb,gaussianKernel:()=>gaussianKernel,geometryBounds:()=>geometryBounds,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,hasShadow:()=>hasShadow,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,interpolateCamera:()=>interpolateCamera,keyframe:()=>keyframe,layoutAllocation:()=>layoutAllocation,layoutByteDifference:()=>layoutByteDifference,layoutCellGrid:()=>layoutCellGrid,layoutTokenRow:()=>layoutTokenRow,lerpArray:()=>lerpArray,loadAdditionalAsset:()=>loadAdditionalAsset,mapNumberLine:()=>mapNumberLine,mergeFocusRegions:()=>mergeFocusRegions,morphPolyline:()=>morphPolyline,multiplyMatrices:()=>multiplyMatrices,normalizeVector:()=>normalizeVector,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,parseDensity:()=>parseDensity,planTeachingRoutedTransfer:()=>planTeachingRoutedTransfer,pointAlongPath:()=>pointAlongPath,prepareScene:()=>prepareScene,projectWorldPoint:()=>projectWorldPoint,reactionBalance:()=>reactionBalance,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderAnimationVideo:()=>renderAnimationVideo,renderMathSvg:()=>renderMathSvg,renderRgbaVideo:()=>renderRgbaVideo,renderSceneFrame:()=>renderSceneFrame,renderSceneVideo:()=>renderSceneVideo,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,rgbChannel:()=>rgbChannel,sampleAnimation:()=>sampleAnimation,sampleAnimationFrame:()=>sampleAnimationFrame,sampleAnimationFrames:()=>sampleAnimationFrames,sampleFunction:()=>sampleFunction,sampleGaussian:()=>sampleGaussian,sampleWave:()=>sampleWave,scaledDotProductAttention:()=>scaledDotProductAttention,scopeDensity:()=>scopeDensity,seededRandom:()=>seededRandom,setDefaultDensity:()=>setDefaultDensity,setDensityResolver:()=>setDensityResolver,smoothstep:()=>smoothstep,stableSoftmax:()=>stableSoftmax,statusColor:()=>statusColor,styles:()=>styles,sumForces:()=>sumForces,tokenHistoryState:()=>tokenHistoryState,toneGradients:()=>toneGradients,tracePolyline:()=>tracePolyline,transposeMatrix:()=>transposeMatrix,tween:()=>tween,typeOf:()=>typeOf,typography:()=>typography,valueChangeState:()=>valueChangeState,videoFrameSchedule:()=>videoFrameSchedule,waveValue:()=>waveValue,weightedVectorState:()=>weightedVectorState,withColorAlpha:()=>withColorAlpha,withDensity:()=>withDensity,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import{Resvg}from"@resvg/resvg-js";import{mkdir,writeFile}from"fs/promises";import{dirname}from"path";import*as gifenc from"gifenc";import parseCssColor from"parse-css-color";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 fonts2=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts:fonts2,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg(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=detectLayoutOverflow2(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow2(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=parseCssColor(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 bounds4=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds4||bounds4.width===frame.width&&bounds4.height===frame.height)return frame;return{...frame,x:bounds4.x,y:bounds4.y,delta:true,width:bounds4.width,height:bounds4.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds4)}}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 pending2;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(pending2&&pixelsEqual(pending2.pixels,frame.pixels)){pending2.delay+=frame.delay;continue}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending2={...frame}}if(pending2){const encoded=deltaPixelFrame(pending2,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 delay2=(cumulative-previous)*10;previous=cumulative;return delay2})}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 amount2=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount2):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount2);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 mkdir(dirname(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 writeFile(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 delay2=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay2),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-=delay2}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 pending2;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(pending2&&pixelsEqual(pending2.pixels,rendered.pixels)){pending2.delay+=sampled.frame.delay;continue}if(pending2){const encoded2=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending2={...rendered,delay:sampled.frame.delay}}if(!pending2||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir(dirname(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}var DEFAULT_ARC_LIFT=80;function assertFiniteProgress(progress){if(!Number.isFinite(progress))throw new Error("Motion progress must be finite")}function clampProgress(progress){assertFiniteProgress(progress);return Math.max(0,Math.min(1,progress))}function assertPoint(point,context){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} coordinates must be finite`)}}function interpolate(from,to2,progress){return{x:from.x*(1-progress)+to2.x*progress,y:from.y*(1-progress)+to2.y*progress}}function smoothstep(progress){const amount2=clampProgress(progress);return amount2*amount2*(3-2*amount2)}function arcSwap(from,to2,progress,options={}){assertPoint(from,"Arc swap start");assertPoint(to2,"Arc swap end");const amount2=clampProgress(progress);const lift=options.lift??DEFAULT_ARC_LIFT;if(!Number.isFinite(lift))throw new Error("Arc swap lift must be finite");if(amount2===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(amount2===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Motion easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(t===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const dx=to2.x-from.x;const dy=to2.y-from.y;const length=Math.hypot(dx,dy);if(!Number.isFinite(length))throw new Error("Arc swap distance must be finite");if(length===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];const normalX=-dy/length;const normalY=dx/length;const arcHeight=4*(1-t)*t*lift;const firstBase=interpolate(from,to2,t);const secondBase=interpolate(to2,from,t);const first={x:firstBase.x+normalX*arcHeight,y:firstBase.y+normalY*arcHeight};const second={x:secondBase.x-normalX*arcHeight,y:secondBase.y-normalY*arcHeight};assertPoint(first,"Arc swap result");assertPoint(second,"Arc swap result");return[first,second]}function pathLengths(points){const lengths=[];let total=0;for(let index=0;index<points.length;index+=1){const point=points[index];assertPoint(point,`Path point ${index}`);if(index===0)continue;const previous=points[index-1];const length=Math.hypot(point.x-previous.x,point.y-previous.y);if(!Number.isFinite(length))throw new Error("Path segment length must be finite");total+=length;if(!Number.isFinite(total))throw new Error("Path length must be finite");lengths.push(length)}return lengths}function tracePolyline(points,progress){const amount2=clampProgress(progress);if(points.length===0)return[];const lengths=pathLengths(points);if(amount2===1)return points.map(({x,y})=>({x,y}));const traced2=[{x:points[0].x,y:points[0].y}];if(amount2===0||lengths.length===0)return traced2;const total=lengths.reduce((sum,length)=>sum+length,0);if(total===0)return traced2;const target=total*amount2;let travelled=0;for(let index=0;index<lengths.length;index+=1){const segmentLength=lengths[index];const next=points[index+1];if(segmentLength===0)continue;const segmentEnd=travelled+segmentLength;if(target>=segmentEnd){traced2.push({x:next.x,y:next.y});travelled=segmentEnd;continue}const segmentProgress=(target-travelled)/segmentLength;const point=interpolate(points[index],next,segmentProgress);assertPoint(point,"Polyline trace result");const previous=traced2[traced2.length-1];if(point.x!==previous.x||point.y!==previous.y)traced2.push(point);return traced2}return traced2}function pointAlongPath(points,progress){if(points.length===0)throw new Error("Cannot find a point along an empty path");const traced2=tracePolyline(points,progress);return{...traced2[traced2.length-1]}}function finite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative(value,name){finite(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function positive(value,name){finite(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function normalizedOpacity(value,name="Canvas opacity"){finite(value,name);return Math.max(0,Math.min(1,value))}function validateBounds(bounds4){finite(bounds4.x,"Canvas x");finite(bounds4.y,"Canvas y");positive(bounds4.width,"Canvas width");positive(bounds4.height,"Canvas height");nonnegative(bounds4.radius??14,"Canvas radius")}function layoutTokenRow(values,options={}){const{advance=24,gap=16,minWidth=64,paddingX=17,width}=options;nonnegative(advance,"Token advance");nonnegative(gap,"Token gap");positive(minWidth,"Token minimum width");nonnegative(paddingX,"Token horizontal padding");if(width!==void 0)positive(width,"Token width");if(options.x!==void 0)finite(options.x,"Token x");if(options.centerX!==void 0)finite(options.centerX,"Token center x");const items=values.map(value=>{const text2=String(value);return{text:text2,x:0,width:width??Math.max(minWidth,text2.length*advance+2*paddingX)}});const totalWidth=items.reduce((total,item)=>total+item.width,0)+Math.max(0,items.length-1)*gap;let x=options.x??(options.centerX??0)-totalWidth/2;finite(x,"Token row origin");for(const item of items){item.x=x;x+=item.width+gap;finite(x,"Token row extent")}return items}function createCanvasComponents(painter){function fade2(alpha3,draw2){const amount2=normalizedOpacity(alpha3);if(amount2>0)painter.opacity(amount2,draw2)}function panel(options,draw2){validateBounds(options);const{x,y,width,height,fill,stroke,radius=14,padding=10,id,scope="container",opacity=1}=options;nonnegative(padding,"Canvas padding");const alpha3=normalizedOpacity(opacity);if(scope!=="container"&&scope!=="label")throw new Error("Canvas scope must be container or label");let shape2;const paint=()=>painter.opacity(alpha3,()=>{shape2=painter.rect(x,y,width,height,fill,stroke,radius);if(draw2){const bounds4={x,y,width,height,radius};const scopeOptions={padding,id};if(scope==="label")painter.labelScope(bounds4,draw2,scopeOptions);else painter.container(bounds4,draw2,scopeOptions)}});if(options.focusTarget&&painter.target)painter.target(options.focusTarget,paint);else paint();return shape2}function card(options){const{label,x,y,width,height,fontSize=32,font="sans",textColor,baselineOffset=fontSize*.34,labelOpacity=1}=options;positive(fontSize,"Canvas font size");finite(baselineOffset,"Canvas text baseline offset");const labelAlpha=normalizedOpacity(labelOpacity,"Canvas label opacity");return panel(options,()=>{fade2(labelAlpha,()=>{painter.text(String(label),x+width/2,y+height/2+baselineOffset,fontSize,textColor,"center",font)})})}function matrix2(options){const{values,x,y,cellSize=112,gap=8,inset:inset2=0,format=String,style={},cellStyle}=options;finite(x,"Matrix x");finite(y,"Matrix y");positive(cellSize,"Matrix cell size");nonnegative(gap,"Matrix gap");finite(inset2,"Matrix inset");if(gap>=cellSize)throw new Error("Matrix gap must be smaller than cell size");const columns=values[0]?.length??0;for(const row of values){if(!Array.isArray(row)||row.length!==columns)throw new Error("Canvas matrix rows must be rectangular")}const shapes=[];for(let row=0;row<values.length;row+=1){for(let column=0;column<columns;column+=1){const value=values[row][column];const cell={...style,...cellStyle?.(value,row,column)};finite(cell.opacity??1,"Canvas opacity");if((cell.opacity??1)<=0)continue;const shape2=card({...cell,x:x+column*cellSize+inset2,y:y+row*cellSize+inset2,width:cellSize-gap,height:cellSize-gap,label:format(value,row,column)});shapes.push(shape2)}}return shapes}function tokenRow(options){const{values,y,height=68,reveal:reveal2=1,opacity=1,...style}=options;finite(y,"Token row y");positive(height,"Token height");finite(reveal2,"Token reveal");const alpha3=normalizedOpacity(opacity);const items=layoutTokenRow(values,options);const shapes=[];for(let index=0;index<items.length;index+=1){const amount2=Math.max(0,Math.min(1,reveal2*items.length-index))*alpha3;if(amount2<=0)continue;const{text:label,x,width}=items[index];const shape2=card({...style,label,x,y,width,height,opacity:amount2});shapes.push(shape2)}return shapes}function particle(options){const{points,progress,radius=9,fill,stroke,strokeWidth=3}=options;finite(progress,"Particle progress");positive(radius,"Particle radius");nonnegative(strokeWidth,"Particle stroke width");if(progress<=0||progress>=1)return null;const point=pointAlongPath(points,progress);painter.circle(point.x,point.y,radius,fill,stroke,strokeWidth);return point}return{panel,card,matrix:matrix2,tokenRow,particle,fade:fade2}}function nonnegative2(value,name){if(!Number.isFinite(value)||value<0)throw new Error(`${name} must be finite and nonnegative`)}function alpha(value){if(!Number.isFinite(value))throw new Error("Transfer opacity must be finite");return Math.max(0,Math.min(1,value))}function bounds(shape2){if(![shape2.x,shape2.y,shape2.width,shape2.height].every(Number.isFinite)||shape2.width<=0||shape2.height<=0){throw new Error("Transfer endpoints require finite positive rectangular bounds")}nonnegative2(shape2.radius??0,"Transfer corner radius")}function center(shape2){return{x:shape2.x+shape2.width/2,y:shape2.y+shape2.height/2}}function edgeDistance(shape2,ux,uy){const halfWidth=shape2.width/2,halfHeight=shape2.height/2;const limit=Math.min(ux===0?Infinity:halfWidth/Math.abs(ux),uy===0?Infinity:halfHeight/Math.abs(uy));const radius=Math.min(shape2.radius??0,halfWidth,halfHeight);if(radius===0)return limit;const outside=distance=>Math.hypot(Math.max(0,Math.abs(ux*distance)-(halfWidth-radius)),Math.max(0,Math.abs(uy*distance)-(halfHeight-radius)))>radius;if(!outside(limit))return limit;let low=0,high=limit;for(let index=0;index<32;index+=1){const middle=(low+high)/2;if(outside(middle))high=middle;else low=middle}return low}function safeGap(shape2,ux,uy,clearance,edge){const expanded2=Math.min(ux===0?Infinity:(shape2.width/2+clearance)/Math.abs(ux),uy===0?Infinity:(shape2.height/2+clearance)/Math.abs(uy));return expanded2-edge}function createTeachingTransfer(painter){return options=>{const{source,target,color="#63DEEC",width=3,margin=2,progress,particle}=options;bounds(source.shape);bounds(target.shape);nonnegative2(width,"Transfer stroke width");if(width===0)throw new Error("Transfer stroke width must be positive");nonnegative2(margin,"Transfer margin");const opacity=Math.min(alpha(source.opacity),alpha(target.opacity),alpha(options.opacity??1));for(const gap of[options.gap,options.fromGap,options.toGap]){if(gap!==void 0)nonnegative2(gap,"Transfer gap")}if(progress!==void 0&&!Number.isFinite(progress))throw new Error("Transfer progress must be finite");if(particle&&progress===void 0)throw new Error("Transfer particle requires progress");const radius=particle?.radius??7,strokeWidth=particle?.strokeWidth??3;nonnegative2(radius,"Transfer particle radius");if(radius===0)throw new Error("Transfer particle radius must be positive");nonnegative2(strokeWidth,"Transfer particle stroke width");if(opacity===0)return null;const a=center(source.shape),z=center(target.shape);const distance=Math.hypot(z.x-a.x,z.y-a.y);if(!Number.isFinite(distance)||distance===0)throw new Error("Transfer endpoints must have distinct finite centers");const ux=(z.x-a.x)/distance,uy=(z.y-a.y)/distance;const sourceEdge=edgeDistance(source.shape,ux,uy),targetEdge=edgeDistance(target.shape,ux,uy);const markerRadius=progress===void 0?0:radius+(particle?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerRadius)+margin;const fromGap=Math.max(options.fromGap??options.gap??0,safeGap(source.shape,ux,uy,clearance,sourceEdge));const toGap=Math.max(options.toGap??options.gap??0,safeGap(target.shape,ux,uy,clearance,targetEdge));if(distance<=sourceEdge+targetEdge+fromGap+toGap)throw new Error("Transfer endpoints leave no room for the requested clearance");let route;painter.opacity(opacity,()=>{route=painter.connect(source.shape,target.shape,{color,width,fromGap,toGap});if(progress!==void 0&&progress>0&&progress<1){const x=route.from.x*(1-progress)+route.to.x*progress;const y=route.from.y*(1-progress)+route.to.y*progress;painter.circle(x,y,radius,particle?.fill??color,particle?.stroke,strokeWidth)}});return route}}function positive2(value,name){if(!Number.isFinite(value)||value<=0)throw new Error(`${name} must be finite and positive`)}function layoutCellGrid(options){const{x,y,width,height,rows,columns}=options;if(![x,y,x+width,y+height].every(Number.isFinite))throw new Error("Grid bounds must be finite");positive2(width,"Grid width");positive2(height,"Grid height");if(![rows,columns,rows*columns].every(Number.isSafeInteger)||rows<=0||columns<=0){throw new Error("Grid rows and columns must be positive safe integers")}const bounds4={x,y,width,height};const cells=Array.from({length:rows},(_,row)=>Array.from({length:columns},(_2,column)=>({x:x+column*width/columns,y:y+row*height/rows,width:width/columns,height:height/rows})));return{bounds:bounds4,cells,cell(row,column){if(!Number.isSafeInteger(row)||!Number.isSafeInteger(column)||row<0||row>=rows||column<0||column>=columns){throw new Error("Grid cell index is outside the grid")}return cells[row][column]}}}function createTeachingGrid(painter){const components=createCanvasComponents(painter);return options=>{const layout=layoutCellGrid(options);const{x,y,width,height,rows,columns,fill="#18283B",stroke="#63DEEC",lineWidth=1,labels,highlights=[],fontSize=28,textColor="#FFFFFF",padding=4}=options;positive2(lineWidth,"Grid line width");if(lineWidth>=Math.min(width/columns,height/rows))throw new Error("Grid line width must be smaller than a cell");positive2(fontSize,"Grid font size");if(!Number.isFinite(padding)||padding<0)throw new Error("Grid padding must be finite and nonnegative");if(labels&&(labels.length!==rows||labels.some(row=>row.length!==columns))){throw new Error("Grid labels must match rows and columns")}for(const highlight of highlights){layout.cell(highlight.row,highlight.column);if(!Number.isFinite(highlight.opacity??1))throw new Error("Grid highlight opacity must be finite")}const cellFocusTarget=painter.target?options.cellFocusTarget:void 0;const shape2=components.panel({...layout.bounds,fill:cellFocusTarget?"transparent":fill,stroke,radius:0,padding:0},()=>{const drawLabel=(r,column)=>{if(!labels)return;const cell=layout.cell(r,column),value=String(labels[r][column]);const baseline=cell.y+cell.height/2+fontSize*.34-(value.split("\n").length-1)*fontSize*.7;painter.labelScope(cell,()=>painter.text(value,cell.x+cell.width/2,baseline,fontSize,textColor,"center"),{padding})};if(cellFocusTarget)for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){const named=cellFocusTarget(row,column),ids=typeof named==="string"?[named]:named??[];const draw2=()=>{const cell=layout.cell(row,column),inset3=lineWidth/2;painter.rect(cell.x+inset3,cell.y+inset3,cell.width-lineWidth,cell.height-lineWidth,fill,void 0,0);for(const highlight of highlights.filter(item=>item.row===row&&item.column===column)){const pad2=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>painter.rect(cell.x+pad2,cell.y+pad2,cell.width-pad2*2,cell.height-pad2*2,highlight.fill,highlight.stroke,0))}drawLabel(row,column)};const scoped=index=>{if(index<ids.length&&painter.target)painter.target(ids[index],()=>scoped(index+1));else draw2()};scoped(0)}for(const highlight of cellFocusTarget?[]:highlights){const cell=layout.cell(highlight.row,highlight.column);const inset3=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>{painter.rect(cell.x+inset3,cell.y+inset3,cell.width-2*inset3,cell.height-2*inset3,highlight.fill,highlight.stroke,0)})}const inset2=lineWidth/2;for(let column=1;column<columns;column+=1){const left=x+column*width/columns;painter.path([{x:left,y:y+inset2},{x:left,y:y+height-inset2}],{color:stroke,width:lineWidth})}for(let row=1;row<rows;row+=1){const top=y+row*height/rows;painter.path([{x:x+inset2,y:top},{x:x+width-inset2,y:top}],{color:stroke,width:lineWidth})}if(!cellFocusTarget)labels?.forEach((row,r)=>row.forEach((_,column)=>drawLabel(r,column)))});return{...layout,shape:shape2}}}function createTeachingTimeline(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,domain:[lo,hi],lanes,intervals,time=hi,ticks:ticks2=[lo,hi],formatTime=String,labelWidth=180,laneGap=18,fontSize=28,color="#8D9CB9",trackColor="#18283B",cursorColor="#FFCE73"}=options;if(![x,y,x+width,y+height,lo,hi,hi-lo,time,labelWidth,laneGap,fontSize].every(Number.isFinite))throw new Error("Timeline values must be finite");if(width<=0||height<=0||hi<=lo||time<lo||time>hi)throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");if(fontSize<=0||labelWidth<=12||labelWidth>=width-6||laneGap<0||!lanes.length)throw new Error("Timeline needs positive label space, font size, and at least one lane");const ids=new Set(lanes.map(lane=>lane.id));if(ids.size!==lanes.length||lanes.some(lane=>!lane.id))throw new Error("Timeline lane IDs must be nonempty and unique");const intervalIds=new Set;for(const interval of intervals){if(!interval.id||intervalIds.has(interval.id)||!ids.has(interval.lane))throw new Error("Timeline intervals need unique IDs and an existing lane");intervalIds.add(interval.id);if(![interval.start,interval.end,interval.opacity??1].every(Number.isFinite)||interval.start<lo||interval.end>hi||interval.end<=interval.start)throw new Error("Timeline intervals must have finite positive durations inside the domain")}for(const lane of lanes){const ordered=intervals.filter(interval=>interval.lane===lane.id).sort((a,b)=>a.start-b.start);if(ordered.some((interval,i)=>i>0&&interval.start<ordered[i-1].end))throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`)}if(ticks2.some(tick=>!Number.isFinite(tick)||tick<lo||tick>hi))throw new Error("Timeline ticks must lie inside the domain");const axisHeight=Math.max(36,fontSize*2+18);const laneHeight=(height-axisHeight-(lanes.length-1)*laneGap)/lanes.length;const labelHeight=fontSize*1.5,barHeight=laneHeight-labelHeight;if(barHeight<12)throw new Error("Timeline height cannot fit lane labels and interval bars");const left=x+labelWidth+3,plotWidth=width-labelWidth-6;const point=value=>{if(!Number.isFinite(value)||value<lo||value>hi)throw new Error("Timeline point must lie inside the domain");return left+(value-lo)/(hi-lo)*plotWidth};const bounds4={x,y,width,height};const result={bounds:bounds4,time,point,lanes:Object.create(null),intervals:Object.create(null)};painter.container(bounds4,()=>{lanes.forEach((lane,index)=>target(lane.focusTarget,()=>{const top=y+index*(laneHeight+laneGap);const track={x:left-2,y:top+labelHeight,width:plotWidth+4,height:barHeight};const shape2=painter.rect(track.x,track.y,track.width,track.height,trackColor,color,0);result.lanes[lane.id]={shape:shape2,bounds:track};painter.labelScope({x,y:top,width:labelWidth-12,height:laneHeight},()=>{painter.text(lane.label,x,top+laneHeight/2+fontSize*.34,fontSize,color,"left")},{padding:0});for(const interval of intervals.filter(item=>item.lane===lane.id)){const visibleEnd=Math.max(interval.start,Math.min(time,interval.end));const elapsed=visibleEnd-interval.start;const bar={x:point(interval.start),y:track.y+2,width:point(visibleEnd)-point(interval.start),height:barHeight-4};const opacity=Math.max(0,Math.min(1,interval.opacity??1));const item={id:interval.id,shape:null,bounds:bar,elapsed,opacity,complete:time>=interval.end};result.intervals[interval.id]=item;if(elapsed===0||opacity===0)continue;target(interval.focusTarget,()=>painter.opacity(opacity,()=>{painter.container(track,()=>{item.shape=painter.rect(bar.x,bar.y,bar.width,bar.height,interval.color??"#63DEEC",void 0,0)},{padding:0});if(interval.label){const labelBounds={x:point(interval.start),y:top,width:point(interval.end)-point(interval.start),height:labelHeight};painter.labelScope(labelBounds,()=>painter.text(interval.label,labelBounds.x+labelBounds.width/2,top+fontSize,fontSize,interval.color??"#63DEEC","center"),{padding:2})}}))}}));const axisY=y+height-axisHeight+Math.max(10,fontSize*.5);painter.line(left,axisY,left+plotWidth,axisY,color,2);for(const tick of ticks2){const px=point(tick);painter.line(px,axisY,px,axisY+6,color,2);painter.labelScope({x:left-labelWidth,y:axisY+8,width:plotWidth+labelWidth,height:fontSize*1.5},()=>{painter.text(formatTime(tick),px,axisY+fontSize*1.4,fontSize,color,tick===hi?"right":tick===lo?"left":"center")},{padding:0})}painter.line(point(time),axisY-8,point(time),axisY+8,cursorColor,3)},{padding:0});return result}}var COLORS=["#63DEEC","#79A6FF","#D6A0FF","#FFCE73"];function layoutAllocation(options){const{x,y,width,height,capacity,parts}=options;if(![x,y,x+width,y+height,capacity].every(Number.isFinite)||width<=0||height<=0||capacity<=0)throw new Error("Allocation needs finite positive bounds and capacity");const ids=new Set;let used=0;for(const part of parts){if(!part.id||ids.has(part.id))throw new Error("Allocation part IDs must be nonempty and unique");ids.add(part.id);if(!Number.isFinite(part.value)||part.value<0)throw new Error("Allocation values must be finite and nonnegative");used+=part.value}if(!Number.isFinite(used)||used-capacity>Number.EPSILON*Math.max(used,capacity)*8)throw new Error("Allocation exceeds capacity");used=Math.min(used,capacity);let offset=0;const segments=parts.map(part=>{const start=Math.min(offset,capacity);offset+=part.value;return{id:part.id,value:part.value,bounds:{x:x+width*(start/capacity),y,width:width*((Math.min(offset,capacity)-start)/capacity),height}}});const remaining=Math.max(0,capacity-used);return{bounds:{x,y,width,height},used,remaining,parts:segments,freeBounds:{x:x+width*(used/capacity),y,width:width*(remaining/capacity),height}}}function createTeachingAllocation(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,fontSize=28,unit="",format=String,color="#8D9CB9",trackColor="#18283B"}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Allocation font size must be finite and positive");const header=fontSize*1.7,barHeight=fontSize*2,rowHeight=fontSize*1.65,gap=fontSize*.6;if(height<header+barHeight+gap+(options.parts.length+1)*rowHeight||width<=6||width*.67<=fontSize)throw new Error("Allocation bounds cannot fit the strip and ledger");const layout=layoutAllocation({...options,x:x+3,y:y+header+3,width:width-6,height:barHeight-6});const suffix=unit?` ${unit}`:"",shapes=[];let shape2;painter.container({x,y,width,height},()=>{painter.labelScope({x,y,width,height:header},()=>painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`,x,y+fontSize,fontSize,color,"left"),{padding:0});const strip={x:x+1,y:y+header+1,width:width-2,height:barHeight-2};shape2=painter.rect(strip.x,strip.y,strip.width,strip.height,trackColor,color,0);painter.container(strip,()=>{layout.parts.forEach((part,index)=>shapes.push(part.bounds.width===0?null:target(options.parts[index].focusTarget,()=>painter.rect(part.bounds.x,part.bounds.y,part.bounds.width,part.bounds.height,options.parts[index].color??COLORS[index%COLORS.length],void 0,0))))},{padding:0});const rows=[...options.parts,{id:"free",label:"Free",value:layout.remaining,color,focusTarget:options.freeFocusTarget}];rows.forEach((part,index)=>target(part.focusTarget,()=>{const top=y+header+barHeight+gap+index*rowHeight,baseline=top+rowHeight/2+fontSize*.34;painter.rect(x,top+(rowHeight-fontSize*.6)/2,fontSize*.6,fontSize*.6,part.color??COLORS[index%COLORS.length],void 0,0);painter.labelScope({x:x+fontSize,y:top,width:width*.67-fontSize,height:rowHeight},()=>painter.text(part.label,x+fontSize,baseline,fontSize,color,"left"),{padding:0});painter.labelScope({x:x+width*.7,y:top,width:width*.3,height:rowHeight},()=>painter.text(`${format(part.value)}${suffix}`,x+width,baseline,fontSize,color,"right"),{padding:0})}))},{padding:0});return{...layout,shapes,shape:shape2}}}var clamp=value=>Math.max(0,Math.min(1,value));var smooth=value=>value*value*(3-2*value);function valueChangeState(options){for(const name of["from","to","progress"]){if(!Number.isFinite(options[name]))throw new Error(`Value change ${name} must be finite`)}if(options.emphasis!==void 0&&!Number.isFinite(options.emphasis))throw new Error("Value change emphasis must be finite");const{from,to:to2}=options;const progress=clamp(options.progress);const changed=from!==to2;const emphasis=changed?clamp(options.emphasis??smooth(clamp(progress/.12))*(1-smooth(clamp((progress-.65)/.35)))):0;const value=from*(1-progress)+to2*progress;const delta=to2-from;if(!Number.isFinite(value)||!Number.isFinite(delta))throw new Error("Value change result must be finite");return{value,previous:from,target:to2,delta,changed,emphasis}}function createTeachingValueChange(painter){function changeCue(options,draw2){const{x,y,width,height,color="#F4D477",restColor="#E9EFFF",fill=color,radius=10}=options;if(![x,y,width,height,radius].every(Number.isFinite)||width<=0||height<=0||radius<0){throw new Error("Value change bounds must be finite with positive dimensions and nonnegative radius")}const state=valueChangeState({from:options.from,to:options.to,progress:options.progress,...options.emphasis===void 0?{}:{emphasis:options.emphasis}});if(state.emphasis>0){painter.opacity(state.emphasis*.12,()=>painter.rect(x,y,width,height,fill,void 0,radius));painter.opacity(state.emphasis,()=>painter.rect(x,y,width,height,"transparent",color,radius))}const result={...state,color:state.emphasis>0?color:restColor};draw2?.(result);return result}function valueChange(options){const{x,y,width,height,label,format=value=>value.toFixed(1),fontSize=36,showDelta=true}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Value change font size must be positive");const lines=1+Number(Boolean(label))+Number(showDelta);if(height<fontSize*(lines===1?1.4:lines===2?2.3:3))throw new Error("Value change height must contain its label and delta");return changeCue(options,state=>painter.labelScope({x,y,width,height},()=>{const center2=x+width/2;if(label)painter.text(label,center2,y+fontSize*.7,fontSize*.55,options.restColor??"#E9EFFF","center");const baseline=label?y+height*(showDelta?.5:.65)+fontSize*.2:showDelta?y+fontSize*1.05:y+height/2+fontSize*.34;painter.text(format(state.value),center2,baseline,fontSize,state.color,"center","mono");if(showDelta){const sign=state.delta>0?"+":"";painter.text(`${format(state.previous)} \u2192 ${format(state.target)} \xB7 \u0394 ${sign}${format(state.delta)}`,center2,y+height-fontSize*.3,fontSize*.46,options.restColor??"#E9EFFF","center","mono")}},{padding:4}))}return{changeCue,valueChange}}function mergeFocusRegions(parts,gap=12){const regions=[];for(const part of parts){let current={...part},index=0;while(index<regions.length){const other=regions[index];if(current.x<=other.x+other.width+gap&&other.x<=current.x+current.width+gap&¤t.y<=other.y+other.height+gap&&other.y<=current.y+current.height+gap){const x=Math.min(current.x,other.x),y=Math.min(current.y,other.y);current={x,y,width:Math.max(current.x+current.width,other.x+other.width)-x,height:Math.max(current.y+current.height,other.y+other.height)-y};regions.splice(index,1);index=0}else index++}regions.push(current)}return regions}function createFocusDirector(painter,options={}){const{cues,strict=false,contextOpacity=.52,minimumContextAlpha=0}=options;if(!Number.isFinite(contextOpacity)||contextOpacity<0||contextOpacity>1)throw new Error("Focus context opacity must be between zero and one");if(!Number.isFinite(minimumContextAlpha)||minimumContextAlpha<0||minimumContextAlpha>1)throw new Error("Minimum context alpha must be between zero and one");const active=Object.values(cues??{}).filter(cue2=>cue2.active&&cue2.strength>0).sort((a,b)=>b.start-a.start||b.id.localeCompare(a.id))[0];const stack=[];function cue(id){const value=cues&&Object.hasOwn(cues,id)?cues[id]:void 0;if(!value&&strict)throw new Error(`Unknown narration cue: ${id}`);return value}function opacity(amount2,draw2){if(amount2===1)return draw2();let result;painter.opacity(amount2,()=>{result=draw2()});return result}return{active,cue,progress(id,fallback=0){return cue(id)?.progress??fallback},visible(id){return cue(id)?.phase!=="before"},reveal(id,draw2){return opacity(cue(id)?.reveal??1,draw2)},target(id,draw2){stack.push(id);try{return draw2()}finally{stack.pop()}},paint(draw2,originalAlpha=1){const focused=!active||stack.some(id=>active.targets.includes(id));let amount2=focused?1:1-(1-contextOpacity)*active.strength;if(!focused&&originalAlpha>0)amount2=Math.max(amount2,Math.min(originalAlpha,minimumContextAlpha)/originalAlpha);return opacity(amount2,draw2)}}}function createTeachingFocus(painter){function focusFrame(options){const{bounds:bounds4,strength,color="#63DEEC",padding=8,clip}=options;if(![bounds4.x,bounds4.y,bounds4.width,bounds4.height,strength,padding].every(Number.isFinite)||bounds4.width<=0||bounds4.height<=0||padding<0||strength<0||strength>1)throw new Error("Invalid focus frame geometry or strength");if(strength===0)return;const corners=offset=>{const x=bounds4.x-offset,y=bounds4.y-offset,w=bounds4.width+offset*2,h=bounds4.height+offset*2;const corner=Math.min(24,w/4,h/4);return[[x,y,1,1],[x+w,y,-1,1],[x,y+h,1,-1],[x+w,y+h,-1,-1]].map(([cx,cy,sx,sy])=>[{x:cx+sx*corner,y:cy},{x:cx,y:cy},{x:cx,y:cy+sy*corner}])};const clear=points=>points.slice(1).every((point,index)=>{const previous=points[index],x=Math.min(previous.x,point.x)-2,y=Math.min(previous.y,point.y)-2;const right=Math.max(previous.x,point.x)+2,bottom=Math.max(previous.y,point.y)+2;return(!clip||x>=clip.x&&y>=clip.y&&right<=clip.x+clip.width&&bottom<=clip.y+clip.height)&&!(options.avoid??[]).some(label=>x<label.x+label.width&&right>label.x&&y<label.y+label.height&&bottom>label.y)});let paths=corners(padding);if(!paths.every(clear)){const alternatives=[padding+6,padding+12,padding+20].map(corners);paths=alternatives.find(candidate=>candidate.every(clear))??paths.filter(clear)}if(paths.length<2)return;painter.opacity(strength*.7,()=>{for(const[index,points]of paths.entries()){painter.path(points,{id:options.id&&`${options.id}:${index}`,color,width:3,clip})}})}return{focusFrame}}var clamp2=value=>Math.max(0,Math.min(1,value));var cleanZero=value=>value===0?0:value;function finite2(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`);return value}function vector(values,dimensions,name){if(values.length!==dimensions)throw new Error(`${name} must have ${dimensions} coordinates`);return values.map(value=>cleanZero(finite2(value,name)))}function add(left,right){return left.map((value,index)=>cleanZero(finite2(value+right[index],"Weighted vector sum")))}function weightedVectorState(options){const progress=clamp2(finite2(options.progress,"Weighted vector progress"));const dimensions=options.initial?.length??options.terms[0]?.values.length??0;if(!dimensions)throw new Error("Weighted vectors require at least one coordinate; an empty sum needs an initial vector");const initial=options.initial?vector(options.initial,dimensions,"Initial vector"):Array(dimensions).fill(0);const ids=new Set;let prefix2=[...initial];const position2=progress*options.terms.length;const completedCount=Math.min(options.terms.length,Math.floor(position2));const terms=options.terms.map((term,index)=>{if(typeof term.id!=="string"||!term.id.trim()||term.id!==term.id.trim()||ids.has(term.id)){throw new Error("Weighted vector terms require distinct nonempty IDs without surrounding whitespace")}ids.add(term.id);const label=term.label??term.id;if(typeof label!=="string"||!label.trim())throw new Error("Weighted vector labels must be nonempty");const weight=finite2(term.weight,"Vector weight");const values=vector(term.values,dimensions,`Vector ${term.id}`);const contribution=values.map(value=>cleanZero(finite2(weight*value,"Weighted vector contribution")));const start=[...prefix2],end=add(start,contribution);prefix2=end;const fraction=clamp2(position2-index);const status=fraction===1?"completed":index===completedCount&&progress<1?"current":"pending";const applied=contribution.map(value=>cleanZero(value*fraction));return{...term,label,values,weight,status,progress:fraction,contribution,applied,start,end,currentEnd:add(start,applied),zero:contribution.every(value=>value===0)}});const completedSum=completedCount?[...terms[completedCount-1].end]:[...initial];const current=terms.find(term=>term.status==="current")??null;return{progress,dimensions,initial,terms,completedCount,current,completedSum,sum:current?[...current.currentEnd]:[...completedSum],total:[...prefix2]}}function positive3(value,name){if(finite2(value,name)<=0)throw new Error(`${name} must be positive`)}function bounds2(value,name){finite2(value.x,`${name} x`);finite2(value.y,`${name} y`);positive3(value.width,`${name} width`);positive3(value.height,`${name} height`)}function createTeachingVectorAccumulation(painter){return options=>{const state=weightedVectorState(options);const{plot,ledger,projection,fontSize=28,color="#63DEEC",restColor="#8D9CB9",completedOpacity=.45,width=4,endpointRadius=5,revealTotal=false,totalLabel="Accumulated vector",format=value=>String(Number(value.toPrecision(4)))}=options;bounds2(plot.bounds,"Vector plot");bounds2(ledger,"Vector ledger");positive3(fontSize,"Vector font size");positive3(width,"Vector stroke width");positive3(endpointRadius,"Vector endpoint radius");finite2(completedOpacity,"Completed vector opacity");if(completedOpacity<0||completedOpacity>1)throw new Error("Completed vector opacity must lie between zero and one");const[x0,x1]=plot.xDomain,[y0,y1]=plot.yDomain;for(const value of[x0,x1,y0,y1])finite2(value,"Vector plot domain");if(x1<=x0||y1<=y0)throw new Error("Vector plot domains must increase");const sx=plot.bounds.width/(x1-x0),sy=plot.bounds.height/(y1-y0);if(!Number.isFinite(sx)||!Number.isFinite(sy)||sx<=0||sy<=0||Math.abs(sx-sy)>Math.max(sx,sy)*1e-9){throw new Error("Weighted vector drawing requires equal-unit plot geometry")}if(state.dimensions!==2&&!projection)throw new Error("Weighted vector drawing requires 2D values or an explicit projection");if(projection&&!projection.label.trim())throw new Error("Vector projection requires a visible declaration");const rowHeight=fontSize*2.5,headerHeight=fontSize*1.6;if(ledger.height<headerHeight+state.terms.length*rowHeight+fontSize*1.8){throw new Error("Vector ledger height must contain the identities, contributions and result")}const point=values=>{const projected=projection?projection.point([...values]):values;if(projected.length!==2)throw new Error("Vector projection must return exactly two coordinates");const[x,y]=projected;finite2(x,"Projected vector x");finite2(y,"Projected vector y");if(x<x0||x>x1||y<y0||y>y1)throw new Error("Vector endpoints must lie inside the declared plot domains");const p=plot.point(x,y);finite2(p.x,"Vector endpoint x");finite2(p.y,"Vector endpoint y");const expectedX=finite2(plot.bounds.x+(x-x0)*sx,"Declared vector endpoint x");const expectedY=finite2(plot.bounds.y+plot.bounds.height-(y-y0)*sy,"Declared vector endpoint y");const tolerance=Math.max(1,Math.abs(expectedX),Math.abs(expectedY),plot.bounds.width,plot.bounds.height)*1e-9;if(Math.abs(p.x-expectedX)>tolerance||Math.abs(p.y-expectedY)>tolerance){throw new Error("Vector plot mapping must match its declared equal-unit transform")}return p};const segments=[];for(const term of state.terms){const from=point(term.start);point(term.end);const to2=point(term.currentEnd);if(term.status!=="pending")segments.push({id:term.id,status:term.status,from,to:to2,zero:Math.hypot(to2.x-from.x,to2.y-from.y)<1e-9})}const endpoint=point(state.sum);const vectorText=values=>`(${values.map(format).join(", ")})`;const target=(id,draw2)=>painter.target?painter.target(id,draw2):draw2();const paintedTerms=state.terms.map((term,index)=>({term,index,input:`${term.label}: ${format(term.weight)} \xD7 ${vectorText(term.values)}`,detail:term.status==="pending"?"pending":`${term.status}: ${vectorText(term.applied)}`}));const totalText=`${totalLabel}: ${revealTotal?vectorText(state.sum):"?"}`;for(const segment of segments){const term=state.terms.find(term2=>term2.id===segment.id);const ink=term.color??color;target(term.id,()=>painter.opacity(term.status==="completed"?completedOpacity:1,()=>{if(segment.zero)painter.circle(segment.to.x,segment.to.y,endpointRadius,"transparent",ink,width);else painter.arrow(segment.from.x,segment.from.y,segment.to.x,segment.to.y,ink,width)}))}if(revealTotal){const mark=()=>{painter.circle(endpoint.x,endpoint.y,endpointRadius*1.5,color)};if(options.totalTarget)target(options.totalTarget,mark);else mark()}painter.labelScope(ledger,()=>{painter.text(projection?`Projection: ${projection.label}`:"Weighted contributions",ledger.x+12,ledger.y+fontSize,fontSize*.85,restColor);for(const{term,index,input,detail}of paintedTerms)target(term.id,()=>{const ink=term.color??color;const y=ledger.y+headerHeight+index*rowHeight;painter.text(input,ledger.x+12,y+fontSize,fontSize,term.status==="pending"?restColor:ink);painter.text(detail,ledger.x+12,y+fontSize*1.9,fontSize*.8,restColor)});const result=()=>{painter.text(totalText,ledger.x+12,ledger.y+headerHeight+state.terms.length*rowHeight+fontSize,fontSize,revealTotal?color:restColor)};if(options.totalTarget)target(options.totalTarget,result);else result()},{padding:4});return{state,segments,endpoint}}}function categoricalSampling(options){if(options.normalization!=="probabilities"&&options.normalization!=="weights")throw new Error("Sampling requires an explicit mass normalization contract");if(!options.categories.length)throw new Error("Sampling needs at least one category");const ids=new Set;let total=0;for(const category of options.categories){if(!category.id||ids.has(category.id)||!category.label.trim())throw new Error("Sampling category IDs must be unique and labels nonempty");if(!Number.isFinite(category.mass)||category.mass<0)throw new Error("Sampling masses must be finite and nonnegative");ids.add(category.id);total+=category.mass}if(!Number.isFinite(total)||total<=0)throw new Error("Sampling total mass must be finite and positive");if(options.normalization==="probabilities"&&Math.abs(total-1)>1e-12)throw new Error("Sampling probabilities must sum to one within 1e-12");let cumulative=0;let lastPositive=0;options.categories.forEach((category,index)=>{if(category.mass>0)lastPositive=index});const categories=options.categories.map((category,index)=>{const lower=cumulative,probability=category.mass/total;cumulative=index===lastPositive?1:Math.min(1,cumulative+probability);if(category.mass>0&&(probability===0||cumulative<=lower))throw new Error("Positive category is too small for cumulative floating-point precision");return{...category,probability,lower,upper:cumulative,count:0,empiricalProbability:null}});ids.clear();const draws=options.draws.map(draw2=>{if(!draw2.id||ids.has(draw2.id))throw new Error("Sampling draw IDs must be nonempty and unique");if(!Number.isFinite(draw2.uniform)||draw2.uniform<0||draw2.uniform>=1)throw new Error("Supplied uniform draws must be finite inside [0, 1)");ids.add(draw2.id);const categoryIndex=categories.findIndex(category=>category.mass>0&&draw2.uniform>=category.lower&&draw2.uniform<category.upper);if(categoryIndex<0)throw new Error("Supplied draw could not be represented by the normalized intervals");categories[categoryIndex].count+=1;return{...draw2,categoryId:categories[categoryIndex].id,categoryIndex}});if(draws.length)categories.forEach(category=>{category.empiricalProbability=category.count/draws.length});return{inputTotal:total,normalization:options.normalization,categories,draws}}var COLORS2=["#79A6FF","#FF8DC3","#63DEEC","#FFCE73","#A6DF91"];function createTeachingCategoricalSampling(painter){return options=>{const model=categoricalSampling(options);const{x,y,width,height,fontSize=28,color="#DEE7F5",trackColor="#18283B",visibleDraws=0,drawProgress=0,showEmpirical=false,formatProbability=value=>value.toFixed(3)}=options;if(![x,y,x+width,y+height,fontSize].every(Number.isFinite)||fontSize<=0||width<=0||height<=0)throw new Error("Sampling needs finite positive bounds and font size");if(!Number.isInteger(visibleDraws)||visibleDraws<0||visibleDraws>model.draws.length)throw new Error("Visible sample count must be an integer inside the supplied draw count");if(!Number.isFinite(drawProgress)||drawProgress<0||drawProgress>1||visibleDraws===model.draws.length&&drawProgress!==0)throw new Error("Sampling progress must be inside [0, 1] for an available next draw");if(showEmpirical&&visibleDraws!==model.draws.length)throw new Error("Empirical reveal requires every supplied sample to be retained");const columns=options.columns??Math.max(1,Math.min(8,model.draws.length));if(!Number.isInteger(columns)||columns<1)throw new Error("Sampling columns must be a positive integer");const railWidth=fontSize*2,contentWidth=width-railWidth;const gap=fontSize*.5,cellWidth=(contentWidth-4-(columns-1)*gap)/columns,cellHeight=fontSize*1.9;const legendColumns=Math.min(3,model.categories.length),legendRows=Math.ceil(model.categories.length/legendColumns),legendHeight=legendRows*fontSize*1.7;const bandY=y+fontSize*4,bandHeight=fontSize*1.3,legendY=bandY+bandHeight+fontSize*1.5;const captionY=legendY+legendHeight+fontSize*.5,poolY=captionY+fontSize*3.3,rows=Math.ceil(model.draws.length/columns),empiricalY=poolY+Math.max(1,rows)*(cellHeight+gap)+fontSize*2;if(cellWidth<fontSize*2||contentWidth/legendColumns<fontSize*5||empiricalY+bandHeight+fontSize*1.7>y+height)throw new Error("Sampling bounds cannot fit probability labels, sample IDs and empirical strip");const inset2=fontSize*.22+2,stripX=x+inset2,stripWidth=contentWidth-inset2*2;const point=u=>stripX+u*stripWidth;const categoryColor=index=>model.categories[index].color??COLORS2[index%COLORS2.length];const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const label=(value,bounds4,align="left",ink=color,size=fontSize)=>painter.labelScope(bounds4,()=>painter.text(value,align==="center"?bounds4.x+bounds4.width/2:align==="right"?bounds4.x+bounds4.width:bounds4.x,bounds4.y+size*1.05,size,ink,align),{padding:0});const strip=(top,empirical)=>{painter.rect(stripX,top,stripWidth,bandHeight,trackColor,void 0,0);let cumulative=0;model.categories.forEach((category,index)=>{const probability=empirical?category.empiricalProbability??0:category.probability;const left=cumulative;cumulative+=probability;if(probability>0)target(category.focusTarget,()=>painter.rect(point(left),top,stripWidth*probability,bandHeight,categoryColor(index),void 0,0))})};const sampleBounds=model.draws.map((_draw,index)=>({x:x+2+index%columns*(cellWidth+gap),y:poolY+Math.floor(index/columns)*(cellHeight+gap),width:cellWidth,height:cellHeight}));const shapes=[];painter.container({x,y,width,height},()=>{label(options.normalization==="weights"?"Original probabilities \xB7 normalized supplied weights":"Original probabilities \xB7 supplied distribution",{x,y,width:contentWidth,height:fontSize*1.6});strip(bandY,false);label("0",{x,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"left",color,fontSize*.8);label("1",{x:x+contentWidth-fontSize*2,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"right",color,fontSize*.8);model.categories.forEach((category,index)=>{const bounds4={x:x+index%legendColumns*contentWidth/legendColumns,y:legendY+Math.floor(index/legendColumns)*fontSize*1.7,width:contentWidth/legendColumns-gap,height:fontSize*1.5};target(category.focusTarget,()=>label(`${category.label}: ${formatProbability(category.probability)}`,bounds4,"left",categoryColor(index)))});label(`Supplied samples \xB7 ${visibleDraws} retained / ${model.draws.length}`,{x,y:poolY-fontSize*1.8,width:contentWidth,height:fontSize*1.5});for(let index=0;index<visibleDraws;index+=1)target(options.sampleFocusTarget,()=>{const draw2=model.draws[index],bounds4=sampleBounds[index];shapes.push(painter.rect(bounds4.x,bounds4.y,bounds4.width,bounds4.height,trackColor,categoryColor(draw2.categoryIndex),4));label(draw2.id,bounds4,"center",categoryColor(draw2.categoryIndex))});if(drawProgress>0&&visibleDraws<model.draws.length)target(options.sampleFocusTarget,()=>{const draw2=model.draws[visibleDraws],destination=sampleBounds[visibleDraws],landed=drawProgress>=.4;const from={x:point(draw2.uniform),y:bandY-fontSize*1.2},onBand={x:point(draw2.uniform),y:bandY+bandHeight/2};const progress=landed?(drawProgress-.4)/.6:drawProgress/.4;const destinationPoint={x:destination.x+destination.width/2,y:destination.y+destination.height/2};const railX=x+width-inset2;const route=landed?[onBand,from,{x:railX,y:from.y},{x:railX,y:destinationPoint.y},destinationPoint]:[from,onBand];const lengths=route.slice(1).map((point2,index)=>Math.hypot(point2.x-route[index].x,point2.y-route[index].y));let remaining=progress*lengths.reduce((sum,length)=>sum+length,0);let marker=route[route.length-1];for(let index=0;index<lengths.length;index+=1){const length=lengths[index];if(remaining<=length&&length>0){const ratio=remaining/length;marker={x:route[index].x+(route[index+1].x-route[index].x)*ratio,y:route[index].y+(route[index+1].y-route[index].y)*ratio};break}remaining-=length}const ink=landed?categoryColor(draw2.categoryIndex):color;painter.circle(marker.x,marker.y,fontSize*.22,ink,trackColor,3);const caption=`${landed?"Copy":"Draw"} ${draw2.id} \xB7 supplied u=${draw2.uniform.toFixed(3)}`;label(caption,{x,y:captionY,width:contentWidth,height:fontSize*1.3},"left",ink,fontSize*.8)});if(showEmpirical){label(model.draws.length?"Empirical frequencies \xB7 supplied sample only":"No samples \xB7 empirical distribution undefined",{x,y:empiricalY-fontSize*1.7,width:contentWidth,height:fontSize*1.5});if(model.draws.length){strip(empiricalY,true);const text2=model.categories.map(category=>`${category.label}: ${category.count}/${model.draws.length}`).join(" \xB7 ");label(text2,{x,y:empiricalY+bandHeight+fontSize*.25,width:contentWidth,height:fontSize*1.3},"left",color,fontSize*.8)}}},{padding:0});return{model,sampleBounds,shapes,point,visibleDraws}}}function finite3(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative3(value,name){finite3(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function bounds3(value,name){for(const field of["x","y","width","height"])finite3(value[field],`${name} ${field}`);if(value.width<=0||value.height<=0)throw new Error(`${name} dimensions must be positive`);finite3(value.x+value.width,`${name} right edge`);finite3(value.y+value.height,`${name} bottom edge`)}function identifier(id,name){if(typeof id!=="string"||!id.trim())throw new Error(`${name} must be a nonempty ID`)}function alpha2(value){finite3(value,"Routed transfer opacity");return Math.max(0,Math.min(1,value))}function expanded(box,clearance){return{left:box.x-clearance,top:box.y-clearance,right:box.x+box.width+clearance,bottom:box.y+box.height+clearance}}function lengthOf(points){let sum=0;for(let i=1;i<points.length;i++)sum+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);return sum}function trimLeads(points,amount2){const length=lengthOf(points);if(length<=2*amount2)throw new Error("endpoint spacing leaves no positive-length clear transfer");const result=[pointAlongSamples(points,amount2/length)];let distance=0;for(let i=1;i<points.length;i++){distance+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);if(distance>amount2+1e-6&&distance<length-amount2-1e-6)result.push(points[i])}result.push(pointAlongSamples(points,1-amount2/length));return result}function parameters(options){identifier(options.id,"Routed transfer ID");identifier(options.source.id,"Routed transfer source");identifier(options.target.id,"Routed transfer target");if(options.source.id===options.target.id)throw new Error("Routed transfer source and target IDs must differ");bounds3(options.source.shape,"Routed transfer source");bounds3(options.target.shape,"Routed transfer target");bounds3(options.corridor,"Routed transfer corridor");const ids=new Set([options.source.id,options.target.id]);for(const obstacle of options.obstacles){identifier(obstacle.id,"Routed transfer obstacle");if(ids.has(obstacle.id))throw new Error(`Duplicate routed transfer object ID: ${obstacle.id}`);ids.add(obstacle.id);bounds3(obstacle.bounds,`Routed transfer obstacle ${obstacle.id}`)}const width=options.width??3,margin=options.margin??2;nonnegative3(width,"Routed transfer width");if(width===0)throw new Error("Routed transfer width must be positive");nonnegative3(margin,"Routed transfer margin");if(options.progress!==void 0)finite3(options.progress,"Routed transfer progress");if(options.marker&&options.progress===void 0)throw new Error("Routed transfer marker requires progress");const radius=options.marker?.radius??7,strokeWidth=options.marker?.strokeWidth??3;nonnegative3(radius,"Routed transfer marker radius");if(radius===0)throw new Error("Routed transfer marker radius must be positive");nonnegative3(strokeWidth,"Routed transfer marker stroke width");const markerInk=options.progress===void 0?0:radius+(options.marker?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerInk)+margin;const opacity=Math.min(alpha2(options.source.opacity),alpha2(options.target.opacity),alpha2(options.opacity??1));return{width,margin,radius,strokeWidth,clearance,opacity}}function planTeachingRoutedTransfer(options){const{clearance}=parameters(options);const fail=reason=>{throw new Error(`Cannot route transfer ${options.id} (${options.source.id} \u2192 ${options.target.id}): ${reason}`)};const guard=clearance+.01,corridor=options.corridor;if(corridor.width<=2*guard||corridor.height<=2*guard)fail("corridor is too small for the requested ink clearance");const origin={x:corridor.x+guard,y:corridor.y+guard};const toLocal=shape2=>{const x=shape2.x-origin.x,y=shape2.y-origin.y;finite3(x,"Routed transfer local x");finite3(y,"Routed transfer local y");return{x:Number(x.toFixed(6)),y:Number(y.toFixed(6)),width:shape2.width,height:shape2.height}};const endpoints=[options.source,options.target];const nodes=endpoints.map(endpoint=>{const b=toLocal(endpoint.shape);return{id:endpoint.id,cx:b.x+b.width/2,cy:b.y+b.height/2,width:b.width,height:b.height}});const obstacles=options.obstacles.map(obstacle=>expanded(toLocal(obstacle.bounds),0));const result=routeOrthogonalGraph(nodes,[{from:options.source.id,to:options.target.id,fromSide:options.source.side,toSide:options.target.side}],corridor.width-2*guard,corridor.height-2*guard,guard,14,obstacles);const raw=result.routes.get(0);if(!raw)return fail(result.failures[0]?.reason??"no legal route was returned");const points=(()=>{try{return trimLeads(raw,guard).map(point=>({x:point.x+origin.x,y:point.y+origin.y}))}catch(error){return fail(error instanceof Error?error.message:String(error))}})();const occupied=[...endpoints.map(endpoint=>expanded(endpoint.shape,clearance)),...options.obstacles.map(obstacle=>expanded(obstacle.bounds,clearance))];for(const point of points){if(point.x<corridor.x+clearance||point.x>corridor.x+corridor.width-clearance||point.y<corridor.y+clearance||point.y>corridor.y+corridor.height-clearance)fail("route ink leaves the permitted corridor")}for(let i=1;i<points.length;i++){if(occupied.some(obstacle=>routingSegmentBlocked(points[i-1],points[i],obstacle)))fail("a complete route segment violates object clearance")}const immutable=Object.freeze(points.map(point=>Object.freeze(point)));return{id:options.id,source:options.source,target:options.target,points:immutable,length:lengthOf(immutable),clearance,positionAt(progress){finite3(progress,"Routed transfer progress");return pointAlongSamples(immutable,Math.max(0,Math.min(1,progress)))}}}function createTeachingRoutedTransfer(painter){return options=>{const{width,radius,strokeWidth,opacity}=parameters(options);if(opacity===0)return null;const route=planTeachingRoutedTransfer(options),color=options.color??"#63DEEC";const paint=()=>painter.opacity(opacity,()=>{painter.path(route.points,{id:`${options.id}:route`,color,width});if(options.progress!==void 0&&options.progress>0&&options.progress<1){const point=route.positionAt(options.progress);painter.circle(point.x,point.y,radius,options.marker?.fill??color,options.marker?.stroke,strokeWidth)}});if(painter.target)painter.target(options.focusTarget??options.id,paint);else paint();return route}}function compareByteSequences(before,after){if(!(before instanceof Uint8Array)||!(after instanceof Uint8Array)){throw new Error("Byte comparison requires two Uint8Arrays")}const left=Array.from(before),right=Array.from(after);let commonPrefix=0,commonSuffix=0;while(commonPrefix<Math.min(left.length,right.length)&&left[commonPrefix]===right[commonPrefix])commonPrefix++;while(commonSuffix<Math.min(left.length,right.length)-commonPrefix&&left[left.length-commonSuffix-1]===right[right.length-commonSuffix-1])commonSuffix++;const columns=[];const add2=(oldOffset,newOffset)=>{const oldByte=oldOffset===null?null:{offset:oldOffset,value:left[oldOffset]};const newByte=newOffset===null?null:{offset:newOffset,value:right[newOffset]};const kind=!oldByte?"insert":!newByte?"delete":oldByte.value===newByte.value?"equal":"replace";columns.push({id:`before:${oldOffset??"none"}|after:${newOffset??"none"}`,kind,before:oldByte,after:newByte})};for(let offset=0;offset<commonPrefix;offset++)add2(offset,offset);const leftMiddle=left.length-commonPrefix-commonSuffix;const rightMiddle=right.length-commonPrefix-commonSuffix;for(let offset=0;offset<Math.max(leftMiddle,rightMiddle);offset++){add2(offset<leftMiddle?commonPrefix+offset:null,offset<rightMiddle?commonPrefix+offset:null)}for(let offset=0;offset<commonSuffix;offset++){add2(left.length-commonSuffix+offset,right.length-commonSuffix+offset)}return{algorithm:"common-prefix/suffix with positional middle",beforeLength:left.length,afterLength:right.length,commonPrefix,commonSuffix,equal:left.length===right.length&&commonPrefix===left.length,columns}}function escapedByte(value){if(!Number.isInteger(value)||value<0||value>255)throw new Error("A byte must be an integer from 0 through 255");if(value===0)return"\\0";if(value===9)return"\\t";if(value===10)return"\\n";if(value===13)return"\\r";if(value===32)return"space";if(value===92)return"\\\\";if(value>=33&&value<=126)return String.fromCharCode(value);return`\\x${value.toString(16).padStart(2,"0").toUpperCase()}`}function byteDifferenceState(options){if(!Number.isFinite(options.scanProgress))throw new Error("Byte scan progress must be finite");const comparison=compareByteSequences(options.before,options.after);const progress=Math.max(0,Math.min(1,options.scanProgress));const scannedColumns=Math.floor(progress*comparison.columns.length);return{comparison,progress,scannedColumns,scanComplete:progress===1,verdict:options.revealVerdict?comparison.equal?"equal":"different":null}}function layoutByteDifference(options){const{x,y,width,height,fontSize=28,maxColumns=10}=options;if(![x,y,width,height,fontSize,x+width,y+height].every(Number.isFinite)||width<=0||height<=0||fontSize<=0){throw new Error("Byte strip bounds and font size must be finite with positive dimensions")}if(fontSize<24)throw new Error("Byte strip font size must be at least 24 px for checked label padding");if(!Number.isSafeInteger(maxColumns)||maxColumns<1)throw new Error("Byte window size must be a positive safe integer");const state=byteDifferenceState(options),all=state.comparison.columns;const start=options.startColumn??Math.max(0,state.comparison.commonPrefix-2);if(!Number.isSafeInteger(start)||start<0||start>all.length||all.length>0&&start===all.length){throw new Error("Byte window start is outside the alignment")}const columns=all.slice(start,start+maxColumns),count=Math.max(1,columns.length);const gutter=fontSize*5.2,cellWidth=(width-gutter)/count;const longest=Math.max(5,...columns.flatMap(column=>[column.before,column.after].map(byte=>byte?String(byte.offset).length+1:5)));if(cellWidth<fontSize*.65*longest+12||height<fontSize*10){throw new Error("Byte strip cannot fit its byte labels and offsets")}const headerHeight=fontSize*1.7,footerHeight=fontSize*1.7,rowHeight=(height-headerHeight-footerHeight)/2;if(cellWidth<=4||rowHeight<=4||gutter-8<=8||headerHeight<=8||footerHeight<=8||rowHeight*.3<=8){throw new Error("Byte strip cannot fit positive cell insets and checked label padding")}const cells=columns.map((column,index)=>({column,alignmentIndex:start+index,beforeBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight,width:cellWidth,height:rowHeight},afterBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight+rowHeight,width:cellWidth,height:rowHeight}}));return{...state,bounds:{x,y,width,height},cells,gutter,headerHeight,footerHeight,rowHeight,omittedLeading:start,omittedTrailing:all.length-start-columns.length}}function createTeachingByteDifference(painter){return options=>{const layout=layoutByteDifference(options);const{x,y,width,height,fontSize=28,fill="#101820",stroke="#516376",textColor="#E9EFFF",mutedColor="#91A3B8",scanColor="#63DEEC",changeColor="#F4D477",beforeLabel="Before",afterLabel="After"}=options;const label=(value,bounds4,size,color=textColor)=>painter.labelScope(bounds4,()=>{painter.text(value,bounds4.x+bounds4.width/2,bounds4.y+bounds4.height/2+size*.34,size,color,"center","mono")},{padding:4});painter.container(layout.bounds,()=>{label("Prefix/suffix alignment; positional middle; not minimum edits",{x,y,width,height:layout.headerHeight},fontSize*.63,mutedColor);for(const[row,name]of[beforeLabel,afterLabel].entries()){label(name,{x,y:y+layout.headerHeight+row*layout.rowHeight,width:layout.gutter-8,height:layout.rowHeight},fontSize*.72)}for(const cell of layout.cells){const visited=cell.alignmentIndex<layout.scannedColumns;const color=visited?cell.column.kind==="equal"?mutedColor:changeColor:stroke;for(const[byte,bounds4]of[[cell.column.before,cell.beforeBounds],[cell.column.after,cell.afterBounds]]){painter.rect(bounds4.x+2,bounds4.y+2,bounds4.width-4,bounds4.height-4,fill,color,0);label(byte?`@${byte.offset}`:"none",{...bounds4,height:bounds4.height*.3},fontSize*.65,mutedColor);label(byte?byte.value.toString(16).padStart(2,"0").toUpperCase():"--",{...bounds4,y:bounds4.y+bounds4.height*.3,height:bounds4.height*.35},fontSize,visited?textColor:mutedColor);label(byte?escapedByte(byte.value):"no byte",{...bounds4,y:bounds4.y+bounds4.height*.65,height:bounds4.height*.35},fontSize*.7,mutedColor)}}if(!layout.cells.length){for(const row of[0,1])label("empty",{x:x+layout.gutter,y:y+layout.headerHeight+row*layout.rowHeight,width:width-layout.gutter,height:layout.rowHeight},fontSize,mutedColor)}const scanPosition=layout.progress*layout.comparison.columns.length-layout.omittedLeading;if(layout.cells.length&&scanPosition>=0&&scanPosition<=layout.cells.length){const cellWidth=layout.cells[0].beforeBounds.width;const cursor=Math.max(1,Math.min(width-layout.gutter-1,scanPosition*cellWidth));painter.rect(x+layout.gutter+cursor-1,y+layout.headerHeight-7,2,5,scanColor,void 0,0)}const verdict=layout.verdict===null?"Verdict held":layout.verdict==="equal"?"Bytes equal":"Bytes differ";label(`${layout.omittedLeading} columns before window; ${layout.omittedTrailing} after \xB7 ${verdict}`,{x,y:y+height-layout.footerHeight,width,height:layout.footerHeight},fontSize*.66,layout.verdict===null?mutedColor:textColor)},{padding:0});return layout}}function tokens(input,name){if(!Array.isArray(input))throw new Error(`Token history ${name} must be an array`);return Object.freeze(input.map(item=>{if(!item||typeof item.id!=="string"||!item.id.trim()||item.id!==item.id.trim()){throw new Error("Token occurrence IDs must be nonempty without surrounding whitespace")}if(!(typeof item.token==="string"&&item.token.trim())&&!(typeof item.token==="number"&&Number.isSafeInteger(item.token)&&item.token>=0)){throw new Error("History tokens require nonempty text or a nonnegative safe integer vocabulary ID")}return Object.freeze({id:item.id,token:item.token})}))}function equal(left,right){return left.id===right.id&&left.token===right.token}function prefix(part,whole,name){if(part.length>whole.length||part.some((token,index)=>!equal(token,whole[index]))){throw new Error(`Token history ${name} must preserve the exact ordered occurrence prefix`)}}function tokenHistoryState(options){const prompt=tokens(options.prompt,"prompt"),accepted=tokens(options.accepted,"accepted");const processed=tokens(options.processed,"processed"),emitted=tokens(options.emitted,"emitted");const history=Object.freeze([...prompt,...accepted]);if(new Set(history.map(token=>token.id)).size!==history.length){throw new Error("Token history requires distinct occurrence IDs, including repeated vocabulary tokens")}prefix(processed,history,"processed");prefix(emitted,accepted,"emitted");if(accepted.length&&processed.length<prompt.length)throw new Error("Accepted output requires the complete processed prompt");if(accepted.length&&processed.length<prompt.length+accepted.length-1){throw new Error("Ordinary decoding permits at most one accepted token awaiting processing")}const phase=options.phase??"resident";if(!["resident","dropped","replay"].includes(phase))throw new Error("Unknown token history phase");if(phase==="replay"&&options.replayProgress===void 0)throw new Error("Replay requires explicit progress");const replayProgress=options.replayProgress??0;if(!Number.isFinite(replayProgress)||replayProgress<0||replayProgress>1){throw new Error("Replay progress must be finite between zero and one")}const position2=replayProgress*processed.length;const completed=phase==="resident"?processed.length:phase==="dropped"?0:Math.floor(position2);const fraction=position2-Math.floor(position2);const moving=phase==="replay"&&fraction>0&&completed<processed.length?Object.freeze({token:processed[completed],position:completed,progress:fraction}):null;return Object.freeze({prompt,accepted,processed,emitted,history,phase,replayProgress,kv:Object.freeze(processed.slice(0,completed)),pendingAccepted:Object.freeze(accepted.filter((_,index)=>prompt.length+index>=processed.length)),moving})}function assertTokenHistoryTransition(before,after){before=tokenHistoryState(before);after=tokenHistoryState(after);prefix(before.prompt,after.prompt,"prompt transition");if(before.prompt.length!==after.prompt.length)throw new Error("A request prompt cannot change during its history");prefix(before.accepted,after.accepted,"accepted transition");prefix(before.emitted,after.emitted,"emitted transition");if(before.phase!=="resident"||after.phase!=="resident"){if(before.accepted.length!==after.accepted.length||before.emitted.length!==after.emitted.length){throw new Error("Drop and replay transitions cannot sample or emit new output")}prefix(before.processed,after.processed,"replay target");if(before.processed.length!==after.processed.length)throw new Error("Replay must rebuild the retained processed prefix")}else if(after.processed.length<before.processed.length){throw new Error("Resident processed history cannot shrink without an explicit drop or replay")}}function createTeachingTokenHistory(painter){return options=>{const state=tokenHistoryState(options);const{x,y,width,height,fontSize=28,gap=8,labelWidth=245,focusPrefix}=options;if(![x,y,x+width,y+height,width,height,fontSize,gap,labelWidth].every(Number.isFinite)||width<=0||height<=0||fontSize<=0||gap<0||labelWidth<=0){throw new Error("Token history drawing bounds and sizes must be finite and positive")}const columns=Math.max(1,state.history.length),top=fontSize*1.9,bottom=fontSize*2;const cellWidth=(width-labelWidth-gap*(columns-1)-4)/columns;const laneHeight=(height-top-bottom)/5,cellHeight=laneHeight-gap;if(cellWidth<fontSize*2.2||cellHeight<fontSize*1.6||labelWidth<fontSize*5){throw new Error("Token history bounds must fit its occurrence columns and five readable lanes")}const color={prompt:"#7FA7FF",accepted:"#92E28C",processed:"#63DEEC",kv:"#63DEEC",emitted:"#92E28C",pending:"#FFD75E",empty:"#586278",text:"#F2EFE6",fill:"#141820",...options.colors};const lanes=[{id:"prompt",label:"Prompt",tokens:state.prompt,offset:0},{id:"accepted",label:"Accepted output",tokens:state.accepted,offset:state.prompt.length},{id:"processed",label:"Processed prefix",tokens:state.processed,offset:0},{id:"kv",label:"Resident KV",tokens:state.kv,offset:0},{id:"emitted",label:"Already delivered",tokens:state.emitted,offset:state.prompt.length}];const pending2=new Set(state.pendingAccepted.map(token=>token.id));const bounds4={x,y,width,height};const target=(id,draw2)=>{if(id&&painter.target)painter.target(id,draw2);else draw2()};const cell=(position2,row)=>({x:x+labelWidth+1+position2*(cellWidth+gap),y:y+top+row*laneHeight,width:cellWidth,height:cellHeight});const paintToken=(token,shape2,stroke,fill=color.fill)=>{painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,fill,stroke,7);painter.labelScope(shape2,()=>painter.text(String(token.token),shape2.x+shape2.width/2,shape2.y+shape2.height/2+fontSize*.34,fontSize,color.text,"center","mono"),{padding:5})};painter.container(bounds4,()=>{for(let position2=0;position2<state.history.length;position2+=1){const shape2=cell(position2,0);painter.labelScope({...shape2,y,height:top},()=>painter.text(`position ${position2}`,shape2.x+shape2.width/2,y+fontSize,fontSize*.7,color.empty,"center"),{padding:3})}lanes.forEach((lane,row)=>target(focusPrefix?`${focusPrefix}-${lane.id}`:void 0,()=>{const labelBounds={x,y:y+top+row*laneHeight,width:labelWidth-gap,height:cellHeight};painter.labelScope(labelBounds,()=>painter.text(lane.label,x+5,labelBounds.y+cellHeight/2+fontSize*.34,fontSize*.82,color[lane.id]),{padding:3});for(let position2=0;position2<columns;position2+=1){const shape2=cell(position2,row),token=lane.tokens[position2-lane.offset];if(token){const isPending=lane.id==="accepted"&&pending2.has(token.id);target(isPending&&focusPrefix?`${focusPrefix}-pending`:void 0,()=>paintToken(token,shape2,isPending?color.pending:color[lane.id],lane.id==="processed"?"transparent":color.fill))}else painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,"transparent",color.empty,7)}}));if(state.moving){const from=cell(state.moving.position,2),to2=cell(state.moving.position,3);const progress=state.moving.progress;const settle=Math.max(0,(progress-.65)/.35);const grow2=Math.max(0,(progress-.8)/.2);const copyWidth=Math.min(from.width,fontSize*3);const copyHeight=Math.min(from.height,fontSize*1.8);const movingWidth=copyWidth+(from.width-copyWidth)*grow2;const movingHeight=copyHeight+(from.height-copyHeight)*grow2;const startInset=Math.min(7,from.width-copyWidth);const startCenterX=from.x+startInset+copyWidth/2;const centerX=startCenterX+(from.x+from.width/2-startCenterX)*settle;const centerY=from.y+from.height/2+(to2.y-from.y)*progress;const moving={x:centerX-movingWidth/2,y:centerY-movingHeight/2,width:movingWidth,height:movingHeight};target(focusPrefix?`${focusPrefix}-replay`:void 0,()=>paintToken(state.moving.token,moving,color.kv))}const pendingText=state.pendingAccepted.map(token=>String(token.token)).join(", ");const message=state.phase==="replay"?"Replay rebuilds KV; no sampling or delivery":state.phase==="dropped"?"KV released; accepted and delivered history retained":pendingText?`Accepted but unprocessed: ${pendingText}`:"All accepted positions are processed";painter.labelScope({x,y:y+height-bottom,width,height:bottom},()=>painter.text(message,x+width/2,y+height-fontSize*.6,fontSize*.82,state.phase==="replay"?color.kv:color.pending,"center"),{padding:3})},{padding:0});return state}}var INK="#8D9CB9";var ACCENT="#63DEEC";var PANEL="#18283B";function finite4(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function positive4(value,name){finite4(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function boundsOf(options){finite4(options.x,"Teaching x");finite4(options.y,"Teaching y");positive4(options.width,"Teaching width");positive4(options.height,"Teaching height");return{x:options.x,y:options.y,width:options.width,height:options.height}}function amount(value,name="Teaching progress"){finite4(value,name);return Math.max(0,Math.min(1,value))}function domainOf(domain,name){finite4(domain[0],`${name} start`);finite4(domain[1],`${name} end`);if(domain[1]<=domain[0]||!Number.isFinite(domain[1]-domain[0])){throw new Error(`${name} must have a finite positive span`)}return[domain[0],domain[1]]}function createTeachingCanvas(painter){const components=createCanvasComponents(painter);function axes2(options){let bounds4=boundsOf(options);const xDomain=domainOf(options.xDomain,"Plot x domain");const yDomain=domainOf(options.yDomain,"Plot y domain");if(options.equalUnits){const xSpan=xDomain[1]-xDomain[0];const ySpan=yDomain[1]-yDomain[0];const pixelsPerUnit=Math.min(bounds4.width/xSpan,bounds4.height/ySpan);const width2=xSpan*pixelsPerUnit;const height2=ySpan*pixelsPerUnit;bounds4=boundsOf({x:bounds4.x+(bounds4.width-width2)/2,y:bounds4.y+(bounds4.height-height2)/2,width:width2,height:height2})}const{x,y,width,height}=bounds4;const{color=INK,gridColor,fontSize=28,xTicks=[],yTicks=[],formatX=String,formatY=String}=options;positive4(fontSize,"Axis font size");xTicks.forEach(tick=>finite4(tick,"Axis x tick"));yTicks.forEach(tick=>finite4(tick,"Axis y tick"));const plot={bounds:bounds4,xDomain,yDomain,point(px,py){finite4(px,"Plot point x");finite4(py,"Plot point y");const point={x:x+(px-xDomain[0])/(xDomain[1]-xDomain[0])*width,y:y+height-(py-yDomain[0])/(yDomain[1]-yDomain[0])*height};finite4(point.x,"Mapped point x");finite4(point.y,"Mapped point y");return point}};for(const tick of xTicks){if(tick<xDomain[0]||tick>xDomain[1])continue;const point=plot.point(tick,yDomain[0]);if(gridColor)painter.path([{x:point.x,y},{x:point.x,y:y+height}],{color:gridColor,width:1,clip:bounds4});painter.line(point.x,y+height,point.x,y+height+7,color,2);painter.text(formatX(tick),point.x,y+height+36,fontSize,color,"center")}for(const tick of yTicks){if(tick<yDomain[0]||tick>yDomain[1])continue;const point=plot.point(xDomain[0],tick);if(gridColor)painter.path([{x,y:point.y},{x:x+width,y:point.y}],{color:gridColor,width:1,clip:bounds4});painter.line(x-7,point.y,x,point.y,color,2);painter.text(formatY(tick),x-18,point.y+9,fontSize,color,"right")}painter.line(x,y+height,x+width,y+height,color,2);painter.line(x,y,x,y+height,color,2);if(options.xLabel)painter.text(options.xLabel,x+width/2,y+height+72,30,color,"center");if(options.yLabel)painter.text(options.yLabel,x,y-26,30,color,"left");return plot}function curve2(options){const{plot,points,color,width=4,progress=1}=options;positive4(width,"Curve width");const mapped=points.map(point=>plot.point(point.x,point.y));const visible=tracePolyline(mapped,progress);if(visible.length>1)painter.path(visible,{color,width,clip:plot.bounds});return visible}function scatter2(options){const{plot,points,color=ACCENT,radius=7,opacity=1}=options;positive4(radius,"Scatter radius");const alpha3=amount(opacity,"Scatter opacity");const projected=points.map(point=>{positive4(point.radius??radius,"Scatter point radius");return{...plot.point(point.x,point.y),radius:point.radius??radius,color:point.color??color,inDomain:point.x>=plot.xDomain[0]&&point.x<=plot.xDomain[1]&&point.y>=plot.yDomain[0]&&point.y<=plot.yDomain[1]}});const shapes=[];if(alpha3===0)return shapes;painter.opacity(alpha3,()=>{for(const point of projected){if(!point.inDomain)continue;shapes.push(painter.circle(point.x,point.y,point.radius,point.color))}});return shapes}function bars(options){const bounds4=boundsOf(options);const{x,y,width,height}=bounds4;const{values,labels,colors:colors2,color=ACCENT,progress=1,showValues=false,format=String,fontSize=28,gap=20}=options;positive4(fontSize,"Bar font size");finite4(gap,"Bar gap");if(gap<0)throw new Error("Bar gap must be nonnegative");values.forEach(value=>{finite4(value,"Bar value");if(value<0)throw new Error("Bar values must be nonnegative")});if(labels&&labels.length!==values.length)throw new Error("Bar labels must match values");if(colors2&&colors2.length!==values.length)throw new Error("Bar colors must match values");const maximumValue=values.reduce((maximum2,value)=>Math.max(maximum2,value),0);const maximum=options.max??(maximumValue||1);positive4(maximum,"Bar maximum");if(maximum<maximumValue)throw new Error("Bar maximum must contain every value");const reveal2=amount(progress);if(!values.length)return{bars:[],slots:[],bounds:bounds4};const barWidth=(width-gap*(values.length-1))/values.length;positive4(barWidth,"Bar width after gaps");const shapes=[];const slots=[];values.forEach((value,index)=>{const left=x+index*(barWidth+gap);const barHeight=value/maximum*height*reveal2;slots.push({x:left,y,width:barWidth,height});shapes.push(barHeight>0?painter.rect(left,y+height-barHeight,barWidth,barHeight,colors2?.[index]??color,void 0,Math.min(8,barWidth/2,barHeight/2)):null);if(labels)painter.text(labels[index],left+barWidth/2,y+height+38,fontSize,INK,"center");if(showValues&&reveal2>0)painter.text(format(value),left+barWidth/2,y+height-barHeight-14,fontSize,colors2?.[index]??color,"center")});return{bars:shapes,slots,bounds:bounds4}}function flowGraph(options){const{nodes,edges,stroke=ACCENT,fill=PANEL,textColor="#FFFFFF",padding=12}=options;finite4(padding,"Flow node padding");if(padding<0)throw new Error("Flow node padding must be nonnegative");const descriptors=Object.create(null);for(const node of nodes){if(!node.id||Object.hasOwn(descriptors,node.id))throw new Error("Flow node IDs must be nonempty and unique");const bounds4=boundsOf(node);positive4(node.fontSize??30,"Flow node font size");finite4(node.radius??14,"Flow node radius");if((node.radius??14)<0)throw new Error("Flow node radius must be nonnegative");descriptors[node.id]={...bounds4,radius:node.radius??14}}for(const edge of edges){if(!Object.hasOwn(descriptors,edge.from)||!Object.hasOwn(descriptors,edge.to))throw new Error("Flow edge must reference existing nodes");if(edge.from===edge.to)throw new Error("Flow edges must connect distinct nodes");if(edge.progress!==void 0)amount(edge.progress);if(edge.width!==void 0)positive4(edge.width,"Flow edge width");for(const gap of[edge.gap,edge.fromGap,edge.toGap]){if(gap!==void 0)finite4(gap,"Flow edge gap")}}const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const routes=edges.map(edge=>target(edge.focusTarget,()=>{const{from,to:to2,progress,focusTarget:_focusTarget,...style}=edge;const route=painter.connect(descriptors[from],descriptors[to2],{color:stroke,...style});if(progress!==void 0)components.particle({points:[route.from,route.to],progress,radius:7,fill:style.color??stroke});return route}));for(const node of nodes){const shape2=target(node.focusTarget,()=>components.card({...descriptors[node.id],label:node.label,id:node.id,fill:node.fill??fill,stroke:node.color??stroke,textColor,fontSize:node.fontSize??30,padding}));Object.assign(descriptors[node.id],shape2)}return{nodes:descriptors,routes}}return{axes:axes2,curve:curve2,scatter:scatter2,bars,flowGraph,transfer:createTeachingTransfer(painter),routedTransfer:createTeachingRoutedTransfer(painter),grid:createTeachingGrid(painter),timeline:createTeachingTimeline(painter),allocation:createTeachingAllocation(painter),vectorAccumulation:createTeachingVectorAccumulation(painter),categoricalSampling:createTeachingCategoricalSampling(painter),byteDifference:createTeachingByteDifference(painter),tokenHistory:createTeachingTokenHistory(painter),...createTeachingValueChange(painter),...createTeachingFocus(painter)}}function position(beat,progress){if(!Number.isSafeInteger(beat)||beat<0)throw new Error("Cue beat must be a nonnegative safe integer");if(!Number.isFinite(progress)||progress<0||progress>1)throw new Error("Cue progress must be between zero and one");if(progress===1){if(!Number.isSafeInteger(beat+1))throw new Error("Cue position exceeds the safe integer range");return{beat:beat+1,beatP:0}}return{beat,beatP:progress}}function compare(left,right){return left.beat===right.beat?left.beatP-right.beatP:left.beat-right.beat}function createCueTrack(options){const ids=new Set;const entry=({id,snapshot})=>{if(typeof id!=="string"||!id.trim()||ids.has(id))throw new Error("Cue IDs must be nonempty and unique");ids.add(id);return Object.freeze({id,snapshot})};const initial=entry(options.initial);const cues=options.cues.map(cue=>({position:position(cue.beat,cue.at),value:entry(cue)}));for(let index=1;index<cues.length;index+=1){if(compare(cues[index-1].position,cues[index].position)>=0){throw new Error("Cue positions must be strictly increasing")}}return Object.freeze({sample(current){const at=position(current.beat,current.beatP);let low=0,high=cues.length;while(low<high){const middle=Math.floor((low+high)/2);if(compare(cues[middle].position,at)<=0)low=middle+1;else high=middle}return low===0?initial:cues[low-1].value}})}function clampProgress2(progress){if(!Number.isFinite(progress))throw new Error("Camera progress must be finite");return Math.max(0,Math.min(1,progress))}function assertCamera(camera,context){if(!Number.isFinite(camera.x)||!Number.isFinite(camera.y)){throw new Error(`${context} coordinates must be finite`)}if(!Number.isFinite(camera.zoom)||camera.zoom<=0){throw new Error(`${context} zoom must be finite and greater than zero`)}}function assertViewport(viewport){if(!Number.isFinite(viewport.width)||viewport.width<=0){throw new Error("Camera viewport width must be finite and greater than zero")}if(!Number.isFinite(viewport.height)||viewport.height<=0){throw new Error("Camera viewport height must be finite and greater than zero")}}function assertZoomConstraints(options){const{minZoom,maxZoom}=options;if(minZoom!==void 0&&(!Number.isFinite(minZoom)||minZoom<=0)){throw new Error("Camera minZoom must be finite and greater than zero")}if(maxZoom!==void 0&&(!Number.isFinite(maxZoom)||maxZoom<=0)){throw new Error("Camera maxZoom must be finite and greater than zero")}if(minZoom!==void 0&&maxZoom!==void 0&&minZoom>maxZoom){throw new Error("Camera minZoom cannot exceed maxZoom")}}function assertZoomInRange(camera,options){if(options.minZoom!==void 0&&camera.zoom<options.minZoom||options.maxZoom!==void 0&&camera.zoom>options.maxZoom){throw new Error("Camera zoom is outside the configured range")}}function interpolateLinear(from,to2,progress){return from*(1-progress)+to2*progress}function interpolateCamera(from,to2,progress,options={}){assertCamera(from,"Camera start");assertCamera(to2,"Camera end");assertZoomConstraints(options);assertZoomInRange(from,options);assertZoomInRange(to2,options);const amount2=clampProgress2(progress);if(amount2===0)return{...from};if(amount2===1)return{...to2};const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Camera easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return{...from};if(t===1)return{...to2};const camera={x:interpolateLinear(from.x,to2.x,t),y:interpolateLinear(from.y,to2.y,t),zoom:Math.exp(Math.log(from.zoom)*(1-t)+Math.log(to2.zoom)*t)};assertCamera(camera,"Camera result");assertZoomInRange(camera,options);return camera}function cameraSvgTransform(camera,viewport){assertCamera(camera,"Camera");assertViewport(viewport);return`translate(${viewport.width/2} ${viewport.height/2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`}function projectWorldPoint(point,camera,viewport){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error("World point coordinates must be finite")}assertCamera(camera,"Camera");assertViewport(viewport);const projected={x:viewport.width/2+(point.x-camera.x)*camera.zoom,y:viewport.height/2+(point.y-camera.y)*camera.zoom};if(!Number.isFinite(projected.x)||!Number.isFinite(projected.y)){throw new Error("Projected world point coordinates must be finite")}return projected}var DEFAULT_MORPH_SAMPLES=64;var MAX_MORPH_SAMPLES=4096;function clampProgress3(progress){if(!Number.isFinite(progress))throw new Error("Polyline morph progress must be finite");return Math.max(0,Math.min(1,progress))}function validatePolyline(points,context){if(!Array.isArray(points)||points.length===0){throw new Error(`${context} polyline must be a non-empty array`)}for(let index=0;index<points.length;index+=1){const point=points[index];if(!point||!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} point ${index} coordinates must be finite`)}}}function validateSamples(samples){if(!Number.isInteger(samples)||samples<2){throw new Error("Polyline morph samples must be an integer of at least 2")}if(samples>MAX_MORPH_SAMPLES){throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`)}}function resamplePolyline(points,samples){const lengths=points.slice(1).map((point,index)=>Math.hypot(point.x-points[index].x,point.y-points[index].y));const total=lengths.reduce((sum,length)=>sum+length,0);if(!Number.isFinite(total))throw new Error("Polyline morph arc length must be finite");if(total===0)return Array.from({length:samples},()=>({...points[0]}));let segment=0;let offset=0;return Array.from({length:samples},(_,index)=>{if(index===samples-1)return{...points[points.length-1]};const distance=total*(index/(samples-1));while(segment<lengths.length-1&&(lengths[segment]===0||distance>offset+lengths[segment])){offset+=lengths[segment++]}const t=(distance-offset)/lengths[segment];const from=points[segment],to2=points[segment+1];return{x:from.x*(1-t)+to2.x*t,y:from.y*(1-t)+to2.y*t}})}function createPolylineMorph(from,to2,options={}){validatePolyline(from,"Start");validatePolyline(to2,"End");const samples=options.samples??DEFAULT_MORPH_SAMPLES;validateSamples(samples);const startSamples=resamplePolyline(from,samples);const endSamples=resamplePolyline(to2,samples);const easing=options.easing??smoothstep;return progress=>{const amount2=clampProgress3(progress);const eased=amount2===0||amount2===1?amount2:easing(amount2);if(!Number.isFinite(eased))throw new Error("Polyline morph easing must return a finite number");const t=Math.max(0,Math.min(1,eased));return startSamples.map((start,index)=>{const end=endSamples[index];return{x:start.x*(1-t)+end.x*t,y:start.y*(1-t)+end.y*t}})}}function morphPolyline(from,to2,progress,options={}){return createPolylineMorph(from,to2,options)(progress)}function graphImportResult(source,graph2,diagnostics){if(graph2.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:graph2,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line2,code,severity,message,column=1){diagnostics.push({code,severity,message,line:line2,column,excerpt:(sourceLines[line2-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line2,index){while(index<line2.length&&/\s/.test(line2[index]??""))index++;return index}function readDelimited(line2,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line2.length;index++){const character=line2[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line2.startsWith(close,index)){return{value:line2.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(line2,from){let index=skipWhitespace(line2,from);const id=line2.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line2,index);if(afterId>=line2.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line2.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(line2,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,endpoint,groupId,line2,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint.id)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint.label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint.label}else{state.nodeIndexes.set(endpoint.id,state.nodes.length);state.nodes.push({id:endpoint.id,label:endpoint.label,...groupId?{group:groupId}:{}})}if(endpoint.shape==="lossy"&&!state.warnedShapes.has(endpoint.id)){state.warnedShapes.add(endpoint.id);addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line2,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line2,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line2,first.next);const hasConnector=CONNECTORS.some(connector2=>line2.startsWith(connector2,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line2,cursor);if(cursor>=line2.length)return;const connector2=CONNECTORS.find(candidate=>line2.startsWith(candidate,cursor));if(!connector2){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+=connector2.length;cursor=skipWhitespace(line2,cursor);let edgeLabel;if(line2[cursor]==="|"){const end=line2.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=line2.slice(cursor+1,end).trim();cursor=skipWhitespace(line2,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(line2,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}:{},...connector2==="---"?{arrow:"none"}:connector2==="-.->"?{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 direction2="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(line2.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line2.startsWith("%%"))continue;if(!sawHeader){const header=line2.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();direction2=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line2.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(line2)){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(line2)){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(line2)){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(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line2,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 graph2={nodes:state.nodes,edges:state.edges,groups:state.groups,direction:direction2};return graphImportResult("mermaid",graph2,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(line2){let quote;let escaped=false;for(const character of line2){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,line2,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line2,"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,line2,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line2,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 direction2="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)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(line2.startsWith("#"))continue;if(hasUnquotedHash(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line2.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line2.includes("{")||line2.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=line2.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction2=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape2=decodeD2Label(shapeMatch[2]??"");if(!id||shape2===void 0||shape2===""){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:shape2,line:lineNumber});continue}const edgeMatch=line2.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 connector2=edgeMatch[2];const to2=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector2||!to2)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,to2,to2,lineNumber,sourceLines,diagnostics,false);edges.push({from,to:to2,...label!==void 0?{label}:{},arrow:connector2==="<->"?"both":connector2==="<-"?"backward":connector2==="--"?"none":"forward"});continue}const nodeMatch=line2.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(line2.includes(".style")||line2.includes(".width")||line2.includes(".height")||line2.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(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line2)){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:line2}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line2,"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:direction2},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage}from"async_hooks";import{tmpdir}from"os";import{join}from"path";import parseCssColor2 from"parse-css-color";import{Children,isValidElement}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.text_overflow","layout.whitespace_imbalance","readability.small_text","render.error","render.svg_context","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=8.5;var SVG_ONLY_ELEMENTS=new Set(["circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","symbol","text","textPath","tspan","use"]);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=parseCssColor2(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 alpha3=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha3<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha3,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha3,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha3,alpha:alpha3}}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 amount2=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount2*4/3;if(unit==="rem")return amount2*16;if(unit==="em")return amount2*(inherited??16);if(unit==="%")return amount2/100*(inherited??16);return amount2}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(!isValidElement(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 analyzeScene(element,theme,trustedComponents,rootBackground2,svgComponents){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path,namespace){if(visited++>=MAX_CONTRAST_NODES||!isValidElement(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path,namespace);return}const props=node.props;const svgShape=svgComponents?.shapes.get(node.type)??(svgComponents&&typeof node.type==="string"&&SVG_ONLY_ELEMENTS.has(node.type)?`<${node.type}>`:void 0);if(namespace==="html"&&svgShape){diagnostics.push({code:"render.svg_context",severity:"error",theme,message:`${svgShape} requires an <svg> ancestor at ${path}; its SVG geometry will not render in an HTML layout.`,suggestion:"Place the element inside a native <svg> or an SVG container such as AxisPlot.",elementId:elementId(props),location:{path}})}const childNamespace=typeof node.type==="string"?node.type==="svg"?"svg":node.type==="foreignObject"?"html":namespace:typeof node.type==="function"?svgComponents?.children.get(node.type):namespace;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}`,childNamespace))}visit(element,{background:colorFromCss(rootBackground2)},"root","html");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(text2){return Array.from(text2.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 text2=String(node.textContent??"").trim();if(text2&&typeof style.transform==="string"&&style.transform.includes("rotate"))continue;if(text2&&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(text2)*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:text2,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(text2){const normalized=text2.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=attribute=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute];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 connectorSource=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>Number(node.props["data-vizmatic-connector-crossing-budget"]??0));const connectorCrossings=connectorSource?Number(connectorSource.props["data-vizmatic-connector-crossings"]):0;if(connectorCrossings>0){const source=connectorSource;diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings} connector crossing${connectorCrossings===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 crossedLabels=maxDataNumber("data-vizmatic-connector-label-crossings");if(crossedLabels>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"info",theme,message:`${crossedLabels} connector${crossedLabels===1?" passes":"s pass"} behind a label or group title. The label masks it, but the line appears broken.`,suggestion:'Shorten or move the label, change graph direction, or route the connector with routing="orthogonal".',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 eight 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 overflowCount=0;const graphNodes=nodes.filter(node=>typeof node.props["data-vizmatic-graph-node-id"]==="string");for(const box of graphNodes){for(const text2 of nodes){if(overflowCount>=MAX_DIAGNOSTICS_PER_RULE)break;if(!String(text2.textContent??"").trim()||text2===box)continue;const startsInside=text2.left>=box.left-1&&text2.left<box.left+box.width&&text2.top>=box.top-1&&text2.top<box.top+box.height;if(!startsInside)continue;const spillsRight=text2.left+text2.width>box.left+box.width+1;const spillsDown=text2.top+text2.height>box.top+box.height+1;if(!spillsRight&&!spillsDown)continue;diagnostics.push({code:"layout.text_overflow",severity:"warning",theme,message:`Text "${textExcerpt(String(text2.textContent))}" spills out of node "${String(box.props["data-vizmatic-graph-node-id"])}".`,suggestion:"Omit the fixed node width and height so the node sizes to its content, or shorten the text.",elementId:elementId(box.props),location:{x:text2.left,y:text2.top,width:text2.width,height:text2.height}});overflowCount+=1;break}}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(bounds4,width,height,theme){const gutters={left:bounds4.x,right:width-bounds4.x-bounds4.width,top:bounds4.y,bottom:height-bounds4.y-bounds4.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:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.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:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.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 SVG_CONTEXT_COMPONENTS={shapes:new Map([[SvgFrame,"SvgFrame"],[SvgPoint,"SvgPoint"],[VectorArrow,"VectorArrow"],[VectorSegment,"VectorSegment"],[ArrowMarkerDef,"ArrowMarkerDef"]]),children:new Map([...[Board,CanvasItem,Canvas,Scene,Row,Column,Panel,Stack,Card,Tile,WindowFrame,CalloutCard,ChartFrame].map(component=>[component,"html"]),[AxisPlot,"svg"]])};var consoleCaptureContext=new AsyncLocalStorage;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(run2){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run2);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(join(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 analyzeScene(element,theme,TRUSTED_COMPONENTS,background,SVG_CONTEXT_COMPONENTS)});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:join(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:join(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}}import parseCssColor3 from"parse-css-color";var themeColorKeys=Object.freeze(Object.keys(getThemeColors("dark")).filter(key=>key!=="preset"&&key!=="fontSans"&&key!=="fontMono"&&key!=="fontSerif"&&key!=="density"));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"||!parseCssColor3(color.trim())){throw new Error(`themeColors.${key} must be a valid CSS color.`)}colors2[key]=color.trim()}return colors2}function parseThemeColorsMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.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(line2){const withoutComment=stripTrailingLineComment(line2.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(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]/.test(line2)}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"||parseCssColor3(background))return background;throw new Error('background must be "theme", "transparent", or a valid CSS color.')}function isThemeColorsMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]/.test(line2)}function mergePlaygroundThemeColors(mode,preset,overrides){return{...getThemeColors(mode,preset),...overrides}}function stripTrailingLineComment(line2){let quoted=false;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[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==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}function readPresetLine(line2){const candidate=stripLineComment(line2.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(line2){const match=line2.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(line2){let quote;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[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==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}import parseCssColor4 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}}import{existsSync}from"fs";import{mkdir as mkdir3,stat as stat2,writeFile as writeFile3}from"fs/promises";import{basename,dirname as dirname3,extname,join as join2,relative,resolve as resolve2}from"path";import{mkdir as mkdir2,stat,writeFile as writeFile2}from"fs/promises";import{totalmem}from"os";import{dirname as dirname2,resolve}from"path";import*as gifenc2 from"gifenc";import parseCssColor5 from"parse-css-color";var midnight={name:"midnight",dark:true,background:"#0b0c10",bloom:.2,colors:{bg:"#0b0c10",surface:"#15171d",ink:"#f2efe6",dim:"#a5a7ad",faint:"#5c5f68",grid:"#23303d",gridStrong:"#3d5266",blue:"#5cc4f0",teal:"#4fd8c4",green:"#8fe08a",yellow:"#ffd75e",gold:"#f2b84b",orange:"#ff9d57",red:"#ff6b6b",pink:"#ff8fc0",purple:"#b49cff"}};var paper={name:"paper",dark:false,background:"#f7f3ea",bloom:0,colors:{bg:"#f7f3ea",surface:"#efe9db",ink:"#1d1b16",dim:"#5e5a50",faint:"#a29c8d",grid:"#e2dbca",gridStrong:"#c4bba6",blue:"#1f6fb2",teal:"#0d8577",green:"#3f8a35",yellow:"#b98500",gold:"#a8740a",orange:"#cf5d12",red:"#c62f2f",pink:"#c2387e",purple:"#6a4bc4"}};var blueprint={name:"blueprint",dark:true,background:"#0b2340",bloom:.16,colors:{bg:"#0b2340",surface:"#123054",ink:"#eaf6ff",dim:"#9cc0dc",faint:"#5d86a8",grid:"#1a3f66",gridStrong:"#2c5f8e",blue:"#7fd4ff",teal:"#6fe6d6",green:"#9de8a4",yellow:"#ffe27a",gold:"#f5c566",orange:"#ffb27a",red:"#ff8d8d",pink:"#ffa8cf",purple:"#c5b4ff"}};var chalk={name:"chalk",dark:true,background:"#10201b",bloom:.1,colors:{bg:"#10201b",surface:"#172c25",ink:"#f4f1e4",dim:"#b1b9a9",faint:"#67786d",grid:"#20392f",gridStrong:"#355547",blue:"#8ccbe8",teal:"#7dd9c1",green:"#a9dc8f",yellow:"#f6dd7c",gold:"#e6bf62",orange:"#f2a874",red:"#ee8a80",pink:"#efa2c2",purple:"#bfa9e6"}};var neon={name:"neon",dark:true,background:"#050507",bloom:.4,colors:{bg:"#050507",surface:"#101016",ink:"#ffffff",dim:"#a9a9b8",faint:"#55555f",grid:"#1a1f2e",gridStrong:"#2f3a55",blue:"#3fb2ff",teal:"#21f0d0",green:"#6dff8e",yellow:"#fff04d",gold:"#ffc22e",orange:"#ff8a2e",red:"#ff4560",pink:"#ff5fb0",purple:"#a56bff"}};var LOOKS={midnight,paper,blueprint,chalk,neon};function resolveLook(look){if(look===void 0)return midnight;if(typeof look!=="string")return look;const found=LOOKS[look];if(!found)throw new Error(`Unknown look: ${JSON.stringify(look)}. Use one of: ${Object.keys(LOOKS).join(", ")}.`);return found}var TRANSPARENT=[0,0,0,0];var cache=new Map;var tokens2=midnight.colors;function setColorTokens(next){tokens2=next}function parseColor(input){const token=tokens2[input];const value=token??input;const cached=cache.get(value);if(cached)return cached;const parsed=parseCssColor5(value);if(!parsed)throw new Error(`Unknown color: ${JSON.stringify(input)}. Use a look token such as "blue" or a CSS color.`);let[r,g,b]=parsed.values;if(parsed.type==="hsl")[r,g,b]=hslToRgb3(r,g,b);const result=[r,g,b,parsed.alpha];cache.set(value,result);return result}function hslToRgb3(h,s,l){const a=s/100*Math.min(l/100,1-l/100);const f=n=>{const k=(n+h/30)%12;return 255*(l/100-a*Math.max(-1,Math.min(k-3,9-k,1)))};return[f(0),f(8),f(4)]}function toPaint(input){if(typeof input==="string")return parseColor(input);return input}function isGradient(paint){return!Array.isArray(paint)}function css(color,alpha3=1){const a=color[3]*alpha3;const r=Math.round(color[0]),g=Math.round(color[1]),b=Math.round(color[2]);if(a>=1)return`rgb(${r},${g},${b})`;return`rgba(${r},${g},${b},${Math.round(a*1e3)/1e3})`}function srgbToLinear(v){const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)}function linearToSrgb(v){const x=v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055;return Math.max(0,Math.min(255,x*255))}function toOklab(c){const r=srgbToLinear(c[0]),g=srgbToLinear(c[1]),b=srgbToLinear(c[2]);const l=Math.cbrt(.4122214708*r+.5363325363*g+.0514459929*b);const m=Math.cbrt(.2119034982*r+.6806995451*g+.1073969566*b);const s=Math.cbrt(.0883024619*r+.2817188376*g+.6299787005*b);return[.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s]}function fromOklab(lab,alpha3){const l=lab[0]+.3963377774*lab[1]+.2158037573*lab[2];const m=lab[0]-.1055613458*lab[1]-.0638541728*lab[2];const s=lab[0]-.0894841775*lab[1]-1.291485548*lab[2];const ll=l*l*l,mm=m*m*m,ss=s*s*s;return[linearToSrgb(4.0767416621*ll-3.3077115913*mm+.2309699292*ss),linearToSrgb(-1.2684380046*ll+2.6097574011*mm-.3413193965*ss),linearToSrgb(-.0041960863*ll-.7034186147*mm+1.707614701*ss),alpha3]}function mixColor(a,b,t){if(t<=0)return a;if(t>=1)return b;const x=toOklab(a),y=toOklab(b);return fromOklab([x[0]+(y[0]-x[0])*t,x[1]+(y[1]-x[1])*t,x[2]+(y[2]-x[2])*t],a[3]+(b[3]-a[3])*t)}function mixPaint(a,b,t){if(t<=0)return a;if(t>=1)return b;const ga=isGradient(a),gb=isGradient(b);if(!ga&&!gb)return mixColor(a,b,t);if(ga&&gb&&a.type===b.type&&a.stops.length===b.stops.length){const stops=a.stops.map((stop,i)=>[stop[0]+(b.stops[i][0]-stop[0])*t,mixColor(stop[1],b.stops[i][1],t)]);if(a.type==="linear"&&b.type==="linear"){return{type:"linear",stops,from:[a.from[0]+(b.from[0]-a.from[0])*t,a.from[1]+(b.from[1]-a.from[1])*t],to:[a.to[0]+(b.to[0]-a.to[0])*t,a.to[1]+(b.to[1]-a.to[1])*t]}}if(a.type==="radial"&&b.type==="radial"){return{type:"radial",stops,center:[a.center[0]+(b.center[0]-a.center[0])*t,a.center[1]+(b.center[1]-a.center[1])*t],radius:a.radius+(b.radius-a.radius)*t}}return{type:"along",stops}}const solidA=ga?sampleStops(a.stops,.5):a;const solidB=gb?sampleStops(b.stops,.5):b;return mixColor(solidA,solidB,t)}function sampleStops(stops,at){if(stops.length===0)return TRANSPARENT;if(at<=stops[0][0])return stops[0][1];for(let i=1;i<stops.length;i++){if(at<=stops[i][0]){const[p0,c0]=stops[i-1],[p1,c1]=stops[i];return mixColor(c0,c1,p1>p0?(at-p0)/(p1-p0):0)}}return stops[stops.length-1][1]}function normalizeStops(colors2){const count=colors2.length;return colors2.map((entry,i)=>{if(Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="number"){return[entry[0],solid(entry[1])]}return[count===1?0:i/(count-1),solid(entry)]})}function solid(input){const paint=toPaint(input);return isGradient(paint)?sampleStops(paint.stops,.5):paint}function linearGradient(from,to2,colors2){return{type:"linear",from,to:to2,stops:normalizeStops(colors2)}}function radialGradient(center2,radius,colors2){return{type:"radial",center:center2,radius,stops:normalizeStops(colors2)}}function along(...colors2){return{type:"along",stops:normalizeStops(colors2)}}function ramp(count,...colors2){const stops=normalizeStops(colors2);return Array.from({length:count},(_,i)=>sampleStops(stops,count===1?0:i/(count-1)))}var IDENTITY=[1,0,0,1,0,0];var EMPTY_BOUNDS={x:0,y:0,width:0,height:0};var KAPPA=.5522847498307936;var LUT_STEPS=10;function mul(m,n){return[m[0]*n[0]+m[2]*n[1],m[1]*n[0]+m[3]*n[1],m[0]*n[2]+m[2]*n[3],m[1]*n[2]+m[3]*n[3],m[0]*n[4]+m[2]*n[5]+m[4],m[1]*n[4]+m[3]*n[5]+m[5]]}function invert(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return IDENTITY;const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function apply(m,x,y){return[m[0]*x+m[2]*y+m[4],m[1]*x+m[3]*y+m[5]]}function compose(x,y,rotation,sx,sy,px,py){const cos=rotation===0?1:Math.cos(rotation);const sin=rotation===0?0:Math.sin(rotation);const a=cos*sx;const b=sin*sx;const c=-sin*sy;const d=cos*sy;return[a,b,c,d,x-a*px-c*py,y-b*px-d*py]}function matScale(m){return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2]))}function ring(points,closed=false){return{p:points instanceof Float64Array?points:Float64Array.from(points),closed}}function segmentCount(r){return Math.max(0,(r.p.length-2)/6)}function lineInto(out,x0,y0,x1,y1){out.push(x0+(x1-x0)/3,y0+(y1-y0)/3,x0+(x1-x0)*2/3,y0+(y1-y0)*2/3,x1,y1)}function linePath(a,b){const out=[a[0],a[1]];lineInto(out,a[0],a[1],b[0],b[1]);return[ring(out)]}function polyPath(points,closed=false){if(points.length===0)return[];const first=points[0];const out=[first[0],first[1]];for(let i=1;i<points.length;i++)lineInto(out,points[i-1][0],points[i-1][1],points[i][0],points[i][1]);if(closed){const last=points[points.length-1];if(last[0]!==first[0]||last[1]!==first[1])lineInto(out,last[0],last[1],first[0],first[1])}return[ring(out,closed)]}function smoothPath(points,closed=false,tension=1/6){const n=points.length;if(n===0)return[];if(n<3)return polyPath(points,closed);const at=i=>closed?points[(i+n)%n]:points[Math.max(0,Math.min(n-1,i))];const out=[points[0][0],points[0][1]];const count=closed?n:n-1;for(let i=0;i<count;i++){const p0=at(i-1),p1=at(i),p2=at(i+1),p3=at(i+2);out.push(p1[0]+(p2[0]-p0[0])*tension,p1[1]+(p2[1]-p0[1])*tension,p2[0]-(p3[0]-p1[0])*tension,p2[1]-(p3[1]-p1[1])*tension,p2[0],p2[1])}return[ring(out,closed)]}function arcPath(cx,cy,rx,ry,from,to2){const sweep=to2-from;if(sweep===0)return[];const closed=Math.abs(Math.abs(sweep)-Math.PI*2)<1e-9;const count=Math.max(1,Math.ceil(Math.abs(sweep)/(Math.PI/4)-1e-9));const step=sweep/count;const k=4/3*Math.tan(step/4);const out=[cx+Math.cos(from)*rx,cy+Math.sin(from)*ry];for(let i=0;i<count;i++){const a0=from+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);out.push(cx+(c0-k*s0)*rx,cy+(s0+k*c0)*ry,cx+(c1+k*s1)*rx,cy+(s1-k*c1)*ry,cx+c1*rx,cy+s1*ry)}if(closed){out[out.length-2]=out[0];out[out.length-1]=out[1]}return[ring(out,closed)]}function circlePath(cx,cy,r){return arcPath(cx,cy,r,r,0,Math.PI*2)}function rectPath(x,y,width,height,radius=0){const r=Math.max(0,Math.min(radius,Math.abs(width)/2,Math.abs(height)/2));if(r===0)return polyPath([[x,y],[x+width,y],[x+width,y+height],[x,y+height]],true);const k=r*(1-KAPPA);const right=x+width,bottom=y+height;const out=[x+r,y];lineInto(out,x+r,y,right-r,y);out.push(right-k,y,right,y+k,right,y+r);lineInto(out,right,y+r,right,bottom-r);out.push(right,bottom-k,right-k,bottom,right-r,bottom);lineInto(out,right-r,bottom,x+r,bottom);out.push(x+k,bottom,x,bottom-k,x,bottom-r);lineInto(out,x,bottom-r,x,y+r);out.push(x,y+k,x+k,y,x+r,y);return[ring(out,true)]}function parametricPath(f,from,to2,samples=64){const count=Math.max(2,Math.floor(samples));const points=[];for(let i=0;i<=count;i++)points.push(f(from+(to2-from)*i/count));return curveThrough(points)}function curveThrough(points){const rings=[];let run2=[];const flush=()=>{if(run2.length>=2)rings.push(...smoothPath(run2));run2=[]};for(const point of points){if(Number.isFinite(point[0])&&Number.isFinite(point[1]))run2.push(point);else flush()}flush();return rings}function concat(...paths){return paths.flat()}function transformPath(path,m){if(m===IDENTITY)return path;const out=new Array(path.length);for(let r=0;r<path.length;r++){const src=path[r].p;const dst=new Float64Array(src.length);for(let i=0;i<src.length;i+=2){const x=src[i],y=src[i+1];dst[i]=m[0]*x+m[2]*y+m[4];dst[i+1]=m[1]*x+m[3]*y+m[5]}out[r]={p:dst,closed:path[r].closed}}return out}function warpPath(path,f,subdivisions=4){const dense=subdivisions>1?path.map(r=>subdivideEach(r,subdivisions)):path;return dense.map(r=>{const count=segmentCount(r);const anchors=[];for(let i=0;i<=count;i++){const mapped=f(r.p[i*6],r.p[i*6+1]);anchors.push(mapped)}const out=[anchors[0][0],anchors[0][1]];for(let i=0;i<count;i++){const c1=f(r.p[i*6+2],r.p[i*6+3]);const c2=f(r.p[i*6+4],r.p[i*6+5]);out.push(c1[0],c1[1],c2[0],c2[1],anchors[i+1][0],anchors[i+1][1])}return ring(out,r.closed)})}function splitInto(src,o,t,left,right){const x0=src[o],y0=src[o+1],x1=src[o+2],y1=src[o+3];const x2=src[o+4],y2=src[o+5],x3=src[o+6],y3=src[o+7];const ax=x0+(x1-x0)*t,ay=y0+(y1-y0)*t;const bx=x1+(x2-x1)*t,by=y1+(y2-y1)*t;const cx=x2+(x3-x2)*t,cy=y2+(y3-y2)*t;const dx=ax+(bx-ax)*t,dy=ay+(by-ay)*t;const ex=bx+(cx-bx)*t,ey=by+(cy-by)*t;const fx=dx+(ex-dx)*t,fy=dy+(ey-dy)*t;left.push(ax,ay,dx,dy,fx,fy);right.length=0;right.push(fx,fy,ex,ey,cx,cy,x3,y3)}function subdivideEach(r,n){const count=segmentCount(r);if(n<=1||count===0)return r;const out=[r.p[0],r.p[1]];for(let i=0;i<count;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));for(let k=n;k>1;k--){const rest=[];splitInto(seg,0,1/k,out,rest);seg=rest}out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,r.closed)}var measures=new WeakMap;function measure(r){const cached=measures.get(r);if(cached)return cached;const count=segmentCount(r);const total=new Float64Array(count);const lut=new Float64Array(count*LUT_STEPS);let sum=0;const p=r.p;for(let i=0;i<count;i++){const o=i*6;const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3],x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];let lastX=x0,lastY=y0,acc=0;for(let k=1;k<=LUT_STEPS;k++){const t=k/LUT_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;acc+=Math.hypot(x-lastX,y-lastY);lut[i*LUT_STEPS+k-1]=acc;lastX=x;lastY=y}sum+=acc;total[i]=sum}const result={total,lut,length:sum};measures.set(r,result);return result}function ringLength(r){return measure(r).length}function pathLength(path){let sum=0;for(const r of path)sum+=measure(r).length;return sum}function locate(m,distance){const count=m.total.length;if(count===0)return[0,0];if(distance<=0)return[0,0];if(distance>=m.length)return[count-1,1];let lo=0,hi=count-1;while(lo<hi){const mid=lo+hi>>1;if(m.total[mid]<distance)lo=mid+1;else hi=mid}const before=lo===0?0:m.total[lo-1];const local=distance-before;const base=lo*LUT_STEPS;let k=0;while(k<LUT_STEPS-1&&m.lut[base+k]<local)k++;const start=k===0?0:m.lut[base+k-1];const end=m.lut[base+k];const fraction=end>start?(local-start)/(end-start):0;return[lo,(k+fraction)/LUT_STEPS]}function trimRing(r,from,to2){const count=segmentCount(r);if(count===0)return null;const a=Math.max(0,Math.min(1,from));const b=Math.max(0,Math.min(1,to2));if(b<=a)return null;if(a===0&&b===1)return r;const m=measure(r);if(m.length===0)return null;const[i0,t0]=locate(m,a*m.length);const[i1,t1]=locate(m,b*m.length);const out=[];for(let i=i0;i<=i1;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));const start=i===i0?t0:0;const end=i===i1?t1:1;if(start>0){const rest=[];splitInto(seg,0,start,[],rest);seg=rest}if(end<1){const left=[];const rest=[];const scaled=start>0?(end-start)/(1-start):end;splitInto(seg,0,scaled,left,rest);seg=[seg[0],seg[1],...left]}if(out.length===0)out.push(seg[0],seg[1]);out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,false)}function trimPath(path,from,to2,each=false){if(from<=0&&to2>=1)return path;const out=[];if(each){for(const r of path){const piece=trimRing(r,from,to2);if(piece)out.push(piece)}return out}const total=pathLength(path);if(total===0)return[];let travelled=0;for(const r of path){const length=ringLength(r);const start=(from*total-travelled)/(length||1);const end=(to2*total-travelled)/(length||1);travelled+=length;if(end<=0||start>=1)continue;const piece=trimRing(r,Math.max(0,start),Math.min(1,end));if(piece)out.push(piece)}return out}function pointAt(path,fraction){const total=pathLength(path);if(total===0){const first=path[0]?.p;return first?[first[0],first[1]]:[0,0]}let remaining=Math.max(0,Math.min(1,fraction))*total;for(let i=0;i<path.length;i++){const r=path[i];const length=ringLength(r);if(remaining<=length||i===path.length-1){const[segment,t]=locate(measure(r),remaining);return evaluate(r.p,segment*6,t)}remaining-=length}return[0,0]}function tangentAt(path,fraction){const delta=.002;const a=pointAt(path,Math.max(0,fraction-delta));const b=pointAt(path,Math.min(1,fraction+delta));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return[(b[0]-a[0])/length,(b[1]-a[1])/length]}function evaluate(p,o,t){const u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;return[a*p[o]+b*p[o+2]+c*p[o+4]+d*p[o+6],a*p[o+1]+b*p[o+3]+c*p[o+5]+d*p[o+7]]}function extendCubicAxis(range,p0,p1,p2,p3){range[0]=Math.min(range[0],p0,p3);range[1]=Math.max(range[1],p0,p3);if(p1>=range[0]&&p1<=range[1]&&p2>=range[0]&&p2<=range[1])return;const a=-p0+3*p1-3*p2+p3;const b=2*(p0-2*p1+p2);const c=p1-p0;const roots=[];if(Math.abs(a)<1e-9){if(Math.abs(b)>1e-9)roots.push(-c/b)}else{const disc=b*b-4*a*c;if(disc>=0){const s=Math.sqrt(disc);roots.push((-b+s)/(2*a),(-b-s)/(2*a))}}for(const t of roots){if(t<=0||t>=1)continue;const u=1-t;const value=u*u*u*p0+3*u*u*t*p1+3*u*t*t*p2+t*t*t*p3;range[0]=Math.min(range[0],value);range[1]=Math.max(range[1],value)}}var ringBounds=new WeakMap;function boundsOfRing(r){const cached=ringBounds.get(r);if(cached)return cached;const p=r.p;if(p.length<2)return EMPTY_BOUNDS;const xs=[p[0],p[0]];const ys=[p[1],p[1]];for(let o=0;o+7<p.length;o+=6){extendCubicAxis(xs,p[o],p[o+2],p[o+4],p[o+6]);extendCubicAxis(ys,p[o+1],p[o+3],p[o+5],p[o+7])}const bounds4={x:xs[0],y:ys[0],width:xs[1]-xs[0],height:ys[1]-ys[0]};ringBounds.set(r,bounds4);return bounds4}function pathBounds(path){if(path.length===0)return null;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const r of path){if(r.p.length<2)continue;const b=boundsOfRing(r);minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height)}if(minX===Infinity)return null;return{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}function unionBounds(a,b){if(!a)return b;if(!b)return a;const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function signedArea(r){const p=r.p;let sum=0;for(let o=0;o+7<p.length;o+=6){sum+=p[o]*p[o+7]-p[o+6]*p[o+1]}return sum/2}function ringCenter(r){const b=boundsOfRing(r);return[b.x+b.width/2,b.y+b.height/2]}function reverseRing(r){const p=r.p;const out=new Float64Array(p.length);for(let i=0;i<p.length;i+=2){out[i]=p[p.length-2-i];out[i+1]=p[p.length-1-i]}return{p:out,closed:r.closed}}function parseSvgPath(d){const tokens4=d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);if(!tokens4)return[];const rings=[];let out=[];let i=0,x=0,y=0,startX=0,startY=0;let lastCmd="",lastCx=0,lastCy=0;const num=()=>Number(tokens4[i++]);const flags=()=>{const token=tokens4[i];if(token.length>1&&(token[0]==="0"||token[0]==="1")&&!token.startsWith("0.")&&!token.startsWith("1.")){tokens4[i]=token.slice(1);return Number(token[0])}i++;return Number(token)};const flush=closed=>{if(out.length>=8)rings.push(ring(out,closed));out=[]};const begin=(px,py)=>{if(out.length===0)out.push(px,py)};let cmd="";while(i<tokens4.length){const token=tokens4[i];if(/^[a-zA-Z]$/.test(token)){cmd=token;i++}else if(cmd==="M"){cmd="L"}else if(cmd==="m"){cmd="l"}else if(cmd===""){throw new Error(`Invalid SVG path data: ${d.slice(0,40)}`)}const rel=cmd>="a";switch(cmd.toUpperCase()){case"M":{flush(false);x=(rel?x:0)+num();y=(rel?y:0)+num();startX=x;startY=y;out.push(x,y);break}case"L":{const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,nx,ny);x=nx;y=ny;break}case"H":{const nx=(rel?x:0)+num();begin(x,y);lineInto(out,x,y,nx,y);x=nx;break}case"V":{const ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,x,ny);y=ny;break}case"C":{const ox=rel?x:0,oy=rel?y:0;const c1x=ox+num(),c1y=oy+num(),c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"S":{const ox=rel?x:0,oy=rel?y:0;const smooth3="CScs".includes(lastCmd);const c1x=smooth3?2*x-lastCx:x,c1y=smooth3?2*y-lastCy:y;const c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"Q":{const ox=rel?x:0,oy=rel?y:0;const qx=ox+num(),qy=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"T":{const ox=rel?x:0,oy=rel?y:0;const smooth3="QTqt".includes(lastCmd);const qx=smooth3?2*x-lastCx:x,qy=smooth3?2*y-lastCy:y;const nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"A":{const rx=num(),ry=num(),angle=num(),large=flags(),sweep=flags();const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);arcInto(out,x,y,rx,ry,angle,large===1,sweep===1,nx,ny);x=nx;y=ny;break}case"Z":{if(out.length>0){if(x!==startX||y!==startY)lineInto(out,x,y,startX,startY);flush(true)}x=startX;y=startY;break}default:throw new Error(`Unsupported SVG path command: ${cmd}`)}lastCmd=cmd}flush(false);return rings}function arcInto(out,x0,y0,rxIn,ryIn,degrees,large,sweep,x1,y1){let rx=Math.abs(rxIn),ry=Math.abs(ryIn);if(rx===0||ry===0||x0===x1&&y0===y1){lineInto(out,x0,y0,x1,y1);return}const phi=degrees*Math.PI/180;const cos=Math.cos(phi),sin=Math.sin(phi);const dx=(x0-x1)/2,dy=(y0-y1)/2;const xp=cos*dx+sin*dy,yp=-sin*dx+cos*dy;const lambda=xp*xp/(rx*rx)+yp*yp/(ry*ry);if(lambda>1){const scale=Math.sqrt(lambda);rx*=scale;ry*=scale}const numerator=rx*rx*ry*ry-rx*rx*yp*yp-ry*ry*xp*xp;const denominator=rx*rx*yp*yp+ry*ry*xp*xp;const factor=(large===sweep?-1:1)*Math.sqrt(Math.max(0,numerator/denominator));const cxp=factor*rx*yp/ry,cyp=-factor*ry*xp/rx;const cx=cos*cxp-sin*cyp+(x0+x1)/2;const cy=sin*cxp+cos*cyp+(y0+y1)/2;const start=Math.atan2((yp-cyp)/ry,(xp-cxp)/rx);let delta=Math.atan2((-yp-cyp)/ry,(-xp-cxp)/rx)-start;if(sweep&&delta<0)delta+=Math.PI*2;if(!sweep&&delta>0)delta-=Math.PI*2;const count=Math.max(1,Math.ceil(Math.abs(delta)/(Math.PI/2)-1e-9));const step=delta/count;const k=4/3*Math.tan(step/4);for(let i=0;i<count;i++){const a0=start+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);const q1x=(c0-k*s0)*rx,q1y=(s0+k*c0)*ry;const q2x=(c1+k*s1)*rx,q2y=(s1-k*c1)*ry;const ex=c1*rx,ey=s1*ry;out.push(cos*q1x-sin*q1y+cx,sin*q1x+cos*q1y+cy,cos*q2x-sin*q2y+cx,sin*q2x+cos*q2y+cy,i===count-1?x1:cos*ex-sin*ey+cx,i===count-1?y1:sin*ex+cos*ey+cy)}}function fmt(value){const rounded=Math.round(value*100)/100;return rounded===0?"0":String(rounded)}function pathToD(path){const parts=[];for(const r of path){const p=r.p;if(p.length<2)continue;parts.push("M",fmt(p[0])," ",fmt(p[1]));if(r.straight){for(let o=2;o+5<p.length;o+=6)parts.push("L",fmt(p[o+4])," ",fmt(p[o+5]));if(r.closed)parts.push("Z");continue}for(let o=2;o+5<p.length;o+=6){parts.push("C",fmt(p[o])," ",fmt(p[o+1])," ",fmt(p[o+2])," ",fmt(p[o+3])," ",fmt(p[o+4])," ",fmt(p[o+5]))}if(r.closed)parts.push("Z")}return parts.join("")}var clock={now:0,mode:"free",frame:0,capture:null};var Track=class{constructor(initial){this.initial=initial}initial;keys=[];sample(t){const keys=this.keys;let lo=0,hi=keys.length-1,index=-1;while(lo<=hi){const mid=lo+hi>>1;if(keys[mid].t0<=t){index=mid;lo=mid+1}else{hi=mid-1}}if(index<0)return this.initial;const key=keys[index];if(t>=key.t1||!key.at)return key.to;const span=key.t1-key.t0;const raw=span>0?(t-key.t0)/span:1;return key.at(key.ease?key.ease(raw):raw)}add(key){const keys=this.keys;let index=keys.length;while(index>0&&keys[index-1].t0>key.t0)index--;keys.splice(index,0,key)}step(t,value){this.add({t0:t,t1:t,ease:null,to:value,at:null})}get end(){let end=0;for(const key of this.keys)if(key.t1>end)end=key.t1;return end}};var clockNow=()=>clock.now;var ALONG_PIECE_LENGTH=14;var MAX_ALONG_PIECES=96;function worldPaint(paint,m){if(!paint||!isGradient(paint))return paint;if(paint.type==="linear"){return{...paint,from:apply(m,paint.from[0],paint.from[1]),to:apply(m,paint.to[0],paint.to[1])}}if(paint.type==="radial"){return{...paint,center:apply(m,paint.center[0],paint.center[1]),radius:paint.radius*matScale(m)}}return paint}function sameMatrix(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]}var worldCache=new WeakMap;function toWorld(node,path,m){const cached=worldCache.get(node);if(cached&&cached.path===path&&sameMatrix(cached.matrix,m))return cached.world;const world=transformPath(path,m);worldCache.set(node,{path,matrix:m,world});return world}function emit(node,path,m,alpha3,ops){const fill=node.get("fill");const stroke=node.get("stroke");const fillAlpha=fill?alpha3*node.get("fillOpacity"):0;const strokeAlpha=stroke?alpha3*node.get("strokeOpacity"):0;const glow=node.get("glow");if(fillAlpha<=.002&&strokeAlpha<=.002&&glow<=0)return;const world=toWorld(node,path,m);const scale=matScale(m);const trimFrom=node.get("trimFrom"),trimTo=node.get("trimTo");let strokePath=world;if(trimFrom>0||trimTo<1)strokePath=trimPath(world,trimFrom,trimTo,node.get("trimEach"));if(strokePath.length===0&&fillAlpha<=.002)return;const dash=node.get("dash");const op={kind:"path",path:world,strokePath,fill:fillAlpha>.002?worldPaint(fill,m):null,fillAlpha,stroke:strokeAlpha>.002?worldPaint(stroke,m):null,strokeAlpha,strokeWidth:node.get("strokeWidth")*scale,cap:node.get("cap"),join:node.get("join"),dash:dash?dash.map(value=>value*scale):null,dashOffset:node.get("dashOffset")*scale,glow:glow*scale,glowColor:node.get("glowColor"),blend:node.get("blend"),node};if(op.stroke&&isGradient(op.stroke)&&op.stroke.type==="along")splitAlong(op,op.stroke,ops);else ops.push(op)}function splitAlong(op,paint,ops){ops.push({...op,stroke:null,strokeAlpha:0});const glowless={...op,fill:null,fillAlpha:0,glow:0};const length=pathLength(op.strokePath);const full=pathLength(op.path);if(length===0)return;const fraction=full>0?Math.min(1,length/full):1;const pieces=Math.min(MAX_ALONG_PIECES,Math.max(2,Math.ceil(length/ALONG_PIECE_LENGTH)));const overlap=.6/pieces;for(let i=0;i<pieces;i++){const from=i/pieces,to2=Math.min(1,(i+1)/pieces+overlap);const piece=trimPath(op.strokePath,from,to2);if(piece.length===0)continue;ops.push({...glowless,strokePath:piece,path:piece,stroke:sampleStops(paint.stops,(i+.5)/pieces*fraction),cap:i===0||i===pieces-1?op.cap:"butt"})}}function walk(node,parent,screen,alpha3,ops){if(!node.get("visible"))return;const opacity=node.get("opacity")*alpha3;if(opacity<=.002)return;const base=node.get("fixed")?screen:parent;const m=mul(base,node.localMatrix());const path=node.get("path");if(path&&path.length>0)emit(node,path,m,opacity,ops);const image=node.get("image");if(image)ops.push({kind:"image",image,matrix:m,alpha:opacity});if(node.rawOps)node.rawOps(m,opacity,ops);if(node.draw){const built=node.draw(clockNow());if(built){const list3=Array.isArray(built)?built:[built];for(const child of list3)walk(child,m,screen,opacity,ops)}}const children=node.children;if(children.length===0)return;let sorted=false;for(let i=0;i<children.length;i++){if(children[i].get("z")!==0){sorted=true;break}}const ordered=sorted?children.map((child,index)=>({child,index,z:child.get("z")})).sort((a,b)=>a.z-b.z||a.index-b.index).map(entry=>entry.child):children;for(const child of ordered)walk(child,m,screen,opacity,ops)}function buildOps(root,camera,width,height){const screen=[1,0,0,1,width/2,height/2];const view=mul(screen,compose(0,0,-camera.rotation,camera.zoom,camera.zoom,camera.x,camera.y));const ops=[];walk(root,view,screen,1,ops);return ops}var GLOW_PASSES=7;function glowPasses(glow,width){const out=[];for(let i=GLOW_PASSES;i>=1;i--){const k=i/GLOW_PASSES;out.push({width:width+glow*2*k,alpha:.16*(1-k)*(1-k)+.018})}return out}function glowOf(op){if(op.glowColor)return op.glowColor;const paint=op.stroke??op.fill;if(!paint)return null;return isGradient(paint)?sampleStops(paint.stops,.5):paint}var dCache=new WeakMap;function pathData(path){let d=dCache.get(path);if(d===void 0){d=pathToD(path);dCache.set(path,d)}return d}function fmt2(value){return String(Math.round(value*1e3)/1e3)}function gradientDef(id,paint){const stops=paint.stops.map(([at,color])=>`<stop offset="${fmt2(at)}" stop-color="${css([color[0],color[1],color[2],1])}"${color[3]<1?` stop-opacity="${fmt2(color[3])}"`:""}/>`).join("");if(paint.type==="linear"){return`<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`}if(paint.type==="radial"){return`<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`}return""}function strokeAttrs(op){let attrs=` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;if(op.dash)attrs+=` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;return attrs}function escapeAttr(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<")}function frameToSvg(frame,options={}){const scale=options.scale??1;const w=frame.width,h=frame.height;const defs=[];const body=[];let gradientCount=0;const paintAttr=(paint,attr,alpha3)=>{if(isGradient(paint)){const id=`g${gradientCount++}`;defs.push(gradientDef(id,paint));return`${attr}="url(#${id})"${alpha3<1?` ${attr}-opacity="${fmt2(alpha3)}"`:""}`}const rgba=paint;const a=rgba[3]*alpha3;return`${attr}="${css([rgba[0],rgba[1],rgba[2],1])}"${a<1?` ${attr}-opacity="${fmt2(a)}"`:""}`};if(frame.background&&!options.transparent)body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);for(const op of frame.ops){if(op.kind==="image"){const m=op.matrix;body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha<1?` opacity="${fmt2(op.alpha)}"`:""} preserveAspectRatio="none"/>`);continue}const style=op.blend!=="normal"?` style="mix-blend-mode:${op.blend}"`:"";if(op.glow>0){const color=glowOf(op);const glowD=pathData(op.strokePath.length?op.strokePath:op.path);if(color&&glowD){const base=Math.max(op.fillAlpha,op.strokeAlpha);const mode=frame.dark?' style="mix-blend-mode:screen"':"";const passes=glowPasses(op.glow,op.stroke?op.strokeWidth:0).map(pass=>`<path d="${glowD}" fill="none" stroke="${css([color[0],color[1],color[2],1])}" stroke-opacity="${fmt2(pass.alpha*base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");body.push(`<g${mode}>${passes}</g>`)}}if(op.fill&&op.stroke&&op.strokePath===op.path){body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)} ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);continue}if(op.fill)body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)}${style}/>`);if(op.stroke&&op.strokePath.length){body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`)}}const defsBlock=defs.length?`<defs>${defs.join("")}</defs>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${w*scale}" height="${h*scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`}var path2dCache=new WeakMap;function ringsToPath2D(path){let cached=path2dCache.get(path);if(cached)return cached;cached=new Path2D;for(const r of path){const p=r.p;if(p.length<2)continue;cached.moveTo(p[0],p[1]);if(r.straight)for(let o=2;o+5<p.length;o+=6)cached.lineTo(p[o+4],p[o+5]);else for(let o=2;o+5<p.length;o+=6)cached.bezierCurveTo(p[o],p[o+1],p[o+2],p[o+3],p[o+4],p[o+5]);if(r.closed)cached.closePath()}path2dCache.set(path,cached);return cached}function canvasPaint(ctx,paint){if(!isGradient(paint))return css(paint);const gradient=paint.type==="linear"?ctx.createLinearGradient(paint.from[0],paint.from[1],paint.to[0],paint.to[1]):paint.type==="radial"?ctx.createRadialGradient(paint.center[0],paint.center[1],0,paint.center[0],paint.center[1],paint.radius):null;if(!gradient)return css(sampleStops(paint.stops,.5));for(const[at,color]of paint.stops)gradient.addColorStop(at,css(color));return gradient}var BLEND={normal:"source-over",screen:"screen",multiply:"multiply",overlay:"overlay"};function paintFrame(ctx,frame,scale=1,images){ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over";ctx.clearRect(0,0,frame.width*scale,frame.height*scale);ctx.setTransform(scale,0,0,scale,0,0);if(frame.background){ctx.fillStyle=frame.background;ctx.fillRect(0,0,frame.width,frame.height)}for(const op of frame.ops){if(op.kind==="image"){const source=images?.(op.image);if(!source)continue;const m=op.matrix;ctx.save();ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]);ctx.globalAlpha=op.alpha;ctx.drawImage(source,0,0,op.image.width,op.image.height);ctx.restore();continue}ctx.globalCompositeOperation=BLEND[op.blend];if(op.glow>0){const color=glowOf(op);if(color){const base=Math.max(op.fillAlpha,op.strokeAlpha);const previous=ctx.globalCompositeOperation;if(frame.dark)ctx.globalCompositeOperation="screen";ctx.strokeStyle=css([color[0],color[1],color[2],1]);ctx.lineCap="round";ctx.lineJoin="round";ctx.setLineDash([]);const glowPath=ringsToPath2D(op.strokePath.length?op.strokePath:op.path);for(const pass of glowPasses(op.glow,op.stroke?op.strokeWidth:0)){ctx.globalAlpha=pass.alpha*base;ctx.lineWidth=pass.width;ctx.stroke(glowPath)}ctx.globalCompositeOperation=previous}}if(op.fill){ctx.globalAlpha=op.fillAlpha;ctx.fillStyle=canvasPaint(ctx,op.fill);ctx.fill(ringsToPath2D(op.path))}if(op.stroke&&op.strokePath.length){ctx.globalAlpha=op.strokeAlpha;ctx.strokeStyle=canvasPaint(ctx,op.stroke);ctx.lineWidth=op.strokeWidth;ctx.lineCap=op.cap;ctx.lineJoin=op.join;ctx.setLineDash(op.dash?[...op.dash]:[]);ctx.lineDashOffset=op.dashOffset;ctx.stroke(ringsToPath2D(op.strokePath))}}ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over"}function frameInkBounds(frame){let result=null;for(const op of frame.ops){if(op.kind!=="path")continue;const b=pathBounds(op.path);if(!b)continue;const pad2=op.stroke?op.strokeWidth/2:0;const next={x:b.x-pad2,y:b.y-pad2,width:b.width+pad2*2,height:b.height+pad2*2};if(!result)result=next;else{const x=Math.min(result.x,next.x),y=Math.min(result.y,next.y);result={x,y,width:Math.max(result.x+result.width,next.x+next.width)-x,height:Math.max(result.y+result.height,next.y+next.height)-y}}}return result}import{createRequire}from"module";import{cpus}from"os";import{Worker}from"worker_threads";import{fileURLToPath}from"url";var RASTER_WORKER_SOURCE=String.raw`
|
|
2
|
+
import{Arrow,ArrowMarkerDef,AttentionMatrix,AxisPlot,Badge,BadgePill,BarChart,Board,Box,CANVAS_ITEM_COMPONENT,CalloutCard,Canvas,CanvasItem,CanvasOverflowError,Card,ChartFrame,CodeBlock,Column,Comparison,Connector,DEFAULT_DENSITY,DENSITY_NAMES,DashedLine,DataTable,DataflowDiagram,DeploymentDiagram,DetailList,DiagramLegend,DonutChart,DotPoint,ELEMENT_SYMBOLS,EntityRelationshipDiagram,EquationCard,FactRows,Flow,FlowArrow,FreeBodyDiagram,GeometryDiagram,GradientChip,GraphDiagram,Grid,Heatmap,Icon,InlineBar,IntervalPlot,KeyValueList,LayeredNetwork,Legend,LineChart,MathText,Matrix,MetricCard,MetricStrip,MiniBarChart,MoleculeDiagram,NumberLine,Panel,ParetoBarChart,ParetoChart,PieChart,Pipeline,PixelGrid,ProgressList,ProgressRow,QuadrantChart,ReactionEnergyDiagram,ReactionEquation,Row,SCENE_LIMITS,SCENE_RUNTIME_VERSION,ScatterPlot,Scene,SequenceDiagram,SmallMultiples,Sparkline,Stack,StackedBar,StatusDot,StatusList,StatusRow,StepCard,SvgFrame,SvgMathText,SvgPoint,TagList,TextLabel,Tile,TileGrid,TiledMatrix,Timeline,TitleBar,ToneStrip,TransformerTopology,TreeDiagram,ValuePill,VectorArrow,VectorSegment,Watermark,WaveDiagram,WindowFrame,analyzeAnimationCadence,assertDensity,canvas,colors,compositeColor,createPlotArea,cropPixels,cropRgbImage,cropRgbRaster,crossCorrelate2d,decodeRgbPng,defineAnimation,defineDiagramIcon,defineIconRegistry,defineIllustration,densityOf,densityTokens,detectBackgroundColor,detectContentBounds,detectLayoutOverflow,detectOverflow,dotProduct,encodePng,encodeRgbPng,entropy,estimateTextWidth,evaluateSceneSource,extractRootJsx,findBareRootJsxStart,flattenRgbImage,formatMathText,formatTensorShape,gaussian,gaussianBlurRgb,gaussianKernel,geometryBounds,getColor,getFonts,getGradient,getReadableColor,getReadableTextColor,getReadableToneColor,getStyles,getThemeColors,getToneColor,getToneFill,getToneGradient,gradients,hasShadow,heatColor,hold,keyframe,lerpArray,loadAdditionalAsset,mapNumberLine,multiplyMatrices,normalizeVector,normalizeWatermark,parallel,parseDensity,pointAlongSamples,prepareScene,primitives_exports,reactionBalance,renderAnimationVideo,renderRgbaVideo,renderSceneFrame,renderSceneVideo,renderToBuffer,renderToPng,renderToPngWithOutput,renderToSvg,rgbChannel,routeOrthogonalGraph,routingSegmentBlocked,sampleAnimation,sampleAnimationFrame,sampleAnimationFrames,sampleFunction,sampleGaussian,sampleWave,satori,scaledDotProductAttention,scopeDensity,seededRandom,setDefaultDensity,setDensityResolver,stableSoftmax,statusColor,styles,sumForces,toneGradients,transposeMatrix,tween,typeOf,typography,videoFrameSchedule,waveValue,withColorAlpha,withDensity,withRenderContext,wrapWithBrand,wrapWithWatermark}from"./chunk-3LQLKLGH.js";import{renderMathSvg}from"./chunk-3F2VQ7NW.js";import{__export}from"./chunk-PSBF4TEK.js";import{existsSync as existsSync2}from"fs";import{mkdir as mkdir4,mkdtemp as mkdtemp2,readFile,readdir,rm as rm2,writeFile as writeFile4}from"fs/promises";import{randomUUID}from"crypto";import{createRequire as createRequire2,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename as basename2,dirname as dirname4,extname as extname2,isAbsolute,join as join3,relative as relative2,resolve as resolve3,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React,{isValidElement as isValidElement2}from"react";import{Resvg as Resvg2}from"@resvg/resvg-js";var index_exports={};__export(index_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AttentionMatrix:()=>AttentionMatrix,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,DEFAULT_DENSITY:()=>DEFAULT_DENSITY,DENSITY_NAMES:()=>DENSITY_NAMES,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DiagramLegend:()=>DiagramLegend,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,ELEMENT_SYMBOLS:()=>ELEMENT_SYMBOLS,EntityRelationshipDiagram:()=>EntityRelationshipDiagram,EquationCard:()=>EquationCard,FactRows:()=>FactRows,Flow:()=>Flow,FlowArrow:()=>FlowArrow,FreeBodyDiagram:()=>FreeBodyDiagram,GeometryDiagram:()=>GeometryDiagram,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,InlineBar:()=>InlineBar,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MetricStrip:()=>MetricStrip,MiniBarChart:()=>MiniBarChart,MoleculeDiagram:()=>MoleculeDiagram,NumberLine:()=>NumberLine,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,PixelGrid:()=>PixelGrid,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,ReactionEnergyDiagram:()=>ReactionEnergyDiagram,ReactionEquation:()=>ReactionEquation,Row:()=>Row,SCENE_LIMITS:()=>SCENE_LIMITS,SCENE_RUNTIME_VERSION:()=>SCENE_RUNTIME_VERSION,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,SmallMultiples:()=>SmallMultiples,Sparkline:()=>Sparkline,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusDot:()=>StatusDot,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TagList:()=>TagList,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,WaveDiagram:()=>WaveDiagram,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,arcSwap:()=>arcSwap,assertDensity:()=>assertDensity,assertTokenHistoryTransition:()=>assertTokenHistoryTransition,byteDifferenceState:()=>byteDifferenceState,cameraSvgTransform:()=>cameraSvgTransform,canvas:()=>canvas,categoricalSampling:()=>categoricalSampling,checkFrame:()=>checkFrame,colors:()=>colors,compareByteSequences:()=>compareByteSequences,compositeColor:()=>compositeColor,createCanvasComponents:()=>createCanvasComponents,createCueTrack:()=>createCueTrack,createFocusDirector:()=>createFocusDirector,createPlotArea:()=>createPlotArea,createPolylineMorph:()=>createPolylineMorph,createTeachingByteDifference:()=>createTeachingByteDifference,createTeachingCanvas:()=>createTeachingCanvas,createTeachingCategoricalSampling:()=>createTeachingCategoricalSampling,createTeachingFocus:()=>createTeachingFocus,createTeachingRoutedTransfer:()=>createTeachingRoutedTransfer,createTeachingTokenHistory:()=>createTeachingTokenHistory,createTeachingValueChange:()=>createTeachingValueChange,createTeachingVectorAccumulation:()=>createTeachingVectorAccumulation,cropPixels:()=>cropPixels,cropRgbImage:()=>cropRgbImage,cropRgbRaster:()=>cropRgbRaster,crossCorrelate2d:()=>crossCorrelate2d,decodeRgbPng:()=>decodeRgbPng,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,densityOf:()=>densityOf,densityTokens:()=>densityTokens,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectLayoutOverflow:()=>detectLayoutOverflow,detectOverflow:()=>detectOverflow,dotProduct:()=>dotProduct,encodeRgbPng:()=>encodeRgbPng,entropy:()=>entropy,escapedByte:()=>escapedByte,estimateTextWidth:()=>estimateTextWidth,evaluateSceneSource:()=>evaluateSceneSource,flattenRgbImage:()=>flattenRgbImage,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,gaussian:()=>gaussian,gaussianBlurRgb:()=>gaussianBlurRgb,gaussianKernel:()=>gaussianKernel,geometryBounds:()=>geometryBounds,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,hasShadow:()=>hasShadow,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,interpolateCamera:()=>interpolateCamera,keyframe:()=>keyframe,layoutAllocation:()=>layoutAllocation,layoutByteDifference:()=>layoutByteDifference,layoutCellGrid:()=>layoutCellGrid,layoutTokenRow:()=>layoutTokenRow,lerpArray:()=>lerpArray,loadAdditionalAsset:()=>loadAdditionalAsset,mapNumberLine:()=>mapNumberLine,mergeFocusRegions:()=>mergeFocusRegions,morphPolyline:()=>morphPolyline,multiplyMatrices:()=>multiplyMatrices,normalizeVector:()=>normalizeVector,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,parseDensity:()=>parseDensity,planTeachingRoutedTransfer:()=>planTeachingRoutedTransfer,pointAlongPath:()=>pointAlongPath,prepareScene:()=>prepareScene,projectWorldPoint:()=>projectWorldPoint,reactionBalance:()=>reactionBalance,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderAnimationVideo:()=>renderAnimationVideo,renderMathSvg:()=>renderMathSvg,renderRgbaVideo:()=>renderRgbaVideo,renderSceneFrame:()=>renderSceneFrame,renderSceneVideo:()=>renderSceneVideo,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,rgbChannel:()=>rgbChannel,sampleAnimation:()=>sampleAnimation,sampleAnimationFrame:()=>sampleAnimationFrame,sampleAnimationFrames:()=>sampleAnimationFrames,sampleFunction:()=>sampleFunction,sampleGaussian:()=>sampleGaussian,sampleWave:()=>sampleWave,scaledDotProductAttention:()=>scaledDotProductAttention,scopeDensity:()=>scopeDensity,seededRandom:()=>seededRandom,setDefaultDensity:()=>setDefaultDensity,setDensityResolver:()=>setDensityResolver,smoothstep:()=>smoothstep,stableSoftmax:()=>stableSoftmax,statusColor:()=>statusColor,styles:()=>styles,sumForces:()=>sumForces,tokenHistoryState:()=>tokenHistoryState,toneGradients:()=>toneGradients,tracePolyline:()=>tracePolyline,transposeMatrix:()=>transposeMatrix,tween:()=>tween,typeOf:()=>typeOf,typography:()=>typography,valueChangeState:()=>valueChangeState,videoFrameSchedule:()=>videoFrameSchedule,waveValue:()=>waveValue,weightedVectorState:()=>weightedVectorState,withColorAlpha:()=>withColorAlpha,withDensity:()=>withDensity,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import{Resvg}from"@resvg/resvg-js";import{mkdir,writeFile}from"fs/promises";import{dirname}from"path";import*as gifenc from"gifenc";import parseCssColor from"parse-css-color";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 fonts2=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts:fonts2,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg(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=detectLayoutOverflow2(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow2(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=parseCssColor(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 bounds4=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds4||bounds4.width===frame.width&&bounds4.height===frame.height)return frame;return{...frame,x:bounds4.x,y:bounds4.y,delta:true,width:bounds4.width,height:bounds4.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds4)}}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 pending2;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(pending2&&pixelsEqual(pending2.pixels,frame.pixels)){pending2.delay+=frame.delay;continue}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending2={...frame}}if(pending2){const encoded=deltaPixelFrame(pending2,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 delay2=(cumulative-previous)*10;previous=cumulative;return delay2})}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 amount2=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount2):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount2);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 mkdir(dirname(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 writeFile(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 delay2=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay2),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-=delay2}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 pending2;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(pending2&&pixelsEqual(pending2.pixels,rendered.pixels)){pending2.delay+=sampled.frame.delay;continue}if(pending2){const encoded2=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending2={...rendered,delay:sampled.frame.delay}}if(!pending2||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir(dirname(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}var DEFAULT_ARC_LIFT=80;function assertFiniteProgress(progress){if(!Number.isFinite(progress))throw new Error("Motion progress must be finite")}function clampProgress(progress){assertFiniteProgress(progress);return Math.max(0,Math.min(1,progress))}function assertPoint(point,context){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} coordinates must be finite`)}}function interpolate(from,to2,progress){return{x:from.x*(1-progress)+to2.x*progress,y:from.y*(1-progress)+to2.y*progress}}function smoothstep(progress){const amount2=clampProgress(progress);return amount2*amount2*(3-2*amount2)}function arcSwap(from,to2,progress,options={}){assertPoint(from,"Arc swap start");assertPoint(to2,"Arc swap end");const amount2=clampProgress(progress);const lift=options.lift??DEFAULT_ARC_LIFT;if(!Number.isFinite(lift))throw new Error("Arc swap lift must be finite");if(amount2===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(amount2===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Motion easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(t===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const dx=to2.x-from.x;const dy=to2.y-from.y;const length=Math.hypot(dx,dy);if(!Number.isFinite(length))throw new Error("Arc swap distance must be finite");if(length===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];const normalX=-dy/length;const normalY=dx/length;const arcHeight=4*(1-t)*t*lift;const firstBase=interpolate(from,to2,t);const secondBase=interpolate(to2,from,t);const first={x:firstBase.x+normalX*arcHeight,y:firstBase.y+normalY*arcHeight};const second={x:secondBase.x-normalX*arcHeight,y:secondBase.y-normalY*arcHeight};assertPoint(first,"Arc swap result");assertPoint(second,"Arc swap result");return[first,second]}function pathLengths(points){const lengths=[];let total=0;for(let index=0;index<points.length;index+=1){const point=points[index];assertPoint(point,`Path point ${index}`);if(index===0)continue;const previous=points[index-1];const length=Math.hypot(point.x-previous.x,point.y-previous.y);if(!Number.isFinite(length))throw new Error("Path segment length must be finite");total+=length;if(!Number.isFinite(total))throw new Error("Path length must be finite");lengths.push(length)}return lengths}function tracePolyline(points,progress){const amount2=clampProgress(progress);if(points.length===0)return[];const lengths=pathLengths(points);if(amount2===1)return points.map(({x,y})=>({x,y}));const traced2=[{x:points[0].x,y:points[0].y}];if(amount2===0||lengths.length===0)return traced2;const total=lengths.reduce((sum,length)=>sum+length,0);if(total===0)return traced2;const target=total*amount2;let travelled=0;for(let index=0;index<lengths.length;index+=1){const segmentLength=lengths[index];const next=points[index+1];if(segmentLength===0)continue;const segmentEnd=travelled+segmentLength;if(target>=segmentEnd){traced2.push({x:next.x,y:next.y});travelled=segmentEnd;continue}const segmentProgress=(target-travelled)/segmentLength;const point=interpolate(points[index],next,segmentProgress);assertPoint(point,"Polyline trace result");const previous=traced2[traced2.length-1];if(point.x!==previous.x||point.y!==previous.y)traced2.push(point);return traced2}return traced2}function pointAlongPath(points,progress){if(points.length===0)throw new Error("Cannot find a point along an empty path");const traced2=tracePolyline(points,progress);return{...traced2[traced2.length-1]}}function finite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative(value,name){finite(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function positive(value,name){finite(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function normalizedOpacity(value,name="Canvas opacity"){finite(value,name);return Math.max(0,Math.min(1,value))}function validateBounds(bounds4){finite(bounds4.x,"Canvas x");finite(bounds4.y,"Canvas y");positive(bounds4.width,"Canvas width");positive(bounds4.height,"Canvas height");nonnegative(bounds4.radius??14,"Canvas radius")}function layoutTokenRow(values,options={}){const{advance=24,gap=16,minWidth=64,paddingX=17,width}=options;nonnegative(advance,"Token advance");nonnegative(gap,"Token gap");positive(minWidth,"Token minimum width");nonnegative(paddingX,"Token horizontal padding");if(width!==void 0)positive(width,"Token width");if(options.x!==void 0)finite(options.x,"Token x");if(options.centerX!==void 0)finite(options.centerX,"Token center x");const items=values.map(value=>{const text2=String(value);return{text:text2,x:0,width:width??Math.max(minWidth,text2.length*advance+2*paddingX)}});const totalWidth=items.reduce((total,item)=>total+item.width,0)+Math.max(0,items.length-1)*gap;let x=options.x??(options.centerX??0)-totalWidth/2;finite(x,"Token row origin");for(const item of items){item.x=x;x+=item.width+gap;finite(x,"Token row extent")}return items}function createCanvasComponents(painter){function fade2(alpha3,draw2){const amount2=normalizedOpacity(alpha3);if(amount2>0)painter.opacity(amount2,draw2)}function panel(options,draw2){validateBounds(options);const{x,y,width,height,fill,stroke,radius=14,padding=10,id,scope="container",opacity=1}=options;nonnegative(padding,"Canvas padding");const alpha3=normalizedOpacity(opacity);if(scope!=="container"&&scope!=="label")throw new Error("Canvas scope must be container or label");let shape2;const paint=()=>painter.opacity(alpha3,()=>{shape2=painter.rect(x,y,width,height,fill,stroke,radius);if(draw2){const bounds4={x,y,width,height,radius};const scopeOptions={padding,id};if(scope==="label")painter.labelScope(bounds4,draw2,scopeOptions);else painter.container(bounds4,draw2,scopeOptions)}});if(options.focusTarget&&painter.target)painter.target(options.focusTarget,paint);else paint();return shape2}function card(options){const{label,x,y,width,height,fontSize=32,font="sans",textColor,baselineOffset=fontSize*.34,labelOpacity=1}=options;positive(fontSize,"Canvas font size");finite(baselineOffset,"Canvas text baseline offset");const labelAlpha=normalizedOpacity(labelOpacity,"Canvas label opacity");return panel(options,()=>{fade2(labelAlpha,()=>{painter.text(String(label),x+width/2,y+height/2+baselineOffset,fontSize,textColor,"center",font)})})}function matrix2(options){const{values,x,y,cellSize=112,gap=8,inset:inset2=0,format=String,style={},cellStyle}=options;finite(x,"Matrix x");finite(y,"Matrix y");positive(cellSize,"Matrix cell size");nonnegative(gap,"Matrix gap");finite(inset2,"Matrix inset");if(gap>=cellSize)throw new Error("Matrix gap must be smaller than cell size");const columns=values[0]?.length??0;for(const row of values){if(!Array.isArray(row)||row.length!==columns)throw new Error("Canvas matrix rows must be rectangular")}const shapes=[];for(let row=0;row<values.length;row+=1){for(let column=0;column<columns;column+=1){const value=values[row][column];const cell={...style,...cellStyle?.(value,row,column)};finite(cell.opacity??1,"Canvas opacity");if((cell.opacity??1)<=0)continue;const shape2=card({...cell,x:x+column*cellSize+inset2,y:y+row*cellSize+inset2,width:cellSize-gap,height:cellSize-gap,label:format(value,row,column)});shapes.push(shape2)}}return shapes}function tokenRow(options){const{values,y,height=68,reveal:reveal2=1,opacity=1,...style}=options;finite(y,"Token row y");positive(height,"Token height");finite(reveal2,"Token reveal");const alpha3=normalizedOpacity(opacity);const items=layoutTokenRow(values,options);const shapes=[];for(let index=0;index<items.length;index+=1){const amount2=Math.max(0,Math.min(1,reveal2*items.length-index))*alpha3;if(amount2<=0)continue;const{text:label,x,width}=items[index];const shape2=card({...style,label,x,y,width,height,opacity:amount2});shapes.push(shape2)}return shapes}function particle(options){const{points,progress,radius=9,fill,stroke,strokeWidth=3}=options;finite(progress,"Particle progress");positive(radius,"Particle radius");nonnegative(strokeWidth,"Particle stroke width");if(progress<=0||progress>=1)return null;const point=pointAlongPath(points,progress);painter.circle(point.x,point.y,radius,fill,stroke,strokeWidth);return point}return{panel,card,matrix:matrix2,tokenRow,particle,fade:fade2}}function nonnegative2(value,name){if(!Number.isFinite(value)||value<0)throw new Error(`${name} must be finite and nonnegative`)}function alpha(value){if(!Number.isFinite(value))throw new Error("Transfer opacity must be finite");return Math.max(0,Math.min(1,value))}function bounds(shape2){if(![shape2.x,shape2.y,shape2.width,shape2.height].every(Number.isFinite)||shape2.width<=0||shape2.height<=0){throw new Error("Transfer endpoints require finite positive rectangular bounds")}nonnegative2(shape2.radius??0,"Transfer corner radius")}function center(shape2){return{x:shape2.x+shape2.width/2,y:shape2.y+shape2.height/2}}function edgeDistance(shape2,ux,uy){const halfWidth=shape2.width/2,halfHeight=shape2.height/2;const limit=Math.min(ux===0?Infinity:halfWidth/Math.abs(ux),uy===0?Infinity:halfHeight/Math.abs(uy));const radius=Math.min(shape2.radius??0,halfWidth,halfHeight);if(radius===0)return limit;const outside=distance=>Math.hypot(Math.max(0,Math.abs(ux*distance)-(halfWidth-radius)),Math.max(0,Math.abs(uy*distance)-(halfHeight-radius)))>radius;if(!outside(limit))return limit;let low=0,high=limit;for(let index=0;index<32;index+=1){const middle=(low+high)/2;if(outside(middle))high=middle;else low=middle}return low}function safeGap(shape2,ux,uy,clearance,edge){const expanded2=Math.min(ux===0?Infinity:(shape2.width/2+clearance)/Math.abs(ux),uy===0?Infinity:(shape2.height/2+clearance)/Math.abs(uy));return expanded2-edge}function createTeachingTransfer(painter){return options=>{const{source,target,color="#63DEEC",width=3,margin=2,progress,particle}=options;bounds(source.shape);bounds(target.shape);nonnegative2(width,"Transfer stroke width");if(width===0)throw new Error("Transfer stroke width must be positive");nonnegative2(margin,"Transfer margin");const opacity=Math.min(alpha(source.opacity),alpha(target.opacity),alpha(options.opacity??1));for(const gap of[options.gap,options.fromGap,options.toGap]){if(gap!==void 0)nonnegative2(gap,"Transfer gap")}if(progress!==void 0&&!Number.isFinite(progress))throw new Error("Transfer progress must be finite");if(particle&&progress===void 0)throw new Error("Transfer particle requires progress");const radius=particle?.radius??7,strokeWidth=particle?.strokeWidth??3;nonnegative2(radius,"Transfer particle radius");if(radius===0)throw new Error("Transfer particle radius must be positive");nonnegative2(strokeWidth,"Transfer particle stroke width");if(opacity===0)return null;const a=center(source.shape),z=center(target.shape);const distance=Math.hypot(z.x-a.x,z.y-a.y);if(!Number.isFinite(distance)||distance===0)throw new Error("Transfer endpoints must have distinct finite centers");const ux=(z.x-a.x)/distance,uy=(z.y-a.y)/distance;const sourceEdge=edgeDistance(source.shape,ux,uy),targetEdge=edgeDistance(target.shape,ux,uy);const markerRadius=progress===void 0?0:radius+(particle?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerRadius)+margin;const fromGap=Math.max(options.fromGap??options.gap??0,safeGap(source.shape,ux,uy,clearance,sourceEdge));const toGap=Math.max(options.toGap??options.gap??0,safeGap(target.shape,ux,uy,clearance,targetEdge));if(distance<=sourceEdge+targetEdge+fromGap+toGap)throw new Error("Transfer endpoints leave no room for the requested clearance");let route;painter.opacity(opacity,()=>{route=painter.connect(source.shape,target.shape,{color,width,fromGap,toGap});if(progress!==void 0&&progress>0&&progress<1){const x=route.from.x*(1-progress)+route.to.x*progress;const y=route.from.y*(1-progress)+route.to.y*progress;painter.circle(x,y,radius,particle?.fill??color,particle?.stroke,strokeWidth)}});return route}}function positive2(value,name){if(!Number.isFinite(value)||value<=0)throw new Error(`${name} must be finite and positive`)}function layoutCellGrid(options){const{x,y,width,height,rows,columns}=options;if(![x,y,x+width,y+height].every(Number.isFinite))throw new Error("Grid bounds must be finite");positive2(width,"Grid width");positive2(height,"Grid height");if(![rows,columns,rows*columns].every(Number.isSafeInteger)||rows<=0||columns<=0){throw new Error("Grid rows and columns must be positive safe integers")}const bounds4={x,y,width,height};const cells=Array.from({length:rows},(_,row)=>Array.from({length:columns},(_2,column)=>({x:x+column*width/columns,y:y+row*height/rows,width:width/columns,height:height/rows})));return{bounds:bounds4,cells,cell(row,column){if(!Number.isSafeInteger(row)||!Number.isSafeInteger(column)||row<0||row>=rows||column<0||column>=columns){throw new Error("Grid cell index is outside the grid")}return cells[row][column]}}}function createTeachingGrid(painter){const components=createCanvasComponents(painter);return options=>{const layout=layoutCellGrid(options);const{x,y,width,height,rows,columns,fill="#18283B",stroke="#63DEEC",lineWidth=1,labels,highlights=[],fontSize=28,textColor="#FFFFFF",padding=4}=options;positive2(lineWidth,"Grid line width");if(lineWidth>=Math.min(width/columns,height/rows))throw new Error("Grid line width must be smaller than a cell");positive2(fontSize,"Grid font size");if(!Number.isFinite(padding)||padding<0)throw new Error("Grid padding must be finite and nonnegative");if(labels&&(labels.length!==rows||labels.some(row=>row.length!==columns))){throw new Error("Grid labels must match rows and columns")}for(const highlight of highlights){layout.cell(highlight.row,highlight.column);if(!Number.isFinite(highlight.opacity??1))throw new Error("Grid highlight opacity must be finite")}const cellFocusTarget=painter.target?options.cellFocusTarget:void 0;const shape2=components.panel({...layout.bounds,fill:cellFocusTarget?"transparent":fill,stroke,radius:0,padding:0},()=>{const drawLabel=(r,column)=>{if(!labels)return;const cell=layout.cell(r,column),value=String(labels[r][column]);const baseline=cell.y+cell.height/2+fontSize*.34-(value.split("\n").length-1)*fontSize*.7;painter.labelScope(cell,()=>painter.text(value,cell.x+cell.width/2,baseline,fontSize,textColor,"center"),{padding})};if(cellFocusTarget)for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){const named=cellFocusTarget(row,column),ids=typeof named==="string"?[named]:named??[];const draw2=()=>{const cell=layout.cell(row,column),inset3=lineWidth/2;painter.rect(cell.x+inset3,cell.y+inset3,cell.width-lineWidth,cell.height-lineWidth,fill,void 0,0);for(const highlight of highlights.filter(item=>item.row===row&&item.column===column)){const pad2=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>painter.rect(cell.x+pad2,cell.y+pad2,cell.width-pad2*2,cell.height-pad2*2,highlight.fill,highlight.stroke,0))}drawLabel(row,column)};const scoped=index=>{if(index<ids.length&&painter.target)painter.target(ids[index],()=>scoped(index+1));else draw2()};scoped(0)}for(const highlight of cellFocusTarget?[]:highlights){const cell=layout.cell(highlight.row,highlight.column);const inset3=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>{painter.rect(cell.x+inset3,cell.y+inset3,cell.width-2*inset3,cell.height-2*inset3,highlight.fill,highlight.stroke,0)})}const inset2=lineWidth/2;for(let column=1;column<columns;column+=1){const left=x+column*width/columns;painter.path([{x:left,y:y+inset2},{x:left,y:y+height-inset2}],{color:stroke,width:lineWidth})}for(let row=1;row<rows;row+=1){const top=y+row*height/rows;painter.path([{x:x+inset2,y:top},{x:x+width-inset2,y:top}],{color:stroke,width:lineWidth})}if(!cellFocusTarget)labels?.forEach((row,r)=>row.forEach((_,column)=>drawLabel(r,column)))});return{...layout,shape:shape2}}}function createTeachingTimeline(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,domain:[lo,hi],lanes,intervals,time=hi,ticks:ticks2=[lo,hi],formatTime=String,labelWidth=180,laneGap=18,fontSize=28,color="#8D9CB9",trackColor="#18283B",cursorColor="#FFCE73"}=options;if(![x,y,x+width,y+height,lo,hi,hi-lo,time,labelWidth,laneGap,fontSize].every(Number.isFinite))throw new Error("Timeline values must be finite");if(width<=0||height<=0||hi<=lo||time<lo||time>hi)throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");if(fontSize<=0||labelWidth<=12||labelWidth>=width-6||laneGap<0||!lanes.length)throw new Error("Timeline needs positive label space, font size, and at least one lane");const ids=new Set(lanes.map(lane=>lane.id));if(ids.size!==lanes.length||lanes.some(lane=>!lane.id))throw new Error("Timeline lane IDs must be nonempty and unique");const intervalIds=new Set;for(const interval of intervals){if(!interval.id||intervalIds.has(interval.id)||!ids.has(interval.lane))throw new Error("Timeline intervals need unique IDs and an existing lane");intervalIds.add(interval.id);if(![interval.start,interval.end,interval.opacity??1].every(Number.isFinite)||interval.start<lo||interval.end>hi||interval.end<=interval.start)throw new Error("Timeline intervals must have finite positive durations inside the domain")}for(const lane of lanes){const ordered=intervals.filter(interval=>interval.lane===lane.id).sort((a,b)=>a.start-b.start);if(ordered.some((interval,i)=>i>0&&interval.start<ordered[i-1].end))throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`)}if(ticks2.some(tick=>!Number.isFinite(tick)||tick<lo||tick>hi))throw new Error("Timeline ticks must lie inside the domain");const axisHeight=Math.max(36,fontSize*2+18);const laneHeight=(height-axisHeight-(lanes.length-1)*laneGap)/lanes.length;const labelHeight=fontSize*1.5,barHeight=laneHeight-labelHeight;if(barHeight<12)throw new Error("Timeline height cannot fit lane labels and interval bars");const left=x+labelWidth+3,plotWidth=width-labelWidth-6;const point=value=>{if(!Number.isFinite(value)||value<lo||value>hi)throw new Error("Timeline point must lie inside the domain");return left+(value-lo)/(hi-lo)*plotWidth};const bounds4={x,y,width,height};const result={bounds:bounds4,time,point,lanes:Object.create(null),intervals:Object.create(null)};painter.container(bounds4,()=>{lanes.forEach((lane,index)=>target(lane.focusTarget,()=>{const top=y+index*(laneHeight+laneGap);const track={x:left-2,y:top+labelHeight,width:plotWidth+4,height:barHeight};const shape2=painter.rect(track.x,track.y,track.width,track.height,trackColor,color,0);result.lanes[lane.id]={shape:shape2,bounds:track};painter.labelScope({x,y:top,width:labelWidth-12,height:laneHeight},()=>{painter.text(lane.label,x,top+laneHeight/2+fontSize*.34,fontSize,color,"left")},{padding:0});for(const interval of intervals.filter(item=>item.lane===lane.id)){const visibleEnd=Math.max(interval.start,Math.min(time,interval.end));const elapsed=visibleEnd-interval.start;const bar={x:point(interval.start),y:track.y+2,width:point(visibleEnd)-point(interval.start),height:barHeight-4};const opacity=Math.max(0,Math.min(1,interval.opacity??1));const item={id:interval.id,shape:null,bounds:bar,elapsed,opacity,complete:time>=interval.end};result.intervals[interval.id]=item;if(elapsed===0||opacity===0)continue;target(interval.focusTarget,()=>painter.opacity(opacity,()=>{painter.container(track,()=>{item.shape=painter.rect(bar.x,bar.y,bar.width,bar.height,interval.color??"#63DEEC",void 0,0)},{padding:0});if(interval.label){const labelBounds={x:point(interval.start),y:top,width:point(interval.end)-point(interval.start),height:labelHeight};painter.labelScope(labelBounds,()=>painter.text(interval.label,labelBounds.x+labelBounds.width/2,top+fontSize,fontSize,interval.color??"#63DEEC","center"),{padding:2})}}))}}));const axisY=y+height-axisHeight+Math.max(10,fontSize*.5);painter.line(left,axisY,left+plotWidth,axisY,color,2);for(const tick of ticks2){const px=point(tick);painter.line(px,axisY,px,axisY+6,color,2);painter.labelScope({x:left-labelWidth,y:axisY+8,width:plotWidth+labelWidth,height:fontSize*1.5},()=>{painter.text(formatTime(tick),px,axisY+fontSize*1.4,fontSize,color,tick===hi?"right":tick===lo?"left":"center")},{padding:0})}painter.line(point(time),axisY-8,point(time),axisY+8,cursorColor,3)},{padding:0});return result}}var COLORS=["#63DEEC","#79A6FF","#D6A0FF","#FFCE73"];function layoutAllocation(options){const{x,y,width,height,capacity,parts}=options;if(![x,y,x+width,y+height,capacity].every(Number.isFinite)||width<=0||height<=0||capacity<=0)throw new Error("Allocation needs finite positive bounds and capacity");const ids=new Set;let used=0;for(const part of parts){if(!part.id||ids.has(part.id))throw new Error("Allocation part IDs must be nonempty and unique");ids.add(part.id);if(!Number.isFinite(part.value)||part.value<0)throw new Error("Allocation values must be finite and nonnegative");used+=part.value}if(!Number.isFinite(used)||used-capacity>Number.EPSILON*Math.max(used,capacity)*8)throw new Error("Allocation exceeds capacity");used=Math.min(used,capacity);let offset=0;const segments=parts.map(part=>{const start=Math.min(offset,capacity);offset+=part.value;return{id:part.id,value:part.value,bounds:{x:x+width*(start/capacity),y,width:width*((Math.min(offset,capacity)-start)/capacity),height}}});const remaining=Math.max(0,capacity-used);return{bounds:{x,y,width,height},used,remaining,parts:segments,freeBounds:{x:x+width*(used/capacity),y,width:width*(remaining/capacity),height}}}function createTeachingAllocation(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,fontSize=28,unit="",format=String,color="#8D9CB9",trackColor="#18283B"}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Allocation font size must be finite and positive");const header=fontSize*1.7,barHeight=fontSize*2,rowHeight=fontSize*1.65,gap=fontSize*.6;if(height<header+barHeight+gap+(options.parts.length+1)*rowHeight||width<=6||width*.67<=fontSize)throw new Error("Allocation bounds cannot fit the strip and ledger");const layout=layoutAllocation({...options,x:x+3,y:y+header+3,width:width-6,height:barHeight-6});const suffix=unit?` ${unit}`:"",shapes=[];let shape2;painter.container({x,y,width,height},()=>{painter.labelScope({x,y,width,height:header},()=>painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`,x,y+fontSize,fontSize,color,"left"),{padding:0});const strip={x:x+1,y:y+header+1,width:width-2,height:barHeight-2};shape2=painter.rect(strip.x,strip.y,strip.width,strip.height,trackColor,color,0);painter.container(strip,()=>{layout.parts.forEach((part,index)=>shapes.push(part.bounds.width===0?null:target(options.parts[index].focusTarget,()=>painter.rect(part.bounds.x,part.bounds.y,part.bounds.width,part.bounds.height,options.parts[index].color??COLORS[index%COLORS.length],void 0,0))))},{padding:0});const rows=[...options.parts,{id:"free",label:"Free",value:layout.remaining,color,focusTarget:options.freeFocusTarget}];rows.forEach((part,index)=>target(part.focusTarget,()=>{const top=y+header+barHeight+gap+index*rowHeight,baseline=top+rowHeight/2+fontSize*.34;painter.rect(x,top+(rowHeight-fontSize*.6)/2,fontSize*.6,fontSize*.6,part.color??COLORS[index%COLORS.length],void 0,0);painter.labelScope({x:x+fontSize,y:top,width:width*.67-fontSize,height:rowHeight},()=>painter.text(part.label,x+fontSize,baseline,fontSize,color,"left"),{padding:0});painter.labelScope({x:x+width*.7,y:top,width:width*.3,height:rowHeight},()=>painter.text(`${format(part.value)}${suffix}`,x+width,baseline,fontSize,color,"right"),{padding:0})}))},{padding:0});return{...layout,shapes,shape:shape2}}}var clamp=value=>Math.max(0,Math.min(1,value));var smooth=value=>value*value*(3-2*value);function valueChangeState(options){for(const name of["from","to","progress"]){if(!Number.isFinite(options[name]))throw new Error(`Value change ${name} must be finite`)}if(options.emphasis!==void 0&&!Number.isFinite(options.emphasis))throw new Error("Value change emphasis must be finite");const{from,to:to2}=options;const progress=clamp(options.progress);const changed=from!==to2;const emphasis=changed?clamp(options.emphasis??smooth(clamp(progress/.12))*(1-smooth(clamp((progress-.65)/.35)))):0;const value=from*(1-progress)+to2*progress;const delta=to2-from;if(!Number.isFinite(value)||!Number.isFinite(delta))throw new Error("Value change result must be finite");return{value,previous:from,target:to2,delta,changed,emphasis}}function createTeachingValueChange(painter){function changeCue(options,draw2){const{x,y,width,height,color="#F4D477",restColor="#E9EFFF",fill=color,radius=10}=options;if(![x,y,width,height,radius].every(Number.isFinite)||width<=0||height<=0||radius<0){throw new Error("Value change bounds must be finite with positive dimensions and nonnegative radius")}const state=valueChangeState({from:options.from,to:options.to,progress:options.progress,...options.emphasis===void 0?{}:{emphasis:options.emphasis}});if(state.emphasis>0){painter.opacity(state.emphasis*.12,()=>painter.rect(x,y,width,height,fill,void 0,radius));painter.opacity(state.emphasis,()=>painter.rect(x,y,width,height,"transparent",color,radius))}const result={...state,color:state.emphasis>0?color:restColor};draw2?.(result);return result}function valueChange(options){const{x,y,width,height,label,format=value=>value.toFixed(1),fontSize=36,showDelta=true}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Value change font size must be positive");const lines=1+Number(Boolean(label))+Number(showDelta);if(height<fontSize*(lines===1?1.4:lines===2?2.3:3))throw new Error("Value change height must contain its label and delta");return changeCue(options,state=>painter.labelScope({x,y,width,height},()=>{const center2=x+width/2;if(label)painter.text(label,center2,y+fontSize*.7,fontSize*.55,options.restColor??"#E9EFFF","center");const baseline=label?y+height*(showDelta?.5:.65)+fontSize*.2:showDelta?y+fontSize*1.05:y+height/2+fontSize*.34;painter.text(format(state.value),center2,baseline,fontSize,state.color,"center","mono");if(showDelta){const sign=state.delta>0?"+":"";painter.text(`${format(state.previous)} \u2192 ${format(state.target)} \xB7 \u0394 ${sign}${format(state.delta)}`,center2,y+height-fontSize*.3,fontSize*.46,options.restColor??"#E9EFFF","center","mono")}},{padding:4}))}return{changeCue,valueChange}}function mergeFocusRegions(parts,gap=12){const regions=[];for(const part of parts){let current={...part},index=0;while(index<regions.length){const other=regions[index];if(current.x<=other.x+other.width+gap&&other.x<=current.x+current.width+gap&¤t.y<=other.y+other.height+gap&&other.y<=current.y+current.height+gap){const x=Math.min(current.x,other.x),y=Math.min(current.y,other.y);current={x,y,width:Math.max(current.x+current.width,other.x+other.width)-x,height:Math.max(current.y+current.height,other.y+other.height)-y};regions.splice(index,1);index=0}else index++}regions.push(current)}return regions}function createFocusDirector(painter,options={}){const{cues,strict=false,contextOpacity=.52,minimumContextAlpha=0}=options;if(!Number.isFinite(contextOpacity)||contextOpacity<0||contextOpacity>1)throw new Error("Focus context opacity must be between zero and one");if(!Number.isFinite(minimumContextAlpha)||minimumContextAlpha<0||minimumContextAlpha>1)throw new Error("Minimum context alpha must be between zero and one");const active=Object.values(cues??{}).filter(cue2=>cue2.active&&cue2.strength>0).sort((a,b)=>b.start-a.start||b.id.localeCompare(a.id))[0];const stack=[];function cue(id){const value=cues&&Object.hasOwn(cues,id)?cues[id]:void 0;if(!value&&strict)throw new Error(`Unknown narration cue: ${id}`);return value}function opacity(amount2,draw2){if(amount2===1)return draw2();let result;painter.opacity(amount2,()=>{result=draw2()});return result}return{active,cue,progress(id,fallback=0){return cue(id)?.progress??fallback},visible(id){return cue(id)?.phase!=="before"},reveal(id,draw2){return opacity(cue(id)?.reveal??1,draw2)},target(id,draw2){stack.push(id);try{return draw2()}finally{stack.pop()}},paint(draw2,originalAlpha=1){const focused=!active||stack.some(id=>active.targets.includes(id));let amount2=focused?1:1-(1-contextOpacity)*active.strength;if(!focused&&originalAlpha>0)amount2=Math.max(amount2,Math.min(originalAlpha,minimumContextAlpha)/originalAlpha);return opacity(amount2,draw2)}}}function createTeachingFocus(painter){function focusFrame(options){const{bounds:bounds4,strength,color="#63DEEC",padding=8,clip}=options;if(![bounds4.x,bounds4.y,bounds4.width,bounds4.height,strength,padding].every(Number.isFinite)||bounds4.width<=0||bounds4.height<=0||padding<0||strength<0||strength>1)throw new Error("Invalid focus frame geometry or strength");if(strength===0)return;const corners=offset=>{const x=bounds4.x-offset,y=bounds4.y-offset,w=bounds4.width+offset*2,h=bounds4.height+offset*2;const corner=Math.min(24,w/4,h/4);return[[x,y,1,1],[x+w,y,-1,1],[x,y+h,1,-1],[x+w,y+h,-1,-1]].map(([cx,cy,sx,sy])=>[{x:cx+sx*corner,y:cy},{x:cx,y:cy},{x:cx,y:cy+sy*corner}])};const clear=points=>points.slice(1).every((point,index)=>{const previous=points[index],x=Math.min(previous.x,point.x)-2,y=Math.min(previous.y,point.y)-2;const right=Math.max(previous.x,point.x)+2,bottom=Math.max(previous.y,point.y)+2;return(!clip||x>=clip.x&&y>=clip.y&&right<=clip.x+clip.width&&bottom<=clip.y+clip.height)&&!(options.avoid??[]).some(label=>x<label.x+label.width&&right>label.x&&y<label.y+label.height&&bottom>label.y)});let paths=corners(padding);if(!paths.every(clear)){const alternatives=[padding+6,padding+12,padding+20].map(corners);paths=alternatives.find(candidate=>candidate.every(clear))??paths.filter(clear)}if(paths.length<2)return;painter.opacity(strength*.7,()=>{for(const[index,points]of paths.entries()){painter.path(points,{id:options.id&&`${options.id}:${index}`,color,width:3,clip})}})}return{focusFrame}}var clamp2=value=>Math.max(0,Math.min(1,value));var cleanZero=value=>value===0?0:value;function finite2(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`);return value}function vector(values,dimensions,name){if(values.length!==dimensions)throw new Error(`${name} must have ${dimensions} coordinates`);return values.map(value=>cleanZero(finite2(value,name)))}function add(left,right){return left.map((value,index)=>cleanZero(finite2(value+right[index],"Weighted vector sum")))}function weightedVectorState(options){const progress=clamp2(finite2(options.progress,"Weighted vector progress"));const dimensions=options.initial?.length??options.terms[0]?.values.length??0;if(!dimensions)throw new Error("Weighted vectors require at least one coordinate; an empty sum needs an initial vector");const initial=options.initial?vector(options.initial,dimensions,"Initial vector"):Array(dimensions).fill(0);const ids=new Set;let prefix2=[...initial];const position2=progress*options.terms.length;const completedCount=Math.min(options.terms.length,Math.floor(position2));const terms=options.terms.map((term,index)=>{if(typeof term.id!=="string"||!term.id.trim()||term.id!==term.id.trim()||ids.has(term.id)){throw new Error("Weighted vector terms require distinct nonempty IDs without surrounding whitespace")}ids.add(term.id);const label=term.label??term.id;if(typeof label!=="string"||!label.trim())throw new Error("Weighted vector labels must be nonempty");const weight=finite2(term.weight,"Vector weight");const values=vector(term.values,dimensions,`Vector ${term.id}`);const contribution=values.map(value=>cleanZero(finite2(weight*value,"Weighted vector contribution")));const start=[...prefix2],end=add(start,contribution);prefix2=end;const fraction=clamp2(position2-index);const status=fraction===1?"completed":index===completedCount&&progress<1?"current":"pending";const applied=contribution.map(value=>cleanZero(value*fraction));return{...term,label,values,weight,status,progress:fraction,contribution,applied,start,end,currentEnd:add(start,applied),zero:contribution.every(value=>value===0)}});const completedSum=completedCount?[...terms[completedCount-1].end]:[...initial];const current=terms.find(term=>term.status==="current")??null;return{progress,dimensions,initial,terms,completedCount,current,completedSum,sum:current?[...current.currentEnd]:[...completedSum],total:[...prefix2]}}function positive3(value,name){if(finite2(value,name)<=0)throw new Error(`${name} must be positive`)}function bounds2(value,name){finite2(value.x,`${name} x`);finite2(value.y,`${name} y`);positive3(value.width,`${name} width`);positive3(value.height,`${name} height`)}function createTeachingVectorAccumulation(painter){return options=>{const state=weightedVectorState(options);const{plot,ledger,projection,fontSize=28,color="#63DEEC",restColor="#8D9CB9",completedOpacity=.45,width=4,endpointRadius=5,revealTotal=false,totalLabel="Accumulated vector",format=value=>String(Number(value.toPrecision(4)))}=options;bounds2(plot.bounds,"Vector plot");bounds2(ledger,"Vector ledger");positive3(fontSize,"Vector font size");positive3(width,"Vector stroke width");positive3(endpointRadius,"Vector endpoint radius");finite2(completedOpacity,"Completed vector opacity");if(completedOpacity<0||completedOpacity>1)throw new Error("Completed vector opacity must lie between zero and one");const[x0,x1]=plot.xDomain,[y0,y1]=plot.yDomain;for(const value of[x0,x1,y0,y1])finite2(value,"Vector plot domain");if(x1<=x0||y1<=y0)throw new Error("Vector plot domains must increase");const sx=plot.bounds.width/(x1-x0),sy=plot.bounds.height/(y1-y0);if(!Number.isFinite(sx)||!Number.isFinite(sy)||sx<=0||sy<=0||Math.abs(sx-sy)>Math.max(sx,sy)*1e-9){throw new Error("Weighted vector drawing requires equal-unit plot geometry")}if(state.dimensions!==2&&!projection)throw new Error("Weighted vector drawing requires 2D values or an explicit projection");if(projection&&!projection.label.trim())throw new Error("Vector projection requires a visible declaration");const rowHeight=fontSize*2.5,headerHeight=fontSize*1.6;if(ledger.height<headerHeight+state.terms.length*rowHeight+fontSize*1.8){throw new Error("Vector ledger height must contain the identities, contributions and result")}const point=values=>{const projected=projection?projection.point([...values]):values;if(projected.length!==2)throw new Error("Vector projection must return exactly two coordinates");const[x,y]=projected;finite2(x,"Projected vector x");finite2(y,"Projected vector y");if(x<x0||x>x1||y<y0||y>y1)throw new Error("Vector endpoints must lie inside the declared plot domains");const p=plot.point(x,y);finite2(p.x,"Vector endpoint x");finite2(p.y,"Vector endpoint y");const expectedX=finite2(plot.bounds.x+(x-x0)*sx,"Declared vector endpoint x");const expectedY=finite2(plot.bounds.y+plot.bounds.height-(y-y0)*sy,"Declared vector endpoint y");const tolerance=Math.max(1,Math.abs(expectedX),Math.abs(expectedY),plot.bounds.width,plot.bounds.height)*1e-9;if(Math.abs(p.x-expectedX)>tolerance||Math.abs(p.y-expectedY)>tolerance){throw new Error("Vector plot mapping must match its declared equal-unit transform")}return p};const segments=[];for(const term of state.terms){const from=point(term.start);point(term.end);const to2=point(term.currentEnd);if(term.status!=="pending")segments.push({id:term.id,status:term.status,from,to:to2,zero:Math.hypot(to2.x-from.x,to2.y-from.y)<1e-9})}const endpoint=point(state.sum);const vectorText=values=>`(${values.map(format).join(", ")})`;const target=(id,draw2)=>painter.target?painter.target(id,draw2):draw2();const paintedTerms=state.terms.map((term,index)=>({term,index,input:`${term.label}: ${format(term.weight)} \xD7 ${vectorText(term.values)}`,detail:term.status==="pending"?"pending":`${term.status}: ${vectorText(term.applied)}`}));const totalText=`${totalLabel}: ${revealTotal?vectorText(state.sum):"?"}`;for(const segment of segments){const term=state.terms.find(term2=>term2.id===segment.id);const ink=term.color??color;target(term.id,()=>painter.opacity(term.status==="completed"?completedOpacity:1,()=>{if(segment.zero)painter.circle(segment.to.x,segment.to.y,endpointRadius,"transparent",ink,width);else painter.arrow(segment.from.x,segment.from.y,segment.to.x,segment.to.y,ink,width)}))}if(revealTotal){const mark=()=>{painter.circle(endpoint.x,endpoint.y,endpointRadius*1.5,color)};if(options.totalTarget)target(options.totalTarget,mark);else mark()}painter.labelScope(ledger,()=>{painter.text(projection?`Projection: ${projection.label}`:"Weighted contributions",ledger.x+12,ledger.y+fontSize,fontSize*.85,restColor);for(const{term,index,input,detail}of paintedTerms)target(term.id,()=>{const ink=term.color??color;const y=ledger.y+headerHeight+index*rowHeight;painter.text(input,ledger.x+12,y+fontSize,fontSize,term.status==="pending"?restColor:ink);painter.text(detail,ledger.x+12,y+fontSize*1.9,fontSize*.8,restColor)});const result=()=>{painter.text(totalText,ledger.x+12,ledger.y+headerHeight+state.terms.length*rowHeight+fontSize,fontSize,revealTotal?color:restColor)};if(options.totalTarget)target(options.totalTarget,result);else result()},{padding:4});return{state,segments,endpoint}}}function categoricalSampling(options){if(options.normalization!=="probabilities"&&options.normalization!=="weights")throw new Error("Sampling requires an explicit mass normalization contract");if(!options.categories.length)throw new Error("Sampling needs at least one category");const ids=new Set;let total=0;for(const category of options.categories){if(!category.id||ids.has(category.id)||!category.label.trim())throw new Error("Sampling category IDs must be unique and labels nonempty");if(!Number.isFinite(category.mass)||category.mass<0)throw new Error("Sampling masses must be finite and nonnegative");ids.add(category.id);total+=category.mass}if(!Number.isFinite(total)||total<=0)throw new Error("Sampling total mass must be finite and positive");if(options.normalization==="probabilities"&&Math.abs(total-1)>1e-12)throw new Error("Sampling probabilities must sum to one within 1e-12");let cumulative=0;let lastPositive=0;options.categories.forEach((category,index)=>{if(category.mass>0)lastPositive=index});const categories=options.categories.map((category,index)=>{const lower=cumulative,probability=category.mass/total;cumulative=index===lastPositive?1:Math.min(1,cumulative+probability);if(category.mass>0&&(probability===0||cumulative<=lower))throw new Error("Positive category is too small for cumulative floating-point precision");return{...category,probability,lower,upper:cumulative,count:0,empiricalProbability:null}});ids.clear();const draws=options.draws.map(draw2=>{if(!draw2.id||ids.has(draw2.id))throw new Error("Sampling draw IDs must be nonempty and unique");if(!Number.isFinite(draw2.uniform)||draw2.uniform<0||draw2.uniform>=1)throw new Error("Supplied uniform draws must be finite inside [0, 1)");ids.add(draw2.id);const categoryIndex=categories.findIndex(category=>category.mass>0&&draw2.uniform>=category.lower&&draw2.uniform<category.upper);if(categoryIndex<0)throw new Error("Supplied draw could not be represented by the normalized intervals");categories[categoryIndex].count+=1;return{...draw2,categoryId:categories[categoryIndex].id,categoryIndex}});if(draws.length)categories.forEach(category=>{category.empiricalProbability=category.count/draws.length});return{inputTotal:total,normalization:options.normalization,categories,draws}}var COLORS2=["#79A6FF","#FF8DC3","#63DEEC","#FFCE73","#A6DF91"];function createTeachingCategoricalSampling(painter){return options=>{const model=categoricalSampling(options);const{x,y,width,height,fontSize=28,color="#DEE7F5",trackColor="#18283B",visibleDraws=0,drawProgress=0,showEmpirical=false,formatProbability=value=>value.toFixed(3)}=options;if(![x,y,x+width,y+height,fontSize].every(Number.isFinite)||fontSize<=0||width<=0||height<=0)throw new Error("Sampling needs finite positive bounds and font size");if(!Number.isInteger(visibleDraws)||visibleDraws<0||visibleDraws>model.draws.length)throw new Error("Visible sample count must be an integer inside the supplied draw count");if(!Number.isFinite(drawProgress)||drawProgress<0||drawProgress>1||visibleDraws===model.draws.length&&drawProgress!==0)throw new Error("Sampling progress must be inside [0, 1] for an available next draw");if(showEmpirical&&visibleDraws!==model.draws.length)throw new Error("Empirical reveal requires every supplied sample to be retained");const columns=options.columns??Math.max(1,Math.min(8,model.draws.length));if(!Number.isInteger(columns)||columns<1)throw new Error("Sampling columns must be a positive integer");const railWidth=fontSize*2,contentWidth=width-railWidth;const gap=fontSize*.5,cellWidth=(contentWidth-4-(columns-1)*gap)/columns,cellHeight=fontSize*1.9;const legendColumns=Math.min(3,model.categories.length),legendRows=Math.ceil(model.categories.length/legendColumns),legendHeight=legendRows*fontSize*1.7;const bandY=y+fontSize*4,bandHeight=fontSize*1.3,legendY=bandY+bandHeight+fontSize*1.5;const captionY=legendY+legendHeight+fontSize*.5,poolY=captionY+fontSize*3.3,rows=Math.ceil(model.draws.length/columns),empiricalY=poolY+Math.max(1,rows)*(cellHeight+gap)+fontSize*2;if(cellWidth<fontSize*2||contentWidth/legendColumns<fontSize*5||empiricalY+bandHeight+fontSize*1.7>y+height)throw new Error("Sampling bounds cannot fit probability labels, sample IDs and empirical strip");const inset2=fontSize*.22+2,stripX=x+inset2,stripWidth=contentWidth-inset2*2;const point=u=>stripX+u*stripWidth;const categoryColor=index=>model.categories[index].color??COLORS2[index%COLORS2.length];const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const label=(value,bounds4,align="left",ink=color,size=fontSize)=>painter.labelScope(bounds4,()=>painter.text(value,align==="center"?bounds4.x+bounds4.width/2:align==="right"?bounds4.x+bounds4.width:bounds4.x,bounds4.y+size*1.05,size,ink,align),{padding:0});const strip=(top,empirical)=>{painter.rect(stripX,top,stripWidth,bandHeight,trackColor,void 0,0);let cumulative=0;model.categories.forEach((category,index)=>{const probability=empirical?category.empiricalProbability??0:category.probability;const left=cumulative;cumulative+=probability;if(probability>0)target(category.focusTarget,()=>painter.rect(point(left),top,stripWidth*probability,bandHeight,categoryColor(index),void 0,0))})};const sampleBounds=model.draws.map((_draw,index)=>({x:x+2+index%columns*(cellWidth+gap),y:poolY+Math.floor(index/columns)*(cellHeight+gap),width:cellWidth,height:cellHeight}));const shapes=[];painter.container({x,y,width,height},()=>{label(options.normalization==="weights"?"Original probabilities \xB7 normalized supplied weights":"Original probabilities \xB7 supplied distribution",{x,y,width:contentWidth,height:fontSize*1.6});strip(bandY,false);label("0",{x,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"left",color,fontSize*.8);label("1",{x:x+contentWidth-fontSize*2,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"right",color,fontSize*.8);model.categories.forEach((category,index)=>{const bounds4={x:x+index%legendColumns*contentWidth/legendColumns,y:legendY+Math.floor(index/legendColumns)*fontSize*1.7,width:contentWidth/legendColumns-gap,height:fontSize*1.5};target(category.focusTarget,()=>label(`${category.label}: ${formatProbability(category.probability)}`,bounds4,"left",categoryColor(index)))});label(`Supplied samples \xB7 ${visibleDraws} retained / ${model.draws.length}`,{x,y:poolY-fontSize*1.8,width:contentWidth,height:fontSize*1.5});for(let index=0;index<visibleDraws;index+=1)target(options.sampleFocusTarget,()=>{const draw2=model.draws[index],bounds4=sampleBounds[index];shapes.push(painter.rect(bounds4.x,bounds4.y,bounds4.width,bounds4.height,trackColor,categoryColor(draw2.categoryIndex),4));label(draw2.id,bounds4,"center",categoryColor(draw2.categoryIndex))});if(drawProgress>0&&visibleDraws<model.draws.length)target(options.sampleFocusTarget,()=>{const draw2=model.draws[visibleDraws],destination=sampleBounds[visibleDraws],landed=drawProgress>=.4;const from={x:point(draw2.uniform),y:bandY-fontSize*1.2},onBand={x:point(draw2.uniform),y:bandY+bandHeight/2};const progress=landed?(drawProgress-.4)/.6:drawProgress/.4;const destinationPoint={x:destination.x+destination.width/2,y:destination.y+destination.height/2};const railX=x+width-inset2;const route=landed?[onBand,from,{x:railX,y:from.y},{x:railX,y:destinationPoint.y},destinationPoint]:[from,onBand];const lengths=route.slice(1).map((point2,index)=>Math.hypot(point2.x-route[index].x,point2.y-route[index].y));let remaining=progress*lengths.reduce((sum,length)=>sum+length,0);let marker=route[route.length-1];for(let index=0;index<lengths.length;index+=1){const length=lengths[index];if(remaining<=length&&length>0){const ratio=remaining/length;marker={x:route[index].x+(route[index+1].x-route[index].x)*ratio,y:route[index].y+(route[index+1].y-route[index].y)*ratio};break}remaining-=length}const ink=landed?categoryColor(draw2.categoryIndex):color;painter.circle(marker.x,marker.y,fontSize*.22,ink,trackColor,3);const caption=`${landed?"Copy":"Draw"} ${draw2.id} \xB7 supplied u=${draw2.uniform.toFixed(3)}`;label(caption,{x,y:captionY,width:contentWidth,height:fontSize*1.3},"left",ink,fontSize*.8)});if(showEmpirical){label(model.draws.length?"Empirical frequencies \xB7 supplied sample only":"No samples \xB7 empirical distribution undefined",{x,y:empiricalY-fontSize*1.7,width:contentWidth,height:fontSize*1.5});if(model.draws.length){strip(empiricalY,true);const text2=model.categories.map(category=>`${category.label}: ${category.count}/${model.draws.length}`).join(" \xB7 ");label(text2,{x,y:empiricalY+bandHeight+fontSize*.25,width:contentWidth,height:fontSize*1.3},"left",color,fontSize*.8)}}},{padding:0});return{model,sampleBounds,shapes,point,visibleDraws}}}function finite3(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative3(value,name){finite3(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function bounds3(value,name){for(const field of["x","y","width","height"])finite3(value[field],`${name} ${field}`);if(value.width<=0||value.height<=0)throw new Error(`${name} dimensions must be positive`);finite3(value.x+value.width,`${name} right edge`);finite3(value.y+value.height,`${name} bottom edge`)}function identifier(id,name){if(typeof id!=="string"||!id.trim())throw new Error(`${name} must be a nonempty ID`)}function alpha2(value){finite3(value,"Routed transfer opacity");return Math.max(0,Math.min(1,value))}function expanded(box,clearance){return{left:box.x-clearance,top:box.y-clearance,right:box.x+box.width+clearance,bottom:box.y+box.height+clearance}}function lengthOf(points){let sum=0;for(let i=1;i<points.length;i++)sum+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);return sum}function trimLeads(points,amount2){const length=lengthOf(points);if(length<=2*amount2)throw new Error("endpoint spacing leaves no positive-length clear transfer");const result=[pointAlongSamples(points,amount2/length)];let distance=0;for(let i=1;i<points.length;i++){distance+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);if(distance>amount2+1e-6&&distance<length-amount2-1e-6)result.push(points[i])}result.push(pointAlongSamples(points,1-amount2/length));return result}function parameters(options){identifier(options.id,"Routed transfer ID");identifier(options.source.id,"Routed transfer source");identifier(options.target.id,"Routed transfer target");if(options.source.id===options.target.id)throw new Error("Routed transfer source and target IDs must differ");bounds3(options.source.shape,"Routed transfer source");bounds3(options.target.shape,"Routed transfer target");bounds3(options.corridor,"Routed transfer corridor");const ids=new Set([options.source.id,options.target.id]);for(const obstacle of options.obstacles){identifier(obstacle.id,"Routed transfer obstacle");if(ids.has(obstacle.id))throw new Error(`Duplicate routed transfer object ID: ${obstacle.id}`);ids.add(obstacle.id);bounds3(obstacle.bounds,`Routed transfer obstacle ${obstacle.id}`)}const width=options.width??3,margin=options.margin??2;nonnegative3(width,"Routed transfer width");if(width===0)throw new Error("Routed transfer width must be positive");nonnegative3(margin,"Routed transfer margin");if(options.progress!==void 0)finite3(options.progress,"Routed transfer progress");if(options.marker&&options.progress===void 0)throw new Error("Routed transfer marker requires progress");const radius=options.marker?.radius??7,strokeWidth=options.marker?.strokeWidth??3;nonnegative3(radius,"Routed transfer marker radius");if(radius===0)throw new Error("Routed transfer marker radius must be positive");nonnegative3(strokeWidth,"Routed transfer marker stroke width");const markerInk=options.progress===void 0?0:radius+(options.marker?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerInk)+margin;const opacity=Math.min(alpha2(options.source.opacity),alpha2(options.target.opacity),alpha2(options.opacity??1));return{width,margin,radius,strokeWidth,clearance,opacity}}function planTeachingRoutedTransfer(options){const{clearance}=parameters(options);const fail=reason=>{throw new Error(`Cannot route transfer ${options.id} (${options.source.id} \u2192 ${options.target.id}): ${reason}`)};const guard=clearance+.01,corridor=options.corridor;if(corridor.width<=2*guard||corridor.height<=2*guard)fail("corridor is too small for the requested ink clearance");const origin={x:corridor.x+guard,y:corridor.y+guard};const toLocal=shape2=>{const x=shape2.x-origin.x,y=shape2.y-origin.y;finite3(x,"Routed transfer local x");finite3(y,"Routed transfer local y");return{x:Number(x.toFixed(6)),y:Number(y.toFixed(6)),width:shape2.width,height:shape2.height}};const endpoints=[options.source,options.target];const nodes=endpoints.map(endpoint=>{const b=toLocal(endpoint.shape);return{id:endpoint.id,cx:b.x+b.width/2,cy:b.y+b.height/2,width:b.width,height:b.height}});const obstacles=options.obstacles.map(obstacle=>expanded(toLocal(obstacle.bounds),0));const result=routeOrthogonalGraph(nodes,[{from:options.source.id,to:options.target.id,fromSide:options.source.side,toSide:options.target.side}],corridor.width-2*guard,corridor.height-2*guard,guard,14,obstacles);const raw=result.routes.get(0);if(!raw)return fail(result.failures[0]?.reason??"no legal route was returned");const points=(()=>{try{return trimLeads(raw,guard).map(point=>({x:point.x+origin.x,y:point.y+origin.y}))}catch(error){return fail(error instanceof Error?error.message:String(error))}})();const occupied=[...endpoints.map(endpoint=>expanded(endpoint.shape,clearance)),...options.obstacles.map(obstacle=>expanded(obstacle.bounds,clearance))];for(const point of points){if(point.x<corridor.x+clearance||point.x>corridor.x+corridor.width-clearance||point.y<corridor.y+clearance||point.y>corridor.y+corridor.height-clearance)fail("route ink leaves the permitted corridor")}for(let i=1;i<points.length;i++){if(occupied.some(obstacle=>routingSegmentBlocked(points[i-1],points[i],obstacle)))fail("a complete route segment violates object clearance")}const immutable=Object.freeze(points.map(point=>Object.freeze(point)));return{id:options.id,source:options.source,target:options.target,points:immutable,length:lengthOf(immutable),clearance,positionAt(progress){finite3(progress,"Routed transfer progress");return pointAlongSamples(immutable,Math.max(0,Math.min(1,progress)))}}}function createTeachingRoutedTransfer(painter){return options=>{const{width,radius,strokeWidth,opacity}=parameters(options);if(opacity===0)return null;const route=planTeachingRoutedTransfer(options),color=options.color??"#63DEEC";const paint=()=>painter.opacity(opacity,()=>{painter.path(route.points,{id:`${options.id}:route`,color,width});if(options.progress!==void 0&&options.progress>0&&options.progress<1){const point=route.positionAt(options.progress);painter.circle(point.x,point.y,radius,options.marker?.fill??color,options.marker?.stroke,strokeWidth)}});if(painter.target)painter.target(options.focusTarget??options.id,paint);else paint();return route}}function compareByteSequences(before,after){if(!(before instanceof Uint8Array)||!(after instanceof Uint8Array)){throw new Error("Byte comparison requires two Uint8Arrays")}const left=Array.from(before),right=Array.from(after);let commonPrefix=0,commonSuffix=0;while(commonPrefix<Math.min(left.length,right.length)&&left[commonPrefix]===right[commonPrefix])commonPrefix++;while(commonSuffix<Math.min(left.length,right.length)-commonPrefix&&left[left.length-commonSuffix-1]===right[right.length-commonSuffix-1])commonSuffix++;const columns=[];const add2=(oldOffset,newOffset)=>{const oldByte=oldOffset===null?null:{offset:oldOffset,value:left[oldOffset]};const newByte=newOffset===null?null:{offset:newOffset,value:right[newOffset]};const kind=!oldByte?"insert":!newByte?"delete":oldByte.value===newByte.value?"equal":"replace";columns.push({id:`before:${oldOffset??"none"}|after:${newOffset??"none"}`,kind,before:oldByte,after:newByte})};for(let offset=0;offset<commonPrefix;offset++)add2(offset,offset);const leftMiddle=left.length-commonPrefix-commonSuffix;const rightMiddle=right.length-commonPrefix-commonSuffix;for(let offset=0;offset<Math.max(leftMiddle,rightMiddle);offset++){add2(offset<leftMiddle?commonPrefix+offset:null,offset<rightMiddle?commonPrefix+offset:null)}for(let offset=0;offset<commonSuffix;offset++){add2(left.length-commonSuffix+offset,right.length-commonSuffix+offset)}return{algorithm:"common-prefix/suffix with positional middle",beforeLength:left.length,afterLength:right.length,commonPrefix,commonSuffix,equal:left.length===right.length&&commonPrefix===left.length,columns}}function escapedByte(value){if(!Number.isInteger(value)||value<0||value>255)throw new Error("A byte must be an integer from 0 through 255");if(value===0)return"\\0";if(value===9)return"\\t";if(value===10)return"\\n";if(value===13)return"\\r";if(value===32)return"space";if(value===92)return"\\\\";if(value>=33&&value<=126)return String.fromCharCode(value);return`\\x${value.toString(16).padStart(2,"0").toUpperCase()}`}function byteDifferenceState(options){if(!Number.isFinite(options.scanProgress))throw new Error("Byte scan progress must be finite");const comparison=compareByteSequences(options.before,options.after);const progress=Math.max(0,Math.min(1,options.scanProgress));const scannedColumns=Math.floor(progress*comparison.columns.length);return{comparison,progress,scannedColumns,scanComplete:progress===1,verdict:options.revealVerdict?comparison.equal?"equal":"different":null}}function layoutByteDifference(options){const{x,y,width,height,fontSize=28,maxColumns=10}=options;if(![x,y,width,height,fontSize,x+width,y+height].every(Number.isFinite)||width<=0||height<=0||fontSize<=0){throw new Error("Byte strip bounds and font size must be finite with positive dimensions")}if(fontSize<24)throw new Error("Byte strip font size must be at least 24 px for checked label padding");if(!Number.isSafeInteger(maxColumns)||maxColumns<1)throw new Error("Byte window size must be a positive safe integer");const state=byteDifferenceState(options),all=state.comparison.columns;const start=options.startColumn??Math.max(0,state.comparison.commonPrefix-2);if(!Number.isSafeInteger(start)||start<0||start>all.length||all.length>0&&start===all.length){throw new Error("Byte window start is outside the alignment")}const columns=all.slice(start,start+maxColumns),count=Math.max(1,columns.length);const gutter=fontSize*5.2,cellWidth=(width-gutter)/count;const longest=Math.max(5,...columns.flatMap(column=>[column.before,column.after].map(byte=>byte?String(byte.offset).length+1:5)));if(cellWidth<fontSize*.65*longest+12||height<fontSize*10){throw new Error("Byte strip cannot fit its byte labels and offsets")}const headerHeight=fontSize*1.7,footerHeight=fontSize*1.7,rowHeight=(height-headerHeight-footerHeight)/2;if(cellWidth<=4||rowHeight<=4||gutter-8<=8||headerHeight<=8||footerHeight<=8||rowHeight*.3<=8){throw new Error("Byte strip cannot fit positive cell insets and checked label padding")}const cells=columns.map((column,index)=>({column,alignmentIndex:start+index,beforeBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight,width:cellWidth,height:rowHeight},afterBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight+rowHeight,width:cellWidth,height:rowHeight}}));return{...state,bounds:{x,y,width,height},cells,gutter,headerHeight,footerHeight,rowHeight,omittedLeading:start,omittedTrailing:all.length-start-columns.length}}function createTeachingByteDifference(painter){return options=>{const layout=layoutByteDifference(options);const{x,y,width,height,fontSize=28,fill="#101820",stroke="#516376",textColor="#E9EFFF",mutedColor="#91A3B8",scanColor="#63DEEC",changeColor="#F4D477",beforeLabel="Before",afterLabel="After"}=options;const label=(value,bounds4,size,color=textColor)=>painter.labelScope(bounds4,()=>{painter.text(value,bounds4.x+bounds4.width/2,bounds4.y+bounds4.height/2+size*.34,size,color,"center","mono")},{padding:4});painter.container(layout.bounds,()=>{label("Prefix/suffix alignment; positional middle; not minimum edits",{x,y,width,height:layout.headerHeight},fontSize*.63,mutedColor);for(const[row,name]of[beforeLabel,afterLabel].entries()){label(name,{x,y:y+layout.headerHeight+row*layout.rowHeight,width:layout.gutter-8,height:layout.rowHeight},fontSize*.72)}for(const cell of layout.cells){const visited=cell.alignmentIndex<layout.scannedColumns;const color=visited?cell.column.kind==="equal"?mutedColor:changeColor:stroke;for(const[byte,bounds4]of[[cell.column.before,cell.beforeBounds],[cell.column.after,cell.afterBounds]]){painter.rect(bounds4.x+2,bounds4.y+2,bounds4.width-4,bounds4.height-4,fill,color,0);label(byte?`@${byte.offset}`:"none",{...bounds4,height:bounds4.height*.3},fontSize*.65,mutedColor);label(byte?byte.value.toString(16).padStart(2,"0").toUpperCase():"--",{...bounds4,y:bounds4.y+bounds4.height*.3,height:bounds4.height*.35},fontSize,visited?textColor:mutedColor);label(byte?escapedByte(byte.value):"no byte",{...bounds4,y:bounds4.y+bounds4.height*.65,height:bounds4.height*.35},fontSize*.7,mutedColor)}}if(!layout.cells.length){for(const row of[0,1])label("empty",{x:x+layout.gutter,y:y+layout.headerHeight+row*layout.rowHeight,width:width-layout.gutter,height:layout.rowHeight},fontSize,mutedColor)}const scanPosition=layout.progress*layout.comparison.columns.length-layout.omittedLeading;if(layout.cells.length&&scanPosition>=0&&scanPosition<=layout.cells.length){const cellWidth=layout.cells[0].beforeBounds.width;const cursor=Math.max(1,Math.min(width-layout.gutter-1,scanPosition*cellWidth));painter.rect(x+layout.gutter+cursor-1,y+layout.headerHeight-7,2,5,scanColor,void 0,0)}const verdict=layout.verdict===null?"Verdict held":layout.verdict==="equal"?"Bytes equal":"Bytes differ";label(`${layout.omittedLeading} columns before window; ${layout.omittedTrailing} after \xB7 ${verdict}`,{x,y:y+height-layout.footerHeight,width,height:layout.footerHeight},fontSize*.66,layout.verdict===null?mutedColor:textColor)},{padding:0});return layout}}function tokens(input,name){if(!Array.isArray(input))throw new Error(`Token history ${name} must be an array`);return Object.freeze(input.map(item=>{if(!item||typeof item.id!=="string"||!item.id.trim()||item.id!==item.id.trim()){throw new Error("Token occurrence IDs must be nonempty without surrounding whitespace")}if(!(typeof item.token==="string"&&item.token.trim())&&!(typeof item.token==="number"&&Number.isSafeInteger(item.token)&&item.token>=0)){throw new Error("History tokens require nonempty text or a nonnegative safe integer vocabulary ID")}return Object.freeze({id:item.id,token:item.token})}))}function equal(left,right){return left.id===right.id&&left.token===right.token}function prefix(part,whole,name){if(part.length>whole.length||part.some((token,index)=>!equal(token,whole[index]))){throw new Error(`Token history ${name} must preserve the exact ordered occurrence prefix`)}}function tokenHistoryState(options){const prompt=tokens(options.prompt,"prompt"),accepted=tokens(options.accepted,"accepted");const processed=tokens(options.processed,"processed"),emitted=tokens(options.emitted,"emitted");const history=Object.freeze([...prompt,...accepted]);if(new Set(history.map(token=>token.id)).size!==history.length){throw new Error("Token history requires distinct occurrence IDs, including repeated vocabulary tokens")}prefix(processed,history,"processed");prefix(emitted,accepted,"emitted");if(accepted.length&&processed.length<prompt.length)throw new Error("Accepted output requires the complete processed prompt");if(accepted.length&&processed.length<prompt.length+accepted.length-1){throw new Error("Ordinary decoding permits at most one accepted token awaiting processing")}const phase=options.phase??"resident";if(!["resident","dropped","replay"].includes(phase))throw new Error("Unknown token history phase");if(phase==="replay"&&options.replayProgress===void 0)throw new Error("Replay requires explicit progress");const replayProgress=options.replayProgress??0;if(!Number.isFinite(replayProgress)||replayProgress<0||replayProgress>1){throw new Error("Replay progress must be finite between zero and one")}const position2=replayProgress*processed.length;const completed=phase==="resident"?processed.length:phase==="dropped"?0:Math.floor(position2);const fraction=position2-Math.floor(position2);const moving=phase==="replay"&&fraction>0&&completed<processed.length?Object.freeze({token:processed[completed],position:completed,progress:fraction}):null;return Object.freeze({prompt,accepted,processed,emitted,history,phase,replayProgress,kv:Object.freeze(processed.slice(0,completed)),pendingAccepted:Object.freeze(accepted.filter((_,index)=>prompt.length+index>=processed.length)),moving})}function assertTokenHistoryTransition(before,after){before=tokenHistoryState(before);after=tokenHistoryState(after);prefix(before.prompt,after.prompt,"prompt transition");if(before.prompt.length!==after.prompt.length)throw new Error("A request prompt cannot change during its history");prefix(before.accepted,after.accepted,"accepted transition");prefix(before.emitted,after.emitted,"emitted transition");if(before.phase!=="resident"||after.phase!=="resident"){if(before.accepted.length!==after.accepted.length||before.emitted.length!==after.emitted.length){throw new Error("Drop and replay transitions cannot sample or emit new output")}prefix(before.processed,after.processed,"replay target");if(before.processed.length!==after.processed.length)throw new Error("Replay must rebuild the retained processed prefix")}else if(after.processed.length<before.processed.length){throw new Error("Resident processed history cannot shrink without an explicit drop or replay")}}function createTeachingTokenHistory(painter){return options=>{const state=tokenHistoryState(options);const{x,y,width,height,fontSize=28,gap=8,labelWidth=245,focusPrefix}=options;if(![x,y,x+width,y+height,width,height,fontSize,gap,labelWidth].every(Number.isFinite)||width<=0||height<=0||fontSize<=0||gap<0||labelWidth<=0){throw new Error("Token history drawing bounds and sizes must be finite and positive")}const columns=Math.max(1,state.history.length),top=fontSize*1.9,bottom=fontSize*2;const cellWidth=(width-labelWidth-gap*(columns-1)-4)/columns;const laneHeight=(height-top-bottom)/5,cellHeight=laneHeight-gap;if(cellWidth<fontSize*2.2||cellHeight<fontSize*1.6||labelWidth<fontSize*5){throw new Error("Token history bounds must fit its occurrence columns and five readable lanes")}const color={prompt:"#7FA7FF",accepted:"#92E28C",processed:"#63DEEC",kv:"#63DEEC",emitted:"#92E28C",pending:"#FFD75E",empty:"#586278",text:"#F2EFE6",fill:"#141820",...options.colors};const lanes=[{id:"prompt",label:"Prompt",tokens:state.prompt,offset:0},{id:"accepted",label:"Accepted output",tokens:state.accepted,offset:state.prompt.length},{id:"processed",label:"Processed prefix",tokens:state.processed,offset:0},{id:"kv",label:"Resident KV",tokens:state.kv,offset:0},{id:"emitted",label:"Already delivered",tokens:state.emitted,offset:state.prompt.length}];const pending2=new Set(state.pendingAccepted.map(token=>token.id));const bounds4={x,y,width,height};const target=(id,draw2)=>{if(id&&painter.target)painter.target(id,draw2);else draw2()};const cell=(position2,row)=>({x:x+labelWidth+1+position2*(cellWidth+gap),y:y+top+row*laneHeight,width:cellWidth,height:cellHeight});const paintToken=(token,shape2,stroke,fill=color.fill)=>{painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,fill,stroke,7);painter.labelScope(shape2,()=>painter.text(String(token.token),shape2.x+shape2.width/2,shape2.y+shape2.height/2+fontSize*.34,fontSize,color.text,"center","mono"),{padding:5})};painter.container(bounds4,()=>{for(let position2=0;position2<state.history.length;position2+=1){const shape2=cell(position2,0);painter.labelScope({...shape2,y,height:top},()=>painter.text(`position ${position2}`,shape2.x+shape2.width/2,y+fontSize,fontSize*.7,color.empty,"center"),{padding:3})}lanes.forEach((lane,row)=>target(focusPrefix?`${focusPrefix}-${lane.id}`:void 0,()=>{const labelBounds={x,y:y+top+row*laneHeight,width:labelWidth-gap,height:cellHeight};painter.labelScope(labelBounds,()=>painter.text(lane.label,x+5,labelBounds.y+cellHeight/2+fontSize*.34,fontSize*.82,color[lane.id]),{padding:3});for(let position2=0;position2<columns;position2+=1){const shape2=cell(position2,row),token=lane.tokens[position2-lane.offset];if(token){const isPending=lane.id==="accepted"&&pending2.has(token.id);target(isPending&&focusPrefix?`${focusPrefix}-pending`:void 0,()=>paintToken(token,shape2,isPending?color.pending:color[lane.id],lane.id==="processed"?"transparent":color.fill))}else painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,"transparent",color.empty,7)}}));if(state.moving){const from=cell(state.moving.position,2),to2=cell(state.moving.position,3);const progress=state.moving.progress;const settle=Math.max(0,(progress-.65)/.35);const grow2=Math.max(0,(progress-.8)/.2);const copyWidth=Math.min(from.width,fontSize*3);const copyHeight=Math.min(from.height,fontSize*1.8);const movingWidth=copyWidth+(from.width-copyWidth)*grow2;const movingHeight=copyHeight+(from.height-copyHeight)*grow2;const startInset=Math.min(7,from.width-copyWidth);const startCenterX=from.x+startInset+copyWidth/2;const centerX=startCenterX+(from.x+from.width/2-startCenterX)*settle;const centerY=from.y+from.height/2+(to2.y-from.y)*progress;const moving={x:centerX-movingWidth/2,y:centerY-movingHeight/2,width:movingWidth,height:movingHeight};target(focusPrefix?`${focusPrefix}-replay`:void 0,()=>paintToken(state.moving.token,moving,color.kv))}const pendingText=state.pendingAccepted.map(token=>String(token.token)).join(", ");const message=state.phase==="replay"?"Replay rebuilds KV; no sampling or delivery":state.phase==="dropped"?"KV released; accepted and delivered history retained":pendingText?`Accepted but unprocessed: ${pendingText}`:"All accepted positions are processed";painter.labelScope({x,y:y+height-bottom,width,height:bottom},()=>painter.text(message,x+width/2,y+height-fontSize*.6,fontSize*.82,state.phase==="replay"?color.kv:color.pending,"center"),{padding:3})},{padding:0});return state}}var INK="#8D9CB9";var ACCENT="#63DEEC";var PANEL="#18283B";function finite4(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function positive4(value,name){finite4(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function boundsOf(options){finite4(options.x,"Teaching x");finite4(options.y,"Teaching y");positive4(options.width,"Teaching width");positive4(options.height,"Teaching height");return{x:options.x,y:options.y,width:options.width,height:options.height}}function amount(value,name="Teaching progress"){finite4(value,name);return Math.max(0,Math.min(1,value))}function domainOf(domain,name){finite4(domain[0],`${name} start`);finite4(domain[1],`${name} end`);if(domain[1]<=domain[0]||!Number.isFinite(domain[1]-domain[0])){throw new Error(`${name} must have a finite positive span`)}return[domain[0],domain[1]]}function createTeachingCanvas(painter){const components=createCanvasComponents(painter);function axes2(options){let bounds4=boundsOf(options);const xDomain=domainOf(options.xDomain,"Plot x domain");const yDomain=domainOf(options.yDomain,"Plot y domain");if(options.equalUnits){const xSpan=xDomain[1]-xDomain[0];const ySpan=yDomain[1]-yDomain[0];const pixelsPerUnit=Math.min(bounds4.width/xSpan,bounds4.height/ySpan);const width2=xSpan*pixelsPerUnit;const height2=ySpan*pixelsPerUnit;bounds4=boundsOf({x:bounds4.x+(bounds4.width-width2)/2,y:bounds4.y+(bounds4.height-height2)/2,width:width2,height:height2})}const{x,y,width,height}=bounds4;const{color=INK,gridColor,fontSize=28,xTicks=[],yTicks=[],formatX=String,formatY=String}=options;positive4(fontSize,"Axis font size");xTicks.forEach(tick=>finite4(tick,"Axis x tick"));yTicks.forEach(tick=>finite4(tick,"Axis y tick"));const plot={bounds:bounds4,xDomain,yDomain,point(px,py){finite4(px,"Plot point x");finite4(py,"Plot point y");const point={x:x+(px-xDomain[0])/(xDomain[1]-xDomain[0])*width,y:y+height-(py-yDomain[0])/(yDomain[1]-yDomain[0])*height};finite4(point.x,"Mapped point x");finite4(point.y,"Mapped point y");return point}};for(const tick of xTicks){if(tick<xDomain[0]||tick>xDomain[1])continue;const point=plot.point(tick,yDomain[0]);if(gridColor)painter.path([{x:point.x,y},{x:point.x,y:y+height}],{color:gridColor,width:1,clip:bounds4});painter.line(point.x,y+height,point.x,y+height+7,color,2);painter.text(formatX(tick),point.x,y+height+36,fontSize,color,"center")}for(const tick of yTicks){if(tick<yDomain[0]||tick>yDomain[1])continue;const point=plot.point(xDomain[0],tick);if(gridColor)painter.path([{x,y:point.y},{x:x+width,y:point.y}],{color:gridColor,width:1,clip:bounds4});painter.line(x-7,point.y,x,point.y,color,2);painter.text(formatY(tick),x-18,point.y+9,fontSize,color,"right")}painter.line(x,y+height,x+width,y+height,color,2);painter.line(x,y,x,y+height,color,2);if(options.xLabel)painter.text(options.xLabel,x+width/2,y+height+72,30,color,"center");if(options.yLabel)painter.text(options.yLabel,x,y-26,30,color,"left");return plot}function curve2(options){const{plot,points,color,width=4,progress=1}=options;positive4(width,"Curve width");const mapped=points.map(point=>plot.point(point.x,point.y));const visible=tracePolyline(mapped,progress);if(visible.length>1)painter.path(visible,{color,width,clip:plot.bounds});return visible}function scatter2(options){const{plot,points,color=ACCENT,radius=7,opacity=1}=options;positive4(radius,"Scatter radius");const alpha3=amount(opacity,"Scatter opacity");const projected=points.map(point=>{positive4(point.radius??radius,"Scatter point radius");return{...plot.point(point.x,point.y),radius:point.radius??radius,color:point.color??color,inDomain:point.x>=plot.xDomain[0]&&point.x<=plot.xDomain[1]&&point.y>=plot.yDomain[0]&&point.y<=plot.yDomain[1]}});const shapes=[];if(alpha3===0)return shapes;painter.opacity(alpha3,()=>{for(const point of projected){if(!point.inDomain)continue;shapes.push(painter.circle(point.x,point.y,point.radius,point.color))}});return shapes}function bars(options){const bounds4=boundsOf(options);const{x,y,width,height}=bounds4;const{values,labels,colors:colors2,color=ACCENT,progress=1,showValues=false,format=String,fontSize=28,gap=20}=options;positive4(fontSize,"Bar font size");finite4(gap,"Bar gap");if(gap<0)throw new Error("Bar gap must be nonnegative");values.forEach(value=>{finite4(value,"Bar value");if(value<0)throw new Error("Bar values must be nonnegative")});if(labels&&labels.length!==values.length)throw new Error("Bar labels must match values");if(colors2&&colors2.length!==values.length)throw new Error("Bar colors must match values");const maximumValue=values.reduce((maximum2,value)=>Math.max(maximum2,value),0);const maximum=options.max??(maximumValue||1);positive4(maximum,"Bar maximum");if(maximum<maximumValue)throw new Error("Bar maximum must contain every value");const reveal2=amount(progress);if(!values.length)return{bars:[],slots:[],bounds:bounds4};const barWidth=(width-gap*(values.length-1))/values.length;positive4(barWidth,"Bar width after gaps");const shapes=[];const slots=[];values.forEach((value,index)=>{const left=x+index*(barWidth+gap);const barHeight=value/maximum*height*reveal2;slots.push({x:left,y,width:barWidth,height});shapes.push(barHeight>0?painter.rect(left,y+height-barHeight,barWidth,barHeight,colors2?.[index]??color,void 0,Math.min(8,barWidth/2,barHeight/2)):null);if(labels)painter.text(labels[index],left+barWidth/2,y+height+38,fontSize,INK,"center");if(showValues&&reveal2>0)painter.text(format(value),left+barWidth/2,y+height-barHeight-14,fontSize,colors2?.[index]??color,"center")});return{bars:shapes,slots,bounds:bounds4}}function flowGraph(options){const{nodes,edges,stroke=ACCENT,fill=PANEL,textColor="#FFFFFF",padding=12}=options;finite4(padding,"Flow node padding");if(padding<0)throw new Error("Flow node padding must be nonnegative");const descriptors=Object.create(null);for(const node of nodes){if(!node.id||Object.hasOwn(descriptors,node.id))throw new Error("Flow node IDs must be nonempty and unique");const bounds4=boundsOf(node);positive4(node.fontSize??30,"Flow node font size");finite4(node.radius??14,"Flow node radius");if((node.radius??14)<0)throw new Error("Flow node radius must be nonnegative");descriptors[node.id]={...bounds4,radius:node.radius??14}}for(const edge of edges){if(!Object.hasOwn(descriptors,edge.from)||!Object.hasOwn(descriptors,edge.to))throw new Error("Flow edge must reference existing nodes");if(edge.from===edge.to)throw new Error("Flow edges must connect distinct nodes");if(edge.progress!==void 0)amount(edge.progress);if(edge.width!==void 0)positive4(edge.width,"Flow edge width");for(const gap of[edge.gap,edge.fromGap,edge.toGap]){if(gap!==void 0)finite4(gap,"Flow edge gap")}}const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const routes=edges.map(edge=>target(edge.focusTarget,()=>{const{from,to:to2,progress,focusTarget:_focusTarget,...style}=edge;const route=painter.connect(descriptors[from],descriptors[to2],{color:stroke,...style});if(progress!==void 0)components.particle({points:[route.from,route.to],progress,radius:7,fill:style.color??stroke});return route}));for(const node of nodes){const shape2=target(node.focusTarget,()=>components.card({...descriptors[node.id],label:node.label,id:node.id,fill:node.fill??fill,stroke:node.color??stroke,textColor,fontSize:node.fontSize??30,padding}));Object.assign(descriptors[node.id],shape2)}return{nodes:descriptors,routes}}return{axes:axes2,curve:curve2,scatter:scatter2,bars,flowGraph,transfer:createTeachingTransfer(painter),routedTransfer:createTeachingRoutedTransfer(painter),grid:createTeachingGrid(painter),timeline:createTeachingTimeline(painter),allocation:createTeachingAllocation(painter),vectorAccumulation:createTeachingVectorAccumulation(painter),categoricalSampling:createTeachingCategoricalSampling(painter),byteDifference:createTeachingByteDifference(painter),tokenHistory:createTeachingTokenHistory(painter),...createTeachingValueChange(painter),...createTeachingFocus(painter)}}function position(beat,progress){if(!Number.isSafeInteger(beat)||beat<0)throw new Error("Cue beat must be a nonnegative safe integer");if(!Number.isFinite(progress)||progress<0||progress>1)throw new Error("Cue progress must be between zero and one");if(progress===1){if(!Number.isSafeInteger(beat+1))throw new Error("Cue position exceeds the safe integer range");return{beat:beat+1,beatP:0}}return{beat,beatP:progress}}function compare(left,right){return left.beat===right.beat?left.beatP-right.beatP:left.beat-right.beat}function createCueTrack(options){const ids=new Set;const entry=({id,snapshot})=>{if(typeof id!=="string"||!id.trim()||ids.has(id))throw new Error("Cue IDs must be nonempty and unique");ids.add(id);return Object.freeze({id,snapshot})};const initial=entry(options.initial);const cues=options.cues.map(cue=>({position:position(cue.beat,cue.at),value:entry(cue)}));for(let index=1;index<cues.length;index+=1){if(compare(cues[index-1].position,cues[index].position)>=0){throw new Error("Cue positions must be strictly increasing")}}return Object.freeze({sample(current){const at=position(current.beat,current.beatP);let low=0,high=cues.length;while(low<high){const middle=Math.floor((low+high)/2);if(compare(cues[middle].position,at)<=0)low=middle+1;else high=middle}return low===0?initial:cues[low-1].value}})}function clampProgress2(progress){if(!Number.isFinite(progress))throw new Error("Camera progress must be finite");return Math.max(0,Math.min(1,progress))}function assertCamera(camera,context){if(!Number.isFinite(camera.x)||!Number.isFinite(camera.y)){throw new Error(`${context} coordinates must be finite`)}if(!Number.isFinite(camera.zoom)||camera.zoom<=0){throw new Error(`${context} zoom must be finite and greater than zero`)}}function assertViewport(viewport){if(!Number.isFinite(viewport.width)||viewport.width<=0){throw new Error("Camera viewport width must be finite and greater than zero")}if(!Number.isFinite(viewport.height)||viewport.height<=0){throw new Error("Camera viewport height must be finite and greater than zero")}}function assertZoomConstraints(options){const{minZoom,maxZoom}=options;if(minZoom!==void 0&&(!Number.isFinite(minZoom)||minZoom<=0)){throw new Error("Camera minZoom must be finite and greater than zero")}if(maxZoom!==void 0&&(!Number.isFinite(maxZoom)||maxZoom<=0)){throw new Error("Camera maxZoom must be finite and greater than zero")}if(minZoom!==void 0&&maxZoom!==void 0&&minZoom>maxZoom){throw new Error("Camera minZoom cannot exceed maxZoom")}}function assertZoomInRange(camera,options){if(options.minZoom!==void 0&&camera.zoom<options.minZoom||options.maxZoom!==void 0&&camera.zoom>options.maxZoom){throw new Error("Camera zoom is outside the configured range")}}function interpolateLinear(from,to2,progress){return from*(1-progress)+to2*progress}function interpolateCamera(from,to2,progress,options={}){assertCamera(from,"Camera start");assertCamera(to2,"Camera end");assertZoomConstraints(options);assertZoomInRange(from,options);assertZoomInRange(to2,options);const amount2=clampProgress2(progress);if(amount2===0)return{...from};if(amount2===1)return{...to2};const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Camera easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return{...from};if(t===1)return{...to2};const camera={x:interpolateLinear(from.x,to2.x,t),y:interpolateLinear(from.y,to2.y,t),zoom:Math.exp(Math.log(from.zoom)*(1-t)+Math.log(to2.zoom)*t)};assertCamera(camera,"Camera result");assertZoomInRange(camera,options);return camera}function cameraSvgTransform(camera,viewport){assertCamera(camera,"Camera");assertViewport(viewport);return`translate(${viewport.width/2} ${viewport.height/2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`}function projectWorldPoint(point,camera,viewport){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error("World point coordinates must be finite")}assertCamera(camera,"Camera");assertViewport(viewport);const projected={x:viewport.width/2+(point.x-camera.x)*camera.zoom,y:viewport.height/2+(point.y-camera.y)*camera.zoom};if(!Number.isFinite(projected.x)||!Number.isFinite(projected.y)){throw new Error("Projected world point coordinates must be finite")}return projected}var DEFAULT_MORPH_SAMPLES=64;var MAX_MORPH_SAMPLES=4096;function clampProgress3(progress){if(!Number.isFinite(progress))throw new Error("Polyline morph progress must be finite");return Math.max(0,Math.min(1,progress))}function validatePolyline(points,context){if(!Array.isArray(points)||points.length===0){throw new Error(`${context} polyline must be a non-empty array`)}for(let index=0;index<points.length;index+=1){const point=points[index];if(!point||!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} point ${index} coordinates must be finite`)}}}function validateSamples(samples){if(!Number.isInteger(samples)||samples<2){throw new Error("Polyline morph samples must be an integer of at least 2")}if(samples>MAX_MORPH_SAMPLES){throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`)}}function resamplePolyline(points,samples){const lengths=points.slice(1).map((point,index)=>Math.hypot(point.x-points[index].x,point.y-points[index].y));const total=lengths.reduce((sum,length)=>sum+length,0);if(!Number.isFinite(total))throw new Error("Polyline morph arc length must be finite");if(total===0)return Array.from({length:samples},()=>({...points[0]}));let segment=0;let offset=0;return Array.from({length:samples},(_,index)=>{if(index===samples-1)return{...points[points.length-1]};const distance=total*(index/(samples-1));while(segment<lengths.length-1&&(lengths[segment]===0||distance>offset+lengths[segment])){offset+=lengths[segment++]}const t=(distance-offset)/lengths[segment];const from=points[segment],to2=points[segment+1];return{x:from.x*(1-t)+to2.x*t,y:from.y*(1-t)+to2.y*t}})}function createPolylineMorph(from,to2,options={}){validatePolyline(from,"Start");validatePolyline(to2,"End");const samples=options.samples??DEFAULT_MORPH_SAMPLES;validateSamples(samples);const startSamples=resamplePolyline(from,samples);const endSamples=resamplePolyline(to2,samples);const easing=options.easing??smoothstep;return progress=>{const amount2=clampProgress3(progress);const eased=amount2===0||amount2===1?amount2:easing(amount2);if(!Number.isFinite(eased))throw new Error("Polyline morph easing must return a finite number");const t=Math.max(0,Math.min(1,eased));return startSamples.map((start,index)=>{const end=endSamples[index];return{x:start.x*(1-t)+end.x*t,y:start.y*(1-t)+end.y*t}})}}function morphPolyline(from,to2,progress,options={}){return createPolylineMorph(from,to2,options)(progress)}function graphImportResult(source,graph2,diagnostics){if(graph2.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:graph2,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line2,code,severity,message,column=1){diagnostics.push({code,severity,message,line:line2,column,excerpt:(sourceLines[line2-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line2,index){while(index<line2.length&&/\s/.test(line2[index]??""))index++;return index}function readDelimited(line2,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line2.length;index++){const character=line2[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line2.startsWith(close,index)){return{value:line2.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(line2,from){let index=skipWhitespace(line2,from);const id=line2.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line2,index);if(afterId>=line2.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line2.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(line2,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,endpoint,groupId,line2,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint.id)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint.label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint.label}else{state.nodeIndexes.set(endpoint.id,state.nodes.length);state.nodes.push({id:endpoint.id,label:endpoint.label,...groupId?{group:groupId}:{}})}if(endpoint.shape==="lossy"&&!state.warnedShapes.has(endpoint.id)){state.warnedShapes.add(endpoint.id);addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line2,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line2,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line2,first.next);const hasConnector=CONNECTORS.some(connector2=>line2.startsWith(connector2,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line2,cursor);if(cursor>=line2.length)return;const connector2=CONNECTORS.find(candidate=>line2.startsWith(candidate,cursor));if(!connector2){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+=connector2.length;cursor=skipWhitespace(line2,cursor);let edgeLabel;if(line2[cursor]==="|"){const end=line2.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=line2.slice(cursor+1,end).trim();cursor=skipWhitespace(line2,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(line2,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}:{},...connector2==="---"?{arrow:"none"}:connector2==="-.->"?{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 direction2="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(line2.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line2.startsWith("%%"))continue;if(!sawHeader){const header=line2.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();direction2=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line2.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(line2)){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(line2)){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(line2)){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(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line2,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 graph2={nodes:state.nodes,edges:state.edges,groups:state.groups,direction:direction2};return graphImportResult("mermaid",graph2,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(line2){let quote;let escaped=false;for(const character of line2){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,line2,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line2,"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,line2,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line2,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 direction2="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)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(line2.startsWith("#"))continue;if(hasUnquotedHash(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line2.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line2.includes("{")||line2.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=line2.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction2=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape2=decodeD2Label(shapeMatch[2]??"");if(!id||shape2===void 0||shape2===""){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:shape2,line:lineNumber});continue}const edgeMatch=line2.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 connector2=edgeMatch[2];const to2=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector2||!to2)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,to2,to2,lineNumber,sourceLines,diagnostics,false);edges.push({from,to:to2,...label!==void 0?{label}:{},arrow:connector2==="<->"?"both":connector2==="<-"?"backward":connector2==="--"?"none":"forward"});continue}const nodeMatch=line2.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(line2.includes(".style")||line2.includes(".width")||line2.includes(".height")||line2.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(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line2)){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:line2}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line2,"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:direction2},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage}from"async_hooks";import{tmpdir}from"os";import{join}from"path";import parseCssColor2 from"parse-css-color";import{Children,isValidElement}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.text_overflow","layout.whitespace_imbalance","readability.small_text","render.error","render.svg_context","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=8.5;var SVG_ONLY_ELEMENTS=new Set(["circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","symbol","text","textPath","tspan","use"]);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=parseCssColor2(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 alpha3=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha3<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha3,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha3,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha3,alpha:alpha3}}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 amount2=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount2*4/3;if(unit==="rem")return amount2*16;if(unit==="em")return amount2*(inherited??16);if(unit==="%")return amount2/100*(inherited??16);return amount2}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(!isValidElement(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 analyzeScene(element,theme,trustedComponents,rootBackground2,svgComponents){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path,namespace){if(visited++>=MAX_CONTRAST_NODES||!isValidElement(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path,namespace);return}const props=node.props;const svgShape=svgComponents?.shapes.get(node.type)??(svgComponents&&typeof node.type==="string"&&SVG_ONLY_ELEMENTS.has(node.type)?`<${node.type}>`:void 0);if(namespace==="html"&&svgShape){diagnostics.push({code:"render.svg_context",severity:"error",theme,message:`${svgShape} requires an <svg> ancestor at ${path}; its SVG geometry will not render in an HTML layout.`,suggestion:"Place the element inside a native <svg> or an SVG container such as AxisPlot.",elementId:elementId(props),location:{path}})}const childNamespace=typeof node.type==="string"?node.type==="svg"?"svg":node.type==="foreignObject"?"html":namespace:typeof node.type==="function"?svgComponents?.children.get(node.type):namespace;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}`,childNamespace))}visit(element,{background:colorFromCss(rootBackground2)},"root","html");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(text2){return Array.from(text2.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 text2=String(node.textContent??"").trim();if(text2&&typeof style.transform==="string"&&style.transform.includes("rotate"))continue;if(text2&&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(text2)*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:text2,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(text2){const normalized=text2.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=attribute=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute];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 connectorSource=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>Number(node.props["data-vizmatic-connector-crossing-budget"]??0));const connectorCrossings=connectorSource?Number(connectorSource.props["data-vizmatic-connector-crossings"]):0;if(connectorCrossings>0){const source=connectorSource;diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings} connector crossing${connectorCrossings===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 crossedLabels=maxDataNumber("data-vizmatic-connector-label-crossings");if(crossedLabels>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"info",theme,message:`${crossedLabels} connector${crossedLabels===1?" passes":"s pass"} behind a label or group title. The label masks it, but the line appears broken.`,suggestion:'Shorten or move the label, change graph direction, or route the connector with routing="orthogonal".',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 eight 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 overflowCount=0;const graphNodes=nodes.filter(node=>typeof node.props["data-vizmatic-graph-node-id"]==="string");for(const box of graphNodes){for(const text2 of nodes){if(overflowCount>=MAX_DIAGNOSTICS_PER_RULE)break;if(!String(text2.textContent??"").trim()||text2===box)continue;const startsInside=text2.left>=box.left-1&&text2.left<box.left+box.width&&text2.top>=box.top-1&&text2.top<box.top+box.height;if(!startsInside)continue;const spillsRight=text2.left+text2.width>box.left+box.width+1;const spillsDown=text2.top+text2.height>box.top+box.height+1;if(!spillsRight&&!spillsDown)continue;diagnostics.push({code:"layout.text_overflow",severity:"warning",theme,message:`Text "${textExcerpt(String(text2.textContent))}" spills out of node "${String(box.props["data-vizmatic-graph-node-id"])}".`,suggestion:"Omit the fixed node width and height so the node sizes to its content, or shorten the text.",elementId:elementId(box.props),location:{x:text2.left,y:text2.top,width:text2.width,height:text2.height}});overflowCount+=1;break}}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(bounds4,width,height,theme){const gutters={left:bounds4.x,right:width-bounds4.x-bounds4.width,top:bounds4.y,bottom:height-bounds4.y-bounds4.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:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.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:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.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 SVG_CONTEXT_COMPONENTS={shapes:new Map([[SvgFrame,"SvgFrame"],[SvgPoint,"SvgPoint"],[VectorArrow,"VectorArrow"],[VectorSegment,"VectorSegment"],[ArrowMarkerDef,"ArrowMarkerDef"]]),children:new Map([...[Board,CanvasItem,Canvas,Scene,Row,Column,Panel,Stack,Card,Tile,WindowFrame,CalloutCard,ChartFrame].map(component=>[component,"html"]),[AxisPlot,"svg"]])};var consoleCaptureContext=new AsyncLocalStorage;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(run2){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run2);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(join(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 analyzeScene(element,theme,TRUSTED_COMPONENTS,background,SVG_CONTEXT_COMPONENTS)});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:join(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:join(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}}import parseCssColor3 from"parse-css-color";var themeColorKeys=Object.freeze(Object.keys(getThemeColors("dark")).filter(key=>key!=="preset"&&key!=="fontSans"&&key!=="fontMono"&&key!=="fontSerif"&&key!=="density"));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"||!parseCssColor3(color.trim())){throw new Error(`themeColors.${key} must be a valid CSS color.`)}colors2[key]=color.trim()}return colors2}function parseThemeColorsMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.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(line2){const withoutComment=stripTrailingLineComment(line2.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(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]/.test(line2)}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"||parseCssColor3(background))return background;throw new Error('background must be "theme", "transparent", or a valid CSS color.')}function isThemeColorsMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]/.test(line2)}function mergePlaygroundThemeColors(mode,preset,overrides){return{...getThemeColors(mode,preset),...overrides}}function stripTrailingLineComment(line2){let quoted=false;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[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==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}function readPresetLine(line2){const candidate=stripLineComment(line2.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(line2){const match=line2.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(line2){let quote;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[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==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}import parseCssColor4 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}}import{existsSync}from"fs";import{mkdir as mkdir3,stat as stat2,writeFile as writeFile3}from"fs/promises";import{basename,dirname as dirname3,extname,join as join2,relative,resolve as resolve2}from"path";import{mkdir as mkdir2,stat,writeFile as writeFile2}from"fs/promises";import{totalmem}from"os";import{dirname as dirname2,resolve}from"path";import*as gifenc2 from"gifenc";import parseCssColor5 from"parse-css-color";var midnight={name:"midnight",dark:true,background:"#0b0c10",bloom:.2,colors:{bg:"#0b0c10",surface:"#15171d",ink:"#f2efe6",dim:"#a5a7ad",faint:"#5c5f68",grid:"#23303d",gridStrong:"#3d5266",blue:"#5cc4f0",teal:"#4fd8c4",green:"#8fe08a",yellow:"#ffd75e",gold:"#f2b84b",orange:"#ff9d57",red:"#ff6b6b",pink:"#ff8fc0",purple:"#b49cff"}};var paper={name:"paper",dark:false,background:"#f7f3ea",bloom:0,colors:{bg:"#f7f3ea",surface:"#efe9db",ink:"#1d1b16",dim:"#5e5a50",faint:"#a29c8d",grid:"#e2dbca",gridStrong:"#c4bba6",blue:"#1f6fb2",teal:"#0d8577",green:"#3f8a35",yellow:"#b98500",gold:"#a8740a",orange:"#cf5d12",red:"#c62f2f",pink:"#c2387e",purple:"#6a4bc4"}};var blueprint={name:"blueprint",dark:true,background:"#0b2340",bloom:.16,colors:{bg:"#0b2340",surface:"#123054",ink:"#eaf6ff",dim:"#9cc0dc",faint:"#5d86a8",grid:"#1a3f66",gridStrong:"#2c5f8e",blue:"#7fd4ff",teal:"#6fe6d6",green:"#9de8a4",yellow:"#ffe27a",gold:"#f5c566",orange:"#ffb27a",red:"#ff8d8d",pink:"#ffa8cf",purple:"#c5b4ff"}};var chalk={name:"chalk",dark:true,background:"#10201b",bloom:.1,colors:{bg:"#10201b",surface:"#172c25",ink:"#f4f1e4",dim:"#b1b9a9",faint:"#67786d",grid:"#20392f",gridStrong:"#355547",blue:"#8ccbe8",teal:"#7dd9c1",green:"#a9dc8f",yellow:"#f6dd7c",gold:"#e6bf62",orange:"#f2a874",red:"#ee8a80",pink:"#efa2c2",purple:"#bfa9e6"}};var neon={name:"neon",dark:true,background:"#050507",bloom:.4,colors:{bg:"#050507",surface:"#101016",ink:"#ffffff",dim:"#a9a9b8",faint:"#55555f",grid:"#1a1f2e",gridStrong:"#2f3a55",blue:"#3fb2ff",teal:"#21f0d0",green:"#6dff8e",yellow:"#fff04d",gold:"#ffc22e",orange:"#ff8a2e",red:"#ff4560",pink:"#ff5fb0",purple:"#a56bff"}};var LOOKS={midnight,paper,blueprint,chalk,neon};function resolveLook(look){if(look===void 0)return midnight;if(typeof look!=="string")return look;const found=LOOKS[look];if(!found)throw new Error(`Unknown look: ${JSON.stringify(look)}. Use one of: ${Object.keys(LOOKS).join(", ")}.`);return found}var TRANSPARENT=[0,0,0,0];var cache=new Map;var tokens2=midnight.colors;function setColorTokens(next){tokens2=next}function parseColor(input){const token=tokens2[input];const value=token??input;const cached=cache.get(value);if(cached)return cached;const parsed=parseCssColor5(value);if(!parsed)throw new Error(`Unknown color: ${JSON.stringify(input)}. Use a look token such as "blue" or a CSS color.`);let[r,g,b]=parsed.values;if(parsed.type==="hsl")[r,g,b]=hslToRgb3(r,g,b);const result=[r,g,b,parsed.alpha];cache.set(value,result);return result}function hslToRgb3(h,s,l){const a=s/100*Math.min(l/100,1-l/100);const f=n=>{const k=(n+h/30)%12;return 255*(l/100-a*Math.max(-1,Math.min(k-3,9-k,1)))};return[f(0),f(8),f(4)]}function toPaint(input){if(typeof input==="string")return parseColor(input);return input}function isGradient(paint){return!Array.isArray(paint)}function css(color,alpha3=1){const a=color[3]*alpha3;const r=Math.round(color[0]),g=Math.round(color[1]),b=Math.round(color[2]);if(a>=1)return`rgb(${r},${g},${b})`;return`rgba(${r},${g},${b},${Math.round(a*1e3)/1e3})`}function srgbToLinear(v){const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)}function linearToSrgb(v){const x=v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055;return Math.max(0,Math.min(255,x*255))}function toOklab(c){const r=srgbToLinear(c[0]),g=srgbToLinear(c[1]),b=srgbToLinear(c[2]);const l=Math.cbrt(.4122214708*r+.5363325363*g+.0514459929*b);const m=Math.cbrt(.2119034982*r+.6806995451*g+.1073969566*b);const s=Math.cbrt(.0883024619*r+.2817188376*g+.6299787005*b);return[.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s]}function fromOklab(lab,alpha3){const l=lab[0]+.3963377774*lab[1]+.2158037573*lab[2];const m=lab[0]-.1055613458*lab[1]-.0638541728*lab[2];const s=lab[0]-.0894841775*lab[1]-1.291485548*lab[2];const ll=l*l*l,mm=m*m*m,ss=s*s*s;return[linearToSrgb(4.0767416621*ll-3.3077115913*mm+.2309699292*ss),linearToSrgb(-1.2684380046*ll+2.6097574011*mm-.3413193965*ss),linearToSrgb(-.0041960863*ll-.7034186147*mm+1.707614701*ss),alpha3]}function mixColor(a,b,t){if(t<=0)return a;if(t>=1)return b;const x=toOklab(a),y=toOklab(b);return fromOklab([x[0]+(y[0]-x[0])*t,x[1]+(y[1]-x[1])*t,x[2]+(y[2]-x[2])*t],a[3]+(b[3]-a[3])*t)}function mixPaint(a,b,t){if(t<=0)return a;if(t>=1)return b;const ga=isGradient(a),gb=isGradient(b);if(!ga&&!gb)return mixColor(a,b,t);if(ga&&gb&&a.type===b.type&&a.stops.length===b.stops.length){const stops=a.stops.map((stop,i)=>[stop[0]+(b.stops[i][0]-stop[0])*t,mixColor(stop[1],b.stops[i][1],t)]);if(a.type==="linear"&&b.type==="linear"){return{type:"linear",stops,from:[a.from[0]+(b.from[0]-a.from[0])*t,a.from[1]+(b.from[1]-a.from[1])*t],to:[a.to[0]+(b.to[0]-a.to[0])*t,a.to[1]+(b.to[1]-a.to[1])*t]}}if(a.type==="radial"&&b.type==="radial"){return{type:"radial",stops,center:[a.center[0]+(b.center[0]-a.center[0])*t,a.center[1]+(b.center[1]-a.center[1])*t],radius:a.radius+(b.radius-a.radius)*t}}return{type:"along",stops}}const solidA=ga?sampleStops(a.stops,.5):a;const solidB=gb?sampleStops(b.stops,.5):b;return mixColor(solidA,solidB,t)}function sampleStops(stops,at){if(stops.length===0)return TRANSPARENT;if(at<=stops[0][0])return stops[0][1];for(let i=1;i<stops.length;i++){if(at<=stops[i][0]){const[p0,c0]=stops[i-1],[p1,c1]=stops[i];return mixColor(c0,c1,p1>p0?(at-p0)/(p1-p0):0)}}return stops[stops.length-1][1]}function normalizeStops(colors2){const count=colors2.length;return colors2.map((entry,i)=>{if(Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="number"){return[entry[0],solid(entry[1])]}return[count===1?0:i/(count-1),solid(entry)]})}function solid(input){const paint=toPaint(input);return isGradient(paint)?sampleStops(paint.stops,.5):paint}function linearGradient(from,to2,colors2){return{type:"linear",from,to:to2,stops:normalizeStops(colors2)}}function radialGradient(center2,radius,colors2){return{type:"radial",center:center2,radius,stops:normalizeStops(colors2)}}function along(...colors2){return{type:"along",stops:normalizeStops(colors2)}}function ramp(count,...colors2){const stops=normalizeStops(colors2);return Array.from({length:count},(_,i)=>sampleStops(stops,count===1?0:i/(count-1)))}var IDENTITY=[1,0,0,1,0,0];var EMPTY_BOUNDS={x:0,y:0,width:0,height:0};var KAPPA=.5522847498307936;var LUT_STEPS=10;function mul(m,n){return[m[0]*n[0]+m[2]*n[1],m[1]*n[0]+m[3]*n[1],m[0]*n[2]+m[2]*n[3],m[1]*n[2]+m[3]*n[3],m[0]*n[4]+m[2]*n[5]+m[4],m[1]*n[4]+m[3]*n[5]+m[5]]}function invert(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return IDENTITY;const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function apply(m,x,y){return[m[0]*x+m[2]*y+m[4],m[1]*x+m[3]*y+m[5]]}function compose(x,y,rotation,sx,sy,px,py){const cos=rotation===0?1:Math.cos(rotation);const sin=rotation===0?0:Math.sin(rotation);const a=cos*sx;const b=sin*sx;const c=-sin*sy;const d=cos*sy;return[a,b,c,d,x-a*px-c*py,y-b*px-d*py]}function matScale(m){return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2]))}function ring(points,closed=false){return{p:points instanceof Float64Array?points:Float64Array.from(points),closed}}function segmentCount(r){return Math.max(0,(r.p.length-2)/6)}function lineInto(out,x0,y0,x1,y1){out.push(x0+(x1-x0)/3,y0+(y1-y0)/3,x0+(x1-x0)*2/3,y0+(y1-y0)*2/3,x1,y1)}function linePath(a,b){const out=[a[0],a[1]];lineInto(out,a[0],a[1],b[0],b[1]);return[ring(out)]}function polyPath(points,closed=false){if(points.length===0)return[];const first=points[0];const out=[first[0],first[1]];for(let i=1;i<points.length;i++)lineInto(out,points[i-1][0],points[i-1][1],points[i][0],points[i][1]);if(closed){const last=points[points.length-1];if(last[0]!==first[0]||last[1]!==first[1])lineInto(out,last[0],last[1],first[0],first[1])}return[ring(out,closed)]}function smoothPath(points,closed=false,tension=1/6){const n=points.length;if(n===0)return[];if(n<3)return polyPath(points,closed);const at=i=>closed?points[(i+n)%n]:points[Math.max(0,Math.min(n-1,i))];const out=[points[0][0],points[0][1]];const count=closed?n:n-1;for(let i=0;i<count;i++){const p0=at(i-1),p1=at(i),p2=at(i+1),p3=at(i+2);out.push(p1[0]+(p2[0]-p0[0])*tension,p1[1]+(p2[1]-p0[1])*tension,p2[0]-(p3[0]-p1[0])*tension,p2[1]-(p3[1]-p1[1])*tension,p2[0],p2[1])}return[ring(out,closed)]}function arcPath(cx,cy,rx,ry,from,to2){const sweep=to2-from;if(sweep===0)return[];const closed=Math.abs(Math.abs(sweep)-Math.PI*2)<1e-9;const count=Math.max(1,Math.ceil(Math.abs(sweep)/(Math.PI/4)-1e-9));const step=sweep/count;const k=4/3*Math.tan(step/4);const out=[cx+Math.cos(from)*rx,cy+Math.sin(from)*ry];for(let i=0;i<count;i++){const a0=from+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);out.push(cx+(c0-k*s0)*rx,cy+(s0+k*c0)*ry,cx+(c1+k*s1)*rx,cy+(s1-k*c1)*ry,cx+c1*rx,cy+s1*ry)}if(closed){out[out.length-2]=out[0];out[out.length-1]=out[1]}return[ring(out,closed)]}function circlePath(cx,cy,r){return arcPath(cx,cy,r,r,0,Math.PI*2)}function rectPath(x,y,width,height,radius=0){const r=Math.max(0,Math.min(radius,Math.abs(width)/2,Math.abs(height)/2));if(r===0)return polyPath([[x,y],[x+width,y],[x+width,y+height],[x,y+height]],true);const k=r*(1-KAPPA);const right=x+width,bottom=y+height;const out=[x+r,y];lineInto(out,x+r,y,right-r,y);out.push(right-k,y,right,y+k,right,y+r);lineInto(out,right,y+r,right,bottom-r);out.push(right,bottom-k,right-k,bottom,right-r,bottom);lineInto(out,right-r,bottom,x+r,bottom);out.push(x+k,bottom,x,bottom-k,x,bottom-r);lineInto(out,x,bottom-r,x,y+r);out.push(x,y+k,x+k,y,x+r,y);return[ring(out,true)]}function parametricPath(f,from,to2,samples=64){const count=Math.max(2,Math.floor(samples));const points=[];for(let i=0;i<=count;i++)points.push(f(from+(to2-from)*i/count));return curveThrough(points)}function curveThrough(points){const rings=[];let run2=[];const flush=()=>{if(run2.length>=2)rings.push(...smoothPath(run2));run2=[]};for(const point of points){if(Number.isFinite(point[0])&&Number.isFinite(point[1]))run2.push(point);else flush()}flush();return rings}function concat(...paths){return paths.flat()}function transformPath(path,m){if(m===IDENTITY)return path;const out=new Array(path.length);for(let r=0;r<path.length;r++){const src=path[r].p;const dst=new Float64Array(src.length);for(let i=0;i<src.length;i+=2){const x=src[i],y=src[i+1];dst[i]=m[0]*x+m[2]*y+m[4];dst[i+1]=m[1]*x+m[3]*y+m[5]}out[r]={p:dst,closed:path[r].closed}}return out}function warpPath(path,f,subdivisions=4){const dense=subdivisions>1?path.map(r=>subdivideEach(r,subdivisions)):path;return dense.map(r=>{const count=segmentCount(r);const anchors=[];for(let i=0;i<=count;i++){const mapped=f(r.p[i*6],r.p[i*6+1]);anchors.push(mapped)}const out=[anchors[0][0],anchors[0][1]];for(let i=0;i<count;i++){const c1=f(r.p[i*6+2],r.p[i*6+3]);const c2=f(r.p[i*6+4],r.p[i*6+5]);out.push(c1[0],c1[1],c2[0],c2[1],anchors[i+1][0],anchors[i+1][1])}return ring(out,r.closed)})}function splitInto(src,o,t,left,right){const x0=src[o],y0=src[o+1],x1=src[o+2],y1=src[o+3];const x2=src[o+4],y2=src[o+5],x3=src[o+6],y3=src[o+7];const ax=x0+(x1-x0)*t,ay=y0+(y1-y0)*t;const bx=x1+(x2-x1)*t,by=y1+(y2-y1)*t;const cx=x2+(x3-x2)*t,cy=y2+(y3-y2)*t;const dx=ax+(bx-ax)*t,dy=ay+(by-ay)*t;const ex=bx+(cx-bx)*t,ey=by+(cy-by)*t;const fx=dx+(ex-dx)*t,fy=dy+(ey-dy)*t;left.push(ax,ay,dx,dy,fx,fy);right.length=0;right.push(fx,fy,ex,ey,cx,cy,x3,y3)}function subdivideEach(r,n){const count=segmentCount(r);if(n<=1||count===0)return r;const out=[r.p[0],r.p[1]];for(let i=0;i<count;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));for(let k=n;k>1;k--){const rest=[];splitInto(seg,0,1/k,out,rest);seg=rest}out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,r.closed)}var measures=new WeakMap;function measure(r){const cached=measures.get(r);if(cached)return cached;const count=segmentCount(r);const total=new Float64Array(count);const lut=new Float64Array(count*LUT_STEPS);let sum=0;const p=r.p;for(let i=0;i<count;i++){const o=i*6;const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3],x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];let lastX=x0,lastY=y0,acc=0;for(let k=1;k<=LUT_STEPS;k++){const t=k/LUT_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;acc+=Math.hypot(x-lastX,y-lastY);lut[i*LUT_STEPS+k-1]=acc;lastX=x;lastY=y}sum+=acc;total[i]=sum}const result={total,lut,length:sum};measures.set(r,result);return result}function ringLength(r){return measure(r).length}function pathLength(path){let sum=0;for(const r of path)sum+=measure(r).length;return sum}function locate(m,distance){const count=m.total.length;if(count===0)return[0,0];if(distance<=0)return[0,0];if(distance>=m.length)return[count-1,1];let lo=0,hi=count-1;while(lo<hi){const mid=lo+hi>>1;if(m.total[mid]<distance)lo=mid+1;else hi=mid}const before=lo===0?0:m.total[lo-1];const local=distance-before;const base=lo*LUT_STEPS;let k=0;while(k<LUT_STEPS-1&&m.lut[base+k]<local)k++;const start=k===0?0:m.lut[base+k-1];const end=m.lut[base+k];const fraction=end>start?(local-start)/(end-start):0;return[lo,(k+fraction)/LUT_STEPS]}function trimRing(r,from,to2){const count=segmentCount(r);if(count===0)return null;const a=Math.max(0,Math.min(1,from));const b=Math.max(0,Math.min(1,to2));if(b<=a)return null;if(a===0&&b===1)return r;const m=measure(r);if(m.length===0)return null;const[i0,t0]=locate(m,a*m.length);const[i1,t1]=locate(m,b*m.length);const out=[];for(let i=i0;i<=i1;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));const start=i===i0?t0:0;const end=i===i1?t1:1;if(start>0){const rest=[];splitInto(seg,0,start,[],rest);seg=rest}if(end<1){const left=[];const rest=[];const scaled=start>0?(end-start)/(1-start):end;splitInto(seg,0,scaled,left,rest);seg=[seg[0],seg[1],...left]}if(out.length===0)out.push(seg[0],seg[1]);out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,false)}function trimPath(path,from,to2,each=false){if(from<=0&&to2>=1)return path;const out=[];if(each){for(const r of path){const piece=trimRing(r,from,to2);if(piece)out.push(piece)}return out}const total=pathLength(path);if(total===0)return[];let travelled=0;for(const r of path){const length=ringLength(r);const start=(from*total-travelled)/(length||1);const end=(to2*total-travelled)/(length||1);travelled+=length;if(end<=0||start>=1)continue;const piece=trimRing(r,Math.max(0,start),Math.min(1,end));if(piece)out.push(piece)}return out}function pointAt(path,fraction){const total=pathLength(path);if(total===0){const first=path[0]?.p;return first?[first[0],first[1]]:[0,0]}let remaining=Math.max(0,Math.min(1,fraction))*total;for(let i=0;i<path.length;i++){const r=path[i];const length=ringLength(r);if(remaining<=length||i===path.length-1){const[segment,t]=locate(measure(r),remaining);return evaluate(r.p,segment*6,t)}remaining-=length}return[0,0]}function tangentAt(path,fraction){const delta=.002;const a=pointAt(path,Math.max(0,fraction-delta));const b=pointAt(path,Math.min(1,fraction+delta));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return[(b[0]-a[0])/length,(b[1]-a[1])/length]}function evaluate(p,o,t){const u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;return[a*p[o]+b*p[o+2]+c*p[o+4]+d*p[o+6],a*p[o+1]+b*p[o+3]+c*p[o+5]+d*p[o+7]]}function extendCubicAxis(range,p0,p1,p2,p3){range[0]=Math.min(range[0],p0,p3);range[1]=Math.max(range[1],p0,p3);if(p1>=range[0]&&p1<=range[1]&&p2>=range[0]&&p2<=range[1])return;const a=-p0+3*p1-3*p2+p3;const b=2*(p0-2*p1+p2);const c=p1-p0;const roots=[];if(Math.abs(a)<1e-9){if(Math.abs(b)>1e-9)roots.push(-c/b)}else{const disc=b*b-4*a*c;if(disc>=0){const s=Math.sqrt(disc);roots.push((-b+s)/(2*a),(-b-s)/(2*a))}}for(const t of roots){if(t<=0||t>=1)continue;const u=1-t;const value=u*u*u*p0+3*u*u*t*p1+3*u*t*t*p2+t*t*t*p3;range[0]=Math.min(range[0],value);range[1]=Math.max(range[1],value)}}var ringBounds=new WeakMap;function boundsOfRing(r){const cached=ringBounds.get(r);if(cached)return cached;const p=r.p;if(p.length<2)return EMPTY_BOUNDS;const xs=[p[0],p[0]];const ys=[p[1],p[1]];for(let o=0;o+7<p.length;o+=6){extendCubicAxis(xs,p[o],p[o+2],p[o+4],p[o+6]);extendCubicAxis(ys,p[o+1],p[o+3],p[o+5],p[o+7])}const bounds4={x:xs[0],y:ys[0],width:xs[1]-xs[0],height:ys[1]-ys[0]};ringBounds.set(r,bounds4);return bounds4}function pathBounds(path){if(path.length===0)return null;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const r of path){if(r.p.length<2)continue;const b=boundsOfRing(r);minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height)}if(minX===Infinity)return null;return{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}function unionBounds(a,b){if(!a)return b;if(!b)return a;const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function signedArea(r){const p=r.p;let sum=0;for(let o=0;o+7<p.length;o+=6){sum+=p[o]*p[o+7]-p[o+6]*p[o+1]}return sum/2}function ringCenter(r){const b=boundsOfRing(r);return[b.x+b.width/2,b.y+b.height/2]}function reverseRing(r){const p=r.p;const out=new Float64Array(p.length);for(let i=0;i<p.length;i+=2){out[i]=p[p.length-2-i];out[i+1]=p[p.length-1-i]}return{p:out,closed:r.closed}}function parseSvgPath(d){const tokens4=d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);if(!tokens4)return[];const rings=[];let out=[];let i=0,x=0,y=0,startX=0,startY=0;let lastCmd="",lastCx=0,lastCy=0;const num=()=>Number(tokens4[i++]);const flags=()=>{const token=tokens4[i];if(token.length>1&&(token[0]==="0"||token[0]==="1")&&!token.startsWith("0.")&&!token.startsWith("1.")){tokens4[i]=token.slice(1);return Number(token[0])}i++;return Number(token)};const flush=closed=>{if(out.length>=8)rings.push(ring(out,closed));out=[]};const begin=(px,py)=>{if(out.length===0)out.push(px,py)};let cmd="";while(i<tokens4.length){const token=tokens4[i];if(/^[a-zA-Z]$/.test(token)){cmd=token;i++}else if(cmd==="M"){cmd="L"}else if(cmd==="m"){cmd="l"}else if(cmd===""){throw new Error(`Invalid SVG path data: ${d.slice(0,40)}`)}const rel=cmd>="a";switch(cmd.toUpperCase()){case"M":{flush(false);x=(rel?x:0)+num();y=(rel?y:0)+num();startX=x;startY=y;out.push(x,y);break}case"L":{const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,nx,ny);x=nx;y=ny;break}case"H":{const nx=(rel?x:0)+num();begin(x,y);lineInto(out,x,y,nx,y);x=nx;break}case"V":{const ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,x,ny);y=ny;break}case"C":{const ox=rel?x:0,oy=rel?y:0;const c1x=ox+num(),c1y=oy+num(),c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"S":{const ox=rel?x:0,oy=rel?y:0;const smooth3="CScs".includes(lastCmd);const c1x=smooth3?2*x-lastCx:x,c1y=smooth3?2*y-lastCy:y;const c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"Q":{const ox=rel?x:0,oy=rel?y:0;const qx=ox+num(),qy=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"T":{const ox=rel?x:0,oy=rel?y:0;const smooth3="QTqt".includes(lastCmd);const qx=smooth3?2*x-lastCx:x,qy=smooth3?2*y-lastCy:y;const nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"A":{const rx=num(),ry=num(),angle=num(),large=flags(),sweep=flags();const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);arcInto(out,x,y,rx,ry,angle,large===1,sweep===1,nx,ny);x=nx;y=ny;break}case"Z":{if(out.length>0){if(x!==startX||y!==startY)lineInto(out,x,y,startX,startY);flush(true)}x=startX;y=startY;break}default:throw new Error(`Unsupported SVG path command: ${cmd}`)}lastCmd=cmd}flush(false);return rings}function arcInto(out,x0,y0,rxIn,ryIn,degrees,large,sweep,x1,y1){let rx=Math.abs(rxIn),ry=Math.abs(ryIn);if(rx===0||ry===0||x0===x1&&y0===y1){lineInto(out,x0,y0,x1,y1);return}const phi=degrees*Math.PI/180;const cos=Math.cos(phi),sin=Math.sin(phi);const dx=(x0-x1)/2,dy=(y0-y1)/2;const xp=cos*dx+sin*dy,yp=-sin*dx+cos*dy;const lambda=xp*xp/(rx*rx)+yp*yp/(ry*ry);if(lambda>1){const scale=Math.sqrt(lambda);rx*=scale;ry*=scale}const numerator=rx*rx*ry*ry-rx*rx*yp*yp-ry*ry*xp*xp;const denominator=rx*rx*yp*yp+ry*ry*xp*xp;const factor=(large===sweep?-1:1)*Math.sqrt(Math.max(0,numerator/denominator));const cxp=factor*rx*yp/ry,cyp=-factor*ry*xp/rx;const cx=cos*cxp-sin*cyp+(x0+x1)/2;const cy=sin*cxp+cos*cyp+(y0+y1)/2;const start=Math.atan2((yp-cyp)/ry,(xp-cxp)/rx);let delta=Math.atan2((-yp-cyp)/ry,(-xp-cxp)/rx)-start;if(sweep&&delta<0)delta+=Math.PI*2;if(!sweep&&delta>0)delta-=Math.PI*2;const count=Math.max(1,Math.ceil(Math.abs(delta)/(Math.PI/2)-1e-9));const step=delta/count;const k=4/3*Math.tan(step/4);for(let i=0;i<count;i++){const a0=start+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);const q1x=(c0-k*s0)*rx,q1y=(s0+k*c0)*ry;const q2x=(c1+k*s1)*rx,q2y=(s1-k*c1)*ry;const ex=c1*rx,ey=s1*ry;out.push(cos*q1x-sin*q1y+cx,sin*q1x+cos*q1y+cy,cos*q2x-sin*q2y+cx,sin*q2x+cos*q2y+cy,i===count-1?x1:cos*ex-sin*ey+cx,i===count-1?y1:sin*ex+cos*ey+cy)}}function fmt(value){const rounded=Math.round(value*100)/100;return rounded===0?"0":String(rounded)}function pathToD(path){const parts=[];for(const r of path){const p=r.p;if(p.length<2)continue;parts.push("M",fmt(p[0])," ",fmt(p[1]));if(r.straight){for(let o=2;o+5<p.length;o+=6)parts.push("L",fmt(p[o+4])," ",fmt(p[o+5]));if(r.closed)parts.push("Z");continue}for(let o=2;o+5<p.length;o+=6){parts.push("C",fmt(p[o])," ",fmt(p[o+1])," ",fmt(p[o+2])," ",fmt(p[o+3])," ",fmt(p[o+4])," ",fmt(p[o+5]))}if(r.closed)parts.push("Z")}return parts.join("")}var clock={now:0,mode:"free",frame:0,capture:null};var Track=class{constructor(initial){this.initial=initial}initial;keys=[];sample(t){const keys=this.keys;let lo=0,hi=keys.length-1,index=-1;while(lo<=hi){const mid=lo+hi>>1;if(keys[mid].t0<=t){index=mid;lo=mid+1}else{hi=mid-1}}if(index<0)return this.initial;const key=keys[index];if(t>=key.t1||!key.at)return key.to;const span=key.t1-key.t0;const raw=span>0?(t-key.t0)/span:1;return key.at(key.ease?key.ease(raw):raw)}add(key){const keys=this.keys;let index=keys.length;while(index>0&&keys[index-1].t0>key.t0)index--;keys.splice(index,0,key)}step(t,value){this.add({t0:t,t1:t,ease:null,to:value,at:null})}get end(){let end=0;for(const key of this.keys)if(key.t1>end)end=key.t1;return end}};var clockNow=()=>clock.now;var ALONG_PIECE_LENGTH=14;var MAX_ALONG_PIECES=96;function worldPaint(paint,m){if(!paint||!isGradient(paint))return paint;if(paint.type==="linear"){return{...paint,from:apply(m,paint.from[0],paint.from[1]),to:apply(m,paint.to[0],paint.to[1])}}if(paint.type==="radial"){return{...paint,center:apply(m,paint.center[0],paint.center[1]),radius:paint.radius*matScale(m)}}return paint}function sameMatrix(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]}var worldCache=new WeakMap;function toWorld(node,path,m){const cached=worldCache.get(node);if(cached&&cached.path===path&&sameMatrix(cached.matrix,m))return cached.world;const world=transformPath(path,m);worldCache.set(node,{path,matrix:m,world});return world}function emit(node,path,m,alpha3,ops){const fill=node.get("fill");const stroke=node.get("stroke");const fillAlpha=fill?alpha3*node.get("fillOpacity"):0;const strokeAlpha=stroke?alpha3*node.get("strokeOpacity"):0;const glow=node.get("glow");if(fillAlpha<=.002&&strokeAlpha<=.002&&glow<=0)return;const world=toWorld(node,path,m);const scale=matScale(m);const trimFrom=node.get("trimFrom"),trimTo=node.get("trimTo");let strokePath=world;if(trimFrom>0||trimTo<1)strokePath=trimPath(world,trimFrom,trimTo,node.get("trimEach"));if(strokePath.length===0&&fillAlpha<=.002)return;const dash=node.get("dash");const op={kind:"path",path:world,strokePath,fill:fillAlpha>.002?worldPaint(fill,m):null,fillAlpha,stroke:strokeAlpha>.002?worldPaint(stroke,m):null,strokeAlpha,strokeWidth:node.get("strokeWidth")*scale,cap:node.get("cap"),join:node.get("join"),dash:dash?dash.map(value=>value*scale):null,dashOffset:node.get("dashOffset")*scale,glow:glow*scale,glowColor:node.get("glowColor"),blend:node.get("blend"),node};if(op.stroke&&isGradient(op.stroke)&&op.stroke.type==="along")splitAlong(op,op.stroke,ops);else ops.push(op)}function splitAlong(op,paint,ops){ops.push({...op,stroke:null,strokeAlpha:0});const glowless={...op,fill:null,fillAlpha:0,glow:0};const length=pathLength(op.strokePath);const full=pathLength(op.path);if(length===0)return;const fraction=full>0?Math.min(1,length/full):1;const pieces=Math.min(MAX_ALONG_PIECES,Math.max(2,Math.ceil(length/ALONG_PIECE_LENGTH)));const overlap=.6/pieces;for(let i=0;i<pieces;i++){const from=i/pieces,to2=Math.min(1,(i+1)/pieces+overlap);const piece=trimPath(op.strokePath,from,to2);if(piece.length===0)continue;ops.push({...glowless,strokePath:piece,path:piece,stroke:sampleStops(paint.stops,(i+.5)/pieces*fraction),cap:i===0||i===pieces-1?op.cap:"butt"})}}function walk(node,parent,screen,alpha3,ops){if(!node.get("visible"))return;const opacity=node.get("opacity")*alpha3;if(opacity<=.002)return;const base=node.get("fixed")?screen:parent;const m=mul(base,node.localMatrix());const path=node.get("path");if(path&&path.length>0)emit(node,path,m,opacity,ops);const image=node.get("image");if(image)ops.push({kind:"image",image,matrix:m,alpha:opacity});if(node.rawOps)node.rawOps(m,opacity,ops);if(node.draw){const built=node.draw(clockNow());if(built){const list3=Array.isArray(built)?built:[built];for(const child of list3)walk(child,m,screen,opacity,ops)}}const children=node.children;if(children.length===0)return;let sorted=false;for(let i=0;i<children.length;i++){if(children[i].get("z")!==0){sorted=true;break}}const ordered=sorted?children.map((child,index)=>({child,index,z:child.get("z")})).sort((a,b)=>a.z-b.z||a.index-b.index).map(entry=>entry.child):children;for(const child of ordered)walk(child,m,screen,opacity,ops)}function buildOps(root,camera,width,height){const screen=[1,0,0,1,width/2,height/2];const view=mul(screen,compose(0,0,-camera.rotation,camera.zoom,camera.zoom,camera.x,camera.y));const ops=[];walk(root,view,screen,1,ops);return ops}var GLOW_PASSES=7;function glowPasses(glow,width){const out=[];for(let i=GLOW_PASSES;i>=1;i--){const k=i/GLOW_PASSES;out.push({width:width+glow*2*k,alpha:.16*(1-k)*(1-k)+.018})}return out}function glowOf(op){if(op.glowColor)return op.glowColor;const paint=op.stroke??op.fill;if(!paint)return null;return isGradient(paint)?sampleStops(paint.stops,.5):paint}var dCache=new WeakMap;function pathData(path){let d=dCache.get(path);if(d===void 0){d=pathToD(path);dCache.set(path,d)}return d}function fmt2(value){return String(Math.round(value*1e3)/1e3)}function gradientDef(id,paint){const stops=paint.stops.map(([at,color])=>`<stop offset="${fmt2(at)}" stop-color="${css([color[0],color[1],color[2],1])}"${color[3]<1?` stop-opacity="${fmt2(color[3])}"`:""}/>`).join("");if(paint.type==="linear"){return`<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`}if(paint.type==="radial"){return`<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`}return""}function strokeAttrs(op){let attrs=` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;if(op.dash)attrs+=` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;return attrs}function escapeAttr(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<")}function frameToSvg(frame,options={}){const scale=options.scale??1;const w=frame.width,h=frame.height;const defs=[];const body=[];let gradientCount=0;const paintAttr=(paint,attr,alpha3)=>{if(isGradient(paint)){const id=`g${gradientCount++}`;defs.push(gradientDef(id,paint));return`${attr}="url(#${id})"${alpha3<1?` ${attr}-opacity="${fmt2(alpha3)}"`:""}`}const rgba=paint;const a=rgba[3]*alpha3;return`${attr}="${css([rgba[0],rgba[1],rgba[2],1])}"${a<1?` ${attr}-opacity="${fmt2(a)}"`:""}`};if(frame.background&&!options.transparent)body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);for(const op of frame.ops){if(op.kind==="image"){const m=op.matrix;body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha<1?` opacity="${fmt2(op.alpha)}"`:""} preserveAspectRatio="none"/>`);continue}const style=op.blend!=="normal"?` style="mix-blend-mode:${op.blend}"`:"";if(op.glow>0){const color=glowOf(op);const glowD=pathData(op.strokePath.length?op.strokePath:op.path);if(color&&glowD){const base=Math.max(op.fillAlpha,op.strokeAlpha);const mode=frame.dark?' style="mix-blend-mode:screen"':"";const passes=glowPasses(op.glow,op.stroke?op.strokeWidth:0).map(pass=>`<path d="${glowD}" fill="none" stroke="${css([color[0],color[1],color[2],1])}" stroke-opacity="${fmt2(pass.alpha*base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");body.push(`<g${mode}>${passes}</g>`)}}if(op.fill&&op.stroke&&op.strokePath===op.path){body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)} ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);continue}if(op.fill)body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)}${style}/>`);if(op.stroke&&op.strokePath.length){body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`)}}const defsBlock=defs.length?`<defs>${defs.join("")}</defs>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${w*scale}" height="${h*scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`}var path2dCache=new WeakMap;function ringsToPath2D(path){let cached=path2dCache.get(path);if(cached)return cached;cached=new Path2D;for(const r of path){const p=r.p;if(p.length<2)continue;cached.moveTo(p[0],p[1]);if(r.straight)for(let o=2;o+5<p.length;o+=6)cached.lineTo(p[o+4],p[o+5]);else for(let o=2;o+5<p.length;o+=6)cached.bezierCurveTo(p[o],p[o+1],p[o+2],p[o+3],p[o+4],p[o+5]);if(r.closed)cached.closePath()}path2dCache.set(path,cached);return cached}function canvasPaint(ctx,paint){if(!isGradient(paint))return css(paint);const gradient=paint.type==="linear"?ctx.createLinearGradient(paint.from[0],paint.from[1],paint.to[0],paint.to[1]):paint.type==="radial"?ctx.createRadialGradient(paint.center[0],paint.center[1],0,paint.center[0],paint.center[1],paint.radius):null;if(!gradient)return css(sampleStops(paint.stops,.5));for(const[at,color]of paint.stops)gradient.addColorStop(at,css(color));return gradient}var BLEND={normal:"source-over",screen:"screen",multiply:"multiply",overlay:"overlay"};function paintFrame(ctx,frame,scale=1,images){ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over";ctx.clearRect(0,0,frame.width*scale,frame.height*scale);ctx.setTransform(scale,0,0,scale,0,0);if(frame.background){ctx.fillStyle=frame.background;ctx.fillRect(0,0,frame.width,frame.height)}for(const op of frame.ops){if(op.kind==="image"){const source=images?.(op.image);if(!source)continue;const m=op.matrix;ctx.save();ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]);ctx.globalAlpha=op.alpha;ctx.drawImage(source,0,0,op.image.width,op.image.height);ctx.restore();continue}ctx.globalCompositeOperation=BLEND[op.blend];if(op.glow>0){const color=glowOf(op);if(color){const base=Math.max(op.fillAlpha,op.strokeAlpha);const previous=ctx.globalCompositeOperation;if(frame.dark)ctx.globalCompositeOperation="screen";ctx.strokeStyle=css([color[0],color[1],color[2],1]);ctx.lineCap="round";ctx.lineJoin="round";ctx.setLineDash([]);const glowPath=ringsToPath2D(op.strokePath.length?op.strokePath:op.path);for(const pass of glowPasses(op.glow,op.stroke?op.strokeWidth:0)){ctx.globalAlpha=pass.alpha*base;ctx.lineWidth=pass.width;ctx.stroke(glowPath)}ctx.globalCompositeOperation=previous}}if(op.fill){ctx.globalAlpha=op.fillAlpha;ctx.fillStyle=canvasPaint(ctx,op.fill);ctx.fill(ringsToPath2D(op.path))}if(op.stroke&&op.strokePath.length){ctx.globalAlpha=op.strokeAlpha;ctx.strokeStyle=canvasPaint(ctx,op.stroke);ctx.lineWidth=op.strokeWidth;ctx.lineCap=op.cap;ctx.lineJoin=op.join;ctx.setLineDash(op.dash?[...op.dash]:[]);ctx.lineDashOffset=op.dashOffset;ctx.stroke(ringsToPath2D(op.strokePath))}}ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over"}function frameInkBounds(frame){let result=null;for(const op of frame.ops){if(op.kind!=="path")continue;const b=pathBounds(op.path);if(!b)continue;const pad2=op.stroke?op.strokeWidth/2:0;const next={x:b.x-pad2,y:b.y-pad2,width:b.width+pad2*2,height:b.height+pad2*2};if(!result)result=next;else{const x=Math.min(result.x,next.x),y=Math.min(result.y,next.y);result={x,y,width:Math.max(result.x+result.width,next.x+next.width)-x,height:Math.max(result.y+result.height,next.y+next.height)-y}}}return result}import{createRequire}from"module";import{cpus}from"os";import{Worker}from"worker_threads";import{fileURLToPath}from"url";var RASTER_WORKER_SOURCE=String.raw`
|
|
3
3
|
const { parentPort, workerData } = require('node:worker_threads')
|
|
4
4
|
const { Resvg } = require(workerData.resvgPath)
|
|
5
5
|
|