semiotic 3.9.1 → 3.9.2

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 (328) hide show
  1. package/README.md +102 -48
  2. package/agent-skill/semiotic-charts/SKILL.md +14 -10
  3. package/ai/componentMetadata.cjs +13 -3
  4. package/ai/dist/mcp-server.js +140 -36407
  5. package/ai/examples.md +109 -6
  6. package/ai/reference.md +55 -18
  7. package/ai/schema.json +5964 -1190
  8. package/ai/surface-manifest.json +51 -7
  9. package/ai/system-prompt.md +16 -3
  10. package/dist/c-3SCUN5HI.min.js +1 -0
  11. package/dist/c-3VVKFA4M.min.js +1 -0
  12. package/dist/c-43TJZS3F.min.js +1 -0
  13. package/dist/c-4DTZPSUD.min.js +1 -0
  14. package/dist/c-4ES5367Y.min.js +1 -0
  15. package/dist/c-54IRWOGM.min.js +1 -0
  16. package/dist/c-5D2S4RMI.min.js +1 -0
  17. package/dist/c-5JWCTX3G.min.js +1 -0
  18. package/dist/c-6CMMSN6N.min.js +1 -0
  19. package/dist/c-6HRB2L7H.min.js +1 -0
  20. package/dist/c-7W4SV36A.min.js +1 -0
  21. package/dist/c-A4WRGZFX.min.js +1 -0
  22. package/dist/c-AG7WWVIH.min.js +1 -0
  23. package/dist/c-AH6J4MTN.min.js +1 -0
  24. package/dist/c-ALYR5LKK.min.js +1 -0
  25. package/dist/c-BYDPC44I.min.js +1 -0
  26. package/dist/c-CFFIU2MW.min.js +1 -0
  27. package/dist/c-CGNHBHCE.min.js +1 -0
  28. package/dist/c-CJYSXIFV.min.js +1 -0
  29. package/dist/c-CKLIFCGN.min.js +1 -0
  30. package/dist/c-CZF7MV67.min.js +1 -0
  31. package/dist/c-D53OKBSY.min.js +1 -0
  32. package/dist/c-DBQ2V7CH.min.js +1 -0
  33. package/dist/c-DPMVAUAW.min.js +1 -0
  34. package/dist/c-ECJCKLYY.min.js +1 -0
  35. package/dist/c-EGATGOWJ.min.js +1 -0
  36. package/dist/c-EGR6VYBW.min.js +1 -0
  37. package/dist/c-ENF72HU5.min.js +1 -0
  38. package/dist/c-ESNR43AN.min.js +1 -0
  39. package/dist/c-F3LIKINL.min.js +1 -0
  40. package/dist/c-F5ZB5GJ6.min.js +1 -0
  41. package/dist/c-G3VYMHKE.min.js +1 -0
  42. package/dist/c-GR6MOEQC.min.js +1 -0
  43. package/dist/c-GSVCN34B.min.js +1 -0
  44. package/dist/c-GYOQCEFP.min.js +1 -0
  45. package/dist/c-H3DNMTCC.min.js +1 -0
  46. package/dist/c-I6J3FEZE.min.js +1 -0
  47. package/dist/c-IGH6MGJ5.min.js +1 -0
  48. package/dist/c-II2EEAJN.min.js +1 -0
  49. package/dist/c-J6M4JHRS.min.js +1 -0
  50. package/dist/c-JM3MGLQV.min.js +1 -0
  51. package/dist/c-KM3N7F7R.min.js +1 -0
  52. package/dist/c-LF5BZFNC.min.js +1 -0
  53. package/dist/c-LKBSGFQC.min.js +1 -0
  54. package/dist/c-NDJADPIF.min.js +1 -0
  55. package/dist/c-NVPQCIL5.min.js +1 -0
  56. package/dist/c-OFWJBEE5.min.js +1 -0
  57. package/dist/c-OYFHP5F5.min.js +1 -0
  58. package/dist/c-PGKQGGQ2.min.js +1 -0
  59. package/dist/c-Q2IPZ3MU.min.js +1 -0
  60. package/dist/c-QKHMBE2E.min.js +1 -0
  61. package/dist/c-QMVM3AY6.min.js +1 -0
  62. package/dist/c-QSGWX53A.min.js +1 -0
  63. package/dist/c-RJKEKZOO.min.js +1 -0
  64. package/dist/c-SFDIIU5G.min.js +1 -0
  65. package/dist/c-SRTBCRVE.min.js +1 -0
  66. package/dist/c-T6UAIKBH.min.js +1 -0
  67. package/dist/c-TMCTEVVW.min.js +1 -0
  68. package/dist/c-TMOSJLT3.min.js +1 -0
  69. package/dist/c-U6ESPM7V.min.js +1 -0
  70. package/dist/c-UC5PTTFI.min.js +1 -0
  71. package/dist/c-VGKUEZBC.min.js +1 -0
  72. package/dist/c-VN2HG5BS.min.js +1 -0
  73. package/dist/{c-J5G56TUH.min.js → c-VPZDY5Q4.min.js} +1 -1
  74. package/dist/c-VRXUB2F2.min.js +1 -0
  75. package/dist/c-VUBQNQJH.min.js +1 -0
  76. package/dist/c-VUH4PGZY.min.js +1 -0
  77. package/dist/c-XDRV7RKW.min.js +1 -0
  78. package/dist/c-YGZHURXZ.min.js +1 -0
  79. package/dist/components/Annotation.d.ts +1 -1
  80. package/dist/components/access/chartAccessCapabilities.generated.d.ts +14 -0
  81. package/dist/components/access/chartAccessContract.d.ts +90 -0
  82. package/dist/components/access/chartAccessContractFixtures.d.ts +11 -0
  83. package/dist/components/ai/aestheticProfileTypes.d.ts +35 -0
  84. package/dist/components/ai/annotationProvenance.d.ts +2 -7
  85. package/dist/components/ai/auditVisualHierarchy.d.ts +49 -0
  86. package/dist/components/ai/builtInChartRecipeLayouts.d.ts +2 -0
  87. package/dist/components/ai/builtInChartRecipePublic.d.ts +4 -0
  88. package/dist/components/ai/builtInChartRecipes.d.ts +26 -0
  89. package/dist/components/ai/chartCapabilities.d.ts +3 -1
  90. package/dist/components/ai/chartRecipeRegistry.d.ts +2 -1
  91. package/dist/components/ai/chartRecipes.d.ts +6 -0
  92. package/dist/components/ai/colorEvidence.d.ts +12 -0
  93. package/dist/components/ai/evaluateAesthetics.d.ts +47 -0
  94. package/dist/components/ai/geoNavigation.d.ts +4 -0
  95. package/dist/components/ai/hierarchyNavigation.d.ts +4 -0
  96. package/dist/components/ai/navigationTree.d.ts +7 -1
  97. package/dist/components/ai/qualityFixtures.d.ts +8 -0
  98. package/dist/components/ai/suggestionPropContracts.d.ts +1 -1
  99. package/dist/components/ai/useNavigationSync.d.ts +3 -3
  100. package/dist/components/charts/index.d.ts +4 -0
  101. package/dist/components/charts/network/ChordDiagram.d.ts +5 -1
  102. package/dist/components/charts/network/CirclePack.d.ts +8 -1
  103. package/dist/components/charts/network/OrbitDiagram.d.ts +9 -0
  104. package/dist/components/charts/network/TreeDiagram.d.ts +8 -1
  105. package/dist/components/charts/network/Treemap.d.ts +8 -1
  106. package/dist/components/charts/ordinal/BarChart.d.ts +6 -0
  107. package/dist/components/charts/ordinal/BoxPlot.d.ts +3 -0
  108. package/dist/components/charts/ordinal/DonutChart.d.ts +3 -0
  109. package/dist/components/charts/ordinal/DotPlot.d.ts +3 -0
  110. package/dist/components/charts/ordinal/FunnelChart.d.ts +3 -0
  111. package/dist/components/charts/ordinal/GaugeChart.d.ts +3 -0
  112. package/dist/components/charts/ordinal/Histogram.d.ts +3 -0
  113. package/dist/components/charts/ordinal/LikertChart.d.ts +3 -0
  114. package/dist/components/charts/ordinal/PieChart.d.ts +3 -0
  115. package/dist/components/charts/ordinal/RadarChart.capability.d.ts +2 -0
  116. package/dist/components/charts/ordinal/RadarChart.d.ts +75 -0
  117. package/dist/components/charts/ordinal/RidgelinePlot.d.ts +3 -0
  118. package/dist/components/charts/ordinal/SwarmPlot.d.ts +3 -0
  119. package/dist/components/charts/ordinal/SwimlaneChart.d.ts +3 -0
  120. package/dist/components/charts/ordinal/ViolinPlot.d.ts +3 -0
  121. package/dist/components/charts/physics/GauntletChart.d.ts +1 -5
  122. package/dist/components/charts/physics/chainReactionTypes.d.ts +3 -0
  123. package/dist/components/charts/physics/gauntletPhysics.d.ts +1 -0
  124. package/dist/components/charts/physics/physicsHocUtils.d.ts +7 -1
  125. package/dist/components/charts/realtime/RealtimeHeatmap.d.ts +10 -1
  126. package/dist/components/charts/realtime/RealtimeHistogram.d.ts +11 -1
  127. package/dist/components/charts/realtime/RealtimeLineChart.d.ts +14 -5
  128. package/dist/components/charts/realtime/RealtimeSwarmChart.d.ts +7 -1
  129. package/dist/components/charts/realtime/RealtimeWaterfallChart.d.ts +7 -1
  130. package/dist/components/charts/realtime/aggregate.d.ts +12 -1
  131. package/dist/components/charts/realtime/realtimeChartRuntime.d.ts +4 -2
  132. package/dist/components/charts/realtime/realtimeStyleRules.d.ts +4 -0
  133. package/dist/components/charts/shared/annotationStatusFilter.d.ts +18 -0
  134. package/dist/components/charts/shared/chartDefinitionPilot.d.ts +5 -4
  135. package/dist/components/charts/shared/chartSpecCore.d.ts +2 -2
  136. package/dist/components/charts/shared/heatmapStyleRules.d.ts +13 -0
  137. package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
  138. package/dist/components/charts/shared/networkUtils.d.ts +14 -0
  139. package/dist/components/charts/shared/selectionUtils.d.ts +3 -1
  140. package/dist/components/charts/shared/types.d.ts +4 -2
  141. package/dist/components/charts/shared/useChartLegend.d.ts +2 -1
  142. package/dist/components/charts/shared/useLikertAggregation.d.ts +8 -2
  143. package/dist/components/charts/shared/useNetworkChartSetup.d.ts +9 -5
  144. package/dist/components/charts/shared/useOrdinalPieceStyle.d.ts +1 -1
  145. package/dist/components/charts/shared/useXYBrush.d.ts +24 -0
  146. package/dist/components/charts/xy/Heatmap.d.ts +16 -0
  147. package/dist/components/charts/xy/LineChart.d.ts +9 -0
  148. package/dist/components/charts/xy/Scatterplot.d.ts +7 -0
  149. package/dist/components/charts/xy/WaterfallChart.capability.d.ts +2 -0
  150. package/dist/components/charts/xy/WaterfallChart.d.ts +68 -0
  151. package/dist/components/evidence/chartEvidenceEnvelope.d.ts +146 -0
  152. package/dist/components/evidence/evidenceGate.d.ts +28 -0
  153. package/dist/components/realtime/BinAccumulator.d.ts +5 -1
  154. package/dist/components/realtime/types.d.ts +16 -7
  155. package/dist/components/recipes/adjacencyFlow.d.ts +12 -0
  156. package/dist/components/recipes/adjacencyFlowAggregation.d.ts +72 -0
  157. package/dist/components/recipes/adjacencyFlowGeometry.d.ts +79 -0
  158. package/dist/components/recipes/lineageDag.d.ts +17 -0
  159. package/dist/components/recipes/lineageDagHulls.d.ts +22 -0
  160. package/dist/components/recipes/transitDiagram.d.ts +75 -0
  161. package/dist/components/recipes/transitDiagramGeometry.d.ts +47 -0
  162. package/dist/components/semiotic-access.d.ts +9 -0
  163. package/dist/components/semiotic-ai-audits.d.ts +17 -0
  164. package/dist/components/semiotic-ai-core.d.ts +9 -0
  165. package/dist/components/semiotic-ai.d.ts +5 -17
  166. package/dist/components/semiotic-evidence.d.ts +10 -0
  167. package/dist/components/semiotic-line.d.ts +9 -0
  168. package/dist/components/semiotic-network.d.ts +3 -0
  169. package/dist/components/semiotic-ordinal.d.ts +2 -0
  170. package/dist/components/semiotic-realtime-core.d.ts +3 -2
  171. package/dist/components/semiotic-recipes-core.d.ts +6 -0
  172. package/dist/components/semiotic-themes-core.d.ts +3 -0
  173. package/dist/components/semiotic-utils-core.d.ts +5 -0
  174. package/dist/components/semiotic-xy.d.ts +3 -0
  175. package/dist/components/semiotic.d.ts +9 -3
  176. package/dist/components/server/renderDashboard.d.ts +37 -0
  177. package/dist/components/server/renderEvidence.d.ts +27 -0
  178. package/dist/components/server/renderToStaticSVG.d.ts +2 -30
  179. package/dist/components/server/serverChartConfigShared.d.ts +13 -0
  180. package/dist/components/server/serverChartConfigs.d.ts +9 -0
  181. package/dist/components/server/serverChartConfigsComposite.d.ts +4 -0
  182. package/dist/components/server/serverChartConfigsCustom.d.ts +2 -0
  183. package/dist/components/server/serverChartConfigsGeo.d.ts +1 -0
  184. package/dist/components/server/serverChartConfigsOrdinal.d.ts +3 -2
  185. package/dist/components/server/serverChartConfigsXY.d.ts +1 -0
  186. package/dist/components/server/serverChartConfigsXYExtra.d.ts +3 -0
  187. package/dist/components/server/serverCompositeChainReaction.d.ts +3 -0
  188. package/dist/components/server/serverOrdinalGauge.d.ts +3 -0
  189. package/dist/components/server/serverOrdinalLikert.d.ts +2 -0
  190. package/dist/components/store/selectionProvenance.d.ts +8 -0
  191. package/dist/components/store/themeCore.d.ts +5 -1
  192. package/dist/components/stream/GeoPipelineStore.d.ts +1 -1
  193. package/dist/components/stream/MarginalGraphics.d.ts +3 -3
  194. package/dist/components/stream/MarginalGraphicsLazy.d.ts +22 -0
  195. package/dist/components/stream/NetworkPipelineStore.d.ts +2 -0
  196. package/dist/components/stream/OrdinalPipelineStore.d.ts +1 -1
  197. package/dist/components/stream/PipelineStore.d.ts +1 -1
  198. package/dist/components/stream/SceneToSVG.d.ts +1 -1
  199. package/dist/components/stream/canvasSetup.d.ts +8 -2
  200. package/dist/components/stream/customLayoutAttempt.d.ts +21 -0
  201. package/dist/components/stream/geoTypes.d.ts +1 -1
  202. package/dist/components/stream/isServerEnvironment.d.ts +6 -0
  203. package/dist/components/stream/layouts/forceLayoutNodeSize.d.ts +12 -0
  204. package/dist/components/stream/layouts/forceLayoutPlugin.d.ts +2 -9
  205. package/dist/components/stream/layouts/forceLayoutWorkerClient.d.ts +2 -21
  206. package/dist/components/stream/layouts/forceLayoutWorkerPolicy.d.ts +21 -0
  207. package/dist/components/stream/layouts/index.d.ts +6 -12
  208. package/dist/components/stream/layouts/missingPlugin.d.ts +7 -0
  209. package/dist/components/stream/layouts/registerBuiltIn.d.ts +1 -0
  210. package/dist/components/stream/layouts/registry.d.ts +12 -0
  211. package/dist/components/stream/marginalConfig.d.ts +3 -0
  212. package/dist/components/stream/networkCustomLayout.d.ts +7 -0
  213. package/dist/components/stream/networkCustomLayoutOutput.d.ts +13 -0
  214. package/dist/components/stream/networkCustomLayoutRunner.d.ts +1 -1
  215. package/dist/components/stream/networkTypes.d.ts +5 -1
  216. package/dist/components/stream/ordinalTypes.d.ts +1 -1
  217. package/dist/components/stream/physics/StreamPhysicsTypes.d.ts +1 -1
  218. package/dist/components/stream/pipelineDomainResolution.d.ts +6 -0
  219. package/dist/components/stream/renderers/pointCanvasRenderer.d.ts +4 -0
  220. package/dist/components/stream/renderers/resolveCSSColor.d.ts +4 -4
  221. package/dist/components/stream/types.d.ts +8 -1
  222. package/dist/components/stream/useEnsureCustomXYRenderers.d.ts +18 -0
  223. package/dist/components/stream/useMarginalValues.d.ts +13 -0
  224. package/dist/components/stream/xyCanvasRenderers.d.ts +4 -4
  225. package/dist/components/stream/xyPlugins/areaPlugin.d.ts +2 -0
  226. package/dist/components/stream/xyPlugins/barPlugin.d.ts +2 -0
  227. package/dist/components/stream/xyPlugins/candlestickPlugin.d.ts +2 -0
  228. package/dist/components/stream/xyPlugins/customPlugin.d.ts +6 -0
  229. package/dist/components/stream/xyPlugins/heatmapPlugin.d.ts +2 -0
  230. package/dist/components/stream/xyPlugins/lineFamily.d.ts +5 -0
  231. package/dist/components/stream/xyPlugins/linePlugin.d.ts +2 -0
  232. package/dist/components/stream/xyPlugins/missingPlugin.d.ts +7 -0
  233. package/dist/components/stream/xyPlugins/mixedPlugin.d.ts +2 -0
  234. package/dist/components/stream/xyPlugins/pointPlugin.d.ts +3 -0
  235. package/dist/components/stream/xyPlugins/registerBuiltIn.d.ts +1 -0
  236. package/dist/components/stream/xyPlugins/registry.d.ts +31 -0
  237. package/dist/components/stream/xyPlugins/stackedAreaPlugin.d.ts +2 -0
  238. package/dist/components/stream/xyPlugins/swarmPlugin.d.ts +2 -0
  239. package/dist/components/stream/xyPlugins/waterfallPlugin.d.ts +2 -0
  240. package/dist/forceLayoutWorker.js +1 -1
  241. package/dist/geo.min.js +1 -1
  242. package/dist/geo.module.min.js +1 -1
  243. package/dist/network.module.min.js +1 -1
  244. package/dist/ordinal.module.min.js +1 -1
  245. package/dist/physics.module.min.js +1 -1
  246. package/dist/rough.module.min.js +1 -1
  247. package/dist/semiotic-access.d.ts +9 -0
  248. package/dist/semiotic-access.min.js +2 -0
  249. package/dist/semiotic-access.module.min.js +2 -0
  250. package/dist/semiotic-ai-core.d.ts +9 -0
  251. package/dist/semiotic-ai-core.min.js +1 -1
  252. package/dist/semiotic-ai-core.module.min.js +1 -1
  253. package/dist/semiotic-ai.d.ts +5 -17
  254. package/dist/semiotic-ai.module.min.js +1 -1
  255. package/dist/semiotic-client-cjs-shared.min.js +1 -1
  256. package/dist/semiotic-client-shared.module.min.js +1 -1
  257. package/dist/semiotic-evidence.d.ts +10 -0
  258. package/dist/semiotic-evidence.min.js +1 -0
  259. package/dist/semiotic-evidence.module.min.js +1 -0
  260. package/dist/semiotic-experimental-auxiliary.module.min.js +1 -1
  261. package/dist/semiotic-experimental-node-auxiliary.module.min.js +1 -1
  262. package/dist/semiotic-experimental-react-shared.module.min.js +1 -1
  263. package/dist/semiotic-experimental-vacp.min.js +1 -1
  264. package/dist/semiotic-experimental-vacp.module.min.js +1 -1
  265. package/dist/semiotic-line.d.ts +9 -0
  266. package/dist/semiotic-line.min.js +2 -0
  267. package/dist/semiotic-line.module.min.js +2 -0
  268. package/dist/semiotic-network.d.ts +3 -0
  269. package/dist/semiotic-ordinal.d.ts +2 -0
  270. package/dist/semiotic-realtime-core.d.ts +3 -2
  271. package/dist/semiotic-realtime-core.module.min.js +1 -1
  272. package/dist/semiotic-recipes-core-cjs-base.min.js +1 -1
  273. package/dist/semiotic-recipes-core.d.ts +6 -0
  274. package/dist/semiotic-recipes-core.module.min.js +1 -1
  275. package/dist/semiotic-server-edge-node.module.min.js +1 -1
  276. package/dist/semiotic-server-edge.min.js +1 -1
  277. package/dist/semiotic-server-edge.module.min.js +1 -1
  278. package/dist/semiotic-server-node.min.js +1 -1
  279. package/dist/semiotic-server-node.module.min.js +1 -1
  280. package/dist/semiotic-themes-core.d.ts +3 -0
  281. package/dist/semiotic-themes-core.min.js +1 -1
  282. package/dist/semiotic-themes-core.module.min.js +1 -1
  283. package/dist/semiotic-themes.min.js +1 -1
  284. package/dist/semiotic-themes.module.min.js +1 -1
  285. package/dist/semiotic-utils-core.d.ts +5 -0
  286. package/dist/semiotic-utils-core.min.js +1 -1
  287. package/dist/semiotic-utils-core.module.min.js +1 -1
  288. package/dist/semiotic-xy.d.ts +3 -0
  289. package/dist/semiotic.d.ts +9 -3
  290. package/dist/semiotic.module.min.js +1 -1
  291. package/dist/server.min.js +1 -1
  292. package/dist/server.module.min.js +1 -1
  293. package/dist/xy.module.min.js +1 -1
  294. package/package.json +39 -60
  295. package/dist/c-3KZD6AXJ.min.js +0 -1
  296. package/dist/c-4TWEX5HG.min.js +0 -1
  297. package/dist/c-5YCIX3VZ.min.js +0 -1
  298. package/dist/c-6FEKTA3U.min.js +0 -1
  299. package/dist/c-74HEEZGK.min.js +0 -1
  300. package/dist/c-BWNB6USU.min.js +0 -1
  301. package/dist/c-C25ENHIK.min.js +0 -1
  302. package/dist/c-CDR5AO3R.min.js +0 -1
  303. package/dist/c-E3JFRRMI.min.js +0 -1
  304. package/dist/c-EBFPQHHO.min.js +0 -1
  305. package/dist/c-GIKRQI4X.min.js +0 -1
  306. package/dist/c-GPYOFETM.min.js +0 -1
  307. package/dist/c-IDUHYYSI.min.js +0 -1
  308. package/dist/c-JAZ73J32.min.js +0 -1
  309. package/dist/c-KG3NXHAL.min.js +0 -1
  310. package/dist/c-KII3PLZE.min.js +0 -1
  311. package/dist/c-LIXGXMNS.min.js +0 -1
  312. package/dist/c-LVEY6D6B.min.js +0 -1
  313. package/dist/c-M4Y3BHFR.min.js +0 -1
  314. package/dist/c-MAIICR2Z.min.js +0 -1
  315. package/dist/c-MG5DM6VE.min.js +0 -1
  316. package/dist/c-O6U6K4CW.min.js +0 -1
  317. package/dist/c-OQ7M4AGV.min.js +0 -1
  318. package/dist/c-OXYMVK7Q.min.js +0 -1
  319. package/dist/c-QHF5YON3.min.js +0 -1
  320. package/dist/c-RR3GO5SW.min.js +0 -1
  321. package/dist/c-S2BXNNJN.min.js +0 -1
  322. package/dist/c-SUILCHWU.min.js +0 -1
  323. package/dist/c-US5ZFT6E.min.js +0 -1
  324. package/dist/c-UUKVD4WB.min.js +0 -1
  325. package/dist/c-WJCD5EUY.min.js +0 -1
  326. package/dist/c-YDAY2WFR.min.js +0 -1
  327. package/dist/c-ZOWWU34K.min.js +0 -1
  328. /package/dist/{c-COHXCW3Q.min.js → c-YZVRZGX2.min.js} +0 -0
@@ -1 +0,0 @@
1
- import{mulberry32 as e}from"./c-N4G2L7ID.min.js";import{commonJsWorkerModuleUrl as t}from"./c-VGW3VG3I.min.js";import{makeRuleValueResolver as i,resolveStyleRules as n}from"./c-S2BXNNJN.min.js";import{buildResolveColor as o,resolveCustomLayoutPalette as r}from"./c-J5G56TUH.min.js";import{ANNOTATION_DISCLOSURE_REVEAL_CSS as s,AccessibleTablePortal as a,AriaLiveTooltip as c,CanvasFrameBackground as d,FlippingTooltip as l,FocusRing as u,SVGChartTitle as h,SafeRender as p,SceneRevisionDiagnosticsObserver as m,ScreenReaderSummary as y,SkipToTableLink as f,TooltipRoot as g,UpdateResultTracker as b,annotationLayout as v,coerceCanvasFill as x,createDefaultAnnotationRules as w,defaultTooltipStyle as k,filterSparseArray as I,getCSSColorCacheVersion as M,getDevicePixelRatio as S,isInteractiveKeyboardTarget as A,isMultiTooltip as C,isMultiTooltipConfig as R,isServerEnvironment as P,normalizeTooltip as $,prepareCanvas as D,renderAnnotationPass as B,renderEmptyState as j,renderLegendFromConfig as T,renderLoadingState as O,resolveCSSColor as E,resolveCanvasPaint as N,resolveMotionAccessor as F,schemeCategory10 as W,setCanvasMarkCursor as q,useAnnotationActivationOptions as z,useCanvasMarkCursorCleanup as H,useChartMode as L,useChartSelection as Y,useDataSummary as _,useFrame as X,useFrameCanvasHost as G,useHydration as U,useResponsiveSize as V,useSceneRevisionDiagnostics as K,useWasHydratingFromSSR as Q,withSceneMarkCursor as J,xySceneNodeToSVG as Z}from"./c-GIKRQI4X.min.js";import{LIGHT_THEME as ee,resolveThemeSemanticColors as te,useReducedMotion as ie,useThemeSelector as ne}from"./c-YDAY2WFR.min.js";import{scaleLinear as oe}from"d3-scale";function re(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function se(e){return e.map(e=>({pointId:e.id,x:e.x,y:e.y,r:Math.max(1,re(e))}))}function ae(e){const{width:t,height:i,pointNodes:n=[],data:o}=e;return{scales:{x:oe().domain([0,Math.max(1,t)]).range([0,Math.max(1,t)]),y:oe().domain([0,Math.max(1,i)]).range([0,Math.max(1,i)])},width:t,height:i,frameType:"network",pointNodes:n,data:o,xAccessor:"x",yAccessor:"y"}}function ce(e){return e?.length?e.map(e=>null!=e.pointId||null==e.bodyId?e:{...e,pointId:e.bodyId+""}):e}import*as de from"react";import{Fragment as le,jsx as ue,jsxs as he}from"react/jsx-runtime";function pe(e){const{width:t,height:i,totalWidth:n,totalHeight:o,margin:r,title:a,legend:c,legendHoverBehavior:d,legendClickBehavior:l,legendHighlightedCategory:u,legendIsolatedCategories:p,legendPosition:m="right",legendLayout:y,pointNodes:f=[],annotations:g,onAnnotationActivate:b,onObservation:x,chartId:k,chartType:I,autoPlaceAnnotations:M,svgAnnotationRules:S,children:A}=e,C=z({onAnnotationActivate:b,onObservation:x,chartId:k,chartType:I}),R=de.useMemo(()=>ce(g),[g]),P=de.useMemo(()=>ae({width:t,height:i,pointNodes:f}),[i,f,t]),$=de.useMemo(()=>R&&M?v({annotations:R,context:P,..."object"==typeof M?M:{}}):R,[P,M,R]),D=de.useMemo(()=>w("network",C),[C]),j=$?B($,D,S,P):null,O=!0===$?.some(e=>"widget"===e.type&&!0===e._annotationDeferred);return he(le,{children:[O?ue("style",{children:s},"physics-annotation-disclosure-style"):null,he("svg",{className:"stream-physics-frame__overlay","data-testid":"stream-physics-overlay",role:"presentation",width:n,height:o,style:{position:"absolute",top:0,left:0,pointerEvents:"none",overflow:"visible"},children:[he("g",{transform:`translate(${r.left},${r.top})`,children:[j,A]}),ue(h,{title:a,totalWidth:n,marginTop:Math.max(r.top,28)}),c?T({legend:c,totalWidth:n,totalHeight:o,margin:r,legendPosition:m,legendLayout:y,title:a,legendHoverBehavior:d,legendClickBehavior:l,legendHighlightedCategory:u,legendIsolatedCategories:p}):null]})]})}var me={seed:1,gravity:{x:0,y:980},fixedDt:1/120,cellSize:64,collisionIterations:6,velocityDamping:.995,sleepSpeed:8,sleepAfter:.35,restitution:.1,friction:.35,maxVelocity:1600,contactWakeSpeed:200},ye=1e-9,fe=.005;function ge(e){return"circle"===e.type?{type:"circle",radius:e.radius}:{type:"aabb",width:e.width,height:e.height}}function be(e){return"aabb"===e.type?{type:"aabb",x:e.x,y:e.y,width:e.width,height:e.height}:{type:"segment",x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,thickness:e.thickness}}function ve(e,t,i){return Math.max(t,Math.min(i,e))}function xe(e,t,i){return Math.min(e??i,t??i)}function we(e,t,i){return ve(Math.max(e??i,t??i),0,1)}function ke(e){return 0>e?-1:1}function Ie(e){if("circle"===e.shape.type){const t=e.shape.radius;return{minX:e.x-t,minY:e.y-t,maxX:e.x+t,maxY:e.y+t}}const t=e.shape.width/2,i=e.shape.height/2;return{minX:e.x-t,minY:e.y-i,maxX:e.x+t,maxY:e.y+i}}function Me(e){const t=e.shape;if("aabb"===t.type){const e=t.width/2,i=t.height/2;return{minX:t.x-e,minY:t.y-i,maxX:t.x+e,maxY:t.y+i}}const i=(t.thickness??0)/2;return{minX:Math.min(t.x1,t.x2)-i,minY:Math.min(t.y1,t.y2)-i,maxX:Math.max(t.x1,t.x2)+i,maxY:Math.max(t.y1,t.y2)+i}}function Se(e,t){return!(e.minX>t.maxX||t.minX>e.maxX||e.minY>t.maxY||t.minY>e.maxY)}function Ae(e,t,i,n,o,r,s,a){const c=o-e,d=(i+s)/2-Math.abs(c);if(0>=d)return null;const l=r-t,u=(n+a)/2-Math.abs(l);return u>0?u>d?{nx:ke(c),ny:0,penetration:d}:{nx:0,ny:ke(l),penetration:u}:null}function Ce(e,t,i,n,o,r,s){const a=r/2,c=s/2,d=e-ve(e,n-a,n+a),l=t-ve(t,o-c,o+c),u=d*d+l*l;if(u>i*i)return null;if(ye>=u){const r=Math.abs(e-(n-a)),s=Math.abs(e-(n+a)),d=Math.abs(t-(o-c)),l=Math.abs(t-(o+c)),u=Math.min(r,s,d,l);return u===r?{nx:-1,ny:0,penetration:i+r}:u===s?{nx:1,ny:0,penetration:i+s}:u===d?{nx:0,ny:-1,penetration:i+d}:{nx:0,ny:1,penetration:i+l}}const h=Math.sqrt(u);return{nx:d/h,ny:l/h,penetration:i-h}}function Re(e,t){if("circle"===e.shape.type&&"circle"===t.shape.type)return function(e,t,i,n,o,r){const s=n-e,a=o-t,c=i+r,d=s*s+a*a;if(d>=c*c)return null;if(ye>=d)return{nx:1,ny:0,penetration:c};const l=Math.sqrt(d);return{nx:s/l,ny:a/l,penetration:c-l}}(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.radius);if("aabb"===e.shape.type&&"aabb"===t.shape.type)return Ae(e.x,e.y,e.shape.width,e.shape.height,t.x,t.y,t.shape.width,t.shape.height);if("circle"===e.shape.type&&"aabb"===t.shape.type){const i=Ce(e.x,e.y,e.shape.radius,t.x,t.y,t.shape.width,t.shape.height);return i?{nx:-i.nx,ny:-i.ny,penetration:i.penetration}:null}return"aabb"===e.shape.type&&"circle"===t.shape.type?Ce(t.x,t.y,t.shape.radius,e.x,e.y,e.shape.width,e.shape.height):null}function Pe(e,t){const i=t.shape;return"aabb"===i.type?"circle"===e.shape.type?Ce(e.x,e.y,e.shape.radius,i.x,i.y,i.width,i.height):Ae(i.x,i.y,i.width,i.height,e.x,e.y,e.shape.width,e.shape.height):function(e,t,i,n,o,r,s,a=0){const c=r-n,d=s-o,l=c*c+d*d,u=l>ye?ve(((e-n)*c+(t-o)*d)/l,0,1):0,h=i+a/2,p=e-(n+c*u),m=t-(o+d*u),y=p*p+m*m;if(y>=h*h)return null;if(ye>=y){const e=Math.sqrt(l);return e>ye?{nx:-d/e,ny:c/e,penetration:h}:{nx:1,ny:0,penetration:h}}const f=Math.sqrt(y);return{nx:p/f,ny:m/f,penetration:h-f}}(e.x,e.y,"circle"===e.shape.type?e.shape.radius:Math.sqrt(e.shape.width*e.shape.width+e.shape.height*e.shape.height)/2,i.x1,i.y1,i.x2,i.y2,i.thickness??0)}function $e(e,t){return`${e}\0${t}`}function De(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function Be(e){return{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,bodyCollisions:e.bodyCollisions,shape:ge(e.shape),sleeping:e.sleeping,datum:e.datum,index:e.index,sleepTime:e.sleepTime,restitution:e.restitution,friction:e.friction}}function je(e){return e&&"function"!=typeof e?{property:e.property,equals:e.equals,notEquals:e.notEquals,oneOf:e.oneOf?.slice(),notOneOf:e.notOneOf?.slice()}:e}function Te(e){return{id:e.id,shape:be(e.shape),sensor:e.sensor,restitution:e.restitution,friction:e.friction,bodyFilter:je(e.bodyFilter),index:e.index}}function Oe(e,t){if(!t)return;let i=e;for(const e of t.split(".")){if(null==i||"object"!=typeof i)return;if(!Object.prototype.hasOwnProperty.call(i,e))return;i=i[e]}return i}function Ee(e,t){return!!t?.some(t=>Object.is(e,t))}function Ne(e,t){if(!t)return!0;if("function"==typeof t)return t(e);const i=Oe(e,t.property);return!("equals"in t&&!Object.is(i,t.equals)||"notEquals"in t&&Object.is(i,t.notEquals)||t.oneOf&&!Ee(i,t.oneOf)||t.notOneOf&&Ee(i,t.notOneOf))}function Fe(e,t){return Ne(t,e.bodyFilter)}var We=class{constructor(t={}){this.capabilities={determinism:"strict",sensors:!0,joints:!1,ccd:!1,maxBodiesHint:5e3,worker:!1},this.bodies=new Map,this.colliders=new Map,this.springs=new Map,this.activeSensors=new Set,this.supportedThisStep=new Set,this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0,this.options={...me,...t},this.random=e(this.options.seed)}init(t={}){this.options={...me,...t},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[],this.nextBodyIndex=0,this.nextColliderIndex=0,this.nextSpringIndex=0}spawn(e){const t={id:e.id,x:e.x,y:e.y,prevX:e.x,prevY:e.y,vx:e.vx??0,vy:e.vy??0,angle:e.angle??0,mass:Math.max(ye,e.mass??1),bodyCollisions:e.bodyCollisions??!0,shape:ge(e.shape),sleeping:!1,datum:e.datum,restitution:e.restitution,friction:e.friction,index:this.nextBodyIndex,sleepTime:0};this.nextBodyIndex+=1,this.bodies.set(e.id,t)}remove(e){for(const t of e){this.bodies.delete(t);for(const e of Array.from(this.activeSensors))De(e).bodyId===t&&this.activeSensors.delete(e)}}setColliders(e){this.colliders.clear(),this.activeSensors.clear(),this.nextColliderIndex=0;for(const t of e)this.colliders.set(t.id,{...t,shape:be(t.shape),bodyFilter:je(t.bodyFilter),index:this.nextColliderIndex}),this.nextColliderIndex+=1}setConstraint(e){const t=e.id??"spring-"+this.nextSpringIndex;return this.springs.set(t,{id:t,bodyId:e.bodyId,target:e.target,restLength:e.restLength??0,stiffness:e.stiffness??40,damping:e.damping??3}),this.nextSpringIndex+=1,t}removeConstraint(e){this.springs.delete(e)}applyImpulse(e,t,i){const n=this.bodies.get(e);n&&(n.vx+=t/n.mass,n.vy+=i/n.mass,this.wake(n))}step(e=this.options.fixedDt){const t=Math.max(0,e);if(this.lastEvents=[],0===t)return;const i=this.sortedBodies();for(const e of i)e.prevX=e.x,e.prevY=e.y;this.applySprings(t);const n=this.options.maxVelocity;for(const e of i)if(!e.sleeping){if(e.vx+=this.options.gravity.x*t,e.vy+=this.options.gravity.y*t,e.vx*=this.options.velocityDamping,e.vy*=this.options.velocityDamping,n>0){const t=Math.sqrt(e.vx*e.vx+e.vy*e.vy);if(t>n){const i=n/t;e.vx*=i,e.vy*=i}}e.x+=e.vx*t,e.y+=e.vy*t}this.supportedThisStep.clear();const o=this.bodyPairKeys(i),r=this.sortedColliders().filter(e=>!e.sensor);for(let e=0;this.options.collisionIterations>e;e+=1)this.resolveBodyPairs(i,o,0===e),this.resolveColliders(i,r,0===e);this.updateSensors(i),this.updateSleeping(i,t)}settle(e=1200,t=this.options.fixedDt){let i=0;for(;e>i&&!this.allSleeping();)this.step(t),i+=1;return i}readState(e=[]){e.length=0;for(const t of this.sortedBodies())e.push({id:t.id,x:t.x,y:t.y,prevX:t.prevX,prevY:t.prevY,vx:t.vx,vy:t.vy,angle:t.angle,mass:t.mass,shape:ge(t.shape),sleeping:t.sleeping,datum:t.datum});return e}events(){return this.lastEvents.slice()}activeSensorPairs(){return Array.from(this.activeSensors).sort().map(De)}allSleeping(){for(const e of this.bodies.values())if(!e.sleeping)return!1;return!0}snapshot(){return{options:{...this.options,gravity:{...this.options.gravity}},bodies:this.sortedBodies().map(Be),colliders:this.sortedColliders().map(Te),springs:Array.from(this.springs.values()).map(e=>({...e,target:{...e.target}})),activeSensors:Array.from(this.activeSensors).sort()}}restore(t){this.options={...t.options,gravity:{...t.options.gravity}},this.random=e(this.options.seed),this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors=new Set(t.activeSensors),this.lastEvents=[],this.nextBodyIndex=0;for(const e of t.bodies){const t=Be(e);this.bodies.set(t.id,t),this.nextBodyIndex=Math.max(this.nextBodyIndex,t.index+1)}this.nextColliderIndex=0;for(const e of t.colliders){const t=Te(e);this.colliders.set(t.id,t),this.nextColliderIndex=Math.max(this.nextColliderIndex,t.index+1)}this.nextSpringIndex=0;for(const e of t.springs){this.springs.set(e.id,{...e,target:{...e.target}});const t=/^spring-(\d+)$/.exec(e.id);t&&(this.nextSpringIndex=Math.max(this.nextSpringIndex,Number(t[1])+1))}}dispose(){this.bodies.clear(),this.colliders.clear(),this.springs.clear(),this.activeSensors.clear(),this.lastEvents=[]}sortedBodies(){return Array.from(this.bodies.values()).sort((e,t)=>e.index-t.index)}sortedColliders(){return Array.from(this.colliders.values()).sort((e,t)=>e.index-t.index)}applySprings(e){for(const t of Array.from(this.springs.values()).sort((e,t)=>e.id.localeCompare(t.id))){const i=this.bodies.get(t.bodyId);if(!i||i.sleeping)continue;const n="point"===t.target.type?t.target:this.bodies.get(t.target.bodyId);if(!n)continue;const o=n.x-i.x,r=n.y-i.y,s=Math.sqrt(o*o+r*r);if(ye>=s)continue;const a=o/s,c=r/s,d=(s-t.restLength)*t.stiffness+((("vx"in n?n.vx:0)-i.vx)*a+(("vy"in n?n.vy:0)-i.vy)*c)*t.damping;i.vx+=d*a*e/i.mass,i.vy+=d*c*e/i.mass}}resolveBodyPairs(e,t,i){for(const n of t){const[t,o]=n.split(":").map(Number),r=e[t],s=e[o];if(!r||!s)continue;const a=Re(r,s);a&&(this.resolveDynamicCollision(r,s,a),i&&this.lastEvents.push({type:"contact",bodyId:r.id,otherId:s.id,sensor:!1}))}}bodyPairKeys(e){const t=Math.max(1,this.options.cellSize),i=new Map;for(let n=0;e.length>n;n+=1){if(!1===e[n].bodyCollisions)continue;const o=Ie(e[n]),r=Math.floor(o.minX/t),s=Math.floor(o.maxX/t),a=Math.floor(o.minY/t),c=Math.floor(o.maxY/t);for(let e=r;s>=e;e+=1)for(let t=a;c>=t;t+=1){const o=`${e}:${t}`,r=i.get(o);r?r.push(n):i.set(o,[n])}}const n=new Set;for(const t of Array.from(i.keys()).sort()){const o=i.get(t)??[];o.sort((e,t)=>e-t);for(let t=0;o.length>t;t+=1)for(let i=t+1;o.length>i;i+=1){const r=o[t],s=o[i];!1!==e[r].bodyCollisions&&!1!==e[s].bodyCollisions&&Se(Ie(e[r]),Ie(e[s]))&&n.add(`${r}:${s}`)}}return Array.from(n).sort((e,t)=>{const[i,n]=e.split(":").map(Number),[o,r]=t.split(":").map(Number);return i===o?n-r:i-o})}resolveDynamicCollision(e,t,i){e.sleeping&&this.contactOpposesGravity(i.nx,i.ny)&&this.supportedThisStep.add(t.id),t.sleeping&&this.contactOpposesGravity(-i.nx,-i.ny)&&this.supportedThisStep.add(e.id);const n=e.sleeping?0:1/e.mass,o=t.sleeping?0:1/t.mass,r=n+o;if(ye>=r)return;const s=Math.max(0,i.penetration-fe)/r;e.x-=i.nx*s*n,e.y-=i.ny*s*n,t.x+=i.nx*s*o,t.y+=i.ny*s*o;const a=(t.vx-e.vx)*i.nx+(t.vy-e.vy)*i.ny;if(a>0)return;const c=Math.abs(a),d=-(1+xe(e.restitution,t.restitution,this.options.restitution))*a/r,l=d*i.nx,u=d*i.ny;e.vx-=l*n,e.vy-=u*n,t.vx+=l*o,t.vy+=u*o,this.applyFriction(e,t,i,d,n,o),c>this.options.contactWakeSpeed&&(this.wake(e),this.wake(t))}applyFriction(e,t,i,n,o,r){const s=-i.ny,a=i.nx,c=(t.vx-e.vx)*s+(t.vy-e.vy)*a,d=o+r;if(ye>=Math.abs(c)||ye>=d)return;const l=we(e.friction,t.friction,this.options.friction),u=ve(-c/d,-n*l,n*l),h=u*s,p=u*a;e.vx-=h*o,e.vy-=p*o,t.vx+=h*r,t.vy+=p*r}resolveColliders(e,t,i){for(const n of e)for(const e of t){if(!Fe(e,n))continue;if(!Se(Ie(n),Me(e)))continue;const t=Pe(n,e);t&&(this.resolveStaticCollision(n,e,t),this.contactOpposesGravity(t.nx,t.ny)&&this.supportedThisStep.add(n.id),i&&this.lastEvents.push({type:"contact",bodyId:n.id,otherId:e.id,sensor:!1}))}}resolveStaticCollision(e,t,i){e.x+=i.nx*Math.max(0,i.penetration-fe),e.y+=i.ny*Math.max(0,i.penetration-fe);const n=e.vx*i.nx+e.vy*i.ny;if(0>n){const o=xe(e.restitution,t.restitution,this.options.restitution);e.vx-=(1+o)*n*i.nx,e.vy-=(1+o)*n*i.ny;const r=-i.ny,s=i.nx,a=e.vx*r+e.vy*s,c=we(e.friction,t.friction,this.options.friction);e.vx-=a*r*c,e.vy-=a*s*c}}updateSensors(e){const t=new Set,i=this.sortedColliders().filter(e=>e.sensor);for(const n of e){const e=Ie(n);for(const o of i){if(!Fe(o,n))continue;if(!Se(e,Me(o)))continue;if(!Pe(n,o))continue;const i=$e(o.id,n.id);t.add(i),this.activeSensors.has(i)||this.lastEvents.push({type:"sensor-enter",bodyId:n.id,sensorId:o.id})}}for(const e of Array.from(this.activeSensors).sort()){if(t.has(e))continue;const{sensorId:i,bodyId:n}=De(e);this.lastEvents.push({type:"sensor-exit",bodyId:n,sensorId:i})}this.activeSensors=t}updateSleeping(e,t){const i=Math.hypot(this.options.gravity.x,this.options.gravity.y)>1;for(const n of e)Math.sqrt(n.vx*n.vx+n.vy*n.vy)>=this.options.sleepSpeed||Math.sqrt((n.x-n.prevX)*(n.x-n.prevX)+(n.y-n.prevY)*(n.y-n.prevY))>=this.options.sleepSpeed*t||i&&!this.supportedThisStep.has(n.id)?n.sleeping?this.wake(n):n.sleepTime=0:(n.sleepTime+=t,n.sleeping||this.options.sleepAfter>n.sleepTime||(n.sleeping=!0,n.vx=0,n.vy=0,this.lastEvents.push({type:"sleep",bodyId:n.id})))}contactOpposesGravity(e,t){const{x:i,y:n}=this.options.gravity,o=Math.hypot(i,n);return 1e-9>=o||-.2>(e*i+t*n)/o}wake(e){e.sleeping&&this.lastEvents.push({type:"wake",bodyId:e.id}),e.sleeping=!1,e.sleepTime=0}nextRandom(){return this.random()}},qe=class{constructor(e={}){this.id="builtin",this.capabilities={...(new We).capabilities,engine:"builtin"},this.world=new We(e)}init(e={}){this.world.init(e)}spawn(e){this.world.spawn(e)}remove(e){this.world.remove(e)}setColliders(e){this.world.setColliders(e)}setConstraint(e){return this.world.setConstraint(e)}removeConstraint(e){this.world.removeConstraint(e)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i)}step(e){this.world.step(e)}settle(e,t){return this.world.settle(e,t)}readState(e){return this.world.readState(e)}events(){return this.world.events()}activeSensorPairs(){return this.world.activeSensorPairs()}allSleeping(){return this.world.allSleeping()}snapshot(){return this.world.snapshot()}restore(e){this.world.restore(e)}nextRandom(){return this.world.nextRandom()}dispose(){this.world.dispose()}};function ze(e={}){return new qe(e)}function He(e,t={}){return e?"function"==typeof e?e(t):(e.init(t),e):ze(t)}var Le=["binId","targetBin","category","windowIndex","lane","group"];function Ye(e,t){if(!Number.isFinite(t))return;e.count+=1,e.total+=t,e.min=Math.min(e.min,t),e.max=Math.max(e.max,t);const i=t-e.mean;e.mean+=i/e.count,e.m2+=i*(t-e.mean)}function _e(e){return{count:e.count,total:e.total,mean:e.count>0?e.mean:0,min:e.count>0?e.min:0,max:e.count>0?e.max:0,variance:e.count>1?e.m2/(e.count-1):0}}function Xe(e){return{count:e.count,total:e.total,mean:e.mean,m2:e.variance*Math.max(0,e.count-1),min:e.count>0?e.min:1/0,max:e.count>0?e.max:-1/0}}function Ge(e,t){if(null!=e[t])return e[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function Ue(e,t,i){return"function"==typeof e?e(t,i):"string"==typeof e?Ge(t,e):void 0}function Ve(e){if(null==e)return;const t=e+"";return t.trim()?t:void 0}function Ke(e){const t=_e(e.value);return{id:e.id,label:e.label,count:t.count,total:t.total,bodyIds:e.bodyIds.slice(),lastBodyId:e.lastBodyId,lastDatum:e.lastDatum,x:_e(e.x),y:_e(e.y),value:t}}var Qe=class{constructor(e=!1){this.bins=new Map,this.nextIndex=0,this.config=e}updateConfig(e){void 0!==e&&(this.config=e,!1===e&&this.clear())}isEnabled(){return!1!==this.config}add(e){if(!1===this.config)return null;const t=this.nextIndex;this.nextIndex+=1;const i=Ve(Ue(this.config.binAccessor,e,t))??function(e){for(const t of Le){const i=Ve(Ge(e,t));if(i)return i}return"sediment"}(e),n=Ve(Ue(this.config.labelAccessor,e,t))??i,o=function(e,t,i){if("number"==typeof e)return e;const n="function"==typeof e?e(t,i):"string"==typeof e?Ge(t,e):1,o="number"==typeof n?n:Number(n);return Number.isFinite(o)?o:1}(this.config.valueAccessor,e,t),r=Math.max(0,Math.floor(this.config.retainBodyIds??12));let s=this.bins.get(i);return s||(s={id:i,label:n,bodyIds:[],x:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},y:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0},value:{count:0,total:0,mean:0,m2:0,min:1/0,max:-1/0}},this.bins.set(i,s)),s.label=n,s.lastBodyId=e.id,s.lastDatum=e.datum,Ye(s.x,e.x),Ye(s.y,e.y),Ye(s.value,o),r>0&&(s.bodyIds.push(e.id),s.bodyIds.length>r&&(s.bodyIds=s.bodyIds.slice(s.bodyIds.length-r))),Ke(s)}clear(){this.bins.clear(),this.nextIndex=0}snapshot(){return Array.from(this.bins.values()).map(Ke)}restore(e=[]){this.bins.clear();for(const t of e)this.bins.set(t.id,{id:t.id,label:t.label,bodyIds:t.bodyIds.slice(),lastBodyId:t.lastBodyId,lastDatum:t.lastDatum,x:Xe(t.x),y:Xe(t.y),value:Xe(t.value)});this.nextIndex=e.reduce((e,t)=>e+t.count,0)}totals(){const e=this.snapshot();return{bins:e.length,count:e.reduce((e,t)=>e+t.count,0),total:e.reduce((e,t)=>e+t.total,0)}}};function Je(e,t={}){const{baselineY:i=0,binWidth:n=24,gap:o=2,maxHeight:r=80,value:s="count",x:a}=t,c=Math.max(1,...e.map(e=>e[s]));return e.map((e,t)=>{const d=Math.max(0,e[s]/c*r),l=a?.(e,t)??t*(n+o);return{binId:e.id,label:e.label,index:t,count:e.count,total:e.total,x:l,y:i-d,width:n,height:d,meanX:e.x.mean,meanY:e.y.mean}})}function Ze(e){const t=Number(e);if(Number.isFinite(t)&&t>0)return Math.floor(t)}function et(e){const t=Math.max(0,Math.floor(e.liveBodies)),i=Math.max(0,Math.floor(e.queuedBodies??0)),n=t+i,o=Ze(e.bodyLimit),r=Ze(e.engineMaxBodiesHint),s=function(e,t,i){if(!1===i)return;const n=Ze(i?.warnAt);return null!=n?n:null!=e?Math.max(1,Math.floor(.8*e)):null!=t?Math.max(1,Math.floor(.8*t)):void 0}(o,r,e.options),a=null==o?0:Math.max(0,t-o),c=a>0?"overflow":null==s||s>n?"ok":"warning";return{action:"overflow"!==c?"continue":e.sedimentEnabled?"sediment":e.evictionEnabled?"evict":"retain",bodyLimit:o,engineMaxBodiesHint:r,liveBodies:t,overflow:a,projectedBodies:n,queuedBodies:i,state:c,warnAt:s}}var tt={bodyLimit:1/0,eviction:"oldest",fixedDt:1/120,maxDeltaSeconds:.1,maxSubsteps:8,settleStepLimit:1200,timeScale:1},it={chartId:"physics",chartType:"physics",sensors:{},onObservation:void 0,onSimulationStateChange:void 0};function nt(e={},t=it){return{chartId:e.chartId??t.chartId,chartType:e.chartType??t.chartType,sensors:e.sensors??t.sensors,onObservation:e.onObservation??t.onObservation,onSimulationStateChange:e.onSimulationStateChange??t.onSimulationStateChange}}function ot(e){return{...e,shape:{...e.shape},datum:e.datum,springs:e.springs?.map(e=>({...e,target:{...e.target}}))}}function rt(e){if(e instanceof Date){const t=e.getTime();return Number.isFinite(t)?t:void 0}const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function st(e,t){if(null!=e[t])return e[t];const i=e.datum;return i&&"object"==typeof i?i[t]:void 0}function at(e){return{...ot(e),sequence:e.sequence,spawnAt:e.spawnAt}}function ct(e){return e.map(e=>({...e,shape:{...e.shape},bodyFilter:e.bodyFilter&&"function"!=typeof e.bodyFilter?{...e.bodyFilter,oneOf:e.bodyFilter.oneOf?.slice(),notOneOf:e.bodyFilter.notOneOf?.slice()}:e.bodyFilter}))}function dt(e){return!1!==e&&{...e}}function lt(e,t){return e.spawnAt===t.spawnAt?e.sequence-t.sequence:e.spawnAt-t.spawnAt}function ut(e){return{...e,gravity:{...e.gravity}}}function ht(e){return"circle"===e.shape.type?e.shape.radius:Math.hypot(e.shape.width,e.shape.height)/2}function pt(e,t,i,n){if("circle"===e.shape.type){const o=e.x-t,r=e.y-i,s=e.shape.radius+n,a=o*o+r*r;return a>s*s?null:a}const o=Math.max(Math.abs(t-e.x)-e.shape.width/2,0),r=Math.max(Math.abs(i-e.y)-e.shape.height/2,0),s=o*o+r*r;return s>n*n?null:s}function mt(e){const t=e.indexOf("\0");return{sensorId:e.slice(0,t),bodyId:e.slice(t+1)}}function yt(e,t={}){const{idPrefix:i="plot",includeFloor:n=!0,includeCeiling:o=!1,includeLeftWall:r=!0,includeRightWall:s=!0,wallThickness:a=20,floorThickness:c=a}=t,d=[],l=e.x+e.width/2,u=e.y+e.height/2;return n&&d.push({id:i+"-floor",shape:{type:"aabb",x:l,y:e.y+e.height+c/2,width:e.width+2*a,height:c}}),o&&d.push({id:i+"-ceiling",shape:{type:"aabb",x:l,y:e.y-c/2,width:e.width+2*a,height:c}}),r&&d.push({id:i+"-left-wall",shape:{type:"aabb",x:e.x-a/2,y:u,width:a,height:e.height+2*c}}),s&&d.push({id:i+"-right-wall",shape:{type:"aabb",x:e.x+e.width+a/2,y:u,width:a,height:e.height+2*c}}),d}function ft(e){const{idPrefix:t="bin",count:i,domainStart:n,domainStep:o,xScale:r,yTop:s,yBottom:a,wallThickness:c=4,includeBoundaryWalls:d=!0,includeInteriorWalls:l=!0,closedBefore:u,lidY:h=s,lidThickness:p=Math.max(2,c)}=e,m=[],y=s+(a-s)/2,f=Math.abs(a-s),g=d?i:i-1;if(l||d)for(let e=d?0:1;g>=e;e+=1){if(!l&&e>0&&i>e)continue;const s=r(n+e*o);m.push({id:`${t}-wall-${e}`,shape:{type:"aabb",x:s,y:y,width:c,height:f}})}if(null!=u)for(let e=0;i>e;e+=1){const i=n+e*o,s=i+o;if(s>=u)continue;const a=r(i),d=r(s);m.push({id:`${t}-lid-${e}`,shape:{type:"segment",x1:Math.min(a,d)+c/2,y1:h,x2:Math.max(a,d)-c/2,y2:h,thickness:p}})}return m}import{quadtree as gt}from"d3-quadtree";var bt=class{constructor(){this.maxSearchRadius=0,this.revision=-1,this.tree=null}hitTest(e,t,i,n,o,r=0,s){const a=this.ensure(e,t);if(!a)return null;let c=null,d=1/0;const l=Math.max(0,s?.searchRadius??Math.max(0,r)+this.maxSearchRadius),u=n-l,h=n+l,p=o-l,m=o+l;return a.visit((e,t,a,l,y)=>{if(u>l||t>h||p>y||a>m)return!0;if(e.length)return!1;let f=e;for(;f;){const e=f.data;if(e&&(!s?.include||s.include(e))){const t=s?.distanceSquared?s.distanceSquared(e,n,o):pt(e,n,o,Math.max(0,r));null!=t&&(d>t||t===d&&i.indexOf(e.id)>i.indexOf(c?.id??""))&&(c=e,d=t)}f=f.next}return!1}),c}ensure(e,t){if(this.tree&&this.revision===t)return this.tree;const i=e.readState();return 0===i.length?(this.tree=null,this.maxSearchRadius=0,this.revision=t,null):(this.maxSearchRadius=i.reduce((e,t)=>Math.max(e,ht(t)),0),this.tree=gt().x(e=>e.x).y(e=>e.y).addAll(i),this.revision=t,this.tree)}},vt=["data","scene-geometry","data-paint","accessibility","evidence"],xt=["scene-geometry","data-paint","accessibility","evidence"],wt=["overlay","accessibility","evidence"],kt=(e,t)=>({retainedData:e,invalidations:t}),It=["layout","scene-geometry","data-paint","overlay","accessibility","evidence"],Mt=["scene-geometry","data-paint","accessibility","evidence"],St=[],At={engine:kt("rebuild",["scene-geometry","data-paint","accessibility","evidence"]),kernel:kt("preserve",Mt),colliders:kt("preserve",Mt),sediment:kt("preserve",Mt),bodyBudget:kt("preserve",It),bodyLimit:kt("preserve",It),eviction:kt("preserve",It),fixedDt:kt("preserve",St),maxDeltaSeconds:kt("preserve",St),maxSubsteps:kt("preserve",St),settleStepLimit:kt("preserve",St),timeScale:kt("preserve",St),observation:kt("preserve",St)},Ct=kt("preserve",It);function Rt(e){let t="preserve";const i=new Set;for(const n of e){const e=At[n]??Ct;"rebuild"===e.retainedData&&(t="rebuild");for(const t of e.invalidations)i.add(t)}return{retainedData:t,invalidations:i}}var Pt=["seed","fixedDt","cellSize","collisionIterations","velocityDamping","sleepSpeed","sleepAfter","restitution","friction","maxVelocity","contactWakeSpeed"];function $t(e,t){return e===t||!(!e||!t)&&e.gravity?.x===t.gravity?.x&&e.gravity?.y===t.gravity?.y&&Pt.every(i=>e[i]===t[i])}function Dt(e,t,i,n){return e||!t?"paused":i||!n?"running":"settled"}var Bt=class{constructor(){this.seconds=0,this.speed=8,this.scratch=[]}setKernelOptions(e){this.speed=function(e){const t=e?.sleepSpeed;return"number"==typeof t&&Number.isFinite(t)&&t>0?t:8}(e)}reset(){this.seconds=0}isAtRest(){return this.seconds>=.6}refresh(e,t,i){if(i>0)return void(this.seconds=0);const n=e.readState(this.scratch),o=this.speed*this.speed;let r=!0;for(const e of n)if(!e.sleeping&&e.vx*e.vx+e.vy*e.vy>=o){r=!1;break}this.seconds=r?this.seconds+Math.max(0,t):0}},jt=class{constructor(e={}){this.activeSensorPairs=new Set,this.accumulator=0,this.bodyBudgetObservationKey="ok",this.bodySpatialIndex=new bt,this.elapsedSeconds=0,this.liveBodyOrder=[],this.nextSequence=0,this.paused=!1,this.queue=[],this.revision=0,this.updateResults=new b,this.simulationState="settled",this.visible=!0,this.quiescence=new Bt;const{bodyBudget:t,colliders:i,engine:n,kernel:o,observation:r,sediment:s,...a}=e;this.config={...tt,...a},this.configInput={...e},this.bodyBudget=t??{},this.engineInput=n,this.observation=nt(r),this.sediment=new Qe(s??!1),this.world=He(n,{fixedDt:this.config.fixedDt,...o}),this.quiescence.setKernelOptions(o),i&&this.world.setColliders(ct(i))}updateConfig(e){const t=function(e,t){return Object.keys(e).filter(i=>"kernel"===i?!$t(e.kernel,t.kernel):e[i]!==t[i])}(e,this.configInput),{colliders:i,bodyBudget:n,engine:o,kernel:r,observation:s,sediment:a,...c}=e;if(this.config={...this.config,...c},void 0!==n&&(this.bodyBudget=n,!1===n&&(this.bodyBudgetObservationKey="ok")),o&&o!==this.engineInput){const e=this.world.snapshot();this.world.dispose(),this.engineInput=o,this.world=He(o,e.options),this.world.restore(e),this.revision+=1}if(r&&!$t(r,this.configInput.kernel)){const e=this.world.snapshot(),t={...e.options,...r,gravity:{...e.options.gravity,...r.gravity}};this.world.restore({...e,options:t}),this.quiescence.setKernelOptions(t),this.revision+=1}s&&(this.observation=nt(s,this.observation)),this.sediment.updateConfig(a),i&&(this.world.setColliders(ct(i)),this.revision+=1),this.configInput={...this.configInput,...e};const d=Rt(t);this.updateResults.record({kind:"config",keys:t},d.invalidations)}updateConfigWithResult(e){return this.updateConfig(e),this.updateResults.last}setColliders(e){this.world.setColliders(ct(e)),this.revision+=1,this.updateResults.record({kind:"config",keys:["colliders"]},Rt(["colliders"]).invalidations)}enqueue(e,t){const i=Array.isArray(e)?e:[e],n=t?function(e,t={}){const i=rt(t.startAt)??0,n=t.pacing??"immediate";if("arrival"===n){const n=e.map((e,i)=>function(e,t,i){return"function"==typeof i?rt(i(e,t)):"string"==typeof i?rt(st(e,i)):rt(e.spawnAt)??rt(st(e,"arrivalTime"))??rt(st(e,"timestamp"))??rt(st(e,"time"))??rt(st(e,"eventTime"))}(e,i,t.timeAccessor)),o=n.filter(e=>null!=e),r=o.length>0?Math.min(...o):0,s=rt(t.timeScale)??1,a=s>0?s:1;return e.map((e,t)=>{const o=n[t],s=null==o?0:Math.max(0,o-r);return{...ot(e),spawnAt:i+s/a}})}if("object"==typeof n){const t=rt(n.ratePerSec);if(t&&t>0)return e.map((e,n)=>({...ot(e),spawnAt:i+n/t}))}return e.map(e=>({...ot(e),spawnAt:i}))}(i,{...t,startAt:t.startAt??this.elapsedSeconds}):i;for(const e of n)this.queue.push({...ot(e),sequence:this.nextSequence,spawnAt:e.spawnAt??this.elapsedSeconds}),this.nextSequence+=1;this.queue.sort(lt),n.length>0&&(this.revision+=1),this.updateResults.record({kind:"enqueue",count:n.length},n.length?vt:[])}enqueueWithResult(e,t){return this.enqueue(e,t),this.updateResults.last}spawnNow(e){this.spawnOne(ot(e)),this.nextSequence+=1,this.observeBodyBudget(),this.evictOverflow(),this.revision+=1,this.updateResults.record({kind:"enqueue",count:1},vt)}materializeDueSpawns(){const e=this.revision,t=[],i=[];return this.spawnDue(t,i),0===t.length||(this.observeBodyBudget(i),this.evictOverflow(i),this.syncSimulationState(i),this.revision+=1,this.updateResults.record({kind:"enqueue",count:t.length},this.revision!==e?vt:[])),t}clear(){const e=this.world.snapshot().options;this.world.init({...e,fixedDt:this.config.fixedDt}),this.activeSensorPairs.clear(),this.liveBodyOrder=[],this.queue=[],this.accumulator=0,this.elapsedSeconds=0,this.nextSequence=0,this.quiescence.reset(),this.sediment.clear(),this.bodyBudgetObservationKey="ok",this.revision+=1,this.syncSimulationState(),this.updateResults.record({kind:"clear"},vt)}tick(e){const t=this.revision,i=[],n=[],o=[],r=[],s=[];if(this.paused||!this.visible){const e=this.result(0,i,n,o,r,s,!1);return this.updateResults.record({kind:"tick",count:0},[]),e}const a=Math.max(0,Math.min(e,this.config.maxDeltaSeconds))*this.config.timeScale;this.elapsedSeconds+=a,this.spawnDue(i,s);const c=this.observeBodyBudget(s),d=this.evictOverflow(s);n.push(...d.evicted),o.push(...d.sedimented),this.syncSimulationState(s),this.accumulator+=a;let l=0;for(;this.accumulator>=this.config.fixedDt&&this.config.maxSubsteps>l;){this.world.step(this.config.fixedDt);const e=this.world.events();r.push(...e),this.observeKernelEvents(e,s),this.observeSensorTransitions(s),this.accumulator-=this.config.fixedDt,l+=1}l===this.config.maxSubsteps&&(this.accumulator=Math.min(this.accumulator,this.config.fixedDt)),this.quiescence.refresh(this.world,a,i.length),(l>0||i.length>0||n.length>0||o.length>0||r.length>0)&&(this.revision+=1);const u=this.result(l,i,n,o,r,s,void 0,c);return this.updateResults.record({kind:"tick",count:l},this.revision!==t?i.length||n.length||o.length?vt:xt:[]),u}settle(e=this.config.settleStepLimit){return this.runSettle(e,!1).steps}settleWithObservations(e=this.config.settleStepLimit){return this.runSettle(e,!0)}settleHost(){return{fixedDt:this.config.fixedDt,queueSize:()=>this.queue.length,atRest:()=>this.atRest(),advanceTime:e=>{this.elapsedSeconds+=e},spawnDue:(e,t)=>this.spawnDue(e,t),observeBodyBudget:e=>this.observeBodyBudget(e),evictOverflow:e=>this.evictOverflow(e),step:e=>this.world.step(e),drainEvents:()=>this.world.events(),observeKernelEvents:(e,t)=>this.observeKernelEvents(e,t),observeSensorTransitions:e=>this.observeSensorTransitions(e),refreshQuiescence:(e,t)=>this.quiescence.refresh(this.world,e,t)}}runSettle(e,t){const i=this.revision,n=[],o=[],r=[],s=[],a=t?[]:void 0;if(t&&(this.paused||!this.visible)){const e=this.result(0,n,o,r,s,a??[],!1);return this.updateResults.record({kind:"settle",count:0},[]),e}this.spawnDue(n,a);const c=this.observeBodyBudget(a),d=this.evictOverflow(a);o.push(...d.evicted),r.push(...d.sedimented),this.syncSimulationState(a),n.length>0&&this.quiescence.reset();const l=t?{spawned:n,evicted:o,sedimented:r,events:s,observations:a}:{spawned:n},{steps:u,budget:h}=function(e,t,i){let n,o=0;for(;t>o&&(e.queueSize()>0||!e.atRest());){e.advanceTime(e.fixedDt);const t=[];if(e.spawnDue(t,i.observations),t.length>0){i.spawned.push(...t),n=e.observeBodyBudget(i.observations);const o=e.evictOverflow(i.observations);i.evicted?.push(...o.evicted),i.sedimented?.push(...o.sedimented)}e.step(e.fixedDt);const r=e.drainEvents();i.events&&(i.events.push(...r),e.observeKernelEvents(r,i.observations),e.observeSensorTransitions(i.observations)),o+=1,e.refreshQuiescence(e.fixedDt,t.length)}return{steps:o,budget:n}}(this.settleHost(),e,l),p=n.length+o.length+r.length>0;(u>0||p||s.length>0)&&(this.revision+=1);const m=this.result(u,n,o,r,s,a??[],void 0,h??c);return this.updateResults.record({kind:"settle",count:u},this.revision===i?[]:p?vt:xt),m}readBodies(e=[]){return this.world.readState(e)}readSediment(){return this.sediment.snapshot()}bodyBudgetStatus(){return this.evaluateBodyBudget()}sedimentTotals(){return this.sediment.totals()}sedimentHeightfield(e={}){return Je(this.readSediment(),e)}hitTest(e,t,i=0,n){return this.bodySpatialIndex.hitTest(this.world,this.revision,this.liveBodyOrder,e,t,i,n)}events(){return this.world.events()}allSleeping(){return this.world.allSleeping()}atRest(){return this.world.allSleeping()||this.quiescence.isAtRest()}hasPendingWork(){return this.queue.length>0||!this.atRest()}queueSize(){return this.queue.length}liveBodyCount(){return this.liveBodyOrder.length}elapsed(){return this.elapsedSeconds}recordObservation(e){const{timestamp:t,chartType:i,chartId:n,...o}=e,r={...o,timestamp:t??this.elapsedSeconds,chartType:i??this.observation.chartType,chartId:n??this.observation.chartId};return this.emitObservation(r),this.updateResults.record({kind:"update",count:1},["evidence"]),r}getLastUpdateResult(){return this.updateResults.last}getUpdateSnapshot(){return this.updateResults.last}subscribeUpdateResult(e){return this.updateResults.subscribe(e)}version(){return this.revision}setPaused(e){const t=this.paused!==e;this.paused=e,this.syncSimulationState(),this.updateResults.record({kind:"pause"},t?wt:[])}setVisible(e){const t=this.visible!==e;this.visible=e,this.syncSimulationState(),this.updateResults.record({kind:"visibility"},t?wt:[])}remove(e){const t=new Set(e),i=new Set(this.liveBodyOrder),n=new Set(this.queue.map(e=>e.id));this.queue=this.queue.filter(e=>!t.has(e.id)),this.liveBodyOrder=this.liveBodyOrder.filter(e=>!t.has(e)),this.world.remove(e),this.removeActiveSensorPairsForBodies(t);const o=e.filter(e=>i.has(e)||n.has(e));return o.length>0&&(this.revision+=1,this.syncSimulationState()),this.updateResults.record({kind:"remove",keys:o,count:o.length},o.length?vt:[]),o}setConstraint(e){const t=this.world.setConstraint(e);return this.revision+=1,this.updateResults.record({kind:"constraint",keys:[t]},xt),t}removeConstraint(e){this.world.removeConstraint(e),this.revision+=1,this.updateResults.record({kind:"constraint",keys:[e]},xt)}applyImpulse(e,t,i){this.world.applyImpulse(e,t,i),this.revision+=1,this.updateResults.record({kind:"impulse",keys:[e]},xt)}nextRandom(){return this.world.nextRandom()}controls(){return e=this,{applyImpulse:(t,i,n)=>e.applyImpulse(t,i,n),clear:()=>e.clear(),hitTest:(t,i,n)=>e.hitTest(t,i,n),pause:()=>e.setPaused(!0),push:(t,i)=>e.enqueue(t,i),pushMany:(t,i)=>e.enqueue(t,i),bodyBudgetStatus:()=>e.bodyBudgetStatus(),readBodies:t=>e.readBodies(t),readSediment:()=>e.readSediment(),recordObservation:t=>e.recordObservation(t),remove:t=>e.remove(t),restore:t=>e.restore(t),resume:()=>e.setPaused(!1),settle:t=>e.settle(t),settleWithObservations:t=>e.settleWithObservations(t),snapshot:()=>e.snapshot(),sedimentHeightfield:t=>e.sedimentHeightfield(t),sedimentTotals:()=>e.sedimentTotals(),step:t=>e.tick(t)};var e}snapshot(){const e=this.world.snapshot();return{accumulator:this.accumulator,activeSensorPairs:Array.from(this.activeSensorPairs).sort(),bodyBudget:dt(this.bodyBudget),config:{...this.config,kernel:ut(e.options)},elapsedSeconds:this.elapsedSeconds,paused:this.paused,queue:this.queue.map(at),revision:this.revision,sediment:this.readSediment(),simulationState:this.simulationState,liveBodyOrder:this.liveBodyOrder.slice(),visible:this.visible,world:e}}restore(e){this.config={bodyLimit:e.config.bodyLimit,eviction:e.config.eviction,fixedDt:e.config.fixedDt,maxDeltaSeconds:e.config.maxDeltaSeconds,maxSubsteps:e.config.maxSubsteps,settleStepLimit:e.config.settleStepLimit,timeScale:e.config.timeScale},this.configInput={...e.config,bodyBudget:dt(e.bodyBudget??{}),kernel:ut(e.world.options)},this.bodyBudget=dt(e.bodyBudget??{}),this.bodyBudgetObservationKey="ok",this.quiescence.setKernelOptions(e.world.options),this.quiescence.reset(),this.activeSensorPairs=new Set(e.activeSensorPairs),this.accumulator=e.accumulator,this.elapsedSeconds=e.elapsedSeconds,this.paused=e.paused,this.queue=e.queue.map(at).sort(lt),this.revision=e.revision,this.sediment.restore(e.sediment??[]),this.simulationState=e.simulationState??Dt(e.paused,e.visible,e.queue.length>0,e.world.bodies.every(e=>e.sleeping)),this.liveBodyOrder=e.liveBodyOrder.slice(),this.visible=e.visible,this.nextSequence=this.queue.reduce((e,t)=>Math.max(e,t.sequence),-1)+1,this.world.restore(e.world),this.updateResults.record({kind:"restore"},vt)}spawnDue(e,t){for(;this.queue.length>0&&this.elapsedSeconds>=this.queue[0].spawnAt;){const i=this.queue.shift();if(!i)return;this.spawnOne(i,t),e.push(i.id)}}spawnOne(e,t){this.liveBodyOrder=this.liveBodyOrder.filter(t=>t!==e.id),this.removeActiveSensorPairsForBodies(new Set([e.id])),this.world.spawn(e),this.liveBodyOrder.push(e.id);for(const t of e.springs??[])this.world.setConstraint({...t,bodyId:e.id});const i=this.world.readState().find(t=>t.id===e.id);this.emitObservation({type:"physics-spawn",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,bodyId:e.id,datum:i?.datum??e.datum,x:i?.x??e.x,y:i?.y??e.y},t)}result(e,t,i,n,o,r,s,a=this.evaluateBodyBudget()){this.syncSimulationState(r);const c=this.world.allSleeping();return{budget:a,elapsedSeconds:this.elapsedSeconds,evicted:i,events:o,observations:r,queueSize:this.queue.length,revision:this.revision,shouldContinue:s??(this.queue.length>0||!this.atRest()),sleeping:c,sedimented:n,spawned:t,steps:e}}observeKernelEvents(e,t){!function(e,t,i){if(0===t.length)return;const n=new Map(e.readState().map(e=>[e.id,e]));for(const e of t){if("sleep"!==e.type)continue;const t=n.get(e.bodyId);i.emit({type:"physics-settle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:e.bodyId,datum:t?.datum,x:t?.x,y:t?.y})}}(this.world,e,this.observationContext(t))}observeSensorTransitions(e){this.activeSensorPairs=function(e,t,i){const n=new Set(e.activeSensorPairs().map(e=>`${e.sensorId}\0${e.bodyId}`));if(0===n.size&&0===t.size)return n;const o=new Map(e.readState().map(e=>[e.id,e])),r=(e,t)=>{const{sensorId:n,bodyId:r}=mt(t),s=i.observation.sensors[n],a=o.get(r);i.emit({type:"enter"===e?s?.enterType??"physics-bin-enter":s?.exitType??"physics-bin-exit",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,bodyId:r,datum:a?.datum,x:a?.x,y:a?.y,sensorId:n,binId:s?.binId??n})};for(const e of Array.from(n).sort())t.has(e)||r("enter",e);for(const e of Array.from(t).sort())n.has(e)||r("exit",e);return n}(this.world,this.activeSensorPairs,this.observationContext(e))}removeActiveSensorPairsForBodies(e){!function(e,t){for(const i of e)t.has(mt(i).bodyId)&&e.delete(i)}(this.activeSensorPairs,e)}observationContext(e){return{elapsedSeconds:this.elapsedSeconds,observation:this.observation,emit:t=>this.emitObservation(t,e)}}emitObservation(e,t){t?.push(e),this.observation.onObservation?.(e)}evaluateBodyBudget(){return et({bodyLimit:this.config.bodyLimit,engineMaxBodiesHint:this.world.capabilities.maxBodiesHint,evictionEnabled:!1!==this.config.eviction,liveBodies:this.liveBodyOrder.length,queuedBodies:this.queue.length,sedimentEnabled:this.sediment.isEnabled(),options:this.bodyBudget})}observeBodyBudget(e){const t=this.evaluateBodyBudget();if("ok"===t.state||!1===this.bodyBudget)return this.bodyBudgetObservationKey="ok",t;const i=`${t.state}:${t.action}`;return i===this.bodyBudgetObservationKey||(this.bodyBudgetObservationKey=i,this.emitObservation({type:"overflow"===t.state?"physics-budget-overflow":"physics-budget-warning",timestamp:this.elapsedSeconds,chartType:this.observation.chartType,chartId:this.observation.chartId,budgetAction:t.action,bodyLimit:t.bodyLimit,engineMaxBodiesHint:t.engineMaxBodiesHint,liveBodies:t.liveBodies,overflow:t.overflow,projectedBodies:t.projectedBodies,queuedBodies:t.queuedBodies,warnAt:t.warnAt},e)),t}syncSimulationState(e){const t=Dt(this.paused,this.visible,this.queue.length>0,this.atRest());if(t===this.simulationState)return;const i=this.simulationState;this.simulationState=t,function(e,t,i){i.observation.onSimulationStateChange?.(t,e),"running"!==t&&"settled"!==t||i.emit({type:"running"===t?"sim-active":"sim-idle",timestamp:i.elapsedSeconds,chartType:i.observation.chartType,chartId:i.observation.chartId,simulationState:t,previousSimulationState:e})}(i,t,this.observationContext(e))}evictOverflow(e){const{evicted:t,sedimented:i,liveBodyOrder:n}=function(e,t,i,n,o,r){const s={evicted:[],sedimented:[],liveBodyOrder:o};if(!1===i)return s;const a=Math.max(0,Math.floor(n));if(!Number.isFinite(a))return s;const c=o.length-a;if(0>=c)return s;const d=function(e,t,i){if("sleeping-first"!==t)return i.slice();const n=new Map(e.readState().map(e=>[e.id,e.sleeping])),o=[],r=[];for(const e of i)n.get(e)?o.push(e):r.push(e);return[...o,...r]}(e,i,o),l=d.slice(0,c);if(0===l.length)return s;const u=function(e,t,i,n){const o=new Map(e.readState().map(e=>[e.id,e])),r=[];for(const e of i){const i=o.get(e);if(!i)continue;const s=t.add(i);s&&(r.push(e),n.emit({type:"physics-sediment",timestamp:n.elapsedSeconds,chartType:n.observation.chartType,chartId:n.observation.chartId,bodyId:e,datum:i.datum,x:i.x,y:i.y,binId:s.id,count:s.count,total:s.total}))}return r}(e,t,l,r);e.remove(l);const h=new Set(l);return{evicted:l,sedimented:u,liveBodyOrder:o.filter(e=>!h.has(e))}}(this.world,this.sediment,this.config.eviction,this.config.bodyLimit,this.liveBodyOrder,this.observationContext(e));return t.length>0&&(this.liveBodyOrder=n,this.removeActiveSensorPairsForBodies(new Set(t))),{evicted:t,sedimented:i}}};function Tt(e,t){if("function"==typeof t){const i=t(e);return Number.isFinite(i)&&i>0?Number(i):1}const i=e.datum;if(t&&i&&"object"==typeof i){const e=Number(i[t]);if(Number.isFinite(e)&&e>0)return e}const n=Number(i?.work??i?.reviewWork??i?.value);return Number.isFinite(n)&&n>0?n:1}function Ot(e,t){if("function"==typeof t){const i=t(e);if(null!=i&&(i+"").length>0)return i+""}else if(t){const i=Oe(e.datum,t),n=Oe(e,t),o=i??n;if(null!=o&&(o+"").length>0)return o+""}return e.id}function Et(e,t){if(0===e.length)return 0;if(1===e.length)return e[0];const i=Math.max(0,Math.min(1,t))*(e.length-1),n=Math.floor(i);return e[n]+(e[Math.ceil(i)]-e[n])*(i-n)}function Nt(e){const t=e.regionId,i=Math.max(0,e.unitsPerSecond),n=e.queueLayout??"lane",o=e.queueSlotSpacing??14,r=e.queueStiffness??.35,s=Number.isFinite(e.maxQueue)?Math.max(0,Math.floor(Number(e.maxQueue))):1/0,a=Math.max(.25,e.metricWindowSeconds??30),c=Math.max(1/60,e.snapshotIntervalSeconds??.25),d=e.releaseImpulse??{x:90,y:0},l=new Map,u=new Map,h=new Map,p=new Map,m=new Map,y=new Map,f=new Map,g=[];let b=0,v=new Map,x=new Map,w=0,k=0,I=0,M=null,S=0,A=0,C=0,R=0,P=0,$=0,D=0,B=0,j=0,T=0,O=0,E=0,N=-1,F=!1;function W(e,i){const n=i(e);return!!n&&n.activeRegionIds.includes(t)}function q(){E+=1}function z(e){return{bodyId:e.bodyId,jobId:e.jobId,visitId:e.visitId,visit:e.visit,regionId:t,work:e.total,queuedAt:e.queuedAt}}function H(i,n,o,r){const s={bodyId:i.id,jobId:n.jobId,visitId:n.visitId,visit:n.visit,remaining:n.work,total:n.work,queuedAt:n.queuedAt,sequence:r};return l.set(n.jobId,s),f.delete(i.id),y.set(i.id,n.jobId),A+=1,C+=n.work,q(),function(i,n,o){const r=z(n);e.onQueued?.(i,r),o.controls.recordObservation({type:"physics-capacity-queued",bodyId:i.id,datum:i.datum,x:i.x,y:i.y,regionId:t,work:n.total,jobId:n.jobId,visitId:n.visitId,visit:n.visit,queuedAt:n.queuedAt,queueDepth:l.size})}(i,s,o),s}function L(e){if(l.size>=s||0===u.size)return;const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);for(const i of t){if(l.size>=s)break;const t=m.get(i.jobId);t&&h.has(i.jobId)?(u.delete(i.jobId),f.delete(i.bodyId),H(t,i,e,i.sequence)):u.delete(i.jobId)}}function Y(){let e=0;for(const t of l.values())e+=t.remaining;return e}function _(){j=Math.max(j,l.size),T=Math.max(T,Y())}function X(){const e=I-a,t=Math.max(0,Math.min(a,I-(M??I)));let n=0,o=0,r=0,s=0,c=0;for(const t of g){if(e>t.end)continue;n+=t.arrivals,o+=t.arrivalWork,r+=t.completions,s+=t.completedWork;const i=t.end-t.start;c+=i>0&&e>t.start?t.processedWork*Math.min(1,Math.max(0,t.end-e)/i):t.processedWork}const d=t>0?o/t:0;return{seconds:t,arrivals:n,arrivalWork:o,completions:r,completedWork:s,processedWork:c,arrivalsPerSecond:t>0?n/t:0,throughputPerSecond:t>0?r/t:0,utilization:t>0&&i>0?Math.max(0,Math.min(1,c/(i*t))):0,pressure:i>0?d/i:0}}return{id:e.id??"capacity-queue:"+t,continuous:!1!==e.continuous,tick:n=>{const o=n.controls.readBodies(),r=new Map,A=new Map;for(const t of o){if(r.set(t.id,t),!W(t.id,n.getRegionState))continue;if(!Ne(t,e.bodyFilter))continue;const i=Ot(t,e.jobKey),o=A.get(i)??[];o.push(t),A.set(i,o)}const C=Number.isFinite(n.dt)?Math.max(0,n.dt):0;if(!F){const e=Number.isFinite(n.elapsed)?Math.max(0,n.elapsed):C;I=Math.max(0,e-C),F=!0}const j=I,T=j+C;I=T,M=null==M?j:Math.min(M,j);const E={start:j,end:T,arrivals:0,arrivalWork:0,completions:0,completedWork:0,processedWork:0},Y=new Map;for(const[e,t]of A){const i=h.get(e)?.bodyId,n=t.find(e=>e.id===i)??t[0];Y.set(e,n),m.set(e,n)}for(const[i,o]of h){if(Y.has(i))continue;const s=l.get(i),a=r.get(o.bodyId)??m.get(i);if(s){l.delete(i),y.delete(s.bodyId),D+=1,B+=s.remaining,q();const r={...z(s),abandonedAt:I,remainingWork:s.remaining,queueSeconds:Math.max(0,I-s.queuedAt)};a&&e.onAbandoned?.(a,r),n.controls.recordObservation({type:"physics-capacity-abandoned",bodyId:o.bodyId,datum:a?.datum,x:a?.x,y:a?.y,regionId:t,work:s.total,remainingWork:s.remaining,jobId:i,visitId:s.visitId,visit:s.visit,queuedAt:s.queuedAt,abandonedAt:I,queueSeconds:r.queueSeconds,queueDepth:l.size})}u.delete(i),f.delete(o.bodyId),h.delete(i),m.delete(i)}for(const[i,o]of Y){if(h.has(i))continue;const r=(p.get(i)??0)+1;p.set(i,r);const a=Tt(o,e.unitAccessor),c={bodyId:o.id,jobId:i,visitId:`${t}:${i}:${r}`,visit:r,regionId:t,work:a,queuedAt:I};h.set(i,c),S+=1,E.arrivals+=1,E.arrivalWork+=a;const d=b++;if(s>l.size)H(o,c,n,d);else{const s={...c,blockedAt:I,sequence:d};u.set(i,s),f.set(o.id,i),$+=1,q(),e.onBlocked?.(o,s),n.controls.recordObservation({type:"physics-capacity-blocked",bodyId:o.id,datum:o.datum,x:o.x,y:o.y,regionId:t,work:a,jobId:i,visitId:c.visitId,visit:r,queuedAt:I,blockedAt:I,queueDepth:l.size,blockedDepth:u.size})}}L(n),_();const X=Array.from(l.values()).sort((e,t)=>e.sequence-t.sequence);let G=i*C;for(const i of X){if(0>=G)break;const o=Math.min(i.remaining,G);if(i.remaining-=o,G-=o,R+=o,E.processedWork+=o,i.remaining>1e-6)continue;l.delete(i.jobId),y.delete(i.bodyId),k+=1,P+=i.total,E.completions+=1,E.completedWork+=i.total;const s=Math.max(0,I-i.queuedAt);O+=s,q();const a=r.get(i.bodyId);if(!a)continue;n.controls.applyImpulse(i.bodyId,d.x??0,d.y??0);const c={...z(i),completedAt:I,queueSeconds:s};e.onProcessed?.(a,c),n.controls.recordObservation({type:"physics-capacity-processed",bodyId:i.bodyId,datum:a.datum,x:a.x,y:a.y,regionId:t,work:i.total,jobId:i.jobId,visitId:i.visitId,visit:i.visit,queuedAt:i.queuedAt,completedAt:I,queueSeconds:s,queueDepth:l.size})}L(n),_(),function(){const e=Array.from(l.values()).sort((e,t)=>e.sequence-t.sequence);v=new Map(e.map((e,t)=>[e.bodyId,t]));const t=Array.from(u.values()).sort((e,t)=>e.sequence-t.sequence);x=new Map(t.map((e,t)=>[e.bodyId,t])),w=e.length}(),function(e){(e.end>e.start||e.arrivals>0||e.completions>0||e.processedWork>0)&&g.push(e);const t=I-a;for(;g.length>0&&t>g[0].end;)g.shift()}(E);const U=Math.floor(I/c);U!==N&&(N=U,q())},getSnapshot:()=>{const e=Y(),n=function(){let e=0;for(const t of u.values())e+=t.work;return e}(),o=l.size,r=Array.from(l.values()).map(e=>Math.max(0,I-e.queuedAt)).sort((e,t)=>e-t),s=r.reduce((e,t)=>e+t,0);return{regionId:t,queueDepth:o,processedCount:k,unitsPerSecond:i,remainingWork:e,meanRemainingWork:o>0?e/o:0,waitingWork:e+n,blockedDepth:u.size,blockedWork:n,arrivalCount:S,admittedCount:A,admittedWork:C,processedWork:R,completedWork:P,blockedCount:$,abandonedCount:D,abandonedWork:B,peakQueueDepth:j,peakRemainingWork:T,queueAge:{count:r.length,meanSeconds:r.length>0?s/r.length:0,p50Seconds:Et(r,.5),p95Seconds:Et(r,.95),oldestSeconds:r.at(-1)??0},meanCompletedQueueSeconds:k>0?O/k:0,window:X(),simulatedAt:I,metricRevision:E}},bodyForce:e=>{if("none"===n)return null;const i=y.get(e.body.id),s=f.get(e.body.id),a=i?l.get(i):void 0,c=s?u.get(s):void 0;if(!a&&!c)return null;const d=a?v.get(e.body.id):x.get(e.body.id);if(null==d)return null;let h;const p=e.regions;if(p)for(let e=0;p.length>e;e+=1)if(p[e].id===t){const t=p[e].shape;t&&"aabb"===t.type&&(h=t);break}return h?{x:((c?h.x-.44*h.width:h.x-.22*h.width-d*(.15*o))-e.body.x)*r,y:(h.y-(d-((c?u.size:w)-1)/2)*o/Math.max(1,Math.sqrt(c?u.size:w))-e.body.y)*r*.85}:{x:8*-Math.sign(e.body.vx||1),y:0}}}}function Ft(e,t){return e||t?{x:(e?.x??0)+(t?.x??0),y:(e?.y??0)+(t?.y??0)}:null}function Wt(e){if(!e?.length)return null;const t=e.slice(),i=t.some(e=>!1!==e.continuous);return{controllers:t,continuous:i,onTick:(e,i,n)=>{const o={result:e,controls:i,dt:n.dt,elapsed:n.elapsed,getRegionState:n.getRegionState};for(const e of t)e.tick(o)},bodyForce:e=>{let i=null;for(const n of t)n.bodyForce&&(i=Ft(i,n.bodyForce(e)));return i}}}function qt(e){const t=new Set,i=e.impulse??{x:-60,y:0};return{id:e.id??"portal:"+e.fromRegionId,continuous:!0===e.continuous,tick:n=>{const o=n.controls.readBodies();for(const r of o){const o=n.getRegionState(r.id),s=o?.activeRegionIds.includes(e.fromRegionId);s?t.has(r.id)||(t.add(r.id),n.controls.applyImpulse(r.id,i.x??0,i.y??0),e.onPortal?.(r)):t.delete(r.id)}}}}import*as zt from"react";import{forwardRef as Ht,memo as Lt,useCallback as Yt,useEffect as _t,useImperativeHandle as Xt,useId as Gt,useRef as Ut}from"react";var Vt={annotationBackground:"rgba(248, 250, 252, 0.94)",annotationStroke:"#334155",annotationText:"#0f172a",background:"#f8fafc",border:"#334155",closedWindowFill:"rgba(220, 38, 38, 0.08)",closedWindowStroke:"rgba(220, 38, 38, 0.55)",danger:"#dc2626",focus:"#f97316",grid:"#cbd5e1",gutterFill:"rgba(71, 85, 105, 0.14)",lateFill:"#f97316",openWindowFill:"rgba(14, 165, 233, 0.07)",openWindowStroke:"rgba(14, 165, 233, 0.3)",primary:"#0ea5e9",selectedFill:"#f97316",selectedStroke:"#7c2d12",success:"#22c55e",text:"#0f172a",textSecondary:"#475569",warning:"#f97316"},Kt={background:{names:["--semiotic-bg","--surface-1","--surface-0"],fallback:Vt.background},border:{names:["--semiotic-border","--surface-3"],fallback:Vt.border},danger:{names:["--semiotic-danger","--viz-4"],fallback:Vt.danger},focus:{names:["--semiotic-focus","--accent","--viz-9"],fallback:Vt.focus},grid:{names:["--semiotic-grid","--surface-3"],fallback:Vt.grid},primary:{names:["--semiotic-primary","--accent","--viz-5"],fallback:Vt.primary},success:{names:["--semiotic-success","--viz-2"],fallback:Vt.success},text:{names:["--semiotic-text","--text-primary"],fallback:Vt.text},textSecondary:{names:["--semiotic-text-secondary","--text-secondary"],fallback:Vt.textSecondary},warning:{names:["--semiotic-warning","--viz-9","--viz-3"],fallback:Vt.warning}};function Qt(e){const t=Kt[e];return t.names.reduceRight((e,t)=>`var(${t}, ${e})`,t.fallback)}function Jt(e,t,i){if(!t)return i.fallback;for(const n of i.names){const i=t.getPropertyValue(n).trim();if(i)return E(e,i)??i}return i.fallback}function Zt(e,t){const i=Math.max(0,Math.min(1,t)),n=e.trim(),o=n.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);if(o){const[,e,t,n]=o;return Zt(`#${e}${e}${t}${t}${n}${n}`,i)}const r=n.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);if(r){const[,e,t,n]=r;return`rgba(${parseInt(e,16)}, ${parseInt(t,16)}, ${parseInt(n,16)}, ${i})`}const s=n.match(/^rgb\s*\(\s*([^)]+?)\s*\)$/i);if(s)return`rgba(${s[1]}, ${i})`;const a=n.match(/^rgba\s*\(\s*([^,]+,\s*[^,]+,\s*[^,]+),\s*[^)]+\)$/i);return a?`rgba(${a[1]}, ${i})`:n}var ei=2500;function ti(e){return"function"==typeof e}function ii(e){return void 0===e||!1===e||!ti(e.binAccessor)&&!ti(e.labelAccessor)&&!ti(e.valueAccessor)}function ni(e){if(void 0!==e){if(!1===e)return!1;if(!ii(e))throw new TypeError("Physics worker sediment config only supports string or numeric accessors");return{binAccessor:"string"==typeof e.binAccessor?e.binAccessor:void 0,labelAccessor:"string"==typeof e.labelAccessor?e.labelAccessor:void 0,valueAccessor:"string"==typeof e.valueAccessor||"number"==typeof e.valueAccessor?e.valueAccessor:void 0,retainBodyIds:e.retainBodyIds}}}function oi(e){if(e)return{chartId:e.chartId,chartType:e.chartType,sensors:e.sensors}}function ri(e){return function(e){return!ti(e?.timeAccessor)}(e)}function si(e={}){if(e.engine)throw new TypeError("Physics workers use the built-in kernel adapter");const{engine:t,observation:i,sediment:n,...o}=e;return{...o,observation:oi(i),sediment:ni(n)}}function ai(){if("undefined"!=typeof DOMException)return new DOMException("Physics worker request aborted","AbortError");const e=Error("Physics worker request aborted");return e.name="AbortError",e}var ci=class{constructor(e=function(){const e="string"==typeof import.meta.url&&import.meta.url?new URL("./physicsWorker.js",import.meta.url):t("physicsWorker.js");return new Worker(e,{type:"module",name:"semiotic-physics"})}()){this.nextRequestId=1,this.pending=new Map,this.worker=e,this.worker.onmessage=e=>{const t=e.data,i=this.pending.get(t.requestId);i&&(this.pending.delete(t.requestId),i.cleanup(),t.ok?i.resolve(t.payload):i.reject(function(e){const t=Error(e.error.message);return t.name=e.error.name??"Error",e.error.stack&&(t.stack=e.error.stack),t}(t)))},this.worker.onerror=e=>{this.rejectAll(Error(e.message||"Physics worker failed")),this.worker.terminate()}}request(e,t){if(t?.aborted)return Promise.reject(ai());const i=this.nextRequestId;this.nextRequestId+=1;const n={command:e,requestId:i};return new Promise((e,o)=>{const r=()=>{this.pending.delete(i),t?.removeEventListener("abort",r),o(ai())},s=()=>t?.removeEventListener("abort",r);this.pending.set(i,{cleanup:s,reject:o,resolve:e}),t?.addEventListener("abort",r,{once:!0});try{this.worker.postMessage(n)}catch(e){this.pending.delete(i),s(),o(e)}})}async init(e,t,i,n){if(!ri(i))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const o=await this.request({type:"init",config:si(e),initialSpawns:t,initialSpawnPacing:i},n);if("frame"!==o.type)throw Error("Physics worker returned a non-frame init response");return o.frame}async restore(e,t){const i=await this.request({type:"restore",snapshot:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame restore response");return i.frame}async initFromSnapshot(e,t,i){const n=await this.request({type:"init",config:si(e),snapshot:t},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame init response");return n.frame}async enqueue(e,t,i){if(!ri(t))throw new TypeError("Physics worker spawn pacing only supports string time accessors");const n=await this.request({type:"enqueue",spawns:e,pacing:t},i);if("frame"!==n.type)throw Error("Physics worker returned a non-frame enqueue response");return n.frame}async tick(e,t){const i=await this.request({type:"tick",deltaSeconds:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame tick response");return i.frame}async settle(e,t){const i=await this.request({type:"settle",maxSteps:e},t);if("frame"!==i.type)throw Error("Physics worker returned a non-frame settle response");return i.frame}async snapshot(e){const t=await this.request({type:"snapshot"},e);if("snapshot"!==t.type)throw Error("Physics worker returned a non-snapshot response");return t.snapshot}async remove(e,t){const i=await this.request({type:"remove",ids:e},t);if("removed"!==i.type)throw Error("Physics worker returned a non-remove response");return{frame:i.frame,removed:i.removed}}terminate(){this.rejectAll(Error("Physics worker terminated")),this.worker.terminate()}rejectAll(e){for(const[t,i]of this.pending)this.pending.delete(t),i.cleanup(),i.reject(e)}};function di(e,t,i){const n=new jt(e);return t?.length&&(n.enqueue(t,i),n.materializeDueSpawns()),n}function li(){return"undefined"!=typeof performance?performance.now():Date.now()}function ui(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 hi={fill:"#4e79a7",stroke:"#172033",strokeWidth:1,opacity:.85};function pi(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 mi(e,t,i){const n="function"==typeof t?t(e,i):t;return{...hi,...n??{}}}function yi(e,t={}){const i=e.settle(t.maxSteps),n=e.readBodies(),o=e.snapshot(),r=function(e,t={},i="settled"){return e.map((e,n)=>function(e,t={},i={index:0,simulationState:"settled"}){const n=function(e){return e.datum&&"object"==typeof e.datum?e.datum:null}(e),o={label:t.getBodyLabel?.(e)??pi(e)},r={style:mi(e,t.bodyStyle,i),datum:n,accessibleDatum:n,accessibility:o,_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,...r}:{type:"point",x:e.x,y:e.y,r:e.shape.radius,pointId:e.id,...r}}(e,t,{index:n,simulationState:i}))}(n,t,o.simulationState),s=function(e,t={}){const i=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=i.filter(e=>e.sleeping).length,o=e.queue.length,r=e.sediment.reduce((e,t)=>e+t.count,0),s="settled"===e.simulationState&&0===o&&n===i.length,a=[];o>0&&a.push("PHYSICS_QUEUE_UNDRAINED");const c=null!=t.charge&&Number.isFinite(t.charge)?function(e,t,i,n){const o=e-(t+i+n);return{charge:e,live:t,queued:i,sedimented:n,unaccounted:o,balanced:0===o}}(t.charge,i.length,o,r):void 0;return c&&!c.balanced&&a.push("PHYSICS_LEDGER_MISMATCH"),{bodyCount:i.length,sleepingCount:n,settled:s,stepsRun:Math.max(0,Math.floor(t.stepsRun??0)),seed:e.world.options.seed,binCounts:ui(t.projectionRows),queuedCount:o,sedimentedCount:r,...c?{ledger:c}:{},warnings:a}}(o,{bodies:n,projectionRows:t.projectionRows,stepsRun:i,charge:t.charge});return{snapshot:o,bodies:n,sceneNodes:r,evidence:s,stepsRun:i}}import{jsx as fi,jsxs as gi}from"react/jsx-runtime";var bi={top:0,right:0,bottom:0,left:0};function vi(e,t,i){return"function"==typeof e?e({size:t,margin:i}):e}import{jsx as xi}from"react/jsx-runtime";import{useEffect as wi,useRef as ki}from"react";function Ii(){return"undefined"==typeof document||!document.hidden}function Mi(e,t){const i=t.mark;if(i)return i;const n=e.datum,o=n?.__physicsMark??n?.mark;return"circle"===o||"halo"===o||"faceted"===o||"pill"===o||"diamond"===o||"square"===o?o:"circle"===e.shape.type?"circle":"square"}function Si(e,t,i){const n=x(e,i.fill)??"#4e79a7",o=x(e,i.stroke),r="none"!==o?o:void 0,s=i.strokeWidth??0,a=i.opacity??1,c=i.fillOpacity??1,d=Mi(t,i),l="circle"===t.shape.type?i.r??t.shape.radius:Math.max(t.shape.width,t.shape.height)/2;if(e.save(),e.globalAlpha*=a,e.beginPath(),"pill"===d||"square"===d||"aabb"===t.shape.type){const i="pill"===d?2.4*l:"aabb"===t.shape.type?t.shape.width:1.7*l,n="pill"===d?1.35*l:"aabb"===t.shape.type?t.shape.height:1.7*l,o=t.x-i/2,r=t.y-n/2,s="pill"===d?n/2:Math.min(4,i/4);e.moveTo(o+s,r),e.arcTo(o+i,r,o+i,r+n,s),e.arcTo(o+i,r+n,o,r+n,s),e.arcTo(o,r+n,o,r,s),e.arcTo(o,r,o+i,r,s),e.closePath()}else if("diamond"===d)e.moveTo(t.x,t.y-l),e.lineTo(t.x+l,t.y),e.lineTo(t.x,t.y+l),e.lineTo(t.x-l,t.y),e.closePath();else if("faceted"===d){const i=6;for(let n=0;i>n;n+=1){const o=2*Math.PI*n/i-Math.PI/2,r=t.x+Math.cos(o)*l,s=t.y+Math.sin(o)*l;0===n?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}else e.arc(t.x,t.y,l,0,2*Math.PI);n&&(e.save(),e.globalAlpha*=c,e.fillStyle=n,e.fill(),e.restore()),"halo"===d&&(s??1.5)>0&&(e.beginPath(),e.arc(t.x,t.y,1.35*l,0,2*Math.PI),e.strokeStyle=r??n,e.lineWidth=Math.max(1.5,s??1.5),e.globalAlpha*=.55,e.stroke(),e.globalAlpha/=.55),r&&s>0&&(e.strokeStyle=r,e.lineWidth=s,i.strokeDasharray&&e.setLineDash(i.strokeDasharray.split(/[,\s]+/).map(e=>Number(e)).filter(e=>Number.isFinite(e))),e.stroke()),e.restore()}function Ai(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Ci(e,t){return"circle"===e.shape.type?t.r??e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function Ri(e){return e.stroke&&"none"!==e.stroke&&(e.strokeWidth??0)>0?(e.strokeWidth??0)/2:0}function Pi(e){return e.sensorId??"stream-region-"+e.id}function $i(e){const t=Pi(e),i={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("boundary"===e.collider&&"aabb"===e.shape.type){const n=e.colliderThickness??8,o=e.shape.x-e.shape.width/2,r=e.shape.x+e.shape.width/2,s=e.shape.y-e.shape.height/2,a=e.shape.y+e.shape.height/2;return[{...i,id:t+"-top",shape:{type:"segment",x1:o,y1:s,x2:r,y2:s,thickness:n}},{...i,id:t+"-right",shape:{type:"segment",x1:r,y1:s,x2:r,y2:a,thickness:n}},{...i,id:t+"-bottom",shape:{type:"segment",x1:r,y1:a,x2:o,y2:a,thickness:n}},{...i,id:t+"-left",shape:{type:"segment",x1:o,y1:a,x2:o,y2:s,thickness:n}}]}return e.collider?[{...i,id:t+"-collider",shape:e.shape}]:[]}function Di(e){if(e)return{activeRegionIds:Array.from(e.activeRegionIds),regionIds:Array.from(e.regionIds),charges:{...e.charges},attributes:{...e.attributes},energy:e.energy}}function Bi(e,t){const i="function"==typeof e?e(t):e;if(!i)return null;const n=Number(i.x??0),o=Number(i.y??0);return Number.isFinite(n)||Number.isFinite(o)?{x:Number.isFinite(n)?n:0,y:Number.isFinite(o)?o:0}:null}function ji(e){if(!1===e.semanticItem)return null;const t=e.shape,i=e.semanticItem??{},n="aabb"===t.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:t.x,y:t.y,width:t.width,height:t.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2,pathData:`M ${t.x1} ${t.y1} L ${t.x2} ${t.y2}`};return{...n,...i,id:i.id??n.id}}function Ti(e){return e.some(e=>null!=e.force||null!=e.damping||null!=e.impulseOnEnter||null!=e.impulseOnExit)}function Oi(e,t){const i="function"==typeof e?e(t):e;if(!i)return null;const n=Number(i.x??0),o=Number(i.y??0);return Number.isFinite(n)||Number.isFinite(o)?{x:Number.isFinite(n)?n:0,y:Number.isFinite(o)?o:0}:null}var Ei=[];function Ni(e){const t=e.store.controls(),i=e.store.snapshot(),n=Math.max(0,e.result.steps*(i.config.fixedDt||1/60)),o=function(e,t,i,n){const o=Number.isFinite(n)?Math.max(0,n):0;if(0>=o||!Ti(t))return!1;const r=new Map(t.map(e=>[e.id,e])),s=e.readBodies();let a=!1;for(const t of s){const n=i.get(t.id);if(!n||!n.activeRegionIds.size)continue;const s=Di(n);if(s)for(const i of n.activeRegionIds){const n=r.get(i);if(!n)continue;const c=Bi(n.force,{body:t,region:n,regionState:s}),d=Number(n.damping??0),l=(c?.x??0)*o-(Number.isFinite(d)?t.vx*d*o:0),u=(c?.y??0)*o-(Number.isFinite(d)?t.vy*d*o:0);(l||u)&&(e.applyImpulse(t.id,l,u),a=!0)}}return a}(t,e.regionEffects,e.regionState,n),r=function(e,t,i,n,o,r){const s=Number.isFinite(r)?Math.max(0,r):0;if(0>=s||!t)return!1;const a=new Map(i.map(e=>[e.id,e])),c=e.readBodies();let d=!1;for(let i=0;c.length>i;i+=1){const r=c[i],l=n.get(r.id),u=Di(l);let h=Ei;if(l&&l.activeRegionIds.size>0){const e=[];for(const t of l.activeRegionIds){const i=a.get(t);i&&e.push(i)}h=e}const p=Oi(t,{body:r,bodies:c,index:i,regionState:u,regions:h,simulationState:o});if(!p)continue;const m=(p.x??0)*s,y=(p.y??0)*s;(m||y)&&(e.applyImpulse(r.id,m,y),d=!0)}return d}(t,e.bodyForces,e.regionEffects,e.regionState,i.simulationState,n);return e.composed&&e.composed.onTick(e.result,t,{dt:n,elapsed:e.result.elapsedSeconds,getRegionState:t=>Di(e.regionState.get(t))}),e.onTick?.(e.result,t),{regionEffectsApplied:o,bodyForcesApplied:r,snapshot:i}}function Fi(e,t,i,n,o,r,s,a,c,d){const l=function(e,t){return!!t?.isActive&&(t.predicate?.(e)??!0)}(e,o),u={selected:l,simulationState:t,regionState:r,regions:s},h="function"==typeof i?i(e,u):i,p=s.reduce((t,i)=>i.bodyStyle?{...t,..."function"==typeof i.bodyStyle?i.bodyStyle(e,u):i.bodyStyle}:t,{}),m=l?"function"==typeof n?n(e,u):n:void 0;return{fill:d?.color??a,stroke:d?.stroke??c,strokeWidth:d?.strokeWidth??1,opacity:d?.opacity??.9,...h,...p,...m}}import{useCallback as Wi}from"react";function qi(e){return"number"==typeof e&&Number.isFinite(e)?e:void 0}function zi(e,t){const i="sensor"===e.physics?t.sensorThickness:t.barrierThickness;return Math.max(0,qi(e.thickness)??qi(i)??qi(t.thickness)??4)}import*as Hi from"react";import*as Li from"react";import{jsx as Yi,jsxs as _i}from"react/jsx-runtime";var Xi={border:0,clip:"rect(0 0 0 0)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1},Gi="semiotic-accessible-data-table",Ui=Gi+" semiotic-accessible-data-table-hidden",Vi=Gi+" semiotic-accessible-data-table-visible",Ki={boxSizing:"border-box",maxWidth:"100%",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},Qi={position:"absolute",top:0,left:0,right:0,zIndex:"var(--semiotic-data-table-z-index, var(--semiotic-overlay-z-index, 20))",padding:"14px 16px 12px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontFamily:"var(--semiotic-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif)",fontSize:13,lineHeight:1.5,color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",borderRadius:"var(--semiotic-border-radius, 0px) var(--semiotic-border-radius, 0px) 0 0"},Ji={marginBottom:8,paddingRight:28,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:12,letterSpacing:"0.01em"},Zi={position:"absolute",top:10,right:10,width:22,height:22,display:"flex",alignItems:"center",justifyContent:"center",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",cursor:"pointer",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",fontSize:13,lineHeight:1,padding:0,borderRadius:"var(--semiotic-border-radius, 4px)"},en={width:"100%",borderCollapse:"collapse",fontSize:12,marginTop:4,fontVariantNumeric:"tabular-nums"},tn={textAlign:"left",padding:"5px 10px",borderBottom:"2px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",fontWeight:600,fontSize:11,textTransform:"uppercase",letterSpacing:"0.04em",color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))"},nn={padding:"4px 10px",borderBottom:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))"},on={textAlign:"left",fontSize:11,color:"var(--semiotic-data-table-muted-text, var(--semiotic-text-secondary, #666))",marginBottom:4,fontStyle:"italic"},rn={marginTop:8,padding:"4px 10px",fontSize:12,cursor:"pointer",border:"1px solid var(--semiotic-data-table-border, var(--semiotic-border, #e0e0e0))",borderRadius:"var(--semiotic-border-radius, 4px)",background:"var(--semiotic-data-table-bg, var(--semiotic-surface, var(--semiotic-bg, #fff)))",color:"var(--semiotic-data-table-text, var(--semiotic-text, #333))",fontFamily:"inherit"};function sn(e){return null==e?null:"string"==typeof e||"number"==typeof e||"boolean"==typeof e?e+"":null}function an(e){return{__semioticHoverData:!0,body:e,data:e.datum??e,id:e.id,type:"body",x:e.x,y:e.y}}function cn(e){if("circle"===e.shape.type){const t=Math.max(4,2*e.shape.radius);return{height:t,shape:"circle",width:t}}return{height:e.shape.height,shape:"rect",width:e.shape.width}}function dn(e){const t=e.datum;if(t&&"object"==typeof t){const e=t.label??t.name??t.id;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e+""}return e.id}function ln(e){const t=un(e.datum??e);return t.length?t.map(([e,t])=>`${e}: ${t}`).join(", "):"Physics body "+e.id}function un(e){return e&&"object"==typeof e?Object.entries(e).map(([e,t])=>{if(e.startsWith("_"))return null;const i=sn(t);return null==i?null:[e,i]}).filter(e=>null!=e).slice(0,8):[]}function hn({hover:e}){const t=un(e.data);return _i("div",{className:"semiotic-tooltip",style:k,children:[Yi("div",{style:{fontWeight:700,marginBottom:t.length?4:0},children:e.id}),t.map(([e,t])=>_i("div",{children:[_i("span",{style:{opacity:.72},children:[e,": "]}),Yi("span",{children:t})]},e))]})}function pn(e){return e.datum&&"object"==typeof e.datum?Object.entries(e.datum).map(([e,t])=>{const i=sn(t);return null==i?null:`${e}: ${i}`}).filter(e=>null!=e).slice(0,8).join(", "):""}function mn(e){const t=[`${e.length} semantic item${1===e.length?"":"s"}.`],i=new Map;for(const t of e)t.group&&i.set(t.group,(i.get(t.group)??0)+1);return i.size&&t.push(Array.from(i).map(([e,t])=>`${e}: ${t}`).join(", ")),t.join(" ")}function yn(e){const{chartTitle:t,items:i,tableId:n}=e,[o,r]=Li.useState(!1),[s,a]=Li.useState(5),c=_(),d=c?.visible??!1,l=o||d,u=Li.useRef(null),h="Data summary for "+(t??"physics chart");Li.useEffect(()=>{l||a(5)},[l]);const p=Li.useCallback(e=>{e.target===e.currentTarget&&(o||d||r(!0))},[o,d]),m=Li.useCallback(e=>{d||u.current?.contains(e.relatedTarget)||r(!1)},[d]);if(!i.length)return Yi("span",{id:n,tabIndex:-1,style:Xi});if(!l)return Yi("div",{id:n,className:Ui,role:"region","aria-label":h,tabIndex:-1,style:Xi,onFocus:p,children:_i("button",{type:"button",onClick:()=>r(!0),style:Ki,children:["View data summary (",i.length," semantic items)"]})});const y=Math.min(s,i.length),f=i.slice(0,y),g=i.length-y;return _i("div",{ref:u,id:n,className:Vi,role:"region","aria-label":h,tabIndex:-1,onBlur:m,style:Qi,children:[Yi("button",{type:"button",className:"semiotic-accessible-data-table-close","aria-label":"Close data summary",onClick:()=>{d&&c&&c.setVisible(!1),r(!1)},style:Zi,children:"×"}),Yi("div",{className:"semiotic-accessible-data-table-summary",role:"note",style:Ji,children:mn(i)}),_i("table",{className:"semiotic-accessible-data-table-table",role:"table","aria-label":"Semantic items for "+(t??"physics chart"),style:en,children:[Yi("caption",{className:"semiotic-accessible-data-table-caption",style:on,children:g>0?`First ${y} of ${i.length} semantic items`:`All ${i.length} semantic items`}),Yi("thead",{children:_i("tr",{children:[Yi("th",{scope:"col",style:tn,children:"Item"}),Yi("th",{scope:"col",style:tn,children:"Description"}),Yi("th",{scope:"col",style:tn,children:"Group"}),Yi("th",{scope:"col",style:tn,children:"Position"}),Yi("th",{scope:"col",style:tn,children:"Data"})]})}),Yi("tbody",{children:f.map((e,t)=>_i("tr",{children:[Yi("th",{scope:"row",style:nn,children:e.label}),Yi("td",{style:nn,children:e.description??e.label}),Yi("td",{style:nn,children:e.group??""}),_i("td",{style:nn,children:[Math.round(e.x),", ",Math.round(e.y)]}),Yi("td",{style:nn,children:pn(e)})]},e.id??`${e.label}-${t}`))})]}),g>0?_i("button",{type:"button",className:"semiotic-accessible-data-table-show-more",onClick:()=>a(e=>e+25),style:rn,children:["Show ",Math.min(25,g)," more"," ",1===g?"row":"rows"," (",g," remaining)"]}):null]})}function fn(e,t,i,n){i.cursor&&((e.targets??(e.targets=new Map)).set(t.id,i),e.collisionGeometry||(e.collisionGeometry=n),e.maxSearchRadius=Math.max(e.maxSearchRadius,n?ht(t):function(e,t){const i=Mi(e,t),n=Ci(e,t),o=Ri(t);return"pill"===i||"square"===i||"aabb"===e.shape.type?Math.hypot(("pill"===i?2.4*n:"aabb"===e.shape.type?e.shape.width:1.7*n)/2+o,("pill"===i?1.35*n:"aabb"===e.shape.type?e.shape.height:1.7*n)/2+o):"halo"===i&&(t.strokeWidth??0)>0?1.35*n+Math.max(1.5,t.strokeWidth??1.5)/2:n+o}(t,i)))}hn.ownsChrome=!0;import{useCallback as gn,useEffect as bn,useRef as vn,useState as xn}from"react";var wn=new Set(["ArrowRight","ArrowLeft","ArrowUp","ArrowDown","Home","End","PageUp","PageDown"]);import{jsx as kn,jsxs as In}from"react/jsx-runtime";var Mn=[640,360],Sn={top:0,right:0,bottom:0,left:0},An="StreamPhysicsFrame",Cn=Qt("background"),Rn=Qt("primary"),Pn=Qt("text"),$n={stroke:Pn,strokeWidth:2,opacity:1},Dn=Lt(Ht(function(e,t){const{accessibleTable:i=!0,annotations:n,onAnnotationActivate:o,autoPlaceAnnotations:r,background:s,backgroundGraphics:h,backgroundGraphicsBackdrop:p,maxDevicePixelRatio:g,bodySemanticItemLimit:b=200,bodySemanticItems:v=!1,bodySemanticUpdateMs:x=200,bodyForces:w,bodyStyle:k,chartId:I,className:C,frameScheduler:R,clock:$,random:B,seed:j,color:T,config:O,controllers:E,continuous:F=!1,description:W,emphasis:z,chartMode:L,enableHover:Y=!0,foregroundGraphics:_,hoverRadius:V=16,initialSpawns:ee,initialSpawnPacing:te,legend:ie,legendClickBehavior:ne,legendHighlightedCategory:oe,legendHoverBehavior:re,legendIsolatedCategories:ae,legendLayout:ce,legendPosition:de,margin:le,onClick:ue,onObservation:he,onRegionEvent:me,onSimulationExecutionChange:ye,onBodyHover:fe,onBodyPointerDown:ge,onSemanticItemActivate:be,onSemanticItemFocus:ve,onTick:xe,opacity:we,paused:ke=!1,regionEffects:Ie=[],responsiveHeight:Me,responsiveWidth:Se,selectedBodyStyle:Ae=$n,selection:Ce,semanticItems:Re=[],simulationExecution:Pe="auto",size:$e=Mn,stroke:De,strokeWidth:Be,summary:je,suspendWhenHidden:Te=!0,svgAnnotationRules:Oe,title:Ee,tooltipContent:Ne,workerBodyThreshold:Fe=ei,renderBody:We,beforePaint:qe,afterPaint:ze}=e,He=zt.useMemo(()=>({color:T,stroke:De,strokeWidth:Be,opacity:we}),[T,we,De,Be]),Le=Ut(he);Le.current=he;const Ye=Ut(I);Ye.current=I;const _e=Ut(new Map),Xe=Ut(Ie);Xe.current=Ie;const Ge=Ut(w),Ue=Ut(xe);Ue.current=xe;const Ve=zt.useMemo(()=>Wt(E),[E]),Ke=Ut(Ve);Ke.current=Ve;const Qe=F||!!Ve?.continuous,Je=Ut(Qe);Je.current=Qe;const Ze=zt.useMemo(()=>{if(!w&&!Ve?.bodyForce)return w;if(!Ve?.bodyForce)return w;if(!w)return Ve.bodyForce;const e=Ve.bodyForce;return t=>{const i="function"==typeof w?w(t):w,n="function"==typeof e?e(t):e;return i||n?{x:(i?.x??0)+(n?.x??0),y:(i?.y??0)+(n?.y??0)}:null}},[w,Ve]);Ge.current=Ze;const et=zt.useMemo(()=>new Map(Ie.map(e=>[Pi(e),e])),[Ie]),tt=zt.useMemo(()=>new Map(Ie.map(e=>[e.id,e])),[Ie]),it=zt.useMemo(()=>Ie.map(ji).filter(e=>null!=e),[Ie]),[nt,ot]=zt.useState([]),rt=zt.useMemo(()=>nt.length||it.length?[...Re,...nt,...it]:Re,[nt,it,Re]),st=zt.useMemo(()=>Ti(Ie),[Ie]),at=!!Ze,ct=Ut(null),dt=Ut($??li);dt.current=$??li;const lt=Yt((e,t,i)=>{const n=ct.current;if(!n||!i)return!1;const o=n.readBodies().find(t=>t.id===e),r=Di(_e.current.get(e));if(!o||!r)return!1;const s=Bi(i,{body:o,region:t,regionState:r});return!(!s||!s.x&&!s.y||(n.applyImpulse(e,s.x??0,s.y??0),0))},[]),ut=Yt((e,t,i)=>{if(!i.bodyId)return;const n=Di(_e.current.get(i.bodyId));if(!n)return;const o={bodyId:i.bodyId,datum:i.datum,observation:i,region:t,regionState:n,type:e};"region-enter"===e?t.onEnter?.(o):t.onExit?.(o),me?.(o)},[me]),ht=Yt(e=>{const t=e.sensorId?et.get(e.sensorId):void 0;if(!t||!e.bodyId)return;const i=function(e,t){let i=e.get(t);return i||(i={activeRegionIds:new Set,attributes:{},charges:{},energy:0,regionIds:new Set},e.set(t,i)),i}(_e.current,e.bodyId),n=ct.current?.readBodies().find(t=>t.id===e.bodyId),o=Di(i),r=n&&o?{body:n,region:t,regionState:o}:null;if("physics-proximity-enter"===e.type){if(i.activeRegionIds.add(t.id),i.regionIds.add(t.id),i.energy+=t.energyDelta??0,r){!function(e,t,i){const n="function"==typeof e.attributes?e.attributes(t):e.attributes;n&&(i.attributes={...i.attributes,...n})}(t,r,i);const e=function(e,t){return void 0!==e.charge?"function"==typeof e.charge?e.charge(t):e.charge:"charge-gate"===e.kind?1:void 0}(t,r);void 0!==e&&(i.charges[t.id]=e)}lt(e.bodyId,t,t.impulseOnEnter),ut("region-enter",t,e)}else"physics-proximity-exit"===e.type&&(i.activeRegionIds.delete(t.id),lt(e.bodyId,t,t.impulseOnExit),ut("region-exit",t,e))},[lt,ut,et]),mt=Ut(!0),yt=X({sizeProp:$e,responsiveWidth:Se,responsiveHeight:Me,userMargin:le,marginDefault:Sn,legend:ie,legendPosition:de,legendLayout:ce,themeDirtyRef:mt,skipInitialThemeInvalidation:!0,foregroundGraphics:_,backgroundGraphics:h,frameScheduler:R,clock:$,random:B,seed:j,paused:ke,suspendWhenHidden:Te}),{margin:ft,rafRef:gt,reducedMotion:bt,reducedMotionRef:vt,renderFnRef:xt,cancelRender:wt,resolvedBackground:kt,resolvedForeground:It,responsiveRef:Mt,scheduleRender:St,size:At,frameRuntime:Ct}=yt,Rt=At[1],Pt=Math.max(1,At[0]-ft.left-ft.right),$t=Math.max(1,Rt-ft.top-ft.bottom),Dt=zt.useMemo(()=>function({annotations:e,chartId:t,chartType:i,config:n,onRegionObservation:o,regionEffects:r,seed:s,size:a}){const c=function(e=[],t={}){const i=t.idPrefix?t.idPrefix+"-":"",n=[];for(const o of e){if("barrier"!==o.physics&&"sensor"!==o.physics)continue;const e=o.axis??t.defaultAxis??"x",r=zi(o,t),s=o.colliderId??`${i}${o.id}`;let a;if("x"===e){const e=qi(o.x),i=qi(o.y1)??qi(t.plotBounds?.y)??qi(o.y),n=qi(o.y2)??(t.plotBounds?t.plotBounds.y+t.plotBounds.height:void 0)??qi(o.y);if(null==e||null==i||null==n)continue;a={type:"segment",x1:e,y1:i,x2:e,y2:n,thickness:r}}else{const e=qi(o.y),i=qi(o.x1)??qi(t.plotBounds?.x)??qi(o.x),n=qi(o.x2)??(t.plotBounds?t.plotBounds.x+t.plotBounds.width:void 0)??qi(o.x);if(null==e||null==i||null==n)continue;a={type:"segment",x1:i,y1:e,x2:n,y2:e,thickness:r}}n.push({id:s,shape:a,sensor:"sensor"===o.physics,..."barrier"!==o.physics||null==o.restitution&&null==t.barrierRestitution?{}:{restitution:qi(o.restitution)??qi(t.barrierRestitution)},..."barrier"!==o.physics||null==o.friction&&null==t.barrierFriction?{}:{friction:qi(o.friction)??qi(t.barrierFriction)}})}return n}((e??[]).filter(e=>"barrier"===e.physics||"sensor"===e.physics),{idPrefix:t?t+"-ann":"physics-ann",plotBounds:{x:0,y:0,width:a[0],height:a[1]}}),d=void 0===s||void 0!==n?.kernel?.seed?n:{...n,kernel:{...n?.kernel,seed:s}},l=r.flatMap(e=>[{id:Pi(e),sensor:!0,shape:e.shape,bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution},...$i(e)]),u=Object.fromEntries(r.map(e=>[Pi(e),{binId:e.binId??e.id,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),h=d?.observation,p=r.length>0;return p||l.length>0||c.length>0||null!=t||h?{...d,colliders:[...d?.colliders??[],...l,...c],observation:{...h,chartId:t??h?.chartId,chartType:h?.chartType??i,sensors:{...h?.sensors??{},...u},onObservation:e=>{p&&o(e),h?.onObservation?.(e)}}}:d}({annotations:n,chartId:I,chartType:An,config:O,onRegionObservation:ht,regionEffects:Ie,seed:j,size:[Pt,$t]}),[n,I,O,ht,Ie,j,Pt,$t]),Bt=Ut(void 0!==Dt?.colliders);if(!ct.current){const e=di(Dt,ee,te);e.setPaused(ke),Te&&e.setVisible(Ii()),ct.current=e}const jt=Ut(null),Tt=Ut(null);Tt.current||(Tt.current=function(){let e=null,t=-1,i=Vt;return{resolve(n){const o=n.canvas??null,r=M();return o===e&&r===t||(e=o,t=r,i=function(e){const t=e.canvas,i="function"==typeof getComputedStyle&&t?getComputedStyle(t):null,n=Jt(e,i,Kt.primary),o=Jt(e,i,Kt.danger),r=Jt(e,i,Kt.warning),s=Jt(e,i,Kt.success),a=Jt(e,i,Kt.border),c=Jt(e,i,Kt.background),d=Jt(e,i,Kt.text),l=Jt(e,i,Kt.textSecondary),u=Jt(e,i,Kt.focus),h=Jt(e,i,Kt.grid);return{annotationBackground:Zt(c,.94),annotationStroke:a,annotationText:d,background:c,border:a,closedWindowFill:Zt(o,.08),closedWindowStroke:Zt(o,.55),danger:o,focus:u,grid:h,gutterFill:Zt(l,.14),lateFill:r,openWindowFill:Zt(n,.07),openWindowStroke:Zt(n,.3),primary:n,selectedFill:r,selectedStroke:u,success:s,text:d,textSecondary:l,warning:r}}(n)),i},invalidate(){t=-1}}}());const Ot=K("StreamPhysicsFrame"),Et=Ut(""),Nt=Gt().replace(/:/g,""),Ft=Ut(!1),qt=Ut(!1),Ht=Ut(0),Lt=Ut(!1),Qt=Ut(!1),ti=Ut(null),ni=Ut(!1),oi=Ut(Ct.now);oi.current=Ct.now;const si=U(),ai=Q(),ui=Ut(new Map),hi=Nt+"-physics-live",pi=function({onObservationRef:e,chartIdRef:t,wallClockRef:i}){return Wi((n,o)=>{const r=e.current;if(!r)return;const s={timestamp:i.current(),chartType:"StreamPhysicsFrame",chartId:t.current};r("hover"===n||"click"===n?{...s,type:n,datum:o?.datum??{},x:o?.x??0,y:o?.y??0}:"focus"===n?{...s,type:n,datum:o?.datum??{},inputType:"touch"===o?.inputType?"pointer":o?.inputType??"keyboard"}:"activate"===n?{...s,type:n,datum:o?.datum??{},inputType:o?.inputType??"keyboard"}:{...s,type:n})},[t,e,i])}({onObservationRef:Le,chartIdRef:Ye,wallClockRef:dt}),{clearHover:mi,focusedBodyIdRef:Oi,focusedSemanticItem:Ei,handleCanvasPointerDown:Li,hoverData:Yi,onKeyDown:_i,setFocusedSemanticItem:Gi,setHoverData:Ui,syncBodySemanticItems:Vi}=function({allSemanticItems:e,bodySemanticItemLimit:t,bodySemanticItems:i,bodySemanticUpdateMs:n,emitObservation:o,enableHover:r,hoverRadius:s,logicalClockRef:a,onBodyHover:c,onBodyPointerDown:d,onClick:l,onSemanticItemActivate:u,onSemanticItemFocus:h,setBodySemanticItemsSnapshot:p,storeRef:m}){const y=vn(-1),[f,g]=xn(null),[b,v]=xn(null),x=vn(null),w=vn(0),k=gn((e,o,r=!1)=>{if(!i)return void p(e=>e.length?[]:e);const s=a.current();if(!r&&n>0&&n>s-w.current)return;w.current=s;const c=function(e,t,i,n){if(!i)return[];const o=Math.max(0,Math.floor(n));if(!o)return[];const r=[];for(let n=0;e.length>n&&o>r.length;n+=1){const o=e[n],s="function"==typeof i?i(o,{index:n,simulationState:t}):void 0;if(!1===s)continue;const a=cn(o);r.push({datum:o.datum??o,description:ln(o),group:"body",label:dn(o),...a,...s??{},bodyId:s?.bodyId??o.id,id:s?.id??"body:"+o.id,x:s?.x??o.x,y:s?.y??o.y})}return r}(e,o,i,t);p(e=>function(e,t){if(e.length!==t.length)return!0;for(let i=0;e.length>i;i+=1){const n=e[i],o=t[i];if(n.id!==o.id||n.label!==o.label||n.description!==o.description||n.group!==o.group||n.bodyId!==o.bodyId||Math.round(n.x)!==Math.round(o.x)||Math.round(n.y)!==Math.round(o.y))return!0}return!1}(e,c)?c:e)},[t,i,n,a,p]),I=gn(t=>{if(!e.length)return;const i=Math.max(0,Math.min(t,e.length-1));y.current=i;const n=e[i];if(x.current=n.bodyId??null,g(n),h?.(n),n.bodyId&&m.current){const e=m.current.readBodies().find(e=>e.id===n.bodyId);if(e){const t=an(e);v(t),c?.(e,t)}}},[e,c,h,m]),M=gn(()=>{y.current=-1,x.current=null,g(null),h?.(null)},[h]),S=gn(()=>{v(e=>e?(c?.(null,null),o("hover-end"),null):e)},[o,c]),C=gn(e=>{M();const t=m.current,i=e.currentTarget.getBoundingClientRect(),n=e.clientX-i.left,r=e.clientY-i.top,a=t?t.hitTest(n,r,Math.max(16,s)):null;d?.(a,e),a?(o("click",{datum:a.datum,x:a.x,y:a.y}),o("activate",{datum:a.datum,inputType:"touch"===e.pointerType?"touch":"pointer"}),l?.(a.datum??null,{x:a.x,y:a.y,body:a})):(o("click-end"),l?.(null,{x:n,y:r,body:null}),S())},[S,M,o,s,d,l,m]);bn(()=>{if(!e.length)return void M();const t=y.current;if(e.length>t){if(t>=0){const i=e[t];if(x.current=i.bodyId??null,g(e=>null!=e&&e.id===i.id&&Math.round(e.x)===Math.round(i.x)&&Math.round(e.y)===Math.round(i.y)?e:i),i.bodyId&&m.current){const e=m.current.readBodies().find(e=>e.id===i.bodyId);if(e){const t=an(e);v(e=>e?.id===t.id&&Math.round(e.x)===Math.round(t.x)&&Math.round(e.y)===Math.round(t.y)?e:t)}}}}else I(e.length-1)},[e,M,I,m]),bn(()=>{r||S()},[S,r]);const R=gn(t=>{if(A(t)||!e.length)return;if("Escape"===t.key)return t.preventDefault(),void M();if(("Enter"===t.key||" "===t.key)&&y.current>=0){t.preventDefault();const i=e[y.current];return o("activate",{datum:i.datum??{id:i.id,label:i.label},inputType:"keyboard"}),void u?.(i)}if(!wn.has(t.key))return;t.preventDefault();const i=y.current;if(0>i){I(0);const t=e[0];return void o("focus",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"})}const n=Math.max(1,Math.floor(.1*e.length));let r=i;if("Home"===t.key?r=0:"End"===t.key?r=e.length-1:"PageDown"===t.key?r=Math.min(e.length-1,i+n):"PageUp"===t.key?r=Math.max(0,i-n):"ArrowRight"===t.key||"ArrowDown"===t.key?r=Math.min(e.length-1,i+1):"ArrowLeft"!==t.key&&"ArrowUp"!==t.key||(r=Math.max(0,i-1)),I(r),r!==i){const t=e[r];o("focus",{datum:t.datum??{id:t.id,label:t.label},inputType:"keyboard"})}},[e,M,o,I,u]);return{clearHover:S,focusedBodyIdRef:x,focusedSemanticItem:f,handleCanvasPointerDown:C,hoverData:b,onKeyDown:R,setFocusedSemanticItem:g,setHoverData:v,syncBodySemanticItems:k}}({allSemanticItems:rt,bodySemanticItemLimit:b,bodySemanticItems:v,bodySemanticUpdateMs:x,emitObservation:pi,enableHover:Y,hoverRadius:V,logicalClockRef:oi,onBodyHover:fe,onBodyPointerDown:ge,onClick:ue,onSemanticItemActivate:be,onSemanticItemFocus:ve,setBodySemanticItemsSnapshot:ot,storeRef:ct}),[Ki,Qi]=zt.useState([]),Ji=Ut(0),Zi=!!n?.length&&n.some(e=>null!=e.pointId||null!=e.bodyId||"latest"===e.anchor),{canvasRef:en,resolutionDirtyRef:tn}=G(yt,{hydrated:si,wasHydratingFromSSR:ai,storeRef:ct,dirtyRef:mt,manageFrameRuntime:!1,skipInitialCanvasPaintInvalidation:!0,maxDevicePixelRatio:g,canvasPaintDependencies:[s,h,St]}),nn=function({canvasRef:e,clearHover:t,emitObservation:i,enableHover:n,hoverRadius:o,onBodyHover:r,setHoverData:s,storeRef:a}){const c=Hi.useRef({inside:!1,x:0,y:0,pointerType:void 0}),d=Hi.useRef(null);d.current??(d.current={maxSearchRadius:0}),H(e);const l=Hi.useCallback(()=>{const e=d.current;return e.targets?.clear(),e.maxSearchRadius=0,e.collisionGeometry=!1,e},[]),u=Hi.useCallback((e,t,i,n)=>{const o=d.current,r=o.targets;if(!r?.size)return;const s=t.hitTest(i,n,0,{include:e=>r.has(e.id),searchRadius:o.maxSearchRadius,distanceSquared:(e,t,i)=>{const n=r.get(e.id);return n?o.collisionGeometry?pt(e,t,i,0):function(e,t,i,n){const o=Mi(e,t),r=Ci(e,t),s=Ri(t),a=i-e.x,c=n-e.y;let d=!1;if("pill"===o||"square"===o||"aabb"===e.shape.type){const t="pill"===o?2.4*r:"aabb"===e.shape.type?e.shape.width:1.7*r,a="pill"===o?1.35*r:"aabb"===e.shape.type?e.shape.height:1.7*r;d=function(e,t,i,n,o,r,s){const a=n/2+s,c=o/2+s,d=Math.abs(t-e.x),l=Math.abs(i-e.y);if(d>a||l>c)return!1;const u=Math.min(r+s,a,c);if(a-u>=d||c-u>=l)return!0;const h=d-(a-u),p=l-(c-u);return u*u>=h*h+p*p}(e,i,n,t,a,"pill"===o?a/2:Math.min(4,t/4),s)}else if("diamond"===o)d=r+s*Math.SQRT2>=Math.abs(a)+Math.abs(c);else if("faceted"===o)d=function(e,t,i,n){const o=Math.abs(t-e.x),r=Math.abs(i-e.y);return Math.sqrt(3)*n/2>=o&&n>=r&&n-o/Math.sqrt(3)>=r}(e,i,n,r+s);else{const e="halo"===o&&(t.strokeWidth??0)>0?1.35*r+Math.max(1.5,t.strokeWidth??1.5)/2:r+s;d=e*e>=a*a+c*c}return d?a*a+c*c:null}(e,n,t,i):null}});q(e,s?r.get(s.id)?.cursor:void 0)},[]),h=Hi.useCallback(e=>{if(!n&&!d.current?.targets?.size)return;if(!n&&"touch"===e.pointerType)return c.current.inside=!1,void q(e.currentTarget);const l=a.current,h=e.currentTarget.getBoundingClientRect(),p=e.clientX-h.left,m=e.clientY-h.top,y=c.current;if(y.inside=!0,y.x=p,y.y=m,y.pointerType=e.pointerType,!l)return;if("touch"===e.pointerType?q(e.currentTarget):u(e.currentTarget,l,p,m),!n)return;const f=l.hitTest(p,m,o);if(!f)return void t();const g=an(f);s(e=>e?.id===g.id&&e.x===g.x&&e.y===g.y?e:(r?.(f,g),i("hover",{datum:f.datum,x:f.x,y:f.y}),g))},[t,i,n,o,r,u,s,a]),p=Hi.useCallback(e=>{c.current.inside=!1,q(e.currentTarget),t()},[t]),m=Hi.useCallback((e,t,i)=>{const n=c.current;n.inside&&"touch"!==n.pointerType&&i.targets?.size?u(e,t,n.x,n.y):q(e)},[u]);return Hi.useMemo(()=>({begin:l,collect:fn,handlePointerLeave:p,handlePointerMove:h,syncBodyCursors:m}),[l,p,h,m])}({canvasRef:en,clearHover:mi,emitObservation:pi,enableHover:Y,hoverRadius:V,onBodyHover:fe,setHoverData:Ui,storeRef:ct}),on=Yt(()=>{const e=en.current,t=ct.current;if(!e||!t)return;const i=Ot.current.beforeCompute(t.getLastUpdateResult(),!1);tn.current=!1;const n=S(g),o=D(e,At,ft,n);if(!o)return void Ot.current.afterCompute(i,!1,!1);const r=Tt.current.resolve(o),a={theme:r,resolvePaint:(e,t)=>N(o,e,t),withAlpha:Zt};o.clearRect(-ft.left,-ft.top,At[0],At[1]),h||"transparent"===s||(o.fillStyle=null==s?r.background:a.resolvePaint(s,r.background),o.fillRect(-ft.left,-ft.top,At[0],At[1])),o.save(),o.beginPath(),o.rect(0,0,Pt,$t),o.clip();const c=t.snapshot(),d=t.readBodies(),l=nn.begin();if(Vi(d,c.simulationState),Zi){const e=oi.current();if(e-Ji.current>=100){Ji.current=e;const t=se(d);Qi(e=>e.length===t.length&&e.every((e,i)=>e.pointId===t[i].pointId&&Math.round(e.x)===Math.round(t[i].x)&&Math.round(e.y)===Math.round(t[i].y))?e:t)}}qe&&(o.save(),qe(o,d,a),o.restore());for(const e of d){const t=_e.current.get(e.id),i=t?Array.from(t.activeRegionIds).map(e=>tt.get(e)).filter(e=>null!=e):[],n=Fi(e,c.simulationState,k,Ae,Ce,Di(t),i,r.primary,r.text,He);nn.collect(l,e,n,!!We),We?(o.save(),We(o,e,n,a),o.restore()):Si(o,e,n)}nn.syncBodyCursors(e,t,l),ze&&(o.save(),ze(o,d,a),o.restore()),function(e,t,i){let n=!1;for(const[o,r]of t){const s=Math.min(1,Math.max(0,(i-r.startedAt)/r.durationMs));if(s>=1){t.delete(o);continue}n=!0;const a=1-Math.pow(1-s,3),{body:c}=r,d=r.scale>0?r.scale:1,l=(r.radius+28*a)*d,u=1-s;e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.fillStyle=r.color,e.lineWidth=Math.max(.5,(2.4*u+.4)*d),e.beginPath(),e.arc(c.x,c.y,l,0,2*Math.PI),e.stroke(),e.globalAlpha*=.18,e.beginPath(),e.arc(c.x,c.y,.52*l,0,2*Math.PI),e.fill(),e.restore(),e.save(),e.globalAlpha*=u,e.strokeStyle=r.color,e.lineWidth=Math.max(.5,1.8*d);for(let t=0;8>t;t+=1){const i=t*(Math.PI/4)+1.4*s,n=(r.radius+5+12*a)*d,o=(r.radius+12+34*a)*d;e.beginPath(),e.moveTo(c.x+Math.cos(i)*n,c.y+Math.sin(i)*n),e.lineTo(c.x+Math.cos(i)*o,c.y+Math.sin(i)*o),e.stroke()}e.restore()}}(o,ui.current,oi.current()),o.restore(),Ot.current.afterCompute(i,!0,!1),mt.current=!1},[en,tn,Ot,At,ft,Pt,$t,h,s,g,Vi,Zi,qe,ze,k,Ae,Ce,He,We,tt,nn]),rn=Yt((e,t)=>{const i=ct.current,n=`${Pe}:${e}:${t??""}`;Et.current!==n&&(Et.current=n,ye?.({execution:e,liveBodies:i?.liveBodyCount()??0,queuedBodies:i?.queueSize()??0,reason:t,requested:Pe}))},[ye,Pe]),sn=Yt((e,t=!0)=>{Ht.current+=1,Ft.current=!1,Lt.current=!1,Qt.current=!1,ni.current=!1,ti.current?.terminate(),ti.current=null,t&&rn("sync",e)},[rn]),un=Yt(()=>si?"undefined"==typeof window||"undefined"==typeof Worker?"worker unavailable":st?"runtime region effects require sync":at?"body forces require sync":Ve?"physics controllers require sync":function(e){return!e||!e.engine&&ii(e.sediment)&&(!(t=e.colliders)||t.every(e=>{const t=e.bodyFilter;return!t||"function"!=typeof t}));var t}(Dt??{})?ri(te)?qt.current?"worker fallback":null:"spawn pacing is not worker-cloneable":"config is not worker-cloneable":"hydrating",[Dt,Ve,at,st,si,te]),pn=Yt(()=>{const e=ct.current,t=un();if(!e||t)return{reason:t,useWorker:!1};const i=e.liveBodyCount(),n=e.queueSize(),o=function(e,t,i=0,n=ei){return"sync"!==e&&("worker"===e||t+i>=n)}(Pe,i,n,Fe);return{reason:o?"worker"===Pe?"forced worker":"body threshold":"below threshold",useWorker:o}},[Pe,Fe,un]),mn=Yt(e=>{const t=ct.current;return t&&e.snapshot?(t.restore(e.snapshot),mt.current=!0,t):t},[]),Dn=Yt((e,t=!0)=>{const i=mn(e);if(!i)return;t&&xe?.(e.result,i.controls()),on();const n=i.snapshot();!e.result.shouldContinue&&ui.current.size<=0||n.paused||!n.visible||vt.current||St()},[mn,xe,on,vt,St]),Bn=Yt(e=>{qt.current=!0,sn("worker failed: "+((e instanceof Error?e.message:e+"")||"unknown error"))},[sn]),jn=Yt(()=>{const e=ct.current;if(!e)return!1;const t=pn();if(!t.useWorker)return Ft.current||ni.current?sn(t.reason??"sync fallback"):rn("sync",t.reason??"sync"),!1;if(Ft.current||ni.current)return!0;const i=ti.current??new ci;ti.current=i,ni.current=!0;const n=Ht.current+1;return Ht.current=n,i.initFromSnapshot(Dt??{},e.snapshot()).then(e=>{if(Ht.current!==n)return;ni.current=!1,Ft.current=!0,qt.current=!1,mn(e),rn("worker",t.reason??"worker"),on();const i=ct.current?.snapshot();e.result.shouldContinue&&i&&!i.paused&&i.visible&&!vt.current&&(jt.current=null,St())}).catch(e=>{Ht.current===n&&Bn(e)}),!0},[mn,Dt,Bn,on,vt,rn,St,sn,pn]),Tn=Yt(e=>"frame"===e.type||"removed"===e.type?e.frame:null,[]),On=Yt((e,t=!0)=>{const i=ti.current;if(!i||!Ft.current)return;const n=Ht.current;i.request(e).then(e=>{if(Ht.current!==n)return;const i=Tn(e);i&&Dn(i,t)}).catch(Bn)},[Dn,Tn,Bn]),En=Yt(()=>{const e=ct.current;if(!e)return;const t=jn(),i=e.snapshot(),n=Qe||at||st||!!Ve;i.paused||!i.visible||!e.hasPendingWork()&&!n||vt.current?xt.current():t&&ni.current||St()},[Ve,Qe,at,st,vt,xt,St,jn]),Nn=Yt(()=>{wt(),gt.current=null;const e=ct.current;if(!e)return;const t=vt.current;if(t&&(jt.current=null),Ft.current&&ti.current){if(Lt.current)return void(Qt.current=!0);let i=0;if(!t){const e=oi.current();i=null!==jt.current?(e-jt.current)/1e3:0,jt.current=e}const n=ti.current,o=Ht.current;return Lt.current=!0,void(t?n.settle():n.tick(i)).then(e=>{Lt.current=!1;const t=Qt.current;Qt.current=!1,Ht.current===o&&(Dn(e),t&&En())}).catch(n=>{Lt.current=!1;const r=Qt.current;if(Qt.current=!1,Ht.current!==o)return;Bn(n);const s=t?e.settleWithObservations():e.tick(i);Ni({store:e,result:s,regionEffects:Xe.current,regionState:_e.current,bodyForces:Ge.current,composed:Ke.current,onTick:Ue.current}),on(),r&&En()})}const i=Ke.current,n=t=>Ni({store:e,result:t,composed:i,regionEffects:Xe.current,regionState:_e.current,bodyForces:Ge.current,onTick:Ue.current});let o;if(t)o=function(e,t,i=4){let n,o=!1,r=!1,s=0;do{const i=e.settleWithObservations(),a=t(i);o=o||a.regionEffectsApplied,r=r||a.bodyForcesApplied,n={...a,regionEffectsApplied:o,bodyForcesApplied:r,result:i},s+=1}while(i>s&&e.hasPendingWork());return n}(e,n);else{const t=oi.current(),i=jt.current;jt.current=t;const r=e.tick(null===i?0:(t-i)/1e3);o={...n(r),result:r}}const{result:r,regionEffectsApplied:s,bodyForcesApplied:a,snapshot:c}=o;on(),(Je.current||r.shouldContinue||s||a||i||ui.current.size>0)&&!c.paused&&c.visible&&!vt.current&&St()},[Dn,Bn,on,wt,En,St,vt,gt]);xt.current=Nn,_t(()=>{qt.current=!1,(Ft.current||ni.current)&&sn("config changed",!1);const e=ct.current;e?.updateConfig(Dt??{}),e&&void 0===Dt?.colliders&&Bt.current&&e.setColliders([]),Bt.current=void 0!==Dt?.colliders,En()},[Dt,sn]),_t(()=>{qt.current=!1,En()},[si,Pe,Fe]),_t(()=>{En()},[bt,En]),function({cancelRender:e,frameRuntime:t,lastFrameTimeRef:i,paused:n,postWorkerCommand:o,requestRender:r,storeRef:s,suspendWhenHidden:a}){const c=ki(o);c.current=o;const d=ki(r);d.current=r,wi(()=>{const o=s.current;o&&(t.setPaused(n),o.setPaused(n),n&&(i.current=null,e()),c.current({type:"setPaused",paused:n},!1),d.current())},[e,t,n]),wi(()=>{if(!a){const e=s.current;return t.setVisible(!0),void(e&&!e.snapshot().visible&&(e.setVisible(!0),c.current({type:"setVisible",visible:!0},!1),d.current()))}if("undefined"==typeof document)return;const n=()=>{const n=s.current;if(!n)return;const o=Ii();t.setVisible(o),n.setVisible(o),o||(i.current=null,e()),c.current({type:"setVisible",visible:o},!1),d.current()};return n(),document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[e,t,a])}({cancelRender:wt,frameRuntime:Ct,lastFrameTimeRef:jt,paused:ke,postWorkerCommand:On,requestRender:En,storeRef:ct,suspendWhenHidden:Te}),_t(()=>()=>sn("unmount",!1),[sn]),_t(()=>{on()},[on]),Xt(t,()=>({...ct.current.controls(),applyImpulse:(e,t,i)=>{ct.current.applyImpulse(e,t,i),On({type:"applyImpulse",id:e,ix:t,iy:i}),En()},clear:()=>{ct.current.clear(),_e.current.clear(),ui.current.clear(),On({type:"clear"}),En()},clearRegionState:e=>{e?_e.current.delete(e):_e.current.clear(),En()},getData:()=>ct.current.readBodies(),getRegionState:e=>e?Di(_e.current.get(e)):function(e){const t={};return e.forEach((e,i)=>{const n=Di(e);n&&Object.defineProperty(t,i,{configurable:!0,enumerable:!0,writable:!0,value:n})}),t}(_e.current),getStore:()=>ct.current,pause:()=>{Ct.setPaused(!0),jt.current=null,wt(),ct.current.setPaused(!0),On({type:"setPaused",paused:!0},!1),En()},push:(e,t)=>{ct.current.enqueue(e,t),ri(t)?On({type:"enqueue",spawns:[e],pacing:t}):(Ft.current||ni.current)&&sn("spawn pacing is not worker-cloneable"),En()},pushMany:(e,t)=>{ct.current.enqueue(e,t),ri(t)?On({type:"enqueue",spawns:e,pacing:t}):(Ft.current||ni.current)&&sn("spawn pacing is not worker-cloneable"),En()},popBodies:(e,t={})=>{const i=ct.current,n=new Map(i.readBodies().map(e=>[e.id,e])),o=i.remove(e),r=oi.current();for(const e of o){const i=n.get(e);i&&(_e.current.delete(e),ui.current.set(e,{body:i,color:t.color??"#f59e0b",durationMs:Math.max(120,t.durationMs??520),radius:t.radius??Ai(i),scale:null!=t.scale&&t.scale>0?t.scale:1,startedAt:r}),Oi.current===e&&(Oi.current=null,Gi(null)),Ui(t=>t?.id===e?null:t))}return o.length&&(On({type:"remove",ids:o}),En()),o},remove:e=>{const t=ct.current.remove(e);for(const t of e)_e.current.delete(t);return On({type:"remove",ids:e}),En(),t},restore:e=>{ct.current.restore(e),_e.current.clear(),ui.current.clear(),On({type:"restore",snapshot:e},!1),En()},resume:()=>{Ct.setPaused(!1),jt.current=null,ct.current.setPaused(!1),On({type:"setPaused",paused:!1},!1),En()},settle:e=>{const t=ct.current.settle(e);return On({type:"settle",maxSteps:e}),En(),t},settleWithObservations:e=>{const t=ct.current.settleWithObservations(e);return On({type:"settle",maxSteps:e}),En(),t},step:e=>{const t=ct.current,i=t.tick(e);return Ni({store:t,result:i,regionEffects:Xe.current,regionState:_e.current,bodyForces:Ge.current,composed:Ke.current,onTick:Ue.current}),On({type:"tick",deltaSeconds:e}),on(),i}}),[wt,Oi,Ct,on,On,En,Gi,Ui,sn]);const Fn=P||!si&&ai,Wn=["stream-physics-frame",L?"stream-physics-frame--mode-"+L:null,z?"stream-physics-frame--emphasis-"+z:null,C].filter(Boolean).join(" "),qn=W??("string"==typeof Ee?Ee:void 0)??"Physics chart",zn=Nt+"-physics-table",Hn=Y&&Yi?Ne?Ne(Yi):kn(hn,{hover:Yi}):null,Ln=Hn&&Yi?kn(l,{x:Yi.x-ft.left,y:Yi.y-ft.top,containerWidth:Pt,containerHeight:$t,margin:ft,className:"stream-physics-tooltip",children:Hn}):null;if(Fn){const t=ct.current??di(Dt,ee,te),i="string"==typeof Ee?Ee:void 0,n=(e,t)=>{const i=_e.current.get(e.id),n=i?Array.from(i.activeRegionIds).map(e=>tt.get(e)).filter(e=>null!=e):[];return Fi(e,t.simulationState,k,Ae,Ce,Di(i),n,Rn,Pn,He)},{element:o}=function(e,t={}){const{width:i=640,height:n=360,title:o,description:r,background:s,backgroundGraphics:a,backgroundGraphicsBackdrop:c,className:d,foregroundGraphics:l,idPrefix:u="physics",margin:h,style:p,renderBodySVG:m,renderChrome:y,...f}=t,g=yi(e,f),b={...bi,...h},v=[i,n],x=vi(a,v,b),w=vi(l,v,b),k=function(e){const t=e.replace(/[^A-Za-z0-9_-]/g,"_");return!t||/^\d/.test(t)?"physics-"+t:t}(u),I=o?k+"-title":void 0,M=r?k+"-desc":void 0,S=[I,M].filter(Boolean).join(" ")||void 0,A=b.left||b.top?`translate(${b.left},${b.top})`:void 0,C=Math.max(1,i-b.left-b.right),R=Math.max(1,n-b.top-b.bottom),P=k+"-plot-clip",$=A&&null!=x?fi("g",{transform:A,children:x}):x;return{element:gi("svg",{xmlns:"http://www.w3.org/2000/svg",className:d??"stream-physics-frame",width:i,height:n,viewBox:`0 0 ${i} ${n}`,role:"img","aria-labelledby":S,style:p,children:[o&&fi("title",{id:I,children:o}),r&&fi("desc",{id:M,children:r}),fi("defs",{children:fi("clipPath",{id:P,children:fi("rect",{width:C,height:R})})}),c&&"transparent"!==c?fi("rect",{className:"stream-frame-background__backdrop",x:0,y:0,width:i,height:n,fill:c}):null,!a&&s&&"transparent"!==s?fi("rect",{x:0,y:0,width:i,height:n,fill:s}):null,$,fi("g",{id:k+"-data-area",transform:A,clipPath:`url(#${P})`,children:g.sceneNodes.map((e,t)=>{const i=g.bodies[t],n=i&&m?m(i,e.style??{},t,k):void 0;return null!=n?J(n,e,t):Z(e,t,k)})}),w,y?.(g)]}),scene:g,evidence:g.evidence}}(t,{width:At[0],height:At[1],title:i,description:W,background:h||"transparent"===s?void 0:s??Cn,backgroundGraphics:kt,backgroundGraphicsBackdrop:p,className:"stream-physics-frame__svg",foregroundGraphics:It,idPrefix:"physics-"+Nt,margin:ft,bodyStyle:n,renderChrome:t=>function(e,t,i,n,o="StreamPhysicsFrame"){return xi(pe,{width:Math.max(1,i[0]-n.left-n.right),height:Math.max(1,i[1]-n.top-n.bottom),totalWidth:i[0],totalHeight:i[1],margin:n,title:t.title,legend:t.legend,legendPosition:t.legendPosition,legendLayout:t.legendLayout,legendHoverBehavior:t.legendHoverBehavior,legendClickBehavior:t.legendClickBehavior,legendHighlightedCategory:t.legendHighlightedCategory,legendIsolatedCategories:t.legendIsolatedCategories,pointNodes:se(e.bodies),annotations:t.annotations,onAnnotationActivate:t.onAnnotationActivate,onObservation:t.onObservation,chartId:t.chartId,chartType:o,autoPlaceAnnotations:t.autoPlaceAnnotations,svgAnnotationRules:t.svgAnnotationRules})}(t,e,At,ft,An)});return In("div",{ref:Mt,className:Wn,"data-semiotic-mode":L,role:"img","aria-label":qn,style:{width:Se?"100%":At[0],height:Me?"100%":At[1]},children:[kn(y,{summary:je}),o]})}return In("div",{ref:Mt,className:Wn,"data-semiotic-mode":L,role:"group","aria-label":qn,"aria-describedby":Ei?hi:void 0,tabIndex:0,style:{position:"relative",width:Se?"100%":At[0],height:Me?"100%":At[1]},onKeyDown:_i,children:["production"!==process.env.NODE_ENV&&ct.current&&kn(m,{store:ct.current,diagnostics:Ot.current}),i?In(a,{accessibleTable:i,children:[kn(f,{tableId:zn}),kn(yn,{chartTitle:"string"==typeof Ee?Ee:qn,items:rt,tableId:zn})]}):null,kn(y,{summary:je}),kn(c,{hoverPoint:Yi}),kn("div",{id:hi,"aria-live":"polite","aria-atomic":"true",style:Xi,children:Ei?Ei.description??Ei.label:""}),In("div",{role:"img","aria-label":qn,style:{position:"relative",width:"100%",height:"100%"},children:[kn(d,{size:At,margin:ft,backdropFill:p,children:kt}),kn("canvas",{ref:en,width:At[0],height:At[1],"aria-hidden":"true",style:{position:"absolute",left:0,top:0,display:"block"},onPointerDown:Li,onPointerMove:nn.handlePointerMove,onPointerLeave:nn.handlePointerLeave}),It,kn(pe,{width:Pt,height:$t,totalWidth:At[0],totalHeight:At[1],margin:ft,title:Ee,legend:ie,legendPosition:de,legendLayout:ce,legendHoverBehavior:re,legendClickBehavior:ne,legendHighlightedCategory:oe,legendIsolatedCategories:ae,pointNodes:Ki,annotations:n,onAnnotationActivate:o,onObservation:he,chartId:I,chartType:An,autoPlaceAnnotations:r,svgAnnotationRules:Oe}),kn(u,{active:null!=Ei,hoverPoint:Ei?{x:Ei.x,y:Ei.y}:null,margin:ft,size:At,shape:Ei?.shape,width:Ei?.width,height:Ei?.height,pathData:Ei?.pathData}),Ln]})]})}));Dn.displayName="StreamPhysicsFrame";var Bn=Dn;import{scaleLinear as jn}from"d3-scale";function Tn(e){const[t,i]=e,n=160>t||116>i,o=n?Math.min(12,Math.max(2,.08*t)):32,r=n?Math.min(8,Math.max(2,.12*i)):24,s=n?r:34;return{width:t,height:i,plot:{x:o,y:r,width:Math.max(1,t-2*o),height:Math.max(1,i-r-s)}}}function On(e){const t=(e??"")+"";if(!t)return"#4e79a7";const i=["#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 i[n%i.length]}function En(e,t){return t?(i,n)=>({..."function"==typeof e?e(i,n):e,..."function"==typeof t?t(i,n):t}):e}function Nn(e,t="#4e79a7",o){const r=o?.styleRules,s=!!r&&r.length>0,a=s?i(o?.valueAccessor):void 0;return i=>{const o=i.datum,c=o&&e?"function"==typeof e?e(o,0):o[e]:void 0,d={fill:null==c?t:On(c),stroke:"#111827",strokeWidth:1,opacity:.9};return s&&o&&Object.assign(d,n(o,r,{value:a?a(o):void 0,category:null==c?void 0:c+""})),d}}function Fn(e,t,i,n){return{fixedDt:1/120,maxSubsteps:8,colliders:t,observation:{chartType:i},kernel:{seed:e,gravity:{x:0,y:760},cellSize:36,collisionIterations:6,velocityDamping:.995,restitution:.08,friction:.4,sleepSpeed:8,sleepAfter:.6,...n}}}function Wn(e,t,i){if(!e.length)return[];const n=Tn(t),o=n.plot.width/Math.max(1,e.length),r=Math.max(1,...e.map(e=>e.value)),s=.62*n.plot.height,a=n.plot.y+n.plot.height;return e.map((e,t)=>{const c=Math.max(8,e.value/r*s),d=`${i} ${e.label}: ${e.value}${null==e.secondary?"":`, ${e.secondary} secondary`}`;return{id:`${i}-${e.label}`,label:d,description:d,datum:e,x:n.plot.x+(t+.5)*o,y:a-c/2,shape:"rect",width:Math.max(12,.58*o),height:c,group:i}})}function qn(e,t,i){return"function"==typeof i?i(e,t):e[i]}function zn(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 Hn(e,t,i){return Math.max(t,Math.min(i,e))}function Ln(e,t){const i=zn(e);return null!=i&&i>0?i:t}function Yn(e){return((e??"unknown")+"").trim().replace(/[^A-Za-z0-9_-]+/g,"_")||"unknown"}function _n(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}}function Xn(e){const{data:t,valueAccessor:i,bins:n,ballRadius:o,seed:r,size:s,valueExtent:a}=e,c=Tn(s),d=t.map((e,t)=>zn(qn(e,t,i))).filter(e=>null!=e),l=function(e){if(!e)return;const t=zn(e[0]),i=zn(e[1]);return null!=t&&null!=i?t>i?[i,t]:[t,i]:void 0}(a),u=l?.[0]??(d.length?Math.min(...d):0),h=l?.[1]??(d.length?Math.max(...d):1),p=h===u?1:h-u,m=jn().domain([0,n]).range([c.plot.x,c.plot.x+c.plot.width]),y=Array.from({length:n},()=>0),f=[];t.forEach((e,t)=>{const r=zn(qn(e,t,i));if(null==r)return;const s=Math.max(0,Math.min(n-1,Math.floor((r-u)/p*n)));y[s]+=1,f.push({id:(e.id??"galton-"+t)+"",x:m(s+.5),y:c.plot.y+o+2,vx:8*(t%5-2),vy:0,mass:1,shape:{type:"circle",radius:o},datum:{...e,value:r,bin:s}})});const g=c.plot.y+c.plot.height;return{config:Fn(r,[...yt({x:c.plot.x,y:c.plot.y,width:c.plot.width,height:c.plot.height},{idPrefix:"galton",wallThickness:20,floorThickness:20}),...ft({idPrefix:"galton-bin",count:n,domainStart:0,domainStep:1,xScale:m,yTop:c.plot.y-400,yBottom:g,wallThickness:6})],"GaltonBoardChart"),initialSpawns:f,initialSpawnPacing:{pacing:{ratePerSec:55}},projectionRows:y.map((e,t)=>({label:t+1+"",value:e})),metadata:{kind:"galton-board",bins:n,plot:c.plot,valueExtent:[u,h]}}}import{scaleLinear as Gn}from"d3-scale";function Un(e){const{count:t,idPrefix:i,wallThickness:n,xScale:o,yBottom:r,yTop:s,yTopForIndex:a}=e;return Array.from({length:t+1},(e,t)=>{const c=Math.min(r-1,a?.(t)??s),d=Math.max(1,r-c);return{id:`${i}-wall-${t}`,shape:{type:"aabb",x:o(t),y:c+d/2,width:n,height:d}}})}function Vn(e){const{data:t,timeAccessor:i,arrivalAccessor:n,windows:o,watermark:r,ballRadius:s,seed:a,size:c,timeExtent:d,timeScale:l=1}=e,u=Tn(c),h=t.map((e,t)=>zn(qn(e,t,i))).filter(e=>null!=e),p=zn(d?.[0]),m=zn(d?.[1]),y=h.length?Math.min(...h):0,f=h.length?Math.max(...h):y+o.size,g=Math.min(p??y,y),b=Math.max(m??f,f),v=Math.floor(g/o.size)*o.size,x=Math.max(1,Math.ceil((b-v+o.size)/o.size)),w=h.length?Math.max(...h):0,k="function"==typeof r?r(w):zn(r?.value)??w-(r?.delay??o.size),I=Math.max(0,Math.min(x,Array.from({length:x},(e,t)=>t).reduce((e,t)=>v+(t+1)*o.size>k?e:e+1,0))),M=function(e,t){const i=Math.max(5*t,Math.min(92,.13*e.plot.width));return{gutter:{x:e.plot.x,y:e.plot.y,width:i,height:e.plot.height},windowPlot:{x:e.plot.x+i,y:e.plot.y,width:Math.max(40,e.plot.width-i),height:e.plot.height},wallTop:e.plot.y+.48*e.plot.height}}(u,s),S=v+x*o.size,A=Gn().domain([v,S]).range([M.windowPlot.x,M.windowPlot.x+M.windowPlot.width]),C=Array.from({length:x},()=>({value:0,secondary:0})),R=[];t.forEach((e,t)=>{const r=zn(qn(e,t,i));if(null==r)return;const a=zn(qn(e,t,n))??r,c=Math.max(0,Math.min(x-1,Math.floor((r-v)/o.size))),d=k>=v+(c+1)*o.size;C[c].value+=d?0:1,C[c].secondary+=d?1:0,R.push({id:(e.id??"event-"+t)+"",x:Math.max(M.windowPlot.x+s,Math.min(M.windowPlot.x+M.windowPlot.width-s,A(r))),y:u.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:c,late:d}})});const P=u.plot.y+u.plot.height,$=function(e,t){const i=Math.max(0,Math.min(e.windowCount,e.closedWindowCount));if(!i)return[];const n=e.windowStart,o=e.windowStart+e.windowCount*e.windowSize,r=Gn().domain([n,o]).range([e.windowPlot.x,e.windowPlot.x+e.windowPlot.width]),s=r(e.windowStart+i*e.windowSize),a=e.windowPlot.x,c=t+Math.max(18,Math.min(.3*e.windowPlot.height,s-a)),d=e=>s===a?t:c+(e-a)/(s-a)*(t-c),l=[];for(let t=0;i>t;t+=1){const i=e.windowStart+t*e.windowSize,n=i+e.windowSize,o=r(i),s=r(n);l.push({id:"eventdrop-lid-"+t,windowIndex:t,x1:o,y1:d(o),x2:s,y2:d(s)})}return l}({closedWindowCount:I,gutter:M.gutter,plot:u.plot,windowCount:x,windowPlot:M.windowPlot,windowSize:o.size,windowStart:v},u.plot.y+.28*u.plot.height);return{config:Fn(a,[...yt({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"eventdrop",wallThickness:20,floorThickness:20}),...Un({idPrefix:"eventdrop-window",count:x,xScale:e=>A(v+e*o.size),yTop:M.wallTop,yTopForIndex:e=>{const t=(e=>{if(0>e||e>I)return null;const t=0===e?$[0]?.y1:$[e-1]?.y2??$[e]?.y1;return"number"==typeof t&&Number.isFinite(t)?t:null})(e);return null==t?M.wallTop:t+1.25*s},yBottom:P,wallThickness:6}),...$.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:R,initialSpawnPacing:{pacing:"arrival",timeAccessor:e=>e.datum?.arrivalTime,timeScale:l},projectionRows:C.map((e,t)=>({label:`${v+t*o.size}-${v+(t+1)*o.size}`,value:e.value,secondary:e.secondary})),metadata:{kind:"event-drop",closedWindowCount:I,gutter:M.gutter,lidSegments:$,lateCount:C.reduce((e,t)=>e+t.secondary,0),plot:u.plot,windowPlot:M.windowPlot,watermarkValue:k,windowCount:x,windowSize:o.size,windowStart:v}}}function Kn(e,t,i){const n=e.width/Math.max(1,t),o=Math.max(2,2*i),r=Math.min(.7*n,Math.max(3.2*o,o+8)),s=Math.max(1,Math.floor(r/o));return{laneWidth:n,tubeWidth:r,ballDiameter:o,perRow:s,centerX:t=>e.x+(t+.5)*n,pileHeight:e=>Math.ceil(Math.max(0,e)/s)*o}}function Qn(e){const{data:t,categoryAccessor:i,valueAccessor:n,unitValue:o,ballRadius:r,seed:s,size:a}=e,c=Ln(o,1),d=Tn(a),l=[],u=new Map,h=new Map,p=[];function m(e){let t=u.get(e);return null==t&&(t=l.length,l.push(e),u.set(e,t)),t}t.forEach((e,t)=>{m((qn(e,t,i)??"unknown")+"")});const y=Math.max(1,l.length),f=Kn(d.plot,y,r),g=Math.max(0,f.tubeWidth/2-r-1),b=l.map(()=>[]);t.forEach((e,t)=>{const o=(qn(e,t,i)??"unknown")+"",s=m(o),a=n?zn(qn(e,t,n)):1,l=Math.max(0,Math.round((a??0)/c)),u=f.centerX(s);for(let i=0;l>i;i+=1){const n=h.get(o)??0,a=f.perRow>1?((f.perRow>1?n%f.perRow:0)/(f.perRow-1)*2-1)*g:0;h.set(o,n+1),b[s].push({id:`${(e.id??"pile-"+t)+""}-${i}`,x:u+a,y:d.plot.y+r+2,vx:(i%3-1)*r/2,vy:0,mass:1,shape:{type:"circle",radius:r},datum:{...e,category:o,unitIndex:i}})}});const v=b.reduce((e,t)=>Math.max(e,t.length),0);for(let e=0;v>e;e+=1)for(const t of b)t.length>e&&p.push(t[e]);const x=d.plot.y+d.plot.height,w=[...yt({x:d.plot.x,y:d.plot.y,width:d.plot.width,height:d.plot.height},{idPrefix:"pile",wallThickness:20,floorThickness:20})],k=d.plot.y-400;for(let e=0;y>e;e+=1){const t=f.centerX(e);for(const i of[-1,1])w.push({id:`pile-tube-${e}-${0>i?"l":"r"}`,shape:{type:"aabb",x:t+i*f.tubeWidth/2,y:(k+x)/2,width:6,height:x-k}})}return{config:Fn(s,w,"UnitPileChart"),initialSpawns:p,initialSpawnPacing:{pacing:{ratePerSec:20}},projectionRows:l.map(e=>({label:e,value:h.get(e)??0}))}}import{scaleLinear as Jn}from"d3-scale";function Zn(e){const{data:t,xAccessor:i,groupAccessor:n,radiusAccessor:o,pointRadius:r,seed:s,size:a,xExtent:c,collisionIterations:d,settle:l}=e,u=Tn(a),h=_n(s),p=[],m=[],y=new Map;t.forEach((e,t)=>{const s=zn(qn(e,t,i));if(null==s)return;const a=n?(qn(e,t,n)??"All")+"":"All",c=o?zn(qn(e,t,o)):null,d=Hn(null!=c&&c>0?c:r,2,18);!function(e){let t=y.get(e);null==t&&(t=m.length,m.push(e),y.set(e,t))}(a),p.push({datum:e,index:t,value:s,group:a,radius:d})});const f=p.map(e=>e.value),g=c?zn(c[0]):null,b=c?zn(c[1]):null,v=f.length?Math.min(...f):0,x=f.length?Math.max(...f):1;let w=g??v,k=b??x;if(w===k&&(w-=.5,k+=.5),w>k){const e=k;k=w,w=e}const I=Math.max(r,...p.map(e=>e.radius)),M=u.plot.x+I+8,S=u.plot.x+u.plot.width-I-8,A=Jn().domain([w,k]).range([M,S]),C=Math.max(1,m.length),R=Math.min(Math.max(28,3*I),u.plot.height/4),P=u.plot.y+R,$=Math.max(0,u.plot.y+u.plot.height-R-P),D=e=>{const t=y.get(e)??0;return 1===C?u.plot.y+.54*u.plot.height:P+t/(C-1)*$},B=new Map,j=p.map((e,t)=>{B.set(e.group,(B.get(e.group)??0)+1);const i=A(e.value),n=D(e.group),o=(h()-.5)*e.radius*1.6,r=(h()-.5)*e.radius*1.6;return{id:(e.datum.id??"collision-swarm-"+t)+"",x:l?i+o:Hn(i+(t%9-4)*e.radius*2.5,M,S),y:l?n+r:u.plot.y-18-t%12*e.radius,vx:l?0:22*(h()-.5),vy:l?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:i,targetY:n},springs:[{target:{type:"point",x:i,y:n},restLength:0,stiffness:34,damping:5.5}]}});return{config:Fn(s,yt({x:u.plot.x,y:u.plot.y,width:u.plot.width,height:u.plot.height},{idPrefix:"collision-swarm",includeCeiling:!1,wallThickness:20,floorThickness:20}),"CollisionSwarmChart",{gravity:{x:0,y:0},cellSize:Math.max(24,4*I),collisionIterations:Math.max(1,Math.round(d??6)),velocityDamping:.992,restitution:.02,friction:.18,sleepSpeed:3,sleepAfter:.5}),initialSpawns:j,projectionRows:m.map(e=>({label:e,value:B.get(e)??0})),metadata:{kind:"collision-swarm",xExtent:[w,k],xRange:[M,S],groups:m.map(e=>({label:e,y:D(e),count:B.get(e)??0})),plot:u.plot}}}function eo(e){if(Array.isArray(e)&&e.length>=2){const t=zn(e[0]),i=zn(e[1]);return null!=t&&null!=i?{x:t,y:i}:null}if(e&&"object"==typeof e){const t=e,i=zn(t.x),n=zn(t.y);return null!=i&&null!=n?{x:i,y:n}:null}return null}function to(e){return Array.isArray(e)?e.map(eo).filter(e=>null!=e):[]}function io(e,t,i){return"normalized"===i?{x:t.plot.x+e.x*t.plot.width,y:t.plot.y+e.y*t.plot.height}:{x:Hn(e.x,t.plot.x,t.plot.x+t.plot.width),y:Hn(e.y,t.plot.y,t.plot.y+t.plot.height)}}function no(e){let t=0;for(let i=1;e.length>i;i+=1)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}function oo(e,t){if(0===e.length)return{x:0,y:0};if(1===e.length)return{...e[0]};const i=Hn(t,0,1)*no(e);let n=0;for(let t=1;e.length>t;t+=1){const o=e[t-1],r=e[t],s=Math.hypot(r.x-o.x,r.y-o.y);if(s>0){if(n+s>=i){const e=(i-n)/s;return{x:o.x+(r.x-o.x)*e,y:o.y+(r.y-o.y)*e}}n+=s}}return{...e[e.length-1]}}function ro(e,t){const i=oo(e,Math.max(0,t-.02)),n=oo(e,Math.min(1,t+.02)),o=n.x-i.x,r=n.y-i.y,s=Math.hypot(o,r)||1;return{x:o/s,y:r/s}}function so(e){const{coordinateMode:t,flowSpeed:i,links:n,maxParticles:o,nodeIdAccessor:r,nodeXAccessor:s,nodeYAccessor:a,nodes:c,particleRadius:d,particleRate:l,pathAccessor:u,pathConstraint:h="path",reducedMotion:p,seed:m,size:y,sourceAccessor:f,targetAccessor:g,throughputAccessor:b}=e,v=Tn(y),x=_n(m),w=new Map,k=new Map,I=[];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")+""}c.forEach((e,t)=>{const i=(qn(e,t,r)??e.id??t)+"",n=zn(qn(e,t,s)),o=zn(qn(e,t,a));if(null!=n&&null!=o){const e={x:n,y:o};w.set(i,e),I.push(e)}k.set(i,(e.label??e.name??i)+"")});const S=[];n.forEach((e,t)=>{const i=M(qn(e,t,f)),n=M(qn(e,t,g)),o=Math.max(0,zn(qn(e,t,b))??0),r=to(u?qn(e,t,u):void 0),s=r.length?r:to(e.path??e.points??e.route);s.forEach(e=>I.push(e)),S.push({id:(e.id??`physical-flow-${i}-${n}-${t}`)+"",link:e,index:t,source:i,target:n,throughput:o,rawPath:s})});const A=(R=I,"normalized"===(C=t)||"pixels"===C?C:R.length>0&&R.every(e=>!(0>e.x||e.x>1||0>e.y||e.y>1))?"normalized":"pixels");var C,R;const P=new Map;for(const[e,t]of w)P.set(e,io(t,v,A));const $=[];for(const e of S){let t=e.rawPath.map(e=>io(e,v,A));if(2>t.length){const i=P.get(e.source),n=P.get(e.target);i&&n&&(t=[i,n])}else P.has(e.source)||P.set(e.source,t[0]),P.has(e.target)||P.set(e.target,t[t.length-1]);t.length>=2&&e.throughput>0&&(k.has(e.source)||k.set(e.source,e.source),k.has(e.target)||k.set(e.target,e.target),$.push({...e,path:t,packetCount:0}))}const D=Ln(l,.12),B=Math.max(1,Math.round(o)),j=$.map(e=>Math.max(1,Math.round(e.throughput*D))),T=j.reduce((e,t)=>e+t,0),O=T>B?B/T:1;$.forEach((e,t)=>{e.packetCount=Math.max(1,Math.floor(j[t]*O))});let E=$.reduce((e,t)=>e+t.packetCount,0);for(;E>B;){const e=$.reduce((e,t,i)=>t.packetCount>1&&(-1===e||t.packetCount>$[e].packetCount)?i:e,-1);if(-1===e)break;$[e].packetCount-=1,E-=1}const N=new Map,F=new Map,W=[],q=Ln(i,90),z=Ln(d,4);$.forEach((e,t)=>{N.set(e.target,(N.get(e.target)??0)+e.throughput),F.set(e.source,(F.get(e.source)??0)+e.throughput);const i=no(e.path);for(let n=0;e.packetCount>n;n+=1){const o=(n+.5)/e.packetCount,r=p?o:Hn(.12+.84*o+.04*(x()-.5),.04,.98),s=p?r:Math.max(0,r-(.18+.12*x())),a=oo(e.path,s),c=oo(e.path,r),d=ro(e.path,s),l={x:-d.y,y:d.x},u=(x()-.5)*z*1.5;W.push({id:`${e.id}-packet-${n}`,x:a.x+l.x*u,y:a.y+l.y*u,vx:p?0:d.x*q+10*(x()-.5),vy:p?0:d.y*q+10*(x()-.5),mass:.8,spawnAt:p?0:.04*t+n/32,shape:{type:"circle",radius:z},datum:{...e.link,source:e.source,target:e.target,throughput:e.throughput,packetIndex:n,packetCount:e.packetCount,routeProgress:r,flowPath:e.path,flowPathLength:i,flowRouteId:e.id,flowSpeed:q,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target},springs:"none"!==h&&p?[{target:{type:"point",x:c.x,y:c.y},restLength:.7*z,stiffness:26,damping:4.25}]:void 0})}});const H=Math.max(18,5*z),L=Array.from(P,([e,t])=>({nodeId:e,label:k.get(e)??e,sensorId:"physical-flow-node-"+Yn(e),point:t})),Y=L.map(e=>({id:e.sensorId,sensor:!0,shape:{type:"aabb",x:e.point.x,y:e.point.y,width:H,height:H}})),_=Object.fromEntries(L.map(e=>[e.sensorId,{binId:e.label,enterType:"physics-proximity-enter",exitType:"physics-proximity-exit"}])),X=Fn(m,[...yt({x:v.plot.x,y:v.plot.y,width:v.plot.width,height:v.plot.height},{idPrefix:"physical-flow",wallThickness:18,floorThickness:18}),...Y],"PacketFlowChart",{gravity:{x:0,y:0},cellSize:Math.max(24,7*z),collisionIterations:3,velocityDamping:.994,restitution:.01,friction:.16,sleepSpeed:2.5,sleepAfter:.7});X.bodyLimit=B,X.eviction="oldest",X.observation={...X.observation,sensors:_};const G=Array.from(P,([e,t])=>({id:e,label:k.get(e)??e,x:t.x,y:t.y,sensorId:"physical-flow-node-"+Yn(e),incoming:N.get(e)??0,outgoing:F.get(e)??0})),U=$.map(e=>({id:e.id,source:e.source,target:e.target,sourceLabel:k.get(e.source)??e.source,targetLabel:k.get(e.target)??e.target,throughput:e.throughput,packetCount:e.packetCount,path:e.path}));return{config:X,initialSpawns:W,projectionRows:G.filter(e=>e.incoming>0||e.outgoing>0).map(e=>({label:e.label,value:e.incoming,secondary:e.outgoing})),metadata:{kind:"physical-flow",coordinateMode:A,particleCount:W.length,totalThroughput:$.reduce((e,t)=>e+t.throughput,0),plot:v.plot,nodes:G,links:U}}}function ao(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function co(e){if(!e||"object"!=typeof e)return!1;const t=e;return"string"==typeof t.id&&(null==t.label||"string"==typeof t.label)&&"number"==typeof t.count&&Number.isFinite(t.count)&&Array.isArray(t.bodyIds)&&t.bodyIds.every(e=>"string"==typeof e)}function lo(e,t){if("region-enter"!==t.type)return e;const i=t.region.id,n=ao(e,i),o=co(n)?n:{id:i,label:t.region.label??i,count:0,bodyIds:[]};if(o.bodyIds.includes(t.bodyId))return e;const r=[...o.bodyIds,t.bodyId];return{...e,[i]:{...o,count:r.length,bodyIds:r}}}function uo(e,t){return(t??Object.keys(e)).map(t=>ao(e,t)).filter(co).map(e=>({label:e.label??e.id,value:e.count}))}function ho(e,t){const i=t instanceof Set?t:new Set(t);return e.map(e=>{const t=e.bodyIds??[],n=t.filter(e=>!i.has(e)),o=t.length-n.length,r=e.completion?.mode??"allMembersAbsorbed",s=e.completion?.valueByBodyId,a=e=>{const t=s?ao(s,e):void 0;return"number"==typeof t&&Number.isFinite(t)&&t>=0?t:1},c=t.reduce((e,t)=>e+a(t),0),d=t.reduce((e,t)=>e+(i.has(t)?a(t):0),0),l=e.completion?.threshold,u="threshold"===r?Number.isFinite(l)&&Number(l)>=0?Number(l):c:void 0;return{id:e.id,label:e.label??e.id,mode:r,complete:t.length>0&&("anyAbsorbed"===r?o>0:"threshold"===r?d>=(u??c):0===n.length),absorbed:o,total:t.length,absorbedValue:d,totalValue:c,threshold:u,missing:n}})}function po(e,t,i){return Math.max(t,Math.min(i,e))}function mo(e,t,i,n,o,r={}){return{id:e,friction:r.friction,restitution:r.restitution,bodyFilter:r.bodyFilter,shape:{type:"segment",x1:t,y1:i,x2:n,y2:o,thickness:r.thickness??8}}}function yo(e){const t=e.shape??"lane",i=Math.max(1,Math.round(e.width)),n=Math.max(1,Math.round(e.height)),o=e.padX??46,r=e.padY??72,s=o,a=i-o,c=r,d=n-Math.max(24,Math.round(.45*r)),l=(c+d)/2,u=Math.max(1,d-c),h=po(e.pinchRatio??.18,.06,.5),p=Number(e.pinchHeightOffset??0),m=Number.isFinite(p)?p:0,y=po(u*h+m,.06*u,.5*u),f=y/2,g=l-f,b=l+f,v=e.idPrefix??"process",x=e.friction??.58,w=e.restitution??.18,k=e.wallThickness??8,I=e.stages;if(!I.length)throw Error("processStageLayout requires at least one stage");const M=po(e.centerStageIndex??Math.floor(I.length/2),0,I.length-1),S=function(e){const t=e.reduce((e,t)=>e+(t.share??1),0);return t>0?t:e.length}(I),A=a-s;let C=s;const R=I.map((e,t)=>{const i=C,n=t===I.length-1?a:C+(e.share??1)/S*A;return C=n,{id:e.id,label:e.label,description:e.description,kind:e.kind??"stage",index:t,x0:i,x1:n,x:(i+n)/2,width:n-i,y:l,height:u}}),P=R[M],$=P.x0,D=P.x1,B=(e,i)=>{if("lane"===t)return"top"===i?c:d;if("funnel"===t){const t=po((e-s)/Math.max(1,a-s),0,1);return"top"===i?c+(g-c)*t:d+(b-d)*t}if($>=e){const t=po((e-s)/Math.max(1,$-s),0,1);return"top"===i?c+(g-c)*t:d+(b-d)*t}if(D>=e)return"top"===i?g:b;const n=po((e-D)/Math.max(1,a-D),0,1);return"top"===i?g+(c-g)*n:b+(d-b)*n},j=R.map(e=>{const t=Math.min(B(e.x0,"top"),B(e.x1,"top")),i=Math.max(B(e.x0,"bottom"),B(e.x1,"bottom"));return{...e,y:(t+i)/2,height:Math.max(1,i-t)}}),T={thickness:k,friction:x,restitution:w},O=[];"lane"===t?O.push(mo(v+"-top",s,c,a,c,T),mo(v+"-bottom",s,d,a,d,T),mo(v+"-left",s,c,s,d,{...T,thickness:Math.max(6,k-2)}),mo(v+"-right",a,c,a,d,{...T,thickness:Math.max(6,k)})):"funnel"===t?O.push(mo(v+"-top",s,c,a,g,T),mo(v+"-bottom",s,d,a,b,T),mo(v+"-left",s,c,s,d,{...T,thickness:Math.max(6,k-2)}),mo(v+"-right",a,g,a,b,{...T,thickness:Math.max(6,k)})):O.push(mo(v+"-left-top",s,c,$,g,T),mo(v+"-left-bottom",s,d,$,b,T),mo(v+"-center-top",$,g,D,g,T),mo(v+"-center-bottom",$,b,D,b,T),mo(v+"-right-top",D,g,a,c,T),mo(v+"-right-bottom",D,b,a,d,T),mo(v+"-left",s,c,s,d,{...T,thickness:Math.max(6,k-2)}),mo(v+"-right",a,c,a,d,{...T,thickness:Math.max(6,k)}));const E=e.membraneDampingScale??.5,N=s,F=Math.max(1,("bowtie"===t?$:a)-N),W=(e.membranes??[]).map(e=>{const t=N+po(e.offset,0,1)*F,i=e.width??18+18*e.cost,n=u-16,o=l+.25*(e.wobble??0);return{...e,x:t,y:o,width:i,height:n}}),q=!1===e.includeMembraneRegions?[]:W.map(e=>bo({id:e.id,label:e.label??e.id,description:e.description??(e.label??e.id)+" is a permeable region. It taxes energy and damps velocity while bodies overlap it.",x:e.x,y:e.y,width:e.width,height:e.height,cost:e.cost,dampingScale:e.dampingScale??E,bodyStyle:e.bodyStyle,metadata:e.metadata,semanticItem:e.semanticItem,color:e.color}));return{shape:t,width:i,height:n,padX:o,padY:r,left:s,right:a,topY:c,bottomY:d,midY:l,centerLeft:$,centerRight:D,pinchHeight:y,pinchTop:g,pinchBottom:b,stages:j,membranes:W,colliders:O,regionEffects:q,boundaryY:B}}function fo(e){return{id:e.id,label:e.label,description:e.description,kind:e.kind,shape:(t=e.x,i=e.y,n=e.width,o=e.height,{type:"aabb",x:t,y:i,width:n,height:o}),bodyFilter:e.bodyFilter,collider:e.collider,colliderThickness:e.colliderThickness,friction:e.friction,restitution:e.restitution,semanticItem:e.semanticItem,metadata:e.metadata,bodyStyle:e.bodyStyle,attributes:e.attributes,onEnter:e.onEnter,onExit:e.onExit};var t,i,n,o}function go(e,t={}){const i=t.idPrefix??"stage",n=Math.max(0,t.insetX??0),o=Math.max(0,t.insetY??1);return e.stages.map(e=>{const r="function"==typeof t.metadata?t.metadata(e):t.metadata??{};return{...fo({id:i?`${i}:${e.id}`:e.id,label:e.label??e.id,description:e.description,kind:"region",x:e.x,y:e.y,width:Math.max(1,e.width-2*n),height:Math.max(1,e.height-2*o),bodyFilter:t.bodyFilter,semanticItem:t.semanticItem,attributes:{primitive:"processStage",stageId:e.id,stageIndex:e.index},metadata:{...r,primitive:"processStage",stageId:e.id,stageIndex:e.index}})}})}function bo(e){const t=e.dampingScale??.5,i=e.energyScale??1,n=po(e.cost,0,2);return{...fo({...e,kind:e.kind??"membrane",attributes:{primitive:"membrane",membraneCost:n,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:n*t,energyDelta:-n*i}}function vo(e){return{...fo({...e,kind:e.kind??"charge-gate",attributes:{primitive:"chargeGate",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),charge:e.charge??!0,energyDelta:e.energyDelta,impulseOnEnter:e.impulseOnEnter}}function xo(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:12,y:0};return{...fo({...e,kind:e.kind??"force-field",attributes:{primitive:"routeSurface",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.015}}function wo(e){const t=e.pressure??e.occupancy??0,i=e.baseDamping??.08,n=e.dampingPerUnit??.12,o=e.energyPerUnit??0;return{...fo({...e,kind:e.kind??"membrane",attributes:{primitive:"pressureField",pressure:t,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),damping:i+t*n,energyDelta:o?-t*o:void 0,force:e.force}}function ko(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force;return{...fo({...e,kind:e.kind??"force-field",attributes:{primitive:"capacitatedSensor",capacity:e.capacity,unitsPerSecond:e.unitsPerSecond??e.capacity,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping,charge:e.charge??e.capacity}}function Io(e){return{...fo({...e,kind:e.kind??"force-field",attributes:{primitive:"portal",targetStage:e.targetStage,..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,impulseOnEnter:e.impulseOnEnter,damping:e.damping??.08}}function Mo(e){const t="number"==typeof e.force?{x:e.force,y:0}:e.force??{x:24,y:0};return{...fo({...e,kind:e.kind??"sink",attributes:{primitive:"absorb",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:t,damping:e.damping??.02,charge:e.charge??"absorbed"}}function So(e){return{...fo({...e,kind:e.kind??"force-field",attributes:{primitive:"forceField",..."object"==typeof e.attributes&&e.attributes?e.attributes:{}}}),force:e.force,damping:e.damping,energyDelta:e.energyDelta}}function Ao(e){const t=e.x??e.anchor?.x??0,i=e.y??e.anchor?.y??0;return{id:e.id,label:e.label,description:e.description,group:e.group,bodyIds:e.bodyIds,datum:e.datum,state:e.state,x:t,y:i,width:e.width,height:e.height,anchor:e.anchor??{x:t,y:i},completion:e.completion,tether:e.tether,semanticItem:e.semanticItem}}function Co(e){const t=e.idPrefix??"lane",i={thickness:e.thickness??8,friction:e.friction??.5,restitution:e.restitution??.16},n=[mo(t+"-top",e.left,e.top,e.right,e.top,i),mo(t+"-bottom",e.left,e.bottom,e.right,e.bottom,i)];return e.openEnds||n.push(mo(t+"-left",e.left,e.top,e.left,e.bottom,i),mo(t+"-right",e.right,e.top,e.right,e.bottom,i)),n}function Ro(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}}function Po(e){const t=e.stages;if(!t.length)throw Error("buildProcessFlowPhysics requires at least one stage");const i=e.size,n=Tn(i),o=Hn(e.ballRadius??6,2,18),r=e.seed??1,s=_n(r),a=e.idAccessor,c=e.stageAccessor??"stage",d=e.groupBy,l=e.groupLabelAccessor,u=e.workAccessor,h=e.radiusAccessor,p=e.groupCompletion??(d?"allAbsorbed":"none"),m=e.springStiffness??.28,y=e.springDamping??.72,f=!0===e.settle,g=t.map(e=>({id:e.id,label:e.label??e.id,description:e.description,share:e.share})),b=yo({width:i[0],height:i[1],shape:"lane",padX:Math.max(28,n.plot.x),padY:Math.max(36,n.plot.y+8),stages:g,idPrefix:"process-flow",includeMembraneRegions:!1,friction:.48,restitution:.14}),v=new Map(b.stages.map((e,t)=>[e.id,t])),x=new Map(b.stages.map(e=>[e.id,e])),w=b.stages[0].id,k=b.stages[0],I=new Set(t.filter(e=>e.absorb).map(e=>e.id)),M=t.map(e=>{const t=x.get(e.id)??k;return function(e,t){const i={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 Mo({...i,kind:e.kind??"sink",force:Ro(e.force,28),damping:e.damping??.04,charge:"absorbed",attributes:{...i.attributes,primitive:"absorb"}});if(e.portal){const t=e.portal.force??e.force??{x:-40,y:0};return Io({...i,kind:e.kind??"force-field",force:Ro(t,-40),damping:e.damping??.1,targetStage:e.portal.targetStageId,attributes:{...i.attributes,primitive:"portal",targetStage:e.portal.targetStageId}})}if(e.capacity){const t=Math.max(.1,e.capacity.unitsPerSecond);return ko({...i,kind:e.kind??"force-field",capacity:t,unitsPerSecond:t,force:Ro(e.force,10+.8*t),damping:e.damping??Math.max(.04,.32-.01*t),attributes:{...i.attributes,unitAccessor:e.capacity.unitAccessor,reviewerCapacity:t}})}if(e.pressure){const t="object"==typeof e.pressure&&e.pressure?e.pressure:{};return wo({...i,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:Ro(e.force,8),attributes:{...i.attributes,primitive:"pressureField"}})}return null!=e.force||null!=e.damping?xo({...i,kind:e.kind??"force-field",force:Ro(e.force,14),damping:e.damping??.02,attributes:{...i.attributes,primitive:"routeSurface"}}):So({...i,kind:e.kind??"force-field",force:{x:10,y:0},damping:.02,attributes:{...i.attributes,primitive:"forceField"}})}(e,{x:t.x,y:b.midY,width:t.width,height:b.bottomY-b.topY})});M.unshift(xo({id:"process-flow-route",label:"process route",description:"Baseline conveyor along the process lane.",x:(b.left+b.right)/2,y:b.midY,width:b.right-b.left,height:b.bottomY-b.topY-12,force:8,damping:.012,semanticItem:!1}));const S=new Map;for(const e of b.stages)S.set(e.id,0);const A=[];e.data.forEach((e,t)=>{const i=(a?qn(e,t,a)??e.id??"process-flow-"+t:e.id??"process-flow-"+t)+"",n=(qn(e,t,c)??w)+"",r=v.has(n)?n:w;S.set(r,(S.get(r)??0)+1);const s=d?(qn(e,t,d)??"")+"":void 0,p=s&&l?(qn(e,t,l)??s)+"":s,m=u?zn(qn(e,t,u))??1:1,y=h?zn(qn(e,t,h)):null,f=Hn(null!=y&&y>0?y:o,2,18);A.push({datum:e,id:i,stageId:r,groupId:s||void 0,groupLabel:p||void 0,work:m,radius:f,index:t})});const C=new Map,R=new Map;for(const e of A){if(!e.groupId)continue;const t=C.get(e.groupId)??[];t.push(e.id),C.set(e.groupId,t),e.groupLabel&&R.set(e.groupId,e.groupLabel)}const P=Hn(e.groupAnchorAlong??.55,.15,.9),$=b.left+(b.right-b.left)*P,D=Array.from(C.keys()),B=D.map((e,i)=>{const n=C.get(e)??[],o=D.length>1?b.topY+28+i/Math.max(1,D.length-1)*(b.bottomY-b.topY-56):b.midY;return Ao({id:e,label:R.get(e)??e,bodyIds:n,anchor:{x:$,y:o},x:$,y:o,completion:"allAbsorbed"===p?{mode:"allMembersAbsorbed",targetZone:t.find(e=>e.absorb)?.id??"merged"}:void 0,tether:{stiffness:.06,visible:!0,restLength:18}})}),j=ho(B,A.filter(e=>I.has(e.stageId)).map(e=>e.id)),T=new Map(B.map(e=>[e.id,e])),O=A.map((e,t)=>{const i=x.get(e.stageId)??k,n=i.x+(s()-.5)*Math.min(24,.2*i.width),o=b.boundaryY(n,"top")+e.radius+10,r=b.boundaryY(n,"bottom")-e.radius-10,a=r>o?o+s()*Math.max(1,r-o):b.midY,c=f?n:b.left+18+t%7*4,d=f?a:b.midY+(s()-.5)*(b.bottomY-b.topY)*.35,l=[{target:{type:"point",x:n,y:a},restLength:.45*e.radius,stiffness:m,damping:y}];if(e.groupId){const t=T.get(e.groupId);t?.anchor&&!I.has(e.stageId)&&l.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:c,y:d,vx:f?0:40+40*s(),vy:f?0:20*(s()-.5),mass:1,shape:{type:"circle",radius:e.radius},spawnAt:f?0:.03*t,springs:l,datum:{...e.datum,id:e.id,stage:e.stageId,groupId:e.groupId,groupLabel:e.groupLabel,work:e.work,__processFlow:!0}}}),E={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:b.colliders,fixedDt:1/60,maxSubsteps:8},N=b.stages.map(e=>({label:e.label??e.id,value:S.get(e.id)??0})),F=t.map(e=>{const t=x.get(e.id)??k;return{id:e.id,label:e.label??e.id,x:t.x,width:t.width,count:S.get(e.id)??0,capacity:e.capacity?.unitsPerSecond,absorb:!0===e.absorb,portalTarget:e.portal?.targetStageId}});return{config:E,initialSpawns:O,initialSpawnPacing:f?void 0:{pacing:"arrival",timeAccessor:"spawnAt",timeScale:1},projectionRows:N,metadata:{kind:"process-flow",plot:n.plot,volume:b,stages:F,groups:B,groupCompletion:j,regionEffects:M}}}import{forwardRef as $o,useCallback as Do,useMemo as Bo,useRef as jo}from"react";import{useImperativeHandle as To,useRef as Oo}from"react";function Eo(e,t){if(!t?.length)return[e];const i=t.filter(t=>{if(t.id===e||t.id.startsWith(e+"-"))return!0;const i=t.datum;return!(!i||"object"!=typeof i||null==i.id)&&i.id+""===e}).map(e=>e.id);return i.length?i:[e]}function No(e,t,i){if("function"==typeof i)return i(e,t)+"";if("string"==typeof i){const t=e[i];if(null!=t)return t+""}return null!=e&&"object"==typeof e&&"id"in e&&null!=e.id?e.id+"":"physics-row-"+t}function Fo(e,t){const i=e?.getData().find(e=>e.id===t),n=i?.datum;if(n&&"object"==typeof n)return n}function Wo(e,t){const{frameRef:i,spawnDatum:n,seedRows:o,idAccessor:r,bodyIdsForSeed:s,seedSpawns:a}=t,c=Oo(new Map),d=Oo(new Map),l=Oo(""),u=o?o.map((e,t)=>No(e,t,r)).join("\0"):"";if(u!==l.current&&(l.current=u,o))for(let e=0;o.length>e;e+=1){const t=o[e],i=No(t,e,r);c.current.set(i,t),d.current.set(i,s?.(t,i,e)??Eo(i,a))}To(e,()=>{const e=c.current,t=d.current;function o(e,t){const i=n(e,t);return{datumId:i.datumId||No(e,t,r),spawns:i.spawns.map(e=>({...e,spawnAt:void 0}))}}function s(n){const o=[];for(const{datum:i,result:r}of n)e.set(r.datumId,i),t.set(r.datumId,r.spawns.map(e=>e.id)),o.push(...r.spawns);if(!o.length)return;const r=i.current;r?(r.pushMany(o),r.step(0)):"production"!==process.env.NODE_ENV&&console.warn("[semiotic/physics] push() called before the physics frame mounted (loading/empty early-return). Omit data for push mode and ensure the chart is mounted.")}function a(n){const o=e.get(n);if(o)return o;const r=t.get(n)??[n];for(const o of r){const r=Fo(i.current,o);if(r)return e.set(n,r),t.has(n)||t.set(n,[o]),r}}return{push:t=>{s([{datum:t,result:o(t,e.size)}])},pushMany:t=>{const i=e.size;s(t.map((e,t)=>({datum:e,result:o(e,i+t)})))},remove:n=>{const o=Array.isArray(n)?n:[n],r=[],s=[];for(const i of o){const n=a(i);n&&r.push(n),e.delete(i),s.push(...t.get(i)??[i]),t.delete(i)}return s.length&&i.current?.remove(s),r},update:(n,r)=>{const c=Array.isArray(n)?n:[n],d=[];for(const n of c){const c=a(n);if(!c)continue;d.push(c);const l=t.get(n)??[n];i.current?.remove(l),e.delete(n),t.delete(n);const u=r(c);s([{datum:u,result:o(u,e.size)}])}return d},clear:()=>{e.clear(),t.clear(),l.current="",i.current?.clear()},getData:()=>{const t=i.current;if(!t)return Array.from(e.values());const n=t.getData().map(e=>e.datum).filter(e=>!!e&&"object"==typeof e);return n.length?n:Array.from(e.values())},getScales:()=>null,getCustomLayout:()=>i.current?.snapshot()??null,popBodies:(e,t)=>i.current?.popBodies(e,t)??[]}},[i,r,n])}import{useCallback as qo,useEffect as zo,useMemo as Ho,useRef as Lo,useState as Yo}from"react";import{Fragment as _o,jsx as Xo,jsxs as Go}from"react/jsx-runtime";function Uo(e){return!!e&&"string"==typeof e.name}function Vo(e,t=!1){if(!e?.datum)return null;const i=e.datum,n=i.sourceDatum;return t&&n&&"object"==typeof n?n:i}function Ko(e){const{selection:t,linkedHover:i,colorBy:n,chartType:o,chartId:r,onBodyHover:s,fallbackFields:a,unwrapSourceDatum:c}=e,d="string"==typeof n?n:void 0,l=Uo(t)?t:void 0,{activeSelectionHook:u,customHoverBehavior:h}=Y({selection:l,linkedHover:i,fallbackFields:d?[d]:a,onObservation:e.onObservation,onClick:e.onClick,chartType:o,chartId:r,colorByField:d}),p=Uo(t)?null:t??null,m=Ho(()=>{if(p)return p;if(!u?.isActive)return null;const e=u.predicate;return{isActive:!0,predicate:t=>{const i=Vo(t,c);return null!=i&&e(i)}}},[u?.isActive,u?.predicate,p,c]),y=Ho(()=>{if(i||s)return(e,t)=>{if(s?.(e,t),!i)return;const n=Vo(e,c);h(n&&t?{...t,data:n}:null)}},[h,s,i,c]);return Ho(()=>({selection:m,onBodyHover:y}),[y,m])}var Qo=new Set(["sample","mechanical"]);function Jo(e,t,i,n){const[o,r]=Yo(0),s=Lo(null),a=Lo(!1),c=function(e){return"number"==typeof e&&Number.isFinite(e)&&e>=0?e:null}(t),d=Lo(c),l=Lo(!!i),u=Lo(n);d.current=c,l.current=!!i,u.current=n;const h=qo(()=>{null!=s.current&&(clearTimeout(s.current),s.current=null)},[]),p=qo(()=>{h();const e=d.current;null!=e&&!l.current&&a.current&&(s.current=setTimeout(()=>{s.current=null,a.current=!1,u.current?.(),r(e=>e+1)},e))},[h]);zo(()=>{null==c||i?h():a.current&&p()},[h,c,i,p]),zo(()=>h,[h]);const m=e?.observation?.onSimulationStateChange,y=qo((e,t)=>{if(m?.(e,t),"running"===e)return a.current=!1,void h();"settled"===e&&"running"===t&&(a.current=!0,p())},[h,m,p]);return{config:Ho(()=>null==c?e:{...e,observation:{...e?.observation,onSimulationStateChange:y}},[e,c,y]),rerunKey:o}}function Zo(e,t,i){const n=i?.hasSimulationMode?function(e){const t=e=>"string"==typeof e&&Qo.has(e);return e.simulationMode?{chartMode:t(e.mode)?void 0:e.mode,simulationMode:e.simulationMode}:t(e.mode)?{chartMode:void 0,simulationMode:e.mode}:{chartMode:e.mode,simulationMode:"sample"}}({mode:e.mode,simulationMode:e.simulationMode}):{chartMode:"sample"===e.mode||"mechanical"===e.mode?void 0:e.mode,simulationMode:"sample"},o=L(n.chartMode,{width:e.width,height:e.height,enableHover:e.enableHover,title:e.title,description:e.description,summary:e.summary,accessibleTable:e.accessibleTable,mobileInteraction:e.mobileInteraction,mobileSemantics:e.mobileSemantics,responsiveRules:e.responsiveRules},{width:t[0],height:t[1]}),r=e.size?.[0],s=e.size?.[1],a=t[0],c=t[1],d=er(Ho(()=>{return e=[a,c],(null!=r&&null!=s?[r,s]:void 0)??[o.width??e[0],o.height??e[1]];var e},[c,a,o.height,o.width,s,r]),e.responsiveWidth,e.responsiveHeight),l=d.size,u=o.compactMode?"sparkline"===n.chartMode?{top:2,right:2,bottom:2,left:2}:{top:8,right:8,bottom:8,left:8}:{top:0,right:0,bottom:0,left:0};const h=e.showProjection??!o.compactMode,p=e.showChrome??!o.compactMode,m=or(e.tooltip,void 0),y=void 0!==m.enableHover?m.enableHover:o.enableHover,f=o.compactMode?o.title:o.title??e.title,g=[e.className,n.chartMode&&"primary"!==n.chartMode?"semiotic-physics--"+n.chartMode:null].filter(Boolean).join(" ")||void 0;return{chartMode:n.chartMode,simulationMode:n.simulationMode,resolved:o,chartSize:l,responsiveContainerRef:d.containerRef,responsiveWidth:d.responsiveWidth,responsiveHeight:d.responsiveHeight,margin:u,showProjection:h,showChrome:p,enableHover:y,title:f,description:o.description??e.description,summary:o.summary??e.summary,accessibleTable:o.accessibleTable??e.accessibleTable,className:g,compactMode:o.compactMode,mobileInteraction:o.mobileInteraction,mobileSemantics:o.mobileSemantics}}function er(e,t,i){const[n,o]=V(e,t,i),r=Math.max(1,o[0]),s=Math.max(1,o[1]);return{containerRef:n,size:Ho(()=>[r,s],[s,r]),responsiveWidth:!!t,responsiveHeight:!!i}}function tr(e){const[t,i]=e.size;return O(e.loading,t,i,e.loadingContent)||j(e.data,t,i,e.emptyContent)}function ir(e,t,i,n){return Xo(p,{componentName:e,width:t[0],height:t[1],children:n?.responsiveWidth||n?.responsiveHeight?Xo("div",{ref:n.responsiveContainerRef,"data-semiotic-physics-responsive-host":"true",style:{position:"relative",width:n.responsiveWidth?"100%":t[0],height:n.responsiveHeight?"100%":t[1]},children:i}):i})}function nr(e,t){return e?t?i=>Go(_o,{children:["function"==typeof e?e(i):e,"function"==typeof t?t(i):t]}):e:t}function or(e,t,i={}){if(!1===e)return{enableHover:!1};const n=!C(e)||R(e)&&"function"==typeof e.content?e:"multi",o=$(n),r="function"==typeof o?i.unwrapSourceDatum?e=>{const t=e.data,i=t?.sourceDatum;return o({...e,data:i&&"object"==typeof i?i:e.data,__semioticHoverData:!0})}:o:t?.tooltipContent;return{enableHover:t?.enableHover,tooltipContent:r}}function rr(e,t,i,n){return{accessibleTable:n?.accessibleTable??e.accessibleTable??t?.accessibleTable,annotations:e.annotations??t?.annotations,autoPlaceAnnotations:e.autoPlaceAnnotations??t?.autoPlaceAnnotations,background:e.background??t?.background,chartId:e.chartId??t?.chartId,chartMode:n?.chartMode??t?.chartMode,className:n?.className??e.className??t?.className,color:e.color??t?.color,description:n?.description??e.description??t?.description,emphasis:e.emphasis??t?.emphasis,enableHover:n?.enableHover??t?.enableHover,hoverRadius:e.hoverRadius??t?.hoverRadius,legend:e.legend??t?.legend,legendLayout:e.legendLayout??t?.legendLayout,legendPosition:e.legendPosition??t?.legendPosition,margin:n?.margin??t?.margin,maxDevicePixelRatio:e.maxDevicePixelRatio??t?.maxDevicePixelRatio,onClick:null!=e.onClick?(t,i)=>{t&&e.onClick?.(t,{x:i.x,y:i.y})}:t?.onClick,onObservation:e.onObservation??t?.onObservation,onAnnotationActivate:t?.onAnnotationActivate,opacity:e.opacity??t?.opacity,selection:n?.selection??t?.selection,semanticItems:t?.semanticItems??i,stroke:e.stroke??t?.stroke,strokeWidth:e.strokeWidth??t?.strokeWidth,summary:n?.summary??e.summary??t?.summary,svgAnnotationRules:e.svgAnnotationRules??t?.svgAnnotationRules,title:n?.title??e.title??t?.title}}import{Fragment as sr,jsx as ar,jsxs as cr}from"react/jsx-runtime";function dr(e){return e.toLocaleString(void 0,Math.abs(e)>=1e3||.01>Math.abs(e)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}import{jsx as lr}from"react/jsx-runtime";var ur=$o(function(e,t){const{data:i,valueAccessor:n="value",styleRules:o,bins:r=21,ballRadius:s,colorBy:a,branchProbability:c=.5,emptyContent:d,frameProps:l,loading:u,loadingContent:h,mechanicalCount:p,paused:m,pegRows:y,referenceLines:f,rerunMS:g,seed:b=1,valueExtent:v}=e,x=Zo(e,[700,420],{hasSimulationMode:!0}),{chartSize:w,simulationMode:k,showProjection:I,className:M,title:S,chartMode:A,margin:C,enableHover:R,description:P,summary:$,accessibleTable:D}=x,B=s??("sparkline"===A?1.5:"context"===A?4:6),j=jo(null),T=Math.max(1,Math.round(y??r-1)),O=Bo(()=>"mechanical"===k?[0,T]:function(e){if(!e)return;const t=Number(e[0]),i=Number(e[1]);return Number.isFinite(t)&&Number.isFinite(i)?t>i?[i,t]:[t,i]:void 0}(v),[T,k,v]),E=Bo(()=>"mechanical"===k?function(e){const t=Math.max(2,Math.round(e.bins)),i=Math.max(1,Math.round(e.pegRows??t-1)),n=Math.max(1,Math.round(e.count??Math.max(64,4*t))),o=Hn(Number.isFinite(e.branchProbability)?e.branchProbability??.5:.5,0,1),r=_n(e.seed??1),s=e.idPrefix??"mechanical";return Array.from({length:n},(e,t)=>{let n=0;for(let e=0;i>e;e+=1)r()<o&&(n+=1);const a=i/2;return{id:`${s}-${t}`,value:n,mechanical:!0,pegRows:i,branchProbability:o,pathRights:n,side:a>n?"left":n>a?"right":"center"}})}({bins:r,branchProbability:c,count:p,pegRows:T,seed:b}):i??[],[r,c,i,p,T,b,k]),N=Bo(()=>Xn({data:E,valueAccessor:n,bins:r,ballRadius:B,seed:b,size:w,valueExtent:O}),[r,E,w,B,O,b,n]),F=Jo(N.config,g,m);Wo(t,{frameRef:j,spawnDatum:Do((e,t)=>{const i=Xn({data:[e],valueAccessor:n,bins:r,ballRadius:B,seed:b+t+1,size:w,valueExtent:O}).initialSpawns[0]??{id:(e.id??"galton-push-"+t)+"",x:Tn(w).plot.x,y:Tn(w).plot.y,mass:1,shape:{type:"circle",radius:B},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[r,w,B,O,b,n]),seedRows:E,seedSpawns:N.initialSpawns});const W="mechanical"===k&&null==a?"side":a,q=Bo(()=>Nn(W,"#4e79a7",{styleRules:o,valueAccessor:n}),[W,o,n]),z=Bo(()=>En(q,l?.bodyStyle),[q,l?.bodyStyle]),H=Bo(()=>Wn(N.projectionRows,w,"bin"),[w,N.projectionRows]),{selection:L,onBodyHover:Y}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:a,chartType:"GaltonBoardChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:l?.onBodyHover,fallbackFields:"string"==typeof n?[n]:void 0}),_=tr({data:"mechanical"===k?E:i,emptyContent:d,loading:u,loadingContent:h,size:w});if(_)return _;const X=function(e,t,i,n,o){const r=Array.isArray(o)?o:o?[o]:[];if(!1!==i||0!==r.length)return({size:o})=>{const s=[Number(o[0])||700,Number(o[1])||420],a=Tn(s),c=Math.max(2,Math.round(t)),d=a.plot.width/c,l=a.plot.y+a.plot.height,u=Math.max(1,...e.map(e=>e.value)),h=!1!==i,[p,m]=n?.valueExtent??[0,c],y=m===p?1:m-p,f=e.map((e,t)=>{const i=l-e.value/u*a.plot.height*.9;return`${0===t?"M":"L"} ${(a.plot.x+(t+.5)*d).toFixed(1)} ${i.toFixed(1)}`}).join(" ");return cr("svg",{"aria-hidden":"true","data-testid":"galton-board-structure-overlay",width:s[0],height:s[1],viewBox:`0 0 ${s[0]} ${s[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[h?cr(sr,{children:[Array.from({length:c+1},(e,t)=>{const i=a.plot.x+t*d;return ar("line",{"data-testid":"galton-board-bin-wall",x1:i,x2:i,y1:a.plot.y,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+t)}),ar("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),ar("path",{d:f,fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),e.map((e,t)=>e.value>0?ar("text",{x:a.plot.x+(t+.5)*d,y:Math.max(a.plot.y+10,l-e.value/u*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.value},`${e.label}-${t}`):null)]}):null,r.map((e,t)=>{const i=Number(e.value);if(!Number.isFinite(i))return null;const n=a.plot.x+Math.max(0,Math.min(1,(i-p)/y))*a.plot.width,o=e.color??"var(--semiotic-warning, #f28e2b)",r="bottom"===e.labelPosition?Math.min(s[1]-8,l+16):a.plot.y+16;return cr("g",{className:e.className,"data-testid":"galton-board-reference-line",children:[ar("line",{x1:n,x2:n,y1:a.plot.y+8,y2:l-4,stroke:o,strokeDasharray:e.strokeDasharray??"6 5",strokeWidth:e.strokeWidth??2}),null==e.label?null:ar("text",{x:Math.min(a.plot.x+a.plot.width-4,n+6),y:r,fill:o,fontSize:10,fontWeight:700,children:e.label})]},`galton-reference-${t}-${i}`)})]})}}(N.projectionRows,r,I,N.metadata,f),G=or(e.tooltip,l),U=rr(e,l,H,{selection:L,chartMode:A,className:M,title:S,description:P,summary:$,accessibleTable:D,enableHover:R,margin:C});return ir("GaltonBoardChart",w,lr(Bn,{...l,...G,...U,ref:j,onBodyHover:Y,config:F.config,foregroundGraphics:nr(X,l?.foregroundGraphics),initialSpawns:N.initialSpawns,initialSpawnPacing:N.initialSpawnPacing,paused:m,responsiveHeight:!1,responsiveWidth:!1,size:w,bodyStyle:z},`${w[0]}x${w[1]}:${F.rerunKey}`),x)});import{forwardRef as hr,useCallback as pr,useMemo as mr,useRef as yr}from"react";import{createElement as fr}from"react";var gr=hr(function(e,t){const{arrivalAccessor:i="arrivalTime",ballRadius:n=7,colorBy:o,styleRules:r,data:s,emptyContent:a,frameProps:c,loading:d,loadingContent:l,paused:u,rerunMS:h,seed:p=1,timeAccessor:m="time",timeExtent:y,timeScale:f=1,watermark:g,windows:b={size:10}}=e,v=Zo(e,[760,360]),{chartSize:x,showProjection:w,className:k,title:I,chartMode:M,margin:S,enableHover:A,description:C,summary:R,accessibleTable:P}=v,$=yr(null),D=mr(()=>s??[],[s]),B=mr(()=>Vn({data:D,timeAccessor:m,arrivalAccessor:i,windows:b,watermark:g,ballRadius:n,seed:p,size:x,timeExtent:y,timeScale:f}),[i,n,x,D,p,m,y,f,g,b]),j=Jo(B.config,h,u),T=B.metadata;Wo(t,{frameRef:$,spawnDatum:pr((e,t)=>{const o=T?function(e,t,i,n){const o=zn(qn(e,t,n.timeAccessor));if(null==o)return null;const r=zn(qn(e,t,n.arrivalAccessor))??o,{windowPlot:s,windowStart:a,windowCount:c,windowSize:d,watermarkValue:l}=i,u=a+c*d,h=Gn().domain([a,u]).range([s.x,s.x+s.width]),p=Math.max(0,Math.min(c-1,Math.floor((o-a)/d))),m=l>=a+(p+1)*d,{ballRadius:y}=n;return{id:(e.id??"event-push-"+t)+"",x:Math.max(s.x+y,Math.min(s.x+s.width-y,h(o))),y:s.y+y+2,vx:8*(t%3-1),vy:0,mass:1,friction:.02,shape:{type:"circle",radius:y},datum:{...e,eventTime:o,arrivalTime:r,windowIndex:p,late:m}}}(e,t,T,{timeAccessor:m,arrivalAccessor:i,ballRadius:n}):null,r=o??{id:(e.id??"event-push-"+t)+"",x:Tn(x).plot.x,y:Tn(x).plot.y,mass:1,shape:{type:"circle",radius:n},datum:e};return{datumId:(e.id??r.id)+"",spawns:[r]}},[i,n,x,T,m]),seedRows:D,seedSpawns:B.initialSpawns});const O=mr(()=>Nn(o,"#4e79a7",{styleRules:r,valueAccessor:m}),[o,r,m]),E=mr(()=>En(O,c?.bodyStyle),[O,c?.bodyStyle]),N=mr(()=>function(e,t,i){if(!t)return Wn(e,i,"window");const n=t.windowPlot.width/Math.max(1,e.length),o=Math.max(1,...e.map(e=>e.value+(e.secondary??0))),r=.62*t.windowPlot.height,s=t.windowPlot.y+t.windowPlot.height;return e.map((e,i)=>{const a=Math.max(8,(e.value+(e.secondary??0))/o*r),c=`window ${e.label}: ${e.value} on time${e.secondary?`, ${e.secondary} late`:""}`;return{id:"window-"+e.label,label:c,description:c,datum:e,x:t.windowPlot.x+(i+.5)*n,y:s-a/2,shape:"rect",width:Math.max(12,.58*n),height:a,group:"window"}})}(B.projectionRows,T,x),[x,B.projectionRows,T]),{selection:F,onBodyHover:W}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"EventDropChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:c?.onBodyHover,fallbackFields:"string"==typeof m?[m]:void 0}),q=tr({data:s,emptyContent:a,loading:d,loadingContent:l,size:x});if(q)return q;const z=function(e,t,i){if(!1!==i&&t)return({size:i})=>{const n=[Number(i[0])||760,Number(i[1])||360],o=Tn(n),r=Math.max(1,t.windowCount),s=t.plot??o.plot,a=t.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=t.windowPlot??s,d=c.width/r,l=s.y+s.height,u=s.y+.48*s.height,h=t.lidSegments[0]?.y1??u,p=t.windowStart,m=t.windowStart+r*t.windowSize,y=c.x+Math.max(0,Math.min(1,m===p?0:(t.watermarkValue-p)/(m-p)))*c.width;return cr("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[ar("rect",{x:s.x,y:s.y,width:s.width,height:s.height,fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.7,strokeWidth:1}),a.width>0?cr("g",{children:[ar("rect",{x:a.x,y:h,width:a.width,height:l-h,fill:"var(--semiotic-danger, #e15759)",fillOpacity:.07,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.55,strokeWidth:1}),ar("text",{x:a.x+a.width/2,y:h-8,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:"gutter"})]}):null,Array.from({length:r},(i,o)=>{const r=e[o],s=c.x+o*d,a=t.closedWindowCount>o,h=r?.secondary??0;return cr("g",{children:[ar("rect",{x:s,y:u,width:d,height:l-u,fill:a?"var(--semiotic-danger, #e15759)":"var(--semiotic-primary, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?t.lidSegments.filter(e=>e.windowIndex===o).map(e=>ar("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},e.id)):null,cr("text",{x:s+d/2,y:u-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[r?.value??0,h?` / ${h} late`:""]}),ar("text",{x:s+d/2,y:Math.min(n[1]-8,l+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:r?.label??""})]},"window-"+o)}),t.lidSegments.filter(e=>null==e.windowIndex).map(e=>ar("line",{x1:e.x1,x2:e.x2,y1:e.y1,y2:e.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},e.id)),ar("line",{x1:s.x,x2:s.x+s.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),ar("line",{"data-testid":"event-drop-watermark",x1:y,x2:y,y1:s.y+8,y2:l,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),cr("text",{x:Math.min(s.x+s.width-4,y+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*t.watermarkValue)/100]}),t.lateCount>0?cr("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:[t.lateCount," late"]}):null]})}}(B.projectionRows,B.metadata,w),H=or(e.tooltip,c),L=rr(e,c,N,{selection:F,chartMode:M,className:k,title:I,description:C,summary:R,accessibleTable:P,enableHover:A,margin:S});return ir("EventDropChart",x,fr(Bn,{...c,...H,...L,ref:$,onBodyHover:W,key:`${x[0]}x${x[1]}:${j.rerunKey}`,config:j.config,foregroundGraphics:nr(z,c?.foregroundGraphics),initialSpawns:B.initialSpawns,initialSpawnPacing:B.initialSpawnPacing,paused:u,responsiveHeight:!1,responsiveWidth:!1,size:x,bodyStyle:E}),v)});import{forwardRef as br,useCallback as vr,useMemo as xr,useRef as wr}from"react";import{createElement as kr}from"react";var Ir=br(function(e,t){const{ballRadius:i=8,categoryAccessor:n="category",colorBy:o,data:r,emptyContent:s,frameProps:a,loading:c,loadingContent:d,mechanicalCategories:l,mechanicalCount:u,paused:h,rerunMS:p,seed:m=1,unitValue:y=1,valueAccessor:f,styleRules:g}=e,b=Zo(e,[700,380],{hasSimulationMode:!0}),{chartSize:v,simulationMode:x,showProjection:w,className:k,title:I,chartMode:M,margin:S,enableHover:A,description:C,summary:R,accessibleTable:P}=b,$=wr(null),D="mechanical"===x&&null==f?"value":f,B=xr(()=>"mechanical"===x?function(e={}){const t=(e.categories?.length?e.categories:["Intake","Review","Build","Ship"]).map(e=>(e+"").trim()).filter(Boolean),i=t.length?t:["Intake"],n=Math.max(i.length,Math.round(e.count??Math.max(48,12*i.length))),o=Ln(e.unitValue,1),r=_n(e.seed??1),s=e.idPrefix??"mechanical-pile",a=i.map(()=>.65+.9*r()),c=a.reduce((e,t)=>e+t,0)||1,d=n-i.length,l=a.map(e=>e/c*d),u=l.map(e=>1+Math.floor(e));let h=n-u.reduce((e,t)=>e+t,0);const p=l.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)u[p[e].index]+=1,h-=1;return i.map((e,t)=>({id:`${s}-${t}`,category:e,value:u[t]*o,mechanical:!0,unitCount:u[t],unitValue:o,share:u[t]/n}))}({categories:l,count:u,seed:m,unitValue:y}):r??[],[r,l,u,m,x,y]),j=xr(()=>Qn({data:B,categoryAccessor:n,valueAccessor:D,unitValue:y,ballRadius:i,seed:m,size:v}),[i,n,v,B,D,m,y]),T=Jo(j.config,p,h);Wo(t,{frameRef:$,spawnDatum:vr((e,t)=>{const o=Qn({data:[e],categoryAccessor:n,valueAccessor:D,unitValue:y,ballRadius:i,seed:m+t+1,size:v}),r={id:(e.id??"pile-push-"+t)+"",x:Tn(v).plot.x,y:Tn(v).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e},s=o.initialSpawns.length?o.initialSpawns:[r];return{datumId:(e.id??s[0].id)+"",spawns:s}},[i,n,v,D,m,y]),seedRows:B,seedSpawns:j.initialSpawns});const O="mechanical"===x&&null==o?"category":o,E=xr(()=>Nn(O,"#4e79a7",{styleRules:g,valueAccessor:f}),[O,g,f]),N=xr(()=>En(E,a?.bodyStyle),[E,a?.bodyStyle]),F=xr(()=>Wn(j.projectionRows,v,"category"),[v,j.projectionRows]),{selection:W,onBodyHover:q}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"UnitPileChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof n?[n]:void 0}),z=tr({data:"mechanical"===x?B:r,emptyContent:s,loading:c,loadingContent:d,size:v});if(z)return z;const H=function(e,t,i){if(!1!==i&&0!==e.length)return({size:i})=>{const n=[Number(i[0])||700,Number(i[1])||380],o=Tn(n),r=Kn(o.plot,e.length,t),s=o.plot.y+o.plot.height;return cr("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[ar("line",{x1:o.plot.x,x2:o.plot.x+o.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),e.map((e,t)=>{const i=Math.min(o.plot.height,r.pileHeight(e.value)),a=r.tubeWidth,c=r.centerX(t),d=s-i;return cr("g",{children:[ar("rect",{x:c-a/2,y:d,width:a,height:i,rx:3,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),ar("text",{x:c,y:Math.max(o.plot.y+12,d-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:e.value}),ar("text",{x:c,y:Math.min(n[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${t}`)})]})}}(j.projectionRows,i,w),L=or(e.tooltip,a),Y=rr(e,a,F,{selection:W,chartMode:M,className:k,title:I,description:C,summary:R,accessibleTable:P,enableHover:A,margin:S});return ir("UnitPileChart",v,kr(Bn,{...a,...L,...Y,ref:$,onBodyHover:q,key:`${v[0]}x${v[1]}:${T.rerunKey}`,config:T.config,foregroundGraphics:nr(H,a?.foregroundGraphics),initialSpawns:j.initialSpawns,initialSpawnPacing:j.initialSpawnPacing,paused:h,responsiveHeight:!1,responsiveWidth:!1,size:v,bodyStyle:N}),b)}),Mr=Ir;import{forwardRef as Sr,useCallback as Ar,useMemo as Cr,useRef as Rr}from"react";import{scaleLinear as Pr}from"d3-scale";function $r(e,t){const i=t.config??{},n=(t.sensors??[]).map(e=>({...e,sensor:!0})),o=[...t.colliders??[],...n],r=[...e.colliders??[],...i.colliders??[],...o];return{...e,...i,observation:{...e.observation,...i.observation},...r.length>0&&{colliders:r}}}function Dr(e){const t=function(e,t,i){const n=e?.observation;return{...e,observation:{...n,chartId:t??n?.chartId??"physics-custom",chartType:n?.chartType??"PhysicsCustomChart",onObservation:i??n?.onObservation}}}(e.config,e.chartId,e.onObservation),i=r(e.colorScheme,e.themeCategorical,W),n=Tn(e.size),s={data:e.data,scales:{x:Pr().domain(e.xExtent??[0,1]).range([n.plot.x,n.plot.x+n.plot.width]),y:Pr().domain(e.yExtent??[0,1]).range([n.plot.y+n.plot.height,n.plot.y])},dimensions:n,theme:{semantic:e.semantic,categorical:[...i]},resolveColor:o(i,e.colorScheme),config:e.layoutConfig??{},world:new jt(t)},a=e.skipLayout?{}:e.layout(s)??{},c=function(e,t){if(!t?.length)return e;const i=new Map;for(const e of t){const{bodyId:t,...n}=e,o=i.get(t)??[];o.push(n),i.set(t,o)}return e.map(e=>{const t=i.get(e.id);return t?.length?{...e,springs:[...e.springs??[],...t]}:e})}([...a.initialSpawns??a.bodies??[]],a.constraints);return{config:$r(t,a),context:s,initialSpawnPacing:a.initialSpawnPacing,initialSpawns:c,result:a}}import{createElement as Br}from"react";var jr=Sr(function(e,t){const{chartId:i,color:n,colorBy:o,colorScheme:r,config:s,controllers:a,data:c,emptyContent:d,frameProps:l={},layout:u,layoutConfig:h,loading:p,loadingContent:m,onObservation:y,opacity:f,paused:g,spawnDatum:b,stroke:v,strokeWidth:x,title:w,xExtent:k,yExtent:M}=e,S=Zo(e,[700,380]),{chartSize:A,className:C,title:R,chartMode:P,margin:$,enableHover:D,description:B,summary:j,accessibleTable:T}=S,O=Rr(null),E=Rr(null),N=Rr(""),{selection:F,onBodyHover:W}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:o,chartType:"PhysicsCustomChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:l?.onBodyHover}),q=tr({data:c,emptyContent:d,loading:p,loadingContent:m,size:A}),z=null!=q,H=Cr(()=>I(c??[]),[c]),L=ne(e=>e.theme),Y=Cr(()=>te(L)??{},[L]),_=L?.colors?.categorical??ee.colors.categorical,X=Cr(()=>[A[0],A[1],H.length,H.map((e,t)=>(e.id??t)+"").join("|"),k?.join(",")??"",M?.join(",")??""].join("::"),[A,H,k,M]),G=Cr(()=>Dr({chartId:i,colorScheme:r,config:s,data:H,layout:u,layoutConfig:h,onObservation:y,semantic:Y,skipLayout:z,size:A,themeCategorical:_,xExtent:k,yExtent:M}),[i,A,r,s,u,h,y,H,Y,z,_,k,M]);N.current===X&&null!=E.current||(N.current=X,E.current=G.initialSpawns);const U=E.current,V=Cr(()=>{const e=[...G.result.controllers??[],...a??[],...l.controllers??[]];return e.length?e:void 0},[l.controllers,a,G.result.controllers]),K=Cr(()=>{const e=[...G.result.regionEffects??[],...l.regionEffects??[]];return e.length?e:void 0},[l.regionEffects,G.result.regionEffects]),Q=Ar(e=>{const t=e.datum,i=t&&o?function(e,t,i){return"function"==typeof i?i(e,0):e[i]}(t,0,o)+"":e.id;return{fill:n??G.context.resolveColor(i,t),stroke:v??"#111827",strokeWidth:x??1,opacity:f??.9}},[n,o,f,G.context,v,x]);Wo(t,{frameRef:O,spawnDatum:Ar((e,t)=>{const n=e;if(b)return function(e,t,i){return Array.isArray(i)?{datumId:(e.id??i[0]?.id??"physics-custom-"+t)+"",spawns:i}:"spawns"in i?i:{datumId:(e.id??i.id??"physics-custom-"+t)+"",spawns:[i]}}(e,t,b(n,t,G.context));const o=Dr({chartId:i,colorScheme:r,config:s,data:[n],layout:u,layoutConfig:h,onObservation:y,semantic:Y,size:A,themeCategorical:_,xExtent:k,yExtent:M}),a=o.initialSpawns.length?o.initialSpawns:[{id:(e.id??"physics-custom-"+t)+"",x:o.context.dimensions.plot.x+o.context.dimensions.plot.width/2,y:o.context.dimensions.plot.y+12,mass:1,shape:{type:"circle",radius:5},datum:e}];return{datumId:(e.id??a[0].id)+"",spawns:a}},[i,A,r,s,b,u,h,y,G.context,Y,_,k,M]),seedRows:H,seedSpawns:U});const J=Ar((e,t)=>{l.onBodyPointerDown?.(e,t)},[l]);if(q)return q;const Z=or(e.tooltip,l),ie=rr(e,l,G.result.semanticItems,{selection:F,chartMode:P,className:C,title:R??w,description:B,summary:j,accessibleTable:T,enableHover:D,margin:$});return ir("PhysicsCustomChart",A,Br(Bn,{...l,...Z,...ie,key:`${A[0]}x${A[1]}`,ref:O,onBodyHover:W,backgroundGraphics:nr(l.backgroundGraphics,G.result.backgroundOverlays),bodyForces:G.result.bodyForces??l.bodyForces,bodyStyle:G.result.bodyStyle??l.bodyStyle??Q,config:G.config,controllers:V,foregroundGraphics:nr(l.foregroundGraphics,G.result.overlays),initialSpawnPacing:G.initialSpawnPacing,initialSpawns:U,onBodyPointerDown:J,paused:g,regionEffects:K,responsiveHeight:!1,responsiveWidth:!1,selectedBodyStyle:G.result.selectedBodyStyle??l.selectedBodyStyle,size:A}),S)});jr.displayName="PhysicsCustomChart";import{forwardRef as Tr,useCallback as Or,useMemo as Er,useRef as Nr}from"react";import{jsx as Fr}from"react/jsx-runtime";var Wr=Tr(function(e,t){const{colorBy:i,styleRules:n,collisionIterations:o,data:r,emptyContent:s,frameProps:a,groupAccessor:c,loading:d,loadingContent:l,paused:u,pointRadius:h,radiusAccessor:p,rerunMS:m,seed:y=1,settle:f,xAccessor:g="x",xExtent:b}=e,v=Zo(e,[700,360]),{chartSize:x,showProjection:w,className:k,title:I,chartMode:M,margin:S,enableHover:A,description:C,summary:R,accessibleTable:P}=v,$=h??("sparkline"===M?2:"context"===M?4:5),D=Nr(null),B=Er(()=>r??[],[r]),j=Er(()=>Zn({data:B,xAccessor:g,groupAccessor:c,radiusAccessor:p,pointRadius:$,seed:y,size:x,xExtent:b,collisionIterations:o,settle:f}),[B,x,o,c,$,p,y,f,g,b]),T=Jo(j.config,m,u);Wo(t,{frameRef:D,spawnDatum:Or((e,t)=>{const i=Zn({data:[e],xAccessor:g,groupAccessor:c,radiusAccessor:p,pointRadius:$,seed:y+t+1,size:x,xExtent:b,collisionIterations:o,settle:f}).initialSpawns[0]??{id:(e.id??"collision-swarm-push-"+t)+"",x:Tn(x).plot.x,y:Tn(x).plot.y,mass:1,shape:{type:"circle",radius:$},datum:e};return{datumId:(e.id??i.id)+"",spawns:[i]}},[x,o,c,$,p,y,f,g,b]),seedRows:B,seedSpawns:j.initialSpawns});const O=i??c,E=Er(()=>Nn(O,"#4e79a7",{styleRules:n,valueAccessor:g}),[O,n,g]),N=Er(()=>En(E,a?.bodyStyle),[E,a?.bodyStyle]),{selection:F,onBodyHover:W}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:O,chartType:"CollisionSwarmChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof g?[g]:void 0}),q=tr({data:r,emptyContent:s,loading:d,loadingContent:l,size:x});if(q)return q;const z=function(e,t){if(!1!==t&&e)return({size:t})=>{const i=[Number(t[0])||700,Number(t[1])||360],n=Tn(i),o=n.plot.y+n.plot.height,[r,s]=e.xExtent,a=r+(s-r)/2,c=[{label:dr(r),x:e.xRange[0]},{label:dr(a),x:e.xRange[0]+(e.xRange[1]-e.xRange[0])/2},{label:dr(s),x:e.xRange[1]}];return cr("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[e.groups.map(e=>cr("g",{children:[ar("line",{x1:n.plot.x,x2:n.plot.x+n.plot.width,y1:e.y,y2:e.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),ar("text",{x:n.plot.x+4,y:e.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:e.label}),cr("text",{x:n.plot.x+n.plot.width-4,y:e.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",e.count]})]},e.label)),ar("line",{x1:e.xRange[0],x2:e.xRange[1],y1:o,y2:o,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(e=>cr("g",{children:[ar("line",{x1:e.x,x2:e.x,y1:o,y2:o+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),ar("text",{x:e.x,y:Math.min(i[1]-8,o+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:e.label})]},`${e.label}-${e.x}`))]})}}(j.metadata,w),H=function(e){if(!e)return[];const t=Math.max(24,e.xRange[1]-e.xRange[0]),i=e.xRange[0]+t/2;return e.groups.map(e=>{const n=`${e.label} lane: ${e.count} points`;return{id:"collision-swarm-"+e.label,label:n,description:n,datum:e,x:i,y:e.y,shape:"rect",width:t,height:28,group:"lane"}})}(j.metadata),L=or(e.tooltip,a),Y=rr(e,a,H,{selection:F,chartMode:M,className:k,title:I,description:C,summary:R,accessibleTable:P,enableHover:A,margin:S});return ir("CollisionSwarmChart",x,Fr(Bn,{...a,...L,...Y,ref:D,onBodyHover:W,config:T.config,foregroundGraphics:nr(z,a?.foregroundGraphics),initialSpawns:j.initialSpawns,paused:u,responsiveHeight:!1,responsiveWidth:!1,size:x,bodyStyle:N},`${x[0]}x${x[1]}:${T.rerunKey}`),v)});function qr(e,t={}){const i=t.id??"physics-process-boundary",n={bodyFilter:t.bodyFilter,friction:t.friction,restitution:t.restitution};if("segment"===e.type)return[{...n,id:i,shape:e}];const o=t.thickness??8,r=e.x-e.width/2,s=e.x+e.width/2,a=e.y-e.height/2,c=e.y+e.height/2;return[{...n,id:i+"-top",shape:{type:"segment",x1:r,y1:a,x2:s,y2:a,thickness:o}},{...n,id:i+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:o}},{...n,id:i+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:r,y2:c,thickness:o}},{...n,id:i+"-left",shape:{type:"segment",x1:r,y1:c,x2:r,y2:a,thickness:o}}]}function zr(e){if(!1===e.semanticItem)return null;const t=e.semanticItem??{},i=e.shape,n="aabb"===i.type?{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:i.x,y:i.y,width:i.width,height:i.height}:{id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"region",x:(i.x1+i.x2)/2,y:(i.y1+i.y2)/2,pathData:`M ${i.x1} ${i.y1} L ${i.x2} ${i.y2}`};return{...n,...t,id:t.id??n.id}}function Hr(e){return e.map(e=>({id:e.id,label:e.label??e.id,description:e.description,group:e.kind??"stage",x:e.x??0,y:e.y??0,width:e.width,height:e.height}))}function Lr(e){return e.flatMap(e=>{if(!1===e.semanticItem)return[];const t=e.semanticItem??{},i={id:e.id,label:e.label??e.id,description:e.description,datum:e.datum,group:e.group??e.state??"body group",x:e.x??0,y:e.y??0,width:e.width,height:e.height};return[{...i,...t,id:t.id??i.id}]})}function Yr(e){return e?Array.isArray(e)?[...e]:Object.entries(e).flatMap(([e,t])=>Array.from({length:Math.max(0,Math.round(Number(t)||0))},()=>e)):[]}function _r(e,t){return t?Array.isArray(t)?[...t]:t.ids?[...t.ids]:t.candidates?t.candidates.filter(t=>e.includes(t)).slice(0,t.count??1):[]:[]}function Xr(e,t){return _r(e.activePositiveIds,t.popPositive)}function Gr(e){const t=Number(e.budget),i=Number.isFinite(t)?Math.max(0,t):0,n=e.properties instanceof Map?e.properties:new Map(e.properties.map(e=>[e.id,e])),o=e.candidates?new Set(e.candidates):null,r=e.attachedIds.map((e,t)=>{const i=n.get(e),o=Number(i?.work??1),r=Number(i?.priority??t);return{id:e,index:t,priority:Number.isFinite(r)?r:t,work:Number.isFinite(o)&&o>0?o:1}}).filter(e=>!o||o.has(e.id)).sort((e,t)=>e.priority-t.priority||e.index-t.index),s=[],a=[];let c=0;for(const e of r)c+e.work>i+Number.EPSILON?a.push(e.id):(s.push(e.id),c+=e.work);return{ids:s,used:c,budget:i,remaining:Math.max(0,i-c),skippedIds:a}}function Ur(e,t){if(!t.from||!t.to||t.from===t.to)return{};const i=Math.max(0,Math.floor(Number(t.count??1)||0)),n=e.negativeIds.filter(e=>e===t.from).length,o=Math.min(i,n);return o?{addNegative:{[t.to]:o},popNegative:{ids:Array.from({length:o},()=>t.from)}}:{}}function Vr(e,t){const i=_r(e.negativeIds,t.popNegative);if(!i.length)return[];const n=new Map;for(const e of i)n.set(e,(n.get(e)??0)+1);const o=[];return e.negativeIds.forEach((e,t)=>{const i=n.get(e)??0;i>0&&(o.push({propertyId:e,index:t}),n.set(e,i-1))}),o}function Kr(e,t,i){if(t.when&&!t.when(i))return e;let n={...e};const o=Xr(n,t);o.length&&(n={...n,activePositiveIds:n.activePositiveIds.filter(e=>!o.includes(e)),poppedPositiveIds:Array.from(new Set([...n.poppedPositiveIds,...o]))});const r=Vr(n,t);if(r.length){const e=new Set(r.map(e=>e.index));n={...n,negativeIds:n.negativeIds.filter((t,i)=>!e.has(i)),poppedNegativeIds:[...n.poppedNegativeIds,...r.map(e=>e.propertyId)]}}const s=Yr(t.addPositive);s.length&&(n={...n,activePositiveIds:Array.from(new Set([...n.activePositiveIds,...s])),missingPositiveIds:n.missingPositiveIds.filter(e=>!s.includes(e))});const a=Yr(t.addNegative);if(a.length&&(n={...n,negativeIds:[...n.negativeIds,...a]}),t.delayDelta&&(n={...n,delay:n.delay+t.delayDelta}),t.metricsDelta){const e={...n.metrics};for(const[i,n]of Object.entries(t.metricsDelta))e[i]=Number(e[i]??0)+n;n={...n,metrics:e}}return t.viabilityDelta&&(n={...n,viability:n.viability+t.viabilityDelta}),t.stage&&(n={...n,stage:t.stage}),t.outcome&&(n={...n,outcome:t.outcome}),n}function Qr(e,t){return{id:e.id,label:e.label??e.id,summary:e.summary??t.find(e=>e.summary)?.summary,time:e.time}}function Jr(e,t){return e.eventsApplied.includes(t.id)?e:{...e,eventsApplied:[...e.eventsApplied,t.id],eventHistory:[...e.eventHistory??[],t],lastEvent:t,stage:t.label??e.stage}}var Zr="gauntlet-core",es="gauntlet-positive",ts="gauntlet-negative";function is(e){const t=ds(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 ns(e,t,i,n){return i?"function"==typeof i?i(e,t):e[i]??n:n}function os(e){return e?.label??e?.id??"property"}function rs(e){return`gauntlet:${e}:core`}function ss(e,t){return`gauntlet:${e}:positive:${t}`}function as(e,t,i){return`gauntlet:${e}:negative:${t}:${i}`}var cs={left:28,top:76,rightInset:30,thickness:8};function ds(e){const t=e.height??e.floorY+36;if(e.width>=220&&t>=160)return cs;const i=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*i))}}function ls(e){return Math.max(.12,Math.min(1,e.width/500,(e.height??e.floorY+36)/260))}function us(e,t,i,n){const o=ds(n),r=Math.max(2,i+2),s=o.top+o.thickness/2+r,a=n.floorY-r,c=(e,t,i)=>t>i?(t+i)/2:Math.max(t,Math.min(i,e));return{x:c(e,o.left+o.thickness/2+r,n.width-o.rightInset-o.thickness/2-r),y:c(t,s,a)}}function hs(e){return{graveyardX:e.graveyardX,graveyardY:e.graveyardY,routeY:e.routeY,socketX:e.socketX,socketY:e.routeY-4,startX:e.startX,startY:e.routeY}}function ps(e,t,i,n){const o=hs(i),r=n?.(e,t,i)??{};return{...o,...r,startY:r.startY??r.routeY??o.startY,socketY:r.socketY??r.routeY??o.socketY,graveyardY:r.graveyardY??o.graveyardY}}function ms(e,t,i=1){const n=[...e].sort((e,t)=>e.localeCompare(t)),o=Math.max(0,n.indexOf(t));return{angle:.82*-Math.PI+(n.length>1?o/(n.length-1):.5)*Math.PI*.64,index:o,radius:(48+o%2*6)*i}}function ys(e,t,i){const n=e.activePositiveIds.reduce((e,i)=>e+(t.get(i)?.value??1),0),o=e.missingPositiveIds.length+e.poppedPositiveIds.length,r=e.negativeIds.reduce((e,t)=>e+(i.get(t)?.load??1),0);return Math.max(0,Math.min(100,75+3*n-8*r-1.2*e.delay-5*o))}function fs(e,t,i,n,o){const r=ns(e,t,i.idAccessor,null!=e.id?e.id+"":"project-"+t)+"",s=n.map(e=>e.id),a=[...ns(e,t,i.positiveAccessor,s)],c=[...ns(e,t,i.negativeAccessor,[])].filter(e=>o.has(e));return{id:r,activePositiveIds:a,datum:e,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...ns(e,t,i.metricsAccessor,{})},missingPositiveIds:s.filter(e=>!a.includes(e)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(ns(e,t,i.startTimeAccessor,0))||0),stage:"project filed",viability:ns(e,t,i.initialViability,100)}}function gs(e,t,i,n,o,r,s){const a=ls(i),c=Math.max(3,28*a),d=n.startX,l=n.startY+(n.startY===i.routeY?38*t*a:0),u=s?.(e,t,i,n)??{},h=u.x??d,p=u.y??l,m={__gauntlet:!0,kind:Zr,projectId:e.id,sourceDatum:e.datum},y=[{...u,id:rs(e.id),x:h,y:p,vx:u.vx??42,vy:u.vy??0,mass:u.mass??7,bodyCollisions:u.bodyCollisions??!0,shape:u.shape??{type:"circle",radius:c},spawnAt:u.spawnAt??e.startedAt,datum:m}],f=us(h,p,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,i);y[0].x=f.x,y[0].y=f.y;for(const t of e.activePositiveIds){const n=o.get(t);if(!n)continue;const r=ms(e.activePositiveIds,t,a),s=n.radius??Math.max(2,10*a),c=us(f.x+Math.cos(r.angle)*r.radius,f.y+Math.sin(r.angle)*r.radius,s,i);y.push({id:ss(e.id,t),x:c.x,y:c.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:u.spawnAt??e.startedAt,datum:{__gauntlet:!0,kind:es,projectId:e.id,property:n,sourceDatum:e.datum},springs:!1===n.spring?[]:[{target:{type:"body",bodyId:rs(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 o=r.get(t);o&&y.push(bs(e,o,n,f.x,f.y,i,u.spawnAt??e.startedAt))}),y}function bs(e,t,i,n,o,r,s){const a=ls(r),c=t.radius??Math.max(2,7.2*a),d=us(n+(i%4*12-12)*a,o+(54+12*Math.floor(i/4))*a,c,r);return{id:as(e.id,t.id,i),x:d.x,y:d.y,vx:10,vy:6,mass:t.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:ts,projectId:e.id,property:t,sourceDatum:e.datum},springs:!1===t.spring?[]:[{target:{type:"body",bodyId:rs(e.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+i%4*3)*a),...t.spring??{}}]}}import{forwardRef as vs,useCallback as xs,useEffect as ws,useImperativeHandle as ks,useMemo as Is,useRef as Ms,useState as Ss}from"react";function As(e,t){const i=e.datum;return!(!i?.__gauntlet||i.projectId!==t||i.kind!==ts)}function Cs(e){const t=e.id.slice(e.id.lastIndexOf(":")+1),i=Number(t);return Number.isFinite(i)?i:-1}function Rs(e,t){return 2>Math.hypot(e.vx,e.vy)&&4>Math.hypot(t.x,t.y)?null:t}import{Fragment as Ps,jsx as $s,jsxs as Ds}from"react/jsx-runtime";var Bs="var(--semiotic-surface, var(--semiotic-bg, #fff))";function js(e){const t=e.data;return t?.__gauntlet?Ds("div",{className:"semiotic-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(15, 23, 42, 0.94))",color:"var(--semiotic-tooltip-text, #f8fafc)",padding:"8px 12px",borderRadius:6,boxShadow:"var(--semiotic-tooltip-shadow, 0 8px 24px rgba(0,0,0,0.35))",maxWidth:280},children:[$s("strong",{children:t.kind===Zr?"string"==typeof t.sourceDatum?.label?t.sourceDatum.label:t.projectId:os(t.property)}),$s("div",{children:t.kind===es?"Positive property":t.kind===ts?"Negative property":"Project core"})]}):null}function Ts(e,t,i,n){const o=t.datum;if(!o?.__gauntlet)return;const r="circle"===t.shape.type?t.shape.radius:8,s=n?.resolvePaint??((t,i)=>N(e,t,i));if(e.save(),e.translate(t.x,t.y),o.kind===Zr)e.fillStyle=s(i.fill,"#0f766e"),e.strokeStyle=s(i.stroke,"#fff"),e.lineWidth=2.4,e.beginPath(),e.arc(0,0,r,0,2*Math.PI),e.fill(),e.stroke();else{const t=o.property;e.fillStyle=s(i.fill??t?.color,"#38bdf8"),e.strokeStyle=s(i.stroke,"#0f172a"),e.lineWidth=1.1,e.beginPath(),o.kind===ts?e.rect(-r,-r,2*r,2*r):e.arc(0,0,r,0,2*Math.PI),e.fill(),e.stroke(),e.fillStyle=s(Bs,"#fff"),e.font=`900 ${o.kind===ts?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,e.textAlign="center",e.textBaseline="middle",e.fillText(t?.short??t?.id?.slice(0,1).toUpperCase()??"?",0,.5)}e.restore()}function Os({layout:e,compact:t,showLabels:i}){const n=t?Math.round(.14*e.height):Math.max(80,e.routeY-180),o=t?Math.max(6,Math.round(.72*e.height)):Math.min(360,e.height-170);return $s(Ps,{children:e.gates.map(r=>Ds("g",{children:[$s("rect",{x:r.x-r.width/2,y:n,width:r.width,height:o,rx:t?2:12,fill:r.color??"var(--semiotic-primary, #38bdf8)",fillOpacity:.1,stroke:r.color??"var(--semiotic-primary, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),i?$s("text",{x:r.x,y:Math.max(64,e.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:r.label??r.id}):null]},r.id))})}function Es({layout:e,states:t,compact:i=!1}){return i?$s("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:$s(Os,{layout:e,compact:!0,showLabels:!1})}):Ds("svg",{"aria-hidden":"true",viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[$s("path",{d:`M ${e.startX-42} ${e.routeY} C ${.24*e.width} ${e.routeY-70}, ${.42*e.width} ${e.routeY+78}, ${.58*e.width} ${e.routeY} S ${.78*e.width} ${e.routeY-82}, ${e.socketX+36} ${e.routeY}`,fill:"none",stroke:"var(--semiotic-primary, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),$s("line",{x1:Math.round(.06*e.width),x2:Math.round(.94*e.width),y1:e.crashY,y2:e.crashY,stroke:"var(--semiotic-danger, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),$s("text",{x:Math.round(.07*e.width),y:e.crashY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),$s(Os,{layout:e,compact:!1,showLabels:!0}),Ds("g",{children:[$s("rect",{x:e.socketX-52,y:e.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-success, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-success, #22c55e)",strokeWidth:1.5}),$s("text",{x:e.socketX,y:e.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),Ds("g",{children:[$s("rect",{x:e.graveyardX-82,y:e.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-danger, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-danger, #ef4444)",strokeOpacity:.7}),$s("text",{x:e.graveyardX,y:e.graveyardY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),$s("text",{x:e.graveyardX,y:e.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:t.some(e=>e.killed)?"lift shut off":"too heavy or too small"})]})]})}function Ns(e){const t=e.datum;return!!t?.__gauntlet&&(t.kind===Zr?{label:t.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${os(t.property)} ${t.kind===es?"positive":"negative"} property`,group:t.kind===es?"positive property":"negative property",description:`${os(t.property)} attached to ${t.projectId}.`})}function Fs({states:e,layout:t}){const i=function(e){return e.map(e=>({label:e.id,value:Math.max(0,Number(e.viability)||0),outcome:e.outcome||e.stage||"in-process"}))}(e);if(!i.length)return null;const n=Math.max(1,...i.map(e=>e.value)),o=Math.max(40,(t.width-80)/i.length);return Ds("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[$s("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),i.map((e,t)=>{const i=40+t*o,r=Math.max(2,e.value/n*28),s=/kill|crash|block|grave/i.test(e.outcome);return Ds("g",{children:[$s("rect",{x:i+.18*o,y:28-r+22,width:Math.max(10,.45*o),height:r,rx:2,fill:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",fillOpacity:.35,stroke:s?"var(--semiotic-danger, #ef4444)":"var(--semiotic-success, #16a34a)",strokeOpacity:.55,strokeWidth:1}),$s("text",{x:i+.4*o,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:e.label})]},e.label)})]})}import{jsx as Ws}from"react/jsx-runtime";import{createElement as qs}from"react";var zs=[],Hs=vs(function(e,t){const{bodyGroups:i,coreBody:n,coreForceMode:o="route",crashDetection:r=!0,crashOffset:s=30,data:a,emptyContent:c,events:d,frameProps:l={},gates:u,initialSpawnPacing:h,loading:p,loadingContent:m,negativeProperties:y,onCapacityChange:f,onClick:g,onStateChange:b,outcome:v,paused:x,positiveProperties:w=zs,projectPlacement:k,rerunMS:M,seed:S,showTethers:A=!0,terminalBehavior:C="outcome",viability:R}=e,P=Ms(null),$=Is(()=>({idAccessor:e.idAccessor,initialViability:e.initialViability,metricsAccessor:e.metricsAccessor,negativeAccessor:e.negativeAccessor,positiveAccessor:e.positiveAccessor,startTimeAccessor:e.startTimeAccessor}),[e.idAccessor,e.initialViability,e.metricsAccessor,e.negativeAccessor,e.positiveAccessor,e.startTimeAccessor]),D=Zo(e,[900,520]),{chartSize:B,showProjection:j,showChrome:T,className:O,title:E,chartMode:F,margin:W,enableHover:q,description:z,summary:H,accessibleTable:L}=D,{selection:Y,onBodyHover:_}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:void 0,chartType:"GauntletChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:l?.onBodyHover,fallbackFields:"string"==typeof e.idAccessor?[e.idAccessor]:["id"],unwrapSourceDatum:!0}),X=tr({data:a,emptyContent:c,loading:p,loadingContent:m,size:B}),G=Is(()=>I(a??[]),[a]),U=Is(()=>G.map((e,t)=>ns(e,t,$.idAccessor,null!=e.id?e.id+"":"project-"+t)+"").join("|"),[G,$.idAccessor]),V=Is(()=>new Map(w.map(e=>[e.id,e])),[w]),K=Is(()=>new Map(y.map(e=>[e.id,e])),[y]),Q=Is(()=>function(e,t,i){const[n,o]=e,r=220>n||160>o,s=Math.round(.48*o),a=r?o-Math.max(3,Math.min(12,.1*o)):o-36,c=(t??[]).filter(e=>!1!==e.enabled),d=Math.max(1,c.length),l=.22*n,u=d>1?(.78*n-l)/(d-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(i,Math.max(3,.22*o)):i),floorY:a,gates:c.map((e,t)=>({...e,id:e.id,x:e.x??Math.round(l+t*u),width:e.width??Math.max(r?8:54,Math.round(.07*n))})),graveyardX:Math.round(n*(r?.72:.84)),graveyardY:a-4,height:o,routeY:s,socketX:Math.round(n*(r?.82:.92)),startX:h,width:n}}(B,u,s),[B,s,u]),J=Is(()=>new Map(Q.gates.map(e=>[e.id,e])),[Q.gates]),Z=Is(()=>Q.gates.map(e=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...e.regionEffect,id:"gauntlet-gate-"+e.id,label:e.label??e.id,description:e.description,bodyFilter:e.capacity?{property:"datum.kind",equals:Zr}:e.regionEffect?.bodyFilter,shape:{type:"aabb",x:e.x,y:Q.routeY,width:e.capacity?e.capacity.sensorWidth??Math.max(220>Q.width?12:96,e.width*(220>Q.width?2:6)):Math.max(e.width,220>Q.width?10:54),height:Math.max(4,Math.min(360,Q.height-(160>Q.height?8:170)))}})),[Q.gates,Q.height,Q.routeY,Q.width]),[ee,te]=Ss(()=>G.map((e,t)=>{const i=fs(e,t,$,w,K);return{...i,viability:R?.(i,{negativeProperties:K,positiveProperties:V})??ys(i,V,K)}})),ie=Ms(ee),ne=Ms(0),oe=Ms(new Map),re=Ms([]),se=Ms(f);se.current=f;const ae=Ms(G);ae.current=G;const ce=Ms(b);ce.current=b;const de=Ms({negativeById:K,positiveById:V,positiveProperties:w,stateAccessors:$,viability:R});de.current={negativeById:K,positiveById:V,positiveProperties:w,stateAccessors:$,viability:R};const le=xs((e,t,i=0)=>{const n=de.current,o=fs(e,t,n.stateAccessors,n.positiveProperties,n.negativeById);return n.stateAccessors.startTimeAccessor||(o.startedAt=Math.max(0,i)),{...o,viability:n.viability?.(o,{negativeProperties:n.negativeById,positiveProperties:n.positiveById})??ys(o,n.positiveById,n.negativeById)}},[]),ue=xs(()=>{oe.current.clear(),re.current=[],ne.current=0;const e=ae.current.map((e,t)=>le(e,t));ie.current=e,te(e)},[le]),he=Jo(Is(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...null!=S&&{seed:S},...l.config?.kernel??{}},colliders:[...is(Q),...l.config?.colliders??[]]}),[l.config?.colliders,l.config?.kernel,Q,S]),M,x,ue),pe=Is(()=>function(e){const{dataKey:t,gates:i,statesRef:n,processedGateVisitsRef:o}=e;return i.flatMap(e=>e.capacity&&e.capacity.unitsPerSecond>0?[Nt({id:`gauntlet-capacity-${t}-${e.id}`,regionId:"gauntlet-gate-"+e.id,unitsPerSecond:e.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Zr},maxQueue:e.capacity.maxQueue,queueLayout:e.capacity.queueLayout,queueSlotSpacing:e.capacity.queueSlotSpacing,queueStiffness:e.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:t=>{const i=t.datum,o=i?.sourceDatum,r=e.capacity?.unitAccessor,s=n.current.find(e=>e.id===i?.projectId);let a;"function"==typeof r?a=s?r(s):void 0:r&&(a=o?.[r]);const c=Number(a??o?.reviewWork??o?.work??s?.metrics.reviewWork??o?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:t=>{const i=t.datum;if(!i?.projectId)return;const n=`${i.projectId}:${e.id}`;o.current.set(n,(o.current.get(n)??0)+1)}})]:[])}({dataKey:`${U}:${he.rerunKey}`,gates:Q.gates,statesRef:ie,processedGateVisitsRef:oe}),[U,Q.gates,he.rerunKey]),me=Is(()=>[...pe,...l.controllers??[]],[pe,l.controllers]);ws(()=>{oe.current.clear(),re.current=[],ne.current=0;const e=ae.current.map((e,t)=>le(e,t));ie.current=e,te(e)},[le,U]),ws(()=>{ie.current=ee,ce.current?.(ee)},[ee]);const ye=xs(e=>[...("function"==typeof d?d(e,Q):d)??[]].sort((e,t)=>e.time-t.time),[d,Q]),fe=xs((e,t,i)=>{if(!t.gateId||!J.get(t.gateId)?.capacity)return!0;const n=Number(t.gateVisit),o=Number.isFinite(n)&&n>0?Math.floor(n):i.filter(e=>e.gateId===t.gateId).findIndex(e=>e.id===t.id)+1;return o>0&&(oe.current.get(`${e.id}:${t.gateId}`)??0)>=o},[J]),ge=xs(()=>{if(!pe.length)return;const e=pe.flatMap(e=>{const t=e.getSnapshot?.();return t?[t]:[]});var t,i;(t=re.current).length===(i=e).length&&t.every((e,t)=>{const n=i[t];return!!n&&e.regionId===n.regionId&&e.queueDepth===n.queueDepth&&e.blockedDepth===n.blockedDepth&&e.processedCount===n.processedCount&&e.metricRevision===n.metricRevision})||(re.current=e,se.current?.(e))},[pe]),be=Is(()=>ee.flatMap((e,t)=>{const i=ps(e,t,Q,k);return gs(e,t,Q,i,V,K,n)}),[n,Q,K,V,k,ee]),ve=xs((e,t)=>{let i=!1;const n=ie.current.map(n=>{if(n.id!==e)return n;const o=t(n);return i=i||o!==n,o});i&&(ie.current=n,te(n))},[]);ks(t,()=>function(e){const{statesRef:t,setStates:i,elapsedRef:n,frameRef:o,layout:r,projectPlacement:s,positiveById:a,negativeById:c,coreBody:d,createState:l}=e;return{push:e=>{const u=l(e,t.current.length,n.current),h=ps(u,t.current.length,r,s),p=gs(u,t.current.length,r,h,a,c,d),m=[...t.current,u];t.current=m,i(m),o.current?.pushMany(p),o.current?.step(0)},pushMany:e=>{const u=[...t.current],h=[],p=n.current;e.forEach(e=>{const t=l(e,u.length,p),i=ps(t,u.length,r,s);h.push(...gs(t,u.length,r,i,a,c,d)),u.push(t)}),t.current=u,i(u),h.length&&o.current?.pushMany(h),o.current?.step(0)},remove:e=>{const n=Array.isArray(e)?e:[e],r=[],s=[];for(const e of n){const i=t.current.find(t=>t.id===e);i&&(r.push(i.datum),s.push(rs(i.id),...i.activePositiveIds.map(e=>ss(i.id,e))),i.negativeIds.forEach((e,t)=>{s.push(as(i.id,e,t))}))}return t.current=t.current.filter(e=>!n.includes(e.id)),i(t.current),o.current?.remove(s),r},update:(e,u)=>{const h=Array.isArray(e)?e:[e],p=[];for(const e of h){const i=t.current.find(t=>t.id===e);if(!i)continue;const h=t.current.findIndex(t=>t.id===e);p.push(i.datum);const m=u(i.datum),y=l(m,0>h?t.current.length:h,i.startedAt??n.current),f=ps(y,0>h?t.current.length:h,r,s);o.current?.remove([rs(i.id),...i.activePositiveIds.map(e=>ss(i.id,e)),...i.negativeIds.map((e,t)=>as(i.id,e,t))]),o.current?.pushMany(gs(y,0>h?t.current.length:h,r,f,a,c,d)),t.current=t.current.map(t=>t.id===e?y:t)}return i(t.current),p},clear:()=>{t.current=[],i([]),o.current?.clear()},getData:()=>t.current.map(e=>e.datum),getScales:()=>null,getCustomLayout:()=>o.current?.snapshot()??null,popBodies:(e,t)=>o.current?.popBodies(e,t)??[]}}({statesRef:ie,setStates:te,elapsedRef:ne,frameRef:P,layout:Q,projectPlacement:k,positiveById:V,negativeById:K,coreBody:n,createState:le}),[n,le,Q,K,V,k]);const xe="sparkline"===F?.22:"mobile"===F?.55:1,we=xs((e,t,i)=>{!function(e){const{project:t,effect:i,controls:n,layout:o,positiveById:r,negativeById:s,coreBody:a,popBodies:c,popScale:d}=e,l=n.readBodies().find(e=>e.id===rs(t.id)),u=n.readBodies(),h=l?.x??o.startX,p=l?.y??o.routeY,m=function(e,t){let i=-1;for(const n of t)As(n,e.id)&&(i=Math.max(i,Cs(n)));return Math.max(e.negativeIds.length,i+1)}(t,u),y=Yr(i.addNegative).flatMap((e,i)=>{const n=s.get(e);return n?[bs(t,n,m+i,h,p,o)]:[]}),f=Yr(i.addPositive).flatMap(e=>{if(!r.get(e)||t.activePositiveIds.includes(e))return[];const i={...hs(o),routeY:p,socketY:p,startX:h,startY:p};return gs({...t,activePositiveIds:[e],negativeIds:[]},0,o,i,r,s,a).filter(e=>e.id.includes(":positive:"))});(y.length||f.length)&&n.pushMany([...y,...f]);const g=Xr(t,i);for(const e of g){const i=r.get(e);c([ss(t.id,e)],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??10)+3,scale:d})}const b=Vr(t,i),v=function(e,t,i){const n=t.filter(t=>As(t,e.id)).sort((e,t)=>Cs(e)-Cs(t)||e.id.localeCompare(t.id)),o=new Set;return i.map(t=>{const i=n.find(e=>!o.has(e.id)&&e.datum.property?.id===t.propertyId);return i?(o.add(i.id),i.id):as(e.id,t.propertyId,t.index)})}(t,u,b);b.forEach((e,t)=>{const i=s.get(e.propertyId);c([v[t]],{color:i?.popColor??i?.color,durationMs:900,radius:(i?.radius??7)+3,scale:d})})}({project:e,effect:t,controls:i,layout:Q,positiveById:V,negativeById:K,coreBody:n,popBodies:(e,t)=>P.current?.popBodies(e,t),popScale:xe})},[n,Q,K,V,xe]),ke=xs(({body:e,bodies:t})=>function(e){const{body:t,bodies:i,layout:n,states:o,projectPlacement:r,positiveById:s,negativeById:a,projectEvents:c,gateById:d,coreForceMode:l,terminalBehavior:u,elapsed:h}=e,p=t.datum;if(!p?.__gauntlet)return null;const m=o.findIndex(e=>e.id===p.projectId),y=0>m?void 0:o[m];if(!y)return null;const f=ps(y,m,n,r),g=i.find(e=>e.id===rs(y.id)),b=ls(n),v=y.negativeIds.reduce((e,t)=>e+(a.get(t)?.load??1),0),x=y.killed?0:58*Math.max(.25,b);if(p.kind!==Zr){if(!g)return null;let e;const o=p.property;if(o?.target){const r=i.filter(e=>{const t=e.datum;return t?.__gauntlet&&t.projectId===y.id&&t.kind===p.kind}).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),s=Math.max(0,r.findIndex(e=>e.id===t.id));e=o.target({body:t,bodies:i,core:g,index:s,layout:n,placement:f,project:y})??{x:g.x,y:g.y}}else if(p.kind===es&&p.property){const t=ms(y.activePositiveIds,p.property.id,b);e={x:g.x+Math.cos(t.angle)*t.radius,y:g.y+Math.sin(t.angle)*t.radius-2}}else{const n=i.filter(e=>e.datum?.kind===ts&&e.datum.projectId===y.id).sort((e,t)=>(e.id+"").localeCompare(t.id+"")),o=Math.max(0,n.findIndex(e=>e.id===t.id)),r=Math.floor(o/4);e={x:g.x+18*(o%4-(Math.min(4,n.length-4*r)-1)/2)*b,y:g.y+(54+13*r)*b}}const r="circle"===t.shape.type?t.shape.radius:8;e=us(e.x,e.y,r,n);const s=us(t.x,t.y,r,n);if(Math.abs(s.x-t.x)>.5||Math.abs(s.y-t.y)>.5)return{x:48*(s.x-t.x)-6*t.vx,y:48*(s.y-t.y)-6*t.vy};const a=p.kind!==es||y.killed?0:3.2*(o?.buoyancy??o?.value??1),c=p.kind===ts?{x:.22*(o?.pull?.x??-8),y:.22*(o?.pull?.y??22)}:{x:0,y:0};return Rs(t,{x:28*(e.x-t.x)-3*(t.vx-g.vx)+c.x+.01*x,y:28*(e.y-t.y)-3*(t.vy-g.vy)+c.y-a})}if(y.killed)return Rs(t,{x:44*((y.crashX??y.metrics.lastX??t.x)-t.x)-9*t.vx,y:(160+12*v)*b-1.6*t.vy});const w=c(y),k=function(e,t,i,n,o,r,s){const a=ls(i);if(t.killed)return{x:t.metrics.lastX??n.graveyardX,y:n.graveyardY};const c=o[o.length-1];if(!c)return{x:n.socketX,y:n.routeY};const d=o.find(i=>e>=i.time&&!t.eventsApplied.includes(i.id)&&!(!i.gateId||!r.get(i.gateId)?.capacity)),l=d?Math.min(e,d.time):e,u="built"===t.outcome||"built_diminished"===t.outcome;if(l>c.time+.85){if("hold-last"===s){const e=c.gateId?r.get(c.gateId):void 0;return{x:c.routeX??e?.x??n.socketX,y:c.routeY??n.routeY}}return u?{x:n.socketX,y:n.socketY}:{x:n.graveyardX,y:n.graveyardY-14}}const h=.85*t.delay+12*t.negativeIds.length+8*(t.poppedPositiveIds.length+t.missingPositiveIds.length),p=[{time:0,x:n.startX,y:n.startY},...o.map(e=>{const t=e.gateId?r.get(e.gateId):void 0;return{time:e.time,x:e.routeX??t?.x??n.startX,y:e.routeY??n.routeY+.28*Math.min(180,h)*a}})].sort((e,t)=>e.time-t.time);let m=p[0],y=p[p.length-1];for(let e=1;p.length>e;e+=1){if(p[e].time>=l){y=p[e];break}m=p[e]}const f=Math.max(0,Math.min(1,(l-m.time)/Math.max(.1,y.time-m.time))),g=f*f*(3-2*f);return{x:m.x+(y.x-m.x)*g,y:m.y+(y.y-m.y)*g+7*Math.sin(2.6*l)*a}}(Math.max(0,h-(y.startedAt??0)),y,n,f,w,d,u),I=y.activePositiveIds.reduce((e,t)=>e+(s.get(t)?.buoyancy??s.get(t)?.value??1),0);return Rs(t,"net"===l?{x:15*(k.x-t.x)-1.8*t.vx+.18*x,y:1.25*(f.routeY-t.y)-1.4*t.vy+32*(v-I)}:{x:15*(k.x-t.x)-1.8*t.vx+.18*x,y:15*(k.y-t.y)-1.8*t.vy+13*v-2.2*I})}({body:e,bodies:t,layout:Q,states:ie.current,projectPlacement:k,positiveById:V,negativeById:K,projectEvents:ye,gateById:J,coreForceMode:o,terminalBehavior:C,elapsed:ne.current}),[o,J,Q,K,V,ye,k,C]),Ie=xs((e,t)=>{!function(e,t,i){const{frameProps:n,elapsedRef:o,statesRef:r,crashDetection:s,layout:a,projectEvents:c,gateById:d,capacityEventReady:l,addBodiesForEffect:u,updateProjectState:h,viability:p,positiveById:m,negativeById:y,outcome:f,reportCapacity:g}=i;n.onTick?.(e,t),o.current=e.elapsedSeconds??t.snapshot().elapsedSeconds,g();for(const e of r.current){const i=t.readBodies().find(t=>t.id===rs(e.id));if(!i)continue;if(s&&!e.killed&&i.y+("circle"===i.shape.type?i.shape.radius:28)>=a.crashY){t.readBodies().forEach(i=>{const n=i.datum;n?.__gauntlet&&n.projectId===e.id&&t.applyImpulse(i.id,-i.vx*i.mass,0)}),h(e.id,e=>{const t={appliedAt:Math.max(0,o.current-(e.startedAt??0)),id:"gauntlet-crash-line",label:"Crash Line",summary:"The project hit the crash threshold; lift and forward motion shut off.",time:Math.max(0,o.current-(e.startedAt??0))};return{...e,crashX:i.x,eventHistory:[...e.eventHistory??[],t],killed:!0,lastEvent:t,metrics:{...e.metrics,lastX:i.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,e.viability)}});continue}if(e.killed)continue;const n=Math.max(0,o.current-(e.startedAt??0)),r=c(e),g=r.filter(t=>n>=t.time&&!e.eventsApplied.includes(t.id)&&l(e,t,r));let b=e;for(const i of g){const o=i.gateId?d.get(i.gateId):void 0,r=i.effects??[];for(const e of r){const n={event:i,gate:o,negativeProperties:y,positiveProperties:m,project:b};e.when&&!e.when(n)||(u(b,e,t),b=Kr(b,e,n))}const s={...Qr(i,r),appliedAt:n};b=Jr(b,s),h(e.id,e=>{let t=Jr(e,s);if(t===e)return e;for(const e of r)t=Kr(t,e,{event:i,gate:o,negativeProperties:y,positiveProperties:m,project:t});const n=p?.(t,{negativeProperties:y,positiveProperties:m})??ys(t,m,y);return t={...t,viability:n},i.final&&(t={...t,outcome:i.outcome??f?.(t,{layout:a,negativeProperties:y,positiveProperties:m})??(t.viability>20?"built":"approved_not_built")}),t})}}}(e,t,{frameProps:l,elapsedRef:ne,statesRef:ie,crashDetection:r,layout:Q,projectEvents:ye,gateById:J,capacityEventReady:fe,addBodiesForEffect:we,updateProjectState:ve,viability:R,positiveById:V,negativeById:K,outcome:v,reportCapacity:ge})},[we,fe,r,l,J,Q,K,v,V,ye,ge,ve,R]),Me=xs((e,t)=>{const i="function"==typeof l.bodyStyle?l.bodyStyle(e,t):l.bodyStyle,n=e.datum;return n?.__gauntlet?{fill:n.kind===Zr?"var(--semiotic-primary, #0f766e)":n.property?.color??"var(--semiotic-primary, #38bdf8)",stroke:n.kind===Zr?Bs:"var(--semiotic-text, #0f172a)",opacity:.96,...i}:i??{}},[l]),Se=Is(()=>"function"==typeof i?i(ee,Q):i??[],[i,Q,ee]),Ae=Is(()=>Lr(Se),[Se]),Ce=Is(()=>j?function(e,t){if(!e.length)return[];const i=Math.max(40,(t.width-80)/e.length);return e.map((e,t)=>{const n=`${e.id}: viability ${Math.round(e.viability)}, ${e.outcome||e.stage}`;return{id:"gauntlet-projection-"+e.id,label:n,description:n,datum:e,x:40+(t+.5)*i,y:28,shape:"rect",width:Math.max(16,.55*i),height:22,group:"settled projection"}})}(ee,Q):[],[Q,j,ee]),Re=Is(()=>[...Ce,...Ae],[Ae,Ce]),Pe=xs((e,t)=>{l.onBodyPointerDown?.(e,t)},[l]),$e=xs((e,t)=>{g&&(e&&"object"==typeof e&&e.__gauntlet?g(e.sourceDatum,{x:t.x,y:t.y}):e&&g(e,{x:t.x,y:t.y}))},[g]),De=xs((e,t,i)=>{l.beforePaint?.(e,t,i),A&&function(e,t,i){const n=new Map(t.filter(e=>e.datum?.kind===Zr).map(e=>[e.datum.projectId,e])),o=i?.resolvePaint??((t,i)=>N(e,t,i)),r=o("var(--semiotic-danger, #ef4444)","#ef4444"),s=o("var(--semiotic-text-secondary, #64748b)","#64748b");e.save(),e.lineWidth=1.1,e.setLineDash([3,4]);for(const i of t){const t=i.datum;if(!t?.__gauntlet||t.kind===Zr)continue;const o=n.get(t.projectId);o&&(e.globalAlpha=t.kind===ts?.24:.36,e.strokeStyle=t.kind===ts?r:s,e.beginPath(),e.moveTo(o.x,o.y),e.lineTo(i.x,i.y),e.stroke())}e.restore()}(e,t,i)},[l,A]),Be=Is(()=>[...Z,...l.regionEffects??[]],[l.regionEffects,Z]);if(X)return X;const je=or(e.tooltip,l),Te=rr(e,l,Re,{selection:Y,chartMode:F,className:O,title:E,description:z,summary:H,accessibleTable:L,enableHover:q,margin:W}),Oe=j?Ws(Fs,{states:ee,layout:Q}):void 0,Ee=nr(T?Ws(Es,{layout:Q,states:ee,compact:D.resolved.compactMode}):void 0,l.backgroundGraphics),Ne=nr(Oe,l.foregroundGraphics),Fe=l.renderBody??Ts,We=je.tooltipContent??js;return ir("GauntletChart",B,qs(Bn,{...l,...je,...Te,key:`${B[0]}x${B[1]}:${U}:${he.rerunKey}`,ref:P,onBodyHover:_,accessibleTable:e.accessibleTable??l.accessibleTable,backgroundGraphics:Ee,backgroundGraphicsBackdrop:l.backgroundGraphicsBackdrop??"var(--semiotic-bg, transparent)",bodyForces:ke,bodySemanticItems:l.bodySemanticItems??Ns,bodyStyle:Me,beforePaint:De,onClick:g?$e:Te.onClick,config:he.config,controllers:me,enableHover:je.enableHover??!0,foregroundGraphics:Ne,hoverRadius:e.hoverRadius??l.hoverRadius??18,initialSpawns:be,initialSpawnPacing:h,onBodyPointerDown:Pe,onTick:Ie,paused:x,regionEffects:Be,renderBody:Fe,responsiveHeight:!1,responsiveWidth:!1,size:B,tooltipContent:We}),D)});Hs.displayName="GauntletChart";var Ls=Hs;import{forwardRef as Ys,useCallback as _s,useMemo as Xs,useRef as Gs}from"react";function Us(e){return e.toLocaleString(void 0,1e3>Math.abs(e)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function Vs(e){return e.map((e,t)=>`${0===t?"M":"L"} ${e.x} ${e.y}`).join(" ")}import{jsx as Ks,jsxs as Qs}from"react/jsx-runtime";import{createElement as Js}from"react";function Zs(e){if(!e||"object"!=typeof e)return null;const t=e,i=Number(t.x),n=Number(t.y);return Number.isFinite(i)&&Number.isFinite(n)?{x:i,y:n}:null}function ea(e){if(!e||"object"!=typeof e)return[];const t=e.flowPath;return Array.isArray(t)?t.map(Zs).filter(e=>null!=e):[]}function ta(e,t){if(2>t.length)return null;let i=0;const n=[];for(let e=1;t.length>e;e+=1){const o=Math.hypot(t[e].x-t[e-1].x,t[e].y-t[e-1].y);n.push(o),i+=o}if(0>=i)return null;let o=null,r=0;for(let s=1;t.length>s;s+=1){const a=t[s-1],c=t[s],d=n[s-1];if(0>=d)continue;const l=c.x-a.x,u=c.y-a.y,h=Math.max(0,Math.min(1,((e.x-a.x)*l+(e.y-a.y)*u)/(d*d))),p={x:a.x+l*h,y:a.y+u*h},m={distance:Math.hypot(e.x-p.x,e.y-p.y),point:p,progress:(r+h*d)/i,tangent:{x:l/d,y:u/d},totalLength:i};o&&m.distance>=o.distance||(o=m),r+=d}return o}function ia(e,t,i){if(0===e.length)return{x:0,y:0};if(1===e.length||0>=i)return{...e[0]};let n=0;const o=Math.max(0,Math.min(1,t))*i;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 na(e){return"circle"===e.shape.type?e.shape.radius:Math.max(e.shape.width,e.shape.height)/2}function oa(e,t,i){const n=Math.hypot(e,t);if(i>=n||0>=n)return[e,t];const o=i/n;return[e*o,t*o]}function ra(e,t,i){const n=ta({...e,x:t[0].x,y:t[0].y},t),o=n?.tangent??{x:t[1].x-t[0].x,y:t[1].y-t[0].y},r=Math.hypot(o.x,o.y)||1,s=o.x/r,a=o.y/r,c=na(e),d=function(e,t){let i=0;for(let t=0;e.length>t;t+=1)i=31*i+e.charCodeAt(t)>>>0;return(i%1e3/1e3-.5)*t*1.4}(e.id,c);return{id:e.id,x:t[0].x+-a*d,y:t[0].y+s*d,vx:s*i,vy:a*i,mass:e.mass,shape:e.shape,datum:{...e.datum&&"object"==typeof e.datum?e.datum:{},routeProgress:0}}}var sa=Ys(function(e,t){const{chartId:i,colorBy:n,coordinateMode:o="auto",data:r,edges:s,emptyContent:a,flowSpeed:c=90,frameProps:d,links:l,loading:u,loadingContent:h,maxParticles:p=180,nodeIdAccessor:m="id",nodeXAccessor:y="x",nodeYAccessor:f="y",nodes:g,onObservation:b,particleRadius:v=4,particleRate:x=.16,pathAccessor:w="path",pathConstraint:k="path",paused:I,reducedMotion:M=!1,rerunMS:S,seed:A=1,showNodeLabels:C=!0,showSensors:R=!1,showStaticFlow:P=!0,sourceAccessor:$="source",styleRules:D,targetAccessor:B="target",throughputAccessor:j="value"}=e,T=Zo(e,[760,420]),{chartSize:O,className:E,title:N,chartMode:F,margin:W,enableHover:q,description:z,summary:H,accessibleTable:L}=T,Y=Gs(null),_=Xs(()=>g??[],[g]),X=Xs(()=>l??s??r??[],[r,s,l]),G=Xs(()=>so({nodes:_,links:X,nodeIdAccessor:m,nodeXAccessor:y,nodeYAccessor:f,sourceAccessor:$,targetAccessor:B,throughputAccessor:j,pathAccessor:w,coordinateMode:o,particleRate:x,maxParticles:p,particleRadius:v,flowSpeed:c,pathConstraint:k,reducedMotion:M,seed:A,size:O}),[X,_,O,o,c,p,m,y,f,v,x,w,k,M,A,$,B,j]);Wo(t,{frameRef:Y,spawnDatum:_s((e,t)=>{const i=so({nodes:_,links:[e],nodeIdAccessor:m,nodeXAccessor:y,nodeYAccessor:f,sourceAccessor:$,targetAccessor:B,throughputAccessor:j,pathAccessor:w,coordinateMode:o,particleRate:x,maxParticles:p,particleRadius:v,flowSpeed:c,pathConstraint:k,reducedMotion:M,seed:A+t+1,size:O}),n={id:(e.id??"physical-flow-push-"+t)+"",x:Tn(O).plot.x,y:Tn(O).plot.y,mass:1,shape:{type:"circle",radius:v},datum:e},r=i.initialSpawns.length?i.initialSpawns:[n];return{datumId:(e.id??r[0].id)+"",spawns:r}},[_,O,o,c,p,m,y,f,v,x,w,k,M,A,$,B,j]),seedRows:X,seedSpawns:G.initialSpawns});const U=n??"source",V=Xs(()=>Nn(U,"#2563eb",{styleRules:D,valueAccessor:j}),[U,D,j]),K=Xs(()=>En(V,d?.bodyStyle),[V,d?.bodyStyle]),Q=Jo(Xs(()=>function(e,t,i){return{...e,observation:{...e.observation,chartId:t??e.observation?.chartId??"physical-flow",chartType:"PacketFlowChart",onObservation:i??e.observation?.onObservation}}}(G.config,i,b),[i,G.config,b]),S,I),J=Gs(d?.onTick);J.current=d?.onTick;const Z=_s((e,t)=>{M||"none"===k||function(e,t){const i=e.readBodies(),n=[],o=[];for(const r of i){const i=ea(r.datum);if(2>i.length)continue;const s=ta(r,i);if(!s)continue;const a=r.datum,c=Number(a?.flowSpeed),d=Number.isFinite(c)&&c>0?c:t;if(s.progress>=.985||s.distance>Math.max(90,14*na(r))){n.push(r.id),o.push(ra(r,i,d));continue}const l=ia(i,Math.min(1,s.progress+Math.max(.035,Math.min(.12,d/s.totalLength*.16))),s.totalLength),u=s.tangent,h=(u.x*d-r.vx)*r.mass*.16+(l.x-r.x)*r.mass*.045+(s.point.x-r.x)*r.mass*.08,p=(u.y*d-r.vy)*r.mass*.16+(l.y-r.y)*r.mass*.045+(s.point.y-r.y)*r.mass*.08,[m,y]=oa(h,p,r.mass*d*.35);e.applyImpulse(r.id,m,y)}n.length&&e.remove(n),o.length&&e.pushMany(o)}(t,c),J.current?.(e,t)},[c,k,M]),{selection:ee,onBodyHover:te}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:n,chartType:"PacketFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:d?.onBodyHover,fallbackFields:"string"==typeof $?[$]:void 0}),ie=tr({data:null==l&&null==s&&null==r?void 0:X,emptyContent:a,loading:u,loadingContent:h,size:O});if(ie)return ie;const ne=function(e,t){const{showNodeLabels:i,showSensors:n,showStaticFlow:o}=t;if(e&&(o||n||i))return({size:t})=>{const r=[Number(t[0])||760,Number(t[1])||420],s=Math.max(1,...e.links.map(e=>e.throughput)),a=new Set(e.nodes.map(e=>e.sensorId));return Qs("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[o?e.links.map(e=>{const t=3+e.throughput/s*16,i=e.path[Math.floor(e.path.length/2)];return Qs("g",{children:[Ks("path",{d:Vs(e.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:t+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),Ks("path",{d:Vs(e.path),fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),i?Ks("text",{x:i.x,y:i.y-t/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:Us(e.throughput)}):null]},e.id)}):null,e.nodes.map(e=>Qs("g",{children:[n&&a.has(e.sensorId)?Ks("rect",{"data-testid":"physical-flow-sensor-overlay",x:e.x-12,y:e.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,o?Ks("circle",{cx:e.x,cy:e.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,i?Ks("text",{x:e.x,y:e.y-14,textAnchor:"middle",fill:"var(--semiotic-text, #111827)",fontSize:11,fontWeight:800,children:e.label}):null]},e.id))]})}}(G.metadata,{showNodeLabels:C,showSensors:R,showStaticFlow:P}),oe=(re=G.metadata)?re.links.map(e=>{const t=e.path[Math.floor(e.path.length/2)]??e.path[0],i=`${e.sourceLabel} to ${e.targetLabel}: ${Us(e.throughput)} throughput, ${e.packetCount} packets`;return{id:e.id,label:i,description:i,datum:e,x:t?.x??0,y:t?.y??0,shape:"path",pathData:Vs(e.path),group:"flow"}}):[];var re;const se=or(e.tooltip,d),ae=rr(e,d,oe,{selection:ee,chartMode:F,className:E,title:N,description:z,summary:H,accessibleTable:L,enableHover:q,margin:W});return ir("PacketFlowChart",O,Js(Bn,{...d,...se,...ae,key:`${O[0]}x${O[1]}:${Q.rerunKey}`,ref:Y,onBodyHover:te,config:Q.config,continuous:!M&&"none"!==k,foregroundGraphics:nr(ne,d?.foregroundGraphics),initialSpawns:G.initialSpawns,onTick:Z,paused:I||M,responsiveHeight:!1,responsiveWidth:!1,simulationExecution:"none"===k?d?.simulationExecution:"sync",size:O,bodyStyle:K,workerBodyThreshold:d?.workerBodyThreshold??1/0}),T)});sa.displayName="PacketFlowChart";var aa=sa;import{Fragment as ca,jsx as da,jsxs as la}from"react/jsx-runtime";var ua={flow:{fill:"rgba(59, 130, 246, 0.14)",stroke:"rgba(96, 165, 250, 0.7)",accent:"#60a5fa"},capacity:{fill:"rgba(251, 146, 60, 0.18)",stroke:"rgba(251, 146, 60, 0.85)",accent:"#fb923c"},portal:{fill:"rgba(244, 114, 182, 0.14)",stroke:"rgba(244, 114, 182, 0.7)",accent:"#f472b6"},absorb:{fill:"rgba(52, 211, 153, 0.18)",stroke:"rgba(52, 211, 153, 0.8)",accent:"#34d399"}};function ha(e,t,i){return Math.max(t,Math.min(i,e))}function pa(e){return 6.2*e.length}function ma(e,t){const i=e.trim();if(t>=i.length)return i;if(1>=t)return i.slice(0,1);const n=i.split(/\s+/).filter(Boolean).map(e=>e[0]).join("").toUpperCase();return n.length>1&&t>=n.length?n:t>3?i.slice(0,Math.max(1,t-2))+"..":i.slice(0,t).toUpperCase()}function ya(e,t,i="auto"){const n=Math.max(1,Math.floor(t/6.2)),o="compact"===i?ma(e,n):"full"===i?e:pa(e)>t?ma(e,n):e;return{text:o,textLength:pa(o)>t?Math.max(4,t):void 0}}function fa(e,t={}){const{showFlowSpine:i=!0,showStageCounts:n=!0,showCapacityBadges:o=!0,showGroupSockets:r=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=t,{width:d,height:l,left:u,right:h,topY:p,bottomY:m,midY:y,stages:f,groups:g=[]}=e,b=m-p;return la("svg",{"aria-hidden":"true","data-testid":c,"data-outline-stages":a?"true":void 0,width:d,height:l,viewBox:`0 0 ${d} ${l}`,style:{position:"absolute",inset:0,pointerEvents:"none"},className:["semiotic-process-chrome",a?"semiotic-process-chrome--outline-stages":null].filter(Boolean).join(" "),children:[da("defs",{children:la("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[da("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),da("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),da("rect",{x:0,y:0,width:d,height:l,fill:"url(#semiotic-process-floor)"}),da("rect",{x:u-6,y:p-8,width:h-u+12,height:b+16,rx:14,fill:"var(--semiotic-process-lane, var(--semiotic-surface, #111827))",fillOpacity:.45,stroke:"var(--semiotic-process-border, var(--semiotic-border, #334155))",strokeOpacity:.95}),i?da("line",{x1:u+8,x2:h-8,y1:y,y2:y,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,f.map((e,t)=>{const i=function(e){return e.absorb?"absorb":e.portalTarget?"portal":null!=e.capacity?"capacity":"flow"}(e),r=ua[i],c=Math.max(12,e.width-8),d=ha(c-8,22,88),u=ya(e.label,Math.max(8,d-10),s),h="none"!==s&&c-8>=22,g=function(e){if(null!=e.capacity){const t=null!=e.queueDepth?" · q "+e.queueDepth:"";return e.capacityLabel?`${e.capacityLabel}${t}`:`cap ${Number.isInteger(e.capacity)?e.capacity+"":e.capacity.toFixed(1)}${t}`}return e.absorb?"absorb":e.portalTarget?"portal":"flow"}(e),v=ya(g,Math.max(16,c-10),"auto"),x=o&&!1!==e.showBadge&&c>=32,w=null!=e.count?`n=${e.count}${null!=e.processed?" done "+e.processed:""}`:"",k=ya(w,Math.max(16,c-8),"auto"),I=Math.max(30,p-15),M=I-13;return la("g",{"data-stage":e.id,"data-role":i,children:[da("rect",{className:"semiotic-process-chrome__stage-bay",x:e.x0+4,y:p+6,width:c,height:b-12,rx:10,fill:a?"none":r.fill,stroke:r.stroke,strokeWidth:a?1.85:"flow"===i?1:1.6}),f.length-1>t?da("polygon",{points:`${e.x1-2},${y-7} ${e.x1+8},${y} ${e.x1-2},${y+7}`,fill:r.accent,opacity:.85}):null,h?la(ca,{children:[da("rect",{className:"semiotic-process-chrome__stage-label-bg",x:e.x-d/2,y:M,width:d,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:r.stroke}),la("text",{x:e.x,y:I,textAnchor:"middle",fill:r.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[da("title",{children:e.label}),u.text]})]}):null,x?la("text",{x:e.x,y:p+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:v.textLength,lengthAdjust:v.textLength?"spacingAndGlyphs":void 0,children:[da("title",{children:g}),v.text]}):null,n&&null!=e.count?la("text",{x:e.x,y:Math.min(l-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:k.textLength,lengthAdjust:k.textLength?"spacingAndGlyphs":void 0,children:[da("title",{children:w}),k.text]}):null]},e.id)}),r?g.map((e,t)=>{const i=e.total??0,n=e.absorbed??0,o=e.complete??(i>0&&n>=i),r=!o&&i>0&&n/i>=.75,s=o?"rgba(52, 211, 153, 0.35)":r?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=o?"#34d399":r?"#fbbf24":"var(--semiotic-border, #64748b)",c=i>0?`${n}/${i}${o?" shipped":r?" almost":""}`:"feature "+(t+1),d=ha(Math.max(54,pa(e.label)+18,pa(c)+16),54,104),l=ya(e.label,d-12,"auto"),u=ya(c,d-12,"auto");return la("g",{"data-group":e.id,children:[da("rect",{x:e.x-d/2,y:e.y-22,width:d,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),la("text",{x:e.x,y:e.y-4,textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #f8fafc))",fontSize:10,fontWeight:800,textLength:l.textLength,lengthAdjust:l.textLength?"spacingAndGlyphs":void 0,children:[da("title",{children:e.label}),l.text]}),la("text",{x:e.x,y:e.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[da("title",{children:c}),u.text]})]},e.id)}):null]})}import{forwardRef as ga,useCallback as ba,useEffect as va,useMemo as xa,useRef as wa,useState as ka}from"react";import{jsx as Ia}from"react/jsx-runtime";import{jsx as Ma}from"react/jsx-runtime";import{createElement as Sa}from"react";var Aa=ga(function(e,t){const{ballRadius:i=6,chromeOptions:n,colorBy:o,data:r,emptyContent:s,frameProps:a={},groupAnchorAlong:c,groupBy:d,groupCompletion:l,groupLabelAccessor:u,gravityX:h,gravityY:p,idAccessor:m,initialSpawnPacing:y,liveCapacity:f=!0,onCapacityChange:g,selection:b,bodyLimit:v,bodyMark:x,loading:w,loadingContent:k,paused:M,radiusAccessor:S,rerunMS:A,route:C="horizontal",seed:R=1,settle:P,springDamping:$,springStiffness:D,stageAccessor:B="stage",stages:j,workAccessor:T}=e,O=Zo(e,[900,420]),{chartSize:E,showProjection:N,showChrome:F,className:W,title:q,chartMode:z,margin:H,enableHover:L,description:Y,summary:_,accessibleTable:X}=O,G=wa(null),U=xa(()=>I(r??[]),[r]),V=xa(()=>({data:U,stages:j,size:E,idAccessor:m,stageAccessor:B,groupBy:d,groupLabelAccessor:u,workAccessor:T,radiusAccessor:S,ballRadius:i,seed:R,route:C,groupCompletion:l,groupAnchorAlong:c,springStiffness:D,springDamping:$,gravityX:h,gravityY:p,settle:P}),[i,E,h,p,c,d,l,u,m,S,C,U,R,P,$,D,B,j,T]),K=xa(()=>Po(V),[V]),Q=K.metadata;Wo(t,{frameRef:G,spawnDatum:ba((e,t)=>{const n=Po({...V,data:[e],seed:R+t+1,settle:!0}).initialSpawns[0]??{id:(e.id??"process-flow-push-"+t)+"",x:Tn(E).plot.x,y:Tn(E).plot.y,mass:1,shape:{type:"circle",radius:i},datum:e};return{datumId:(e.id??n.id)+"",spawns:[n]}},[i,V,E,R]),seedRows:U,seedSpawns:K.initialSpawns});const J=xa(()=>Nn(o),[o]),Z=xa(()=>{if(!f)return a.controllers;const e=[...j.filter(e=>e.capacity&&e.capacity.unitsPerSecond>0).map(e=>{const t=e.capacity.unitsPerSecond;return Nt({id:"process-capacity-"+e.id,regionId:"process-stage-"+e.id,unitsPerSecond:t,unitAccessor:e.capacity.unitAccessor??(T?"string"==typeof T?T:e=>{const t=e.datum;if(!t)return 1;try{return Number(T(t,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*t),y:0},queueLayout:"lane",continuous:!0})}),...a.controllers??[]];return e.length?e:void 0},[a.controllers,f,j,T]),[ee,te]=ka({}),ie=wa(Z);ie.current=Z;const ne=wa(a.onTick);ne.current=a.onTick;const oe=!1!==F||null!=g;va(()=>{if(!g)return;const e=Object.values(ee);e.length&&g(e)},[ee,g]);const re=ba((e,t)=>{if(ne.current?.(e,t),!oe)return;const i=ie.current;if(!i?.length)return;const n={};for(const e of i){const t=e.getSnapshot?.();t&&"string"==typeof t.regionId&&(n[t.regionId]=t)}te(e=>function(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){const i=e[n],o=t[n];if(!o)return!1;if(i.queueDepth!==o.queueDepth||i.blockedDepth!==o.blockedDepth||i.processedCount!==o.processedCount||i.unitsPerSecond!==o.unitsPerSecond||i.regionId!==o.regionId||i.metricRevision!==o.metricRevision)return!1}return!0}(e,n)?e:n)},[oe]),se=xa(()=>{const e=J,t=a.bodyStyle;return x||t?(i,n)=>{const o="function"==typeof t?t(i,n):t;return{..."function"==typeof e?e(i):e,...o,mark:o?.mark??i.datum?.__physicsMark??i.datum?.mark??x}}:e},[x,J,a.bodyStyle]),ae=Jo(xa(()=>({...K.config,...null!=v?{bodyLimit:v,eviction:"oldest"}:{},...a.config}),[v,a.config,K.config]),A,M),{selection:ce,onBodyHover:de}=Ko({selection:b,linkedHover:e.linkedHover,colorBy:o,chartType:"ProcessFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:a?.onBodyHover,fallbackFields:"string"==typeof B?[B]:void 0}),le=tr({data:r,emptyContent:s,loading:w,loadingContent:k,size:E});if(le)return le;if(!j?.length)return ir("ProcessFlowChart",E,Ma("div",{role:"status",style:{width:E[0],height:E[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}),O);const ue=function(e,t,i={},n){if(!1===t||!e)return;const{volume:o,stages:r,groups:s,groupCompletion:a}=e,c=new Map(o.stages.map(e=>[e.id,e])),d=new Map(a.map(e=>[e.id,e]));return({size:e})=>{const t=Number(e[0])||o.width,a=Number(e[1])||o.height,l=r.map(e=>{const t=c.get(e.id),n=i["process-stage-"+e.id];return{id:e.id,label:e.label,x0:t?.x0??e.x-e.width/2,x1:(t?.x0??e.x-e.width/2)+(t?.width??e.width),x:e.x,width:t?.width??e.width,count:e.count,capacity:e.capacity,absorb:e.absorb,portalTarget:e.portalTarget,queueDepth:n?.queueDepth,processed:n?.processedCount}}),u=s.map(e=>{const t=d.get(e.id);return{id:e.id,label:e.label??e.id,x:e.anchor?.x??e.x??0,y:e.anchor?.y??e.y??0,absorbed:t?.absorbed,total:t?.total,complete:t?.complete}});return fa({width:t,height:a,left:o.left,right:o.right,topY:o.topY,bottomY:o.bottomY,midY:o.midY,stages:l,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...n})}}(Q,F,ee,n),he=function(e,t,i){if(!1===i||!t||0===e.length)return;const n=new Map(t.volume.stages.map(e=>[e.id,e]));return({size:i})=>{const o=[Number(i[0])||t.volume.width,Number(i[1])||t.volume.height],r=Tn(o),s=Math.max(1,...e.map(e=>e.value)),a=Math.min(48,.18*r.plot.height),c=r.plot.y+6;return Ia("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:t.stages.map((t,i)=>{const o=e[i];if(!o)return null;const r=n.get(t.id);if(!r)return null;const d=Math.max(2,o.value/s*a),l=Math.max(8,.35*r.width);return Ia("rect",{x:r.x-l/2,y:c,width:l,height:d,rx:2,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.18,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.45,strokeWidth:1},t.id)})})}}(K.projectionRows,Q,N),pe=[...Wn(K.projectionRows,E,"stage"),...Lr(Q?.groups??[])],me=or(e.tooltip,a),ye=rr(e,a,pe,{chartMode:z,className:W,title:q,description:Y,summary:_,accessibleTable:X,enableHover:L,margin:H}),fe=[...Q?.regionEffects??[],...a.regionEffects??[]];return ir("ProcessFlowChart",E,Sa(Bn,{...a,...me,...ye,key:`${E[0]}x${E[1]}:${ae.rerunKey}`,ref:G,onBodyHover:de,controllers:Z,regionEffects:fe,selection:ce??a.selection,backgroundGraphics:nr(ue,a.backgroundGraphics),foregroundGraphics:nr(he,a.foregroundGraphics),initialSpawns:K.initialSpawns,initialSpawnPacing:y??K.initialSpawnPacing,onTick:re,paused:M,responsiveHeight:!1,responsiveWidth:!1,size:E,bodyStyle:se,config:ae.config}),O)});function Ca(e=[]){const t=Object.create(null);for(const[i,n]of e)t[i]=n;return t}function Ra(...e){const t=Ca();for(const i of e)for(const[e,n]of Object.entries(i??{}))t[e]=n;return t}function Pa(e){return Ra(e)}function $a(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 Da(e){const t=Ca(Object.entries(e.components).map(([e,t])=>[e,{...t,initialMetrics:Pa(t.initialMetrics),metrics:Pa(t.metrics),productIds:[...t.productIds],history:$a(t.history)}])),i=Ca(Object.entries(e.products).map(([e,t])=>[e,{...t,metrics:Pa(t.metrics),sourceIds:[...t.sourceIds],history:$a(t.history)}])),n=Ca(Object.entries(e.relations).map(([e,t])=>[e,{...t,sourceIds:[...t.sourceIds],metrics:t.metrics?Pa(t.metrics):void 0}]));return{...e,eventsApplied:[...e.eventsApplied],components:t,products:i,relations:n,input:{amount:e.input.amount,metrics:Pa(e.input.metrics)},metrics:Pa(e.metrics),loss:{amount:e.loss.amount,metrics:Pa(e.loss.metrics)},history:$a(e.history)}}Aa.displayName="ProcessFlowChart";var Ba=1e-9;function ja(e,t){return t>e?-1:e>t?1:0}function Ta(e,t,i,n,o){return{severity:e,code:t,message:i,path:n,ids:o?[...o]:void 0}}function Oa(e){const t=new Set,i=new Set;for(const n of e)t.has(n)&&i.add(n),t.add(n);return[...i].sort(ja)}function Ea(e,t){return e?Object.entries(e).flatMap(([e,i])=>Number.isFinite(i)?[]:[Ta("error","invalid-metric",`Metric "${e}" must be a finite number.`,`${t}.${e}`)]):[]}function Na(e,t){for(const[i,n]of Object.entries(t))e[i]=Number(e[i]??0)+n}function Fa(e,t,i="selector"){const n=[],o=Object.values(e.components),r=new Set(o.map(e=>e.id)),s=(t.ids??[]).filter(e=>!r.has(e));if(s.length&&n.push(Ta("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,i+".ids",s)),void 0===t.count||Number.isInteger(t.count)&&t.count>=0||n.push(Ta("error","invalid-selector-count","Selector count must be a non-negative integer.",i+".count")),n.some(e=>"error"===e.severity))return{ids:[],diagnostics:n};const a=t.ids?new Set(t.ids):null,c=t.categories?new Set(t.categories):null,d=t.statuses?new Set(t.statuses):null,l=t.outletIds?new Set(t.outletIds):null;let u=o.filter(e=>!a||a.has(e.id)).filter(e=>!c||c.has(e.category)).filter(e=>!d||d.has(e.status)).filter(e=>!l||void 0!==e.outletId&&l.has(e.outletId)).map(e=>e.id).sort(ja);return void 0!==t.count&&(u=u.slice(0,t.count)),u.length||n.push(Ta("warning","empty-selector","Selector matched no source components.",i)),{ids:u,diagnostics:n}}function Wa(e,t,i={}){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,...i}}function qa(e,t){const i={...t,eventId:e.event.id};e.materializations.push(i),e.observations.push({...i,phaseId:e.context.phaseId,authoredAt:e.context.authoredAt,appliedAt:e.context.appliedAt})}function za(e,t,i){return!(void 0!==t&&!e.outletIds.has(t)&&(e.diagnostics.push(Ta("error","unknown-outlet",`Unknown outlet "${t}".`,i,[t])),1))}function Ha(e,t,i){const n=Oa(t);t.length||e.diagnostics.push(Ta("error","empty-source-list","A product requires at least one source component.",i)),n.length&&e.diagnostics.push(Ta("error","duplicate-source",`Source ids may appear only once: ${n.join(", ")}.`,i,n));const o=t.filter(t=>!e.state.components[t]);o.length&&e.diagnostics.push(Ta("error","unknown-component",`Unknown source component id${1===o.length?"":"s"}: ${o.join(", ")}.`,i,o));const r=t.filter(t=>(e.state.components[t]?.productIds.length??0)>0);r.length&&e.diagnostics.push(Ta("error","source-already-assigned",`Source component${1===r.length?" is":"s are"} already assigned: ${r.join(", ")}.`,i,r));const s=t.filter(t=>"consumed"===e.state.components[t]?.status&&!r.includes(t));return s.length&&e.diagnostics.push(Ta("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,i,s)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}function La(e,t,i,n,o){const r=n?.amount??0;(!Number.isFinite(r)||0>r||r>t+Ba)&&e.diagnostics.push(Ta("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",o+".amount")),e.diagnostics.push(...Ea(n?.metrics,o+".metrics"));for(const[t,r]of Object.entries(n?.metrics??{}))(0>r||r>Number(i[t]??0)+Ba)&&e.diagnostics.push(Ta("error","invalid-metric-loss",`Metric loss "${t}" must be non-negative and no greater than its sources.`,`${o}.metrics.${t}`));return!e.diagnostics.some(e=>"error"===e.severity)}function Ya(e,t,i,n,o,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:i,metrics:r&&e.metrics?Ra(n,e.metrics):Pa(n),status:r?"complete":"forming",sourceIds:[...t],outletId:r?e.outletId??(o.outletIds.has("product")?"product":void 0):void 0,createdByEventId:o.event.id,createdAt:o.context.appliedAt,completedByEventId:r?o.event.id:void 0,completedAt:r?o.context.appliedAt:void 0,history:[s]}}function _a(e,t,i,n){void 0!==t.amount&&Math.abs(t.amount-i)>Ba&&e.diagnostics.push(Ta("warning","declared-product-amount-mismatch",`Product "${t.id}" declares ${t.amount}, while its sources yield ${i}.`,n,[t.id]))}function Xa(e,t,i){const n=`events.${e.event.id}.effects.${i}`,o=e.state;if("set-state"===t.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(t.state)||e.diagnostics.push(Ta("error","invalid-component-state",`set-state cannot assign "${t.state+""}".`,n+".state")),e.diagnostics.push(...Ea(t.metricsDelta,n+".metricsDelta")),za(e,t.outletId,n+".outletId");const i=Fa(o,t.select,n+".select");e.diagnostics.push(...i.diagnostics);const r=i.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Ta("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=Wa(e,t,{sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0});for(const e of i.ids){const i=o.components[e];i.status=t.state,i.outletId=t.outletId,i.reason=t.reason,t.metricsDelta&&Na(i.metrics,t.metricsDelta),i.history.push(s)}return o.history.push(s),void(i.ids.length&&qa(e,{type:"retarget-component",sourceIds:i.ids,outletIds:t.outletId?[t.outletId]:void 0}))}if("set-relation"===t.type){const{relation:i}=t;i.id&&!o.relations[i.id]||e.diagnostics.push(Ta("error","duplicate-relation",`Relation id "${i.id}" is missing or already active.`,n+".relation.id",[i.id]));const r=function(e,t,i){const n=Oa(t),o=t.filter(t=>!e.state.components[t]);return 2>t.length&&e.diagnostics.push(Ta("error","insufficient-relation-sources","A relation requires at least two source components.",i)),n.length&&e.diagnostics.push(Ta("error","duplicate-source",`Relation source ids must be unique: ${n.join(", ")}.`,i,n)),o.length&&e.diagnostics.push(Ta("error","unknown-component",`Relation references unknown source component${1===o.length?"":"s"}: ${o.join(", ")}.`,i,o)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.components[t])}(e,i.sourceIds,n+".relation.sourceIds");if(e.diagnostics.push(...Ea(i.metrics,n+".relation.metrics")),!r||e.diagnostics.some(e=>"error"===e.severity))return;o.relations[i.id]={...i,sourceIds:[...i.sourceIds],metrics:i.metrics?Pa(i.metrics):void 0,status:"active",createdByEventId:e.event.id,createdAt:e.context.appliedAt};const s=Wa(e,t,{sourceIds:[...i.sourceIds],relationIds:[i.id]});return o.history.push(s),void qa(e,{type:"activate-relation",sourceIds:[...i.sourceIds],relationIds:[i.id]})}if("resolve-relation"===t.type){const i=Oa(t.relationIds),r=t.relationIds.filter(e=>!o.relations[e]),s=t.relationIds.filter(e=>"resolved"===o.relations[e]?.status);if(i.length&&e.diagnostics.push(Ta("error","duplicate-relation","Relation ids must be unique.",n+".relationIds",i)),r.length&&e.diagnostics.push(Ta("error","unknown-relation",`Unknown relation: ${r.join(", ")}.`,n+".relationIds",r)),s.length&&e.diagnostics.push(Ta("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,n+".relationIds",s)),e.diagnostics.some(e=>"error"===e.severity))return;for(const i of t.relationIds){const n=o.relations[i];n.status="resolved",n.resolution=t.resolution,n.resolvedByEventId=e.event.id,n.resolvedAt=e.context.appliedAt,n.reason=t.reason}const a=Wa(e,t,{relationIds:[...t.relationIds]});return o.history.push(a),void qa(e,{type:"resolve-relation",relationIds:[...t.relationIds]})}if("combine"===t.type||"contribute"===t.type){const i=e.productDefinitions.get(t.productId);i||e.diagnostics.push(Ta("error","unknown-product",`Product "${t.productId}" has no declared mold.`,n+".productId",[t.productId]));const r=o.products[t.productId];"combine"===t.type&&r&&e.diagnostics.push(Ta("error","duplicate-product",`Product "${t.productId}" has already been formed.`,n+".productId",[t.productId])),"contribute"!==t.type||r&&"forming"===r.status||e.diagnostics.push(Ta("error","product-not-forming",`Contributions require an existing forming product "${t.productId}".`,n+".productId",[t.productId]));const s=Ha(e,t.sourceIds,n+".sourceIds"),a="contribute"===t.type&&r?[...r.sourceIds,...t.sourceIds]:t.sourceIds,c=function(e,t,i,n){if(!t?.length)return[];const o=Oa(t),r=t.filter(t=>!e.state.relations[t]),s=t.filter(t=>"resolved"===e.state.relations[t]?.status),a=new Set(i),c=t.filter(t=>(e.state.relations[t]?.sourceIds??[]).some(e=>!a.has(e)));return o.length&&e.diagnostics.push(Ta("error","duplicate-relation","Basis relations must be unique.",n,o)),r.length&&e.diagnostics.push(Ta("error","unknown-relation",`Unknown basis relation: ${r.join(", ")}.`,n,r)),s.length&&e.diagnostics.push(Ta("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,n,s)),c.length&&e.diagnostics.push(Ta("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,n,c)),e.diagnostics.some(e=>"error"===e.severity)?null:t.map(t=>e.state.relations[t])}(e,t.basisRelationIds,a,n+".basisRelationIds");if(!s||!c||!i||e.diagnostics.some(e=>"error"===e.severity))return;const d=s.reduce((e,t)=>e+t.amount,0),l=function(e){const t=Ca();for(const i of e)Na(t,i.metrics);return t}(s);if(!La(e,d,l,t.loss,n+".loss"))return;const u=d-(t.loss?.amount??0);!function(e,t,i){e.state.loss.amount+=i?.amount??0;for(const[n,o]of Object.entries(i?.metrics??{}))t[n]=Number(t[n]??0)-o,e.state.loss.metrics[n]=Number(e.state.loss.metrics[n]??0)+o}(e,l,t.loss);const h="combine"===t.type&&!1!==t.complete,p=Wa(e,t,{sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0});let m;if("combine"===t.type){if(h&&_a(e,i,u,n+".productId"),m=Ya(i,t.sourceIds,u,l,e,h,p),h&&!za(e,m.outletId,n+".productId"))return;o.products[t.productId]=m}else m=r,m.sourceIds.push(...t.sourceIds),m.amount+=u,Na(m.metrics,l),m.history.push(p);for(const e of s)e.productIds=[t.productId],e.status="consumed",e.outletId=void 0,e.history.push(p);return o.history.push(p),function(e,t){if(t.length){for(const i of t)i.status="resolved",i.resolution="combined",i.resolvedByEventId=e.event.id,i.resolvedAt=e.context.appliedAt;qa(e,{type:"resolve-relation",relationIds:t.map(e=>e.id)})}}(e,c),qa(e,{type:"combine"===t.type?"form-product":"update-product",sourceIds:[...t.sourceIds],productIds:[t.productId],relationIds:t.basisRelationIds?[...t.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(h&&qa(e,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===t.type){const i=o.products[t.productId];return i?void function(e,t,i,n,o,r){const s=e.productDefinitions.get(t.id),a=i??s?.outletId??(e.outletIds.has("product")?"product":void 0);if(!za(e,a,r+".outletId"))return;if("complete"===t.status)return void e.diagnostics.push(Ta("error","product-already-complete",`Product "${t.id}" is already complete.`,r,[t.id]));s&&(_a(e,s,t.amount,r+".productId"),void 0!==s.amount&&(t.amount=s.amount),s.metrics&&(t.metrics=Ra(t.metrics,s.metrics))),t.status="complete",t.outletId=a,t.reason=n,t.completedByEventId=e.event.id,t.completedAt=e.context.appliedAt;const c=Wa(e,o,{sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0});t.history.push(c),e.state.history.push(c),qa(e,{type:"complete-product",sourceIds:[...t.sourceIds],productIds:[t.id],outletIds:a?[a]:void 0})}(e,i,t.outletId,t.reason,t,n):void e.diagnostics.push(Ta("error","unknown-product-state",`Product "${t.productId}" has not been formed.`,n+".productId",[t.productId]))}if("split"===t.type){const i=Ha(e,[t.sourceId],n+".sourceId");t.products.length||e.diagnostics.push(Ta("error","empty-split","A split requires at least one product allocation.",n+".products"));const r=t.products.map(e=>e.productId),s=Oa(r);s.length&&e.diagnostics.push(Ta("error","duplicate-product","Split product ids must be unique.",n+".products",s));const a=r.map(t=>e.productDefinitions.get(t)),c=r.filter((e,t)=>!a[t]),d=r.filter(e=>o.products[e]);c.length&&e.diagnostics.push(Ta("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,n+".products",c)),d.length&&e.diagnostics.push(Ta("error","duplicate-product",`Split products already exist: ${d.join(", ")}.`,n+".products",d));for(const[i,o]of t.products.entries())void 0===o.amount||Number.isFinite(o.amount)&&o.amount>=0||e.diagnostics.push(Ta("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${n}.products.${i}.amount`)),e.diagnostics.push(...Ea(o.metrics,`${n}.products.${i}.metrics`));if(!i?.length||e.diagnostics.some(e=>"error"===e.severity))return;const l=i[0];if(!La(e,l.amount,l.metrics,t.loss,n+".loss"))return;const u=l.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(Ta("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",n+".products"));const m=p?h:t.products.map(()=>u/t.products.length),y=m.reduce((e,t)=>e+t,0);if(Math.abs(y-u)>Ba)return void e.diagnostics.push(Ta("error","split-amount-mismatch",`Split allocations total ${y}, but ${u} remains after loss.`,n+".products"));const f=Pa(l.metrics);for(const[e,i]of Object.entries(t.loss?.metrics??{}))f[e]=Number(f[e]??0)-i;const g=Wa(e,t,{sourceIds:[l.id],productIds:r});if(t.products.forEach((i,r)=>{const s=a[r],c=u>Ba?m[r]/u:1/t.products.length,d=Ca(Object.entries(f).map(([e,t])=>[e,t*c])),h=i.metrics??s.metrics??d,p=Ya({...s,amount:m[r],metrics:h},[l.id],m[r],Pa(h),e,!0,g);za(e,p.outletId,`${n}.products.${r}.productId`)&&(o.products[p.id]=p)}),e.diagnostics.some(e=>"error"===e.severity))return;l.productIds=r,l.status="consumed",l.outletId=void 0,l.history.push(g),o.loss.amount+=t.loss?.amount??0;for(const[e,i]of Object.entries(t.loss?.metrics??{}))o.loss.metrics[e]=Number(o.loss.metrics[e]??0)+i;o.history.push(g),qa(e,{type:"split-source",sourceIds:[l.id],productIds:r});for(const t of r)qa(e,{type:"complete-product",sourceIds:[l.id],productIds:[t],outletIds:o.products[t].outletId?[o.products[t].outletId]:void 0});return}if("eject"===t.type){za(e,t.outletId,n+".outletId");const i=Fa(o,t.select,n+".select");e.diagnostics.push(...i.diagnostics);const r=i.ids.filter(e=>o.components[e].productIds.length);if(r.length&&e.diagnostics.push(Ta("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=Wa(e,t,{sourceIds:i.ids,outletIds:[t.outletId]});for(const e of i.ids){const i=o.components[e];i.status=t.state??"ejected",i.outletId=t.outletId,i.reason=t.reason,i.history.push(s)}return o.history.push(s),void(i.ids.length&&qa(e,{type:"retarget-component",sourceIds:i.ids,outletIds:[t.outletId]}))}if("set-metric"===t.type){if(e.diagnostics.push(...Ea(t.metricsDelta,n+".metricsDelta")),e.diagnostics.some(e=>"error"===e.severity))return;let i,r;if("run"===t.target)Na(o.metrics,t.metricsDelta);else if("components"in t.target){const r=Fa(o,t.target.components,n+".target.components");if(e.diagnostics.push(...r.diagnostics),e.diagnostics.some(e=>"error"===e.severity))return;i=r.ids;for(const e of r.ids)Na(o.components[e].metrics,t.metricsDelta)}else{r=[...t.target.productIds];const i=Oa(r),s=r.filter(e=>!o.products[e]);if(i.length&&e.diagnostics.push(Ta("error","duplicate-product","Metric target product ids must be unique.",n+".target.productIds",i)),s.length&&e.diagnostics.push(Ta("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)Na(o.products[e].metrics,t.metricsDelta)}return void o.history.push(Wa(e,t,{sourceIds:i,productIds:r}))}t.outcome.trim()?(o.outcome=t.outcome,o.summary=t.summary,o.history.push(Wa(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(Ta("error","invalid-outcome","Outcome must be a non-empty string.",n+".outcome"))}function Ga(e,t,i){if(e.eventsApplied.includes(t.id))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:[Ta("warning","duplicate-event-application",`Event "${t.id}" has already been applied.`,"events."+t.id,[t.id])]};const n=Da(e),o={state:n,event:t,context:i,productDefinitions:new Map(i.products.map(e=>[e.id,e])),outletIds:new Set(i.outlets.map(e=>e.id)),diagnostics:[],materializations:[],observations:[]};for(const[i,n]of t.effects.entries())if(Xa(o,n,i),o.diagnostics.some(e=>"error"===e.severity))return{applied:!1,state:e,materializations:[],observations:[],diagnostics:o.diagnostics};return n.elapsed=Math.max(n.elapsed,i.appliedAt),n.phaseId=i.phaseId,n.eventsApplied.push(t.id),o.observations.unshift({type:"crucible-event",eventId:t.id,phaseId:i.phaseId,authoredAt:i.authoredAt,appliedAt:i.appliedAt}),{applied:!0,state:n,materializations:o.materializations,observations:o.observations,diagnostics:o.diagnostics}}function Ua(e,t={}){const i=t.groupBy??"outlet",n=new Map,o=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"},i),o=n.get(t);if(o)return o.count+=1,o.amount+=e.amount,void Na(o.metrics,e.metrics);n.set(t,{key:t,label:"product"===i&&"product"===e.kind?e.label:t,count:1,amount:e.amount,metrics:Pa(e.metrics),status:"status"===i?e.status:void 0,outletId:"outlet"===i?e.outletId:void 0,category:"category"===i?e.category:void 0,productId:"product"===i&&"product"===e.kind?e.id:void 0})};for(const t of Object.values(e.components))t.productIds.length||"consumed"===t.status||o({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))o({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)||ja(e.key,t.key))}var Va=Ua;function Ka(e,t={}){const i=t.field??"amount",n=e=>"amount"===i?e.amount:Number(e.metrics[i]??0),o="amount"===i?e.input.amount:Number(e.input.metrics[i]??0),r=Object.values(e.products).reduce((e,t)=>e+n(t),0),s=Object.values(e.components).filter(e=>!e.productIds.length&&"consumed"!==e.status).reduce((e,t)=>e+n(t),0),a="amount"===i?e.loss.amount:Number(e.loss.metrics[i]??0),c=r+s+a,d=c-o;return{field:i,input:o,products:r,unassigned:s,loss:a,output:c,delta:d,conserved:Math.max(0,t.tolerance??1e-6)>=Math.abs(d)}}function Qa(e,t={}){return{history:$a(e.history),projection:Ua(e,t.projection),conservation:Ka(e,t.conservation)}}var Ja=900,Za=520,ec=[900,520],tc=[{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}],ic=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),nc=1e-9;function oc(e,t){return t>e?-1:e>t?1:0}function rc(e,t,i,n,o){return{severity:e,code:t,message:i,path:n,ids:o?[...o]:void 0}}function sc(e){const t=new Set,i=new Set;for(const n of e)t.has(n)&&i.add(n),t.add(n);return[...i].sort(oc)}function ac(e){const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function cc(e,t,i,n,o,r){if(!i)return n;try{return("function"==typeof i?i(e,t):e[i])??n}catch(e){return o.push(rc("error","accessor-error",`Accessor threw: ${e instanceof Error?e.message:e+""}.`,r)),n}}function dc(e,t,i){if(!e||"object"!=typeof e||Array.isArray(e))return null!=e&&t.push(rc("error","invalid-metrics","Metrics must be a numeric object.",i)),Ca();const n=Ca();for(const[o,r]of Object.entries(e)){const e=ac(r);null!=e?n[o]=e:t.push(rc("error","invalid-metric",`Metric "${o}" must be finite.`,`${i}.${o}`))}return n}function lc(e){const t=[],i=Ca(),n=[];let o=0;const r=Ca();e.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",d=((cc(s,a,e.idAccessor,c,t,`data.${a}.id`)??c)+"").trim();if(!d)return void t.push(rc("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));n.push(d);const l=ac(cc(s,a,e.amountAccessor,1,t,`data.${a}.amount`)),u=null==l||0>l?0:l;(null==l||0>l)&&t.push(rc("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[d]));const h=dc(cc(s,a,e.metricsAccessor,{},t,`data.${a}.metrics`),t,`data.${a}.metrics`),p=cc(s,a,e.initialStateAccessor,"active",t,`data.${a}.status`),m=ic.has(p)?p:"active";ic.has(p)||t.push(rc("error","invalid-component-status",`Unknown component status "${p+""}".`,`data.${a}.status`,[d]));const y=cc(s,a,e.labelAccessor,(s.label??s.name??d)+"",t,`data.${a}.label`)+"",f=cc(s,a,e.categoryAccessor,"component",t,`data.${a}.category`)+"";Object.hasOwn(i,d)||(i[d]={id:d,label:y,category:f,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:Ra(h),metrics:Ra(h),productIds:[],history:[]},o+=u,function(e,t){for(const[i,n]of Object.entries(t))e[i]=Number(e[i]??0)+n}(r,h))});const s=sc(n);s.length&&t.push(rc("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=dc(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:i,products:Ca(),relations:Ca(),input:{amount:o,metrics:r},metrics:a,loss:{amount:0,metrics:Ca()},history:[]},diagnostics:t}}function uc(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 hc(e=ec,t=tc){const i=Math.max(1,ac(e[0])??900),n=Math.max(1,ac(e[1])??520),o=360>i||260>n,r=o?Math.max(4,.035*Math.min(i,n)):20,s=o?Math.max(10,.075*n):34,a={x:r,y:r,width:Math.max(1,i-2*r),height:s},c=o?Math.max(16,.14*n):Math.min(78,.16*n),d={x:r,y:n-r-c,width:Math.max(1,i-2*r),height:c},l=o?Math.max(12,.08*i):Math.min(150,.17*i),u=a.y+a.height+(o?12:38),h=d.y-(o?10:34),p={x:l,y:u,width:Math.max(24,i-2*l),height:Math.max(24,h-u)},m=Math.max(18,Math.min(.32*p.width,o?84:180)),y={x:p.x+(p.width-m)/2,y:p.y-(o?10:24),width:m,height:o?12:28},f=uc(t),g={left:f.filter(e=>"left"===(e.side??"bottom")),right:f.filter(e=>"right"===e.side),bottom:f.filter(e=>"bottom"===(e.side??"bottom"))},b=[],v=(e,t)=>{const n=Math.max(8,l-1.5*r),s=p.height/Math.max(1,t.length);t.forEach((t,a)=>{b.push({...t,side:e,x:"left"===e?r:i-r-n,y:p.y+a*s,width:n,height:Math.max(8,s-(o?2:8))})})};v("left",g.left),v("right",g.right);const x=p.width/Math.max(1,g.bottom.length);return g.bottom.forEach((e,t)=>{b.push({...e,side:"bottom",x:p.x+t*x,y:p.y+p.height+(o?2:7),width:Math.max(8,x-(o?2:8)),height:Math.max(8,d.y-p.y-p.height-(o?4:12))})}),b.sort((e,t)=>f.findIndex(t=>t.id===e.id)-f.findIndex(e=>e.id===t.id)),{width:i,height:n,phaseRail:a,chamber:p,mouth:y,projection:d,outlets:b}}function pc(e){const{id:t,orientation:i,fixed:n,start:o,end:r,openings:s,thickness:a,friction:c,restitution:d}=e,l=function(e,t,i){const n=i.map(([i,n])=>[Math.max(e,Math.min(i,n)),Math.min(t,Math.max(i,n))]).filter(([e,t])=>t>e+nc).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];let r=e;for(const[e,t]of n)e>r+nc&&o.push([r,e]),r=Math.max(r,t);return t>r+nc&&o.push([r,t]),o}(o,r,s);return l.map(([e,o],r)=>({id:1===l.length?t:`${t}:${r}`,friction:c,restitution:d,shape:"horizontal"===i?{type:"segment",x1:e,y1:n,x2:o,y2:n,thickness:a}:{type:"segment",x1:n,y1:e,x2:n,y2:o,thickness:a}}))}function mc(e){const{chamber:t,mouth:i}=e,n=Math.max(2,Math.min(10,.018*Math.min(e.width,e.height))),o=Math.max(t.x,i.x),r=Math.min(t.x+t.width,i.x+i.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:o,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(...pc({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}),...pc({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}),...pc({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}function yc(e){let t=2166136261;for(let i=0;e.length>i;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}function fc(e){return"number"==typeof e&&Number.isFinite(e)?e>>>0:"string"==typeof e?yc(e):1}function gc(e,t){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:t.map(e=>({...e,shape:{...e.shape}})),observation:{chartType:"crucible"},kernel:{seed:fc(e),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function bc(e){return"crucible:component:"+encodeURIComponent(e)}function vc(e){return"crucible:product:"+encodeURIComponent(e)}function xc(e,t){return`crucible:bond:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function wc(e,t,i,n){if(void 0!==i&&Number.isFinite(i)&&i>0)return i;const o=Math.min(...t,e),r=Math.max(...t,e);return r-o>nc?n[0]+(n[1]-n[0])*Math.sqrt(Math.max(0,e-o)/(r-o)):(n[0]+n[1])/2}function kc(e,t){const i=Math.max(.25,Math.min(1,t.width/900,t.height/520)),n=e?.[0]??7*i,o=e?.[1]??18*i,r=Math.max(1,Math.min(n,o));return[r,Math.max(r,Math.max(n,o))]}function Ic(e,t,i={}){const n=Object.values(e.components).sort((e,t)=>oc(e.id,t.id)),o=n.map(e=>e.amount),r=kc(i.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}}(fc(i.seed)),a=t.mouth.x+t.mouth.width/2,c=t.chamber.y+Math.max(18,.18*t.chamber.height),d=Math.max(4,.28*t.chamber.width),l=Math.max(4,.12*t.chamber.height);return n.map((e,t)=>{const u=t/Math.max(1,n.length)*Math.PI*2+.18*(s()-.5),h=wc(e.amount,o,i.bodyRadius,r),p={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:bc(e.id),x:a+Math.cos(u)*d*(.45+.45*s()),y:c+Math.sin(u)*l*(.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}})}function Mc(e,t){if(!e)return[];const i=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/i));return Array.from({length:e},(e,o)=>({x:t.x+t.width/i*(o%i+.5),y:t.y+(Math.floor(o/i)+.5)*(t.height/n)}))}function Sc(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 Ac(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 Cc(e,t,i={}){const n=Object.values(e.products).sort((e,t)=>oc(e.id,t.id)),o=Object.values(e.components).sort((e,t)=>oc(e.id,t.id)),r=[...o.map(e=>e.amount),...n.map(e=>e.amount)],s=kc(i.radiusRange,t),a=function(e,t){const i=new Map;for(const t of e){const e=t.outletId??"__chamber__",n=i.get(e)??[];n.push(t),i.set(e,n)}const n=new Map;for(const[e,o]of i){o.sort((e,t)=>(e.order??Number.MAX_SAFE_INTEGER)-(t.order??Number.MAX_SAFE_INTEGER)||oc(e.id,t.id));const i=Mc(o.length,Ac(t,"__chamber__"===e?void 0:e));o.forEach((e,t)=>n.set(e.id,i[t]))}return n}(n,t),c=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},o=1.28*wc(e.amount,r,i.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:e.id,product:e};return{id:vc(e.id),x:n.x,y:n.y,mass:Math.max(.25,o*o*.018),bodyCollisions:!1,shape:{type:"circle",radius:o},datum:c}}),d=new Map;for(const e of o.filter(e=>!e.productIds.length)){const t=Sc(e)??"__chamber__",i=d.get(t)??[];i.push(e),d.set(t,i)}const l=new Map;for(const[e,i]of d){const n=Mc(i.length,Ac(t,"__chamber__"===e?void 0:e));i.forEach((e,t)=>l.set(e.id,n[t]))}return[...o.map(e=>{let n=l.get(e.id);if(e.productIds.length){const i=e.productIds.map(e=>a.get(e)).filter(e=>!!e);if(i.length){n={x:i.reduce((e,t)=>e+t.x,0)/i.length,y:i.reduce((e,t)=>e+t.y,0)/i.length};const o=yc(e.id)/4294967295*Math.PI*2,r=Math.min(20,Math.max(4,.012*t.width));n={x:n.x+Math.cos(o)*r,y:n.y+Math.sin(o)*r}}}n??(n={x:t.chamber.x+t.chamber.width/2,y:t.chamber.y+t.chamber.height/2});const o=wc(e.amount,r,i.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:e.id,sourceDatum:e.datum};return{id:bc(e.id),x:n.x,y:n.y,mass:Math.max(.25,o*o*.015),shape:{type:"circle",radius:o},datum:c}}),...c]}var Rc=Cc;function Pc(e){return Array.isArray(e)?e.map(Pc):e&&"object"==typeof e?Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e&&"function"!=typeof e).sort(([e],[t])=>oc(e,t)).map(([e,t])=>[e,Pc(t)])):e}function $c(e){return JSON.stringify(Pc(e))}function Dc(e,t){const i=ac(t)??0,n=Math.max(0,Math.min(e.duration,i));if(!e.phases.length)return{elapsed:n,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const o=n>=e.duration-nc,r=o?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:o?r.duration:Math.max(0,n-r.start),complete:o}}function Bc(e,t){if(void 0===t)return e.duration;if("number"==typeof t)return Math.max(0,Math.min(e.duration,ac(t)??0));const i=e.phases.find(e=>e.id===t.phaseId);if(!i)return e.duration;const n=Math.max(0,Math.min(1,ac(t.progress??0)??0));return i.start+i.duration*n}function jc(e,t=e.duration){const i=Dc(e,t);let n=Da(e.initialState);const o=[],r=[],s=[];for(const t of e.events){if(t.authoredAt>i.elapsed+nc)break;const a=Ga(n,t,{phaseId:t.phaseId,authoredAt:t.authoredAt,appliedAt:t.authoredAt,products:e.products,outlets:e.outlets});o.push(...a.diagnostics),r.push(...a.materializations),s.push(...a.observations),a.applied&&(n=a.state)}return n.elapsed=i.elapsed,n.phaseId=i.phaseId,n.phaseIndex=i.phaseIndex,n.phaseElapsed=i.phaseElapsed,n.complete=i.complete,i.complete&&"in_process"===n.outcome&&(n.outcome="complete"),n.playing=!1,{state:n,diagnostics:o,materializations:r,observations:s}}function Tc(e){const t=function(e){const t=[];e.length||t.push(rc("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const i=sc(e.map(e=>e.id));i.length&&t.push(rc("error","duplicate-phase-id",`Phase ids must be unique: ${i.join(", ")}.`,"phases",i));let n=0;return{phases:e.map((e,i)=>{const o=ac(e.duration),r=null!=o&&o>0?o:0;e.id.trim()||t.push(rc("error","invalid-phase-id","Phase ids may not be empty.",`phases.${i}.id`)),null!=o&&o>0||t.push(rc("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${i}.duration`,[e.id])),void 0===e.intensity||Number.isFinite(e.intensity)||t.push(rc("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${i}.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:i,start:n,end:n+r};return n=s.end,s}),diagnostics:t}}(e.phases),i=t.phases.at(-1)?.end??0,n=uc(e.outlets??tc),o=(e.products??[]).map(e=>({...e,metrics:e.metrics?Ra(e.metrics):void 0})),r=function(e,t,i){const n=[],o=sc(e.map(e=>e.id));o.length&&n.push(rc("error","duplicate-event-id",`Event ids must be unique: ${o.join(", ")}.`,"events",o));const r=[];return e.forEach((e,o)=>{let s,a,c;if(e.id.trim()||n.push(rc("error","invalid-event-id","Event ids may not be empty.",`events.${o}.id`)),"time"in e.at&&void 0!==e.at.time){const r=ac(e.at.time);if(null==r||0>r||r>i+nc)return void n.push(rc("error","event-time-out-of-range",`Event time must fall between 0 and ${i}.`,`events.${o}.at.time`,[e.id]));s=Math.max(0,Math.min(i,r));const d=function(e,t,i){const n=e.find(e=>nc>=Math.abs(e.start-i));if(n)return{phase:n,boundaryRank:1};const o=e.find(e=>i>=e.start&&e.end>i);return o?{phase:o,boundaryRank:0}:nc>=Math.abs(i-t)&&e.length?{phase:e[e.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(t,i,s);a=d.phase,c=d.boundaryRank}else{if(a=t.find(t=>t.id===e.at.phaseId),!a)return void n.push(rc("error","unknown-event-phase",`Event references unknown phase "${e.at.phaseId}".`,`events.${o}.at.phaseId`,[e.id,e.at.phaseId]));const i=e.at.progress??0;if(!Number.isFinite(i)||0>i||i>1)return void n.push(rc("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${o}.at.progress`,[e.id]));s=a.start+a.duration*i,c=0===i?1:0}a?r.push({...e,index:o,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):n.push(rc("error","event-without-phase","Event could not be assigned to a phase.",`events.${o}.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,i),s=lc(e),a=hc(e.size??ec,n),c=mc(a),d=function(e,t){const i=[],n=new Set(t.map(e=>e.id)),o=sc(t.map(e=>e.id)),r=sc(e.map(e=>e.id));return o.length&&i.push(rc("error","duplicate-outlet-id",`Outlet ids must be unique: ${o.join(", ")}.`,"outlets",o)),r.length&&i.push(rc("error","duplicate-product-id",`Product ids must be unique: ${r.join(", ")}.`,"products",r)),t.forEach((e,t)=>{e.id.trim()||i.push(rc("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${t}.id`)),void 0===e.order||Number.isFinite(e.order)||i.push(rc("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${t}.order`,[e.id]))}),e.forEach((e,t)=>{e.id.trim()||i.push(rc("error","invalid-product-id","Product ids may not be empty.",`products.${t}.id`)),void 0===e.amount||Number.isFinite(e.amount)&&e.amount>=0||i.push(rc("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)||i.push(rc("error","unknown-outlet",`Product "${e.id}" references unknown outlet "${e.outletId}".`,`products.${t}.outletId`,[e.outletId])),dc(e.metrics??{},i,`products.${t}.metrics`)}),i}(o,n),l=$c({seed:e.seed??1,components:Object.values(s.state.components).sort((e,t)=>oc(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:i,description:n,intensity:o,motion:r,color:s,metrics:a})=>({id:e,duration:t,label:i,description:n,intensity:o,motion:r,color:s,metrics:a})),products:o,outlets:n,events:r.events.map(({id:e,label:t,description:i,summary:n,authoredAt:o,phaseId:r,boundaryRank:s,effects:a})=>({id:e,label:t,description:i,summary:n,authoredAt:o,phaseId:r,boundaryRank:s,effects:a}))}),u=Ic(s.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),h=[...t.diagnostics,...r.diagnostics,...s.diagnostics,...d],p={phases:t.phases,events:r.events,products:o,outlets:n,duration:i,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:gc(e.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:l,diagnostics:h},m=jc(p),y=Object.values(m.state.products).filter(e=>"forming"===e.status).map(e=>e.id),f=y.length?[rc("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${y.join(", ")}.`,"events",y)]:[];return p.terminalState=m.state,p.terminalSpawns=Rc(m.state,a,{seed:e.seed,bodyRadius:e.bodyRadius,radiusRange:e.radiusRange}),p.diagnostics=[...h,...m.diagnostics,...f],p}function Oc(e,t,i){return{id:e.id??t,at:{...e.at},effects:i,...void 0===e.label?null:{label:e.label},...void 0===e.description?null:{description:e.description},...void 0===e.summary?null:{summary:e.summary}}}function Ec(e){if(e)return{...e,...e.metrics?{metrics:{...e.metrics}}:null}}function Nc(e){const{productId:t,form:i,contributions:n=[],complete:o}=e,r=e.idPrefix??t,s=Ec(i.loss),a=[Oc(i,r+"-form",[{type:"combine",sourceIds:[...i.sourceIds],productId:t,...i.basisRelationIds?{basisRelationIds:[...i.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return n.forEach((e,i)=>{const n=Ec(e.loss);a.push(Oc(e,`${r}-contribute-${i+1}`,[{type:"contribute",sourceIds:[...e.sourceIds],productId:t,...e.basisRelationIds?{basisRelationIds:[...e.basisRelationIds]}:null,...n?{loss:n}:null}]))}),a.push(Oc(o,r+"-complete",[{type:"complete-product",productId:t,...void 0===o.outletId?null:{outletId:o.outletId},...void 0===o.reason?null:{reason:o.reason}}])),a}import{forwardRef as Fc,useCallback as Wc,useEffect as qc,useImperativeHandle as zc,useMemo as Hc,useRef as Lc,useState as Yc}from"react";function _c(e,t){return e.playing=t&&!e.complete,e}function Xc(e,t,i=!1){const n=jc(e,t);return{...n,state:_c(n.state,i)}}function Gc(e,t,i,n=t.playing){const o=Xc(e,i,n),r=new Set(t.eventsApplied);return{...o,observations:o.observations.filter(e=>!r.has(e.eventId)),materializations:o.materializations.filter(e=>!r.has(e.eventId))}}function Uc(e,t,i={}){return Cc(t,e.layout,i)}function Vc(e,t){return function(e){let t=2166136261;for(let i=0;e.length>i;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}(`${t}:${e}`)/4294967295}function Kc(e,t){return e.phases[t.phaseIndex]??e.phases.find(e=>e.id===t.phaseId)}function Qc(e,t,i={}){return new Map(Uc(e,t,i).flatMap(e=>{const t=e.datum;return t?.__crucible?[[`${t.kind}:${t.semanticId}`,{x:e.x,y:e.y}]]:[]}))}function Jc(e,t){const i=Object.values(e.terminalState.products).map(e=>e.id).sort(),n=Math.max(0,i.indexOf(t))/Math.max(1,i.length)*Math.PI*2-Math.PI/2,o=Math.min(58,.19*e.layout.chamber.width),r=Math.min(38,.16*e.layout.chamber.height);return{x:e.layout.chamber.x+e.layout.chamber.width/2+Math.cos(n)*o,y:e.layout.chamber.y+.52*e.layout.chamber.height+Math.sin(n)*r}}import*as Zc from"react";import{jsx as ed,jsxs as td}from"react/jsx-runtime";function id(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 nd(e){const t=e.productIds.length?` Contributes to ${e.productIds.join(", ")}.`:e.outletId?` Routed to ${e.outletId}.`:"",i=e.reason?` ${e.reason}.`:"";return`${id(e.amount)} amount; ${e.status}.${t}${i}`}function od(e){const t=e.outletId?` Routed to ${e.outletId}.`:"";return`${e.status} product with ${e.sourceIds.length} source${1===e.sourceIds.length?"":"s"} and ${id(e.amount)} amount.${t}`}function rd(e,t,i,n){const o=t.datum;if(!o?.__crucible)return;const r="circle"===t.shape.type?t.shape.radius:8,s="product"===o.kind?"#b8792d":"#356b63",a=n?.resolvePaint??((t,i)=>N(e,t,i)),c=a(i.fill,s),d=a(i.stroke,"#26323a");if(e.save(),e.translate(t.x,t.y),e.globalAlpha="number"==typeof i.opacity?i.opacity:.96,e.fillStyle=c,e.strokeStyle=d,e.lineWidth="number"==typeof i.strokeWidth?i.strokeWidth:1.25,"product"===o.kind){e.shadowColor="string"==typeof c?c:s,e.shadowBlur=10,e.beginPath();for(let t=0;6>t;t+=1){const i=-Math.PI/2+t/6*Math.PI*2,n=Math.cos(i)*r,o=Math.sin(i)*r;0===t?e.moveTo(n,o):e.lineTo(n,o)}e.closePath(),e.fill(),e.shadowBlur=0,e.stroke(),e.beginPath(),e.arc(0,0,Math.max(2,.36*r),0,2*Math.PI),e.strokeStyle=a("var(--semiotic-bg, #fffaf0)","#fffaf0"),e.globalAlpha*=.72,e.stroke()}else e.beginPath(),e.arc(0,0,r,0,2*Math.PI),e.fill(),e.stroke(),e.beginPath(),e.arc(.25*-r,.28*-r,Math.max(1,.18*r),0,2*Math.PI),e.fillStyle="rgba(255,255,255,0.34)",e.fill();e.restore()}import{Fragment as sd,jsx as ad,jsxs as cd}from"react/jsx-runtime";var dd="var(--semiotic-text, #26323a)",ld="var(--semiotic-text-secondary, #6c7377)",ud="var(--semiotic-primary, #b8792d)",hd="var(--semiotic-danger, #9f3d35)",pd="var(--semiotic-success, #356b63)";function md(e){const{x:t,y:i,width:n,height:o}=e.chamber,r=Math.min(.14*n,48),s=i+o;return[`M ${t} ${i}`,`L ${t+r} ${s-.16*o}`,`Q ${t+n/2} ${s+.1*o} ${t+n-r} ${s-.16*o}`,`L ${t+n} ${i}`].join(" ")}function yd({layout:e,phases:t,state:i,compact:n=!1}){const o=Math.max(1,t.reduce((e,t)=>e+Math.max(0,t.duration),0));return cd("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[cd("defs",{children:[cd("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[ad("stop",{offset:"0",stopColor:ud,stopOpacity:"0.03"}),ad("stop",{offset:"0.66",stopColor:ud,stopOpacity:"0.1"}),ad("stop",{offset:"1",stopColor:hd,stopOpacity:"0.18"})]}),ad("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:ad("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:dd,strokeOpacity:"0.08",strokeWidth:"1"})})]}),ad("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:dd,strokeOpacity:"0.52",strokeWidth:n?1:2.2}),ad("path",{d:md(e),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),ad("line",{x1:e.mouth.x,x2:e.mouth.x+e.mouth.width,y1:e.mouth.y,y2:e.mouth.y,stroke:dd,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:n?2:5}),n?null:ad("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/o*e.phaseRail.width,c=Math.max(0,n.duration)/o*e.phaseRail.width,d=n.id===i.phaseId,l=i.phaseIndex>r||i.complete;return cd("g",{children:[ad("rect",{x:a,y:e.phaseRail.y,width:Math.max(1,c-2),height:e.phaseRail.height,rx:2,fill:d?n.color??ud:l?pd:dd,fillOpacity:d?.68:l?.28:.09}),46>c?null:ad("text",{x:a+c/2,y:e.phaseRail.y+e.phaseRail.height+13,fill:d?dd:ld,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:d?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(n.label??n.id).toUpperCase()})]},n.id)})}),e.outlets.map(e=>cd("g",{children:[ad("rect",{x:e.x,y:e.y,width:e.width,height:e.height,rx:3,fill:e.color??("left"===e.side?hd:pd),fillOpacity:"0.1",stroke:e.color??("left"===e.side?hd:pd),strokeDasharray:"3 3",strokeOpacity:"0.62"}),n?null:ad("text",{x:e.x+e.width/2,y:e.y+Math.min(13,e.height/2+3),fill:ld,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(e.label??e.id).toUpperCase()})]},e.id))]})}function fd(e,t){return"count"===t?e.count:"amount"===t?e.amount:Number(e.metrics[t]??0)}function gd({rows:e,layout:t,projection:i,amountLabel:n}){if(!e.length)return null;const o=i.measure??"count",r=e.map(e=>Math.max(0,fd(e,o))),s=Math.max(1,...r),a=t.projection.width/Math.max(1,e.length),c=t.projection.height>48?21:4,d=Math.max(5,t.projection.height-c-5);return ad("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,i)=>{const l=r[i],u=Math.max(l>0?2:0,l/s*d),h=t.projection.x+i*a+.18*a;return cd("g",{children:[ad("rect",{x:h,y:t.projection.y+d-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===e.status||"ejected"===e.status?hd:"complete"===e.status?ud:pd,fillOpacity:"0.68"}),c>4&&a>=34?cd(sd,{children:[ad("text",{x:h+.32*a,y:t.projection.y+d+10,fill:ld,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:e.label.length>13?e.label.slice(0,12)+"…":e.label}),cd("text",{x:h+.32*a,y:t.projection.y+d+19,fill:dd,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[id(l),"amount"===o&&n?" "+n:""]})]}):null]},e.key)})})}function bd({controls:e,duration:t,elapsed:i,phaseLabel:n,playing:o,complete:r,playbackRate:s,disabled:a,onPlayPause:c,onReset:d,onStepPhase:l,onPlaybackRateChange:u}){const h=t>0?Math.min(1,Math.max(0,i/t)):1;return cd("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:dd,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[e.playPause?ad("button",{type:"button",disabled:a,onClick:c,"aria-pressed":o,children:o?"Pause":r?"Replay":"Play"}):null,e.stepPhase?ad("button",{type:"button",disabled:a,onClick:l,children:"Next phase"}):null,e.reset?ad("button",{type:"button",disabled:a,onClick:d,children:"Reset"}):null,e.timeline?cd("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[ad("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:n}),ad("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:ad("span",{style:{background:ud,display:"block",height:"100%",transform:`scaleX(${h})`,transformOrigin:"left center"}})}),cd("span",{style:{color:ld,fontVariantNumeric:"tabular-nums"},children:[i.toFixed(1),"s"]})]}):null,e.speed?cd("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",cd("select",{disabled:a,value:s,onChange:e=>u(Number(e.currentTarget.value)),children:[ad("option",{value:.25,children:"¼×"}),ad("option",{value:.5,children:"½×"}),ad("option",{value:1,children:"1×"}),ad("option",{value:2,children:"2×"})]})]}):null]})}function vd(e,t,i,n){const o="function"==typeof n?n(t,i):n,r=t.datum;return{fill:e,stroke:"product"===r?.kind?"var(--semiotic-bg, #fffaf0)":dd,strokeWidth:"product"===r?.kind?1.8:1.1,opacity:.96,...o}}var xd=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function wd(e){let t=2166136261;for(let i=0;e.length>i;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t>>>0}function kd(e){return"number"==typeof e&&Number.isFinite(e)?e:wd((e??"crucible")+"")}function Id(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.max(.05,Math.min(8,t)):1}function Md(e,t,i){return"category"===t?e.category:"status"===t?e.status:"outlet"===t?e.outletId??"in chamber":"product"===t?e.productIds[0]??"unalloyed":function(e,t,i){return(("function"==typeof e?e(t,i):t[e])??"unassigned")+""}(t,e.datum,i)}function Sd(e){return xd[wd(e)%xd.length]}function Ad(e,t){const i=Object.keys(e.components).length,n=Object.keys(e.products).length,o=Object.values(e.products).reduce((e,t)=>e+t.amount,0),r=t?" "+t:" amount",s=e.outcome?` Outcome: ${e.outcome}.`:"";return`${i} source component${1===i?"":"s"}; ${n} product${1===n?"":"s"}; ${o.toLocaleString()}${r} in products.${s}`}import{jsx as Cd,jsxs as Rd}from"react/jsx-runtime";import{createElement as Pd}from"react";var $d=Fc(function(e,t){const{amountAccessor:i,amountLabel:n,bodyRadius:o,categoryAccessor:r,colorBy:s="category",conservation:a,controls:c,data:d,emptyContent:l,events:u,frameProps:h={},idAccessor:p,initialStateAccessor:m,initialSpawnPacing:y,labelAccessor:f,loading:g,loadingContent:b,metrics:v,metricsAccessor:x,onClick:w,onConservation:k,onCrucibleObservation:M,onDiagnostic:S,onStateChange:A,outlets:C,paused:R,phases:P,playback:$="replay",playbackRate:D=1,products:B,projection:j,radiusRange:T,rerunMS:O,seed:E,showBonds:N=!0,snapshotAt:F}=e,W=Lc(null),q=Lc(R);q.current=R;const z=ie(),H=Q(),L=Zo(e,ec),{chartMode:Y,chartSize:_,responsiveContainerRef:X,responsiveHeight:G,responsiveWidth:U,showChrome:V,showProjection:K,className:J,title:Z,description:ee,summary:te,accessibleTable:ne,enableHover:oe,margin:re}=L,se=_,ae=Hc(()=>I(d??[]),[d]),ce=Hc(()=>Tc({data:ae,phases:P,products:B,outlets:C,events:u,idAccessor:p,labelAccessor:f,categoryAccessor:r,amountAccessor:i,metricsAccessor:x,initialStateAccessor:m,metrics:v,size:se,seed:E,bodyRadius:o,radiusRange:T}),[i,o,r,u,p,m,f,v,x,C,P,B,T,se,ae,E]),de=Object.values(ce.initialState.components).map((e,t)=>Md(e,s,t)).join("\0"),le=`${ce.semanticKey}:${se[0]}x${se[1]}:${(o??"auto")+""}:${T?.join(",")??"auto"}:${de}`,ue=Lc(ce),he=Lc(le);he.current!==le&&(he.current=le,ue.current=ce);const pe=ue.current,me="snapshot"===$||z||H,ye=me?function(e,t){return Bc(e,t)}(pe,F):0,fe=!me,ge=Hc(()=>Xc(pe,ye,fe&&!R),[he.current,ye,fe]),[be,ve]=Yc(ge),xe=Lc(be),[we,ke]=Yc(fe),Ie=Lc(we),[Me,Se]=Yc(0),[Ae,Ce]=Yc(()=>Id(D)),Re=Lc(Qc(pe,ge.state,{seed:E,bodyRadius:o,radiusRange:T})),Pe=Lc(""),$e=Lc(A),De=Lc(M),Be=Lc(S),je=Lc(k);$e.current=A,De.current=M,Be.current=S,je.current=k;const Te=Lc({seed:E,bodyRadius:o,radiusRange:T});Te.current={seed:E,bodyRadius:o,radiusRange:T};const Oe=Wc((e,t=!1)=>{if(xe.current=e,Re.current=Qc(ue.current,e.state,Te.current),ve(e),t)for(const t of e.observations)De.current?.(t)},[]);qc(()=>{Ce(Id(D))},[D]),qc(()=>{const e=!me,t=Xc(pe,me?ye:0,e&&!q.current);Ie.current=e,ke(e),Oe(t)},[Oe,pe,ye,me,le]),qc(()=>{const e=xe.current,t=Ie.current&&!R&&!e.state.complete;if(e.state.playing===t)return;const i={...e,state:Da(e.state)};i.state.playing=t,Oe(i)},[Oe,R]),qc(()=>{for(const e of pe.diagnostics)Be.current?.(e)},[le,pe.diagnostics]),qc(()=>{if($e.current?.(be.state),a){const e=!0===a?{}:a;je.current?.(Ka(be.state,e))}},[a,be.state]);const Ee=Wc(()=>{Pe.current="";const e=!me,t=Xc(ue.current,0,e&&!R);Ie.current=e,ke(e),Oe(t)},[Oe,R,me]),Ne=Hc(()=>({...pe.config,...h.config,fixedDt:h.config?.fixedDt??pe.config.fixedDt,maxSubsteps:h.config?.maxSubsteps??pe.config.maxSubsteps,settleStepLimit:h.config?.settleStepLimit??pe.config.settleStepLimit,timeScale:Ae,colliders:[...pe.config.colliders??[],...h.config?.colliders??[]],kernel:{...pe.config.kernel,...h.config?.kernel,gravity:h.config?.kernel?.gravity??pe.config.kernel?.gravity??{x:0,y:0}},observation:{...pe.config.observation,...h.config?.observation,chartType:"CrucibleChart"}}),[h.config,Ae,pe.config]),Fe=me||!!R||!we&&!be.state.complete,We=Jo(Ne,O,Fe,Ee),qe=Wc(()=>{if("number"!=typeof O||!Number.isFinite(O)||0>O)return;const e=`${le}:${Me}:${We.rerunKey}`;Pe.current!==e&&(Pe.current=e,We.config?.observation?.onSimulationStateChange?.("settled","running"))},[We.config,We.rerunKey,O,Me,le]),ze=Wc(()=>{const e=Xc(ue.current,0,!1);Ie.current=!1,ke(!1),Oe(e),Se(e=>e+1)},[Oe]),He=Wc(()=>{const e=ue.current,t=Gc(e,xe.current.state,e.duration,!1);Ie.current=!1,ke(!1),Oe(t,!0);const i=Uc(e,t.state,Te.current),n=W.current;n&&(n.clear(),n.pushMany(i),n.step(0),n.settle()),qe()},[Oe,qe]),Le=Wc(()=>{Ie.current=!1,ke(!1);const e={...xe.current,state:Da(xe.current.state)};e.state.playing=!1,Oe(e)},[Oe]),Ye=Wc(()=>{if(Pe.current="",me){const e=Xc(ue.current,ye,!1);return Ie.current=!1,ke(!1),Oe(e),void Se(e=>e+1)}const e=Xc(ue.current,0,!R);Ie.current=!0,ke(!0),Oe(e),Se(e=>e+1)},[Oe,R,ye,me]),_e=Wc(()=>{if(me)return void Ye();if(xe.current.state.complete)return void Ye();Ie.current=!0,ke(!0);const e={...xe.current,state:Da(xe.current.state)};e.state.playing=!R,Oe(e)},[Oe,R,Ye,me]),Xe=Wc(()=>{const e=ue.current,t=function(e,t){const i=e.phases.find(e=>e.end>t+1e-7);return i?.end??e.duration}(e,xe.current.state.elapsed),i=Gc(e,xe.current.state,t,!1);Ie.current=!1,ke(!1),Oe(i,!0);const n=W.current;n&&(n.clear(),n.pushMany(Uc(e,i.state,Te.current)),n.step(0))},[Oe]);zc(t,()=>({play:_e,pause:Le,reset:ze,replay:Ye,stepPhase:Xe,settle:He,getCrucibleState:()=>Da(xe.current.state)}),[Le,_e,Ye,ze,He,Xe]);const Ge=Wc((e,t)=>{if(h.onTick?.(e,t),me||R||!Ie.current)return;const i=xe.current.state,n=Math.min(ue.current.duration,e.elapsedSeconds);if(i.elapsed+.045>=n&&ue.current.duration>n)return;const o=Gc(ue.current,i,n,ue.current.duration>n),r=o.state.eventsApplied.length!==i.eventsApplied.length;if(r&&function(e,t){const i=new Set(e.readBodies().map(e=>e.id)),n=t.filter(e=>!i.has(e.id));n.length&&e.pushMany([...n]),n.map(e=>e.id)}(t,Uc(ue.current,o.state,Te.current)),o.state.complete){Ie.current=!1,ke(!1);const e=Uc(ue.current,o.state,Te.current);t.clear(),t.pushMany(e),t.step(0),t.settle()}Oe(o,r),o.state.complete&&qe()},[Oe,h,R,qe,me]),Ue=Wc(({body:e})=>function(e){const t=function(e){const{body:t,plan:i,state:n,targets:o}=e,r=t.datum;if(!r?.__crucible)return null;let s=o.get(`${r.kind}:${r.semanticId}`);if(!s)return null;const a=Kc(i,n),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),d=a?.motion??"hold",l=n.elapsed;if("product"===r.kind){const e=n.products[r.semanticId];"forming"===e?.status&&(s=Jc(i,e.id))}else{const e=n.components[r.semanticId],t=e?.productIds.map(e=>n.products[e]).find(e=>"forming"===e?.status);if(t){const n=Jc(i,t.id),o=Vc(e.id,17)*Math.PI*2,r=Math.max(5,Math.min(18,.026*i.layout.width));s={x:n.x+Math.cos(o)*r,y:n.y+Math.sin(o)*r}}}const u=r.semanticId,h=Vc(u,23)*Math.PI*2;if(!n.complete&&!(i.layout.chamber.x>s.x||s.x>i.layout.chamber.x+i.layout.chamber.width||i.layout.chamber.y>s.y||s.y>i.layout.chamber.y+i.layout.chamber.height))if("mix"===d){const e=Math.min(34,.1*i.layout.chamber.width)*c,t=Math.min(24,.09*i.layout.chamber.height)*c;s={x:s.x+Math.cos(l*(1.4+Vc(u,29))+h)*e,y:s.y+Math.sin(l*(1.8+Vc(u,31))+h)*t}}else if("press"===d){const e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.56*i.layout.chamber.height;s={x:e+(s.x-e)*Math.max(.3,1-.32*c),y:t+(s.y-t)*Math.max(.35,1-.26*c)}}else if("separate"===d){const e=.5>Vc(u,41)?-1:1;s={x:s.x+e*Math.min(28,.075*i.layout.chamber.width)*c,y:s.y}}else if("bind"===d){const e=i.layout.chamber.x+i.layout.chamber.width/2,t=i.layout.chamber.y+.5*i.layout.chamber.height;s={x:e+.72*(s.x-e),y:t+.72*(s.y-t)}}else"charge"===d?s={x:s.x,y:s.y+4*Math.sin(2*l+h)*c}:"quench"===d&&(s={x:s.x+2*Math.sin(h)*c,y:s.y});return s}(e);if(!t)return null;const{body:i,state:n}=e,o=t.x-i.x,r=t.y-i.y,s=Math.hypot(o,r),a=Math.hypot(i.vx,i.vy);if(n.complete&&.7>s&&.45>a)return null;const c=!n.complete&&"pour"===Kc(e.plan,n)?.motion,d=n.complete?.68:c?.72:.5,l=n.complete?.22:c?.18:.14,u=n.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,o*d-i.vx*l)),y:Math.max(-u,Math.min(u,r*d-i.vy*l))}}({body:e,plan:ue.current,state:xe.current.state,targets:Re.current}),[]),Ve=Hc(()=>new Map(Object.keys(pe.initialState.components).map((e,t)=>[e,t])),[pe.initialState.components]),Ke=Wc(t=>{if(e.color)return e.color;const i=t.datum;if(!i?.__crucible)return"var(--semiotic-primary, #b8792d)";if("product"===i.kind){const e=xe.current.state.products[i.semanticId];return e?.color??Sd(e?.id??i.semanticId)}const n=xe.current.state.components[i.semanticId];return n?Sd(Md(n,s,Ve.get(n.id)??0)):"var(--semiotic-primary, #356b63)"},[s,Ve,e.color]),Qe=Wc((t,i)=>({...vd(Ke(t),t,i,h.bodyStyle),...void 0!==e.stroke?{stroke:e.stroke}:null,...void 0!==e.strokeWidth?{strokeWidth:e.strokeWidth}:null,...void 0!==e.opacity?{opacity:e.opacity}:null}),[Ke,h.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),Je=Wc((e,t)=>("function"==typeof h.bodySemanticItems?h.bodySemanticItems(e,t):void 0)??function(e,t){const i=e.datum;if(!i?.__crucible)return!1;if("component"===i.kind){const e=t.components[i.semanticId];return!!e&&{id:"crucible-component-"+e.id,label:e.label,description:nd(e),group:"source component · "+e.status,datum:e}}const n=t.products[i.semanticId];return!!n&&{id:"crucible-product-"+n.id,label:n.label,description:od(n),group:"derived product · "+n.status,datum:n}}(e,xe.current.state),[h]),Ze=Wc(e=>{if(!w||!e||"object"!=typeof e)return;if(!e.__crucible)return;const t=xe.current.state,i="component"===e.kind?t.components[e.semanticId]:t.products[e.semanticId];i&&w(i)},[w]),et=Wc((e,t,i)=>{h.beforePaint?.(e,t,i),N&&function(e,t,i){const n=new Map;for(const e of t){const t=e.datum;t?.__crucible&&n.set(`${t.kind}:${t.semanticId}`,e)}e.save(),e.lineCap="round";for(const t of Object.values(i.relations)){if("active"!==t.status)continue;const i=t.sourceIds.map(e=>n.get("component:"+e)).filter(e=>!!e);2>i.length||(e.strokeStyle="rejected"===t.category?"#9f3d35":"#b8792d",e.globalAlpha=.4,e.lineWidth=Math.max(.8,1.3*Number(t.strength??1)),e.setLineDash([3,4]),e.beginPath(),i.forEach((t,i)=>{0===i?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.stroke())}e.setLineDash([]);for(const t of Object.values(i.products)){const i=n.get("product:"+t.id);if(i)for(const o of t.sourceIds){const r=n.get("component:"+o);r&&(e.strokeStyle=t.color??"#b8792d",e.globalAlpha="complete"===t.status?.5:.28,e.lineWidth="complete"===t.status?1.6:1,e.beginPath(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke())}}e.restore()}(e,t,xe.current.state)},[h,N]),tt=Hc(()=>j??{groupBy:"outlet",measure:"count"},[j]),it=Hc(()=>Ua(be.state,tt),[tt,be.state]),nt=Hc(()=>K?function(e,t,i,n){if(!e.length)return[];const o=i.measure??"count",r=t.projection.width/Math.max(1,e.length);return e.map((e,i)=>{const s=fd(e,o),a="amount"===o&&n?`${id(s)} ${n}`:`${id(s)} ${o}`;return{id:"crucible-projection-"+e.key,label:`${e.label}: ${a}`,description:`${e.count} source component${1===e.count?"":"s"}; ${id(e.amount)} amount.`,datum:e,group:"settled composition",x:t.projection.x+(i+.5)*r,y:t.projection.y+t.projection.height/2,shape:"rect",width:Math.max(12,.62*r),height:Math.max(8,t.projection.height-8)}})}(it,pe.layout,tt,n):[],[n,pe.layout,tt,it,K]),ot=or(e.tooltip,h),{selection:rt,onBodyHover:st}=Ko({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"CrucibleChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover}),at=rr({...e,onClick:void 0},h,nt,{selection:rt,chartMode:Y,className:J,title:Z??"Crucible",description:ee??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:te??Ad(be.state,n),accessibleTable:ne,enableHover:oe,margin:re}),ct=nr(V?Cd(yd,{layout:pe.layout,phases:pe.phases,state:be.state,compact:L.compactMode||360>se[0]||260>se[1]}):void 0,h.backgroundGraphics),dt=nr(K?Cd(gd,{rows:it,layout:pe.layout,projection:tt,amountLabel:n}):void 0,h.foregroundGraphics),lt=Wc(e=>function(e,t){const i=e.data;if(!i?.__crucible)return null;const n="component"===i.kind?t.components[i.semanticId]:t.products[i.semanticId];if(!n)return null;const o="product"===i.kind;return cd("div",{className:"semiotic-tooltip semiotic-crucible-tooltip",style:{background:"var(--semiotic-tooltip-bg, rgba(38, 50, 58, 0.96))",border:"1px solid rgba(255,255,255,0.2)",borderRadius:3,boxShadow:"0 8px 24px rgba(0,0,0,0.28)",color:"var(--semiotic-tooltip-text, #fffaf0)",maxWidth:290,padding:"9px 12px"},children:[ad("strong",{children:n.label}),ad("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:o?"Product · "+n.status:"Source · "+n.status}),ad("div",{style:{marginTop:4},children:o?od(n):nd(n)})]})}(e,xe.current.state),[]),ut=me?Uc(pe,be.state,Te.current):pe.initialSpawns,ht=function(e){return e?!0===e?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:e.playPause??!0,reset:e.reset??!0,stepPhase:e.stepPhase??!0,timeline:e.timeline??!0,speed:e.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(c),pt=Object.values(ht).some(Boolean),mt=pe.phases[be.state.phaseIndex],yt=tr({data:d,emptyContent:l,loading:g,loadingContent:b,size:se});if(yt)return yt;const ft=pe.diagnostics.filter(e=>"error"===e.severity);return ft.length?Rd("div",{className:J,role:"alert",style:{maxWidth:"100%",width:se[0]},children:[Cd("strong",{children:"CrucibleChart could not compile this treatment tape."}),Cd("ul",{children:ft.map((e,t)=>Cd("li",{children:e.message},`${e.code}-${t}`))})]}):ir("CrucibleChart",se,Rd("div",{ref:X,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:U?"100%":se[0],height:G?"100%":void 0},children:[pt?Cd(bd,{controls:ht,duration:pe.duration,elapsed:be.state.elapsed,phaseLabel:mt?.label??mt?.id??"Complete",playing:we&&!R,complete:be.state.complete,playbackRate:Ae,disabled:me,onPlayPause:we?Le:_e,onReset:ze,onStepPhase:Xe,onPlaybackRateChange:Ce}):null,Pd(Bn,{...h,...ot,...at,key:`${se[0]}x${se[1]}:${le}:${Me}:${We.rerunKey}:${me?ye:"replay"}`,ref:W,onBodyHover:st,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:ct,bodyForces:Ue,bodySemanticItems:Je,bodyStyle:Qe,beforePaint:et,config:We.config,continuous:!me&&we&&!R&&!be.state.complete,enableHover:ot.enableHover??oe,foregroundGraphics:dt,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:ut,initialSpawnPacing:y,onClick:w?Ze:at.onClick,onTick:Ge,paused:Fe,renderBody:h.renderBody??rd,responsiveHeight:!1,responsiveWidth:!1,seed:kd(E),size:se,tooltipContent:ot.tooltipContent??lt})]}))});function Dd(e,t,i={}){const n=new Set,o=[...e.get(t)??[]];for(let t=0;o.length>t;t++){const i=o[t];n.has(i)||(n.add(i),o.push(...e.get(i)??[]))}return i.includeStart&&n.add(t),n}function Bd(e,t,i){return F(i,e,t)}function jd(e,t){return t>e?-1:e>t?1:0}function Td(e,t){return`dependency:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Od(e,t){return`socket:${encodeURIComponent(e)}:${t}`}function Ed(e){const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):0}function Nd(e){const t=[],i=new Map,n=[],o=new Set;e.data.forEach((r,s)=>{const a=(Bd(r,s,e.taskIDAccessor)??"")+"";if(!a)return void t.push({code:"duplicate-task-id",message:`Task row ${s} has an empty id.`,taskIDs:[]});if(i.has(a))return void t.push({code:"duplicate-task-id",message:`Task id "${a}" occurs more than once.`,taskIDs:[a]});const c=(Bd(r,s,e.laneAccessor)??"Unassigned")+"";o.has(c)||(o.add(c),n.push(c));const d=Bd(r,s,e.dependencyAccessor)??[],l=Array.from(new Set(Array.from(d,e=>e+""))).sort(jd),u=Bd(r,s,e.blockerAccessor),h=Bd(r,s,e.statusAccessor)??(u?"blocked":"waiting");i.set(a,{id:a,label:(Bd(r,s,e.labelAccessor)??a)+"",lane:c,laneIndex:0,level:0,index:s,datum:r,dependencyIDs:l,incomingEdgeIDs:[],outgoingEdgeIDs:[],socketIDs:[],start:Bd(r,s,e.startAccessor),end:Bd(r,s,e.endAccessor),progress:Ed(Bd(r,s,e.progressAccessor)),status:h,completionTime:Bd(r,s,e.completionTimeAccessor),blockerReason:u||void 0,milestone:!!Bd(r,s,e.milestoneAccessor)})});const r=e.laneOrder?[...e.laneOrder,...n.filter(t=>!e.laneOrder?.includes(t))]:n,s=new Map(r.map((e,t)=>[e,t]));for(const e of i.values())e.laneIndex=s.get(e.lane)??0;const a=new Map,c=new Map;for(const e of i.keys())a.set(e,[]),c.set(e,[]);const d=[],l=[...i.values()].sort((e,t)=>e.index-t.index);for(const e of l)e.dependencyIDs.forEach((n,o)=>{const r=i.get(n);if(!r)return void t.push({code:"missing-dependency",message:`Task "${e.id}" depends on missing task "${n}".`,taskIDs:[e.id,n]});const s={id:Td(n,e.id),sourceID:n,targetID:e.id,sourceIndex:r.index,targetIndex:e.index,socketID:Od(e.id,o),socketIndex:o};d.push(s),a.get(e.id)?.push(s),c.get(n)?.push(s),e.incomingEdgeIDs.push(s.id),e.socketIDs.push(s.socketID),r.outgoingEdgeIDs.push(s.id)});for(const e of a.values())e.sort((e,t)=>jd(e.sourceID,t.sourceID)),e.forEach((e,t)=>{e.socketIndex=t,e.socketID=Od(e.targetID,t)});for(const e of c.values())e.sort((e,t)=>jd(e.targetID,t.targetID));for(const e of i.values()){const t=a.get(e.id)??[];e.incomingEdgeIDs=t.map(e=>e.id),e.socketIDs=t.map(e=>e.socketID),e.outgoingEdgeIDs=(c.get(e.id)??[]).map(e=>e.id)}const u=new Map,h=new Map;for(const e of i.keys())u.set(e,a.get(e)?.length??0),h.set(e,0);const p=[...i.keys()].filter(e=>0===u.get(e)).sort(jd);let m=0;for(;p.length;){const e=p.shift();m+=1;for(const t of c.get(e)??[]){const i=Math.max(h.get(t.targetID)??0,(h.get(e)??0)+1);h.set(t.targetID,i);const n=(u.get(t.targetID)??0)-1;if(u.set(t.targetID,n),0===n){const e=p.findIndex(e=>e>t.targetID);0>e?p.push(t.targetID):p.splice(e,0,t.targetID)}}}if(m!==i.size){const e=[...i.keys()].filter(e=>(u.get(e)??0)>0).sort(jd);t.push({code:"cycle",message:`Dependency graph contains a cycle involving: ${e.join(", ")}.`,taskIDs:e})}let y=0;const f=[...i.values()].sort((e,t)=>e.index-t.index);for(const e of f)e.level=h.get(e.id)??0,y=Math.max(y,e.level);return{nodes:f,edges:d,byID:i,incoming:a,outgoing:c,lanes:r,maxLevel:y,diagnostics:t,valid:0===t.length}}function Fd(e,t,i={}){const n=Math.max(240,t.width),o=Math.max(220,t.height),r=t.paddingX??48,s=t.paddingTop??48,a=t.paddingBottom??44,c=Math.max(70,(n-2*r)/Math.max(1,e.lanes.length)),d=Math.max(76,(o-s-a)/Math.max(1,e.maxLevel+1)),l=Math.min(i.taskWidth??112,Math.max(58,.78*c)),u=Math.min(i.taskHeight??58,.64*d),h=i.socketRadius??5,p=Math.max(1,Math.round(i.gutterCount??3)),m=new Map;for(const t of e.nodes){const e=`${t.laneIndex}:${t.level}`,i=m.get(e)??[];i.push(t),m.set(e,i)}for(const e of m.values())e.sort((e,t)=>jd(e.id,t.id));const y=.86*d,f=e.nodes.map(e=>{const t=m.get(`${e.laneIndex}:${e.level}`)??[e],i=Math.max(0,t.findIndex(t=>t.id===e.id))-(t.length-1)/2,n=(o=t.length)>1?Math.max(22,Math.min(u,(y-4*(o-1))/o)):u;var o;return{taskID:e.id,lane:e.lane,laneIndex:e.laneIndex,level:e.level,x:r+c*(e.laneIndex+.5),y:s+d*(e.level+.5)+i*(n+4),width:l,height:n}}),g=new Map(f.map(e=>[e.taskID,e])),b=[],v=[];e.edges.forEach((t,i)=>{const n=g.get(t.sourceID),o=g.get(t.targetID);if(!n||!o)return;const r=e.incoming.get(t.targetID)??[],s=Math.min(.72*o.width,14*Math.max(1,r.length-1)),a=r.length>1?o.x-s/2+s*t.socketIndex/(r.length-1):o.x,c=o.y-o.height/2-h-2;b.push({id:t.socketID,edgeID:t.id,taskID:o.taskID,index:t.socketIndex,x:a,y:c,radius:h});const d={x:n.x,y:n.y+n.height/2+3},l=Math.min(c-10,d.y+.48*Math.max(18,c-d.y)+7*(i%p-(p-1)/2));var u;v.push({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,socketID:t.socketID,points:(u=[d,{x:d.x,y:l},{x:a,y:l},{x:a,y:c}],u.filter((e,t)=>{const i=u[t-1];return!i||i.x!==e.x||i.y!==e.y}))})});const x=new Map(b.map(e=>[e.id,e])),w=new Map(v.map(e=>[e.edgeID,e]));return{tasks:f,sockets:b,routes:v,taskByID:g,socketByID:x,routeByEdgeID:w}}function Wd(e,t,i="all"){const n=Array.from(new Set(t)).sort(jd),o=new Set,r=()=>n.every(e=>o.has(e));return{taskID:e,mode:i,incomingEdgeIDs:n,deliver:e=>n.includes(e)?(o.add(e),r()):r(),reset:(e=[])=>{o.clear();for(const t of e)n.includes(t)&&o.add(t)},isSatisfied:r,getSnapshot:()=>({taskID:e,mode:i,incomingEdgeIDs:[...n],deliveredEdgeIDs:[...o].sort(jd),satisfied:r()})}}function qd(e){return e instanceof Date?e.getTime():Number(e)}function zd(e,t){const i=qd("object"!=typeof t||t instanceof Date?t:t.currentTime),n=e.map((e,t)=>({event:e,index:t,time:qd(e.at)})).filter(e=>Number.isFinite(e.time)&&i>=e.time).sort((e,t)=>e.time-t.time||e.index-t.index),o=new Set,r=new Map,s=new Set,a=new Set;for(const{event:e}of n)"task-completed"===e.type?(o.add(e.taskID),r.delete(e.taskID)):"task-blocked"===e.type?r.set(e.taskID,e.reason):"task-unblocked"===e.type?r.delete(e.taskID):"dependency-delivered"===e.type?s.add(e.edgeID):"task-armed"===e.type&&a.add(e.taskID);return{currentTime:i,appliedEvents:n.map(e=>e.event),completedTaskIDs:o,blockedByTaskID:r,deliveredEdgeIDs:s,armedTaskIDs:a}}function Hd(e,t,i={}){const n=new Set(i.completedTaskIDs??[]),o=[...Dd(function(e,t){const i=new Map;for(const t of e)i.set(t.id,new Set);for(const e of t)i.has(e.source)||i.set(e.source,new Set),i.has(e.target)||i.set(e.target,new Set),i.get(e.source).add(e.target);return i}(e.nodes,e.edges.map(e=>({source:e.sourceID,target:e.targetID}))),t)].map(t=>e.byID.get(t)).filter(e=>null!=e).filter(e=>!(i.isComplete?i.isComplete(e):n.has(e.id)||"done"===e.status)).sort((e,t)=>e.index-t.index),r=Array.from(new Set(o.map(e=>e.lane)));return{blockerID:t,downstreamTaskCount:o.length,affectedLaneCount:r.length,downstreamTaskIDs:o.map(e=>e.id),affectedLanes:r}}$d.displayName="CrucibleChart";import{forwardRef as Ld,useCallback as Yd,useEffect as _d,useImperativeHandle as Xd,useMemo as Gd,useRef as Ud,useState as Vd}from"react";var Kd=[];function Qd(e,t=0){if(e instanceof Date)return e.getTime();const i=Number(e);return Number.isFinite(i)?i:t}function Jd(e){if(null==e.completionTime)return null;const t=Qd(e.completionTime,NaN);return Number.isFinite(t)?t:null}function Zd(e,t,i,n){const o=new Set;for(const r of e.nodes){const s=e.incoming.get(r.id)??[];(n.has(r.id)||!i.has(r.id)&&s.every(e=>t.has(e.id)))&&o.add(r.id)}return o}function el(e,t,i,n){const o=e.nodes.map(Jd).filter(e=>null!=e),r=o.length?Math.min(...o)-1:0,s="replay"!==t||n?i:r,a=new Set,c=new Map;for(const i of e.nodes){const e=Jd(i);(null!=e&&s>=e||"done"===i.status&&"replay"!==t)&&a.add(i.id),i.blockerReason&&!a.has(i.id)&&c.set(i.id,i.blockerReason)}const d=new Set;if("replay"!==t||n)for(const t of e.edges)a.has(t.sourceID)&&d.add(t.id);return{currentTime:s,playing:!1,completed:a,delivered:d,inFlight:new Set,armed:Zd(e,d,c,a),blockers:c,previewTaskID:null}}function tl(e){return{...e,completed:new Set(e.completed),delivered:new Set(e.delivered),inFlight:new Set(e.inFlight),armed:new Set(e.armed),blockers:new Map(e.blockers)}}function il(e){const t=e.datum;return"dependency-ball"===t?.kind&&Array.isArray(t.route)?t:null}function nl(e){const t=il(e.body);if(!t||2>t.route.length)return null;const i=function(e){let t=0;for(let i=1;e.length>i;i+=1)t+=Math.hypot(e[i].x-e[i-1].x,e[i].y-e[i-1].y);return t}(t.route),n=function(e,t){let i=1/0,n=0,o=0;for(let r=1;t.length>r;r+=1){const s=t[r-1],a=t[r],c=a.x-s.x,d=a.y-s.y,l=c*c+d*d,u=Math.sqrt(l);if(0>=u)continue;const h=Math.max(0,Math.min(1,((e.x-s.x)*c+(e.y-s.y)*d)/l)),p=Math.hypot(e.x-(s.x+c*h),e.y-(s.y+d*h));i>p&&(i=p,n=o+h*u),o+=u}return n}(e.body,t.route),o=function(e,t){if(2>e.length)return{point:e[0]??{x:0,y:0},tangent:{x:0,y:1}};let i=0;for(let n=1;e.length>n;n+=1){const o=e[n-1],r=e[n],s=r.x-o.x,a=r.y-o.y,c=Math.hypot(s,a);if(c>0){if(i+c>=t){const e=Math.max(0,Math.min(1,(t-i)/c));return{point:{x:o.x+s*e,y:o.y+a*e},tangent:{x:s/c,y:a/c}}}i+=c}}const n=e[e.length-2],o=e[e.length-1],r=o.x-n.x,s=o.y-n.y,a=Math.hypot(r,s)||1;return{point:o,tangent:{x:r/a,y:s/a}}}(t.route,Math.min(i,n+22));return{x:2.5*(78*o.tangent.x-e.body.vx)+8*(o.point.x-e.body.x),y:2.5*(78*o.tangent.y-e.body.vy)+8*(o.point.y-e.body.y)}}function ol(e,t,i){const n=t.points[0]??{x:0,y:0},o=t.points[1]??n,r=o.x-n.x,s=o.y-n.y,a=Math.hypot(r,s)||1;return{id:"dependency-ball:"+e.id,x:n.x,y:n.y,vx:r/a*42,vy:s/a*42,mass:.7,restitution:.02,friction:.12,bodyCollisions:!1,shape:{type:"circle",radius:5},datum:{kind:"dependency-ball",edgeID:e.id,sourceID:e.sourceID,targetID:e.targetID,route:t.points,...i?{sourceDatum:i}:{}}}}import{jsx as rl,jsxs as sl}from"react/jsx-runtime";function al({machine:e,layout:t,runtime:i,downstreamSet:n,selectedSet:o,width:r,height:s,seed:a,reduced:c,onSelectTask:d}){const l=t.tasks.length?Math.min(...t.tasks.map(e=>e.y-e.height/2)):60,u=Math.max(20,l-12),h=Math.max(26,l-6);return sl("svg",{"aria-hidden":"true",width:r,height:s,viewBox:`0 0 ${r} ${s}`,style:{position:"absolute",inset:0,overflow:"visible",pointerEvents:"none"},children:[rl("defs",{children:rl("filter",{id:"chain-shadow-"+a,x:"-20%",y:"-20%",width:"140%",height:"150%",children:rl("feDropShadow",{dx:"0",dy:"2",stdDeviation:"2",floodOpacity:"0.2"})})}),e.lanes.map((e,i)=>{const n=t.tasks.filter(e=>e.laneIndex===i),o=n[0]?.x??0;return sl("g",{children:[rl("line",{x1:o,x2:o,y1:h,y2:s-24,stroke:"var(--semiotic-grid, #d7dde0)",strokeWidth:1,strokeDasharray:"3 7"}),rl("text",{x:o,y:u,textAnchor:"middle",fontSize:12,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e})]},e)}),t.routes.map(e=>{const t=i.delivered.has(e.edgeID),o=i.inFlight.has(e.edgeID),r=n.has(e.targetID)||n.has(e.sourceID),s=e.points.map(e=>`${e.x},${e.y}`).join(" ");return rl("polyline",{points:s,fill:"none",stroke:r?"var(--semiotic-selection-color, #e08a1e)":t?"var(--semiotic-success, #2b8a66)":"var(--semiotic-grid, #aeb8bd)",strokeWidth:r?4:o?3:2,strokeOpacity:t||o||r?.95:.48,strokeLinecap:"round",strokeLinejoin:"round"},e.edgeID)}),t.sockets.map(e=>{const t=i.delivered.has(e.edgeID);return sl("g",{children:[rl("circle",{cx:e.x,cy:e.y,r:e.radius+2,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.5}),t&&rl("circle",{cx:e.x,cy:e.y,r:e.radius-.5,fill:"var(--semiotic-success, #2b8a66)"})]},e.id)}),e.nodes.map(e=>{const r=t.taskByID.get(e.id);if(!r)return null;const s=i.completed.has(e.id),l=i.blockers.has(e.id),u=i.previewTaskID===e.id,h=o.has(e.id)||u,p=n.has(e.id),m=function(e,t){return t.completed.has(e.id)?"var(--semiotic-success, #2b8a66)":t.blockers.has(e.id)?"var(--semiotic-error, #c64035)":"in-progress"===e.status?"var(--semiotic-warning, #d18a22)":t.armed.has(e.id)?"var(--semiotic-primary, #2474a6)":"var(--semiotic-text-secondary, #75818a)"}(e,i),y=r.x-r.width/2,f=r.y-r.height/2,g=Math.max(2,r.height*e.progress);return sl("g",{children:[sl("g",{style:{transform:`rotate(${s?76:0}deg)`,transformBox:"fill-box",transformOrigin:"50% 100%",transition:c?"none":"transform 520ms cubic-bezier(.2,.8,.25,1)",filter:"url(#chain-shadow-"+a+")"},children:[rl("rect",{x:y,y:f,width:r.width,height:r.height,rx:e.milestone?12:4,fill:"var(--semiotic-bg, #fff)",stroke:h||p?"var(--semiotic-selection-color, #e08a1e)":m,strokeWidth:h?4:p?3:2}),rl("rect",{x:y+3,y:f+r.height-g+1,width:r.width-6,height:Math.max(0,g-4),rx:2,fill:m,opacity:s?.86:.46})]}),l&&sl("g",{opacity:u?.28:1,children:[rl("line",{x1:y-8,x2:y+14,y1:r.y+9,y2:r.y-9,stroke:"var(--semiotic-error, #c64035)",strokeWidth:7,strokeLinecap:"round"}),rl("circle",{cx:y-8,cy:r.y+9,r:3,fill:"var(--semiotic-error, #c64035)"})]}),sl("g",{onPointerDown:()=>d(e.id),style:{cursor:"pointer",pointerEvents:"auto"},children:[rl("rect",{x:y,y:f,width:r.width,height:r.height,fill:"transparent"}),rl("text",{x:r.x,y:r.y-4,textAnchor:"middle",fontSize:10.5,fontWeight:700,fill:"var(--semiotic-text, #243039)",children:e.label.length>24?e.label.slice(0,22)+"…":e.label}),sl("text",{x:r.x,y:r.y+12,textAnchor:"middle",fontSize:9.5,fill:"var(--semiotic-text-secondary, #5f6b72)",children:[Math.round(100*e.progress),"% · ",s?"done":l?"blocked":i.armed.has(e.id)?"ready":"waiting"]})]})]},e.id)})]})}import{jsx as cl,jsxs as dl}from"react/jsx-runtime";var ll={border:0,clip:"rect(0 0 0 0)",clipPath:"inset(50%)",height:1,margin:-1,overflow:"hidden",padding:0,position:"absolute",whiteSpace:"nowrap",width:1};function ul({blockerSummary:e,machine:t,runtime:i}){return dl("table",{style:ll,children:[cl("caption",{children:e}),cl("thead",{children:dl("tr",{children:[cl("th",{children:"Task"}),cl("th",{children:"Lane"}),cl("th",{children:"Progress"}),cl("th",{children:"State"}),cl("th",{children:"Waiting on"}),cl("th",{children:"Downstream reach"})]})}),cl("tbody",{children:t.nodes.map(e=>{const n=Hd(t,e.id,{completedTaskIDs:i.completed}),o=i.completed.has(e.id)?"Completed":i.blockers.has(e.id)?"Blocked":i.armed.has(e.id)?"Armed":"Waiting",r=i.blockers.get(e.id)??(e.dependencyIDs.filter(e=>!i.completed.has(e)).join(", ")||"None");return dl("tr",{children:[cl("th",{scope:"row",children:e.label}),cl("td",{children:e.lane}),dl("td",{children:[Math.round(100*e.progress),"%"]}),cl("td",{children:o}),cl("td",{children:r}),dl("td",{children:[n.downstreamTaskCount," tasks /"," ",n.affectedLaneCount," lanes"]})]},e.id)})})]})}import{jsx as hl,jsxs as pl}from"react/jsx-runtime";var ml=Ld(function(e,t){const{data:i,taskIDAccessor:n,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:c,endAccessor:d,progressAccessor:l,statusAccessor:u,completionTimeAccessor:h,blockerAccessor:p,milestoneAccessor:m,mode:y="snapshot",insight:f="blocker-amplification",currentTime:b,controls:v=!1,selectedTaskIDs:x,onSelectionChange:w,onObservation:k,reducedMotion:I,seed:M=31,width:S=920,height:A=620,responsiveWidth:C,responsiveHeight:R,title:P="Dependency chain reaction",description:$,className:D,accessibleTable:B=!0,enableHover:j=!0}=e,T=er(Gd(()=>[S,A],[A,S]),C,R),[O,E]=T.size,N=Ud(null),[F,W]=Vd([]),q=x?Array.from(x):F,z=Gd(()=>new Set(q),[q]),H=Qd(b,1/0),L="settle"===I,Y=Gd(()=>Nd({data:i,taskIDAccessor:n,labelAccessor:o,laneAccessor:r,dependencyAccessor:s,startAccessor:c,endAccessor:d,progressAccessor:l,statusAccessor:u,completionTimeAccessor:h,blockerAccessor:p,milestoneAccessor:m}),[i,n,o,r,s,c,d,l,u,h,p,m]),_=Gd(()=>Fd(Y,{width:O,height:E}),[Y,O,E]),[X,G]=Vd(()=>el(Y,y,H,L)),U=Ud(X),V=Yd(e=>{U.current=e,G(e)},[]),K=Yd(e=>k?.(e),[k]);_d(()=>{const e=el(Y,y,H,L);N.current?.clear(),U.current=e,G(e)},[_,Y,y,H,L]);const Q=Yd(e=>{const t=z.has(e)?q.filter(t=>t!==e):[e];x||W(t),w?.(t)},[x,w,z,q]),J=Yd(e=>{if(L)return;const t=tl(U.current),i=[];for(const n of Y.outgoing.get(e)??[]){if(t.delivered.has(n.id)||t.inFlight.has(n.id))continue;const e=_.routeByEdgeID.get(n.id);e&&(t.inFlight.add(n.id),i.push(ol(n,e,Y.byID.get(n.sourceID)?.datum)))}i.length&&(V(t),N.current?.pushMany(i,{pacing:{ratePerSec:8}}))},[V,_,Y,L]),Z=Yd((e,t)=>{const i=Y.byID.get(e),n=U.current;if(!i||n.completed.has(e))return;const o=tl(n);o.completed.add(e),o.blockers.delete(e),o.armed.add(e),null!=t&&(o.currentTime=t),V(o),K({type:"task-completed",taskID:e,datum:i.datum}),J(e)},[V,K,Y,J]),ee=Yd(e=>{const t=tl(U.current),i=[],n=[];for(const n of e){if(t.delivered.has(n))continue;const e=Y.edges.find(e=>e.id===n);e&&(t.delivered.add(n),t.inFlight.delete(n),i.push(e))}for(const e of i){const i=Y.byID.get(e.targetID);!i||t.blockers.has(i.id)||t.armed.has(i.id)||(Y.incoming.get(i.id)??[]).every(e=>t.delivered.has(e.id))&&(t.armed.add(i.id),n.push(i.id))}if(i.length){V(t);for(const e of i)K({type:"dependency-delivered",sourceID:e.sourceID,targetID:e.targetID});for(const e of n)K({type:"task-armed",taskID:e})}},[V,K,Y]),te=Yd((e,t)=>{const i=[],n=[];for(const e of t.readBodies()){const t=il(e);if(!t||U.current.delivered.has(t.edgeID))continue;const o=t.route[t.route.length-1];o&&9>=Math.hypot(e.x-o.x,e.y-o.y)&&(i.push(t.edgeID),n.push(e.id))}n.length&&t.remove(n),i.length&&ee(i)},[ee]),ie=Yd(()=>{const e=tl(U.current);for(const t of Y.edges)e.completed.has(t.sourceID)&&e.delivered.add(t.id);e.inFlight.clear(),e.armed=Zd(Y,e.delivered,e.blockers,e.completed),e.playing=!1,N.current?.settle(),V(e),K({type:"machine-settled"})},[V,K,Y]),ne=Yd(()=>{const e=tl(U.current);e.playing=!1,V(e)},[V]),oe=Yd(()=>{const e=U.current,t=Y.nodes.map(e=>({node:e,time:Jd(e)})).filter(t=>null!=t.time&&t.time>e.currentTime&&!e.completed.has(t.node.id)).sort((e,t)=>e.time-t.time||e.node.index-t.node.index)[0];if(t)return void Z(t.node.id,t.time);ne();const i=[...e.blockers.keys()].map(t=>Hd(Y,t,{completedTaskIDs:e.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);i[0]&&K({type:"machine-stalled",blockerID:i[0].blockerID,downstreamTaskCount:i[0].downstreamTaskCount,affectedLaneCount:i[0].affectedLaneCount})},[K,Y,ne,Z]),re=Yd(()=>{if(L)return void ie();const e=tl(U.current);e.playing=!0,V(e)},[V,L,ie]);_d(()=>{if(!X.playing||"replay"!==y||L)return;const e=window.setInterval(oe,760);return()=>window.clearInterval(e)},[y,L,X.playing,oe]);const se=Yd(()=>{N.current?.clear(),V(el(Y,y,H,L))},[V,Y,y,H,L]),ae=Yd(e=>{if(!Y.byID.has(e))return;const t=tl(U.current);t.previewTaskID=e,V(t);const i=Hd(Y,e,{completedTaskIDs:t.completed});K({type:"blocker-previewed",blockerID:e,downstreamTaskIDs:i.downstreamTaskIDs})},[V,K,Y]),ce=Yd(()=>{const e=tl(U.current);e.previewTaskID=null,V(e)},[V]),de=Yd((e,t)=>{if(!Y.byID.has(e))return;const i=tl(U.current);i.blockers.set(e,t),i.armed.delete(e),V(i)},[V,Y]),le=Yd(e=>{if(!Y.byID.has(e))return;const t=tl(U.current);t.blockers.delete(e),(Y.incoming.get(e)??[]).every(e=>t.delivered.has(e.id))&&t.armed.add(e),V(t)},[V,Y]),ue=Yd(e=>Hd(Y,e,{completedTaskIDs:U.current.completed}),[Y]),he=Yd(()=>{const e=U.current;return{currentTime:e.currentTime,playing:e.playing,previewTaskID:e.previewTaskID,selectedTaskIDs:[...q],tasks:Y.nodes.map(t=>({taskID:t.id,completed:e.completed.has(t.id),armed:e.armed.has(t.id),blocked:e.blockers.has(t.id),blockerReason:e.blockers.get(t.id)})),dependencies:Y.edges.map(t=>({edgeID:t.id,sourceID:t.sourceID,targetID:t.targetID,state:e.delivered.has(t.id)?"delivered":e.inFlight.has(t.id)?"in-flight":"waiting"}))}},[Y,q]);Xd(t,()=>({play:re,pause:ne,step:oe,reset:se,settle:ie,previewResolve:ae,clearPreview:ce,completeTask:Z,blockTask:de,unblockTask:le,getAmplification:ue,getMachineState:he}),[de,ce,ue,he,ne,Z,re,ae,se,ie,oe,le]);const pe=X.previewTaskID??q[0]??null,me=pe?Hd(Y,pe,{completedTaskIDs:X.completed}):null,ye=Gd(()=>new Set(me?.downstreamTaskIDs??[]),[me?.downstreamTaskIDs]),fe=Gd(()=>function(e,t,i){return e.nodes.flatMap(n=>{const o=t.taskByID.get(n.id);if(!o)return[];const r=e.incoming.get(n.id)??[],s=r.filter(e=>i.delivered.has(e.id)).length,a=i.blockers.get(n.id),c=i.completed.has(n.id)?"completed":a?"blocked: "+a:i.armed.has(n.id)?"armed":"waiting";return[{id:n.id,label:`${n.label}, ${n.lane}, ${Math.round(100*n.progress)}%, ${c}`,description:`${s} of ${r.length} prerequisites delivered.`,datum:n.datum,x:o.x,y:o.y,width:o.width,height:o.height,shape:"rect",group:n.lane}]})}(Y,_,X),[_,Y,X]),ge=Gd(()=>hl(al,{machine:Y,layout:_,runtime:X,downstreamSet:ye,selectedSet:z,width:O,height:E,seed:M,reduced:L,onSelectTask:Q}),[ye,E,_,Y,L,X,M,Q,z,O]),be=Gd(()=>{const e=[...X.blockers.keys()].map(e=>Hd(Y,e,{completedTaskIDs:X.completed})).sort((e,t)=>t.affectedLaneCount-e.affectedLaneCount||t.downstreamTaskCount-e.downstreamTaskCount);return e.length?e.map(e=>`${Y.byID.get(e.blockerID)?.label??e.blockerID} affects ${e.downstreamTaskCount} unfinished tasks across ${e.affectedLaneCount} lanes.`).join(" "):"No explicit blockers are active."},[Y,X.blockers,X.completed]),ve=Gd(()=>[{id:"chain-left",shape:{type:"segment",x1:2,y1:0,x2:2,y2:E,thickness:4}},{id:"chain-right",shape:{type:"segment",x1:O-2,y1:0,x2:O-2,y2:E,thickness:4}},{id:"chain-top",shape:{type:"segment",x1:0,y1:2,x2:O,y2:2,thickness:4}},{id:"chain-bottom",shape:{type:"segment",x1:0,y1:E-2,x2:O,y2:E-2,thickness:4}}],[E,O]),xe=!0===v?["play","pause","step","reset","settle"]:v||[],we=or(e.tooltip,void 0,{unwrapSourceDatum:!0}),ke=Yd(e=>{const t=e.data,i=(t.sourceID??"")+"",n=(t.targetID??"")+"",o=Y.byID.get(i),r=Y.byID.get(n);return pl(g,{children:[pl("div",{style:{fontWeight:700},children:[o?.label??i," → ",r?.label??n]}),hl("div",{children:"Dependency in flight"}),r?.lane?pl("div",{children:["Target lane: ",r.lane]}):null]})},[Y]);return pl("div",Y.valid?{className:D,style:{width:C?"100%":O,maxWidth:"100%",position:"relative"},children:[xe.length>0&&hl("div",{"aria-label":"Chain reaction replay controls",style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8},children:xe.map(e=>hl("button",{type:"button",onClick:"play"===e?re:"pause"===e?ne:"step"===e?oe:"reset"===e?se:ie,"aria-pressed":"play"===e?X.playing:void 0,children:e[0].toUpperCase()+e.slice(1)},e))}),hl("div",{ref:T.containerRef,"data-semiotic-physics-responsive-host":"true",style:{position:"relative",width:C?"100%":O,height:R?"100%":E},children:hl(Bn,{ref:N,size:[O,E],responsiveWidth:!1,responsiveHeight:!1,maxDevicePixelRatio:e.maxDevicePixelRatio,title:P,description:$??"Tasks are arranged by workstream and dependency depth. Balls represent satisfied prerequisites; task completion remains an explicit data event.",summary:`${be}${me&&"blocker-amplification"===f?` Selected task reaches ${me.downstreamTaskCount} unfinished tasks across ${me.affectedLaneCount} lanes.`:""}`,accessibleTable:!1,enableHover:we.enableHover??j,initialSpawns:Kd,bodyForces:nl,bodyStyle:{fill:"var(--semiotic-primary, #f0a329)",stroke:"var(--semiotic-text, #243039)",strokeWidth:1.25},bodySemanticItems:!1,semanticItems:fe,onSemanticItemActivate:e=>e.id&&Q(e.id),foregroundGraphics:()=>ge,paused:L,continuous:X.inFlight.size>0,onTick:te,tooltipContent:!1===e.tooltip?void 0:we.tooltipContent??ke,config:{bodyLimit:Math.max(16,Y.edges.length+4),colliders:ve,settleStepLimit:2200,kernel:{seed:M,gravity:{x:0,y:7},fixedDt:1/60,cellSize:28,collisionIterations:2,velocityDamping:.992,restitution:.02,friction:.12,maxVelocity:150,sleepSpeed:1.1,sleepAfter:.8},observation:{chartType:"ChainReactionChart"}}},`${O}x${E}`)}),B&&hl(a,{accessibleTable:B,children:hl(ul,{blockerSummary:be,machine:Y,runtime:X})})]}:{className:D,role:"alert",style:{width:O,maxWidth:"100%"},children:[hl("strong",{children:"ChainReactionChart could not compile this dependency graph."}),hl("ul",{children:Y.diagnostics.map((e,t)=>hl("li",{children:e.message},`${e.code}-${t}`))})]})});ml.displayName="ChainReactionChart";export{se as bodiesToAnnotationAnchors,ae as buildPhysicsAnnotationContext,ce as normalizePhysicsAnnotations,pe as PhysicsSVGOverlay,Oe as valueAtPath,Ne as matchesPhysicsBodyFilter,qe as BuiltInPhysicsEngineAdapter,ze as createDefaultPhysicsEngineAdapter,Qe as PhysicsSedimentAccumulator,Je as sedimentHeightfield,et as evaluatePhysicsBodyBudget,yt as collidersFromPlotBounds,ft as collidersFromXScaleBins,jt as PhysicsPipelineStore,Nt as createCapacityQueueController,Wt as composePhysicsControllers,qt as createPortalController,Dn as StreamPhysicsFrame,Bn as StreamPhysicsFrame_default,Xn as buildGaltonBoardPhysics,Vn as buildEventDropPhysics,Qn as buildPhysicsPile,Zn as buildCollisionSwarmPhysics,so as buildPhysicalFlowPhysics,lo as aggregateRegionCounts,uo as regionCountsToProjectionRows,ho as groupCompletionRows,yo as processStageLayout,go as processStageRegions,bo as membraneRegion,vo as chargeGateRegion,xo as routeSurfaceRegion,wo as pressureFieldRegion,ko as capacitatedRegion,Io as portalRegion,Mo as absorbRegion,So as forceFieldRegion,Ao as bodyGroupSpec,Co as processLaneWalls,Po as buildProcessFlowPhysics,ur as GaltonBoardChart,gr as EventDropChart,Ir as UnitPileChart,Mr as PhysicsPileChart,jr as PhysicsCustomChart,Wr as CollisionSwarmChart,qr as physicsProcessBoundaryColliders,zr as physicsProcessRegionSemanticItem,Hr as physicsProcessStageSemanticItems,Lr as physicsProcessGroupSemanticItems,ys as defaultViability,Gr as planGauntletPropertyWork,Ur as replaceGauntletNegative,Kr as applyGauntletEffect,Qr as eventLogItem,Jr as recordGauntletEvent,Hs as GauntletChart,Ls as GuantletChart,sa as PacketFlowChart,aa as PhysicalFlowChart,fa as processChrome,Aa as ProcessFlowChart,Da as cloneCrucibleState,Fa as resolveCrucibleSelector,Ga as applyCrucibleEvent,Ua as buildCrucibleProjection,Va as crucibleProjectionRows,Ka as evaluateCrucibleConservation,Qa as buildCrucibleEvidence,Ja as DEFAULT_CRUCIBLE_WIDTH,Za as DEFAULT_CRUCIBLE_HEIGHT,ec as DEFAULT_CRUCIBLE_SIZE,tc as DEFAULT_CRUCIBLE_OUTLETS,lc as createInitialCrucibleState,hc as buildCrucibleLayout,mc as crucibleBoundaryColliders,gc as buildCruciblePhysicsConfig,bc as crucibleComponentBodyId,vc as crucibleProductBodyId,xc as crucibleBondId,Ic as buildCrucibleInitialSpawns,Cc as buildCrucibleStateSpawns,Rc as buildCrucibleTerminalSpawns,$c as crucibleSemanticKey,Dc as resolveCrucibleTime,Bc as resolveCrucibleSnapshotAt,jc as replayCruciblePlan,Tc as compileCruciblePlan,Nc as buildCrucibleProductEvents,$d as CrucibleChart,Nd as compileDependencyMachine,Fd as routeDependencyTracks,Wd as createLogicalJoin,zd as replayStateTransitions,Hd as calculateBlockerAmplification,ml as ChainReactionChart};