semiotic 3.8.8 → 3.8.9

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.
Files changed (104) hide show
  1. package/CLAUDE.md +5 -4
  2. package/README.md +44 -44
  3. package/ai/schema.json +263 -1
  4. package/ai/surface-manifest.json +1 -1
  5. package/ai/system-prompt.md +1 -1
  6. package/dist/chunk-chunk-2X3FJCME.module.min.js +1 -0
  7. package/dist/{chunk-chunk-UEZ6SHW5.module.min.js → chunk-chunk-2ZHHWZQM.module.min.js} +1 -1
  8. package/dist/chunk-chunk-5ZON5NMV.module.min.js +2 -0
  9. package/dist/{chunk-chunk-L6FFYGYS.module.min.js → chunk-chunk-6S3YGYW7.module.min.js} +1 -1
  10. package/dist/chunk-chunk-7C5EDZ3Z.module.min.js +2 -0
  11. package/dist/chunk-chunk-A3I4HBD5.module.min.js +1 -0
  12. package/dist/{chunk-chunk-4MLLQUGW.module.min.js → chunk-chunk-AFQHURLO.module.min.js} +1 -1
  13. package/dist/{chunk-chunk-OG3TTJGJ.module.min.js → chunk-chunk-DDB4TLQG.module.min.js} +1 -1
  14. package/dist/{chunk-chunk-W5HWGQMD.module.min.js → chunk-chunk-DTH3SUOU.module.min.js} +1 -1
  15. package/dist/{chunk-chunk-H5IFO6CU.module.min.js → chunk-chunk-DVCWU7MT.module.min.js} +1 -1
  16. package/dist/{chunk-chunk-JRHXQGEV.module.min.js → chunk-chunk-FSIHAW6L.module.min.js} +1 -1
  17. package/dist/{chunk-chunk-BWV55BZK.module.min.js → chunk-chunk-G2RGVEYY.module.min.js} +1 -1
  18. package/dist/chunk-chunk-HAJVODLO.module.min.js +2 -0
  19. package/dist/{chunk-chunk-BZNOAHJV.module.min.js → chunk-chunk-HIV7AW2V.module.min.js} +1 -1
  20. package/dist/{chunk-chunk-LJDH3WV3.module.min.js → chunk-chunk-JZAMMSQQ.module.min.js} +1 -1
  21. package/dist/{chunk-chunk-VUWYT7DY.module.min.js → chunk-chunk-MXMRXSCI.module.min.js} +1 -1
  22. package/dist/chunk-chunk-MXVBXFKW.module.min.js +2 -0
  23. package/dist/{chunk-chunk-7LE56WAE.module.min.js → chunk-chunk-OFAP623Y.module.min.js} +1 -1
  24. package/dist/{chunk-chunk-SFLUSZ73.module.min.js → chunk-chunk-OHLRAEQZ.module.min.js} +1 -1
  25. package/dist/{chunk-chunk-CD6PVVS3.module.min.js → chunk-chunk-PRNXOCYZ.module.min.js} +1 -1
  26. package/dist/chunk-chunk-RLKZVJMQ.module.min.js +2 -0
  27. package/dist/chunk-chunk-SK2TQMG4.module.min.js +2 -0
  28. package/dist/chunk-chunk-SKLYXNYW.module.min.js +2 -0
  29. package/dist/{chunk-chunk-57RBPDBQ.module.min.js → chunk-chunk-U4NZCU5T.module.min.js} +1 -1
  30. package/dist/{chunk-chunk-QQJNG23C.module.min.js → chunk-chunk-VKL6DI43.module.min.js} +1 -1
  31. package/dist/chunk-chunk-W62673ZE.module.min.js +1 -0
  32. package/dist/{chunk-chunk-WSDJFBKX.module.min.js → chunk-chunk-XCC25CZZ.module.min.js} +1 -1
  33. package/dist/{chunk-chunk-AF53TBSN.module.min.js → chunk-chunk-XECNOUZY.module.min.js} +1 -1
  34. package/dist/{chunk-chunk-FC3NZWYR.module.min.js → chunk-chunk-XYZDTYAF.module.min.js} +1 -1
  35. package/dist/components/Tooltip/Tooltip.d.ts +54 -1
  36. package/dist/components/charts/physics/chainReactionTypes.d.ts +1 -0
  37. package/dist/components/charts/physics/physicsHocUtils.d.ts +1 -1
  38. package/dist/components/charts/realtime/RealtimeHeatmap.d.ts +2 -0
  39. package/dist/components/charts/realtime/RealtimeHistogram.d.ts +2 -0
  40. package/dist/components/charts/realtime/RealtimeLineChart.d.ts +2 -0
  41. package/dist/components/charts/realtime/RealtimeSwarmChart.d.ts +2 -0
  42. package/dist/components/charts/realtime/RealtimeWaterfallChart.d.ts +2 -0
  43. package/dist/components/charts/shared/formatUtils.d.ts +40 -9
  44. package/dist/components/charts/shared/streamPropsHelpers.d.ts +1 -0
  45. package/dist/components/charts/shared/types.d.ts +8 -1
  46. package/dist/components/semiotic-utils-core.d.ts +1 -0
  47. package/dist/components/semiotic.d.ts +4 -3
  48. package/dist/components/stream/GeoTileRenderer.d.ts +1 -0
  49. package/dist/components/stream/canvasSetup.d.ts +15 -4
  50. package/dist/components/stream/geoTypes.d.ts +2 -0
  51. package/dist/components/stream/networkFramePaint.d.ts +8 -0
  52. package/dist/components/stream/networkTypes.d.ts +2 -0
  53. package/dist/components/stream/ordinalTypes.d.ts +2 -0
  54. package/dist/components/stream/physics/StreamPhysicsTypes.d.ts +2 -0
  55. package/dist/components/stream/pipelineConfig.d.ts +2 -0
  56. package/dist/components/stream/pipelineDomainResolution.d.ts +1 -1
  57. package/dist/components/stream/types.d.ts +8 -1
  58. package/dist/components/stream/useCanvasFrameHost.d.ts +9 -0
  59. package/dist/components/stream/xyFrameAxisTypes.d.ts +5 -0
  60. package/dist/geo.min.js +1 -1
  61. package/dist/geo.module.min.js +1 -1
  62. package/dist/network.min.js +1 -1
  63. package/dist/network.module.min.js +1 -1
  64. package/dist/ordinal.min.js +1 -1
  65. package/dist/ordinal.module.min.js +1 -1
  66. package/dist/physics.min.js +1 -1
  67. package/dist/physics.module.min.js +1 -1
  68. package/dist/realtime.min.js +1 -1
  69. package/dist/realtime.module.min.js +1 -1
  70. package/dist/semiotic-ai-core.min.js +1 -1
  71. package/dist/semiotic-ai-core.module.min.js +1 -1
  72. package/dist/semiotic-ai.min.js +1 -1
  73. package/dist/semiotic-ai.module.min.js +1 -1
  74. package/dist/semiotic-experimental.min.js +1 -1
  75. package/dist/semiotic-experimental.module.min.js +1 -1
  76. package/dist/semiotic-realtime-core.min.js +1 -1
  77. package/dist/semiotic-realtime-core.module.min.js +1 -1
  78. package/dist/semiotic-server-edge.min.js +1 -1
  79. package/dist/semiotic-server-edge.module.min.js +1 -1
  80. package/dist/semiotic-server-node.min.js +1 -1
  81. package/dist/semiotic-server-node.module.min.js +1 -1
  82. package/dist/semiotic-utils-core.d.ts +1 -0
  83. package/dist/semiotic-utils-core.min.js +1 -1
  84. package/dist/semiotic-utils-core.module.min.js +1 -1
  85. package/dist/semiotic-utils.min.js +1 -1
  86. package/dist/semiotic-utils.module.min.js +1 -1
  87. package/dist/semiotic.d.ts +4 -3
  88. package/dist/semiotic.min.js +1 -1
  89. package/dist/semiotic.module.min.js +1 -1
  90. package/dist/server.min.js +1 -1
  91. package/dist/server.module.min.js +1 -1
  92. package/dist/xy.min.js +1 -1
  93. package/dist/xy.module.min.js +1 -1
  94. package/package.json +1 -1
  95. package/dist/chunk-chunk-3GCILWPB.module.min.js +0 -2
  96. package/dist/chunk-chunk-46KRGJQP.module.min.js +0 -1
  97. package/dist/chunk-chunk-7T25U75Z.module.min.js +0 -2
  98. package/dist/chunk-chunk-BTZYH2IE.module.min.js +0 -1
  99. package/dist/chunk-chunk-FRGBMTZR.module.min.js +0 -1
  100. package/dist/chunk-chunk-HCNDE26Q.module.min.js +0 -2
  101. package/dist/chunk-chunk-JJ4BSUYL.module.min.js +0 -2
  102. package/dist/chunk-chunk-N3Q33XCB.module.min.js +0 -2
  103. package/dist/chunk-chunk-RGJ6TKAH.module.min.js +0 -2
  104. package/dist/chunk-chunk-WGROBM3I.module.min.js +0 -2
@@ -1 +1 @@
1
- import{composeStyleRules as e,computeArcBoundingBox as t,darkenColor as o,lightenColor as n,makeNodeRuleContext as i,makeRuleValueResolver as r,makeXYRuleContext as s,resolveStyleRules as a,styleRulesToNodeStyle as l,styleRulesToXYStyle as c,sweepToAngles as u}from"./chunk-chunk-HBFA4NN6.module.min.js";import{PhysicsPipelineStore as d,absorbRegion as h,bodyGroupSpec as p,capacitatedRegion as g,collidersFromPlotBounds as m,collidersFromXScaleBins as f,countPairwiseCrossings as y,forceFieldRegion as b,groupCompletionRows as x,orderByBarycenter as v,orderExactSmall as w,packBandsBySilhouette as A,placeWithMinGap as S,portalRegion as k,pressureFieldRegion as M,processStageLayout as _,refineByAdjacentSwaps as P,routeSurfaceRegion as T}from"./chunk-chunk-FEPXDKJP.module.min.js";import"./chunk-chunk-SIRIJ3DY.module.min.js";import{AnnotationLabel as L,DEFAULT_COLOR as R,DEFAULT_LEGEND_ROW_HEIGHT as I,DEPTH_PALETTE_COLORS as C,PipelineStore as z,STREAMING_PALETTE as F,SafeRender as O,SemioticAnnotation as B,StreamXYFrame_default as N,TITLE_BASELINE as E,attachUpdateResultStore as j,buildBaseMetadataProps as $,buildCustomBehaviorProps as D,buildDatumIndexMap as W,buildRectNode as Y,buildResolveColor as H,buildRibbonGeometry as V,compactTimestampBufferForRemoval as G,composeLegendConfigs as X,computeDecayOpacity as q,computeEasing as U,computePulseIntensity as Q,computeRawProgress as Z,confidenceZScore as K,createColorScale as J,createCustomLayoutFailureDiagnostic as ee,createTimestampBufferForData as te,distinctCategories as oe,ensureRingBufferCapacity as ne,filterSparseArray as ie,fitLinearForForecast as re,forecastIntervalStats as se,geoSceneNodeToSVG as ae,getColor as le,getCrosshairProps as ce,getLayoutPlugin as ue,getSize as de,hasActivePulses as he,hasTextTitle as pe,isChartMode as ge,isGradientLegendConfig as me,isLegendConfig as fe,layoutVerticalLegendGroups as ye,lerp as be,networkLabelToSVG as xe,networkSceneEdgeToSVG as ve,networkSceneNodeToSVG as we,normalizeColorGradient as Ae,normalizeGradient as Se,normalizeSemanticGradient as ke,now as Me,ordinalSceneNodeToSVG as _e,pushWithTimestamp as Pe,renderAnnotationPass as Te,renderEmptyState as Le,renderLoadingState as Re,renderSceneListWithBackend as Ie,renderSceneWithBackend as Ce,reserveTitleMargin as ze,resolveAxisChromeGutter as Fe,resolveCategoricalPalette as Oe,resolveChartMode as Be,resolveCustomLayoutPalette as Ne,resolveDefaultFill as Ee,resolveDownwardHistogramExtent as je,resolveExplicitColor as $e,resolveGridDash as De,resolveLegendDistance as We,resolveLegendMetrics as Ye,resolveLegendSideGutter as He,resolveMobileInteraction as Ve,resolveSideLegendMargin as Ge,resolveSideLegendWidth as Xe,reverseGradient as qe,setPulseState as Ue,snapOrdinalIntroTargets as Qe,ticksForMode as Ze,toIdSet as Ke,useCategoryColors as Je,useChartLegendAndMargin as et,useChartMode as tt,useChartSelection as ot,useColorScale as nt,useLegendInteraction as it,useThemeCategorical as rt,warnCustomLayoutDiagnostics as st,xySceneNodeToSVG as at}from"./chunk-chunk-BTZYH2IE.module.min.js";import{useTheme as lt}from"./chunk-chunk-OZK46A5U.module.min.js";import{IncrementalExtent as ct,RingBuffer as ut,defaultTooltipStyle as dt,isHatchFill as ht,normalizeTooltip as pt,resolveSvgFill as gt}from"./chunk-chunk-L6FFYGYS.module.min.js";import{UpdateResultTracker as mt,annotationLayout as ft,getSequentialInterpolator as yt,interpolateBrBG as bt,interpolatePRGn as xt,interpolatePiYG as vt,interpolateRdBu as wt,interpolateRdYlBu as At,interpolateRdYlGn as St,interpolateSpectral as kt,interpolateViridis as Mt,makeSymbolResolver as _t,schemeCategory10 as Pt,useCustomLayoutSelection as Tt}from"./chunk-chunk-LSJUXBMF.module.min.js";import"./chunk-chunk-U66USBWU.module.min.js";import{filterAnnotationsByStatus as Lt}from"./chunk-chunk-5VVNW5AZ.module.min.js";import{accessorsEquivalent as Rt,resolveAccessor as It,resolveStringAccessor as Ct}from"./chunk-chunk-NWIGA3UK.module.min.js";import{getMax as zt,getMin as Ft,getMinMax as Ot}from"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-IY7RYD4S.module.min.js";import"./chunk-chunk-J3QOW4OE.module.min.js";import{DARK_THEME as Bt,HIGH_CONTRAST_THEME as Nt,LIGHT_THEME as Et,THEME_PRESETS as jt,applyThemeAccessibility as $t,resolveThemeSemanticColors as Dt,useThemeSelector as Wt}from"./chunk-chunk-HADHLMY5.module.min.js";function Yt(e){if(null==e)return;if("number"==typeof e)return{top:e,right:e,bottom:e,left:e};const t={};return"number"==typeof e.top&&(t.top=e.top),"number"==typeof e.right&&(t.right=e.right),"number"==typeof e.bottom&&(t.bottom=e.bottom),"number"==typeof e.left&&(t.left=e.left),t}import*as Ht from"react-dom/server";import*as Vt from"react";function Gt(e){return void 0!==e.stroke||void 0!==e.strokeWidth||void 0!==e.opacity}function Xt(e,t){if(!Gt(t))return e??((...e)=>({}));const o={};return void 0!==t.stroke&&(o.stroke=t.stroke),void 0!==t.strokeWidth&&(o.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(o.opacity=t.opacity),e?(...t)=>({...e(...t)||{},...o}):(...e)=>({...o})}function qt(e,t,o){return"function"==typeof e?e(o):o[e||t]}function Ut(e){return e instanceof Date?e.getTime():Number(e)}function Qt(e,t){return Mt(1===t?.5:e/(t-1))}function Zt(e){const t={};return void 0!==e.stroke&&(t.stroke=e.stroke),void 0!==e.strokeWidth&&(t.strokeWidth=e.strokeWidth),void 0!==e.opacity&&(t.opacity=e.opacity),t}function Kt(e){if(!e)return Et;if("string"==typeof e){if("light"===e)return Et;if("dark"===e)return Bt;if("high-contrast"===e)return Nt;return jt[e]||Et}const t="dark"===e.mode?Bt:Et,o={...t,...e,colors:{...t.colors,...e.colors||{}},typography:{...t.typography,...e.typography||{}},tooltip:{...t.tooltip,...e.tooltip||{}}};return $t(o)}function Jt(e){return{background:e.colors.background,text:e.colors.text,textSecondary:e.colors.textSecondary,grid:e.colors.grid,border:e.colors.border,primary:e.colors.primary,fontFamily:e.typography.fontFamily,titleSize:e.typography.titleSize,labelSize:e.typography.labelSize,tickSize:e.typography.tickSize,categorical:e.colors.categorical,annotation:e.colors.annotation??e.colors.text,legendSize:e.typography.legendSize??e.typography.labelSize,titleFontSize:e.typography.titleFontSize??e.typography.titleSize,tickFontFamily:e.typography.tickFontFamily??e.typography.fontFamily}}var eo="__forecastSegment",to="__forecastOpacity";function oo(e,t,o,n){const i=t.uncertaintyOpacity,r=t.confidenceAccessor;if(!i&&!r)return;const s="object"==typeof i?i:{},a=s.min??.15,l=s.max??1;if(r){const t="function"==typeof r?r:e=>e[r];for(const o of e){const e=t(o);null!=e&&Number.isFinite(e)&&(o[to]=a+Math.max(0,Math.min(1,e))*(l-a))}return}const c=e.map(e=>{const t=o(e),i=n(e);return null!=t&&null!=i&&Number.isFinite(t)&&Number.isFinite(i)?Math.abs(t-i):NaN}),u=c.filter(e=>Number.isFinite(e));if(0===u.length)return;const[d,h]=Ot(u),p=h-d;e.forEach((e,t)=>{const o=c[t];Number.isFinite(o)&&(e[to]=l-(p>0?(o-d)/p:0)*(l-a))})}function no(e,t){return"function"==typeof t?t(e):!!e[t]}var io="__semiotic_resolvedX",ro="__semiotic_resolvedY",so="__compoundGroup";function ao(e,t,o){const n=e[t],i=e[o];return null==n||null==i||Number.isNaN(n)||Number.isNaN(i)}function lo(e){const t=e.xAccessor||"x",i=e.yAccessor||"y",r=e.lineBy,s=e.colorBy||r;let a=Array.isArray(e.data)?ie(e.data).filter(e=>!!e&&"object"==typeof e):[];const l=function(e,t,o){const n="function"==typeof t,i="function"==typeof o,r=n?io:t,s=i?ro:o;return n||i?{xKey:r,yKey:s,rows:e.map(e=>{const r={...e};return n&&(r[io]=t(e)),i&&(r[ro]=o(e)),r})}:{rows:e,xKey:r,yKey:s}}(a,t,i);a=l.rows;const c=l.xKey,u=l.yKey,d=Array.isArray(e.annotations)?[...e.annotations]:[];let h,p="string"==typeof r||"function"==typeof r?r:void 0,g=e.baseLineStyle;if(e.forecast){const t=function(e,t,o,n,i){return(r=n).isTraining||r.isForecast||r.isAnomaly||r.upperBounds||r.lowerBounds?function(e,t,o,n,i){const{isTraining:r,isForecast:s,isAnomaly:a,upperBounds:l,lowerBounds:c,color:u="#6366f1",bandOpacity:d=.15,anomalyColor:h="#ef4444",anomalyRadius:p=6,label:g}=n,m=e.map(e=>{let t="observed";return s&&no(e,s)?t="forecast":r&&no(e,r)&&(t="training"),{...e,[eo]:t}}),f=n._groupBy,y=[];if(f){const e=new Map;for(const t of m){const o=t[f]??"__default";e.has(o)||e.set(o,[]),e.get(o).push(t)}const t=[];for(const[,o]of e)for(let e=0;o.length-1>e;e++)o[e][eo]!==o[e+1][eo]&&(t.push({...o[e+1],[eo]:o[e][eo]}),t.push({...o[e],[eo]:o[e+1][eo]}));y.push(...m,...t)}else for(let e=0;m.length>e;e++)y.push(m[e]),m.length-1>e&&m[e][eo]!==m[e+1][eo]&&(y.push({...m[e+1],[eo]:m[e][eo]}),y.push({...m[e],[eo]:m[e+1][eo]}));if(n.trainUnderline){const e=[];for(const t of y)"training"===t[eo]&&e.push({...t,[eo]:"training-base"});y.unshift(...e)}const b=[];if(l&&c){const e="string"==typeof l?l:"__envUpper",t="string"==typeof c?c:"__envLower";if("function"==typeof l||"function"==typeof c)for(const o of y)"function"==typeof l&&(o[e]=l(o)),"function"==typeof c&&(o[t]=c(o));b.push({type:"envelope",upperAccessor:e,lowerAccessor:t,fill:u,fillOpacity:d,label:g})}if(n.uncertaintyOpacity||n.confidenceAccessor){const e=l?"function"==typeof l?l:e=>e[l]:()=>{},t=c?"function"==typeof c?c:e=>e[c]:()=>{};oo(y.filter(e=>"forecast"===e[eo]),n,e,t)}if(a){const e=n.anomalyStyle,t={type:"highlight",filter:e=>no(e,a)};e?(t.style=e,t.r=p):"function"==typeof h?(t.style=e=>{const t=h(e);return{stroke:t,strokeWidth:1.5,fill:t,fillOpacity:.7}},t.r=p):(t.color=h,t.r=p,t.style={stroke:h,strokeWidth:1.5,fill:h,fillOpacity:.7}),b.push(t)}return i&&b.push({type:"anomaly-band",threshold:i.threshold??2,showBand:!1!==i.showBand,fill:i.bandColor||"#6366f1",fillOpacity:i.bandOpacity??.1,anomalyColor:i.anomalyColor||"#ef4444",anomalyRadius:i.anomalyRadius??6,label:i.label}),{processedData:y,annotations:b}}(e,0,0,n,i):function(e,t,o,n,i){const{trainEnd:r,steps:s=10,confidence:a=.95,color:l="#6366f1",bandOpacity:c=.15,label:u}=n;if(null==r)return{processedData:e,annotations:[]};const d=[],h=[];for(const o of e)o[t]>r?h.push({...o,[eo]:"observed"}):d.push({...o,[eo]:"training"});const p=d.map(e=>[e[t],e[o]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]),g=[],m=[];if(p.length>=3){const i=p.length,r=re(p);if(r){const{se:d,meanX:h,ssX:f}=se(p,r),y=K(a),b=e.map(e=>e[t]).filter(e=>null!=e&&isFinite(e)),x=zt(b),v=p.length>1?(p[i-1][0]-p[0][0])/(i-1):1;for(let e=1;s>=e;e++){const n=x+e*v,s=r(n),a=d*Math.sqrt(1+1/i+(f>0?(n-h)**2/f:0))*y;m.push({[t]:n,[o]:s,[eo]:"forecast",__forecastUpper:s+a,__forecastLower:s-a})}oo(m,n,e=>e.__forecastUpper,e=>e.__forecastLower),g.push({type:"envelope",upperAccessor:"__forecastUpper",lowerAccessor:"__forecastLower",fill:l,fillOpacity:c,label:u})}}g.push({type:"x-threshold",x:r,color:"#94a3b8",strokeWidth:1,strokeDasharray:"4,2",label:"Train / Forecast"}),i&&g.push({type:"anomaly-band",threshold:i.threshold??2,showBand:!1!==i.showBand,fill:i.bandColor||"#6366f1",fillOpacity:i.bandOpacity??.1,anomalyColor:i.anomalyColor||"#ef4444",anomalyRadius:i.anomalyRadius??6,label:i.label});const f=[];if(f.push(...d),d.length>0&&h.length>0&&f.push({...d[d.length-1],[eo]:"observed"}),f.push(...h),m.length>0){const e=h.length>0?h[h.length-1]:d[d.length-1];e&&f.push({...e,[eo]:"forecast"}),f.push(...m)}return{processedData:f,annotations:g}}(e,t,o,n,i);var r}(a,c,u,r&&"string"==typeof r&&"object"==typeof e.forecast?{...e.forecast,_groupBy:r}:e.forecast,e.anomaly);if(a=t.processedData,d.push(...t.annotations),h=function(e,t,o){const n=o.upperBounds,i=o.lowerBounds;if(!n&&!i)return;const r="function"==typeof n?n:"string"==typeof n?e=>e[n]:null,s="function"==typeof i?i:"string"==typeof i?e=>e[i]:null;let a=1/0,l=-1/0;for(const o of e){const e=Number(o[t]);if(Number.isFinite(e)&&(a>e&&(a=e),e>l&&(l=e)),r){const e=r(o);null!=e&&Number.isFinite(e)&&(e>l&&(l=e),a>e&&(a=e))}if(s){const e=s(o);null!=e&&Number.isFinite(e)&&(a>e&&(a=e),e>l&&(l=e))}}return Number.isFinite(a)&&Number.isFinite(l)?[a,l]:void 0}(a,u,e.forecast),r&&"string"==typeof r?(a=a.map(e=>({...e,[so]:`${e[r]}__${e[eo]||"observed"}`})),p=so):p=eo,e.baseLineStyle){const t=function(t,i){const r=i.trainDasharray??"8,4",s=i.forecastDasharray??"4,4",a=i.color||"#6366f1",l=i.trainOpacity,c=i.forecastOpacity,u=i.trainStroke,d=i.trainLinecap,h=i.trainUnderline;return t=>{const i=(t=>e.baseLineStyle(t))(t),p=t[eo];if("training"===p){let e=i.stroke;return"darken"===u?e=o(i.stroke||"#666",.5):u&&(e=u),{...i,stroke:e,strokeDasharray:r,...d&&{strokeLinecap:d},...null!=l&&{strokeOpacity:l}}}if("training-base"===p){let e=i.stroke||"#666";return"lighten"===h&&(e=n(e,.4)),{...i,stroke:e,strokeDasharray:void 0}}if("forecast"===p){const e=t[to],o=null!=e?e:c;return{...i,stroke:a,strokeDasharray:s,...null!=o&&{strokeOpacity:o}}}return i}}(0,e.forecast);g=e=>t(e)}}else e.anomaly&&d.push(...(m=e.anomaly,[{type:"anomaly-band",threshold:m.threshold??2,showBand:!1!==m.showBand,fill:m.bandColor||"#6366f1",fillOpacity:m.bandOpacity??.1,anomalyColor:m.anomalyColor||"#ef4444",anomalyRadius:m.anomalyRadius??6,label:m.label}]));var m;if(e.gapStrategy){if("function"==typeof p){const e=p;a=a.map(t=>({...t,__semiotic_gapGroup:e(t)})),p="__semiotic_gapGroup"}const t=function(e,t,o,n,i){const r=new Map;for(const t of e){const e=i?(t[i]??"")+"":"__single";r.has(e)||r.set(e,[]),r.get(e).push(t)}if("interpolate"===t){const e=[];for(const[,t]of r)for(const i of t)ao(i,o,n)||e.push(i);return{rows:e,groupKey:i}}if("zero"===t){const e=[];for(const[,t]of r)for(const i of t)ao(i,o,n)?e.push({...i,[n]:0}):e.push(i);return{rows:e,groupKey:i}}const s=[],a="_gapSegment";for(const[e,t]of r){let i=0,r=[];const l=()=>{if(0===r.length)return;const t="__single"===e?"__seg"+i:`${e}__seg${i}`;for(const e of r)s.push({...e,[a]:t});r=[],i++};for(const e of t)ao(e,o,n)?l():r.push(e);l()}return{rows:s,groupKey:a}}(a,e.gapStrategy,c,u,"string"==typeof p?p:void 0);a=t.rows,t.groupKey&&(p=t.groupKey)}let f;if(e.directLabel){const t=function(e,t,o,n,i,r,s,a){if(!t||!o)return{annotations:[]};const l="object"==typeof t?t:{},c=l.position||"end",u=l.fontSize||11,d="function"==typeof o?o:e=>e[o],h=new Map;for(const t of e){const e=d(t);if(null==e)continue;const o=e+"";""!==o&&(h.has(o)||h.set(o,[]),h.get(o).push(t))}const p=new Map;for(const[e,t]of h)t.sort((e,t)=>Number(e[n])-Number(t[n])),p.set(e,"end"===c?t[t.length-1]:t[0]);const g=J(Array.from(p.entries()).map(([e])=>({__lbl:e})),"__lbl",r??s),m=Array.from(p.entries()).map(([e,t])=>({type:"text",label:e,[n]:t[n],[i]:t[i],dx:"end"===c?6:-6,dy:0,color:g?le({__lbl:e},"__lbl",g):a||R,fontSize:u}));m.sort((e,t)=>Number(e[i])-Number(t[i]));for(let e=1;m.length>e;e++){const t=m[e-1],o=m[e],n=Number(t[i])+t.dy;u+2>Math.abs(Number(o[i])+o.dy-n)&&(o.dy+=u+2)}const f=m.reduce((e,t)=>Math.max(e,(t.label+"").length*(.6*u)),0)+10;return{annotations:m,marginExtra:"end"===c?{right:f}:{left:f}}}(a,e.directLabel,"string"==typeof s||"function"==typeof s?s:void 0,c,u,e.colorScheme,e.themeCategorical,e.color);d.push(...t.annotations),f=t.marginExtra}return{data:a,xAccessor:"function"==typeof t?c:t,yAccessor:"function"==typeof i?u:i,groupAccessor:p,colorAccessor:s,annotations:d,lineStyle:g,yExtent:h,marginExtra:f}}import{forwardRef as co,useCallback as uo,useMemo as ho}from"react";import{forwardRef as po,useMemo as go}from"react";import{useMemo as mo,useRef as fo}from"react";import{useCallback as yo,useMemo as bo,useState as xo}from"react";import{useMemo as vo}from"react";import{useImperativeHandle as wo,useRef as Ao}from"react";function So(e){const t=fo(null);return function(e,t){const{variant:o,frameRef:n,overrides:i}=t,r=Ao(i);r.current=i,wo(e,()=>{const e=function(e,t){if("xy"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>e.current?.remove(t)??[],update:(t,o)=>e.current?.update(t,o)??[],replace:t=>e.current?.replace?.(t),clear:()=>e.current?.clear(),getData:()=>e.current?.getData()??[],getScales:()=>e.current?.getScales()??null,getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}if("network"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>{const o=Array.isArray(t)?t:[t],n=e.current?.getTopology()?.nodes??[],i=[];for(const t of o){const o=n.find(e=>e.id===t);o&&i.push({...o.data??{},id:t}),e.current?.removeNode(t)}return i},update:(t,o)=>(Array.isArray(t)?t:[t]).flatMap(t=>{const n=e.current?.updateNode(t,o);return n?[{...n,id:t}]:[]}),clear:()=>e.current?.clear(),getData:()=>e.current?.getTopology()?.nodes?.map(e=>e.data)??[],getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}if("geo-points"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>e.current?.removePoint(t)??[],update:(t,o)=>{const n=e.current?.removePoint(t)??[];for(const t of n)e.current?.push(o(t));return n},clear:()=>e.current?.clear(),getData:()=>e.current?.getData()??[],getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}const o=t;return{push:e=>o.current?.pushLine(e),pushMany:e=>o.current?.pushManyLines(e),remove:e=>o.current?.removeLine(e)??[],update:(e,t)=>{const n=o.current?.removeLine(e)??[];for(const e of n)o.current?.pushLine(t(e));return n},clear:()=>o.current?.clear(),getData:()=>o.current?.getLines()??[],getCustomLayout:()=>o.current?.getCustomLayout?.()??null,getLayoutFailure:()=>o.current?.getLayoutFailure?.()??null}}(o,n);return new Proxy(e,{get(e,t,o){if("string"==typeof t){const e=r.current?.[t];if("function"==typeof e)return e}return Reflect.get(e,t,o)},has:(e,t)=>!("string"!=typeof t||!r.current||!(t in r.current))||Reflect.has(e,t)})},[])}(e.imperativeRef,{variant:e.imperativeVariant,frameRef:t}),{frameRef:t,resolved:tt(e.mode,{width:e.width,height:e.height,showGrid:e.showGrid,enableHover:e.enableHover,showLegend:e.showLegend,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,xLabel:e.xLabel,yLabel:e.yLabel,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules}),normalizedMargin:mo(()=>Yt(e.margin),[e.margin])}}import{jsx as ko}from"react/jsx-runtime";var Mo=po(function(e,t){const{data:o,layout:n,layoutConfig:i,onLayoutError:r,xExtent:s,yExtent:a,showAxes:l=!1,margin:c,className:u,annotations:d,onObservation:h,onClick:p,selection:g,linkedHover:m,hoverHighlight:f,chartId:y,loading:b,loadingContent:x,emptyContent:v,colorBy:w,colorScheme:A,legend:S,legendInteraction:k,legendPosition:M,frameProps:_={}}=e,{legend:P,...T}=_,L=go(()=>X(P,S),[P,S]),{frameRef:R,resolved:I,safeData:C,setup:z,earlyReturn:B}=function(e){const t=So(e),{resolved:o,normalizedMargin:n}=t,i=function(e){const{data:t,rawData:o,colorBy:n,colorScheme:i,legendInteraction:r,legendPosition:s,selection:a,linkedHover:l,fallbackFields:c,unwrapData:u=!1,onObservation:d,chartType:h,chartId:p,showLegend:g,legend:m,legendLayout:f,userMargin:y,marginDefaults:b,onClick:x,hoverHighlight:v,mobileInteraction:w,mobileSemantics:A,loading:S,loadingContent:k,emptyContent:M,width:_,height:P,hasTitle:T,axisChrome:L}=e,R=void 0===o,I=bo(()=>ie(t),[t]),[C,z]=xo([]),O=yo(e=>{z(t=>t.length===e.length&&t.every((t,o)=>t===e[o])?t:e)},[]),B="string"==typeof n?n:void 0,N=bo(()=>Ve(w,{width:_,mobileSemantics:A}),[w,_,A]),{activeSelectionHook:E,hoverSelectionHook:j,customHoverBehavior:$,customClickBehavior:D,crosshairSourceId:W}=ot({selection:a,linkedHover:l,fallbackFields:c,unwrapData:u,onObservation:d,chartType:h,chartId:p,onClick:x,hoverHighlight:v,colorByField:B,mobileInteraction:N}),Y=ce(l,W),H=nt(I,n,i),V=bo(()=>oe(I,n),[I,n]),G=bo(()=>R&&C.length>0?C:V,[R,C,V]),X=it(r,n,G),q=bo(()=>j||(X.legendSelectionHook?X.legendSelectionHook:E),[j,X.legendSelectionHook,E]),U=function(e){const t=Wt(e=>e.theme.colors.selectionOpacity);return vo(()=>{if(void 0!==e||void 0!==t)return{name:e?.name??"",...e,unselectedOpacity:e?.unselectedOpacity??t}},[e,t])}(a),Q=rt(),Z=Je(),K=bo(()=>{if(H)return H;if(!n||0===G.length)return;const e=Array.isArray(i)&&i.length>0||"string"==typeof i&&i.length>0?i:Q&&Q.length>0?Q:F,t="__streamCat",o=G.map(e=>({[t]:e})),r=J(o,t,e);return e=>Z?.[e]||r(e)||"#999"},[H,n,G,i,Q,Z]),{legend:ee,margin:te,legendPosition:ne}=et({data:I,colorBy:n,colorScale:K,showLegend:g,legendPosition:s,userMargin:y,defaults:b,categories:G,additionalLegend:m,chartWidth:_,legendLayout:f,hasTitle:T,axisChrome:L}),re=bo(()=>{const e={};return ee&&(e.legend=ee,e.legendPosition=ne,f&&(e.legendLayout=f)),r&&"none"!==r&&(e.legendHoverBehavior=X.onLegendHover,e.legendClickBehavior=X.onLegendClick,e.legendHighlightedCategory=X.highlightedCategory,e.legendIsolatedCategories=X.isolatedCategories),R&&n&&(e.legendCategoryAccessor=n,e.onCategoriesChange=O),e},[ee,ne,f,r,X.onLegendHover,X.onLegendClick,X.highlightedCategory,X.isolatedCategories,R,n,O]),se=Array.isArray(o)?ie(o):o,ae=Re(S,_,P,k),le=ae?null:Le(se,_,P,M);return{data:I,colorScale:H,allCategories:G,legendState:X,effectiveSelectionHook:q,activeSelectionHook:E,customHoverBehavior:$,customClickBehavior:D,mobileInteraction:N,legend:ee,margin:te,legendPosition:ne,earlyReturn:ae||le||null,legendBehaviorProps:re,crosshairProps:Y,resolvedSelection:U}}({data:e.data??[],rawData:e.data,colorBy:e.colorBy,colorScheme:e.colorScheme,legendInteraction:e.legendInteraction,legendPosition:e.legendPosition,selection:e.selection,linkedHover:e.linkedHover,hoverHighlight:e.hoverHighlight,fallbackFields:"string"==typeof e.colorBy?[e.colorBy]:[],unwrapData:e.unwrapData,onObservation:e.onObservation,onClick:e.onClick,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,chartType:e.chartTypeLabel,chartId:e.chartId,showLegend:o.showLegend,legend:e.legend,userMargin:n,marginDefaults:o.marginDefaults,loading:e.loading,loadingContent:e.loadingContent,emptyContent:e.emptyContent,width:o.width,height:o.height});return{...t,safeData:i.data,setup:i,earlyReturn:i.earlyReturn}}({imperativeRef:t,imperativeVariant:"xy",chartTypeLabel:"XYCustomChart",unwrapData:!1,data:o,colorBy:w,colorScheme:A,legend:L,legendInteraction:k,legendPosition:M,selection:g,linkedHover:m,hoverHighlight:f,onObservation:h,onClick:p,chartId:y,loading:b,loadingContent:x,emptyContent:v,margin:c,width:e.width,height:e.height,showGrid:e.showGrid,enableHover:e.enableHover,showLegend:e.showLegend,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mode:e.mode,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules,xLabel:e.xLabel,yLabel:e.yLabel}),E=z.effectiveSelectionHook,j=go(()=>E?.isActive?{isActive:!0,predicate:E.predicate}:null,[E?.isActive,E?.predicate]);if(B)return B;const{width:W,height:Y,enableHover:H,showGrid:V,title:G,description:q,summary:U,accessibleTable:Q,xLabel:Z,yLabel:K}=I,ee={chartType:"custom",...null!=o&&{data:C},customLayout:n,layoutConfig:i,onLayoutError:r,...j&&{layoutSelection:j},xExtent:s,yExtent:a,colorAccessor:w,colorScheme:A,size:[W,Y],responsiveWidth:e.responsiveWidth,responsiveHeight:e.responsiveHeight,margin:z.margin,showAxes:l,xLabel:Z,yLabel:K,enableHover:H,showGrid:V,...z.legendBehaviorProps,...$({title:G,description:q,summary:U,accessibleTable:Q,className:u,animate:e.animate,axisExtent:e.axisExtent,autoPlaceAnnotations:e.autoPlaceAnnotations}),...null!=e.tooltip&&{tooltipContent:e.tooltip},...D({linkedHover:m,selection:g,onObservation:h,onClick:p,hoverRadius:e.hoverRadius,hoverHighlight:f,mobileInteraction:z.mobileInteraction,customHoverBehavior:z.customHoverBehavior,customClickBehavior:z.customClickBehavior}),...d&&d.length>0&&{annotations:d},...z.crosshairProps,...T};return ko(O,{componentName:"XYCustomChart",width:W,height:Y,children:ko(N,{ref:R,...ee})})});function _o(e,t,o,n,i){const r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*o+i*i*i*n}function Po(e,t,o,n,i){const r=1-i;return 3*r*r*(t-e)+6*r*i*(o-t)+3*i*i*(n-o)}function To(e,t,o,n,i){const r=[],s=(e.x+t.x)/2;for(let a=0;i>=a;a++){const l=a/i;let c,u,d,h;"linear"===n?(c=e.x+(t.x-e.x)*l,u=e.y+(t.y-e.y)*l,d=t.x-e.x,h=t.y-e.y):(c=_o(e.x,s,s,t.x,l),u=_o(e.y,e.y,t.y,t.y,l),d=Po(e.x,s,s,t.x,l),h=Po(e.y,e.y,t.y,t.y,l)),r.push({x:c,y:u,dx:d,dy:h,radius:e.radius+(t.radius-e.radius)*l,datumIndex:.5>l?o:o+1})}return r}function Lo(e,t={}){const o=[],n=[],i=[];if(2>e.length)return{topPath:o,bottomPath:n,datumIndices:i};const r=t.curve??"smooth",s=Math.max(2,Math.floor(t.samplesPerSegment??12));for(let t=0;e.length-1>t;t++){const a=To(e[t],e[t+1],t,r,s);for(let e=0===t?0:1;a.length>e;e++){const t=a[e],r=Math.hypot(t.dx,t.dy)||1,s=-t.dy/r,l=t.dx/r,c=Math.max(0,t.radius);o.push([t.x+s*c,t.y+l*c]),n.push([t.x-s*c,t.y-l*c]),i.push(t.datumIndex)}}return{topPath:o,bottomPath:n,datumIndices:i}}Mo.displayName="XYCustomChart";import{jsx as Ro,jsxs as Io}from"react/jsx-runtime";function Co(e,t,o){return"function"==typeof e?e(t,o):t[e]}function zo(e){return e instanceof Date?"date:"+e.getTime():`${typeof e}:${e+""}`}function Fo(e,t){if(!e?.length)return;const o=new Map(t.map((e,t)=>[zo(e),t]));return e.map(e=>{const t={...e},n=n=>{if(!(n in e))return;const i=o.get(zo(e[n]));void 0!==i&&(t[n]=i)};return n("x"),n("x0"),n("x1"),"string"!=typeof e.type||"x-threshold"!==e.type&&"x"!==e.type||n("value"),t})}function Oo(e){const{seriesOrder:t,overallOrder:o,highlightTop:n,color:i,colorScheme:r,neutralColor:s,themeCategorical:a,themeNeutral:l}=e;if(null==n&&null==i)return r;const c=new Set(o.slice(0,null==n?o.length:Math.max(0,Math.floor(n)))),u=new Map,d={};for(const e of t)d[e]=i??(c.has(e)?Ee(void 0,a,r,e,u):s??l??"#b8bec8");return d}function Bo(e,t={}){const o=t.xAccessor??"x",n=t.yAccessor??"y",i=t.lineBy??"series",r=t.rankDirection??"descending",s=[],a=new Map,l=new Map,c=[],u=new Map;let d=1/0,h=-1/0;e.forEach((e,t)=>{const r=Co(o,e,t),p=zo(r);let g=a.get(p);null==g&&(g=s.length,a.set(p,g),s.push(r),l.set(g,[]));const m=Co(i,e,t)+"";u.has(m)||(u.set(m,c.length),c.push(m));const f=Number(Co(n,e,t));Number.isFinite(f)&&(d=Math.min(d,f),h=Math.max(h,f),l.get(g)?.push({datum:e,inputIndex:t,series:m,value:f}))});const p=[],g=new Map,m=new Map;for(let e=0;s.length>e;e++){const t=l.get(e)??[];t.sort((e,t)=>("descending"===r?t.value-e.value:e.value-t.value)||(u.get(e.series)??0)-(u.get(t.series)??0)),t.forEach((t,o)=>{const n=o+1;p.push({datum:t.datum,xIndex:e,xValue:s[e],series:t.series,value:t.value,rank:n}),g.set(t.series,(g.get(t.series)??0)+n),m.set(t.series,(m.get(t.series)??0)+1)})}const f=c.length+1,y=[...c].sort((e,t)=>{const o=m.get(e)??0,n=m.get(t)??0;return((g.get(e)??0)+(s.length-o)*f)/Math.max(1,s.length)-((g.get(t)??0)+(s.length-n)*f)/Math.max(1,s.length)||(u.get(e)??0)-(u.get(t)??0)}),b=new Set(y.slice(0,null==t.highlightTop?y.length:Math.max(0,Math.floor(t.highlightTop))));return{data:p.map(e=>{const t=b.has(e.series);return{...e.datum,x:e.xIndex,y:e.rank,__bumpRaw:e.datum,__bumpSeries:e.series,__bumpColorGroup:t?e.series:"Other",__bumpValue:e.value,__bumpRank:e.rank,__bumpXValue:e.xValue,__bumpHighlighted:t}}),xValues:s,seriesOrder:c,overallOrder:y,valueExtent:d===1/0?[0,0]:[d,h]}}function No({datum:e,x:t,y:o,side:n,color:i,highlighted:r,labelStyle:s}){const a=Tt(),l=a.isActive&&!a.predicate(e),c="function"==typeof s?s(e.__bumpRaw):s;return Ro("text",{className:"semiotic-bump-label",x:t+("end"===n?8:-8),y:o,dy:"0.35em",textAnchor:"end"===n?"start":"end",fill:i,fillOpacity:l?.16:1,fontWeight:r?650:450,fontSize:12,style:{pointerEvents:"none",fontFamily:"var(--semiotic-font-family, sans-serif)",fontSize:"var(--semiotic-axis-label-font-size, 12px)",...c},children:e.__bumpSeries})}function Eo(e,t,o){const[n,i]=t,[r,s]=o;return i===n?(r+s)/2:r+(s-r)*Math.max(0,Math.min(1,(e-n)/(i-n)))}function jo(e){const t=e instanceof Date?e.getTime():Number(e);return Number.isFinite(t)?t:void 0}function $o(e){return{value:e.__bumpValue,x:jo(e.__bumpXValue),y:e.__bumpValue,category:e.__bumpSeries}}function Do(e){const t=e.config,o=new Map;for(const t of e.data){const e=o.get(t.__bumpSeries)??[];e.push(t),o.set(t.__bumpSeries,e)}const n=t.seriesOrder.filter(e=>o.has(e)).sort((e,n)=>(o.get(e)?.[0]?.__bumpHighlighted?1:0)-(o.get(n)?.[0]?.__bumpHighlighted?1:0)||t.seriesOrder.indexOf(e)-t.seriesOrder.indexOf(n)),i=[],r=[];for(const s of n){const n=(o.get(s)??[]).sort((e,t)=>e.x-t.x);if(2>n.length)continue;const l=n[0].__bumpHighlighted,c=e.resolveColor(n[0].__bumpSeries,n[0]),u=t.color??(l?c:t.neutralColor??e.theme.semantic.textSecondary??e.theme.semantic.border??c),d=n.map(o=>({x:e.scales.x(o.x),y:e.scales.y(o.y),radius:t.ribbon?Eo(o.__bumpValue,t.valueExtent,t.ribbonSizeRange)/2:Math.max(.5,t.lineWidth/2)})),h=Lo(d,{curve:t.curve,samplesPerSegment:t.samplesPerSegment}),p=h.datumIndices.map(e=>n[e]),g={fill:u,fillOpacity:1,opacity:l?t.ribbon?t.ribbonOpacity:t.lineOpacity:Math.min(t.ribbon?t.ribbonOpacity:t.lineOpacity,.58)};t.styleRules?.length&&Object.assign(g,a(n[0].__bumpRaw,t.styleRules,$o(n[0]))),t.areaStyle&&Object.assign(g,t.areaStyle(n[0].__bumpRaw)??{}),void 0!==t.stroke&&(g.stroke=t.stroke),void 0!==t.strokeWidth&&(g.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(g.opacity=t.opacity),i.push({type:"area",topPath:h.topPath,bottomPath:h.bottomPath,style:g,datum:p,accessibleDatum:n.map(e=>e.__bumpRaw),accessibility:{label:s+" ranking trajectory",tableFields:n.map(e=>e.__bumpRaw)},group:s,interactive:!0}),t.showPoints&&n.forEach((e,o)=>{const n={fill:u,stroke:"none",opacity:l?1:.75};t.styleRules?.length&&Object.assign(n,a(e.__bumpRaw,t.styleRules,$o(e))),t.pointStyle&&Object.assign(n,t.pointStyle(e.__bumpRaw)??{}),void 0!==t.stroke&&(n.stroke=t.stroke),void 0!==t.strokeWidth&&(n.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(n.opacity=t.opacity),i.push({type:"point",x:d[o].x,y:d[o].y,r:n.r??t.pointRadius,style:n,datum:e,accessibleDatum:e.__bumpRaw,accessibility:{label:`${s}, rank ${e.__bumpRank}, value ${e.__bumpValue}`},pointId:`${s}:${e.x}`})});const m=!0===t.showLabels?"end":t.showLabels,f=(e,o,n)=>{r.push(Ro(No,{datum:e,x:d[o].x,y:d[o].y,side:n,color:"string"==typeof g.fill?g.fill:u,highlighted:l,labelStyle:t.labelStyle},`${s}-${n}`))};"start"!==m&&"both"!==m||f(n[0],0,"start"),"end"!==m&&"both"!==m||f(n.at(-1),n.length-1,"end")}return{nodes:i,overlays:r.length?Ro("g",{className:"semiotic-bump-labels",children:r}):void 0,restyle:(e,t)=>{const o=function(e){const t=Array.isArray(e.datum)?e.datum[0]:e.datum;return t&&"object"==typeof t&&"__bumpSeries"in t?t:void 0}(e);if(t?.isActive&&o&&!t.predicate(o))return{opacity:.14}}}}function Wo(e,t,o,n,i){const s=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrAreaColorBy",d="function"==typeof t?s.map(e=>({...e,__ssrAreaColorBy:t(e)})):s,h=t?J(d,u,c):void 0,p=!1!==i.showLine,g="number"==typeof i.lineWidth?i.lineWidth:2,m="number"==typeof i.areaOpacity?i.areaOpacity:.7,f=r(i.yAccessor),y=i.styleRules;return(e,o)=>{const n=t&&h?le(e,t,h):"string"==typeof i.color?i.color:R,r={fill:n,fillOpacity:m,stroke:p?n:"none",...p&&{strokeWidth:g}};return y?.length&&Object.assign(r,a(e,y,{value:f(e),category:o})),void 0!==i.stroke&&(r.stroke=i.stroke),void 0!==i.strokeWidth&&(r.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(r.opacity=i.opacity),r}}function Yo(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=Kt(n.theme).colors.categorical,a=o??n.colorScheme??s,l="string"==typeof t?t:"__ssrBubbleColorBy",c="function"==typeof t?r.map(e=>({...e,__ssrBubbleColorBy:t(e)})):r,u=t?J(c,l,a):void 0,d=i.sizeBy,h=Array.isArray(i.sizeRange)?i.sizeRange:[5,40],p=d?r.map(e=>"function"==typeof d?d(e):Number(e[d])).filter(Number.isFinite):[],g=p.length?Ot(p):void 0;return e=>({fill:t&&u?le(e,t,u):"string"==typeof i.color?i.color:R,fillOpacity:"number"==typeof i.bubbleOpacity?i.bubbleOpacity:.6,r:d?de(e,d,h,g):h[0],stroke:i.stroke??i.bubbleStrokeColor??"white",strokeWidth:i.strokeWidth??i.bubbleStrokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}})}function Ho(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrScatterColorBy",d="function"==typeof t?r.map(e=>({...e,__ssrScatterColorBy:t(e)})):r,h=t?J(d,u,c):void 0,p=i.sizeBy,g=Array.isArray(i.sizeRange)?i.sizeRange:[3,15],m=p?r.map(e=>"function"==typeof p?p(e):Number(e[p])).filter(Number.isFinite):[],f=m.length?Ot(m):void 0,y=s(i.xAccessor,i.yAccessor),b=i.styleRules;return e=>{const o={fill:t&&h?le(e,t,h):"string"==typeof i.color?i.color:R,fillOpacity:"number"==typeof i.pointOpacity?i.pointOpacity:.8,r:p?de(e,p,g,f):"number"==typeof i.pointRadius?i.pointRadius:5};return b?.length&&Object.assign(o,a(e,b,y(e))),void 0!==i.stroke&&(o.stroke=i.stroke),void 0!==i.strokeWidth&&(o.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(o.opacity=i.opacity),o}}co(function(e,t){const o=rt(),n=lt(),{data:i,xAccessor:r,yAccessor:s,lineBy:a,rankDirection:l="descending",ribbon:c=!1,curve:u="smooth",ribbonSizeRange:d=[4,28],samplesPerSegment:h=12,lineWidth:p=3,highlightTop:g,neutralColor:m,styleRules:f,labelStyle:y,colorScheme:b,ribbonOpacity:x=.82,lineOpacity:v=.9,showPoints:w=!1,pointRadius:A=3,showLabels:S=!0,showAxes:k=!0,showGrid:M=!0,showLegend:_=!1,enableHover:P=!0,hoverHighlight:T=!0,tooltip:L,frameProps:R={},xFormat:I,yFormat:C,onClick:z}=e,F=ho(()=>Bo(i,{xAccessor:r,yAccessor:s,lineBy:a,rankDirection:l,highlightTop:g}),[i,r,s,a,l,g]),{axes:O,areaStyle:B,pointStyle:N,...E}=R,j=ho(()=>Oo({seriesOrder:F.seriesOrder,overallOrder:F.overallOrder,highlightTop:g,color:e.color,colorScheme:b,neutralColor:m,themeCategorical:o,themeNeutral:n.colors.textSecondary}),[F.seriesOrder,F.overallOrder,g,e.color,b,m,o,n.colors.textSecondary]),$=ho(()=>({ribbon:c,curve:u,samplesPerSegment:h,ribbonSizeRange:d,valueExtent:F.valueExtent,seriesOrder:F.seriesOrder,lineWidth:p,ribbonOpacity:x,lineOpacity:v,neutralColor:m,color:e.color,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,styleRules:f,areaStyle:B,pointStyle:N,labelStyle:y,showPoints:w,pointRadius:A,showLabels:S}),[c,u,h,d,F.valueExtent,F.seriesOrder,p,x,v,m,e.color,e.stroke,e.strokeWidth,e.opacity,f,B,N,y,w,A,S]),D=uo((e,t)=>{if(0===F.xValues.length)return"";const o=F.xValues[Math.max(0,Math.min(F.xValues.length-1,Math.round(Number(e))))];return I?I(o,t):(o instanceof Date?o.toLocaleDateString():o)+""},[F.xValues,I]),W=uo(e=>C?C(e):e.toLocaleString(),[C]),Y=ho(()=>"multi"===L?void 0:pt(L),[L]),H=uo(e=>{const t=e?.data??e;return t?!1===L?null:Y?Y({...e,data:t.__bumpRaw,__semioticHoverData:!0}):Io("div",{className:"semiotic-tooltip",style:dt,children:[Ro("div",{style:{fontWeight:700},children:t.__bumpSeries}),Io("div",{children:[D(t.x)," · Rank ",t.__bumpRank]}),Io("div",{children:["Value: ",W(t.__bumpValue)]})]}):null},[W,D,Y,L]),V=ho(()=>{if(z)return(e,t)=>{z(e.__bumpRaw??e,t)}},[z]),G=Math.max(1,F.seriesOrder.length),X=F.xValues.map((e,t)=>t),q=Array.from({length:G},(e,t)=>t+1),U=O??[{orient:"left",tickValues:q,tickFormat:e=>e+"",label:e.yLabel??"Rank",baseline:!1},{orient:"bottom",tickValues:X,tickFormat:D,label:e.xLabel,tickAnchor:"edges"}],Q=ho(()=>Fo(e.annotations,F.xValues),[e.annotations,F.xValues]);return Ro(Mo,{ref:t,data:F.data,layout:Do,layoutConfig:$,xExtent:[0,Math.max(1,F.xValues.length-1)],yExtent:[G+.5,.5],showAxes:k,showGrid:M,showLegend:_,enableHover:P,hoverHighlight:T,colorBy:"__bumpSeries",colorScheme:j,tooltip:H,onClick:V,hoverRadius:e.hoverRadius,width:e.width,height:e.height,responsiveWidth:e.responsiveWidth,responsiveHeight:e.responsiveHeight,responsiveRules:e.responsiveRules,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,mode:e.mode,margin:e.margin??{top:20,right:S?110:24,bottom:48,left:48},className:e.className,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,selection:e.selection,linkedHover:e.linkedHover,legend:e.legend,legendInteraction:e.legendInteraction,legendPosition:e.legendPosition,onObservation:e.onObservation,chartId:e.chartId,loading:e.loading,loadingContent:e.loadingContent,emptyContent:e.emptyContent,animate:e.animate,autoPlaceAnnotations:e.autoPlaceAnnotations,annotations:Q,xLabel:e.xLabel,yLabel:e.yLabel??"Rank",frameProps:{axes:U,axisExtent:"exact",...E}})}).displayName="BumpChart";var Vo={frameType:"xy",buildProps:(e,t,o,n,i)=>({chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,sizeRange:i.sizeRange||[5,40],colorScheme:o,...n,pointStyle:n.pointStyle||Yo(e,t,o,n,i),showLegend:n.showLegend??!!t})},Go={frameType:"xy",layout:{margin:e=>({top:20,right:!1===e.showLabels?24:110,bottom:48,left:48})},buildProps:(e,t,o,n,i)=>{const r=Bo(Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],{xAccessor:i.xAccessor,yAccessor:i.yAccessor,lineBy:i.lineBy,rankDirection:i.rankDirection,highlightTop:"number"==typeof i.highlightTop?i.highlightTop:void 0}),s=Math.max(1,r.seriesOrder.length),a=Kt(n.theme),l=Oo({seriesOrder:r.seriesOrder,overallOrder:r.overallOrder,highlightTop:"number"==typeof i.highlightTop?i.highlightTop:void 0,color:"string"==typeof i.color?i.color:void 0,colorScheme:o,neutralColor:"string"==typeof i.neutralColor?i.neutralColor:void 0,themeCategorical:a.colors.categorical,themeNeutral:a.colors.textSecondary}),c={ribbon:!0===i.ribbon,curve:"linear"===i.curve?"linear":"smooth",samplesPerSegment:"number"==typeof i.samplesPerSegment?i.samplesPerSegment:12,ribbonSizeRange:Array.isArray(i.ribbonSizeRange)?i.ribbonSizeRange:[4,28],valueExtent:r.valueExtent,seriesOrder:r.seriesOrder,lineWidth:"number"==typeof i.lineWidth?i.lineWidth:3,ribbonOpacity:"number"==typeof i.ribbonOpacity?i.ribbonOpacity:.82,lineOpacity:"number"==typeof i.lineOpacity?i.lineOpacity:.9,neutralColor:"string"==typeof i.neutralColor?i.neutralColor:void 0,color:"string"==typeof i.color?i.color:void 0,stroke:"string"==typeof i.stroke?i.stroke:void 0,strokeWidth:"number"==typeof i.strokeWidth?i.strokeWidth:void 0,opacity:"number"==typeof i.opacity?i.opacity:void 0,styleRules:i.styleRules,areaStyle:n.areaStyle,pointStyle:n.pointStyle,labelStyle:i.labelStyle,showPoints:!0===i.showPoints,pointRadius:"number"==typeof i.pointRadius?i.pointRadius:3,showLabels:i.showLabels??!0},u=n.xFormat,d=(e,t)=>{if(0===r.xValues.length)return"";const o=r.xValues[Math.max(0,Math.min(r.xValues.length-1,Math.round(Number(e))))];return u?u(o,t):(o instanceof Date?o.toLocaleDateString():o)+""},h=r.xValues.map((e,t)=>t),p=Array.from({length:s},(e,t)=>t+1),g=n.axes??[{orient:"left",tickValues:p,tickFormat:e=>e+"",label:n.yLabel??"Rank",baseline:!1},{orient:"bottom",tickValues:h,tickFormat:d,label:n.xLabel,tickAnchor:"edges"}];return{...n,chartType:"custom",data:r.data,xAccessor:"x",yAccessor:"y",xExtent:[0,Math.max(1,r.xValues.length-1)],yExtent:[s+.5,.5],customLayout:Do,layoutConfig:c,colorAccessor:"__bumpSeries",colorScheme:l,xFormat:d,axes:g,axisExtent:"exact",showAxes:n.showAxes??!0,showLegend:n.showLegend??!1,annotations:Fo(n.annotations,r.xValues)}}};function Xo(e,t,o,n,i){if(!i.showPoints)return;const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=Kt(n.theme).colors.categorical,a=o??n.colorScheme??s,l="string"==typeof t?t:"__ssrPointColorBy",c="function"==typeof t?r.map(e=>({...e,__ssrPointColorBy:t(e)})):r,u=t?J(c,l,a):void 0,d="number"==typeof i.pointRadius?i.pointRadius:3;return e=>{const o=t&&u?le(e,t,u):"string"==typeof i.color?i.color:R;return{r:d,fill:o,stroke:"none"}}}var qo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=t||i.lineBy,l=i.fillArea,c=Array.isArray(l)?"mixed":l?"area":"line",u=Kt(n.theme).colors.categorical,d=function(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrLineColorBy",d="function"==typeof t?r.map(e=>({...e,__ssrLineColorBy:t(e)})):r,h=t?J(d,u,c):void 0,p=s(i.xAccessor,i.yAccessor),g=function(e){const{lineWidth:t=2,colorBy:o,colorScale:n,color:i,resolveStroke:r,fillArea:s,areaOpacity:l=.3,styleRules:c,ruleContext:u}=e;return(e,d)=>{const h={strokeWidth:t},p=!0===s||Array.isArray(s)&&null!=d&&s.includes(d);let g;return r?g=r(e,d):o?n&&(g=le(e,o,n)):g=i||R,void 0!==g&&(h.stroke=g,p&&(h.fill=g,h.fillOpacity=l)),c?.length&&Object.assign(h,a(e,c,u?u(e,d):{value:void 0,category:d})),h}}({lineWidth:"number"==typeof i.lineWidth?i.lineWidth:2,colorBy:t,colorScale:h,color:"string"==typeof i.color?i.color:void 0,fillArea:i.fillArea,areaOpacity:"number"==typeof i.areaOpacity?i.areaOpacity:.3,styleRules:i.styleRules,ruleContext:p});return Xt(g,{stroke:"string"==typeof i.stroke?i.stroke:void 0,strokeWidth:"number"==typeof i.strokeWidth?i.strokeWidth:void 0,opacity:"number"==typeof i.opacity?i.opacity:void 0})}(e,r,o,n,i),h=lo({data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",lineBy:i.lineBy,colorBy:r,colorScheme:o,color:"string"==typeof i.color?i.color:void 0,forecast:i.forecast,anomaly:i.anomaly,gapStrategy:i.gapStrategy,directLabel:i.directLabel,annotations:n.annotations,themeCategorical:u,baseLineStyle:d}),p=n.pointStyle||Xo(h.data,h.colorAccessor,o,n,i);let g=n.margin;h.marginExtra&&g&&"object"==typeof g?g={...g,...null!=h.marginExtra.right&&{right:Math.max(Number(g.right)||0,h.marginExtra.right)},...null!=h.marginExtra.left&&{left:Math.max(Number(g.left)||0,h.marginExtra.left)}}:h.marginExtra&&null==g&&(g={top:20,right:h.marginExtra.right??20,bottom:30,left:h.marginExtra.left??40});const m=(!i.directLabel||void 0!==n.showLegend)&&(n.showLegend??!!h.colorAccessor);return{chartType:c,data:h.data,xAccessor:h.xAccessor,yAccessor:h.yAccessor,groupAccessor:h.groupAccessor,colorAccessor:h.colorAccessor,colorScheme:o,lineStyle:h.lineStyle||d,...Array.isArray(l)&&{areaGroups:l},...l&&null!=i.areaOpacity&&{areaOpacity:i.areaOpacity},...null!=i.band&&{band:i.band},...n,...void 0!==g&&{margin:g},annotations:h.annotations,...h.yExtent&&!n.yExtent&&{yExtent:h.yExtent},...p&&{pointStyle:p},showLegend:m}}},Uo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=Array.isArray(e)?ie(e):[],s=i.timeAccessor||"time",a=i.valueAccessor||"value",l=i.categoryAccessor,c=i.valueExtent||n.yExtent,u="down"===i.direction?je({data:r,timeAccessor:s,valueAccessor:a,binSize:Number(i.binSize),valueExtent:c,extentPadding:i.extentPadding}):c,d={...void 0!==i.fill&&{fill:i.fill},...void 0!==i.stroke&&{stroke:i.stroke},...void 0!==i.strokeWidth&&{strokeWidth:i.strokeWidth},...void 0!==i.opacity&&{opacity:i.opacity},...void 0!==i.gap&&{gap:i.gap}};return{chartType:"bar",data:r,...n,runtimeMode:"streaming",windowMode:"growing",windowSize:Math.max(1,r.length),arrowOfTime:i.arrowOfTime||"right",timeAccessor:s,valueAccessor:a,xExtent:i.timeExtent||n.xExtent,yExtent:u,extentPadding:i.extentPadding??n.extentPadding,binSize:i.binSize,categoryAccessor:l,barColors:i.colors||n.barColors,colorScheme:i.colors||n.colorScheme,barStyle:n.barStyle||d,showLegend:n.showLegend??!!l}}},Qo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=t||i.areaBy,s=function({data:e,safeData:t,areaBy:o,lineDataAccessor:n}){if(null==e)return[];const i=void 0!==t[0]?.[n];if(!i&&!o)return t;let r;if(i)r=t;else{const e=t.reduce((e,t)=>{const i="function"==typeof o?o(t):t[o],r=i+"";if(!e[r]){const t={[n]:[]};"string"==typeof o&&(t[o]=i),e[r]=t}return e[r][n].push(t),e},{});r=Object.values(e)}return r.flatMap(e=>{const t=Array.isArray(e[n])?e[n]:[];return"string"==typeof o?t.map(t=>({...t,[o]:t[o]??e[o]})):t})}({data:e,safeData:Array.isArray(e)?ie(e):[],areaBy:i.areaBy,lineDataAccessor:i.lineDataAccessor||"coordinates"}),a=ke(i.semanticGradient),l=a?.stops.length?qe(a):Se(n.gradientFill),c=!1!==i.semanticLine&&a?.stops.length?a.stops.flatMap(({offset:e,color:t})=>t?[{offset:e,color:t}]:[]):void 0,u=n.pointStyle||Xo(s,r,o,n,i);return{chartType:"area",data:s,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",y0Accessor:i.y0Accessor,groupAccessor:i.areaBy||void 0,colorAccessor:r,colorScheme:o,...n,...void 0!==l&&{gradientFill:l},...c&&{semanticLineStops:c},lineStyle:n.lineStyle||Wo(s,r,o,n,i),...u&&{pointStyle:u}}}},Zo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=i.xAccessor||"x",s=i.seriesAAccessor||"a",a=i.seriesBAccessor||"b",l=e=>Ut(qt(r,"x",e)),c=e=>Ut(qt(s,"a",e)),u=e=>Ut(qt(a,"b",e)),d=i.seriesAColor||"var(--semiotic-danger, #dc2626)",h=i.seriesBColor||"var(--semiotic-info, #2563eb)",p=i.areaOpacity??.6,g=i.lineWidth??1.5,m=!1!==i.showLines,f=!1!==n.showLegend,y=i.seriesALabel||"A",b=i.seriesBLabel||"B",x=n.legendPosition||"right",v=function(e,t,o,n){if(!e.length)return[];const i=e.filter(e=>Number.isFinite(t(e))).sort((e,o)=>t(e)-t(o)),r=[];let s=0,a=null,l=null,c=[];const u=(e,t)=>e>t?"A":t>e?"B":null,d=e=>`seg-${s}-${e}`,h=e=>r.push(e),p=(e,t)=>{h({__x:e.x,__y:e.y,__y0:e.y,__diffSegment:d(t),__diffWinner:t,__valA:e.y,__valB:e.y,__sourceDatum:e.datum})};for(let e=0;i.length>e;e++){const r=i[e],g=t(r),m=o(r),f=n(r);if(!Number.isFinite(g)||!Number.isFinite(m)||!Number.isFinite(f))continue;const y=u(m,f);if(null!==y)if(null!=a){if(l&&l.w!==y){let e,t;if(c.length>0)e=c[0].x,t=c[0].y;else{const o=m-l.a-(f-l.b);if(0!==o){const n=Math.max(0,Math.min(1,(l.b-l.a)/o));e=l.x+n*(g-l.x),t=l.a+n*(m-l.a)}else e=l.x,t=l.a}h({__x:e,__y:t,__y0:t,__diffSegment:d(a),__diffWinner:a,__valA:t,__valB:t}),s++,a=y,h({__x:e,__y:t,__y0:t,__diffSegment:d(a),__diffWinner:a,__valA:t,__valB:t});for(let e=1;c.length>e;e++)p(c[e],a)}else for(const e of c)p(e,a);c=[],h({__x:g,__y:f>m?f:m,__y0:f>m?m:f,__diffSegment:d(a),__diffWinner:a,__valA:m,__valB:f,__sourceDatum:r}),l={x:g,a:m,b:f,w:y}}else{a=y;for(const e of c)p(e,a);c=[],h({__x:g,__y:f>m?f:m,__y0:f>m?m:f,__diffSegment:d(a),__diffWinner:a,__valA:m,__valB:f,__sourceDatum:r}),l={x:g,a:m,b:f,w:y}}else c.push({x:g,y:m,datum:r})}for(const e of c)p(e,a??"A");return r}(Array.isArray(e)?e:[],l,c,u),w=[];if(m&&Array.isArray(e)){const t=e.filter(e=>Number.isFinite(l(e))).sort((e,t)=>l(e)-l(t));for(const e of t){const t=l(e),o=c(e),n=u(e);Number.isFinite(o)&&w.push({__x:t,__y:o,__diffSegment:"line-A"}),Number.isFinite(n)&&w.push({__x:t,__y:n,__diffSegment:"line-B"})}}return{chartType:"mixed",data:[...v,...w],xAccessor:"__x",yAccessor:"__y",y0Accessor:"__y0",groupAccessor:"__diffSegment",areaGroups:Array.from(new Set(v.map(e=>e.__diffSegment))),areaStyle:e=>{const t=e.__diffSegment;return{fill:"A"==(t?.endsWith("-A")?"A":"B")?d:h,stroke:"none",fillOpacity:p}},lineStyle:e=>({stroke:"A"==("line-A"===e.__diffSegment?"A":"B")?d:h,strokeWidth:g,fill:"none"}),curve:i.curve||"linear",...n,...f&&{legend:{legendGroups:[{label:"",type:"fill",styleFn:e=>({fill:e.color||"currentColor"}),items:[{label:y,color:d},{label:b,color:h}]}]},legendPosition:x}}}},Ko={frameType:"xy",buildProps:(e,t,o,n,i)=>{const s=t||i.areaBy,l="string"==typeof s&&Array.isArray(e)?J(e,s,o):void 0,c="number"==typeof i.areaOpacity?i.areaOpacity:.7,u=n.lineStyle||(e=>{const t=null==s?void 0:le(e,s,l),o=i.showLine??!0,n={fill:i.color??t,stroke:o?i.stroke??t:"none",...o?{strokeWidth:i.strokeWidth??i.lineWidth??2}:{},fillOpacity:c,...null==i.opacity?{}:{opacity:i.opacity}},u=i.styleRules;if(u?.length){const t=r(i.yAccessor),o=s?"function"==typeof s?(s(e)??"")+"":(e[s]??"")+"":void 0;Object.assign(n,a(e,u,{value:t(e),category:o}))}return n}),d=i.normalize?"zero":i.baseline??"zero",h=n.pointStyle||Xo(e,s,o,n,i);return{chartType:"stackedarea",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",groupAccessor:i.areaBy,colorAccessor:s,colorScheme:o,normalize:i.normalize,baseline:d,stackOrder:i.stackOrder,lineStyle:u,...n,...h&&{pointStyle:h},curve:n.curve??i.curve??"monotoneX",showLegend:n.showLegend??!!s}}},Jo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const[r]=n.size??[600,400];return{chartType:"candlestick",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.highAccessor||"high",highAccessor:i.highAccessor||"high",lowAccessor:i.lowAccessor||"low",openAccessor:i.openAccessor,closeAccessor:i.closeAccessor,candlestickStyle:i.candlestickStyle,...n,scalePadding:n.scalePadding??Math.max(2,Math.min(12,Math.round(r/40))),extentPadding:n.extentPadding??(r>200?.1:.02)}}},en={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=n.pointStyle||Ho(e,t,o,n,i),s=c(i.styleRules,i.xAccessor||"x",i.yAccessor||"y"),a=s?e=>({..."function"==typeof r?r(e):r,...s(e)}):r;return{chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,...i.symbolBy&&{symbolAccessor:i.symbolBy},...i.symbolMap&&{symbolMap:i.symbolMap},colorScheme:o,...n,sizeRange:i.sizeRange||[3,15],pointStyle:a,showLegend:n.showLegend??!!t}}},tn={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=i.xCenter,s=i.yCenter,a=i.quadrants,l=i.centerlineStyle||{},c=!1!==i.showQuadrantLabels,u=i.quadrantLabelSize??12,d=l.stroke||"#999",h=l.strokeWidth??1,p=Array.isArray(l.strokeDasharray)?l.strokeDasharray.join(","):l.strokeDasharray,g=Vt.createElement,m=a?[(e,t,o)=>{if(!t?.x||!t?.y)return null;const n=o.width,i=o.height,l=null!=r?t.x(r):n/2,m=null!=s?t.y(s):i/2;if(null!=r&&!Number.isFinite(l))return null;if(null!=s&&!Number.isFinite(m))return null;const f=Math.max(0,Math.min(n,l)),y=Math.max(0,Math.min(i,m)),b=[{c:a.topLeft,x:0,y:0,w:f,h:y},{c:a.topRight,x:f,y:0,w:n-f,h:y},{c:a.bottomLeft,x:0,y:y,w:f,h:i-y},{c:a.bottomRight,x:f,y:y,w:n-f,h:i-y}],x=c?[g("text",{key:"ltl",x:8,y:8+u,fill:a.topLeft.color,fontWeight:600,fontSize:u,opacity:.5},a.topLeft.label),g("text",{key:"ltr",x:n-8,y:8+u,fill:a.topRight.color,fontWeight:600,fontSize:u,opacity:.5,textAnchor:"end"},a.topRight.label),g("text",{key:"lbl",x:8,y:i-8,fill:a.bottomLeft.color,fontWeight:600,fontSize:u,opacity:.5},a.bottomLeft.label),g("text",{key:"lbr",x:n-8,y:i-8,fill:a.bottomRight.color,fontWeight:600,fontSize:u,opacity:.5,textAnchor:"end"},a.bottomRight.label)]:[];return g(Vt.Fragment,null,...b.map((e,t)=>e.w>0&&e.h>0?g("rect",{key:"qf-"+t,x:e.x,y:e.y,width:e.w,height:e.h,fill:e.c.color,opacity:e.c.opacity??.08}):null),g("line",{key:"vc",x1:f,y1:0,x2:f,y2:i,stroke:d,strokeWidth:h,strokeDasharray:p}),g("line",{key:"hc",x1:0,y1:y,x2:n,y2:y,stroke:d,strokeWidth:h,strokeDasharray:p}),...x)}]:void 0;return{chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,sizeRange:i.sizeRange||[3,15],colorScheme:o,pointStyle:n.pointStyle||i.pointStyle||Ho(e,t,o,n,i),...n,showLegend:n.showLegend??!!t,...m&&{svgPreRenderers:m}}}},on={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=function(e,t){if(!Array.isArray(e))return{data:e,orderMap:new WeakMap};const o=t.xAccessor||"x",n=t.yAccessor||"y",i=t.orderAccessor?[...e].sort((e,o)=>null==e||"object"!=typeof e?1:null==o||"object"!=typeof o?-1:Ut(qt(t.orderAccessor,"order",e))-Ut(qt(t.orderAccessor,"order",o))):e,r=new WeakMap;let s=0;for(const e of i){if(null==e||"object"!=typeof e)continue;const t=Ut(qt(o,"x",e)),i=Ut(qt(n,"y",e));Number.isFinite(t)&&Number.isFinite(i)&&s++}let a=0;for(const e of i){if(null==e||"object"!=typeof e)continue;const t=Ut(qt(o,"x",e)),i=Ut(qt(n,"y",e));Number.isFinite(t)&&Number.isFinite(i)&&r.set(e,{idx:a++,total:s})}return{data:i,orderMap:r}}(e,i),s=i.pointRadius??4,a=[e=>{const t=e.filter(e=>"point"===e.type&&"number"==typeof e.x&&"number"==typeof e.y);if(2>t.length)return null;const o=[];for(let e=0;t.length-1>e;e++){const n=t[e],i=t[e+1],r=Qt(e,t.length);100>t.length&&o.push(Vt.createElement("line",{key:"halo-"+e,x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:"white",strokeWidth:s+2,strokeLinecap:"round",opacity:.5})),o.push(Vt.createElement("line",{key:"segment-"+e,x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:r,strokeWidth:s,strokeLinecap:"round"}))}return Vt.createElement(Vt.Fragment,null,...o)}];return{chartType:"scatter",data:r.data,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,colorScheme:o,pointStyle:Xt(e=>{const t=r.orderMap.get(e),o=t?.idx??0,n=t?.total??1;return{fill:n>0?Qt(o,n):"#6366f1",stroke:"white",strokeWidth:1,r:s,fillOpacity:1}},Zt(i)),...n,svgPreRenderers:a}}},nn={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=Number.isFinite(i.cellBorderWidth)?Math.max(0,i.cellBorderWidth):1;return{chartType:"heatmap",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",valueAccessor:i.valueAccessor,colorScheme:o||i.colorScheme||"blues",showValues:i.showValues,heatmapValueFormat:i.valueFormat,areaStyle:()=>({stroke:i.cellBorderColor??"#fff",strokeWidth:r}),...n}}};function rn(e){return Math.max(0,Math.min(1,e))}function sn(e){const t=e.trim();if(t.startsWith("#")){let e=t.slice(1);if(3===e.length&&(e=e.split("").map(e=>e+e).join("")),6===e.length&&/^[0-9a-f]{6}$/i.test(e))return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}const o=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(o){const e=[Number(o[1]),Number(o[2]),Number(o[3])];if(e.every(Number.isFinite))return e}return null}function an(e,t,o){const n=e=>Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(o)}`}function ln(e,t,o){const n=e.filter(e=>Number.isFinite(e.offset)).map(e=>({offset:rn(e.offset),color:e.color??o,opacity:null==e.opacity?1:rn(e.opacity)})).sort((e,t)=>e.offset-t.offset);if(0===n.length)return"#999999";const i=e=>{if(1===e.opacity)return e.color;const t=sn(e.color);return t?`rgba(${t[0]},${t[1]},${t[2]},${e.opacity})`:e.color};if(1===n.length)return i(n[0]);const r=rn(t);if(n[0].offset>=r)return i(n[0]);if(r>=n[n.length-1].offset)return i(n[n.length-1]);for(let e=0;n.length-1>e;e++){const t=n[e],o=n[e+1];if(t.offset>r||r>o.offset)continue;const s=o.offset-t.offset,a=s>0?(r-t.offset)/s:0,l=sn(t.color),c=sn(o.color);if(!l||!c)return i(.5>a?t:o);const[u,d,h]=l,[p,g,m]=c,f=u+(p-u)*a,y=d+(g-d)*a,b=h+(m-h)*a,x=t.opacity+(o.opacity-t.opacity)*a;return 1===x?an(f,y,b):`rgba(${Math.round(f)},${Math.round(y)},${Math.round(b)},${x})`}return i(n[n.length-1])}function cn(e,t,o){return null==o?`${e}-${t}`:`${e}-${t}-${o}`}import{Fragment as un,jsx as dn,jsxs as hn}from"react/jsx-runtime";import{useMemo as pn,useCallback as gn,useRef as mn}from"react";var fn={RdBu:wt,PiYG:vt,PRGn:xt,BrBG:bt,RdYlBu:At,RdYlGn:St,Spectral:kt},yn="__likert_neutral_neg",bn="__likert_neutral_pos";function xn(e,t){if("function"==typeof e)return e;const o=e||t;return e=>e[o]}import*as vn from"react";function wn(e){return Se(e)}function An(e,t,o,n,i){const s=Kt(n.theme).colors.categorical,l=o??n.colorScheme,c=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],u="string"==typeof t?t:"__ssrColorBy",d="function"==typeof t?c.map(e=>({...e,__ssrColorBy:t(e)})):c,h=t?J(d,u,l??s):void 0,p=Ee("string"==typeof i.color?i.color:void 0,s,l,void 0,new Map),g=r(i.valueAccessor),m=i.styleRules,f=n.pieceStyle;return(e,o)=>{const n={fill:t&&h?le(e,t,h):p};return m?.length&&Object.assign(n,a(e,m,{value:g(e),category:o})),"function"==typeof f?Object.assign(n,f(e,o)||{}):f&&"object"==typeof f&&Object.assign(n,f),void 0!==i.stroke&&(n.stroke=i.stroke),void 0!==i.strokeWidth&&(n.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(n.opacity=i.opacity),n}}function Sn(e,t,o,n,i){const r=An(e,t,o,n,i);return(e,t)=>{const o=r(e,t);return void 0===o.fillOpacity&&(o.fillOpacity=.8),void 0===o.stroke&&(o.stroke=o.fill),o}}function kn(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s="string"==typeof t?t:"__ssrViolinColorBy",a="function"==typeof t?r.map(e=>({...e,__ssrViolinColorBy:t(e)})):r,l=Kt(n.theme).colors.categorical,c=o??n.colorScheme,u=t?J(a,s,c??l):void 0,d=Ee("string"==typeof i.color?i.color:void 0,l,c,void 0,new Map);return e=>{const o=t&&u?le(e,t,u):d;return{fill:o,fillOpacity:.6,stroke:i.stroke??o,...void 0!==i.strokeWidth&&{strokeWidth:i.strokeWidth},...void 0!==i.opacity&&{opacity:i.opacity}}}}function Mn(e,t,o,n,i){const r=An(e,t,o,n,i),s="number"==typeof i.dotRadius?i.dotRadius:5;return(e,t)=>({r:s,fillOpacity:.8,...r(e,t)})}function _n(e,t,o,n,i){const r=An(e,t,o,n,i),s=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],a=i.sizeBy,l=Array.isArray(i.sizeRange)?i.sizeRange:[3,8],c=a?s.map(e=>"function"==typeof a?a(e):Number(e[a])).filter(Number.isFinite):[],u=c.length?Ot(c):void 0,d="number"==typeof i.pointRadius?i.pointRadius:4,h="number"==typeof i.pointOpacity?i.pointOpacity:.7;return(e,t)=>({r:a?de(e,a,l,u):d,fillOpacity:h,...r(e,t)})}var Pn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"bar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"horizontal"===i.orientation?"horizontal":"vertical",oSort:i.sort??!1,colorAccessor:t,colorScheme:o,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,t,o,n,i)})},Tn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.stackBy;return{chartType:"bar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",stackBy:i.stackBy,colorAccessor:r,colorScheme:o,projection:"horizontal"===i.orientation?"horizontal":"vertical",normalize:i.normalize,oSort:i.sort??!1,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},Ln={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.groupBy;return{chartType:"clusterbar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",groupBy:i.groupBy,colorAccessor:r,colorScheme:o,projection:"horizontal"===i.orientation?"horizontal":"vertical",oSort:i.sort??!1,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},Rn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.categoryAccessor;return{chartType:"pie",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"radial",colorAccessor:r,colorScheme:o,...null!=i.cornerRadius&&{cornerRadius:i.cornerRadius},...null!=i.startAngle&&{startAngle:i.startAngle},...n,pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},In={frameType:"ordinal",layout:{primarySize:{width:400,height:400}},buildProps:(e,t,o,n,i)=>{const r=t||i.categoryAccessor;return{chartType:"donut",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"radial",margin:n.margin??{top:50,right:40,bottom:60,left:70},innerRadius:i.innerRadius??60,colorAccessor:r,colorScheme:o,...null!=i.cornerRadius&&{cornerRadius:i.cornerRadius},...null!=i.startAngle&&{startAngle:i.startAngle},...n,pieceStyle:An(e,r,o,n,i)}}},Cn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=i.valueAccessor||"value",a=r.map(e=>Number("function"==typeof s?s(e):e[s])).filter(Number.isFinite),l=a.length?[Math.min(...a),Math.max(...a)]:void 0;return{chartType:"histogram",data:e,oAccessor:i.categoryAccessor||(e=>null==e.category?"All":e.category+""),rAccessor:s,projection:"horizontal",bins:i.bins??25,normalize:i.relative??!1,colorAccessor:t,colorScheme:o,barPadding:i.categoryPadding??20,...i.valueExtent?{rExtent:i.valueExtent}:l?{rExtent:l}:{},...n,summaryStyle:Sn(e,t,o,n,i)}}},zn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"boxplot",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,...null!=i.showOutliers&&{showOutliers:i.showOutliers},...null!=i.outlierRadius&&{outlierRadius:i.outlierRadius},...n,summaryStyle:n.summaryStyle||Sn(e,t,o,n,i)})},Fn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"violin",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,projection:"horizontal"===i.orientation?"horizontal":"vertical",bins:i.bins??25,showIQR:i.showIQR??!0,barPadding:i.categoryPadding??20,colorScheme:o,...n,summaryStyle:n.summaryStyle||kn(e,t,o,n,i),showLegend:n.showLegend??!!t,...i.valueExtent&&{rExtent:i.valueExtent}})},On={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"swarm",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,...i.symbolBy&&{symbolAccessor:i.symbolBy},...i.symbolMap&&{symbolMap:i.symbolMap},colorScheme:o,...n,sizeRange:i.sizeRange||[3,8],pieceStyle:n.pieceStyle||_n(e,t,o,n,i),showLegend:n.showLegend??!!t})},Bn={frameType:"ordinal",layout:{modeDefaults:{showGrid:!0}},buildProps:(e,t,o,n,i)=>({chartType:"point",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",oSort:i.sort??"auto",barPadding:i.categoryPadding??10,...n,pieceStyle:Mn(e,t,o,n,i),showGrid:n.showGrid??!0,showLegend:n.showLegend??!!t})},Nn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.subcategoryAccessor;return{chartType:"swimlane",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",stackBy:i.subcategoryAccessor,colorAccessor:r,categoryAccessor:i.categoryAccessor,subcategoryAccessor:i.subcategoryAccessor,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",...null!=i.trackFill&&{trackFill:i.trackFill},...i.valueExtent&&{rExtent:i.valueExtent},...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:n.pieceStyle||An(e,r,o,n,i),showLegend:n.showLegend??!!r,barPadding:i.barPadding??40}}},En={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"ridgeline",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",bins:i.bins??20,amplitude:i.amplitude??1.5,barPadding:i.categoryPadding??5,oSort:i.oSort??!1,...n,summaryStyle:n.summaryStyle||((r,s)=>({fillOpacity:.5,...An(e,t,o,n,i)(r,s)})),showLegend:n.showLegend??!!t})},jn={frameType:"ordinal",layout:{margin:(e,t)=>({...t.marginDefaults,left:"vertical"===e.orientation?t.marginDefaults.left:Math.max(100,t.marginDefaults.left)})},buildProps:(e,t,o,n,i)=>{const r=Array.isArray(i.levels)&&i.levels.length>=2?i.levels:["Strongly disagree","Disagree","Neutral","Agree","Strongly agree"],s="vertical"!==i.orientation;let a=function(e,t,o,n,i,r){const s=new Map,a=new Set(t);for(const l of e){const e=o(l);s.has(e)||s.set(e,new Map);const c=s.get(e);if(n){const e=n(l);if(null==e||!Number.isFinite(e))continue;if(!Number.isInteger(e)){"production"!==process.env.NODE_ENV&&console.warn("[LikertChart] Ignoring non-integer Likert score:",e);continue}const o=e-1;if(0>o||o>=t.length)continue;const i=t[o];c.set(i,(c.get(i)||0)+1)}else if(i&&r){const e=i(l),t=r(l);if(!a.has(e))continue;c.set(e,(c.get(e)||0)+(Number.isFinite(t)?t:0))}}const l=[];for(const[e,o]of s){let n=0;for(const e of t)n+=o.get(e)||0;if(0!==n)for(let i=0;t.length>i;i++){const r=t[i],s=o.get(r)||0;l.push({__likertCategory:e,__likertLevel:r,__likertLevelLabel:r,__likertCount:s,__likertPct:s/n*100,__likertLevelIndex:i})}}return l}(Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],r,xn(i.categoryAccessor,"question"),i.levelAccessor?null:xn(i.valueAccessor,"score"),i.levelAccessor?xn(i.levelAccessor,"level"):null,i.levelAccessor?xn(i.countAccessor,"count"):null);s&&(a=function(e,t){const o=t.length,n=o%2!=0,i=Math.floor(o/2),r=new Map;for(const t of e){const e=r.get(t.__likertCategory)||[];e.push(t),r.set(t.__likertCategory,e)}const s=[];for(const[,e]of r){const t=new Map;let r,a;for(const o of e)o.__likertLevel===yn?r=o:o.__likertLevel===bn?a=o:t.set(o.__likertLevelIndex,o);n&&r&&s.push(r);for(let e=i-1;e>=0;e--){const o=t.get(e);o&&s.push(o)}n&&a&&s.push(a);for(let e=n?i+1:i;o>e;e++){const o=t.get(e);o&&s.push(o)}}return s}(function(e,t){const o=t.length,n=o%2!=0,i=Math.floor(o/2),r=[];for(const t of e){const e=t.__likertLevelIndex;if(n&&e===i){const e=t.__likertPct/2;r.push({...t,__likertLevel:yn,__likertPct:-e}),r.push({...t,__likertLevel:bn,__likertPct:e})}else r.push(i>e?{...t,__likertPct:-t.__likertPct}:t)}return r}(a,r),r));const l=Kt(n.theme).colors.diverging,c=Array.isArray(o)&&o.length>=r.length?o:function(e,t){if(0>=e)return[];if(t){const o=fn[t];if(o){if(1===e)return[o(.5)];const t=[];for(let n=0;e>n;n++)t.push(o(n/(e-1)));return t}}const o=["#da1e28","#ff8389","#ffb3b8"],n=["#a6c8ff","#4589ff","#0043ce"],i="#a8a8a8";if(1===e)return[i];const r=e%2!=0,s=Math.floor(e/2),a=[];for(let e=0;s>e;e++)a.push(o[Math.min(Math.floor(e*o.length/s),o.length-1)]);r&&a.push(i);for(let e=0;s>e;e++)a.push(n[Math.min(Math.floor(e*n.length/s),n.length-1)]);return a}(r.length,l),u=new Map(r.map((e,t)=>[e,c[t]||"#888"])),d=r.length%2&&u.get(r[Math.floor(r.length/2)])||"#888",h="function"==typeof i.valueFormat?i.valueFormat:e=>Math.abs(Number(e)).toFixed(0)+"%",p=!1===n.showLegend?void 0:{legendGroups:[{label:"",items:r.map(e=>({label:e})),styleFn:e=>({fill:u.get(e.label)||"#888"})}]},g=X(p,n.legend);return{chartType:"bar",data:a,oAccessor:"__likertCategory",rAccessor:"__likertPct",stackBy:"__likertLevel",normalize:!1,projection:s?"horizontal":"vertical",barPadding:i.barPadding,showGrid:n.showGrid,oLabel:i.categoryLabel,rLabel:i.valueLabel||(s?void 0:"Percentage"),rFormat:h,...i.categoryFormat&&{oFormat:i.categoryFormat},...i.valueExtent&&{rExtent:i.valueExtent},...n,pieceStyle:Xt(e=>{const t=e.__likertLevel||e.data?.__likertLevel;return{fill:t===yn||t===bn?d:u.get((e.__likertLevelLabel||e.data?.__likertLevelLabel||t)+"")||"#888"}},Zt(i)),showLegend:n.showLegend??!0,legendPosition:n.legendPosition||"right",...g&&{legend:g},__legendIncludesAutomatic:!0}}},$n={frameType:"ordinal",layout:{margin:(e,t)=>"vertical"===e.orientation?{top:t.title?60:40,right:20,bottom:60,left:60}:{top:t.title?40:10,right:10,bottom:10,left:10}},buildProps:(e,t,o,n,i)=>{const r="vertical"===i.orientation,s=t||i.categoryAccessor;return{chartType:r?"bar-funnel":"funnel",data:e,oAccessor:i.stepAccessor||"step",rAccessor:i.valueAccessor||"value",colorAccessor:s,categoryAccessor:i.categoryAccessor,projection:r?"vertical":"horizontal",connectorAccessor:i.connectorAccessor,connectorStyle:i.connectorStyle,...!r&&null!=i.connectorOpacity&&{connectorOpacity:i.connectorOpacity},barPadding:r?40:0,colorScheme:o,...n,showAxes:r,showGrid:r,pieceStyle:An(e,s,o,n,i),showLabels:i.showLabels??!0}}},Dn={frameType:"ordinal",layout:{primarySize:{width:300,height:250}},renderOverlay:function(e,{theme:t}){const o=e.__gauge;if(!o)return null;const n=(o.startAngleDeg+(o.gMax===o.gMin?0:(Math.max(o.gMin,Math.min(o.gMax,o.value??o.gMin))-o.gMin)/(o.gMax-o.gMin))*o.sweep-90)*Math.PI/180,i=o.needleColor||t.colors.text,r=o.showScaleLabels?(o.thresholds||[]).filter(e=>e.value>o.gMin&&o.gMax>e.value):[];return hn(un,{children:[o.showNeedle&&hn(un,{children:[dn("line",{x1:o.centerX,y1:o.centerY,x2:o.centerX+o.needleLength*Math.cos(n),y2:o.centerY+o.needleLength*Math.sin(n),stroke:i,strokeWidth:2.5,strokeLinecap:"round"}),dn("circle",{cx:o.centerX,cy:o.centerY,r:4,fill:i})]}),null!=o.contextValue&&dn("text",{x:o.centerX,y:o.contextValueY,textAnchor:"middle",dominantBaseline:"middle",fontSize:o.valueFontSize,fontWeight:700,fill:i,children:o.contextValue}),r.map((e,n)=>{const i=(o.startAngleDeg+(o.gMax===o.gMin?0:(e.value-o.gMin)/(o.gMax-o.gMin))*o.sweep-90)*Math.PI/180,r=o.innerRadius-1,s=o.radius+1,a=o.radius+10,l=((i+Math.PI/2)/(2*Math.PI)*12+12)%12,c=l>=11||1>l?"middle":5>l?"start":7>l?"middle":"end",u=l>=11||1>l?"auto":5>l?"middle":7>l?"hanging":"middle";return hn("g",{children:[dn("line",{x1:o.centerX+Math.cos(i)*r,y1:o.centerY+Math.sin(i)*r,x2:o.centerX+Math.cos(i)*s,y2:o.centerY+Math.sin(i)*s,stroke:t.colors.border,strokeWidth:2,strokeLinecap:"round"}),dn("text",{x:o.centerX+Math.cos(i)*a,y:o.centerY+Math.sin(i)*a,textAnchor:c,dominantBaseline:u,fill:t.colors.textSecondary,fontSize:10,children:e.label||e.value+""})]},"gauge-label-"+n)})]})},buildProps:(e,o,n,i,r)=>{const s=r.min??0,a=r.max??100,l=r.sweep??240,c=r.arcWidth??.3,d=!1!==r.showNeedle,h=!1!==r.fillZones,{startAngleDeg:p}=u(l),g=r.thresholds||[{value:a,color:r.color||"#4e79a7"}],m=Ae(i.gradientFill),f=function(e){const{min:t,max:o,value:n,thresholds:i,fillColor:r,backgroundColor:s,fillZones:a,showScaleLabels:l,gradientFill:c,gradientSteps:u=240}=e,d=o-t||1,h=(Math.max(t,Math.min(o,n))-t)/d;let p=i&&i.length>0?[...i].sort((e,t)=>e.value-t.value):[{value:o,color:r||"#007bff"}];p=p.map(e=>({...e,value:Math.max(t,Math.min(o,e.value))})),o>p[p.length-1].value&&p.push({value:o,color:p[p.length-1].color});const g=!!c&&c.stops.length>=2,m=[],f=new Map,y=[];if(g){const e=a?h:1,t=cn("bg",0);if(m.push({category:t,value:1,_zone:"Track",_isFill:!1,_pctStart:0,_pct:1,_roundedEnds:{start:!0,end:!0},_nonInteractive:!0}),f.set(t,{fill:s,opacity:.4}),e>0){const t=Math.max(1,Math.floor(u)),o=Math.max(1,Math.min(t,Math.round(e*t))),n=[];for(let t=0;o>t;t++)n.push(ln(c.stops,e*(t+.5)/o,r||p[0]?.color||"#007bff"));const i=cn("fill",0);m.push({category:i,value:e,_zone:"Gradient",_isFill:!0,_pctStart:0,_pct:e,_roundedEnds:{start:!0,end:!0},_nonInteractive:!0,_gradientBand:{colors:n}}),f.set(i,{fill:n[0]||s})}}else{let e=t;for(let o=0;p.length>o;o++){const n=p[o],i=(n.value-e)/d,r=(e-t)/d,l=(n.value-t)/d,c=Math.max(0,(a?Math.min(h,l):l)-r),u=a?Math.max(0,i-c):0;if(c>0){const e=cn("fill",o);m.push({category:e,value:c,_zone:n.label||"Zone "+(o+1),_isFill:!0}),f.set(e,{fill:n.color})}if(u>0){const e=cn("bg",o);m.push({category:e,value:u,_zone:n.label||"Zone "+(o+1),_isFill:!1}),f.set(e,{fill:s,opacity:.4})}e=n.value}}if(l&&i&&i.length>0)for(const e of i)e.value>t&&o>e.value&&y.push({type:"gauge-label",value:e.value,label:e.label||e.value+""});return{gaugeData:m,pieceStyle:(e,t)=>f.get(t||e.category)||{fill:s},gaugeAnnotations:y}}({min:s,max:a,value:r.value,thresholds:g,fillColor:r.color,backgroundColor:r.backgroundColor||"#e0e0e0",fillZones:h,showScaleLabels:!1!==r.showScaleLabels,gradientFill:m}),[y,b]=i.size||[300,250],x=t(l),v=Math.min(10,Math.max(1,Math.min(y,b)/12)),w=Math.max(4,Math.min((y-2*v)/x.width,(b-2*v)/x.height)-2),A=Math.max(0,Math.min(w-1.5,w*(1-c))),S=y/2-x.cx*w,k=b/2-x.cy*w,M=2*(w+4),_=Math.max(s,Math.min(a,r.value??s)),P="function"==typeof r.valueFormat?r.valueFormat(_):Math.round(_)+"",T=r.centerContent??i.centerContent,L=null!=T?"function"==typeof T?T(_,s,a):T:"sparkline"===r.mode||"context"===r.mode?void 0:vn.createElement("div",{style:{textAlign:"center",lineHeight:1.2}},vn.createElement("div",{style:{fontSize:Math.max(16,.3*w),fontWeight:700,color:"var(--semiotic-text, #333)"}},P),!1!==r.showScaleLabels&&vn.createElement("div",{style:{fontSize:11,color:"var(--semiotic-text-secondary, #666)"}},`${s} – ${a}`));return{chartType:"donut",data:f.gaugeData,oAccessor:"category",rAccessor:"value",projection:"radial",innerRadius:A,sweepAngle:l,startAngle:p,oSort:!1,pieceStyle:Xt(f.pieceStyle,Zt(r)),...null!=r.cornerRadius&&{cornerRadius:r.cornerRadius},...i,size:[y,b],margin:{top:k-M/2,bottom:b-k-M/2,left:S-M/2,right:y-S-M/2},...null!=L&&{centerContent:L},showAxes:!1,annotations:[...Array.isArray(i.annotations)?i.annotations:[],...f.gaugeAnnotations],__gauge:{gMin:s,gMax:a,sweep:l,arcWidth:c,value:_,startAngleDeg:p,thresholds:g,centerX:S,centerY:k,radius:w,innerRadius:A,showScaleLabels:!1!==r.showScaleLabels,needleLength:A>20?A-8:w-1,showNeedle:d,needleColor:r.needleColor,..."context"===r.mode&&null==T&&{contextValue:P,contextValueY:k-.2*A,valueFontSize:Math.max(12,Math.min(22,.28*w))}}}}};import{scaleTime as Wn}from"d3-scale";var Yn={static:{duplicateIds:"fatal",invalidSystemTime:"warn"},mcp:{duplicateIds:"fatal",invalidSystemTime:"warn"},push:{duplicateIds:"warn",invalidSystemTime:"strip"}};function Hn(e="static"){return Yn[e]??Yn.static}var Vn=new Set(["invalid-domain","missing-node","backward-edge","invalid-edge-time","invalid-value","invalid-node-time"]);function Gn(e){return"fatal"===e.severity||"warn"===e.severity?e.severity:Vn.has(e.kind)?"fatal":"warn"}function Xn(e){return"invalid-node-time"===e.kind?`node ${e.id} has an invalid xExtent (must be [start, end] with start <= end)`:"invalid-edge-time"===e.kind?`edge ${e.id} has an invalid startTime or endTime`:"invalid-domain"===e.kind?"time domain must be a 2-tuple of finite times [start, end] with start <= end":"invalid-value"===e.kind?`edge ${e.id} must have a positive finite value`:"missing-node"===e.kind?`edge ${e.id} references missing ${e.endpoint} node "${e.nodeId}"`:"backward-edge"===e.kind?`edge ${e.id} (${e.source}->${e.target}) ends before it starts`:"duplicate-node"===e.kind?`node id "${e.id}" is duplicated`:"duplicate-edge"===e.kind?`edge id "${e.id}" is duplicated`:"invalid-system-time"===e.kind?`edge ${e.id} has an invalid systemInTime or systemOutTime`:e.kind}function qn(e,t){return t>e?-1:e>t?1:0}function Un(e){return e.occupants.map(e=>e.id).sort(qn).join("\0")}function Qn(e,t,o=0){return e.slice(0,-1).map((n,i)=>null!=n.group&&n.group===e[i+1].group?o:t)}function Zn(e,t){return e.map(e=>{const o=new Map;for(const n of e.occupants){const e=t[n.id];if(e)for(const t of e.samples){const e=o.get(t.t)??{before:0,after:0},n=t.boundaryOffset??0;o.set(t.t,{before:Math.max(e.before,t.topMass-n),after:Math.max(e.after,t.botMass+n)})}}return[...o].sort((e,t)=>e[0]-t[0]).map(([e,t])=>({at:e,...t}))})}function Kn(e,t,o){if(0===e.length)return[];const{padding:n,plotH:i,valueScale:r}=o,s=o.stackValueScale??r,a=Qn(e,n,o.groupPadding??0),l=[n+e[0].peak.topPeak*s];for(let o=1;e.length>o;o++)l.push(l[o-1]+t[o-1]*s+a[o-1]);const c=l[l.length-1]+e[e.length-1].peak.botPeak*s+n;if(c>i&&c>0){const e=i/c;for(let t=0;l.length>t;t++)l[t]*=e}return l}function Jn(e,t){const o=(e.boundaryOffset??0)*t,n=e.value*t;if("out"===e.kind){const i=e.sideMassBefore*t;return o+("top"===e.side?n/2-i:i-n/2)}const i=e.sideMassAfter*t;return o+("top"===e.side?n/2-i:i-n/2)}function ei(e,t,o,n,i,r){const s=r.adjacentClearance?[...r.adjacentClearance]:A(Zn(n,o)).adjacentClearance,a=Kn(n,s,r);let l="hug"===r.lanePlacement?function(e,t,o,n,i,r,s){const a=e.length;if(0===a)return[];const{padding:l,plotH:c,valueScale:u}=s,d=Qn(e,l,s.groupPadding??0),h=i.map((e,t)=>e*u+d[t]),p=l+e[0].peak.topPeak*u,g=c-l-e[a-1].peak.botPeak*u;if(h.reduce((e,t)=>e+t,0)+1e-6>=g-p)return Kn(e,i,s);let m=1===a?[(p+g)/2]:[...r];for(let e=0;12>e;e++){const e=Array(a).fill(0),i=Array(a).fill(0);for(const r of o){const o=t[r.source],s=t[r.target];if(null==o||null==s||o===s)continue;const a=n[r.source]?.localAttachments.get(r.id),l=n[r.target]?.localAttachments.get(r.id);if(!a||!l)continue;const c=r.value>0&&Number.isFinite(r.value)?r.value:1,d=Jn(a,u),h=Jn(l,u);e[o]+=(m[s]+h-d)*c,i[o]+=c,e[s]+=(m[o]+d-h)*c,i[s]+=c}const r=m.map((t,o)=>0===i[o]?t:.45*t+e[o]/i[o]*.55),s=S({desired:r,minGaps:h,weights:i.map(e=>Math.max(1,e)),min:p,max:g});let l=0;for(let e=0;a>e;e++)l=Math.max(l,Math.abs(s[e]-m[e]));if(m=s,.01>l)break}return m}(n,i,t,o,s,a,r):[...a];if("hug"===r.lanePlacement){const o=t=>{const o={};for(const n of e)o[n.id]=t[i[n.id]];return o};ti(o(l),t)>ti(o(a),t)+1e-6&&(l=[...a])}const c={};for(const t of e)c[t.id]=l[i[t.id]];let u=1/0,d=-1/0;for(const t of e){const e=c[t.id],n=o[t.id];Number.isFinite(e)&&n&&(u=Math.min(u,e-n.topPeak*r.valueScale),d=Math.max(d,e+n.botPeak*r.valueScale))}return{adjacentClearance:s,centerlines:c,slotCenter:l,stackCenter:a,verticalUtilization:Number.isFinite(u)&&Number.isFinite(d)&&r.plotH>0?Math.max(0,Math.min(1,(d-u)/r.plotH)):0}}function ti(e,t){let o=0;for(const n of t){const t=e[n.source],i=e[n.target];Number.isFinite(t)&&Number.isFinite(i)&&(o+=Math.abs(t-i)*(n.value>0?n.value:1))}return o}function oi(e,t){const o=e?.samples;if(!o||0===o.length||o[0].t>t)return{top:0,bot:0};let n=0,i=o.length-1,r=0;for(;i>=n;){const e=n+i>>>1;o[e].t>t?i=e-1:(r=e,n=e+1)}const s=o[r].boundaryOffset??0;return{top:o[r].topMass-s,bot:o[r].botMass+s}}function ni(e,t,o,n,i){const r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*o+i*i*i*n}function ii(e,t){let o=0,n=1;for(let i=0;28>i;i++){const i=(o+n)/2;e>ni(0,t,t,1,i)?o=i:n=i}return(o+n)/2}function ri(e,t,o){const n=t+Jn(e,o),i=e.value*o/2;return[n-i,n+i]}function si(e,t,o,n){return Math.max(0,Math.min(t,n)-Math.max(e,o))/Math.max(1e-9,t-e)}function ai(e,t,o,n,i,r,s){const{valueScale:a,domain:l,mode:c="quality"}=s,u="source"===s.ribbonLane?.85:"target"===s.ribbonLane?.15:.5;let d=0;for(const s of e){const e=n[s.source],h=n[s.target];if(null==e||null==h||2>Math.abs(e-h))continue;const p=t[s.source]?.localAttachments.get(s.id),g=t[s.target]?.localAttachments.get(s.id);if(!p||!g)continue;const m=Math.max(s.startTime,l?.[0]??-1/0),f=Math.min(s.endTime,l?.[1]??1/0);if(m>=f)continue;const[y,b]=ri(p,i[s.source],a),[x,v]=ri(g,i[s.target],a),w=Math.min(e,h)+1,A=Math.max(e,h)-1;for(let e=w;A>=e;e++){const n=o[e];if(!n)continue;const l=[m,f];if("quality"===c)for(const e of n.occupants)for(const o of t[e.id]?.samples??[])o.t>m&&f>o.t&&l.push(o.t);const h=e=>{const o=ii((e-m)/(f-m),u),l=ni(y,y,x,x,o),c=ni(b,b,v,v,o);let d=0;for(const o of n.occupants){if(o.id===s.source||o.id===s.target)continue;const n=r[o.id];if(null!=n?.start&&n.start>e)continue;if(null!=n?.end&&e>n.end)continue;const u=oi(t[o.id],e),h=i[o.id];d=Math.max(d,si(l,c,h-u.top*a,h+u.bot*a))}return d},p=[...new Set(l)].sort((e,t)=>e-t);let g=0;for(let e=0;p.length-1>e;e++){const t=p[e],o=p[e+1]-t;g+=(h(t+.25*o)+h(t+.5*o)+h(t+.75*o))/3*o}d+=g/(f-m)*(s.value>0?s.value:1)}}return d}function li(e,t,o,n,i,r,s,a,l,c,u="both",d){return{crossings:e,weightedLength:t,pixelLength:ti(s,o),transitOcclusion:ai(o,n,i,r,s,a,{valueScale:l,ribbonLane:u,domain:d,mode:"quality"}),verticalUtilization:c}}function ci(e,t){return t?Math.max(t[0],Math.min(t[1],e)):e}function ui(e,t){return e.map(e=>({t:ci(e.t,t),topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}}))}function di(e,t,o){const n=t+(e.boundaryOffset??0)*o,i=e.value*o;if("out"===e.kind){const t=e.sideMassBefore*o;if("top"===e.side){const e=n-t;return[e,e+i]}const r=n+t;return[r-i,r]}const r=e.sideMassAfter*o;if("top"===e.side){const e=n-r;return[e,e+i]}const s=n+r;return[s-i,s]}function hi(e,t,o,n,i="temporal"){const r=t.incoming[e.id],s=t.outgoing[e.id],a=[];for(const e of r)a.push({time:e.endTime,delta:+e.value,edge:e,kind:"in",side:o.get(e.id).targetSide});for(const e of s)a.push({time:e.startTime,delta:-e.value,edge:e,kind:"out",side:o.get(e.id).sourceSide});const l={create:0,in:1,"transfer-out":2,"transfer-in":3,out:4},c=()=>{a.sort((e,t)=>e.time-t.time||(e.phase??0)-(t.phase??0)||(e.sequence??0)-(t.sequence??0)||(l[e.kind]??99)-(l[t.kind]??99)||((e,t)=>{if(!n||!e.edge||!t.edge||e.kind!==t.kind||e.side!==t.side)return 0;if("out"===e.kind){if(e.edge.target===t.edge.target&&e.edge.endTime===t.edge.endTime)return 0;const o=n.get(e.edge.id)?.target,i=n.get(t.edge.id)?.target;return"number"==typeof o&&Number.isFinite(o)&&"number"==typeof i&&Number.isFinite(i)&&o!==i?"top"===e.side?o-i:i-o:0}if("in"===e.kind){if(e.edge.source===t.edge.source&&e.edge.startTime===t.edge.startTime)return 0;const o=n.get(e.edge.id)?.source,i=n.get(t.edge.id)?.source;return"number"==typeof o&&Number.isFinite(o)&&"number"==typeof i&&Number.isFinite(i)&&o!==i?"top"===e.side?i-o:o-i:0}return 0})(e,t)||qn(e.edge?.id??"",t.edge?.id??"")||qn(e.side,t.side)||e.delta-t.delta)},u=a.length?Ft(a.map(e=>e.time)):null,d=Array.isArray(e.xExtent)&&Number.isFinite(e.xExtent[0])?e.xExtent[0]:null,h=null!=d?d-1:null!=u&&Number.isFinite(u)?u-1:null;c();let p=null,g=0;for(const e of a)e.time!==p&&(p=e.time,g=0),e.sequence=g++;const m=e=>({time:e.time,phase:0,sequence:e.sequence??0}),f=[];let y=0,b=0;for(const e of a)if("out"===e.kind){const t=Math.abs(e.delta);let o=t-("top"===e.side?y:b);if(o>0){const t="top"===e.side?"bot":"top",n=Math.min(o,"top"===t?y:b);if(n>0){const i=m(e);f.push({...i,delta:-n,kind:"transfer-out",side:t}),f.push({...i,delta:+n,kind:"transfer-in",side:e.side}),"top"===t?y-=n:b-=n,"top"===e.side?y+=n:b+=n,o-=n}o>0&&null!==h&&(f.push({time:h,delta:+o,kind:"create",side:e.side}),"top"===e.side?y+=o:b+=o)}"top"===e.side?y-=t:b-=t}else if("in"===e.kind){const t=Math.abs(e.delta);"top"===e.side?y+=t:b+=t}a.push(...f),c();let x=0,v=0,w=0,A=0,S=0,k=0;const M=[],_=new Map,P=e=>{M.push({t:e,topMass:x,botMass:v,...Math.abs(w)>1e-12&&{boundaryOffset:w}})},T=()=>{A=Math.max(A,x+v),S=Math.max(S,x-w),k=Math.max(k,v+w)};for(const e of a){if("transfer-out"!==e.kind&&"transfer-in"!==e.kind&&P(e.time),("in"===e.kind||"out"===e.kind)&&e.edge){const t="top"===e.side?x:v;_.set(e.edge.id,{side:e.side,time:e.time,sideMassBefore:t,sideMassAfter:t+e.delta,kind:e.kind,value:Math.abs(e.delta),...Math.abs(w)>1e-12&&{boundaryOffset:w}})}"top"===e.side?x+=e.delta:v+=e.delta,"transfer-in"===e.kind?(w+="top"===e.side?e.delta:-e.delta,T(),P(e.time)):"transfer-out"!==e.kind&&(T(),"out"!==e.kind||x+v>1e-12||(w=0),P(e.time))}const L=[];let R=0;for(;M.length>R;){let e=R;for(;M.length>e+1&&M[e+1].t===M[R].t;)e++;L.push(M[R]);for(let t=R+1;e>=t;t++){const e=L[L.length-1];M[t].topMass===e.topMass&&M[t].botMass===e.botMass&&(M[t].boundaryOffset??0)===(e.boundaryOffset??0)||L.push(M[t])}R=e+1}const I=Array.isArray(e.xExtent)&&Number.isFinite(e.xExtent[1])?e.xExtent[1]:null;let C=null;for(const e of s)null!=e.systemInTime&&Number.isFinite(e.systemInTime)&&e.startTime>e.systemInTime&&(null===C||C>e.systemInTime)&&(C=e.systemInTime);let z=null;for(const e of r)null!=e.systemOutTime&&Number.isFinite(e.systemOutTime)&&e.systemOutTime>e.endTime&&(null===z||e.systemOutTime>z)&&(z=e.systemOutTime);if(L.length>0){const e=L[L.length-1],t=Math.max(null!=I?I:-1/0,null!=z?z:-1/0);Number.isFinite(t)&&t>e.t&&e.topMass+e.botMass>0&&L.push({t:t,topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}});const o=L[0],n=L.find(e=>e.topMass+e.botMass>0);let i,r=1/0;null!=d&&Number.isFinite(d)&&o.t>d&&o.topMass+o.botMass>0&&(r=d,i=o),n&&null!=C&&Number.isFinite(C)&&n.t>C&&r>C&&(r=C,i=n),i&&Number.isFinite(r)&&L.unshift({t:r,topMass:i.topMass,botMass:i.botMass,...null!=i.boundaryOffset&&{boundaryOffset:i.boundaryOffset}})}let F=L;if("max"===i&&null!=d&&null!=I&&I>d){let e,t=0;for(const o of L){const n=o.topMass+o.botMass;n>t&&(t=n,e=o)}if(e){const t={topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}};F=[...L.filter(e=>d>e.t),{t:d,...t},{t:I,...t},...L.filter(e=>e.t>I)]}}return{samples:F,peak:A,topPeak:S,botPeak:k,localAttachments:_}}function pi(e){const t={};return e.forEach((e,o)=>{for(const n of e.occupants)t[n.id]=o}),t}function gi(e,t,o){e.splice(0,e.length,...o);const n=pi(o);for(const e of Object.keys(t))delete t[e];Object.assign(t,n)}function mi(e){const t=new Map,o=[];e.forEach((e,n)=>{if(!e.group)return void o.push({anchor:n,stableId:Un(e),slots:[e]});const i=t.get(e.group)??{indexes:[],slots:[]};i.indexes.push(n),i.slots.push(e),t.set(e.group,i)});for(const[e,n]of t)o.push({anchor:n.indexes.reduce((e,t)=>e+t,0)/n.indexes.length,stableId:`${e}\0${n.slots.map(Un).join("\0")}`,slots:n.slots});return o.sort((e,t)=>e.anchor-t.anchor||qn(e.stableId,t.stableId))}function fi(e){return e.some(e=>e.group)?mi(e).flatMap(e=>e.slots):[...e]}function yi(e){return e.flatMap(e=>e.slots)}function bi(e,t,o){const n=new Map;return e.forEach((e,t)=>{for(const o of e.slots)n.set(o,t)}),e.map((e,i)=>{if(1>=e.slots.length)return e;const r=new Map;for(const t of e.slots)r.set(t,0);for(const e of t){const t=n.get(e.source),o=n.get(e.target);if(null==t||null==o)continue;const s=Number.isFinite(e.weight)&&e.weight>0?e.weight:1;if(t===i&&o!==i){const t=o>i?1:-1;r.set(e.source,(r.get(e.source)??0)+s*t)}else if(o===i&&t!==i){const o=t>i?1:-1;r.set(e.target,(r.get(e.target)??0)+s*o)}}const s=[...e.slots].sort((e,t)=>(r.get(e)??0)-(r.get(t)??0)||o(e,t));return{...e,slots:s}})}function xi(e,t){e.some(e=>e.group)&&gi(e,t,fi(e))}function vi(e,t){return e.source!==t.source&&e.target!==t.target&&e.source!==t.target&&e.target!==t.source&&Math.min(e.endTime,t.endTime)>Math.max(e.startTime,t.startTime)}function wi(e,t){return y(t,t=>[e[t.source],e[t.target]],vi)}function Ai(e,t){let o=0;for(const n of t){const t=e[n.source],i=e[n.target];null!=t&&null!=i&&(o+=Math.abs(t-i)*(n.value>0?n.value:1))}return o}function Si(e,t,o){const[n,i]=o.get(e.first),[r,s]=o.get(e.second);return 0>(t.get(n)-t.get(r))*(t.get(i)-t.get(s))?1:0}var ki=e=>{let t=1;for(let o=2;e>=o;o++)t*=o;return t},Mi=828*ki(8),_i=3e3;function Pi(e,t,o,n,i,r,s){const a=[...i],l=new Map(i.map(e=>[e,Un(e)])),c=new Map;for(const e of i)for(const t of e.occupants)c.set(t.id,e);const u=new Map,d=[];for(const e of t){const t=c.get(e.source),o=c.get(e.target);t&&o&&(u.set(e,[t,o]),t!==o&&d.push({source:t,target:o,weight:e.value}))}const h=[];for(let e=0;t.length>e;e++)if(u.has(t[e]))for(let o=e+1;t.length>o;o++){if(!u.has(t[o])||!vi(t[e],t[o]))continue;const n=new Set([...u.get(t[e]),...u.get(t[o])]);h.push({index:h.length,first:t[e],second:t[o],involvedSlots:n})}const p=new Map;for(const e of i)p.set(e,[]);for(const e of h)for(const t of e.involvedSlots)p.get(t)?.push(e);const g=new Uint32Array(h.length);let m=0;const f=t.reduce((e,t)=>e+(t.value>0?t.value:1),0),y=s.plotH/Math.max(1,i.length),b=i.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),x=Math.max(1,f)*(Math.max(1,s.plotH)+y*Math.max(b,i.length)+1e-6*Math.max(1,i.length-1))+1,S=4*y,k={fullCrossing:0,localCrossing:0},M=new Map,_=(e,t)=>{let n=M.get(e);n||(n=new Map,M.set(e,n));const i=n.get(t);if(null!=i)return i;const r=function(e,t,o){return A(Zn([e,t],o)).adjacentClearance[0]??0}(e,t,o);return n.set(t,r),r},T=new Map(i.map((e,t)=>[e,t])),L=t.flatMap(e=>{const t=u.get(e);return t?[{source:T.get(t[0]),target:T.get(t[1]),weight:e.value>0?e.value:1}]:[]}),R=new Map;for(const e of t){const t=u.get(e);t&&R.set(e,{source:T.get(t[0]),target:T.get(t[1])})}const I=new Map,C=new Map;for(const e of t)I.has(e.source)||I.set(e.source,new Set),C.has(e.target)||C.set(e.target,new Set),I.get(e.source).add(e.target),C.get(e.target).add(e.source);const z=t.flatMap(e=>{if(!(e=>{const t=new Set([...I.get(e.source)??[],...C.get(e.source)??[]]),o=new Set([...I.get(e.target)??[],...C.get(e.target)??[]]);return 1===I.get(e.source)?.size&&I.get(e.source).has(e.target)||1===t.size&&t.has(e.target)||1===o.size&&o.has(e.source)})(e))return[];const t=R.get(e);return t&&t.source!==t.target?[{source:t.source,target:t.target,weight:e.value>0?e.value:1}]:[]}),F=e=>{let t=0;for(const o of z)t+=Math.max(0,Math.abs(e[o.source]-e[o.target])-1)*o.weight;return t*S},O=e=>{const t=new Int16Array(i.length);for(let o=0;e.length>o;o++)t[T.get(e[o])]=o;return F(t)},B=h.map(e=>{const t=R.get(e.first),o=R.get(e.second);return[t.source,t.target,o.source,o.target]}),N=new Int16Array(i.length),E=new Float64Array(i.length),j=new Float64Array(i.length+1),$=e=>{for(let t=0;e.length>t;t++)N[T.get(e[t])]=t;let t=0;for(const[e,o,n,i]of B)0>(N[e]-N[n])*(N[o]-N[i])&&t++;if(e.length>0){const t=T.get(e[0]);E[t]=s.padding+e[0].peak.topPeak*s.valueScale;for(let t=1;e.length>t;t++){const o=T.get(e[t-1]),n=T.get(e[t]);E[n]=E[o]+_(e[t-1],e[t])*s.valueScale+s.padding}const o=T.get(e[e.length-1]),n=E[o]+e[e.length-1].peak.botPeak*s.valueScale+s.padding;if(n>s.plotH&&n>0){const e=s.plotH/n;for(let t=0;E.length>t;t++)E[t]*=e}}j[0]=0;for(let t=0;e.length>t;t++)j[t+1]=j[t]+e[t].peak.topPeak+e[t].peak.botPeak;let o=0,n=0,i=0;for(const e of L){const t=N[e.source],r=N[e.target];if(o+=Math.abs(t-r)*e.weight,n+=Math.abs(E[e.source]-E[e.target])*e.weight,Math.abs(t-r)>=2){const o=Math.min(t,r)+1;i+=(j[Math.max(t,r)]-j[o])*e.weight}}return t*x+n+i*y+F(N)+1e-6*o},D=(e,o)=>{const n=Array(e.length+1).fill(0);for(let t=0;e.length>t;t++)n[t+1]=n[t]+e[t].peak.topPeak+e[t].peak.botPeak;let i=0;for(const e of t){const t=o[e.source],r=o[e.target];if(null==t||null==r||2>Math.abs(t-r))continue;const s=Math.min(t,r)+1;i+=(n[Math.max(t,r)]-n[s])*(e.value>0?e.value:1)}return i},W=n=>{const i=pi(n),r=n.slice(0,-1).map((e,t)=>_(e,n[t+1])),a=ei(e,t,o,n,i,{plotH:s.plotH,padding:s.padding,valueScale:s.valueScale,lanePlacement:s.lanePlacement??"stack",groupPadding:s.groupPadding,adjacentClearance:r});return{map:i,geometry:a,weightedLength:Ai(i,t),pixelLength:ti(a.centerlines,t),transitOcclusion:D(n,i)}},Y=(e,t,o)=>({crossings:e,weightedLength:t.weightedLength,pixelLength:t.pixelLength,transitOcclusion:t.transitOcclusion,cost:e*x+t.pixelLength+t.transitOcclusion*y+O(o)+1e-6*t.weightedLength}),H=(e,t)=>{let o=t;if(null==o){const t=new Map(e.map((e,t)=>[e,t]));o=h.reduce((e,o)=>e+Si(o,t,u),0),k.fullCrossing++}return Y(o,W(e),e)},V=(e,i,r="quality")=>{let a=i;if(null==a){const t=new Map(e.map((e,t)=>[e,t]));a=h.reduce((e,o)=>e+Si(o,t,u),0),k.fullCrossing++}const l=W(e);return Y(a,{...l,transitOcclusion:ai(t,o,e,l.map,l.geometry.centerlines,n,{valueScale:s.valueScale,ribbonLane:s.ribbonLane,domain:s.domain,mode:r})},e)};let G=[...a];const X=(e,t)=>qn(l.get(e),l.get(t)),q=function(e){const t=new Set;for(const o of e)if(o.group){if(t.has(o.group))return!0;t.add(o.group)}return!1}(G),U=e=>{const t=(e=>{const t=v(e,d,e=>H(e).cost,{passes:6,compare:X,maxEvaluations:_i});let o=H(t),n=_i;for(let e=0;6>e&&n>0;e++){let i=!1;const r=Array.from({length:t.length-1},(e,t)=>t);e%2==1&&r.reverse();for(const e of r){if(0>=n--)break;const r=t[e],s=t[e+1],a=new Map(t.map((e,t)=>[e,t]));let l=0;const c=[];m++;for(const e of[...p.get(r)??[],...p.get(s)??[]])g[e.index]!==m&&(g[e.index]=m,c.push(e),l+=Si(e,a,u));[t[e],t[e+1]]=[s,r];const d=new Map(a);d.set(r,e+1),d.set(s,e);let h=0;for(const e of c)h+=Si(e,d,u);k.localCrossing+=c.length;const f=H(t,o.crossings-l+h);o.cost>f.cost?(o=f,i=!0):[t[e],t[e+1]]=[r,s]}if(!i)break}return t})(e);if((e.length>8?1/0:ki(e.length)*(e.length+L.length+B.length))>Mi)return t;const o=w(e,$,{maxItems:8,maxEvaluations:5e4}),n=V(o),i=V(t);return n.crossings!==i.crossings&&i.crossings>n.crossings?o:t},Q="geometry-refine"===s.mode;if(Q||"crossing-min"!==s.laneOrder&&"crossing-min+inside-out"!==s.laneOrder){if(!Q&&"inside-out"===s.laneOrder)if(q){const e=mi(G),t=e=>e.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),o=[...e].sort((e,o)=>t(o)-t(e)||qn(e.stableId,o.stableId)),n=Array(o.length);let i=Math.floor((o.length-1)/2)-1,r=Math.floor((o.length-1)/2)+1;o.length>0&&(n[Math.floor((o.length-1)/2)]=o[0]);for(let e=1;o.length>e;e++)e%2==1&&o.length>r||0>i?n[r++]=o[e]:n[i--]=o[e];G=yi(n)}else{const e=[...G].sort((e,t)=>t.peak.topPeak+t.peak.botPeak-(e.peak.topPeak+e.peak.botPeak)||X(e,t)),t=Array(e.length);let o=Math.floor((e.length-1)/2)-1,n=Math.floor((e.length-1)/2)+1;e.length>0&&(t[Math.floor((e.length-1)/2)]=e[0]);for(let i=1;e.length>i;i++)i%2==1&&e.length>n||0>o?t[n++]=e[i]:t[o--]=e[i];G=t}}else G=q?(e=>{let t=mi(e);if(1>=t.length)return yi(t);const o=e=>H(yi(e)).cost;t=mi(U(e)),t=bi(t,d,X);const n=function(e,t){const o=new Map;for(const t of e)for(const e of t.slots)o.set(e,t);const n=new Map;for(const e of t){const t=o.get(e.source),i=o.get(e.target);if(!t||!i||t===i)continue;const r=Number.isFinite(e.weight)&&e.weight>0?e.weight:1,s=i.stableId>t.stableId?`${t.stableId}\0${i.stableId}`:`${i.stableId}\0${t.stableId}`,a=n.get(s);a?a.weight=(a.weight??0)+r:n.set(s,{source:t,target:i,weight:r})}return[...n.values()]}(t,d);t=v(t,n,o,{passes:6,compare:(e,t)=>qn(e.stableId,t.stableId),maxEvaluations:_i}),t=P(t,o,{passes:8,maxEvaluations:_i});const i=t.length>8?1/0:ki(t.length)*(t.length+L.length+B.length);if(Mi>=i){const e=w(t,e=>$(yi(e)),{maxItems:8,maxEvaluations:5e4}),o=yi(e),n=yi(t),i=V(o),r=V(n);i.crossings!==r.crossings?t=r.crossings>i.crossings?e:t:r.cost>i.cost&&(t=e)}return t=bi(t,d,X),yi(t)})(G):U(G);if(!Q&&"crossing-min+inside-out"===s.laneOrder&&G.length>1)if(q){const e=mi(G);let t=H(yi(e)),o=yi(e),n=t;const i=Math.floor((e.length-1)/2),r=e=>e.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),s=[...e].sort((e,t)=>r(t)-r(e)||qn(e.stableId,t.stableId));for(const r of s){const s=e.indexOf(r);if(s===i)continue;e.splice(s,1),e.splice(i,0,r);const a=yi(e),l=H(a);l.cost>t.cost?(e.splice(i,1),e.splice(s,0,r)):(t=l,n.cost>l.cost&&(o=a,n=l))}G=o}else{let e=H(G),t=[...G],o=e;const n=Math.floor((G.length-1)/2),i=[...G].sort((e,t)=>t.peak.topPeak+t.peak.botPeak-(e.peak.topPeak+e.peak.botPeak)||X(e,t));for(const r of i){const i=G.indexOf(r);if(i===n)continue;G.splice(i,1),G.splice(n,0,r);const s=H(G);s.cost>e.cost?(G.splice(n,1),G.splice(i,0,r)):(e=s,o.cost>s.cost&&(t=[...G],o=s))}G=t}if((Q||"crossing-min"===s.laneOrder||"crossing-min+inside-out"===s.laneOrder)&&G.length>1)if(q){let e=mi(G),t=V(yi(e),void 0,"score");for(let o=0;6>o&&e.length>1;o++){let o=!1;for(let n=0;e.length-1>n;n++){[e[n],e[n+1]]=[e[n+1],e[n]];const i=yi(e),r=V(i,void 0,"score");t.cost>r.cost?(G=i,t=r,o=!0):[e[n],e[n+1]]=[e[n+1],e[n]]}if(!o)break}e=bi(mi(G),d,X),G=yi(e)}else{let e=V(G,void 0,"score");for(let t=0;G.length-1>t;t++){const o=G[t],n=G[t+1],i=new Map(G.map((e,t)=>[e,t]));let r=0;const s=[];m++;for(const e of[...p.get(o)??[],...p.get(n)??[]])g[e.index]!==m&&(g[e.index]=m,s.push(e),r+=Si(e,i,u));[G[t],G[t+1]]=[n,o];const a=new Map(i);a.set(o,t+1),a.set(n,t);let l=0;for(const e of s)l+=Si(e,a,u);k.localCrossing+=s.length;const c=V(G,e.crossings-r+l,"score");e.cost>c.cost?e=c:[G[t],G[t+1]]=[o,n]}}const Z=fi(a);G=fi(G);let K=V(G);const J=V(Z);if(Q){const e=O(Z),t=O(G);(K.crossings>J.crossings||K.crossings===J.crossings&&t>e+1e-9||K.cost>J.cost)&&(G=Z,K=J)}else K.cost>J.cost&&(G=Z,K=J);return gi(i,r,G),{before:J,after:K,initialOrder:a.map(e=>l.get(e)),evaluations:k}}function Ti(e,t,o){const n=e.map(e=>{const n=e.occupants.map(e=>({id:e.id,end:o[e.id]?.end??e.end}));let i=0,r=0;for(const e of n){const o=t[e.id];i=Math.max(i,o?.topPeak||0),r=Math.max(r,o?.botPeak||0)}return{occupants:n,peak:{topPeak:i,botPeak:r},...null!=e.group?{group:e.group}:{}}}),i={};return n.forEach((e,t)=>{for(const o of e.occupants)i[o.id]=t}),{slots:n,slotByNode:i}}var Li=new Map,Ri=1e-9,Ii=1e5;function Ci(e,t){let o=1/0,n=-1/0;for(const t of e?.samples??[])t.topMass+t.botMass>Ri&&(o=Math.min(o,t.t),n=Math.max(n,t.t));return Number.isFinite(o)&&Number.isFinite(n)?(null!=t.start&&(o=Math.max(o,t.start)),null!=t.end&&(n=Math.min(n,t.end)),o>n?{start:null,end:null}:{start:o,end:n}):{start:null,end:null}}function zi(e,t){return null!=e.start&&null!=e.end&&null!=t.start&&null!=t.end&&!(t.start>=e.end||e.start>=t.end)}function Fi(e,t){return qn(e,t)>0?`${t}\0${e}`:`${e}\0${t}`}function Oi(e){const t=new Map,o=new Map;for(const n of e)o.has(n.source)||o.set(n.source,new Set),t.has(n.target)||t.set(n.target,new Set),o.get(n.source).add(n.target),t.get(n.target).add(n.source);return{incoming:new Map([...t].map(([e,t])=>[e,t.size])),outgoing:new Map([...o].map(([e,t])=>[e,t.size]))}}function Bi(e){const t=new Map,o=new Map,n=(e,t,o,n)=>{let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(o,(i.get(o)??0)+n)};for(const i of e){const e=i.value>0&&Number.isFinite(i.value)?i.value:1;n(t,i.source,i.target,e),n(o,i.target,i.source,e)}const i=new Map,r=e=>{if(i.has(e))return;const n=t.get(e),r=o.get(e);if(n&&1===n.size&&(!r||0===r.size)){const[t,o]=[...n][0];return void i.set(e,{partner:t,weight:o})}const s=new Map;for(const[e,t]of n??[])s.set(e,(s.get(e)??0)+t);for(const[e,t]of r??[])s.set(e,(s.get(e)??0)+t);if(1===s.size){const[t,o]=[...s][0];i.set(e,{partner:t,weight:o})}};for(const t of e)r(t.source),r(t.target);return i}function Ni(e,t,o){const n=o.get(e),i=o.get(t);return!n||!i||n.partner===i.partner||n.partner===t||i.partner===e}function Ei(e,t,o){return!!o.has(e)&&t.some(t=>!Ni(e,t,o))}function ji(e,t){return(e.value>0&&Number.isFinite(e.value)?e.value:1)*(1+(1===t.outgoing.get(e.source)?1:0)+(1===t.incoming.get(e.target)?1:0))}function $i(e,t,o,n){if(12>=e.length||1>=n.slotCount)return n.assignment;const i=new Map(e.map((e,t)=>[e,t])),r=Array.from({length:e.length},()=>new Map),s=Oi(o);for(const e of o){const t=i.get(e.source),o=i.get(e.target);if(null==t||null==o||t===o)continue;const n=ji(e,s);r[t].set(o,(r[t].get(o)??0)+n),r[o].set(t,(r[o].get(t)??0)+n)}const a=Bi(o),l=e.map(e=>a.get(e)?.weight??0),c=Array.from({length:e.length},()=>new Map);let u=0;for(let o=0;e.length-1>o&&5e4>u;o++)if(a.has(e[o]))for(let n=o+1;e.length>n;n++){if(!a.has(e[n]))continue;if(t.conflicts(e[o],e[n]))continue;u++;const i=Math.min(l[o],l[n])||Math.max(l[o],l[n]),r=Ni(e[o],e[n],a)?i:-i;if(Math.abs(r)>Ri&&(c[o].set(n,r),c[n].set(o,r),u>=5e4))break}const d=[...n.assignment],h=Array.from({length:n.slotCount},()=>[]);d.forEach((e,t)=>h[e].push(t));const p=(e,t,o)=>{const n=d[t],i=d[o];let r=0;const s=new Set;for(const a of[t,o])for(const[l,c]of e[a]){const e=l>a?`${a}:${l}`:`${l}:${a}`;if(s.has(e))continue;s.add(e);const u=(a===t?i:n)===(l===t?i:l===o?n:d[l]);d[a]===d[l]!==u&&(r+=u?c:-c)}return r},g=(e,t,o)=>{let n=0;for(const[i,r]of e[t]){const e=o===d[i];d[t]===d[i]!==e&&(n+=e?r:-r)}return n},m=(e,t)=>e>Ri||Ri>=Math.abs(e)&&t>Ri,f=(e,t,o,n)=>e>o+Ri||Ri>=Math.abs(e-o)&&t>n+Ri;let y=0;for(let o=0;32>o&&Ii>y;o++){let o=null,n=-1,i=-1,s=-1,a=-1/0,l=-1/0;for(let u=0;e.length>u;u++){for(let p=0;h.length>p&&y++<Ii;p++){if(p===d[u])continue;if(!h[p].every(o=>!t.conflicts(e[u],e[o])))continue;const y=g(r,u,p),b=g(c,u,p);m(y,b)&&f(y,b,a,l)&&(o="move",n=u,i=-1,s=p,a=y,l=b)}if(y>=Ii)break}for(let u=0;e.length-1>u;u++){for(let g=u+1;e.length>g&&y++<Ii;g++){const y=d[u],b=d[g];if(y===b)continue;if(!h[b].every(o=>o===g||!t.conflicts(e[u],e[o])))continue;if(!h[y].every(o=>o===u||!t.conflicts(e[g],e[o])))continue;const x=p(r,u,g),v=p(c,u,g);m(x,v)&&f(x,v,a,l)&&(o="swap",n=u,i=g,s=-1,a=x,l=v)}if(y>=Ii)break}if(null==o||-1===n)break;if("move"===o){const e=d[n];h[e].splice(h[e].indexOf(n),1),h[s].push(n),d[n]=s;continue}const u=d[n],b=d[i];h[u].splice(h[u].indexOf(n),1,i),h[b].splice(h[b].indexOf(i),1,n),d[n]=b,d[i]=u}return d}function Di(e,t,o,n){const i=function(e,t,o,n){return`${e.map(e=>{const t=o[e.id],i=n[e.id];return[e.id,e.group??"",e.xExtent?.[0]??"",e.xExtent?.[1]??"",t?.topPeak??0,t?.botPeak??0,i?.start??"",i?.end??""].join(":")}).join("|")}#${t.map(e=>[e.id,e.source,e.target,e.value,e.startTime,e.endTime].join(":")).join("|")}`}(e,t,o,n),r=Li.get(i);if(r)return Ti(r.slots,o,n);const s={};for(const t of e)s[t.id]=Ci(o[t.id],n[t.id]);const a=function(e,t){return e.filter(e=>null!=t[e.id].start).sort((e,o)=>t[e.id].start-t[o.id].start||t[e.id].end-t[o.id].end||qn(e.id,o.id)).map(e=>e.id)}(e,s),l=new Map(e.map(e=>[e.id,e])),c=new Map(e.map(e=>[e.id,e.group||void 0])),u=function(e,t,o,n,i){const r=new Set,s=new Map(e.map(e=>[e,new Set])),a=new Map(e.map(e=>[e,new Set]));for(const e of n)r.add(Fi(e.source,e.target)),s.get(e.target)?.add(e.source),a.get(e.source)?.add(e.target);const l=new Map,c=new Set,u=(e,t)=>{for(let o=0;e.length>o;o++)for(let n=o+1;e.length>n;n++){const i=Fi(e[o],e[n]);t instanceof Map?t.set(i,[e[o],e[n]]):t.add(i)}};for(const e of a.values())u([...e],l);for(const e of s.values())u([...e],c);const d=new Set;for(const[e,[n,i]]of l)c.has(e)&&(zi(t[n],t[i])||zi(o[n],o[i])&&(d.add(n),d.add(i)));return{conflicts:(e,o)=>{const n=i.get(e),s=i.get(o);return null!=n&&null!=s&&n!==s||null!=n!=(null!=s)&&!r.has(Fi(e,o))||!!zi(t[e],t[o])||!(!d.has(e)&&!d.has(o))&&!r.has(Fi(e,o))}}}(a,s,n,t,c),d=function(e,t,o=new Map){const n=[],i=[];for(const r of e){let e=n.findIndex(e=>e.every(e=>!t.conflicts(r,e))&&!Ei(r,e,o));-1!==e||o.has(r)||(e=n.findIndex(e=>e.every(e=>!t.conflicts(r,e)))),-1===e&&(e=n.length,n.push([])),n[e].push(r),i.push(e)}return{assignment:i,slotCount:n.length}}(a,u,Bi(t)),h=function(e,t,o,n){if(0===e.length||e.length>12||1>=n.slotCount)return n.assignment;const i=new Map(e.map((e,t)=>[e,t])),r=Array.from({length:e.length},()=>new Float64Array(e.length)),s=Array.from({length:e.length},()=>new Map),a=Array.from({length:e.length},()=>new Map),l=Oi(o);for(const e of o){const t=i.get(e.source),o=i.get(e.target);if(null==t||null==o||t===o)continue;const n=ji(e,l);r[t][o]+=n,r[o][t]+=n,a[t].set(o,(a[t].get(o)??0)+n),s[o].set(t,(s[o].get(t)??0)+n)}const c=Bi(o),u=e.map(e=>c.get(e)?.weight??0),d=Array.from({length:e.length},()=>new Float64Array(e.length));for(let t=0;e.length>t;t++)for(let o=t+1;e.length>o;o++){for(const[e,n]of s[t])d[t][o]+=Math.min(n,s[o].get(e)??0);for(const[e,n]of a[t])d[t][o]+=Math.min(n,a[o].get(e)??0);if(c.has(e[t])&&c.has(e[o])){const n=Math.min(u[t],u[o])||Math.max(u[t],u[o]);d[t][o]+=Ni(e[t],e[o],c)?n:-n}d[o][t]=d[t][o]}let h=[...n.assignment],p=(t=>{let o=0,n=0;for(let i=0;e.length>i;i++)for(let s=i+1;e.length>s;s++)t[i]===t[s]&&(o+=r[i][s],n+=d[i][s]);return{flow:o,affinity:n}})(h),g=0;const m=Array(e.length).fill(-1),f=Array.from({length:n.slotCount},()=>[]),y=(o,i,s,a)=>{if(g>=75e3)return;if(o===e.length)return g++,void((s>p.flow||s===p.flow&&a>p.affinity||s===p.flow&&a===p.affinity&&function(e,t){for(let o=0;Math.min(e.length,t.length)>o;o++)if(e[o]!==t[o])return t[o]>e[o];return t.length>e.length}(m,h))&&(h=[...m],p={flow:s,affinity:a}));const l=Math.min(i+1,n.slotCount-1);for(let n=0;l>=n;n++){if(f[n].some(n=>t.conflicts(e[o],e[n])))continue;let l=0,c=0;for(const e of f[n])l+=r[o][e],c+=d[o][e];if(m[o]=n,f[n].push(o),y(o+1,Math.max(i,n),s+l,a+c),f[n].pop(),m[o]=-1,g>=75e3)return}};return m[0]=0,f[0].push(0),y(1,0,0,0),h}(a,u,t,{...d,assignment:$i(a,u,t,d)}),p=new Map,g=h.map(e=>(p.has(e)||p.set(e,p.size),p.get(e))),m=Array.from({length:p.size||(e.length>0?1:0)},()=>({occupants:[],peak:{topPeak:0,botPeak:0}})),f={};a.forEach((e,t)=>{const o=g[t],n=m[o];n.occupants.push({id:e,end:s[e].end??-1/0});const i=l.get(e)?.group;i&&(n.group=i),f[e]=o});for(const t of[...e].sort((e,t)=>qn(e.id,t.id)))null==f[t.id]&&(m[0].occupants.push({id:t.id,end:-1/0}),f[t.id]=0);for(const e of m){e.occupants.sort((e,t)=>(s[e.id].start??1/0)-(s[t.id].start??1/0)||qn(e.id,t.id));for(const t of e.occupants){const n=o[t.id];e.peak.topPeak=Math.max(e.peak.topPeak,n?.topPeak||0),e.peak.botPeak=Math.max(e.peak.botPeak,n?.botPeak||0)}}const y={slots:m,slotByNode:f};return function(e,t){for(Li.has(e)&&Li.delete(e),Li.set(e,{slots:t.slots.map(e=>({occupants:e.occupants.map(e=>({...e})),peak:{...e.peak},...null!=e.group?{group:e.group}:{}})),slotByNode:{...t.slotByNode}});Li.size>12;){const e=Li.keys().next().value;if(null==e)break;Li.delete(e)}}(i,y),y}function Wi(e){return e.topMass+e.botMass}function Yi(e,t){const o=e.samples.filter(e=>e.t===t);if(o.length>0)return o.reduce((e,t)=>Wi(t)<Wi(e)?e:t,o[0]);let n=null;for(const o of e.samples){if(o.t>t)break;n=o}return n}function Hi(e,t,o,n,i,r,s=0){const a=new Map;for(const o of e){if(!o.group||!t[o.id])continue;const e=a.get(o.group)??[];e.push(o),a.set(o.group,e)}if(0===a.size||0>=r)return t;const l=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,{...t,samples:t.samples.map(e=>({...e})),localAttachments:new Map([...t.localAttachments].map(([e,t])=>[e,{...t}]))}]));for(const[e,c]of a){const a=o.map((e,t)=>({slot:e,index:t})).filter(({slot:t})=>t.group===e);if(0===a.length)continue;const u=a[0].slot,d=a.at(-1).slot,h=i[u.occupants[0]?.id],p=i[d.occupants[0]?.id];if(!Number.isFinite(h)||!Number.isFinite(p))continue;const g=(h-u.peak.topPeak*r+(p+d.peak.botPeak*r))/2,m=[...new Set(c.flatMap(e=>t[e.id].samples.map(e=>e.t)))].sort((e,t)=>e-t),f=new Map;for(const e of c)f.set(e.id,new Map);for(const e of m){const o=new Map;for(const i of c){const r=Yi(t[i.id],e);if(!r||1e-9>=Wi(r))continue;const s=n[i.id];if(null==s)continue;const a=o.get(s)??[];a.push({node:i,sample:r}),o.set(s,a)}const a=[...o].sort((e,t)=>e[0]-t[0]).map(([e,t])=>({slot:e,active:t,mass:Math.max(...t.map(({sample:e})=>Wi(e)))}));if(0===a.length)continue;let l=g-(a.reduce((e,t)=>e+t.mass,0)*r+Math.max(0,s)*Math.max(0,a.length-1))/2;for(const t of a){for(const{node:o,sample:n}of t.active){const t=(l-i[o.id])/r+n.topMass-(n.boundaryOffset??0);f.get(o.id).set(e,t)}l+=t.mass*r+Math.max(0,s)}}for(const e of c){const o=t[e.id],n=l[e.id],i=f.get(e.id),r=[];for(const e of m){const t=i.get(e),n=o.samples.filter(t=>t.t===e);if(n.length>0){r.push(...n.map(e=>({...e,...null!=t?{boundaryOffset:(e.boundaryOffset??0)+t}:{}})));continue}const s=Yi(o,e);null!=t&&s&&Wi(s)>1e-9&&r.push({...s,t:e,boundaryOffset:(s.boundaryOffset??0)+t})}n.samples=r,n.localAttachments=new Map([...o.localAttachments].map(([e,t])=>{const o=i.get(t.time);return[e,{...t,...null!=o?{boundaryOffset:(t.boundaryOffset??0)+o}:{}}]}))}}return l}function Vi(e,t,o,n,i){const{plotH:r,padding:s,valueScale:a,packing:l,laneOrder:c,lifetimeMode:u="half",lanePlacement:d="stack",groupPadding:h=0,ribbonLane:p="both",domain:g}=i,m={},f={};for(const t of e)m[t.id]=o[t.id].topPeak||0,f[t.id]=o[t.id].botPeak||0;const y="half"===u,b={};for(const t of e){const e=Array.isArray(t.xExtent)?t.xExtent[0]:null,o=Array.isArray(t.xExtent)?t.xExtent[1]:null;let i=null!=e&&Number.isFinite(e)?e:1/0,r=null!=o&&Number.isFinite(o)?o:-1/0;for(const e of n.outgoing[t.id]){i>e.startTime&&(i=e.startTime),null!=e.systemInTime&&Number.isFinite(e.systemInTime)&&i>e.systemInTime&&(i=e.systemInTime);const t=y?(e.startTime+e.endTime)/2:e.endTime;t>r&&(r=t)}for(const e of n.incoming[t.id]){const t=y?(e.startTime+e.endTime)/2:e.startTime;i>t&&(i=t),e.endTime>r&&(r=e.endTime),null!=e.systemOutTime&&Number.isFinite(e.systemOutTime)&&e.systemOutTime>r&&(r=e.systemOutTime)}b[t.id]={start:Number.isFinite(i)?i:null,end:Number.isFinite(r)?r:null}}let x={},v=[],w=[];if(i.frozenSlots){const e=Ti(i.frozenSlots,o,b);v=e.slots,x=e.slotByNode,w=v.map(Un)}else if("reuse"===l){const n=Di(e,t,o,b);v=n.slots,x=n.slotByNode}else e.forEach((e,t)=>{v.push({occupants:[{id:e.id,end:b[e.id]?.end??-1/0}],peak:{topPeak:m[e.id],botPeak:f[e.id]},...e.group?{group:e.group}:{}}),x[e.id]=t});xi(v,x),0===w.length&&(w=v.map(Un));let A=null;i.frozenSlots||(i.fixedSlotOrder?function(e,t,o){const n=new Map(o.map((e,t)=>[e,t]));gi(e,t,[...e].sort((e,t)=>(n.get(Un(e))??1/0)-(n.get(Un(t))??1/0)||qn(Un(e),Un(t))))}(v,x,i.fixedSlotOrder):i.runOrdering&&c&&"insertion"!==c&&(A=Pi(e,t,o,b,v,x,{plotH:r,padding:s,valueScale:a,groupPadding:h,laneOrder:c,ribbonLane:p,domain:g}))),xi(v,x);const S=ei(e,t,o,v,x,{plotH:r,padding:s,valueScale:a,stackValueScale:i.stackValueScale,lanePlacement:d,groupPadding:h}),k=0===v.length?0:v[0].peak.topPeak+S.adjacentClearance.reduce((e,t)=>e+t,0)+v[v.length-1].peak.botPeak,M=A?.before.crossings??null,_=A?.after.crossings??null,P=A?.before.weightedLength??null,T=A?.after.weightedLength??null;return{effectiveSlotsHeight:k,centerlines:S.centerlines,laneLifetime:b,slots:v,slotByNode:x,slotCenter:S.slotCenter,stackCenter:S.stackCenter,verticalUtilization:S.verticalUtilization,selectedSlotOrder:v.map(Un),initialSlotOrder:w,ordering:A,crossingsBefore:M,crossingsAfter:_,lengthBefore:P,lengthAfter:T}}function Gi(e,t,o,n,i,r,s,a,l={}){const c=i,u=e=>a?Math.max(a[0],Math.min(a[1],e)):e;let d=r(u(e.time));const h=r(u(o.time)),p=e.value*c,g=o.value*c,m=t+(e.boundaryOffset??0)*c,f=n+(o.boundaryOffset??0)*c,y=e.sideMassBefore*c,b=o.sideMassAfter*c;let x,v,w,A;"top"===e.side?(x=m-y,v=x+p):(v=m+y,x=v-p),"top"===o.side?(w=f-b,A=w+g):(A=f+b,w=A-g);const S=l.sourceRunwayStart,k=l.minRun,M=Math.abs((w+A)/2-(x+v)/2),_=h-d,P="number"==typeof S&&Number.isFinite(S),T="number"==typeof k&&Number.isFinite(k)&&k>0;if(P&&M>1e-9&&_>0&&("auto"===k||T)){const t="source"===s?.85:"target"===s?.15:.5,o="auto"===k?Math.min(144,Math.sqrt(8*M/(1.5*Math.min(t*t,(1-t)*(1-t))))):k;if(o>_){const t=r(u(Math.min(S,e.time)));Number.isFinite(t)&&(d=Math.min(d,Math.max(Math.min(d,t),h-o)))}}const L="source"===s?d+.85*(h-d):"target"===s?d+.15*(h-d):(d+h)/2;return{sx:d,sTop:x,sBot:v,tx:h,tTop:w,tBot:A,cp1X:L,cp2X:L}}function Xi(e){return Math.max(18,11*e.length*.58)}function qi(e){const t=1.22*Xi(e.labelText)+4;return"start"===e.labelAnchor?[e.labelX,e.labelX+t]:"middle"===e.labelAnchor?[e.labelX-t/2,e.labelX+t/2]:[e.labelX-t,e.labelX]}function Ui(e,t){const o=e.labelX-Xi(e.labelText),n=t.labelX-Xi(t.labelText);return t.labelX+3>=o&&e.labelX+3>=n}var Qi=/(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?),(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/gi;function Zi(e){return e.replace(Qi,(e,t,o)=>`${o},${t}`)}function Ki(e){if(!e)return;const t=e=>({x:e.y,y:e.x});return{...e,...e.points&&{points:e.points.map(t)},...e.segments&&{segments:e.segments.map(e=>e.map(t))}}}function Ji(e){return{...e,pathD:Zi(e.pathD),y0:e.x0,y1:e.x1,x0:0,x1:0}}function er(e){const{nodes:t,edges:o,domain:n,plotW:r,plotH:s,ribbonLane:l,ribbonMinRun:c=0,edgeOpacity:u,colorOf:d,layoutOpts:h,orientation:p="horizontal",showLabels:g=!0,labelPriorityAccessor:m,maxLabels:f,selectionDatum:y="raw",styleRules:b,colorBy:x,valueAccessor:v,usageMode:w="static"}=e,A="vertical"===p?s:r,S="vertical"===p?r:s,k=function(e,t,o,n={}){const i=Hn(n.usageMode??"static"),r=[],s=new Set;for(const t of e)s.has(t.id)&&r.push({kind:"duplicate-node",id:t.id,severity:i.duplicateIds}),s.add(t.id);const a=new Set,l=Array.isArray(o)&&2===o.length,c=l&&Number.isFinite(o[0])&&Number.isFinite(o[1]);l&&c&&c&&o[1]>=o[0]||r.push({kind:"invalid-domain"});for(const t of e)null!=t.xExtent&&(Array.isArray(t.xExtent)&&2===t.xExtent.length&&Number.isFinite(t.xExtent[0])&&Number.isFinite(t.xExtent[1])&&t.xExtent[1]>=t.xExtent[0]||r.push({kind:"invalid-node-time",id:t.id}));for(const e of t)a.has(e.id)&&r.push({kind:"duplicate-edge",id:e.id,severity:i.duplicateIds}),a.add(e.id),s.has(e.source)||r.push({kind:"missing-node",id:e.id,endpoint:"source",nodeId:e.source}),s.has(e.target)||r.push({kind:"missing-node",id:e.id,endpoint:"target",nodeId:e.target}),Number.isFinite(e.startTime)&&Number.isFinite(e.endTime)?((null!=e.systemInTime&&!Number.isFinite(e.systemInTime)||null!=e.systemOutTime&&!Number.isFinite(e.systemOutTime))&&r.push({kind:"invalid-system-time",id:e.id,severity:"warn"}),Number.isFinite(e.value)&&e.value>0||r.push({kind:"invalid-value",id:e.id}),e.startTime>e.endTime&&r.push({kind:"backward-edge",severity:"fatal",id:e.id,source:e.source,target:e.target})):r.push({kind:"invalid-edge-time",id:e.id});return r}(t,o,n,{usageMode:w}),{fatal:M,warnings:_}=function(e){const t=[],o=[];for(const n of e)"fatal"===Gn(n)?t.push(n):o.push(n);return{fatal:t,warnings:o}}(k),P=function(e,t,o="static"){if("strip"!==Hn(o).invalidSystemTime)return e;const n=new Set(t.filter(e=>"invalid-system-time"===e.kind).map(e=>e.id));return 0===n.size?e:e.map(e=>{if(!n.has(e.id))return e;const t={...e};return null==t.systemInTime||Number.isFinite(t.systemInTime)||delete t.systemInTime,null==t.systemOutTime||Number.isFinite(t.systemOutTime)||delete t.systemOutTime,t})}(o,k,w),T=Wn().domain(n).range([0,A]);if(M.length>0)return{layout:null,layoutConfig:{bands:[],ribbons:[],showLabels:!1!==g},issues:M,warnings:_,xScale:T};const L=function(e,t,o){const{plotH:n,pairing:i="temporal",packing:r="reuse",laneOrder:s="crossing-min",lifetimeMode:a="half",maxValueScale:l,lanePlacement:c="stack",nodeSizing:u="temporal",groupPadding:d=0,ribbonLane:h="both",domain:p}=o,g=Number.isFinite(d)?Math.max(0,d):0,m=function(e,t){const o={},n={};for(const t of e)o[t.id]=[],n[t.id]=[];for(const e of t)n[e.source]&&n[e.source].push(e),o[e.target]&&o[e.target].push(e);return{incoming:o,outgoing:n}}(e,t),f=function(e,t,o,n="temporal"){const i="temporal"===n?(e,t)=>e.endTime-t.endTime||qn(e.id,t.id):(e,t)=>t.value-e.value||qn(e.id,t.id),r="temporal"===n?(e,t)=>e.startTime-t.startTime||qn(e.id,t.id):(e,t)=>t.value-e.value||qn(e.id,t.id),s=new Map;for(const e of t)s.set(e.id,{});const a=(e,t)=>{const o=new Map;for(const n of e){const e=n[t];o.has(e)||o.set(e,{partner:e,edges:[],total:0,earliestStart:1/0,latestEnd:-1/0});const i=o.get(e);i.edges.push(n),i.total+=n.value,i.earliestStart=Math.min(i.earliestStart,n.startTime),i.latestEnd=Math.max(i.latestEnd,n.endTime)}const s=[...o.values()];s.sort("temporal"===n?(e,o)=>"target"===t?e.earliestStart-o.earliestStart||qn(e.partner,o.partner):e.latestEnd-o.latestEnd||qn(e.partner,o.partner):(e,t)=>t.total-e.total||qn(e.partner,t.partner));for(const e of s)e.edges.sort("target"===t?r:i);return s};for(const t of e){const e=o.outgoing[t.id],n=o.incoming[t.id];if(0===n.length)a(e,"target").forEach((e,t)=>{const o=t%2==0?"top":"bot";for(const t of e.edges)s.get(t.id).sourceSide=o});else if(0===e.length)a(n,"source").forEach((e,t)=>{const o=t%2==0?"top":"bot";for(const t of e.edges)s.get(t.id).targetSide=o});else{const t=a(n,"source"),o=a(e,"target"),i=Math.max(t.length,o.length);for(let e=0;i>e;e++){const n=e%2==0?"top":"bot";if(t[e])for(const o of t[e].edges)s.get(o.id).targetSide=n;if(o[e])for(const t of o[e].edges)s.get(t.id).sourceSide=n}}}return s}(e,t,m,i);let y={};for(const t of e)y[t.id]=hi(t,m,f,void 0,u);const b=Vi(e,t,y,m,{plotH:n,padding:12,valueScale:1,packing:r,laneOrder:s,lifetimeMode:a,runOrdering:!0,lanePlacement:"stack",groupPadding:g,ribbonLane:h,domain:p}),x=b.slots.map(e=>({occupants:e.occupants.map(e=>({...e})),peak:{...e.peak},...null!=e.group?{group:e.group}:{}})),v=new Set;for(const e of t){const t=b.slotByNode[e.source],o=b.slotByNode[e.target];if(void 0===t||void 0===o)continue;const n=f.get(e.id);t!==o?t>o?(n.sourceSide="top",n.targetSide="bot"):(n.sourceSide="bot",n.targetSide="top"):(v.add(e.id),n.sourceSide="bot",n.targetSide="bot")}for(const t of e){const e=m.outgoing[t.id],o=m.incoming[t.id],n=new Set(e.map(e=>f.get(e.id).sourceSide)),i=new Set(o.map(e=>f.get(e.id).targetSide));if(1===n.size&&o.length>0){const e=[...n][0];for(const t of o)b.slotByNode[t.source]===b.slotByNode[t.target]&&(f.get(t.id).targetSide=e)}if(1===i.size&&e.length>0){const t=[...i][0];for(const o of e)b.slotByNode[o.source]===b.slotByNode[o.target]&&(f.get(o.id).sourceSide=t)}}!function(e,t,o){const n=new Map,i=[];for(const t of e)i.push({time:t.startTime,kind:"out",edge:t}),i.push({time:t.endTime,kind:"in",edge:t});i.sort((e,t)=>e.time-t.time||(e.kind===t.kind?0:"in"===e.kind?-1:1)||("out"===e.kind?t.edge.value-e.edge.value:0)||qn(e.edge.id,t.edge.id));const r=e=>{let t=n.get(e);return t||(t={top:0,bot:0},n.set(e,t)),t},s=(e,t,o)=>{const n="top"===t?"bot":"top",i=Math.min(o,e[t]);e[t]-=i;const r=o-i;r>0&&(e[n]=Math.max(0,e[n]-r))};for(const e of i){const{edge:n}=e;if("in"===e.kind){const e=t.get(n.id)?.targetSide??"bot";r(n.target)[e]+=n.value;continue}const i=r(n.source),a=t.get(n.id);let l=a.sourceSide??"bot";if(o[n.source]===o[n.target]){const e=i.top>=n.value,t=i.bot>=n.value;e!==t?l=e?"top":"bot":e||t||i.top===i.bot||(l=i.top>i.bot?"top":"bot"),a.sourceSide=l,a.targetSide=l}s(i,l,n.value)}}(t,f,b.slotByNode),function(e,t,o,n){for(const i of e){const e=t.incoming[i.id],r=t.outgoing[i.id];if(0===e.length||0===r.length)continue;const s=()=>{const t={inTop:0,inBot:0,outTop:0,outBot:0};for(const n of e)"top"===o.get(n.id).targetSide?t.inTop+=n.value:t.inBot+=n.value;for(const e of r)"top"===o.get(e.id).sourceSide?t.outTop+=e.value:t.outBot+=e.value;return t},a=(e,t)=>{const i=s(),a="top"===e?i.outTop-i.inTop:i.outBot-i.inBot,l="top"===t?i.inTop-i.outTop:i.inBot-i.outBot;if(0>=a||0>=l)return!1;const c=Math.min(a,l),u=r.filter(t=>!n.has(t.id)&&o.get(t.id).sourceSide===e&&c>=t.value).sort((e,t)=>t.value-e.value||qn(e.id,t.id));return 0!==u.length&&(o.get(u[0].id).sourceSide=t,!0)};let l=r.length+1;for(;l-- >0&&(a("top","bot")||a("bot","top")););}}(e,m,f,v),y={};for(const t of e)y[t.id]=hi(t,m,f,void 0,u);const w=Vi(e,t,y,m,{plotH:n,padding:12,valueScale:1,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:x,lanePlacement:"stack",groupPadding:g,ribbonLane:h,domain:p}),A=w.effectiveSlotsHeight??w.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),S=w.slots.slice(0,-1).reduce((e,t,o)=>e+(null!=t.group&&t.group===w.slots[o+1].group?1:0),0),k=Math.max(1,w.slots.length+1-S),M=Math.min(12,Math.max(0,.35*n-S*g)/k),_=2*M+Qn(w.slots,M,g).reduce((e,t)=>e+t,0),P=A>0?Math.max(0,(n-_)/A):1,T=Number.isFinite(l)&&l>0?Math.min(P,l):P;let L=Vi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:x,lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P});const R=Number.isFinite(l)&&l>0&&P>l+1e-12;if("insertion"!==s&&("hug"===c||R)&&L.slots.length>1&&(Pi(e,t,y,L.laneLifetime,L.slots,L.slotByNode,{plotH:n,padding:M,valueScale:T,groupPadding:g,laneOrder:s,ribbonLane:h,domain:p,lanePlacement:c,mode:"geometry-refine"}),L=Vi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:L.slots,fixedSlotOrder:L.slots.map(Un),lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P})),function(e,t){const o=(e,o)=>{for(const n of e){const e=new Map;for(const i of n){const n=`${("out"===o?t.get(i.id)?.sourceSide:t.get(i.id)?.targetSide)??""}\0${"out"===o?i.startTime:i.endTime}`,r="out"===o?`${i.target}\0${i.endTime}`:`${i.source}\0${i.startTime}`,s=e.get(n);if(null!=s&&s!==r)return!0;e.set(n,r)}}return!1};return o(Object.values(e.outgoing),"out")||o(Object.values(e.incoming),"in")}(m,f)){const o=function(e,t,o,n){const i=new Map;for(const r of e){const e=t[r.source]?.localAttachments.get(r.id),s=t[r.target]?.localAttachments.get(r.id),a=o[r.source],l=o[r.target];if(!(e&&s&&Number.isFinite(a)&&Number.isFinite(l)))continue;const c=di(e,a,n),u=di(s,l,n);i.set(r.id,{source:(c[0]+c[1])/2,target:(u[0]+u[1])/2})}return i}(t,y,L.centerlines,T);y={};for(const t of e)y[t.id]=hi(t,m,f,o,u);L=Vi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:L.slots,fixedSlotOrder:L.slots.map(Un),lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P})}const I=new Map(b.initialSlotOrder.map((e,t)=>[e,t])),C=[...L.slots].sort((e,t)=>(I.get(Un(e))??1/0)-(I.get(Un(t))??1/0)||qn(Un(e),Un(t))),z={};C.forEach((e,t)=>{for(const o of e.occupants)z[o.id]=t});const F=ei(e,t,y,C,z,{plotH:n,padding:M,valueScale:T,stackValueScale:P,lanePlacement:"stack",groupPadding:g}),O=Hi(e,y,C,z,F.centerlines,T,g),B=li(wi(z,t),Ai(z,t),t,O,C,z,F.centerlines,L.laneLifetime,T,F.verticalUtilization,h,p);y=Hi(e,y,L.slots,L.slotByNode,L.centerlines,T,g);const N=li(wi(L.slotByNode,t),Ai(L.slotByNode,t),t,y,L.slots,L.slotByNode,L.centerlines,L.laneLifetime,T,L.verticalUtilization,h,p);return{nodeData:y,sides:f,valueScale:T,padding:M,compressedPadding:12>M,centerlines:L.centerlines,laneLifetime:L.laneLifetime,slots:L.slots,slotByNode:L.slotByNode,crossingsBefore:"insertion"===s?null:B.crossings,crossingsAfter:"insertion"===s?null:N.crossings,lengthBefore:"insertion"===s?null:B.weightedLength,lengthAfter:"insertion"===s?null:N.weightedLength,layoutQualityBefore:B,layoutQuality:N}}(t,P,{plotH:S,...h,ribbonLane:l,domain:n}),{centerlines:R,nodeData:I,valueScale:C}=L,z=i(x,v),F=[],O=[],B=0===c?new Map:function(e,t,o){const n=new Set(t.map(e=>e.target)),i=new Map(e.map(e=>[e.id,e])),r=new Map;for(const e of t){if(n.has(e.source))continue;const t=r.get(e.source)??[];t.push(e),r.set(e.source,t)}const s=new Map;for(const t of e){if(!t.group)continue;const e=s.get(t.group)??[];e.push(t),s.set(t.group,e)}const a=new Set;for(const[e,t]of s){const o=t.flatMap(e=>r.get(e.id)??[]),i=new Set(o.map(e=>e.startTime));o.length>0&&1===i.size&&t.every(e=>{const t=e.xExtent?.[0],i=o[0].startTime;return!n.has(e.id)&&(r.get(e.id)?.length??0)>0&&Number.isFinite(t)&&i>t})&&a.add(e)}const l=new Map;for(const[e,t]of r){const n=i.get(e);if(n?.group&&!a.has(n.group))continue;const r=n?.xExtent?.[0],s=[...t].sort((e,t)=>e.startTime-t.startTime||e.id.localeCompare(t.id)),c=s[0]?.startTime-1;let u=null;for(let e=0;s.length>e;){const t=s[e].startTime;let n=e+1;for(;s.length>n&&s[n].startTime===t;)n++;for(let t=e;n>t;t++){const e=s[t],n=Number.isFinite(r)&&e.startTime>r,i=Number.isFinite(e.systemInTime)&&e.startTime>e.systemInTime;if(!n&&!i)continue;let a=o[0];n&&(a=Math.max(a,r)),i&&(a=Math.max(a,e.systemInTime)),!n&&i&&Number.isFinite(c)&&(a=Math.max(a,c)),null!=u&&(a=Math.max(a,u)),e.startTime>a&&l.set(e.id,a)}u=t,e=n}}for(const[e,t]of s){if(!a.has(e))continue;const o=t.flatMap(e=>r.get(e.id)??[]);if(!o.every(e=>l.has(e.id))){for(const e of o)l.delete(e.id);continue}const n=Math.max(...o.map(e=>l.get(e.id)));for(const e of o)l.set(e.id,n)}return l}(t,P,n),N=new Map(t.filter(e=>e.group).map(e=>[e.id,e.group])),E=new Map;for(const e of P){const t=I[e.source]?.localAttachments.get(e.id),o=I[e.target]?.localAttachments.get(e.id);t&&o&&E.set(e.id,Gi(t,R[e.source],o,R[e.target],C,T,l,n,{minRun:c,sourceRunwayStart:B.get(e.id)}))}const j=function(e,t,o,n,i,r){const s=new Map(t),a=new Map;for(const t of e){const e=r?.get(t.source),o=null==e?"node:"+t.source:"group:"+e,n=a.get(o)??new Map,i=n.get(t.startTime)??[];i.push(t),n.set(t.startTime,i),a.set(o,n)}for(const e of a.values())for(const[r,a]of e){if(!a.some(e=>o.has(e.id)))continue;const e=a.map(e=>t.get(e.id));if(e.some(e=>null==e))continue;const l=n(r),c=Math.min(...e.map(e=>e.sx));if(c>=l-1e-9)continue;const u=Math.max(...a.map(e=>{const t=o.get(e.id);return null==t?l:Math.min(l,n(t))})),d=Math.min(l,Math.max(c,u));for(const e of a){const o=t.get(e.id),n=d+(o.tx-d)*("source"===i?.85:"target"===i?.15:.5);s.set(e.id,{...o,sx:d,cp1X:n,cp2X:n})}}return s}(P,E,B,T,l,N),$=function(e,t,o,n,i){const r=new Map;for(const s of e){if(!o.has(s.id))continue;const e=t.get(s.id);if(!e||e.sx>=n(s.startTime)-1e-9)continue;const a=i(e.sx);Number.isFinite(a)&&s.startTime>a&&r.set(s.id,a)}return r}(P,j,B,T,e=>n[0]+e/A*(n[1]-n[0])),D=function(e,t,o){const n=new Map,i=new Map;for(const[e,t]of o??[]){const o=i.get(t)??[];o.push(e),i.set(t,o)}for(const r of e){const e=t.get(r.id);if(null==e||!Number.isFinite(e)||e>=r.startTime)continue;const s=o?.get(r.source),a=null==s?[r.source]:i.get(s)??[r.source];for(const t of a){const o=n.get(t)??new Map,i=o.get(r.startTime);o.set(r.startTime,null==i?e:Math.min(i,e)),n.set(t,o)}}return n}(P,$,N);t.forEach((e,t)=>{const o=I[e.id];if(!o||0===o.samples.length)return;const i=(r=o.samples,(s=D.get(e.id))&&0!==s.size?r.map(e=>{const t=s.get(e.t);return null==t?e:{...e,t:t}}):r);var r,s;const l=function(e,t,o,n,i){if(0===e.length)return null;const r=ui(e,i),s=e=>t+(r[e].boundaryOffset??0)*o,a=e=>s(e)-r[e].topMass*o,l=e=>s(e)+r[e].botMass*o;let c=`M${n(r[0].t)},${a(0)}`;for(let e=1;r.length>e;e++)c+=` L${n(r[e].t)},${a(e)}`;c+=` L${n(r[r.length-1].t)},${l(r.length-1)}`;for(let e=r.length-2;e>=0;e--)c+=` L${n(r[e].t)},${l(e)}`;return c+" Z"}(i,R[e.id],C,T,n);if(!l)return;const c=ui(i,n),u=c.find(e=>e.topMass+e.botMass>0)||c[0],h=R[e.id]+(u.botMass-u.topMass+2*(u.boundaryOffset??0))*C/2;let g,m,f=d(e.id,t),y=f,x=.5;const v=e.__raw??e;if(b&&b.length>0){const e=a(v,b,z(v));"string"==typeof e.fill?f=e.fill:null!=e.fill&&ht(e.fill)&&(m=e.fill,f=e.fill.background&&"transparent"!==e.fill.background?e.fill.background:f),"string"==typeof e.stroke&&(y=e.stroke),"number"==typeof e.strokeWidth&&(x=e.strokeWidth),"number"==typeof e.fillOpacity&&(g=e.fillOpacity),"number"==typeof e.opacity&&null==g&&(g=e.opacity)}const w=function(e,t,o,n,i,r){const s=o.nodeData[e];if(!s||0===s.samples.length)return[];const a=o.valueScale,l=o.centerlines[e],c=ui(s.samples,i),u=c.find(e=>e.topMass+e.botMass>0)||c[0],d=[...c].reverse().find(e=>e.topMass+e.botMass>0)||c[c.length-1],h=n(u.t),p=n(d.t),g=e=>n(ci(e,i)),m=[],f=(e,t,o,n)=>`M${e},${t} L${o},${t} L${o},${n} L${e},${n} Z`;for(const o of t){if(o.source===e&&null!=o.systemInTime&&Number.isFinite(o.systemInTime)){const e=s.localAttachments.get(o.id),t=r?.get(o.id)??o.startTime;if(e&&"out"===e.kind&&t>o.systemInTime){const n=g(o.systemInTime),r=g(t),s=null!=i&&i[0]>o.systemInTime,c=s?n:n-20,u=s?Math.min(r,n+20):n,d=Math.max(h,c);if(r>d){const[t,o]=di(e,l,a);m.push({pathD:f(d,t,r,o),x0:c,x1:u,from:0,to:1})}}}if(o.target===e&&null!=o.systemOutTime&&Number.isFinite(o.systemOutTime)){const e=s.localAttachments.get(o.id);if(e&&"in"===e.kind&&o.systemOutTime>o.endTime){const t=g(o.systemOutTime),n=g(o.endTime),i=t+20,r=Math.min(p,i);if(r>n){const[o,s]=di(e,l,a);m.push({pathD:f(n,o,r,s),x0:t,x1:i,from:1,to:0})}}}}return m}(e.id,P,L,T,n,$);F.push({id:e.id,pathD:l,fill:f,stroke:y,strokeWidth:x,...null!=g&&{fillOpacity:g},...m&&{hatchFill:m},...w.length>0&&{gradientStubs:w},rawDatum:v,labelX:T("vertical"===p&&e.xExtent?e.xExtent[0]:u.t)-4,labelY:h,labelText:e.label??e.id})});const W=new Map;t.forEach((e,t)=>W.set(e.id,t)),P.forEach(e=>{const t=j.get(e.id);if(!t)return;const o=W.get(e.source)??0,n=d(e.source,o),{pathD:i,bezier:r}=V(t),s=e.__raw??e,a="function"==typeof u?Number(u(s)):u,l=Number.isFinite(a)?Math.max(0,Math.min(1,a)):.35;O.push({id:e.id,pathD:i,fill:n,opacity:l,rawDatum:s,bezier:r})});const Y=function(e,t,o){const n=e.map(e=>({...e})),i=new Map;for(const e of n){const o=t[e.id];if(null==o)continue;const n=i.get(o)??[];n.push(e),i.set(o,n)}const r=e=>{if(2>e.length)return;const t=e.reduce((e,t)=>e+t.labelY,0)/e.length,n=(e.length-1)/2;e.forEach((e,i)=>{e.labelY=Math.max(8,Math.min(o-8,t+16*(i-n)))})};for(const e of i.values()){e.sort((e,t)=>e.labelX-t.labelX||e.id.localeCompare(t.id));let t=[],o=-1/0;for(const n of e){const e=n.labelX-Xi(n.labelText);t.length>0&&e>o+3&&(r(t),t=[],o=-1/0),t.push(n),o=Math.max(o,n.labelX)}r(t)}return function(e,t){const o=[...e].sort((e,t)=>e.labelY-t.labelY||e.labelX-t.labelX||e.id.localeCompare(t.id));for(let e=0;3>e;e+=1){for(let e=0;o.length>e;e+=1){let t=8;for(let n=0;e>n;n+=1)Ui(o[e],o[n])&&(t=Math.max(t,o[n].labelY+16));o[e].labelY=Math.max(o[e].labelY,t)}for(let e=o.length-1;e>=0;e-=1){let n=t-8;for(let t=e+1;o.length>t;t+=1)Ui(o[e],o[t])&&(n=Math.min(n,o[t].labelY-16));o[e].labelY=Math.min(o[e].labelY,n)}}}(n,o),n}(F,L.slotByNode,S).map(e=>function(e,t){return"horizontal"===t?e:{...e,pathD:Zi(e.pathD),gradientStubs:e.gradientStubs?.map(Ji),labelX:e.labelY,labelY:e.labelX,labelAnchor:"middle",labelBaseline:"auto"}}(e,p)),H="vertical"===p?function(e,t,o){const n=e.map(e=>({...e}));for(const e of n){const o=1.22*Xi(e.labelText)+4;e.labelX=t-4>o?Math.max(o/2+2,Math.min(t-o/2-2,e.labelX)):t/2}const i=[],r=[...n].sort((e,t)=>e.labelY-t.labelY||e.labelX-t.labelX);for(const e of r){const t=i[i.length-1];!t||Math.abs(t[0].labelY-e.labelY)>14?i.push([e]):t.push(e)}for(const e of i){e.sort((e,t)=>e.labelX-t.labelX||e.id.localeCompare(t.id));const t=[],n=new Map;for(const o of e){const[e,i]=qi(o);let r=t.findIndex(t=>e>t+8);-1===r&&(r=t.length),t[r]=i,n.set(o,r)}const i=e.reduce((e,t)=>e+t.labelY,0)/e.length,r=14*t.length+8>i;for(const t of e){const e=n.get(t)??0;t.labelY=r?Math.min(o-8,12+14*e):Math.max(8,i-14*e)}}return n}(Y,r,s):Y,G=new Map;if(null!=m)for(const e of t){const t=e.__raw??e,o="function"==typeof m?m(t):Number(t[m]);Number.isFinite(o)&&G.set(e.id,o)}const X=function(e,t,o,n,i={}){if(!1===n)return e.map(e=>({...e,labelText:"",labelDeferred:!1,labelFullText:void 0}));if(!0===n)return e.map(e=>({...e,labelDeferred:!1,labelFullText:void 0}));let r=Math.max(4,Math.min(e.length,Math.floor(Math.max(1,t*o)/14e3)));Number.isFinite(i.maxLabels)&&i.maxLabels>=0&&(r=Math.min(r,Math.floor(i.maxLabels)));const s=e.map((e,t)=>{const o=i.priorityById?.get(e.id),n=Math.abs(e.labelY);return{band:e,index:t,score:null!=o&&Number.isFinite(o)?1e6*o+Xi(e.labelText):Xi(e.labelText)+.01*n}}).filter(e=>e.band.labelText.trim().length>0).sort((e,t)=>t.score-e.score||e.index-t.index||e.band.id.localeCompare(t.band.id)),a=new Set(s.slice(0,r).map(e=>e.band.id));return e.map(e=>a.has(e.id)||0===e.labelText.trim().length?{...e,labelDeferred:!1,labelFullText:void 0}:{...e,labelFullText:e.labelText,labelText:"",labelDeferred:!0})}(H,r,s,g,{...G.size>0&&{priorityById:G},...null!=f&&{maxLabels:f}});return{layout:L,layoutConfig:{bands:X,ribbons:O.map(e=>function(e,t){return"horizontal"===t?e:{...e,pathD:Zi(e.pathD),bezier:Ki(e.bezier)}}(e,p)),showLabels:!1!==g,selectionDatum:y},issues:[],warnings:_,xScale:T}}import{Fragment as tr,jsx as or,jsxs as nr}from"react/jsx-runtime";var ir="var(--semiotic-grid, #94a3b8)",rr="var(--semiotic-text-secondary, #475569)",sr="var(--semiotic-text-secondary, #94a3b8)",ar=.22;function lr(e,t,o){return!t?.isActive||t.predicate(function(e,t){return"scene"===t?e:e.data}(e,o))}var cr=e=>{const{bands:t=[],ribbons:o=[],showLabels:n=!0,selectionDatum:i="raw"}=e.config,r=e.selection??null,s=[];for(const e of o){const t={__kind:"ribbon",data:e.rawDatum,id:e.id},o=!lr(t,r,i);s.push({type:"bezier",pathD:e.pathD,...e.bezier&&{bezierCache:e.bezier},style:{fill:e.fill,opacity:o?Math.min(e.opacity,ar):e.opacity,stroke:"none"},datum:t})}for(const e of t){if(!e.gradientStubs)continue;const t=!lr({__kind:"band",data:e.rawDatum,id:e.id},r,i);for(let o=0;e.gradientStubs.length>o;o++){const n=e.gradientStubs[o];s.push({type:"bezier",pathD:n.pathD,interactive:!1,style:{fill:e.fill,fillOpacity:t?ar:e.fillOpacity??.86,stroke:"none"},_gradient:{x0:n.x0,x1:n.x1,...null!=n.y0&&{y0:n.y0},...null!=n.y1&&{y1:n.y1},from:n.from,to:n.to},datum:{__kind:"band",data:e.rawDatum,id:`${e.id}__stub${o}`}})}}for(const e of t){const t=!(!e.gradientStubs||0>=e.gradientStubs.length),o={__kind:"band",data:e.rawDatum,id:e.id},n=!lr(o,r,i);s.push({type:"bezier",pathD:e.pathD,style:{...t?{fill:"none"}:{fill:e.hatchFill??e.fill,fillOpacity:n?ar:e.fillOpacity??.86},stroke:e.stroke??("string"==typeof e.fill?e.fill:"#666"),strokeWidth:e.strokeWidth??.5,...n&&t?{opacity:ar}:{}},datum:o})}const a=n?t.flatMap(e=>{const t=e.labelDeferred&&e.labelFullText?.trim(),o=e.labelText.trim().length>0,n=t&&r?.isActive&&lr({__kind:"band",data:e.rawDatum,id:e.id},r,i),s=o?e.labelText:n?e.labelFullText:"";return s.trim()?[{x:e.labelX,y:e.labelY,text:s,anchor:e.labelAnchor??"end",baseline:e.labelBaseline??"middle",fontSize:11,fontWeight:600}]:[]}):[];return{sceneNodes:t.map(e=>({type:"circle",id:e.id,cx:-1e4,cy:-1e4,r:0,style:{fill:e.fill},datum:{__kind:"band",data:e.rawDatum,id:e.id}})),sceneEdges:s,labels:a}};function ur(e,t){if(!e)return[];const o=[],n=e=>{o.push(e);const i="function"==typeof t?t(e):e[t];i&&Array.isArray(i)&&i.forEach(n)};return n(e),o}function dr(e,t,o,n){if(e&&e.length>0)return e;const i=new Set;return t.forEach(e=>{const t="function"==typeof o?o(e):e[o],r="function"==typeof n?n(e):e[n];i.add(t),i.add(r)}),Array.from(i).map(e=>({id:e}))}function hr(e,t,o={}){return Xt(t?"function"==typeof t?o=>({...e(o),...t(o)??{}}):o=>({...e(o),...t}):e,o)}var pr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=function(e){if(void 0!==e.edgeStyle)return e.edgeStyle;const{edgeWidth:t,edgeColor:o,edgeOpacity:n}=e,i=e.strokeWidth??1;return void 0!==t||void 0!==o||void 0!==n||void 0!==e.stroke||void 0!==e.strokeWidth||void 0!==e.opacity?r=>{const s=r?.data||r;let a=i;if("number"==typeof t)a=t;else if("function"==typeof t)a=t(s);else if("string"==typeof t){const e=s?.[t],o="number"==typeof e?e:Number(e);a=Number.isFinite(o)&&o>0?o:i}return{stroke:o??e.stroke??"#999",strokeWidth:a,opacity:n??e.opacity??.6}}:void 0}(i),s=Kt(n.theme).colors.categorical,a=new Map,c=i.nodeStyle??(e=>({fill:t?le(e?.data||e,t,void 0):Ee(void 0,s,o,void 0,a),..."number"==typeof i.nodeSize&&{r:i.nodeSize}})),u=l(i.styleRules,t,"number"==typeof i.nodeSize?void 0:i.nodeSize),d=Xt(u?(e,t)=>({...c(e),...u(e,t)}):c,{stroke:i.nodeStroke??i.stroke,strokeWidth:i.nodeStrokeWidth??i.strokeWidth,opacity:i.opacity});return{chartType:"force",nodes:i.nodes,edges:i.edges,nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor,sourceAccessor:i.sourceAccessor,targetAccessor:i.targetAccessor,colorBy:t,colorScheme:o,iterations:i.iterations,forceStrength:i.forceStrength,showLabels:i.showLabels??!1,nodeLabel:i.nodeLabel,nodeSize:i.nodeSize??8,nodeSizeRange:i.nodeSizeRange,nodeStyle:d,edgeStyle:r,...n}}},gr={frameType:"network",layout:{margin:{top:30,right:80,bottom:40,left:80}},buildProps:(e,t,o,n,i)=>{const r=e=>null==e?NaN:e instanceof Date?e.getTime():"number"==typeof e?e:new Date(e).getTime(),s=i.sourceAccessor||"source",a=i.targetAccessor||"target",l=i.valueAccessor||"value",c=i.nodeIdAccessor||"id",u=i.startTimeAccessor||"startTime",d=i.endTimeAccessor||"endTime",h=i.systemInTimeAccessor,p=i.systemOutTimeAccessor,g=i.xExtentAccessor||"xExtent",m=i.groupBy,f=i.edgeIdAccessor||"id",y=(e,t)=>"function"==typeof e?e(t):t[e],b=Array.isArray(i.edges)?i.edges:[],x=Array.isArray(i.nodes)?i.nodes:[],v=x.length>0?x:dr([],b,s,a),w=[r(i.domain?.[0]),r(i.domain?.[1])],A=v.map(e=>{const t=y(c,e)+"",o=y(g,e),n=i.nodeLabel?y(i.nodeLabel,e):t,s={id:t,label:null==n?t:n+"",__raw:e},a=m?y(m,e):null;if(null!=a&&a+""!=""&&(s.group=a+""),Array.isArray(o)&&2===o.length){const e=r(o[0]),t=r(o[1]);Number.isFinite(e)&&Number.isFinite(t)&&(s.xExtent=[e,t])}return s}),S=b.map((e,t)=>{const o=y(f,e),n={id:null!=o?o+"":`${y(s,e)}-${y(a,e)}-${t}`,source:y(s,e)+"",target:y(a,e)+"",value:Number(y(l,e)),startTime:r(y(u,e)),endTime:r(y(d,e)),__raw:e};if(h){const t=r(y(h,e));Number.isFinite(t)&&(n.systemInTime=t)}if(p){const t=r(y(p,e));Number.isFinite(t)&&(n.systemOutTime=t)}return n}),[k,M]=n.size??[600,400],_=n.margin,P="vertical"===i.orientation?"vertical":"horizontal",T=function(e,t,o,n="horizontal"){return"vertical"===n?{top:e?38:t?28:16,right:24,bottom:24,left:o?72:24}:{top:e?30:t?24:8,right:80,bottom:o?28:8,left:80}}(!!n.title,!!i.showQualityReadout,Array.isArray(i.axisTicks)&&i.axisTicks.length>0,P),L={...T,..._},R=(n.showLegend??!!t)&&!!t,I=n.legendPosition??"right",C=n.__explicitMargin,z=e=>"number"==typeof C||null!=C&&"object"==typeof C&&null!=C[e];R&&("right"!==I||z("right")?"bottom"!==I||z("bottom")||(L.bottom=Math.max(L.bottom,80)):L.right=Math.max(L.right,140));const F=L,O=k-F.left-F.right,B=M-F.top-F.bottom,N=Kt(n.theme),E=Oe(o,N.colors.categorical,Pt),j="function"==typeof t?t:null,$=j?v.map(e=>({_cat:j(e)})):v,D=j?"_cat":"string"==typeof t?t:void 0,W=o??[...E],Y=D?J($,D,W):null,H=new Map;for(const e of A)H.set(e.id,e.__raw);const V=(e,o)=>{if(t&&H.has(e)){const o=H.get(e);return j?le({_cat:j(o)},"_cat",Y??void 0):le(o,"string"==typeof t?t:"id",Y??void 0)}return E[o%E.length]},G=R&&t?(()=>{const e=new Map;v.forEach((o,n)=>{const i=y(t,o),r=null==i?"":i+"";r&&!e.has(r)&&e.set(r,{label:r,color:V(y(c,o)+"",n)})});const o=Array.from(e.values());return o.length>0?{legendGroups:[{type:"fill",label:"",items:o,styleFn:e=>{const t=e.color||"#333";return{fill:t,stroke:t}}}]}:void 0})():void 0,q=X(G,n.legend),U=!1!==i.showLabels&&("auto"!==i.showLabels||"auto"),{layout:Q,layoutConfig:Z,issues:K,xScale:ee}=er({nodes:A,edges:S,domain:w,plotW:O,plotH:B,orientation:P,ribbonLane:i.ribbonLane||"both",ribbonMinRun:"auto"===i.ribbonMinRun||"number"==typeof i.ribbonMinRun?i.ribbonMinRun:0,edgeOpacity:"number"==typeof i.edgeOpacity?i.edgeOpacity:.35,colorOf:V,showLabels:U,styleRules:i.styleRules,colorBy:t,valueAccessor:l,layoutOpts:{pairing:i.pairing||"temporal",packing:i.packing||"reuse",laneOrder:i.laneOrder||"crossing-min",lifetimeMode:i.lifetimeMode||"half",maxValueScale:"number"==typeof i.maxValueScale?i.maxValueScale:void 0,lanePlacement:i.lanePlacement||"stack",nodeSizing:i.nodeSizing||"temporal",groupPadding:"number"==typeof i.groupPadding?i.groupPadding:0}});if(K.length>0){const e=K.map(Xn).join("; ");throw Error("ProcessSankey: data invalid — "+e)}const te=Q?function(e){const t=e.layout,o=e.nodes,n=e.orientation,i=e.plotW,r=e.plotH,s=e.timelineExtent,a=e.axisTicks,l=e.showQualityReadout??!1,c=e.showLaneRails??!1,u=(e.warnings??[]).slice(0,3),d=e.timeFormat,h=e.colorOf,p=e.toTime,g=e.xScale,{centerlines:m,laneLifetime:f,nodeData:y,valueScale:b,compressedPadding:x,crossingsBefore:v,crossingsAfter:w,layoutQualityBefore:A,layoutQuality:S}=t;let k=null,M=null;for(const e of o){const t=f[e.id];if(!t||null===t.start||null===t.end)continue;const o=g(t.start),n=g(t.end);(null===k||k>o)&&(k=o),(null===M||n>M)&&(M=n)}const _=e=>Math.max(0,Math.min(s,e)),P=_(k??0),T=Math.max(P,_(M??s)),L=a.map((e,t)=>({tick:e,index:t,coordinate:g(p(e.date))})).filter(({coordinate:e})=>e>=P-.5&&T+.5>=e),R=null!==(w??null)&&null!=A&&null!=S,I=l&&(R||u.length>0)?nr("g",{fill:sr,fontSize:10,textAnchor:"end",children:[R&&nr(tr,{children:[nr("text",{x:i,y:-14,children:["crossings: ",v," → ",w," ","pixel length: ",Math.round(A.pixelLength)," → ",Math.round(S.pixelLength)]}),nr("text",{x:i,y:-3,children:["transit: ",A.transitOcclusion.toFixed(1)," → ",S.transitOcclusion.toFixed(1)," ","lane use: ",Math.round(100*S.verticalUtilization),"%"]})]}),u.map((e,t)=>nr("text",{x:i,y:R?10+11*t:11*t-3,fill:"var(--semiotic-warning, #b45309)",children:["warn: ",e]},"warn-"+t))]}):null,C=x?or("text",{x:i,y:"vertical"===n?-3:2,fontSize:10,fill:sr,textAnchor:"end",children:"dense layout: lane gaps compressed"}):null,z=(e,t)=>h?h(e,t):ir;return nr("g","vertical"===n?{children:[I,C,L.map(({index:e,coordinate:t})=>or("line",{x1:0,y1:t,x2:i,y2:t,stroke:ir,strokeOpacity:.15,strokeDasharray:"2 4"},"grid-"+e)),c&&o.map((e,t)=>{const o=f[e.id];if(!o||null===o.start)return null;const n=y[e.id],i=n?{topPeak:n.topPeak,botPeak:n.botPeak}:{topPeak:0,botPeak:0},r=m[e.id]+(i.botPeak-i.topPeak)*b/2,s=g(o.start),a=g(o.end),l=z(e.id,t);return nr("g",{children:[or("line",{x1:r,y1:s,x2:r,y2:a,stroke:l,strokeOpacity:.35,strokeWidth:1,strokeDasharray:"3 3"}),or("line",{x1:r-4,y1:s,x2:r+4,y2:s,stroke:l,strokeOpacity:.5}),or("line",{x1:r-4,y1:a,x2:r+4,y2:a,stroke:l,strokeOpacity:.5})]},"lane-"+e.id)}),or("line",{x1:-4,y1:P,x2:-4,y2:T,stroke:ir}),L.map(({tick:e,index:t,coordinate:o})=>{const n=p(e.date),i=null!=e.label?e.label:d?d(new Date(n)):"";return nr("g",{transform:`translate(-4,${o})`,children:[or("line",{x2:-6,stroke:ir}),or("text",{x:-10,y:4,textAnchor:"end",fontSize:11,fill:rr,children:i})]},t)})]}:{children:[I,C,L.map(({index:e,coordinate:t})=>or("line",{x1:t,y1:0,x2:t,y2:r,stroke:ir,strokeOpacity:.15,strokeDasharray:"2 4"},"grid-"+e)),c&&o.map((e,t)=>{const o=f[e.id];if(!o||null===o.start)return null;const n=y[e.id],i=n?{topPeak:n.topPeak,botPeak:n.botPeak}:{topPeak:0,botPeak:0},r=m[e.id]+(i.botPeak-i.topPeak)*b/2,s=g(o.start),a=g(o.end),l=z(e.id,t);return nr("g",{children:[or("line",{x1:s,y1:r,x2:a,y2:r,stroke:l,strokeOpacity:.35,strokeWidth:1,strokeDasharray:"3 3"}),or("line",{x1:s,y1:r-4,x2:s,y2:r+4,stroke:l,strokeOpacity:.5}),or("line",{x1:a,y1:r-4,x2:a,y2:r+4,stroke:l,strokeOpacity:.5})]},"lane-"+e.id)}),or("line",{x1:P,y1:r+4,x2:T,y2:r+4,stroke:ir}),L.map(({tick:e,index:t,coordinate:o})=>{const n=p(e.date),i=null!=e.label?e.label:d?d(new Date(n)):"";return nr("g",{transform:`translate(${o},${r+4})`,children:[or("line",{y2:6,stroke:ir}),or("text",{y:20,textAnchor:"middle",fontSize:11,fill:rr,children:i})]},t)})]})}({layout:Q,nodes:A,orientation:P,plotW:O,plotH:B,timelineExtent:"vertical"===P?B:O,axisTicks:Array.isArray(i.axisTicks)?i.axisTicks.map(e=>({date:e.date,label:e.label})):[],showQualityReadout:!!i.showQualityReadout,showLaneRails:!!i.showLaneRails,timeFormat:"function"==typeof i.timeFormat?e=>i.timeFormat(e):void 0,colorOf:V,toTime:e=>r(e),xScale:e=>Number(ee(e))}):void 0;return{chartType:"force",nodes:v,edges:b,customNetworkLayout:cr,layoutConfig:Z,sourceAccessor:s,targetAccessor:a,valueAccessor:l,nodeIDAccessor:c,colorBy:t,colorScheme:o,...te&&{backgroundGraphics:te},...n,showLegend:R,...q&&{legend:q,legendPosition:I},__legendIncludesAutomatic:!0,margin:F}}},mr={frameType:"network",layout:{primarySize:{width:800,height:600}},buildProps:(e,t,o,n,i)=>{const r=Array.isArray(i.nodes)?i.nodes:dr([],Array.isArray(i.edges)?i.edges:[],i.sourceAccessor||"source",i.targetAccessor||"target"),s=Kt(n.theme).colors.categorical,a=new Map,c="string"==typeof t?t:"__ssrSankeyColorBy",u="function"==typeof t?r.map(e=>({...e,__ssrSankeyColorBy:t(e)})):r,d=t?J(u,c,o??n.colorScheme??s):void 0,h=e=>({fill:t?le(e?.data||e,t,d):Ee(void 0,s,o,void 0,a),stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}),p=l(i.styleRules,t,i.valueAccessor),g=p?(e,t)=>({...h(e),...p(e,t)}):h,m=function({edgeColorBy:e,colorBy:t,colorScale:o,nodeStyleFn:n,edgeOpacity:i,baseStyle:r={}}){return s=>{const a={fillOpacity:i,...r};if("function"==typeof e)a.fill=e(s);else if("source"===e){const e="object"==typeof s.source?s.source:null;t&&e?a.fill=le(e.data||e,t,o):e&&(a.fill=n(e,e.index).fill)}else if("target"===e){const e="object"==typeof s.target?s.target:null;t&&e?a.fill=le(e.data||e,t,o):e&&(a.fill=n(e,e.index).fill)}else"gradient"===e&&(a.fill="#999",a.fillOpacity=.7*i);return a}}({edgeColorBy:i.edgeColorBy??"source",colorBy:t,colorScale:d,nodeStyleFn:g,edgeOpacity:i.edgeOpacity??.5,baseStyle:{stroke:"none",strokeWidth:0}});return{chartType:"sankey",nodes:i.nodes,edges:i.edges,nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor,sourceAccessor:i.sourceAccessor,targetAccessor:i.targetAccessor,valueAccessor:i.valueAccessor,orientation:i.orientation,nodeAlign:i.nodeAlign,nodeWidth:i.nodeWidth,nodePaddingRatio:i.nodePaddingRatio,showLabels:i.showLabels,nodeLabel:i.nodeLabel,colorBy:t,edgeColorBy:i.edgeColorBy,edgeOpacity:i.edgeOpacity,nodeStyle:Xt(i.nodeStyle||g,Zt(i)),edgeStyle:Xt(i.edgeStyle||m,Zt(i)),colorScheme:o,...n}}},fr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{if(!(t||Array.isArray(i.styleRules)&&i.styleRules.length>0||n.nodeStyle||i.nodeStyle||Gt(Zt(i))))return{chartType:"chord",nodes:i.nodes,edges:i.edges,valueAccessor:i.valueAccessor,padAngle:i.padAngle,groupWidth:i.groupWidth,showLabels:i.showLabels,colorBy:t,edgeColorBy:i.edgeColorBy,colorScheme:o,...n};const r=Array.isArray(i.edges)?i.edges:[],s=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:dr([],r,i.sourceAccessor||"source",i.targetAccessor||"target"),a=Kt(n.theme).colors.categorical,c=Oe(o,a),u="string"==typeof t?t:"__ssrChordColorBy",d="function"==typeof t?s.map(e=>({...e,__ssrChordColorBy:t(e)})):s,h=t?J(d,u,o??n.colorScheme??a):void 0,p=new Map,g=i.nodeIdAccessor||i.nodeIDAccessor||"id",m=(e,o)=>{const n=e?.data||e;let r;if(t)r=le(n,t,h);else{const t=(e.id??n?.[g]??"")+"";p.has(t)||p.set(t,p.size);const i=e.index??o??p.get(t);r=c[i%c.length]}return{fill:r,stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}},f=l(i.styleRules,t,i.valueAccessor,m)??m;return{chartType:"chord",nodes:i.nodes,edges:i.edges,valueAccessor:i.valueAccessor,padAngle:i.padAngle,groupWidth:i.groupWidth,showLabels:i.showLabels,colorBy:t,edgeColorBy:i.edgeColorBy,colorScheme:o,nodeStyle:Xt(i.nodeStyle||f,Zt(i)),...n}}},yr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrTreeColorBy:l(e)})):a,u=l?"__ssrTreeColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=n.nodeStyle||i.nodeStyle;return{chartType:"cluster"===i.layout?"cluster":"tree",data:e,childrenAccessor:i.childrenAccessor,colorBy:t,colorByDepth:i.colorByDepth,orientation:i.orientation,showLabels:i.showLabels,nodeLabel:!1!==i.showLabels?i.nodeLabel||i.nodeIdAccessor:void 0,colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrTreeColorBy:l(n)},"__ssrTreeColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}},h,Zt(i))}}},br={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrTreemapColorBy:l(e)})):a,u=l?"__ssrTreemapColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=i.showLabels??n.showLabels,p=i.labelMode,g=void 0!==i.paddingTop?i.paddingTop:n.paddingTop,m=void 0!==g?g:!h||"parent"!==p&&"all"!==p?void 0:18,f=n.nodeStyle||i.nodeStyle;return{chartType:"treemap",data:e,childrenAccessor:i.childrenAccessor,hierarchySum:i.valueAccessor,colorBy:t,colorByDepth:i.colorByDepth,showLabels:i.showLabels,labelMode:p,nodeLabel:h?i.nodeLabel||i.nodeIdAccessor:void 0,...null!=i.padding&&{padding:i.padding},...null!=m&&{paddingTop:m},colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrTreemapColorBy:l(n)},"__ssrTreemapColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),stroke:"var(--semiotic-cell-border, var(--semiotic-border, #fff))",strokeWidth:1,strokeOpacity:.8}},f,Zt(i))}}},xr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrCirclePackColorBy:l(e)})):a,u=l?"__ssrCirclePackColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=n.nodeStyle||i.nodeStyle;return{chartType:"circlepack",data:e,childrenAccessor:i.childrenAccessor,hierarchySum:i.valueAccessor,colorBy:t,colorByDepth:i.colorByDepth,showLabels:i.showLabels,nodeLabel:i.showLabels??n.showLabels?i.nodeLabel||i.nodeIdAccessor:void 0,...null!=i.padding&&{padding:i.padding},colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrCirclePackColorBy:l(n)},"__ssrCirclePackColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),fillOpacity:i.circleOpacity??.7,stroke:"currentColor",strokeWidth:1,strokeOpacity:.3}},h,Zt(i))}}},vr={fill:"#f0f0f0",stroke:"#ccc",strokeWidth:.5};import{scaleSequential as wr}from"d3-scale";function Ar(e){return e&&"object"==typeof e&&e.properties?{...e.properties,...e}:e}var Sr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(t,o,n,i,r)=>{const s="string"==typeof n?n:"blues",a=r.areaStyle??function(e,t,o,n){if(!Array.isArray(e))return;const i=e=>"function"==typeof t?t(e):null!=t?e?.properties?.[t]??e?.[t]:void 0;let r=1/0,s=-1/0;for(const t of e){const e=i(t);null!=e&&isFinite(e)&&(r>e&&(r=e),e>s&&(s=e))}const a=wr(yt(o)).domain([Number.isFinite(r)?r:0,Number.isFinite(s)?s:1]);return e=>{const t=i(e);return{fill:null!=t&&isFinite(t)?a(t):"#ccc",stroke:"#999",strokeWidth:.5,fillOpacity:n}}}(r.areas,r.valueAccessor,s,r.areaOpacity??1),l=r.styleRules?e(a,r.styleRules,e=>{return{value:(t=e,"function"==typeof r.valueAccessor?r.valueAccessor(t):null!=r.valueAccessor?t?.properties?.[r.valueAccessor]??t?.[r.valueAccessor]:void 0)};var t},Ar):a;return{areas:r.areas,projection:r.projection||"equalEarth",areaStyle:l,valueAccessor:r.valueAccessor,colorScheme:s,graticule:r.graticule,fitPadding:r.fitPadding,...i}}},kr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(t,o,n,r,s)=>{const a=t||s.points,l=s.pointStyle??function(e,t,o,n){const i=Array.isArray(e)?e:[];let r,s;if(t){const e="string"==typeof t?t:"__geoColorBy",n="string"==typeof t?i:i.map(e=>({...e,__geoColorBy:t(e)}));r=J(n,e,o)}if(n.sizeBy){const e=i.map("function"==typeof n.sizeBy?n.sizeBy:e=>e?.[n.sizeBy]).filter(e=>null!=e&&isFinite(e));e.length>0&&(s=Ot(e))}return e=>({fill:t&&r?le(e,t,r):R,fillOpacity:n.fillOpacity,stroke:"#fff",strokeWidth:n.strokeWidth,r:n.sizeBy?de(e,n.sizeBy,n.sizeRange,s):n.pointRadius??6})}(a,o,n,{sizeBy:s.sizeBy,sizeRange:s.sizeRange||[3,30],fillOpacity:.7,strokeWidth:.5}),c=s.styleRules?e(l,s.styleRules,i(o,s.sizeBy)):l;return{points:a,xAccessor:s.xAccessor||"lon",yAccessor:s.yAccessor||"lat",areas:s.areas,areaStyle:s.areaStyle||vr,pointStyle:c,sizeBy:s.sizeBy,colorBy:o,colorScheme:n,projection:s.projection||"equalEarth",graticule:s.graticule,fitPadding:s.fitPadding,...r}}},Mr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(e,t,o,n,i)=>{const r=(Array.isArray(e)?e:null)||i.flows||[],s=i.nodeIdAccessor||"id",a=i.valueAccessor||"value",l=i.xAccessor||"lon",c=i.yAccessor||"lat",u="function"==typeof l?l:e=>e[l],d="function"==typeof c?c:e=>e[c],h=(i.nodes||[]).map(e=>({...e,x:u(e),y:d(e)})),p=new Map;for(const e of h)p.set(e[s]+"",e);const g=i.edgeColorBy??t,m="function"==typeof g,f=r.map(e=>{if(!e||null==e.source||null==e.target)return null;const t=p.get(e.source+""),o=p.get(e.target+"");return t&&o?{...e,coordinates:[{x:t.x,y:t.y},{x:o.x,y:o.y}]}:null}).filter(Boolean),y="__flowMapEdgeColor",b=(()=>{if(!g)return null;if(m){const e=f.map(e=>({[y]:g(e)}));return J(e,y,o||"category10")}return J(f,g,o||"category10")})(),x=e=>g&&b?le(e,g,b):"#007bff";let v=1/0,w=-1/0;for(const e of f){const t=Number(e[a]??0);isFinite(t)&&(v>t&&(v=t),t>w&&(w=t))}const A=w>v?w-v:0,[S,k]=i.edgeWidthRange??[1,8],M=k-S,_=i.edgeOpacity??.6,P=i.edgeLinecap??"round";return{lines:f,points:h,xAccessor:"x",yAccessor:"y",lineDataAccessor:"coordinates",lineType:i.lineType||"geo",flowStyle:i.flowStyle||"basic",areas:i.areas,areaStyle:i.areaStyle||vr,projection:i.projection||"equalEarth",graticule:i.graticule,fitPadding:i.fitPadding,colorScheme:o,lineStyle:e=>{const t=Number(e?.[a]),o=Number.isFinite(t)?t:v,n=S+Math.max(0,Math.min(1,A>0?(o-v)/A:0))*M;return{stroke:x(e),strokeWidth:n,strokeLinecap:P,opacity:_,fillOpacity:0}},pointStyle:()=>({fill:"#333",r:4,fillOpacity:.8}),...n}}};import*as _r from"react";function Pr(e){const[t,o]=e,n=160>t||116>o,i=n?Math.min(12,Math.max(2,.08*t)):32,r=n?Math.min(8,Math.max(2,.12*o)):24,s=n?r:34;return{width:t,height:o,plot:{x:i,y:r,width:Math.max(1,t-2*i),height:Math.max(1,o-r-s)}}}function Tr(e){const t=(e??"")+"";if(!t)return"#4e79a7";const o=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let n=0;for(let e=0;t.length>e;e+=1)n=31*n+t.charCodeAt(e)>>>0;return o[n%o.length]}function Lr(e,t="#4e79a7",o){const n=o?.styleRules,i=!!n&&n.length>0,s=i?r(o?.valueAccessor):void 0;return o=>{const r=o.datum,l=r&&e?"function"==typeof e?e(r,0):r[e]:void 0,c={fill:null==l?t:Tr(l),stroke:"#111827",strokeWidth:1,opacity:.9};return i&&r&&Object.assign(c,a(r,n,{value:s?s(r):void 0,category:null==l?void 0:l+""})),c}}function Rr(e,t,o,n){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:o},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...n}}}function Ir(e,t,o){return"function"==typeof o?o(e,t):e[o]}function Cr(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function zr(e,t,o){return Math.max(t,Math.min(o,e))}function Fr(e,t){const o=Cr(e);return null!=o&&o>0?o:t}function Or(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Br(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}import{scaleLinear as Nr}from"d3-scale";import{scaleLinear as Er}from"d3-scale";function jr(e){const{count:t,idPrefix:o,wallThickness:n,xScale:i,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const l=Math.min(r-1,a?.(t)??s),c=Math.max(1,r-l);return{id:`${o}-wall-${t}`,shape:{type:"aabb",x:i(t),y:l+c/2,width:n,height:c}}})}import{scaleLinear as $r}from"d3-scale";function Dr(e){if(Array.isArray(e)&&e.length>=2){const t=Cr(e[0]),o=Cr(e[1]);return null!=t&&null!=o?{x:t,y:o}:null}if(e&&"object"==typeof e){const t=e,o=Cr(t.x),n=Cr(t.y);return null!=o&&null!=n?{x:o,y:n}:null}return null}function Wr(e){return Array.isArray(e)?e.map(Dr).filter(e=>null!=e):[]}function Yr(e,t,o){return"normalized"===o?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:zr(e.x,t.plot.x,t.plot.x+t.plot.width),y:zr(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Hr(e){let t=0;for(let o=1;e.length>o;o+=1)t+=Math.hypot(e[o].x-e[o-1].x,e[o].y-e[o-1].y);return t}function Vr(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const o=zr(t,0,1)*Hr(e);let n=0;for(let t=1;e.length>t;t+=1){const i=e[t-1],r=e[t],s=Math.hypot(r.x-i.x,r.y-i.y);if(s>0){if(n+s>=o){const e=(o-n)/s;return{x:i.x+(r.x-i.x)*e,y:i.y+(r.y-i.y)*e}}n+=s}}return{...e[e.length-1]}}function Gr(e,t){const o=Vr(e,Math.max(0,t-.02)),n=Vr(e,Math.min(1,t+.02)),i=n.x-o.x,r=n.y-o.y,s=Math.hypot(i,r)||1;return{x:i/s,y:r/s}}function Xr(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}import{scaleLinear as qr}from"d3-scale";function Ur(e,t){const o=t.config??{},n=(t.sensors??[]).map(e=>({...e,sensor:!0})),i=[...t.colliders??[],...n],r=[...e.colliders??[],...o.colliders??[],...i];return{...e,...o,observation:{...e.observation,...o.observation},...r.length>0&&{colliders:r}}}function Qr(e){const t=os(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function Zr(e,t,o,n){return o?"function"==typeof o?o(e,t):e[o]??n:n}function Kr(e){return`gauntlet:${e}:core`}function Jr(e,t){return`gauntlet:${e}:positive:${t}`}function es(e,t,o){return`gauntlet:${e}:negative:${t}:${o}`}var ts={left:28,top:76,rightInset:30,thickness:8};function os(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return ts;const o=Math.max(1,Math.min(e.width,t)),n=Math.max(2,.04*e.width);return{left:n,top:Math.max(2,.08*t),rightInset:n,thickness:Math.max(1,Math.min(4,.04*o))}}function ns(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function is(e,t,o,n){const i=os(n),r=Math.max(2,o+2),s=i.top+i.thickness/2+r,a=n.floorY-r,l=(e,t,o)=>t>o?(t+o)/2:Math.max(t,Math.min(o,e));return{x:l(e,i.left+i.thickness/2+r,n.width-i.rightInset-i.thickness/2-r),y:l(t,s,a)}}function rs(e,t,o=1){const n=[...e].sort((e,t)=>e.localeCompare(t)),i=Math.max(0,n.indexOf(t));return{angle:.82*-Math.PI+(n.length>1?i/(n.length-1):.5)*Math.PI*.64,index:i,radius:(48+i%2*6)*o}}function ss(e,t,o){const n=e.activePositiveIds.reduce((e,o)=>e+(t.get(o)?.value??1),0),i=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(o.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*n-8*r-1.2*e.delay-5*i))}function as(e){const t=function(e,t,o){const[n,i]=e,r=220>n||160>i,s=Math.round(.48*i),a=r?i-Math.max(3,Math.min(12,.1*i)):i-36,l=(t??[]).filter(e=>!1!==e.enabled),c=Math.max(1,l.length),u=.22*n,d=c>1?(.78*n-u)/(c-1):0,h=r?Math.max(Math.round(.12*n),.08*n+6):Math.max(Math.round(.14*n),110);return{crashY:a-(r?Math.min(o,Math.max(3,.22*i)):o),floorY:a,gates:l.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(u+t*d),width:e.width??Math.max(r?8:54,Math.round(.07*n))})),graveyardX:Math.round(n*(r?.72:.84)),graveyardY:a-4,height:i,routeY:s,socketX:Math.round(n*(r?.82:.92)),startX:h,width:n}}(e.size??[900,520],e.gates,e.crashOffset??30),o=e.positiveProperties??[],n=new Map(o.map(e=>[e.id,e])),i=new Map((e.negativeProperties??[]).map(e=>[e.id,e])),r={idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor},s=(e.data??[]).map((t,s)=>{const a=function(e,t,o,n,i){const r=Zr(e,t,o.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=n.map(e=>e.id),a=[...Zr(e,t,o.positiveAccessor,s)],l=[...Zr(e,t,o.negativeAccessor,[])].filter(e=>i.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Zr(e,t,o.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:l,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Zr(e,t,o.startTimeAccessor,0))||0),stage:"project filed",viability:Zr(e,t,o.initialViability,100)}}(t,s,r,o,i);return{...a,viability:e.viability?.(a,{negativeProperties:i,positiveProperties:n})??ss(a,n,i)}}),a=s.flatMap((o,r)=>{const s=function(e,t,o,n){const i=function(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}(o),r=n?.(e,t,o)??{};return{...i,...r,startY:r.startY??r.routeY??i.startY,socketY:r.socketY??r.routeY??i.socketY,graveyardY:r.graveyardY??i.graveyardY}}(o,r,t,e.projectPlacement);return function(e,t,o,n,i,r,s){const a=ns(o),l=Math.max(3,28*a),c=n.startX,u=n.startY+(n.startY===o.routeY?38*t*a:0),d=s?.(e,t,o,n)??{},h=d.x??c,p=d.y??u,g={__gauntlet:!0,kind:"gauntlet-core",projectId:e.id,sourceDatum:e.datum},m=[{...d,id:Kr(e.id),x:h,y:p,vx:d.vx??42,vy:d.vy??0,mass:d.mass??7,bodyCollisions:d.bodyCollisions??!0,shape:d.shape??{type:"circle",radius:l},spawnAt:d.spawnAt??e.startedAt,datum:g}],f=is(h,p,d.shape&&"radius"in d.shape&&Number(d.shape.radius)||l,o);m[0].x=f.x,m[0].y=f.y;for(const t of e.activePositiveIds){const n=i.get(t);if(!n)continue;const r=rs(e.activePositiveIds,t,a),s=n.radius??Math.max(2,10*a),l=is(f.x+Math.cos(r.angle)*r.radius,f.y+Math.sin(r.angle)*r.radius,s,o);m.push({id:Jr(e.id,t),x:l.x,y:l.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:n.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:d.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:"gauntlet-positive",projectId:e.id,property:n,sourceDatum:e.datum},springs:!1===n.spring?[]:[{target:{type:"body",bodyId:Kr(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...n.spring??{}}]})}return e.negativeIds.forEach((t,n)=>{const i=r.get(t);i&&m.push(function(e,t,o,n,i,r,s){const a=ns(r),l=t.radius??Math.max(2,7.2*a),c=is(n+(o%4*12-12)*a,i+(54+12*Math.floor(o/4))*a,l,r);return{id:es(e.id,t.id,o),x:c.x,y:c.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:l},spawnAt:s,datum:{__gauntlet:!0,kind:"gauntlet-negative",projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Kr(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+o%4*3)*a),...t.spring??{}}]}}(e,i,n,f.x,f.y,o,d.spawnAt??e.startedAt))}),m}(o,r,t,s,n,i,e.coreBody)});return{layout:t,initialSpawns:a,config:{fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7},colliders:Qr(t)}}}var ls=1e-9;function cs(e,t){return t>e?-1:e>t?1:0}function us(e){return{...e}}function ds(e){return e.map(e=>({...e,sourceIds:e.sourceIds?[...e.sourceIds]:void 0,productIds:e.productIds?[...e.productIds]:void 0,relationIds:e.relationIds?[...e.relationIds]:void 0,outletIds:e.outletIds?[...e.outletIds]:void 0}))}function hs(e){const t=Object.fromEntries(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:us(t.initialMetrics),metrics:us(t.metrics),productIds:[...t.productIds],history:ds(t.history)}])),o=Object.fromEntries(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:us(t.metrics),sourceIds:[...t.sourceIds],history:ds(t.history)}])),n=Object.fromEntries(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?us(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:o,relations:n,input:{amount:e.input.amount,metrics:us(e.input.metrics)},metrics:us(e.metrics),loss:{amount:e.loss.amount,metrics:us(e.loss.metrics)},history:ds(e.history)}}function ps(e,t,o,n,i){return{severity:e,code:t,message:o,path:n,ids:i?[...i]:void 0}}function gs(e){const t=new Set,o=new Set;for(const n of e)t.has(n)&&o.add(n),t.add(n);return[...o].sort(cs)}function ms(e,t){return e?Object.entries(e).flatMap(([e,o])=>Number.isFinite(o)?[]:[ps("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function fs(e,t){for(const[o,n]of Object.entries(t))e[o]=Number(e[o]??0)+n}function ys(e,t,o="selector"){const n=[],i=Object.values(e.components),r=new Set(i.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&n.push(ps("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,o+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||n.push(ps("error","invalid-selector-count","Selector count must be a non-negative integer.",o+".count")),n.some(e=>"error"===e.severity))return{ids:[],diagnostics:n};const a=t.ids?new Set(t.ids):null,l=t.categories?new Set(t.categories):null,c=t.statuses?new Set(t.statuses):null,u=t.outletIds?new Set(t.outletIds):null;let d=i.filter(e=>!a||a.has(e.id)).filter(e=>!l||l.has(e.category)).filter(e=>!c||c.has(e.status)).filter(e=>!u||void 0!==e.outletId&&u.has(e.outletId)).map(e=>e.id).sort(cs);return void 0!==t.count&&(d=d.slice(0,t.count)),d.length||n.push(ps("warning","empty-selector","Selector matched no source components.",o)),{ids:d,diagnostics:n}}function bs(e,t,o={}){return{eventId:e.event.id,effectType:t.type,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,label:e.event.label,summary:e.event.summary,...o}}function xs(e,t){const o={...t,eventId:e.event.id};e.materializations.push(o),e.observations.push({...o,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function vs(e,t,o){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(ps("error","unknown-outlet",`Unknown outlet "${t}".`,o,[t])),1))}function ws(e,t,o){const n=gs(t);t.length||e.diagnostics.push(ps("error","empty-source-list","A product requires at least one source component.",o)),n.length&&e.diagnostics.push(ps("error","duplicate-source",`Source ids may appear only once: ${n.join(", ")}.`,o,n));const i=t.filter(t=>!e.state.components[t]);i.length&&e.diagnostics.push(ps("error","unknown-component",`Unknown source component id${1===i.length?"":"s"}: ${i.join(", ")}.`,o,i));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,o,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(ps("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,o,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function As(e,t,o,n,i){const r=n?.amount??0;(!Number.isFinite(r)||0>r||r>t+ls)&&e.diagnostics.push(ps("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",i+".amount")),e.diagnostics.push(...ms(n?.metrics,i+".metrics"));for(const[t,r]of Object.entries(n?.metrics??{}))(0>r||r>Number(o[t]??0)+ls)&&e.diagnostics.push(ps("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${i}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function Ss(e,t,o,n,i,r,s){return{id:e.id,label:e.label??e.id,description:e.description,category:e.category??"product",color:e.color,order:e.order,declaredAmount:e.amount,amount:r&&void 0!==e.amount?e.amount:o,metrics:r&&e.metrics?{...n,...e.metrics}:n,status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(i.outletIds.has("product")?"product":void 0):void 0,createdByEventId:i.event.id,createdAt:i.context.appliedAt,completedByEventId:r?i.event.id:void 0,completedAt:r?i.context.appliedAt:void 0,history:[s]}}function ks(e,t,o,n){void 0!==t.amount&&Math.abs(t.amount-o)>ls&&e.diagnostics.push(ps("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${o}.`,n,[t.id]))}function Ms(e,t,o){const n=`events.${e.event.id}.effects.${o}`,i=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(ps("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,n+".state")),e.diagnostics.push(...ms(t.metricsDelta,n+".metricsDelta")),vs(e,t.outletId,n+".outletId");const o=ys(i,t.select,n+".select");e.diagnostics.push(...o.diagnostics);const r=o.ids.filter(e=>i.components[e].productIds.length);if(r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,n+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=bs(e,t,{sourceIds:o.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of o.ids){const o=i.components[e];o.status=t.state,o.outletId=t.outletId,o.reason=t.reason,t.metricsDelta&&fs(o.metrics,t.metricsDelta),o.history.push(s)}return i.history.push(s),void(o.ids.length&&xs(e,{type:"retarget-component",sourceIds:o.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:o}=t;o.id&&!i.relations[o.id]||e.diagnostics.push(ps("error","duplicate-relation",`Relation id "${o.id}" is missing or already active.`,n+".relation.id",[o.id]));const r=function(e,t,o){const n=gs(t),i=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(ps("error","insufficient-relation-sources","A relation requires at least two source components.",o)),n.length&&e.diagnostics.push(ps("error","duplicate-source",`Relation source ids must be unique: ${n.join(", ")}.`,o,n)),i.length&&e.diagnostics.push(ps("error","unknown-component",`Relation references unknown source component${1===i.length?"":"s"}: ${i.join(", ")}.`,o,i)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,o.sourceIds,n+".relation.sourceIds");if(e.diagnostics.push(...ms(o.metrics,n+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;i.relations[o.id]={...o,sourceIds:[...o.sourceIds],metrics:o.metrics?{...o.metrics}:void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=bs(e,t,{sourceIds:[...o.sourceIds],relationIds:[o.id]});return i.history.push(s),void xs(e,{type:"activate-relation",sourceIds:[...o.sourceIds],relationIds:[o.id]})}if("resolve-relation"===t.type){const o=gs(t.relationIds),r=t.relationIds.filter(e=>!i.relations[e]),s=t.relationIds.filter(e=>"resolved"===i.relations[e]?.status);if(o.length&&e.diagnostics.push(ps("error","duplicate-relation","Relation ids must be unique.",n+".relationIds",o)),r.length&&e.diagnostics.push(ps("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,n+".relationIds",r)),s.length&&e.diagnostics.push(ps("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,n+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const o of t.relationIds){const n=i.relations[o];n.status="resolved",n.resolution=t.resolution,n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt,n.reason=t.reason}const a=bs(e,t,{relationIds:[...t.relationIds]});return i.history.push(a),void xs(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const o=e.productDefinitions.get(t.productId);o||e.diagnostics.push(ps("error","unknown-product",`Product "${t.productId}" has no declared mold.`,n+".productId",[t.productId]));const r=i.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(ps("error","duplicate-product",`Product "${t.productId}" has already been formed.`,n+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(ps("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,n+".productId",[t.productId]));const s=ws(e,t.sourceIds,n+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,l=function(e,t,o,n){if(!t?.length)return[];const i=gs(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(o),l=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return i.length&&e.diagnostics.push(ps("error","duplicate-relation","Basis relations must be unique.",n,i)),r.length&&e.diagnostics.push(ps("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,n,r)),s.length&&e.diagnostics.push(ps("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,n,s)),l.length&&e.diagnostics.push(ps("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${l.join(", ")}.`,n,l)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,n+".basisRelationIds");if(!s||!l||!o||e.diagnostics.some(e=>"error"===e.severity))return;const c=s.reduce((e,t)=>e+t.amount,0),u=function(e){const t={};for(const o of e)fs(t,o.metrics);return t}(s);if(!As(e,c,u,t.loss,n+".loss"))return;const d=c-(t.loss?.amount??0);!function(e,t,o){e.state.loss.amount+=o?.amount??0;for(const[n,i]of Object.entries(o?.metrics??{}))t[n]=Number(t[n]??0)-i,e.state.loss.metrics[n]=Number(e.state.loss.metrics[n]??0)+i}(e,u,t.loss);const h="combine"===t.type&&!1!==t.complete,p=bs(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let g;if("combine"===t.type){if(h&&ks(e,o,d,n+".productId"),g=Ss(o,t.sourceIds,d,u,e,h,p),h&&!vs(e,g.outletId,n+".productId"))return;i.products[t.productId]=g}else g=r,g.sourceIds.push(...t.sourceIds),g.amount+=d,fs(g.metrics,u),g.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return i.history.push(p),function(e,t){if(t.length){for(const o of t)o.status="resolved",o.resolution="combined",o.resolvedByEventId=e.event.id,o.resolvedAt=e.context.appliedAt;xs(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,l),xs(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:g.outletId?[g.outletId]:void 0}),void(h&&xs(e,{type:"complete-product",sourceIds:[...g.sourceIds],productIds:[g.id],outletIds:g.outletId?[g.outletId]:void 0}))}if("complete-product"===t.type){const o=i.products[t.productId];return o?void function(e,t,o,n,i,r){const s=e.productDefinitions.get(t.id),a=o??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!vs(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(ps("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(ks(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics={...t.metrics,...s.metrics})),t.status="complete",t.outletId=a,t.reason=n,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const l=bs(e,i,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(l),e.state.history.push(l),xs(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,o,t.outletId,t.reason,t,n):void e.diagnostics.push(ps("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,n+".productId",[t.productId]))}if("split"===t.type){const o=ws(e,[t.sourceId],n+".sourceId");t.products.length||e.diagnostics.push(ps("error","empty-split","A split requires at least one product allocation.",n+".products"));const r=t.products.map(e=>e.productId),s=gs(r);s.length&&e.diagnostics.push(ps("error","duplicate-product","Split product ids must be unique.",n+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),l=r.filter((e,t)=>!a[t]),c=r.filter(e=>i.products[e]);l.length&&e.diagnostics.push(ps("error","unknown-product",`Split references undeclared product molds: ${l.join(", ")}.`,n+".products",l)),c.length&&e.diagnostics.push(ps("error","duplicate-product",`Split products already exist: ${c.join(", ")}.`,n+".products",c));for(const[o,i]of t.products.entries())void 0===i.amount||Number.isFinite(i.amount)&&i.amount>=0||e.diagnostics.push(ps("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${n}.products.${o}.amount`)),e.diagnostics.push(...ms(i.metrics,`${n}.products.${o}.metrics`));if(!o?.length||e.diagnostics.some(e=>"error"===e.severity))return;const u=o[0];if(!As(e,u.amount,u.metrics,t.loss,n+".loss"))return;const d=u.amount-(t.loss?.amount??0),h=t.products.map((e,t)=>e.amount??a[t]?.amount),p=h.filter(e=>void 0!==e).length;if(0!==p&&p!==h.length)return void e.diagnostics.push(ps("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",n+".products"));const g=p?h:t.products.map(()=>d/t.products.length),m=g.reduce((e,t)=>e+t,0);if(Math.abs(m-d)>ls)return void e.diagnostics.push(ps("error","split-amount-mismatch",`Split allocations total ${m}, but ${d} remains after loss.`,n+".products"));const f={...u.metrics};for(const[e,o]of Object.entries(t.loss?.metrics??{}))f[e]=Number(f[e]??0)-o;const y=bs(e,t,{sourceIds:[u.id],productIds:r});if(t.products.forEach((o,r)=>{const s=a[r],l=d>ls?g[r]/d:1/t.products.length,c=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,t*l])),h=o.metrics??s.metrics??c,p=Ss({...s,amount:g[r],metrics:h},[u.id],g[r],{...h},e,!0,y);vs(e,p.outletId,`${n}.products.${r}.productId`)&&(i.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;u.productIds=r,u.status="consumed",u.outletId=void 0,u.history.push(y),i.loss.amount+=t.loss?.amount??0;for(const[e,o]of Object.entries(t.loss?.metrics??{}))i.loss.metrics[e]=Number(i.loss.metrics[e]??0)+o;i.history.push(y),xs(e,{type:"split-source",sourceIds:[u.id],productIds:r});for(const t of r)xs(e,{type:"complete-product",sourceIds:[u.id],productIds:[t],outletIds:i.products[t].outletId?[i.products[t].outletId]:void 0});return}if("eject"===t.type){vs(e,t.outletId,n+".outletId");const o=ys(i,t.select,n+".select");e.diagnostics.push(...o.diagnostics);const r=o.ids.filter(e=>i.components[e].productIds.length);if(r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,n+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=bs(e,t,{sourceIds:o.ids,outletIds:[t.outletId]});for(const e of o.ids){const o=i.components[e];o.status=t.state??"ejected",o.outletId=t.outletId,o.reason=t.reason,o.history.push(s)}return i.history.push(s),void(o.ids.length&&xs(e,{type:"retarget-component",sourceIds:o.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...ms(t.metricsDelta,n+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let o,r;if("run"===t.target)fs(i.metrics,t.metricsDelta);else if("components"in t.target){const r=ys(i,t.target.components,n+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;o=r.ids;for(const e of r.ids)fs(i.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const o=gs(r),s=r.filter(e=>!i.products[e]);if(o.length&&e.diagnostics.push(ps("error","duplicate-product","Metric target product ids must be unique.",n+".target.productIds",o)),s.length&&e.diagnostics.push(ps("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,n+".target.productIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const e of r)fs(i.products[e].metrics,t.metricsDelta)}return void i.history.push(bs(e,t,{sourceIds:o,productIds:r}))}t.outcome.trim()?(i.outcome=t.outcome,i.summary=t.summary,i.history.push(bs(e,t)),e.observations.push({type:"crucible-outcome",eventId:e.event.id,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,outcome:t.outcome})):e.diagnostics.push(ps("error","invalid-outcome","Outcome must be a non-empty string.",n+".outcome"))}function _s(e,t,o){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[ps("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const n=hs(e),i={state:n,event:t,context:o,productDefinitions:new Map(o.products.map(e=>[e.id,e])),outletIds:new Set(o.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[o,n]of t.effects.entries())if(Ms(i,n,o),i.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:i.diagnostics};return n.elapsed=Math.max(n.elapsed,o.appliedAt),n.phaseId=o.phaseId,n.eventsApplied.push(t.id),i.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:o.phaseId,authoredAt:o.authoredAt,appliedAt:o.appliedAt}),{applied:!0,state:n,materializations:i.materializations,observations:i.observations,diagnostics:i.diagnostics}}var Ps=[900,520],Ts=[{id:"product",label:"Products",side:"bottom",order:0},{id:"retained",label:"Retained",side:"bottom",order:1},{id:"residue",label:"Residue",side:"left",order:2},{id:"failed",label:"Failed",side:"right",order:3},{id:"recovered",label:"Recovered",side:"right",order:4}],Ls=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Rs=1e-9;function Is(e,t){return t>e?-1:e>t?1:0}function Cs(e,t,o,n,i){return{severity:e,code:t,message:o,path:n,ids:i?[...i]:void 0}}function zs(e){const t=new Set,o=new Set;for(const n of e)t.has(n)&&o.add(n),t.add(n);return[...o].sort(Is)}function Fs(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Os(e,t,o,n,i,r){if(!o)return n;try{return("function"==typeof o?o(e,t):e[o])??n}catch(e){return i.push(Cs("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),n}}function Bs(e,t,o){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(Cs("error","invalid-metrics","Metrics must be a numeric object.",o)),{};const n={};for(const[i,r]of Object.entries(e)){const e=Fs(r);null!=e?n[i]=e:t.push(Cs("error","invalid-metric",`Metric "${i}" must be finite.`,`${o}.${i}`))}return n}function Ns(e){return e.map((e,t)=>({outlet:e,index:t})).sort((e,t)=>(e.outlet.order??e.index)-(t.outlet.order??t.index)||e.index-t.index).map(({outlet:e})=>({...e}))}function Es(e){const{id:t,orientation:o,fixed:n,start:i,end:r,openings:s,thickness:a,friction:l,restitution:c}=e,u=function(e,t,o){const n=o.map(([o,n])=>[Math.max(e,Math.min(o,n)),Math.min(t,Math.max(o,n))]).filter(([e,t])=>t>e+Rs).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),i=[];let r=e;for(const[e,t]of n)e>r+Rs&&i.push([r,e]),r=Math.max(r,t);return t>r+Rs&&i.push([r,t]),i}(i,r,s);return u.map(([e,i],r)=>({id:1===u.length?t:`${t}:${r}`,friction:l,restitution:c,shape:"horizontal"===o?{type:"segment",x1:e,y1:n,x2:i,y2:n,thickness:a}:{type:"segment",x1:n,y1:e,x2:n,y2:i,thickness:a}}))}function js(e){let t=2166136261;for(let o=0;e.length>o;o+=1)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return t>>>0}function $s(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?js(e):1}function Ds(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:$s(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function Ws(e){return"crucible:component:"+encodeURIComponent(e)}function Ys(e,t,o,n){if(void 0!==o&&Number.isFinite(o)&&o>0)return o;const i=Math.min(...t,e),r=Math.max(...t,e);return r-i>Rs?n[0]+(n[1]-n[0])*Math.sqrt(Math.max(0,e-i)/(r-i)):(n[0]+n[1])/2}function Hs(e,t){const o=Math.max(.25,Math.min(1,t.width/900,t.height/520)),n=e?.[0]??7*o,i=e?.[1]??18*o,r=Math.max(1,Math.min(n,i));return[r,Math.max(r,Math.max(n,i))]}function Vs(e,t){if(!e)return[];const o=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),n=Math.max(1,Math.ceil(e/o));return Array.from({length:e},(e,i)=>({x:t.x+t.width/o*(i%o+.5),y:t.y+(Math.floor(i/o)+.5)*(t.height/n)}))}function Gs(e){return e.outletId?e.outletId:"failed"===e.status?"failed":"recovered"===e.status?"recovered":"retained"===e.status?"retained":"ejected"===e.status?"residue":void 0}function Xs(e,t){return e.outlets.find(e=>e.id===t)||{x:e.chamber.x+.18*e.chamber.width,y:e.chamber.y+.2*e.chamber.height,width:.64*e.chamber.width,height:.6*e.chamber.height}}function qs(e,t,o={}){const n=Object.values(e.products).sort((e,t)=>Is(e.id,t.id)),i=Object.values(e.components).sort((e,t)=>Is(e.id,t.id)),r=[...i.map(e=>e.amount),...n.map(e=>e.amount)],s=Hs(o.radiusRange,t),a=function(e,t){const o=new Map;for(const t of e){const e=t.outletId??"__chamber__",n=o.get(e)??[];n.push(t),o.set(e,n)}const n=new Map;for(const[e,i]of o){i.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Is(e.id,t.id));const o=Vs(i.length,Xs(t,"__chamber__"===e?void 0:e));i.forEach((e,t)=>n.set(e.id,o[t]))}return n}(n,t),l=n.map(e=>{const n=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},i=1.28*Ys(e.amount,r,o.bodyRadius,s),l={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:(c=e.id,"crucible:product:"+encodeURIComponent(c)),x:n.x,y:n.y,mass:Math.max(.25,i*i*.018),bodyCollisions:!1,shape:{type:"circle",radius:i},datum:l};var c}),c=new Map;for(const e of i.filter(e=>!e.productIds.length)){const t=Gs(e)??"__chamber__",o=c.get(t)??[];o.push(e),c.set(t,o)}const u=new Map;for(const[e,o]of c){const n=Vs(o.length,Xs(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>u.set(e.id,n[t]))}return[...i.map(e=>{let n=u.get(e.id);if(e.productIds.length){const o=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(o.length){n={x:o.reduce((e,t)=>e+t.x,0)/o.length,y:o.reduce((e,t)=>e+t.y,0)/o.length};const i=js(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));n={x:n.x+Math.cos(i)*r,y:n.y+Math.sin(i)*r}}}n??(n={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const i=Ys(e.amount,r,o.bodyRadius,s),l={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:Ws(e.id),x:n.x,y:n.y,mass:Math.max(.25,i*i*.015),shape:{type:"circle",radius:i},datum:l}}),...l]}var Us=qs;function Qs(e){return Array.isArray(e)?e.map(Qs):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Is(e,t)).map(([e,t])=>[e,Qs(t)])):e}function Zs(e,t=e.duration){const o=function(e,t){const o=Fs(t)??0,n=Math.max(0,Math.min(e.duration,o));if(!e.phases.length)return{elapsed:n,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const i=n>=e.duration-Rs,r=i?e.phases[e.phases.length-1]:e.phases.find(e=>n>=e.start&&e.end>n)??e.phases[0];return{elapsed:n,phaseId:r.id,phaseIndex:r.index,phaseElapsed:i?r.duration:Math.max(0,n-r.start),complete:i}}(e,t);let n=hs(e.initialState);const i=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>o.elapsed+Rs)break;const a=_s(n,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});i.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(n=a.state)}return n.elapsed=o.elapsed,n.phaseId=o.phaseId,n.phaseIndex=o.phaseIndex,n.phaseElapsed=o.phaseElapsed,n.complete=o.complete,o.complete&&"in_process"===n.outcome&&(n.outcome="complete"),n.playing=!1,{state:n,diagnostics:i,materializations:r,observations:s}}function Ks(e){const t=function(e){const t=[];e.length||t.push(Cs("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const o=zs(e.map(e=>e.id));o.length&&t.push(Cs("error","duplicate-phase-id",`Phase ids must be unique: ${o.join(", ")}.`,"phases",o));let n=0;return{phases:e.map((e,o)=>{const i=Fs(e.duration),r=null!=i&&i>0?i:0;e.id.trim()||t.push(Cs("error","invalid-phase-id","Phase ids may not be empty.",`phases.${o}.id`)),null!=i&&i>0||t.push(Cs("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${o}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(Cs("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${o}.intensity`,[e.id]));const s={...e,duration:r,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:o,start:n,end:n+r};return n=s.end,s}),diagnostics:t}}(e.phases),o=t.phases.at(-1)?.end??0,n=Ns(e.outlets??Ts),i=(e.products??[]).map(e=>({...e,metrics:e.metrics?{...e.metrics}:void 0})),r=function(e,t,o){const n=[],i=zs(e.map(e=>e.id));i.length&&n.push(Cs("error","duplicate-event-id",`Event ids must be unique: ${i.join(", ")}.`,"events",i));const r=[];return e.forEach((e,i)=>{let s,a,l;if(e.id.trim()||n.push(Cs("error","invalid-event-id","Event ids may not be empty.",`events.${i}.id`)),"time"in e.at&&void 0!==e.at.time){const r=Fs(e.at.time);if(null==r||0>r||r>o+Rs)return void n.push(Cs("error","event-time-out-of-range",`Event time must fall between 0 and ${o}.`,`events.${i}.at.time`,[e.id]));s=Math.max(0,Math.min(o,r));const c=function(e,t,o){const n=e.find(e=>Rs>=Math.abs(e.start-o));if(n)return{phase:n,boundaryRank:1};const i=e.find(e=>o>=e.start&&e.end>o);return i?{phase:i,boundaryRank:0}:Rs>=Math.abs(o-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,o,s);a=c.phase,l=c.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void n.push(Cs("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${i}.at.phaseId`,[e.id,e.at.phaseId]));const o=e.at.progress??0;if(!Number.isFinite(o)||0>o||o>1)return void n.push(Cs("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${i}.at.progress`,[e.id]));s=a.start+a.duration*o,l=0===o?1:0}a?r.push({...e,index:i,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:l}):n.push(Cs("error","event-without-phase","Event could not be assigned to a phase.",`events.${i}.at`,[e.id]))}),r.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:r,diagnostics:n}}(e.events??[],t.phases,o),s=function(e){const t=[],o={},n=[];let i=0;const r={};e.data.forEach((s,a)=>{const l=(s.id??"component-"+a)+"",c=((Os(s,a,e.idAccessor,l,t,`data.${a}.id`)??l)+"").trim();if(!c)return void t.push(Cs("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));n.push(c);const u=Fs(Os(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),d=null==u||0>u?0:u;(null==u||0>u)&&t.push(Cs("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[c]));const h=Bs(Os(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=Os(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),g=Ls.has(p)?p:"active";Ls.has(p)||t.push(Cs("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[c]));const m=Os(s,a,e.labelAccessor,(s.label??s.name??c)+"",t,`data.${a}.label`)+"",f=Os(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";o[c]||(o[c]={id:c,label:m,category:f,datum:s,status:g,initialAmount:d,amount:d,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},i+=d,function(e,t){for(const[o,n]of Object.entries(t))e[o]=Number(e[o]??0)+n}(r,h))});const s=zs(n);s.length&&t.push(Cs("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=Bs(e.metrics??{},t,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:e.phases[0]?.id??"",phaseIndex:e.phases.length?0:-1,playing:!1,complete:0===e.phases.length,outcome:"in_process",eventsApplied:[],components:o,products:{},relations:{},input:{amount:i,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:t}}(e),a=function(e=Ps,t=Ts){const o=Math.max(1,Fs(e[0])??900),n=Math.max(1,Fs(e[1])??520),i=360>o||260>n,r=i?Math.max(4,.035*Math.min(o,n)):20,s=i?Math.max(10,.075*n):34,a={x:r,y:r,width:Math.max(1,o-2*r),height:s},l=i?Math.max(16,.14*n):Math.min(78,.16*n),c={x:r,y:n-r-l,width:Math.max(1,o-2*r),height:l},u=i?Math.max(12,.08*o):Math.min(150,.17*o),d=a.y+a.height+(i?12:38),h=c.y-(i?10:34),p={x:u,y:d,width:Math.max(24,o-2*u),height:Math.max(24,h-d)},g=Math.max(18,Math.min(.32*p.width,i?84:180)),m={x:p.x+(p.width-g)/2,y:p.y-(i?10:24),width:g,height:i?12:28},f=Ns(t),y={left:f.filter(e=>"left"===(e.side??"bottom")),right:f.filter(e=>"right"===e.side),bottom:f.filter(e=>"bottom"===(e.side??"bottom"))},b=[],x=(e,t)=>{const n=Math.max(8,u-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:o-r-n,y:p.y+a*s,width:n,height:Math.max(8,s-(i?2:8))})})};x("left",y.left),x("right",y.right);const v=p.width/Math.max(1,y.bottom.length);return y.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*v,y:p.y+p.height+(i?2:7),width:Math.max(8,v-(i?2:8)),height:Math.max(8,c.y-p.y-p.height-(i?4:12))})}),b.sort((e,t)=>f.findIndex(t=>t.id===e.id)-f.findIndex(e=>e.id===t.id)),{width:o,height:n,phaseRail:a,chamber:p,mouth:m,projection:c,outlets:b}}(e.size??Ps,n),l=function(e){const{chamber:t,mouth:o}=e,n=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),i=Math.max(t.x,o.x),r=Math.min(t.x+t.width,o.x+o.width),s={left:e.outlets.filter(e=>"left"===e.side),right:e.outlets.filter(e=>"right"===e.side),bottom:e.outlets.filter(e=>"bottom"===e.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:t.x,y1:t.y,x2:i,y2:t.y,thickness:n}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:n}}];a.push(...Es({id:"crucible:wall:left",orientation:"vertical",fixed:t.x,start:t.y,end:t.y+t.height,openings:s.left.map(e=>[e.y,e.y+e.height]),thickness:n,friction:.46,restitution:.12}),...Es({id:"crucible:wall:right",orientation:"vertical",fixed:t.x+t.width,start:t.y,end:t.y+t.height,openings:s.right.map(e=>[e.y,e.y+e.height]),thickness:n,friction:.46,restitution:.12}),...Es({id:"crucible:wall:bottom",orientation:"horizontal",fixed:t.y+t.height,start:t.x,end:t.x+t.width,openings:s.bottom.map(e=>[e.x,e.x+e.width]),thickness:n,friction:.5,restitution:.08}));for(const t of e.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(t.id),sensor:!0,shape:{type:"aabb",x:t.x+t.width/2,y:t.y+t.height/2,width:t.width,height:t.height}});return a}(a),c=function(e,t){const o=[],n=new Set(t.map(e=>e.id)),i=zs(t.map(e=>e.id)),r=zs(e.map(e=>e.id));return i.length&&o.push(Cs("error","duplicate-outlet-id",`Outlet ids must be unique: ${i.join(", ")}.`,"outlets",i)),r.length&&o.push(Cs("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||o.push(Cs("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||o.push(Cs("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||o.push(Cs("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||o.push(Cs("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0===e.outletId||n.has(e.outletId)||o.push(Cs("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),Bs(e.metrics??{},o,`products.${t}.metrics`)}),o}(i,n),u=(d={seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Is(e.id,t.id)).map(e=>({id:e.id,label:e.label,category:e.category,amount:e.amount,metrics:e.metrics,status:e.status})),phases:t.phases.map(({id:e,duration:t,label:o,description:n,intensity:i,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:o,description:n,intensity:i,motion:r,color:s,metrics:a})),products:i,outlets:n,events:r.events.map(({id:e,label:t,description:o,summary:n,authoredAt:i,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:o,summary:n,authoredAt:i,phaseId:r,boundaryRank:s,effects:a}))},JSON.stringify(Qs(d)));var d;const h=function(e,t,o={}){const n=Object.values(e.components).sort((e,t)=>Is(e.id,t.id)),i=n.map(e=>e.amount),r=Hs(o.radiusRange,t),s=function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}($s(o.seed)),a=t.mouth.x+t.mouth.width/2,l=t.chamber.y+Math.max(18,.18*t.chamber.height),c=Math.max(4,.28*t.chamber.width),u=Math.max(4,.12*t.chamber.height);return n.map((e,t)=>{const d=t/Math.max(1,n.length)*Math.PI*2+.18*(s()-.5),h=Ys(e.amount,i,o.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:Ws(e.id),x:a+Math.cos(d)*c*(.45+.45*s()),y:l+Math.sin(d)*u*(.45+.45*s()),vx:24*(s()-.5),vy:18*(s()-.5),mass:Math.max(.25,h*h*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:h},datum:p}})}(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...c],g={phases:t.phases,events:r.events,products:i,outlets:n,duration:o,initialState:s.state,terminalState:s.state,layout:a,colliders:l,config:Ds(e.seed,l),initialSpawns:h,terminalSpawns:[],semanticKey:u,diagnostics:p},m=Zs(g),f=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),y=f.length?[Cs("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return g.terminalState=m.state,g.terminalSpawns=Us(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),g.diagnostics=[...p,...m.diagnostics,...y],g}import*as Js from"react";import{jsx as ea,jsxs as ta}from"react/jsx-runtime";function oa(e){return Number.isFinite(e)?1e3>Math.abs(e)?Number.isInteger(e)?e+"":e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):e.toLocaleString():"0"}function na(e,t,o,n){const i=e.datum;if(!i?.__crucible)return;const r="circle"===e.shape.type?e.shape.radius:8,s="string"==typeof t.fill?t.fill:"product"===i.kind?"#b8792d":"#356b63",a="string"==typeof t.stroke?t.stroke:"#26323a",l="number"==typeof t.strokeWidth?t.strokeWidth:1.25,c="number"==typeof t.opacity?t.opacity:.96,u=n?`${n}-crucible-body-${o}`:"crucible-body-"+o;if("product"===i.kind){const t=Array.from({length:6},(t,o)=>{const n=-Math.PI/2+o/6*Math.PI*2;return`${e.x+Math.cos(n)*r},${e.y+Math.sin(n)*r}`}).join(" "),o=u+"-glow";return ta(Js.Fragment,{children:[ea("defs",{children:ea("filter",{id:o,x:"-60%",y:"-60%",width:"220%",height:"220%",children:ea("feDropShadow",{dx:"0",dy:"0",stdDeviation:"4",floodColor:s,floodOpacity:"0.8"})})}),ea("polygon",{points:t,fill:s,stroke:a,strokeWidth:l,opacity:c,filter:`url(#${o})`}),ea("circle",{cx:e.x,cy:e.y,r:Math.max(2,.36*r),fill:"none",stroke:"var(--semiotic-bg, #fffaf0)",strokeWidth:l,opacity:.72*c})]},u)}return ta(Js.Fragment,{children:[ea("circle",{cx:e.x,cy:e.y,r:r,fill:s,stroke:a,strokeWidth:l,opacity:c}),ea("circle",{cx:e.x-.25*r,cy:e.y-.28*r,r:Math.max(1,.18*r),fill:"rgba(255,255,255,0.34)"})]},u)}import{Fragment as ia,jsx as ra,jsxs as sa}from"react/jsx-runtime";var aa="var(--semiotic-text, #26323a)",la="var(--semiotic-text-secondary, #6c7377)",ca="var(--semiotic-primary, #b8792d)",ua="var(--semiotic-danger, #9f3d35)",da="var(--semiotic-success, #356b63)";function ha(e){const{x:t,y:o,width:n,height:i}=e.chamber,r=Math.min(.14*n,48),s=o+i;return[`M ${t} ${o}`,`L ${t+r} ${s-.16*i}`,`Q ${t+n/2} ${s+.1*i} ${t+n-r} ${s-.16*i}`,`L ${t+n} ${o}`].join(" ")}function pa({layout:e,phases:t,state:o,compact:n=!1}){const i=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return sa("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[sa("defs",{children:[sa("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[ra("stop",{offset:"0",stopColor:ca,stopOpacity:"0.03"}),ra("stop",{offset:"0.66",stopColor:ca,stopOpacity:"0.1"}),ra("stop",{offset:"1",stopColor:ua,stopOpacity:"0.18"})]}),ra("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:ra("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:aa,strokeOpacity:"0.08",strokeWidth:"1"})})]}),ra("rect",{x:e.chamber.x,y:e.chamber.y,width:e.chamber.width,height:e.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:aa,strokeOpacity:"0.52",strokeWidth:n?1:2.2}),ra("path",{d:ha(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),ra("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:aa,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:n?2:5}),n?null:ra("g",{"data-testid":"crucible-phase-rail",children:t.map((n,r)=>{const s=t.slice(0,r).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/i*e.phaseRail.width,l=Math.max(0,n.duration)/i*e.phaseRail.width,c=n.id===o.phaseId,u=o.phaseIndex>r||o.complete;return sa("g",{children:[ra("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,l-2),height:e.phaseRail.height,rx:2,fill:c?n.color??ca:u?da:aa,fillOpacity:c?.68:u?.28:.09}),46>l?null:ra("text",{x:a+l/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:c?aa:la,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:c?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(n.label??n.id).toUpperCase()})]},n.id)})}),e.outlets.map(e=>sa("g",{children:[ra("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?ua:da),fillOpacity:"0.1",stroke:e.color??("left"===e.side?ua:da),strokeDasharray:"3 3",strokeOpacity:"0.62"}),n?null:ra("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:la,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function ga({rows:e,layout:t,projection:o,amountLabel:n}){if(!e.length)return null;const i=o.measure??"count",r=e.map(e=>Math.max(0,function(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}(e,i))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),l=t.projection.height>48?21:4,c=Math.max(5,t.projection.height-l-5);return ra("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:e.map((e,o)=>{const u=r[o],d=Math.max(u>0?2:0,u/s*c),h=t.projection.x+o*a+.18*a;return sa("g",{children:[ra("rect",{x:h,y:t.projection.y+c-d,width:Math.max(3,.64*a),height:d,rx:2,fill:"failed"===e.status||"ejected"===e.status?ua:"complete"===e.status?ca:da,fillOpacity:"0.68"}),l>4&&a>=34?sa(ia,{children:[ra("text",{x:h+.32*a,y:t.projection.y+c+10,fill:la,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),sa("text",{x:h+.32*a,y:t.projection.y+c+19,fill:aa,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[oa(u),"amount"===i&&n?" "+n:""]})]}):null]},e.key)})})}function ma(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function fa(e){return e.map(e=>({...e,spawnAt:void 0}))}function ya(e,t){return e?t?o=>_r.createElement(_r.Fragment,null,e,"function"==typeof t?t(o):t):e:t}var ba=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function xa(e){let t=2166136261;for(let o=0;e.length>o;o+=1)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return ba[(t>>>0)%ba.length]}var va={Sparkline:{frameType:"xy",layout:{mode:"sparkline"},buildProps:(e,t,o,n,i)=>({chartType:"line",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",groupAccessor:i.lineBy||t,colorAccessor:t,...n,showAxes:!1,margin:n.margin,showLegend:!1,showGrid:!1,title:void 0})},BumpChart:Go,LineChart:qo,AreaChart:Qo,DifferenceChart:Zo,StackedAreaChart:Ko,Scatterplot:en,CandlestickChart:Jo,BubbleChart:Vo,ConnectedScatterplot:on,QuadrantChart:tn,Heatmap:nn,TemporalHistogram:Uo,XYCustomChart:{frameType:"xy",buildProps:(e,t,o,n,i)=>({chartType:"custom",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n,showAxes:i.frameProps?.showAxes??i.showAxes??!1,showLegend:n.showLegend??!!t})},BarChart:Pn,StackedBarChart:Tn,GroupedBarChart:Ln,PieChart:Rn,DonutChart:In,Histogram:Cn,BoxPlot:zn,ViolinPlot:Fn,SwarmPlot:On,DotPlot:Bn,SwimlaneChart:Nn,RidgelinePlot:En,LikertChart:jn,FunnelChart:$n,GaugeChart:Dn,OrdinalCustomChart:{frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"custom",data:e,oAccessor:i.categoryAccessor||i.oAccessor||"category",rAccessor:i.valueAccessor||i.rAccessor||"value",projection:i.projection||"vertical",colorAccessor:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n,showAxes:i.frameProps?.showAxes??i.showAxes??!1})},ForceDirectedGraph:pr,NetworkCustomChart:{frameType:"network",layout:{margin:{top:40,right:40,bottom:40,left:40}},buildProps:(e,t,o,n,i)=>({chartType:"force",nodes:i.nodes||e||[],edges:i.edges||[],nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor||"id",sourceAccessor:i.sourceAccessor||"source",targetAccessor:i.targetAccessor||"target",valueAccessor:i.valueAccessor||"value",colorBy:t,colorScheme:o,customNetworkLayout:i.layout||i.customNetworkLayout,layoutConfig:i.layoutConfig,...n})},SankeyDiagram:mr,ProcessSankey:gr,ChordDiagram:fr,TreeDiagram:yr,Treemap:br,CirclePack:xr,ChoroplethMap:Sr,ProportionalSymbolMap:kr,FlowMap:Mr,GeoCustomChart:{frameType:"geo",buildProps:(e,t,o,n,i)=>({points:i.points||e||[],areas:i.areas||[],lines:i.lines||[],projection:i.projection||"equirectangular",xAccessor:i.xAccessor||"lon",yAccessor:i.yAccessor||"lat",lineDataAccessor:i.lineDataAccessor,colorBy:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n})},GaltonBoardChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s=i.bins??21,a=i.seed??1,l=Math.max(1,Math.round(i.pegRows??s-1)),c="mechanical"===i.mode,u=c?function(e){const t=Math.max(2,Math.round(e.bins)),o=Math.max(1,Math.round(e.pegRows??t-1)),n=Math.max(1,Math.round(e.count??Math.max(64,4*t))),i=zr(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Br(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:n},(e,t)=>{let n=0;for(let e=0;o>e;e+=1)r()<i&&(n+=1);const a=o/2;return{id:`${s}-${t}`,value:n,mechanical:!0,pegRows:o,branchProbability:i,pathRights:n,side:a>n?"left":n>a?"right":"center"}})}({bins:s,branchProbability:i.branchProbability,count:i.mechanicalCount,pegRows:l,seed:a}):Array.isArray(e)?e:[],d=function(e){const{data:t,valueAccessor:o,bins:n,ballRadius:i,seed:r,size:s,valueExtent:a}=e,l=Pr(s),c=t.map((e,t)=>Cr(Ir(e,t,o))).filter(e=>null!=e),u=function(e){if(!e)return;const t=Cr(e[0]),o=Cr(e[1]);return null!=t&&null!=o?t>o?[o,t]:[t,o]:void 0}(a),d=u?.[0]??(c.length?Math.min(...c):0),h=u?.[1]??(c.length?Math.max(...c):1),p=h===d?1:h-d,g=Nr().domain([0,n]).range([l.plot.x,l.plot.x+l.plot.width]),y=Array.from({length:n},()=>0),b=[];t.forEach((e,t)=>{const r=Cr(Ir(e,t,o));if(null==r)return;const s=Math.max(0,Math.min(n-1,Math.floor((r-d)/p*n)));y[s]+=1,b.push({id:(e.id??"galton-"+t)+"",x:g(s+.5),y:l.plot.y+i+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:i},datum:{...e,value:r,bin:s}})});const x=l.plot.y+l.plot.height;return{config:Rr(r,[...m({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...f({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:g,yTop:l.plot.y-400,yBottom:x,wallThickness:6})],"GaltonBoardChart"),initialSpawns:b,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:y.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:n,plot:l.plot,valueExtent:[d,h]}}}({data:u,valueAccessor:i.valueAccessor||"value",bins:s,ballRadius:i.ballRadius??4,seed:a,size:r,valueExtent:c?[0,l]:void 0});return{...n,config:d.config,initialSpawns:fa(d.initialSpawns),projectionRows:d.projectionRows,bodyStyle:Lr(t||i.colorBy||(c?"side":void 0),"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||"value"})}}},EventDropChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s=function(e){const{data:t,timeAccessor:o,arrivalAccessor:n,windows:i,watermark:r,ballRadius:s,seed:a,size:l,timeExtent:c,timeScale:u=1}=e,d=Pr(l),h=t.map((e,t)=>Cr(Ir(e,t,o))).filter(e=>null!=e),p=Cr(c?.[0]),g=Cr(c?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+i.size,b=Math.min(p??f,f),x=Math.max(g??y,y),v=Math.floor(b/i.size)*i.size,w=Math.max(1,Math.ceil((x-v+i.size)/i.size)),A=h.length?Math.max(...h):0,S="function"==typeof r?r(A):Cr(r?.value)??A-(r?.delay??i.size),k=Math.max(0,Math.min(w,Array.from({length:w},(e,t)=>t).reduce((e,t)=>v+(t+1)*i.size>S?e:e+1,0))),M=function(e,t){const o=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:o,height:e.plot.height},windowPlot:{x:e.plot.x+o,y:e.plot.y,width:Math.max(40,e.plot.width-o),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(d,s),_=v+w*i.size,P=Er().domain([v,_]).range([M.windowPlot.x,M.windowPlot.x+M.windowPlot.width]),T=Array.from({length:w},()=>({value:0,secondary:0})),L=[];t.forEach((e,t)=>{const r=Cr(Ir(e,t,o));if(null==r)return;const a=Cr(Ir(e,t,n))??r,l=Math.max(0,Math.min(w-1,Math.floor((r-v)/i.size))),c=S>=v+(l+1)*i.size;T[l].value+=c?0:1,T[l].secondary+=c?1:0,L.push({id:(e.id??"event-"+t)+"",x:Math.max(M.windowPlot.x+s,Math.min(M.windowPlot.x+M.windowPlot.width-s,P(r))),y:d.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:l,late:c}})});const R=d.plot.y+d.plot.height,I=function(e,t){const o=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!o)return[];const n=e.windowStart,i=e.windowStart+e.windowCount*e.windowSize,r=Er().domain([n,i]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+o*e.windowSize),a=e.windowPlot.x,l=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),c=e=>s===a?t:l+(e-a)/(s-a)*(t-l),u=[];for(let t=0;o>t;t+=1){const o=e.windowStart+t*e.windowSize,n=o+e.windowSize,i=r(o),s=r(n);u.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:i,y1:c(i),x2:s,y2:c(s)})}return u}({closedWindowCount:k,gutter:M.gutter,plot:d.plot,windowCount:w,windowPlot:M.windowPlot,windowSize:i.size,windowStart:v},d.plot.y+.28*d.plot.height);return{config:Rr(a,[...m({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...jr({idPrefix:"eventdrop-window",count:w,xScale:e=>P(v+e*i.size),yTop:M.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>k)return null;const t=0===e?I[0]?.y1:I[e-1]?.y2??I[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?M.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...I.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:L,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:u},projectionRows:T.map((e,t)=>({label:`${v+t*i.size}-${v+(t+1)*i.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:k,gutter:M.gutter,lidSegments:I,lateCount:T.reduce((e,t)=>e+t.secondary,0),plot:d.plot,windowPlot:M.windowPlot,watermarkValue:S,windowCount:w,windowSize:i.size,windowStart:v}}}({data:Array.isArray(e)?e:[],timeAccessor:i.timeAccessor||"time",arrivalAccessor:i.arrivalAccessor||"arrivalTime",windows:i.windows||{size:10},watermark:i.watermark,ballRadius:i.ballRadius??5,seed:i.seed??1,size:r,timeExtent:i.timeExtent,timeScale:i.timeScale??1});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||i.timeAccessor||"time"})}}},UnitPileChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s="mechanical"===i.mode,a=function(e){const{data:t,categoryAccessor:o,valueAccessor:n,unitValue:i,ballRadius:r,seed:s,size:a}=e,l=Fr(i,1),c=Pr(a),u=[],d=new Map,h=new Map,p=[];function g(e){let t=d.get(e);return null==t&&(t=u.length,u.push(e),d.set(e,t)),t}t.forEach((e,t)=>{g((Ir(e,t,o)??"unknown")+"")});const f=Math.max(1,u.length),y=function(e,t,o){const n=e.width/Math.max(1,t),i=Math.max(2,2*o),r=Math.min(.7*n,Math.max(3.2*i,i+8)),s=Math.max(1,Math.floor(r/i));return{laneWidth:n,tubeWidth:r,ballDiameter:i,perRow:s,centerX:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*i}}(c.plot,f,r),b=Math.max(0,y.tubeWidth/2-r-1),x=u.map(()=>[]);t.forEach((e,t)=>{const i=(Ir(e,t,o)??"unknown")+"",s=g(i),a=n?Cr(Ir(e,t,n)):1,u=Math.max(0,Math.round((a??0)/l)),d=y.centerX(s);for(let o=0;u>o;o+=1){const n=h.get(i)??0,a=y.perRow>1?((y.perRow>1?n%y.perRow:0)/(y.perRow-1)*2-1)*b:0;h.set(i,n+1),x[s].push({id:`${(e.id??"pile-"+t)+""}-${o}`,x:d+a,y:c.plot.y+r+2,vx:(o%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:i,unitIndex:o}})}});const v=x.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;v>e;e+=1)for(const t of x)t.length>e&&p.push(t[e]);const w=c.plot.y+c.plot.height,A=[...m({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],S=c.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const o of[-1,1])A.push({id:`pile-tube-${e}-${0>o?"l":"r"}`,shape:{type:"aabb",x:t+o*y.tubeWidth/2,y:(S+w)/2,width:6,height:w-S}})}return{config:Rr(s,A,"UnitPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:u.map(e=>({label:e,value:h.get(e)??0}))}}({data:s?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),o=t.length?t:["Intake"],n=Math.max(o.length,Math.round(e.count??Math.max(48,12*o.length))),i=Fr(e.unitValue,1),r=Br(e.seed??1),s=e.idPrefix??"mechanical-pile",a=o.map(()=>.65+.9*r()),l=a.reduce((e,t)=>e+t,0)||1,c=n-o.length,u=a.map(e=>e/l*c),d=u.map(e=>1+Math.floor(e));let h=n-d.reduce((e,t)=>e+t,0);const p=u.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)d[p[e].index]+=1,h-=1;return o.map((e,t)=>({id:`${s}-${t}`,category:e,value:d[t]*i,mechanical:!0,unitCount:d[t],unitValue:i,share:d[t]/n}))}({categories:i.mechanicalCategories,count:i.mechanicalCount,seed:i.seed??1,unitValue:i.unitValue??1}):Array.isArray(e)?e:[],categoryAccessor:i.categoryAccessor||"category",valueAccessor:i.valueAccessor||(s?"value":void 0),unitValue:i.unitValue??1,ballRadius:i.ballRadius??5,seed:i.seed??1,size:r});return{...n,config:a.config,initialSpawns:fa(a.initialSpawns),projectionRows:a.projectionRows,bodyStyle:Lr(t||i.colorBy||(s?"category":void 0),"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||"value"})}}},CollisionSwarmChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,360],s=function(e){const{data:t,xAccessor:o,groupAccessor:n,radiusAccessor:i,pointRadius:r,seed:s,size:a,xExtent:l,collisionIterations:c,settle:u}=e,d=Pr(a),h=Br(s),p=[],g=[],f=new Map;t.forEach((e,t)=>{const s=Cr(Ir(e,t,o));if(null==s)return;const a=n?(Ir(e,t,n)??"All")+"":"All",l=i?Cr(Ir(e,t,i)):null,c=zr(null!=l&&l>0?l:r,2,18);!function(e){let t=f.get(e);null==t&&(t=g.length,g.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:c})});const y=p.map(e=>e.value),b=l?Cr(l[0]):null,x=l?Cr(l[1]):null,v=y.length?Math.min(...y):0,w=y.length?Math.max(...y):1;let A=b??v,S=x??w;if(A===S&&(A-=.5,S+=.5),A>S){const e=S;S=A,A=e}const k=Math.max(r,...p.map(e=>e.radius)),M=d.plot.x+k+8,_=d.plot.x+d.plot.width-k-8,P=$r().domain([A,S]).range([M,_]),T=Math.max(1,g.length),L=Math.min(Math.max(28,3*k),d.plot.height/4),R=d.plot.y+L,I=Math.max(0,d.plot.y+d.plot.height-L-R),C=e=>{const t=f.get(e)??0;return 1===T?d.plot.y+.54*d.plot.height:R+t/(T-1)*I},z=new Map,F=p.map((e,t)=>{z.set(e.group,(z.get(e.group)??0)+1);const o=P(e.value),n=C(e.group),i=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:u?o+i:zr(o+(t%9-4)*e.radius*2.5,M,_),y:u?n+r:d.plot.y-18-t%12*e.radius,vx:u?0:22*(h()-.5),vy:u?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:o,targetY:n},springs:[{target:{type:"point",x:o,y:n},restLength:0,stiffness:34,damping:5.5}]}});return{config:Rr(s,m({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*k),collisionIterations:Math.max(1,Math.round(c??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:F,projectionRows:g.map(e=>({label:e,value:z.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[A,S],xRange:[M,_],groups:g.map(e=>({label:e,y:C(e),count:z.get(e)??0})),plot:d.plot}}}({data:Array.isArray(e)?e:[],xAccessor:i.xAccessor||"x",groupAccessor:i.groupAccessor,radiusAccessor:i.radiusAccessor,pointRadius:i.pointRadius??5,seed:i.seed??1,size:r,xExtent:i.xExtent,collisionIterations:i.collisionIterations,settle:i.settle});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy||i.groupAccessor,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.xAccessor||"x"})}}},ProcessFlowChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,420],s=Array.isArray(i.stages)?i.stages:[],a=function(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const o=e.size,n=Pr(o),i=zr(e.ballRadius??6,2,18),r=e.seed??1,s=Br(r),a=e.idAccessor,l=e.stageAccessor??"stage",c=e.groupBy,u=e.groupLabelAccessor,d=e.workAccessor,m=e.radiusAccessor,f=e.groupCompletion??(c?"allAbsorbed":"none"),y=e.springStiffness??.28,v=e.springDamping??.72,w=!0===e.settle,A=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),S=_({width:o[0],height:o[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:A,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),P=new Map(S.stages.map((e,t)=>[e.id,t])),L=new Map(S.stages.map(e=>[e.id,e])),R=S.stages[0].id,I=S.stages[0],C=new Set(t.filter(e=>e.absorb).map(e=>e.id)),z=t.map(e=>{const t=L.get(e.id)??I;return function(e,t){const o={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return h({...o,kind:e.kind??"sink",force:Xr(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...o.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return k({...o,kind:e.kind??"force-field",force:Xr(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...o.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return g({...o,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:Xr(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...o.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return M({...o,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:Xr(e.force,8),attributes:{...o.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?T({...o,kind:e.kind??"force-field",force:Xr(e.force,14),damping:e.damping??.02,attributes:{...o.attributes,primitive:"routeSurface"}}):b({...o,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...o.attributes,primitive:"forceField"}})}(e,{x:t.x,y:S.midY,width:t.width,height:S.bottomY-S.topY})});z.unshift(T({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(S.left+S.right)/2,y:S.midY,width:S.right-S.left,height:S.bottomY-S.topY-12,force:8,damping:.012,semanticItem:!1}));const F=new Map;for(const e of S.stages)F.set(e.id,0);const O=[];e.data.forEach((e,t)=>{const o=(a?Ir(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",n=(Ir(e,t,l)??R)+"",r=P.has(n)?n:R;F.set(r,(F.get(r)??0)+1);const s=c?(Ir(e,t,c)??"")+"":void 0,h=s&&u?(Ir(e,t,u)??s)+"":s,p=d?Cr(Ir(e,t,d))??1:1,g=m?Cr(Ir(e,t,m)):null,f=zr(null!=g&&g>0?g:i,2,18);O.push({datum:e,id:o,stageId:r,groupId:s||void 0,groupLabel:h||void 0,work:p,radius:f,index:t})});const B=new Map,N=new Map;for(const e of O){if(!e.groupId)continue;const t=B.get(e.groupId)??[];t.push(e.id),B.set(e.groupId,t),e.groupLabel&&N.set(e.groupId,e.groupLabel)}const E=zr(e.groupAnchorAlong??.55,.15,.9),j=S.left+(S.right-S.left)*E,$=Array.from(B.keys()),D=$.map((e,o)=>{const n=B.get(e)??[],i=$.length>1?S.topY+28+o/Math.max(1,$.length-1)*(S.bottomY-S.topY-56):S.midY;return p({id:e,label:N.get(e)??e,bodyIds:n,anchor:{x:j,y:i},x:j,y:i,completion:"allAbsorbed"===f?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),W=O.filter(e=>C.has(e.stageId)).map(e=>e.id),Y=x(D,W),H=new Map(D.map(e=>[e.id,e])),V=O.map((e,t)=>{const o=L.get(e.stageId)??I,n=o.x+(s()-.5)*Math.min(24,.2*o.width),i=S.boundaryY(n,"top")+e.radius+10,r=S.boundaryY(n,"bottom")-e.radius-10,a=r>i?i+s()*Math.max(1,r-i):S.midY,l=w?n:S.left+18+t%7*4,c=w?a:S.midY+(s()-.5)*(S.bottomY-S.topY)*.35,u=[{target:{type:"point",x:n,y:a},restLength:.45*e.radius,stiffness:y,damping:v}];if(e.groupId){const t=H.get(e.groupId);t?.anchor&&!C.has(e.stageId)&&u.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:l,y:c,vx:w?0:40+40*s(),vy:w?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:w?0:.03*t,springs:u,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),G={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:S.colliders,fixedDt:1/60,maxSubsteps:8},X=S.stages.map(e=>({label:e.label??e.id,value:F.get(e.id)??0})),q=t.map(e=>{const t=L.get(e.id)??I;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:F.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:G,initialSpawns:V,initialSpawnPacing:w?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:X,metadata:{kind:"process-flow",plot:n.plot,volume:S,stages:q,groups:D,groupCompletion:Y,regionEffects:z}}}({data:Array.isArray(e)?e:[],stages:s,size:r,idAccessor:i.idAccessor,stageAccessor:i.stageAccessor||"stage",groupBy:i.groupBy,groupLabelAccessor:i.groupLabelAccessor,workAccessor:i.workAccessor,radiusAccessor:i.radiusAccessor,ballRadius:i.ballRadius??6,seed:i.seed??1,groupCompletion:i.groupCompletion,groupAnchorAlong:i.groupAnchorAlong,settle:i.settle??!0,gravityX:i.gravityX,gravityY:i.gravityY}),l=a.metadata;return{...n,config:a.config,initialSpawns:fa(a.initialSpawns),projectionRows:a.projectionRows,regionEffects:l?.regionEffects,bodyStyle:Lr(t||i.colorBy||i.groupBy,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.workAccessor||i.stageAccessor||"stage"})}}},GauntletChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,520],s=as({data:Array.isArray(e)?e:[],size:r,gates:i.gates,positiveProperties:i.positiveProperties,negativeProperties:i.negativeProperties,crashOffset:i.crashOffset,idAccessor:i.idAccessor,positiveAccessor:i.positiveAccessor,negativeAccessor:i.negativeAccessor,metricsAccessor:i.metricsAccessor,initialViability:i.initialViability,projectPlacement:i.projectPlacement,coreBody:i.coreBody,viability:i.viability});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:[],bodyStyle:Lr(t||i.colorBy)}}},CrucibleChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,520],s=Ks({data:Array.isArray(e)?e:[],phases:Array.isArray(i.phases)?i.phases:[],products:Array.isArray(i.products)?i.products:void 0,outlets:Array.isArray(i.outlets)?i.outlets:void 0,events:Array.isArray(i.events)?i.events:void 0,idAccessor:i.idAccessor,labelAccessor:i.labelAccessor,categoryAccessor:i.categoryAccessor,amountAccessor:i.amountAccessor,metricsAccessor:i.metricsAccessor,initialStateAccessor:i.initialStateAccessor,metrics:i.metrics,size:r,seed:i.seed,bodyRadius:"number"==typeof i.bodyRadius?i.bodyRadius:void 0,radiusRange:i.radiusRange}),a="snapshot"===i.playback?function(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,Fs(t)??0));const o=e.phases.find(e=>e.id===t.phaseId);if(!o)return e.duration;const n=Math.max(0,Math.min(1,Fs(t.progress??0)??0));return o.start+o.duration*n}(s,i.snapshotAt):s.duration,l=Zs(s,a).state,c=i.projection&&"object"==typeof i.projection?i.projection:{groupBy:"outlet",measure:"count"},u=function(e,t={}){const o=t.groupBy??"outlet",n=new Map,i=e=>{const t=function(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}({...e,status:e.status??"active"},o),i=n.get(t);if(i)return i.count+=1,i.amount+=e.amount,void fs(i.metrics,e.metrics);n.set(t,{key:t,label:"product"===o&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:{...e.metrics},status:"status"===o?e.status:void 0,outletId:"outlet"===o?e.outletId:void 0,category:"category"===o?e.category:void 0,productId:"product"===o&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||i({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(const t of Object.values(e.products))i({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});const r=new Map((t.order??[]).map((e,t)=>[e,t]));return[...n.values()].sort((e,t)=>(r.get(e.key)??Number.MAX_SAFE_INTEGER)-(r.get(t.key)??Number.MAX_SAFE_INTEGER)||cs(e.key,t.key))}(l,c),d=c.measure??"count",h=function(e,t={}){const o=t.bodies??[],n=Math.max(0,t.recentBodyLimit??6),i=new Map;for(const e of o){const o=t.getContainerId?.(e);if(!o)continue;const n=i.get(o);n?n.push(e):i.set(o,[e])}const r=e.map(e=>{const o=i.get(e.id)??[],r=Math.max(0,Math.floor(e.count??o.length)),s=o.slice(Math.max(0,o.length-n)).map(e=>({id:e.id,label:t.getBodyLabel?.(e)??ma(e),datum:e.datum}));return{id:e.id,label:e.label,count:r,share:0,secondary:e.secondary,secondaryLabel:e.secondaryLabel,observed:e.observed,bodyIds:o.map(e=>e.id),recentBodies:s,metadata:e.metadata}}),s=r.reduce((e,t)=>e+t.count,0);return r.map(e=>({...e,share:s>0?e.count/s:0}))}(u.map(e=>({id:e.key,label:e.label,count:e.count,secondary:"count"===d||"amount"===d?e.amount:Number(e.metrics[d]??0),secondaryLabel:"count"===d||"amount"===d?i.amountLabel??"amount":d,metadata:{amount:e.amount,metrics:e.metrics,status:e.status,outletId:e.outletId,category:e.category,productId:e.productId}}))),p={seed:i.seed,bodyRadius:"number"==typeof i.bodyRadius?i.bodyRadius:void 0,radiusRange:i.radiusRange},g=t??i.colorBy??"category",m=!1===i.showChrome?null:_r.createElement(pa,{layout:s.layout,phases:s.phases,state:l,compact:520>r[0]||360>r[1]}),f=!1===i.showProjection?null:_r.createElement(ga,{rows:u,layout:s.layout,projection:c,amountLabel:i.amountLabel});return{...n,config:s.config,initialSpawns:fa(qs(l,s.layout,p)),projectionRows:h,bodyStyle:e=>function(e,t,o,n){const i=e.datum,r={stroke:n.stroke??("product"===i?.kind?"#fffaf0":"#26323a"),strokeWidth:n.strokeWidth??("product"===i?.kind?1.8:1.1),opacity:n.opacity??.96};if(!i?.__crucible)return{...r,fill:n.color??"#b8792d"};if("product"===i.kind){const e=t.products[i.semanticId];return{...r,fill:n.color??e?.color??xa(e?.id??i.semanticId)}}const s=t.components[i.semanticId];if(!s)return{...r,fill:n.color??"#356b63"};let a;return a="status"===o?s.status:"outlet"===o?s.outletId??"in chamber":"product"===o?s.productIds[0]??"unalloyed":"category"===o||null==o?s.category:"function"==typeof o?(o(s.datum)??"unassigned")+"":(s.datum[o+""]??"unassigned")+"",{...r,fill:n.color??xa(a)}}(e,l,g,i),getBodyLabel:e=>function(e,t){const o=e.datum;if(o?.__crucible)return"product"===o.kind?t.products[o.semanticId]?.label:t.components[o.semanticId]?.label}(e,l),renderBodySVG:na,backgroundGraphics:ya(m,n.backgroundGraphics),foregroundGraphics:ya(f,n.foregroundGraphics)}}},PacketFlowChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[760,420],s=function(e){const{coordinateMode:t,flowSpeed:o,links:n,maxParticles:i,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:l,particleRadius:c,particleRate:u,pathAccessor:d,pathConstraint:h="path",reducedMotion:p,seed:g,size:f,sourceAccessor:y,targetAccessor:b,throughputAccessor:x}=e,v=Pr(f),w=Br(g),A=new Map,S=new Map,k=[];function M(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}l.forEach((e,t)=>{const o=(Ir(e,t,r)??e.id??t)+"",n=Cr(Ir(e,t,s)),i=Cr(Ir(e,t,a));if(null!=n&&null!=i){const e={x:n,y:i};A.set(o,e),k.push(e)}S.set(o,(e.label??e.name??o)+"")});const _=[];n.forEach((e,t)=>{const o=M(Ir(e,t,y)),n=M(Ir(e,t,b)),i=Math.max(0,Cr(Ir(e,t,x))??0),r=Wr(d?Ir(e,t,d):void 0),s=r.length?r:Wr(e.path??e.points??e.route);s.forEach(e=>k.push(e)),_.push({id:(e.id??`physical-flow-${o}-${n}-${t}`)+"",link:e,index:t,source:o,target:n,throughput:i,rawPath:s})});const P=(L=k,"normalized"===(T=t)||"pixels"===T?T:L.length>0&&L.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var T,L;const R=new Map;for(const[e,t]of A)R.set(e,Yr(t,v,P));const I=[];for(const e of _){let t=e.rawPath.map(e=>Yr(e,v,P));if(2>t.length){const o=R.get(e.source),n=R.get(e.target);o&&n&&(t=[o,n])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(S.has(e.source)||S.set(e.source,e.source),S.has(e.target)||S.set(e.target,e.target),I.push({...e,path:t,packetCount:0}))}const C=Fr(u,.12),z=Math.max(1,Math.round(i)),F=I.map(e=>Math.max(1,Math.round(e.throughput*C))),O=F.reduce((e,t)=>e+t,0),B=O>z?z/O:1;I.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(F[t]*B))});let N=I.reduce((e,t)=>e+t.packetCount,0);for(;N>z;){const e=I.reduce((e,t,o)=>t.packetCount>1&&(-1===e||t.packetCount>I[e].packetCount)?o:e,-1);if(-1===e)break;I[e].packetCount-=1,N-=1}const E=new Map,j=new Map,$=[],D=Fr(o,90),W=Fr(c,4);I.forEach((e,t)=>{E.set(e.target,(E.get(e.target)??0)+e.throughput),j.set(e.source,(j.get(e.source)??0)+e.throughput);const o=Hr(e.path);for(let n=0;e.packetCount>n;n+=1){const i=(n+.5)/e.packetCount,r=p?i:zr(.12+.84*i+.04*(w()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*w())),a=Vr(e.path,s),l=Vr(e.path,r),c=Gr(e.path,s),u={x:-c.y,y:c.x},d=(w()-.5)*W*1.5;$.push({id:`${e.id}-packet-${n}`,x:a.x+u.x*d,y:a.y+u.y*d,vx:p?0:c.x*D+10*(w()-.5),vy:p?0:c.y*D+10*(w()-.5),mass:.8,spawnAt:p?0:.04*t+n/32,shape:{type:"circle",radius:W},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:n,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:o,flowRouteId:e.id,flowSpeed:D,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:l.x,y:l.y},restLength:.7*W,stiffness:26,damping:4.25}]:void 0})}});const Y=Math.max(18,5*W),H=Array.from(R,([e,t])=>({nodeId:e,label:S.get(e)??e,sensorId:"physical-flow-node-"+Or(e),point:t})),V=H.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:Y,height:Y}})),G=Object.fromEntries(H.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),X=Rr(g,[...m({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...V],"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*W),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});X.bodyLimit=z,X.eviction="oldest",X.observation={...X.observation,sensors:G};const q=Array.from(R,([e,t])=>({id:e,label:S.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+Or(e),incoming:E.get(e)??0,outgoing:j.get(e)??0})),U=I.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:X,initialSpawns:$,projectionRows:q.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:P,particleCount:$.length,totalThroughput:I.reduce((e,t)=>e+t.throughput,0),plot:v.plot,nodes:q,links:U}}}({nodes:Array.isArray(i.nodes)?i.nodes:[],links:Array.isArray(i.links)?i.links:Array.isArray(i.edges)?i.edges:Array.isArray(e)?e:[],nodeIdAccessor:i.nodeIdAccessor||"id",nodeXAccessor:i.nodeXAccessor||"x",nodeYAccessor:i.nodeYAccessor||"y",sourceAccessor:i.sourceAccessor||"source",targetAccessor:i.targetAccessor||"target",throughputAccessor:i.throughputAccessor||"value",pathAccessor:i.pathAccessor||"path",coordinateMode:i.coordinateMode||"auto",particleRate:i.particleRate??.16,maxParticles:i.maxParticles??180,particleRadius:i.particleRadius??4,flowSpeed:i.flowSpeed??90,pathConstraint:i.pathConstraint||"path",reducedMotion:!0,seed:i.seed??1,size:r});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy||"source")}}},PhysicsCustomChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[700,380],s=function(e){const t=function(e,t,o){const n=e?.observation;return{...e,observation:{...n,chartId:t??n?.chartId??"physics-custom",chartType:n?.chartType??"PhysicsCustomChart",onObservation:o??n?.onObservation}}}(e.config,e.chartId,e.onObservation),o=Ne(e.colorScheme,e.themeCategorical,Pt),n=Pr(e.size),i={data:e.data,scales:{x:qr().domain(e.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:qr().domain(e.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:e.semantic,categorical:[...o]},resolveColor:H(o,e.colorScheme),config:e.layoutConfig??{},world:new d(t)},r=e.skipLayout?{}:e.layout(i)??{},s=function(e,t){if(!t?.length)return e;const o=new Map;for(const e of t){const{bodyId:t,...n}=e,i=o.get(t)??[];i.push(n),o.set(t,i)}return e.map(e=>{const t=o.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...r.initialSpawns??r.bodies??[]],r.constraints);return{config:Ur(t,r),context:i,initialSpawnPacing:r.initialSpawnPacing,initialSpawns:s,result:r}}({chartId:i.chartId,colorScheme:o,config:i.config,data:Array.isArray(e)?e:[],layout:i.layout,layoutConfig:i.layoutConfig,semantic:Dt(Et)??{},size:r,themeCategorical:Et.colors.categorical,xExtent:i.xExtent,yExtent:i.yExtent});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:[],bodyStyle:s.result.bodyStyle??Lr(t||i.colorBy)}}}};function wa(e){const t=e instanceof Date?e.getTime():"number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Aa(e){if(!e||2>e.length)return;const t=wa(e[0]),o=wa(e[e.length-1]);return null!==t&&null!==o?[t,o]:void 0}function Sa(e){const{count:t,byType:o}=function(e){const t={};for(const o of e){const e="string"==typeof o?.type&&o.type.length>0?o.type:"node";t[e]=(t[e]??0)+1}return{count:e.length,byType:t}}(e.marks),n=0===t,i=[...e.extraWarnings??[]];n&&!i.includes("EMPTY_SCENE")&&i.push("EMPTY_SCENE");const r=e.margin,s=r?{x:r.left,y:r.top,width:e.width-r.left-r.right,height:e.height-r.top-r.bottom}:void 0;return{component:"",frameType:e.frameType,status:n?"empty":"ok",empty:n,markCount:t,markCountByType:o,width:e.width,height:e.height,...e.xDomain?{xDomain:e.xDomain}:{},...e.yDomain?{yDomain:e.yDomain}:{},...e.categories?{categories:e.categories}:{},...void 0!==e.nodeCount?{nodeCount:e.nodeCount}:{},...void 0!==e.edgeCount?{edgeCount:e.edgeCount}:{},...void 0!==e.legendItems?{legendItems:e.legendItems}:{},annotationCount:Array.isArray(e.annotations)?e.annotations.length:0,ariaLabel:"string"==typeof e.description&&e.description||"string"==typeof e.title&&e.title||`${e.frameType} chart, ${t} marks`,warnings:i,...r?{margin:r}:{},...s?{plot:s}:{}}}import*as ka from"react";import*as Ma from"react-dom/server";import{scaleOrdinal as _a}from"d3-scale";import{jsx as Pa,jsxs as Ta}from"react/jsx-runtime";var La=I;function Ra(e,t,o){if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return t=>$e(e,t)??"#999"}const n=Array.isArray(t)?t:o.colors.categorical.length>0?o.colors.categorical:Pt;return _a().domain(e).range(n)}function Ia(e,t,o){if(0===e.length)return;const n=Ra(e,t,o);return{legendGroups:[{label:"",type:"fill",items:e.map(e=>({label:e})),styleFn:e=>({fill:n(e.label)})}]}}function Ca(e){return"left"===e?"start":"right"===e?"end":e??"start"}function za(e){return Number(e.typography.legendSize??e.typography.labelSize??e.typography.tickSize)||11}function Fa(e,t,o,n){const i=za(n);return t+o+Math.ceil(e.length*i*.58)}function Oa(e){const{categories:t,theme:o,position:n="right",totalWidth:i,margin:r,legendLayout:s}=e,{swatchSize:a,labelGap:l,itemGap:c,rowHeight:u}=Ye(s),d=a+l,h="top"===n||"bottom"===n,p=Math.max(a,i-r.left-r.right),g=t.map(e=>Fa(e,a,l,o));if(h){const e=Math.max(a,s?.maxWidth??p),o=[];let n=0,i=0;g.forEach((t,r)=>{const s=0===i?t:i+c+t;i>0&&s>e?(o.push({start:n,end:r,width:i}),n=r,i=t):i=s}),t.length>0&&o.push({start:n,end:t.length,width:i});const r=Ca(s?.align),l=[];return o.forEach((o,n)=>{let i="center"===r?Math.max(0,(e-o.width)/2):"end"===r?Math.max(0,e-o.width):0;for(let e=o.start;o.end>e;e++)l.push({category:t[e],width:g[e],x:i,y:n*u}),i+=g[e]+c}),{items:l,width:Math.max(0,...o.map(e=>e.width)),height:o.length*u,swatchSize:a,labelOffset:d,swatchRadius:0}}const m=Math.max(0,...g);return{items:t.map((e,t)=>({category:e,width:g[t],x:0,y:t*u})),width:m,height:t.length*u,swatchSize:a,labelOffset:d,swatchRadius:0}}function Ba(e){const{legendGroups:t,theme:o,position:n="right",totalWidth:i,margin:r,legendLayout:s}=e,{swatchSize:a,labelGap:l,rowHeight:c}=Ye(s),u=a+l,d=Math.max(12,za(o)),h="top"===n||"bottom"===n,p=Math.max(a,i-r.left-r.right);if(h){const n=Math.max(a,s?.maxWidth??p),i=Ca(s?.align);let r=0,l=0;const c=[];for(const i of t){const t=i.items.map(e=>e.label),u=Oa({...e,categories:t,legendLayout:{...s,maxWidth:Math.max(a,n-d-8),align:"start"}}),h=i.label?d:0,p=i.label?Fa(i.label,0,0,o):0,g=h>0?h+8:0,m=g+u.width,f=Math.max(u.height,p);c.push({group:i,x:r,y:0,itemOffsetX:g,itemOffsetY:0,width:m,height:f,items:u.items}),r+=m+12,l=Math.max(l,f)}const h=c.length>0?r-12:0,g=h>n?0:"center"===i?Math.max(0,(n-h)/2):"end"===i?Math.max(0,n-h):0;return{groups:c.map(e=>({...e,x:e.x+g})),width:h,height:l,swatchSize:a,labelOffset:u,swatchRadius:0}}const g=ye(t.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),c);let m=0;return{groups:t.map((e,t)=>{const n=e.items.map(e=>Fa(e.label,a,l,o)),i=Math.max(0,...n,e.label?Fa(e.label,0,0,o):0);return m=Math.max(m,i),{group:e,x:0,y:g[t].itemsY,itemOffsetX:0,itemOffsetY:0,width:i,height:e.items.length*c,items:e.items.map((e,t)=>({category:e.label,width:n[t],x:0,y:t*c}))}}),width:m,height:g.at(-1)?.endY??0,swatchSize:a,labelOffset:u,swatchRadius:0}}function Na(e){const t="top"===e.position||"bottom"===e.position,o=Math.max(1,e.totalWidth-e.margin.left-e.margin.right);return t?{width:Math.min(e.legendLayout?.maxWidth??o,200),height:e.gradient.label?34:26,swatchSize:12}:{width:e.gradient.label?86:72,height:e.gradient.label?124:108,swatchSize:14}}function Ea(e,t){if(!t||!e||0===e.length)return[];const o="function"==typeof t?t:e=>e[t],n=new Set;for(const t of e){const e=o(t);null!=e&&n.add(e+"")}return Array.from(n)}import{jsx as ja,jsxs as $a}from"react/jsx-runtime";var Da=16;function Wa(e,t){return e.color||t.colors.annotation||t.colors.text}function Ya(e,t,o){const n=e.labelBackground,i=t.colors.background,r=i&&"transparent"!==i?i:t.colors.surface||i;return void 0===n?"none"===o?"none":{type:"halo",fill:r}:!1===n||"none"===n?"none":!0===n||"halo"===n?{type:"halo",fill:r}:"box"===n?{type:"box",fill:r}:{fill:r,...n}}function Ha(e,t,o){return null!=e.x&&t.x?t.x(e.x):o&&null!=e[o]&&t.x?t.x(e[o]):"number"==typeof e.x?e.x:null}function Va(e,t,o){return null!=e.y&&t.y?t.y(e.y):o&&null!=e[o]&&t.y?t.y(e[o]):"number"==typeof e.y?e.y:null}function Ga(e){const{annotations:t}=e;if(!t||0===t.length)return null;const o=Lt(t),n=e.scales.geoProjection,i=n?o.map(e=>{if(!Array.isArray(e.coordinates)||2>e.coordinates.length)return e;const t=n([Number(e.coordinates[0]),Number(e.coordinates[1])]);return t?{...e,x:t[0],y:t[1]}:e}):o,r=!!n&&!e.scales.x&&!e.scales.y,s=e=>Number(e),a=e.scales.x??(r?s:void 0),l=e.scales.y??(r?s:void 0),c=e.projection?"horizontal"===e.projection?"horizontal":"vertical":void 0,u={scales:{x:a,y:l,time:a,value:l,o:e.scales.o,...n?{geoProjection:n}:{}},width:e.layout.width,height:e.layout.height,xAccessor:e.xAccessor,yAccessor:e.yAccessor,data:e.annotationData,frameType:e.projection?"ordinal":n||e.scales.x||e.scales.y?"xy":"network",...c?{projection:c}:{}},d=e.autoPlaceAnnotations?ft({annotations:i,context:u,..."object"==typeof e.autoPlaceAnnotations?e.autoPlaceAnnotations:{}}):i,h=Te(d,(t,o)=>function(e,t,o){const{scales:n,layout:i,theme:r,xAccessor:s,yAccessor:a}=o;switch(e.type){case"y-threshold":{const s=e.value;if(null==s)return null;const a=Wa(e,r),l=e.label,c=e.labelPosition||"right",u=e.strokeDasharray||"6,4",d=e.strokeWidth??1.5;if("horizontal"===o.projection&&n.r){const o=n.r(s);return null==o?null:$a("g",{opacity:e.opacity,children:[ja("line",{x1:o,y1:0,x2:o,y2:i.height,stroke:a,strokeWidth:d,strokeDasharray:u}),l&&ja(L,{x:o+4,y:Da,textAnchor:"start",fontSize:r.typography.tickSize,fill:a,fontFamily:r.typography.fontFamily,text:l,background:Ya(e,r,"halo")})]},"ann-ythresh-"+t)}const h=n.y?n.y(s):n.r?n.r(s):null;return null==h?null:$a("g",{children:[ja("line",{x1:0,y1:h,x2:i.width,y2:h,stroke:a,strokeWidth:d,strokeDasharray:u}),l&&ja(L,{x:"left"===c?4:"center"===c?i.width/2:i.width-4,y:20>h?Math.min(i.height-4,h+Da):h-6,textAnchor:"left"===c?"start":"center"===c?"middle":"end",fontSize:r.typography.tickSize,fill:a,fontFamily:r.typography.fontFamily,text:l,background:Ya(e,r,"halo")})]},"ann-ythresh-"+t)}case"x-threshold":{const s=e.value;if(null==s)return null;const a="horizontal"===o.projection&&n.r?n.r(s):n.x?n.x(s):null;if(null==a)return null;const l=Wa(e,r),c=e.label,u=e.labelPosition||"top";return $a("g",{opacity:e.opacity,children:[ja("line",{x1:a,y1:0,x2:a,y2:i.height,stroke:l,strokeWidth:e.strokeWidth??1.5,strokeDasharray:e.strokeDasharray||"6,4"}),c&&ja(L,{x:a>.6*i.width?a-4:a+4,y:"bottom"===u?i.height-4:"center"===u?i.height/2:Da,textAnchor:a>.6*i.width?"end":"start",fontSize:r.typography.tickSize,fill:l,fontFamily:r.typography.fontFamily,text:c,background:Ya(e,r,"halo")})]},"ann-xthresh-"+t)}case"band":{const o=n.y?.domain?.(),s=e.y0??o?.[0],a=e.y1??o?.[1],l=null!=s&&n.y?n.y(s):null,c=null!=a&&n.y?n.y(a):null;if(null==l||null==c)return null;const u=Math.min(l,c),d=Math.abs(c-l),h=gt(e.fill||Wa(e,r),"ssr-band-"+t),p=e.fillOpacity??.1;return $a("g",{opacity:e.opacity,children:[h.def&&ja("defs",{children:h.def}),ja("rect",{x:0,y:u,width:i.width,height:d,fill:h.fill,fillOpacity:p}),e.label&&ja(L,{x:i.width-4,y:Math.max(u,0)+Da,textAnchor:"end",fontSize:r.typography.tickSize,fill:e.color||Wa(e,r),fontFamily:r.typography.fontFamily,fontWeight:"bold",text:e.label,background:Ya(e,r,"halo")})]},"ann-band-"+t)}case"x-band":{const o=n.x?.domain?.(),s=e.x0??o?.[0],a=e.x1??o?.[1],l=null!=s&&n.x?n.x(s):null,c=null!=a&&n.x?n.x(a):null;if(null==l||null==c)return null;const u=Math.min(l,c),d=Math.abs(c-l),h=gt(e.fill||Wa(e,r),"ssr-xband-"+t),p=e.fillOpacity??.1;return $a("g",{opacity:e.opacity,children:[h.def&&ja("defs",{children:h.def}),ja("rect",{x:u,y:0,width:d,height:i.height,fill:h.fill,fillOpacity:p}),e.label&&ja(L,{x:u+4,y:Da,textAnchor:"start",fontSize:r.typography.tickSize,fill:e.color||r.colors.primary||Wa(e,r),fontFamily:r.typography.fontFamily,fontWeight:"bold",text:e.label,background:Ya(e,r,"halo")})]},"ann-xband-"+t)}case"category-highlight":{if(null==e.category||!n.o)return null;const s=n.o(e.category+"");if(null==s)return null;const a=n.o.bandwidth?n.o.bandwidth():40,l=Wa(e,r),c=e.opacity??.1,u=e.label;return $a("g","horizontal"===o.projection?{children:[ja("rect",{x:0,y:s,width:i.width,height:a,fill:l,opacity:c}),u&&ja(L,{x:12,y:s+a/2,dominantBaseline:"middle",fill:l,fontSize:r.typography.tickSize,fontWeight:"bold",fontFamily:r.typography.fontFamily,text:u,background:Ya(e,r,"none")})]}:{children:[ja("rect",{x:s,y:0,width:a,height:i.height,fill:l,opacity:c}),u&&ja(L,{x:s+a/2,y:Da,textAnchor:"middle",fill:l,fontSize:r.typography.tickSize,fontWeight:"bold",fontFamily:r.typography.fontFamily,text:u,background:Ya(e,r,"none")})]},"ann-cathighlight-"+t)}case"label":case"callout":case"callout-circle":case"callout-rect":case"text":{const{x:o,y:i}=function(e,t,o,n){if(Array.isArray(e.coordinates)&&e.coordinates.length>=2&&t.geoProjection){const o=t.geoProjection([e.coordinates[0],e.coordinates[1]]);if(o)return{x:o[0],y:o[1]}}return{x:Ha(e,t,o),y:Va(e,t,n)}}(e,n,s,a);if(null==o||null==i)return null;const l="text"===e.type,c=e.dx??(l?0:30),u=e.dy??(l?0:-30),d=e.color||r.colors.text;if(!l){const n="callout"===e.type?"callout-circle":e.type,r="callout-circle"===n?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===n?{width:e.width,height:e.height}:void 0;return ja(B,{noteData:{x:o,y:i,dx:c,dy:u,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:n,...r?{subject:r}:{},connector:e.connector||{end:"arrow"},color:d,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-label-"+t)}return ja("g",{children:ja("text",{x:o+c,y:i+u,textAnchor:e.textAnchor||"start",fontSize:e.fontSize||r.typography.labelSize,fill:d,fontFamily:r.typography.fontFamily,fontWeight:e.fontWeight,opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:e.label||e.title})},"ann-label-"+t)}default:return null}}(t,o,e),e.svgAnnotationRules,u);return h.length>0?ja("g",{id:(e.idPrefix?e.idPrefix+"-":"")+"annotations",className:"semiotic-annotations",children:h}):null}import*as Xa from"react";import{jsx as qa,jsxs as Ua}from"react/jsx-runtime";function Qa(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){const t=e.id;return null==t?null:t+""}return null}function Za(e){const t=e._idPrefix||e.chartId;if(t){const e=(t+"").replace(/[^a-zA-Z0-9_-]/g,"_");return/^[A-Za-z_]/.test(e)?e:"c"+e}const o=`${e.chartType||""}:${e.title||""}:${Array.isArray(e.data)?e.data.length:0}`;let n=0;for(let e=0;o.length>e;e++)n=31*n+o.charCodeAt(e)|0;return"c"+(n>>>0).toString(36)}function Ka(e,t,o){const n=e.showLegend&&!e.__legendIncludesAutomatic?Ia(t,e.colorScheme,o):void 0;return X(n,e.legend)}var Ja={right:110,left:110,top:50,bottom:80};function el(e,t){if(e.__autoLegendMargin&&!tl(e,t))return Ja[t]}function tl(e,t){const o=e.__explicitMargin;return"number"==typeof o||!(!o||"object"!=typeof o||"number"!=typeof o[t])}function ol(e,t){const{props:o,categories:n,theme:i,size:r,hasTitle:s}=t,a=o.legendPosition||"right",l={theme:i,position:a,size:r,hasTitle:s,legendLayout:o.legendLayout,axisChrome:o.axisChrome,minimumMargin:el(o,a),preserveExplicitMargin:tl(o,a)};if(null!=o.legend){const t=Ka(o,n,i);(fe(t)||me(t))&&function(e,t){if(t.preserveExplicitMargin)return;const o=t.position||"right",n={theme:t.theme,position:o,totalWidth:t.size[0],totalHeight:t.size[1],margin:e,hasTitle:t.hasTitle,legendLayout:t.legendLayout},i=fe(t.legend)?function(e){const{width:t,height:o,swatchSize:n}=Ba(e);return{width:t,height:o,swatchSize:n}}({...n,legendGroups:t.legend.legendGroups}):me(t.legend)?Na({...n,gradient:t.legend.gradient}):null;if(!i)return;const r=We(t.legend),s=Math.max(t.minimumMargin??0,Ge(t.legend,t.legendLayout)),a=Fe(t.axisChrome,t.legendLayout),l=Math.max(t.minimumMargin??0,r+i.height+(t.hasTitle?24:0)),c=Math.max(t.minimumMargin??0,a+r+i.height);"right"===o?e.right=Math.max(e.right,s):"left"===o?e.left=Math.max(e.left,s):"top"===o?e.top=Math.max(e.top,l):e.bottom=Math.max(e.bottom,c)}(e,{...l,legend:t})}else o.showLegend&&n.length>0&&function(e,t){if(0===t.categories.length)return;if(t.preserveExplicitMargin)return;const o=t.position||"right",n=function(e){const{width:t,height:o,swatchSize:n}=Oa(e);return{width:t,height:o,swatchSize:n}}({categories:t.categories,colorScheme:t.colorScheme,theme:t.theme,position:o,totalWidth:t.size[0],totalHeight:t.size[1],margin:e,hasTitle:t.hasTitle,legendLayout:t.legendLayout}),i=Ia(t.categories,t.colorScheme,t.theme),r=We(i),s=Math.max(t.minimumMargin??0,Ge(i,t.legendLayout)),a=Fe(t.axisChrome,t.legendLayout),l=Math.max(t.minimumMargin??0,r+n.height+(t.hasTitle?24:0)),c=Math.max(t.minimumMargin??0,a+r+n.height);"right"===o?e.right=Math.max(e.right,s):"left"===o?e.left=Math.max(e.left,s):"top"===o?e.top=Math.max(e.top,l):e.bottom=Math.max(e.bottom,c)}(e,{...l,categories:n,colorScheme:o.colorScheme});return a}function nl(e){const{props:t,categories:o,theme:n,size:i,margin:r,hasTitle:s}=e,a=t.legendPosition||"right",l={theme:n,position:a,size:i,margin:r,hasTitle:s,legendLayout:t.legendLayout,axisChrome:t.axisChrome,idPrefix:t._idPrefix};if(null!=t.legend){const e=Ka(t,o,n);if(Xa.isValidElement(e))return e;const i=function(e,t){const o={theme:t.theme,position:t.position||"right",totalWidth:t.size[0],totalHeight:t.size[1],margin:t.margin,hasTitle:t.hasTitle,legendLayout:t.legendLayout,idPrefix:t.idPrefix,reservedWidth:t.reservedWidth,axisChrome:t.axisChrome,legendDistance:fe(e)||me(e)?e.legendDistance:void 0};return fe(e)?function(e){if(0===(t=e.legendGroups,t.flatMap(e=>e.items.map((t,o)=>({group:e,item:t,itemIndex:o,label:t.label})))).length)return null;var t;const o=Ba(e),n="top"===e.position||"bottom"===e.position,i={legendGroups:e.legendGroups,legendDistance:e.legendDistance},r=e.reservedWidth??Xe(i,e.legendLayout),s=We(i),a=He(e.legendLayout),l=Fe(e.axisChrome,e.legendLayout),c=Fe(void 0,e.legendLayout),u=e.theme.colors.grid||e.theme.colors.textSecondary;let d,h;if("left"===e.position?(d=e.margin.left-a-r-s,h=e.margin.top):"top"===e.position?(d=e.margin.left,h=e.margin.top-c-s-o.height):"bottom"===e.position?(d=e.margin.left,h=Math.max(e.totalHeight-e.margin.bottom+s,Math.min(e.totalHeight-e.margin.bottom+l+s,e.totalHeight-o.height))):(d=e.totalWidth-e.margin.right+a+s,h=e.margin.top),!n){const t=ye(e.legendGroups.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),Math.max(o.swatchSize,e.legendLayout?.rowHeight??La)),n=e.legendGroups.flatMap((n,i)=>{const s=t[i],a=n.type??"fill",l=[Pa("line",{x1:0,y1:s.lineY,x2:r,y2:s.lineY,stroke:"gray"},"legend-group-neatline-"+i)];return n.label&&null!=s.labelY&&l.push(Pa("text",{y:s.labelY,fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:n.label},"legend-group-label-"+i)),l.push(Pa("g",{transform:`translate(0,${s.itemsY})`,children:n.items.map((t,r)=>{const s=n.styleFn(t,r),l="function"==typeof a?a(t):"line"===a?Pa("line",{x1:0,y1:0,x2:o.swatchSize,y2:o.swatchSize,style:s}):Pa("rect",{width:o.swatchSize,height:o.swatchSize,rx:o.swatchRadius,style:s});return Ta("g",{transform:`translate(0,${r*Math.max(o.swatchSize,e.legendLayout?.rowHeight??La)})`,children:[l,Pa("text",{x:o.labelOffset,y:o.swatchSize/2,dominantBaseline:"central",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:t.label})]},`legend-${i}-${r}`)})},"legend-group-"+i)),l});return Pa("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,"data-orientation":"vertical",children:n})}const p=o.groups.flatMap((t,i)=>{const{group:r}=t,s=r.type??"fill",a=[];if(r.label&&a.push(Pa("text",n?{transform:`translate(${t.x},${t.y}) rotate(90)`,textAnchor:"start",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:r.label}:{x:t.x,y:t.y+za(e.theme),fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:r.label},"legend-group-label-"+i)),a.push(...t.items.map((n,a)=>{const l=r.items[a],c=r.styleFn(l,a),u="function"==typeof s?s(l):"line"===s?Pa("line",{x1:0,y1:0,x2:o.swatchSize,y2:o.swatchSize,style:c}):Pa("rect",{width:o.swatchSize,height:o.swatchSize,rx:o.swatchRadius,style:c});return Ta("g",{transform:`translate(${t.x+t.itemOffsetX+n.x},${t.y+t.itemOffsetY+n.y})`,children:[u,Pa("text",{x:o.labelOffset,y:o.swatchSize/2,dominantBaseline:"central",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:n.category})]},`legend-${i}-${a}`)})),n&&o.groups.length-1>i){const e=t.x+t.width+6;a.push(Pa("line",{x1:e,y1:0,x2:e,y2:o.height,stroke:u},"legend-group-separator-"+i))}return a});return Pa("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,"data-orientation":n?"horizontal":"vertical",children:p})}({...o,legendGroups:e.legendGroups}):me(e)?function(e){const t=Na(e),o="top"===e.position||"bottom"===e.position,n={gradient:e.gradient,legendDistance:e.legendDistance},i=Xe(n),r=We(n),s=He(e.legendLayout),a=Fe(e.axisChrome,e.legendLayout),l=Fe(void 0,e.legendLayout),c=(e.idPrefix?e.idPrefix+"-":"")+"semiotic-static-gradient-legend",u=e.gradient.format||(e=>Math.round(100*e)/100+"");let d,h;"left"===e.position?(d=e.margin.left-s-i-r,h=e.margin.top):"top"===e.position?(d=e.margin.left,h=e.margin.top-l-r-t.height):"bottom"===e.position?(d=e.margin.left,h=Math.max(e.totalHeight-e.margin.bottom+r,Math.min(e.totalHeight-e.margin.bottom+a+r,e.totalHeight-t.height))):(d=e.totalWidth-e.margin.right+s+r,h=e.margin.top);const p=Array.from({length:17},(t,n)=>{const i=n/16;return Pa("stop",{offset:100*i+"%",stopColor:e.gradient.colorFn(o?e.gradient.domain[0]+i*(e.gradient.domain[1]-e.gradient.domain[0]):e.gradient.domain[1]-i*(e.gradient.domain[1]-e.gradient.domain[0]))},n)});if(o){const o=12,n=e.gradient.label?0:void 0,i=e.gradient.label?8:0;return Ta("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,children:[Pa("defs",{children:Pa("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:p})}),e.gradient.label&&Pa("text",{x:t.width/2,y:n,textAnchor:"middle",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:e.gradient.label}),Pa("rect",{x:0,y:i,width:t.width,height:o,fill:`url(#${c})`,rx:2}),Pa("text",{x:0,y:i+o+12,textAnchor:"start",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[0])}),Pa("text",{x:t.width,y:i+o+12,textAnchor:"end",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[1])})]})}const g=e.gradient.label?-6:void 0;return Ta("g",{className:"semiotic-legend",transform:`translate(${d},${h+(e.gradient.label?12:0)})`,children:[Pa("defs",{children:Pa("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:p})}),e.gradient.label&&Pa("text",{x:0,y:g,textAnchor:"start",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:e.gradient.label}),Pa("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),Pa("text",{x:19,y:10,fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[1])}),Pa("text",{x:19,y:100,fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[0])})]})}({...o,gradient:e.gradient}):null}(e,l);return i||(fe(e)||me(e)?null:e??null)}return t.showLegend&&0!==o.length?function(e){const{categories:t,colorScheme:o,theme:n,position:i="right",totalWidth:r,totalHeight:s,margin:a}=e;if(!t||0===t.length)return null;const l=Ra(t,o,n),c="top"===i||"bottom"===i,u=Oa(e),d=Ia(t,o,n),h=e.reservedWidth??Xe(d,e.legendLayout),p="number"==typeof e.legendDistance?Math.max(0,e.legendDistance):We(d),g=He(e.legendLayout),m=Fe(e.axisChrome,e.legendLayout),f=Fe(void 0,e.legendLayout);let y,b;if("left"===i?(y=a.left-g-h-p,b=a.top):"top"===i?(y=a.left,b=a.top-f-p-u.height):"bottom"===i?(y=a.left,b=Math.max(s-a.bottom+p,Math.min(s-a.bottom+m+p,s-u.height))):(y=r-a.right+g+p,b=a.top),c){const e=u.items.map((e,t)=>Ta("g",{transform:`translate(${e.x},${e.y})`,children:[Pa("rect",{width:u.swatchSize,height:u.swatchSize,fill:l(e.category),rx:u.swatchRadius}),Pa("text",{x:u.labelOffset,y:u.swatchSize/2,dominantBaseline:"central",fontSize:za(n),fill:n.colors.text,fontFamily:n.typography.fontFamily,children:e.category})]},"legend-"+t));return Pa("g",{className:"semiotic-legend",transform:`translate(${y},${b})`,children:e})}const x=ye([{hasLabel:!1,itemCount:t.length}],Math.max(u.swatchSize,e.legendLayout?.rowHeight??La))[0],v=u.items.map((e,t)=>Ta("g",{transform:`translate(${e.x},${e.y+x.itemsY})`,children:[Pa("rect",{width:u.swatchSize,height:u.swatchSize,fill:l(e.category),rx:u.swatchRadius}),Pa("text",{x:u.labelOffset,y:u.swatchSize/2,dominantBaseline:"central",fontSize:za(n),fill:n.colors.text,fontFamily:n.typography.fontFamily,children:e.category})]},"legend-"+t));return Ta("g",{className:"semiotic-legend",transform:`translate(${y},${b})`,children:[Pa("line",{x1:0,y1:x.lineY,x2:h,y2:x.lineY,stroke:"gray"}),v]})}({categories:o,colorScheme:t.colorScheme,theme:n,position:a,totalWidth:i[0],totalHeight:i[1],margin:r,hasTitle:s,legendLayout:t.legendLayout,axisChrome:t.axisChrome,idPrefix:t._idPrefix}):null}function il(e){return Math.round(100*e)/100+""}function rl(e,t){const o=Jt(t.theme),n=t.background??o.background,i=t.idPrefix?t.idPrefix+"-":"",r="string"==typeof t.title?t.title:void 0,s=r?i+"semiotic-title":void 0,a=t.description?i+"semiotic-desc":void 0,l=[s,a].filter(Boolean).join(" ")||void 0;return Ua("svg",{xmlns:"http://www.w3.org/2000/svg",className:t.className,width:t.width,height:t.height,role:"img","aria-labelledby":l,style:{fontFamily:o.fontFamily},children:[r&&qa("title",{id:s,children:r}),t.description&&qa("desc",{id:a,children:t.description}),t.defs&&qa("defs",{children:t.defs}),n&&"transparent"!==n&&qa("rect",{x:0,y:0,width:t.width,height:t.height,fill:n}),qa("g",{id:i+"data-area",transform:t.innerTransform,children:e}),r&&qa("text",{id:i+"chart-title",x:t.width/2,y:E,textAnchor:"middle",fontSize:o.titleSize,fontWeight:"bold",fill:o.text,fontFamily:o.fontFamily,children:r}),t.legend&&qa("g",{id:i+"legend",children:t.legend}),t.outerElements]})}import{Fragment as sl,jsx as al,jsxs as ll}from"react/jsx-runtime";function cl(e,t){const o=Kt(e.theme),n=e.size||[500,300],i=ze({top:20,right:20,bottom:30,left:40,...e.margin},e.title),r=pe(e.title),s=ie(e.data),a=e.showLegend?Ea(s,e.colorAccessor||e.groupAccessor||e.categoryAccessor):[],l={hasAxis:!1!==e.showAxes,hasAxisLabel:!!e.xLabel};ol(i,{props:{...e,axisChrome:l},categories:a,theme:o,size:n,hasTitle:r});const c=n[0]-i.left-i.right,u=n[1]-i.top-i.bottom,d="streaming"===e.runtimeMode||["bar","swarm","waterfall"].includes(e.chartType),h=e.colorScheme||o.colors.categorical,p={chartType:e.chartType,windowSize:e.windowSize??200,windowMode:e.windowMode??"sliding",arrowOfTime:d?e.arrowOfTime??"right":"right",extentPadding:e.extentPadding??.1,xAccessor:d?void 0:e.xAccessor,yAccessor:d?void 0:e.yAccessor,timeAccessor:d?e.timeAccessor:void 0,valueAccessor:e.valueAccessor,colorAccessor:e.colorAccessor,sizeAccessor:e.sizeAccessor,symbolAccessor:e.symbolAccessor,symbolMap:e.symbolMap,groupAccessor:e.groupAccessor,categoryAccessor:e.categoryAccessor,lineDataAccessor:e.lineDataAccessor,xExtent:e.xExtent,yExtent:e.yExtent,axisExtent:e.axisExtent,sizeRange:e.sizeRange,xScaleType:e.xScaleType,yScaleType:e.yScaleType,scalePadding:e.scalePadding,binSize:e.binSize,normalize:e.normalize,baseline:e.baseline,stackOrder:e.stackOrder,boundsAccessor:e.boundsAccessor,boundsStyle:e.boundsStyle,band:e.band,y0Accessor:e.y0Accessor,areaGroups:e.areaGroups?e.areaGroups instanceof Set?e.areaGroups:new Set(e.areaGroups):void 0,curve:e.curve,gradientFill:Se(e.gradientFill),lineGradient:Ae(e.lineGradient),semanticLineStops:e.semanticLineStops,openAccessor:e.openAccessor,highAccessor:e.highAccessor,lowAccessor:e.lowAccessor,closeAccessor:e.closeAccessor,candlestickStyle:e.candlestickStyle,lineStyle:e.lineStyle,pointStyle:e.pointStyle,areaStyle:e.areaStyle,barStyle:e.barStyle,waterfallStyle:e.waterfallStyle,swarmStyle:e.swarmStyle,colorScheme:h,themeCategorical:o.colors.categorical,themeSemantic:Dt(o),customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,layoutSelection:e.layoutSelection,barColors:e.barColors,showValues:e.showValues,heatmapValueFormat:e.heatmapValueFormat},g=new z(p);if(e.data&&g.ingest({inserts:s,bounded:!0}),g.computeScene({width:c,height:u}),!g.scales||0===g.scene.length)return t&&(t.evidence=Sa({frameType:"xy",width:n[0],height:n[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,extraWarnings:g.scales?[]:["NO_SCALES"],margin:i})),Ma.renderToStaticMarkup(rl(null,{width:n[0],height:n[1],className:"stream-xy-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));const m=e._idPrefix,f=Ie({nodes:g.scene,renderMode:e.renderMode,fallback:(e,t)=>at(e,t,m)});t&&(t.evidence=Sa({frameType:"xy",width:n[0],height:n[1],marks:f.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,xDomain:Aa(g.scales.x?.domain?.()),yDomain:Aa(g.scales.y?.domain?.()),legendItems:a.length>0?a.length:void 0,margin:i}));const y=e.showGrid?function(e,t,o,n,i,r){const{grid:s}=Jt(o),a=n?n+"-":"",l="exact"===i?5:Math.min(5,Math.max(2,Math.floor(t.width/70))),c="exact"===i?5:Math.min(5,Math.max(2,Math.floor(t.height/30))),u=Ze(e.x,l,i),d=Ze(e.y,c,i),h=!1!==r?.find(e=>"bottom"===e.orient)?.grid,p=!1!==r?.find(e=>"left"===e.orient)?.grid,g=De(r?.find(e=>"bottom"===e.orient)?.gridStyle),m=De(r?.find(e=>"left"===e.orient)?.gridStyle);return Ua("g",{id:a+"grid",className:"semiotic-grid",opacity:.8,children:[h&&u.map((o,n)=>{const i=e.x(o);return qa("line",{x1:i,y1:0,x2:i,y2:t.height,stroke:s,strokeWidth:.5,strokeDasharray:g},"gx-"+n)}),p&&d.map((o,n)=>{const i=e.y(o);return qa("line",{x1:0,y1:i,x2:t.width,y2:i,stroke:s,strokeWidth:.5,strokeDasharray:m},"gy-"+n)})]})}(g.scales,{width:c,height:u},o,m,e.axisExtent,e.axes):null,b=f.map(e=>e.element),x=Za(e)+"-plot-clip",v=!1!==e.showAxes?function(e,t,o,n,i){const r=Jt(n),s=He(o.legendLayout),a=o.legend&&"left"===o.legendPosition&&s>0?s:o.margin?.left??40,l="exact"===o.axisExtent?5:Math.min(5,Math.max(2,Math.floor(t.width/70))),c="exact"===o.axisExtent?5:Math.min(5,Math.max(2,Math.floor(t.height/30))),u=o.axes?.find(e=>"bottom"===e.orient),d=o.axes?.find(e=>"left"===e.orient),h=u?.tickValues??Ze(e.x,u?.ticks??l,o.axisExtent),p=h.map(e=>e.valueOf()),g=u?.tickFormat||o.xFormat||o.tickFormatTime||il,m=h.map((t,o)=>({pixel:e.x(t),label:g(t,o,p)})),f=d?.tickValues??Ze(e.y,d?.ticks??c,o.axisExtent),y=d?.tickFormat||o.yFormat||o.tickFormatValue||il,b=f.map(t=>({pixel:e.y(t),label:y(t)})),x=u?.label??o.xLabel,v=d?.label??o.yLabel;return Ua("g",{id:(i?i+"-":"")+"axes",className:"stream-axes",children:[!1!==u?.baseline&&qa("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:r.border,strokeWidth:1}),m.map((e,o)=>Ua("g",{transform:`translate(${e.pixel},${t.height})`,children:[qa("line",{y2:5,stroke:r.border,strokeWidth:1}),qa("text",{y:18,textAnchor:"middle",fontSize:r.tickSize,fill:r.textSecondary,fontFamily:r.fontFamily,children:e.label})]},"xtick-"+o)),x&&qa("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:r.labelSize,fill:r.text,fontFamily:r.fontFamily,children:x}),!1!==d?.baseline&&qa("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:r.border,strokeWidth:1}),b.map((e,t)=>Ua("g",{transform:`translate(0,${e.pixel})`,children:[qa("line",{x2:-5,stroke:r.border,strokeWidth:1}),qa("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:r.tickSize,fill:r.textSecondary,fontFamily:r.fontFamily,children:e.label})]},"ytick-"+t)),v&&qa("text",{x:15-a,y:t.height/2,textAnchor:"middle",fontSize:r.labelSize,fill:r.text,fontFamily:r.fontFamily,transform:`rotate(-90, ${15-a}, ${t.height/2})`,children:v})]})}(g.scales,{width:c,height:u},e,o,m):null,w=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,annotationData:s,scales:{x:g.scales.x,y:g.scales.y},layout:{width:c,height:u},theme:o,xAccessor:"string"==typeof e.xAccessor?e.xAccessor:void 0,yAccessor:"string"==typeof e.yAccessor?e.yAccessor:void 0,idPrefix:m}):null,A=e.svgPreRenderers&&g.scales?e.svgPreRenderers.map((e,t)=>{try{return al(ka.Fragment,{children:e(g.scene,g.scales,{width:c,height:u})},"pre-"+t)}catch{return null}}).filter(Boolean):null,S=nl({props:{...e,axisChrome:l},categories:a,theme:o,size:n,margin:i,hasTitle:r});return Ma.renderToStaticMarkup(rl(ll(sl,{children:[e.backgroundGraphics,A,y,al("defs",{children:al("clipPath",{id:x,children:al("rect",{x:0,y:0,width:c,height:u})})}),al("g",{clipPath:`url(#${x})`,children:b}),v,w,e.foregroundGraphics,g.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-xy-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:c,innerHeight:u,legend:S,idPrefix:e._idPrefix}))}import*as ul from"react-dom/server";import{scaleBand as dl,scaleLinear as hl}from"d3-scale";var pl=class{constructor(){this.colorSchemeMap=new Map,this.colorSchemeIndex=0}resetColors(){this.colorSchemeMap.clear(),this.colorSchemeIndex=0}resolvePieceStyle(e,t,o){if(t&&"function"==typeof e.pieceStyle){const n=e.pieceStyle(t,o);return n&&!n.fill&&o?{...n,fill:this.getColorFromScheme(e,o)}:n}return e.pieceStyle&&"object"==typeof e.pieceStyle?e.pieceStyle:e.barColors&&o?{fill:e.barColors[o]||"#007bff"}:{fill:o?this.getColorFromScheme(e,o):"#007bff"}}resolveSummaryStyle(e,t,o){return t&&"function"==typeof e.summaryStyle?e.summaryStyle(t,o):e.summaryStyle&&"object"==typeof e.summaryStyle?e.summaryStyle:{fill:"#007bff",fillOpacity:.6,stroke:"#007bff",strokeWidth:1}}getColorFromScheme(e,t){const o=this.colorSchemeMap.get(t);if(o)return o;const n=Array.isArray(e.colorScheme)?e.colorScheme:e.themeCategorical||F,i=n[this.colorSchemeIndex%n.length];return this.colorSchemeIndex++,this.colorSchemeMap.set(t,i),i}};function gl(e){const t=e.getSymbol;return t?_t(t,e.config.symbolMap):null}function ml(e,t,o,n,i,r,s){e.push(t?{type:"symbol",x:n,y:i,size:Math.PI*r*r,symbolType:t(o),style:s,datum:o}:{type:"point",x:n,y:i,r:r,style:s,datum:o})}function fl(e,t){const{columns:o,config:n,resolvePieceStyle:i}=e,r=[],s=Math.min(t.width,t.height)/2-4,a="donut"===n.chartType?n.innerRadius||60:0,l=-Math.PI/2+(n.startAngle||0)*Math.PI/180,c=null!=n.sweepAngle?n.sweepAngle*Math.PI/180:2*Math.PI,u=null!=n.sweepAngle&&360>n.sweepAngle,d=Object.values(o),h=d.some(e=>{const t=e.pieceData[0];return t&&("number"==typeof t._pct||"number"==typeof t._pctStart||null!=t._roundedEnds)}),p=u&&!h&&d.length>1&&(n.cornerRadius??0)>0;for(let e=0;d.length>e;e++){const t=d[e],o=t.pieceData[0],u="number"==typeof o?._pctStart?o._pctStart:t.pctStart,h=l+u*c,g=l+(u+("number"==typeof o?._pct?o._pct:t.pct))*c,m=i(t.pieceData[0],t.name),f=0===e,y=e===d.length-1,b={type:"wedge",cx:0,cy:0,innerRadius:a,outerRadius:s,startAngle:h,endAngle:g,...n.cornerRadius&&{cornerRadius:n.cornerRadius},style:m,datum:o?._nonInteractive?null:t.pieceData,category:t.name};o?._roundedEnds?b.roundedEnds=o._roundedEnds:p&&(b.roundedEnds={start:f,end:y}),o?._gradientBand&&(b._gradientBand=o._gradientBand),r.push(b)}return r}import{quantile as yl}from"d3-array";function bl(e){const t=e.length,o=e[0],n=e[t-1];return{n:t,min:o,q1:yl(e,.25)??o,median:yl(e,.5)??(o+n)/2,q3:yl(e,.75)??n,max:n,mean:e.reduce((e,t)=>e+t,0)/t}}import{scaleLinear as xl}from"d3-scale";var vl={bar:function(e,t){const{scales:o,columns:n,config:i,getR:r,getStack:s,resolvePieceStyle:a}=e,{r:l,projection:c}=o,u=[],d="vertical"===c,h="horizontal"===c,p=i.normalize,g=[];if(s){const e=new Set;for(const t of Object.values(n))for(const o of t.pieceData){const t=s(o);e.has(t)||(e.add(t),g.push(t))}}else g.push("_default");for(const e of Object.values(n)){const t=new Map;for(const o of e.pieceData){const e=s?s(o):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const n=t.get(e);n.total+=r(o),n.pieces.push(o)}let o=0;if(p)for(const e of t.values())o+=Math.abs(e.total);let n=0,i=0;for(const r of g){const c=t.get(r);if(!c)continue;let g=c.total;p&&o>0&&(g/=o);const m=a(c.pieces[0],s?r:e.name),f={...c.pieces[0],__aggregateValue:c.total,__pieceCount:c.pieces.length,category:e.name};if(d){const t=l(0>g?i:n+g),o=0>g?l(i+g)-l(i):l(n)-l(n+g);u.push(Y(e.x,t,e.width,Math.abs(o),m,f,r)),0>g?i+=g:n+=g}else if(h){const t=l(0>g?i+g:n),o=0>g?l(i)-l(i+g):l(n+g)-l(n);u.push(Y(t,e.x,Math.abs(o),e.width,m,f,r)),0>g?i+=g:n+=g}}}const m="vertical"===c,f=i.roundedTop&&i.roundedTop>0?Math.max(0,i.roundedTop):0;for(const e of u){if("rect"!==e.type)continue;const t=e.datum?.__aggregateValue??0;e.roundedEdge=m?0>t?"bottom":"top":0>t?"left":"right",i.gradientFill&&(e.fillGradient=i.gradientFill)}if(f>0){const e=new Map;for(const t of u){if("rect"!==t.type)continue;const o=t.datum?.category||"";e.has(o)||e.set(o,[]),e.get(o).push(t)}for(const t of e.values()){if(0===t.length)continue;const e=t.filter(e=>(e.datum?.__aggregateValue??0)>=0),o=t.filter(e=>0>(e.datum?.__aggregateValue??0));e.length>0&&(e.reduce(m?(e,t)=>t.y>e.y?e:t:(e,t)=>e.x+e.w>t.x+t.w?e:t).roundedTop=f),o.length>0&&(o.reduce(m?(e,t)=>e.y+e.h>t.y+t.h?e:t:(e,t)=>t.x>e.x?e:t).roundedTop=f)}}return u},clusterbar:function(e,t){const{scales:o,columns:n,config:i,getR:r,getGroup:s,resolvePieceStyle:a}=e,{r:l,projection:c}=o,u=[],d="vertical"===c,h=[],p=new Set;for(const e of Object.values(n))for(const t of e.pieceData){const e=s?s(t):"_default";p.has(e)||(p.add(e),h.push(e))}const g=h.length||1;for(const e of Object.values(n)){const t=e.width/g,o=.2*t,n=t-o,i=new Map;for(const t of e.pieceData){const e=s?s(t):"_default";i.has(e)||i.set(e,[]),i.get(e).push(t)}for(let s=0;h.length>s;s++){const c=i.get(h[s])||[];for(const i of c){const c=r(i),p=a(i,h[s]);if(d){const r=e.x+s*t+o/2,a=l(0),d=l(c);u.push(Y(r,Math.min(a,d),n,Math.abs(a-d),p,i,h[s]))}else{const r=e.x+s*t+o/2,a=l(0),d=l(c);u.push(Y(Math.min(a,d),r,Math.abs(d-a),n,p,i,h[s]))}}}}const m=i.roundedTop&&i.roundedTop>0?Math.max(0,i.roundedTop):0;for(const e of u){if("rect"!==e.type)continue;if(null==e.datum)continue;const t=r(e.datum);m>0&&(e.roundedTop=m),e.roundedEdge=d?0>t?"bottom":"top":0>t?"left":"right",i.gradientFill&&(e.fillGradient=i.gradientFill)}return u},point:function(e,t){const{scales:o,columns:n,getR:i,multiScales:r,resolvePieceStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d="radial"===l,h=r.length>0,p=gl(e),g=2*Math.PI,m=-Math.PI/2;for(const e of Object.values(n))for(const t of e.pieceData){const o=t.__rIndex??0,n=t.__rValue??i(t),l=h&&r[o]||a,f=s(t,e.name),y=f.r||5;let b,x;if(d){const t=m+(e.pctStart+e.pct/2)*g,o=l(n);b=Math.cos(t)*o,x=Math.sin(t)*o}else u?(b=e.middle,x=l(n)):(b=l(n),x=e.middle);ml(c,p,t,b,x,y,f)}return c},swarm:function(e,t){const{scales:o,columns:n,getR:i,resolvePieceStyle:r}=e,{r:s,projection:a}=o,l=[],c="vertical"===a,u=gl(e);for(const e of Object.values(n)){const t=e.width/2;for(let o=0;e.pieceData.length>o;o++){const n=e.pieceData[o],a=i(n),d=r(n,e.name),h=d.r||4,p=(7919*o%100/100-.5)*t*.8;ml(l,u,n,c?e.middle+p:s(a),c?s(a):e.middle+p,h,d)}}return l},pie:fl,donut:fl,boxplot:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d=!1!==i.showOutliers;for(const t of Object.values(n)){const o=t.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(0===o.length)continue;const n=o[0],i=o[o.length-1],l=yl(o,.25)??n,h=yl(o,.5)??(n+i)/2,p=yl(o,.75)??i,g=p-l,m=l-1.5*g,f=p+1.5*g,y=o.find(e=>e>=m)??n,b=[...o].reverse().find(e=>f>=e)??i,x=s(t.pieceData[0],t.name),v=[];if(d)for(const e of t.pieceData){const o=r(e);if(m>o||o>f){const n=u?t.middle:a(o),i=u?a(o):t.middle;v.push({px:n,py:i,value:o,datum:e})}}if(c.push({type:"boxplot",x:u?t.middle:0,y:u?0:t.middle,projection:u?"vertical":"horizontal",columnWidth:.6*t.width,minPos:a(y),q1Pos:a(l),medianPos:a(h),q3Pos:a(p),maxPos:a(b),stats:{n:o.length,min:y,q1:l,median:h,q3:p,max:b,mean:o.reduce((e,t)=>e+t,0)/o.length},style:x,datum:t.pieceData,category:t.name,outliers:v}),d)for(const t of v)c.push({type:"point",x:t.px,y:t.py,r:3,style:{fill:x.fill||e.config.themeSemantic?.secondary||"#999",opacity:.6},datum:t.datum})}return c},violin:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d=i.bins||20,h=!1!==i.showIQR;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(2>t.length)continue;const o=t[0],n=t[t.length-1],i=(n-o)/d||1,l=Array(d).fill(0);for(const e of t)l[Math.min(Math.floor((e-o)/i),d-1)]++;const p=zt(l,1),g=e.width/2*.9;let m;if(u){m=`M ${e.middle} ${a(o)}`;for(let t=0;d>t;t++){const n=a(o+(t+.5)*i);m+=` L ${e.middle+l[t]/p*g} ${n}`}m+=` L ${e.middle} ${a(n)}`;for(let t=d-1;t>=0;t--){const n=a(o+(t+.5)*i);m+=` L ${e.middle-l[t]/p*g} ${n}`}m+=" Z"}else{m=`M ${a(o)} ${e.middle}`;for(let t=0;d>t;t++)m+=` L ${a(o+(t+.5)*i)} ${e.middle-l[t]/p*g}`;m+=` L ${a(n)} ${e.middle}`;for(let t=d-1;t>=0;t--)m+=` L ${a(o+(t+.5)*i)} ${e.middle+l[t]/p*g}`;m+=" Z"}const f=s(e.pieceData[0],e.name);let y;if(h&&t.length>=4){const i=yl(t,.25)??o,r=yl(t,.5)??(o+n)/2,s=yl(t,.75)??n;y={q1Pos:a(i),medianPos:a(r),q3Pos:a(s),centerPos:e.middle,isVertical:u}}const b=u?{x:e.x,y:Math.min(a(n),a(o)),width:e.width,height:Math.abs(a(n)-a(o))}:{x:Math.min(a(o),a(n)),y:e.x,width:Math.abs(a(n)-a(o)),height:e.width};c.push({type:"violin",pathString:m,translateX:0,translateY:0,bounds:b,iqrLine:y,stats:bl(t),style:f,datum:e.pieceData,category:e.name})}return c},histogram:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a}=o,l=[],c=i.bins||25,u=i.normalize,d=a.domain?.(),h=d?+d[0]:void 0,p=d?+d[1]:void 0;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e));if(0===t.length)continue;const[o,n]=Ot(t),i=null!=h&&isFinite(h)?h:o,d=null!=p&&isFinite(p)?p:n,g=(d-i)/c||1,m=Array(c).fill(0);for(const e of t)i>e||e>d||m[Math.min(Math.floor((e-i)/g),c-1)]++;const f=t.length,y=zt(m,1),b=s(e.pieceData[0],e.name);for(let t=0;c>t;t++){if(0===m[t])continue;const o=(u?m[t]/f:m[t]/y)*e.width*.9,n=a(i+t*g),r=a(i+(t+1)*g);l.push(Y(Math.min(n,r),e.x+e.width-o,Math.abs(r-n),o,b,{bin:t,count:m[t],range:[i+t*g,i+(t+1)*g],category:e.name},e.name))}}return l},ridgeline:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u=i.bins||20,d="horizontal"===l,h=i.amplitude||1.5;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(2>t.length)continue;const o=t[0],n=t[t.length-1],i=(n-o)/u||1,l=Array(u).fill(0);for(const e of t)o>e||e>n||l[Math.min(Math.floor((e-o)/i),u-1)]++;const p=zt(l,1),g=s(e.pieceData[0],e.name),m=e.width*h;let f;if(d){const t=e.x+e.width;f=`M ${a(o)} ${t}`;for(let e=0;u>e;e++)f+=` L ${a(o+(e+.5)*i)} ${t-l[e]/p*m}`;f+=` L ${a(n)} ${t} Z`}else{const t=e.x;f=`M ${t} ${a(o)}`;for(let e=0;u>e;e++){const n=a(o+(e+.5)*i);f+=` L ${t+l[e]/p*m} ${n}`}f+=` L ${t} ${a(n)} Z`}const y=d?{x:Math.min(a(o),a(n)),y:e.x,width:Math.abs(a(n)-a(o)),height:e.width}:{x:e.x,y:Math.min(a(n),a(o)),width:e.width,height:Math.abs(a(n)-a(o))};c.push({type:"violin",pathString:f,translateX:0,translateY:0,bounds:y,stats:bl(t),style:{...g,fillOpacity:g.fillOpacity??.5},datum:e.pieceData,category:e.name})}return c},timeline:function(e,t){const{scales:o,columns:n,getRawRange:i,resolvePieceStyle:r}=e,{r:s,projection:a}=o,l=[],c="horizontal"===a;for(const e of Object.values(n))for(const t of e.pieceData){const o=i(t);if(!o)continue;const[n,a]=o,u=r(t,e.name);if(c){const o=s(Math.min(n,a)),i=s(Math.max(n,a));l.push(Y(o,e.x,i-o,e.width,u,t,e.name))}else{const o=s(Math.max(n,a)),i=s(Math.min(n,a));l.push(Y(e.x,o,e.width,i-o,u,t,e.name))}}return l},funnel:function(e,t){const{columns:o,getR:n,getStack:i,resolvePieceStyle:r}=e,s=[],a=t.width/2,l=!1!==e.config.showLabels,c=e.scales.o.domain().map(e=>o[e]).filter(Boolean);if(0===c.length)return s;const u=[],d=new Set;for(const e of c)for(const t of e.pieceData){const e=i?i(t):"_default";d.has(e)||(d.add(e),u.push(e))}const h=u.length>1&&"_default"!==u[0],p=[];let g=0;for(const e of c){const t=new Map;let o=0;for(const r of e.pieceData){const e=i?i(r):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const s=t.get(e),a=n(r);s.total+=a,s.pieces.push(r),o+=a}p.push({col:e,groups:t,stepTotal:o}),h||o>g&&(g=o)}if(h)for(const e of p){let t=0,o=0;for(let n=0;u.length>n;n++){const i=e.groups.get(u[n]);i&&(n%2==0?t+=i.total:o+=i.total)}const n=Math.max(t,o);n>g&&(g=n)}if(0===g)return s;const m=new Map;for(const e of u){const t=p[0].groups.get(e);m.set(e,t?.total??0)}const f=p[0].stepTotal,y=h?.95*a:.9*t.width,b=xl().domain([0,g]).range([0,y]),x=e.config.connectorOpacity??.3;let v=new Map;for(let t=0;p.length>t;t++){const o=p[t],n=o.col,i=0===t,c=n.width,d=.55*c,g=n.x+(c-d)/2,y=new Map;if(h){let e=0;for(const t of u){const n=o.groups.get(t);n&&(e+=b(n.total))}let t=a,c=a;for(let h=0;u.length>h;h++){const p=u[h],f=o.groups.get(p);if(!f)continue;const x=b(f.total),v=h%2==0,w=v?t:c-x;v?t+=x:c-=x;const A=r(f.pieces[0],p),S=m.get(p)??f.total,k={...f.pieces[0],__funnelValue:f.total,__funnelPercent:S>0?f.total/S*100:0,__funnelStep:n.name,__funnelIsFirstStep:i,__aggregateValue:f.total,__pieceCount:f.pieces.length,category:p};l&&(0===h&&(k.__funnelStepLabel=n.name,k.__funnelStepLabelX=a,k.__funnelStepLabelY=g,k.__funnelRowWidth=e),k.__funnelValueLabelX=w+x/2,k.__funnelValueLabelY=g,k.__funnelBarW=x),s.push(Y(w,g,x,d,A,k,p)),y.set(p,{x:w,y:g,w:x,h:d})}}else{const e=o.stepTotal,t=b(e),c=a-t/2,h=u[0],p="_default"!==h,m=o.groups.get(h)?.pieces[0]??n.pieceData[0],x=p?h:n.name,v=r(m,x),w=f>0?e/f*100:0,A={...m,__funnelValue:e,__funnelPercent:w,__funnelStep:n.name,__funnelIsFirstStep:i,category:p?h:n.name};l&&(A.__funnelStepLabel=n.name,A.__funnelStepLabelX=a,A.__funnelStepLabelY=g,A.__funnelRowWidth=t,A.__funnelValueLabelX=a,A.__funnelValueLabelY=g,A.__funnelBarW=t),s.push(Y(c,g,t,d,v,A,x)),y.set(h,{x:c,y:g,w:t,h:d})}if(t>0&&v.size>0){const t=h?u:[u[0]];for(const i of t){const t=v.get(i),a=y.get(i);if(!t||!a)continue;const l=(()=>{const e=o.groups.get(i);return r(e?e.pieces[0]:n.pieceData[0],"_default"===i?n.name:i)})(),c={type:"trapezoid",points:[[t.x,t.y+t.h],[t.x+t.w,t.y+t.h],[a.x+a.w,a.y],[a.x,a.y]],style:{fill:l.fill||e.config.themeSemantic?.secondary||"#999",opacity:x},datum:o.groups.get(i)?.pieces[0]??n.pieceData[0],category:"_default"===i?n.name:i};s.push(c)}}v=y}return s},"bar-funnel":function(e,t){const{columns:o,getR:n,getStack:i,resolvePieceStyle:r,scales:s}=e,a=[],l=s.o.domain().map(e=>o[e]).filter(Boolean);if(0===l.length)return a;const c=[],u=new Set;for(const e of l)for(const t of e.pieceData){const e=i?i(t):"_default";u.has(e)||(u.add(e),c.push(e))}const d=c.length>1&&"_default"!==c[0],h=[];for(const e of l){const t=new Map;let o=0;for(const r of e.pieceData){const e=i?i(r):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const s=t.get(e),a=n(r);s.total+=a,s.pieces.push(r),o+=a}h.push({col:e,groups:t,stepTotal:o})}const p=new Map;for(const e of c){const t=h[0]?.groups.get(e);p.set(e,t?.total??0)}const g=s.r,m=d?c.length:1,f=d?.15:0;for(let e=0;h.length>e;e++){const t=h[e],o=t.col,n=0===e,i=e>0?h[e-1]:null,s=o.width/m,l=s*f,u=s-l;for(let e=0;c.length>e;e++){const h=c[e],m=t.groups.get(h);if(!m)continue;const f=m.total,y=p.get(h)??f,b=y>0?f/y*100:0,x=i?.groups.get(h),v=n?0:Math.max(0,(x?.total??f)-f),w=o.x+e*s+l/2,A=g(f),S=g(0)-A,k=r(m.pieces[0],d?h:o.name),M={...m.pieces[0],__barFunnelValue:f,__barFunnelPercent:b,__barFunnelIsFirstStep:n,__barFunnelIsDropoff:!1,__barFunnelStep:o.name,__barFunnelDropoffValue:v,__barFunnelCategory:"_default"===h?void 0:h,category:d?h:o.name,__barFunnelLabelX:w+u/2,__barFunnelLabelY:g(f+v)};if(a.push(Y(w,A,u,S,k,M,d?h:o.name)),v>0){const e=g(f+v),t=A-e,n={...k},i={...m.pieces[0],__barFunnelValue:v,__barFunnelPercent:y>0?v/y*100:0,__barFunnelIsFirstStep:!1,__barFunnelIsDropoff:!0,__barFunnelStep:o.name,__barFunnelCategory:"_default"===h?void 0:h,category:d?h:o.name};a.push(Y(w,e,u,t,n,i,d?h:o.name))}}}return a},swimlane:function(e,t){const{scales:o,columns:n,getR:i,getStack:r,resolvePieceStyle:s}=e,{r:a,projection:l}=o,c=[],u="horizontal"===l,d=e.config.gradientFill,h=u?"left":"bottom",p=e.config.trackFill;if(p){const e="string"==typeof p?p:p.color,t="string"==typeof p?1:p.opacity??1,[o,i]=a.range(),r=Math.min(o,i),s=Math.abs(i-o);for(const o of Object.values(n)){const n={fill:e,opacity:t},i=u?Y(r,o.x,s,o.width,n,null,"__track__"):Y(o.x,r,o.width,s,n,null,"__track__");c.push(i)}}const g=e.config.roundedTop&&e.config.roundedTop>0?Math.max(0,e.config.roundedTop):0;for(const e of Object.values(n)){let t=0;const o=c.length;for(const o of e.pieceData){const n=Math.abs(i(o));if(0===n)continue;const l=r?r(o):e.name,p=s(o,l);let g;if(u){const i=a(t),r=a(t+n);g=Y(i,e.x,r-i,e.width,p,o,l)}else{const i=a(t+n),r=a(t);g=Y(e.x,i,e.width,r-i,p,o,l)}d&&(g.fillGradient=d,g.roundedEdge=h),c.push(g),t+=n}if(g>0&&c.length>o){const e=c.slice(o),t=e[0],n=e[e.length-1];1===e.length?t.cornerRadii={tl:g,tr:g,br:g,bl:g}:u?(t.cornerRadii={tl:g,bl:g},n.cornerRadii={tr:g,br:g}):(t.cornerRadii={bl:g,br:g},n.cornerRadii={tl:g,tr:g})}}return c}},wl=["data","domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Al=["scene-style","data-paint","accessibility","evidence"],Sl=(e,t)=>({retainedData:e,invalidations:t}),kl=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Ml=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],_l=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Pl=["scene-geometry","data-paint","accessibility","evidence"],Tl=["scene-style","data-paint","accessibility","evidence"],Ll=[],Rl={chartType:Sl("rebuild",kl),runtimeMode:Sl("rebuild",kl),categoryAccessor:Sl("rebuild",kl),valueAccessor:Sl("rebuild",kl),oAccessor:Sl("rebuild",kl),rAccessor:Sl("rebuild",kl),stackBy:Sl("rebuild",kl),groupBy:Sl("rebuild",kl),timeAccessor:Sl("rebuild",kl),accessorRevision:Sl("rebuild",kl),colorAccessor:Sl("rebuild",Tl),symbolAccessor:Sl("rebuild",Pl),connectorAccessor:Sl("rebuild",Pl),dataIdAccessor:Sl("rebuild",Pl),projection:Sl("preserve",Ml),extentPadding:Sl("preserve",Ml),axisExtent:Sl("preserve",Ml),rExtent:Sl("preserve",Ml),oExtent:Sl("preserve",Ml),multiAxis:Sl("preserve",Ml),normalize:Sl("preserve",Ml),bins:Sl("preserve",Ml),oSort:Sl("preserve",_l),barPadding:Sl("preserve",_l),roundedTop:Sl("preserve",_l),baselinePadding:Sl("preserve",_l),innerRadius:Sl("preserve",_l),cornerRadius:Sl("preserve",_l),startAngle:Sl("preserve",_l),sweepAngle:Sl("preserve",_l),trackFill:Sl("preserve",_l),showOutliers:Sl("preserve",_l),showIQR:Sl("preserve",_l),amplitude:Sl("preserve",_l),connectorOpacity:Sl("preserve",_l),showLabels:Sl("preserve",_l),dynamicColumnWidth:Sl("rebuild",_l),customLayout:Sl("preserve",_l),layoutConfig:Sl("preserve",_l),layoutMargin:Sl("preserve",_l),symbolMap:Sl("preserve",Pl),pieceStyle:Sl("preserve",Tl),summaryStyle:Sl("preserve",Tl),connectorStyle:Sl("preserve",Tl),gradientFill:Sl("preserve",Tl),colorScheme:Sl("preserve",Tl),themeCategorical:Sl("preserve",Tl),themeSemantic:Sl("preserve",Tl),themeSequential:Sl("preserve",Tl),themeDiverging:Sl("preserve",Tl),barColors:Sl("preserve",Tl),decay:Sl("preserve",Tl),pulse:Sl("preserve",Tl),staleness:Sl("preserve",Tl),layoutSelection:Sl("preserve",Tl),windowSize:Sl("preserve",Ll),windowMode:Sl("preserve",Ll),clock:Sl("preserve",Ll),transition:Sl("preserve",Ll),introAnimation:Sl("preserve",Ll),onLayoutError:Sl("preserve",Ll)},Il=Sl("preserve",_l),Cl=class{constructor(){this.tracker=new mt}get last(){return this.tracker.last}subscribe(e){return this.tracker.subscribe(e)}recordData(e,t){return this.tracker.record({kind:e,...void 0===t?{}:{count:t}},wl)}recordNoop(e){return this.tracker.record({kind:e,..."restyle"===e?{}:{count:0}},[])}recordRestyle(e){return e?this.tracker.record({kind:"restyle"},Al):this.recordNoop("restyle")}recordConfig(e){const t=function(e){let t="preserve";const o=new Set;for(const n of e){const e=Rl[n]??Il;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)o.add(t)}return{retainedData:t,invalidations:o}}(e);return this.tracker.record({kind:"config",keys:e},t.invalidations)}};import{quadtree as zl}from"d3-quadtree";var Fl=class{constructor(e){this.rExtent=new ct,this.rExtents=[],this.windowSizeWarned=!1,this.updateResults=new Cl,this.rAccessors=[],this.categories=new Set,this._hasStreamingData=!1,this.styleResolver=new pl,this.timestampBuffer=null,this.activeTransition=null,this.prevPositionMap=new Map,this.exitNodes=[],this.lastIngestTime=0,this.scales=null,this.multiScales=[],this.scene=[],this.columns={},this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customLayoutFailedThisBuild=!1,this._customLayoutDiagnosticsWarned=new Set,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this.version=0,this._dataVersion=0,this._bufferArrayCache=null,this._pointQuadtree=null,this._maxPointRadius=0,this._datumIndexCache=null,this._categoryIndexCache=null,this._hasRenderedOnce=!1,this.config=e,this.buffer=new ut(e.windowSize),this.getO=Ct(e.categoryAccessor||e.oAccessor,"category");const t=e.valueAccessor||e.rAccessor;Array.isArray(t)?(this.rAccessors=t.map(e=>It(e,"value")),this.getR=this.rAccessors[0],this.rExtents=t.map(()=>new ct)):(this.getR=It(t,"value"),this.rAccessors=[this.getR],this.rExtents=[this.rExtent]),this.getStack=Ct(e.stackBy),this.getGroup=Ct(e.groupBy),this.getColor=Ct(e.colorAccessor),this.getSymbol=Ct(e.symbolAccessor),this.getConnector=Ct(e.connectorAccessor),this.getDataId=Ct(e.dataIdAccessor),e.pulse&&(this.timestampBuffer=new ut(e.windowSize))}syncPulseTimestampBuffer(){var e,t,o,n;this.timestampBuffer=(e=!!this.config.pulse,t=this.buffer,o=this.timestampBuffer,n=this.currentTime(),e?null!=o&&o.capacity===t.capacity&&o.size===t.size?o:te(t,n):null)}currentTime(){return this.config.clock?.()??Me()}ingest(e){const t=this.currentTime();if(this.lastIngestTime=t,this._dataVersion++,e.bounded){this.buffer.clear(),this.rExtent.clear();for(const e of this.rExtents)e.clear();e.preserveCategoryOrder?this._hasStreamingData=!0:this.categories.clear(),this.timestampBuffer&&this.timestampBuffer.clear(),ne(this.buffer,e.totalSize||e.inserts.length,this.timestampBuffer);for(const o of e.inserts)Pe(this.buffer,o,this.timestampBuffer,t),this.categories.add(this.getO(o)),this.pushValueExtent(o)}else{this._hasStreamingData=!0;for(const o of e.inserts){const e=Pe(this.buffer,o,this.timestampBuffer,t);this.categories.add(this.getO(o)),this.pushValueExtent(o),null!=e&&this.evictValueExtent(e)}}return this.updateResults.recordData(e.bounded?"replace":"ingest",e.inserts.length),!0}ingestWithResult(e){return this.ingest(e),this.updateResults.last}pushValueExtent(e){if("timeline"===this.config.chartType){const t=this.getRawRange(e);t&&(this.rExtent.push(t[0]),this.rExtent.push(t[1]))}else if(this.rAccessors.length>1){for(let t=0;this.rAccessors.length>t;t++)this.rExtents[t].push(this.rAccessors[t](e));this.rExtent.push(this.getR(e))}else this.rExtent.push(this.getR(e))}evictValueExtent(e){if("timeline"===this.config.chartType){const t=this.getRawRange(e);t&&(this.rExtent.evict(t[0]),this.rExtent.evict(t[1]))}else if(this.rAccessors.length>1){for(let t=0;this.rAccessors.length>t;t++)this.rExtents[t].evict(this.rAccessors[t](e));this.rExtent.evict(this.getR(e))}else this.rExtent.evict(this.getR(e))}getRawRange(e){const t=this.config.valueAccessor||this.config.rAccessor;if(!t)return null;const o="function"==typeof t?t(e):e[t];return Array.isArray(o)&&o.length>=2?[+o[0],+o[1]]:null}computeScene(e){const{config:t,buffer:o}=this,n=this.scales,i=this.multiScales,r=this.columns;if(0===o.size)return this.scales=null,this.multiScales=[],this.scene=[],this.columns={},this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,void this.version++;this.rExtent.dirty&&this.rExtent.recalculate(o,this.getR);const s=this.getBufferArray(),a=t.projection||"vertical",l=t.oExtent||this.resolveCategories(s),c=this.computeValueDomain(s,l),u="horizontal"===a,d="radial"===a,h=Math.min(.9,Math.max(0,null!=t.barPadding?t.barPadding/("vertical"===a?e.width:e.height):.1));let p,g;if(d){p=dl().domain(l).range([0,1]).padding(0);const o=Math.min(e.width,e.height)/2,n=t.innerRadius||0;g=hl().domain(c).range([n,o])}else u?(p=dl().domain(l).range([0,e.height]).padding(h),g=hl().domain(c).range([0,e.width])):(p=dl().domain(l).range([0,e.width]).padding(h),g=hl().domain(c).range([e.height,0]));this.scales={o:p,r:g,projection:a},this.multiScales=this.rAccessors.length>1&&t.multiAxis?this.rAccessors.map((n,i)=>{const r=this.rExtents[i];r.dirty&&r.recalculate(o,n);let[s,a]=r.extent;s===1/0&&(s=0,a=1);const l=a-s,c=l>0?l*(t.extentPadding??.05):1;return s-=c,a+=c,s>0&&(s=0),u?hl().domain([s,a]).range([0,e.width]):hl().domain([s,a]).range([e.height,0])}):[];let m=s;this.rAccessors.length>1&&(m=s.flatMap(e=>this.rAccessors.map((t,o)=>({...e,__rIndex:o,__rValue:t(e),__rName:this.resolveRAccessorName(o)})))),this.columns=this.buildColumns(m,l,p,a,e),this._customLayoutFailedThisBuild=!1;const f=this.buildSceneNodes(m,e);this._customLayoutFailedThisBuild?!0===this.lastCustomLayoutFailure?.preservedLastGoodScene?(this.scales=n,this.multiScales=i,this.columns=r):(this.scene=[],this.rebuildPointQuadtree()):(this.config.transition&&this.scene.length>0&&this.snapshotPositions(),this.scene=f,this.rebuildPointQuadtree(),this.config.decay&&this.applyDecay(this.scene,s),this.config.pulse&&this.applyPulse(this.scene,s),this.config.transition&&!this._hasRenderedOnce&&this.scene.length>0&&(this.config.introAnimation&&this.synthesizeIntroPositions(),this._hasRenderedOnce=!0),this.config.transition&&this.prevPositionMap.size>0&&this.startTransition(),this.version++)}resolveRAccessorName(e){const t=this.config.valueAccessor||this.config.rAccessor,o=Array.isArray(t)?t[e]:t;return"string"==typeof o?o:"value"+e}resolveCategories(e){const t=this.config.oSort,o="streaming"===this.config.runtimeMode||this._hasStreamingData,n="auto"===t?void 0:t;let i=null;if(o){i=new Set;for(const t of e)i.add(this.getO(t))}const r=i?Array.from(this.categories).filter(e=>i.has(e)):Array.from(this.categories);if(o&&void 0===n){const e=Math.max(50,3*i.size);if(this.categories.size>e){let t=this.categories.size-e;for(const e of this.categories){if(0>=t)break;i.has(e)||(this.categories.delete(e),t--)}}return r}if(!1===n)return r;if("function"==typeof n)return r.sort(n);const s=new Map;for(const t of e){const e=this.getO(t);s.set(e,(s.get(e)||0)+Math.abs(this.getR(t)))}return r.sort("asc"===n?(e,t)=>(s.get(e)||0)-(s.get(t)||0):(e,t)=>(s.get(t)||0)-(s.get(e)||0))}computeValueDomain(e,t){return function(e){const{data:t,chartType:o,projection:n,normalize:i,rExtent:r,extentPadding:s=.05,baselinePadding:a,axisExtent:l,getO:c,getR:u,getStack:d,rawRExtent:h}=e,p=s;if("radial"===n&&("pie"===o||"donut"===o))return[0,1];let g=0,m=0;if("bar"===o&&d&&i)g=0,m=1;else if("bar"===o&&d){const e=new Map,o=new Map;for(const n of t){const t=c(n),i=u(n);0>i?o.set(t,(o.get(t)||0)+i):e.set(t,(e.get(t)||0)+i)}for(const t of e.values())t>m&&(m=t);for(const e of o.values())g>e&&(g=e)}else if("bar"===o){const e=new Map;for(const o of t){const t=c(o),n=u(o);e.set(t,(e.get(t)||0)+n)}for(const t of e.values())t>m&&(m=t),g>t&&(g=t)}else if("swimlane"===o){const e=new Map;for(const o of t){const t=c(o),n=Math.abs(u(o));e.set(t,(e.get(t)||0)+n)}for(const t of e.values())t>m&&(m=t)}else if("clusterbar"===o||"bar-funnel"===o)for(const e of t){const t=u(e);t>m&&(m=t),g>t&&(g=t)}else{const e=h[0],t=h[1];e!==1/0&&(g=e),t!==-1/0&&(m=t)}r&&(null!=r[0]&&(g=r[0]),null!=r[1]&&(m=r[1]));const f="bar"===o||"clusterbar"===o||"bar-funnel"===o||"swimlane"===o;if(f&&null==r?.[0]&&null==r?.[1]&&(g>0&&(g=0),0>m&&(m=0)),"bar-funnel"!==o&&"exact"!==l){const e=m-g,t=e>0?e*p:1,n=f&&!a&&0===g,i=f&&!a&&0===m||"swimlane"===o;null!=r?.[0]||n||(g-=t),null!=r?.[1]||i||(m+=t)}return[g,m]}({data:e,chartType:this.config.chartType,projection:this.config.projection,normalize:this.config.normalize,rExtent:this.config.rExtent,extentPadding:this.config.extentPadding,baselinePadding:this.config.baselinePadding,axisExtent:this.config.axisExtent,getO:this.getO,getR:this.getR,getStack:this.getStack,rawRExtent:this.rExtent.extent})}buildColumns(e,t,o,n,i){return function(e){const{data:t,oExtent:o,oScale:n,projection:i,layout:r,dynamicColumnWidth:s,getO:a,getR:l}=e,c={},u=new Map;for(const e of t){const t=a(e);u.has(t)||u.set(t,[]),u.get(t).push(e)}let d=0;if("radial"===i)for(const e of t)d+=Math.abs(l(e));let h=null;if(s&&"radial"!==i){h=new Map;let e=0;for(const t of o){const o=u.get(t)||[];let n;n="string"==typeof s?o.reduce((e,t)=>e+(Number(t[s])||0),0):s(o),h.set(t,n),e+=n}const t=("horizontal"===i?r.height:r.width)-n.padding()*n.step()*o.length;if(e>0)for(const[o,n]of h)h.set(o,n/e*t)}let p=0,g=0;for(const e of o){const t=u.get(e)||[],o=t.reduce((e,t)=>e+Math.abs(l(t)),0),i=d>0?o/d:0;let r,s;h?(r=g,s=h.get(e)||n.bandwidth(),g+=s+n.padding()*n.step()):(r=n(e)??0,s=n.bandwidth()),c[e]={name:e,x:r,y:0,width:s,middle:r+s/2,padding:n.padding()*n.step(),pieceData:t,pct:i,pctStart:p},p+=i}return c}({data:e,oExtent:t,oScale:o,projection:n,layout:i,dynamicColumnWidth:this.config.dynamicColumnWidth,getO:this.getO,getR:this.getR})}getSceneContext(){return{scales:this.scales,columns:this.columns,config:this.config,getR:this.getR,getStack:this.getStack,getGroup:this.getGroup,getColor:this.getColor,getSymbol:this.getSymbol,getConnector:this.getConnector,getO:this.getO,multiScales:this.multiScales,rAccessors:this.rAccessors,resolvePieceStyle:(e,t)=>this.styleResolver.resolvePieceStyle(this.config,e,t),resolveSummaryStyle:(e,t)=>this.styleResolver.resolveSummaryStyle(this.config,e,t),getRawRange:e=>this.getRawRange(e)}}buildSceneNodes(e,t){if(!this.scales)return[];if(this.config.customLayout){const o=this.buildLayoutContext(e,t);let n;try{n=this.config.customLayout(o)}catch(e){const t=null!==this.lastCustomLayoutResult,o=ee("ordinal",e,t,this.version);this.lastCustomLayoutFailure=o,this._customLayoutFailedThisBuild=!0,"production"!==process.env.NODE_ENV&&console.error("[semiotic] ordinal customLayout threw:",e);try{this.config.onLayoutError?.(o)}catch(e){"production"!==process.env.NODE_ENV&&console.error("[semiotic] onLayoutError threw:",e)}return t?this.scene:(this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,[])}this.customLayoutOverlays=n.overlays??null,this.lastCustomLayoutResult=n,this.lastCustomLayoutFailure=null;const i=n.nodes??[];if(this._customRestyle=n.restyle,this.hasCustomRestyle=!!n.restyle,this.hasCustomRestyle){this._baseStyles=new WeakMap;for(const e of i)e.style&&this._baseStyles.set(e,e.style);this.applyCustomRestyle(i,this.config.layoutSelection??null)}return st({label:"ordinal customLayout",nodes:i,overlays:this.customLayoutOverlays,warned:this._customLayoutDiagnosticsWarned}),i}this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1;const o=this.getSceneContext(),n=vl[this.config.chartType];let i=n?n(o,t):[];if(this.getConnector&&this.scales){const e=function(e,t){const{scales:o,config:n,getConnector:i,getO:r}=e;if(!i||!o)return[];const s=[],{projection:a}=o,l=new Map;for(const e of t){if("point"!==e.type&&"rect"!==e.type)continue;const t=e.datum;if(!t)continue;const o=i(t);if(!o)continue;let n,s;"point"===e.type?(n=e.x,s=e.y):(n=e.x+e.w/2,s=e.y+("vertical"===a?0:e.h/2)),l.has(o)||l.set(o,[]),l.get(o).push({x:n,y:s,datum:t,category:r(t)})}const c=o.o.domain(),u=n.connectorStyle;for(const[t,o]of l)if(o.length>=2){o.sort((e,t)=>c.indexOf(e.category)-c.indexOf(t.category));for(let n=0;o.length-1>n;n++){const i=o[n],r=o[n+1],a="function"==typeof u?u(i.datum):u||{stroke:e.config.themeSemantic?.border||e.config.themeSemantic?.secondary||"#999",strokeWidth:1,opacity:.5};s.push({type:"connector",x1:i.x,y1:i.y,x2:r.x,y2:r.y,style:a,datum:i.datum,group:t})}}return s}(o,i);i=[...e,...i]}return i}buildLayoutContext(e,t){const o=this.config,n=o.layoutMargin??{top:0,right:0,bottom:0,left:0},i=Ne(o.colorScheme,o.themeCategorical,F),r=this.scales;return{data:e,scales:{o:r.o,r:r.r,projection:r.projection},dimensions:{width:t.width,height:t.height,margin:n,plot:"radial"===r.projection?{x:-t.width/2,y:-t.height/2,width:t.width,height:t.height}:{x:0,y:0,width:t.width,height:t.height}},theme:{semantic:o.themeSemantic??{},categorical:[...i]},resolveColor:H(i,o.colorScheme),config:o.layoutConfig??{},selection:o.layoutSelection??null}}computeDecayOpacity(e,t){const o=this.config.decay;return o&&t>1?q(o,e,t):1}getDatumIndexMap(e){if(this._datumIndexCache&&this._datumIndexCache.version===this._dataVersion)return this._datumIndexCache.map;const t=W(e);return this._datumIndexCache={version:this._dataVersion,map:t},t}getCategoryIndexMap(e){if(this._categoryIndexCache&&this._categoryIndexCache.version===this._dataVersion)return this._categoryIndexCache.map;const t=function(e,t){const o="function"==typeof t,n=o?null:t||"category",i=new Map;for(let r=0;e.length>r;r++){const s=e[r],a=o?t(s):s[n],l=i.get(a);l?l.push(r):i.set(a,[r])}return i}(e,this.config.categoryAccessor||this.config.oAccessor);return this._categoryIndexCache={version:this._dataVersion,map:t},t}rebuildPointQuadtree(){const e=function(e){let t=0,o=0;for(const n of e)"point"===n.type&&(t++,n.r>o&&(o=n.r));if(500>=t)return{quadtree:null,maxRadius:o};const n=Array(t);let i=0;for(const t of e)"point"===t.type&&(n[i++]=t);return{maxRadius:o,quadtree:zl().x(e=>e.x).y(e=>e.y).addAll(n)}}(this.scene);this._pointQuadtree=e.quadtree,this._maxPointRadius=e.maxRadius}get pointQuadtree(){return this._pointQuadtree}get maxPointRadius(){return this._maxPointRadius}applyDecay(e,t){if(!this.config.decay)return;const o=t.length;if(1>=o)return;const n=this.getDatumIndexMap(t);for(const t of e){if("connector"===t.type||"violin"===t.type||"boxplot"===t.type||"wedge"===t.type)continue;if(!t.datum)continue;const e=n.get(t.datum);if(null==e)continue;const i=this.computeDecayOpacity(e,o);t.style={...t.style,opacity:(t.style?.opacity??1)*i}}}applyPulse(e,t,o=this.currentTime()){return!(!this.config.pulse||!this.timestampBuffer)&&function(e,t,o,n,i,r){const s=e.color??"rgba(255,255,255,0.6)",a=e.glowRadius??4;let l=!1;for(const c of t){if("connector"===c.type||"violin"===c.type||"boxplot"===c.type)continue;if("wedge"===c.type){const t=c.category;if(!t)continue;let n=0;for(const s of i(t)??[]){const t=o.get(s);null!=t&&(n=Math.max(n,Q(e,t,r)))}l=Ue(c,n,s)||l;continue}if(null==c.datum)continue;const t=n.get(c.datum);if(null==t)continue;const u=o.get(t),d=null==u?0:Q(e,u,r);l=Ue(c,d,s,a)||l}return l}(this.config.pulse,e,this.timestampBuffer,this.getDatumIndexMap(t),e=>this.getCategoryIndexMap(t).get(e),o)}refreshPulse(e){return!0!==this.lastCustomLayoutFailure?.preservedLastGoodScene&&this.applyPulse(this.scene,this.getBufferArray(),e)}hasActivePulsesAt(e){return!!this.config.pulse&&he(this.config.pulse,this.timestampBuffer,e)}get hasActivePulses(){return this.hasActivePulsesAt(this.currentTime())}synthesizeIntroPositions(){this.prevPositionMap.clear();const e=new Map,t=this.scales?.r(0)??0,o="horizontal"!==this.scales?.projection;let n;for(let i=0;this.scene.length>i;i++){const r=this.scene[i],s=this.getNodeKey(r,e);s&&("rect"===r.type?this.prevPositionMap.set(s,o?{x:r.x,y:t,w:r.w,h:0,opacity:r.style.opacity??1}:{x:t,y:r.y,w:0,h:r.h,opacity:r.style.opacity??1}):"point"===r.type?this.prevPositionMap.set(s,{x:r.x,y:r.y,r:0,opacity:0}):"wedge"===r.type&&(void 0===n&&(n=r.startAngle),this.prevPositionMap.set(s,{x:r.cx,y:r.cy,startAngle:n,endAngle:n,innerRadius:r.innerRadius,outerRadius:r.outerRadius,opacity:0})))}}getNodeKey(e,t){if("point"===e.type){const o=`p:${e.datum?this.getO(e.datum):""}:${e.datum?this.getR(e.datum):0}`,n=t.get(o)||0;return t.set(o,n+1),`${o}:${n}`}if("rect"===e.type){const o=e.datum?null!=e.datum.category&&""!==e.datum.category?e.datum.category+"":(this.getO(e.datum)??"")+"":"",n=`r:${e.group||""}:${o}`,i=t.get(n)||0;return t.set(n,i+1),0===i?n:`${n}:${i}`}return"wedge"===e.type?"w:"+(e.category??""):null}snapshotPositions(){this.prevPositionMap.clear();const e=new Map;for(let t=0;this.scene.length>t;t++){const o=this.scene[t],n=this.getNodeKey(o,e);n&&("point"===o.type?this.prevPositionMap.set(n,{x:o.x,y:o.y,r:o.r,opacity:o.style.opacity??o.style.fillOpacity}):"rect"===o.type?this.prevPositionMap.set(n,{x:o.x,y:o.y,w:o.w,h:o.h,opacity:o.style.opacity??o.style.fillOpacity}):"wedge"===o.type&&this.prevPositionMap.set(n,{x:o.cx,y:o.cy,startAngle:o.startAngle,endAngle:o.endAngle,innerRadius:o.innerRadius,outerRadius:o.outerRadius,opacity:o.style.opacity??1}))}}startTransition(){if(!this.config.transition||0===this.prevPositionMap.size)return;const e=this.config.transition.duration??300;if(this.exitNodes.length>0){const e=new Set(this.exitNodes);this.scene=this.scene.filter(t=>!e.has(t)),this.exitNodes=[]}let t=!1;const o=new Set,n=new Map;for(let e=0;this.scene.length>e;e++){const i=this.scene[e],r=this.getNodeKey(i,n);if(!r)continue;i._transitionKey=r;const s=this.prevPositionMap.get(r);if("point"===i.type)s?(o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,(s.x!==i.x||s.y!==i.y||void 0!==s.r&&s.r!==i.r)&&(i._targetX=i.x,i._targetY=i.y,i._targetR=i.r,i.x=s.x,i.y=s.y,void 0!==s.r&&(i.r=s.r),t=!0)):(i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i._targetR=i.r,i.r=0,i.style={...i.style,opacity:0},t=!0);else if("rect"===i.type)s?(o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,s.x===i.x&&s.y===i.y&&s.w===i.w&&s.h===i.h||(i._targetX=i.x,i._targetY=i.y,i._targetW=i.w,i._targetH=i.h,i.x=s.x,i.y=s.y,i.w=s.w??i.w,i.h=s.h??i.h,t=!0)):(i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i.style={...i.style,opacity:0},t=!0);else if("wedge"===i.type)if(s)o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,s.startAngle===i.startAngle&&s.endAngle===i.endAngle||(i._targetStartAngle=i.startAngle,i._targetEndAngle=i.endAngle,i.startAngle=s.startAngle,i.endAngle=s.endAngle,t=!0);else{i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i._targetStartAngle=i.startAngle,i._targetEndAngle=i.endAngle;const e=i.startAngle;i.startAngle=e,i.endAngle=e,i.style={...i.style,opacity:0},this.prevPositionMap.set(r,{x:i.cx,y:i.cy,startAngle:e,endAngle:e,innerRadius:i.innerRadius,outerRadius:i.outerRadius,opacity:0}),t=!0}}this.exitNodes=[];for(const[e,n]of this.prevPositionMap)if(!o.has(e)){if(e.startsWith("p:"))this.exitNodes.push({type:"point",x:n.x,y:n.y,r:n.r??3,style:{opacity:n.opacity??1},datum:null,_targetOpacity:0,_transitionKey:e});else if(e.startsWith("r:"))this.exitNodes.push({type:"rect",x:n.x,y:n.y,w:n.w??0,h:n.h??0,style:{opacity:n.opacity??1,fill:"#999"},datum:null,_targetOpacity:0,_transitionKey:e});else if(e.startsWith("w:")){const t=((n.startAngle??0)+(n.endAngle??0))/2,o={type:"wedge",cx:n.x,cy:n.y,innerRadius:n.innerRadius??0,outerRadius:n.outerRadius??100,startAngle:n.startAngle??0,endAngle:n.endAngle??0,style:{opacity:n.opacity??1},datum:null,category:e.slice(2),_targetStartAngle:t,_targetEndAngle:t,_targetOpacity:0,_transitionKey:e};this.exitNodes.push(o)}t=!0}this.exitNodes.length>0&&(this.scene=[...this.scene,...this.exitNodes]),t&&(this.activeTransition={startTime:this.currentTime(),duration:e})}advanceTransition(e){if(!this.activeTransition)return!1;const t=Z(e,this.activeTransition),o=U(t,"linear"===this.config.transition?.easing?"linear":"ease-out-cubic");for(const e of this.scene){const t=e._transitionKey;if(t)if("point"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style.opacity=be(n?n.opacity??1:0,e._targetOpacity,o)}const n=this.prevPositionMap.get(t);void 0!==e._targetX&&n&&(e.x=be(n.x,e._targetX,o),e.y=be(n.y,e._targetY,o)),void 0!==e._targetR&&void 0!==n?.r&&(e.r=be(n.r,e._targetR,o))}else if("rect"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style.opacity=be(n?n.opacity??1:0,e._targetOpacity,o)}if(void 0===e._targetX)continue;const n=this.prevPositionMap.get(t);if(!n)continue;e.x=be(n.x,e._targetX,o),e.y=be(n.y,e._targetY,o),void 0!==n.w&&(e.w=be(n.w,e._targetW,o),e.h=be(n.h,e._targetH,o))}else if("wedge"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style={...e.style,opacity:be(n?n.opacity??1:0,e._targetOpacity,o)}}if(void 0!==e._targetStartAngle&&void 0!==e._targetEndAngle){const n=this.prevPositionMap.get(t);n&&void 0!==n.startAngle&&(e.startAngle=be(n.startAngle,e._targetStartAngle,o),e.endAngle=be(n.endAngle,e._targetEndAngle,o))}}}if(t>=1){for(const e of this.scene)if(void 0!==e._targetOpacity&&(e.style={...e.style||{},opacity:0===e._targetOpacity?0:e._targetOpacity},e._targetOpacity=void 0),"point"===e.type){if(void 0===e._targetX&&void 0===e._targetR)continue;void 0!==e._targetX&&(e.x=e._targetX,e.y=e._targetY),void 0!==e._targetR&&(e.r=e._targetR),e._targetX=void 0,e._targetY=void 0,e._targetR=void 0}else if("rect"===e.type){if(void 0===e._targetX)continue;e.x=e._targetX,e.y=e._targetY,e.w=e._targetW,e.h=e._targetH,e._targetX=void 0,e._targetY=void 0,e._targetW=void 0,e._targetH=void 0}else"wedge"===e.type&&void 0!==e._targetStartAngle&&(e.startAngle=e._targetStartAngle,e.endAngle=e._targetEndAngle,e._targetStartAngle=void 0,e._targetEndAngle=void 0);if(this.exitNodes.length>0){const e=new Set(this.exitNodes);this.scene=this.scene.filter(t=>!e.has(t)),this.exitNodes=[]}return this.activeTransition=null,!1}return!0}cancelIntroAnimation(){this.prevPositionMap.clear(),this.activeTransition=null,Qe(this.scene),this.exitNodes=[]}getBufferArray(){return this._bufferArrayCache?.version!==this._dataVersion&&(this._bufferArrayCache={version:this._dataVersion,data:this.buffer.toArray()}),this._bufferArrayCache.data}getData(){return this.buffer.toArray()}remove(e){if(!this.getDataId)throw Error("remove() requires dataIdAccessor to be configured");this.config.transition&&this.scene.length>0&&this.snapshotPositions();const t=Ke(e),o=this.getDataId,n=e=>t.has(o(e));G(this.buffer,this.timestampBuffer,n);const i=this.buffer.remove(n);if(0===i.length)return this.updateResults.recordNoop("remove"),i;for(const e of i)this.evictValueExtent(e);return this.categories.clear(),this.buffer.forEach(e=>this.categories.add(this.getO(e))),this._dataVersion++,this.version++,this.lastIngestTime=this.currentTime(),this.updateResults.recordData("remove",i.length),i}update(e,t){if(!this.getDataId)throw Error("update() requires dataIdAccessor to be configured");const o=Ke(e),n=this.getDataId,i=new Set;this.buffer.forEach((e,t)=>{o.has(n(e))&&i.add(t)});const r=this.buffer.update(e=>o.has(n(e)),t);if(0===r.length)return this.updateResults.recordNoop("update"),r;for(const e of r)this.evictValueExtent(e);return this.categories.clear(),this.buffer.forEach((e,t)=>{this.categories.add(this.getO(e)),i.has(t)&&this.pushValueExtent(e)}),this._dataVersion++,this.version++,this.lastIngestTime=this.currentTime(),this.updateResults.recordData("update",r.length),r}clear(){this.buffer.clear(),this.rExtent.clear(),this.categories.clear(),this._hasStreamingData=!1,this._hasRenderedOnce=!1,this.timestampBuffer&&this.timestampBuffer.clear(),this.prevPositionMap.clear(),this.exitNodes=[],this.activeTransition=null,this.lastIngestTime=0,this.scales=null,this.scene=[],this.columns={},this.multiScales=[],this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._pointQuadtree=null,this._maxPointRadius=0,this.styleResolver.resetColors(),this._dataVersion++,this.version++,this.updateResults.recordData("clear")}get size(){return this.buffer.size}getOAccessor(){return this.getO}getRAccessor(){return this.getR}applyCustomRestyle(e,t){const o=this._customRestyle;if(o)for(const n of e){const e=this._baseStyles.get(n)??n.style??{},i=o(n,t);n.style=i?{...e,...i}:e}}restyleScene(e){this._customRestyle?(this.applyCustomRestyle(this.scene,e),this.updateResults.recordRestyle(!0)):this.updateResults.recordRestyle(!1)}rebuildAccessorDerivedState(){this.categories.clear(),this.rExtent.clear();for(const e of this.rExtents)e.clear();this._categoryIndexCache=null,this.buffer.forEach(e=>{this.categories.add(this.getO(e)),this.pushValueExtent(e)})}updateConfig(e){const t={...this.config},o=Object.keys(e).filter(o=>e[o]!==t[o]);"production"!==process.env.NODE_ENV&&!this.windowSizeWarned&&"windowSize"in e&&e.windowSize!==t.windowSize&&(this.windowSizeWarned=!0,console.warn(`[Semiotic] windowSize changed after mount (${t.windowSize} → ${e.windowSize}) but it is a mount-only setting — the ring buffer keeps its original capacity. Remount the chart (e.g. via a React key) to apply a new windowSize.`)),("colorScheme"in e&&e.colorScheme!==t.colorScheme||"themeCategorical"in e&&e.themeCategorical!==t.themeCategorical||"colorAccessor"in e&&!Rt(e.colorAccessor,t.colorAccessor))&&this.styleResolver.resetColors(),("categoryAccessor"in e&&!Rt(e.categoryAccessor,t.categoryAccessor)||"oAccessor"in e&&!Rt(e.oAccessor,t.oAccessor))&&(this._categoryIndexCache=null),Object.assign(this.config,e),"pulse"in e&&this.syncPulseTimestampBuffer();let n=!1;("categoryAccessor"in e||"oAccessor"in e)&&(Rt(this.config.categoryAccessor||this.config.oAccessor,t.categoryAccessor||t.oAccessor)||(this.getO=Ct(this.config.categoryAccessor||this.config.oAccessor,"category"),n=!0));let i=!1;if("valueAccessor"in e||"rAccessor"in e){const e=this.config.valueAccessor||this.config.rAccessor,o=t.valueAccessor||t.rAccessor,n=Array.isArray(e)?e:[e],r=Array.isArray(o)?o:[o];if(i=n.length!==r.length||n.some((e,t)=>!Rt(e,r[t])),i){const e=this.config.valueAccessor||this.config.rAccessor;Array.isArray(e)?(this.rAccessors=e.map(e=>It(e,"value")),this.getR=this.rAccessors[0],this.rExtents=e.map(()=>new ct)):(this.getR=It(e,"value"),this.rAccessors=[this.getR],this.rExtents=[this.rExtent])}}"stackBy"in e&&!Rt(e.stackBy,t.stackBy)&&(this.getStack=null!=this.config.stackBy?Ct(this.config.stackBy):void 0),"groupBy"in e&&!Rt(e.groupBy,t.groupBy)&&(this.getGroup=null!=this.config.groupBy?Ct(this.config.groupBy):void 0),"colorAccessor"in e&&!Rt(e.colorAccessor,t.colorAccessor)&&(this.getColor=null!=this.config.colorAccessor?Ct(this.config.colorAccessor):void 0),"symbolAccessor"in e&&!Rt(e.symbolAccessor,t.symbolAccessor)&&(this.getSymbol=null!=this.config.symbolAccessor?Ct(this.config.symbolAccessor):void 0),"connectorAccessor"in e&&!Rt(e.connectorAccessor,t.connectorAccessor)&&(this.getConnector=null!=this.config.connectorAccessor?Ct(this.config.connectorAccessor):void 0),(n||i||"accessorRevision"in e&&e.accessorRevision!==t.accessorRevision)&&this.rebuildAccessorDerivedState(),this.updateResults.recordConfig(o)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}};j(Fl);import{jsx as Ol,jsxs as Bl}from"react/jsx-runtime";import{Fragment as Nl,jsx as El,jsxs as jl}from"react/jsx-runtime";function $l(e,t){const o=Kt(e.theme),n=e.size||[500,400],i=ze({top:20,right:20,bottom:30,left:40,...e.margin},e.title),r=pe(e.title),s=ie(e.data),a=e.showLegend?Ea(s,e.colorAccessor||e.stackBy||e.groupBy):[],l=e.projection||"vertical",c={hasAxis:!1!==e.showAxes&&"radial"!==l,hasAxisLabel:"horizontal"===l?!(!e.valueLabel&&!e.rLabel):!(!e.categoryLabel&&!e.oLabel)};ol(i,{props:{...e,axisChrome:c},categories:a,theme:o,size:n,hasTitle:r});const u=n[0]-i.left-i.right,d=n[1]-i.top-i.bottom,h=e.projection||"vertical",p="radial"===h,g=e.colorScheme||o.colors.categorical,m={chartType:e.chartType,windowSize:e.windowSize??1e4,windowMode:e.windowMode??"sliding",extentPadding:e.extentPadding??.05,projection:h,oAccessor:e.oAccessor,rAccessor:e.rAccessor,colorAccessor:e.colorAccessor,stackBy:e.stackBy,groupBy:e.groupBy,categoryAccessor:e.categoryAccessor,valueAccessor:e.valueAccessor,timeAccessor:e.timeAccessor,rExtent:e.rExtent,oExtent:e.oExtent,axisExtent:e.axisExtent,barPadding:e.barPadding,roundedTop:e.roundedTop,innerRadius:e.innerRadius,cornerRadius:e.cornerRadius,normalize:e.normalize,startAngle:e.startAngle,sweepAngle:e.sweepAngle,bins:e.bins,showOutliers:e.showOutliers,showIQR:e.showIQR,amplitude:e.amplitude,oSort:e.oSort,connectorAccessor:e.connectorAccessor,connectorStyle:e.connectorStyle,dynamicColumnWidth:e.dynamicColumnWidth,pieceStyle:e.pieceStyle,summaryStyle:e.summaryStyle,gradientFill:Se(e.gradientFill),symbolAccessor:e.symbolAccessor,symbolMap:e.symbolMap,multiAxis:e.multiAxis,baselinePadding:e.baselinePadding,trackFill:e.trackFill,connectorOpacity:e.connectorOpacity,showLabels:e.showLabels,colorScheme:g,themeCategorical:o.colors.categorical,themeSemantic:Dt(o),customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,layoutSelection:e.layoutSelection,barColors:e.barColors},f=new Fl(m);if(e.data&&f.ingest({inserts:s,bounded:!0}),f.computeScene({width:u,height:d}),!f.scales||0===f.scene.length)return t&&(t.evidence=Sa({frameType:"ordinal",width:n[0],height:n[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,extraWarnings:f.scales?[]:["NO_SCALES"],margin:i})),ul.renderToStaticMarkup(rl(null,{width:n[0],height:n[1],className:"stream-ordinal-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:u,innerHeight:d,idPrefix:e._idPrefix}));const y=e._idPrefix,b=e.showGrid?function(e,t,o,n,i){const r=e.scales;if(!r||"radial"===r.projection)return null;const{grid:s}=Jt(o),a=n?n+"-":"",l="vertical"===r.projection,c=Ze(r.r,5,i);return qa("g",l?{id:a+"grid",className:"semiotic-grid",opacity:.8,children:c.map((e,o)=>{const n=r.r(e);return qa("line",{x1:0,y1:n,x2:t.width,y2:n,stroke:s,strokeWidth:.5},"gr-"+o)})}:{id:a+"grid",className:"semiotic-grid",opacity:.8,children:c.map((e,o)=>{const n=r.r(e);return qa("line",{x1:n,y1:0,x2:n,y2:t.height,stroke:s,strokeWidth:.5},"gr-"+o)})})}(f,{width:u,height:d},o,y,e.axisExtent):null;let x=null;if(f.scene.some(e=>"rect"===e.type&&e.datum?.__barFunnelIsDropoff)){const t=Za(e),n=new Set;for(const e of f.scene)"rect"===e.type&&e.datum?.__barFunnelIsDropoff&&n.add("string"==typeof e.style.fill?e.style.fill:"#666");x=Array.from(n).map((e,n)=>function(e){const{id:t,background:o="transparent",stroke:n="#000",lineWidth:i=1.5,spacing:r=6,angle:s=45}=e,a=Math.max(8,Math.ceil(2*r));return Bl("pattern",{id:t,width:a,height:a,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[o&&"transparent"!==o&&Ol("rect",{width:a,height:a,fill:o}),Ol("line",{x1:0,y1:0,x2:0,y2:a,stroke:n,strokeWidth:i}),Ol("line",{x1:r,y1:0,x2:r,y2:a,stroke:n,strokeWidth:i})]},t)}({id:`funnel-hatch-${t}-${n}`,background:e,stroke:"transparent"===o.colors.background?"#fff":o.colors.background,lineWidth:1.5,spacing:5,angle:45}));const i=new Map;Array.from(n).forEach((e,o)=>i.set(e,`funnel-hatch-${t}-${o}`));for(const e of f.scene)"rect"===e.type&&e.datum?.__barFunnelIsDropoff&&(e.style={...e.style,fill:`url(#${i.get("string"==typeof e.style.fill?e.style.fill:"#666")})`})}const v=Ie({nodes:f.scene,renderMode:e.renderMode,fallback:(e,t)=>_e(e,t,y)}),w=v.map(e=>e.element);if(t){const o=f.scales.o?.domain?.();t.evidence=Sa({frameType:"ordinal",width:n[0],height:n[1],marks:v.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,yDomain:Aa(f.scales.r?.domain?.()),categories:Array.isArray(o)?o.map(String):void 0,margin:i})}const A=!1!==e.showAxes?function(e,t,o,n,i){const r=e.scales;if(!r)return null;if("radial"===r.projection)return null;const s=Jt(n),a="vertical"===r.projection,l=o.categoryFormat||o.oFormat,c=o.valueFormat||o.rFormat,u=o.categoryLabel||o.oLabel,d=o.valueLabel||o.rLabel,h=Object.values(e.columns).map(e=>({pixel:e.middle,label:(l||String)(e.name)})),p=Ze(r.r,5,o.axisExtent).map(e=>({pixel:r.r(e),label:(c||il)(e)}));return jl("g",a?{id:(i?i+"-":"")+"axes",className:"ordinal-axes",children:[El("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:s.border,strokeWidth:1}),h.map((e,o)=>jl("g",{transform:`translate(${e.pixel},${t.height})`,children:[El("line",{y2:5,stroke:s.border,strokeWidth:1}),El("text",{y:18,textAnchor:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oxtick-"+o)),u&&El("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,children:u}),El("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:s.border,strokeWidth:1}),p.map((e,t)=>jl("g",{transform:`translate(0,${e.pixel})`,children:[El("line",{x2:-5,stroke:s.border,strokeWidth:1}),El("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oytick-"+t)),d&&El("text",{x:15-(o.margin?.left??40),y:t.height/2,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,transform:`rotate(-90, ${15-(o.margin?.left??40)}, ${t.height/2})`,children:d})]}:{id:(i?i+"-":"")+"axes",className:"ordinal-axes",children:[El("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:s.border,strokeWidth:1}),p.map((e,o)=>jl("g",{transform:`translate(${e.pixel},${t.height})`,children:[El("line",{y2:5,stroke:s.border,strokeWidth:1}),El("text",{y:18,textAnchor:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oxtick-"+o)),d&&El("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,children:d}),El("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:s.border,strokeWidth:1}),h.map((e,t)=>jl("g",{transform:`translate(0,${e.pixel})`,children:[El("line",{x2:-5,stroke:s.border,strokeWidth:1}),El("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oytick-"+t)),u&&El("text",{x:15-(o.margin?.left??40),y:t.height/2,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,transform:`rotate(-90, ${15-(o.margin?.left??40)}, ${t.height/2})`,children:u})]})}(f,{width:u,height:d},e,o,y):null,S=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,annotationData:s,scales:{o:f.scales.o,r:f.scales.r,y:"vertical"===f.scales.projection?f.scales.r:void 0},layout:{width:u,height:d},theme:o,projection:h,idPrefix:y}):null,k=nl({props:{...e,axisChrome:c},categories:a,theme:o,size:n,margin:i,hasTitle:r}),M=p?i.left+u/2:i.left,_=p?i.top+d/2:i.top,P=p&&e.centerContent?El("foreignObject",{x:i.left,y:i.top,width:u,height:d,pointerEvents:"none",children:El("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center"},children:e.centerContent})}):null;return ul.renderToStaticMarkup(rl(jl(Nl,{children:[e.backgroundGraphics,b,w,A,S,e.foregroundGraphics,f.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-ordinal-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${M},${_})`,innerWidth:u,innerHeight:d,legend:k,defs:x,outerElements:P,idPrefix:e._idPrefix}))}import*as Dl from"react-dom/server";import{Fragment as Wl,jsxs as Yl}from"react/jsx-runtime";function Hl(e,t){return e?"function"==typeof e?e:t=>t[e]:e=>e[t]}var Vl=new Set(["tree","cluster","treemap","circlepack","partition"]);function Gl(e,t){const o=Kt(e.theme),n=e.chartType||"force",i=()=>Sa({frameType:"network",width:r[0],height:r[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,nodeCount:0,edgeCount:0,margin:s}),r=e.size||[500,500],s=ze({top:20,right:20,bottom:20,left:20,...e.margin},e.title),a=pe(e.title),l=e.showLegend?(()=>{const t="string"==typeof(o=e.colorBy)||"function"==typeof o?e.colorBy:void 0;var o;if(!t)return[];const n=ie(e.nodes||[]);if(n.length>0)return Ea(n,t);const i=Array.isArray(e.edges)?ie(e.edges):[];if(0===i.length)return[];const r=Hl(e.sourceAccessor,"source"),s=Hl(e.targetAccessor,"target");return Ea(Array.from(new Set(i.flatMap(e=>[r(e),s(e)]).filter(e=>null!=e).map(String))).map(e=>({id:e})),t)})():[];ol(s,{props:e,categories:l,theme:o,size:r,hasTitle:a});const c=r[0]-s.left-s.right,u=r[1]-s.top-s.bottom,d=ue(n);if(!d&&!e.customNetworkLayout)throw Error(`No layout plugin found for chart type: "${n}". Supported types: force, sankey, chord, tree, cluster, treemap, circlepack, partition.`);const h={chartType:n,nodeIDAccessor:e.nodeIDAccessor,sourceAccessor:e.sourceAccessor,targetAccessor:e.targetAccessor,valueAccessor:e.valueAccessor,childrenAccessor:e.childrenAccessor,hierarchySum:e.hierarchySum,orientation:e.orientation,nodeAlign:e.nodeAlign,nodePaddingRatio:e.nodePaddingRatio,nodeWidth:e.nodeWidth,iterations:e.iterations,forceStrength:e.forceStrength,padAngle:e.padAngle,groupWidth:e.groupWidth,sortGroups:e.sortGroups,edgeSort:e.edgeSort,treeOrientation:e.treeOrientation,edgeType:e.edgeType,padding:e.padding,paddingTop:e.paddingTop,nodeStyle:e.nodeStyle,edgeStyle:e.edgeStyle,nodeLabel:e.nodeLabel,showLabels:e.showLabels,labelMode:e.labelMode,colorBy:e.colorBy,colorScheme:e.colorScheme||o.colors.categorical,edgeColorBy:e.edgeColorBy,edgeOpacity:e.edgeOpacity,colorByDepth:e.colorByDepth,nodeSize:e.nodeSize,nodeSizeRange:e.nodeSizeRange,customNetworkLayout:e.customNetworkLayout,layoutConfig:e.layoutConfig};let p,g;if(Vl.has(n)){const n=e.data||e.edges;if(!n||Array.isArray(n))return t&&(t.evidence=i()),Dl.renderToStaticMarkup(rl(null,{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));h.__hierarchyRoot=n,p=[],g=[]}else{const n=ie(e.nodes||[]),a=Array.isArray(e.edges)?ie(e.edges):[];if(0===n.length&&0===a.length)return t&&(t.evidence=i()),Dl.renderToStaticMarkup(rl(null,{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));if(g=function(e,t){const o=Hl(t.sourceAccessor,"source"),n=Hl(t.targetAccessor,"target"),i=Hl(t.valueAccessor,"value");return e.map(e=>({source:o(e)+"",target:n(e)+"",value:Number(i(e))||1,y0:0,y1:0,sankeyWidth:0,data:e}))}(a,h),0===n.length&&g.length>0){const e=new Set;for(const t of g){const o=Qa(t.source),n=Qa(t.target);o&&e.add(o),n&&e.add(n)}p=Array.from(e).map(e=>({id:e,x:0,y:0,x0:0,x1:0,y0:0,y1:0,width:0,height:0,value:0,data:{id:e}}))}else p=function(e,t){const o=Hl(t.nodeIDAccessor,"id");return e.map(e=>({id:o(e)+"",x:e.x??0,y:e.y??0,x0:0,x1:0,y0:0,y1:0,width:0,height:0,value:0,data:e}))}(n,h)}let m=[],f=[],y=[],b=null;if(h.customNetworkLayout){const e=h.colorScheme,t=Ne(e,o.colors.categorical,Pt),n=H(t,e),i={nodes:p,edges:g,dimensions:{width:c,height:u,plot:{x:0,y:0,width:c,height:u}},theme:{semantic:o.colors,categorical:[...t]},resolveColor:n,config:h.layoutConfig??{}},r=h.customNetworkLayout(i);m=r.sceneNodes??[],f=r.sceneEdges??[],y=r.labels??[],b=r.overlays??null}else if(d){d.computeLayout(p,g,h,[c,u]);const e=d.buildScene(p,g,h,[c,u]);m=e.sceneNodes,f=e.sceneEdges,y=e.labels}const x=Jt(o);for(const e of y)e.fill||(e.fill=x.text);const v=Ie({nodes:f,renderMode:e.renderMode,fallback:(e,t)=>ve(e,t)}),w=Ie({nodes:m,renderMode:e.renderMode,fallback:(e,t)=>we(e,t)});t&&(t.evidence=Sa({frameType:"network",width:r[0],height:r[1],marks:[...w.map(({node:e})=>({type:"node:"+(e.type??"node")})),...v.map(({node:e})=>({type:"edge:"+(e.type??"edge")}))],title:e.title,description:e.description,annotations:e.annotations,nodeCount:w.length,edgeCount:v.length,margin:s}));const A=v.map(e=>e.element),S=w.map(e=>e.element),k=y.map((e,t)=>xe(e,t)).filter(Boolean),M=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{},layout:{width:c,height:u},theme:o,idPrefix:e._idPrefix}):null,_=nl({props:e,categories:l,theme:o,size:r,margin:s,hasTitle:a});return Dl.renderToStaticMarkup(rl(Yl(Wl,{children:[e.backgroundGraphics,A,S,k,M,e.foregroundGraphics,b]}),{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,legend:_,idPrefix:e._idPrefix}))}import*as Xl from"react-dom/server";import{geoPath as ql}from"d3-geo";import{quadtree as Ul}from"d3-quadtree";import{geoMercator as Ql,geoEqualEarth as Zl,geoAlbersUsa as Kl,geoOrthographic as Jl,geoNaturalEarth1 as ec,geoEquirectangular as tc}from"d3-geo";var oc={mercator:Ql,equalEarth:Zl,albersUsa:Kl,orthographic:Jl,naturalEarth:ec,equirectangular:tc};function nc(e,t){return e?"function"==typeof e?e:t=>t[e]:e=>e[t]}function ic(e){return e?"function"==typeof e?e:t=>t[e]:e=>e.coordinates||e.data||[]}function rc(e,t,o){return e?"function"==typeof e?{...o,...e(t)}:{...o,...e}:{...o}}function sc(e,t){if(2>e.length)return[e];const o=.4*t,n=[];let i=[e[0]];for(let t=1;e.length>t;t++){const r=e[t];Math.abs(r[0]-e[t-1][0])>o?(2>i.length||n.push(i),i=[r]):i.push(r)}return 2>i.length||n.push(i),n}function ac(e,t,o=24){const n=t[0]-e[0],i=t[1]-e[1],r=Math.sqrt(n*n+i*i);if(0===r)return[e,t];const s=-i/r,a=n/r,l=Math.min(.3*r,80),c=(e[0]+t[0])/2+s*l,u=(e[1]+t[1])/2+a*l,d=[];for(let n=0;o>=n;n++){const i=n/o,r=1-i;d.push([r*r*e[0]+2*r*i*c+i*i*t[0],r*r*e[1]+2*r*i*u+i*i*t[1]])}return d}function lc(e,t){if(2>e.length)return e;const o=t/2+1,n=[];for(let t=0;e.length>t;t++){const i=e[t];let r,s;0===t?(r=e[1][0]-i[0],s=e[1][1]-i[1]):t===e.length-1?(r=i[0]-e[t-1][0],s=i[1]-e[t-1][1]):(r=e[t+1][0]-e[t-1][0],s=e[t+1][1]-e[t-1][1]);const a=Math.sqrt(r*r+s*s)||1;n.push([i[0]+s/a*o,i[1]+-r/a*o])}return n}function cc(e,t,o,n,i){const r=t[0]-e[0],s=t[1]-e[1],a=Math.sqrt(r*r+s*s);if(0===a)return[e,t];const l=s/a,c=-r/a,u=i/2+1;return[[e[0]+l*u,e[1]+c*u],[t[0]+l*u,t[1]+c*u]]}import{scaleLinear as uc}from"d3-scale";var dc=["data","domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],hc=["scene-style","data-paint","accessibility","evidence"],pc=(e,t)=>({retainedData:e,invalidations:t}),gc=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],mc=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],fc=["scene-geometry","data-paint","accessibility","evidence"],yc=["scene-style","data-paint","accessibility","evidence"],bc=["overlay","accessibility","evidence"],xc=[],vc={xAccessor:pc("rebuild",gc),yAccessor:pc("rebuild",gc),lineDataAccessor:pc("rebuild",gc),pointIdAccessor:pc("rebuild",fc),lineIdAccessor:pc("rebuild",fc),windowSize:pc("rebuild",gc),projection:pc("preserve",mc),projectionExtent:pc("preserve",mc),fitPadding:pc("preserve",mc),lineType:pc("preserve",mc),flowStyle:pc("preserve",mc),graticule:pc("preserve",mc),projectionTransform:pc("preserve",mc),customLayout:pc("preserve",mc),layoutConfig:pc("preserve",mc),layoutMargin:pc("preserve",mc),areaStyle:pc("preserve",yc),pointStyle:pc("preserve",["scene-geometry","scene-style","data-paint","accessibility","evidence"]),lineStyle:pc("preserve",yc),colorScheme:pc("preserve",yc),themeCategorical:pc("preserve",yc),themeDiverging:pc("preserve",yc),themeSemantic:pc("preserve",yc),themeSequential:pc("preserve",yc),decay:pc("preserve",yc),pulse:pc("preserve",yc),layoutSelection:pc("preserve",yc),annotations:pc("preserve",bc),autoPlaceAnnotations:pc("preserve",bc),clock:pc("preserve",xc),transition:pc("preserve",xc),introAnimation:pc("preserve",xc),onLayoutError:pc("preserve",xc)},wc=pc("preserve",mc),Ac=class{constructor(){this.tracker=new mt}get last(){return this.tracker.last}subscribe(e){return this.tracker.subscribe(e)}recordData(e,t){return this.tracker.record({kind:e,...void 0===t?{}:{count:t}},dc)}recordNoop(e){return this.tracker.record({kind:e,..."restyle"===e?{}:{count:0}},[])}recordRestyle(e){return e?this.tracker.record({kind:"restyle"},hc):this.recordNoop("restyle")}recordConfig(e,t={}){const o=function(e){let t="preserve";const o=new Set;for(const n of e){const e=vc[n]??wc;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)o.add(t)}return{retainedData:t,invalidations:o}}(e),n=new Set(o.invalidations);return t.retainedDataChanged&&n.add("data"),this.tracker.record({kind:"config",keys:e},n)}};import{geoDistance as Sc,geoGraticule as kc,geoInterpolate as Mc}from"d3-geo";function _c(e){if(null==e)return 0;if("number"==typeof e&&Number.isFinite(e)&&e>=0&&.5>e)return e;throw new RangeError(`[semiotic] fitPadding must be a finite fraction in [0, 0.5); received ${e+""}.`)}var Pc=class e{constructor(e){this.updateResults=new Ac,this.scene=[],this.scales=null,this.version=0,this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customLayoutDiagnosticsWarned=new Set,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._customLayoutFailedThisBuild=!1,this._quadtree=null,this._maxPointRadius=0,this.projection=null,this.geoPath=null,this.baseScale=0,this.baseTranslate=[0,0],this.baseRotation=[0,0,0],this.currentZoom=1,this.cartogramLayout=null,this.areas=[],this.pointData=[],this.lineData=[],this.pointBuffer=null,this.streaming=!1,this.lastIngestTime=0,this.timestampBuffer=null,this.activeTransition=null,this.prevPositions=null,this._hasRenderedOnce=!1,this.config=function(e){return{...e,fitPadding:_c(e.fitPadding)}}(e)}currentTime(){return this.config.clock?.()??Me()}getConfiguredWindowSize(){const e=this.config.windowSize??500;if(!Number.isInteger(e)||1>e)throw Error("GeoPipelineStore windowSize must be a positive integer");return e}retainNewestLines(e=this.getConfiguredWindowSize()){this.lineData.length>e&&(this.lineData=this.lineData.slice(-e))}resizeStreamingWindow(e){if(this.pointBuffer){const t=this.pointBuffer.toArray(),o=this.timestampBuffer?.toArray()??[],n=t.slice(-e),i=o.slice(-n.length),r=this.currentTime();this.pointBuffer=new ut(e),this.timestampBuffer=new ut(e),n.forEach((e,t)=>{this.pointBuffer.push(e),this.timestampBuffer.push(i[t]??r)})}this.retainNewestLines(e)}updateConfig(e){const t=function(e){return"fitPadding"in e?{...e,fitPadding:_c(e.fitPadding)}:e}(e),o=this.config,n=this.getConfiguredWindowSize(),i=Object.keys(t).filter(e=>t[e]!==o[e]);this.config={...this.config,...t};const r=this.getConfiguredWindowSize(),s=this.streaming&&r!==n;s&&(this.resizeStreamingWindow(r),this.version++),"customLayout"in t&&!t.customLayout&&(this.lastCustomLayoutFailure=null),this.updateResults.recordConfig(i,{retainedDataChanged:s})}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setAreas(e){this.areas=e,this.updateResults.recordData("replace",e.length)}setAreasWithResult(e){return this.setAreas(e),this.updateResults.last}setPoints(e){this.pointData=e.slice(),this.pointBuffer=null,this.timestampBuffer=null,this.streaming=!1,this.updateResults.recordData("replace",e.length)}setPointsWithResult(e){return this.setPoints(e),this.updateResults.last}setLines(e){this.lineData=e.slice(),this.streaming&&this.retainNewestLines(),this.updateResults.recordData("replace",e.length)}setLinesWithResult(e){return this.setLines(e),this.updateResults.last}initStreaming(e){void 0!==e&&e!==this.config.windowSize&&(this.config={...this.config,windowSize:e});const t=this.getConfiguredWindowSize(),o=this.pointBuffer?this.pointBuffer.toArray():this.pointData,n=this.timestampBuffer?.toArray()??[],i=o.slice(-t),r=n.slice(-i.length),s=this.currentTime();this.pointBuffer=new ut(t),this.timestampBuffer=new ut(t),i.forEach((e,t)=>{this.pointBuffer.push(e),this.timestampBuffer.push(r[t]??s)}),this.pointData=[],this.retainNewestLines(t),this.streaming=!0}pushPoint(e){this.pointBuffer||this.initStreaming();const t=this.currentTime();Pe(this.pointBuffer,e,this.timestampBuffer,t),this.lastIngestTime=t,this.updateResults.recordData("ingest",1)}pushPointWithResult(e){return this.pushPoint(e),this.updateResults.last}pushMany(e){this.pointBuffer||this.initStreaming();const t=this.currentTime();for(const o of e)Pe(this.pointBuffer,o,this.timestampBuffer,t);this.lastIngestTime=t,this.updateResults.recordData("ingest",e.length)}pushManyWithResult(e){return this.pushMany(e),this.updateResults.last}pushLine(e){null!=e&&"object"==typeof e?(this.streaming||this.initStreaming(),this.lineData.push(e),this.retainNewestLines(),this.version++,this.updateResults.recordData("ingest",1)):this.updateResults.recordNoop("ingest")}pushManyLines(e){if(!Array.isArray(e)||0===e.length)return void this.updateResults.recordNoop("ingest");const t=e.filter(e=>null!=e&&"object"==typeof e);if(0!==t.length){this.streaming||this.initStreaming();for(const e of t)this.lineData.push(e);this.retainNewestLines(),this.version++,this.updateResults.recordData("ingest",t.length)}else this.updateResults.recordNoop("ingest")}removeLine(e){const{lineIdAccessor:t}=this.config;if(!t)throw Error("removeLine() requires lineIdAccessor to be configured");const o="function"==typeof t?t:e=>e[t],n=new Set(Array.isArray(e)?e:[e]),i=[];return this.lineData=this.lineData.filter(e=>!n.has(o(e)+"")||(i.push(e),!1)),i.length>0?(this.version++,this.updateResults.recordData("remove",i.length)):this.updateResults.recordNoop("remove"),i}getLines(){return this.lineData.slice()}removePoint(e){const{pointIdAccessor:t}=this.config;if(!t)throw Error("removePoint() requires pointIdAccessor to be configured");const o="function"==typeof t?t:e=>e[t],n=new Set(Array.isArray(e)?e:[e]);if(this.streaming&&this.pointBuffer){const e=e=>n.has(o(e)+"");G(this.pointBuffer,this.timestampBuffer,e);const t=this.pointBuffer.remove(e);return t.length>0?(this.version++,this.updateResults.recordData("remove",t.length)):this.updateResults.recordNoop("remove"),t}{const e=[];return this.pointData=this.pointData.filter(t=>!n.has(o(t)+"")||(e.push(t),!1)),e.length>0?(this.version++,this.updateResults.recordData("remove",e.length)):this.updateResults.recordNoop("remove"),e}}clear(){this.areas=[],this.pointData=[],this.lineData=[],this.pointBuffer=null,this.timestampBuffer=null,this.streaming=!1,this.scene=[],this.scales=null,this._hasRenderedOnce=!1,this.activeTransition=null,this.prevPositions=null,this._quadtree=null,this._maxPointRadius=0,this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._customLayoutFailedThisBuild=!1,this.version++,this.updateResults.recordData("clear")}restyleScene(e){const t=this._customRestyle;if(t){for(const o of this.scene){const n=this._baseStyles.get(o)??o.style,i=t(o,e);o.style=i?{...n,...i}:n}this.markStylePaintPending(),this.updateResults.recordRestyle(!0)}else this.updateResults.recordRestyle(!1)}computeScene(e){const{config:t}=this,o=this.projection,n=this.geoPath,i=this.scales,r=this.baseScale,s=[...this.baseTranslate],a=[...this.baseRotation],l=this.scene;this.projection=function(e){if(!e)return Zl();if("string"==typeof e){const t=oc[e];return t?t():("production"!==process.env.NODE_ENV&&console.warn(`GeoFrame: Unknown projection "${e}", falling back to equalEarth`),Zl())}if("object"==typeof e&&"type"in e){const t=oc[e.type],o=t?t():Zl();return e.rotate&&"rotate"in o&&o.rotate(e.rotate),e.center&&"center"in o&&o.center(e.center),o}return e}(t.projection),this.geoPath=ql(this.projection),this.fitProjection(e),this.geoPath=ql(this.projection);const c=this.projection;this.scales={projection:c,geoPath:this.geoPath,projectedPoint:(e,t)=>c([e,t]),invertedPoint:(e,t)=>c.invert?c.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const u=this.buildSceneNodes(e);if(this._customLayoutFailedThisBuild)!0===this.lastCustomLayoutFailure?.preservedLastGoodScene?(this.projection=o,this.geoPath=n,this.scales=i,this.baseScale=r,this.baseTranslate=s,this.baseRotation=a):(this.scene=[],this.rebuildQuadtree());else{if(this.scene=u,this.rebuildQuadtree(),t.projectionTransform&&this.applyCartogramTransform(t.projectionTransform,e),t.decay&&this.streaming&&this.applyDecay(),t.pulse&&this.streaming&&this.applyPulse(),t.transition&&!this._hasRenderedOnce&&this.scene.length>0&&t.introAnimation){const t=e.width/2,o=e.height/2,n=this.scene.filter(e=>"point"===e.type).map(e=>({...e,x:t,y:o}));n.length>0&&this.startTransition(n)}this._hasRenderedOnce=!0,t.transition&&l.length>0&&this.startTransition(l),this.version++}}fitProjection(e){const t=this.projection,o=this.config,n=[...this.areas],i=nc(o.xAccessor,"lon"),r=nc(o.yAccessor,"lat"),s=this.getPoints();if(s.length>0){const e=s.map(e=>[i(e),r(e)]);n.push({type:"Feature",properties:{},geometry:{type:"MultiPoint",coordinates:e}})}const a=ic(o.lineDataAccessor);for(const e of this.lineData){const t=a(e);if(t&&t.length>0){const e=t.map(e=>[i(e),r(e)]);n.push({type:"Feature",properties:{},geometry:{type:"LineString",coordinates:e}})}}if(0!==n.length){if(o.projectionExtent){const[[n,i],[r,s]]=o.projectionExtent;t.fitExtent([[0,0],[e.width,e.height]],{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[[n,i],[n,s],[r,s],[r,i],[n,i]]]}})}else if(t.clipAngle&&(t.clipAngle()??0)>0){const n=o.fitPadding??0,i=Math.min(e.width,e.height);t.scale(i/2-i*n),t.translate([e.width/2,e.height/2])}else{const i=o.fitPadding??0,r=e.width*i,s=e.height*i;t.fitExtent([[r,s],[e.width-r,e.height-s]],{type:"FeatureCollection",features:n})}this.baseScale=t.scale(),this.baseTranslate=t.translate(),this.baseRotation=t.rotate?.()??[0,0,0]}}applyZoomTransform(e,t){const o=this.projection;if(!o)return;const n=this.geoPath,i=this.scales,r=o.scale(),s=[...o.translate()],a=this.currentZoom;o.scale(this.baseScale*e.k),o.translate([this.baseTranslate[0]*e.k+e.x,this.baseTranslate[1]*e.k+e.y]),this.currentZoom=e.k,this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const l=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.scale(r),o.translate(s),this.currentZoom=a,this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=l,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}applyZoomScale(e,t){const o=this.projection;if(!o)return;const n=this.geoPath,i=this.scales,r=o.scale(),s=[...o.translate()],a=this.currentZoom;o.scale(this.baseScale*e),o.translate(this.baseTranslate),this.currentZoom=e,this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const l=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.scale(r),o.translate(s),this.currentZoom=a,this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=l,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}applyRotation(e,t){const o=this.projection;if(!o||!o.rotate)return;const n=this.geoPath,i=this.scales,r=[...o.rotate()];o.rotate(e),this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const s=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.rotate(r),this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=s,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}setRotation(e){const t=this.projection;t&&t.rotate&&t.rotate(e)}hasProjection(){return null!=this.projection}getRotation(){return this.projection?.rotate?.()??this.baseRotation}getBaseProjectionState(){return{scale:this.baseScale,translate:[...this.baseTranslate]}}getPoints(){return this.streaming&&this.pointBuffer?this.pointBuffer.toArray():this.pointData}rebuildQuadtree(){let t=0,o=0;for(const e of this.scene)"point"===e.type&&!1!==e.interactive&&(o++,e.r>t&&(t=e.r));if(this._maxPointRadius=t,e.QUADTREE_THRESHOLD>=o)return void(this._quadtree=null);const n=Array(o);let i=0;for(const e of this.scene)"point"===e.type&&!1!==e.interactive&&(n[i++]=e);this._quadtree=Ul().x(e=>e.x).y(e=>e.y).addAll(n)}get quadtree(){return this._quadtree}get maxPointRadius(){return this._maxPointRadius}buildSceneNodes(e){this._customLayoutFailedThisBuild=!1;const{config:t}=this,o=this.projection,n=this.geoPath;if(t.customLayout&&this.scales){const o=t.layoutMargin??{top:0,right:0,bottom:0,left:0},n=Ne(t.colorScheme,t.themeCategorical,F),i={areas:this.areas.slice(),points:this.getPoints().slice(),lines:this.lineData.slice(),scales:this.scales,dimensions:{width:e.width,height:e.height,margin:o,plot:{x:0,y:0,width:e.width,height:e.height}},theme:{semantic:t.themeSemantic??{},categorical:[...n]},resolveColor:H(n,t.colorScheme),config:t.layoutConfig??{},selection:t.layoutSelection??null};let r;try{r=t.customLayout(i)}catch(e){const o=null!==this.lastCustomLayoutResult,n=ee("geo",e,o,this.version);this.lastCustomLayoutFailure=n,this._customLayoutFailedThisBuild=!0,"production"!==process.env.NODE_ENV&&console.error("[semiotic] geo customLayout threw:",e);try{t.onLayoutError?.(n)}catch(e){"production"!==process.env.NODE_ENV&&console.error("[semiotic] onLayoutError threw:",e)}return o?this.scene:(this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,[])}const s=r.nodes??[];if(this.customLayoutOverlays=r.overlays??null,this.lastCustomLayoutResult=r,this.lastCustomLayoutFailure=null,this._customRestyle=r.restyle,this.hasCustomRestyle=!!r.restyle,this._baseStyles=new WeakMap,this.hasCustomRestyle){for(const e of s)this._baseStyles.set(e,e.style);this.restyleScene(t.layoutSelection??null)}return st({label:"geo customLayout",nodes:s,overlays:this.customLayoutOverlays,warned:this._customLayoutDiagnosticsWarned}),s}return this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,function({config:e,projection:t,path:o,areas:n,points:i,lines:r,layout:s}){const a=nc(e.xAccessor,"lon"),l=nc(e.yAccessor,"lat"),c=[],u=function(e){return{fill:e.themeSemantic?.surface||"#e0e0e0",stroke:e.themeSemantic?.border||"#999",strokeWidth:.5,fillOpacity:1}}(e),d=function(e){return{stroke:e.themeSemantic?.primary||"#4e79a7",strokeWidth:1.5,fill:"none"}}(e),h=function(e){return{fill:e.themeSemantic?.primary||"#4e79a7",r:4,fillOpacity:.8}}(e);if(e.graticule){const t=!0===e.graticule?{}:e.graticule,n=kc();t.step&&n.step(t.step);const i=o(n())||"";i&&c.push({type:"geoarea",pathData:i,centroid:[s.width/2,s.height/2],bounds:[[0,0],[s.width,s.height]],screenArea:0,style:{fill:"none",stroke:t.stroke||"#e0e0e0",strokeWidth:t.strokeWidth||.5,strokeDasharray:t.strokeDasharray||"2,2"},datum:null,interactive:!1})}for(const t of n){const n=o(t);if(!n)continue;const i=o.centroid(t),r=o.bounds(t),s=o.area(t);c.push({type:"geoarea",pathData:n,centroid:i,bounds:r,screenArea:s,style:rc(e.areaStyle,t,u),datum:t,interactive:!0})}const p=ic(e.lineDataAccessor);for(const o of r){const n=p(o);if(!n||2>n.length)continue;let i=[];if("geo"===e.lineType){const e=Array(n.length);for(let t=0;n.length>t;t++)e[t]=[a(n[t]),l(n[t])];for(let o=0;e.length-1>o;o++){const n=e[o],r=e[o+1],s=Sc(n,r)||0,a=Math.max(2,Math.ceil(s/(Math.PI/180))),l=Mc(n,r);for(let e=0;a>=e;e++){if(o>0&&0===e)continue;const n=t(l(e/a));null!=n&&i.push(n)}}}else for(let e=0;n.length>e;e++){const o=n[e],r=t([a(o),l(o)]);null!=r&&i.push(r)}if(2>i.length)continue;const r=rc(e.lineStyle,o,d),u="number"==typeof r.strokeWidth?r.strokeWidth:1;2!==n.length||2>i.length||"arc"!==e.flowStyle?2!==n.length||2>i.length||"offset"!==e.flowStyle||(i="geo"===e.lineType?lc(i,u):cc(i[0],i[i.length-1],0,0,u)):i=ac(i[0],i[i.length-1]);const h=sc(i,s.width);if(h.length>1)for(const e of h)2>e.length||c.push({type:"line",path:e,style:{...r,_edgeFade:!0},datum:o});else c.push({type:"line",path:2>i.length&&h[0]||i,style:r,datum:o})}const g=e.pointIdAccessor?"function"==typeof e.pointIdAccessor?e.pointIdAccessor:t=>t[e.pointIdAccessor]:null,m=t.clipAngle?t.clipAngle()??0:0,f=m>0?m*Math.PI/180:null,y=t.rotate?t.rotate():[0,0,0],b="function"==typeof t.center?t.center():[0,0],x=[(b[0]??0)-y[0],(b[1]??0)-y[1]];for(const o of i){const n=a(o),i=l(o);if(null!=f&&Sc([n,i],x)>f)continue;const r=t([n,i]);if(!r)continue;const s=e.pointStyle?e.pointStyle(o):{...h},u={type:"point",x:r[0],y:r[1],r:s.r||4,style:s,datum:o,pointId:g?g(o)+"":void 0};c.push(u)}return c}({config:t,projection:o,path:n,areas:this.areas,points:this.getPoints(),lines:this.lineData,layout:e})}applyCartogramTransform(e,t){const o=function(e,t,o,n){const i=e.filter(e=>"point"===e.type);if(2>i.length)return null;const r=t.strength??1,s=Number.isFinite(r)?Math.max(0,Math.min(1,r)):1,a="strip"===t.layout?"strip":"radial";if("radial"===a&&0===s)return null;const l=t.centerAccessor?"function"==typeof t.centerAccessor?t.centerAccessor:e=>e[t.centerAccessor]:e=>e.id,c="function"==typeof t.costAccessor?t.costAccessor:e=>e[t.costAccessor],u=i.find(e=>e.datum&&l(e.datum)+""==t.center+"");if(!u)return"production"!==process.env.NODE_ENV&&console.warn(`GeoFrame: Distance cartogram center "${t.center}" not found in point data`),null;const d=i.map(e=>e.datum?Number(c(e.datum)):NaN).filter(e=>isFinite(e)&&e>=0),h=zt(d,1);n>0&&"production"!==process.env.NODE_ENV&&console.warn("GeoFrame: Distance cartogram does not support area rendering. Areas will be ignored. Remove areas or set projectionTransform to null to render them.");for(let t=e.length-1;t>=0;t--){const o=e[t];"geoarea"===o.type&&o.interactive&&e.splice(t,1)}const p="strip"===a?function(e,t,o,n,i){const r=Math.max(3,Math.min(8,.35*i.height)),s=Math.max(1,i.width-2*r),a=i.height/2,l=uc().domain([0,n]).range([0,s]);t.x=r,t.y=a;const c=[];for(const i of e){if(i===t)continue;if(!i.datum){i.x=r,i.y=a;continue}const e=Number(o(i.datum)),s=r+(isFinite(e)&&e>=0&&n>0?l(e):0);i.x=s,i.y=a,c.push({node:i,x:s})}c.sort((e,t)=>e.x-t.x);const u=Math.max(0,Math.min(i.height/2-1,6));let d=0;for(;c.length>d;){let e=d+1;for(;c.length>e&&3>Math.abs(c[e].x-c[d].x);)e++;const t=e-d;if(t>1&&u>0)for(let e=0;t>e;e++)c[d+e].node.y=a+(e-(t-1)/2)*Math.min(2.5,2*u/Math.max(1,t-1));d=e}return{cx:r,cy:a,maxCost:n,availableRadius:s,layout:"strip"}}(i,u,c,h,o):function(e,t,o,n,i,r){const s=t.x,a=t.y,l=r.width/2,c=r.height/2,u=Math.min(r.width,r.height)/2,d=uc().domain([0,n]).range([0,u]);for(const r of e){if(r===t)continue;if(!r.datum)continue;const e=r.x,u=r.y,h=Math.atan2(u-a,e-s),p=Math.hypot(e-s,u-a),g=Number(o(r.datum)),m=isFinite(g)&&g>=0?n>0?d(g):0:p,f=l+Math.cos(h)*m,y=c+Math.sin(h)*m;r.x=e+(f-e)*i,r.y=u+(y-u)*i}return t.x=s+(l-s)*i,t.y=a+(c-a)*i,{cx:t.x,cy:t.y,maxCost:n,availableRadius:u,layout:"radial"}}(i,u,c,h,s,o),g=e.filter(e=>"line"===e.type);if(g.length>0){const e=new Map;for(const t of i)null!=t.pointId&&e.set(t.pointId+"",[t.x,t.y]);for(const o of g){const n=o.datum?.source,i=o.datum?.target;if(null!=n&&null!=i){const r=e.get(n+""),s=e.get(i+"");if(r&&s)if("fractional"===t.lineMode&&o.path.length>2){const e=o.path[0],t=o.path[o.path.length-1],n=[r[0]-e[0],r[1]-e[1]],i=[s[0]-t[0],s[1]-t[1]],a=[0];for(let e=1;o.path.length>e;e++)a.push(a[e-1]+Math.hypot(o.path[e][0]-o.path[e-1][0],o.path[e][1]-o.path[e-1][1]));const l=a[a.length-1];o.path=o.path.map((e,t)=>{const r=l>0?a[t]/l:t/(o.path.length-1);return[e[0]+n[0]*(1-r)+i[0]*r,e[1]+n[1]*(1-r)+i[1]*r]})}else o.path=[r,s]}}}return p}(this.scene,e,t,this.areas.length);o&&(this.cartogramLayout=o)}applyDecay(){const e=this.config.decay;if(!e||!this.pointBuffer)return;const t=this.pointBuffer.size;if(0===t)return;const o=this.scene.filter(e=>"point"===e.type);for(let n=0;o.length>n;n++){const i=q(e,n,t);o[n]._decayOpacity=i,o[n].style={...o[n].style,opacity:i}}}applyPulse(e=this.currentTime()){const t=this.config.pulse;if(!t||!this.timestampBuffer)return!1;const o=this.scene.filter(e=>"point"===e.type),n=this.timestampBuffer.toArray(),i=t.color||"rgba(255,255,255,0.6)",r=t.glowRadius??4;let s=!1;for(let a=0;o.length>a&&n.length>a;a++){const l=Q(t,n[a],e);s=Ue(o[a],l,i,r)||s}return s}refreshPulse(e){return!0!==this.lastCustomLayoutFailure?.preservedLastGoodScene&&this.applyPulse(e)}hasActivePulsesAt(e){return!!this.config.pulse&&he(this.config.pulse,this.timestampBuffer,e)}get hasActivePulses(){return this.hasActivePulsesAt(this.currentTime())}startTransition(e){const t=this.config.transition?.duration??300;if(0>=t)return;const o=new Map;for(const t of e)"point"===t.type&&t.pointId&&o.set(t.pointId,[t.x,t.y]);const n=this.scene.filter(e=>"point"===e.type);let i=!1;for(const e of n)if(e.pointId){const t=o.get(e.pointId);t&&(e._targetX=e.x,e._targetY=e.y,e.x=t[0],e.y=t[1],(Math.abs(t[0]-e._targetX)>.5||Math.abs(t[1]-e._targetY)>.5)&&(i=!0))}for(const e of n)e.pointId&&!o.has(e.pointId)&&(e._targetOpacity=e.style?.opacity??e.style?.fillOpacity??1,e.style={...e.style,opacity:0},i=!0);i&&(this.activeTransition={startTime:this.currentTime(),duration:t})}cancelIntroAnimation(){this.activeTransition=null;for(const e of this.scene)"point"===e.type&&(null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity},e._targetOpacity=void 0),null!=e._targetX&&(e.x=e._targetX,e.y=e._targetY,e._targetX=void 0,e._targetY=void 0))}advanceTransition(e){if(!this.activeTransition)return!1;const t=Z(e,this.activeTransition),o=U(t),n=this.scene.filter(e=>"point"===e.type);for(const e of n){if(null!=e._targetX&&null!=e._targetY){const t=e.y;e.x=be(e.x,e._targetX,o),e.y=be(t,e._targetY,o)}null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity*o})}if(t>=1){for(const e of n)null!=e._targetX&&(e.x=e._targetX,e.y=e._targetY,e._targetX=void 0,e._targetY=void 0),null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity},e._targetOpacity=void 0);return this.activeTransition=null,!1}return!0}};Pc.QUADTREE_THRESHOLD=500;var Tc=Pc;j(Tc);import{Fragment as Lc,jsxs as Rc}from"react/jsx-runtime";function Ic(e,t){const o=Kt(e.theme),n=e.size||[e.width||600,e.height||400],i=ze({top:10,right:10,bottom:10,left:10,...e.margin},e.title),r=pe(e.title),s=Array.isArray(e.areas)?ie(e.areas):e.areas,a=ie(e.points),l=ie(e.lines),c=e.showLegend?(()=>{const t="string"==typeof(o=e.colorBy)||"function"==typeof o?e.colorBy:void 0;var o;return Ea(a.length>0?a:Array.isArray(s)&&s.length>0?"string"==typeof t?s.map(e=>({...e.properties||{},...e})):s:[],t)})():[];ol(i,{props:e,categories:c,theme:o,size:n,hasTitle:r});const u=n[0]-(i.left??0)-(i.right??0),d=n[1]-(i.top??0)-(i.bottom??0),h={projection:e.projection||"equalEarth",xAccessor:e.xAccessor,yAccessor:e.yAccessor,lineDataAccessor:e.lineDataAccessor,pointIdAccessor:e.pointIdAccessor,lineType:e.lineType,areaStyle:e.areaStyle,pointStyle:e.pointStyle,lineStyle:e.lineStyle,graticule:e.graticule,fitPadding:e.fitPadding,projectionTransform:e.projectionTransform,customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,themeCategorical:o.colors.categorical,themeSemantic:Dt(o)},p=new Tc(h);if(s){if("string"==typeof s)throw Error(`Geo SSR requires pre-resolved GeoJSON features. Reference string "${s}" cannot be resolved synchronously. Use \`const features = await resolveReferenceGeography('${s}')\` before calling renderGeoToStaticSVG.`);p.setAreas(s)}e.points&&p.setPoints(a),e.lines&&p.setLines(l),p.computeScene({width:u,height:d});const g=Ie({nodes:p.scene,renderMode:e.renderMode,fallback:(e,t)=>ae(e,t)});if(t&&(t.evidence=Sa({frameType:"geo",width:n[0],height:n[1],marks:g.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,legendItems:c.length>0?c.length:void 0,margin:i})),0===g.length){const t=e.backgroundGraphics||e.foregroundGraphics||e.annotations||p.customLayoutOverlays?Rc(Lc,{children:[e.backgroundGraphics,e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{geoProjection:p.scales?.projectedPoint?([e,t])=>p.scales.projectedPoint(e,t):void 0},layout:{width:u,height:d},theme:o,idPrefix:e._idPrefix}):null,e.foregroundGraphics,p.customLayoutOverlays]}):null;return Xl.renderToStaticMarkup(rl(t,{width:n[0],height:n[1],className:"stream-geo-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left??0},${i.top??0})`,innerWidth:u,innerHeight:d,idPrefix:e._idPrefix}))}const m=g.map(e=>e.element),f=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{geoProjection:p.scales?.projectedPoint?([e,t])=>p.scales.projectedPoint(e,t):void 0},layout:{width:u,height:d},theme:o,idPrefix:e._idPrefix}):null,y=nl({props:e,categories:c,theme:o,size:n,margin:i,hasTitle:r});return Xl.renderToStaticMarkup(rl(Rc(Lc,{children:[e.backgroundGraphics,m,f,e.foregroundGraphics,p.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-geo-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left??0},${i.top??0})`,innerWidth:u,innerHeight:d,legend:y,idPrefix:e._idPrefix}))}import*as Cc from"react-dom/server";function zc(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Fc={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Oc(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function Bc(e,t){const o="function"==typeof t?t(e):t;return{...Fc,...o??{}}}function Nc(e,t={}){return e.map(e=>function(e,t={}){const o=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),n={label:t.getBodyLabel?.(e)??Oc(e)},i={style:Bc(e,t.bodyStyle),datum:o,accessibleDatum:o,accessibility:n,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...i}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...i}}(e,t))}import{jsx as Ec,jsxs as jc}from"react/jsx-runtime";var $c={top:0,right:0,bottom:0,left:0};function Dc(e,t,o){return"function"==typeof e?e({size:t,margin:o}):e}function Wc(e,t){const o=e.size??[e.width??600,e.height??400],n=new d(e.config);Array.isArray(e.initialSpawns)&&e.initialSpawns.length>0&&n.enqueue(e.initialSpawns.map(e=>({...e,spawnAt:void 0})));const i=function(e,t={}){const{width:o=640,height:n=360,title:i,description:r,background:s,backgroundGraphics:a,className:l,foregroundGraphics:c,idPrefix:u="physics",margin:d,renderBodySVG:h,...p}=t,g=function(e,t={}){const o=e.settle(t.maxSteps),n=e.readBodies(),i=e.snapshot(),r=Nc(n,t),s=function(e,t={}){const o=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),n=o.filter(e=>e.sleeping).length,i=e.queue.length,r=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===i&&n===o.length,a=[];i>0&&a.push("PHYSICS_QUEUE_UNDRAINED");const l=null!=t.charge&&Number.isFinite(t.charge)?function(e,t,o,n){const i=e-(t+o+n);return{charge:e,live:t,queued:o,sedimented:n,unaccounted:i,balanced:0===i}}(t.charge,o.length,i,r):void 0;return l&&!l.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:o.length,sleepingCount:n,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:zc(t.projectionRows),queuedCount:i,sedimentedCount:r,...l?{ledger:l}:{},warnings:a}}(i,{bodies:n,projectionRows:t.projectionRows,stepsRun:o,charge:t.charge});return{snapshot:i,bodies:n,sceneNodes:r,evidence:s,stepsRun:o}}(e,p),m={...$c,...d},f=[o,n],y=Dc(a,f,m),b=Dc(c,f,m),x=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(u),v=i?x+"-title":void 0,w=r?x+"-desc":void 0,A=[v,w].filter(Boolean).join(" ")||void 0;return{svg:Cc.renderToStaticMarkup(jc("svg",{xmlns:"http://www.w3.org/2000/svg",className:l??"stream-physics-frame",width:o,height:n,viewBox:`0 0 ${o} ${n}`,role:"img","aria-labelledby":A,children:[i&&Ec("title",{id:v,children:i}),r&&Ec("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?Ec("rect",{x:0,y:0,width:o,height:n,fill:s}):null,y,Ec("g",{id:x+"-data-area",children:g.sceneNodes.map((e,t)=>{const o=g.bodies[t];return(o&&h?h(o,e.style??{},t,x):void 0)??at(e,t,x)})}),b]})),scene:g,evidence:g.evidence}}(n,{...e,width:o[0],height:o[1],charge:e.charge,idPrefix:e.idPrefix??e._idPrefix??"physics"});return t&&(t.evidence=Sa({frameType:"physics",width:o[0],height:o[1],marks:i.scene.sceneNodes,title:e.title,description:e.description,annotations:[],extraWarnings:[...0===i.scene.sceneNodes.length?["PHYSICS_EMPTY_SCENE"]:[],...i.scene.evidence.warnings]})),i.svg}import*as Yc from"react-dom/server";import{jsx as Hc,jsxs as Vc}from"react/jsx-runtime";var Gc={tile:{width:280,height:184,padding:16,labelSize:13,captionSize:11,valueSize:40,detailSize:13,align:"start",border:!0,showHeader:!0,showDetail:!0},presentation:{width:540,height:320,padding:32,labelSize:18,captionSize:14,valueSize:96,detailSize:18,align:"center",border:!0,showHeader:!0,showDetail:!0},inline:{width:240,height:64,padding:8,labelSize:0,captionSize:0,valueSize:28,detailSize:13,align:"start",border:!1,showHeader:!1,showDetail:!0},thumbnail:{width:96,height:56,padding:6,labelSize:0,captionSize:0,valueSize:22,detailSize:0,align:"center",border:!1,showHeader:!1,showDetail:!1}};function Xc(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}var qc={BigNumber:function(e,t){const o="presentation"===e.mode||"inline"===e.mode||"thumbnail"===e.mode?e.mode:"tile",n=Gc[o],i=Xc(e.width,n.width),r=Xc(e.height,n.height),s="number"==typeof e.padding&&Number.isFinite(e.padding)?Math.max(0,e.padding):n.padding,a="center"===e.align||"end"===e.align||"start"===e.align?e.align:n.align,l="center"===a?"middle":"end"===a?"end":"start",c="center"===a?i/2:"end"===a?i-s:s,u=Kt(e.theme),d="number"==typeof e.value&&Number.isFinite(e.value)?e.value:void 0,h=function(e,t={}){if("function"==typeof e)return e;const o=t.locale??"en-US";if("currency"===e){const e=t.precision??2,n=new Intl.NumberFormat(o,{style:"currency",currency:t.currency??"USD",maximumFractionDigits:e,minimumFractionDigits:e});return e=>n.format(e)}if("percent"===e){const e=new Intl.NumberFormat(o,{style:"percent",maximumFractionDigits:t.precision??1,minimumFractionDigits:0});return t=>e.format(t)}if("compact"===e){const e=new Intl.NumberFormat(o,{notation:"compact",maximumFractionDigits:t.precision??1,minimumFractionDigits:0});return t=>e.format(t)}if("duration"===e)return e=>function(e){if(!Number.isFinite(e))return e+"";const t=0>e?"-":"",o=Math.abs(e);if(1e3>o)return`${t}${Math.round(o)}ms`;const n=o/1e3;if(60>n)return`${t}${i=n,Math.round(100*i)/100+""}s`;var i;const r=n/60;if(60>r){const e=Math.floor(r),o=Math.round(n-60*e);return 0===o?`${t}${e}m`:`${t}${e}m ${o}s`}const s=r/60;if(24>s){const e=Math.floor(s),o=Math.round(r-60*e);return 0===o?`${t}${e}h`:`${t}${e}h ${o}m`}const a=Math.floor(s/24),l=Math.round(s-24*a);return 0===l?`${t}${a}d`:`${t}${a}d ${l}h`}(e);const n=new Intl.NumberFormat(o,{notation:t.notation??"standard",maximumFractionDigits:t.precision??0,minimumFractionDigits:0});return e=>n.format(e)}("string"==typeof e.format||"function"==typeof e.format?e.format:"number",{locale:"string"==typeof e.locale?e.locale:void 0,currency:"string"==typeof e.currency?e.currency:void 0,precision:"number"==typeof e.precision?e.precision:void 0}),p=void 0===d?"No value":(g=h(d),`${("string"==typeof e.prefix?e.prefix:void 0)??""}${g}${("string"==typeof e.suffix?e.suffix:void 0)??""}`);var g;const m=void 0===d?void 0:function(e,t){if(!t||0===t.length)return null;if(!Number.isFinite(e))return null;const o=t.filter(e=>Number.isFinite(e.at)||e.at===-1/0).slice().sort((e,t)=>e.at-t.at);let n=null;for(const t of o){if(t.at>e)break;n=t}return n}(d,e.thresholds),f="string"==typeof e.color?e.color:function(e,t,o){return t||("success"===e?o.colors.success??"#2ca02c":"warning"===e?o.colors.warning??"#b26a00":"danger"===e?o.colors.danger??"#d62728":"info"===e?o.colors.info??o.colors.primary:o.colors.text)}(m?.level??"neutral",m?.color,u),y="string"==typeof e.label?e.label:void 0,b="string"==typeof e.caption?e.caption:void 0,x="string"==typeof e.unit?e.unit:void 0,v=void 0===d?void 0:function(e,t,o){const n=e.comparison&&"object"==typeof e.comparison?e.comparison:void 0,i=n&&"number"==typeof n.value&&Number.isFinite(n.value)?n.value:void 0,r=("number"==typeof e.delta&&Number.isFinite(e.delta)?e.delta:void 0)??(void 0===i?void 0:t-i);if(void 0===r)return;const s=function(e,t){return Number.isFinite(e)?0===e?t(0):`${e>0?"+":"−"}${t(Math.abs(e))}`:""}(r,o);return`${s}${n&&"string"==typeof n.label?" "+n.label:""}`}(e,d,h),w=void 0===d?void 0:function(e,t,o){const n=e.target&&"object"==typeof e.target?e.target:void 0;if(!n||"number"!=typeof n.value||!Number.isFinite(n.value))return;const i="string"==typeof n.label?" "+n.label:"";return 0===n.value?`target ${o(n.value)}${i}`:`${new Intl.NumberFormat("string"==typeof e.locale?e.locale:"en-US",{style:"percent",maximumFractionDigits:0}).format(t/n.value)} of ${o(n.value)}${i}`}(e,d,h),A=[v,w,m?.label].filter(Boolean).join(" · "),S="string"==typeof e.description&&e.description||[y,p,x,A].filter(Boolean).join(", "),k="string"==typeof e.background?e.background:u.colors.surface??u.colors.background,M="string"==typeof e.borderColor?e.borderColor:u.colors.border,_=s+n.labelSize,P=_+n.captionSize+4,T="presentation"===o?r/2+.32*n.valueSize:"thumbnail"===o?r/2+.34*n.valueSize:Math.min(r-s-(A?26:4),(n.showHeader&&(y||b)?b?P+10:_+14:s)+n.valueSize),L=c+("start"===l?Math.max(n.valueSize,p.length*n.valueSize*.55):0),R=Yc.renderToStaticMarkup(Vc("svg",{xmlns:"http://www.w3.org/2000/svg",width:i,height:r,viewBox:`0 0 ${i} ${r}`,role:"img","aria-label":S,"data-semiotic-component":"BigNumber",children:[Hc("title",{children:y??p}),"string"==typeof e.description&&Hc("desc",{children:e.description}),Hc("rect",{x:n.border?.5:0,y:n.border?.5:0,width:n.border?i-1:i,height:n.border?r-1:r,rx:n.border?8:0,fill:k,stroke:n.border?M:"none"}),n.showHeader&&y&&Hc("text",{x:c,y:_,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.labelSize,fontWeight:600,fill:u.colors.text,children:y}),n.showHeader&&b&&Hc("text",{x:c,y:P,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.captionSize,fill:u.colors.textSecondary,children:b}),Hc("text",{x:c,y:T,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.valueSize,fontWeight:600,fontVariant:"tabular-nums",fill:void 0===d?u.colors.textSecondary:f,"data-mark-type":"value",children:p}),x&&void 0!==d&&"start"===l&&Hc("text",{x:L+6,y:T,textAnchor:"start",fontFamily:u.typography.fontFamily,fontSize:Math.max(11,Math.round(.32*n.valueSize)),fontWeight:500,fill:u.colors.textSecondary,children:x}),n.showDetail&&A&&Hc("text",{x:c,y:Math.min(r-s,T+n.detailSize+10),textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.detailSize,fill:u.colors.textSecondary,children:A})]}));return t&&(t.evidence=Sa({frameType:"value",width:i,height:r,marks:void 0===d?[]:[{type:"value"}],title:y,description:S})),R}};function Uc(e,t,o){return qc[e](t,o)}import{Fragment as Qc,jsx as Zc,jsxs as Kc}from"react/jsx-runtime";function Jc(e,t){switch(e){case"xy":return cl(t);case"ordinal":return $l(t);case"network":return Gl(t);case"geo":return Ic(t);case"physics":return Wc(t);default:throw Error(`Unknown frame type: ${e}. Must be "xy", "ordinal", "network", "geo", or "physics".`)}}function eu(e){return cl(e)}function tu(e){return $l(e)}function ou(e){return Gl(e)}function nu(e){return Ic(e)}var iu=["showAxes","axes","axisExtent","xLabel","yLabel","yLabelRight","categoryLabel","valueLabel","xFormat","yFormat","categoryFormat","valueFormat","tickFormatTime","tickFormatValue","xScaleType","yScaleType","xExtent","yExtent","rExtent","oExtent","extentPadding","scalePadding","sizeRange","innerRadius","centerContent","curve","gradientFill","lineGradient","lineStyle","pointStyle","areaStyle","barStyle","waterfallStyle","swarmStyle","pieceStyle","summaryStyle","nodeStyle","edgeStyle","connectorStyle","backgroundGraphics","foregroundGraphics","svgPreRenderers","svgAnnotationRules","barColors","legend","legendLayout","autoPlaceAnnotations"],ru=["width","height","showAxes","showGrid","enableHover","showLegend","showLabels","showCategoryTicks","orientation","title","description","summary","accessibleTable","xLabel","yLabel","categoryLabel","valueLabel","linkedHover","mobileInteraction","mobileSemantics","responsiveRules"];function su(e,t){const o={};for(const n of t)void 0!==e[n]&&(o[n]=e[n]);return o}function au(e,t,o){return cu(e,t).svg}function lu(e,t,o){const n={},{svg:i,frameType:r}=cu(e,t,0,n),s=n.evidence??Sa({frameType:r,width:"number"==typeof t.width?t.width:600,height:"number"==typeof t.height?t.height:400,marks:[],title:"string"==typeof t.title?t.title:void 0,description:"string"==typeof t.description?t.description:void 0,annotations:t.annotations,extraWarnings:["NO_EVIDENCE"]});return s.component=e,{svg:i,evidence:s}}function cu(e,t,o,n){if(e in qc)return{svg:Uc(e,t,n),frameType:"value"};const i=va[e];if(!i)throw Error(`Unknown chart component: "${e}". See CLAUDE.md for supported chart types.`);const r=i.layout?.mode??(ge(t.mode)?t.mode:void 0),s=Be(r,{...i.layout?.modeDefaults,...su(t,ru)},i.layout?.primarySize),{data:a,theme:l,background:c,className:u,annotations:d,margin:h,colorScheme:p,colorBy:g,legendPosition:m,...f}=t,{width:y,height:b}=s,x=[y,b],v=f.frameProps||{},w=i.layout?.margin,A="function"==typeof w?w(t,s):w??s.marginDefaults,S=void 0!==h?h:v.margin,k=Yt(S),M="number"==typeof S?{top:S,right:S,bottom:S,left:S}:{...A,...k},_=su(f,iu),P=e=>v[e]??s[e],T={...v,..._,theme:l,title:s.title,description:s.description,showAxes:P("showAxes"),showLegend:P("showLegend"),showLabels:P("showLabels"),showGrid:P("showGrid"),xLabel:P("xLabel"),yLabel:P("yLabel"),categoryLabel:P("categoryLabel"),valueLabel:P("valueLabel"),background:c,className:u,annotations:d,size:x,margin:M,__explicitMargin:S,__autoLegendMargin:!0,...void 0!==p&&{colorScheme:p},...void 0!==m&&{legendPosition:m},_idPrefix:f._idPrefix},L=i.buildProps(a,g,p,T,f);let R;switch(i.frameType){case"xy":R=cl(L,n);break;case"ordinal":R=$l(L,n);break;case"network":R=Gl(L,n);break;case"geo":R=Ic(L,n);break;case"physics":R=Wc(L,n)}const I=i.renderOverlay?.(L,{theme:Kt(l)});if(null!=I){const e=Ht.renderToStaticMarkup(Zc(Qc,{children:I}));R=R.replace("</svg>",e+"</svg>")}return{svg:R,frameType:i.frameType}}function uu(e,t={}){const{title:o,subtitle:n,theme:i,width:r=1200,height:s,layout:a={},background:l}=t,c=Jt(Kt(i)),u=a.columns||2,d=a.gap??16;let h=0;o&&(h+=30),n&&(h+=20),h>0&&(h+=10);const p=Math.floor((r-d-d*(u-1))/u),g=[];let m=0,f=h+d,y=0;for(const t of e){const e=Math.min(t.colSpan||1,u),o=t.props.height||300;m+e>u&&(f+=y+d,m=0,y=0),g.push({chart:t,x:d/2+m*(p+d),y:f,w:p*e+d*(e-1),h:o}),y=Math.max(y,o),m+=e}const b=s||f+y+d,x=g.map((e,t)=>{const{chart:o,x:n,y:r,w:s,h:a}=e,l={...o.props,width:s,height:a,theme:i,_idPrefix:"chart-"+t};let c;return c=o.component?au(o.component,l):o.frameType?Jc(o.frameType,l):`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${a}"></svg>`,Zc("g",{transform:`translate(${n},${r})`,children:Zc("foreignObject",{width:s,height:a,children:Zc("div",{xmlns:"http://www.w3.org/1999/xhtml",dangerouslySetInnerHTML:{__html:c}})})},"dashboard-chart-"+t)});return Ht.renderToStaticMarkup(Kc("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:b,role:"img","aria-label":o||"Dashboard",style:{fontFamily:c.fontFamily},children:[o&&Zc("title",{children:o}),l&&Zc("rect",{x:0,y:0,width:r,height:b,fill:l}),o&&Zc("text",{x:r/2,y:24,textAnchor:"middle",fontSize:c.titleSize+4,fontWeight:"bold",fill:c.text,fontFamily:c.fontFamily,children:o}),n&&Zc("text",{x:r/2,y:o?46:20,textAnchor:"middle",fontSize:c.labelSize,fill:c.textSecondary,fontFamily:c.fontFamily,children:n}),x]}))}import*as du from"react-dom/server";import{Fragment as hu,jsx as pu,jsxs as gu}from"react/jsx-runtime";function mu(e,t,o,n={}){const{stepSize:i,windowSize:r,frameCount:s,xExtent:a,yExtent:l,transitionFrames:c=4,fps:u=12,easing:d="ease-out",decay:h}=n,p=o.width||600,g=o.height||400,m=Kt(o.theme),f={...o,...a&&{xExtent:a},...l&&{yExtent:l}};if(!t||0===t.length)return[];const y=i||Math.max(1,Math.ceil(t.length/(s||Math.min(60,Math.max(10,t.length))))),b=[];for(let e=y;t.length>=e;e+=y)b.push(e);b[b.length-1]!==t.length&&b.push(t.length);const x=new Set(["bar","pie","donut","clusterbar","swarm","point","boxplot","violin","histogram","timeline","swimlane","ridgeline","funnel","bar-funnel"]).has(e),v=ze({top:20,right:20,bottom:30,left:40,...o.margin},o.title),w=p-v.left-v.right,A=g-v.top-v.bottom,S=[];if(x)for(let n=0;b.length>n;n++){const i=b[n],s=t.slice(r?Math.max(0,i-r):0,i),a={chartType:e,windowSize:1e4,windowMode:"sliding",extentPadding:.05,projection:o.projection||"vertical",oAccessor:o.oAccessor||o.categoryAccessor||"category",rAccessor:o.rAccessor||o.valueAccessor||"value",colorAccessor:o.colorAccessor||o.colorBy,stackBy:o.stackBy,groupBy:o.groupBy,barPadding:o.barPadding,innerRadius:o.innerRadius,normalize:o.normalize,bins:o.bins,colorScheme:o.colorScheme||m.colors.categorical,...h&&{decay:h}},l=new Fl(a);l.ingest({inserts:s,bounded:!0}),l.computeScene({width:w,height:A}),l.scene.length>0&&S.push(wu(l.scene,p,g,m,f))}else for(let n=0;b.length>n;n++){const i=b[n],s=t.slice(r?Math.max(0,i-r):0,i),y={chartType:e,windowSize:s.length+10,windowMode:"sliding",arrowOfTime:"right",extentPadding:.1,xAccessor:o.xAccessor||"x",yAccessor:o.yAccessor||"y",colorAccessor:o.colorAccessor||o.colorBy,groupAccessor:o.groupAccessor||o.lineBy,lineDataAccessor:o.lineDataAccessor,xExtent:a,yExtent:l,colorScheme:o.colorScheme||m.colors.categorical,lineStyle:o.lineStyle,pointStyle:o.pointStyle,areaStyle:o.areaStyle,sizeAccessor:o.sizeAccessor||o.sizeBy,sizeRange:o.sizeRange,...h&&{decay:h},...c>0&&{transition:{duration:c*(1e3/u),easing:d}}},x=new z(y);if(x.ingest({inserts:s,bounded:!0}),x.computeScene({width:w,height:A}),0===x.scene.length)continue;const v=x.scales?{y:x.scales.y}:void 0;if(S.push(vu(x.scene,p,g,m,f,v)),c>0&&n>0&&x.activeTransition){const e=c*(1e3/u);for(let t=1;c>=t;t++)x.advanceTransition(x.activeTransition.startTime+t/c*e),S.push(vu(x.scene,p,g,m,f,v))}}return S}function fu(e,t,o={}){return t.map(t=>{try{return au(e,{...o,...t})}catch{return`<svg xmlns="http://www.w3.org/2000/svg" width="${o.width||t.width||600}" height="${o.height||t.height||400}"></svg>`}})}function yu(e,t,o){const n=t.size??[t.width??600,t.height??400],i=Kt(t.theme),r=Jt(i),s=t.background||i.colors.background,a=t.idPrefix??"physics-gif",l=t.title?`${a}-title-${o}`:void 0,c=t.description?`${a}-desc-${o}`:void 0,u=[l,c].filter(Boolean).join(" ")||void 0,d=Nc(e.readBodies(),{bodyStyle:t.bodyStyle,getBodyLabel:t.getBodyLabel}),h=gu("svg",{xmlns:"http://www.w3.org/2000/svg",className:t.className??"stream-physics-frame",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,role:"img","aria-labelledby":u,style:{fontFamily:r.fontFamily},children:[t.title&&pu("title",{id:l,children:t.title}),t.description&&pu("desc",{id:c,children:t.description}),s&&"transparent"!==s?pu("rect",{x:0,y:0,width:n[0],height:n[1],fill:s}):null,pu("g",{id:`${a}-frame-${o}`,children:d.map((e,t)=>at(e,t,`${a}-${o}`))})]});return du.renderToStaticMarkup(h)}function bu(e,t={}){const{fps:o=12,frameCount:n,durationSeconds:i=2,includeInitialFrame:r=!0,stepDt:s,stepsPerFrame:a,background:l}=t,c=Math.max(.001,s??e.config?.fixedDt??1/120),u=a??Math.max(1,Math.round(1/Math.max(1,o)/c)),h=n??Math.max(1,Math.ceil(i*Math.max(1,o))),p=l?{...e,background:l}:e,g=new d(e.config);e.initialSpawns?.length&&g.enqueue(e.initialSpawns,e.initialSpawnPacing);const m=[];for(r&&(g.tick(0),m.push(yu(g,p,0)));h>m.length;){for(let e=0;u>e;e+=1)g.tick(c);m.push(yu(g,p,m.length))}return m}function xu(e,t){const o=e.background||t.colors.background;return o&&"transparent"!==o?o:null}function vu(e,t,o,n,i,r){const s=Jt(n),a=ze({top:20,right:20,bottom:30,left:40,...i.margin},i.title),l=t-a.left-a.right,c=o-a.top-a.bottom,u=xu(i,n),d=i.renderMode,h=e.map((e,t)=>Ce({node:e,index:t,renderMode:d,fallback:()=>at(e,t)})).filter(Boolean),p=function(e,t,o,n,i,r){if(!e||0===e.length)return null;const s=Jt(n),a=[];for(let n=0;e.length>n;n++){const l=e[n];if("y-threshold"===l.type&&null!=l.value){let e=null;if(r)e=r(l.value);else if(i){const[t,n]=i,r=n-t;if(0===r)continue;e=o-(l.value-t)/r*o}if(null==e)continue;const c=l.color||s.primary,u=l.labelPosition||"right";a.push(gu("g",{children:[pu("line",{x1:0,y1:e,x2:t,y2:e,stroke:c,strokeWidth:l.strokeWidth??1.5,strokeDasharray:l.strokeDasharray||"6,4"}),l.label&&pu("text",{x:"left"===u?4:"center"===u?t/2:t-4,y:20>e?Math.min(o-4,e+16):e-5,textAnchor:"left"===u?"start":"center"===u?"middle":"end",fontSize:s.tickSize,fill:c,fontFamily:s.fontFamily,children:l.label})]},"ann-"+n))}}return a.length>0?pu(hu,{children:a}):null}(i.annotations,l,c,n,i.yExtent,r?.y),g="string"==typeof i.title?i.title:void 0,m="string"==typeof i.description?i.description:void 0,f=g?"semiotic-title":void 0,y=m?"semiotic-desc":void 0,b=[f,y].filter(Boolean).join(" ")||void 0;return du.renderToStaticMarkup(gu("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:o,role:"img","aria-labelledby":b,style:{fontFamily:s.fontFamily},children:[g&&pu("title",{id:f,children:g}),m&&pu("desc",{id:y,children:m}),u&&pu("rect",{x:0,y:0,width:t,height:o,fill:u}),gu("g",{transform:`translate(${a.left},${a.top})`,children:[p,h]}),g&&pu("text",{x:t/2,y:E,textAnchor:"middle",fontSize:s.titleSize,fontWeight:"bold",fill:s.text,fontFamily:s.fontFamily,children:g})]}))}function wu(e,t,o,n,i){const r=Jt(n),s=ze({top:20,right:20,bottom:30,left:40,...i.margin},i.title),a="radial"===i.projection,l=a?s.left+(t-s.left-s.right)/2:s.left,c=a?s.top+(o-s.top-s.bottom)/2:s.top,u=xu(i,n),d=i.renderMode,h=e.map((e,t)=>Ce({node:e,index:t,renderMode:d,fallback:()=>_e(e,t)})).filter(Boolean),p="string"==typeof i.title?i.title:void 0,g="string"==typeof i.description?i.description:void 0,m=p?"semiotic-title":void 0,f=g?"semiotic-desc":void 0,y=[m,f].filter(Boolean).join(" ")||void 0;return du.renderToStaticMarkup(gu("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:o,role:"img","aria-labelledby":y,style:{fontFamily:r.fontFamily},children:[p&&pu("title",{id:m,children:p}),g&&pu("desc",{id:f,children:g}),u&&pu("rect",{x:0,y:0,width:t,height:o,fill:u}),pu("g",{transform:`translate(${l},${c})`,children:h}),p&&pu("text",{x:t/2,y:E,textAnchor:"middle",fontSize:r.titleSize,fontWeight:"bold",fill:r.text,fontFamily:r.fontFamily,children:p})]}))}export{mu as generateFrameSVGs,fu as generateFrameSequence,bu as generatePhysicsFrameSVGs,au as renderChart,lu as renderChartWithEvidence,uu as renderDashboard,nu as renderGeoToStaticSVG,ou as renderNetworkToStaticSVG,tu as renderOrdinalToStaticSVG,Jc as renderToStaticSVG,eu as renderXYToStaticSVG,Kt as resolveTheme,Jt as themeStyles};
1
+ import{composeStyleRules as e,computeArcBoundingBox as t,darkenColor as o,lightenColor as n,makeNodeRuleContext as i,makeRuleValueResolver as r,makeXYRuleContext as s,resolveStyleRules as a,styleRulesToNodeStyle as l,styleRulesToXYStyle as c,sweepToAngles as u}from"./chunk-chunk-HBFA4NN6.module.min.js";import{PhysicsPipelineStore as d,absorbRegion as h,bodyGroupSpec as p,capacitatedRegion as g,collidersFromPlotBounds as m,collidersFromXScaleBins as f,countPairwiseCrossings as y,forceFieldRegion as b,groupCompletionRows as x,orderByBarycenter as v,orderExactSmall as w,packBandsBySilhouette as A,placeWithMinGap as S,portalRegion as k,pressureFieldRegion as M,processStageLayout as _,refineByAdjacentSwaps as P,routeSurfaceRegion as T}from"./chunk-chunk-FEPXDKJP.module.min.js";import"./chunk-chunk-SIRIJ3DY.module.min.js";import{AnnotationLabel as L,DEFAULT_COLOR as R,DEFAULT_LEGEND_ROW_HEIGHT as I,DEPTH_PALETTE_COLORS as C,PipelineStore as z,STREAMING_PALETTE as F,SafeRender as O,SemioticAnnotation as B,StreamXYFrame_default as N,TITLE_BASELINE as E,attachUpdateResultStore as j,buildBaseMetadataProps as $,buildCustomBehaviorProps as D,buildDatumIndexMap as W,buildRectNode as Y,buildResolveColor as V,buildRibbonGeometry as H,compactTimestampBufferForRemoval as G,composeLegendConfigs as X,computeDecayOpacity as q,computeEasing as U,computePulseIntensity as Q,computeRawProgress as Z,confidenceZScore as K,createColorScale as J,createCustomLayoutFailureDiagnostic as ee,createTimestampBufferForData as te,distinctCategories as oe,ensureRingBufferCapacity as ne,filterSparseArray as ie,fitLinearForForecast as re,forecastIntervalStats as se,geoSceneNodeToSVG as ae,getColor as le,getCrosshairProps as ce,getLayoutPlugin as ue,getSize as de,hasActivePulses as he,hasTextTitle as pe,isChartMode as ge,isGradientLegendConfig as me,isLegendConfig as fe,layoutVerticalLegendGroups as ye,lerp as be,networkLabelToSVG as xe,networkSceneEdgeToSVG as ve,networkSceneNodeToSVG as we,normalizeColorGradient as Ae,normalizeGradient as Se,normalizeSemanticGradient as ke,now as Me,ordinalSceneNodeToSVG as _e,pushWithTimestamp as Pe,renderAnnotationPass as Te,renderEmptyState as Le,renderLoadingState as Re,renderSceneListWithBackend as Ie,renderSceneWithBackend as Ce,reserveTitleMargin as ze,resolveAxisChromeGutter as Fe,resolveCategoricalPalette as Oe,resolveChartMode as Be,resolveCustomLayoutPalette as Ne,resolveDefaultFill as Ee,resolveDownwardHistogramExtent as je,resolveExplicitColor as $e,resolveGridDash as De,resolveLegendDistance as We,resolveLegendMetrics as Ye,resolveLegendSideGutter as Ve,resolveMobileInteraction as He,resolveSideLegendMargin as Ge,resolveSideLegendWidth as Xe,reverseGradient as qe,setPulseState as Ue,snapOrdinalIntroTargets as Qe,ticksForMode as Ze,toIdSet as Ke,useCategoryColors as Je,useChartLegendAndMargin as et,useChartMode as tt,useChartSelection as ot,useColorScale as nt,useLegendInteraction as it,useThemeCategorical as rt,warnCustomLayoutDiagnostics as st,xySceneNodeToSVG as at}from"./chunk-chunk-A3I4HBD5.module.min.js";import{useTheme as lt}from"./chunk-chunk-OZK46A5U.module.min.js";import{IncrementalExtent as ct,RingBuffer as ut,defaultTooltipStyle as dt,isHatchFill as ht,normalizeTooltip as pt,resolveSvgFill as gt}from"./chunk-chunk-6S3YGYW7.module.min.js";import{UpdateResultTracker as mt,annotationLayout as ft,getSequentialInterpolator as yt,interpolateBrBG as bt,interpolatePRGn as xt,interpolatePiYG as vt,interpolateRdBu as wt,interpolateRdYlBu as At,interpolateRdYlGn as St,interpolateSpectral as kt,interpolateViridis as Mt,makeSymbolResolver as _t,schemeCategory10 as Pt,useCustomLayoutSelection as Tt}from"./chunk-chunk-LSJUXBMF.module.min.js";import"./chunk-chunk-U66USBWU.module.min.js";import{filterAnnotationsByStatus as Lt}from"./chunk-chunk-5VVNW5AZ.module.min.js";import{accessorsEquivalent as Rt,resolveAccessor as It,resolveStringAccessor as Ct}from"./chunk-chunk-NWIGA3UK.module.min.js";import{getMax as zt,getMin as Ft,getMinMax as Ot}from"./chunk-chunk-JJ2OOIET.module.min.js";import"./chunk-chunk-IY7RYD4S.module.min.js";import"./chunk-chunk-J3QOW4OE.module.min.js";import{DARK_THEME as Bt,HIGH_CONTRAST_THEME as Nt,LIGHT_THEME as Et,THEME_PRESETS as jt,applyThemeAccessibility as $t,resolveThemeSemanticColors as Dt,useThemeSelector as Wt}from"./chunk-chunk-HADHLMY5.module.min.js";function Yt(e){if(null==e)return;if("number"==typeof e)return{top:e,right:e,bottom:e,left:e};const t={};return"number"==typeof e.top&&(t.top=e.top),"number"==typeof e.right&&(t.right=e.right),"number"==typeof e.bottom&&(t.bottom=e.bottom),"number"==typeof e.left&&(t.left=e.left),t}import*as Vt from"react-dom/server";import*as Ht from"react";function Gt(e){return void 0!==e.stroke||void 0!==e.strokeWidth||void 0!==e.opacity}function Xt(e,t){if(!Gt(t))return e??((...e)=>({}));const o={};return void 0!==t.stroke&&(o.stroke=t.stroke),void 0!==t.strokeWidth&&(o.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(o.opacity=t.opacity),e?(...t)=>({...e(...t)||{},...o}):(...e)=>({...o})}function qt(e,t,o){return"function"==typeof e?e(o):o[e||t]}function Ut(e){return e instanceof Date?e.getTime():Number(e)}function Qt(e,t){return Mt(1===t?.5:e/(t-1))}function Zt(e){const t={};return void 0!==e.stroke&&(t.stroke=e.stroke),void 0!==e.strokeWidth&&(t.strokeWidth=e.strokeWidth),void 0!==e.opacity&&(t.opacity=e.opacity),t}function Kt(e){if(!e)return Et;if("string"==typeof e){if("light"===e)return Et;if("dark"===e)return Bt;if("high-contrast"===e)return Nt;return jt[e]||Et}const t="dark"===e.mode?Bt:Et,o={...t,...e,colors:{...t.colors,...e.colors||{}},typography:{...t.typography,...e.typography||{}},tooltip:{...t.tooltip,...e.tooltip||{}}};return $t(o)}function Jt(e){return{background:e.colors.background,text:e.colors.text,textSecondary:e.colors.textSecondary,grid:e.colors.grid,border:e.colors.border,primary:e.colors.primary,fontFamily:e.typography.fontFamily,titleSize:e.typography.titleSize,labelSize:e.typography.labelSize,tickSize:e.typography.tickSize,categorical:e.colors.categorical,annotation:e.colors.annotation??e.colors.text,legendSize:e.typography.legendSize??e.typography.labelSize,titleFontSize:e.typography.titleFontSize??e.typography.titleSize,tickFontFamily:e.typography.tickFontFamily??e.typography.fontFamily}}var eo="__forecastSegment",to="__forecastOpacity";function oo(e,t,o,n){const i=t.uncertaintyOpacity,r=t.confidenceAccessor;if(!i&&!r)return;const s="object"==typeof i?i:{},a=s.min??.15,l=s.max??1;if(r){const t="function"==typeof r?r:e=>e[r];for(const o of e){const e=t(o);null!=e&&Number.isFinite(e)&&(o[to]=a+Math.max(0,Math.min(1,e))*(l-a))}return}const c=e.map(e=>{const t=o(e),i=n(e);return null!=t&&null!=i&&Number.isFinite(t)&&Number.isFinite(i)?Math.abs(t-i):NaN}),u=c.filter(e=>Number.isFinite(e));if(0===u.length)return;const[d,h]=Ot(u),p=h-d;e.forEach((e,t)=>{const o=c[t];Number.isFinite(o)&&(e[to]=l-(p>0?(o-d)/p:0)*(l-a))})}function no(e,t){return"function"==typeof t?t(e):!!e[t]}var io="__semiotic_resolvedX",ro="__semiotic_resolvedY",so="__compoundGroup";function ao(e,t,o){const n=e[t],i=e[o];return null==n||null==i||Number.isNaN(n)||Number.isNaN(i)}function lo(e){const t=e.xAccessor||"x",i=e.yAccessor||"y",r=e.lineBy,s=e.colorBy||r;let a=Array.isArray(e.data)?ie(e.data).filter(e=>!!e&&"object"==typeof e):[];const l=function(e,t,o){const n="function"==typeof t,i="function"==typeof o,r=n?io:t,s=i?ro:o;return n||i?{xKey:r,yKey:s,rows:e.map(e=>{const r={...e};return n&&(r[io]=t(e)),i&&(r[ro]=o(e)),r})}:{rows:e,xKey:r,yKey:s}}(a,t,i);a=l.rows;const c=l.xKey,u=l.yKey,d=Array.isArray(e.annotations)?[...e.annotations]:[];let h,p="string"==typeof r||"function"==typeof r?r:void 0,g=e.baseLineStyle;if(e.forecast){const t=function(e,t,o,n,i){return(r=n).isTraining||r.isForecast||r.isAnomaly||r.upperBounds||r.lowerBounds?function(e,t,o,n,i){const{isTraining:r,isForecast:s,isAnomaly:a,upperBounds:l,lowerBounds:c,color:u="#6366f1",bandOpacity:d=.15,anomalyColor:h="#ef4444",anomalyRadius:p=6,label:g}=n,m=e.map(e=>{let t="observed";return s&&no(e,s)?t="forecast":r&&no(e,r)&&(t="training"),{...e,[eo]:t}}),f=n._groupBy,y=[];if(f){const e=new Map;for(const t of m){const o=t[f]??"__default";e.has(o)||e.set(o,[]),e.get(o).push(t)}const t=[];for(const[,o]of e)for(let e=0;o.length-1>e;e++)o[e][eo]!==o[e+1][eo]&&(t.push({...o[e+1],[eo]:o[e][eo]}),t.push({...o[e],[eo]:o[e+1][eo]}));y.push(...m,...t)}else for(let e=0;m.length>e;e++)y.push(m[e]),m.length-1>e&&m[e][eo]!==m[e+1][eo]&&(y.push({...m[e+1],[eo]:m[e][eo]}),y.push({...m[e],[eo]:m[e+1][eo]}));if(n.trainUnderline){const e=[];for(const t of y)"training"===t[eo]&&e.push({...t,[eo]:"training-base"});y.unshift(...e)}const b=[];if(l&&c){const e="string"==typeof l?l:"__envUpper",t="string"==typeof c?c:"__envLower";if("function"==typeof l||"function"==typeof c)for(const o of y)"function"==typeof l&&(o[e]=l(o)),"function"==typeof c&&(o[t]=c(o));b.push({type:"envelope",upperAccessor:e,lowerAccessor:t,fill:u,fillOpacity:d,label:g})}if(n.uncertaintyOpacity||n.confidenceAccessor){const e=l?"function"==typeof l?l:e=>e[l]:()=>{},t=c?"function"==typeof c?c:e=>e[c]:()=>{};oo(y.filter(e=>"forecast"===e[eo]),n,e,t)}if(a){const e=n.anomalyStyle,t={type:"highlight",filter:e=>no(e,a)};e?(t.style=e,t.r=p):"function"==typeof h?(t.style=e=>{const t=h(e);return{stroke:t,strokeWidth:1.5,fill:t,fillOpacity:.7}},t.r=p):(t.color=h,t.r=p,t.style={stroke:h,strokeWidth:1.5,fill:h,fillOpacity:.7}),b.push(t)}return i&&b.push({type:"anomaly-band",threshold:i.threshold??2,showBand:!1!==i.showBand,fill:i.bandColor||"#6366f1",fillOpacity:i.bandOpacity??.1,anomalyColor:i.anomalyColor||"#ef4444",anomalyRadius:i.anomalyRadius??6,label:i.label}),{processedData:y,annotations:b}}(e,0,0,n,i):function(e,t,o,n,i){const{trainEnd:r,steps:s=10,confidence:a=.95,color:l="#6366f1",bandOpacity:c=.15,label:u}=n;if(null==r)return{processedData:e,annotations:[]};const d=[],h=[];for(const o of e)o[t]>r?h.push({...o,[eo]:"observed"}):d.push({...o,[eo]:"training"});const p=d.map(e=>[e[t],e[o]]).filter(e=>null!=e[0]&&null!=e[1]&&isFinite(e[0])&&isFinite(e[1])).sort((e,t)=>e[0]-t[0]),g=[],m=[];if(p.length>=3){const i=p.length,r=re(p);if(r){const{se:d,meanX:h,ssX:f}=se(p,r),y=K(a),b=e.map(e=>e[t]).filter(e=>null!=e&&isFinite(e)),x=zt(b),v=p.length>1?(p[i-1][0]-p[0][0])/(i-1):1;for(let e=1;s>=e;e++){const n=x+e*v,s=r(n),a=d*Math.sqrt(1+1/i+(f>0?(n-h)**2/f:0))*y;m.push({[t]:n,[o]:s,[eo]:"forecast",__forecastUpper:s+a,__forecastLower:s-a})}oo(m,n,e=>e.__forecastUpper,e=>e.__forecastLower),g.push({type:"envelope",upperAccessor:"__forecastUpper",lowerAccessor:"__forecastLower",fill:l,fillOpacity:c,label:u})}}g.push({type:"x-threshold",x:r,color:"#94a3b8",strokeWidth:1,strokeDasharray:"4,2",label:"Train / Forecast"}),i&&g.push({type:"anomaly-band",threshold:i.threshold??2,showBand:!1!==i.showBand,fill:i.bandColor||"#6366f1",fillOpacity:i.bandOpacity??.1,anomalyColor:i.anomalyColor||"#ef4444",anomalyRadius:i.anomalyRadius??6,label:i.label});const f=[];if(f.push(...d),d.length>0&&h.length>0&&f.push({...d[d.length-1],[eo]:"observed"}),f.push(...h),m.length>0){const e=h.length>0?h[h.length-1]:d[d.length-1];e&&f.push({...e,[eo]:"forecast"}),f.push(...m)}return{processedData:f,annotations:g}}(e,t,o,n,i);var r}(a,c,u,r&&"string"==typeof r&&"object"==typeof e.forecast?{...e.forecast,_groupBy:r}:e.forecast,e.anomaly);if(a=t.processedData,d.push(...t.annotations),h=function(e,t,o){const n=o.upperBounds,i=o.lowerBounds;if(!n&&!i)return;const r="function"==typeof n?n:"string"==typeof n?e=>e[n]:null,s="function"==typeof i?i:"string"==typeof i?e=>e[i]:null;let a=1/0,l=-1/0;for(const o of e){const e=Number(o[t]);if(Number.isFinite(e)&&(a>e&&(a=e),e>l&&(l=e)),r){const e=r(o);null!=e&&Number.isFinite(e)&&(e>l&&(l=e),a>e&&(a=e))}if(s){const e=s(o);null!=e&&Number.isFinite(e)&&(a>e&&(a=e),e>l&&(l=e))}}return Number.isFinite(a)&&Number.isFinite(l)?[a,l]:void 0}(a,u,e.forecast),r&&"string"==typeof r?(a=a.map(e=>({...e,[so]:`${e[r]}__${e[eo]||"observed"}`})),p=so):p=eo,e.baseLineStyle){const t=function(t,i){const r=i.trainDasharray??"8,4",s=i.forecastDasharray??"4,4",a=i.color||"#6366f1",l=i.trainOpacity,c=i.forecastOpacity,u=i.trainStroke,d=i.trainLinecap,h=i.trainUnderline;return t=>{const i=(t=>e.baseLineStyle(t))(t),p=t[eo];if("training"===p){let e=i.stroke;return"darken"===u?e=o(i.stroke||"#666",.5):u&&(e=u),{...i,stroke:e,strokeDasharray:r,...d&&{strokeLinecap:d},...null!=l&&{strokeOpacity:l}}}if("training-base"===p){let e=i.stroke||"#666";return"lighten"===h&&(e=n(e,.4)),{...i,stroke:e,strokeDasharray:void 0}}if("forecast"===p){const e=t[to],o=null!=e?e:c;return{...i,stroke:a,strokeDasharray:s,...null!=o&&{strokeOpacity:o}}}return i}}(0,e.forecast);g=e=>t(e)}}else e.anomaly&&d.push(...(m=e.anomaly,[{type:"anomaly-band",threshold:m.threshold??2,showBand:!1!==m.showBand,fill:m.bandColor||"#6366f1",fillOpacity:m.bandOpacity??.1,anomalyColor:m.anomalyColor||"#ef4444",anomalyRadius:m.anomalyRadius??6,label:m.label}]));var m;if(e.gapStrategy){if("function"==typeof p){const e=p;a=a.map(t=>({...t,__semiotic_gapGroup:e(t)})),p="__semiotic_gapGroup"}const t=function(e,t,o,n,i){const r=new Map;for(const t of e){const e=i?(t[i]??"")+"":"__single";r.has(e)||r.set(e,[]),r.get(e).push(t)}if("interpolate"===t){const e=[];for(const[,t]of r)for(const i of t)ao(i,o,n)||e.push(i);return{rows:e,groupKey:i}}if("zero"===t){const e=[];for(const[,t]of r)for(const i of t)ao(i,o,n)?e.push({...i,[n]:0}):e.push(i);return{rows:e,groupKey:i}}const s=[],a="_gapSegment";for(const[e,t]of r){let i=0,r=[];const l=()=>{if(0===r.length)return;const t="__single"===e?"__seg"+i:`${e}__seg${i}`;for(const e of r)s.push({...e,[a]:t});r=[],i++};for(const e of t)ao(e,o,n)?l():r.push(e);l()}return{rows:s,groupKey:a}}(a,e.gapStrategy,c,u,"string"==typeof p?p:void 0);a=t.rows,t.groupKey&&(p=t.groupKey)}let f;if(e.directLabel){const t=function(e,t,o,n,i,r,s,a){if(!t||!o)return{annotations:[]};const l="object"==typeof t?t:{},c=l.position||"end",u=l.fontSize||11,d="function"==typeof o?o:e=>e[o],h=new Map;for(const t of e){const e=d(t);if(null==e)continue;const o=e+"";""!==o&&(h.has(o)||h.set(o,[]),h.get(o).push(t))}const p=new Map;for(const[e,t]of h)t.sort((e,t)=>Number(e[n])-Number(t[n])),p.set(e,"end"===c?t[t.length-1]:t[0]);const g=J(Array.from(p.entries()).map(([e])=>({__lbl:e})),"__lbl",r??s),m=Array.from(p.entries()).map(([e,t])=>({type:"text",label:e,[n]:t[n],[i]:t[i],dx:"end"===c?6:-6,dy:0,color:g?le({__lbl:e},"__lbl",g):a||R,fontSize:u}));m.sort((e,t)=>Number(e[i])-Number(t[i]));for(let e=1;m.length>e;e++){const t=m[e-1],o=m[e],n=Number(t[i])+t.dy;u+2>Math.abs(Number(o[i])+o.dy-n)&&(o.dy+=u+2)}const f=m.reduce((e,t)=>Math.max(e,(t.label+"").length*(.6*u)),0)+10;return{annotations:m,marginExtra:"end"===c?{right:f}:{left:f}}}(a,e.directLabel,"string"==typeof s||"function"==typeof s?s:void 0,c,u,e.colorScheme,e.themeCategorical,e.color);d.push(...t.annotations),f=t.marginExtra}return{data:a,xAccessor:"function"==typeof t?c:t,yAccessor:"function"==typeof i?u:i,groupAccessor:p,colorAccessor:s,annotations:d,lineStyle:g,yExtent:h,marginExtra:f}}import{forwardRef as co,useCallback as uo,useMemo as ho}from"react";import{forwardRef as po,useMemo as go}from"react";import{useMemo as mo,useRef as fo}from"react";import{useCallback as yo,useMemo as bo,useState as xo}from"react";import{useMemo as vo}from"react";import{useImperativeHandle as wo,useRef as Ao}from"react";function So(e){const t=fo(null);return function(e,t){const{variant:o,frameRef:n,overrides:i}=t,r=Ao(i);r.current=i,wo(e,()=>{const e=function(e,t){if("xy"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>e.current?.remove(t)??[],update:(t,o)=>e.current?.update(t,o)??[],replace:t=>e.current?.replace?.(t),clear:()=>e.current?.clear(),getData:()=>e.current?.getData()??[],getScales:()=>e.current?.getScales()??null,getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}if("network"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>{const o=Array.isArray(t)?t:[t],n=e.current?.getTopology()?.nodes??[],i=[];for(const t of o){const o=n.find(e=>e.id===t);o&&i.push({...o.data??{},id:t}),e.current?.removeNode(t)}return i},update:(t,o)=>(Array.isArray(t)?t:[t]).flatMap(t=>{const n=e.current?.updateNode(t,o);return n?[{...n,id:t}]:[]}),clear:()=>e.current?.clear(),getData:()=>e.current?.getTopology()?.nodes?.map(e=>e.data)??[],getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}if("geo-points"===e){const e=t;return{push:t=>e.current?.push(t),pushMany:t=>e.current?.pushMany(t),remove:t=>e.current?.removePoint(t)??[],update:(t,o)=>{const n=e.current?.removePoint(t)??[];for(const t of n)e.current?.push(o(t));return n},clear:()=>e.current?.clear(),getData:()=>e.current?.getData()??[],getCustomLayout:()=>e.current?.getCustomLayout?.()??null,getLayoutFailure:()=>e.current?.getLayoutFailure?.()??null}}const o=t;return{push:e=>o.current?.pushLine(e),pushMany:e=>o.current?.pushManyLines(e),remove:e=>o.current?.removeLine(e)??[],update:(e,t)=>{const n=o.current?.removeLine(e)??[];for(const e of n)o.current?.pushLine(t(e));return n},clear:()=>o.current?.clear(),getData:()=>o.current?.getLines()??[],getCustomLayout:()=>o.current?.getCustomLayout?.()??null,getLayoutFailure:()=>o.current?.getLayoutFailure?.()??null}}(o,n);return new Proxy(e,{get(e,t,o){if("string"==typeof t){const e=r.current?.[t];if("function"==typeof e)return e}return Reflect.get(e,t,o)},has:(e,t)=>!("string"!=typeof t||!r.current||!(t in r.current))||Reflect.has(e,t)})},[])}(e.imperativeRef,{variant:e.imperativeVariant,frameRef:t}),{frameRef:t,resolved:tt(e.mode,{width:e.width,height:e.height,showGrid:e.showGrid,enableHover:e.enableHover,showLegend:e.showLegend,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,xLabel:e.xLabel,yLabel:e.yLabel,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules}),normalizedMargin:mo(()=>Yt(e.margin),[e.margin])}}import{jsx as ko}from"react/jsx-runtime";var Mo=po(function(e,t){const{data:o,layout:n,layoutConfig:i,onLayoutError:r,xExtent:s,yExtent:a,showAxes:l=!1,margin:c,className:u,annotations:d,onObservation:h,onClick:p,selection:g,linkedHover:m,hoverHighlight:f,chartId:y,loading:b,loadingContent:x,emptyContent:v,colorBy:w,colorScheme:A,legend:S,legendInteraction:k,legendPosition:M,frameProps:_={}}=e,{legend:P,...T}=_,L=go(()=>X(P,S),[P,S]),{frameRef:R,resolved:I,safeData:C,setup:z,earlyReturn:B}=function(e){const t=So(e),{resolved:o,normalizedMargin:n}=t,i=function(e){const{data:t,rawData:o,colorBy:n,colorScheme:i,legendInteraction:r,legendPosition:s,selection:a,linkedHover:l,fallbackFields:c,unwrapData:u=!1,onObservation:d,chartType:h,chartId:p,showLegend:g,legend:m,legendLayout:f,userMargin:y,marginDefaults:b,onClick:x,hoverHighlight:v,mobileInteraction:w,mobileSemantics:A,loading:S,loadingContent:k,emptyContent:M,width:_,height:P,hasTitle:T,axisChrome:L}=e,R=void 0===o,I=bo(()=>ie(t),[t]),[C,z]=xo([]),O=yo(e=>{z(t=>t.length===e.length&&t.every((t,o)=>t===e[o])?t:e)},[]),B="string"==typeof n?n:void 0,N=bo(()=>He(w,{width:_,mobileSemantics:A}),[w,_,A]),{activeSelectionHook:E,hoverSelectionHook:j,customHoverBehavior:$,customClickBehavior:D,crosshairSourceId:W}=ot({selection:a,linkedHover:l,fallbackFields:c,unwrapData:u,onObservation:d,chartType:h,chartId:p,onClick:x,hoverHighlight:v,colorByField:B,mobileInteraction:N}),Y=ce(l,W),V=nt(I,n,i),H=bo(()=>oe(I,n),[I,n]),G=bo(()=>R&&C.length>0?C:H,[R,C,H]),X=it(r,n,G),q=bo(()=>j||(X.legendSelectionHook?X.legendSelectionHook:E),[j,X.legendSelectionHook,E]),U=function(e){const t=Wt(e=>e.theme.colors.selectionOpacity);return vo(()=>{if(void 0!==e||void 0!==t)return{name:e?.name??"",...e,unselectedOpacity:e?.unselectedOpacity??t}},[e,t])}(a),Q=rt(),Z=Je(),K=bo(()=>{if(V)return V;if(!n||0===G.length)return;const e=Array.isArray(i)&&i.length>0||"string"==typeof i&&i.length>0?i:Q&&Q.length>0?Q:F,t="__streamCat",o=G.map(e=>({[t]:e})),r=J(o,t,e);return e=>Z?.[e]||r(e)||"#999"},[V,n,G,i,Q,Z]),{legend:ee,margin:te,legendPosition:ne}=et({data:I,colorBy:n,colorScale:K,showLegend:g,legendPosition:s,userMargin:y,defaults:b,categories:G,additionalLegend:m,chartWidth:_,legendLayout:f,hasTitle:T,axisChrome:L}),re=bo(()=>{const e={};return ee&&(e.legend=ee,e.legendPosition=ne,f&&(e.legendLayout=f)),r&&"none"!==r&&(e.legendHoverBehavior=X.onLegendHover,e.legendClickBehavior=X.onLegendClick,e.legendHighlightedCategory=X.highlightedCategory,e.legendIsolatedCategories=X.isolatedCategories),R&&n&&(e.legendCategoryAccessor=n,e.onCategoriesChange=O),e},[ee,ne,f,r,X.onLegendHover,X.onLegendClick,X.highlightedCategory,X.isolatedCategories,R,n,O]),se=Array.isArray(o)?ie(o):o,ae=Re(S,_,P,k),le=ae?null:Le(se,_,P,M);return{data:I,colorScale:V,allCategories:G,legendState:X,effectiveSelectionHook:q,activeSelectionHook:E,customHoverBehavior:$,customClickBehavior:D,mobileInteraction:N,legend:ee,margin:te,legendPosition:ne,earlyReturn:ae||le||null,legendBehaviorProps:re,crosshairProps:Y,resolvedSelection:U}}({data:e.data??[],rawData:e.data,colorBy:e.colorBy,colorScheme:e.colorScheme,legendInteraction:e.legendInteraction,legendPosition:e.legendPosition,selection:e.selection,linkedHover:e.linkedHover,hoverHighlight:e.hoverHighlight,fallbackFields:"string"==typeof e.colorBy?[e.colorBy]:[],unwrapData:e.unwrapData,onObservation:e.onObservation,onClick:e.onClick,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,chartType:e.chartTypeLabel,chartId:e.chartId,showLegend:o.showLegend,legend:e.legend,userMargin:n,marginDefaults:o.marginDefaults,loading:e.loading,loadingContent:e.loadingContent,emptyContent:e.emptyContent,width:o.width,height:o.height});return{...t,safeData:i.data,setup:i,earlyReturn:i.earlyReturn}}({imperativeRef:t,imperativeVariant:"xy",chartTypeLabel:"XYCustomChart",unwrapData:!1,data:o,colorBy:w,colorScheme:A,legend:L,legendInteraction:k,legendPosition:M,selection:g,linkedHover:m,hoverHighlight:f,onObservation:h,onClick:p,chartId:y,loading:b,loadingContent:x,emptyContent:v,margin:c,width:e.width,height:e.height,showGrid:e.showGrid,enableHover:e.enableHover,showLegend:e.showLegend,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mode:e.mode,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules,xLabel:e.xLabel,yLabel:e.yLabel}),E=z.effectiveSelectionHook,j=go(()=>E?.isActive?{isActive:!0,predicate:E.predicate}:null,[E?.isActive,E?.predicate]);if(B)return B;const{width:W,height:Y,enableHover:V,showGrid:H,title:G,description:q,summary:U,accessibleTable:Q,xLabel:Z,yLabel:K}=I,ee={chartType:"custom",...null!=o&&{data:C},customLayout:n,layoutConfig:i,onLayoutError:r,...j&&{layoutSelection:j},xExtent:s,yExtent:a,colorAccessor:w,colorScheme:A,size:[W,Y],responsiveWidth:e.responsiveWidth,responsiveHeight:e.responsiveHeight,margin:z.margin,showAxes:l,xLabel:Z,yLabel:K,enableHover:V,showGrid:H,...z.legendBehaviorProps,...$({title:G,description:q,summary:U,accessibleTable:Q,className:u,animate:e.animate,maxDevicePixelRatio:e.maxDevicePixelRatio,axisExtent:e.axisExtent,autoPlaceAnnotations:e.autoPlaceAnnotations}),...null!=e.tooltip&&{tooltipContent:e.tooltip},...D({linkedHover:m,selection:g,onObservation:h,onClick:p,hoverRadius:e.hoverRadius,hoverHighlight:f,mobileInteraction:z.mobileInteraction,customHoverBehavior:z.customHoverBehavior,customClickBehavior:z.customClickBehavior}),...d&&d.length>0&&{annotations:d},...z.crosshairProps,...T};return ko(O,{componentName:"XYCustomChart",width:W,height:Y,children:ko(N,{ref:R,...ee})})});function _o(e,t,o,n,i){const r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*o+i*i*i*n}function Po(e,t,o,n,i){const r=1-i;return 3*r*r*(t-e)+6*r*i*(o-t)+3*i*i*(n-o)}function To(e,t,o,n,i){const r=[],s=(e.x+t.x)/2;for(let a=0;i>=a;a++){const l=a/i;let c,u,d,h;"linear"===n?(c=e.x+(t.x-e.x)*l,u=e.y+(t.y-e.y)*l,d=t.x-e.x,h=t.y-e.y):(c=_o(e.x,s,s,t.x,l),u=_o(e.y,e.y,t.y,t.y,l),d=Po(e.x,s,s,t.x,l),h=Po(e.y,e.y,t.y,t.y,l)),r.push({x:c,y:u,dx:d,dy:h,radius:e.radius+(t.radius-e.radius)*l,datumIndex:.5>l?o:o+1})}return r}function Lo(e,t={}){const o=[],n=[],i=[];if(2>e.length)return{topPath:o,bottomPath:n,datumIndices:i};const r=t.curve??"smooth",s=Math.max(2,Math.floor(t.samplesPerSegment??12));for(let t=0;e.length-1>t;t++){const a=To(e[t],e[t+1],t,r,s);for(let e=0===t?0:1;a.length>e;e++){const t=a[e],r=Math.hypot(t.dx,t.dy)||1,s=-t.dy/r,l=t.dx/r,c=Math.max(0,t.radius);o.push([t.x+s*c,t.y+l*c]),n.push([t.x-s*c,t.y-l*c]),i.push(t.datumIndex)}}return{topPath:o,bottomPath:n,datumIndices:i}}Mo.displayName="XYCustomChart";import{jsx as Ro,jsxs as Io}from"react/jsx-runtime";function Co(e,t,o){return"function"==typeof e?e(t,o):t[e]}function zo(e){return e instanceof Date?"date:"+e.getTime():`${typeof e}:${e+""}`}function Fo(e,t){if(!e?.length)return;const o=new Map(t.map((e,t)=>[zo(e),t]));return e.map(e=>{const t={...e},n=n=>{if(!(n in e))return;const i=o.get(zo(e[n]));void 0!==i&&(t[n]=i)};return n("x"),n("x0"),n("x1"),"string"!=typeof e.type||"x-threshold"!==e.type&&"x"!==e.type||n("value"),t})}function Oo(e){const{seriesOrder:t,overallOrder:o,highlightTop:n,color:i,colorScheme:r,neutralColor:s,themeCategorical:a,themeNeutral:l}=e;if(null==n&&null==i)return r;const c=new Set(o.slice(0,null==n?o.length:Math.max(0,Math.floor(n)))),u=new Map,d={};for(const e of t)d[e]=i??(c.has(e)?Ee(void 0,a,r,e,u):s??l??"#b8bec8");return d}function Bo(e,t={}){const o=t.xAccessor??"x",n=t.yAccessor??"y",i=t.lineBy??"series",r=t.rankDirection??"descending",s=[],a=new Map,l=new Map,c=[],u=new Map;let d=1/0,h=-1/0;e.forEach((e,t)=>{const r=Co(o,e,t),p=zo(r);let g=a.get(p);null==g&&(g=s.length,a.set(p,g),s.push(r),l.set(g,[]));const m=Co(i,e,t)+"";u.has(m)||(u.set(m,c.length),c.push(m));const f=Number(Co(n,e,t));Number.isFinite(f)&&(d=Math.min(d,f),h=Math.max(h,f),l.get(g)?.push({datum:e,inputIndex:t,series:m,value:f}))});const p=[],g=new Map,m=new Map;for(let e=0;s.length>e;e++){const t=l.get(e)??[];t.sort((e,t)=>("descending"===r?t.value-e.value:e.value-t.value)||(u.get(e.series)??0)-(u.get(t.series)??0)),t.forEach((t,o)=>{const n=o+1;p.push({datum:t.datum,xIndex:e,xValue:s[e],series:t.series,value:t.value,rank:n}),g.set(t.series,(g.get(t.series)??0)+n),m.set(t.series,(m.get(t.series)??0)+1)})}const f=c.length+1,y=[...c].sort((e,t)=>{const o=m.get(e)??0,n=m.get(t)??0;return((g.get(e)??0)+(s.length-o)*f)/Math.max(1,s.length)-((g.get(t)??0)+(s.length-n)*f)/Math.max(1,s.length)||(u.get(e)??0)-(u.get(t)??0)}),b=new Set(y.slice(0,null==t.highlightTop?y.length:Math.max(0,Math.floor(t.highlightTop))));return{data:p.map(e=>{const t=b.has(e.series);return{...e.datum,x:e.xIndex,y:e.rank,__bumpRaw:e.datum,__bumpSeries:e.series,__bumpColorGroup:t?e.series:"Other",__bumpValue:e.value,__bumpRank:e.rank,__bumpXValue:e.xValue,__bumpHighlighted:t}}),xValues:s,seriesOrder:c,overallOrder:y,valueExtent:d===1/0?[0,0]:[d,h]}}function No({datum:e,x:t,y:o,side:n,color:i,highlighted:r,labelStyle:s}){const a=Tt(),l=a.isActive&&!a.predicate(e),c="function"==typeof s?s(e.__bumpRaw):s;return Ro("text",{className:"semiotic-bump-label",x:t+("end"===n?8:-8),y:o,dy:"0.35em",textAnchor:"end"===n?"start":"end",fill:i,fillOpacity:l?.16:1,fontWeight:r?650:450,fontSize:12,style:{pointerEvents:"none",fontFamily:"var(--semiotic-font-family, sans-serif)",fontSize:"var(--semiotic-axis-label-font-size, 12px)",...c},children:e.__bumpSeries})}function Eo(e,t,o){const[n,i]=t,[r,s]=o;return i===n?(r+s)/2:r+(s-r)*Math.max(0,Math.min(1,(e-n)/(i-n)))}function jo(e){const t=e instanceof Date?e.getTime():Number(e);return Number.isFinite(t)?t:void 0}function $o(e){return{value:e.__bumpValue,x:jo(e.__bumpXValue),y:e.__bumpValue,category:e.__bumpSeries}}function Do(e){const t=e.config,o=new Map;for(const t of e.data){const e=o.get(t.__bumpSeries)??[];e.push(t),o.set(t.__bumpSeries,e)}const n=t.seriesOrder.filter(e=>o.has(e)).sort((e,n)=>(o.get(e)?.[0]?.__bumpHighlighted?1:0)-(o.get(n)?.[0]?.__bumpHighlighted?1:0)||t.seriesOrder.indexOf(e)-t.seriesOrder.indexOf(n)),i=[],r=[];for(const s of n){const n=(o.get(s)??[]).sort((e,t)=>e.x-t.x);if(2>n.length)continue;const l=n[0].__bumpHighlighted,c=e.resolveColor(n[0].__bumpSeries,n[0]),u=t.color??(l?c:t.neutralColor??e.theme.semantic.textSecondary??e.theme.semantic.border??c),d=n.map(o=>({x:e.scales.x(o.x),y:e.scales.y(o.y),radius:t.ribbon?Eo(o.__bumpValue,t.valueExtent,t.ribbonSizeRange)/2:Math.max(.5,t.lineWidth/2)})),h=Lo(d,{curve:t.curve,samplesPerSegment:t.samplesPerSegment}),p=h.datumIndices.map(e=>n[e]),g={fill:u,fillOpacity:1,opacity:l?t.ribbon?t.ribbonOpacity:t.lineOpacity:Math.min(t.ribbon?t.ribbonOpacity:t.lineOpacity,.58)};t.styleRules?.length&&Object.assign(g,a(n[0].__bumpRaw,t.styleRules,$o(n[0]))),t.areaStyle&&Object.assign(g,t.areaStyle(n[0].__bumpRaw)??{}),void 0!==t.stroke&&(g.stroke=t.stroke),void 0!==t.strokeWidth&&(g.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(g.opacity=t.opacity),i.push({type:"area",topPath:h.topPath,bottomPath:h.bottomPath,style:g,datum:p,accessibleDatum:n.map(e=>e.__bumpRaw),accessibility:{label:s+" ranking trajectory",tableFields:n.map(e=>e.__bumpRaw)},group:s,interactive:!0}),t.showPoints&&n.forEach((e,o)=>{const n={fill:u,stroke:"none",opacity:l?1:.75};t.styleRules?.length&&Object.assign(n,a(e.__bumpRaw,t.styleRules,$o(e))),t.pointStyle&&Object.assign(n,t.pointStyle(e.__bumpRaw)??{}),void 0!==t.stroke&&(n.stroke=t.stroke),void 0!==t.strokeWidth&&(n.strokeWidth=t.strokeWidth),void 0!==t.opacity&&(n.opacity=t.opacity),i.push({type:"point",x:d[o].x,y:d[o].y,r:n.r??t.pointRadius,style:n,datum:e,accessibleDatum:e.__bumpRaw,accessibility:{label:`${s}, rank ${e.__bumpRank}, value ${e.__bumpValue}`},pointId:`${s}:${e.x}`})});const m=!0===t.showLabels?"end":t.showLabels,f=(e,o,n)=>{r.push(Ro(No,{datum:e,x:d[o].x,y:d[o].y,side:n,color:"string"==typeof g.fill?g.fill:u,highlighted:l,labelStyle:t.labelStyle},`${s}-${n}`))};"start"!==m&&"both"!==m||f(n[0],0,"start"),"end"!==m&&"both"!==m||f(n.at(-1),n.length-1,"end")}return{nodes:i,overlays:r.length?Ro("g",{className:"semiotic-bump-labels",children:r}):void 0,restyle:(e,t)=>{const o=function(e){const t=Array.isArray(e.datum)?e.datum[0]:e.datum;return t&&"object"==typeof t&&"__bumpSeries"in t?t:void 0}(e);if(t?.isActive&&o&&!t.predicate(o))return{opacity:.14}}}}function Wo(e,t,o,n,i){const s=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrAreaColorBy",d="function"==typeof t?s.map(e=>({...e,__ssrAreaColorBy:t(e)})):s,h=t?J(d,u,c):void 0,p=!1!==i.showLine,g="number"==typeof i.lineWidth?i.lineWidth:2,m="number"==typeof i.areaOpacity?i.areaOpacity:.7,f=r(i.yAccessor),y=i.styleRules;return(e,o)=>{const n=t&&h?le(e,t,h):"string"==typeof i.color?i.color:R,r={fill:n,fillOpacity:m,stroke:p?n:"none",...p&&{strokeWidth:g}};return y?.length&&Object.assign(r,a(e,y,{value:f(e),category:o})),void 0!==i.stroke&&(r.stroke=i.stroke),void 0!==i.strokeWidth&&(r.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(r.opacity=i.opacity),r}}function Yo(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=Kt(n.theme).colors.categorical,a=o??n.colorScheme??s,l="string"==typeof t?t:"__ssrBubbleColorBy",c="function"==typeof t?r.map(e=>({...e,__ssrBubbleColorBy:t(e)})):r,u=t?J(c,l,a):void 0,d=i.sizeBy,h=Array.isArray(i.sizeRange)?i.sizeRange:[5,40],p=d?r.map(e=>"function"==typeof d?d(e):Number(e[d])).filter(Number.isFinite):[],g=p.length?Ot(p):void 0;return e=>({fill:t&&u?le(e,t,u):"string"==typeof i.color?i.color:R,fillOpacity:"number"==typeof i.bubbleOpacity?i.bubbleOpacity:.6,r:d?de(e,d,h,g):h[0],stroke:i.stroke??i.bubbleStrokeColor??"white",strokeWidth:i.strokeWidth??i.bubbleStrokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}})}function Vo(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrScatterColorBy",d="function"==typeof t?r.map(e=>({...e,__ssrScatterColorBy:t(e)})):r,h=t?J(d,u,c):void 0,p=i.sizeBy,g=Array.isArray(i.sizeRange)?i.sizeRange:[3,15],m=p?r.map(e=>"function"==typeof p?p(e):Number(e[p])).filter(Number.isFinite):[],f=m.length?Ot(m):void 0,y=s(i.xAccessor,i.yAccessor),b=i.styleRules;return e=>{const o={fill:t&&h?le(e,t,h):"string"==typeof i.color?i.color:R,fillOpacity:"number"==typeof i.pointOpacity?i.pointOpacity:.8,r:p?de(e,p,g,f):"number"==typeof i.pointRadius?i.pointRadius:5};return b?.length&&Object.assign(o,a(e,b,y(e))),void 0!==i.stroke&&(o.stroke=i.stroke),void 0!==i.strokeWidth&&(o.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(o.opacity=i.opacity),o}}co(function(e,t){const o=rt(),n=lt(),{data:i,xAccessor:r,yAccessor:s,lineBy:a,rankDirection:l="descending",ribbon:c=!1,curve:u="smooth",ribbonSizeRange:d=[4,28],samplesPerSegment:h=12,lineWidth:p=3,highlightTop:g,neutralColor:m,styleRules:f,labelStyle:y,colorScheme:b,ribbonOpacity:x=.82,lineOpacity:v=.9,showPoints:w=!1,pointRadius:A=3,showLabels:S=!0,showAxes:k=!0,showGrid:M=!0,showLegend:_=!1,enableHover:P=!0,hoverHighlight:T=!0,tooltip:L,frameProps:R={},xFormat:I,yFormat:C,onClick:z}=e,F=ho(()=>Bo(i,{xAccessor:r,yAccessor:s,lineBy:a,rankDirection:l,highlightTop:g}),[i,r,s,a,l,g]),{axes:O,areaStyle:B,pointStyle:N,...E}=R,j=ho(()=>Oo({seriesOrder:F.seriesOrder,overallOrder:F.overallOrder,highlightTop:g,color:e.color,colorScheme:b,neutralColor:m,themeCategorical:o,themeNeutral:n.colors.textSecondary}),[F.seriesOrder,F.overallOrder,g,e.color,b,m,o,n.colors.textSecondary]),$=ho(()=>({ribbon:c,curve:u,samplesPerSegment:h,ribbonSizeRange:d,valueExtent:F.valueExtent,seriesOrder:F.seriesOrder,lineWidth:p,ribbonOpacity:x,lineOpacity:v,neutralColor:m,color:e.color,stroke:e.stroke,strokeWidth:e.strokeWidth,opacity:e.opacity,styleRules:f,areaStyle:B,pointStyle:N,labelStyle:y,showPoints:w,pointRadius:A,showLabels:S}),[c,u,h,d,F.valueExtent,F.seriesOrder,p,x,v,m,e.color,e.stroke,e.strokeWidth,e.opacity,f,B,N,y,w,A,S]),D=uo((e,t)=>{if(0===F.xValues.length)return"";const o=F.xValues[Math.max(0,Math.min(F.xValues.length-1,Math.round(Number(e))))];return I?I(o,t):(o instanceof Date?o.toLocaleDateString():o)+""},[F.xValues,I]),W=uo(e=>C?C(e):e.toLocaleString(),[C]),Y=ho(()=>"multi"===L?void 0:pt(L),[L]),V=uo(e=>{const t=e?.data??e;return t?!1===L?null:Y?Y({...e,data:t.__bumpRaw,__semioticHoverData:!0}):Io("div",{className:"semiotic-tooltip",style:dt,children:[Ro("div",{style:{fontWeight:700},children:t.__bumpSeries}),Io("div",{children:[D(t.x)," · Rank ",t.__bumpRank]}),Io("div",{children:["Value: ",W(t.__bumpValue)]})]}):null},[W,D,Y,L]),H=ho(()=>{if(z)return(e,t)=>{z(e.__bumpRaw??e,t)}},[z]),G=Math.max(1,F.seriesOrder.length),X=F.xValues.map((e,t)=>t),q=Array.from({length:G},(e,t)=>t+1),U=O??[{orient:"left",tickValues:q,tickFormat:e=>e+"",label:e.yLabel??"Rank",baseline:!1},{orient:"bottom",tickValues:X,tickFormat:D,label:e.xLabel,tickAnchor:"edges"}],Q=ho(()=>Fo(e.annotations,F.xValues),[e.annotations,F.xValues]);return Ro(Mo,{ref:t,data:F.data,layout:Do,layoutConfig:$,xExtent:[0,Math.max(1,F.xValues.length-1)],yExtent:[G+.5,.5],showAxes:k,showGrid:M,showLegend:_,enableHover:P,hoverHighlight:T,colorBy:"__bumpSeries",colorScheme:j,tooltip:V,onClick:H,hoverRadius:e.hoverRadius,width:e.width,height:e.height,responsiveWidth:e.responsiveWidth,responsiveHeight:e.responsiveHeight,responsiveRules:e.responsiveRules,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,mode:e.mode,margin:e.margin??{top:20,right:S?110:24,bottom:48,left:48},className:e.className,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,selection:e.selection,linkedHover:e.linkedHover,legend:e.legend,legendInteraction:e.legendInteraction,legendPosition:e.legendPosition,onObservation:e.onObservation,chartId:e.chartId,loading:e.loading,loadingContent:e.loadingContent,emptyContent:e.emptyContent,animate:e.animate,autoPlaceAnnotations:e.autoPlaceAnnotations,annotations:Q,xLabel:e.xLabel,yLabel:e.yLabel??"Rank",frameProps:{axes:U,axisExtent:"exact",...E}})}).displayName="BumpChart";var Ho={frameType:"xy",buildProps:(e,t,o,n,i)=>({chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,sizeRange:i.sizeRange||[5,40],colorScheme:o,...n,pointStyle:n.pointStyle||Yo(e,t,o,n,i),showLegend:n.showLegend??!!t})},Go={frameType:"xy",layout:{margin:e=>({top:20,right:!1===e.showLabels?24:110,bottom:48,left:48})},buildProps:(e,t,o,n,i)=>{const r=Bo(Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],{xAccessor:i.xAccessor,yAccessor:i.yAccessor,lineBy:i.lineBy,rankDirection:i.rankDirection,highlightTop:"number"==typeof i.highlightTop?i.highlightTop:void 0}),s=Math.max(1,r.seriesOrder.length),a=Kt(n.theme),l=Oo({seriesOrder:r.seriesOrder,overallOrder:r.overallOrder,highlightTop:"number"==typeof i.highlightTop?i.highlightTop:void 0,color:"string"==typeof i.color?i.color:void 0,colorScheme:o,neutralColor:"string"==typeof i.neutralColor?i.neutralColor:void 0,themeCategorical:a.colors.categorical,themeNeutral:a.colors.textSecondary}),c={ribbon:!0===i.ribbon,curve:"linear"===i.curve?"linear":"smooth",samplesPerSegment:"number"==typeof i.samplesPerSegment?i.samplesPerSegment:12,ribbonSizeRange:Array.isArray(i.ribbonSizeRange)?i.ribbonSizeRange:[4,28],valueExtent:r.valueExtent,seriesOrder:r.seriesOrder,lineWidth:"number"==typeof i.lineWidth?i.lineWidth:3,ribbonOpacity:"number"==typeof i.ribbonOpacity?i.ribbonOpacity:.82,lineOpacity:"number"==typeof i.lineOpacity?i.lineOpacity:.9,neutralColor:"string"==typeof i.neutralColor?i.neutralColor:void 0,color:"string"==typeof i.color?i.color:void 0,stroke:"string"==typeof i.stroke?i.stroke:void 0,strokeWidth:"number"==typeof i.strokeWidth?i.strokeWidth:void 0,opacity:"number"==typeof i.opacity?i.opacity:void 0,styleRules:i.styleRules,areaStyle:n.areaStyle,pointStyle:n.pointStyle,labelStyle:i.labelStyle,showPoints:!0===i.showPoints,pointRadius:"number"==typeof i.pointRadius?i.pointRadius:3,showLabels:i.showLabels??!0},u=n.xFormat,d=(e,t)=>{if(0===r.xValues.length)return"";const o=r.xValues[Math.max(0,Math.min(r.xValues.length-1,Math.round(Number(e))))];return u?u(o,t):(o instanceof Date?o.toLocaleDateString():o)+""},h=r.xValues.map((e,t)=>t),p=Array.from({length:s},(e,t)=>t+1),g=n.axes??[{orient:"left",tickValues:p,tickFormat:e=>e+"",label:n.yLabel??"Rank",baseline:!1},{orient:"bottom",tickValues:h,tickFormat:d,label:n.xLabel,tickAnchor:"edges"}];return{...n,chartType:"custom",data:r.data,xAccessor:"x",yAccessor:"y",xExtent:[0,Math.max(1,r.xValues.length-1)],yExtent:[s+.5,.5],customLayout:Do,layoutConfig:c,colorAccessor:"__bumpSeries",colorScheme:l,xFormat:d,axes:g,axisExtent:"exact",showAxes:n.showAxes??!0,showLegend:n.showLegend??!1,annotations:Fo(n.annotations,r.xValues)}}};function Xo(e,t,o,n,i){if(!i.showPoints)return;const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=Kt(n.theme).colors.categorical,a=o??n.colorScheme??s,l="string"==typeof t?t:"__ssrPointColorBy",c="function"==typeof t?r.map(e=>({...e,__ssrPointColorBy:t(e)})):r,u=t?J(c,l,a):void 0,d="number"==typeof i.pointRadius?i.pointRadius:3;return e=>{const o=t&&u?le(e,t,u):"string"==typeof i.color?i.color:R;return{r:d,fill:o,stroke:"none"}}}var qo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=t||i.lineBy,l=i.fillArea,c=Array.isArray(l)?"mixed":l?"area":"line",u=Kt(n.theme).colors.categorical,d=function(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],l=Kt(n.theme).colors.categorical,c=o??n.colorScheme??l,u="string"==typeof t?t:"__ssrLineColorBy",d="function"==typeof t?r.map(e=>({...e,__ssrLineColorBy:t(e)})):r,h=t?J(d,u,c):void 0,p=s(i.xAccessor,i.yAccessor),g=function(e){const{lineWidth:t=2,colorBy:o,colorScale:n,color:i,resolveStroke:r,fillArea:s,areaOpacity:l=.3,styleRules:c,ruleContext:u}=e;return(e,d)=>{const h={strokeWidth:t},p=!0===s||Array.isArray(s)&&null!=d&&s.includes(d);let g;return r?g=r(e,d):o?n&&(g=le(e,o,n)):g=i||R,void 0!==g&&(h.stroke=g,p&&(h.fill=g,h.fillOpacity=l)),c?.length&&Object.assign(h,a(e,c,u?u(e,d):{value:void 0,category:d})),h}}({lineWidth:"number"==typeof i.lineWidth?i.lineWidth:2,colorBy:t,colorScale:h,color:"string"==typeof i.color?i.color:void 0,fillArea:i.fillArea,areaOpacity:"number"==typeof i.areaOpacity?i.areaOpacity:.3,styleRules:i.styleRules,ruleContext:p});return Xt(g,{stroke:"string"==typeof i.stroke?i.stroke:void 0,strokeWidth:"number"==typeof i.strokeWidth?i.strokeWidth:void 0,opacity:"number"==typeof i.opacity?i.opacity:void 0})}(e,r,o,n,i),h=lo({data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",lineBy:i.lineBy,colorBy:r,colorScheme:o,color:"string"==typeof i.color?i.color:void 0,forecast:i.forecast,anomaly:i.anomaly,gapStrategy:i.gapStrategy,directLabel:i.directLabel,annotations:n.annotations,themeCategorical:u,baseLineStyle:d}),p=n.pointStyle||Xo(h.data,h.colorAccessor,o,n,i);let g=n.margin;h.marginExtra&&g&&"object"==typeof g?g={...g,...null!=h.marginExtra.right&&{right:Math.max(Number(g.right)||0,h.marginExtra.right)},...null!=h.marginExtra.left&&{left:Math.max(Number(g.left)||0,h.marginExtra.left)}}:h.marginExtra&&null==g&&(g={top:20,right:h.marginExtra.right??20,bottom:30,left:h.marginExtra.left??40});const m=(!i.directLabel||void 0!==n.showLegend)&&(n.showLegend??!!h.colorAccessor);return{chartType:c,data:h.data,xAccessor:h.xAccessor,yAccessor:h.yAccessor,groupAccessor:h.groupAccessor,colorAccessor:h.colorAccessor,colorScheme:o,lineStyle:h.lineStyle||d,...Array.isArray(l)&&{areaGroups:l},...l&&null!=i.areaOpacity&&{areaOpacity:i.areaOpacity},...null!=i.band&&{band:i.band},...n,...void 0!==g&&{margin:g},annotations:h.annotations,...h.yExtent&&!n.yExtent&&{yExtent:h.yExtent},...p&&{pointStyle:p},showLegend:m}}},Uo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=Array.isArray(e)?ie(e):[],s=i.timeAccessor||"time",a=i.valueAccessor||"value",l=i.categoryAccessor,c=i.valueExtent||n.yExtent,u="down"===i.direction?je({data:r,timeAccessor:s,valueAccessor:a,binSize:Number(i.binSize),valueExtent:c,extentPadding:i.extentPadding}):c,d={...void 0!==i.fill&&{fill:i.fill},...void 0!==i.stroke&&{stroke:i.stroke},...void 0!==i.strokeWidth&&{strokeWidth:i.strokeWidth},...void 0!==i.opacity&&{opacity:i.opacity},...void 0!==i.gap&&{gap:i.gap}};return{chartType:"bar",data:r,...n,runtimeMode:"streaming",windowMode:"growing",windowSize:Math.max(1,r.length),arrowOfTime:i.arrowOfTime||"right",timeAccessor:s,valueAccessor:a,xExtent:i.timeExtent||n.xExtent,yExtent:u,extentPadding:i.extentPadding??n.extentPadding,binSize:i.binSize,categoryAccessor:l,barColors:i.colors||n.barColors,colorScheme:i.colors||n.colorScheme,barStyle:n.barStyle||d,showLegend:n.showLegend??!!l}}},Qo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=t||i.areaBy,s=function({data:e,safeData:t,areaBy:o,lineDataAccessor:n}){if(null==e)return[];const i=void 0!==t[0]?.[n];if(!i&&!o)return t;let r;if(i)r=t;else{const e=t.reduce((e,t)=>{const i="function"==typeof o?o(t):t[o],r=i+"";if(!e[r]){const t={[n]:[]};"string"==typeof o&&(t[o]=i),e[r]=t}return e[r][n].push(t),e},{});r=Object.values(e)}return r.flatMap(e=>{const t=Array.isArray(e[n])?e[n]:[];return"string"==typeof o?t.map(t=>({...t,[o]:t[o]??e[o]})):t})}({data:e,safeData:Array.isArray(e)?ie(e):[],areaBy:i.areaBy,lineDataAccessor:i.lineDataAccessor||"coordinates"}),a=ke(i.semanticGradient),l=a?.stops.length?qe(a):Se(n.gradientFill),c=!1!==i.semanticLine&&a?.stops.length?a.stops.flatMap(({offset:e,color:t})=>t?[{offset:e,color:t}]:[]):void 0,u=n.pointStyle||Xo(s,r,o,n,i);return{chartType:"area",data:s,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",y0Accessor:i.y0Accessor,groupAccessor:i.areaBy||void 0,colorAccessor:r,colorScheme:o,...n,...void 0!==l&&{gradientFill:l},...c&&{semanticLineStops:c},lineStyle:n.lineStyle||Wo(s,r,o,n,i),...u&&{pointStyle:u}}}},Zo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=i.xAccessor||"x",s=i.seriesAAccessor||"a",a=i.seriesBAccessor||"b",l=e=>Ut(qt(r,"x",e)),c=e=>Ut(qt(s,"a",e)),u=e=>Ut(qt(a,"b",e)),d=i.seriesAColor||"var(--semiotic-danger, #dc2626)",h=i.seriesBColor||"var(--semiotic-info, #2563eb)",p=i.areaOpacity??.6,g=i.lineWidth??1.5,m=!1!==i.showLines,f=!1!==n.showLegend,y=i.seriesALabel||"A",b=i.seriesBLabel||"B",x=n.legendPosition||"right",v=function(e,t,o,n){if(!e.length)return[];const i=e.filter(e=>Number.isFinite(t(e))).sort((e,o)=>t(e)-t(o)),r=[];let s=0,a=null,l=null,c=[];const u=(e,t)=>e>t?"A":t>e?"B":null,d=e=>`seg-${s}-${e}`,h=e=>r.push(e),p=(e,t)=>{h({__x:e.x,__y:e.y,__y0:e.y,__diffSegment:d(t),__diffWinner:t,__valA:e.y,__valB:e.y,__sourceDatum:e.datum})};for(let e=0;i.length>e;e++){const r=i[e],g=t(r),m=o(r),f=n(r);if(!Number.isFinite(g)||!Number.isFinite(m)||!Number.isFinite(f))continue;const y=u(m,f);if(null!==y)if(null!=a){if(l&&l.w!==y){let e,t;if(c.length>0)e=c[0].x,t=c[0].y;else{const o=m-l.a-(f-l.b);if(0!==o){const n=Math.max(0,Math.min(1,(l.b-l.a)/o));e=l.x+n*(g-l.x),t=l.a+n*(m-l.a)}else e=l.x,t=l.a}h({__x:e,__y:t,__y0:t,__diffSegment:d(a),__diffWinner:a,__valA:t,__valB:t}),s++,a=y,h({__x:e,__y:t,__y0:t,__diffSegment:d(a),__diffWinner:a,__valA:t,__valB:t});for(let e=1;c.length>e;e++)p(c[e],a)}else for(const e of c)p(e,a);c=[],h({__x:g,__y:f>m?f:m,__y0:f>m?m:f,__diffSegment:d(a),__diffWinner:a,__valA:m,__valB:f,__sourceDatum:r}),l={x:g,a:m,b:f,w:y}}else{a=y;for(const e of c)p(e,a);c=[],h({__x:g,__y:f>m?f:m,__y0:f>m?m:f,__diffSegment:d(a),__diffWinner:a,__valA:m,__valB:f,__sourceDatum:r}),l={x:g,a:m,b:f,w:y}}else c.push({x:g,y:m,datum:r})}for(const e of c)p(e,a??"A");return r}(Array.isArray(e)?e:[],l,c,u),w=[];if(m&&Array.isArray(e)){const t=e.filter(e=>Number.isFinite(l(e))).sort((e,t)=>l(e)-l(t));for(const e of t){const t=l(e),o=c(e),n=u(e);Number.isFinite(o)&&w.push({__x:t,__y:o,__diffSegment:"line-A"}),Number.isFinite(n)&&w.push({__x:t,__y:n,__diffSegment:"line-B"})}}return{chartType:"mixed",data:[...v,...w],xAccessor:"__x",yAccessor:"__y",y0Accessor:"__y0",groupAccessor:"__diffSegment",areaGroups:Array.from(new Set(v.map(e=>e.__diffSegment))),areaStyle:e=>{const t=e.__diffSegment;return{fill:"A"==(t?.endsWith("-A")?"A":"B")?d:h,stroke:"none",fillOpacity:p}},lineStyle:e=>({stroke:"A"==("line-A"===e.__diffSegment?"A":"B")?d:h,strokeWidth:g,fill:"none"}),curve:i.curve||"linear",...n,...f&&{legend:{legendGroups:[{label:"",type:"fill",styleFn:e=>({fill:e.color||"currentColor"}),items:[{label:y,color:d},{label:b,color:h}]}]},legendPosition:x}}}},Ko={frameType:"xy",buildProps:(e,t,o,n,i)=>{const s=t||i.areaBy,l="string"==typeof s&&Array.isArray(e)?J(e,s,o):void 0,c="number"==typeof i.areaOpacity?i.areaOpacity:.7,u=n.lineStyle||(e=>{const t=null==s?void 0:le(e,s,l),o=i.showLine??!0,n={fill:i.color??t,stroke:o?i.stroke??t:"none",...o?{strokeWidth:i.strokeWidth??i.lineWidth??2}:{},fillOpacity:c,...null==i.opacity?{}:{opacity:i.opacity}},u=i.styleRules;if(u?.length){const t=r(i.yAccessor),o=s?"function"==typeof s?(s(e)??"")+"":(e[s]??"")+"":void 0;Object.assign(n,a(e,u,{value:t(e),category:o}))}return n}),d=i.normalize?"zero":i.baseline??"zero",h=n.pointStyle||Xo(e,s,o,n,i);return{chartType:"stackedarea",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",groupAccessor:i.areaBy,colorAccessor:s,colorScheme:o,normalize:i.normalize,baseline:d,stackOrder:i.stackOrder,lineStyle:u,...n,...h&&{pointStyle:h},curve:n.curve??i.curve??"monotoneX",showLegend:n.showLegend??!!s}}},Jo={frameType:"xy",buildProps:(e,t,o,n,i)=>{const[r]=n.size??[600,400];return{chartType:"candlestick",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.highAccessor||"high",highAccessor:i.highAccessor||"high",lowAccessor:i.lowAccessor||"low",openAccessor:i.openAccessor,closeAccessor:i.closeAccessor,candlestickStyle:i.candlestickStyle,...n,scalePadding:n.scalePadding??Math.max(2,Math.min(12,Math.round(r/40))),extentPadding:n.extentPadding??(r>200?.1:.02)}}},en={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=n.pointStyle||Vo(e,t,o,n,i),s=c(i.styleRules,i.xAccessor||"x",i.yAccessor||"y"),a=s?e=>({..."function"==typeof r?r(e):r,...s(e)}):r;return{chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,...i.symbolBy&&{symbolAccessor:i.symbolBy},...i.symbolMap&&{symbolMap:i.symbolMap},colorScheme:o,...n,sizeRange:i.sizeRange||[3,15],pointStyle:a,showLegend:n.showLegend??!!t}}},tn={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=i.xCenter,s=i.yCenter,a=i.quadrants,l=i.centerlineStyle||{},c=!1!==i.showQuadrantLabels,u=i.quadrantLabelSize??12,d=l.stroke||"#999",h=l.strokeWidth??1,p=Array.isArray(l.strokeDasharray)?l.strokeDasharray.join(","):l.strokeDasharray,g=Ht.createElement,m=a?[(e,t,o)=>{if(!t?.x||!t?.y)return null;const n=o.width,i=o.height,l=null!=r?t.x(r):n/2,m=null!=s?t.y(s):i/2;if(null!=r&&!Number.isFinite(l))return null;if(null!=s&&!Number.isFinite(m))return null;const f=Math.max(0,Math.min(n,l)),y=Math.max(0,Math.min(i,m)),b=[{c:a.topLeft,x:0,y:0,w:f,h:y},{c:a.topRight,x:f,y:0,w:n-f,h:y},{c:a.bottomLeft,x:0,y:y,w:f,h:i-y},{c:a.bottomRight,x:f,y:y,w:n-f,h:i-y}],x=c?[g("text",{key:"ltl",x:8,y:8+u,fill:a.topLeft.color,fontWeight:600,fontSize:u,opacity:.5},a.topLeft.label),g("text",{key:"ltr",x:n-8,y:8+u,fill:a.topRight.color,fontWeight:600,fontSize:u,opacity:.5,textAnchor:"end"},a.topRight.label),g("text",{key:"lbl",x:8,y:i-8,fill:a.bottomLeft.color,fontWeight:600,fontSize:u,opacity:.5},a.bottomLeft.label),g("text",{key:"lbr",x:n-8,y:i-8,fill:a.bottomRight.color,fontWeight:600,fontSize:u,opacity:.5,textAnchor:"end"},a.bottomRight.label)]:[];return g(Ht.Fragment,null,...b.map((e,t)=>e.w>0&&e.h>0?g("rect",{key:"qf-"+t,x:e.x,y:e.y,width:e.w,height:e.h,fill:e.c.color,opacity:e.c.opacity??.08}):null),g("line",{key:"vc",x1:f,y1:0,x2:f,y2:i,stroke:d,strokeWidth:h,strokeDasharray:p}),g("line",{key:"hc",x1:0,y1:y,x2:n,y2:y,stroke:d,strokeWidth:h,strokeDasharray:p}),...x)}]:void 0;return{chartType:"scatter",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,sizeAccessor:i.sizeBy,sizeRange:i.sizeRange||[3,15],colorScheme:o,pointStyle:n.pointStyle||i.pointStyle||Vo(e,t,o,n,i),...n,showLegend:n.showLegend??!!t,...m&&{svgPreRenderers:m}}}},on={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=function(e,t){if(!Array.isArray(e))return{data:e,orderMap:new WeakMap};const o=t.xAccessor||"x",n=t.yAccessor||"y",i=t.orderAccessor?[...e].sort((e,o)=>null==e||"object"!=typeof e?1:null==o||"object"!=typeof o?-1:Ut(qt(t.orderAccessor,"order",e))-Ut(qt(t.orderAccessor,"order",o))):e,r=new WeakMap;let s=0;for(const e of i){if(null==e||"object"!=typeof e)continue;const t=Ut(qt(o,"x",e)),i=Ut(qt(n,"y",e));Number.isFinite(t)&&Number.isFinite(i)&&s++}let a=0;for(const e of i){if(null==e||"object"!=typeof e)continue;const t=Ut(qt(o,"x",e)),i=Ut(qt(n,"y",e));Number.isFinite(t)&&Number.isFinite(i)&&r.set(e,{idx:a++,total:s})}return{data:i,orderMap:r}}(e,i),s=i.pointRadius??4,a=[e=>{const t=e.filter(e=>"point"===e.type&&"number"==typeof e.x&&"number"==typeof e.y);if(2>t.length)return null;const o=[];for(let e=0;t.length-1>e;e++){const n=t[e],i=t[e+1],r=Qt(e,t.length);100>t.length&&o.push(Ht.createElement("line",{key:"halo-"+e,x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:"white",strokeWidth:s+2,strokeLinecap:"round",opacity:.5})),o.push(Ht.createElement("line",{key:"segment-"+e,x1:n.x,y1:n.y,x2:i.x,y2:i.y,stroke:r,strokeWidth:s,strokeLinecap:"round"}))}return Ht.createElement(Ht.Fragment,null,...o)}];return{chartType:"scatter",data:r.data,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,colorScheme:o,pointStyle:Xt(e=>{const t=r.orderMap.get(e),o=t?.idx??0,n=t?.total??1;return{fill:n>0?Qt(o,n):"#6366f1",stroke:"white",strokeWidth:1,r:s,fillOpacity:1}},Zt(i)),...n,svgPreRenderers:a}}},nn={frameType:"xy",buildProps:(e,t,o,n,i)=>{const r=Number.isFinite(i.cellBorderWidth)?Math.max(0,i.cellBorderWidth):1;return{chartType:"heatmap",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",valueAccessor:i.valueAccessor,colorScheme:o||i.colorScheme||"blues",showValues:i.showValues,heatmapValueFormat:i.valueFormat,areaStyle:()=>({stroke:i.cellBorderColor??"#fff",strokeWidth:r}),...n}}};function rn(e){return Math.max(0,Math.min(1,e))}function sn(e){const t=e.trim();if(t.startsWith("#")){let e=t.slice(1);if(3===e.length&&(e=e.split("").map(e=>e+e).join("")),6===e.length&&/^[0-9a-f]{6}$/i.test(e))return[parseInt(e.slice(0,2),16),parseInt(e.slice(2,4),16),parseInt(e.slice(4,6),16)]}const o=e.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i);if(o){const e=[Number(o[1]),Number(o[2]),Number(o[3])];if(e.every(Number.isFinite))return e}return null}function an(e,t,o){const n=e=>Math.max(0,Math.min(255,Math.round(e))).toString(16).padStart(2,"0");return`#${n(e)}${n(t)}${n(o)}`}function ln(e,t,o){const n=e.filter(e=>Number.isFinite(e.offset)).map(e=>({offset:rn(e.offset),color:e.color??o,opacity:null==e.opacity?1:rn(e.opacity)})).sort((e,t)=>e.offset-t.offset);if(0===n.length)return"#999999";const i=e=>{if(1===e.opacity)return e.color;const t=sn(e.color);return t?`rgba(${t[0]},${t[1]},${t[2]},${e.opacity})`:e.color};if(1===n.length)return i(n[0]);const r=rn(t);if(n[0].offset>=r)return i(n[0]);if(r>=n[n.length-1].offset)return i(n[n.length-1]);for(let e=0;n.length-1>e;e++){const t=n[e],o=n[e+1];if(t.offset>r||r>o.offset)continue;const s=o.offset-t.offset,a=s>0?(r-t.offset)/s:0,l=sn(t.color),c=sn(o.color);if(!l||!c)return i(.5>a?t:o);const[u,d,h]=l,[p,g,m]=c,f=u+(p-u)*a,y=d+(g-d)*a,b=h+(m-h)*a,x=t.opacity+(o.opacity-t.opacity)*a;return 1===x?an(f,y,b):`rgba(${Math.round(f)},${Math.round(y)},${Math.round(b)},${x})`}return i(n[n.length-1])}function cn(e,t,o){return null==o?`${e}-${t}`:`${e}-${t}-${o}`}import{Fragment as un,jsx as dn,jsxs as hn}from"react/jsx-runtime";import{useMemo as pn,useCallback as gn,useRef as mn}from"react";var fn={RdBu:wt,PiYG:vt,PRGn:xt,BrBG:bt,RdYlBu:At,RdYlGn:St,Spectral:kt},yn="__likert_neutral_neg",bn="__likert_neutral_pos";function xn(e,t){if("function"==typeof e)return e;const o=e||t;return e=>e[o]}import*as vn from"react";function wn(e){return Se(e)}function An(e,t,o,n,i){const s=Kt(n.theme).colors.categorical,l=o??n.colorScheme,c=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],u="string"==typeof t?t:"__ssrColorBy",d="function"==typeof t?c.map(e=>({...e,__ssrColorBy:t(e)})):c,h=t?J(d,u,l??s):void 0,p=Ee("string"==typeof i.color?i.color:void 0,s,l,void 0,new Map),g=r(i.valueAccessor),m=i.styleRules,f=n.pieceStyle;return(e,o)=>{const n={fill:t&&h?le(e,t,h):p};return m?.length&&Object.assign(n,a(e,m,{value:g(e),category:o})),"function"==typeof f?Object.assign(n,f(e,o)||{}):f&&"object"==typeof f&&Object.assign(n,f),void 0!==i.stroke&&(n.stroke=i.stroke),void 0!==i.strokeWidth&&(n.strokeWidth=i.strokeWidth),void 0!==i.opacity&&(n.opacity=i.opacity),n}}function Sn(e,t,o,n,i){const r=An(e,t,o,n,i);return(e,t)=>{const o=r(e,t);return void 0===o.fillOpacity&&(o.fillOpacity=.8),void 0===o.stroke&&(o.stroke=o.fill),o}}function kn(e,t,o,n,i){const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s="string"==typeof t?t:"__ssrViolinColorBy",a="function"==typeof t?r.map(e=>({...e,__ssrViolinColorBy:t(e)})):r,l=Kt(n.theme).colors.categorical,c=o??n.colorScheme,u=t?J(a,s,c??l):void 0,d=Ee("string"==typeof i.color?i.color:void 0,l,c,void 0,new Map);return e=>{const o=t&&u?le(e,t,u):d;return{fill:o,fillOpacity:.6,stroke:i.stroke??o,...void 0!==i.strokeWidth&&{strokeWidth:i.strokeWidth},...void 0!==i.opacity&&{opacity:i.opacity}}}}function Mn(e,t,o,n,i){const r=An(e,t,o,n,i),s="number"==typeof i.dotRadius?i.dotRadius:5;return(e,t)=>({r:s,fillOpacity:.8,...r(e,t)})}function _n(e,t,o,n,i){const r=An(e,t,o,n,i),s=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],a=i.sizeBy,l=Array.isArray(i.sizeRange)?i.sizeRange:[3,8],c=a?s.map(e=>"function"==typeof a?a(e):Number(e[a])).filter(Number.isFinite):[],u=c.length?Ot(c):void 0,d="number"==typeof i.pointRadius?i.pointRadius:4,h="number"==typeof i.pointOpacity?i.pointOpacity:.7;return(e,t)=>({r:a?de(e,a,l,u):d,fillOpacity:h,...r(e,t)})}var Pn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"bar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"horizontal"===i.orientation?"horizontal":"vertical",oSort:i.sort??!1,colorAccessor:t,colorScheme:o,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,t,o,n,i)})},Tn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.stackBy;return{chartType:"bar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",stackBy:i.stackBy,colorAccessor:r,colorScheme:o,projection:"horizontal"===i.orientation?"horizontal":"vertical",normalize:i.normalize,oSort:i.sort??!1,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},Ln={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.groupBy;return{chartType:"clusterbar",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",groupBy:i.groupBy,colorAccessor:r,colorScheme:o,projection:"horizontal"===i.orientation?"horizontal":"vertical",oSort:i.sort??!1,barPadding:i.barPadding,...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},Rn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.categoryAccessor;return{chartType:"pie",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"radial",colorAccessor:r,colorScheme:o,...null!=i.cornerRadius&&{cornerRadius:i.cornerRadius},...null!=i.startAngle&&{startAngle:i.startAngle},...n,pieceStyle:An(e,r,o,n,i),showLegend:n.showLegend??!!r}}},In={frameType:"ordinal",layout:{primarySize:{width:400,height:400}},buildProps:(e,t,o,n,i)=>{const r=t||i.categoryAccessor;return{chartType:"donut",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",projection:"radial",margin:n.margin??{top:50,right:40,bottom:60,left:70},innerRadius:i.innerRadius??60,colorAccessor:r,colorScheme:o,...null!=i.cornerRadius&&{cornerRadius:i.cornerRadius},...null!=i.startAngle&&{startAngle:i.startAngle},...n,pieceStyle:An(e,r,o,n,i)}}},Cn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],s=i.valueAccessor||"value",a=r.map(e=>Number("function"==typeof s?s(e):e[s])).filter(Number.isFinite),l=a.length?[Math.min(...a),Math.max(...a)]:void 0;return{chartType:"histogram",data:e,oAccessor:i.categoryAccessor||(e=>null==e.category?"All":e.category+""),rAccessor:s,projection:"horizontal",bins:i.bins??25,normalize:i.relative??!1,colorAccessor:t,colorScheme:o,barPadding:i.categoryPadding??20,...i.valueExtent?{rExtent:i.valueExtent}:l?{rExtent:l}:{},...n,summaryStyle:Sn(e,t,o,n,i)}}},zn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"boxplot",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,...null!=i.showOutliers&&{showOutliers:i.showOutliers},...null!=i.outlierRadius&&{outlierRadius:i.outlierRadius},...n,summaryStyle:n.summaryStyle||Sn(e,t,o,n,i)})},Fn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"violin",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,projection:"horizontal"===i.orientation?"horizontal":"vertical",bins:i.bins??25,showIQR:i.showIQR??!0,barPadding:i.categoryPadding??20,colorScheme:o,...n,summaryStyle:n.summaryStyle||kn(e,t,o,n,i),showLegend:n.showLegend??!!t,...i.valueExtent&&{rExtent:i.valueExtent}})},On={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"swarm",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,...i.symbolBy&&{symbolAccessor:i.symbolBy},...i.symbolMap&&{symbolMap:i.symbolMap},colorScheme:o,...n,sizeRange:i.sizeRange||[3,8],pieceStyle:n.pieceStyle||_n(e,t,o,n,i),showLegend:n.showLegend??!!t})},Bn={frameType:"ordinal",layout:{modeDefaults:{showGrid:!0}},buildProps:(e,t,o,n,i)=>({chartType:"point",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",oSort:i.sort??"auto",barPadding:i.categoryPadding??10,...n,pieceStyle:Mn(e,t,o,n,i),showGrid:n.showGrid??!0,showLegend:n.showLegend??!!t})},Nn={frameType:"ordinal",buildProps:(e,t,o,n,i)=>{const r=t||i.subcategoryAccessor;return{chartType:"swimlane",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",stackBy:i.subcategoryAccessor,colorAccessor:r,categoryAccessor:i.categoryAccessor,subcategoryAccessor:i.subcategoryAccessor,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",...null!=i.trackFill&&{trackFill:i.trackFill},...i.valueExtent&&{rExtent:i.valueExtent},...null!=i.roundedTop&&{roundedTop:i.roundedTop},...n,gradientFill:wn(n.gradientFill),pieceStyle:n.pieceStyle||An(e,r,o,n,i),showLegend:n.showLegend??!!r,barPadding:i.barPadding??40}}},En={frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"ridgeline",data:e,oAccessor:i.categoryAccessor||"category",rAccessor:i.valueAccessor||"value",colorAccessor:t,colorScheme:o,projection:"vertical"===i.orientation?"vertical":"horizontal",bins:i.bins??20,amplitude:i.amplitude??1.5,barPadding:i.categoryPadding??5,oSort:i.oSort??!1,...n,summaryStyle:n.summaryStyle||((r,s)=>({fillOpacity:.5,...An(e,t,o,n,i)(r,s)})),showLegend:n.showLegend??!!t})},jn={frameType:"ordinal",layout:{margin:(e,t)=>({...t.marginDefaults,left:"vertical"===e.orientation?t.marginDefaults.left:Math.max(100,t.marginDefaults.left)})},buildProps:(e,t,o,n,i)=>{const r=Array.isArray(i.levels)&&i.levels.length>=2?i.levels:["Strongly disagree","Disagree","Neutral","Agree","Strongly agree"],s="vertical"!==i.orientation;let a=function(e,t,o,n,i,r){const s=new Map,a=new Set(t);for(const l of e){const e=o(l);s.has(e)||s.set(e,new Map);const c=s.get(e);if(n){const e=n(l);if(null==e||!Number.isFinite(e))continue;if(!Number.isInteger(e)){"production"!==process.env.NODE_ENV&&console.warn("[LikertChart] Ignoring non-integer Likert score:",e);continue}const o=e-1;if(0>o||o>=t.length)continue;const i=t[o];c.set(i,(c.get(i)||0)+1)}else if(i&&r){const e=i(l),t=r(l);if(!a.has(e))continue;c.set(e,(c.get(e)||0)+(Number.isFinite(t)?t:0))}}const l=[];for(const[e,o]of s){let n=0;for(const e of t)n+=o.get(e)||0;if(0!==n)for(let i=0;t.length>i;i++){const r=t[i],s=o.get(r)||0;l.push({__likertCategory:e,__likertLevel:r,__likertLevelLabel:r,__likertCount:s,__likertPct:s/n*100,__likertLevelIndex:i})}}return l}(Array.isArray(e)?e.filter(e=>!!e&&"object"==typeof e):[],r,xn(i.categoryAccessor,"question"),i.levelAccessor?null:xn(i.valueAccessor,"score"),i.levelAccessor?xn(i.levelAccessor,"level"):null,i.levelAccessor?xn(i.countAccessor,"count"):null);s&&(a=function(e,t){const o=t.length,n=o%2!=0,i=Math.floor(o/2),r=new Map;for(const t of e){const e=r.get(t.__likertCategory)||[];e.push(t),r.set(t.__likertCategory,e)}const s=[];for(const[,e]of r){const t=new Map;let r,a;for(const o of e)o.__likertLevel===yn?r=o:o.__likertLevel===bn?a=o:t.set(o.__likertLevelIndex,o);n&&r&&s.push(r);for(let e=i-1;e>=0;e--){const o=t.get(e);o&&s.push(o)}n&&a&&s.push(a);for(let e=n?i+1:i;o>e;e++){const o=t.get(e);o&&s.push(o)}}return s}(function(e,t){const o=t.length,n=o%2!=0,i=Math.floor(o/2),r=[];for(const t of e){const e=t.__likertLevelIndex;if(n&&e===i){const e=t.__likertPct/2;r.push({...t,__likertLevel:yn,__likertPct:-e}),r.push({...t,__likertLevel:bn,__likertPct:e})}else r.push(i>e?{...t,__likertPct:-t.__likertPct}:t)}return r}(a,r),r));const l=Kt(n.theme).colors.diverging,c=Array.isArray(o)&&o.length>=r.length?o:function(e,t){if(0>=e)return[];if(t){const o=fn[t];if(o){if(1===e)return[o(.5)];const t=[];for(let n=0;e>n;n++)t.push(o(n/(e-1)));return t}}const o=["#da1e28","#ff8389","#ffb3b8"],n=["#a6c8ff","#4589ff","#0043ce"],i="#a8a8a8";if(1===e)return[i];const r=e%2!=0,s=Math.floor(e/2),a=[];for(let e=0;s>e;e++)a.push(o[Math.min(Math.floor(e*o.length/s),o.length-1)]);r&&a.push(i);for(let e=0;s>e;e++)a.push(n[Math.min(Math.floor(e*n.length/s),n.length-1)]);return a}(r.length,l),u=new Map(r.map((e,t)=>[e,c[t]||"#888"])),d=r.length%2&&u.get(r[Math.floor(r.length/2)])||"#888",h="function"==typeof i.valueFormat?i.valueFormat:e=>Math.abs(Number(e)).toFixed(0)+"%",p=!1===n.showLegend?void 0:{legendGroups:[{label:"",items:r.map(e=>({label:e})),styleFn:e=>({fill:u.get(e.label)||"#888"})}]},g=X(p,n.legend);return{chartType:"bar",data:a,oAccessor:"__likertCategory",rAccessor:"__likertPct",stackBy:"__likertLevel",normalize:!1,projection:s?"horizontal":"vertical",barPadding:i.barPadding,showGrid:n.showGrid,oLabel:i.categoryLabel,rLabel:i.valueLabel||(s?void 0:"Percentage"),rFormat:h,...i.categoryFormat&&{oFormat:i.categoryFormat},...i.valueExtent&&{rExtent:i.valueExtent},...n,pieceStyle:Xt(e=>{const t=e.__likertLevel||e.data?.__likertLevel;return{fill:t===yn||t===bn?d:u.get((e.__likertLevelLabel||e.data?.__likertLevelLabel||t)+"")||"#888"}},Zt(i)),showLegend:n.showLegend??!0,legendPosition:n.legendPosition||"right",...g&&{legend:g},__legendIncludesAutomatic:!0}}},$n={frameType:"ordinal",layout:{margin:(e,t)=>"vertical"===e.orientation?{top:t.title?60:40,right:20,bottom:60,left:60}:{top:t.title?40:10,right:10,bottom:10,left:10}},buildProps:(e,t,o,n,i)=>{const r="vertical"===i.orientation,s=t||i.categoryAccessor;return{chartType:r?"bar-funnel":"funnel",data:e,oAccessor:i.stepAccessor||"step",rAccessor:i.valueAccessor||"value",colorAccessor:s,categoryAccessor:i.categoryAccessor,projection:r?"vertical":"horizontal",connectorAccessor:i.connectorAccessor,connectorStyle:i.connectorStyle,...!r&&null!=i.connectorOpacity&&{connectorOpacity:i.connectorOpacity},barPadding:r?40:0,colorScheme:o,...n,showAxes:r,showGrid:r,pieceStyle:An(e,s,o,n,i),showLabels:i.showLabels??!0}}},Dn={frameType:"ordinal",layout:{primarySize:{width:300,height:250}},renderOverlay:function(e,{theme:t}){const o=e.__gauge;if(!o)return null;const n=(o.startAngleDeg+(o.gMax===o.gMin?0:(Math.max(o.gMin,Math.min(o.gMax,o.value??o.gMin))-o.gMin)/(o.gMax-o.gMin))*o.sweep-90)*Math.PI/180,i=o.needleColor||t.colors.text,r=o.showScaleLabels?(o.thresholds||[]).filter(e=>e.value>o.gMin&&o.gMax>e.value):[];return hn(un,{children:[o.showNeedle&&hn(un,{children:[dn("line",{x1:o.centerX,y1:o.centerY,x2:o.centerX+o.needleLength*Math.cos(n),y2:o.centerY+o.needleLength*Math.sin(n),stroke:i,strokeWidth:2.5,strokeLinecap:"round"}),dn("circle",{cx:o.centerX,cy:o.centerY,r:4,fill:i})]}),null!=o.contextValue&&dn("text",{x:o.centerX,y:o.contextValueY,textAnchor:"middle",dominantBaseline:"middle",fontSize:o.valueFontSize,fontWeight:700,fill:i,children:o.contextValue}),r.map((e,n)=>{const i=(o.startAngleDeg+(o.gMax===o.gMin?0:(e.value-o.gMin)/(o.gMax-o.gMin))*o.sweep-90)*Math.PI/180,r=o.innerRadius-1,s=o.radius+1,a=o.radius+10,l=((i+Math.PI/2)/(2*Math.PI)*12+12)%12,c=l>=11||1>l?"middle":5>l?"start":7>l?"middle":"end",u=l>=11||1>l?"auto":5>l?"middle":7>l?"hanging":"middle";return hn("g",{children:[dn("line",{x1:o.centerX+Math.cos(i)*r,y1:o.centerY+Math.sin(i)*r,x2:o.centerX+Math.cos(i)*s,y2:o.centerY+Math.sin(i)*s,stroke:t.colors.border,strokeWidth:2,strokeLinecap:"round"}),dn("text",{x:o.centerX+Math.cos(i)*a,y:o.centerY+Math.sin(i)*a,textAnchor:c,dominantBaseline:u,fill:t.colors.textSecondary,fontSize:10,children:e.label||e.value+""})]},"gauge-label-"+n)})]})},buildProps:(e,o,n,i,r)=>{const s=r.min??0,a=r.max??100,l=r.sweep??240,c=r.arcWidth??.3,d=!1!==r.showNeedle,h=!1!==r.fillZones,{startAngleDeg:p}=u(l),g=r.thresholds||[{value:a,color:r.color||"#4e79a7"}],m=Ae(i.gradientFill),f=function(e){const{min:t,max:o,value:n,thresholds:i,fillColor:r,backgroundColor:s,fillZones:a,showScaleLabels:l,gradientFill:c,gradientSteps:u=240}=e,d=o-t||1,h=(Math.max(t,Math.min(o,n))-t)/d;let p=i&&i.length>0?[...i].sort((e,t)=>e.value-t.value):[{value:o,color:r||"#007bff"}];p=p.map(e=>({...e,value:Math.max(t,Math.min(o,e.value))})),o>p[p.length-1].value&&p.push({value:o,color:p[p.length-1].color});const g=!!c&&c.stops.length>=2,m=[],f=new Map,y=[];if(g){const e=a?h:1,t=cn("bg",0);if(m.push({category:t,value:1,_zone:"Track",_isFill:!1,_pctStart:0,_pct:1,_roundedEnds:{start:!0,end:!0},_nonInteractive:!0}),f.set(t,{fill:s,opacity:.4}),e>0){const t=Math.max(1,Math.floor(u)),o=Math.max(1,Math.min(t,Math.round(e*t))),n=[];for(let t=0;o>t;t++)n.push(ln(c.stops,e*(t+.5)/o,r||p[0]?.color||"#007bff"));const i=cn("fill",0);m.push({category:i,value:e,_zone:"Gradient",_isFill:!0,_pctStart:0,_pct:e,_roundedEnds:{start:!0,end:!0},_nonInteractive:!0,_gradientBand:{colors:n}}),f.set(i,{fill:n[0]||s})}}else{let e=t;for(let o=0;p.length>o;o++){const n=p[o],i=(n.value-e)/d,r=(e-t)/d,l=(n.value-t)/d,c=Math.max(0,(a?Math.min(h,l):l)-r),u=a?Math.max(0,i-c):0;if(c>0){const e=cn("fill",o);m.push({category:e,value:c,_zone:n.label||"Zone "+(o+1),_isFill:!0}),f.set(e,{fill:n.color})}if(u>0){const e=cn("bg",o);m.push({category:e,value:u,_zone:n.label||"Zone "+(o+1),_isFill:!1}),f.set(e,{fill:s,opacity:.4})}e=n.value}}if(l&&i&&i.length>0)for(const e of i)e.value>t&&o>e.value&&y.push({type:"gauge-label",value:e.value,label:e.label||e.value+""});return{gaugeData:m,pieceStyle:(e,t)=>f.get(t||e.category)||{fill:s},gaugeAnnotations:y}}({min:s,max:a,value:r.value,thresholds:g,fillColor:r.color,backgroundColor:r.backgroundColor||"#e0e0e0",fillZones:h,showScaleLabels:!1!==r.showScaleLabels,gradientFill:m}),[y,b]=i.size||[300,250],x=t(l),v=Math.min(10,Math.max(1,Math.min(y,b)/12)),w=Math.max(4,Math.min((y-2*v)/x.width,(b-2*v)/x.height)-2),A=Math.max(0,Math.min(w-1.5,w*(1-c))),S=y/2-x.cx*w,k=b/2-x.cy*w,M=2*(w+4),_=Math.max(s,Math.min(a,r.value??s)),P="function"==typeof r.valueFormat?r.valueFormat(_):Math.round(_)+"",T=r.centerContent??i.centerContent,L=null!=T?"function"==typeof T?T(_,s,a):T:"sparkline"===r.mode||"context"===r.mode?void 0:vn.createElement("div",{style:{textAlign:"center",lineHeight:1.2}},vn.createElement("div",{style:{fontSize:Math.max(16,.3*w),fontWeight:700,color:"var(--semiotic-text, #333)"}},P),!1!==r.showScaleLabels&&vn.createElement("div",{style:{fontSize:11,color:"var(--semiotic-text-secondary, #666)"}},`${s} – ${a}`));return{chartType:"donut",data:f.gaugeData,oAccessor:"category",rAccessor:"value",projection:"radial",innerRadius:A,sweepAngle:l,startAngle:p,oSort:!1,pieceStyle:Xt(f.pieceStyle,Zt(r)),...null!=r.cornerRadius&&{cornerRadius:r.cornerRadius},...i,size:[y,b],margin:{top:k-M/2,bottom:b-k-M/2,left:S-M/2,right:y-S-M/2},...null!=L&&{centerContent:L},showAxes:!1,annotations:[...Array.isArray(i.annotations)?i.annotations:[],...f.gaugeAnnotations],__gauge:{gMin:s,gMax:a,sweep:l,arcWidth:c,value:_,startAngleDeg:p,thresholds:g,centerX:S,centerY:k,radius:w,innerRadius:A,showScaleLabels:!1!==r.showScaleLabels,needleLength:A>20?A-8:w-1,showNeedle:d,needleColor:r.needleColor,..."context"===r.mode&&null==T&&{contextValue:P,contextValueY:k-.2*A,valueFontSize:Math.max(12,Math.min(22,.28*w))}}}}};import{scaleTime as Wn}from"d3-scale";var Yn={static:{duplicateIds:"fatal",invalidSystemTime:"warn"},mcp:{duplicateIds:"fatal",invalidSystemTime:"warn"},push:{duplicateIds:"warn",invalidSystemTime:"strip"}};function Vn(e="static"){return Yn[e]??Yn.static}var Hn=new Set(["invalid-domain","missing-node","backward-edge","invalid-edge-time","invalid-value","invalid-node-time"]);function Gn(e){return"fatal"===e.severity||"warn"===e.severity?e.severity:Hn.has(e.kind)?"fatal":"warn"}function Xn(e){return"invalid-node-time"===e.kind?`node ${e.id} has an invalid xExtent (must be [start, end] with start <= end)`:"invalid-edge-time"===e.kind?`edge ${e.id} has an invalid startTime or endTime`:"invalid-domain"===e.kind?"time domain must be a 2-tuple of finite times [start, end] with start <= end":"invalid-value"===e.kind?`edge ${e.id} must have a positive finite value`:"missing-node"===e.kind?`edge ${e.id} references missing ${e.endpoint} node "${e.nodeId}"`:"backward-edge"===e.kind?`edge ${e.id} (${e.source}->${e.target}) ends before it starts`:"duplicate-node"===e.kind?`node id "${e.id}" is duplicated`:"duplicate-edge"===e.kind?`edge id "${e.id}" is duplicated`:"invalid-system-time"===e.kind?`edge ${e.id} has an invalid systemInTime or systemOutTime`:e.kind}function qn(e,t){return t>e?-1:e>t?1:0}function Un(e){return e.occupants.map(e=>e.id).sort(qn).join("\0")}function Qn(e,t,o=0){return e.slice(0,-1).map((n,i)=>null!=n.group&&n.group===e[i+1].group?o:t)}function Zn(e,t){return e.map(e=>{const o=new Map;for(const n of e.occupants){const e=t[n.id];if(e)for(const t of e.samples){const e=o.get(t.t)??{before:0,after:0},n=t.boundaryOffset??0;o.set(t.t,{before:Math.max(e.before,t.topMass-n),after:Math.max(e.after,t.botMass+n)})}}return[...o].sort((e,t)=>e[0]-t[0]).map(([e,t])=>({at:e,...t}))})}function Kn(e,t,o){if(0===e.length)return[];const{padding:n,plotH:i,valueScale:r}=o,s=o.stackValueScale??r,a=Qn(e,n,o.groupPadding??0),l=[n+e[0].peak.topPeak*s];for(let o=1;e.length>o;o++)l.push(l[o-1]+t[o-1]*s+a[o-1]);const c=l[l.length-1]+e[e.length-1].peak.botPeak*s+n;if(c>i&&c>0){const e=i/c;for(let t=0;l.length>t;t++)l[t]*=e}return l}function Jn(e,t){const o=(e.boundaryOffset??0)*t,n=e.value*t;if("out"===e.kind){const i=e.sideMassBefore*t;return o+("top"===e.side?n/2-i:i-n/2)}const i=e.sideMassAfter*t;return o+("top"===e.side?n/2-i:i-n/2)}function ei(e,t,o,n,i,r){const s=r.adjacentClearance?[...r.adjacentClearance]:A(Zn(n,o)).adjacentClearance,a=Kn(n,s,r);let l="hug"===r.lanePlacement?function(e,t,o,n,i,r,s){const a=e.length;if(0===a)return[];const{padding:l,plotH:c,valueScale:u}=s,d=Qn(e,l,s.groupPadding??0),h=i.map((e,t)=>e*u+d[t]),p=l+e[0].peak.topPeak*u,g=c-l-e[a-1].peak.botPeak*u;if(h.reduce((e,t)=>e+t,0)+1e-6>=g-p)return Kn(e,i,s);let m=1===a?[(p+g)/2]:[...r];for(let e=0;12>e;e++){const e=Array(a).fill(0),i=Array(a).fill(0);for(const r of o){const o=t[r.source],s=t[r.target];if(null==o||null==s||o===s)continue;const a=n[r.source]?.localAttachments.get(r.id),l=n[r.target]?.localAttachments.get(r.id);if(!a||!l)continue;const c=r.value>0&&Number.isFinite(r.value)?r.value:1,d=Jn(a,u),h=Jn(l,u);e[o]+=(m[s]+h-d)*c,i[o]+=c,e[s]+=(m[o]+d-h)*c,i[s]+=c}const r=m.map((t,o)=>0===i[o]?t:.45*t+e[o]/i[o]*.55),s=S({desired:r,minGaps:h,weights:i.map(e=>Math.max(1,e)),min:p,max:g});let l=0;for(let e=0;a>e;e++)l=Math.max(l,Math.abs(s[e]-m[e]));if(m=s,.01>l)break}return m}(n,i,t,o,s,a,r):[...a];if("hug"===r.lanePlacement){const o=t=>{const o={};for(const n of e)o[n.id]=t[i[n.id]];return o};ti(o(l),t)>ti(o(a),t)+1e-6&&(l=[...a])}const c={};for(const t of e)c[t.id]=l[i[t.id]];let u=1/0,d=-1/0;for(const t of e){const e=c[t.id],n=o[t.id];Number.isFinite(e)&&n&&(u=Math.min(u,e-n.topPeak*r.valueScale),d=Math.max(d,e+n.botPeak*r.valueScale))}return{adjacentClearance:s,centerlines:c,slotCenter:l,stackCenter:a,verticalUtilization:Number.isFinite(u)&&Number.isFinite(d)&&r.plotH>0?Math.max(0,Math.min(1,(d-u)/r.plotH)):0}}function ti(e,t){let o=0;for(const n of t){const t=e[n.source],i=e[n.target];Number.isFinite(t)&&Number.isFinite(i)&&(o+=Math.abs(t-i)*(n.value>0?n.value:1))}return o}function oi(e,t){const o=e?.samples;if(!o||0===o.length||o[0].t>t)return{top:0,bot:0};let n=0,i=o.length-1,r=0;for(;i>=n;){const e=n+i>>>1;o[e].t>t?i=e-1:(r=e,n=e+1)}const s=o[r].boundaryOffset??0;return{top:o[r].topMass-s,bot:o[r].botMass+s}}function ni(e,t,o,n,i){const r=1-i;return r*r*r*e+3*r*r*i*t+3*r*i*i*o+i*i*i*n}function ii(e,t){let o=0,n=1;for(let i=0;28>i;i++){const i=(o+n)/2;e>ni(0,t,t,1,i)?o=i:n=i}return(o+n)/2}function ri(e,t,o){const n=t+Jn(e,o),i=e.value*o/2;return[n-i,n+i]}function si(e,t,o,n){return Math.max(0,Math.min(t,n)-Math.max(e,o))/Math.max(1e-9,t-e)}function ai(e,t,o,n,i,r,s){const{valueScale:a,domain:l,mode:c="quality"}=s,u="source"===s.ribbonLane?.85:"target"===s.ribbonLane?.15:.5;let d=0;for(const s of e){const e=n[s.source],h=n[s.target];if(null==e||null==h||2>Math.abs(e-h))continue;const p=t[s.source]?.localAttachments.get(s.id),g=t[s.target]?.localAttachments.get(s.id);if(!p||!g)continue;const m=Math.max(s.startTime,l?.[0]??-1/0),f=Math.min(s.endTime,l?.[1]??1/0);if(m>=f)continue;const[y,b]=ri(p,i[s.source],a),[x,v]=ri(g,i[s.target],a),w=Math.min(e,h)+1,A=Math.max(e,h)-1;for(let e=w;A>=e;e++){const n=o[e];if(!n)continue;const l=[m,f];if("quality"===c)for(const e of n.occupants)for(const o of t[e.id]?.samples??[])o.t>m&&f>o.t&&l.push(o.t);const h=e=>{const o=ii((e-m)/(f-m),u),l=ni(y,y,x,x,o),c=ni(b,b,v,v,o);let d=0;for(const o of n.occupants){if(o.id===s.source||o.id===s.target)continue;const n=r[o.id];if(null!=n?.start&&n.start>e)continue;if(null!=n?.end&&e>n.end)continue;const u=oi(t[o.id],e),h=i[o.id];d=Math.max(d,si(l,c,h-u.top*a,h+u.bot*a))}return d},p=[...new Set(l)].sort((e,t)=>e-t);let g=0;for(let e=0;p.length-1>e;e++){const t=p[e],o=p[e+1]-t;g+=(h(t+.25*o)+h(t+.5*o)+h(t+.75*o))/3*o}d+=g/(f-m)*(s.value>0?s.value:1)}}return d}function li(e,t,o,n,i,r,s,a,l,c,u="both",d){return{crossings:e,weightedLength:t,pixelLength:ti(s,o),transitOcclusion:ai(o,n,i,r,s,a,{valueScale:l,ribbonLane:u,domain:d,mode:"quality"}),verticalUtilization:c}}function ci(e,t){return t?Math.max(t[0],Math.min(t[1],e)):e}function ui(e,t){return e.map(e=>({t:ci(e.t,t),topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}}))}function di(e,t,o){const n=t+(e.boundaryOffset??0)*o,i=e.value*o;if("out"===e.kind){const t=e.sideMassBefore*o;if("top"===e.side){const e=n-t;return[e,e+i]}const r=n+t;return[r-i,r]}const r=e.sideMassAfter*o;if("top"===e.side){const e=n-r;return[e,e+i]}const s=n+r;return[s-i,s]}function hi(e,t,o,n,i="temporal"){const r=t.incoming[e.id],s=t.outgoing[e.id],a=[];for(const e of r)a.push({time:e.endTime,delta:+e.value,edge:e,kind:"in",side:o.get(e.id).targetSide});for(const e of s)a.push({time:e.startTime,delta:-e.value,edge:e,kind:"out",side:o.get(e.id).sourceSide});const l={create:0,in:1,"transfer-out":2,"transfer-in":3,out:4},c=()=>{a.sort((e,t)=>e.time-t.time||(e.phase??0)-(t.phase??0)||(e.sequence??0)-(t.sequence??0)||(l[e.kind]??99)-(l[t.kind]??99)||((e,t)=>{if(!n||!e.edge||!t.edge||e.kind!==t.kind||e.side!==t.side)return 0;if("out"===e.kind){if(e.edge.target===t.edge.target&&e.edge.endTime===t.edge.endTime)return 0;const o=n.get(e.edge.id)?.target,i=n.get(t.edge.id)?.target;return"number"==typeof o&&Number.isFinite(o)&&"number"==typeof i&&Number.isFinite(i)&&o!==i?"top"===e.side?o-i:i-o:0}if("in"===e.kind){if(e.edge.source===t.edge.source&&e.edge.startTime===t.edge.startTime)return 0;const o=n.get(e.edge.id)?.source,i=n.get(t.edge.id)?.source;return"number"==typeof o&&Number.isFinite(o)&&"number"==typeof i&&Number.isFinite(i)&&o!==i?"top"===e.side?i-o:o-i:0}return 0})(e,t)||qn(e.edge?.id??"",t.edge?.id??"")||qn(e.side,t.side)||e.delta-t.delta)},u=a.length?Ft(a.map(e=>e.time)):null,d=Array.isArray(e.xExtent)&&Number.isFinite(e.xExtent[0])?e.xExtent[0]:null,h=null!=d?d-1:null!=u&&Number.isFinite(u)?u-1:null;c();let p=null,g=0;for(const e of a)e.time!==p&&(p=e.time,g=0),e.sequence=g++;const m=e=>({time:e.time,phase:0,sequence:e.sequence??0}),f=[];let y=0,b=0;for(const e of a)if("out"===e.kind){const t=Math.abs(e.delta);let o=t-("top"===e.side?y:b);if(o>0){const t="top"===e.side?"bot":"top",n=Math.min(o,"top"===t?y:b);if(n>0){const i=m(e);f.push({...i,delta:-n,kind:"transfer-out",side:t}),f.push({...i,delta:+n,kind:"transfer-in",side:e.side}),"top"===t?y-=n:b-=n,"top"===e.side?y+=n:b+=n,o-=n}o>0&&null!==h&&(f.push({time:h,delta:+o,kind:"create",side:e.side}),"top"===e.side?y+=o:b+=o)}"top"===e.side?y-=t:b-=t}else if("in"===e.kind){const t=Math.abs(e.delta);"top"===e.side?y+=t:b+=t}a.push(...f),c();let x=0,v=0,w=0,A=0,S=0,k=0;const M=[],_=new Map,P=e=>{M.push({t:e,topMass:x,botMass:v,...Math.abs(w)>1e-12&&{boundaryOffset:w}})},T=()=>{A=Math.max(A,x+v),S=Math.max(S,x-w),k=Math.max(k,v+w)};for(const e of a){if("transfer-out"!==e.kind&&"transfer-in"!==e.kind&&P(e.time),("in"===e.kind||"out"===e.kind)&&e.edge){const t="top"===e.side?x:v;_.set(e.edge.id,{side:e.side,time:e.time,sideMassBefore:t,sideMassAfter:t+e.delta,kind:e.kind,value:Math.abs(e.delta),...Math.abs(w)>1e-12&&{boundaryOffset:w}})}"top"===e.side?x+=e.delta:v+=e.delta,"transfer-in"===e.kind?(w+="top"===e.side?e.delta:-e.delta,T(),P(e.time)):"transfer-out"!==e.kind&&(T(),"out"!==e.kind||x+v>1e-12||(w=0),P(e.time))}const L=[];let R=0;for(;M.length>R;){let e=R;for(;M.length>e+1&&M[e+1].t===M[R].t;)e++;L.push(M[R]);for(let t=R+1;e>=t;t++){const e=L[L.length-1];M[t].topMass===e.topMass&&M[t].botMass===e.botMass&&(M[t].boundaryOffset??0)===(e.boundaryOffset??0)||L.push(M[t])}R=e+1}const I=Array.isArray(e.xExtent)&&Number.isFinite(e.xExtent[1])?e.xExtent[1]:null;let C=null;for(const e of s)null!=e.systemInTime&&Number.isFinite(e.systemInTime)&&e.startTime>e.systemInTime&&(null===C||C>e.systemInTime)&&(C=e.systemInTime);let z=null;for(const e of r)null!=e.systemOutTime&&Number.isFinite(e.systemOutTime)&&e.systemOutTime>e.endTime&&(null===z||e.systemOutTime>z)&&(z=e.systemOutTime);if(L.length>0){const e=L[L.length-1],t=Math.max(null!=I?I:-1/0,null!=z?z:-1/0);Number.isFinite(t)&&t>e.t&&e.topMass+e.botMass>0&&L.push({t:t,topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}});const o=L[0],n=L.find(e=>e.topMass+e.botMass>0);let i,r=1/0;null!=d&&Number.isFinite(d)&&o.t>d&&o.topMass+o.botMass>0&&(r=d,i=o),n&&null!=C&&Number.isFinite(C)&&n.t>C&&r>C&&(r=C,i=n),i&&Number.isFinite(r)&&L.unshift({t:r,topMass:i.topMass,botMass:i.botMass,...null!=i.boundaryOffset&&{boundaryOffset:i.boundaryOffset}})}let F=L;if("max"===i&&null!=d&&null!=I&&I>d){let e,t=0;for(const o of L){const n=o.topMass+o.botMass;n>t&&(t=n,e=o)}if(e){const t={topMass:e.topMass,botMass:e.botMass,...null!=e.boundaryOffset&&{boundaryOffset:e.boundaryOffset}};F=[...L.filter(e=>d>e.t),{t:d,...t},{t:I,...t},...L.filter(e=>e.t>I)]}}return{samples:F,peak:A,topPeak:S,botPeak:k,localAttachments:_}}function pi(e){const t={};return e.forEach((e,o)=>{for(const n of e.occupants)t[n.id]=o}),t}function gi(e,t,o){e.splice(0,e.length,...o);const n=pi(o);for(const e of Object.keys(t))delete t[e];Object.assign(t,n)}function mi(e){const t=new Map,o=[];e.forEach((e,n)=>{if(!e.group)return void o.push({anchor:n,stableId:Un(e),slots:[e]});const i=t.get(e.group)??{indexes:[],slots:[]};i.indexes.push(n),i.slots.push(e),t.set(e.group,i)});for(const[e,n]of t)o.push({anchor:n.indexes.reduce((e,t)=>e+t,0)/n.indexes.length,stableId:`${e}\0${n.slots.map(Un).join("\0")}`,slots:n.slots});return o.sort((e,t)=>e.anchor-t.anchor||qn(e.stableId,t.stableId))}function fi(e){return e.some(e=>e.group)?mi(e).flatMap(e=>e.slots):[...e]}function yi(e){return e.flatMap(e=>e.slots)}function bi(e,t,o){const n=new Map;return e.forEach((e,t)=>{for(const o of e.slots)n.set(o,t)}),e.map((e,i)=>{if(1>=e.slots.length)return e;const r=new Map;for(const t of e.slots)r.set(t,0);for(const e of t){const t=n.get(e.source),o=n.get(e.target);if(null==t||null==o)continue;const s=Number.isFinite(e.weight)&&e.weight>0?e.weight:1;if(t===i&&o!==i){const t=o>i?1:-1;r.set(e.source,(r.get(e.source)??0)+s*t)}else if(o===i&&t!==i){const o=t>i?1:-1;r.set(e.target,(r.get(e.target)??0)+s*o)}}const s=[...e.slots].sort((e,t)=>(r.get(e)??0)-(r.get(t)??0)||o(e,t));return{...e,slots:s}})}function xi(e,t){e.some(e=>e.group)&&gi(e,t,fi(e))}function vi(e,t){return e.source!==t.source&&e.target!==t.target&&e.source!==t.target&&e.target!==t.source&&Math.min(e.endTime,t.endTime)>Math.max(e.startTime,t.startTime)}function wi(e,t){return y(t,t=>[e[t.source],e[t.target]],vi)}function Ai(e,t){let o=0;for(const n of t){const t=e[n.source],i=e[n.target];null!=t&&null!=i&&(o+=Math.abs(t-i)*(n.value>0?n.value:1))}return o}function Si(e,t,o){const[n,i]=o.get(e.first),[r,s]=o.get(e.second);return 0>(t.get(n)-t.get(r))*(t.get(i)-t.get(s))?1:0}var ki=e=>{let t=1;for(let o=2;e>=o;o++)t*=o;return t},Mi=828*ki(8),_i=3e3;function Pi(e,t,o,n,i,r,s){const a=[...i],l=new Map(i.map(e=>[e,Un(e)])),c=new Map;for(const e of i)for(const t of e.occupants)c.set(t.id,e);const u=new Map,d=[];for(const e of t){const t=c.get(e.source),o=c.get(e.target);t&&o&&(u.set(e,[t,o]),t!==o&&d.push({source:t,target:o,weight:e.value}))}const h=[];for(let e=0;t.length>e;e++)if(u.has(t[e]))for(let o=e+1;t.length>o;o++){if(!u.has(t[o])||!vi(t[e],t[o]))continue;const n=new Set([...u.get(t[e]),...u.get(t[o])]);h.push({index:h.length,first:t[e],second:t[o],involvedSlots:n})}const p=new Map;for(const e of i)p.set(e,[]);for(const e of h)for(const t of e.involvedSlots)p.get(t)?.push(e);const g=new Uint32Array(h.length);let m=0;const f=t.reduce((e,t)=>e+(t.value>0?t.value:1),0),y=s.plotH/Math.max(1,i.length),b=i.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),x=Math.max(1,f)*(Math.max(1,s.plotH)+y*Math.max(b,i.length)+1e-6*Math.max(1,i.length-1))+1,S=4*y,k={fullCrossing:0,localCrossing:0},M=new Map,_=(e,t)=>{let n=M.get(e);n||(n=new Map,M.set(e,n));const i=n.get(t);if(null!=i)return i;const r=function(e,t,o){return A(Zn([e,t],o)).adjacentClearance[0]??0}(e,t,o);return n.set(t,r),r},T=new Map(i.map((e,t)=>[e,t])),L=t.flatMap(e=>{const t=u.get(e);return t?[{source:T.get(t[0]),target:T.get(t[1]),weight:e.value>0?e.value:1}]:[]}),R=new Map;for(const e of t){const t=u.get(e);t&&R.set(e,{source:T.get(t[0]),target:T.get(t[1])})}const I=new Map,C=new Map;for(const e of t)I.has(e.source)||I.set(e.source,new Set),C.has(e.target)||C.set(e.target,new Set),I.get(e.source).add(e.target),C.get(e.target).add(e.source);const z=t.flatMap(e=>{if(!(e=>{const t=new Set([...I.get(e.source)??[],...C.get(e.source)??[]]),o=new Set([...I.get(e.target)??[],...C.get(e.target)??[]]);return 1===I.get(e.source)?.size&&I.get(e.source).has(e.target)||1===t.size&&t.has(e.target)||1===o.size&&o.has(e.source)})(e))return[];const t=R.get(e);return t&&t.source!==t.target?[{source:t.source,target:t.target,weight:e.value>0?e.value:1}]:[]}),F=e=>{let t=0;for(const o of z)t+=Math.max(0,Math.abs(e[o.source]-e[o.target])-1)*o.weight;return t*S},O=e=>{const t=new Int16Array(i.length);for(let o=0;e.length>o;o++)t[T.get(e[o])]=o;return F(t)},B=h.map(e=>{const t=R.get(e.first),o=R.get(e.second);return[t.source,t.target,o.source,o.target]}),N=new Int16Array(i.length),E=new Float64Array(i.length),j=new Float64Array(i.length+1),$=e=>{for(let t=0;e.length>t;t++)N[T.get(e[t])]=t;let t=0;for(const[e,o,n,i]of B)0>(N[e]-N[n])*(N[o]-N[i])&&t++;if(e.length>0){const t=T.get(e[0]);E[t]=s.padding+e[0].peak.topPeak*s.valueScale;for(let t=1;e.length>t;t++){const o=T.get(e[t-1]),n=T.get(e[t]);E[n]=E[o]+_(e[t-1],e[t])*s.valueScale+s.padding}const o=T.get(e[e.length-1]),n=E[o]+e[e.length-1].peak.botPeak*s.valueScale+s.padding;if(n>s.plotH&&n>0){const e=s.plotH/n;for(let t=0;E.length>t;t++)E[t]*=e}}j[0]=0;for(let t=0;e.length>t;t++)j[t+1]=j[t]+e[t].peak.topPeak+e[t].peak.botPeak;let o=0,n=0,i=0;for(const e of L){const t=N[e.source],r=N[e.target];if(o+=Math.abs(t-r)*e.weight,n+=Math.abs(E[e.source]-E[e.target])*e.weight,Math.abs(t-r)>=2){const o=Math.min(t,r)+1;i+=(j[Math.max(t,r)]-j[o])*e.weight}}return t*x+n+i*y+F(N)+1e-6*o},D=(e,o)=>{const n=Array(e.length+1).fill(0);for(let t=0;e.length>t;t++)n[t+1]=n[t]+e[t].peak.topPeak+e[t].peak.botPeak;let i=0;for(const e of t){const t=o[e.source],r=o[e.target];if(null==t||null==r||2>Math.abs(t-r))continue;const s=Math.min(t,r)+1;i+=(n[Math.max(t,r)]-n[s])*(e.value>0?e.value:1)}return i},W=n=>{const i=pi(n),r=n.slice(0,-1).map((e,t)=>_(e,n[t+1])),a=ei(e,t,o,n,i,{plotH:s.plotH,padding:s.padding,valueScale:s.valueScale,lanePlacement:s.lanePlacement??"stack",groupPadding:s.groupPadding,adjacentClearance:r});return{map:i,geometry:a,weightedLength:Ai(i,t),pixelLength:ti(a.centerlines,t),transitOcclusion:D(n,i)}},Y=(e,t,o)=>({crossings:e,weightedLength:t.weightedLength,pixelLength:t.pixelLength,transitOcclusion:t.transitOcclusion,cost:e*x+t.pixelLength+t.transitOcclusion*y+O(o)+1e-6*t.weightedLength}),V=(e,t)=>{let o=t;if(null==o){const t=new Map(e.map((e,t)=>[e,t]));o=h.reduce((e,o)=>e+Si(o,t,u),0),k.fullCrossing++}return Y(o,W(e),e)},H=(e,i,r="quality")=>{let a=i;if(null==a){const t=new Map(e.map((e,t)=>[e,t]));a=h.reduce((e,o)=>e+Si(o,t,u),0),k.fullCrossing++}const l=W(e);return Y(a,{...l,transitOcclusion:ai(t,o,e,l.map,l.geometry.centerlines,n,{valueScale:s.valueScale,ribbonLane:s.ribbonLane,domain:s.domain,mode:r})},e)};let G=[...a];const X=(e,t)=>qn(l.get(e),l.get(t)),q=function(e){const t=new Set;for(const o of e)if(o.group){if(t.has(o.group))return!0;t.add(o.group)}return!1}(G),U=e=>{const t=(e=>{const t=v(e,d,e=>V(e).cost,{passes:6,compare:X,maxEvaluations:_i});let o=V(t),n=_i;for(let e=0;6>e&&n>0;e++){let i=!1;const r=Array.from({length:t.length-1},(e,t)=>t);e%2==1&&r.reverse();for(const e of r){if(0>=n--)break;const r=t[e],s=t[e+1],a=new Map(t.map((e,t)=>[e,t]));let l=0;const c=[];m++;for(const e of[...p.get(r)??[],...p.get(s)??[]])g[e.index]!==m&&(g[e.index]=m,c.push(e),l+=Si(e,a,u));[t[e],t[e+1]]=[s,r];const d=new Map(a);d.set(r,e+1),d.set(s,e);let h=0;for(const e of c)h+=Si(e,d,u);k.localCrossing+=c.length;const f=V(t,o.crossings-l+h);o.cost>f.cost?(o=f,i=!0):[t[e],t[e+1]]=[r,s]}if(!i)break}return t})(e);if((e.length>8?1/0:ki(e.length)*(e.length+L.length+B.length))>Mi)return t;const o=w(e,$,{maxItems:8,maxEvaluations:5e4}),n=H(o),i=H(t);return n.crossings!==i.crossings&&i.crossings>n.crossings?o:t},Q="geometry-refine"===s.mode;if(Q||"crossing-min"!==s.laneOrder&&"crossing-min+inside-out"!==s.laneOrder){if(!Q&&"inside-out"===s.laneOrder)if(q){const e=mi(G),t=e=>e.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),o=[...e].sort((e,o)=>t(o)-t(e)||qn(e.stableId,o.stableId)),n=Array(o.length);let i=Math.floor((o.length-1)/2)-1,r=Math.floor((o.length-1)/2)+1;o.length>0&&(n[Math.floor((o.length-1)/2)]=o[0]);for(let e=1;o.length>e;e++)e%2==1&&o.length>r||0>i?n[r++]=o[e]:n[i--]=o[e];G=yi(n)}else{const e=[...G].sort((e,t)=>t.peak.topPeak+t.peak.botPeak-(e.peak.topPeak+e.peak.botPeak)||X(e,t)),t=Array(e.length);let o=Math.floor((e.length-1)/2)-1,n=Math.floor((e.length-1)/2)+1;e.length>0&&(t[Math.floor((e.length-1)/2)]=e[0]);for(let i=1;e.length>i;i++)i%2==1&&e.length>n||0>o?t[n++]=e[i]:t[o--]=e[i];G=t}}else G=q?(e=>{let t=mi(e);if(1>=t.length)return yi(t);const o=e=>V(yi(e)).cost;t=mi(U(e)),t=bi(t,d,X);const n=function(e,t){const o=new Map;for(const t of e)for(const e of t.slots)o.set(e,t);const n=new Map;for(const e of t){const t=o.get(e.source),i=o.get(e.target);if(!t||!i||t===i)continue;const r=Number.isFinite(e.weight)&&e.weight>0?e.weight:1,s=i.stableId>t.stableId?`${t.stableId}\0${i.stableId}`:`${i.stableId}\0${t.stableId}`,a=n.get(s);a?a.weight=(a.weight??0)+r:n.set(s,{source:t,target:i,weight:r})}return[...n.values()]}(t,d);t=v(t,n,o,{passes:6,compare:(e,t)=>qn(e.stableId,t.stableId),maxEvaluations:_i}),t=P(t,o,{passes:8,maxEvaluations:_i});const i=t.length>8?1/0:ki(t.length)*(t.length+L.length+B.length);if(Mi>=i){const e=w(t,e=>$(yi(e)),{maxItems:8,maxEvaluations:5e4}),o=yi(e),n=yi(t),i=H(o),r=H(n);i.crossings!==r.crossings?t=r.crossings>i.crossings?e:t:r.cost>i.cost&&(t=e)}return t=bi(t,d,X),yi(t)})(G):U(G);if(!Q&&"crossing-min+inside-out"===s.laneOrder&&G.length>1)if(q){const e=mi(G);let t=V(yi(e)),o=yi(e),n=t;const i=Math.floor((e.length-1)/2),r=e=>e.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),s=[...e].sort((e,t)=>r(t)-r(e)||qn(e.stableId,t.stableId));for(const r of s){const s=e.indexOf(r);if(s===i)continue;e.splice(s,1),e.splice(i,0,r);const a=yi(e),l=V(a);l.cost>t.cost?(e.splice(i,1),e.splice(s,0,r)):(t=l,n.cost>l.cost&&(o=a,n=l))}G=o}else{let e=V(G),t=[...G],o=e;const n=Math.floor((G.length-1)/2),i=[...G].sort((e,t)=>t.peak.topPeak+t.peak.botPeak-(e.peak.topPeak+e.peak.botPeak)||X(e,t));for(const r of i){const i=G.indexOf(r);if(i===n)continue;G.splice(i,1),G.splice(n,0,r);const s=V(G);s.cost>e.cost?(G.splice(n,1),G.splice(i,0,r)):(e=s,o.cost>s.cost&&(t=[...G],o=s))}G=t}if((Q||"crossing-min"===s.laneOrder||"crossing-min+inside-out"===s.laneOrder)&&G.length>1)if(q){let e=mi(G),t=H(yi(e),void 0,"score");for(let o=0;6>o&&e.length>1;o++){let o=!1;for(let n=0;e.length-1>n;n++){[e[n],e[n+1]]=[e[n+1],e[n]];const i=yi(e),r=H(i,void 0,"score");t.cost>r.cost?(G=i,t=r,o=!0):[e[n],e[n+1]]=[e[n+1],e[n]]}if(!o)break}e=bi(mi(G),d,X),G=yi(e)}else{let e=H(G,void 0,"score");for(let t=0;G.length-1>t;t++){const o=G[t],n=G[t+1],i=new Map(G.map((e,t)=>[e,t]));let r=0;const s=[];m++;for(const e of[...p.get(o)??[],...p.get(n)??[]])g[e.index]!==m&&(g[e.index]=m,s.push(e),r+=Si(e,i,u));[G[t],G[t+1]]=[n,o];const a=new Map(i);a.set(o,t+1),a.set(n,t);let l=0;for(const e of s)l+=Si(e,a,u);k.localCrossing+=s.length;const c=H(G,e.crossings-r+l,"score");e.cost>c.cost?e=c:[G[t],G[t+1]]=[o,n]}}const Z=fi(a);G=fi(G);let K=H(G);const J=H(Z);if(Q){const e=O(Z),t=O(G);(K.crossings>J.crossings||K.crossings===J.crossings&&t>e+1e-9||K.cost>J.cost)&&(G=Z,K=J)}else K.cost>J.cost&&(G=Z,K=J);return gi(i,r,G),{before:J,after:K,initialOrder:a.map(e=>l.get(e)),evaluations:k}}function Ti(e,t,o){const n=e.map(e=>{const n=e.occupants.map(e=>({id:e.id,end:o[e.id]?.end??e.end}));let i=0,r=0;for(const e of n){const o=t[e.id];i=Math.max(i,o?.topPeak||0),r=Math.max(r,o?.botPeak||0)}return{occupants:n,peak:{topPeak:i,botPeak:r},...null!=e.group?{group:e.group}:{}}}),i={};return n.forEach((e,t)=>{for(const o of e.occupants)i[o.id]=t}),{slots:n,slotByNode:i}}var Li=new Map,Ri=1e-9,Ii=1e5;function Ci(e,t){let o=1/0,n=-1/0;for(const t of e?.samples??[])t.topMass+t.botMass>Ri&&(o=Math.min(o,t.t),n=Math.max(n,t.t));return Number.isFinite(o)&&Number.isFinite(n)?(null!=t.start&&(o=Math.max(o,t.start)),null!=t.end&&(n=Math.min(n,t.end)),o>n?{start:null,end:null}:{start:o,end:n}):{start:null,end:null}}function zi(e,t){return null!=e.start&&null!=e.end&&null!=t.start&&null!=t.end&&!(t.start>=e.end||e.start>=t.end)}function Fi(e,t){return qn(e,t)>0?`${t}\0${e}`:`${e}\0${t}`}function Oi(e){const t=new Map,o=new Map;for(const n of e)o.has(n.source)||o.set(n.source,new Set),t.has(n.target)||t.set(n.target,new Set),o.get(n.source).add(n.target),t.get(n.target).add(n.source);return{incoming:new Map([...t].map(([e,t])=>[e,t.size])),outgoing:new Map([...o].map(([e,t])=>[e,t.size]))}}function Bi(e){const t=new Map,o=new Map,n=(e,t,o,n)=>{let i=e.get(t);i||(i=new Map,e.set(t,i)),i.set(o,(i.get(o)??0)+n)};for(const i of e){const e=i.value>0&&Number.isFinite(i.value)?i.value:1;n(t,i.source,i.target,e),n(o,i.target,i.source,e)}const i=new Map,r=e=>{if(i.has(e))return;const n=t.get(e),r=o.get(e);if(n&&1===n.size&&(!r||0===r.size)){const[t,o]=[...n][0];return void i.set(e,{partner:t,weight:o})}const s=new Map;for(const[e,t]of n??[])s.set(e,(s.get(e)??0)+t);for(const[e,t]of r??[])s.set(e,(s.get(e)??0)+t);if(1===s.size){const[t,o]=[...s][0];i.set(e,{partner:t,weight:o})}};for(const t of e)r(t.source),r(t.target);return i}function Ni(e,t,o){const n=o.get(e),i=o.get(t);return!n||!i||n.partner===i.partner||n.partner===t||i.partner===e}function Ei(e,t,o){return!!o.has(e)&&t.some(t=>!Ni(e,t,o))}function ji(e,t){return(e.value>0&&Number.isFinite(e.value)?e.value:1)*(1+(1===t.outgoing.get(e.source)?1:0)+(1===t.incoming.get(e.target)?1:0))}function $i(e,t,o,n){if(12>=e.length||1>=n.slotCount)return n.assignment;const i=new Map(e.map((e,t)=>[e,t])),r=Array.from({length:e.length},()=>new Map),s=Oi(o);for(const e of o){const t=i.get(e.source),o=i.get(e.target);if(null==t||null==o||t===o)continue;const n=ji(e,s);r[t].set(o,(r[t].get(o)??0)+n),r[o].set(t,(r[o].get(t)??0)+n)}const a=Bi(o),l=e.map(e=>a.get(e)?.weight??0),c=Array.from({length:e.length},()=>new Map);let u=0;for(let o=0;e.length-1>o&&5e4>u;o++)if(a.has(e[o]))for(let n=o+1;e.length>n;n++){if(!a.has(e[n]))continue;if(t.conflicts(e[o],e[n]))continue;u++;const i=Math.min(l[o],l[n])||Math.max(l[o],l[n]),r=Ni(e[o],e[n],a)?i:-i;if(Math.abs(r)>Ri&&(c[o].set(n,r),c[n].set(o,r),u>=5e4))break}const d=[...n.assignment],h=Array.from({length:n.slotCount},()=>[]);d.forEach((e,t)=>h[e].push(t));const p=(e,t,o)=>{const n=d[t],i=d[o];let r=0;const s=new Set;for(const a of[t,o])for(const[l,c]of e[a]){const e=l>a?`${a}:${l}`:`${l}:${a}`;if(s.has(e))continue;s.add(e);const u=(a===t?i:n)===(l===t?i:l===o?n:d[l]);d[a]===d[l]!==u&&(r+=u?c:-c)}return r},g=(e,t,o)=>{let n=0;for(const[i,r]of e[t]){const e=o===d[i];d[t]===d[i]!==e&&(n+=e?r:-r)}return n},m=(e,t)=>e>Ri||Ri>=Math.abs(e)&&t>Ri,f=(e,t,o,n)=>e>o+Ri||Ri>=Math.abs(e-o)&&t>n+Ri;let y=0;for(let o=0;32>o&&Ii>y;o++){let o=null,n=-1,i=-1,s=-1,a=-1/0,l=-1/0;for(let u=0;e.length>u;u++){for(let p=0;h.length>p&&y++<Ii;p++){if(p===d[u])continue;if(!h[p].every(o=>!t.conflicts(e[u],e[o])))continue;const y=g(r,u,p),b=g(c,u,p);m(y,b)&&f(y,b,a,l)&&(o="move",n=u,i=-1,s=p,a=y,l=b)}if(y>=Ii)break}for(let u=0;e.length-1>u;u++){for(let g=u+1;e.length>g&&y++<Ii;g++){const y=d[u],b=d[g];if(y===b)continue;if(!h[b].every(o=>o===g||!t.conflicts(e[u],e[o])))continue;if(!h[y].every(o=>o===u||!t.conflicts(e[g],e[o])))continue;const x=p(r,u,g),v=p(c,u,g);m(x,v)&&f(x,v,a,l)&&(o="swap",n=u,i=g,s=-1,a=x,l=v)}if(y>=Ii)break}if(null==o||-1===n)break;if("move"===o){const e=d[n];h[e].splice(h[e].indexOf(n),1),h[s].push(n),d[n]=s;continue}const u=d[n],b=d[i];h[u].splice(h[u].indexOf(n),1,i),h[b].splice(h[b].indexOf(i),1,n),d[n]=b,d[i]=u}return d}function Di(e,t,o,n){const i=function(e,t,o,n){return`${e.map(e=>{const t=o[e.id],i=n[e.id];return[e.id,e.group??"",e.xExtent?.[0]??"",e.xExtent?.[1]??"",t?.topPeak??0,t?.botPeak??0,i?.start??"",i?.end??""].join(":")}).join("|")}#${t.map(e=>[e.id,e.source,e.target,e.value,e.startTime,e.endTime].join(":")).join("|")}`}(e,t,o,n),r=Li.get(i);if(r)return Ti(r.slots,o,n);const s={};for(const t of e)s[t.id]=Ci(o[t.id],n[t.id]);const a=function(e,t){return e.filter(e=>null!=t[e.id].start).sort((e,o)=>t[e.id].start-t[o.id].start||t[e.id].end-t[o.id].end||qn(e.id,o.id)).map(e=>e.id)}(e,s),l=new Map(e.map(e=>[e.id,e])),c=new Map(e.map(e=>[e.id,e.group||void 0])),u=function(e,t,o,n,i){const r=new Set,s=new Map(e.map(e=>[e,new Set])),a=new Map(e.map(e=>[e,new Set]));for(const e of n)r.add(Fi(e.source,e.target)),s.get(e.target)?.add(e.source),a.get(e.source)?.add(e.target);const l=new Map,c=new Set,u=(e,t)=>{for(let o=0;e.length>o;o++)for(let n=o+1;e.length>n;n++){const i=Fi(e[o],e[n]);t instanceof Map?t.set(i,[e[o],e[n]]):t.add(i)}};for(const e of a.values())u([...e],l);for(const e of s.values())u([...e],c);const d=new Set;for(const[e,[n,i]]of l)c.has(e)&&(zi(t[n],t[i])||zi(o[n],o[i])&&(d.add(n),d.add(i)));return{conflicts:(e,o)=>{const n=i.get(e),s=i.get(o);return null!=n&&null!=s&&n!==s||null!=n!=(null!=s)&&!r.has(Fi(e,o))||!!zi(t[e],t[o])||!(!d.has(e)&&!d.has(o))&&!r.has(Fi(e,o))}}}(a,s,n,t,c),d=function(e,t,o=new Map){const n=[],i=[];for(const r of e){let e=n.findIndex(e=>e.every(e=>!t.conflicts(r,e))&&!Ei(r,e,o));-1!==e||o.has(r)||(e=n.findIndex(e=>e.every(e=>!t.conflicts(r,e)))),-1===e&&(e=n.length,n.push([])),n[e].push(r),i.push(e)}return{assignment:i,slotCount:n.length}}(a,u,Bi(t)),h=function(e,t,o,n){if(0===e.length||e.length>12||1>=n.slotCount)return n.assignment;const i=new Map(e.map((e,t)=>[e,t])),r=Array.from({length:e.length},()=>new Float64Array(e.length)),s=Array.from({length:e.length},()=>new Map),a=Array.from({length:e.length},()=>new Map),l=Oi(o);for(const e of o){const t=i.get(e.source),o=i.get(e.target);if(null==t||null==o||t===o)continue;const n=ji(e,l);r[t][o]+=n,r[o][t]+=n,a[t].set(o,(a[t].get(o)??0)+n),s[o].set(t,(s[o].get(t)??0)+n)}const c=Bi(o),u=e.map(e=>c.get(e)?.weight??0),d=Array.from({length:e.length},()=>new Float64Array(e.length));for(let t=0;e.length>t;t++)for(let o=t+1;e.length>o;o++){for(const[e,n]of s[t])d[t][o]+=Math.min(n,s[o].get(e)??0);for(const[e,n]of a[t])d[t][o]+=Math.min(n,a[o].get(e)??0);if(c.has(e[t])&&c.has(e[o])){const n=Math.min(u[t],u[o])||Math.max(u[t],u[o]);d[t][o]+=Ni(e[t],e[o],c)?n:-n}d[o][t]=d[t][o]}let h=[...n.assignment],p=(t=>{let o=0,n=0;for(let i=0;e.length>i;i++)for(let s=i+1;e.length>s;s++)t[i]===t[s]&&(o+=r[i][s],n+=d[i][s]);return{flow:o,affinity:n}})(h),g=0;const m=Array(e.length).fill(-1),f=Array.from({length:n.slotCount},()=>[]),y=(o,i,s,a)=>{if(g>=75e3)return;if(o===e.length)return g++,void((s>p.flow||s===p.flow&&a>p.affinity||s===p.flow&&a===p.affinity&&function(e,t){for(let o=0;Math.min(e.length,t.length)>o;o++)if(e[o]!==t[o])return t[o]>e[o];return t.length>e.length}(m,h))&&(h=[...m],p={flow:s,affinity:a}));const l=Math.min(i+1,n.slotCount-1);for(let n=0;l>=n;n++){if(f[n].some(n=>t.conflicts(e[o],e[n])))continue;let l=0,c=0;for(const e of f[n])l+=r[o][e],c+=d[o][e];if(m[o]=n,f[n].push(o),y(o+1,Math.max(i,n),s+l,a+c),f[n].pop(),m[o]=-1,g>=75e3)return}};return m[0]=0,f[0].push(0),y(1,0,0,0),h}(a,u,t,{...d,assignment:$i(a,u,t,d)}),p=new Map,g=h.map(e=>(p.has(e)||p.set(e,p.size),p.get(e))),m=Array.from({length:p.size||(e.length>0?1:0)},()=>({occupants:[],peak:{topPeak:0,botPeak:0}})),f={};a.forEach((e,t)=>{const o=g[t],n=m[o];n.occupants.push({id:e,end:s[e].end??-1/0});const i=l.get(e)?.group;i&&(n.group=i),f[e]=o});for(const t of[...e].sort((e,t)=>qn(e.id,t.id)))null==f[t.id]&&(m[0].occupants.push({id:t.id,end:-1/0}),f[t.id]=0);for(const e of m){e.occupants.sort((e,t)=>(s[e.id].start??1/0)-(s[t.id].start??1/0)||qn(e.id,t.id));for(const t of e.occupants){const n=o[t.id];e.peak.topPeak=Math.max(e.peak.topPeak,n?.topPeak||0),e.peak.botPeak=Math.max(e.peak.botPeak,n?.botPeak||0)}}const y={slots:m,slotByNode:f};return function(e,t){for(Li.has(e)&&Li.delete(e),Li.set(e,{slots:t.slots.map(e=>({occupants:e.occupants.map(e=>({...e})),peak:{...e.peak},...null!=e.group?{group:e.group}:{}})),slotByNode:{...t.slotByNode}});Li.size>12;){const e=Li.keys().next().value;if(null==e)break;Li.delete(e)}}(i,y),y}function Wi(e){return e.topMass+e.botMass}function Yi(e,t){const o=e.samples.filter(e=>e.t===t);if(o.length>0)return o.reduce((e,t)=>Wi(t)<Wi(e)?e:t,o[0]);let n=null;for(const o of e.samples){if(o.t>t)break;n=o}return n}function Vi(e,t,o,n,i,r,s=0){const a=new Map;for(const o of e){if(!o.group||!t[o.id])continue;const e=a.get(o.group)??[];e.push(o),a.set(o.group,e)}if(0===a.size||0>=r)return t;const l=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,{...t,samples:t.samples.map(e=>({...e})),localAttachments:new Map([...t.localAttachments].map(([e,t])=>[e,{...t}]))}]));for(const[e,c]of a){const a=o.map((e,t)=>({slot:e,index:t})).filter(({slot:t})=>t.group===e);if(0===a.length)continue;const u=a[0].slot,d=a.at(-1).slot,h=i[u.occupants[0]?.id],p=i[d.occupants[0]?.id];if(!Number.isFinite(h)||!Number.isFinite(p))continue;const g=(h-u.peak.topPeak*r+(p+d.peak.botPeak*r))/2,m=[...new Set(c.flatMap(e=>t[e.id].samples.map(e=>e.t)))].sort((e,t)=>e-t),f=new Map;for(const e of c)f.set(e.id,new Map);for(const e of m){const o=new Map;for(const i of c){const r=Yi(t[i.id],e);if(!r||1e-9>=Wi(r))continue;const s=n[i.id];if(null==s)continue;const a=o.get(s)??[];a.push({node:i,sample:r}),o.set(s,a)}const a=[...o].sort((e,t)=>e[0]-t[0]).map(([e,t])=>({slot:e,active:t,mass:Math.max(...t.map(({sample:e})=>Wi(e)))}));if(0===a.length)continue;let l=g-(a.reduce((e,t)=>e+t.mass,0)*r+Math.max(0,s)*Math.max(0,a.length-1))/2;for(const t of a){for(const{node:o,sample:n}of t.active){const t=(l-i[o.id])/r+n.topMass-(n.boundaryOffset??0);f.get(o.id).set(e,t)}l+=t.mass*r+Math.max(0,s)}}for(const e of c){const o=t[e.id],n=l[e.id],i=f.get(e.id),r=[];for(const e of m){const t=i.get(e),n=o.samples.filter(t=>t.t===e);if(n.length>0){r.push(...n.map(e=>({...e,...null!=t?{boundaryOffset:(e.boundaryOffset??0)+t}:{}})));continue}const s=Yi(o,e);null!=t&&s&&Wi(s)>1e-9&&r.push({...s,t:e,boundaryOffset:(s.boundaryOffset??0)+t})}n.samples=r,n.localAttachments=new Map([...o.localAttachments].map(([e,t])=>{const o=i.get(t.time);return[e,{...t,...null!=o?{boundaryOffset:(t.boundaryOffset??0)+o}:{}}]}))}}return l}function Hi(e,t,o,n,i){const{plotH:r,padding:s,valueScale:a,packing:l,laneOrder:c,lifetimeMode:u="half",lanePlacement:d="stack",groupPadding:h=0,ribbonLane:p="both",domain:g}=i,m={},f={};for(const t of e)m[t.id]=o[t.id].topPeak||0,f[t.id]=o[t.id].botPeak||0;const y="half"===u,b={};for(const t of e){const e=Array.isArray(t.xExtent)?t.xExtent[0]:null,o=Array.isArray(t.xExtent)?t.xExtent[1]:null;let i=null!=e&&Number.isFinite(e)?e:1/0,r=null!=o&&Number.isFinite(o)?o:-1/0;for(const e of n.outgoing[t.id]){i>e.startTime&&(i=e.startTime),null!=e.systemInTime&&Number.isFinite(e.systemInTime)&&i>e.systemInTime&&(i=e.systemInTime);const t=y?(e.startTime+e.endTime)/2:e.endTime;t>r&&(r=t)}for(const e of n.incoming[t.id]){const t=y?(e.startTime+e.endTime)/2:e.startTime;i>t&&(i=t),e.endTime>r&&(r=e.endTime),null!=e.systemOutTime&&Number.isFinite(e.systemOutTime)&&e.systemOutTime>r&&(r=e.systemOutTime)}b[t.id]={start:Number.isFinite(i)?i:null,end:Number.isFinite(r)?r:null}}let x={},v=[],w=[];if(i.frozenSlots){const e=Ti(i.frozenSlots,o,b);v=e.slots,x=e.slotByNode,w=v.map(Un)}else if("reuse"===l){const n=Di(e,t,o,b);v=n.slots,x=n.slotByNode}else e.forEach((e,t)=>{v.push({occupants:[{id:e.id,end:b[e.id]?.end??-1/0}],peak:{topPeak:m[e.id],botPeak:f[e.id]},...e.group?{group:e.group}:{}}),x[e.id]=t});xi(v,x),0===w.length&&(w=v.map(Un));let A=null;i.frozenSlots||(i.fixedSlotOrder?function(e,t,o){const n=new Map(o.map((e,t)=>[e,t]));gi(e,t,[...e].sort((e,t)=>(n.get(Un(e))??1/0)-(n.get(Un(t))??1/0)||qn(Un(e),Un(t))))}(v,x,i.fixedSlotOrder):i.runOrdering&&c&&"insertion"!==c&&(A=Pi(e,t,o,b,v,x,{plotH:r,padding:s,valueScale:a,groupPadding:h,laneOrder:c,ribbonLane:p,domain:g}))),xi(v,x);const S=ei(e,t,o,v,x,{plotH:r,padding:s,valueScale:a,stackValueScale:i.stackValueScale,lanePlacement:d,groupPadding:h}),k=0===v.length?0:v[0].peak.topPeak+S.adjacentClearance.reduce((e,t)=>e+t,0)+v[v.length-1].peak.botPeak,M=A?.before.crossings??null,_=A?.after.crossings??null,P=A?.before.weightedLength??null,T=A?.after.weightedLength??null;return{effectiveSlotsHeight:k,centerlines:S.centerlines,laneLifetime:b,slots:v,slotByNode:x,slotCenter:S.slotCenter,stackCenter:S.stackCenter,verticalUtilization:S.verticalUtilization,selectedSlotOrder:v.map(Un),initialSlotOrder:w,ordering:A,crossingsBefore:M,crossingsAfter:_,lengthBefore:P,lengthAfter:T}}function Gi(e,t,o,n,i,r,s,a,l={}){const c=i,u=e=>a?Math.max(a[0],Math.min(a[1],e)):e;let d=r(u(e.time));const h=r(u(o.time)),p=e.value*c,g=o.value*c,m=t+(e.boundaryOffset??0)*c,f=n+(o.boundaryOffset??0)*c,y=e.sideMassBefore*c,b=o.sideMassAfter*c;let x,v,w,A;"top"===e.side?(x=m-y,v=x+p):(v=m+y,x=v-p),"top"===o.side?(w=f-b,A=w+g):(A=f+b,w=A-g);const S=l.sourceRunwayStart,k=l.minRun,M=Math.abs((w+A)/2-(x+v)/2),_=h-d,P="number"==typeof S&&Number.isFinite(S),T="number"==typeof k&&Number.isFinite(k)&&k>0;if(P&&M>1e-9&&_>0&&("auto"===k||T)){const t="source"===s?.85:"target"===s?.15:.5,o="auto"===k?Math.min(144,Math.sqrt(8*M/(1.5*Math.min(t*t,(1-t)*(1-t))))):k;if(o>_){const t=r(u(Math.min(S,e.time)));Number.isFinite(t)&&(d=Math.min(d,Math.max(Math.min(d,t),h-o)))}}const L="source"===s?d+.85*(h-d):"target"===s?d+.15*(h-d):(d+h)/2;return{sx:d,sTop:x,sBot:v,tx:h,tTop:w,tBot:A,cp1X:L,cp2X:L}}function Xi(e){return Math.max(18,11*e.length*.58)}function qi(e){const t=1.22*Xi(e.labelText)+4;return"start"===e.labelAnchor?[e.labelX,e.labelX+t]:"middle"===e.labelAnchor?[e.labelX-t/2,e.labelX+t/2]:[e.labelX-t,e.labelX]}function Ui(e,t){const o=e.labelX-Xi(e.labelText),n=t.labelX-Xi(t.labelText);return t.labelX+3>=o&&e.labelX+3>=n}var Qi=/(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?),(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/gi;function Zi(e){return e.replace(Qi,(e,t,o)=>`${o},${t}`)}function Ki(e){if(!e)return;const t=e=>({x:e.y,y:e.x});return{...e,...e.points&&{points:e.points.map(t)},...e.segments&&{segments:e.segments.map(e=>e.map(t))}}}function Ji(e){return{...e,pathD:Zi(e.pathD),y0:e.x0,y1:e.x1,x0:0,x1:0}}function er(e){const{nodes:t,edges:o,domain:n,plotW:r,plotH:s,ribbonLane:l,ribbonMinRun:c=0,edgeOpacity:u,colorOf:d,layoutOpts:h,orientation:p="horizontal",showLabels:g=!0,labelPriorityAccessor:m,maxLabels:f,selectionDatum:y="raw",styleRules:b,colorBy:x,valueAccessor:v,usageMode:w="static"}=e,A="vertical"===p?s:r,S="vertical"===p?r:s,k=function(e,t,o,n={}){const i=Vn(n.usageMode??"static"),r=[],s=new Set;for(const t of e)s.has(t.id)&&r.push({kind:"duplicate-node",id:t.id,severity:i.duplicateIds}),s.add(t.id);const a=new Set,l=Array.isArray(o)&&2===o.length,c=l&&Number.isFinite(o[0])&&Number.isFinite(o[1]);l&&c&&c&&o[1]>=o[0]||r.push({kind:"invalid-domain"});for(const t of e)null!=t.xExtent&&(Array.isArray(t.xExtent)&&2===t.xExtent.length&&Number.isFinite(t.xExtent[0])&&Number.isFinite(t.xExtent[1])&&t.xExtent[1]>=t.xExtent[0]||r.push({kind:"invalid-node-time",id:t.id}));for(const e of t)a.has(e.id)&&r.push({kind:"duplicate-edge",id:e.id,severity:i.duplicateIds}),a.add(e.id),s.has(e.source)||r.push({kind:"missing-node",id:e.id,endpoint:"source",nodeId:e.source}),s.has(e.target)||r.push({kind:"missing-node",id:e.id,endpoint:"target",nodeId:e.target}),Number.isFinite(e.startTime)&&Number.isFinite(e.endTime)?((null!=e.systemInTime&&!Number.isFinite(e.systemInTime)||null!=e.systemOutTime&&!Number.isFinite(e.systemOutTime))&&r.push({kind:"invalid-system-time",id:e.id,severity:"warn"}),Number.isFinite(e.value)&&e.value>0||r.push({kind:"invalid-value",id:e.id}),e.startTime>e.endTime&&r.push({kind:"backward-edge",severity:"fatal",id:e.id,source:e.source,target:e.target})):r.push({kind:"invalid-edge-time",id:e.id});return r}(t,o,n,{usageMode:w}),{fatal:M,warnings:_}=function(e){const t=[],o=[];for(const n of e)"fatal"===Gn(n)?t.push(n):o.push(n);return{fatal:t,warnings:o}}(k),P=function(e,t,o="static"){if("strip"!==Vn(o).invalidSystemTime)return e;const n=new Set(t.filter(e=>"invalid-system-time"===e.kind).map(e=>e.id));return 0===n.size?e:e.map(e=>{if(!n.has(e.id))return e;const t={...e};return null==t.systemInTime||Number.isFinite(t.systemInTime)||delete t.systemInTime,null==t.systemOutTime||Number.isFinite(t.systemOutTime)||delete t.systemOutTime,t})}(o,k,w),T=Wn().domain(n).range([0,A]);if(M.length>0)return{layout:null,layoutConfig:{bands:[],ribbons:[],showLabels:!1!==g},issues:M,warnings:_,xScale:T};const L=function(e,t,o){const{plotH:n,pairing:i="temporal",packing:r="reuse",laneOrder:s="crossing-min",lifetimeMode:a="half",maxValueScale:l,lanePlacement:c="stack",nodeSizing:u="temporal",groupPadding:d=0,ribbonLane:h="both",domain:p}=o,g=Number.isFinite(d)?Math.max(0,d):0,m=function(e,t){const o={},n={};for(const t of e)o[t.id]=[],n[t.id]=[];for(const e of t)n[e.source]&&n[e.source].push(e),o[e.target]&&o[e.target].push(e);return{incoming:o,outgoing:n}}(e,t),f=function(e,t,o,n="temporal"){const i="temporal"===n?(e,t)=>e.endTime-t.endTime||qn(e.id,t.id):(e,t)=>t.value-e.value||qn(e.id,t.id),r="temporal"===n?(e,t)=>e.startTime-t.startTime||qn(e.id,t.id):(e,t)=>t.value-e.value||qn(e.id,t.id),s=new Map;for(const e of t)s.set(e.id,{});const a=(e,t)=>{const o=new Map;for(const n of e){const e=n[t];o.has(e)||o.set(e,{partner:e,edges:[],total:0,earliestStart:1/0,latestEnd:-1/0});const i=o.get(e);i.edges.push(n),i.total+=n.value,i.earliestStart=Math.min(i.earliestStart,n.startTime),i.latestEnd=Math.max(i.latestEnd,n.endTime)}const s=[...o.values()];s.sort("temporal"===n?(e,o)=>"target"===t?e.earliestStart-o.earliestStart||qn(e.partner,o.partner):e.latestEnd-o.latestEnd||qn(e.partner,o.partner):(e,t)=>t.total-e.total||qn(e.partner,t.partner));for(const e of s)e.edges.sort("target"===t?r:i);return s};for(const t of e){const e=o.outgoing[t.id],n=o.incoming[t.id];if(0===n.length)a(e,"target").forEach((e,t)=>{const o=t%2==0?"top":"bot";for(const t of e.edges)s.get(t.id).sourceSide=o});else if(0===e.length)a(n,"source").forEach((e,t)=>{const o=t%2==0?"top":"bot";for(const t of e.edges)s.get(t.id).targetSide=o});else{const t=a(n,"source"),o=a(e,"target"),i=Math.max(t.length,o.length);for(let e=0;i>e;e++){const n=e%2==0?"top":"bot";if(t[e])for(const o of t[e].edges)s.get(o.id).targetSide=n;if(o[e])for(const t of o[e].edges)s.get(t.id).sourceSide=n}}}return s}(e,t,m,i);let y={};for(const t of e)y[t.id]=hi(t,m,f,void 0,u);const b=Hi(e,t,y,m,{plotH:n,padding:12,valueScale:1,packing:r,laneOrder:s,lifetimeMode:a,runOrdering:!0,lanePlacement:"stack",groupPadding:g,ribbonLane:h,domain:p}),x=b.slots.map(e=>({occupants:e.occupants.map(e=>({...e})),peak:{...e.peak},...null!=e.group?{group:e.group}:{}})),v=new Set;for(const e of t){const t=b.slotByNode[e.source],o=b.slotByNode[e.target];if(void 0===t||void 0===o)continue;const n=f.get(e.id);t!==o?t>o?(n.sourceSide="top",n.targetSide="bot"):(n.sourceSide="bot",n.targetSide="top"):(v.add(e.id),n.sourceSide="bot",n.targetSide="bot")}for(const t of e){const e=m.outgoing[t.id],o=m.incoming[t.id],n=new Set(e.map(e=>f.get(e.id).sourceSide)),i=new Set(o.map(e=>f.get(e.id).targetSide));if(1===n.size&&o.length>0){const e=[...n][0];for(const t of o)b.slotByNode[t.source]===b.slotByNode[t.target]&&(f.get(t.id).targetSide=e)}if(1===i.size&&e.length>0){const t=[...i][0];for(const o of e)b.slotByNode[o.source]===b.slotByNode[o.target]&&(f.get(o.id).sourceSide=t)}}!function(e,t,o){const n=new Map,i=[];for(const t of e)i.push({time:t.startTime,kind:"out",edge:t}),i.push({time:t.endTime,kind:"in",edge:t});i.sort((e,t)=>e.time-t.time||(e.kind===t.kind?0:"in"===e.kind?-1:1)||("out"===e.kind?t.edge.value-e.edge.value:0)||qn(e.edge.id,t.edge.id));const r=e=>{let t=n.get(e);return t||(t={top:0,bot:0},n.set(e,t)),t},s=(e,t,o)=>{const n="top"===t?"bot":"top",i=Math.min(o,e[t]);e[t]-=i;const r=o-i;r>0&&(e[n]=Math.max(0,e[n]-r))};for(const e of i){const{edge:n}=e;if("in"===e.kind){const e=t.get(n.id)?.targetSide??"bot";r(n.target)[e]+=n.value;continue}const i=r(n.source),a=t.get(n.id);let l=a.sourceSide??"bot";if(o[n.source]===o[n.target]){const e=i.top>=n.value,t=i.bot>=n.value;e!==t?l=e?"top":"bot":e||t||i.top===i.bot||(l=i.top>i.bot?"top":"bot"),a.sourceSide=l,a.targetSide=l}s(i,l,n.value)}}(t,f,b.slotByNode),function(e,t,o,n){for(const i of e){const e=t.incoming[i.id],r=t.outgoing[i.id];if(0===e.length||0===r.length)continue;const s=()=>{const t={inTop:0,inBot:0,outTop:0,outBot:0};for(const n of e)"top"===o.get(n.id).targetSide?t.inTop+=n.value:t.inBot+=n.value;for(const e of r)"top"===o.get(e.id).sourceSide?t.outTop+=e.value:t.outBot+=e.value;return t},a=(e,t)=>{const i=s(),a="top"===e?i.outTop-i.inTop:i.outBot-i.inBot,l="top"===t?i.inTop-i.outTop:i.inBot-i.outBot;if(0>=a||0>=l)return!1;const c=Math.min(a,l),u=r.filter(t=>!n.has(t.id)&&o.get(t.id).sourceSide===e&&c>=t.value).sort((e,t)=>t.value-e.value||qn(e.id,t.id));return 0!==u.length&&(o.get(u[0].id).sourceSide=t,!0)};let l=r.length+1;for(;l-- >0&&(a("top","bot")||a("bot","top")););}}(e,m,f,v),y={};for(const t of e)y[t.id]=hi(t,m,f,void 0,u);const w=Hi(e,t,y,m,{plotH:n,padding:12,valueScale:1,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:x,lanePlacement:"stack",groupPadding:g,ribbonLane:h,domain:p}),A=w.effectiveSlotsHeight??w.slots.reduce((e,t)=>e+t.peak.topPeak+t.peak.botPeak,0),S=w.slots.slice(0,-1).reduce((e,t,o)=>e+(null!=t.group&&t.group===w.slots[o+1].group?1:0),0),k=Math.max(1,w.slots.length+1-S),M=Math.min(12,Math.max(0,.35*n-S*g)/k),_=2*M+Qn(w.slots,M,g).reduce((e,t)=>e+t,0),P=A>0?Math.max(0,(n-_)/A):1,T=Number.isFinite(l)&&l>0?Math.min(P,l):P;let L=Hi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:x,lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P});const R=Number.isFinite(l)&&l>0&&P>l+1e-12;if("insertion"!==s&&("hug"===c||R)&&L.slots.length>1&&(Pi(e,t,y,L.laneLifetime,L.slots,L.slotByNode,{plotH:n,padding:M,valueScale:T,groupPadding:g,laneOrder:s,ribbonLane:h,domain:p,lanePlacement:c,mode:"geometry-refine"}),L=Hi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:L.slots,fixedSlotOrder:L.slots.map(Un),lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P})),function(e,t){const o=(e,o)=>{for(const n of e){const e=new Map;for(const i of n){const n=`${("out"===o?t.get(i.id)?.sourceSide:t.get(i.id)?.targetSide)??""}\0${"out"===o?i.startTime:i.endTime}`,r="out"===o?`${i.target}\0${i.endTime}`:`${i.source}\0${i.startTime}`,s=e.get(n);if(null!=s&&s!==r)return!0;e.set(n,r)}}return!1};return o(Object.values(e.outgoing),"out")||o(Object.values(e.incoming),"in")}(m,f)){const o=function(e,t,o,n){const i=new Map;for(const r of e){const e=t[r.source]?.localAttachments.get(r.id),s=t[r.target]?.localAttachments.get(r.id),a=o[r.source],l=o[r.target];if(!(e&&s&&Number.isFinite(a)&&Number.isFinite(l)))continue;const c=di(e,a,n),u=di(s,l,n);i.set(r.id,{source:(c[0]+c[1])/2,target:(u[0]+u[1])/2})}return i}(t,y,L.centerlines,T);y={};for(const t of e)y[t.id]=hi(t,m,f,o,u);L=Hi(e,t,y,m,{plotH:n,padding:M,valueScale:T,packing:r,laneOrder:s,lifetimeMode:a,frozenSlots:L.slots,fixedSlotOrder:L.slots.map(Un),lanePlacement:c,groupPadding:g,ribbonLane:h,domain:p,stackValueScale:P})}const I=new Map(b.initialSlotOrder.map((e,t)=>[e,t])),C=[...L.slots].sort((e,t)=>(I.get(Un(e))??1/0)-(I.get(Un(t))??1/0)||qn(Un(e),Un(t))),z={};C.forEach((e,t)=>{for(const o of e.occupants)z[o.id]=t});const F=ei(e,t,y,C,z,{plotH:n,padding:M,valueScale:T,stackValueScale:P,lanePlacement:"stack",groupPadding:g}),O=Vi(e,y,C,z,F.centerlines,T,g),B=li(wi(z,t),Ai(z,t),t,O,C,z,F.centerlines,L.laneLifetime,T,F.verticalUtilization,h,p);y=Vi(e,y,L.slots,L.slotByNode,L.centerlines,T,g);const N=li(wi(L.slotByNode,t),Ai(L.slotByNode,t),t,y,L.slots,L.slotByNode,L.centerlines,L.laneLifetime,T,L.verticalUtilization,h,p);return{nodeData:y,sides:f,valueScale:T,padding:M,compressedPadding:12>M,centerlines:L.centerlines,laneLifetime:L.laneLifetime,slots:L.slots,slotByNode:L.slotByNode,crossingsBefore:"insertion"===s?null:B.crossings,crossingsAfter:"insertion"===s?null:N.crossings,lengthBefore:"insertion"===s?null:B.weightedLength,lengthAfter:"insertion"===s?null:N.weightedLength,layoutQualityBefore:B,layoutQuality:N}}(t,P,{plotH:S,...h,ribbonLane:l,domain:n}),{centerlines:R,nodeData:I,valueScale:C}=L,z=i(x,v),F=[],O=[],B=0===c?new Map:function(e,t,o){const n=new Set(t.map(e=>e.target)),i=new Map(e.map(e=>[e.id,e])),r=new Map;for(const e of t){if(n.has(e.source))continue;const t=r.get(e.source)??[];t.push(e),r.set(e.source,t)}const s=new Map;for(const t of e){if(!t.group)continue;const e=s.get(t.group)??[];e.push(t),s.set(t.group,e)}const a=new Set;for(const[e,t]of s){const o=t.flatMap(e=>r.get(e.id)??[]),i=new Set(o.map(e=>e.startTime));o.length>0&&1===i.size&&t.every(e=>{const t=e.xExtent?.[0],i=o[0].startTime;return!n.has(e.id)&&(r.get(e.id)?.length??0)>0&&Number.isFinite(t)&&i>t})&&a.add(e)}const l=new Map;for(const[e,t]of r){const n=i.get(e);if(n?.group&&!a.has(n.group))continue;const r=n?.xExtent?.[0],s=[...t].sort((e,t)=>e.startTime-t.startTime||e.id.localeCompare(t.id)),c=s[0]?.startTime-1;let u=null;for(let e=0;s.length>e;){const t=s[e].startTime;let n=e+1;for(;s.length>n&&s[n].startTime===t;)n++;for(let t=e;n>t;t++){const e=s[t],n=Number.isFinite(r)&&e.startTime>r,i=Number.isFinite(e.systemInTime)&&e.startTime>e.systemInTime;if(!n&&!i)continue;let a=o[0];n&&(a=Math.max(a,r)),i&&(a=Math.max(a,e.systemInTime)),!n&&i&&Number.isFinite(c)&&(a=Math.max(a,c)),null!=u&&(a=Math.max(a,u)),e.startTime>a&&l.set(e.id,a)}u=t,e=n}}for(const[e,t]of s){if(!a.has(e))continue;const o=t.flatMap(e=>r.get(e.id)??[]);if(!o.every(e=>l.has(e.id))){for(const e of o)l.delete(e.id);continue}const n=Math.max(...o.map(e=>l.get(e.id)));for(const e of o)l.set(e.id,n)}return l}(t,P,n),N=new Map(t.filter(e=>e.group).map(e=>[e.id,e.group])),E=new Map;for(const e of P){const t=I[e.source]?.localAttachments.get(e.id),o=I[e.target]?.localAttachments.get(e.id);t&&o&&E.set(e.id,Gi(t,R[e.source],o,R[e.target],C,T,l,n,{minRun:c,sourceRunwayStart:B.get(e.id)}))}const j=function(e,t,o,n,i,r){const s=new Map(t),a=new Map;for(const t of e){const e=r?.get(t.source),o=null==e?"node:"+t.source:"group:"+e,n=a.get(o)??new Map,i=n.get(t.startTime)??[];i.push(t),n.set(t.startTime,i),a.set(o,n)}for(const e of a.values())for(const[r,a]of e){if(!a.some(e=>o.has(e.id)))continue;const e=a.map(e=>t.get(e.id));if(e.some(e=>null==e))continue;const l=n(r),c=Math.min(...e.map(e=>e.sx));if(c>=l-1e-9)continue;const u=Math.max(...a.map(e=>{const t=o.get(e.id);return null==t?l:Math.min(l,n(t))})),d=Math.min(l,Math.max(c,u));for(const e of a){const o=t.get(e.id),n=d+(o.tx-d)*("source"===i?.85:"target"===i?.15:.5);s.set(e.id,{...o,sx:d,cp1X:n,cp2X:n})}}return s}(P,E,B,T,l,N),$=function(e,t,o,n,i){const r=new Map;for(const s of e){if(!o.has(s.id))continue;const e=t.get(s.id);if(!e||e.sx>=n(s.startTime)-1e-9)continue;const a=i(e.sx);Number.isFinite(a)&&s.startTime>a&&r.set(s.id,a)}return r}(P,j,B,T,e=>n[0]+e/A*(n[1]-n[0])),D=function(e,t,o){const n=new Map,i=new Map;for(const[e,t]of o??[]){const o=i.get(t)??[];o.push(e),i.set(t,o)}for(const r of e){const e=t.get(r.id);if(null==e||!Number.isFinite(e)||e>=r.startTime)continue;const s=o?.get(r.source),a=null==s?[r.source]:i.get(s)??[r.source];for(const t of a){const o=n.get(t)??new Map,i=o.get(r.startTime);o.set(r.startTime,null==i?e:Math.min(i,e)),n.set(t,o)}}return n}(P,$,N);t.forEach((e,t)=>{const o=I[e.id];if(!o||0===o.samples.length)return;const i=(r=o.samples,(s=D.get(e.id))&&0!==s.size?r.map(e=>{const t=s.get(e.t);return null==t?e:{...e,t:t}}):r);var r,s;const l=function(e,t,o,n,i){if(0===e.length)return null;const r=ui(e,i),s=e=>t+(r[e].boundaryOffset??0)*o,a=e=>s(e)-r[e].topMass*o,l=e=>s(e)+r[e].botMass*o;let c=`M${n(r[0].t)},${a(0)}`;for(let e=1;r.length>e;e++)c+=` L${n(r[e].t)},${a(e)}`;c+=` L${n(r[r.length-1].t)},${l(r.length-1)}`;for(let e=r.length-2;e>=0;e--)c+=` L${n(r[e].t)},${l(e)}`;return c+" Z"}(i,R[e.id],C,T,n);if(!l)return;const c=ui(i,n),u=c.find(e=>e.topMass+e.botMass>0)||c[0],h=R[e.id]+(u.botMass-u.topMass+2*(u.boundaryOffset??0))*C/2;let g,m,f=d(e.id,t),y=f,x=.5;const v=e.__raw??e;if(b&&b.length>0){const e=a(v,b,z(v));"string"==typeof e.fill?f=e.fill:null!=e.fill&&ht(e.fill)&&(m=e.fill,f=e.fill.background&&"transparent"!==e.fill.background?e.fill.background:f),"string"==typeof e.stroke&&(y=e.stroke),"number"==typeof e.strokeWidth&&(x=e.strokeWidth),"number"==typeof e.fillOpacity&&(g=e.fillOpacity),"number"==typeof e.opacity&&null==g&&(g=e.opacity)}const w=function(e,t,o,n,i,r){const s=o.nodeData[e];if(!s||0===s.samples.length)return[];const a=o.valueScale,l=o.centerlines[e],c=ui(s.samples,i),u=c.find(e=>e.topMass+e.botMass>0)||c[0],d=[...c].reverse().find(e=>e.topMass+e.botMass>0)||c[c.length-1],h=n(u.t),p=n(d.t),g=e=>n(ci(e,i)),m=[],f=(e,t,o,n)=>`M${e},${t} L${o},${t} L${o},${n} L${e},${n} Z`;for(const o of t){if(o.source===e&&null!=o.systemInTime&&Number.isFinite(o.systemInTime)){const e=s.localAttachments.get(o.id),t=r?.get(o.id)??o.startTime;if(e&&"out"===e.kind&&t>o.systemInTime){const n=g(o.systemInTime),r=g(t),s=null!=i&&i[0]>o.systemInTime,c=s?n:n-20,u=s?Math.min(r,n+20):n,d=Math.max(h,c);if(r>d){const[t,o]=di(e,l,a);m.push({pathD:f(d,t,r,o),x0:c,x1:u,from:0,to:1})}}}if(o.target===e&&null!=o.systemOutTime&&Number.isFinite(o.systemOutTime)){const e=s.localAttachments.get(o.id);if(e&&"in"===e.kind&&o.systemOutTime>o.endTime){const t=g(o.systemOutTime),n=g(o.endTime),i=t+20,r=Math.min(p,i);if(r>n){const[o,s]=di(e,l,a);m.push({pathD:f(n,o,r,s),x0:t,x1:i,from:1,to:0})}}}}return m}(e.id,P,L,T,n,$);F.push({id:e.id,pathD:l,fill:f,stroke:y,strokeWidth:x,...null!=g&&{fillOpacity:g},...m&&{hatchFill:m},...w.length>0&&{gradientStubs:w},rawDatum:v,labelX:T("vertical"===p&&e.xExtent?e.xExtent[0]:u.t)-4,labelY:h,labelText:e.label??e.id})});const W=new Map;t.forEach((e,t)=>W.set(e.id,t)),P.forEach(e=>{const t=j.get(e.id);if(!t)return;const o=W.get(e.source)??0,n=d(e.source,o),{pathD:i,bezier:r}=H(t),s=e.__raw??e,a="function"==typeof u?Number(u(s)):u,l=Number.isFinite(a)?Math.max(0,Math.min(1,a)):.35;O.push({id:e.id,pathD:i,fill:n,opacity:l,rawDatum:s,bezier:r})});const Y=function(e,t,o){const n=e.map(e=>({...e})),i=new Map;for(const e of n){const o=t[e.id];if(null==o)continue;const n=i.get(o)??[];n.push(e),i.set(o,n)}const r=e=>{if(2>e.length)return;const t=e.reduce((e,t)=>e+t.labelY,0)/e.length,n=(e.length-1)/2;e.forEach((e,i)=>{e.labelY=Math.max(8,Math.min(o-8,t+16*(i-n)))})};for(const e of i.values()){e.sort((e,t)=>e.labelX-t.labelX||e.id.localeCompare(t.id));let t=[],o=-1/0;for(const n of e){const e=n.labelX-Xi(n.labelText);t.length>0&&e>o+3&&(r(t),t=[],o=-1/0),t.push(n),o=Math.max(o,n.labelX)}r(t)}return function(e,t){const o=[...e].sort((e,t)=>e.labelY-t.labelY||e.labelX-t.labelX||e.id.localeCompare(t.id));for(let e=0;3>e;e+=1){for(let e=0;o.length>e;e+=1){let t=8;for(let n=0;e>n;n+=1)Ui(o[e],o[n])&&(t=Math.max(t,o[n].labelY+16));o[e].labelY=Math.max(o[e].labelY,t)}for(let e=o.length-1;e>=0;e-=1){let n=t-8;for(let t=e+1;o.length>t;t+=1)Ui(o[e],o[t])&&(n=Math.min(n,o[t].labelY-16));o[e].labelY=Math.min(o[e].labelY,n)}}}(n,o),n}(F,L.slotByNode,S).map(e=>function(e,t){return"horizontal"===t?e:{...e,pathD:Zi(e.pathD),gradientStubs:e.gradientStubs?.map(Ji),labelX:e.labelY,labelY:e.labelX,labelAnchor:"middle",labelBaseline:"auto"}}(e,p)),V="vertical"===p?function(e,t,o){const n=e.map(e=>({...e}));for(const e of n){const o=1.22*Xi(e.labelText)+4;e.labelX=t-4>o?Math.max(o/2+2,Math.min(t-o/2-2,e.labelX)):t/2}const i=[],r=[...n].sort((e,t)=>e.labelY-t.labelY||e.labelX-t.labelX);for(const e of r){const t=i[i.length-1];!t||Math.abs(t[0].labelY-e.labelY)>14?i.push([e]):t.push(e)}for(const e of i){e.sort((e,t)=>e.labelX-t.labelX||e.id.localeCompare(t.id));const t=[],n=new Map;for(const o of e){const[e,i]=qi(o);let r=t.findIndex(t=>e>t+8);-1===r&&(r=t.length),t[r]=i,n.set(o,r)}const i=e.reduce((e,t)=>e+t.labelY,0)/e.length,r=14*t.length+8>i;for(const t of e){const e=n.get(t)??0;t.labelY=r?Math.min(o-8,12+14*e):Math.max(8,i-14*e)}}return n}(Y,r,s):Y,G=new Map;if(null!=m)for(const e of t){const t=e.__raw??e,o="function"==typeof m?m(t):Number(t[m]);Number.isFinite(o)&&G.set(e.id,o)}const X=function(e,t,o,n,i={}){if(!1===n)return e.map(e=>({...e,labelText:"",labelDeferred:!1,labelFullText:void 0}));if(!0===n)return e.map(e=>({...e,labelDeferred:!1,labelFullText:void 0}));let r=Math.max(4,Math.min(e.length,Math.floor(Math.max(1,t*o)/14e3)));Number.isFinite(i.maxLabels)&&i.maxLabels>=0&&(r=Math.min(r,Math.floor(i.maxLabels)));const s=e.map((e,t)=>{const o=i.priorityById?.get(e.id),n=Math.abs(e.labelY);return{band:e,index:t,score:null!=o&&Number.isFinite(o)?1e6*o+Xi(e.labelText):Xi(e.labelText)+.01*n}}).filter(e=>e.band.labelText.trim().length>0).sort((e,t)=>t.score-e.score||e.index-t.index||e.band.id.localeCompare(t.band.id)),a=new Set(s.slice(0,r).map(e=>e.band.id));return e.map(e=>a.has(e.id)||0===e.labelText.trim().length?{...e,labelDeferred:!1,labelFullText:void 0}:{...e,labelFullText:e.labelText,labelText:"",labelDeferred:!0})}(V,r,s,g,{...G.size>0&&{priorityById:G},...null!=f&&{maxLabels:f}});return{layout:L,layoutConfig:{bands:X,ribbons:O.map(e=>function(e,t){return"horizontal"===t?e:{...e,pathD:Zi(e.pathD),bezier:Ki(e.bezier)}}(e,p)),showLabels:!1!==g,selectionDatum:y},issues:[],warnings:_,xScale:T}}import{Fragment as tr,jsx as or,jsxs as nr}from"react/jsx-runtime";var ir="var(--semiotic-grid, #94a3b8)",rr="var(--semiotic-text-secondary, #475569)",sr="var(--semiotic-text-secondary, #94a3b8)",ar=.22;function lr(e,t,o){return!t?.isActive||t.predicate(function(e,t){return"scene"===t?e:e.data}(e,o))}var cr=e=>{const{bands:t=[],ribbons:o=[],showLabels:n=!0,selectionDatum:i="raw"}=e.config,r=e.selection??null,s=[];for(const e of o){const t={__kind:"ribbon",data:e.rawDatum,id:e.id},o=!lr(t,r,i);s.push({type:"bezier",pathD:e.pathD,...e.bezier&&{bezierCache:e.bezier},style:{fill:e.fill,opacity:o?Math.min(e.opacity,ar):e.opacity,stroke:"none"},datum:t})}for(const e of t){if(!e.gradientStubs)continue;const t=!lr({__kind:"band",data:e.rawDatum,id:e.id},r,i);for(let o=0;e.gradientStubs.length>o;o++){const n=e.gradientStubs[o];s.push({type:"bezier",pathD:n.pathD,interactive:!1,style:{fill:e.fill,fillOpacity:t?ar:e.fillOpacity??.86,stroke:"none"},_gradient:{x0:n.x0,x1:n.x1,...null!=n.y0&&{y0:n.y0},...null!=n.y1&&{y1:n.y1},from:n.from,to:n.to},datum:{__kind:"band",data:e.rawDatum,id:`${e.id}__stub${o}`}})}}for(const e of t){const t=!(!e.gradientStubs||0>=e.gradientStubs.length),o={__kind:"band",data:e.rawDatum,id:e.id},n=!lr(o,r,i);s.push({type:"bezier",pathD:e.pathD,style:{...t?{fill:"none"}:{fill:e.hatchFill??e.fill,fillOpacity:n?ar:e.fillOpacity??.86},stroke:e.stroke??("string"==typeof e.fill?e.fill:"#666"),strokeWidth:e.strokeWidth??.5,...n&&t?{opacity:ar}:{}},datum:o})}const a=n?t.flatMap(e=>{const t=e.labelDeferred&&e.labelFullText?.trim(),o=e.labelText.trim().length>0,n=t&&r?.isActive&&lr({__kind:"band",data:e.rawDatum,id:e.id},r,i),s=o?e.labelText:n?e.labelFullText:"";return s.trim()?[{x:e.labelX,y:e.labelY,text:s,anchor:e.labelAnchor??"end",baseline:e.labelBaseline??"middle",fontSize:11,fontWeight:600}]:[]}):[];return{sceneNodes:t.map(e=>({type:"circle",id:e.id,cx:-1e4,cy:-1e4,r:0,style:{fill:e.fill},datum:{__kind:"band",data:e.rawDatum,id:e.id}})),sceneEdges:s,labels:a}};function ur(e,t){if(!e)return[];const o=[],n=e=>{o.push(e);const i="function"==typeof t?t(e):e[t];i&&Array.isArray(i)&&i.forEach(n)};return n(e),o}function dr(e,t,o,n){if(e&&e.length>0)return e;const i=new Set;return t.forEach(e=>{const t="function"==typeof o?o(e):e[o],r="function"==typeof n?n(e):e[n];i.add(t),i.add(r)}),Array.from(i).map(e=>({id:e}))}function hr(e,t,o={}){return Xt(t?"function"==typeof t?o=>({...e(o),...t(o)??{}}):o=>({...e(o),...t}):e,o)}var pr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=function(e){if(void 0!==e.edgeStyle)return e.edgeStyle;const{edgeWidth:t,edgeColor:o,edgeOpacity:n}=e,i=e.strokeWidth??1;return void 0!==t||void 0!==o||void 0!==n||void 0!==e.stroke||void 0!==e.strokeWidth||void 0!==e.opacity?r=>{const s=r?.data||r;let a=i;if("number"==typeof t)a=t;else if("function"==typeof t)a=t(s);else if("string"==typeof t){const e=s?.[t],o="number"==typeof e?e:Number(e);a=Number.isFinite(o)&&o>0?o:i}return{stroke:o??e.stroke??"#999",strokeWidth:a,opacity:n??e.opacity??.6}}:void 0}(i),s=Kt(n.theme).colors.categorical,a=new Map,c=i.nodeStyle??(e=>({fill:t?le(e?.data||e,t,void 0):Ee(void 0,s,o,void 0,a),..."number"==typeof i.nodeSize&&{r:i.nodeSize}})),u=l(i.styleRules,t,"number"==typeof i.nodeSize?void 0:i.nodeSize),d=Xt(u?(e,t)=>({...c(e),...u(e,t)}):c,{stroke:i.nodeStroke??i.stroke,strokeWidth:i.nodeStrokeWidth??i.strokeWidth,opacity:i.opacity});return{chartType:"force",nodes:i.nodes,edges:i.edges,nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor,sourceAccessor:i.sourceAccessor,targetAccessor:i.targetAccessor,colorBy:t,colorScheme:o,iterations:i.iterations,forceStrength:i.forceStrength,showLabels:i.showLabels??!1,nodeLabel:i.nodeLabel,nodeSize:i.nodeSize??8,nodeSizeRange:i.nodeSizeRange,nodeStyle:d,edgeStyle:r,...n}}},gr={frameType:"network",layout:{margin:{top:30,right:80,bottom:40,left:80}},buildProps:(e,t,o,n,i)=>{const r=e=>null==e?NaN:e instanceof Date?e.getTime():"number"==typeof e?e:new Date(e).getTime(),s=i.sourceAccessor||"source",a=i.targetAccessor||"target",l=i.valueAccessor||"value",c=i.nodeIdAccessor||"id",u=i.startTimeAccessor||"startTime",d=i.endTimeAccessor||"endTime",h=i.systemInTimeAccessor,p=i.systemOutTimeAccessor,g=i.xExtentAccessor||"xExtent",m=i.groupBy,f=i.edgeIdAccessor||"id",y=(e,t)=>"function"==typeof e?e(t):t[e],b=Array.isArray(i.edges)?i.edges:[],x=Array.isArray(i.nodes)?i.nodes:[],v=x.length>0?x:dr([],b,s,a),w=[r(i.domain?.[0]),r(i.domain?.[1])],A=v.map(e=>{const t=y(c,e)+"",o=y(g,e),n=i.nodeLabel?y(i.nodeLabel,e):t,s={id:t,label:null==n?t:n+"",__raw:e},a=m?y(m,e):null;if(null!=a&&a+""!=""&&(s.group=a+""),Array.isArray(o)&&2===o.length){const e=r(o[0]),t=r(o[1]);Number.isFinite(e)&&Number.isFinite(t)&&(s.xExtent=[e,t])}return s}),S=b.map((e,t)=>{const o=y(f,e),n={id:null!=o?o+"":`${y(s,e)}-${y(a,e)}-${t}`,source:y(s,e)+"",target:y(a,e)+"",value:Number(y(l,e)),startTime:r(y(u,e)),endTime:r(y(d,e)),__raw:e};if(h){const t=r(y(h,e));Number.isFinite(t)&&(n.systemInTime=t)}if(p){const t=r(y(p,e));Number.isFinite(t)&&(n.systemOutTime=t)}return n}),[k,M]=n.size??[600,400],_=n.margin,P="vertical"===i.orientation?"vertical":"horizontal",T=function(e,t,o,n="horizontal"){return"vertical"===n?{top:e?38:t?28:16,right:24,bottom:24,left:o?72:24}:{top:e?30:t?24:8,right:80,bottom:o?28:8,left:80}}(!!n.title,!!i.showQualityReadout,Array.isArray(i.axisTicks)&&i.axisTicks.length>0,P),L={...T,..._},R=(n.showLegend??!!t)&&!!t,I=n.legendPosition??"right",C=n.__explicitMargin,z=e=>"number"==typeof C||null!=C&&"object"==typeof C&&null!=C[e];R&&("right"!==I||z("right")?"bottom"!==I||z("bottom")||(L.bottom=Math.max(L.bottom,80)):L.right=Math.max(L.right,140));const F=L,O=k-F.left-F.right,B=M-F.top-F.bottom,N=Kt(n.theme),E=Oe(o,N.colors.categorical,Pt),j="function"==typeof t?t:null,$=j?v.map(e=>({_cat:j(e)})):v,D=j?"_cat":"string"==typeof t?t:void 0,W=o??[...E],Y=D?J($,D,W):null,V=new Map;for(const e of A)V.set(e.id,e.__raw);const H=(e,o)=>{if(t&&V.has(e)){const o=V.get(e);return j?le({_cat:j(o)},"_cat",Y??void 0):le(o,"string"==typeof t?t:"id",Y??void 0)}return E[o%E.length]},G=R&&t?(()=>{const e=new Map;v.forEach((o,n)=>{const i=y(t,o),r=null==i?"":i+"";r&&!e.has(r)&&e.set(r,{label:r,color:H(y(c,o)+"",n)})});const o=Array.from(e.values());return o.length>0?{legendGroups:[{type:"fill",label:"",items:o,styleFn:e=>{const t=e.color||"#333";return{fill:t,stroke:t}}}]}:void 0})():void 0,q=X(G,n.legend),U=!1!==i.showLabels&&("auto"!==i.showLabels||"auto"),{layout:Q,layoutConfig:Z,issues:K,xScale:ee}=er({nodes:A,edges:S,domain:w,plotW:O,plotH:B,orientation:P,ribbonLane:i.ribbonLane||"both",ribbonMinRun:"auto"===i.ribbonMinRun||"number"==typeof i.ribbonMinRun?i.ribbonMinRun:0,edgeOpacity:"number"==typeof i.edgeOpacity?i.edgeOpacity:.35,colorOf:H,showLabels:U,styleRules:i.styleRules,colorBy:t,valueAccessor:l,layoutOpts:{pairing:i.pairing||"temporal",packing:i.packing||"reuse",laneOrder:i.laneOrder||"crossing-min",lifetimeMode:i.lifetimeMode||"half",maxValueScale:"number"==typeof i.maxValueScale?i.maxValueScale:void 0,lanePlacement:i.lanePlacement||"stack",nodeSizing:i.nodeSizing||"temporal",groupPadding:"number"==typeof i.groupPadding?i.groupPadding:0}});if(K.length>0){const e=K.map(Xn).join("; ");throw Error("ProcessSankey: data invalid — "+e)}const te=Q?function(e){const t=e.layout,o=e.nodes,n=e.orientation,i=e.plotW,r=e.plotH,s=e.timelineExtent,a=e.axisTicks,l=e.showQualityReadout??!1,c=e.showLaneRails??!1,u=(e.warnings??[]).slice(0,3),d=e.timeFormat,h=e.colorOf,p=e.toTime,g=e.xScale,{centerlines:m,laneLifetime:f,nodeData:y,valueScale:b,compressedPadding:x,crossingsBefore:v,crossingsAfter:w,layoutQualityBefore:A,layoutQuality:S}=t;let k=null,M=null;for(const e of o){const t=f[e.id];if(!t||null===t.start||null===t.end)continue;const o=g(t.start),n=g(t.end);(null===k||k>o)&&(k=o),(null===M||n>M)&&(M=n)}const _=e=>Math.max(0,Math.min(s,e)),P=_(k??0),T=Math.max(P,_(M??s)),L=a.map((e,t)=>({tick:e,index:t,coordinate:g(p(e.date))})).filter(({coordinate:e})=>e>=P-.5&&T+.5>=e),R=null!==(w??null)&&null!=A&&null!=S,I=l&&(R||u.length>0)?nr("g",{fill:sr,fontSize:10,textAnchor:"end",children:[R&&nr(tr,{children:[nr("text",{x:i,y:-14,children:["crossings: ",v," → ",w," ","pixel length: ",Math.round(A.pixelLength)," → ",Math.round(S.pixelLength)]}),nr("text",{x:i,y:-3,children:["transit: ",A.transitOcclusion.toFixed(1)," → ",S.transitOcclusion.toFixed(1)," ","lane use: ",Math.round(100*S.verticalUtilization),"%"]})]}),u.map((e,t)=>nr("text",{x:i,y:R?10+11*t:11*t-3,fill:"var(--semiotic-warning, #b45309)",children:["warn: ",e]},"warn-"+t))]}):null,C=x?or("text",{x:i,y:"vertical"===n?-3:2,fontSize:10,fill:sr,textAnchor:"end",children:"dense layout: lane gaps compressed"}):null,z=(e,t)=>h?h(e,t):ir;return nr("g","vertical"===n?{children:[I,C,L.map(({index:e,coordinate:t})=>or("line",{x1:0,y1:t,x2:i,y2:t,stroke:ir,strokeOpacity:.15,strokeDasharray:"2 4"},"grid-"+e)),c&&o.map((e,t)=>{const o=f[e.id];if(!o||null===o.start)return null;const n=y[e.id],i=n?{topPeak:n.topPeak,botPeak:n.botPeak}:{topPeak:0,botPeak:0},r=m[e.id]+(i.botPeak-i.topPeak)*b/2,s=g(o.start),a=g(o.end),l=z(e.id,t);return nr("g",{children:[or("line",{x1:r,y1:s,x2:r,y2:a,stroke:l,strokeOpacity:.35,strokeWidth:1,strokeDasharray:"3 3"}),or("line",{x1:r-4,y1:s,x2:r+4,y2:s,stroke:l,strokeOpacity:.5}),or("line",{x1:r-4,y1:a,x2:r+4,y2:a,stroke:l,strokeOpacity:.5})]},"lane-"+e.id)}),or("line",{x1:-4,y1:P,x2:-4,y2:T,stroke:ir}),L.map(({tick:e,index:t,coordinate:o})=>{const n=p(e.date),i=null!=e.label?e.label:d?d(new Date(n)):"";return nr("g",{transform:`translate(-4,${o})`,children:[or("line",{x2:-6,stroke:ir}),or("text",{x:-10,y:4,textAnchor:"end",fontSize:11,fill:rr,children:i})]},t)})]}:{children:[I,C,L.map(({index:e,coordinate:t})=>or("line",{x1:t,y1:0,x2:t,y2:r,stroke:ir,strokeOpacity:.15,strokeDasharray:"2 4"},"grid-"+e)),c&&o.map((e,t)=>{const o=f[e.id];if(!o||null===o.start)return null;const n=y[e.id],i=n?{topPeak:n.topPeak,botPeak:n.botPeak}:{topPeak:0,botPeak:0},r=m[e.id]+(i.botPeak-i.topPeak)*b/2,s=g(o.start),a=g(o.end),l=z(e.id,t);return nr("g",{children:[or("line",{x1:s,y1:r,x2:a,y2:r,stroke:l,strokeOpacity:.35,strokeWidth:1,strokeDasharray:"3 3"}),or("line",{x1:s,y1:r-4,x2:s,y2:r+4,stroke:l,strokeOpacity:.5}),or("line",{x1:a,y1:r-4,x2:a,y2:r+4,stroke:l,strokeOpacity:.5})]},"lane-"+e.id)}),or("line",{x1:P,y1:r+4,x2:T,y2:r+4,stroke:ir}),L.map(({tick:e,index:t,coordinate:o})=>{const n=p(e.date),i=null!=e.label?e.label:d?d(new Date(n)):"";return nr("g",{transform:`translate(${o},${r+4})`,children:[or("line",{y2:6,stroke:ir}),or("text",{y:20,textAnchor:"middle",fontSize:11,fill:rr,children:i})]},t)})]})}({layout:Q,nodes:A,orientation:P,plotW:O,plotH:B,timelineExtent:"vertical"===P?B:O,axisTicks:Array.isArray(i.axisTicks)?i.axisTicks.map(e=>({date:e.date,label:e.label})):[],showQualityReadout:!!i.showQualityReadout,showLaneRails:!!i.showLaneRails,timeFormat:"function"==typeof i.timeFormat?e=>i.timeFormat(e):void 0,colorOf:H,toTime:e=>r(e),xScale:e=>Number(ee(e))}):void 0;return{chartType:"force",nodes:v,edges:b,customNetworkLayout:cr,layoutConfig:Z,sourceAccessor:s,targetAccessor:a,valueAccessor:l,nodeIDAccessor:c,colorBy:t,colorScheme:o,...te&&{backgroundGraphics:te},...n,showLegend:R,...q&&{legend:q,legendPosition:I},__legendIncludesAutomatic:!0,margin:F}}},mr={frameType:"network",layout:{primarySize:{width:800,height:600}},buildProps:(e,t,o,n,i)=>{const r=Array.isArray(i.nodes)?i.nodes:dr([],Array.isArray(i.edges)?i.edges:[],i.sourceAccessor||"source",i.targetAccessor||"target"),s=Kt(n.theme).colors.categorical,a=new Map,c="string"==typeof t?t:"__ssrSankeyColorBy",u="function"==typeof t?r.map(e=>({...e,__ssrSankeyColorBy:t(e)})):r,d=t?J(u,c,o??n.colorScheme??s):void 0,h=e=>({fill:t?le(e?.data||e,t,d):Ee(void 0,s,o,void 0,a),stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}),p=l(i.styleRules,t,i.valueAccessor),g=p?(e,t)=>({...h(e),...p(e,t)}):h,m=function({edgeColorBy:e,colorBy:t,colorScale:o,nodeStyleFn:n,edgeOpacity:i,baseStyle:r={}}){return s=>{const a={fillOpacity:i,...r};if("function"==typeof e)a.fill=e(s);else if("source"===e){const e="object"==typeof s.source?s.source:null;t&&e?a.fill=le(e.data||e,t,o):e&&(a.fill=n(e,e.index).fill)}else if("target"===e){const e="object"==typeof s.target?s.target:null;t&&e?a.fill=le(e.data||e,t,o):e&&(a.fill=n(e,e.index).fill)}else"gradient"===e&&(a.fill="#999",a.fillOpacity=.7*i);return a}}({edgeColorBy:i.edgeColorBy??"source",colorBy:t,colorScale:d,nodeStyleFn:g,edgeOpacity:i.edgeOpacity??.5,baseStyle:{stroke:"none",strokeWidth:0}});return{chartType:"sankey",nodes:i.nodes,edges:i.edges,nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor,sourceAccessor:i.sourceAccessor,targetAccessor:i.targetAccessor,valueAccessor:i.valueAccessor,orientation:i.orientation,nodeAlign:i.nodeAlign,nodeWidth:i.nodeWidth,nodePaddingRatio:i.nodePaddingRatio,showLabels:i.showLabels,nodeLabel:i.nodeLabel,colorBy:t,edgeColorBy:i.edgeColorBy,edgeOpacity:i.edgeOpacity,nodeStyle:Xt(i.nodeStyle||g,Zt(i)),edgeStyle:Xt(i.edgeStyle||m,Zt(i)),colorScheme:o,...n}}},fr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{if(!(t||Array.isArray(i.styleRules)&&i.styleRules.length>0||n.nodeStyle||i.nodeStyle||Gt(Zt(i))))return{chartType:"chord",nodes:i.nodes,edges:i.edges,valueAccessor:i.valueAccessor,padAngle:i.padAngle,groupWidth:i.groupWidth,showLabels:i.showLabels,colorBy:t,edgeColorBy:i.edgeColorBy,colorScheme:o,...n};const r=Array.isArray(i.edges)?i.edges:[],s=Array.isArray(i.nodes)&&i.nodes.length>0?i.nodes:dr([],r,i.sourceAccessor||"source",i.targetAccessor||"target"),a=Kt(n.theme).colors.categorical,c=Oe(o,a),u="string"==typeof t?t:"__ssrChordColorBy",d="function"==typeof t?s.map(e=>({...e,__ssrChordColorBy:t(e)})):s,h=t?J(d,u,o??n.colorScheme??a):void 0,p=new Map,g=i.nodeIdAccessor||i.nodeIDAccessor||"id",m=(e,o)=>{const n=e?.data||e;let r;if(t)r=le(n,t,h);else{const t=(e.id??n?.[g]??"")+"";p.has(t)||p.set(t,p.size);const i=e.index??o??p.get(t);r=c[i%c.length]}return{fill:r,stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}},f=l(i.styleRules,t,i.valueAccessor,m)??m;return{chartType:"chord",nodes:i.nodes,edges:i.edges,valueAccessor:i.valueAccessor,padAngle:i.padAngle,groupWidth:i.groupWidth,showLabels:i.showLabels,colorBy:t,edgeColorBy:i.edgeColorBy,colorScheme:o,nodeStyle:Xt(i.nodeStyle||f,Zt(i)),...n}}},yr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrTreeColorBy:l(e)})):a,u=l?"__ssrTreeColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=n.nodeStyle||i.nodeStyle;return{chartType:"cluster"===i.layout?"cluster":"tree",data:e,childrenAccessor:i.childrenAccessor,colorBy:t,colorByDepth:i.colorByDepth,orientation:i.orientation,showLabels:i.showLabels,nodeLabel:!1!==i.showLabels?i.nodeLabel||i.nodeIdAccessor:void 0,colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrTreeColorBy:l(n)},"__ssrTreeColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,...void 0!==i.opacity&&{opacity:i.opacity}}},h,Zt(i))}}},br={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrTreemapColorBy:l(e)})):a,u=l?"__ssrTreemapColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=i.showLabels??n.showLabels,p=i.labelMode,g=void 0!==i.paddingTop?i.paddingTop:n.paddingTop,m=void 0!==g?g:!h||"parent"!==p&&"all"!==p?void 0:18,f=n.nodeStyle||i.nodeStyle;return{chartType:"treemap",data:e,childrenAccessor:i.childrenAccessor,hierarchySum:i.valueAccessor,colorBy:t,colorByDepth:i.colorByDepth,showLabels:i.showLabels,labelMode:p,nodeLabel:h?i.nodeLabel||i.nodeIdAccessor:void 0,...null!=i.padding&&{padding:i.padding},...null!=m&&{paddingTop:m},colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrTreemapColorBy:l(n)},"__ssrTreemapColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),stroke:"var(--semiotic-cell-border, var(--semiotic-border, #fff))",strokeWidth:1,strokeOpacity:.8}},f,Zt(i))}}},xr={frameType:"network",layout:{primarySize:{width:600,height:600}},buildProps:(e,t,o,n,i)=>{const r=Kt(n.theme).colors.categorical,s=new Map,a=ur(e??null,i.childrenAccessor),l="function"==typeof t?t:null,c=l?a.map(e=>({__ssrCirclePackColorBy:l(e)})):a,u=l?"__ssrCirclePackColorBy":"string"==typeof t?t:void 0,d=t&&u?J(c,u,o??n.colorScheme??r):void 0,h=n.nodeStyle||i.nodeStyle;return{chartType:"circlepack",data:e,childrenAccessor:i.childrenAccessor,hierarchySum:i.valueAccessor,colorBy:t,colorByDepth:i.colorByDepth,showLabels:i.showLabels,nodeLabel:i.showLabels??n.showLabels?i.nodeLabel||i.nodeIdAccessor:void 0,...null!=i.padding&&{padding:i.padding},colorScheme:o,...n,nodeStyle:hr(e=>{const n=e?.data||e;return{fill:i.colorByDepth?C[Number(e?.depth||0)%C.length]:t?l?le({__ssrCirclePackColorBy:l(n)},"__ssrCirclePackColorBy",d??void 0):le(n,t,d??void 0):Ee(void 0,r,o,void 0,s),fillOpacity:i.circleOpacity??.7,stroke:"currentColor",strokeWidth:1,strokeOpacity:.3}},h,Zt(i))}}},vr={fill:"#f0f0f0",stroke:"#ccc",strokeWidth:.5};import{scaleSequential as wr}from"d3-scale";function Ar(e){return e&&"object"==typeof e&&e.properties?{...e.properties,...e}:e}var Sr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(t,o,n,i,r)=>{const s="string"==typeof n?n:"blues",a=r.areaStyle??function(e,t,o,n){if(!Array.isArray(e))return;const i=e=>"function"==typeof t?t(e):null!=t?e?.properties?.[t]??e?.[t]:void 0;let r=1/0,s=-1/0;for(const t of e){const e=i(t);null!=e&&isFinite(e)&&(r>e&&(r=e),e>s&&(s=e))}const a=wr(yt(o)).domain([Number.isFinite(r)?r:0,Number.isFinite(s)?s:1]);return e=>{const t=i(e);return{fill:null!=t&&isFinite(t)?a(t):"#ccc",stroke:"#999",strokeWidth:.5,fillOpacity:n}}}(r.areas,r.valueAccessor,s,r.areaOpacity??1),l=r.styleRules?e(a,r.styleRules,e=>{return{value:(t=e,"function"==typeof r.valueAccessor?r.valueAccessor(t):null!=r.valueAccessor?t?.properties?.[r.valueAccessor]??t?.[r.valueAccessor]:void 0)};var t},Ar):a;return{areas:r.areas,projection:r.projection||"equalEarth",areaStyle:l,valueAccessor:r.valueAccessor,colorScheme:s,graticule:r.graticule,fitPadding:r.fitPadding,...i}}},kr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(t,o,n,r,s)=>{const a=t||s.points,l=s.pointStyle??function(e,t,o,n){const i=Array.isArray(e)?e:[];let r,s;if(t){const e="string"==typeof t?t:"__geoColorBy",n="string"==typeof t?i:i.map(e=>({...e,__geoColorBy:t(e)}));r=J(n,e,o)}if(n.sizeBy){const e=i.map("function"==typeof n.sizeBy?n.sizeBy:e=>e?.[n.sizeBy]).filter(e=>null!=e&&isFinite(e));e.length>0&&(s=Ot(e))}return e=>({fill:t&&r?le(e,t,r):R,fillOpacity:n.fillOpacity,stroke:"#fff",strokeWidth:n.strokeWidth,r:n.sizeBy?de(e,n.sizeBy,n.sizeRange,s):n.pointRadius??6})}(a,o,n,{sizeBy:s.sizeBy,sizeRange:s.sizeRange||[3,30],fillOpacity:.7,strokeWidth:.5}),c=s.styleRules?e(l,s.styleRules,i(o,s.sizeBy)):l;return{points:a,xAccessor:s.xAccessor||"lon",yAccessor:s.yAccessor||"lat",areas:s.areas,areaStyle:s.areaStyle||vr,pointStyle:c,sizeBy:s.sizeBy,colorBy:o,colorScheme:n,projection:s.projection||"equalEarth",graticule:s.graticule,fitPadding:s.fitPadding,...r}}},Mr={frameType:"geo",layout:{margin:{top:10,right:10,bottom:10,left:10}},buildProps:(e,t,o,n,i)=>{const r=(Array.isArray(e)?e:null)||i.flows||[],s=i.nodeIdAccessor||"id",a=i.valueAccessor||"value",l=i.xAccessor||"lon",c=i.yAccessor||"lat",u="function"==typeof l?l:e=>e[l],d="function"==typeof c?c:e=>e[c],h=(i.nodes||[]).map(e=>({...e,x:u(e),y:d(e)})),p=new Map;for(const e of h)p.set(e[s]+"",e);const g=i.edgeColorBy??t,m="function"==typeof g,f=r.map(e=>{if(!e||null==e.source||null==e.target)return null;const t=p.get(e.source+""),o=p.get(e.target+"");return t&&o?{...e,coordinates:[{x:t.x,y:t.y},{x:o.x,y:o.y}]}:null}).filter(Boolean),y="__flowMapEdgeColor",b=(()=>{if(!g)return null;if(m){const e=f.map(e=>({[y]:g(e)}));return J(e,y,o||"category10")}return J(f,g,o||"category10")})(),x=e=>g&&b?le(e,g,b):"#007bff";let v=1/0,w=-1/0;for(const e of f){const t=Number(e[a]??0);isFinite(t)&&(v>t&&(v=t),t>w&&(w=t))}const A=w>v?w-v:0,[S,k]=i.edgeWidthRange??[1,8],M=k-S,_=i.edgeOpacity??.6,P=i.edgeLinecap??"round";return{lines:f,points:h,xAccessor:"x",yAccessor:"y",lineDataAccessor:"coordinates",lineType:i.lineType||"geo",flowStyle:i.flowStyle||"basic",areas:i.areas,areaStyle:i.areaStyle||vr,projection:i.projection||"equalEarth",graticule:i.graticule,fitPadding:i.fitPadding,colorScheme:o,lineStyle:e=>{const t=Number(e?.[a]),o=Number.isFinite(t)?t:v,n=S+Math.max(0,Math.min(1,A>0?(o-v)/A:0))*M;return{stroke:x(e),strokeWidth:n,strokeLinecap:P,opacity:_,fillOpacity:0}},pointStyle:()=>({fill:"#333",r:4,fillOpacity:.8}),...n}}};import*as _r from"react";function Pr(e){const[t,o]=e,n=160>t||116>o,i=n?Math.min(12,Math.max(2,.08*t)):32,r=n?Math.min(8,Math.max(2,.12*o)):24,s=n?r:34;return{width:t,height:o,plot:{x:i,y:r,width:Math.max(1,t-2*i),height:Math.max(1,o-r-s)}}}function Tr(e){const t=(e??"")+"";if(!t)return"#4e79a7";const o=["#4e79a7","#59a14f","#e15759","#f28e2b","#76b7b2","#edc948","#b07aa1","#ff9da7"];let n=0;for(let e=0;t.length>e;e+=1)n=31*n+t.charCodeAt(e)>>>0;return o[n%o.length]}function Lr(e,t="#4e79a7",o){const n=o?.styleRules,i=!!n&&n.length>0,s=i?r(o?.valueAccessor):void 0;return o=>{const r=o.datum,l=r&&e?"function"==typeof e?e(r,0):r[e]:void 0,c={fill:null==l?t:Tr(l),stroke:"#111827",strokeWidth:1,opacity:.9};return i&&r&&Object.assign(c,a(r,n,{value:s?s(r):void 0,category:null==l?void 0:l+""})),c}}function Rr(e,t,o,n){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:o},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...n}}}function Ir(e,t,o){return"function"==typeof o?o(e,t):e[o]}function Cr(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:null}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:null}function zr(e,t,o){return Math.max(t,Math.min(o,e))}function Fr(e,t){const o=Cr(e);return null!=o&&o>0?o:t}function Or(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function Br(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}import{scaleLinear as Nr}from"d3-scale";import{scaleLinear as Er}from"d3-scale";function jr(e){const{count:t,idPrefix:o,wallThickness:n,xScale:i,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const l=Math.min(r-1,a?.(t)??s),c=Math.max(1,r-l);return{id:`${o}-wall-${t}`,shape:{type:"aabb",x:i(t),y:l+c/2,width:n,height:c}}})}import{scaleLinear as $r}from"d3-scale";function Dr(e){if(Array.isArray(e)&&e.length>=2){const t=Cr(e[0]),o=Cr(e[1]);return null!=t&&null!=o?{x:t,y:o}:null}if(e&&"object"==typeof e){const t=e,o=Cr(t.x),n=Cr(t.y);return null!=o&&null!=n?{x:o,y:n}:null}return null}function Wr(e){return Array.isArray(e)?e.map(Dr).filter(e=>null!=e):[]}function Yr(e,t,o){return"normalized"===o?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:zr(e.x,t.plot.x,t.plot.x+t.plot.width),y:zr(e.y,t.plot.y,t.plot.y+t.plot.height)}}function Vr(e){let t=0;for(let o=1;e.length>o;o+=1)t+=Math.hypot(e[o].x-e[o-1].x,e[o].y-e[o-1].y);return t}function Hr(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const o=zr(t,0,1)*Vr(e);let n=0;for(let t=1;e.length>t;t+=1){const i=e[t-1],r=e[t],s=Math.hypot(r.x-i.x,r.y-i.y);if(s>0){if(n+s>=o){const e=(o-n)/s;return{x:i.x+(r.x-i.x)*e,y:i.y+(r.y-i.y)*e}}n+=s}}return{...e[e.length-1]}}function Gr(e,t){const o=Hr(e,Math.max(0,t-.02)),n=Hr(e,Math.min(1,t+.02)),i=n.x-o.x,r=n.y-o.y,s=Math.hypot(i,r)||1;return{x:i/s,y:r/s}}function Xr(e,t=12){return"number"==typeof e?{x:e,y:0}:e&&"object"==typeof e?{x:Number.isFinite(e.x)?Number(e.x):t,y:Number.isFinite(e.y)?Number(e.y):0}:{x:t,y:0}}import{scaleLinear as qr}from"d3-scale";function Ur(e,t){const o=t.config??{},n=(t.sensors??[]).map(e=>({...e,sensor:!0})),i=[...t.colliders??[],...n],r=[...e.colliders??[],...o.colliders??[],...i];return{...e,...o,observation:{...e.observation,...o.observation},...r.length>0&&{colliders:r}}}function Qr(e){const t=os(e);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:t.left,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:t.top,x2:e.width-t.rightInset,y2:t.top,thickness:t.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:t.left,y1:e.floorY,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:e.width-t.rightInset,y1:t.top,x2:e.width-t.rightInset,y2:e.floorY,thickness:t.thickness}}]}function Zr(e,t,o,n){return o?"function"==typeof o?o(e,t):e[o]??n:n}function Kr(e){return`gauntlet:${e}:core`}function Jr(e,t){return`gauntlet:${e}:positive:${t}`}function es(e,t,o){return`gauntlet:${e}:negative:${t}:${o}`}var ts={left:28,top:76,rightInset:30,thickness:8};function os(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return ts;const o=Math.max(1,Math.min(e.width,t)),n=Math.max(2,.04*e.width);return{left:n,top:Math.max(2,.08*t),rightInset:n,thickness:Math.max(1,Math.min(4,.04*o))}}function ns(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function is(e,t,o,n){const i=os(n),r=Math.max(2,o+2),s=i.top+i.thickness/2+r,a=n.floorY-r,l=(e,t,o)=>t>o?(t+o)/2:Math.max(t,Math.min(o,e));return{x:l(e,i.left+i.thickness/2+r,n.width-i.rightInset-i.thickness/2-r),y:l(t,s,a)}}function rs(e,t,o=1){const n=[...e].sort((e,t)=>e.localeCompare(t)),i=Math.max(0,n.indexOf(t));return{angle:.82*-Math.PI+(n.length>1?i/(n.length-1):.5)*Math.PI*.64,index:i,radius:(48+i%2*6)*o}}function ss(e,t,o){const n=e.activePositiveIds.reduce((e,o)=>e+(t.get(o)?.value??1),0),i=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(o.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*n-8*r-1.2*e.delay-5*i))}function as(e){const t=function(e,t,o){const[n,i]=e,r=220>n||160>i,s=Math.round(.48*i),a=r?i-Math.max(3,Math.min(12,.1*i)):i-36,l=(t??[]).filter(e=>!1!==e.enabled),c=Math.max(1,l.length),u=.22*n,d=c>1?(.78*n-u)/(c-1):0,h=r?Math.max(Math.round(.12*n),.08*n+6):Math.max(Math.round(.14*n),110);return{crashY:a-(r?Math.min(o,Math.max(3,.22*i)):o),floorY:a,gates:l.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(u+t*d),width:e.width??Math.max(r?8:54,Math.round(.07*n))})),graveyardX:Math.round(n*(r?.72:.84)),graveyardY:a-4,height:i,routeY:s,socketX:Math.round(n*(r?.82:.92)),startX:h,width:n}}(e.size??[900,520],e.gates,e.crashOffset??30),o=e.positiveProperties??[],n=new Map(o.map(e=>[e.id,e])),i=new Map((e.negativeProperties??[]).map(e=>[e.id,e])),r={idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor},s=(e.data??[]).map((t,s)=>{const a=function(e,t,o,n,i){const r=Zr(e,t,o.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=n.map(e=>e.id),a=[...Zr(e,t,o.positiveAccessor,s)],l=[...Zr(e,t,o.negativeAccessor,[])].filter(e=>i.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Zr(e,t,o.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:l,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Zr(e,t,o.startTimeAccessor,0))||0),stage:"project filed",viability:Zr(e,t,o.initialViability,100)}}(t,s,r,o,i);return{...a,viability:e.viability?.(a,{negativeProperties:i,positiveProperties:n})??ss(a,n,i)}}),a=s.flatMap((o,r)=>{const s=function(e,t,o,n){const i=function(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}(o),r=n?.(e,t,o)??{};return{...i,...r,startY:r.startY??r.routeY??i.startY,socketY:r.socketY??r.routeY??i.socketY,graveyardY:r.graveyardY??i.graveyardY}}(o,r,t,e.projectPlacement);return function(e,t,o,n,i,r,s){const a=ns(o),l=Math.max(3,28*a),c=n.startX,u=n.startY+(n.startY===o.routeY?38*t*a:0),d=s?.(e,t,o,n)??{},h=d.x??c,p=d.y??u,g={__gauntlet:!0,kind:"gauntlet-core",projectId:e.id,sourceDatum:e.datum},m=[{...d,id:Kr(e.id),x:h,y:p,vx:d.vx??42,vy:d.vy??0,mass:d.mass??7,bodyCollisions:d.bodyCollisions??!0,shape:d.shape??{type:"circle",radius:l},spawnAt:d.spawnAt??e.startedAt,datum:g}],f=is(h,p,d.shape&&"radius"in d.shape&&Number(d.shape.radius)||l,o);m[0].x=f.x,m[0].y=f.y;for(const t of e.activePositiveIds){const n=i.get(t);if(!n)continue;const r=rs(e.activePositiveIds,t,a),s=n.radius??Math.max(2,10*a),l=is(f.x+Math.cos(r.angle)*r.radius,f.y+Math.sin(r.angle)*r.radius,s,o);m.push({id:Jr(e.id,t),x:l.x,y:l.y,vx:18*Math.cos(r.angle),vy:18*Math.sin(r.angle),mass:n.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:d.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:"gauntlet-positive",projectId:e.id,property:n,sourceDatum:e.datum},springs:!1===n.spring?[]:[{target:{type:"body",bodyId:Kr(e.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+r.index%2*4)*a),...n.spring??{}}]})}return e.negativeIds.forEach((t,n)=>{const i=r.get(t);i&&m.push(function(e,t,o,n,i,r,s){const a=ns(r),l=t.radius??Math.max(2,7.2*a),c=is(n+(o%4*12-12)*a,i+(54+12*Math.floor(o/4))*a,l,r);return{id:es(e.id,t.id,o),x:c.x,y:c.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:l},spawnAt:s,datum:{__gauntlet:!0,kind:"gauntlet-negative",projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:Kr(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+o%4*3)*a),...t.spring??{}}]}}(e,i,n,f.x,f.y,o,d.spawnAt??e.startedAt))}),m}(o,r,t,s,n,i,e.coreBody)});return{layout:t,initialSpawns:a,config:{fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7},colliders:Qr(t)}}}var ls=1e-9;function cs(e,t){return t>e?-1:e>t?1:0}function us(e){return{...e}}function ds(e){return e.map(e=>({...e,sourceIds:e.sourceIds?[...e.sourceIds]:void 0,productIds:e.productIds?[...e.productIds]:void 0,relationIds:e.relationIds?[...e.relationIds]:void 0,outletIds:e.outletIds?[...e.outletIds]:void 0}))}function hs(e){const t=Object.fromEntries(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:us(t.initialMetrics),metrics:us(t.metrics),productIds:[...t.productIds],history:ds(t.history)}])),o=Object.fromEntries(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:us(t.metrics),sourceIds:[...t.sourceIds],history:ds(t.history)}])),n=Object.fromEntries(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?us(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:o,relations:n,input:{amount:e.input.amount,metrics:us(e.input.metrics)},metrics:us(e.metrics),loss:{amount:e.loss.amount,metrics:us(e.loss.metrics)},history:ds(e.history)}}function ps(e,t,o,n,i){return{severity:e,code:t,message:o,path:n,ids:i?[...i]:void 0}}function gs(e){const t=new Set,o=new Set;for(const n of e)t.has(n)&&o.add(n),t.add(n);return[...o].sort(cs)}function ms(e,t){return e?Object.entries(e).flatMap(([e,o])=>Number.isFinite(o)?[]:[ps("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function fs(e,t){for(const[o,n]of Object.entries(t))e[o]=Number(e[o]??0)+n}function ys(e,t,o="selector"){const n=[],i=Object.values(e.components),r=new Set(i.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&n.push(ps("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,o+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||n.push(ps("error","invalid-selector-count","Selector count must be a non-negative integer.",o+".count")),n.some(e=>"error"===e.severity))return{ids:[],diagnostics:n};const a=t.ids?new Set(t.ids):null,l=t.categories?new Set(t.categories):null,c=t.statuses?new Set(t.statuses):null,u=t.outletIds?new Set(t.outletIds):null;let d=i.filter(e=>!a||a.has(e.id)).filter(e=>!l||l.has(e.category)).filter(e=>!c||c.has(e.status)).filter(e=>!u||void 0!==e.outletId&&u.has(e.outletId)).map(e=>e.id).sort(cs);return void 0!==t.count&&(d=d.slice(0,t.count)),d.length||n.push(ps("warning","empty-selector","Selector matched no source components.",o)),{ids:d,diagnostics:n}}function bs(e,t,o={}){return{eventId:e.event.id,effectType:t.type,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,label:e.event.label,summary:e.event.summary,...o}}function xs(e,t){const o={...t,eventId:e.event.id};e.materializations.push(o),e.observations.push({...o,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function vs(e,t,o){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(ps("error","unknown-outlet",`Unknown outlet "${t}".`,o,[t])),1))}function ws(e,t,o){const n=gs(t);t.length||e.diagnostics.push(ps("error","empty-source-list","A product requires at least one source component.",o)),n.length&&e.diagnostics.push(ps("error","duplicate-source",`Source ids may appear only once: ${n.join(", ")}.`,o,n));const i=t.filter(t=>!e.state.components[t]);i.length&&e.diagnostics.push(ps("error","unknown-component",`Unknown source component id${1===i.length?"":"s"}: ${i.join(", ")}.`,o,i));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,o,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(ps("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,o,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function As(e,t,o,n,i){const r=n?.amount??0;(!Number.isFinite(r)||0>r||r>t+ls)&&e.diagnostics.push(ps("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",i+".amount")),e.diagnostics.push(...ms(n?.metrics,i+".metrics"));for(const[t,r]of Object.entries(n?.metrics??{}))(0>r||r>Number(o[t]??0)+ls)&&e.diagnostics.push(ps("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${i}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function Ss(e,t,o,n,i,r,s){return{id:e.id,label:e.label??e.id,description:e.description,category:e.category??"product",color:e.color,order:e.order,declaredAmount:e.amount,amount:r&&void 0!==e.amount?e.amount:o,metrics:r&&e.metrics?{...n,...e.metrics}:n,status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(i.outletIds.has("product")?"product":void 0):void 0,createdByEventId:i.event.id,createdAt:i.context.appliedAt,completedByEventId:r?i.event.id:void 0,completedAt:r?i.context.appliedAt:void 0,history:[s]}}function ks(e,t,o,n){void 0!==t.amount&&Math.abs(t.amount-o)>ls&&e.diagnostics.push(ps("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${o}.`,n,[t.id]))}function Ms(e,t,o){const n=`events.${e.event.id}.effects.${o}`,i=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(ps("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,n+".state")),e.diagnostics.push(...ms(t.metricsDelta,n+".metricsDelta")),vs(e,t.outletId,n+".outletId");const o=ys(i,t.select,n+".select");e.diagnostics.push(...o.diagnostics);const r=o.ids.filter(e=>i.components[e].productIds.length);if(r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Assigned source components cannot be retargeted: ${r.join(", ")}.`,n+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=bs(e,t,{sourceIds:o.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of o.ids){const o=i.components[e];o.status=t.state,o.outletId=t.outletId,o.reason=t.reason,t.metricsDelta&&fs(o.metrics,t.metricsDelta),o.history.push(s)}return i.history.push(s),void(o.ids.length&&xs(e,{type:"retarget-component",sourceIds:o.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:o}=t;o.id&&!i.relations[o.id]||e.diagnostics.push(ps("error","duplicate-relation",`Relation id "${o.id}" is missing or already active.`,n+".relation.id",[o.id]));const r=function(e,t,o){const n=gs(t),i=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(ps("error","insufficient-relation-sources","A relation requires at least two source components.",o)),n.length&&e.diagnostics.push(ps("error","duplicate-source",`Relation source ids must be unique: ${n.join(", ")}.`,o,n)),i.length&&e.diagnostics.push(ps("error","unknown-component",`Relation references unknown source component${1===i.length?"":"s"}: ${i.join(", ")}.`,o,i)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,o.sourceIds,n+".relation.sourceIds");if(e.diagnostics.push(...ms(o.metrics,n+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;i.relations[o.id]={...o,sourceIds:[...o.sourceIds],metrics:o.metrics?{...o.metrics}:void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=bs(e,t,{sourceIds:[...o.sourceIds],relationIds:[o.id]});return i.history.push(s),void xs(e,{type:"activate-relation",sourceIds:[...o.sourceIds],relationIds:[o.id]})}if("resolve-relation"===t.type){const o=gs(t.relationIds),r=t.relationIds.filter(e=>!i.relations[e]),s=t.relationIds.filter(e=>"resolved"===i.relations[e]?.status);if(o.length&&e.diagnostics.push(ps("error","duplicate-relation","Relation ids must be unique.",n+".relationIds",o)),r.length&&e.diagnostics.push(ps("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,n+".relationIds",r)),s.length&&e.diagnostics.push(ps("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,n+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const o of t.relationIds){const n=i.relations[o];n.status="resolved",n.resolution=t.resolution,n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt,n.reason=t.reason}const a=bs(e,t,{relationIds:[...t.relationIds]});return i.history.push(a),void xs(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const o=e.productDefinitions.get(t.productId);o||e.diagnostics.push(ps("error","unknown-product",`Product "${t.productId}" has no declared mold.`,n+".productId",[t.productId]));const r=i.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(ps("error","duplicate-product",`Product "${t.productId}" has already been formed.`,n+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(ps("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,n+".productId",[t.productId]));const s=ws(e,t.sourceIds,n+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,l=function(e,t,o,n){if(!t?.length)return[];const i=gs(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(o),l=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return i.length&&e.diagnostics.push(ps("error","duplicate-relation","Basis relations must be unique.",n,i)),r.length&&e.diagnostics.push(ps("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,n,r)),s.length&&e.diagnostics.push(ps("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,n,s)),l.length&&e.diagnostics.push(ps("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${l.join(", ")}.`,n,l)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,n+".basisRelationIds");if(!s||!l||!o||e.diagnostics.some(e=>"error"===e.severity))return;const c=s.reduce((e,t)=>e+t.amount,0),u=function(e){const t={};for(const o of e)fs(t,o.metrics);return t}(s);if(!As(e,c,u,t.loss,n+".loss"))return;const d=c-(t.loss?.amount??0);!function(e,t,o){e.state.loss.amount+=o?.amount??0;for(const[n,i]of Object.entries(o?.metrics??{}))t[n]=Number(t[n]??0)-i,e.state.loss.metrics[n]=Number(e.state.loss.metrics[n]??0)+i}(e,u,t.loss);const h="combine"===t.type&&!1!==t.complete,p=bs(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let g;if("combine"===t.type){if(h&&ks(e,o,d,n+".productId"),g=Ss(o,t.sourceIds,d,u,e,h,p),h&&!vs(e,g.outletId,n+".productId"))return;i.products[t.productId]=g}else g=r,g.sourceIds.push(...t.sourceIds),g.amount+=d,fs(g.metrics,u),g.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return i.history.push(p),function(e,t){if(t.length){for(const o of t)o.status="resolved",o.resolution="combined",o.resolvedByEventId=e.event.id,o.resolvedAt=e.context.appliedAt;xs(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,l),xs(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:g.outletId?[g.outletId]:void 0}),void(h&&xs(e,{type:"complete-product",sourceIds:[...g.sourceIds],productIds:[g.id],outletIds:g.outletId?[g.outletId]:void 0}))}if("complete-product"===t.type){const o=i.products[t.productId];return o?void function(e,t,o,n,i,r){const s=e.productDefinitions.get(t.id),a=o??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!vs(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(ps("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(ks(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics={...t.metrics,...s.metrics})),t.status="complete",t.outletId=a,t.reason=n,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const l=bs(e,i,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(l),e.state.history.push(l),xs(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,o,t.outletId,t.reason,t,n):void e.diagnostics.push(ps("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,n+".productId",[t.productId]))}if("split"===t.type){const o=ws(e,[t.sourceId],n+".sourceId");t.products.length||e.diagnostics.push(ps("error","empty-split","A split requires at least one product allocation.",n+".products"));const r=t.products.map(e=>e.productId),s=gs(r);s.length&&e.diagnostics.push(ps("error","duplicate-product","Split product ids must be unique.",n+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),l=r.filter((e,t)=>!a[t]),c=r.filter(e=>i.products[e]);l.length&&e.diagnostics.push(ps("error","unknown-product",`Split references undeclared product molds: ${l.join(", ")}.`,n+".products",l)),c.length&&e.diagnostics.push(ps("error","duplicate-product",`Split products already exist: ${c.join(", ")}.`,n+".products",c));for(const[o,i]of t.products.entries())void 0===i.amount||Number.isFinite(i.amount)&&i.amount>=0||e.diagnostics.push(ps("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${n}.products.${o}.amount`)),e.diagnostics.push(...ms(i.metrics,`${n}.products.${o}.metrics`));if(!o?.length||e.diagnostics.some(e=>"error"===e.severity))return;const u=o[0];if(!As(e,u.amount,u.metrics,t.loss,n+".loss"))return;const d=u.amount-(t.loss?.amount??0),h=t.products.map((e,t)=>e.amount??a[t]?.amount),p=h.filter(e=>void 0!==e).length;if(0!==p&&p!==h.length)return void e.diagnostics.push(ps("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",n+".products"));const g=p?h:t.products.map(()=>d/t.products.length),m=g.reduce((e,t)=>e+t,0);if(Math.abs(m-d)>ls)return void e.diagnostics.push(ps("error","split-amount-mismatch",`Split allocations total ${m}, but ${d} remains after loss.`,n+".products"));const f={...u.metrics};for(const[e,o]of Object.entries(t.loss?.metrics??{}))f[e]=Number(f[e]??0)-o;const y=bs(e,t,{sourceIds:[u.id],productIds:r});if(t.products.forEach((o,r)=>{const s=a[r],l=d>ls?g[r]/d:1/t.products.length,c=Object.fromEntries(Object.entries(f).map(([e,t])=>[e,t*l])),h=o.metrics??s.metrics??c,p=Ss({...s,amount:g[r],metrics:h},[u.id],g[r],{...h},e,!0,y);vs(e,p.outletId,`${n}.products.${r}.productId`)&&(i.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;u.productIds=r,u.status="consumed",u.outletId=void 0,u.history.push(y),i.loss.amount+=t.loss?.amount??0;for(const[e,o]of Object.entries(t.loss?.metrics??{}))i.loss.metrics[e]=Number(i.loss.metrics[e]??0)+o;i.history.push(y),xs(e,{type:"split-source",sourceIds:[u.id],productIds:r});for(const t of r)xs(e,{type:"complete-product",sourceIds:[u.id],productIds:[t],outletIds:i.products[t].outletId?[i.products[t].outletId]:void 0});return}if("eject"===t.type){vs(e,t.outletId,n+".outletId");const o=ys(i,t.select,n+".select");e.diagnostics.push(...o.diagnostics);const r=o.ids.filter(e=>i.components[e].productIds.length);if(r.length&&e.diagnostics.push(ps("error","source-already-assigned",`Assigned source components cannot be ejected: ${r.join(", ")}.`,n+".select",r)),e.diagnostics.some(e=>"error"===e.severity))return;const s=bs(e,t,{sourceIds:o.ids,outletIds:[t.outletId]});for(const e of o.ids){const o=i.components[e];o.status=t.state??"ejected",o.outletId=t.outletId,o.reason=t.reason,o.history.push(s)}return i.history.push(s),void(o.ids.length&&xs(e,{type:"retarget-component",sourceIds:o.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...ms(t.metricsDelta,n+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let o,r;if("run"===t.target)fs(i.metrics,t.metricsDelta);else if("components"in t.target){const r=ys(i,t.target.components,n+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;o=r.ids;for(const e of r.ids)fs(i.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const o=gs(r),s=r.filter(e=>!i.products[e]);if(o.length&&e.diagnostics.push(ps("error","duplicate-product","Metric target product ids must be unique.",n+".target.productIds",o)),s.length&&e.diagnostics.push(ps("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,n+".target.productIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const e of r)fs(i.products[e].metrics,t.metricsDelta)}return void i.history.push(bs(e,t,{sourceIds:o,productIds:r}))}t.outcome.trim()?(i.outcome=t.outcome,i.summary=t.summary,i.history.push(bs(e,t)),e.observations.push({type:"crucible-outcome",eventId:e.event.id,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt,outcome:t.outcome})):e.diagnostics.push(ps("error","invalid-outcome","Outcome must be a non-empty string.",n+".outcome"))}function _s(e,t,o){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[ps("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const n=hs(e),i={state:n,event:t,context:o,productDefinitions:new Map(o.products.map(e=>[e.id,e])),outletIds:new Set(o.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[o,n]of t.effects.entries())if(Ms(i,n,o),i.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:i.diagnostics};return n.elapsed=Math.max(n.elapsed,o.appliedAt),n.phaseId=o.phaseId,n.eventsApplied.push(t.id),i.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:o.phaseId,authoredAt:o.authoredAt,appliedAt:o.appliedAt}),{applied:!0,state:n,materializations:i.materializations,observations:i.observations,diagnostics:i.diagnostics}}var Ps=[900,520],Ts=[{id:"product",label:"Products",side:"bottom",order:0},{id:"retained",label:"Retained",side:"bottom",order:1},{id:"residue",label:"Residue",side:"left",order:2},{id:"failed",label:"Failed",side:"right",order:3},{id:"recovered",label:"Recovered",side:"right",order:4}],Ls=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Rs=1e-9;function Is(e,t){return t>e?-1:e>t?1:0}function Cs(e,t,o,n,i){return{severity:e,code:t,message:o,path:n,ids:i?[...i]:void 0}}function zs(e){const t=new Set,o=new Set;for(const n of e)t.has(n)&&o.add(n),t.add(n);return[...o].sort(Is)}function Fs(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Os(e,t,o,n,i,r){if(!o)return n;try{return("function"==typeof o?o(e,t):e[o])??n}catch(e){return i.push(Cs("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),n}}function Bs(e,t,o){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(Cs("error","invalid-metrics","Metrics must be a numeric object.",o)),{};const n={};for(const[i,r]of Object.entries(e)){const e=Fs(r);null!=e?n[i]=e:t.push(Cs("error","invalid-metric",`Metric "${i}" must be finite.`,`${o}.${i}`))}return n}function Ns(e){return e.map((e,t)=>({outlet:e,index:t})).sort((e,t)=>(e.outlet.order??e.index)-(t.outlet.order??t.index)||e.index-t.index).map(({outlet:e})=>({...e}))}function Es(e){const{id:t,orientation:o,fixed:n,start:i,end:r,openings:s,thickness:a,friction:l,restitution:c}=e,u=function(e,t,o){const n=o.map(([o,n])=>[Math.max(e,Math.min(o,n)),Math.min(t,Math.max(o,n))]).filter(([e,t])=>t>e+Rs).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),i=[];let r=e;for(const[e,t]of n)e>r+Rs&&i.push([r,e]),r=Math.max(r,t);return t>r+Rs&&i.push([r,t]),i}(i,r,s);return u.map(([e,i],r)=>({id:1===u.length?t:`${t}:${r}`,friction:l,restitution:c,shape:"horizontal"===o?{type:"segment",x1:e,y1:n,x2:i,y2:n,thickness:a}:{type:"segment",x1:n,y1:e,x2:n,y2:i,thickness:a}}))}function js(e){let t=2166136261;for(let o=0;e.length>o;o+=1)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return t>>>0}function $s(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?js(e):1}function Ds(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:$s(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function Ws(e){return"crucible:component:"+encodeURIComponent(e)}function Ys(e,t,o,n){if(void 0!==o&&Number.isFinite(o)&&o>0)return o;const i=Math.min(...t,e),r=Math.max(...t,e);return r-i>Rs?n[0]+(n[1]-n[0])*Math.sqrt(Math.max(0,e-i)/(r-i)):(n[0]+n[1])/2}function Vs(e,t){const o=Math.max(.25,Math.min(1,t.width/900,t.height/520)),n=e?.[0]??7*o,i=e?.[1]??18*o,r=Math.max(1,Math.min(n,i));return[r,Math.max(r,Math.max(n,i))]}function Hs(e,t){if(!e)return[];const o=Math.min(e,Math.max(1,Math.ceil(Math.sqrt(e*Math.max(.5,t.width/Math.max(1,t.height)))))),n=Math.max(1,Math.ceil(e/o));return Array.from({length:e},(e,i)=>({x:t.x+t.width/o*(i%o+.5),y:t.y+(Math.floor(i/o)+.5)*(t.height/n)}))}function Gs(e){return e.outletId?e.outletId:"failed"===e.status?"failed":"recovered"===e.status?"recovered":"retained"===e.status?"retained":"ejected"===e.status?"residue":void 0}function Xs(e,t){return e.outlets.find(e=>e.id===t)||{x:e.chamber.x+.18*e.chamber.width,y:e.chamber.y+.2*e.chamber.height,width:.64*e.chamber.width,height:.6*e.chamber.height}}function qs(e,t,o={}){const n=Object.values(e.products).sort((e,t)=>Is(e.id,t.id)),i=Object.values(e.components).sort((e,t)=>Is(e.id,t.id)),r=[...i.map(e=>e.amount),...n.map(e=>e.amount)],s=Vs(o.radiusRange,t),a=function(e,t){const o=new Map;for(const t of e){const e=t.outletId??"__chamber__",n=o.get(e)??[];n.push(t),o.set(e,n)}const n=new Map;for(const[e,i]of o){i.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||Is(e.id,t.id));const o=Hs(i.length,Xs(t,"__chamber__"===e?void 0:e));i.forEach((e,t)=>n.set(e.id,o[t]))}return n}(n,t),l=n.map(e=>{const n=a.get(e.id)??{x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2},i=1.28*Ys(e.amount,r,o.bodyRadius,s),l={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:(c=e.id,"crucible:product:"+encodeURIComponent(c)),x:n.x,y:n.y,mass:Math.max(.25,i*i*.018),bodyCollisions:!1,shape:{type:"circle",radius:i},datum:l};var c}),c=new Map;for(const e of i.filter(e=>!e.productIds.length)){const t=Gs(e)??"__chamber__",o=c.get(t)??[];o.push(e),c.set(t,o)}const u=new Map;for(const[e,o]of c){const n=Hs(o.length,Xs(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>u.set(e.id,n[t]))}return[...i.map(e=>{let n=u.get(e.id);if(e.productIds.length){const o=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(o.length){n={x:o.reduce((e,t)=>e+t.x,0)/o.length,y:o.reduce((e,t)=>e+t.y,0)/o.length};const i=js(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));n={x:n.x+Math.cos(i)*r,y:n.y+Math.sin(i)*r}}}n??(n={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const i=Ys(e.amount,r,o.bodyRadius,s),l={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:Ws(e.id),x:n.x,y:n.y,mass:Math.max(.25,i*i*.015),shape:{type:"circle",radius:i},datum:l}}),...l]}var Us=qs;function Qs(e){return Array.isArray(e)?e.map(Qs):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>Is(e,t)).map(([e,t])=>[e,Qs(t)])):e}function Zs(e,t=e.duration){const o=function(e,t){const o=Fs(t)??0,n=Math.max(0,Math.min(e.duration,o));if(!e.phases.length)return{elapsed:n,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const i=n>=e.duration-Rs,r=i?e.phases[e.phases.length-1]:e.phases.find(e=>n>=e.start&&e.end>n)??e.phases[0];return{elapsed:n,phaseId:r.id,phaseIndex:r.index,phaseElapsed:i?r.duration:Math.max(0,n-r.start),complete:i}}(e,t);let n=hs(e.initialState);const i=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>o.elapsed+Rs)break;const a=_s(n,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});i.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(n=a.state)}return n.elapsed=o.elapsed,n.phaseId=o.phaseId,n.phaseIndex=o.phaseIndex,n.phaseElapsed=o.phaseElapsed,n.complete=o.complete,o.complete&&"in_process"===n.outcome&&(n.outcome="complete"),n.playing=!1,{state:n,diagnostics:i,materializations:r,observations:s}}function Ks(e){const t=function(e){const t=[];e.length||t.push(Cs("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const o=zs(e.map(e=>e.id));o.length&&t.push(Cs("error","duplicate-phase-id",`Phase ids must be unique: ${o.join(", ")}.`,"phases",o));let n=0;return{phases:e.map((e,o)=>{const i=Fs(e.duration),r=null!=i&&i>0?i:0;e.id.trim()||t.push(Cs("error","invalid-phase-id","Phase ids may not be empty.",`phases.${o}.id`)),null!=i&&i>0||t.push(Cs("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${o}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(Cs("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${o}.intensity`,[e.id]));const s={...e,duration:r,intensity:void 0===e.intensity?.5:Number.isFinite(e.intensity)?Math.max(0,Math.min(1,e.intensity)):.5,motion:e.motion??"hold",index:o,start:n,end:n+r};return n=s.end,s}),diagnostics:t}}(e.phases),o=t.phases.at(-1)?.end??0,n=Ns(e.outlets??Ts),i=(e.products??[]).map(e=>({...e,metrics:e.metrics?{...e.metrics}:void 0})),r=function(e,t,o){const n=[],i=zs(e.map(e=>e.id));i.length&&n.push(Cs("error","duplicate-event-id",`Event ids must be unique: ${i.join(", ")}.`,"events",i));const r=[];return e.forEach((e,i)=>{let s,a,l;if(e.id.trim()||n.push(Cs("error","invalid-event-id","Event ids may not be empty.",`events.${i}.id`)),"time"in e.at&&void 0!==e.at.time){const r=Fs(e.at.time);if(null==r||0>r||r>o+Rs)return void n.push(Cs("error","event-time-out-of-range",`Event time must fall between 0 and ${o}.`,`events.${i}.at.time`,[e.id]));s=Math.max(0,Math.min(o,r));const c=function(e,t,o){const n=e.find(e=>Rs>=Math.abs(e.start-o));if(n)return{phase:n,boundaryRank:1};const i=e.find(e=>o>=e.start&&e.end>o);return i?{phase:i,boundaryRank:0}:Rs>=Math.abs(o-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,o,s);a=c.phase,l=c.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void n.push(Cs("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${i}.at.phaseId`,[e.id,e.at.phaseId]));const o=e.at.progress??0;if(!Number.isFinite(o)||0>o||o>1)return void n.push(Cs("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${i}.at.progress`,[e.id]));s=a.start+a.duration*o,l=0===o?1:0}a?r.push({...e,index:i,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:l}):n.push(Cs("error","event-without-phase","Event could not be assigned to a phase.",`events.${i}.at`,[e.id]))}),r.sort((e,t)=>e.authoredAt-t.authoredAt||e.boundaryRank-t.boundaryRank||e.index-t.index),{events:r,diagnostics:n}}(e.events??[],t.phases,o),s=function(e){const t=[],o={},n=[];let i=0;const r={};e.data.forEach((s,a)=>{const l=(s.id??"component-"+a)+"",c=((Os(s,a,e.idAccessor,l,t,`data.${a}.id`)??l)+"").trim();if(!c)return void t.push(Cs("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));n.push(c);const u=Fs(Os(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),d=null==u||0>u?0:u;(null==u||0>u)&&t.push(Cs("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[c]));const h=Bs(Os(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=Os(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),g=Ls.has(p)?p:"active";Ls.has(p)||t.push(Cs("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[c]));const m=Os(s,a,e.labelAccessor,(s.label??s.name??c)+"",t,`data.${a}.label`)+"",f=Os(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";o[c]||(o[c]={id:c,label:m,category:f,datum:s,status:g,initialAmount:d,amount:d,initialMetrics:{...h},metrics:{...h},productIds:[],history:[]},i+=d,function(e,t){for(const[o,n]of Object.entries(t))e[o]=Number(e[o]??0)+n}(r,h))});const s=zs(n);s.length&&t.push(Cs("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=Bs(e.metrics??{},t,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:e.phases[0]?.id??"",phaseIndex:e.phases.length?0:-1,playing:!1,complete:0===e.phases.length,outcome:"in_process",eventsApplied:[],components:o,products:{},relations:{},input:{amount:i,metrics:r},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:t}}(e),a=function(e=Ps,t=Ts){const o=Math.max(1,Fs(e[0])??900),n=Math.max(1,Fs(e[1])??520),i=360>o||260>n,r=i?Math.max(4,.035*Math.min(o,n)):20,s=i?Math.max(10,.075*n):34,a={x:r,y:r,width:Math.max(1,o-2*r),height:s},l=i?Math.max(16,.14*n):Math.min(78,.16*n),c={x:r,y:n-r-l,width:Math.max(1,o-2*r),height:l},u=i?Math.max(12,.08*o):Math.min(150,.17*o),d=a.y+a.height+(i?12:38),h=c.y-(i?10:34),p={x:u,y:d,width:Math.max(24,o-2*u),height:Math.max(24,h-d)},g=Math.max(18,Math.min(.32*p.width,i?84:180)),m={x:p.x+(p.width-g)/2,y:p.y-(i?10:24),width:g,height:i?12:28},f=Ns(t),y={left:f.filter(e=>"left"===(e.side??"bottom")),right:f.filter(e=>"right"===e.side),bottom:f.filter(e=>"bottom"===(e.side??"bottom"))},b=[],x=(e,t)=>{const n=Math.max(8,u-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:o-r-n,y:p.y+a*s,width:n,height:Math.max(8,s-(i?2:8))})})};x("left",y.left),x("right",y.right);const v=p.width/Math.max(1,y.bottom.length);return y.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*v,y:p.y+p.height+(i?2:7),width:Math.max(8,v-(i?2:8)),height:Math.max(8,c.y-p.y-p.height-(i?4:12))})}),b.sort((e,t)=>f.findIndex(t=>t.id===e.id)-f.findIndex(e=>e.id===t.id)),{width:o,height:n,phaseRail:a,chamber:p,mouth:m,projection:c,outlets:b}}(e.size??Ps,n),l=function(e){const{chamber:t,mouth:o}=e,n=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),i=Math.max(t.x,o.x),r=Math.min(t.x+t.width,o.x+o.width),s={left:e.outlets.filter(e=>"left"===e.side),right:e.outlets.filter(e=>"right"===e.side),bottom:e.outlets.filter(e=>"bottom"===e.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:t.x,y1:t.y,x2:i,y2:t.y,thickness:n}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:r,y1:t.y,x2:t.x+t.width,y2:t.y,thickness:n}}];a.push(...Es({id:"crucible:wall:left",orientation:"vertical",fixed:t.x,start:t.y,end:t.y+t.height,openings:s.left.map(e=>[e.y,e.y+e.height]),thickness:n,friction:.46,restitution:.12}),...Es({id:"crucible:wall:right",orientation:"vertical",fixed:t.x+t.width,start:t.y,end:t.y+t.height,openings:s.right.map(e=>[e.y,e.y+e.height]),thickness:n,friction:.46,restitution:.12}),...Es({id:"crucible:wall:bottom",orientation:"horizontal",fixed:t.y+t.height,start:t.x,end:t.x+t.width,openings:s.bottom.map(e=>[e.x,e.x+e.width]),thickness:n,friction:.5,restitution:.08}));for(const t of e.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(t.id),sensor:!0,shape:{type:"aabb",x:t.x+t.width/2,y:t.y+t.height/2,width:t.width,height:t.height}});return a}(a),c=function(e,t){const o=[],n=new Set(t.map(e=>e.id)),i=zs(t.map(e=>e.id)),r=zs(e.map(e=>e.id));return i.length&&o.push(Cs("error","duplicate-outlet-id",`Outlet ids must be unique: ${i.join(", ")}.`,"outlets",i)),r.length&&o.push(Cs("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||o.push(Cs("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||o.push(Cs("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||o.push(Cs("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||o.push(Cs("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${t}.amount`,[e.id])),void 0===e.outletId||n.has(e.outletId)||o.push(Cs("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),Bs(e.metrics??{},o,`products.${t}.metrics`)}),o}(i,n),u=(d={seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>Is(e.id,t.id)).map(e=>({id:e.id,label:e.label,category:e.category,amount:e.amount,metrics:e.metrics,status:e.status})),phases:t.phases.map(({id:e,duration:t,label:o,description:n,intensity:i,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:o,description:n,intensity:i,motion:r,color:s,metrics:a})),products:i,outlets:n,events:r.events.map(({id:e,label:t,description:o,summary:n,authoredAt:i,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:o,summary:n,authoredAt:i,phaseId:r,boundaryRank:s,effects:a}))},JSON.stringify(Qs(d)));var d;const h=function(e,t,o={}){const n=Object.values(e.components).sort((e,t)=>Is(e.id,t.id)),i=n.map(e=>e.amount),r=Vs(o.radiusRange,t),s=function(e){let t=e>>>0;return()=>{t+=1831565813;let e=t;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296}}($s(o.seed)),a=t.mouth.x+t.mouth.width/2,l=t.chamber.y+Math.max(18,.18*t.chamber.height),c=Math.max(4,.28*t.chamber.width),u=Math.max(4,.12*t.chamber.height);return n.map((e,t)=>{const d=t/Math.max(1,n.length)*Math.PI*2+.18*(s()-.5),h=Ys(e.amount,i,o.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:Ws(e.id),x:a+Math.cos(d)*c*(.45+.45*s()),y:l+Math.sin(d)*u*(.45+.45*s()),vx:24*(s()-.5),vy:18*(s()-.5),mass:Math.max(.25,h*h*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:h},datum:p}})}(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...c],g={phases:t.phases,events:r.events,products:i,outlets:n,duration:o,initialState:s.state,terminalState:s.state,layout:a,colliders:l,config:Ds(e.seed,l),initialSpawns:h,terminalSpawns:[],semanticKey:u,diagnostics:p},m=Zs(g),f=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),y=f.length?[Cs("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${f.join(", ")}.`,"events",f)]:[];return g.terminalState=m.state,g.terminalSpawns=Us(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),g.diagnostics=[...p,...m.diagnostics,...y],g}import*as Js from"react";import{jsx as ea,jsxs as ta}from"react/jsx-runtime";function oa(e){return Number.isFinite(e)?1e3>Math.abs(e)?Number.isInteger(e)?e+"":e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):e.toLocaleString():"0"}function na(e,t,o,n){const i=e.datum;if(!i?.__crucible)return;const r="circle"===e.shape.type?e.shape.radius:8,s="string"==typeof t.fill?t.fill:"product"===i.kind?"#b8792d":"#356b63",a="string"==typeof t.stroke?t.stroke:"#26323a",l="number"==typeof t.strokeWidth?t.strokeWidth:1.25,c="number"==typeof t.opacity?t.opacity:.96,u=n?`${n}-crucible-body-${o}`:"crucible-body-"+o;if("product"===i.kind){const t=Array.from({length:6},(t,o)=>{const n=-Math.PI/2+o/6*Math.PI*2;return`${e.x+Math.cos(n)*r},${e.y+Math.sin(n)*r}`}).join(" "),o=u+"-glow";return ta(Js.Fragment,{children:[ea("defs",{children:ea("filter",{id:o,x:"-60%",y:"-60%",width:"220%",height:"220%",children:ea("feDropShadow",{dx:"0",dy:"0",stdDeviation:"4",floodColor:s,floodOpacity:"0.8"})})}),ea("polygon",{points:t,fill:s,stroke:a,strokeWidth:l,opacity:c,filter:`url(#${o})`}),ea("circle",{cx:e.x,cy:e.y,r:Math.max(2,.36*r),fill:"none",stroke:"var(--semiotic-bg, #fffaf0)",strokeWidth:l,opacity:.72*c})]},u)}return ta(Js.Fragment,{children:[ea("circle",{cx:e.x,cy:e.y,r:r,fill:s,stroke:a,strokeWidth:l,opacity:c}),ea("circle",{cx:e.x-.25*r,cy:e.y-.28*r,r:Math.max(1,.18*r),fill:"rgba(255,255,255,0.34)"})]},u)}import{Fragment as ia,jsx as ra,jsxs as sa}from"react/jsx-runtime";var aa="var(--semiotic-text, #26323a)",la="var(--semiotic-text-secondary, #6c7377)",ca="var(--semiotic-primary, #b8792d)",ua="var(--semiotic-danger, #9f3d35)",da="var(--semiotic-success, #356b63)";function ha(e){const{x:t,y:o,width:n,height:i}=e.chamber,r=Math.min(.14*n,48),s=o+i;return[`M ${t} ${o}`,`L ${t+r} ${s-.16*i}`,`Q ${t+n/2} ${s+.1*i} ${t+n-r} ${s-.16*i}`,`L ${t+n} ${o}`].join(" ")}function pa({layout:e,phases:t,state:o,compact:n=!1}){const i=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return sa("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[sa("defs",{children:[sa("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[ra("stop",{offset:"0",stopColor:ca,stopOpacity:"0.03"}),ra("stop",{offset:"0.66",stopColor:ca,stopOpacity:"0.1"}),ra("stop",{offset:"1",stopColor:ua,stopOpacity:"0.18"})]}),ra("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:ra("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:aa,strokeOpacity:"0.08",strokeWidth:"1"})})]}),ra("rect",{x:e.chamber.x,y:e.chamber.y,width:e.chamber.width,height:e.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:aa,strokeOpacity:"0.52",strokeWidth:n?1:2.2}),ra("path",{d:ha(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),ra("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:aa,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:n?2:5}),n?null:ra("g",{"data-testid":"crucible-phase-rail",children:t.map((n,r)=>{const s=t.slice(0,r).reduce((e,t)=>e+Math.max(0,t.duration),0),a=e.phaseRail.x+s/i*e.phaseRail.width,l=Math.max(0,n.duration)/i*e.phaseRail.width,c=n.id===o.phaseId,u=o.phaseIndex>r||o.complete;return sa("g",{children:[ra("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,l-2),height:e.phaseRail.height,rx:2,fill:c?n.color??ca:u?da:aa,fillOpacity:c?.68:u?.28:.09}),46>l?null:ra("text",{x:a+l/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:c?aa:la,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:c?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(n.label??n.id).toUpperCase()})]},n.id)})}),e.outlets.map(e=>sa("g",{children:[ra("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?ua:da),fillOpacity:"0.1",stroke:e.color??("left"===e.side?ua:da),strokeDasharray:"3 3",strokeOpacity:"0.62"}),n?null:ra("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:la,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function ga({rows:e,layout:t,projection:o,amountLabel:n}){if(!e.length)return null;const i=o.measure??"count",r=e.map(e=>Math.max(0,function(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}(e,i))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),l=t.projection.height>48?21:4,c=Math.max(5,t.projection.height-l-5);return ra("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:e.map((e,o)=>{const u=r[o],d=Math.max(u>0?2:0,u/s*c),h=t.projection.x+o*a+.18*a;return sa("g",{children:[ra("rect",{x:h,y:t.projection.y+c-d,width:Math.max(3,.64*a),height:d,rx:2,fill:"failed"===e.status||"ejected"===e.status?ua:"complete"===e.status?ca:da,fillOpacity:"0.68"}),l>4&&a>=34?sa(ia,{children:[ra("text",{x:h+.32*a,y:t.projection.y+c+10,fill:la,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),sa("text",{x:h+.32*a,y:t.projection.y+c+19,fill:aa,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[oa(u),"amount"===i&&n?" "+n:""]})]}):null]},e.key)})})}function ma(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function fa(e){return e.map(e=>({...e,spawnAt:void 0}))}function ya(e,t){return e?t?o=>_r.createElement(_r.Fragment,null,e,"function"==typeof t?t(o):t):e:t}var ba=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function xa(e){let t=2166136261;for(let o=0;e.length>o;o+=1)t^=e.charCodeAt(o),t=Math.imul(t,16777619);return ba[(t>>>0)%ba.length]}var va={Sparkline:{frameType:"xy",layout:{mode:"sparkline"},buildProps:(e,t,o,n,i)=>({chartType:"line",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",groupAccessor:i.lineBy||t,colorAccessor:t,...n,showAxes:!1,margin:n.margin,showLegend:!1,showGrid:!1,title:void 0})},BumpChart:Go,LineChart:qo,AreaChart:Qo,DifferenceChart:Zo,StackedAreaChart:Ko,Scatterplot:en,CandlestickChart:Jo,BubbleChart:Ho,ConnectedScatterplot:on,QuadrantChart:tn,Heatmap:nn,TemporalHistogram:Uo,XYCustomChart:{frameType:"xy",buildProps:(e,t,o,n,i)=>({chartType:"custom",data:e,xAccessor:i.xAccessor||"x",yAccessor:i.yAccessor||"y",colorAccessor:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n,showAxes:i.frameProps?.showAxes??i.showAxes??!1,showLegend:n.showLegend??!!t})},BarChart:Pn,StackedBarChart:Tn,GroupedBarChart:Ln,PieChart:Rn,DonutChart:In,Histogram:Cn,BoxPlot:zn,ViolinPlot:Fn,SwarmPlot:On,DotPlot:Bn,SwimlaneChart:Nn,RidgelinePlot:En,LikertChart:jn,FunnelChart:$n,GaugeChart:Dn,OrdinalCustomChart:{frameType:"ordinal",buildProps:(e,t,o,n,i)=>({chartType:"custom",data:e,oAccessor:i.categoryAccessor||i.oAccessor||"category",rAccessor:i.valueAccessor||i.rAccessor||"value",projection:i.projection||"vertical",colorAccessor:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n,showAxes:i.frameProps?.showAxes??i.showAxes??!1})},ForceDirectedGraph:pr,NetworkCustomChart:{frameType:"network",layout:{margin:{top:40,right:40,bottom:40,left:40}},buildProps:(e,t,o,n,i)=>({chartType:"force",nodes:i.nodes||e||[],edges:i.edges||[],nodeIDAccessor:i.nodeIdAccessor||i.nodeIDAccessor||"id",sourceAccessor:i.sourceAccessor||"source",targetAccessor:i.targetAccessor||"target",valueAccessor:i.valueAccessor||"value",colorBy:t,colorScheme:o,customNetworkLayout:i.layout||i.customNetworkLayout,layoutConfig:i.layoutConfig,...n})},SankeyDiagram:mr,ProcessSankey:gr,ChordDiagram:fr,TreeDiagram:yr,Treemap:br,CirclePack:xr,ChoroplethMap:Sr,ProportionalSymbolMap:kr,FlowMap:Mr,GeoCustomChart:{frameType:"geo",buildProps:(e,t,o,n,i)=>({points:i.points||e||[],areas:i.areas||[],lines:i.lines||[],projection:i.projection||"equirectangular",xAccessor:i.xAccessor||"lon",yAccessor:i.yAccessor||"lat",lineDataAccessor:i.lineDataAccessor,colorBy:t,colorScheme:o,customLayout:i.layout||i.customLayout,layoutConfig:i.layoutConfig,...n})},GaltonBoardChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s=i.bins??21,a=i.seed??1,l=Math.max(1,Math.round(i.pegRows??s-1)),c="mechanical"===i.mode,u=c?function(e){const t=Math.max(2,Math.round(e.bins)),o=Math.max(1,Math.round(e.pegRows??t-1)),n=Math.max(1,Math.round(e.count??Math.max(64,4*t))),i=zr(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=Br(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:n},(e,t)=>{let n=0;for(let e=0;o>e;e+=1)r()<i&&(n+=1);const a=o/2;return{id:`${s}-${t}`,value:n,mechanical:!0,pegRows:o,branchProbability:i,pathRights:n,side:a>n?"left":n>a?"right":"center"}})}({bins:s,branchProbability:i.branchProbability,count:i.mechanicalCount,pegRows:l,seed:a}):Array.isArray(e)?e:[],d=function(e){const{data:t,valueAccessor:o,bins:n,ballRadius:i,seed:r,size:s,valueExtent:a}=e,l=Pr(s),c=t.map((e,t)=>Cr(Ir(e,t,o))).filter(e=>null!=e),u=function(e){if(!e)return;const t=Cr(e[0]),o=Cr(e[1]);return null!=t&&null!=o?t>o?[o,t]:[t,o]:void 0}(a),d=u?.[0]??(c.length?Math.min(...c):0),h=u?.[1]??(c.length?Math.max(...c):1),p=h===d?1:h-d,g=Nr().domain([0,n]).range([l.plot.x,l.plot.x+l.plot.width]),y=Array.from({length:n},()=>0),b=[];t.forEach((e,t)=>{const r=Cr(Ir(e,t,o));if(null==r)return;const s=Math.max(0,Math.min(n-1,Math.floor((r-d)/p*n)));y[s]+=1,b.push({id:(e.id??"galton-"+t)+"",x:g(s+.5),y:l.plot.y+i+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:i},datum:{...e,value:r,bin:s}})});const x=l.plot.y+l.plot.height;return{config:Rr(r,[...m({x:l.plot.x,y:l.plot.y,width:l.plot.width,height:l.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...f({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:g,yTop:l.plot.y-400,yBottom:x,wallThickness:6})],"GaltonBoardChart"),initialSpawns:b,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:y.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:n,plot:l.plot,valueExtent:[d,h]}}}({data:u,valueAccessor:i.valueAccessor||"value",bins:s,ballRadius:i.ballRadius??4,seed:a,size:r,valueExtent:c?[0,l]:void 0});return{...n,config:d.config,initialSpawns:fa(d.initialSpawns),projectionRows:d.projectionRows,bodyStyle:Lr(t||i.colorBy||(c?"side":void 0),"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||"value"})}}},EventDropChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s=function(e){const{data:t,timeAccessor:o,arrivalAccessor:n,windows:i,watermark:r,ballRadius:s,seed:a,size:l,timeExtent:c,timeScale:u=1}=e,d=Pr(l),h=t.map((e,t)=>Cr(Ir(e,t,o))).filter(e=>null!=e),p=Cr(c?.[0]),g=Cr(c?.[1]),f=h.length?Math.min(...h):0,y=h.length?Math.max(...h):f+i.size,b=Math.min(p??f,f),x=Math.max(g??y,y),v=Math.floor(b/i.size)*i.size,w=Math.max(1,Math.ceil((x-v+i.size)/i.size)),A=h.length?Math.max(...h):0,S="function"==typeof r?r(A):Cr(r?.value)??A-(r?.delay??i.size),k=Math.max(0,Math.min(w,Array.from({length:w},(e,t)=>t).reduce((e,t)=>v+(t+1)*i.size>S?e:e+1,0))),M=function(e,t){const o=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:o,height:e.plot.height},windowPlot:{x:e.plot.x+o,y:e.plot.y,width:Math.max(40,e.plot.width-o),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(d,s),_=v+w*i.size,P=Er().domain([v,_]).range([M.windowPlot.x,M.windowPlot.x+M.windowPlot.width]),T=Array.from({length:w},()=>({value:0,secondary:0})),L=[];t.forEach((e,t)=>{const r=Cr(Ir(e,t,o));if(null==r)return;const a=Cr(Ir(e,t,n))??r,l=Math.max(0,Math.min(w-1,Math.floor((r-v)/i.size))),c=S>=v+(l+1)*i.size;T[l].value+=c?0:1,T[l].secondary+=c?1:0,L.push({id:(e.id??"event-"+t)+"",x:Math.max(M.windowPlot.x+s,Math.min(M.windowPlot.x+M.windowPlot.width-s,P(r))),y:d.plot.y+s+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,spawnAt:a,shape:{type:"circle",radius:s},datum:{...e,eventTime:r,arrivalTime:a,windowIndex:l,late:c}})});const R=d.plot.y+d.plot.height,I=function(e,t){const o=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!o)return[];const n=e.windowStart,i=e.windowStart+e.windowCount*e.windowSize,r=Er().domain([n,i]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+o*e.windowSize),a=e.windowPlot.x,l=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),c=e=>s===a?t:l+(e-a)/(s-a)*(t-l),u=[];for(let t=0;o>t;t+=1){const o=e.windowStart+t*e.windowSize,n=o+e.windowSize,i=r(o),s=r(n);u.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:i,y1:c(i),x2:s,y2:c(s)})}return u}({closedWindowCount:k,gutter:M.gutter,plot:d.plot,windowCount:w,windowPlot:M.windowPlot,windowSize:i.size,windowStart:v},d.plot.y+.28*d.plot.height);return{config:Rr(a,[...m({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...jr({idPrefix:"eventdrop-window",count:w,xScale:e=>P(v+e*i.size),yTop:M.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>k)return null;const t=0===e?I[0]?.y1:I[e-1]?.y2??I[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?M.wallTop:t+1.25*s},yBottom:R,wallThickness:6}),...I.map(e=>({id:e.id,shape:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:Math.max(4,.42*s)},friction:.02,restitution:.01}))],"EventDropChart",{friction:.08}),initialSpawns:L,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:u},projectionRows:T.map((e,t)=>({label:`${v+t*i.size}-${v+(t+1)*i.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:k,gutter:M.gutter,lidSegments:I,lateCount:T.reduce((e,t)=>e+t.secondary,0),plot:d.plot,windowPlot:M.windowPlot,watermarkValue:S,windowCount:w,windowSize:i.size,windowStart:v}}}({data:Array.isArray(e)?e:[],timeAccessor:i.timeAccessor||"time",arrivalAccessor:i.arrivalAccessor||"arrivalTime",windows:i.windows||{size:10},watermark:i.watermark,ballRadius:i.ballRadius??5,seed:i.seed??1,size:r,timeExtent:i.timeExtent,timeScale:i.timeScale??1});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||i.timeAccessor||"time"})}}},UnitPileChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,400],s="mechanical"===i.mode,a=function(e){const{data:t,categoryAccessor:o,valueAccessor:n,unitValue:i,ballRadius:r,seed:s,size:a}=e,l=Fr(i,1),c=Pr(a),u=[],d=new Map,h=new Map,p=[];function g(e){let t=d.get(e);return null==t&&(t=u.length,u.push(e),d.set(e,t)),t}t.forEach((e,t)=>{g((Ir(e,t,o)??"unknown")+"")});const f=Math.max(1,u.length),y=function(e,t,o){const n=e.width/Math.max(1,t),i=Math.max(2,2*o),r=Math.min(.7*n,Math.max(3.2*i,i+8)),s=Math.max(1,Math.floor(r/i));return{laneWidth:n,tubeWidth:r,ballDiameter:i,perRow:s,centerX:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*i}}(c.plot,f,r),b=Math.max(0,y.tubeWidth/2-r-1),x=u.map(()=>[]);t.forEach((e,t)=>{const i=(Ir(e,t,o)??"unknown")+"",s=g(i),a=n?Cr(Ir(e,t,n)):1,u=Math.max(0,Math.round((a??0)/l)),d=y.centerX(s);for(let o=0;u>o;o+=1){const n=h.get(i)??0,a=y.perRow>1?((y.perRow>1?n%y.perRow:0)/(y.perRow-1)*2-1)*b:0;h.set(i,n+1),x[s].push({id:`${(e.id??"pile-"+t)+""}-${o}`,x:d+a,y:c.plot.y+r+2,vx:(o%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:i,unitIndex:o}})}});const v=x.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;v>e;e+=1)for(const t of x)t.length>e&&p.push(t[e]);const w=c.plot.y+c.plot.height,A=[...m({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],S=c.plot.y-400;for(let e=0;f>e;e+=1){const t=y.centerX(e);for(const o of[-1,1])A.push({id:`pile-tube-${e}-${0>o?"l":"r"}`,shape:{type:"aabb",x:t+o*y.tubeWidth/2,y:(S+w)/2,width:6,height:w-S}})}return{config:Rr(s,A,"UnitPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:u.map(e=>({label:e,value:h.get(e)??0}))}}({data:s?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),o=t.length?t:["Intake"],n=Math.max(o.length,Math.round(e.count??Math.max(48,12*o.length))),i=Fr(e.unitValue,1),r=Br(e.seed??1),s=e.idPrefix??"mechanical-pile",a=o.map(()=>.65+.9*r()),l=a.reduce((e,t)=>e+t,0)||1,c=n-o.length,u=a.map(e=>e/l*c),d=u.map(e=>1+Math.floor(e));let h=n-d.reduce((e,t)=>e+t,0);const p=u.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction);for(let e=0;h>0;e=(e+1)%p.length)d[p[e].index]+=1,h-=1;return o.map((e,t)=>({id:`${s}-${t}`,category:e,value:d[t]*i,mechanical:!0,unitCount:d[t],unitValue:i,share:d[t]/n}))}({categories:i.mechanicalCategories,count:i.mechanicalCount,seed:i.seed??1,unitValue:i.unitValue??1}):Array.isArray(e)?e:[],categoryAccessor:i.categoryAccessor||"category",valueAccessor:i.valueAccessor||(s?"value":void 0),unitValue:i.unitValue??1,ballRadius:i.ballRadius??5,seed:i.seed??1,size:r});return{...n,config:a.config,initialSpawns:fa(a.initialSpawns),projectionRows:a.projectionRows,bodyStyle:Lr(t||i.colorBy||(s?"category":void 0),"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.valueAccessor||"value"})}}},CollisionSwarmChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[600,360],s=function(e){const{data:t,xAccessor:o,groupAccessor:n,radiusAccessor:i,pointRadius:r,seed:s,size:a,xExtent:l,collisionIterations:c,settle:u}=e,d=Pr(a),h=Br(s),p=[],g=[],f=new Map;t.forEach((e,t)=>{const s=Cr(Ir(e,t,o));if(null==s)return;const a=n?(Ir(e,t,n)??"All")+"":"All",l=i?Cr(Ir(e,t,i)):null,c=zr(null!=l&&l>0?l:r,2,18);!function(e){let t=f.get(e);null==t&&(t=g.length,g.push(e),f.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:c})});const y=p.map(e=>e.value),b=l?Cr(l[0]):null,x=l?Cr(l[1]):null,v=y.length?Math.min(...y):0,w=y.length?Math.max(...y):1;let A=b??v,S=x??w;if(A===S&&(A-=.5,S+=.5),A>S){const e=S;S=A,A=e}const k=Math.max(r,...p.map(e=>e.radius)),M=d.plot.x+k+8,_=d.plot.x+d.plot.width-k-8,P=$r().domain([A,S]).range([M,_]),T=Math.max(1,g.length),L=Math.min(Math.max(28,3*k),d.plot.height/4),R=d.plot.y+L,I=Math.max(0,d.plot.y+d.plot.height-L-R),C=e=>{const t=f.get(e)??0;return 1===T?d.plot.y+.54*d.plot.height:R+t/(T-1)*I},z=new Map,F=p.map((e,t)=>{z.set(e.group,(z.get(e.group)??0)+1);const o=P(e.value),n=C(e.group),i=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:u?o+i:zr(o+(t%9-4)*e.radius*2.5,M,_),y:u?n+r:d.plot.y-18-t%12*e.radius,vx:u?0:22*(h()-.5),vy:u?0:24+18*h(),mass:1,shape:{type:"circle",radius:e.radius},datum:{...e.datum,xValue:e.value,group:e.group,radius:e.radius,targetX:o,targetY:n},springs:[{target:{type:"point",x:o,y:n},restLength:0,stiffness:34,damping:5.5}]}});return{config:Rr(s,m({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*k),collisionIterations:Math.max(1,Math.round(c??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:F,projectionRows:g.map(e=>({label:e,value:z.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[A,S],xRange:[M,_],groups:g.map(e=>({label:e,y:C(e),count:z.get(e)??0})),plot:d.plot}}}({data:Array.isArray(e)?e:[],xAccessor:i.xAccessor||"x",groupAccessor:i.groupAccessor,radiusAccessor:i.radiusAccessor,pointRadius:i.pointRadius??5,seed:i.seed??1,size:r,xExtent:i.xExtent,collisionIterations:i.collisionIterations,settle:i.settle});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy||i.groupAccessor,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.xAccessor||"x"})}}},ProcessFlowChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,420],s=Array.isArray(i.stages)?i.stages:[],a=function(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const o=e.size,n=Pr(o),i=zr(e.ballRadius??6,2,18),r=e.seed??1,s=Br(r),a=e.idAccessor,l=e.stageAccessor??"stage",c=e.groupBy,u=e.groupLabelAccessor,d=e.workAccessor,m=e.radiusAccessor,f=e.groupCompletion??(c?"allAbsorbed":"none"),y=e.springStiffness??.28,v=e.springDamping??.72,w=!0===e.settle,A=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),S=_({width:o[0],height:o[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:A,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),P=new Map(S.stages.map((e,t)=>[e.id,t])),L=new Map(S.stages.map(e=>[e.id,e])),R=S.stages[0].id,I=S.stages[0],C=new Set(t.filter(e=>e.absorb).map(e=>e.id)),z=t.map(e=>{const t=L.get(e.id)??I;return function(e,t){const o={id:"process-stage-"+e.id,label:e.label??e.id,description:e.description,x:t.x,y:t.y,width:Math.max(12,.92*t.width),height:Math.max(40,.88*t.height),semanticItem:!1,attributes:{stageId:e.id}};if(e.absorb)return h({...o,kind:e.kind??"sink",force:Xr(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...o.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return k({...o,kind:e.kind??"force-field",force:Xr(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...o.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return g({...o,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:Xr(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...o.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return M({...o,kind:e.kind??"membrane",pressure:t.pressure,occupancy:t.occupancy,baseDamping:t.baseDamping??e.damping??.1,dampingPerUnit:t.dampingPerUnit??.1,energyPerUnit:t.energyPerUnit??0,force:Xr(e.force,8),attributes:{...o.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?T({...o,kind:e.kind??"force-field",force:Xr(e.force,14),damping:e.damping??.02,attributes:{...o.attributes,primitive:"routeSurface"}}):b({...o,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...o.attributes,primitive:"forceField"}})}(e,{x:t.x,y:S.midY,width:t.width,height:S.bottomY-S.topY})});z.unshift(T({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(S.left+S.right)/2,y:S.midY,width:S.right-S.left,height:S.bottomY-S.topY-12,force:8,damping:.012,semanticItem:!1}));const F=new Map;for(const e of S.stages)F.set(e.id,0);const O=[];e.data.forEach((e,t)=>{const o=(a?Ir(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",n=(Ir(e,t,l)??R)+"",r=P.has(n)?n:R;F.set(r,(F.get(r)??0)+1);const s=c?(Ir(e,t,c)??"")+"":void 0,h=s&&u?(Ir(e,t,u)??s)+"":s,p=d?Cr(Ir(e,t,d))??1:1,g=m?Cr(Ir(e,t,m)):null,f=zr(null!=g&&g>0?g:i,2,18);O.push({datum:e,id:o,stageId:r,groupId:s||void 0,groupLabel:h||void 0,work:p,radius:f,index:t})});const B=new Map,N=new Map;for(const e of O){if(!e.groupId)continue;const t=B.get(e.groupId)??[];t.push(e.id),B.set(e.groupId,t),e.groupLabel&&N.set(e.groupId,e.groupLabel)}const E=zr(e.groupAnchorAlong??.55,.15,.9),j=S.left+(S.right-S.left)*E,$=Array.from(B.keys()),D=$.map((e,o)=>{const n=B.get(e)??[],i=$.length>1?S.topY+28+o/Math.max(1,$.length-1)*(S.bottomY-S.topY-56):S.midY;return p({id:e,label:N.get(e)??e,bodyIds:n,anchor:{x:j,y:i},x:j,y:i,completion:"allAbsorbed"===f?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),W=O.filter(e=>C.has(e.stageId)).map(e=>e.id),Y=x(D,W),V=new Map(D.map(e=>[e.id,e])),H=O.map((e,t)=>{const o=L.get(e.stageId)??I,n=o.x+(s()-.5)*Math.min(24,.2*o.width),i=S.boundaryY(n,"top")+e.radius+10,r=S.boundaryY(n,"bottom")-e.radius-10,a=r>i?i+s()*Math.max(1,r-i):S.midY,l=w?n:S.left+18+t%7*4,c=w?a:S.midY+(s()-.5)*(S.bottomY-S.topY)*.35,u=[{target:{type:"point",x:n,y:a},restLength:.45*e.radius,stiffness:y,damping:v}];if(e.groupId){const t=V.get(e.groupId);t?.anchor&&!C.has(e.stageId)&&u.push({target:{type:"point",x:t.anchor.x,y:t.anchor.y},restLength:t.tether?.restLength??22,stiffness:t.tether?.stiffness??.05,damping:.8})}return{id:e.id,x:l,y:c,vx:w?0:40+40*s(),vy:w?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:w?0:.03*t,springs:u,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),G={kernel:{seed:r,gravity:{x:e.gravityX??22,y:e.gravityY??0},restitution:.14,friction:.48,velocityDamping:.988,maxVelocity:420,sleepSpeed:8,sleepAfter:.9,collisionIterations:4},colliders:S.colliders,fixedDt:1/60,maxSubsteps:8},X=S.stages.map(e=>({label:e.label??e.id,value:F.get(e.id)??0})),q=t.map(e=>{const t=L.get(e.id)??I;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:F.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:G,initialSpawns:H,initialSpawnPacing:w?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:X,metadata:{kind:"process-flow",plot:n.plot,volume:S,stages:q,groups:D,groupCompletion:Y,regionEffects:z}}}({data:Array.isArray(e)?e:[],stages:s,size:r,idAccessor:i.idAccessor,stageAccessor:i.stageAccessor||"stage",groupBy:i.groupBy,groupLabelAccessor:i.groupLabelAccessor,workAccessor:i.workAccessor,radiusAccessor:i.radiusAccessor,ballRadius:i.ballRadius??6,seed:i.seed??1,groupCompletion:i.groupCompletion,groupAnchorAlong:i.groupAnchorAlong,settle:i.settle??!0,gravityX:i.gravityX,gravityY:i.gravityY}),l=a.metadata;return{...n,config:a.config,initialSpawns:fa(a.initialSpawns),projectionRows:a.projectionRows,regionEffects:l?.regionEffects,bodyStyle:Lr(t||i.colorBy||i.groupBy,"#4e79a7",{styleRules:i.styleRules,valueAccessor:i.workAccessor||i.stageAccessor||"stage"})}}},GauntletChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,520],s=as({data:Array.isArray(e)?e:[],size:r,gates:i.gates,positiveProperties:i.positiveProperties,negativeProperties:i.negativeProperties,crashOffset:i.crashOffset,idAccessor:i.idAccessor,positiveAccessor:i.positiveAccessor,negativeAccessor:i.negativeAccessor,metricsAccessor:i.metricsAccessor,initialViability:i.initialViability,projectPlacement:i.projectPlacement,coreBody:i.coreBody,viability:i.viability});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:[],bodyStyle:Lr(t||i.colorBy)}}},CrucibleChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[900,520],s=Ks({data:Array.isArray(e)?e:[],phases:Array.isArray(i.phases)?i.phases:[],products:Array.isArray(i.products)?i.products:void 0,outlets:Array.isArray(i.outlets)?i.outlets:void 0,events:Array.isArray(i.events)?i.events:void 0,idAccessor:i.idAccessor,labelAccessor:i.labelAccessor,categoryAccessor:i.categoryAccessor,amountAccessor:i.amountAccessor,metricsAccessor:i.metricsAccessor,initialStateAccessor:i.initialStateAccessor,metrics:i.metrics,size:r,seed:i.seed,bodyRadius:"number"==typeof i.bodyRadius?i.bodyRadius:void 0,radiusRange:i.radiusRange}),a="snapshot"===i.playback?function(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,Fs(t)??0));const o=e.phases.find(e=>e.id===t.phaseId);if(!o)return e.duration;const n=Math.max(0,Math.min(1,Fs(t.progress??0)??0));return o.start+o.duration*n}(s,i.snapshotAt):s.duration,l=Zs(s,a).state,c=i.projection&&"object"==typeof i.projection?i.projection:{groupBy:"outlet",measure:"count"},u=function(e,t={}){const o=t.groupBy??"outlet",n=new Map,i=e=>{const t=function(e,t){return"product"===t?"product"===e.kind?e.id:"unassigned":"outlet"===t?e.outletId??"unassigned":"category"===t?e.category:e.status}({...e,status:e.status??"active"},o),i=n.get(t);if(i)return i.count+=1,i.amount+=e.amount,void fs(i.metrics,e.metrics);n.set(t,{key:t,label:"product"===o&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:{...e.metrics},status:"status"===o?e.status:void 0,outletId:"outlet"===o?e.outletId:void 0,category:"category"===o?e.category:void 0,productId:"product"===o&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||i({kind:"component",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});for(const t of Object.values(e.products))i({kind:"product",id:t.id,label:t.label,status:t.status,outletId:t.outletId,category:t.category,amount:t.amount,metrics:t.metrics});const r=new Map((t.order??[]).map((e,t)=>[e,t]));return[...n.values()].sort((e,t)=>(r.get(e.key)??Number.MAX_SAFE_INTEGER)-(r.get(t.key)??Number.MAX_SAFE_INTEGER)||cs(e.key,t.key))}(l,c),d=c.measure??"count",h=function(e,t={}){const o=t.bodies??[],n=Math.max(0,t.recentBodyLimit??6),i=new Map;for(const e of o){const o=t.getContainerId?.(e);if(!o)continue;const n=i.get(o);n?n.push(e):i.set(o,[e])}const r=e.map(e=>{const o=i.get(e.id)??[],r=Math.max(0,Math.floor(e.count??o.length)),s=o.slice(Math.max(0,o.length-n)).map(e=>({id:e.id,label:t.getBodyLabel?.(e)??ma(e),datum:e.datum}));return{id:e.id,label:e.label,count:r,share:0,secondary:e.secondary,secondaryLabel:e.secondaryLabel,observed:e.observed,bodyIds:o.map(e=>e.id),recentBodies:s,metadata:e.metadata}}),s=r.reduce((e,t)=>e+t.count,0);return r.map(e=>({...e,share:s>0?e.count/s:0}))}(u.map(e=>({id:e.key,label:e.label,count:e.count,secondary:"count"===d||"amount"===d?e.amount:Number(e.metrics[d]??0),secondaryLabel:"count"===d||"amount"===d?i.amountLabel??"amount":d,metadata:{amount:e.amount,metrics:e.metrics,status:e.status,outletId:e.outletId,category:e.category,productId:e.productId}}))),p={seed:i.seed,bodyRadius:"number"==typeof i.bodyRadius?i.bodyRadius:void 0,radiusRange:i.radiusRange},g=t??i.colorBy??"category",m=!1===i.showChrome?null:_r.createElement(pa,{layout:s.layout,phases:s.phases,state:l,compact:520>r[0]||360>r[1]}),f=!1===i.showProjection?null:_r.createElement(ga,{rows:u,layout:s.layout,projection:c,amountLabel:i.amountLabel});return{...n,config:s.config,initialSpawns:fa(qs(l,s.layout,p)),projectionRows:h,bodyStyle:e=>function(e,t,o,n){const i=e.datum,r={stroke:n.stroke??("product"===i?.kind?"#fffaf0":"#26323a"),strokeWidth:n.strokeWidth??("product"===i?.kind?1.8:1.1),opacity:n.opacity??.96};if(!i?.__crucible)return{...r,fill:n.color??"#b8792d"};if("product"===i.kind){const e=t.products[i.semanticId];return{...r,fill:n.color??e?.color??xa(e?.id??i.semanticId)}}const s=t.components[i.semanticId];if(!s)return{...r,fill:n.color??"#356b63"};let a;return a="status"===o?s.status:"outlet"===o?s.outletId??"in chamber":"product"===o?s.productIds[0]??"unalloyed":"category"===o||null==o?s.category:"function"==typeof o?(o(s.datum)??"unassigned")+"":(s.datum[o+""]??"unassigned")+"",{...r,fill:n.color??xa(a)}}(e,l,g,i),getBodyLabel:e=>function(e,t){const o=e.datum;if(o?.__crucible)return"product"===o.kind?t.products[o.semanticId]?.label:t.components[o.semanticId]?.label}(e,l),renderBodySVG:na,backgroundGraphics:ya(m,n.backgroundGraphics),foregroundGraphics:ya(f,n.foregroundGraphics)}}},PacketFlowChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[760,420],s=function(e){const{coordinateMode:t,flowSpeed:o,links:n,maxParticles:i,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:l,particleRadius:c,particleRate:u,pathAccessor:d,pathConstraint:h="path",reducedMotion:p,seed:g,size:f,sourceAccessor:y,targetAccessor:b,throughputAccessor:x}=e,v=Pr(f),w=Br(g),A=new Map,S=new Map,k=[];function M(e){if(e&&"object"==typeof e){const t=e;if("function"==typeof r){const e=r(t,0);if(null!=e)return e+""}if("string"==typeof r&&null!=t[r])return t[r]+"";if(null!=t.id)return t.id+""}return(e??"unknown")+""}l.forEach((e,t)=>{const o=(Ir(e,t,r)??e.id??t)+"",n=Cr(Ir(e,t,s)),i=Cr(Ir(e,t,a));if(null!=n&&null!=i){const e={x:n,y:i};A.set(o,e),k.push(e)}S.set(o,(e.label??e.name??o)+"")});const _=[];n.forEach((e,t)=>{const o=M(Ir(e,t,y)),n=M(Ir(e,t,b)),i=Math.max(0,Cr(Ir(e,t,x))??0),r=Wr(d?Ir(e,t,d):void 0),s=r.length?r:Wr(e.path??e.points??e.route);s.forEach(e=>k.push(e)),_.push({id:(e.id??`physical-flow-${o}-${n}-${t}`)+"",link:e,index:t,source:o,target:n,throughput:i,rawPath:s})});const P=(L=k,"normalized"===(T=t)||"pixels"===T?T:L.length>0&&L.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var T,L;const R=new Map;for(const[e,t]of A)R.set(e,Yr(t,v,P));const I=[];for(const e of _){let t=e.rawPath.map(e=>Yr(e,v,P));if(2>t.length){const o=R.get(e.source),n=R.get(e.target);o&&n&&(t=[o,n])}else R.has(e.source)||R.set(e.source,t[0]),R.has(e.target)||R.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(S.has(e.source)||S.set(e.source,e.source),S.has(e.target)||S.set(e.target,e.target),I.push({...e,path:t,packetCount:0}))}const C=Fr(u,.12),z=Math.max(1,Math.round(i)),F=I.map(e=>Math.max(1,Math.round(e.throughput*C))),O=F.reduce((e,t)=>e+t,0),B=O>z?z/O:1;I.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(F[t]*B))});let N=I.reduce((e,t)=>e+t.packetCount,0);for(;N>z;){const e=I.reduce((e,t,o)=>t.packetCount>1&&(-1===e||t.packetCount>I[e].packetCount)?o:e,-1);if(-1===e)break;I[e].packetCount-=1,N-=1}const E=new Map,j=new Map,$=[],D=Fr(o,90),W=Fr(c,4);I.forEach((e,t)=>{E.set(e.target,(E.get(e.target)??0)+e.throughput),j.set(e.source,(j.get(e.source)??0)+e.throughput);const o=Vr(e.path);for(let n=0;e.packetCount>n;n+=1){const i=(n+.5)/e.packetCount,r=p?i:zr(.12+.84*i+.04*(w()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*w())),a=Hr(e.path,s),l=Hr(e.path,r),c=Gr(e.path,s),u={x:-c.y,y:c.x},d=(w()-.5)*W*1.5;$.push({id:`${e.id}-packet-${n}`,x:a.x+u.x*d,y:a.y+u.y*d,vx:p?0:c.x*D+10*(w()-.5),vy:p?0:c.y*D+10*(w()-.5),mass:.8,spawnAt:p?0:.04*t+n/32,shape:{type:"circle",radius:W},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:n,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:o,flowRouteId:e.id,flowSpeed:D,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:l.x,y:l.y},restLength:.7*W,stiffness:26,damping:4.25}]:void 0})}});const Y=Math.max(18,5*W),V=Array.from(R,([e,t])=>({nodeId:e,label:S.get(e)??e,sensorId:"physical-flow-node-"+Or(e),point:t})),H=V.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:Y,height:Y}})),G=Object.fromEntries(V.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),X=Rr(g,[...m({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...H],"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*W),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});X.bodyLimit=z,X.eviction="oldest",X.observation={...X.observation,sensors:G};const q=Array.from(R,([e,t])=>({id:e,label:S.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+Or(e),incoming:E.get(e)??0,outgoing:j.get(e)??0})),U=I.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:S.get(e.source)??e.source,targetLabel:S.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:X,initialSpawns:$,projectionRows:q.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:P,particleCount:$.length,totalThroughput:I.reduce((e,t)=>e+t.throughput,0),plot:v.plot,nodes:q,links:U}}}({nodes:Array.isArray(i.nodes)?i.nodes:[],links:Array.isArray(i.links)?i.links:Array.isArray(i.edges)?i.edges:Array.isArray(e)?e:[],nodeIdAccessor:i.nodeIdAccessor||"id",nodeXAccessor:i.nodeXAccessor||"x",nodeYAccessor:i.nodeYAccessor||"y",sourceAccessor:i.sourceAccessor||"source",targetAccessor:i.targetAccessor||"target",throughputAccessor:i.throughputAccessor||"value",pathAccessor:i.pathAccessor||"path",coordinateMode:i.coordinateMode||"auto",particleRate:i.particleRate??.16,maxParticles:i.maxParticles??180,particleRadius:i.particleRadius??4,flowSpeed:i.flowSpeed??90,pathConstraint:i.pathConstraint||"path",reducedMotion:!0,seed:i.seed??1,size:r});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:s.projectionRows,bodyStyle:Lr(t||i.colorBy||"source")}}},PhysicsCustomChart:{frameType:"physics",buildProps:(e,t,o,n,i)=>{const r=n.size??[700,380],s=function(e){const t=function(e,t,o){const n=e?.observation;return{...e,observation:{...n,chartId:t??n?.chartId??"physics-custom",chartType:n?.chartType??"PhysicsCustomChart",onObservation:o??n?.onObservation}}}(e.config,e.chartId,e.onObservation),o=Ne(e.colorScheme,e.themeCategorical,Pt),n=Pr(e.size),i={data:e.data,scales:{x:qr().domain(e.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:qr().domain(e.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:e.semantic,categorical:[...o]},resolveColor:V(o,e.colorScheme),config:e.layoutConfig??{},world:new d(t)},r=e.skipLayout?{}:e.layout(i)??{},s=function(e,t){if(!t?.length)return e;const o=new Map;for(const e of t){const{bodyId:t,...n}=e,i=o.get(t)??[];i.push(n),o.set(t,i)}return e.map(e=>{const t=o.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...r.initialSpawns??r.bodies??[]],r.constraints);return{config:Ur(t,r),context:i,initialSpawnPacing:r.initialSpawnPacing,initialSpawns:s,result:r}}({chartId:i.chartId,colorScheme:o,config:i.config,data:Array.isArray(e)?e:[],layout:i.layout,layoutConfig:i.layoutConfig,semantic:Dt(Et)??{},size:r,themeCategorical:Et.colors.categorical,xExtent:i.xExtent,yExtent:i.yExtent});return{...n,config:s.config,initialSpawns:fa(s.initialSpawns),projectionRows:[],bodyStyle:s.result.bodyStyle??Lr(t||i.colorBy)}}}};function wa(e){const t=e instanceof Date?e.getTime():"number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function Aa(e){if(!e||2>e.length)return;const t=wa(e[0]),o=wa(e[e.length-1]);return null!==t&&null!==o?[t,o]:void 0}function Sa(e){const{count:t,byType:o}=function(e){const t={};for(const o of e){const e="string"==typeof o?.type&&o.type.length>0?o.type:"node";t[e]=(t[e]??0)+1}return{count:e.length,byType:t}}(e.marks),n=0===t,i=[...e.extraWarnings??[]];n&&!i.includes("EMPTY_SCENE")&&i.push("EMPTY_SCENE");const r=e.margin,s=r?{x:r.left,y:r.top,width:e.width-r.left-r.right,height:e.height-r.top-r.bottom}:void 0;return{component:"",frameType:e.frameType,status:n?"empty":"ok",empty:n,markCount:t,markCountByType:o,width:e.width,height:e.height,...e.xDomain?{xDomain:e.xDomain}:{},...e.yDomain?{yDomain:e.yDomain}:{},...e.categories?{categories:e.categories}:{},...void 0!==e.nodeCount?{nodeCount:e.nodeCount}:{},...void 0!==e.edgeCount?{edgeCount:e.edgeCount}:{},...void 0!==e.legendItems?{legendItems:e.legendItems}:{},annotationCount:Array.isArray(e.annotations)?e.annotations.length:0,ariaLabel:"string"==typeof e.description&&e.description||"string"==typeof e.title&&e.title||`${e.frameType} chart, ${t} marks`,warnings:i,...r?{margin:r}:{},...s?{plot:s}:{}}}import*as ka from"react";import*as Ma from"react-dom/server";import{scaleOrdinal as _a}from"d3-scale";import{jsx as Pa,jsxs as Ta}from"react/jsx-runtime";var La=I;function Ra(e,t,o){if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;return t=>$e(e,t)??"#999"}const n=Array.isArray(t)?t:o.colors.categorical.length>0?o.colors.categorical:Pt;return _a().domain(e).range(n)}function Ia(e,t,o){if(0===e.length)return;const n=Ra(e,t,o);return{legendGroups:[{label:"",type:"fill",items:e.map(e=>({label:e})),styleFn:e=>({fill:n(e.label)})}]}}function Ca(e){return"left"===e?"start":"right"===e?"end":e??"start"}function za(e){return Number(e.typography.legendSize??e.typography.labelSize??e.typography.tickSize)||11}function Fa(e,t,o,n){const i=za(n);return t+o+Math.ceil(e.length*i*.58)}function Oa(e){const{categories:t,theme:o,position:n="right",totalWidth:i,margin:r,legendLayout:s}=e,{swatchSize:a,labelGap:l,itemGap:c,rowHeight:u}=Ye(s),d=a+l,h="top"===n||"bottom"===n,p=Math.max(a,i-r.left-r.right),g=t.map(e=>Fa(e,a,l,o));if(h){const e=Math.max(a,s?.maxWidth??p),o=[];let n=0,i=0;g.forEach((t,r)=>{const s=0===i?t:i+c+t;i>0&&s>e?(o.push({start:n,end:r,width:i}),n=r,i=t):i=s}),t.length>0&&o.push({start:n,end:t.length,width:i});const r=Ca(s?.align),l=[];return o.forEach((o,n)=>{let i="center"===r?Math.max(0,(e-o.width)/2):"end"===r?Math.max(0,e-o.width):0;for(let e=o.start;o.end>e;e++)l.push({category:t[e],width:g[e],x:i,y:n*u}),i+=g[e]+c}),{items:l,width:Math.max(0,...o.map(e=>e.width)),height:o.length*u,swatchSize:a,labelOffset:d,swatchRadius:0}}const m=Math.max(0,...g);return{items:t.map((e,t)=>({category:e,width:g[t],x:0,y:t*u})),width:m,height:t.length*u,swatchSize:a,labelOffset:d,swatchRadius:0}}function Ba(e){const{legendGroups:t,theme:o,position:n="right",totalWidth:i,margin:r,legendLayout:s}=e,{swatchSize:a,labelGap:l,rowHeight:c}=Ye(s),u=a+l,d=Math.max(12,za(o)),h="top"===n||"bottom"===n,p=Math.max(a,i-r.left-r.right);if(h){const n=Math.max(a,s?.maxWidth??p),i=Ca(s?.align);let r=0,l=0;const c=[];for(const i of t){const t=i.items.map(e=>e.label),u=Oa({...e,categories:t,legendLayout:{...s,maxWidth:Math.max(a,n-d-8),align:"start"}}),h=i.label?d:0,p=i.label?Fa(i.label,0,0,o):0,g=h>0?h+8:0,m=g+u.width,f=Math.max(u.height,p);c.push({group:i,x:r,y:0,itemOffsetX:g,itemOffsetY:0,width:m,height:f,items:u.items}),r+=m+12,l=Math.max(l,f)}const h=c.length>0?r-12:0,g=h>n?0:"center"===i?Math.max(0,(n-h)/2):"end"===i?Math.max(0,n-h):0;return{groups:c.map(e=>({...e,x:e.x+g})),width:h,height:l,swatchSize:a,labelOffset:u,swatchRadius:0}}const g=ye(t.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),c);let m=0;return{groups:t.map((e,t)=>{const n=e.items.map(e=>Fa(e.label,a,l,o)),i=Math.max(0,...n,e.label?Fa(e.label,0,0,o):0);return m=Math.max(m,i),{group:e,x:0,y:g[t].itemsY,itemOffsetX:0,itemOffsetY:0,width:i,height:e.items.length*c,items:e.items.map((e,t)=>({category:e.label,width:n[t],x:0,y:t*c}))}}),width:m,height:g.at(-1)?.endY??0,swatchSize:a,labelOffset:u,swatchRadius:0}}function Na(e){const t="top"===e.position||"bottom"===e.position,o=Math.max(1,e.totalWidth-e.margin.left-e.margin.right);return t?{width:Math.min(e.legendLayout?.maxWidth??o,200),height:e.gradient.label?34:26,swatchSize:12}:{width:e.gradient.label?86:72,height:e.gradient.label?124:108,swatchSize:14}}function Ea(e,t){if(!t||!e||0===e.length)return[];const o="function"==typeof t?t:e=>e[t],n=new Set;for(const t of e){const e=o(t);null!=e&&n.add(e+"")}return Array.from(n)}import{jsx as ja,jsxs as $a}from"react/jsx-runtime";var Da=16;function Wa(e,t){return e.color||t.colors.annotation||t.colors.text}function Ya(e,t,o){const n=e.labelBackground,i=t.colors.background,r=i&&"transparent"!==i?i:t.colors.surface||i;return void 0===n?"none"===o?"none":{type:"halo",fill:r}:!1===n||"none"===n?"none":!0===n||"halo"===n?{type:"halo",fill:r}:"box"===n?{type:"box",fill:r}:{fill:r,...n}}function Va(e,t,o){return null!=e.x&&t.x?t.x(e.x):o&&null!=e[o]&&t.x?t.x(e[o]):"number"==typeof e.x?e.x:null}function Ha(e,t,o){return null!=e.y&&t.y?t.y(e.y):o&&null!=e[o]&&t.y?t.y(e[o]):"number"==typeof e.y?e.y:null}function Ga(e){const{annotations:t}=e;if(!t||0===t.length)return null;const o=Lt(t),n=e.scales.geoProjection,i=n?o.map(e=>{if(!Array.isArray(e.coordinates)||2>e.coordinates.length)return e;const t=n([Number(e.coordinates[0]),Number(e.coordinates[1])]);return t?{...e,x:t[0],y:t[1]}:e}):o,r=!!n&&!e.scales.x&&!e.scales.y,s=e=>Number(e),a=e.scales.x??(r?s:void 0),l=e.scales.y??(r?s:void 0),c=e.projection?"horizontal"===e.projection?"horizontal":"vertical":void 0,u={scales:{x:a,y:l,time:a,value:l,o:e.scales.o,...n?{geoProjection:n}:{}},width:e.layout.width,height:e.layout.height,xAccessor:e.xAccessor,yAccessor:e.yAccessor,data:e.annotationData,frameType:e.projection?"ordinal":n||e.scales.x||e.scales.y?"xy":"network",...c?{projection:c}:{}},d=e.autoPlaceAnnotations?ft({annotations:i,context:u,..."object"==typeof e.autoPlaceAnnotations?e.autoPlaceAnnotations:{}}):i,h=Te(d,(t,o)=>function(e,t,o){const{scales:n,layout:i,theme:r,xAccessor:s,yAccessor:a}=o;switch(e.type){case"y-threshold":{const s=e.value;if(null==s)return null;const a=Wa(e,r),l=e.label,c=e.labelPosition||"right",u=e.strokeDasharray||"6,4",d=e.strokeWidth??1.5;if("horizontal"===o.projection&&n.r){const o=n.r(s);return null==o?null:$a("g",{opacity:e.opacity,children:[ja("line",{x1:o,y1:0,x2:o,y2:i.height,stroke:a,strokeWidth:d,strokeDasharray:u}),l&&ja(L,{x:o+4,y:Da,textAnchor:"start",fontSize:r.typography.tickSize,fill:a,fontFamily:r.typography.fontFamily,text:l,background:Ya(e,r,"halo")})]},"ann-ythresh-"+t)}const h=n.y?n.y(s):n.r?n.r(s):null;return null==h?null:$a("g",{children:[ja("line",{x1:0,y1:h,x2:i.width,y2:h,stroke:a,strokeWidth:d,strokeDasharray:u}),l&&ja(L,{x:"left"===c?4:"center"===c?i.width/2:i.width-4,y:20>h?Math.min(i.height-4,h+Da):h-6,textAnchor:"left"===c?"start":"center"===c?"middle":"end",fontSize:r.typography.tickSize,fill:a,fontFamily:r.typography.fontFamily,text:l,background:Ya(e,r,"halo")})]},"ann-ythresh-"+t)}case"x-threshold":{const s=e.value;if(null==s)return null;const a="horizontal"===o.projection&&n.r?n.r(s):n.x?n.x(s):null;if(null==a)return null;const l=Wa(e,r),c=e.label,u=e.labelPosition||"top";return $a("g",{opacity:e.opacity,children:[ja("line",{x1:a,y1:0,x2:a,y2:i.height,stroke:l,strokeWidth:e.strokeWidth??1.5,strokeDasharray:e.strokeDasharray||"6,4"}),c&&ja(L,{x:a>.6*i.width?a-4:a+4,y:"bottom"===u?i.height-4:"center"===u?i.height/2:Da,textAnchor:a>.6*i.width?"end":"start",fontSize:r.typography.tickSize,fill:l,fontFamily:r.typography.fontFamily,text:c,background:Ya(e,r,"halo")})]},"ann-xthresh-"+t)}case"band":{const o=n.y?.domain?.(),s=e.y0??o?.[0],a=e.y1??o?.[1],l=null!=s&&n.y?n.y(s):null,c=null!=a&&n.y?n.y(a):null;if(null==l||null==c)return null;const u=Math.min(l,c),d=Math.abs(c-l),h=gt(e.fill||Wa(e,r),"ssr-band-"+t),p=e.fillOpacity??.1;return $a("g",{opacity:e.opacity,children:[h.def&&ja("defs",{children:h.def}),ja("rect",{x:0,y:u,width:i.width,height:d,fill:h.fill,fillOpacity:p}),e.label&&ja(L,{x:i.width-4,y:Math.max(u,0)+Da,textAnchor:"end",fontSize:r.typography.tickSize,fill:e.color||Wa(e,r),fontFamily:r.typography.fontFamily,fontWeight:"bold",text:e.label,background:Ya(e,r,"halo")})]},"ann-band-"+t)}case"x-band":{const o=n.x?.domain?.(),s=e.x0??o?.[0],a=e.x1??o?.[1],l=null!=s&&n.x?n.x(s):null,c=null!=a&&n.x?n.x(a):null;if(null==l||null==c)return null;const u=Math.min(l,c),d=Math.abs(c-l),h=gt(e.fill||Wa(e,r),"ssr-xband-"+t),p=e.fillOpacity??.1;return $a("g",{opacity:e.opacity,children:[h.def&&ja("defs",{children:h.def}),ja("rect",{x:u,y:0,width:d,height:i.height,fill:h.fill,fillOpacity:p}),e.label&&ja(L,{x:u+4,y:Da,textAnchor:"start",fontSize:r.typography.tickSize,fill:e.color||r.colors.primary||Wa(e,r),fontFamily:r.typography.fontFamily,fontWeight:"bold",text:e.label,background:Ya(e,r,"halo")})]},"ann-xband-"+t)}case"category-highlight":{if(null==e.category||!n.o)return null;const s=n.o(e.category+"");if(null==s)return null;const a=n.o.bandwidth?n.o.bandwidth():40,l=Wa(e,r),c=e.opacity??.1,u=e.label;return $a("g","horizontal"===o.projection?{children:[ja("rect",{x:0,y:s,width:i.width,height:a,fill:l,opacity:c}),u&&ja(L,{x:12,y:s+a/2,dominantBaseline:"middle",fill:l,fontSize:r.typography.tickSize,fontWeight:"bold",fontFamily:r.typography.fontFamily,text:u,background:Ya(e,r,"none")})]}:{children:[ja("rect",{x:s,y:0,width:a,height:i.height,fill:l,opacity:c}),u&&ja(L,{x:s+a/2,y:Da,textAnchor:"middle",fill:l,fontSize:r.typography.tickSize,fontWeight:"bold",fontFamily:r.typography.fontFamily,text:u,background:Ya(e,r,"none")})]},"ann-cathighlight-"+t)}case"label":case"callout":case"callout-circle":case"callout-rect":case"text":{const{x:o,y:i}=function(e,t,o,n){if(Array.isArray(e.coordinates)&&e.coordinates.length>=2&&t.geoProjection){const o=t.geoProjection([e.coordinates[0],e.coordinates[1]]);if(o)return{x:o[0],y:o[1]}}return{x:Va(e,t,o),y:Ha(e,t,n)}}(e,n,s,a);if(null==o||null==i)return null;const l="text"===e.type,c=e.dx??(l?0:30),u=e.dy??(l?0:-30),d=e.color||r.colors.text;if(!l){const n="callout"===e.type?"callout-circle":e.type,r="callout-circle"===n?{radius:e.radius??12,radiusPadding:e.radiusPadding}:"callout-rect"===n?{width:e.width,height:e.height}:void 0;return ja(B,{noteData:{x:o,y:i,dx:c,dy:u,note:{label:e.label,title:e.title,wrap:e.wrap||120},type:n,...r?{subject:r}:{},connector:e.connector||{end:"arrow"},color:d,disable:e.disable,opacity:e.opacity,strokeDasharray:e.strokeDasharray,className:e.className}},"ann-label-"+t)}return ja("g",{children:ja("text",{x:o+c,y:i+u,textAnchor:e.textAnchor||"start",fontSize:e.fontSize||r.typography.labelSize,fill:d,fontFamily:r.typography.fontFamily,fontWeight:e.fontWeight,opacity:e.opacity,strokeDasharray:e.strokeDasharray,children:e.label||e.title})},"ann-label-"+t)}default:return null}}(t,o,e),e.svgAnnotationRules,u);return h.length>0?ja("g",{id:(e.idPrefix?e.idPrefix+"-":"")+"annotations",className:"semiotic-annotations",children:h}):null}import*as Xa from"react";import{jsx as qa,jsxs as Ua}from"react/jsx-runtime";function Qa(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){const t=e.id;return null==t?null:t+""}return null}function Za(e){const t=e._idPrefix||e.chartId;if(t){const e=(t+"").replace(/[^a-zA-Z0-9_-]/g,"_");return/^[A-Za-z_]/.test(e)?e:"c"+e}const o=`${e.chartType||""}:${e.title||""}:${Array.isArray(e.data)?e.data.length:0}`;let n=0;for(let e=0;o.length>e;e++)n=31*n+o.charCodeAt(e)|0;return"c"+(n>>>0).toString(36)}function Ka(e,t,o){const n=e.showLegend&&!e.__legendIncludesAutomatic?Ia(t,e.colorScheme,o):void 0;return X(n,e.legend)}var Ja={right:110,left:110,top:50,bottom:80};function el(e,t){if(e.__autoLegendMargin&&!tl(e,t))return Ja[t]}function tl(e,t){const o=e.__explicitMargin;return"number"==typeof o||!(!o||"object"!=typeof o||"number"!=typeof o[t])}function ol(e,t){const{props:o,categories:n,theme:i,size:r,hasTitle:s}=t,a=o.legendPosition||"right",l={theme:i,position:a,size:r,hasTitle:s,legendLayout:o.legendLayout,axisChrome:o.axisChrome,minimumMargin:el(o,a),preserveExplicitMargin:tl(o,a)};if(null!=o.legend){const t=Ka(o,n,i);(fe(t)||me(t))&&function(e,t){if(t.preserveExplicitMargin)return;const o=t.position||"right",n={theme:t.theme,position:o,totalWidth:t.size[0],totalHeight:t.size[1],margin:e,hasTitle:t.hasTitle,legendLayout:t.legendLayout},i=fe(t.legend)?function(e){const{width:t,height:o,swatchSize:n}=Ba(e);return{width:t,height:o,swatchSize:n}}({...n,legendGroups:t.legend.legendGroups}):me(t.legend)?Na({...n,gradient:t.legend.gradient}):null;if(!i)return;const r=We(t.legend),s=Math.max(t.minimumMargin??0,Ge(t.legend,t.legendLayout)),a=Fe(t.axisChrome,t.legendLayout),l=Math.max(t.minimumMargin??0,r+i.height+(t.hasTitle?24:0)),c=Math.max(t.minimumMargin??0,a+r+i.height);"right"===o?e.right=Math.max(e.right,s):"left"===o?e.left=Math.max(e.left,s):"top"===o?e.top=Math.max(e.top,l):e.bottom=Math.max(e.bottom,c)}(e,{...l,legend:t})}else o.showLegend&&n.length>0&&function(e,t){if(0===t.categories.length)return;if(t.preserveExplicitMargin)return;const o=t.position||"right",n=function(e){const{width:t,height:o,swatchSize:n}=Oa(e);return{width:t,height:o,swatchSize:n}}({categories:t.categories,colorScheme:t.colorScheme,theme:t.theme,position:o,totalWidth:t.size[0],totalHeight:t.size[1],margin:e,hasTitle:t.hasTitle,legendLayout:t.legendLayout}),i=Ia(t.categories,t.colorScheme,t.theme),r=We(i),s=Math.max(t.minimumMargin??0,Ge(i,t.legendLayout)),a=Fe(t.axisChrome,t.legendLayout),l=Math.max(t.minimumMargin??0,r+n.height+(t.hasTitle?24:0)),c=Math.max(t.minimumMargin??0,a+r+n.height);"right"===o?e.right=Math.max(e.right,s):"left"===o?e.left=Math.max(e.left,s):"top"===o?e.top=Math.max(e.top,l):e.bottom=Math.max(e.bottom,c)}(e,{...l,categories:n,colorScheme:o.colorScheme});return a}function nl(e){const{props:t,categories:o,theme:n,size:i,margin:r,hasTitle:s}=e,a=t.legendPosition||"right",l={theme:n,position:a,size:i,margin:r,hasTitle:s,legendLayout:t.legendLayout,axisChrome:t.axisChrome,idPrefix:t._idPrefix};if(null!=t.legend){const e=Ka(t,o,n);if(Xa.isValidElement(e))return e;const i=function(e,t){const o={theme:t.theme,position:t.position||"right",totalWidth:t.size[0],totalHeight:t.size[1],margin:t.margin,hasTitle:t.hasTitle,legendLayout:t.legendLayout,idPrefix:t.idPrefix,reservedWidth:t.reservedWidth,axisChrome:t.axisChrome,legendDistance:fe(e)||me(e)?e.legendDistance:void 0};return fe(e)?function(e){if(0===(t=e.legendGroups,t.flatMap(e=>e.items.map((t,o)=>({group:e,item:t,itemIndex:o,label:t.label})))).length)return null;var t;const o=Ba(e),n="top"===e.position||"bottom"===e.position,i={legendGroups:e.legendGroups,legendDistance:e.legendDistance},r=e.reservedWidth??Xe(i,e.legendLayout),s=We(i),a=Ve(e.legendLayout),l=Fe(e.axisChrome,e.legendLayout),c=Fe(void 0,e.legendLayout),u=e.theme.colors.grid||e.theme.colors.textSecondary;let d,h;if("left"===e.position?(d=e.margin.left-a-r-s,h=e.margin.top):"top"===e.position?(d=e.margin.left,h=e.margin.top-c-s-o.height):"bottom"===e.position?(d=e.margin.left,h=Math.max(e.totalHeight-e.margin.bottom+s,Math.min(e.totalHeight-e.margin.bottom+l+s,e.totalHeight-o.height))):(d=e.totalWidth-e.margin.right+a+s,h=e.margin.top),!n){const t=ye(e.legendGroups.map(e=>({hasLabel:!!e.label,itemCount:e.items.length})),Math.max(o.swatchSize,e.legendLayout?.rowHeight??La)),n=e.legendGroups.flatMap((n,i)=>{const s=t[i],a=n.type??"fill",l=[Pa("line",{x1:0,y1:s.lineY,x2:r,y2:s.lineY,stroke:"gray"},"legend-group-neatline-"+i)];return n.label&&null!=s.labelY&&l.push(Pa("text",{y:s.labelY,fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:n.label},"legend-group-label-"+i)),l.push(Pa("g",{transform:`translate(0,${s.itemsY})`,children:n.items.map((t,r)=>{const s=n.styleFn(t,r),l="function"==typeof a?a(t):"line"===a?Pa("line",{x1:0,y1:0,x2:o.swatchSize,y2:o.swatchSize,style:s}):Pa("rect",{width:o.swatchSize,height:o.swatchSize,rx:o.swatchRadius,style:s});return Ta("g",{transform:`translate(0,${r*Math.max(o.swatchSize,e.legendLayout?.rowHeight??La)})`,children:[l,Pa("text",{x:o.labelOffset,y:o.swatchSize/2,dominantBaseline:"central",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:t.label})]},`legend-${i}-${r}`)})},"legend-group-"+i)),l});return Pa("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,"data-orientation":"vertical",children:n})}const p=o.groups.flatMap((t,i)=>{const{group:r}=t,s=r.type??"fill",a=[];if(r.label&&a.push(Pa("text",n?{transform:`translate(${t.x},${t.y}) rotate(90)`,textAnchor:"start",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:r.label}:{x:t.x,y:t.y+za(e.theme),fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:r.label},"legend-group-label-"+i)),a.push(...t.items.map((n,a)=>{const l=r.items[a],c=r.styleFn(l,a),u="function"==typeof s?s(l):"line"===s?Pa("line",{x1:0,y1:0,x2:o.swatchSize,y2:o.swatchSize,style:c}):Pa("rect",{width:o.swatchSize,height:o.swatchSize,rx:o.swatchRadius,style:c});return Ta("g",{transform:`translate(${t.x+t.itemOffsetX+n.x},${t.y+t.itemOffsetY+n.y})`,children:[u,Pa("text",{x:o.labelOffset,y:o.swatchSize/2,dominantBaseline:"central",fontSize:za(e.theme),fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:n.category})]},`legend-${i}-${a}`)})),n&&o.groups.length-1>i){const e=t.x+t.width+6;a.push(Pa("line",{x1:e,y1:0,x2:e,y2:o.height,stroke:u},"legend-group-separator-"+i))}return a});return Pa("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,"data-orientation":n?"horizontal":"vertical",children:p})}({...o,legendGroups:e.legendGroups}):me(e)?function(e){const t=Na(e),o="top"===e.position||"bottom"===e.position,n={gradient:e.gradient,legendDistance:e.legendDistance},i=Xe(n),r=We(n),s=Ve(e.legendLayout),a=Fe(e.axisChrome,e.legendLayout),l=Fe(void 0,e.legendLayout),c=(e.idPrefix?e.idPrefix+"-":"")+"semiotic-static-gradient-legend",u=e.gradient.format||(e=>Math.round(100*e)/100+"");let d,h;"left"===e.position?(d=e.margin.left-s-i-r,h=e.margin.top):"top"===e.position?(d=e.margin.left,h=e.margin.top-l-r-t.height):"bottom"===e.position?(d=e.margin.left,h=Math.max(e.totalHeight-e.margin.bottom+r,Math.min(e.totalHeight-e.margin.bottom+a+r,e.totalHeight-t.height))):(d=e.totalWidth-e.margin.right+s+r,h=e.margin.top);const p=Array.from({length:17},(t,n)=>{const i=n/16;return Pa("stop",{offset:100*i+"%",stopColor:e.gradient.colorFn(o?e.gradient.domain[0]+i*(e.gradient.domain[1]-e.gradient.domain[0]):e.gradient.domain[1]-i*(e.gradient.domain[1]-e.gradient.domain[0]))},n)});if(o){const o=12,n=e.gradient.label?0:void 0,i=e.gradient.label?8:0;return Ta("g",{className:"semiotic-legend",transform:`translate(${d},${h})`,children:[Pa("defs",{children:Pa("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"100%",y2:"0%",children:p})}),e.gradient.label&&Pa("text",{x:t.width/2,y:n,textAnchor:"middle",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:e.gradient.label}),Pa("rect",{x:0,y:i,width:t.width,height:o,fill:`url(#${c})`,rx:2}),Pa("text",{x:0,y:i+o+12,textAnchor:"start",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[0])}),Pa("text",{x:t.width,y:i+o+12,textAnchor:"end",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[1])})]})}const g=e.gradient.label?-6:void 0;return Ta("g",{className:"semiotic-legend",transform:`translate(${d},${h+(e.gradient.label?12:0)})`,children:[Pa("defs",{children:Pa("linearGradient",{id:c,x1:"0%",y1:"0%",x2:"0%",y2:"100%",children:p})}),e.gradient.label&&Pa("text",{x:0,y:g,textAnchor:"start",fontSize:e.theme.typography.tickSize,fill:e.theme.colors.text,fontFamily:e.theme.typography.fontFamily,children:e.gradient.label}),Pa("rect",{x:0,y:0,width:14,height:100,fill:`url(#${c})`,rx:2}),Pa("text",{x:19,y:10,fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[1])}),Pa("text",{x:19,y:100,fontSize:e.theme.typography.tickSize,fill:e.theme.colors.textSecondary,fontFamily:e.theme.typography.fontFamily,children:u(e.gradient.domain[0])})]})}({...o,gradient:e.gradient}):null}(e,l);return i||(fe(e)||me(e)?null:e??null)}return t.showLegend&&0!==o.length?function(e){const{categories:t,colorScheme:o,theme:n,position:i="right",totalWidth:r,totalHeight:s,margin:a}=e;if(!t||0===t.length)return null;const l=Ra(t,o,n),c="top"===i||"bottom"===i,u=Oa(e),d=Ia(t,o,n),h=e.reservedWidth??Xe(d,e.legendLayout),p="number"==typeof e.legendDistance?Math.max(0,e.legendDistance):We(d),g=Ve(e.legendLayout),m=Fe(e.axisChrome,e.legendLayout),f=Fe(void 0,e.legendLayout);let y,b;if("left"===i?(y=a.left-g-h-p,b=a.top):"top"===i?(y=a.left,b=a.top-f-p-u.height):"bottom"===i?(y=a.left,b=Math.max(s-a.bottom+p,Math.min(s-a.bottom+m+p,s-u.height))):(y=r-a.right+g+p,b=a.top),c){const e=u.items.map((e,t)=>Ta("g",{transform:`translate(${e.x},${e.y})`,children:[Pa("rect",{width:u.swatchSize,height:u.swatchSize,fill:l(e.category),rx:u.swatchRadius}),Pa("text",{x:u.labelOffset,y:u.swatchSize/2,dominantBaseline:"central",fontSize:za(n),fill:n.colors.text,fontFamily:n.typography.fontFamily,children:e.category})]},"legend-"+t));return Pa("g",{className:"semiotic-legend",transform:`translate(${y},${b})`,children:e})}const x=ye([{hasLabel:!1,itemCount:t.length}],Math.max(u.swatchSize,e.legendLayout?.rowHeight??La))[0],v=u.items.map((e,t)=>Ta("g",{transform:`translate(${e.x},${e.y+x.itemsY})`,children:[Pa("rect",{width:u.swatchSize,height:u.swatchSize,fill:l(e.category),rx:u.swatchRadius}),Pa("text",{x:u.labelOffset,y:u.swatchSize/2,dominantBaseline:"central",fontSize:za(n),fill:n.colors.text,fontFamily:n.typography.fontFamily,children:e.category})]},"legend-"+t));return Ta("g",{className:"semiotic-legend",transform:`translate(${y},${b})`,children:[Pa("line",{x1:0,y1:x.lineY,x2:h,y2:x.lineY,stroke:"gray"}),v]})}({categories:o,colorScheme:t.colorScheme,theme:n,position:a,totalWidth:i[0],totalHeight:i[1],margin:r,hasTitle:s,legendLayout:t.legendLayout,axisChrome:t.axisChrome,idPrefix:t._idPrefix}):null}function il(e){return Math.round(100*e)/100+""}function rl(e,t){const o=Jt(t.theme),n=t.background??o.background,i=t.idPrefix?t.idPrefix+"-":"",r="string"==typeof t.title?t.title:void 0,s=r?i+"semiotic-title":void 0,a=t.description?i+"semiotic-desc":void 0,l=[s,a].filter(Boolean).join(" ")||void 0;return Ua("svg",{xmlns:"http://www.w3.org/2000/svg",className:t.className,width:t.width,height:t.height,role:"img","aria-labelledby":l,style:{fontFamily:o.fontFamily},children:[r&&qa("title",{id:s,children:r}),t.description&&qa("desc",{id:a,children:t.description}),t.defs&&qa("defs",{children:t.defs}),n&&"transparent"!==n&&qa("rect",{x:0,y:0,width:t.width,height:t.height,fill:n}),qa("g",{id:i+"data-area",transform:t.innerTransform,children:e}),r&&qa("text",{id:i+"chart-title",x:t.width/2,y:E,textAnchor:"middle",fontSize:o.titleSize,fontWeight:"bold",fill:o.text,fontFamily:o.fontFamily,children:r}),t.legend&&qa("g",{id:i+"legend",children:t.legend}),t.outerElements]})}import{Fragment as sl,jsx as al,jsxs as ll}from"react/jsx-runtime";function cl(e,t){const o=Kt(e.theme),n=e.size||[500,300],i=ze({top:20,right:20,bottom:30,left:40,...e.margin},e.title),r=pe(e.title),s=ie(e.data),a=e.showLegend?Ea(s,e.colorAccessor||e.groupAccessor||e.categoryAccessor):[],l={hasAxis:!1!==e.showAxes,hasAxisLabel:!!e.xLabel};ol(i,{props:{...e,axisChrome:l},categories:a,theme:o,size:n,hasTitle:r});const c=n[0]-i.left-i.right,u=n[1]-i.top-i.bottom,d="streaming"===e.runtimeMode||["bar","swarm","waterfall"].includes(e.chartType),h=e.colorScheme||o.colors.categorical,p=(e.axes?.find(e=>"left"===e.orient)??e.axes?.find(e=>"right"===e.orient))?.extent??e.axisExtent,g={chartType:e.chartType,windowSize:e.windowSize??200,windowMode:e.windowMode??"sliding",arrowOfTime:d?e.arrowOfTime??"right":"right",extentPadding:e.extentPadding??.1,xAccessor:d?void 0:e.xAccessor,yAccessor:d?void 0:e.yAccessor,timeAccessor:d?e.timeAccessor:void 0,valueAccessor:e.valueAccessor,colorAccessor:e.colorAccessor,sizeAccessor:e.sizeAccessor,symbolAccessor:e.symbolAccessor,symbolMap:e.symbolMap,groupAccessor:e.groupAccessor,categoryAccessor:e.categoryAccessor,lineDataAccessor:e.lineDataAccessor,xExtent:e.xExtent,yExtent:e.yExtent,axisExtent:e.axisExtent,yAxisExtent:p,sizeRange:e.sizeRange,xScaleType:e.xScaleType,yScaleType:e.yScaleType,scalePadding:e.scalePadding,binSize:e.binSize,normalize:e.normalize,baseline:e.baseline,stackOrder:e.stackOrder,boundsAccessor:e.boundsAccessor,boundsStyle:e.boundsStyle,band:e.band,y0Accessor:e.y0Accessor,areaGroups:e.areaGroups?e.areaGroups instanceof Set?e.areaGroups:new Set(e.areaGroups):void 0,curve:e.curve,gradientFill:Se(e.gradientFill),lineGradient:Ae(e.lineGradient),semanticLineStops:e.semanticLineStops,openAccessor:e.openAccessor,highAccessor:e.highAccessor,lowAccessor:e.lowAccessor,closeAccessor:e.closeAccessor,candlestickStyle:e.candlestickStyle,lineStyle:e.lineStyle,pointStyle:e.pointStyle,areaStyle:e.areaStyle,barStyle:e.barStyle,waterfallStyle:e.waterfallStyle,swarmStyle:e.swarmStyle,colorScheme:h,themeCategorical:o.colors.categorical,themeSemantic:Dt(o),customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,layoutSelection:e.layoutSelection,barColors:e.barColors,showValues:e.showValues,heatmapValueFormat:e.heatmapValueFormat},m=new z(g);if(e.data&&m.ingest({inserts:s,bounded:!0}),m.computeScene({width:c,height:u}),!m.scales||0===m.scene.length)return t&&(t.evidence=Sa({frameType:"xy",width:n[0],height:n[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,extraWarnings:m.scales?[]:["NO_SCALES"],margin:i})),Ma.renderToStaticMarkup(rl(null,{width:n[0],height:n[1],className:"stream-xy-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));const f=e._idPrefix,y=Ie({nodes:m.scene,renderMode:e.renderMode,fallback:(e,t)=>at(e,t,f)});t&&(t.evidence=Sa({frameType:"xy",width:n[0],height:n[1],marks:y.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,xDomain:Aa(m.scales.x?.domain?.()),yDomain:Aa(m.scales.y?.domain?.()),legendItems:a.length>0?a.length:void 0,margin:i}));const b=e.showGrid?function(e,t,o,n,i,r){const{grid:s}=Jt(o),a=n?n+"-":"",l=r?.find(e=>"bottom"===e.orient),c=r?.find(e=>"top"===e.orient),u=r?.find(e=>"left"===e.orient),d=r?.find(e=>"right"===e.orient),h=l??c,p=u??d,g=h?.extent??i,m=p?.extent??i,f="exact"===g?5:Math.min(5,Math.max(2,Math.floor(t.width/70))),y="exact"===m?5:Math.min(5,Math.max(2,Math.floor(t.height/30))),b=h?.tickValues??Ze(e.x,h?.ticks??f,g),x=p?.tickValues??Ze(e.y,p?.ticks??y,m),v=!1!==h?.grid,w=!1!==p?.grid,A=De(h?.gridStyle),S=De(p?.gridStyle);return Ua("g",{id:a+"grid",className:"semiotic-grid",opacity:.8,children:[v&&b.map((o,n)=>{const i=e.x(o);return qa("line",{x1:i,y1:0,x2:i,y2:t.height,stroke:s,strokeWidth:.5,strokeDasharray:A},"gx-"+n)}),w&&x.map((o,n)=>{const i=e.y(o);return qa("line",{x1:0,y1:i,x2:t.width,y2:i,stroke:s,strokeWidth:.5,strokeDasharray:S},"gy-"+n)})]})}(m.scales,{width:c,height:u},o,f,e.axisExtent,e.axes):null,x=y.map(e=>e.element),v=Za(e)+"-plot-clip",w=!1!==e.showAxes?function(e,t,o,n,i){const r=Jt(n),s=Ve(o.legendLayout),a=o.legend&&"left"===o.legendPosition&&s>0?s:o.margin?.left??40,l=o.axes?.find(e=>"bottom"===e.orient),c=o.axes?.find(e=>"top"===e.orient),u=o.axes?.find(e=>"left"===e.orient),d=o.axes?.find(e=>"right"===e.orient),h=l??c,p=u??d,g=h?.extent??o.axisExtent,m=p?.extent??o.axisExtent,f="exact"===g?5:Math.min(5,Math.max(2,Math.floor(t.width/70))),y="exact"===m?5:Math.min(5,Math.max(2,Math.floor(t.height/30))),b=h?.tickValues??Ze(e.x,h?.ticks??f,g),x=b.map(e=>e.valueOf()),v=h?.tickFormat||o.xFormat||o.tickFormatTime||il,w=b.map((t,o)=>({pixel:e.x(t),label:v(t,o,x)})),A=p?.tickValues??Ze(e.y,p?.ticks??y,m),S=p?.tickFormat||o.yFormat||o.tickFormatValue||il,k=A.map(t=>({pixel:e.y(t),label:S(t)})),M=h?.label??o.xLabel,_=p?.label??o.yLabel;return Ua("g",{id:(i?i+"-":"")+"axes",className:"stream-axes",children:[!1!==h?.baseline&&qa("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:r.border,strokeWidth:1}),w.map((e,o)=>Ua("g",{transform:`translate(${e.pixel},${t.height})`,children:[qa("line",{y2:5,stroke:r.border,strokeWidth:1}),qa("text",{y:18,textAnchor:"middle",fontSize:r.tickSize,fill:r.textSecondary,fontFamily:r.fontFamily,children:e.label})]},"xtick-"+o)),M&&qa("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:r.labelSize,fill:r.text,fontFamily:r.fontFamily,children:M}),!1!==p?.baseline&&qa("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:r.border,strokeWidth:1}),k.map((e,t)=>Ua("g",{transform:`translate(0,${e.pixel})`,children:[qa("line",{x2:-5,stroke:r.border,strokeWidth:1}),qa("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:r.tickSize,fill:r.textSecondary,fontFamily:r.fontFamily,children:e.label})]},"ytick-"+t)),_&&qa("text",{x:15-a,y:t.height/2,textAnchor:"middle",fontSize:r.labelSize,fill:r.text,fontFamily:r.fontFamily,transform:`rotate(-90, ${15-a}, ${t.height/2})`,children:_})]})}(m.scales,{width:c,height:u},e,o,f):null,A=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,annotationData:s,scales:{x:m.scales.x,y:m.scales.y},layout:{width:c,height:u},theme:o,xAccessor:"string"==typeof e.xAccessor?e.xAccessor:void 0,yAccessor:"string"==typeof e.yAccessor?e.yAccessor:void 0,idPrefix:f}):null,S=e.svgPreRenderers&&m.scales?e.svgPreRenderers.map((e,t)=>{try{return al(ka.Fragment,{children:e(m.scene,m.scales,{width:c,height:u})},"pre-"+t)}catch{return null}}).filter(Boolean):null,k=nl({props:{...e,axisChrome:l},categories:a,theme:o,size:n,margin:i,hasTitle:r});return Ma.renderToStaticMarkup(rl(ll(sl,{children:[e.backgroundGraphics,S,b,al("defs",{children:al("clipPath",{id:v,children:al("rect",{x:0,y:0,width:c,height:u})})}),al("g",{clipPath:`url(#${v})`,children:x}),w,A,e.foregroundGraphics,m.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-xy-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:c,innerHeight:u,legend:k,idPrefix:e._idPrefix}))}import*as ul from"react-dom/server";import{scaleBand as dl,scaleLinear as hl}from"d3-scale";var pl=class{constructor(){this.colorSchemeMap=new Map,this.colorSchemeIndex=0}resetColors(){this.colorSchemeMap.clear(),this.colorSchemeIndex=0}resolvePieceStyle(e,t,o){if(t&&"function"==typeof e.pieceStyle){const n=e.pieceStyle(t,o);return n&&!n.fill&&o?{...n,fill:this.getColorFromScheme(e,o)}:n}return e.pieceStyle&&"object"==typeof e.pieceStyle?e.pieceStyle:e.barColors&&o?{fill:e.barColors[o]||"#007bff"}:{fill:o?this.getColorFromScheme(e,o):"#007bff"}}resolveSummaryStyle(e,t,o){return t&&"function"==typeof e.summaryStyle?e.summaryStyle(t,o):e.summaryStyle&&"object"==typeof e.summaryStyle?e.summaryStyle:{fill:"#007bff",fillOpacity:.6,stroke:"#007bff",strokeWidth:1}}getColorFromScheme(e,t){const o=this.colorSchemeMap.get(t);if(o)return o;const n=Array.isArray(e.colorScheme)?e.colorScheme:e.themeCategorical||F,i=n[this.colorSchemeIndex%n.length];return this.colorSchemeIndex++,this.colorSchemeMap.set(t,i),i}};function gl(e){const t=e.getSymbol;return t?_t(t,e.config.symbolMap):null}function ml(e,t,o,n,i,r,s){e.push(t?{type:"symbol",x:n,y:i,size:Math.PI*r*r,symbolType:t(o),style:s,datum:o}:{type:"point",x:n,y:i,r:r,style:s,datum:o})}function fl(e,t){const{columns:o,config:n,resolvePieceStyle:i}=e,r=[],s=Math.min(t.width,t.height)/2-4,a="donut"===n.chartType?n.innerRadius||60:0,l=-Math.PI/2+(n.startAngle||0)*Math.PI/180,c=null!=n.sweepAngle?n.sweepAngle*Math.PI/180:2*Math.PI,u=null!=n.sweepAngle&&360>n.sweepAngle,d=Object.values(o),h=d.some(e=>{const t=e.pieceData[0];return t&&("number"==typeof t._pct||"number"==typeof t._pctStart||null!=t._roundedEnds)}),p=u&&!h&&d.length>1&&(n.cornerRadius??0)>0;for(let e=0;d.length>e;e++){const t=d[e],o=t.pieceData[0],u="number"==typeof o?._pctStart?o._pctStart:t.pctStart,h=l+u*c,g=l+(u+("number"==typeof o?._pct?o._pct:t.pct))*c,m=i(t.pieceData[0],t.name),f=0===e,y=e===d.length-1,b={type:"wedge",cx:0,cy:0,innerRadius:a,outerRadius:s,startAngle:h,endAngle:g,...n.cornerRadius&&{cornerRadius:n.cornerRadius},style:m,datum:o?._nonInteractive?null:t.pieceData,category:t.name};o?._roundedEnds?b.roundedEnds=o._roundedEnds:p&&(b.roundedEnds={start:f,end:y}),o?._gradientBand&&(b._gradientBand=o._gradientBand),r.push(b)}return r}import{quantile as yl}from"d3-array";function bl(e){const t=e.length,o=e[0],n=e[t-1];return{n:t,min:o,q1:yl(e,.25)??o,median:yl(e,.5)??(o+n)/2,q3:yl(e,.75)??n,max:n,mean:e.reduce((e,t)=>e+t,0)/t}}import{scaleLinear as xl}from"d3-scale";var vl={bar:function(e,t){const{scales:o,columns:n,config:i,getR:r,getStack:s,resolvePieceStyle:a}=e,{r:l,projection:c}=o,u=[],d="vertical"===c,h="horizontal"===c,p=i.normalize,g=[];if(s){const e=new Set;for(const t of Object.values(n))for(const o of t.pieceData){const t=s(o);e.has(t)||(e.add(t),g.push(t))}}else g.push("_default");for(const e of Object.values(n)){const t=new Map;for(const o of e.pieceData){const e=s?s(o):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const n=t.get(e);n.total+=r(o),n.pieces.push(o)}let o=0;if(p)for(const e of t.values())o+=Math.abs(e.total);let n=0,i=0;for(const r of g){const c=t.get(r);if(!c)continue;let g=c.total;p&&o>0&&(g/=o);const m=a(c.pieces[0],s?r:e.name),f={...c.pieces[0],__aggregateValue:c.total,__pieceCount:c.pieces.length,category:e.name};if(d){const t=l(0>g?i:n+g),o=0>g?l(i+g)-l(i):l(n)-l(n+g);u.push(Y(e.x,t,e.width,Math.abs(o),m,f,r)),0>g?i+=g:n+=g}else if(h){const t=l(0>g?i+g:n),o=0>g?l(i)-l(i+g):l(n+g)-l(n);u.push(Y(t,e.x,Math.abs(o),e.width,m,f,r)),0>g?i+=g:n+=g}}}const m="vertical"===c,f=i.roundedTop&&i.roundedTop>0?Math.max(0,i.roundedTop):0;for(const e of u){if("rect"!==e.type)continue;const t=e.datum?.__aggregateValue??0;e.roundedEdge=m?0>t?"bottom":"top":0>t?"left":"right",i.gradientFill&&(e.fillGradient=i.gradientFill)}if(f>0){const e=new Map;for(const t of u){if("rect"!==t.type)continue;const o=t.datum?.category||"";e.has(o)||e.set(o,[]),e.get(o).push(t)}for(const t of e.values()){if(0===t.length)continue;const e=t.filter(e=>(e.datum?.__aggregateValue??0)>=0),o=t.filter(e=>0>(e.datum?.__aggregateValue??0));e.length>0&&(e.reduce(m?(e,t)=>t.y>e.y?e:t:(e,t)=>e.x+e.w>t.x+t.w?e:t).roundedTop=f),o.length>0&&(o.reduce(m?(e,t)=>e.y+e.h>t.y+t.h?e:t:(e,t)=>t.x>e.x?e:t).roundedTop=f)}}return u},clusterbar:function(e,t){const{scales:o,columns:n,config:i,getR:r,getGroup:s,resolvePieceStyle:a}=e,{r:l,projection:c}=o,u=[],d="vertical"===c,h=[],p=new Set;for(const e of Object.values(n))for(const t of e.pieceData){const e=s?s(t):"_default";p.has(e)||(p.add(e),h.push(e))}const g=h.length||1;for(const e of Object.values(n)){const t=e.width/g,o=.2*t,n=t-o,i=new Map;for(const t of e.pieceData){const e=s?s(t):"_default";i.has(e)||i.set(e,[]),i.get(e).push(t)}for(let s=0;h.length>s;s++){const c=i.get(h[s])||[];for(const i of c){const c=r(i),p=a(i,h[s]);if(d){const r=e.x+s*t+o/2,a=l(0),d=l(c);u.push(Y(r,Math.min(a,d),n,Math.abs(a-d),p,i,h[s]))}else{const r=e.x+s*t+o/2,a=l(0),d=l(c);u.push(Y(Math.min(a,d),r,Math.abs(d-a),n,p,i,h[s]))}}}}const m=i.roundedTop&&i.roundedTop>0?Math.max(0,i.roundedTop):0;for(const e of u){if("rect"!==e.type)continue;if(null==e.datum)continue;const t=r(e.datum);m>0&&(e.roundedTop=m),e.roundedEdge=d?0>t?"bottom":"top":0>t?"left":"right",i.gradientFill&&(e.fillGradient=i.gradientFill)}return u},point:function(e,t){const{scales:o,columns:n,getR:i,multiScales:r,resolvePieceStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d="radial"===l,h=r.length>0,p=gl(e),g=2*Math.PI,m=-Math.PI/2;for(const e of Object.values(n))for(const t of e.pieceData){const o=t.__rIndex??0,n=t.__rValue??i(t),l=h&&r[o]||a,f=s(t,e.name),y=f.r||5;let b,x;if(d){const t=m+(e.pctStart+e.pct/2)*g,o=l(n);b=Math.cos(t)*o,x=Math.sin(t)*o}else u?(b=e.middle,x=l(n)):(b=l(n),x=e.middle);ml(c,p,t,b,x,y,f)}return c},swarm:function(e,t){const{scales:o,columns:n,getR:i,resolvePieceStyle:r}=e,{r:s,projection:a}=o,l=[],c="vertical"===a,u=gl(e);for(const e of Object.values(n)){const t=e.width/2;for(let o=0;e.pieceData.length>o;o++){const n=e.pieceData[o],a=i(n),d=r(n,e.name),h=d.r||4,p=(7919*o%100/100-.5)*t*.8;ml(l,u,n,c?e.middle+p:s(a),c?s(a):e.middle+p,h,d)}}return l},pie:fl,donut:fl,boxplot:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d=!1!==i.showOutliers;for(const t of Object.values(n)){const o=t.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(0===o.length)continue;const n=o[0],i=o[o.length-1],l=yl(o,.25)??n,h=yl(o,.5)??(n+i)/2,p=yl(o,.75)??i,g=p-l,m=l-1.5*g,f=p+1.5*g,y=o.find(e=>e>=m)??n,b=[...o].reverse().find(e=>f>=e)??i,x=s(t.pieceData[0],t.name),v=[];if(d)for(const e of t.pieceData){const o=r(e);if(m>o||o>f){const n=u?t.middle:a(o),i=u?a(o):t.middle;v.push({px:n,py:i,value:o,datum:e})}}if(c.push({type:"boxplot",x:u?t.middle:0,y:u?0:t.middle,projection:u?"vertical":"horizontal",columnWidth:.6*t.width,minPos:a(y),q1Pos:a(l),medianPos:a(h),q3Pos:a(p),maxPos:a(b),stats:{n:o.length,min:y,q1:l,median:h,q3:p,max:b,mean:o.reduce((e,t)=>e+t,0)/o.length},style:x,datum:t.pieceData,category:t.name,outliers:v}),d)for(const t of v)c.push({type:"point",x:t.px,y:t.py,r:3,style:{fill:x.fill||e.config.themeSemantic?.secondary||"#999",opacity:.6},datum:t.datum})}return c},violin:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u="vertical"===l,d=i.bins||20,h=!1!==i.showIQR;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(2>t.length)continue;const o=t[0],n=t[t.length-1],i=(n-o)/d||1,l=Array(d).fill(0);for(const e of t)l[Math.min(Math.floor((e-o)/i),d-1)]++;const p=zt(l,1),g=e.width/2*.9;let m;if(u){m=`M ${e.middle} ${a(o)}`;for(let t=0;d>t;t++){const n=a(o+(t+.5)*i);m+=` L ${e.middle+l[t]/p*g} ${n}`}m+=` L ${e.middle} ${a(n)}`;for(let t=d-1;t>=0;t--){const n=a(o+(t+.5)*i);m+=` L ${e.middle-l[t]/p*g} ${n}`}m+=" Z"}else{m=`M ${a(o)} ${e.middle}`;for(let t=0;d>t;t++)m+=` L ${a(o+(t+.5)*i)} ${e.middle-l[t]/p*g}`;m+=` L ${a(n)} ${e.middle}`;for(let t=d-1;t>=0;t--)m+=` L ${a(o+(t+.5)*i)} ${e.middle+l[t]/p*g}`;m+=" Z"}const f=s(e.pieceData[0],e.name);let y;if(h&&t.length>=4){const i=yl(t,.25)??o,r=yl(t,.5)??(o+n)/2,s=yl(t,.75)??n;y={q1Pos:a(i),medianPos:a(r),q3Pos:a(s),centerPos:e.middle,isVertical:u}}const b=u?{x:e.x,y:Math.min(a(n),a(o)),width:e.width,height:Math.abs(a(n)-a(o))}:{x:Math.min(a(o),a(n)),y:e.x,width:Math.abs(a(n)-a(o)),height:e.width};c.push({type:"violin",pathString:m,translateX:0,translateY:0,bounds:b,iqrLine:y,stats:bl(t),style:f,datum:e.pieceData,category:e.name})}return c},histogram:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a}=o,l=[],c=i.bins||25,u=i.normalize,d=a.domain?.(),h=d?+d[0]:void 0,p=d?+d[1]:void 0;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e));if(0===t.length)continue;const[o,n]=Ot(t),i=null!=h&&isFinite(h)?h:o,d=null!=p&&isFinite(p)?p:n,g=(d-i)/c||1,m=Array(c).fill(0);for(const e of t)i>e||e>d||m[Math.min(Math.floor((e-i)/g),c-1)]++;const f=t.length,y=zt(m,1),b=s(e.pieceData[0],e.name);for(let t=0;c>t;t++){if(0===m[t])continue;const o=(u?m[t]/f:m[t]/y)*e.width*.9,n=a(i+t*g),r=a(i+(t+1)*g);l.push(Y(Math.min(n,r),e.x+e.width-o,Math.abs(r-n),o,b,{bin:t,count:m[t],range:[i+t*g,i+(t+1)*g],category:e.name},e.name))}}return l},ridgeline:function(e,t){const{scales:o,columns:n,config:i,getR:r,resolveSummaryStyle:s}=e,{r:a,projection:l}=o,c=[],u=i.bins||20,d="horizontal"===l,h=i.amplitude||1.5;for(const e of Object.values(n)){const t=e.pieceData.map(e=>r(e)).filter(e=>null!=e&&!isNaN(e)).sort((e,t)=>e-t);if(2>t.length)continue;const o=t[0],n=t[t.length-1],i=(n-o)/u||1,l=Array(u).fill(0);for(const e of t)o>e||e>n||l[Math.min(Math.floor((e-o)/i),u-1)]++;const p=zt(l,1),g=s(e.pieceData[0],e.name),m=e.width*h;let f;if(d){const t=e.x+e.width;f=`M ${a(o)} ${t}`;for(let e=0;u>e;e++)f+=` L ${a(o+(e+.5)*i)} ${t-l[e]/p*m}`;f+=` L ${a(n)} ${t} Z`}else{const t=e.x;f=`M ${t} ${a(o)}`;for(let e=0;u>e;e++){const n=a(o+(e+.5)*i);f+=` L ${t+l[e]/p*m} ${n}`}f+=` L ${t} ${a(n)} Z`}const y=d?{x:Math.min(a(o),a(n)),y:e.x,width:Math.abs(a(n)-a(o)),height:e.width}:{x:e.x,y:Math.min(a(n),a(o)),width:e.width,height:Math.abs(a(n)-a(o))};c.push({type:"violin",pathString:f,translateX:0,translateY:0,bounds:y,stats:bl(t),style:{...g,fillOpacity:g.fillOpacity??.5},datum:e.pieceData,category:e.name})}return c},timeline:function(e,t){const{scales:o,columns:n,getRawRange:i,resolvePieceStyle:r}=e,{r:s,projection:a}=o,l=[],c="horizontal"===a;for(const e of Object.values(n))for(const t of e.pieceData){const o=i(t);if(!o)continue;const[n,a]=o,u=r(t,e.name);if(c){const o=s(Math.min(n,a)),i=s(Math.max(n,a));l.push(Y(o,e.x,i-o,e.width,u,t,e.name))}else{const o=s(Math.max(n,a)),i=s(Math.min(n,a));l.push(Y(e.x,o,e.width,i-o,u,t,e.name))}}return l},funnel:function(e,t){const{columns:o,getR:n,getStack:i,resolvePieceStyle:r}=e,s=[],a=t.width/2,l=!1!==e.config.showLabels,c=e.scales.o.domain().map(e=>o[e]).filter(Boolean);if(0===c.length)return s;const u=[],d=new Set;for(const e of c)for(const t of e.pieceData){const e=i?i(t):"_default";d.has(e)||(d.add(e),u.push(e))}const h=u.length>1&&"_default"!==u[0],p=[];let g=0;for(const e of c){const t=new Map;let o=0;for(const r of e.pieceData){const e=i?i(r):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const s=t.get(e),a=n(r);s.total+=a,s.pieces.push(r),o+=a}p.push({col:e,groups:t,stepTotal:o}),h||o>g&&(g=o)}if(h)for(const e of p){let t=0,o=0;for(let n=0;u.length>n;n++){const i=e.groups.get(u[n]);i&&(n%2==0?t+=i.total:o+=i.total)}const n=Math.max(t,o);n>g&&(g=n)}if(0===g)return s;const m=new Map;for(const e of u){const t=p[0].groups.get(e);m.set(e,t?.total??0)}const f=p[0].stepTotal,y=h?.95*a:.9*t.width,b=xl().domain([0,g]).range([0,y]),x=e.config.connectorOpacity??.3;let v=new Map;for(let t=0;p.length>t;t++){const o=p[t],n=o.col,i=0===t,c=n.width,d=.55*c,g=n.x+(c-d)/2,y=new Map;if(h){let e=0;for(const t of u){const n=o.groups.get(t);n&&(e+=b(n.total))}let t=a,c=a;for(let h=0;u.length>h;h++){const p=u[h],f=o.groups.get(p);if(!f)continue;const x=b(f.total),v=h%2==0,w=v?t:c-x;v?t+=x:c-=x;const A=r(f.pieces[0],p),S=m.get(p)??f.total,k={...f.pieces[0],__funnelValue:f.total,__funnelPercent:S>0?f.total/S*100:0,__funnelStep:n.name,__funnelIsFirstStep:i,__aggregateValue:f.total,__pieceCount:f.pieces.length,category:p};l&&(0===h&&(k.__funnelStepLabel=n.name,k.__funnelStepLabelX=a,k.__funnelStepLabelY=g,k.__funnelRowWidth=e),k.__funnelValueLabelX=w+x/2,k.__funnelValueLabelY=g,k.__funnelBarW=x),s.push(Y(w,g,x,d,A,k,p)),y.set(p,{x:w,y:g,w:x,h:d})}}else{const e=o.stepTotal,t=b(e),c=a-t/2,h=u[0],p="_default"!==h,m=o.groups.get(h)?.pieces[0]??n.pieceData[0],x=p?h:n.name,v=r(m,x),w=f>0?e/f*100:0,A={...m,__funnelValue:e,__funnelPercent:w,__funnelStep:n.name,__funnelIsFirstStep:i,category:p?h:n.name};l&&(A.__funnelStepLabel=n.name,A.__funnelStepLabelX=a,A.__funnelStepLabelY=g,A.__funnelRowWidth=t,A.__funnelValueLabelX=a,A.__funnelValueLabelY=g,A.__funnelBarW=t),s.push(Y(c,g,t,d,v,A,x)),y.set(h,{x:c,y:g,w:t,h:d})}if(t>0&&v.size>0){const t=h?u:[u[0]];for(const i of t){const t=v.get(i),a=y.get(i);if(!t||!a)continue;const l=(()=>{const e=o.groups.get(i);return r(e?e.pieces[0]:n.pieceData[0],"_default"===i?n.name:i)})(),c={type:"trapezoid",points:[[t.x,t.y+t.h],[t.x+t.w,t.y+t.h],[a.x+a.w,a.y],[a.x,a.y]],style:{fill:l.fill||e.config.themeSemantic?.secondary||"#999",opacity:x},datum:o.groups.get(i)?.pieces[0]??n.pieceData[0],category:"_default"===i?n.name:i};s.push(c)}}v=y}return s},"bar-funnel":function(e,t){const{columns:o,getR:n,getStack:i,resolvePieceStyle:r,scales:s}=e,a=[],l=s.o.domain().map(e=>o[e]).filter(Boolean);if(0===l.length)return a;const c=[],u=new Set;for(const e of l)for(const t of e.pieceData){const e=i?i(t):"_default";u.has(e)||(u.add(e),c.push(e))}const d=c.length>1&&"_default"!==c[0],h=[];for(const e of l){const t=new Map;let o=0;for(const r of e.pieceData){const e=i?i(r):"_default";t.has(e)||t.set(e,{total:0,pieces:[]});const s=t.get(e),a=n(r);s.total+=a,s.pieces.push(r),o+=a}h.push({col:e,groups:t,stepTotal:o})}const p=new Map;for(const e of c){const t=h[0]?.groups.get(e);p.set(e,t?.total??0)}const g=s.r,m=d?c.length:1,f=d?.15:0;for(let e=0;h.length>e;e++){const t=h[e],o=t.col,n=0===e,i=e>0?h[e-1]:null,s=o.width/m,l=s*f,u=s-l;for(let e=0;c.length>e;e++){const h=c[e],m=t.groups.get(h);if(!m)continue;const f=m.total,y=p.get(h)??f,b=y>0?f/y*100:0,x=i?.groups.get(h),v=n?0:Math.max(0,(x?.total??f)-f),w=o.x+e*s+l/2,A=g(f),S=g(0)-A,k=r(m.pieces[0],d?h:o.name),M={...m.pieces[0],__barFunnelValue:f,__barFunnelPercent:b,__barFunnelIsFirstStep:n,__barFunnelIsDropoff:!1,__barFunnelStep:o.name,__barFunnelDropoffValue:v,__barFunnelCategory:"_default"===h?void 0:h,category:d?h:o.name,__barFunnelLabelX:w+u/2,__barFunnelLabelY:g(f+v)};if(a.push(Y(w,A,u,S,k,M,d?h:o.name)),v>0){const e=g(f+v),t=A-e,n={...k},i={...m.pieces[0],__barFunnelValue:v,__barFunnelPercent:y>0?v/y*100:0,__barFunnelIsFirstStep:!1,__barFunnelIsDropoff:!0,__barFunnelStep:o.name,__barFunnelCategory:"_default"===h?void 0:h,category:d?h:o.name};a.push(Y(w,e,u,t,n,i,d?h:o.name))}}}return a},swimlane:function(e,t){const{scales:o,columns:n,getR:i,getStack:r,resolvePieceStyle:s}=e,{r:a,projection:l}=o,c=[],u="horizontal"===l,d=e.config.gradientFill,h=u?"left":"bottom",p=e.config.trackFill;if(p){const e="string"==typeof p?p:p.color,t="string"==typeof p?1:p.opacity??1,[o,i]=a.range(),r=Math.min(o,i),s=Math.abs(i-o);for(const o of Object.values(n)){const n={fill:e,opacity:t},i=u?Y(r,o.x,s,o.width,n,null,"__track__"):Y(o.x,r,o.width,s,n,null,"__track__");c.push(i)}}const g=e.config.roundedTop&&e.config.roundedTop>0?Math.max(0,e.config.roundedTop):0;for(const e of Object.values(n)){let t=0;const o=c.length;for(const o of e.pieceData){const n=Math.abs(i(o));if(0===n)continue;const l=r?r(o):e.name,p=s(o,l);let g;if(u){const i=a(t),r=a(t+n);g=Y(i,e.x,r-i,e.width,p,o,l)}else{const i=a(t+n),r=a(t);g=Y(e.x,i,e.width,r-i,p,o,l)}d&&(g.fillGradient=d,g.roundedEdge=h),c.push(g),t+=n}if(g>0&&c.length>o){const e=c.slice(o),t=e[0],n=e[e.length-1];1===e.length?t.cornerRadii={tl:g,tr:g,br:g,bl:g}:u?(t.cornerRadii={tl:g,bl:g},n.cornerRadii={tr:g,br:g}):(t.cornerRadii={bl:g,br:g},n.cornerRadii={tl:g,tr:g})}}return c}},wl=["data","domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Al=["scene-style","data-paint","accessibility","evidence"],Sl=(e,t)=>({retainedData:e,invalidations:t}),kl=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Ml=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],_l=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Pl=["scene-geometry","data-paint","accessibility","evidence"],Tl=["scene-style","data-paint","accessibility","evidence"],Ll=[],Rl={chartType:Sl("rebuild",kl),runtimeMode:Sl("rebuild",kl),categoryAccessor:Sl("rebuild",kl),valueAccessor:Sl("rebuild",kl),oAccessor:Sl("rebuild",kl),rAccessor:Sl("rebuild",kl),stackBy:Sl("rebuild",kl),groupBy:Sl("rebuild",kl),timeAccessor:Sl("rebuild",kl),accessorRevision:Sl("rebuild",kl),colorAccessor:Sl("rebuild",Tl),symbolAccessor:Sl("rebuild",Pl),connectorAccessor:Sl("rebuild",Pl),dataIdAccessor:Sl("rebuild",Pl),projection:Sl("preserve",Ml),extentPadding:Sl("preserve",Ml),axisExtent:Sl("preserve",Ml),rExtent:Sl("preserve",Ml),oExtent:Sl("preserve",Ml),multiAxis:Sl("preserve",Ml),normalize:Sl("preserve",Ml),bins:Sl("preserve",Ml),oSort:Sl("preserve",_l),barPadding:Sl("preserve",_l),roundedTop:Sl("preserve",_l),baselinePadding:Sl("preserve",_l),innerRadius:Sl("preserve",_l),cornerRadius:Sl("preserve",_l),startAngle:Sl("preserve",_l),sweepAngle:Sl("preserve",_l),trackFill:Sl("preserve",_l),showOutliers:Sl("preserve",_l),showIQR:Sl("preserve",_l),amplitude:Sl("preserve",_l),connectorOpacity:Sl("preserve",_l),showLabels:Sl("preserve",_l),dynamicColumnWidth:Sl("rebuild",_l),customLayout:Sl("preserve",_l),layoutConfig:Sl("preserve",_l),layoutMargin:Sl("preserve",_l),symbolMap:Sl("preserve",Pl),pieceStyle:Sl("preserve",Tl),summaryStyle:Sl("preserve",Tl),connectorStyle:Sl("preserve",Tl),gradientFill:Sl("preserve",Tl),colorScheme:Sl("preserve",Tl),themeCategorical:Sl("preserve",Tl),themeSemantic:Sl("preserve",Tl),themeSequential:Sl("preserve",Tl),themeDiverging:Sl("preserve",Tl),barColors:Sl("preserve",Tl),decay:Sl("preserve",Tl),pulse:Sl("preserve",Tl),staleness:Sl("preserve",Tl),layoutSelection:Sl("preserve",Tl),windowSize:Sl("preserve",Ll),windowMode:Sl("preserve",Ll),clock:Sl("preserve",Ll),transition:Sl("preserve",Ll),introAnimation:Sl("preserve",Ll),onLayoutError:Sl("preserve",Ll)},Il=Sl("preserve",_l),Cl=class{constructor(){this.tracker=new mt}get last(){return this.tracker.last}subscribe(e){return this.tracker.subscribe(e)}recordData(e,t){return this.tracker.record({kind:e,...void 0===t?{}:{count:t}},wl)}recordNoop(e){return this.tracker.record({kind:e,..."restyle"===e?{}:{count:0}},[])}recordRestyle(e){return e?this.tracker.record({kind:"restyle"},Al):this.recordNoop("restyle")}recordConfig(e){const t=function(e){let t="preserve";const o=new Set;for(const n of e){const e=Rl[n]??Il;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)o.add(t)}return{retainedData:t,invalidations:o}}(e);return this.tracker.record({kind:"config",keys:e},t.invalidations)}};import{quadtree as zl}from"d3-quadtree";var Fl=class{constructor(e){this.rExtent=new ct,this.rExtents=[],this.windowSizeWarned=!1,this.updateResults=new Cl,this.rAccessors=[],this.categories=new Set,this._hasStreamingData=!1,this.styleResolver=new pl,this.timestampBuffer=null,this.activeTransition=null,this.prevPositionMap=new Map,this.exitNodes=[],this.lastIngestTime=0,this.scales=null,this.multiScales=[],this.scene=[],this.columns={},this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customLayoutFailedThisBuild=!1,this._customLayoutDiagnosticsWarned=new Set,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this.version=0,this._dataVersion=0,this._bufferArrayCache=null,this._pointQuadtree=null,this._maxPointRadius=0,this._datumIndexCache=null,this._categoryIndexCache=null,this._hasRenderedOnce=!1,this.config=e,this.buffer=new ut(e.windowSize),this.getO=Ct(e.categoryAccessor||e.oAccessor,"category");const t=e.valueAccessor||e.rAccessor;Array.isArray(t)?(this.rAccessors=t.map(e=>It(e,"value")),this.getR=this.rAccessors[0],this.rExtents=t.map(()=>new ct)):(this.getR=It(t,"value"),this.rAccessors=[this.getR],this.rExtents=[this.rExtent]),this.getStack=Ct(e.stackBy),this.getGroup=Ct(e.groupBy),this.getColor=Ct(e.colorAccessor),this.getSymbol=Ct(e.symbolAccessor),this.getConnector=Ct(e.connectorAccessor),this.getDataId=Ct(e.dataIdAccessor),e.pulse&&(this.timestampBuffer=new ut(e.windowSize))}syncPulseTimestampBuffer(){var e,t,o,n;this.timestampBuffer=(e=!!this.config.pulse,t=this.buffer,o=this.timestampBuffer,n=this.currentTime(),e?null!=o&&o.capacity===t.capacity&&o.size===t.size?o:te(t,n):null)}currentTime(){return this.config.clock?.()??Me()}ingest(e){const t=this.currentTime();if(this.lastIngestTime=t,this._dataVersion++,e.bounded){this.buffer.clear(),this.rExtent.clear();for(const e of this.rExtents)e.clear();e.preserveCategoryOrder?this._hasStreamingData=!0:this.categories.clear(),this.timestampBuffer&&this.timestampBuffer.clear(),ne(this.buffer,e.totalSize||e.inserts.length,this.timestampBuffer);for(const o of e.inserts)Pe(this.buffer,o,this.timestampBuffer,t),this.categories.add(this.getO(o)),this.pushValueExtent(o)}else{this._hasStreamingData=!0;for(const o of e.inserts){const e=Pe(this.buffer,o,this.timestampBuffer,t);this.categories.add(this.getO(o)),this.pushValueExtent(o),null!=e&&this.evictValueExtent(e)}}return this.updateResults.recordData(e.bounded?"replace":"ingest",e.inserts.length),!0}ingestWithResult(e){return this.ingest(e),this.updateResults.last}pushValueExtent(e){if("timeline"===this.config.chartType){const t=this.getRawRange(e);t&&(this.rExtent.push(t[0]),this.rExtent.push(t[1]))}else if(this.rAccessors.length>1){for(let t=0;this.rAccessors.length>t;t++)this.rExtents[t].push(this.rAccessors[t](e));this.rExtent.push(this.getR(e))}else this.rExtent.push(this.getR(e))}evictValueExtent(e){if("timeline"===this.config.chartType){const t=this.getRawRange(e);t&&(this.rExtent.evict(t[0]),this.rExtent.evict(t[1]))}else if(this.rAccessors.length>1){for(let t=0;this.rAccessors.length>t;t++)this.rExtents[t].evict(this.rAccessors[t](e));this.rExtent.evict(this.getR(e))}else this.rExtent.evict(this.getR(e))}getRawRange(e){const t=this.config.valueAccessor||this.config.rAccessor;if(!t)return null;const o="function"==typeof t?t(e):e[t];return Array.isArray(o)&&o.length>=2?[+o[0],+o[1]]:null}computeScene(e){const{config:t,buffer:o}=this,n=this.scales,i=this.multiScales,r=this.columns;if(0===o.size)return this.scales=null,this.multiScales=[],this.scene=[],this.columns={},this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,void this.version++;this.rExtent.dirty&&this.rExtent.recalculate(o,this.getR);const s=this.getBufferArray(),a=t.projection||"vertical",l=t.oExtent||this.resolveCategories(s),c=this.computeValueDomain(s,l),u="horizontal"===a,d="radial"===a,h=Math.min(.9,Math.max(0,null!=t.barPadding?t.barPadding/("vertical"===a?e.width:e.height):.1));let p,g;if(d){p=dl().domain(l).range([0,1]).padding(0);const o=Math.min(e.width,e.height)/2,n=t.innerRadius||0;g=hl().domain(c).range([n,o])}else u?(p=dl().domain(l).range([0,e.height]).padding(h),g=hl().domain(c).range([0,e.width])):(p=dl().domain(l).range([0,e.width]).padding(h),g=hl().domain(c).range([e.height,0]));this.scales={o:p,r:g,projection:a},this.multiScales=this.rAccessors.length>1&&t.multiAxis?this.rAccessors.map((n,i)=>{const r=this.rExtents[i];r.dirty&&r.recalculate(o,n);let[s,a]=r.extent;s===1/0&&(s=0,a=1);const l=a-s,c=l>0?l*(t.extentPadding??.05):1;return s-=c,a+=c,s>0&&(s=0),u?hl().domain([s,a]).range([0,e.width]):hl().domain([s,a]).range([e.height,0])}):[];let m=s;this.rAccessors.length>1&&(m=s.flatMap(e=>this.rAccessors.map((t,o)=>({...e,__rIndex:o,__rValue:t(e),__rName:this.resolveRAccessorName(o)})))),this.columns=this.buildColumns(m,l,p,a,e),this._customLayoutFailedThisBuild=!1;const f=this.buildSceneNodes(m,e);this._customLayoutFailedThisBuild?!0===this.lastCustomLayoutFailure?.preservedLastGoodScene?(this.scales=n,this.multiScales=i,this.columns=r):(this.scene=[],this.rebuildPointQuadtree()):(this.config.transition&&this.scene.length>0&&this.snapshotPositions(),this.scene=f,this.rebuildPointQuadtree(),this.config.decay&&this.applyDecay(this.scene,s),this.config.pulse&&this.applyPulse(this.scene,s),this.config.transition&&!this._hasRenderedOnce&&this.scene.length>0&&(this.config.introAnimation&&this.synthesizeIntroPositions(),this._hasRenderedOnce=!0),this.config.transition&&this.prevPositionMap.size>0&&this.startTransition(),this.version++)}resolveRAccessorName(e){const t=this.config.valueAccessor||this.config.rAccessor,o=Array.isArray(t)?t[e]:t;return"string"==typeof o?o:"value"+e}resolveCategories(e){const t=this.config.oSort,o="streaming"===this.config.runtimeMode||this._hasStreamingData,n="auto"===t?void 0:t;let i=null;if(o){i=new Set;for(const t of e)i.add(this.getO(t))}const r=i?Array.from(this.categories).filter(e=>i.has(e)):Array.from(this.categories);if(o&&void 0===n){const e=Math.max(50,3*i.size);if(this.categories.size>e){let t=this.categories.size-e;for(const e of this.categories){if(0>=t)break;i.has(e)||(this.categories.delete(e),t--)}}return r}if(!1===n)return r;if("function"==typeof n)return r.sort(n);const s=new Map;for(const t of e){const e=this.getO(t);s.set(e,(s.get(e)||0)+Math.abs(this.getR(t)))}return r.sort("asc"===n?(e,t)=>(s.get(e)||0)-(s.get(t)||0):(e,t)=>(s.get(t)||0)-(s.get(e)||0))}computeValueDomain(e,t){return function(e){const{data:t,chartType:o,projection:n,normalize:i,rExtent:r,extentPadding:s=.05,baselinePadding:a,axisExtent:l,getO:c,getR:u,getStack:d,rawRExtent:h}=e,p=s;if("radial"===n&&("pie"===o||"donut"===o))return[0,1];let g=0,m=0;if("bar"===o&&d&&i)g=0,m=1;else if("bar"===o&&d){const e=new Map,o=new Map;for(const n of t){const t=c(n),i=u(n);0>i?o.set(t,(o.get(t)||0)+i):e.set(t,(e.get(t)||0)+i)}for(const t of e.values())t>m&&(m=t);for(const e of o.values())g>e&&(g=e)}else if("bar"===o){const e=new Map;for(const o of t){const t=c(o),n=u(o);e.set(t,(e.get(t)||0)+n)}for(const t of e.values())t>m&&(m=t),g>t&&(g=t)}else if("swimlane"===o){const e=new Map;for(const o of t){const t=c(o),n=Math.abs(u(o));e.set(t,(e.get(t)||0)+n)}for(const t of e.values())t>m&&(m=t)}else if("clusterbar"===o||"bar-funnel"===o)for(const e of t){const t=u(e);t>m&&(m=t),g>t&&(g=t)}else{const e=h[0],t=h[1];e!==1/0&&(g=e),t!==-1/0&&(m=t)}r&&(null!=r[0]&&(g=r[0]),null!=r[1]&&(m=r[1]));const f="bar"===o||"clusterbar"===o||"bar-funnel"===o||"swimlane"===o;if(f&&null==r?.[0]&&null==r?.[1]&&(g>0&&(g=0),0>m&&(m=0)),"bar-funnel"!==o&&"exact"!==l){const e=m-g,t=e>0?e*p:1,n=f&&!a&&0===g,i=f&&!a&&0===m||"swimlane"===o;null!=r?.[0]||n||(g-=t),null!=r?.[1]||i||(m+=t)}return[g,m]}({data:e,chartType:this.config.chartType,projection:this.config.projection,normalize:this.config.normalize,rExtent:this.config.rExtent,extentPadding:this.config.extentPadding,baselinePadding:this.config.baselinePadding,axisExtent:this.config.axisExtent,getO:this.getO,getR:this.getR,getStack:this.getStack,rawRExtent:this.rExtent.extent})}buildColumns(e,t,o,n,i){return function(e){const{data:t,oExtent:o,oScale:n,projection:i,layout:r,dynamicColumnWidth:s,getO:a,getR:l}=e,c={},u=new Map;for(const e of t){const t=a(e);u.has(t)||u.set(t,[]),u.get(t).push(e)}let d=0;if("radial"===i)for(const e of t)d+=Math.abs(l(e));let h=null;if(s&&"radial"!==i){h=new Map;let e=0;for(const t of o){const o=u.get(t)||[];let n;n="string"==typeof s?o.reduce((e,t)=>e+(Number(t[s])||0),0):s(o),h.set(t,n),e+=n}const t=("horizontal"===i?r.height:r.width)-n.padding()*n.step()*o.length;if(e>0)for(const[o,n]of h)h.set(o,n/e*t)}let p=0,g=0;for(const e of o){const t=u.get(e)||[],o=t.reduce((e,t)=>e+Math.abs(l(t)),0),i=d>0?o/d:0;let r,s;h?(r=g,s=h.get(e)||n.bandwidth(),g+=s+n.padding()*n.step()):(r=n(e)??0,s=n.bandwidth()),c[e]={name:e,x:r,y:0,width:s,middle:r+s/2,padding:n.padding()*n.step(),pieceData:t,pct:i,pctStart:p},p+=i}return c}({data:e,oExtent:t,oScale:o,projection:n,layout:i,dynamicColumnWidth:this.config.dynamicColumnWidth,getO:this.getO,getR:this.getR})}getSceneContext(){return{scales:this.scales,columns:this.columns,config:this.config,getR:this.getR,getStack:this.getStack,getGroup:this.getGroup,getColor:this.getColor,getSymbol:this.getSymbol,getConnector:this.getConnector,getO:this.getO,multiScales:this.multiScales,rAccessors:this.rAccessors,resolvePieceStyle:(e,t)=>this.styleResolver.resolvePieceStyle(this.config,e,t),resolveSummaryStyle:(e,t)=>this.styleResolver.resolveSummaryStyle(this.config,e,t),getRawRange:e=>this.getRawRange(e)}}buildSceneNodes(e,t){if(!this.scales)return[];if(this.config.customLayout){const o=this.buildLayoutContext(e,t);let n;try{n=this.config.customLayout(o)}catch(e){const t=null!==this.lastCustomLayoutResult,o=ee("ordinal",e,t,this.version);this.lastCustomLayoutFailure=o,this._customLayoutFailedThisBuild=!0,"production"!==process.env.NODE_ENV&&console.error("[semiotic] ordinal customLayout threw:",e);try{this.config.onLayoutError?.(o)}catch(e){"production"!==process.env.NODE_ENV&&console.error("[semiotic] onLayoutError threw:",e)}return t?this.scene:(this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,[])}this.customLayoutOverlays=n.overlays??null,this.lastCustomLayoutResult=n,this.lastCustomLayoutFailure=null;const i=n.nodes??[];if(this._customRestyle=n.restyle,this.hasCustomRestyle=!!n.restyle,this.hasCustomRestyle){this._baseStyles=new WeakMap;for(const e of i)e.style&&this._baseStyles.set(e,e.style);this.applyCustomRestyle(i,this.config.layoutSelection??null)}return st({label:"ordinal customLayout",nodes:i,overlays:this.customLayoutOverlays,warned:this._customLayoutDiagnosticsWarned}),i}this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1;const o=this.getSceneContext(),n=vl[this.config.chartType];let i=n?n(o,t):[];if(this.getConnector&&this.scales){const e=function(e,t){const{scales:o,config:n,getConnector:i,getO:r}=e;if(!i||!o)return[];const s=[],{projection:a}=o,l=new Map;for(const e of t){if("point"!==e.type&&"rect"!==e.type)continue;const t=e.datum;if(!t)continue;const o=i(t);if(!o)continue;let n,s;"point"===e.type?(n=e.x,s=e.y):(n=e.x+e.w/2,s=e.y+("vertical"===a?0:e.h/2)),l.has(o)||l.set(o,[]),l.get(o).push({x:n,y:s,datum:t,category:r(t)})}const c=o.o.domain(),u=n.connectorStyle;for(const[t,o]of l)if(o.length>=2){o.sort((e,t)=>c.indexOf(e.category)-c.indexOf(t.category));for(let n=0;o.length-1>n;n++){const i=o[n],r=o[n+1],a="function"==typeof u?u(i.datum):u||{stroke:e.config.themeSemantic?.border||e.config.themeSemantic?.secondary||"#999",strokeWidth:1,opacity:.5};s.push({type:"connector",x1:i.x,y1:i.y,x2:r.x,y2:r.y,style:a,datum:i.datum,group:t})}}return s}(o,i);i=[...e,...i]}return i}buildLayoutContext(e,t){const o=this.config,n=o.layoutMargin??{top:0,right:0,bottom:0,left:0},i=Ne(o.colorScheme,o.themeCategorical,F),r=this.scales;return{data:e,scales:{o:r.o,r:r.r,projection:r.projection},dimensions:{width:t.width,height:t.height,margin:n,plot:"radial"===r.projection?{x:-t.width/2,y:-t.height/2,width:t.width,height:t.height}:{x:0,y:0,width:t.width,height:t.height}},theme:{semantic:o.themeSemantic??{},categorical:[...i]},resolveColor:V(i,o.colorScheme),config:o.layoutConfig??{},selection:o.layoutSelection??null}}computeDecayOpacity(e,t){const o=this.config.decay;return o&&t>1?q(o,e,t):1}getDatumIndexMap(e){if(this._datumIndexCache&&this._datumIndexCache.version===this._dataVersion)return this._datumIndexCache.map;const t=W(e);return this._datumIndexCache={version:this._dataVersion,map:t},t}getCategoryIndexMap(e){if(this._categoryIndexCache&&this._categoryIndexCache.version===this._dataVersion)return this._categoryIndexCache.map;const t=function(e,t){const o="function"==typeof t,n=o?null:t||"category",i=new Map;for(let r=0;e.length>r;r++){const s=e[r],a=o?t(s):s[n],l=i.get(a);l?l.push(r):i.set(a,[r])}return i}(e,this.config.categoryAccessor||this.config.oAccessor);return this._categoryIndexCache={version:this._dataVersion,map:t},t}rebuildPointQuadtree(){const e=function(e){let t=0,o=0;for(const n of e)"point"===n.type&&(t++,n.r>o&&(o=n.r));if(500>=t)return{quadtree:null,maxRadius:o};const n=Array(t);let i=0;for(const t of e)"point"===t.type&&(n[i++]=t);return{maxRadius:o,quadtree:zl().x(e=>e.x).y(e=>e.y).addAll(n)}}(this.scene);this._pointQuadtree=e.quadtree,this._maxPointRadius=e.maxRadius}get pointQuadtree(){return this._pointQuadtree}get maxPointRadius(){return this._maxPointRadius}applyDecay(e,t){if(!this.config.decay)return;const o=t.length;if(1>=o)return;const n=this.getDatumIndexMap(t);for(const t of e){if("connector"===t.type||"violin"===t.type||"boxplot"===t.type||"wedge"===t.type)continue;if(!t.datum)continue;const e=n.get(t.datum);if(null==e)continue;const i=this.computeDecayOpacity(e,o);t.style={...t.style,opacity:(t.style?.opacity??1)*i}}}applyPulse(e,t,o=this.currentTime()){return!(!this.config.pulse||!this.timestampBuffer)&&function(e,t,o,n,i,r){const s=e.color??"rgba(255,255,255,0.6)",a=e.glowRadius??4;let l=!1;for(const c of t){if("connector"===c.type||"violin"===c.type||"boxplot"===c.type)continue;if("wedge"===c.type){const t=c.category;if(!t)continue;let n=0;for(const s of i(t)??[]){const t=o.get(s);null!=t&&(n=Math.max(n,Q(e,t,r)))}l=Ue(c,n,s)||l;continue}if(null==c.datum)continue;const t=n.get(c.datum);if(null==t)continue;const u=o.get(t),d=null==u?0:Q(e,u,r);l=Ue(c,d,s,a)||l}return l}(this.config.pulse,e,this.timestampBuffer,this.getDatumIndexMap(t),e=>this.getCategoryIndexMap(t).get(e),o)}refreshPulse(e){return!0!==this.lastCustomLayoutFailure?.preservedLastGoodScene&&this.applyPulse(this.scene,this.getBufferArray(),e)}hasActivePulsesAt(e){return!!this.config.pulse&&he(this.config.pulse,this.timestampBuffer,e)}get hasActivePulses(){return this.hasActivePulsesAt(this.currentTime())}synthesizeIntroPositions(){this.prevPositionMap.clear();const e=new Map,t=this.scales?.r(0)??0,o="horizontal"!==this.scales?.projection;let n;for(let i=0;this.scene.length>i;i++){const r=this.scene[i],s=this.getNodeKey(r,e);s&&("rect"===r.type?this.prevPositionMap.set(s,o?{x:r.x,y:t,w:r.w,h:0,opacity:r.style.opacity??1}:{x:t,y:r.y,w:0,h:r.h,opacity:r.style.opacity??1}):"point"===r.type?this.prevPositionMap.set(s,{x:r.x,y:r.y,r:0,opacity:0}):"wedge"===r.type&&(void 0===n&&(n=r.startAngle),this.prevPositionMap.set(s,{x:r.cx,y:r.cy,startAngle:n,endAngle:n,innerRadius:r.innerRadius,outerRadius:r.outerRadius,opacity:0})))}}getNodeKey(e,t){if("point"===e.type){const o=`p:${e.datum?this.getO(e.datum):""}:${e.datum?this.getR(e.datum):0}`,n=t.get(o)||0;return t.set(o,n+1),`${o}:${n}`}if("rect"===e.type){const o=e.datum?null!=e.datum.category&&""!==e.datum.category?e.datum.category+"":(this.getO(e.datum)??"")+"":"",n=`r:${e.group||""}:${o}`,i=t.get(n)||0;return t.set(n,i+1),0===i?n:`${n}:${i}`}return"wedge"===e.type?"w:"+(e.category??""):null}snapshotPositions(){this.prevPositionMap.clear();const e=new Map;for(let t=0;this.scene.length>t;t++){const o=this.scene[t],n=this.getNodeKey(o,e);n&&("point"===o.type?this.prevPositionMap.set(n,{x:o.x,y:o.y,r:o.r,opacity:o.style.opacity??o.style.fillOpacity}):"rect"===o.type?this.prevPositionMap.set(n,{x:o.x,y:o.y,w:o.w,h:o.h,opacity:o.style.opacity??o.style.fillOpacity}):"wedge"===o.type&&this.prevPositionMap.set(n,{x:o.cx,y:o.cy,startAngle:o.startAngle,endAngle:o.endAngle,innerRadius:o.innerRadius,outerRadius:o.outerRadius,opacity:o.style.opacity??1}))}}startTransition(){if(!this.config.transition||0===this.prevPositionMap.size)return;const e=this.config.transition.duration??300;if(this.exitNodes.length>0){const e=new Set(this.exitNodes);this.scene=this.scene.filter(t=>!e.has(t)),this.exitNodes=[]}let t=!1;const o=new Set,n=new Map;for(let e=0;this.scene.length>e;e++){const i=this.scene[e],r=this.getNodeKey(i,n);if(!r)continue;i._transitionKey=r;const s=this.prevPositionMap.get(r);if("point"===i.type)s?(o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,(s.x!==i.x||s.y!==i.y||void 0!==s.r&&s.r!==i.r)&&(i._targetX=i.x,i._targetY=i.y,i._targetR=i.r,i.x=s.x,i.y=s.y,void 0!==s.r&&(i.r=s.r),t=!0)):(i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i._targetR=i.r,i.r=0,i.style={...i.style,opacity:0},t=!0);else if("rect"===i.type)s?(o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,s.x===i.x&&s.y===i.y&&s.w===i.w&&s.h===i.h||(i._targetX=i.x,i._targetY=i.y,i._targetW=i.w,i._targetH=i.h,i.x=s.x,i.y=s.y,i.w=s.w??i.w,i.h=s.h??i.h,t=!0)):(i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i.style={...i.style,opacity:0},t=!0);else if("wedge"===i.type)if(s)o.add(r),i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,s.startAngle===i.startAngle&&s.endAngle===i.endAngle||(i._targetStartAngle=i.startAngle,i._targetEndAngle=i.endAngle,i.startAngle=s.startAngle,i.endAngle=s.endAngle,t=!0);else{i._targetOpacity=i.style.opacity??i.style.fillOpacity??1,i._targetStartAngle=i.startAngle,i._targetEndAngle=i.endAngle;const e=i.startAngle;i.startAngle=e,i.endAngle=e,i.style={...i.style,opacity:0},this.prevPositionMap.set(r,{x:i.cx,y:i.cy,startAngle:e,endAngle:e,innerRadius:i.innerRadius,outerRadius:i.outerRadius,opacity:0}),t=!0}}this.exitNodes=[];for(const[e,n]of this.prevPositionMap)if(!o.has(e)){if(e.startsWith("p:"))this.exitNodes.push({type:"point",x:n.x,y:n.y,r:n.r??3,style:{opacity:n.opacity??1},datum:null,_targetOpacity:0,_transitionKey:e});else if(e.startsWith("r:"))this.exitNodes.push({type:"rect",x:n.x,y:n.y,w:n.w??0,h:n.h??0,style:{opacity:n.opacity??1,fill:"#999"},datum:null,_targetOpacity:0,_transitionKey:e});else if(e.startsWith("w:")){const t=((n.startAngle??0)+(n.endAngle??0))/2,o={type:"wedge",cx:n.x,cy:n.y,innerRadius:n.innerRadius??0,outerRadius:n.outerRadius??100,startAngle:n.startAngle??0,endAngle:n.endAngle??0,style:{opacity:n.opacity??1},datum:null,category:e.slice(2),_targetStartAngle:t,_targetEndAngle:t,_targetOpacity:0,_transitionKey:e};this.exitNodes.push(o)}t=!0}this.exitNodes.length>0&&(this.scene=[...this.scene,...this.exitNodes]),t&&(this.activeTransition={startTime:this.currentTime(),duration:e})}advanceTransition(e){if(!this.activeTransition)return!1;const t=Z(e,this.activeTransition),o=U(t,"linear"===this.config.transition?.easing?"linear":"ease-out-cubic");for(const e of this.scene){const t=e._transitionKey;if(t)if("point"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style.opacity=be(n?n.opacity??1:0,e._targetOpacity,o)}const n=this.prevPositionMap.get(t);void 0!==e._targetX&&n&&(e.x=be(n.x,e._targetX,o),e.y=be(n.y,e._targetY,o)),void 0!==e._targetR&&void 0!==n?.r&&(e.r=be(n.r,e._targetR,o))}else if("rect"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style.opacity=be(n?n.opacity??1:0,e._targetOpacity,o)}if(void 0===e._targetX)continue;const n=this.prevPositionMap.get(t);if(!n)continue;e.x=be(n.x,e._targetX,o),e.y=be(n.y,e._targetY,o),void 0!==n.w&&(e.w=be(n.w,e._targetW,o),e.h=be(n.h,e._targetH,o))}else if("wedge"===e.type){if(void 0!==e._targetOpacity){const n=this.prevPositionMap.get(t);e.style={...e.style,opacity:be(n?n.opacity??1:0,e._targetOpacity,o)}}if(void 0!==e._targetStartAngle&&void 0!==e._targetEndAngle){const n=this.prevPositionMap.get(t);n&&void 0!==n.startAngle&&(e.startAngle=be(n.startAngle,e._targetStartAngle,o),e.endAngle=be(n.endAngle,e._targetEndAngle,o))}}}if(t>=1){for(const e of this.scene)if(void 0!==e._targetOpacity&&(e.style={...e.style||{},opacity:0===e._targetOpacity?0:e._targetOpacity},e._targetOpacity=void 0),"point"===e.type){if(void 0===e._targetX&&void 0===e._targetR)continue;void 0!==e._targetX&&(e.x=e._targetX,e.y=e._targetY),void 0!==e._targetR&&(e.r=e._targetR),e._targetX=void 0,e._targetY=void 0,e._targetR=void 0}else if("rect"===e.type){if(void 0===e._targetX)continue;e.x=e._targetX,e.y=e._targetY,e.w=e._targetW,e.h=e._targetH,e._targetX=void 0,e._targetY=void 0,e._targetW=void 0,e._targetH=void 0}else"wedge"===e.type&&void 0!==e._targetStartAngle&&(e.startAngle=e._targetStartAngle,e.endAngle=e._targetEndAngle,e._targetStartAngle=void 0,e._targetEndAngle=void 0);if(this.exitNodes.length>0){const e=new Set(this.exitNodes);this.scene=this.scene.filter(t=>!e.has(t)),this.exitNodes=[]}return this.activeTransition=null,!1}return!0}cancelIntroAnimation(){this.prevPositionMap.clear(),this.activeTransition=null,Qe(this.scene),this.exitNodes=[]}getBufferArray(){return this._bufferArrayCache?.version!==this._dataVersion&&(this._bufferArrayCache={version:this._dataVersion,data:this.buffer.toArray()}),this._bufferArrayCache.data}getData(){return this.buffer.toArray()}remove(e){if(!this.getDataId)throw Error("remove() requires dataIdAccessor to be configured");this.config.transition&&this.scene.length>0&&this.snapshotPositions();const t=Ke(e),o=this.getDataId,n=e=>t.has(o(e));G(this.buffer,this.timestampBuffer,n);const i=this.buffer.remove(n);if(0===i.length)return this.updateResults.recordNoop("remove"),i;for(const e of i)this.evictValueExtent(e);return this.categories.clear(),this.buffer.forEach(e=>this.categories.add(this.getO(e))),this._dataVersion++,this.version++,this.lastIngestTime=this.currentTime(),this.updateResults.recordData("remove",i.length),i}update(e,t){if(!this.getDataId)throw Error("update() requires dataIdAccessor to be configured");const o=Ke(e),n=this.getDataId,i=new Set;this.buffer.forEach((e,t)=>{o.has(n(e))&&i.add(t)});const r=this.buffer.update(e=>o.has(n(e)),t);if(0===r.length)return this.updateResults.recordNoop("update"),r;for(const e of r)this.evictValueExtent(e);return this.categories.clear(),this.buffer.forEach((e,t)=>{this.categories.add(this.getO(e)),i.has(t)&&this.pushValueExtent(e)}),this._dataVersion++,this.version++,this.lastIngestTime=this.currentTime(),this.updateResults.recordData("update",r.length),r}clear(){this.buffer.clear(),this.rExtent.clear(),this.categories.clear(),this._hasStreamingData=!1,this._hasRenderedOnce=!1,this.timestampBuffer&&this.timestampBuffer.clear(),this.prevPositionMap.clear(),this.exitNodes=[],this.activeTransition=null,this.lastIngestTime=0,this.scales=null,this.scene=[],this.columns={},this.multiScales=[],this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._pointQuadtree=null,this._maxPointRadius=0,this.styleResolver.resetColors(),this._dataVersion++,this.version++,this.updateResults.recordData("clear")}get size(){return this.buffer.size}getOAccessor(){return this.getO}getRAccessor(){return this.getR}applyCustomRestyle(e,t){const o=this._customRestyle;if(o)for(const n of e){const e=this._baseStyles.get(n)??n.style??{},i=o(n,t);n.style=i?{...e,...i}:e}}restyleScene(e){this._customRestyle?(this.applyCustomRestyle(this.scene,e),this.updateResults.recordRestyle(!0)):this.updateResults.recordRestyle(!1)}rebuildAccessorDerivedState(){this.categories.clear(),this.rExtent.clear();for(const e of this.rExtents)e.clear();this._categoryIndexCache=null,this.buffer.forEach(e=>{this.categories.add(this.getO(e)),this.pushValueExtent(e)})}updateConfig(e){const t={...this.config},o=Object.keys(e).filter(o=>e[o]!==t[o]);"production"!==process.env.NODE_ENV&&!this.windowSizeWarned&&"windowSize"in e&&e.windowSize!==t.windowSize&&(this.windowSizeWarned=!0,console.warn(`[Semiotic] windowSize changed after mount (${t.windowSize} → ${e.windowSize}) but it is a mount-only setting — the ring buffer keeps its original capacity. Remount the chart (e.g. via a React key) to apply a new windowSize.`)),("colorScheme"in e&&e.colorScheme!==t.colorScheme||"themeCategorical"in e&&e.themeCategorical!==t.themeCategorical||"colorAccessor"in e&&!Rt(e.colorAccessor,t.colorAccessor))&&this.styleResolver.resetColors(),("categoryAccessor"in e&&!Rt(e.categoryAccessor,t.categoryAccessor)||"oAccessor"in e&&!Rt(e.oAccessor,t.oAccessor))&&(this._categoryIndexCache=null),Object.assign(this.config,e),"pulse"in e&&this.syncPulseTimestampBuffer();let n=!1;("categoryAccessor"in e||"oAccessor"in e)&&(Rt(this.config.categoryAccessor||this.config.oAccessor,t.categoryAccessor||t.oAccessor)||(this.getO=Ct(this.config.categoryAccessor||this.config.oAccessor,"category"),n=!0));let i=!1;if("valueAccessor"in e||"rAccessor"in e){const e=this.config.valueAccessor||this.config.rAccessor,o=t.valueAccessor||t.rAccessor,n=Array.isArray(e)?e:[e],r=Array.isArray(o)?o:[o];if(i=n.length!==r.length||n.some((e,t)=>!Rt(e,r[t])),i){const e=this.config.valueAccessor||this.config.rAccessor;Array.isArray(e)?(this.rAccessors=e.map(e=>It(e,"value")),this.getR=this.rAccessors[0],this.rExtents=e.map(()=>new ct)):(this.getR=It(e,"value"),this.rAccessors=[this.getR],this.rExtents=[this.rExtent])}}"stackBy"in e&&!Rt(e.stackBy,t.stackBy)&&(this.getStack=null!=this.config.stackBy?Ct(this.config.stackBy):void 0),"groupBy"in e&&!Rt(e.groupBy,t.groupBy)&&(this.getGroup=null!=this.config.groupBy?Ct(this.config.groupBy):void 0),"colorAccessor"in e&&!Rt(e.colorAccessor,t.colorAccessor)&&(this.getColor=null!=this.config.colorAccessor?Ct(this.config.colorAccessor):void 0),"symbolAccessor"in e&&!Rt(e.symbolAccessor,t.symbolAccessor)&&(this.getSymbol=null!=this.config.symbolAccessor?Ct(this.config.symbolAccessor):void 0),"connectorAccessor"in e&&!Rt(e.connectorAccessor,t.connectorAccessor)&&(this.getConnector=null!=this.config.connectorAccessor?Ct(this.config.connectorAccessor):void 0),(n||i||"accessorRevision"in e&&e.accessorRevision!==t.accessorRevision)&&this.rebuildAccessorDerivedState(),this.updateResults.recordConfig(o)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}};j(Fl);import{jsx as Ol,jsxs as Bl}from"react/jsx-runtime";import{Fragment as Nl,jsx as El,jsxs as jl}from"react/jsx-runtime";function $l(e,t){const o=Kt(e.theme),n=e.size||[500,400],i=ze({top:20,right:20,bottom:30,left:40,...e.margin},e.title),r=pe(e.title),s=ie(e.data),a=e.showLegend?Ea(s,e.colorAccessor||e.stackBy||e.groupBy):[],l=e.projection||"vertical",c={hasAxis:!1!==e.showAxes&&"radial"!==l,hasAxisLabel:"horizontal"===l?!(!e.valueLabel&&!e.rLabel):!(!e.categoryLabel&&!e.oLabel)};ol(i,{props:{...e,axisChrome:c},categories:a,theme:o,size:n,hasTitle:r});const u=n[0]-i.left-i.right,d=n[1]-i.top-i.bottom,h=e.projection||"vertical",p="radial"===h,g=e.colorScheme||o.colors.categorical,m={chartType:e.chartType,windowSize:e.windowSize??1e4,windowMode:e.windowMode??"sliding",extentPadding:e.extentPadding??.05,projection:h,oAccessor:e.oAccessor,rAccessor:e.rAccessor,colorAccessor:e.colorAccessor,stackBy:e.stackBy,groupBy:e.groupBy,categoryAccessor:e.categoryAccessor,valueAccessor:e.valueAccessor,timeAccessor:e.timeAccessor,rExtent:e.rExtent,oExtent:e.oExtent,axisExtent:e.axisExtent,barPadding:e.barPadding,roundedTop:e.roundedTop,innerRadius:e.innerRadius,cornerRadius:e.cornerRadius,normalize:e.normalize,startAngle:e.startAngle,sweepAngle:e.sweepAngle,bins:e.bins,showOutliers:e.showOutliers,showIQR:e.showIQR,amplitude:e.amplitude,oSort:e.oSort,connectorAccessor:e.connectorAccessor,connectorStyle:e.connectorStyle,dynamicColumnWidth:e.dynamicColumnWidth,pieceStyle:e.pieceStyle,summaryStyle:e.summaryStyle,gradientFill:Se(e.gradientFill),symbolAccessor:e.symbolAccessor,symbolMap:e.symbolMap,multiAxis:e.multiAxis,baselinePadding:e.baselinePadding,trackFill:e.trackFill,connectorOpacity:e.connectorOpacity,showLabels:e.showLabels,colorScheme:g,themeCategorical:o.colors.categorical,themeSemantic:Dt(o),customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,layoutSelection:e.layoutSelection,barColors:e.barColors},f=new Fl(m);if(e.data&&f.ingest({inserts:s,bounded:!0}),f.computeScene({width:u,height:d}),!f.scales||0===f.scene.length)return t&&(t.evidence=Sa({frameType:"ordinal",width:n[0],height:n[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,extraWarnings:f.scales?[]:["NO_SCALES"],margin:i})),ul.renderToStaticMarkup(rl(null,{width:n[0],height:n[1],className:"stream-ordinal-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left},${i.top})`,innerWidth:u,innerHeight:d,idPrefix:e._idPrefix}));const y=e._idPrefix,b=e.showGrid?function(e,t,o,n,i){const r=e.scales;if(!r||"radial"===r.projection)return null;const{grid:s}=Jt(o),a=n?n+"-":"",l="vertical"===r.projection,c=Ze(r.r,5,i);return qa("g",l?{id:a+"grid",className:"semiotic-grid",opacity:.8,children:c.map((e,o)=>{const n=r.r(e);return qa("line",{x1:0,y1:n,x2:t.width,y2:n,stroke:s,strokeWidth:.5},"gr-"+o)})}:{id:a+"grid",className:"semiotic-grid",opacity:.8,children:c.map((e,o)=>{const n=r.r(e);return qa("line",{x1:n,y1:0,x2:n,y2:t.height,stroke:s,strokeWidth:.5},"gr-"+o)})})}(f,{width:u,height:d},o,y,e.axisExtent):null;let x=null;if(f.scene.some(e=>"rect"===e.type&&e.datum?.__barFunnelIsDropoff)){const t=Za(e),n=new Set;for(const e of f.scene)"rect"===e.type&&e.datum?.__barFunnelIsDropoff&&n.add("string"==typeof e.style.fill?e.style.fill:"#666");x=Array.from(n).map((e,n)=>function(e){const{id:t,background:o="transparent",stroke:n="#000",lineWidth:i=1.5,spacing:r=6,angle:s=45}=e,a=Math.max(8,Math.ceil(2*r));return Bl("pattern",{id:t,width:a,height:a,patternUnits:"userSpaceOnUse",patternTransform:0!==s?`rotate(${s})`:void 0,children:[o&&"transparent"!==o&&Ol("rect",{width:a,height:a,fill:o}),Ol("line",{x1:0,y1:0,x2:0,y2:a,stroke:n,strokeWidth:i}),Ol("line",{x1:r,y1:0,x2:r,y2:a,stroke:n,strokeWidth:i})]},t)}({id:`funnel-hatch-${t}-${n}`,background:e,stroke:"transparent"===o.colors.background?"#fff":o.colors.background,lineWidth:1.5,spacing:5,angle:45}));const i=new Map;Array.from(n).forEach((e,o)=>i.set(e,`funnel-hatch-${t}-${o}`));for(const e of f.scene)"rect"===e.type&&e.datum?.__barFunnelIsDropoff&&(e.style={...e.style,fill:`url(#${i.get("string"==typeof e.style.fill?e.style.fill:"#666")})`})}const v=Ie({nodes:f.scene,renderMode:e.renderMode,fallback:(e,t)=>_e(e,t,y)}),w=v.map(e=>e.element);if(t){const o=f.scales.o?.domain?.();t.evidence=Sa({frameType:"ordinal",width:n[0],height:n[1],marks:v.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,yDomain:Aa(f.scales.r?.domain?.()),categories:Array.isArray(o)?o.map(String):void 0,margin:i})}const A=!1!==e.showAxes?function(e,t,o,n,i){const r=e.scales;if(!r)return null;if("radial"===r.projection)return null;const s=Jt(n),a="vertical"===r.projection,l=o.categoryFormat||o.oFormat,c=o.valueFormat||o.rFormat,u=o.categoryLabel||o.oLabel,d=o.valueLabel||o.rLabel,h=Object.values(e.columns).map(e=>({pixel:e.middle,label:(l||String)(e.name)})),p=Ze(r.r,5,o.axisExtent).map(e=>({pixel:r.r(e),label:(c||il)(e)}));return jl("g",a?{id:(i?i+"-":"")+"axes",className:"ordinal-axes",children:[El("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:s.border,strokeWidth:1}),h.map((e,o)=>jl("g",{transform:`translate(${e.pixel},${t.height})`,children:[El("line",{y2:5,stroke:s.border,strokeWidth:1}),El("text",{y:18,textAnchor:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oxtick-"+o)),u&&El("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,children:u}),El("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:s.border,strokeWidth:1}),p.map((e,t)=>jl("g",{transform:`translate(0,${e.pixel})`,children:[El("line",{x2:-5,stroke:s.border,strokeWidth:1}),El("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oytick-"+t)),d&&El("text",{x:15-(o.margin?.left??40),y:t.height/2,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,transform:`rotate(-90, ${15-(o.margin?.left??40)}, ${t.height/2})`,children:d})]}:{id:(i?i+"-":"")+"axes",className:"ordinal-axes",children:[El("line",{x1:0,y1:t.height,x2:t.width,y2:t.height,stroke:s.border,strokeWidth:1}),p.map((e,o)=>jl("g",{transform:`translate(${e.pixel},${t.height})`,children:[El("line",{y2:5,stroke:s.border,strokeWidth:1}),El("text",{y:18,textAnchor:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oxtick-"+o)),d&&El("text",{x:t.width/2,y:t.height+40,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,children:d}),El("line",{x1:0,y1:0,x2:0,y2:t.height,stroke:s.border,strokeWidth:1}),h.map((e,t)=>jl("g",{transform:`translate(0,${e.pixel})`,children:[El("line",{x2:-5,stroke:s.border,strokeWidth:1}),El("text",{x:-8,textAnchor:"end",dominantBaseline:"middle",fontSize:s.tickSize,fill:s.textSecondary,fontFamily:s.fontFamily,children:e.label})]},"oytick-"+t)),u&&El("text",{x:15-(o.margin?.left??40),y:t.height/2,textAnchor:"middle",fontSize:s.labelSize,fill:s.text,fontFamily:s.fontFamily,transform:`rotate(-90, ${15-(o.margin?.left??40)}, ${t.height/2})`,children:u})]})}(f,{width:u,height:d},e,o,y):null,S=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,annotationData:s,scales:{o:f.scales.o,r:f.scales.r,y:"vertical"===f.scales.projection?f.scales.r:void 0},layout:{width:u,height:d},theme:o,projection:h,idPrefix:y}):null,k=nl({props:{...e,axisChrome:c},categories:a,theme:o,size:n,margin:i,hasTitle:r}),M=p?i.left+u/2:i.left,_=p?i.top+d/2:i.top,P=p&&e.centerContent?El("foreignObject",{x:i.left,y:i.top,width:u,height:d,pointerEvents:"none",children:El("div",{style:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center"},children:e.centerContent})}):null;return ul.renderToStaticMarkup(rl(jl(Nl,{children:[e.backgroundGraphics,b,w,A,S,e.foregroundGraphics,f.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-ordinal-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${M},${_})`,innerWidth:u,innerHeight:d,legend:k,defs:x,outerElements:P,idPrefix:e._idPrefix}))}import*as Dl from"react-dom/server";import{Fragment as Wl,jsxs as Yl}from"react/jsx-runtime";function Vl(e,t){return e?"function"==typeof e?e:t=>t[e]:e=>e[t]}var Hl=new Set(["tree","cluster","treemap","circlepack","partition"]);function Gl(e,t){const o=Kt(e.theme),n=e.chartType||"force",i=()=>Sa({frameType:"network",width:r[0],height:r[1],marks:[],title:e.title,description:e.description,annotations:e.annotations,nodeCount:0,edgeCount:0,margin:s}),r=e.size||[500,500],s=ze({top:20,right:20,bottom:20,left:20,...e.margin},e.title),a=pe(e.title),l=e.showLegend?(()=>{const t="string"==typeof(o=e.colorBy)||"function"==typeof o?e.colorBy:void 0;var o;if(!t)return[];const n=ie(e.nodes||[]);if(n.length>0)return Ea(n,t);const i=Array.isArray(e.edges)?ie(e.edges):[];if(0===i.length)return[];const r=Vl(e.sourceAccessor,"source"),s=Vl(e.targetAccessor,"target");return Ea(Array.from(new Set(i.flatMap(e=>[r(e),s(e)]).filter(e=>null!=e).map(String))).map(e=>({id:e})),t)})():[];ol(s,{props:e,categories:l,theme:o,size:r,hasTitle:a});const c=r[0]-s.left-s.right,u=r[1]-s.top-s.bottom,d=ue(n);if(!d&&!e.customNetworkLayout)throw Error(`No layout plugin found for chart type: "${n}". Supported types: force, sankey, chord, tree, cluster, treemap, circlepack, partition.`);const h={chartType:n,nodeIDAccessor:e.nodeIDAccessor,sourceAccessor:e.sourceAccessor,targetAccessor:e.targetAccessor,valueAccessor:e.valueAccessor,childrenAccessor:e.childrenAccessor,hierarchySum:e.hierarchySum,orientation:e.orientation,nodeAlign:e.nodeAlign,nodePaddingRatio:e.nodePaddingRatio,nodeWidth:e.nodeWidth,iterations:e.iterations,forceStrength:e.forceStrength,padAngle:e.padAngle,groupWidth:e.groupWidth,sortGroups:e.sortGroups,edgeSort:e.edgeSort,treeOrientation:e.treeOrientation,edgeType:e.edgeType,padding:e.padding,paddingTop:e.paddingTop,nodeStyle:e.nodeStyle,edgeStyle:e.edgeStyle,nodeLabel:e.nodeLabel,showLabels:e.showLabels,labelMode:e.labelMode,colorBy:e.colorBy,colorScheme:e.colorScheme||o.colors.categorical,edgeColorBy:e.edgeColorBy,edgeOpacity:e.edgeOpacity,colorByDepth:e.colorByDepth,nodeSize:e.nodeSize,nodeSizeRange:e.nodeSizeRange,customNetworkLayout:e.customNetworkLayout,layoutConfig:e.layoutConfig};let p,g;if(Hl.has(n)){const n=e.data||e.edges;if(!n||Array.isArray(n))return t&&(t.evidence=i()),Dl.renderToStaticMarkup(rl(null,{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));h.__hierarchyRoot=n,p=[],g=[]}else{const n=ie(e.nodes||[]),a=Array.isArray(e.edges)?ie(e.edges):[];if(0===n.length&&0===a.length)return t&&(t.evidence=i()),Dl.renderToStaticMarkup(rl(null,{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,idPrefix:e._idPrefix}));if(g=function(e,t){const o=Vl(t.sourceAccessor,"source"),n=Vl(t.targetAccessor,"target"),i=Vl(t.valueAccessor,"value");return e.map(e=>({source:o(e)+"",target:n(e)+"",value:Number(i(e))||1,y0:0,y1:0,sankeyWidth:0,data:e}))}(a,h),0===n.length&&g.length>0){const e=new Set;for(const t of g){const o=Qa(t.source),n=Qa(t.target);o&&e.add(o),n&&e.add(n)}p=Array.from(e).map(e=>({id:e,x:0,y:0,x0:0,x1:0,y0:0,y1:0,width:0,height:0,value:0,data:{id:e}}))}else p=function(e,t){const o=Vl(t.nodeIDAccessor,"id");return e.map(e=>({id:o(e)+"",x:e.x??0,y:e.y??0,x0:0,x1:0,y0:0,y1:0,width:0,height:0,value:0,data:e}))}(n,h)}let m=[],f=[],y=[],b=null;if(h.customNetworkLayout){const e=h.colorScheme,t=Ne(e,o.colors.categorical,Pt),n=V(t,e),i={nodes:p,edges:g,dimensions:{width:c,height:u,plot:{x:0,y:0,width:c,height:u}},theme:{semantic:o.colors,categorical:[...t]},resolveColor:n,config:h.layoutConfig??{}},r=h.customNetworkLayout(i);m=r.sceneNodes??[],f=r.sceneEdges??[],y=r.labels??[],b=r.overlays??null}else if(d){d.computeLayout(p,g,h,[c,u]);const e=d.buildScene(p,g,h,[c,u]);m=e.sceneNodes,f=e.sceneEdges,y=e.labels}const x=Jt(o);for(const e of y)e.fill||(e.fill=x.text);const v=Ie({nodes:f,renderMode:e.renderMode,fallback:(e,t)=>ve(e,t)}),w=Ie({nodes:m,renderMode:e.renderMode,fallback:(e,t)=>we(e,t)});t&&(t.evidence=Sa({frameType:"network",width:r[0],height:r[1],marks:[...w.map(({node:e})=>({type:"node:"+(e.type??"node")})),...v.map(({node:e})=>({type:"edge:"+(e.type??"edge")}))],title:e.title,description:e.description,annotations:e.annotations,nodeCount:w.length,edgeCount:v.length,margin:s}));const A=v.map(e=>e.element),S=w.map(e=>e.element),k=y.map((e,t)=>xe(e,t)).filter(Boolean),M=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{},layout:{width:c,height:u},theme:o,idPrefix:e._idPrefix}):null,_=nl({props:e,categories:l,theme:o,size:r,margin:s,hasTitle:a});return Dl.renderToStaticMarkup(rl(Yl(Wl,{children:[e.backgroundGraphics,A,S,k,M,e.foregroundGraphics,b]}),{width:r[0],height:r[1],className:"stream-network-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${s.left},${s.top})`,innerWidth:c,innerHeight:u,legend:_,idPrefix:e._idPrefix}))}import*as Xl from"react-dom/server";import{geoPath as ql}from"d3-geo";import{quadtree as Ul}from"d3-quadtree";import{geoMercator as Ql,geoEqualEarth as Zl,geoAlbersUsa as Kl,geoOrthographic as Jl,geoNaturalEarth1 as ec,geoEquirectangular as tc}from"d3-geo";var oc={mercator:Ql,equalEarth:Zl,albersUsa:Kl,orthographic:Jl,naturalEarth:ec,equirectangular:tc};function nc(e,t){return e?"function"==typeof e?e:t=>t[e]:e=>e[t]}function ic(e){return e?"function"==typeof e?e:t=>t[e]:e=>e.coordinates||e.data||[]}function rc(e,t,o){return e?"function"==typeof e?{...o,...e(t)}:{...o,...e}:{...o}}function sc(e,t){if(2>e.length)return[e];const o=.4*t,n=[];let i=[e[0]];for(let t=1;e.length>t;t++){const r=e[t];Math.abs(r[0]-e[t-1][0])>o?(2>i.length||n.push(i),i=[r]):i.push(r)}return 2>i.length||n.push(i),n}function ac(e,t,o=24){const n=t[0]-e[0],i=t[1]-e[1],r=Math.sqrt(n*n+i*i);if(0===r)return[e,t];const s=-i/r,a=n/r,l=Math.min(.3*r,80),c=(e[0]+t[0])/2+s*l,u=(e[1]+t[1])/2+a*l,d=[];for(let n=0;o>=n;n++){const i=n/o,r=1-i;d.push([r*r*e[0]+2*r*i*c+i*i*t[0],r*r*e[1]+2*r*i*u+i*i*t[1]])}return d}function lc(e,t){if(2>e.length)return e;const o=t/2+1,n=[];for(let t=0;e.length>t;t++){const i=e[t];let r,s;0===t?(r=e[1][0]-i[0],s=e[1][1]-i[1]):t===e.length-1?(r=i[0]-e[t-1][0],s=i[1]-e[t-1][1]):(r=e[t+1][0]-e[t-1][0],s=e[t+1][1]-e[t-1][1]);const a=Math.sqrt(r*r+s*s)||1;n.push([i[0]+s/a*o,i[1]+-r/a*o])}return n}function cc(e,t,o,n,i){const r=t[0]-e[0],s=t[1]-e[1],a=Math.sqrt(r*r+s*s);if(0===a)return[e,t];const l=s/a,c=-r/a,u=i/2+1;return[[e[0]+l*u,e[1]+c*u],[t[0]+l*u,t[1]+c*u]]}import{scaleLinear as uc}from"d3-scale";var dc=["data","domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],hc=["scene-style","data-paint","accessibility","evidence"],pc=(e,t)=>({retainedData:e,invalidations:t}),gc=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],mc=["domain","layout","scene-geometry","data-paint","overlay","accessibility","evidence"],fc=["scene-geometry","data-paint","accessibility","evidence"],yc=["scene-style","data-paint","accessibility","evidence"],bc=["overlay","accessibility","evidence"],xc=[],vc={xAccessor:pc("rebuild",gc),yAccessor:pc("rebuild",gc),lineDataAccessor:pc("rebuild",gc),pointIdAccessor:pc("rebuild",fc),lineIdAccessor:pc("rebuild",fc),windowSize:pc("rebuild",gc),projection:pc("preserve",mc),projectionExtent:pc("preserve",mc),fitPadding:pc("preserve",mc),lineType:pc("preserve",mc),flowStyle:pc("preserve",mc),graticule:pc("preserve",mc),projectionTransform:pc("preserve",mc),customLayout:pc("preserve",mc),layoutConfig:pc("preserve",mc),layoutMargin:pc("preserve",mc),areaStyle:pc("preserve",yc),pointStyle:pc("preserve",["scene-geometry","scene-style","data-paint","accessibility","evidence"]),lineStyle:pc("preserve",yc),colorScheme:pc("preserve",yc),themeCategorical:pc("preserve",yc),themeDiverging:pc("preserve",yc),themeSemantic:pc("preserve",yc),themeSequential:pc("preserve",yc),decay:pc("preserve",yc),pulse:pc("preserve",yc),layoutSelection:pc("preserve",yc),annotations:pc("preserve",bc),autoPlaceAnnotations:pc("preserve",bc),clock:pc("preserve",xc),transition:pc("preserve",xc),introAnimation:pc("preserve",xc),onLayoutError:pc("preserve",xc)},wc=pc("preserve",mc),Ac=class{constructor(){this.tracker=new mt}get last(){return this.tracker.last}subscribe(e){return this.tracker.subscribe(e)}recordData(e,t){return this.tracker.record({kind:e,...void 0===t?{}:{count:t}},dc)}recordNoop(e){return this.tracker.record({kind:e,..."restyle"===e?{}:{count:0}},[])}recordRestyle(e){return e?this.tracker.record({kind:"restyle"},hc):this.recordNoop("restyle")}recordConfig(e,t={}){const o=function(e){let t="preserve";const o=new Set;for(const n of e){const e=vc[n]??wc;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)o.add(t)}return{retainedData:t,invalidations:o}}(e),n=new Set(o.invalidations);return t.retainedDataChanged&&n.add("data"),this.tracker.record({kind:"config",keys:e},n)}};import{geoDistance as Sc,geoGraticule as kc,geoInterpolate as Mc}from"d3-geo";function _c(e){if(null==e)return 0;if("number"==typeof e&&Number.isFinite(e)&&e>=0&&.5>e)return e;throw new RangeError(`[semiotic] fitPadding must be a finite fraction in [0, 0.5); received ${e+""}.`)}var Pc=class e{constructor(e){this.updateResults=new Ac,this.scene=[],this.scales=null,this.version=0,this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customLayoutDiagnosticsWarned=new Set,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._customLayoutFailedThisBuild=!1,this._quadtree=null,this._maxPointRadius=0,this.projection=null,this.geoPath=null,this.baseScale=0,this.baseTranslate=[0,0],this.baseRotation=[0,0,0],this.currentZoom=1,this.cartogramLayout=null,this.areas=[],this.pointData=[],this.lineData=[],this.pointBuffer=null,this.streaming=!1,this.lastIngestTime=0,this.timestampBuffer=null,this.activeTransition=null,this.prevPositions=null,this._hasRenderedOnce=!1,this.config=function(e){return{...e,fitPadding:_c(e.fitPadding)}}(e)}currentTime(){return this.config.clock?.()??Me()}getConfiguredWindowSize(){const e=this.config.windowSize??500;if(!Number.isInteger(e)||1>e)throw Error("GeoPipelineStore windowSize must be a positive integer");return e}retainNewestLines(e=this.getConfiguredWindowSize()){this.lineData.length>e&&(this.lineData=this.lineData.slice(-e))}resizeStreamingWindow(e){if(this.pointBuffer){const t=this.pointBuffer.toArray(),o=this.timestampBuffer?.toArray()??[],n=t.slice(-e),i=o.slice(-n.length),r=this.currentTime();this.pointBuffer=new ut(e),this.timestampBuffer=new ut(e),n.forEach((e,t)=>{this.pointBuffer.push(e),this.timestampBuffer.push(i[t]??r)})}this.retainNewestLines(e)}updateConfig(e){const t=function(e){return"fitPadding"in e?{...e,fitPadding:_c(e.fitPadding)}:e}(e),o=this.config,n=this.getConfiguredWindowSize(),i=Object.keys(t).filter(e=>t[e]!==o[e]);this.config={...this.config,...t};const r=this.getConfiguredWindowSize(),s=this.streaming&&r!==n;s&&(this.resizeStreamingWindow(r),this.version++),"customLayout"in t&&!t.customLayout&&(this.lastCustomLayoutFailure=null),this.updateResults.recordConfig(i,{retainedDataChanged:s})}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setAreas(e){this.areas=e,this.updateResults.recordData("replace",e.length)}setAreasWithResult(e){return this.setAreas(e),this.updateResults.last}setPoints(e){this.pointData=e.slice(),this.pointBuffer=null,this.timestampBuffer=null,this.streaming=!1,this.updateResults.recordData("replace",e.length)}setPointsWithResult(e){return this.setPoints(e),this.updateResults.last}setLines(e){this.lineData=e.slice(),this.streaming&&this.retainNewestLines(),this.updateResults.recordData("replace",e.length)}setLinesWithResult(e){return this.setLines(e),this.updateResults.last}initStreaming(e){void 0!==e&&e!==this.config.windowSize&&(this.config={...this.config,windowSize:e});const t=this.getConfiguredWindowSize(),o=this.pointBuffer?this.pointBuffer.toArray():this.pointData,n=this.timestampBuffer?.toArray()??[],i=o.slice(-t),r=n.slice(-i.length),s=this.currentTime();this.pointBuffer=new ut(t),this.timestampBuffer=new ut(t),i.forEach((e,t)=>{this.pointBuffer.push(e),this.timestampBuffer.push(r[t]??s)}),this.pointData=[],this.retainNewestLines(t),this.streaming=!0}pushPoint(e){this.pointBuffer||this.initStreaming();const t=this.currentTime();Pe(this.pointBuffer,e,this.timestampBuffer,t),this.lastIngestTime=t,this.updateResults.recordData("ingest",1)}pushPointWithResult(e){return this.pushPoint(e),this.updateResults.last}pushMany(e){this.pointBuffer||this.initStreaming();const t=this.currentTime();for(const o of e)Pe(this.pointBuffer,o,this.timestampBuffer,t);this.lastIngestTime=t,this.updateResults.recordData("ingest",e.length)}pushManyWithResult(e){return this.pushMany(e),this.updateResults.last}pushLine(e){null!=e&&"object"==typeof e?(this.streaming||this.initStreaming(),this.lineData.push(e),this.retainNewestLines(),this.version++,this.updateResults.recordData("ingest",1)):this.updateResults.recordNoop("ingest")}pushManyLines(e){if(!Array.isArray(e)||0===e.length)return void this.updateResults.recordNoop("ingest");const t=e.filter(e=>null!=e&&"object"==typeof e);if(0!==t.length){this.streaming||this.initStreaming();for(const e of t)this.lineData.push(e);this.retainNewestLines(),this.version++,this.updateResults.recordData("ingest",t.length)}else this.updateResults.recordNoop("ingest")}removeLine(e){const{lineIdAccessor:t}=this.config;if(!t)throw Error("removeLine() requires lineIdAccessor to be configured");const o="function"==typeof t?t:e=>e[t],n=new Set(Array.isArray(e)?e:[e]),i=[];return this.lineData=this.lineData.filter(e=>!n.has(o(e)+"")||(i.push(e),!1)),i.length>0?(this.version++,this.updateResults.recordData("remove",i.length)):this.updateResults.recordNoop("remove"),i}getLines(){return this.lineData.slice()}removePoint(e){const{pointIdAccessor:t}=this.config;if(!t)throw Error("removePoint() requires pointIdAccessor to be configured");const o="function"==typeof t?t:e=>e[t],n=new Set(Array.isArray(e)?e:[e]);if(this.streaming&&this.pointBuffer){const e=e=>n.has(o(e)+"");G(this.pointBuffer,this.timestampBuffer,e);const t=this.pointBuffer.remove(e);return t.length>0?(this.version++,this.updateResults.recordData("remove",t.length)):this.updateResults.recordNoop("remove"),t}{const e=[];return this.pointData=this.pointData.filter(t=>!n.has(o(t)+"")||(e.push(t),!1)),e.length>0?(this.version++,this.updateResults.recordData("remove",e.length)):this.updateResults.recordNoop("remove"),e}}clear(){this.areas=[],this.pointData=[],this.lineData=[],this.pointBuffer=null,this.timestampBuffer=null,this.streaming=!1,this.scene=[],this.scales=null,this._hasRenderedOnce=!1,this.activeTransition=null,this.prevPositions=null,this._quadtree=null,this._maxPointRadius=0,this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,this._customLayoutFailedThisBuild=!1,this.version++,this.updateResults.recordData("clear")}restyleScene(e){const t=this._customRestyle;if(t){for(const o of this.scene){const n=this._baseStyles.get(o)??o.style,i=t(o,e);o.style=i?{...n,...i}:n}this.markStylePaintPending(),this.updateResults.recordRestyle(!0)}else this.updateResults.recordRestyle(!1)}computeScene(e){const{config:t}=this,o=this.projection,n=this.geoPath,i=this.scales,r=this.baseScale,s=[...this.baseTranslate],a=[...this.baseRotation],l=this.scene;this.projection=function(e){if(!e)return Zl();if("string"==typeof e){const t=oc[e];return t?t():("production"!==process.env.NODE_ENV&&console.warn(`GeoFrame: Unknown projection "${e}", falling back to equalEarth`),Zl())}if("object"==typeof e&&"type"in e){const t=oc[e.type],o=t?t():Zl();return e.rotate&&"rotate"in o&&o.rotate(e.rotate),e.center&&"center"in o&&o.center(e.center),o}return e}(t.projection),this.geoPath=ql(this.projection),this.fitProjection(e),this.geoPath=ql(this.projection);const c=this.projection;this.scales={projection:c,geoPath:this.geoPath,projectedPoint:(e,t)=>c([e,t]),invertedPoint:(e,t)=>c.invert?c.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const u=this.buildSceneNodes(e);if(this._customLayoutFailedThisBuild)!0===this.lastCustomLayoutFailure?.preservedLastGoodScene?(this.projection=o,this.geoPath=n,this.scales=i,this.baseScale=r,this.baseTranslate=s,this.baseRotation=a):(this.scene=[],this.rebuildQuadtree());else{if(this.scene=u,this.rebuildQuadtree(),t.projectionTransform&&this.applyCartogramTransform(t.projectionTransform,e),t.decay&&this.streaming&&this.applyDecay(),t.pulse&&this.streaming&&this.applyPulse(),t.transition&&!this._hasRenderedOnce&&this.scene.length>0&&t.introAnimation){const t=e.width/2,o=e.height/2,n=this.scene.filter(e=>"point"===e.type).map(e=>({...e,x:t,y:o}));n.length>0&&this.startTransition(n)}this._hasRenderedOnce=!0,t.transition&&l.length>0&&this.startTransition(l),this.version++}}fitProjection(e){const t=this.projection,o=this.config,n=[...this.areas],i=nc(o.xAccessor,"lon"),r=nc(o.yAccessor,"lat"),s=this.getPoints();if(s.length>0){const e=s.map(e=>[i(e),r(e)]);n.push({type:"Feature",properties:{},geometry:{type:"MultiPoint",coordinates:e}})}const a=ic(o.lineDataAccessor);for(const e of this.lineData){const t=a(e);if(t&&t.length>0){const e=t.map(e=>[i(e),r(e)]);n.push({type:"Feature",properties:{},geometry:{type:"LineString",coordinates:e}})}}if(0!==n.length){if(o.projectionExtent){const[[n,i],[r,s]]=o.projectionExtent;t.fitExtent([[0,0],[e.width,e.height]],{type:"Feature",properties:{},geometry:{type:"Polygon",coordinates:[[[n,i],[n,s],[r,s],[r,i],[n,i]]]}})}else if(t.clipAngle&&(t.clipAngle()??0)>0){const n=o.fitPadding??0,i=Math.min(e.width,e.height);t.scale(i/2-i*n),t.translate([e.width/2,e.height/2])}else{const i=o.fitPadding??0,r=e.width*i,s=e.height*i;t.fitExtent([[r,s],[e.width-r,e.height-s]],{type:"FeatureCollection",features:n})}this.baseScale=t.scale(),this.baseTranslate=t.translate(),this.baseRotation=t.rotate?.()??[0,0,0]}}applyZoomTransform(e,t){const o=this.projection;if(!o)return;const n=this.geoPath,i=this.scales,r=o.scale(),s=[...o.translate()],a=this.currentZoom;o.scale(this.baseScale*e.k),o.translate([this.baseTranslate[0]*e.k+e.x,this.baseTranslate[1]*e.k+e.y]),this.currentZoom=e.k,this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const l=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.scale(r),o.translate(s),this.currentZoom=a,this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=l,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}applyZoomScale(e,t){const o=this.projection;if(!o)return;const n=this.geoPath,i=this.scales,r=o.scale(),s=[...o.translate()],a=this.currentZoom;o.scale(this.baseScale*e),o.translate(this.baseTranslate),this.currentZoom=e,this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const l=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.scale(r),o.translate(s),this.currentZoom=a,this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=l,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}applyRotation(e,t){const o=this.projection;if(!o||!o.rotate)return;const n=this.geoPath,i=this.scales,r=[...o.rotate()];o.rotate(e),this.geoPath=ql(o),this.scales={projection:o,geoPath:this.geoPath,projectedPoint:(e,t)=>o([e,t]),invertedPoint:(e,t)=>o.invert?o.invert([e,t]):null},this._customLayoutFailedThisBuild=!1;const s=this.buildSceneNodes(t);this._customLayoutFailedThisBuild?this.lastCustomLayoutFailure?.preservedLastGoodScene?(o.rotate(r),this.geoPath=n,this.scales=i):(this.scene=[],this.rebuildQuadtree()):(this.scene=s,this.rebuildQuadtree(),this.config.projectionTransform&&this.applyCartogramTransform(this.config.projectionTransform,t),this.version++)}setRotation(e){const t=this.projection;t&&t.rotate&&t.rotate(e)}hasProjection(){return null!=this.projection}getRotation(){return this.projection?.rotate?.()??this.baseRotation}getBaseProjectionState(){return{scale:this.baseScale,translate:[...this.baseTranslate]}}getPoints(){return this.streaming&&this.pointBuffer?this.pointBuffer.toArray():this.pointData}rebuildQuadtree(){let t=0,o=0;for(const e of this.scene)"point"===e.type&&!1!==e.interactive&&(o++,e.r>t&&(t=e.r));if(this._maxPointRadius=t,e.QUADTREE_THRESHOLD>=o)return void(this._quadtree=null);const n=Array(o);let i=0;for(const e of this.scene)"point"===e.type&&!1!==e.interactive&&(n[i++]=e);this._quadtree=Ul().x(e=>e.x).y(e=>e.y).addAll(n)}get quadtree(){return this._quadtree}get maxPointRadius(){return this._maxPointRadius}buildSceneNodes(e){this._customLayoutFailedThisBuild=!1;const{config:t}=this,o=this.projection,n=this.geoPath;if(t.customLayout&&this.scales){const o=t.layoutMargin??{top:0,right:0,bottom:0,left:0},n=Ne(t.colorScheme,t.themeCategorical,F),i={areas:this.areas.slice(),points:this.getPoints().slice(),lines:this.lineData.slice(),scales:this.scales,dimensions:{width:e.width,height:e.height,margin:o,plot:{x:0,y:0,width:e.width,height:e.height}},theme:{semantic:t.themeSemantic??{},categorical:[...n]},resolveColor:V(n,t.colorScheme),config:t.layoutConfig??{},selection:t.layoutSelection??null};let r;try{r=t.customLayout(i)}catch(e){const o=null!==this.lastCustomLayoutResult,n=ee("geo",e,o,this.version);this.lastCustomLayoutFailure=n,this._customLayoutFailedThisBuild=!0,"production"!==process.env.NODE_ENV&&console.error("[semiotic] geo customLayout threw:",e);try{t.onLayoutError?.(n)}catch(e){"production"!==process.env.NODE_ENV&&console.error("[semiotic] onLayoutError threw:",e)}return o?this.scene:(this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,[])}const s=r.nodes??[];if(this.customLayoutOverlays=r.overlays??null,this.lastCustomLayoutResult=r,this.lastCustomLayoutFailure=null,this._customRestyle=r.restyle,this.hasCustomRestyle=!!r.restyle,this._baseStyles=new WeakMap,this.hasCustomRestyle){for(const e of s)this._baseStyles.set(e,e.style);this.restyleScene(t.layoutSelection??null)}return st({label:"geo customLayout",nodes:s,overlays:this.customLayoutOverlays,warned:this._customLayoutDiagnosticsWarned}),s}return this.customLayoutOverlays=null,this.lastCustomLayoutResult=null,this.lastCustomLayoutFailure=null,this._customRestyle=void 0,this.hasCustomRestyle=!1,this._baseStyles=new WeakMap,function({config:e,projection:t,path:o,areas:n,points:i,lines:r,layout:s}){const a=nc(e.xAccessor,"lon"),l=nc(e.yAccessor,"lat"),c=[],u=function(e){return{fill:e.themeSemantic?.surface||"#e0e0e0",stroke:e.themeSemantic?.border||"#999",strokeWidth:.5,fillOpacity:1}}(e),d=function(e){return{stroke:e.themeSemantic?.primary||"#4e79a7",strokeWidth:1.5,fill:"none"}}(e),h=function(e){return{fill:e.themeSemantic?.primary||"#4e79a7",r:4,fillOpacity:.8}}(e);if(e.graticule){const t=!0===e.graticule?{}:e.graticule,n=kc();t.step&&n.step(t.step);const i=o(n())||"";i&&c.push({type:"geoarea",pathData:i,centroid:[s.width/2,s.height/2],bounds:[[0,0],[s.width,s.height]],screenArea:0,style:{fill:"none",stroke:t.stroke||"#e0e0e0",strokeWidth:t.strokeWidth||.5,strokeDasharray:t.strokeDasharray||"2,2"},datum:null,interactive:!1})}for(const t of n){const n=o(t);if(!n)continue;const i=o.centroid(t),r=o.bounds(t),s=o.area(t);c.push({type:"geoarea",pathData:n,centroid:i,bounds:r,screenArea:s,style:rc(e.areaStyle,t,u),datum:t,interactive:!0})}const p=ic(e.lineDataAccessor);for(const o of r){const n=p(o);if(!n||2>n.length)continue;let i=[];if("geo"===e.lineType){const e=Array(n.length);for(let t=0;n.length>t;t++)e[t]=[a(n[t]),l(n[t])];for(let o=0;e.length-1>o;o++){const n=e[o],r=e[o+1],s=Sc(n,r)||0,a=Math.max(2,Math.ceil(s/(Math.PI/180))),l=Mc(n,r);for(let e=0;a>=e;e++){if(o>0&&0===e)continue;const n=t(l(e/a));null!=n&&i.push(n)}}}else for(let e=0;n.length>e;e++){const o=n[e],r=t([a(o),l(o)]);null!=r&&i.push(r)}if(2>i.length)continue;const r=rc(e.lineStyle,o,d),u="number"==typeof r.strokeWidth?r.strokeWidth:1;2!==n.length||2>i.length||"arc"!==e.flowStyle?2!==n.length||2>i.length||"offset"!==e.flowStyle||(i="geo"===e.lineType?lc(i,u):cc(i[0],i[i.length-1],0,0,u)):i=ac(i[0],i[i.length-1]);const h=sc(i,s.width);if(h.length>1)for(const e of h)2>e.length||c.push({type:"line",path:e,style:{...r,_edgeFade:!0},datum:o});else c.push({type:"line",path:2>i.length&&h[0]||i,style:r,datum:o})}const g=e.pointIdAccessor?"function"==typeof e.pointIdAccessor?e.pointIdAccessor:t=>t[e.pointIdAccessor]:null,m=t.clipAngle?t.clipAngle()??0:0,f=m>0?m*Math.PI/180:null,y=t.rotate?t.rotate():[0,0,0],b="function"==typeof t.center?t.center():[0,0],x=[(b[0]??0)-y[0],(b[1]??0)-y[1]];for(const o of i){const n=a(o),i=l(o);if(null!=f&&Sc([n,i],x)>f)continue;const r=t([n,i]);if(!r)continue;const s=e.pointStyle?e.pointStyle(o):{...h},u={type:"point",x:r[0],y:r[1],r:s.r||4,style:s,datum:o,pointId:g?g(o)+"":void 0};c.push(u)}return c}({config:t,projection:o,path:n,areas:this.areas,points:this.getPoints(),lines:this.lineData,layout:e})}applyCartogramTransform(e,t){const o=function(e,t,o,n){const i=e.filter(e=>"point"===e.type);if(2>i.length)return null;const r=t.strength??1,s=Number.isFinite(r)?Math.max(0,Math.min(1,r)):1,a="strip"===t.layout?"strip":"radial";if("radial"===a&&0===s)return null;const l=t.centerAccessor?"function"==typeof t.centerAccessor?t.centerAccessor:e=>e[t.centerAccessor]:e=>e.id,c="function"==typeof t.costAccessor?t.costAccessor:e=>e[t.costAccessor],u=i.find(e=>e.datum&&l(e.datum)+""==t.center+"");if(!u)return"production"!==process.env.NODE_ENV&&console.warn(`GeoFrame: Distance cartogram center "${t.center}" not found in point data`),null;const d=i.map(e=>e.datum?Number(c(e.datum)):NaN).filter(e=>isFinite(e)&&e>=0),h=zt(d,1);n>0&&"production"!==process.env.NODE_ENV&&console.warn("GeoFrame: Distance cartogram does not support area rendering. Areas will be ignored. Remove areas or set projectionTransform to null to render them.");for(let t=e.length-1;t>=0;t--){const o=e[t];"geoarea"===o.type&&o.interactive&&e.splice(t,1)}const p="strip"===a?function(e,t,o,n,i){const r=Math.max(3,Math.min(8,.35*i.height)),s=Math.max(1,i.width-2*r),a=i.height/2,l=uc().domain([0,n]).range([0,s]);t.x=r,t.y=a;const c=[];for(const i of e){if(i===t)continue;if(!i.datum){i.x=r,i.y=a;continue}const e=Number(o(i.datum)),s=r+(isFinite(e)&&e>=0&&n>0?l(e):0);i.x=s,i.y=a,c.push({node:i,x:s})}c.sort((e,t)=>e.x-t.x);const u=Math.max(0,Math.min(i.height/2-1,6));let d=0;for(;c.length>d;){let e=d+1;for(;c.length>e&&3>Math.abs(c[e].x-c[d].x);)e++;const t=e-d;if(t>1&&u>0)for(let e=0;t>e;e++)c[d+e].node.y=a+(e-(t-1)/2)*Math.min(2.5,2*u/Math.max(1,t-1));d=e}return{cx:r,cy:a,maxCost:n,availableRadius:s,layout:"strip"}}(i,u,c,h,o):function(e,t,o,n,i,r){const s=t.x,a=t.y,l=r.width/2,c=r.height/2,u=Math.min(r.width,r.height)/2,d=uc().domain([0,n]).range([0,u]);for(const r of e){if(r===t)continue;if(!r.datum)continue;const e=r.x,u=r.y,h=Math.atan2(u-a,e-s),p=Math.hypot(e-s,u-a),g=Number(o(r.datum)),m=isFinite(g)&&g>=0?n>0?d(g):0:p,f=l+Math.cos(h)*m,y=c+Math.sin(h)*m;r.x=e+(f-e)*i,r.y=u+(y-u)*i}return t.x=s+(l-s)*i,t.y=a+(c-a)*i,{cx:t.x,cy:t.y,maxCost:n,availableRadius:u,layout:"radial"}}(i,u,c,h,s,o),g=e.filter(e=>"line"===e.type);if(g.length>0){const e=new Map;for(const t of i)null!=t.pointId&&e.set(t.pointId+"",[t.x,t.y]);for(const o of g){const n=o.datum?.source,i=o.datum?.target;if(null!=n&&null!=i){const r=e.get(n+""),s=e.get(i+"");if(r&&s)if("fractional"===t.lineMode&&o.path.length>2){const e=o.path[0],t=o.path[o.path.length-1],n=[r[0]-e[0],r[1]-e[1]],i=[s[0]-t[0],s[1]-t[1]],a=[0];for(let e=1;o.path.length>e;e++)a.push(a[e-1]+Math.hypot(o.path[e][0]-o.path[e-1][0],o.path[e][1]-o.path[e-1][1]));const l=a[a.length-1];o.path=o.path.map((e,t)=>{const r=l>0?a[t]/l:t/(o.path.length-1);return[e[0]+n[0]*(1-r)+i[0]*r,e[1]+n[1]*(1-r)+i[1]*r]})}else o.path=[r,s]}}}return p}(this.scene,e,t,this.areas.length);o&&(this.cartogramLayout=o)}applyDecay(){const e=this.config.decay;if(!e||!this.pointBuffer)return;const t=this.pointBuffer.size;if(0===t)return;const o=this.scene.filter(e=>"point"===e.type);for(let n=0;o.length>n;n++){const i=q(e,n,t);o[n]._decayOpacity=i,o[n].style={...o[n].style,opacity:i}}}applyPulse(e=this.currentTime()){const t=this.config.pulse;if(!t||!this.timestampBuffer)return!1;const o=this.scene.filter(e=>"point"===e.type),n=this.timestampBuffer.toArray(),i=t.color||"rgba(255,255,255,0.6)",r=t.glowRadius??4;let s=!1;for(let a=0;o.length>a&&n.length>a;a++){const l=Q(t,n[a],e);s=Ue(o[a],l,i,r)||s}return s}refreshPulse(e){return!0!==this.lastCustomLayoutFailure?.preservedLastGoodScene&&this.applyPulse(e)}hasActivePulsesAt(e){return!!this.config.pulse&&he(this.config.pulse,this.timestampBuffer,e)}get hasActivePulses(){return this.hasActivePulsesAt(this.currentTime())}startTransition(e){const t=this.config.transition?.duration??300;if(0>=t)return;const o=new Map;for(const t of e)"point"===t.type&&t.pointId&&o.set(t.pointId,[t.x,t.y]);const n=this.scene.filter(e=>"point"===e.type);let i=!1;for(const e of n)if(e.pointId){const t=o.get(e.pointId);t&&(e._targetX=e.x,e._targetY=e.y,e.x=t[0],e.y=t[1],(Math.abs(t[0]-e._targetX)>.5||Math.abs(t[1]-e._targetY)>.5)&&(i=!0))}for(const e of n)e.pointId&&!o.has(e.pointId)&&(e._targetOpacity=e.style?.opacity??e.style?.fillOpacity??1,e.style={...e.style,opacity:0},i=!0);i&&(this.activeTransition={startTime:this.currentTime(),duration:t})}cancelIntroAnimation(){this.activeTransition=null;for(const e of this.scene)"point"===e.type&&(null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity},e._targetOpacity=void 0),null!=e._targetX&&(e.x=e._targetX,e.y=e._targetY,e._targetX=void 0,e._targetY=void 0))}advanceTransition(e){if(!this.activeTransition)return!1;const t=Z(e,this.activeTransition),o=U(t),n=this.scene.filter(e=>"point"===e.type);for(const e of n){if(null!=e._targetX&&null!=e._targetY){const t=e.y;e.x=be(e.x,e._targetX,o),e.y=be(t,e._targetY,o)}null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity*o})}if(t>=1){for(const e of n)null!=e._targetX&&(e.x=e._targetX,e.y=e._targetY,e._targetX=void 0,e._targetY=void 0),null!=e._targetOpacity&&(e.style={...e.style,opacity:e._targetOpacity},e._targetOpacity=void 0);return this.activeTransition=null,!1}return!0}};Pc.QUADTREE_THRESHOLD=500;var Tc=Pc;j(Tc);import{Fragment as Lc,jsxs as Rc}from"react/jsx-runtime";function Ic(e,t){const o=Kt(e.theme),n=e.size||[e.width||600,e.height||400],i=ze({top:10,right:10,bottom:10,left:10,...e.margin},e.title),r=pe(e.title),s=Array.isArray(e.areas)?ie(e.areas):e.areas,a=ie(e.points),l=ie(e.lines),c=e.showLegend?(()=>{const t="string"==typeof(o=e.colorBy)||"function"==typeof o?e.colorBy:void 0;var o;return Ea(a.length>0?a:Array.isArray(s)&&s.length>0?"string"==typeof t?s.map(e=>({...e.properties||{},...e})):s:[],t)})():[];ol(i,{props:e,categories:c,theme:o,size:n,hasTitle:r});const u=n[0]-(i.left??0)-(i.right??0),d=n[1]-(i.top??0)-(i.bottom??0),h={projection:e.projection||"equalEarth",xAccessor:e.xAccessor,yAccessor:e.yAccessor,lineDataAccessor:e.lineDataAccessor,pointIdAccessor:e.pointIdAccessor,lineType:e.lineType,areaStyle:e.areaStyle,pointStyle:e.pointStyle,lineStyle:e.lineStyle,graticule:e.graticule,fitPadding:e.fitPadding,projectionTransform:e.projectionTransform,customLayout:e.customLayout,layoutConfig:e.layoutConfig,layoutMargin:i,themeCategorical:o.colors.categorical,themeSemantic:Dt(o)},p=new Tc(h);if(s){if("string"==typeof s)throw Error(`Geo SSR requires pre-resolved GeoJSON features. Reference string "${s}" cannot be resolved synchronously. Use \`const features = await resolveReferenceGeography('${s}')\` before calling renderGeoToStaticSVG.`);p.setAreas(s)}e.points&&p.setPoints(a),e.lines&&p.setLines(l),p.computeScene({width:u,height:d});const g=Ie({nodes:p.scene,renderMode:e.renderMode,fallback:(e,t)=>ae(e,t)});if(t&&(t.evidence=Sa({frameType:"geo",width:n[0],height:n[1],marks:g.map(e=>e.node),title:e.title,description:e.description,annotations:e.annotations,legendItems:c.length>0?c.length:void 0,margin:i})),0===g.length){const t=e.backgroundGraphics||e.foregroundGraphics||e.annotations||p.customLayoutOverlays?Rc(Lc,{children:[e.backgroundGraphics,e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{geoProjection:p.scales?.projectedPoint?([e,t])=>p.scales.projectedPoint(e,t):void 0},layout:{width:u,height:d},theme:o,idPrefix:e._idPrefix}):null,e.foregroundGraphics,p.customLayoutOverlays]}):null;return Xl.renderToStaticMarkup(rl(t,{width:n[0],height:n[1],className:"stream-geo-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left??0},${i.top??0})`,innerWidth:u,innerHeight:d,idPrefix:e._idPrefix}))}const m=g.map(e=>e.element),f=e.annotations?Ga({annotations:e.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations,svgAnnotationRules:e.svgAnnotationRules,scales:{geoProjection:p.scales?.projectedPoint?([e,t])=>p.scales.projectedPoint(e,t):void 0},layout:{width:u,height:d},theme:o,idPrefix:e._idPrefix}):null,y=nl({props:e,categories:c,theme:o,size:n,margin:i,hasTitle:r});return Xl.renderToStaticMarkup(rl(Rc(Lc,{children:[e.backgroundGraphics,m,f,e.foregroundGraphics,p.customLayoutOverlays]}),{width:n[0],height:n[1],className:"stream-geo-frame"+(e.className?" "+e.className:""),title:e.title,description:e.description,background:e.background,theme:o,innerTransform:`translate(${i.left??0},${i.top??0})`,innerWidth:u,innerHeight:d,legend:y,idPrefix:e._idPrefix}))}import*as Cc from"react-dom/server";function zc(e=[]){return e.map(e=>({id:e.id,label:e.label,count:e.count,...null!=e.secondary?{secondary:e.secondary}:{},...e.secondaryLabel?{secondaryLabel:e.secondaryLabel}:{},...null!=e.observed?{observed:e.observed}:{}}))}var Fc={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function Oc(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if(null!=e&&""!==e)return e+""}return e.id}function Bc(e,t){const o="function"==typeof t?t(e):t;return{...Fc,...o??{}}}function Nc(e,t={}){return e.map(e=>function(e,t={}){const o=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),n={label:t.getBodyLabel?.(e)??Oc(e)},i={style:Bc(e,t.bodyStyle),datum:o,accessibleDatum:o,accessibility:n,_transitionKey:e.id};return"aabb"===e.shape.type?{type:"rect",x:e.x-e.shape.width/2,y:e.y-e.shape.height/2,w:e.shape.width,h:e.shape.height,...i}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...i}}(e,t))}import{jsx as Ec,jsxs as jc}from"react/jsx-runtime";var $c={top:0,right:0,bottom:0,left:0};function Dc(e,t,o){return"function"==typeof e?e({size:t,margin:o}):e}function Wc(e,t){const o=e.size??[e.width??600,e.height??400],n=new d(e.config);Array.isArray(e.initialSpawns)&&e.initialSpawns.length>0&&n.enqueue(e.initialSpawns.map(e=>({...e,spawnAt:void 0})));const i=function(e,t={}){const{width:o=640,height:n=360,title:i,description:r,background:s,backgroundGraphics:a,className:l,foregroundGraphics:c,idPrefix:u="physics",margin:d,renderBodySVG:h,...p}=t,g=function(e,t={}){const o=e.settle(t.maxSteps),n=e.readBodies(),i=e.snapshot(),r=Nc(n,t),s=function(e,t={}){const o=t.bodies??function(e){return e.world.bodies.map(e=>({id:e.id,x:e.x,y:e.y,prevX:e.prevX,prevY:e.prevY,vx:e.vx,vy:e.vy,angle:e.angle,mass:e.mass,shape:{...e.shape},sleeping:e.sleeping,datum:e.datum}))}(e),n=o.filter(e=>e.sleeping).length,i=e.queue.length,r=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===i&&n===o.length,a=[];i>0&&a.push("PHYSICS_QUEUE_UNDRAINED");const l=null!=t.charge&&Number.isFinite(t.charge)?function(e,t,o,n){const i=e-(t+o+n);return{charge:e,live:t,queued:o,sedimented:n,unaccounted:i,balanced:0===i}}(t.charge,o.length,i,r):void 0;return l&&!l.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:o.length,sleepingCount:n,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:zc(t.projectionRows),queuedCount:i,sedimentedCount:r,...l?{ledger:l}:{},warnings:a}}(i,{bodies:n,projectionRows:t.projectionRows,stepsRun:o,charge:t.charge});return{snapshot:i,bodies:n,sceneNodes:r,evidence:s,stepsRun:o}}(e,p),m={...$c,...d},f=[o,n],y=Dc(a,f,m),b=Dc(c,f,m),x=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(u),v=i?x+"-title":void 0,w=r?x+"-desc":void 0,A=[v,w].filter(Boolean).join(" ")||void 0;return{svg:Cc.renderToStaticMarkup(jc("svg",{xmlns:"http://www.w3.org/2000/svg",className:l??"stream-physics-frame",width:o,height:n,viewBox:`0 0 ${o} ${n}`,role:"img","aria-labelledby":A,children:[i&&Ec("title",{id:v,children:i}),r&&Ec("desc",{id:w,children:r}),!a&&s&&"transparent"!==s?Ec("rect",{x:0,y:0,width:o,height:n,fill:s}):null,y,Ec("g",{id:x+"-data-area",children:g.sceneNodes.map((e,t)=>{const o=g.bodies[t];return(o&&h?h(o,e.style??{},t,x):void 0)??at(e,t,x)})}),b]})),scene:g,evidence:g.evidence}}(n,{...e,width:o[0],height:o[1],charge:e.charge,idPrefix:e.idPrefix??e._idPrefix??"physics"});return t&&(t.evidence=Sa({frameType:"physics",width:o[0],height:o[1],marks:i.scene.sceneNodes,title:e.title,description:e.description,annotations:[],extraWarnings:[...0===i.scene.sceneNodes.length?["PHYSICS_EMPTY_SCENE"]:[],...i.scene.evidence.warnings]})),i.svg}import*as Yc from"react-dom/server";import{jsx as Vc,jsxs as Hc}from"react/jsx-runtime";var Gc={tile:{width:280,height:184,padding:16,labelSize:13,captionSize:11,valueSize:40,detailSize:13,align:"start",border:!0,showHeader:!0,showDetail:!0},presentation:{width:540,height:320,padding:32,labelSize:18,captionSize:14,valueSize:96,detailSize:18,align:"center",border:!0,showHeader:!0,showDetail:!0},inline:{width:240,height:64,padding:8,labelSize:0,captionSize:0,valueSize:28,detailSize:13,align:"start",border:!1,showHeader:!1,showDetail:!0},thumbnail:{width:96,height:56,padding:6,labelSize:0,captionSize:0,valueSize:22,detailSize:0,align:"center",border:!1,showHeader:!1,showDetail:!1}};function Xc(e,t){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:t}var qc={BigNumber:function(e,t){const o="presentation"===e.mode||"inline"===e.mode||"thumbnail"===e.mode?e.mode:"tile",n=Gc[o],i=Xc(e.width,n.width),r=Xc(e.height,n.height),s="number"==typeof e.padding&&Number.isFinite(e.padding)?Math.max(0,e.padding):n.padding,a="center"===e.align||"end"===e.align||"start"===e.align?e.align:n.align,l="center"===a?"middle":"end"===a?"end":"start",c="center"===a?i/2:"end"===a?i-s:s,u=Kt(e.theme),d="number"==typeof e.value&&Number.isFinite(e.value)?e.value:void 0,h=function(e,t={}){if("function"==typeof e)return e;const o=t.locale??"en-US";if("currency"===e){const e=t.precision??2,n=new Intl.NumberFormat(o,{style:"currency",currency:t.currency??"USD",maximumFractionDigits:e,minimumFractionDigits:e});return e=>n.format(e)}if("percent"===e){const e=new Intl.NumberFormat(o,{style:"percent",maximumFractionDigits:t.precision??1,minimumFractionDigits:0});return t=>e.format(t)}if("compact"===e){const e=new Intl.NumberFormat(o,{notation:"compact",maximumFractionDigits:t.precision??1,minimumFractionDigits:0});return t=>e.format(t)}if("duration"===e)return e=>function(e){if(!Number.isFinite(e))return e+"";const t=0>e?"-":"",o=Math.abs(e);if(1e3>o)return`${t}${Math.round(o)}ms`;const n=o/1e3;if(60>n)return`${t}${i=n,Math.round(100*i)/100+""}s`;var i;const r=n/60;if(60>r){const e=Math.floor(r),o=Math.round(n-60*e);return 0===o?`${t}${e}m`:`${t}${e}m ${o}s`}const s=r/60;if(24>s){const e=Math.floor(s),o=Math.round(r-60*e);return 0===o?`${t}${e}h`:`${t}${e}h ${o}m`}const a=Math.floor(s/24),l=Math.round(s-24*a);return 0===l?`${t}${a}d`:`${t}${a}d ${l}h`}(e);const n=new Intl.NumberFormat(o,{notation:t.notation??"standard",maximumFractionDigits:t.precision??0,minimumFractionDigits:0});return e=>n.format(e)}("string"==typeof e.format||"function"==typeof e.format?e.format:"number",{locale:"string"==typeof e.locale?e.locale:void 0,currency:"string"==typeof e.currency?e.currency:void 0,precision:"number"==typeof e.precision?e.precision:void 0}),p=void 0===d?"No value":(g=h(d),`${("string"==typeof e.prefix?e.prefix:void 0)??""}${g}${("string"==typeof e.suffix?e.suffix:void 0)??""}`);var g;const m=void 0===d?void 0:function(e,t){if(!t||0===t.length)return null;if(!Number.isFinite(e))return null;const o=t.filter(e=>Number.isFinite(e.at)||e.at===-1/0).slice().sort((e,t)=>e.at-t.at);let n=null;for(const t of o){if(t.at>e)break;n=t}return n}(d,e.thresholds),f="string"==typeof e.color?e.color:function(e,t,o){return t||("success"===e?o.colors.success??"#2ca02c":"warning"===e?o.colors.warning??"#b26a00":"danger"===e?o.colors.danger??"#d62728":"info"===e?o.colors.info??o.colors.primary:o.colors.text)}(m?.level??"neutral",m?.color,u),y="string"==typeof e.label?e.label:void 0,b="string"==typeof e.caption?e.caption:void 0,x="string"==typeof e.unit?e.unit:void 0,v=void 0===d?void 0:function(e,t,o){const n=e.comparison&&"object"==typeof e.comparison?e.comparison:void 0,i=n&&"number"==typeof n.value&&Number.isFinite(n.value)?n.value:void 0,r=("number"==typeof e.delta&&Number.isFinite(e.delta)?e.delta:void 0)??(void 0===i?void 0:t-i);if(void 0===r)return;const s=function(e,t){return Number.isFinite(e)?0===e?t(0):`${e>0?"+":"−"}${t(Math.abs(e))}`:""}(r,o);return`${s}${n&&"string"==typeof n.label?" "+n.label:""}`}(e,d,h),w=void 0===d?void 0:function(e,t,o){const n=e.target&&"object"==typeof e.target?e.target:void 0;if(!n||"number"!=typeof n.value||!Number.isFinite(n.value))return;const i="string"==typeof n.label?" "+n.label:"";return 0===n.value?`target ${o(n.value)}${i}`:`${new Intl.NumberFormat("string"==typeof e.locale?e.locale:"en-US",{style:"percent",maximumFractionDigits:0}).format(t/n.value)} of ${o(n.value)}${i}`}(e,d,h),A=[v,w,m?.label].filter(Boolean).join(" · "),S="string"==typeof e.description&&e.description||[y,p,x,A].filter(Boolean).join(", "),k="string"==typeof e.background?e.background:u.colors.surface??u.colors.background,M="string"==typeof e.borderColor?e.borderColor:u.colors.border,_=s+n.labelSize,P=_+n.captionSize+4,T="presentation"===o?r/2+.32*n.valueSize:"thumbnail"===o?r/2+.34*n.valueSize:Math.min(r-s-(A?26:4),(n.showHeader&&(y||b)?b?P+10:_+14:s)+n.valueSize),L=c+("start"===l?Math.max(n.valueSize,p.length*n.valueSize*.55):0),R=Yc.renderToStaticMarkup(Hc("svg",{xmlns:"http://www.w3.org/2000/svg",width:i,height:r,viewBox:`0 0 ${i} ${r}`,role:"img","aria-label":S,"data-semiotic-component":"BigNumber",children:[Vc("title",{children:y??p}),"string"==typeof e.description&&Vc("desc",{children:e.description}),Vc("rect",{x:n.border?.5:0,y:n.border?.5:0,width:n.border?i-1:i,height:n.border?r-1:r,rx:n.border?8:0,fill:k,stroke:n.border?M:"none"}),n.showHeader&&y&&Vc("text",{x:c,y:_,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.labelSize,fontWeight:600,fill:u.colors.text,children:y}),n.showHeader&&b&&Vc("text",{x:c,y:P,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.captionSize,fill:u.colors.textSecondary,children:b}),Vc("text",{x:c,y:T,textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.valueSize,fontWeight:600,fontVariant:"tabular-nums",fill:void 0===d?u.colors.textSecondary:f,"data-mark-type":"value",children:p}),x&&void 0!==d&&"start"===l&&Vc("text",{x:L+6,y:T,textAnchor:"start",fontFamily:u.typography.fontFamily,fontSize:Math.max(11,Math.round(.32*n.valueSize)),fontWeight:500,fill:u.colors.textSecondary,children:x}),n.showDetail&&A&&Vc("text",{x:c,y:Math.min(r-s,T+n.detailSize+10),textAnchor:l,fontFamily:u.typography.fontFamily,fontSize:n.detailSize,fill:u.colors.textSecondary,children:A})]}));return t&&(t.evidence=Sa({frameType:"value",width:i,height:r,marks:void 0===d?[]:[{type:"value"}],title:y,description:S})),R}};function Uc(e,t,o){return qc[e](t,o)}import{Fragment as Qc,jsx as Zc,jsxs as Kc}from"react/jsx-runtime";function Jc(e,t){switch(e){case"xy":return cl(t);case"ordinal":return $l(t);case"network":return Gl(t);case"geo":return Ic(t);case"physics":return Wc(t);default:throw Error(`Unknown frame type: ${e}. Must be "xy", "ordinal", "network", "geo", or "physics".`)}}function eu(e){return cl(e)}function tu(e){return $l(e)}function ou(e){return Gl(e)}function nu(e){return Ic(e)}var iu=["showAxes","axes","axisExtent","xLabel","yLabel","yLabelRight","categoryLabel","valueLabel","xFormat","yFormat","categoryFormat","valueFormat","tickFormatTime","tickFormatValue","xScaleType","yScaleType","xExtent","yExtent","rExtent","oExtent","extentPadding","scalePadding","sizeRange","innerRadius","centerContent","curve","gradientFill","lineGradient","lineStyle","pointStyle","areaStyle","barStyle","waterfallStyle","swarmStyle","pieceStyle","summaryStyle","nodeStyle","edgeStyle","connectorStyle","backgroundGraphics","foregroundGraphics","svgPreRenderers","svgAnnotationRules","barColors","legend","legendLayout","autoPlaceAnnotations"],ru=["width","height","showAxes","showGrid","enableHover","showLegend","showLabels","showCategoryTicks","orientation","title","description","summary","accessibleTable","xLabel","yLabel","categoryLabel","valueLabel","linkedHover","mobileInteraction","mobileSemantics","responsiveRules"];function su(e,t){const o={};for(const n of t)void 0!==e[n]&&(o[n]=e[n]);return o}function au(e,t,o){return cu(e,t).svg}function lu(e,t,o){const n={},{svg:i,frameType:r}=cu(e,t,0,n),s=n.evidence??Sa({frameType:r,width:"number"==typeof t.width?t.width:600,height:"number"==typeof t.height?t.height:400,marks:[],title:"string"==typeof t.title?t.title:void 0,description:"string"==typeof t.description?t.description:void 0,annotations:t.annotations,extraWarnings:["NO_EVIDENCE"]});return s.component=e,{svg:i,evidence:s}}function cu(e,t,o,n){if(e in qc)return{svg:Uc(e,t,n),frameType:"value"};const i=va[e];if(!i)throw Error(`Unknown chart component: "${e}". See CLAUDE.md for supported chart types.`);const r=i.layout?.mode??(ge(t.mode)?t.mode:void 0),s=Be(r,{...i.layout?.modeDefaults,...su(t,ru)},i.layout?.primarySize),{data:a,theme:l,background:c,className:u,annotations:d,margin:h,colorScheme:p,colorBy:g,legendPosition:m,...f}=t,{width:y,height:b}=s,x=[y,b],v=f.frameProps||{},w=i.layout?.margin,A="function"==typeof w?w(t,s):w??s.marginDefaults,S=void 0!==h?h:v.margin,k=Yt(S),M="number"==typeof S?{top:S,right:S,bottom:S,left:S}:{...A,...k},_=su(f,iu),P=e=>v[e]??s[e],T={...v,..._,theme:l,title:s.title,description:s.description,showAxes:P("showAxes"),showLegend:P("showLegend"),showLabels:P("showLabels"),showGrid:P("showGrid"),xLabel:P("xLabel"),yLabel:P("yLabel"),categoryLabel:P("categoryLabel"),valueLabel:P("valueLabel"),background:c,className:u,annotations:d,size:x,margin:M,__explicitMargin:S,__autoLegendMargin:!0,...void 0!==p&&{colorScheme:p},...void 0!==m&&{legendPosition:m},_idPrefix:f._idPrefix},L=i.buildProps(a,g,p,T,f);let R;switch(i.frameType){case"xy":R=cl(L,n);break;case"ordinal":R=$l(L,n);break;case"network":R=Gl(L,n);break;case"geo":R=Ic(L,n);break;case"physics":R=Wc(L,n)}const I=i.renderOverlay?.(L,{theme:Kt(l)});if(null!=I){const e=Vt.renderToStaticMarkup(Zc(Qc,{children:I}));R=R.replace("</svg>",e+"</svg>")}return{svg:R,frameType:i.frameType}}function uu(e,t={}){const{title:o,subtitle:n,theme:i,width:r=1200,height:s,layout:a={},background:l}=t,c=Jt(Kt(i)),u=a.columns||2,d=a.gap??16;let h=0;o&&(h+=30),n&&(h+=20),h>0&&(h+=10);const p=Math.floor((r-d-d*(u-1))/u),g=[];let m=0,f=h+d,y=0;for(const t of e){const e=Math.min(t.colSpan||1,u),o=t.props.height||300;m+e>u&&(f+=y+d,m=0,y=0),g.push({chart:t,x:d/2+m*(p+d),y:f,w:p*e+d*(e-1),h:o}),y=Math.max(y,o),m+=e}const b=s||f+y+d,x=g.map((e,t)=>{const{chart:o,x:n,y:r,w:s,h:a}=e,l={...o.props,width:s,height:a,theme:i,_idPrefix:"chart-"+t};let c;return c=o.component?au(o.component,l):o.frameType?Jc(o.frameType,l):`<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${a}"></svg>`,Zc("g",{transform:`translate(${n},${r})`,children:Zc("foreignObject",{width:s,height:a,children:Zc("div",{xmlns:"http://www.w3.org/1999/xhtml",dangerouslySetInnerHTML:{__html:c}})})},"dashboard-chart-"+t)});return Vt.renderToStaticMarkup(Kc("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:b,role:"img","aria-label":o||"Dashboard",style:{fontFamily:c.fontFamily},children:[o&&Zc("title",{children:o}),l&&Zc("rect",{x:0,y:0,width:r,height:b,fill:l}),o&&Zc("text",{x:r/2,y:24,textAnchor:"middle",fontSize:c.titleSize+4,fontWeight:"bold",fill:c.text,fontFamily:c.fontFamily,children:o}),n&&Zc("text",{x:r/2,y:o?46:20,textAnchor:"middle",fontSize:c.labelSize,fill:c.textSecondary,fontFamily:c.fontFamily,children:n}),x]}))}import*as du from"react-dom/server";import{Fragment as hu,jsx as pu,jsxs as gu}from"react/jsx-runtime";function mu(e,t,o,n={}){const{stepSize:i,windowSize:r,frameCount:s,xExtent:a,yExtent:l,transitionFrames:c=4,fps:u=12,easing:d="ease-out",decay:h}=n,p=o.width||600,g=o.height||400,m=Kt(o.theme),f={...o,...a&&{xExtent:a},...l&&{yExtent:l}};if(!t||0===t.length)return[];const y=i||Math.max(1,Math.ceil(t.length/(s||Math.min(60,Math.max(10,t.length))))),b=[];for(let e=y;t.length>=e;e+=y)b.push(e);b[b.length-1]!==t.length&&b.push(t.length);const x=new Set(["bar","pie","donut","clusterbar","swarm","point","boxplot","violin","histogram","timeline","swimlane","ridgeline","funnel","bar-funnel"]).has(e),v=ze({top:20,right:20,bottom:30,left:40,...o.margin},o.title),w=p-v.left-v.right,A=g-v.top-v.bottom,S=[];if(x)for(let n=0;b.length>n;n++){const i=b[n],s=t.slice(r?Math.max(0,i-r):0,i),a={chartType:e,windowSize:1e4,windowMode:"sliding",extentPadding:.05,projection:o.projection||"vertical",oAccessor:o.oAccessor||o.categoryAccessor||"category",rAccessor:o.rAccessor||o.valueAccessor||"value",colorAccessor:o.colorAccessor||o.colorBy,stackBy:o.stackBy,groupBy:o.groupBy,barPadding:o.barPadding,innerRadius:o.innerRadius,normalize:o.normalize,bins:o.bins,colorScheme:o.colorScheme||m.colors.categorical,...h&&{decay:h}},l=new Fl(a);l.ingest({inserts:s,bounded:!0}),l.computeScene({width:w,height:A}),l.scene.length>0&&S.push(wu(l.scene,p,g,m,f))}else for(let n=0;b.length>n;n++){const i=b[n],s=t.slice(r?Math.max(0,i-r):0,i),y={chartType:e,windowSize:s.length+10,windowMode:"sliding",arrowOfTime:"right",extentPadding:.1,xAccessor:o.xAccessor||"x",yAccessor:o.yAccessor||"y",colorAccessor:o.colorAccessor||o.colorBy,groupAccessor:o.groupAccessor||o.lineBy,lineDataAccessor:o.lineDataAccessor,xExtent:a,yExtent:l,colorScheme:o.colorScheme||m.colors.categorical,lineStyle:o.lineStyle,pointStyle:o.pointStyle,areaStyle:o.areaStyle,sizeAccessor:o.sizeAccessor||o.sizeBy,sizeRange:o.sizeRange,...h&&{decay:h},...c>0&&{transition:{duration:c*(1e3/u),easing:d}}},x=new z(y);if(x.ingest({inserts:s,bounded:!0}),x.computeScene({width:w,height:A}),0===x.scene.length)continue;const v=x.scales?{y:x.scales.y}:void 0;if(S.push(vu(x.scene,p,g,m,f,v)),c>0&&n>0&&x.activeTransition){const e=c*(1e3/u);for(let t=1;c>=t;t++)x.advanceTransition(x.activeTransition.startTime+t/c*e),S.push(vu(x.scene,p,g,m,f,v))}}return S}function fu(e,t,o={}){return t.map(t=>{try{return au(e,{...o,...t})}catch{return`<svg xmlns="http://www.w3.org/2000/svg" width="${o.width||t.width||600}" height="${o.height||t.height||400}"></svg>`}})}function yu(e,t,o){const n=t.size??[t.width??600,t.height??400],i=Kt(t.theme),r=Jt(i),s=t.background||i.colors.background,a=t.idPrefix??"physics-gif",l=t.title?`${a}-title-${o}`:void 0,c=t.description?`${a}-desc-${o}`:void 0,u=[l,c].filter(Boolean).join(" ")||void 0,d=Nc(e.readBodies(),{bodyStyle:t.bodyStyle,getBodyLabel:t.getBodyLabel}),h=gu("svg",{xmlns:"http://www.w3.org/2000/svg",className:t.className??"stream-physics-frame",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,role:"img","aria-labelledby":u,style:{fontFamily:r.fontFamily},children:[t.title&&pu("title",{id:l,children:t.title}),t.description&&pu("desc",{id:c,children:t.description}),s&&"transparent"!==s?pu("rect",{x:0,y:0,width:n[0],height:n[1],fill:s}):null,pu("g",{id:`${a}-frame-${o}`,children:d.map((e,t)=>at(e,t,`${a}-${o}`))})]});return du.renderToStaticMarkup(h)}function bu(e,t={}){const{fps:o=12,frameCount:n,durationSeconds:i=2,includeInitialFrame:r=!0,stepDt:s,stepsPerFrame:a,background:l}=t,c=Math.max(.001,s??e.config?.fixedDt??1/120),u=a??Math.max(1,Math.round(1/Math.max(1,o)/c)),h=n??Math.max(1,Math.ceil(i*Math.max(1,o))),p=l?{...e,background:l}:e,g=new d(e.config);e.initialSpawns?.length&&g.enqueue(e.initialSpawns,e.initialSpawnPacing);const m=[];for(r&&(g.tick(0),m.push(yu(g,p,0)));h>m.length;){for(let e=0;u>e;e+=1)g.tick(c);m.push(yu(g,p,m.length))}return m}function xu(e,t){const o=e.background||t.colors.background;return o&&"transparent"!==o?o:null}function vu(e,t,o,n,i,r){const s=Jt(n),a=ze({top:20,right:20,bottom:30,left:40,...i.margin},i.title),l=t-a.left-a.right,c=o-a.top-a.bottom,u=xu(i,n),d=i.renderMode,h=e.map((e,t)=>Ce({node:e,index:t,renderMode:d,fallback:()=>at(e,t)})).filter(Boolean),p=function(e,t,o,n,i,r){if(!e||0===e.length)return null;const s=Jt(n),a=[];for(let n=0;e.length>n;n++){const l=e[n];if("y-threshold"===l.type&&null!=l.value){let e=null;if(r)e=r(l.value);else if(i){const[t,n]=i,r=n-t;if(0===r)continue;e=o-(l.value-t)/r*o}if(null==e)continue;const c=l.color||s.primary,u=l.labelPosition||"right";a.push(gu("g",{children:[pu("line",{x1:0,y1:e,x2:t,y2:e,stroke:c,strokeWidth:l.strokeWidth??1.5,strokeDasharray:l.strokeDasharray||"6,4"}),l.label&&pu("text",{x:"left"===u?4:"center"===u?t/2:t-4,y:20>e?Math.min(o-4,e+16):e-5,textAnchor:"left"===u?"start":"center"===u?"middle":"end",fontSize:s.tickSize,fill:c,fontFamily:s.fontFamily,children:l.label})]},"ann-"+n))}}return a.length>0?pu(hu,{children:a}):null}(i.annotations,l,c,n,i.yExtent,r?.y),g="string"==typeof i.title?i.title:void 0,m="string"==typeof i.description?i.description:void 0,f=g?"semiotic-title":void 0,y=m?"semiotic-desc":void 0,b=[f,y].filter(Boolean).join(" ")||void 0;return du.renderToStaticMarkup(gu("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:o,role:"img","aria-labelledby":b,style:{fontFamily:s.fontFamily},children:[g&&pu("title",{id:f,children:g}),m&&pu("desc",{id:y,children:m}),u&&pu("rect",{x:0,y:0,width:t,height:o,fill:u}),gu("g",{transform:`translate(${a.left},${a.top})`,children:[p,h]}),g&&pu("text",{x:t/2,y:E,textAnchor:"middle",fontSize:s.titleSize,fontWeight:"bold",fill:s.text,fontFamily:s.fontFamily,children:g})]}))}function wu(e,t,o,n,i){const r=Jt(n),s=ze({top:20,right:20,bottom:30,left:40,...i.margin},i.title),a="radial"===i.projection,l=a?s.left+(t-s.left-s.right)/2:s.left,c=a?s.top+(o-s.top-s.bottom)/2:s.top,u=xu(i,n),d=i.renderMode,h=e.map((e,t)=>Ce({node:e,index:t,renderMode:d,fallback:()=>_e(e,t)})).filter(Boolean),p="string"==typeof i.title?i.title:void 0,g="string"==typeof i.description?i.description:void 0,m=p?"semiotic-title":void 0,f=g?"semiotic-desc":void 0,y=[m,f].filter(Boolean).join(" ")||void 0;return du.renderToStaticMarkup(gu("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:o,role:"img","aria-labelledby":y,style:{fontFamily:r.fontFamily},children:[p&&pu("title",{id:m,children:p}),g&&pu("desc",{id:f,children:g}),u&&pu("rect",{x:0,y:0,width:t,height:o,fill:u}),pu("g",{transform:`translate(${l},${c})`,children:h}),p&&pu("text",{x:t/2,y:E,textAnchor:"middle",fontSize:r.titleSize,fontWeight:"bold",fill:r.text,fontFamily:r.fontFamily,children:p})]}))}export{mu as generateFrameSVGs,fu as generateFrameSequence,bu as generatePhysicsFrameSVGs,au as renderChart,lu as renderChartWithEvidence,uu as renderDashboard,nu as renderGeoToStaticSVG,ou as renderNetworkToStaticSVG,tu as renderOrdinalToStaticSVG,Jc as renderToStaticSVG,eu as renderXYToStaticSVG,Kt as resolveTheme,Jt as themeStyles};