semiotic 3.8.6 → 3.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +33 -7
- package/README.md +82 -55
- package/ai/behaviorContracts.cjs +86 -1
- package/ai/componentMetadata.cjs +4 -9
- package/ai/dist/mcp-server.js +97 -10
- package/ai/examples.md +154 -7
- package/ai/schema.json +1611 -145
- package/ai/surface-manifest.json +12 -10
- package/ai/system-prompt.md +9 -3
- package/dist/{chunk-chartContainerDataAudit-FEOD5GTQ.module.min.js → chunk-chartContainerDataAudit-JDSVSKGM.module.min.js} +1 -1
- package/dist/chunk-chunk-2YAZHXL4.module.min.js +2 -0
- package/dist/{chunk-chunk-G7WFWHAD.module.min.js → chunk-chunk-4ITOQRXM.module.min.js} +1 -1
- package/dist/chunk-chunk-5SD6BHVW.module.min.js +2 -0
- package/dist/chunk-chunk-6V5VQVCT.module.min.js +2 -0
- package/dist/chunk-chunk-7TTBHSAG.module.min.js +2 -0
- package/dist/chunk-chunk-7ZDJSYKI.module.min.js +2 -0
- package/dist/chunk-chunk-BGHPD3RA.module.min.js +1 -0
- package/dist/chunk-chunk-BMRZ2SPU.module.min.js +2 -0
- package/dist/chunk-chunk-BNGBEY7N.module.min.js +2 -0
- package/dist/chunk-chunk-C7APLVQD.module.min.js +2 -0
- package/dist/chunk-chunk-DGWFBOGB.module.min.js +1 -0
- package/dist/{chunk-chunk-Q2BS46W2.module.min.js → chunk-chunk-DIVE2DRA.module.min.js} +1 -1
- package/dist/chunk-chunk-FBUNUIPV.module.min.js +2 -0
- package/dist/chunk-chunk-FQPKOAIH.module.min.js +2 -0
- package/dist/chunk-chunk-FRO4TRXK.module.min.js +2 -0
- package/dist/chunk-chunk-G7QVPZUD.module.min.js +2 -0
- package/dist/chunk-chunk-GBPYV4FP.module.min.js +2 -0
- package/dist/chunk-chunk-GU2EJIDJ.module.min.js +2 -0
- package/dist/chunk-chunk-J5QD4RAM.module.min.js +2 -0
- package/dist/{chunk-chunk-RA7JCG7D.module.min.js → chunk-chunk-JWXLNZSM.module.min.js} +1 -1
- package/dist/chunk-chunk-KXAFCCDB.module.min.js +2 -0
- package/dist/chunk-chunk-LG7YKJAK.module.min.js +2 -0
- package/dist/{chunk-chunk-XP3OHHFX.module.min.js → chunk-chunk-LVHDZAT3.module.min.js} +1 -1
- package/dist/chunk-chunk-LWITSR2O.module.min.js +2 -0
- package/dist/{chunk-chunk-SMVD3EQJ.module.min.js → chunk-chunk-MX35T6RX.module.min.js} +1 -1
- package/dist/chunk-chunk-NH4MEAKP.module.min.js +2 -0
- package/dist/chunk-chunk-NJETWX42.module.min.js +2 -0
- package/dist/chunk-chunk-NW25WGLS.module.min.js +2 -0
- package/dist/{chunk-chunk-GFTVACTO.module.min.js → chunk-chunk-OI7R7EJB.module.min.js} +1 -1
- package/dist/{chunk-chunk-OM6NWS4H.module.min.js → chunk-chunk-ONMLEXHR.module.min.js} +1 -1
- package/dist/chunk-chunk-OY66GCE6.module.min.js +1 -0
- package/dist/chunk-chunk-PZFT457G.module.min.js +1 -0
- package/dist/chunk-chunk-Q3WW6JGR.module.min.js +1 -0
- package/dist/chunk-chunk-Q6XKQTOQ.module.min.js +1 -0
- package/dist/chunk-chunk-RJRM2E6P.module.min.js +1 -0
- package/dist/chunk-chunk-RPL7WYXI.module.min.js +1 -0
- package/dist/chunk-chunk-SV4XAZ3Q.module.min.js +1 -0
- package/dist/chunk-chunk-TSCFL235.module.min.js +1 -0
- package/dist/chunk-chunk-UOQRPGPK.module.min.js +2 -0
- package/dist/chunk-chunk-V3OAKG32.module.min.js +1 -0
- package/dist/chunk-chunk-WLOIUMWG.module.min.js +2 -0
- package/dist/chunk-chunk-XEGXX4F7.module.min.js +1 -0
- package/dist/chunk-chunk-XFRBLXYM.module.min.js +1 -0
- package/dist/chunk-chunk-Z2AJERX5.module.min.js +2 -0
- package/dist/chunk-chunk-ZXYDYAB7.module.min.js +2 -0
- package/dist/components/ai/SemioticVACPBridge.d.ts +22 -0
- package/dist/components/ai/chartCapabilities.d.ts +4 -3
- package/dist/components/ai/conversationArc.d.ts +2 -176
- package/dist/components/ai/conversationArcTypes.d.ts +202 -0
- package/dist/components/ai/readerGrounding.d.ts +12 -0
- package/dist/components/ai/vacpAdapter.d.ts +13 -0
- package/dist/components/ai/vacpAdapterActions.d.ts +2 -0
- package/dist/components/ai/vacpAdapterModel.d.ts +7 -0
- package/dist/components/ai/vacpAdapterRuntime.d.ts +26 -0
- package/dist/components/ai/vacpAdapterState.d.ts +3 -0
- package/dist/components/ai/vacpAdapterTypes.d.ts +169 -0
- package/dist/components/ai/vacpTypes.d.ts +160 -0
- package/dist/components/charts/index.d.ts +4 -4
- package/dist/components/charts/physics/ChainReactionChart.capability.d.ts +9 -0
- package/dist/components/charts/physics/ChainReactionChart.d.ts +29 -0
- package/dist/components/charts/physics/CollisionSwarmChart.d.ts +1 -1
- package/dist/components/charts/physics/EventDropChart.d.ts +7 -2
- package/dist/components/charts/physics/GaltonBoardChart.d.ts +1 -1
- package/dist/components/charts/physics/{PhysicsPileChart.capability.d.ts → PacketFlowChart.capability.d.ts} +1 -1
- package/dist/components/charts/physics/{PhysicalFlowChart.d.ts → PacketFlowChart.d.ts} +22 -6
- package/dist/components/charts/physics/PhysicsCustomChart.d.ts +1 -1
- package/dist/components/charts/physics/ProcessFlowChart.d.ts +7 -4
- package/dist/components/charts/physics/{PhysicalFlowChart.capability.d.ts → UnitPileChart.capability.d.ts} +1 -1
- package/dist/components/charts/physics/{PhysicsPileChart.d.ts → UnitPileChart.d.ts} +19 -6
- package/dist/components/charts/physics/crucibleChartProps.d.ts +1 -1
- package/dist/components/charts/physics/crucibleChartUtils.d.ts +9 -0
- package/dist/components/charts/physics/gauntletChartProps.d.ts +6 -1
- package/dist/components/charts/physics/gauntletTerminal.d.ts +61 -0
- package/dist/components/charts/physics/packetFlowSemantics.d.ts +6 -0
- package/dist/components/charts/physics/physicsHocUtils.d.ts +45 -2
- package/dist/components/charts/shared/auditAccessibilityStyles.d.ts +9 -0
- package/dist/components/charts/shared/knownChartComponents.d.ts +1 -1
- package/dist/components/charts/shared/useChartLegend.d.ts +8 -1
- package/dist/components/charts/shared/useChartSetup.d.ts +7 -0
- package/dist/components/data/portability/capabilityBinding.d.ts +41 -0
- package/dist/components/data/portability/index.d.ts +2 -0
- package/dist/components/legendLayout.d.ts +56 -0
- package/dist/components/recipes/geographicDotGrid.d.ts +82 -0
- package/dist/components/recipes/geographicGrid.d.ts +100 -0
- package/dist/components/recipes/physics.d.ts +2 -0
- package/dist/components/recipes/physicsStageGeography.d.ts +137 -0
- package/dist/components/semiotic-ai.d.ts +4 -3
- package/dist/components/semiotic-experimental-vacp.d.ts +11 -0
- package/dist/components/semiotic-experimental.d.ts +6 -3
- package/dist/components/semiotic-geo.d.ts +4 -0
- package/dist/components/semiotic-physics.d.ts +9 -6
- package/dist/components/semiotic-recipes-core.d.ts +6 -1
- package/dist/components/server/renderEvidence.d.ts +1 -1
- package/dist/components/server/renderToStaticSVG.d.ts +2 -1
- package/dist/components/server/serverChartConfigHeatmap.d.ts +6 -0
- package/dist/components/server/serverChartConfigNetworkStyles.d.ts +12 -0
- package/dist/components/server/serverChartConfigShared.d.ts +16 -0
- package/dist/components/server/serverChartConfigs.d.ts +2 -2
- package/dist/components/server/serverChartConfigsPhysics.d.ts +2 -2
- package/dist/components/server/serverChartConfigsXY.d.ts +0 -1
- package/dist/components/server/staticLegend.d.ts +6 -0
- package/dist/components/server/staticSVGChrome.d.ts +10 -2
- package/dist/components/server/staticValue.d.ts +8 -0
- package/dist/components/stream/geoPipelineConfig.d.ts +10 -0
- package/dist/components/stream/legendRenderer.d.ts +8 -0
- package/dist/components/stream/physics/PhysicsEvidence.d.ts +37 -0
- package/dist/components/stream/physics/PhysicsPipelineStore.d.ts +9 -0
- package/dist/components/stream/physics/PhysicsSettledScene.d.ts +5 -0
- package/dist/components/stream/physics/physicsFramePipelineConfig.d.ts +19 -0
- package/dist/components/stream/physics/physicsPipelineSettle.d.ts +52 -0
- package/dist/components/stream/physics/physicsRegionRuntime.d.ts +23 -0
- package/dist/components/stream/types.d.ts +2 -0
- package/dist/components/types/legendTypes.d.ts +17 -1
- package/dist/controls.min.js +1 -1
- package/dist/controls.module.min.js +1 -1
- package/dist/geo.min.js +1 -1
- package/dist/geo.module.min.js +1 -1
- package/dist/network.min.js +1 -1
- package/dist/network.module.min.js +1 -1
- package/dist/ordinal.min.js +1 -1
- package/dist/ordinal.module.min.js +1 -1
- package/dist/physics.min.js +1 -1
- package/dist/physics.module.min.js +1 -1
- package/dist/physicsWorker.js +1 -1
- package/dist/realtime.min.js +1 -1
- package/dist/realtime.module.min.js +1 -1
- package/dist/semiotic-ai-core.min.js +1 -1
- package/dist/semiotic-ai-core.module.min.js +1 -1
- package/dist/semiotic-ai.d.ts +4 -3
- package/dist/semiotic-ai.min.js +1 -1
- package/dist/semiotic-ai.module.min.js +1 -1
- package/dist/semiotic-data.module.min.js +1 -1
- package/dist/semiotic-experimental-vacp.d.ts +11 -0
- package/dist/semiotic-experimental-vacp.min.js +1 -0
- package/dist/semiotic-experimental-vacp.module.min.js +1 -0
- package/dist/semiotic-experimental.d.ts +6 -3
- package/dist/semiotic-experimental.min.js +2 -1
- package/dist/semiotic-experimental.module.min.js +2 -1
- package/dist/semiotic-geo.d.ts +4 -0
- package/dist/semiotic-physics.d.ts +9 -6
- package/dist/semiotic-realtime-core.min.js +1 -1
- package/dist/semiotic-realtime-core.module.min.js +1 -1
- package/dist/semiotic-recipes-core.d.ts +6 -1
- package/dist/semiotic-recipes-core.min.js +1 -1
- package/dist/semiotic-recipes-core.module.min.js +1 -1
- package/dist/semiotic-recipes.min.js +1 -1
- package/dist/semiotic-recipes.module.min.js +1 -1
- package/dist/semiotic-server-edge.min.js +1 -1
- package/dist/semiotic-server-edge.module.min.js +1 -1
- package/dist/semiotic-server-node.min.js +1 -1
- package/dist/semiotic-server-node.module.min.js +1 -1
- package/dist/semiotic-utils-core.min.js +1 -1
- package/dist/semiotic-utils-core.module.min.js +1 -1
- package/dist/semiotic-utils.min.js +1 -1
- package/dist/semiotic-utils.module.min.js +1 -1
- package/dist/semiotic.min.js +1 -1
- package/dist/semiotic.module.min.js +1 -1
- package/dist/server.min.js +1 -1
- package/dist/server.module.min.js +1 -1
- package/dist/xy.min.js +1 -1
- package/dist/xy.module.min.js +1 -1
- package/package.json +18 -2
- package/spec/README.md +94 -2
- package/spec/bindings/README.md +14 -3
- package/spec/v0.1/examples/annotation-provenance-reviewed-revision.json +27 -0
- package/spec/v0.1/examples/annotation-provenance-watcher-threshold.json +21 -0
- package/spec/v0.1/examples/audience-profile-executive-review.json +24 -0
- package/spec/v0.1/examples/audience-profile-incident-operators.json +42 -0
- package/spec/v0.1/examples/chart-capability-bar-comparison.json +48 -0
- package/spec/v0.1/examples/chart-capability-service-flow.json +54 -0
- package/dist/chunk-chunk-2CHN2TA3.module.min.js +0 -1
- package/dist/chunk-chunk-3SHB24AG.module.min.js +0 -1
- package/dist/chunk-chunk-4MMOOYTX.module.min.js +0 -2
- package/dist/chunk-chunk-5RKXZQ2P.module.min.js +0 -1
- package/dist/chunk-chunk-75OTQSXS.module.min.js +0 -1
- package/dist/chunk-chunk-7ALTGHK6.module.min.js +0 -1
- package/dist/chunk-chunk-A5GRQUOF.module.min.js +0 -1
- package/dist/chunk-chunk-AAF5LZAU.module.min.js +0 -2
- package/dist/chunk-chunk-ARZGA4LJ.module.min.js +0 -2
- package/dist/chunk-chunk-C4YA6TDR.module.min.js +0 -1
- package/dist/chunk-chunk-CAFLML4L.module.min.js +0 -2
- package/dist/chunk-chunk-CO5KQMGH.module.min.js +0 -1
- package/dist/chunk-chunk-FHBN7OEB.module.min.js +0 -2
- package/dist/chunk-chunk-GMQ5AYTD.module.min.js +0 -1
- package/dist/chunk-chunk-IP2UE74X.module.min.js +0 -1
- package/dist/chunk-chunk-ITDWLZXV.module.min.js +0 -2
- package/dist/chunk-chunk-JCG72SGW.module.min.js +0 -2
- package/dist/chunk-chunk-LPSPATPC.module.min.js +0 -1
- package/dist/chunk-chunk-PX5YQGDP.module.min.js +0 -2
- package/dist/chunk-chunk-QSQVBIJA.module.min.js +0 -1
- package/dist/chunk-chunk-RCF52Z42.module.min.js +0 -2
- package/dist/chunk-chunk-RNUHEXZA.module.min.js +0 -2
- package/dist/chunk-chunk-ROZWKEUG.module.min.js +0 -1
- package/dist/chunk-chunk-T2FKJD4O.module.min.js +0 -2
- package/dist/chunk-chunk-UDREYOLV.module.min.js +0 -1
- package/dist/chunk-chunk-VOWE3SAP.module.min.js +0 -2
- package/dist/chunk-chunk-VQPNBUSW.module.min.js +0 -2
- package/dist/chunk-chunk-WAWCIHFJ.module.min.js +0 -1
- package/dist/chunk-chunk-WYARAXHR.module.min.js +0 -2
- package/dist/chunk-chunk-XV3KGYTR.module.min.js +0 -2
- package/dist/chunk-chunk-YC2IVEPX.module.min.js +0 -1
- package/dist/chunk-chunk-ZOAQDIJO.module.min.js +0 -1
- package/dist/chunk-chunk-ZXIXAPRE.module.min.js +0 -2
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{filterAnnotationsByStatus as e,resolveAccessor as t,resolveRawAccessor as n}from"./chunk-chunk-XFRBLXYM.module.min.js";var r=new Set(["LineChart","AreaChart","StackedAreaChart","DifferenceChart","Scatterplot","BubbleChart","ConnectedScatterplot","QuadrantChart","MultiAxisLineChart","MinimapChart"]),o=new Set(["BarChart","StackedBarChart","GroupedBarChart","DotPlot"]),a=new Set(["PieChart","DonutChart","FunnelChart"]),i=new Set(["Histogram","BoxPlot","ViolinPlot","RidgelinePlot","SwarmPlot"]);function s(e,t){return o.has(e)||a.has(e)||"SwimlaneChart"===e||"GaugeChart"===e?{measure:t.valueAccessor,measureFallback:"value",dimension:t.categoryAccessor??t.stepAccessor,dimensionFallback:"category"}:{measure:t.yAccessor??t.valueAccessor,measureFallback:"y",dimension:t.xAccessor,dimensionFallback:"x"}}function l(e){for(const t of["lineBy","areaBy","stackBy","groupBy","colorBy"]){const n=e[t];if("string"==typeof n&&n)return n}}function c(e,t){return null==e?"—":e instanceof Date?e.toISOString().slice(0,10):"number"==typeof e?t(e):e+""}function u(e,t=new Set){if(null===e)return!0;const n=typeof e;if("string"===n||"boolean"===n)return!0;if("number"===n)return Number.isFinite(e);if("object"!==n)return!1;if(t.has(e))return!1;t.add(e);const r=Array.isArray(e)?e.every(e=>u(e,t)):Object.entries(e).every(([,e])=>u(e,t));return t.delete(e),r}var h=Symbol.for("semiotic.chartRecipeRegistry");function d(e){return function(){const e=globalThis;return e[h]||(e[h]={recipes:new Map,capabilities:new Map,layouts:new Map}),e[h]}().recipes.get(e)}function p(e){return"string"==typeof e?d(e):e&&"object"==typeof e&&"string"==typeof e.id?e:void 0}function f(e){return"string"==typeof e?e:e.id??e.name}function m(e){return e.layoutConfig&&"object"==typeof e.layoutConfig?e.layoutConfig:{}}function g(e){return Array.isArray(e.data)?e.data:Array.isArray(e.nodes)?e.nodes:Array.isArray(e.points)?e.points:Array.isArray(e.areas)?e.areas:[]}function y(e,t,n){return n??p(t.recipe)??p(t.recipeId)??d(e)}function b(e,t,n=[]){const r=e.accessor?t[e.accessor]:void 0;if("string"==typeof r&&r)return r;if(e.field)return e.field;const o=n.find(e=>e&&"object"==typeof e);if(!o)return;const a=Object.entries(o).filter(([e,t])=>!e.startsWith("_")&&null!=t);return"quantitative"===e.semanticType?a.find(([,e])=>"number"==typeof e)?.[0]:"identifier"===e.semanticType?["id","key","name"].find(e=>e in o):a.find(([,e])=>"string"==typeof e)?.[0]}function $(e,t){return e.dataRoles.find(e=>e.role===t)}function v(e,t){return e.dataRoles.find(e=>t.includes(e.semanticType))}function C(e,t,n,r,o,a={}){const i={...a};if(t)for(const[e,n]of Object.entries(t))i[e]=n;for(const e of n.dataRoles){const n=b(e,r,o),a=t&&n?t[n]:n;void 0!==a&&(i[e.role]=a)}return e.replace(/\{([^}]+)\}/g,(e,t)=>{const n=i[t];return null==n?`{${t}}`:n+""})}var w={LineChart:"line chart",AreaChart:"area chart",StackedAreaChart:"stacked area chart",DifferenceChart:"difference chart",Scatterplot:"scatter plot",BubbleChart:"bubble chart",ConnectedScatterplot:"connected scatter plot",QuadrantChart:"quadrant chart",MultiAxisLineChart:"dual-axis line chart",CandlestickChart:"candlestick chart",Heatmap:"heatmap",MinimapChart:"line chart",BarChart:"bar chart",StackedBarChart:"stacked bar chart",GroupedBarChart:"grouped bar chart",DotPlot:"dot plot",Histogram:"histogram",BoxPlot:"box plot",ViolinPlot:"violin plot",RidgelinePlot:"ridgeline plot",SwarmPlot:"swarm plot",PieChart:"pie chart",DonutChart:"donut chart",FunnelChart:"funnel chart",GaugeChart:"gauge",LikertChart:"Likert chart",SwimlaneChart:"swimlane chart",ForceDirectedGraph:"network graph",SankeyDiagram:"Sankey diagram",ProcessSankey:"temporal Sankey diagram",ChordDiagram:"chord diagram",TreeDiagram:"tree diagram",Treemap:"treemap",CirclePack:"circle-packing chart",OrbitDiagram:"orbit diagram",ChoroplethMap:"choropleth map",ProportionalSymbolMap:"proportional-symbol map",FlowMap:"flow map",DistanceCartogram:"distance cartogram",BigNumber:"single value",StreamPhysicsFrame:"physics stream frame",EventDropChart:"event-drop physics chart",GaltonBoardChart:"Galton board chart",UnitPileChart:"physics pile chart",CollisionSwarmChart:"collision swarm chart",PacketFlowChart:"physical flow chart",ProcessFlowChart:"process flow physics chart",CrucibleChart:"crucible physics chart",PhysicsCustomChart:"custom physics chart"},S=new Set(["ForceDirectedGraph","SankeyDiagram","ProcessSankey","ChordDiagram"]),x=new Set(["StreamPhysicsFrame","EventDropChart","GaltonBoardChart","UnitPileChart","CollisionSwarmChart","PacketFlowChart","ProcessFlowChart","GauntletChart","CrucibleChart","PhysicsCustomChart"]);function k(e){return w[e]||e.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase()+" chart"}function A(e){const t="number"==typeof e?e:"string"==typeof e?Number(e):NaN;return Number.isFinite(t)?t:void 0}var P=new Set(["Scatterplot","BubbleChart","ConnectedScatterplot","QuadrantChart","ScatterplotMatrix"]),j={"outlier-detection":"alerting","change-detection":"alerting",trend:"tracking","composition-over-time":"apportioning","compare-series":"comparing","compare-categories":"comparing",rank:"ranking","part-to-whole":"apportioning",distribution:"characterizing",correlation:"relating",flow:"tracing",hierarchy:"nesting",geo:"locating"},F={"time-series":"tracking",categorical:"comparing",distribution:"characterizing",relationship:"relating",flow:"tracing",network:"tracing",hierarchy:"nesting",geo:"locating",realtime:"tracking",value:"presenting",custom:"presenting"},L=["trend","compare-series","compare-categories","rank","part-to-whole","distribution","correlation","flow","hierarchy","geo","composition-over-time","change-detection","outlier-detection"],D={alerting:"alerting",tracking:"trend",comparing:"comparison",ranking:"ranking",apportioning:"composition",characterizing:"distribution",relating:"correlation",tracing:"flow",nesting:"hierarchy",locating:"locator",presenting:"single-value"};function B(e){return j[e]}function N(e,t){const n=function(e){if(e){if("fits"in e||"buildProps"in e){const t=e,n={};for(const[e,r]of Object.entries(t.intentScores))"number"==typeof r&&Number.isFinite(r)&&(n[e]=r);return{family:t.family,intentScores:Object.keys(n).length?n:void 0}}return e}}(t);if(n?.act)return n.act;if(n?.intentScores){const e=function(e){let t,n=0;for(const[r,o]of Object.entries(e))if("number"==typeof o&&o>0)if(o>n)t=r,n=o;else if(o===n&&void 0!==t){const e=L.indexOf(r),n=L.indexOf(t);-1===e||-1!==n&&e>=n||(t=r)}return t}(n.intentScores);if(e&&j[e]&&(n.intentScores[e]??0)>=3)return j[e]}return n?.family?F[n.family]:function(e){return a.has(e)||"StackedAreaChart"===e?"apportioning":P.has(e)?"relating":o.has(e)?"comparing":i.has(e)?"characterizing":r.has(e)?"tracking":S.has(e)?"tracing":"BigNumber"===e?"presenting":void 0}(e)}var I=new Set(["y-threshold","x-threshold","band","x-band","callout","label"]),M=new Set(["system","agent","watcher"]),R=new Set(["ai","agent","system","computed","dbt","great-expectations"]),O=new Set(["rule","statistical-test","llm-inference","computed"]);function T(e){const t=e.annotations;return!!Array.isArray(t)&&t.some(e=>{if(!e||"object"!=typeof e)return!1;const t=e;if("string"!=typeof t.type||!I.has(t.type))return!1;const n=t.provenance;return!(!n||"object"!=typeof n)&&(M.has(n.authorKind)||R.has(n.source)||O.has(n.basis))})}function G(e="en"){let t,n;try{t=new Intl.NumberFormat(e,{notation:"compact",maximumFractionDigits:1}),n=new Intl.NumberFormat(e,{maximumFractionDigits:2})}catch{t=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}),n=new Intl.NumberFormat("en",{maximumFractionDigits:2})}return e=>Number.isFinite(e)?1e4>Math.abs(e)?n.format(e):t.format(e):e+""}var E={"y-threshold":"a threshold line","x-threshold":"a threshold line",band:"a highlighted band","x-band":"a highlighted band",label:"a label",callout:"a callout","callout-circle":"a callout","callout-rect":"a callout",text:"a text note",bracket:"a bracket",enclose:"an enclosure","rect-enclose":"an enclosure",highlight:"a highlight",widget:"a widget",trend:"a trend line",envelope:"an envelope","anomaly-band":"an anomaly band",forecast:"a forecast","category-highlight":"a category highlight"};function U(e){const t=E["string"==typeof e.type?e.type:"annotation"]||"an annotation",n=function(e){const t=e.provenance&&"object"==typeof e.provenance?e.provenance:null,n=t?.authorKind??t?.source??t?.basis;return"watcher"===n?"a watcher-flagged ":"agent"===n||"ai"===n||"llm-inference"===n?"an AI-suggested ":""}(e),r=n?n+t.replace(/^an? /,""):t,o="string"==typeof e.label?e.label:"string"==typeof e.title?e.title:void 0;return o?`${r} labeled "${o}"`:r}function q(t){const n=Array.isArray(t.annotations)?t.annotations:null;if(!n||0===n.length)return;const r=e(n.filter(e=>!!e&&"object"==typeof e));if(0===r.length)return;const o=r.map(U),a=o.slice(0,5),i=o.length-a.length,s=function(e){return e.length>1?2===e.length?`${e[0]} and ${e[1]}`:`${e.slice(0,-1).join(", ")}, and ${e[e.length-1]}`:e[0]??""}(a)+(i>0?`, and ${i} more`:""),l=r.length;return`The author has marked ${1===l?"one feature":l+" features"} on this chart: ${s}.`}function z(e,u,h={}){const d=void 0!==h.levels,p=new Set(h.levels??["l1","l2","l3"]);d||!h.capability&&!T(u)||p.add("l4");const $=y(e,u,h.recipe);if($){const e=["l1","l2","l3","l4"].filter(e=>p.has(e));d||e.includes("l4")||e.push("l4");const t=function(e,t,n={}){const r=g(t),o=m(t),a=n.locale??"en",i="function"==typeof e.description?e.description({data:r,config:o,locale:a}):void 0,s=i?.levels??function(e,t,n,r){const o=v(e,["nominal","ordinal"]),a=v(e,["quantitative"]),i=o?b(o,n,t):void 0,s=a?b(a,n,t):void 0,l=o?.role??i??"category",c=a?.role??s??"value",u=e.encodings??[],h=u.length?u.slice(0,3).map(e=>e.meaning.replace(/\.$/,"")).join("; "):`${l} and ${c} are mapped through the recipe's declared visual semantics`,{number:d,percent:p}=function(e){try{return{number:new Intl.NumberFormat(e,{maximumFractionDigits:2}),percent:new Intl.NumberFormat(e,{style:"percent",maximumFractionDigits:1})}}catch{return{number:new Intl.NumberFormat("en",{maximumFractionDigits:2}),percent:new Intl.NumberFormat("en",{style:"percent",maximumFractionDigits:1})}}}(r),m=new Map;if(i&&s)for(const e of t){const t=(e[i]??"Uncategorized")+"",n=Number(e[s]);Number.isFinite(n)&&m.set(t,(m.get(t)??0)+n)}const g=[...m].sort((e,t)=>t[1]-e[1]),y=g.reduce((e,[,t])=>e+t,0),$=g[0],C=g[1],w=y>0?(($?.[1]??0)+(C?.[1]??0))/y:0,S=e.intents.map(e=>({id:f(e),strength:"string"==typeof e?void 0:e.strength})).sort((e,t)=>"primary"===e.strength?-1:"primary"===t.strength?1:0)[0]?.id,x=e.audience?.primary??e.audienceFit?.find(e=>"strong"===e.fit)?.audience;return{l1:`A ${e.name.toLowerCase()} encodes ${l} and ${c}. ${k=h,k?k.charAt(0).toUpperCase()+k.slice(1):k}.`,l2:g.length>0?`${g.length} categories total ${d.format(y)}. ${$[0]} accounts for ${d.format($[1])}${y>0?` (${p.format($[1]/y)})`:""}${C?`, followed by ${C[0]} at ${d.format(C[1])}`:""}.`:`${t.length} data ${1===t.length?"item is":"items are"} represented.`,l3:2>g.length?$?$[0]+" is the only represented category.":"No quantitative pattern can be derived from the available data.":.5>w?`The total is distributed across ${g.length} categories without the first two forming a majority.`:`Most of the total is concentrated in ${$[0]} and ${C[0]}, which together account for ${p.format(w)}.`,l4:`The chart is intended for ${S??"explanation"}${x?` with a ${x} audience`:""}: ${e.designContract.whyCustom}`};var k}(e,r,o,a),l=n.levels??["l1","l2","l3","l4"],c={};for(const e of l)s[e]&&(c[e]=s[e]);const u=["l1","l2","l3","l4"].map(e=>c[e]).filter(e=>!!e).join(" "),h=n.includeCaveats?[...e.reception?.risks??[],...e.caveats??[],...(e.designContract.misuse??[]).map(e=>"Misuse: "+e)]:void 0;return{text:u,levels:c,...h?.length?{caveats:h}:{}}}($,u,{levels:e,locale:h.locale,audience:h.audience,includeCaveats:h.includeCaveats}),n=q(u);return{...t,text:n?`${n} ${t.text}`.trim():t.text,...n?{annotations:n}:{}}}const C=G(h.locale??"en"),w=k(e),P=Array.isArray(u.data)?u.data:null,j=l(u),F=x.has(e)?function(e,t){const n=e.physics&&"object"==typeof e.physics?e.physics:null,r=e.settledProjection&&"object"==typeof e.settledProjection?e.settledProjection:null,o=[e.settledProjectionRows,e.projectionRows,r?.rows,n?.settledProjectionRows,n?.projectionRows,n?.settledProjection&&"object"==typeof n.settledProjection?n.settledProjection.rows:void 0].find(e=>Array.isArray(e));return Array.isArray(o)?o.map((e,n)=>{if(!e||"object"!=typeof e)return null;const r=e,o=A(r.count??r.value??r.total??r.bodies??r.events);if(null==o)return null;const a=r.label??r.id??r.name??"container "+(n+1),i=A(r.secondary??r.secondaryCount),s=A(r.observed??r.observedCount);return{label:c(a,t),count:o,...null!=i?{secondary:i}:{},..."string"==typeof r.secondaryLabel&&r.secondaryLabel?{secondaryLabel:r.secondaryLabel}:{},...null!=s?{observed:s}:{}}}).filter(e=>null!=e):null}(u,C):null,{measure:L,measureFallback:B,dimension:I,dimensionFallback:M}=s(e,u),R="string"==typeof L&&L?L:B,O="string"==typeof I&&I?I:M,E={};if(x.has(e)&&function(e,t,n,r,o,a){const i=function(e){return"EventDropChart"===e?"time window":"GaltonBoardChart"===e?"bin":"CollisionSwarmChart"===e?"group lane":"PacketFlowChart"===e?"flow node":"CrucibleChart"===e?"result group":"container"}(e),s=function(e){return"EventDropChart"===e?"event":"GaltonBoardChart"===e?"sample":"CollisionSwarmChart"===e?"point":"PacketFlowChart"===e?"packet":"CrucibleChart"===e?"settled item":"body"}(e);if(o.has("l1")&&(r.l1=function(e,t){return"EventDropChart"===e?"An event-drop physics chart that collapses moving events into a settled projection by event-time window.":"GaltonBoardChart"===e?"A Galton board chart that collapses falling samples into a settled histogram projection.":"UnitPileChart"===e?"A physics pile chart that collapses moving bodies into a settled bar-style projection by container.":"CollisionSwarmChart"===e?"A collision swarm chart that separates overlapping points while preserving their quantitative axis position.":"PacketFlowChart"===e?"A physical flow chart that keeps authored routes visible while packet bodies show throughput and proximity events.":"CrucibleChart"===e?"A crucible physics chart that replays authored phases and events into declared products and outlets; the settled ledger, not collisions, determines the result.":`A ${t} whose accessible reading is the settled projection rather than individual trajectories.`}(e,t)),!o.has("l2")&&!o.has("l3"))return;if(!n||0===n.length)return void(o.has("l2")&&(r.l2="No settled projection is loaded yet."));const l=n.reduce((e,t)=>e+t.count,0),c=n.filter(e=>e.count>0).sort((e,t)=>t.count-e.count),u=c[0]??n.slice().sort((e,t)=>t.count-e.count)[0];if(!u)return;const h=n.reduce((e,t)=>e+(t.secondary??0),0),d=n.find(e=>e.secondaryLabel)?.secondaryLabel??"secondary";if(o.has("l2"))if(0===c.length)r.l2=`The settled projection contains ${a(l)} ${J(l,s)} across ${n.length} ${J(n.length,i)}; no ${J(2,i)} are non-empty yet.`;else{const e=h>0?` ${a(h)} ${J(h,s)} ${1===h?"is":"are"} marked ${d}.`:"";r.l2=`The settled projection contains ${a(l)} ${J(l,s)} across ${n.length} ${J(n.length,i)}; ${c.length} ${J(c.length,i)} ${1===c.length?"is":"are"} non-empty. The largest ${i} is ${u.label} with ${a(u.count)} ${J(u.count,s)}.${e}`}if(o.has("l3")&&l>0&&c.length>0){const e=c.find(e=>e!==u),t=function(e,t){if(0>=t)return"0%";const n=e/t*100;return(10>n?Math.round(10*n)/10:Math.round(n))+"%"}(u.count,l);r.l3=e?`The settled projection is most concentrated in ${u.label}, which holds ${a(u.count)} ${J(u.count,s)} (${t}); ${e.label} follows with ${a(e.count)} ${J(e.count,s)}.`:`The settled projection is concentrated in ${u.label}, which holds all ${a(u.count)} ${J(u.count,s)}.`}}(e,w,F,E,p,C),p.has("l1")&&!x.has(e))if(r.has(e)||o.has(e))E.l1=`A ${w} of ${R} by ${O}`+(j?`, split by ${j}.`:".");else if(a.has(e))E.l1=`A ${w} showing ${R} across ${O} categories.`;else if(i.has(e))E.l1=`A ${w} of the distribution of ${R}`+(j?` by ${j}.`:".");else if(S.has(e)){const e=Array.isArray(u.nodes)?u.nodes.length:void 0,t=Array.isArray(u.edges)?u.edges.length:void 0,n=[null!=e?`${e} ${J(e,"node")}`:null,null!=t?`${t} ${J(t,"edge")}`:null].filter(Boolean);E.l1=`A ${w}${n.length?" with "+n.join(" and "):""}.`}else if("BigNumber"===e){const e="string"==typeof u.label?u.label:R;E.l1=`A single value${e?" for "+e:""}.`}else E.l1=`A ${w}.`;const U=r.has(e)||o.has(e)||a.has(e)||i.has(e);let z=null;if((p.has("l2")||p.has("l3")||p.has("l4"))&&U&&P&&P.length>0&&(z=function(e,t,n,r){let o=0,a=0,i=1/0,s=-1/0,l=null,u=null,h=0,d=0,p=null,f=null,m=NaN,g=NaN;for(const n of e){const e=t(n);Number.isFinite(e)&&(0===o&&(m=e,p=n),g=e,f=n,i>e&&(i=e,l=n,h=o),e>s&&(s=e,u=n,d=o),o++,a+=e)}return 0===o?null:{count:o,min:i,max:s,mean:a/o,minLabel:c(null!=l?n(l):null,r),maxLabel:c(null!=u?n(u):null,r),first:m,last:g,firstLabel:c(null!=p?n(p):null,r),lastLabel:c(null!=f?n(f):null,r),minIndex:h,maxIndex:d}}(P,t(L,B),n(I,M),C)),p.has("l2")&&U&&(P&&0!==P.length?z&&(E.l2=a.has(e)?`${z.count} segments totaling ${C(function(e){return e.mean*e.count}(z))}. Largest is ${z.maxLabel} at ${C(z.max)}; smallest is ${z.minLabel} at ${C(z.min)}.`:`${R} ranges from ${C(z.min)} (${z.minLabel}) to ${C(z.max)} (${z.maxLabel}), with a mean of ${C(z.mean)} across ${z.count} points.`):E.l2="No data is loaded yet."),p.has("l3")&&z&&!j&&r.has(e)?E.l3=function(e,t,n){const{first:r,last:o,min:a,max:i,maxLabel:s,minLabel:l,firstLabel:c,lastLabel:u,minIndex:h,maxIndex:d,count:p}=e,f=i-a,m=o-r;if(0===f)return`${H(t)} is constant at ${n(r)} across the series.`;if(.04>f/(Math.abs(e.mean)||1))return`${H(t)} ends roughly where it started (${n(r)} at ${c} to ${n(o)} at ${u}), ranging between ${n(a)} and ${n(i)}.`;const g=d>0&&p-1>d,y=h>0&&p-1>h,b=(i-Math.max(r,o))/f,$=(Math.min(r,o)-a)/f;return g&&b>.15?`Overall ${t} climbs to a peak of ${n(i)} (${s}), then falls to ${n(o)} (${u}).`:y&&$>.15?`Overall ${t} drops to a low of ${n(a)} (${l}), then recovers to ${n(o)} (${u}).`:.05>Math.abs(m)/f?`${H(t)} ends roughly where it started (${n(r)} at ${c} to ${n(o)} at ${u}), ranging between ${n(a)} and ${n(i)}.`:m>0?d===p-1?`Overall ${t} rises from ${n(r)} (${c}) to a peak of ${n(o)} (${u}).`:`Overall ${t} rises from ${n(r)} (${c}) to ${n(o)} (${u}), after peaking at ${n(i)} (${s}).`:h===p-1?`Overall ${t} falls from ${n(r)} (${c}) to a low of ${n(o)} (${u}).`:`Overall ${t} falls from ${n(r)} (${c}) to ${n(o)} (${u}), after dipping to ${n(a)} (${l}).`}(z,R,C):p.has("l3")&&z&&!j&&o.has(e)&&(E.l3=`The highest ${O} is ${z.maxLabel} and the lowest is ${z.minLabel}.`),p.has("l4")){const t=T(u)?"alerting":N(e,h.capability);t&&(E.l4=function(e,t,n,r,i,s,l,c){const u=D[e],h=/^[aeiou]/i.test(u)?"an":"a";let d,p;switch(e){case"locating":d="This is a map",p="read values by location";break;case"presenting":d="This is a single-value display",p=`read ${"string"==typeof n.label&&n.label?n.label:i} as the headline number`;break;case"tracing":d=`This is ${h} ${u} chart`,p="follow the movement between states";break;case"nesting":d=`This is ${h} ${u} chart`,p="read it for nested structure and how children sum into their parents";break;case"relating":d=`This is ${h} ${u} chart`,p=`read it for whether ${s} and ${i} move together`;break;default:d=`This is ${h} ${u} chart`,p=function(e,t,n,r,i,s){if(!t)switch(e){case"alerting":return"watch for points that break from the rest";case"tracking":return"read it for the overall direction of "+n;case"comparing":return`compare ${n} across ${r}`;case"ranking":return"read it top to bottom by "+n;case"apportioning":return`read each ${r}'s share of the whole`;case"characterizing":return"read it for the spread and shape of "+n;default:return"read the highlighted features"}switch(e){case"alerting":return function(e,t,n){if(o.has(n)||a.has(n))return`${e.maxLabel} stands out at ${t(e.max)} — check it first`;const{first:r,last:i,min:s,max:l,minLabel:c,maxLabel:u,lastLabel:h,minIndex:d,maxIndex:p,count:f}=e,m=l-s;if(m>0){const e=p>0&&f-1>p,n=d>0&&f-1>d,o=(l-Math.max(r,i))/m,a=(Math.min(r,i)-s)/m;if(e&&o>.15)return`the peak of ${t(l)} at ${u} is the point to investigate`;if(n&&a>.15)return`the dip to ${t(s)} at ${c} is the point to investigate`;if(i>=l)return`the climb to ${t(i)} at ${h} warrants a closer look`;if(s>=i)return`the drop to ${t(i)} at ${h} warrants a closer look`}return`the extremes — ${u} (${t(l)}) and ${c} (${t(s)}) — are the points to check`}(t,i,s);case"tracking":return`read it for the trajectory of ${n}, which ${function(e){const t=e.max-e.min,n=e.last-e.first;return 0===t||.05>Math.abs(n)/t?"holds roughly steady":n>0?"rises":"falls"}(t)} from ${i(t.first)} (${t.firstLabel}) to ${i(t.last)} (${t.lastLabel})`;case"comparing":return`compare ${n} across ${r}; ${t.maxLabel} leads at ${i(t.max)}`;case"ranking":return`read it top to bottom by ${n}; ${t.maxLabel} ranks highest at ${i(t.max)}`;case"apportioning":{const e=t.mean*t.count,n=e>0?Math.round(t.max/e*100):null;return`read each ${r}'s share of the ${i(e)} total; ${t.maxLabel} is the largest at ${i(t.max)}${null!=n?` (${n}%)`:""}`}case"characterizing":return`read it for the spread of ${n}, from ${i(t.min)} to ${i(t.max)}`;default:return"read the highlighted features"}}(e,r,i,s,l,t)}return`${d}; ${p}.${function(e,t){if(!t)return"";const n=t.familiarity?.[e];return"number"!=typeof n||n>2?"":` This ${k(e)} may be unfamiliar${t.name?` to ${t.name.toLowerCase()} readers`:""} — lean on this description.`}(t,c)}`}(t,e,u,j?null:z,R,O,C,h.audience))}const V=["l1","l2","l3","l4"].filter(e=>p.has(e)&&E[e]).map(e=>E[e]).join(" "),Q=q(u);return{text:Q?`${Q} ${V}`.trim():V,levels:E,...Q?{annotations:Q}:{}}}function H(e){return e.length?e[0].toUpperCase()+e.slice(1):e}function J(e,t){return 1!==e&&"body"===t?"bodies":1===e?t:t+"s"}function V(e){return((e??"unknown")+"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Q(u,h,d={}){const p=d.locale??"en",f=Math.max(1,d.maxLeaves??200),w=G(p),S=y(u,h,d.recipe);if(S)return function(e,t,n={}){const r=g(t),o=m(t),a=Math.max(1,n.maxLeaves??200);if("function"==typeof e.navigation)return e.navigation({data:r,config:o,locale:n.locale??"en"});const i=(s=e.navigation)&&"object"==typeof s?e.navigation:void 0;var s;const l=(i?.groupByRole?$(e,i.groupByRole):void 0)??(i?.groupBy?.[0]?$(e,i.groupBy[0])??e.dataRoles.find(e=>e.field===i.groupBy?.[0]):void 0)??v(e,["nominal","ordinal"]),c=l?b(l,o,r):void 0,u=(i?.idRole?$(e,i.idRole):void 0)??v(e,["identifier"]),h=u?b(u,o,r):void 0,d={id:"root",role:"chart",label:i?.summaryTemplate?C(i.summaryTemplate,void 0,e,o,r,{count:r.length}):`${e.name}: ${r.length} ${1===r.length?"item":"items"} represented.`,level:1,children:[]};let p=0;const f=(t,n,a)=>{const s=h?t[h]:void 0,l=i?.itemLabelTemplate?C(i.itemLabelTemplate,t,e,o,r,{count:r.length}):function(e,t,n,r){const o=v(t,["nominal","ordinal"]),a=t.dataRoles.filter(e=>"quantitative"===e.semanticType),i=o?b(o,n,r):void 0,s=[];i&&null!=e[i]&&s.push(e[i]+"");for(const t of a){const o=b(t,n,r);o&&null!=e[o]&&s.push(`${t.role}: ${e[o]+""}`)}return s.length>0?s.join(", "):"Data item"}(t,e,o,r);return{id:"datum-"+V(s??n),role:"datum",label:l,level:a,datum:t}};if(c){const e=new Map;for(const t of r){const n=(t[c]??"Uncategorized")+"",r=e.get(n);r?r.push(t):e.set(n,[t])}d.children=[...e].map(([e,t],n)=>{const r=t.slice(0,Math.max(0,a-p));p+=r.length;const o=r.map((e,t)=>f(e,1e5*n+t,3));return t.length>r.length&&o.push({id:"more-"+V(e),role:"datum",label:`…and ${t.length-r.length} more items`,level:3}),{id:"group-"+V(e),role:"series",label:`${e}: ${t.length} ${1===t.length?"item":"items"}.`,level:2,children:o}})}else{const e=r.slice(0,a);d.children=e.map((e,t)=>f(e,t,2)),r.length>e.length&&d.children.push({id:"more",role:"datum",label:`…and ${r.length-e.length} more items`,level:2})}return d}(S,h,{maxLeaves:f,locale:p});const x={id:"root",role:"chart",label:z(u,h,{locale:p}).text||"Chart.",level:1,children:[]},k=function(t,n){const r=Array.isArray(t.annotations)?t.annotations:null;if(!r)return null;const o=e(r.filter(e=>!!e&&"object"==typeof e));if(0===o.length)return null;let a=0;const i=o.slice(0,n).map(e=>{const t=e.lifecycle?.status,n=t&&"accepted"!==t?` (${t})`:"";return{id:"annotation-"+a++,role:"annotation",level:3,label:`${r=U(e),r?r.charAt(0).toUpperCase()+r.slice(1):r}${n}.`,datum:e};var r});o.length>n&&i.push({id:"annotation-"+a++,role:"annotation",level:3,label:`…and ${o.length-n} more annotations.`});const s=o.length;return{id:"annotations",role:"annotation",level:2,label:`Annotations: ${1===s?"one marked feature":s+" marked features"}.`,children:i}}(h,f),A=Array.isArray(h.data)?h.data:null,P=r.has(u)||o.has(u)||a.has(u)||i.has(u);if(!A||0===A.length||!P)return k&&(x.children=[k]),x;const{measure:j,measureFallback:F,dimension:L,dimensionFallback:D}=s(u,h),B=t(j,F),N=n(L,D),I="string"==typeof j&&j?j:F,M="string"==typeof L&&L?L:D,R=l(h);let O=0;const T=e=>`${e}-${O++}`,E=(e,t)=>{const n=e.slice(0,f).map(e=>((e,t)=>{const n=B(e),r=c(N(e),w);return{id:T("datum"),role:"datum",level:t,label:`${r}: ${Number.isFinite(n)?w(n):"—"}`,value:Number.isFinite(n)?n:void 0,datum:e}})(e,t));return e.length>f&&n.push({id:T("more"),role:"datum",level:t,label:`…and ${e.length-f} more points`}),n},q=[];if(r.has(u)||o.has(u)){let e=1/0,t=-1/0,n=1/0,r=-1/0;const a=[];let i=!0;for(const o of A){const s=B(o);Number.isFinite(s)&&(e>s&&(e=s),s>t&&(t=s));const l=N(o);a.push(l),"number"==typeof l&&Number.isFinite(l)?(n>l&&(n=l),l>r&&(r=l)):i=!1}const s=new Set,l=[];for(const e of a){const t=e+"";s.has(t)||(s.add(t),l.push(e))}const h=i?`${w(n)} to ${w(r)}`:`${c(l[0],w)} to ${c(l[l.length-1],w)} (${o.has(u)?l.length+" categories":A.length+" points"})`;q.push({id:T("axis"),role:"axis",level:2,label:`${o.has(u)?"Category axis":"X axis"}: ${M}, ${h}.`}),e>t||q.push({id:T("axis"),role:"axis",level:2,label:`Value axis: ${I}, ${w(e)} to ${w(t)}.`})}if(R){const e=n(R,R),t=new Map;for(const n of A){const r=(e(n)??"—")+"",o=t.get(r);o?o.push(n):t.set(r,[n])}const r=[];for(const[e,n]of t){const t=z(u,{...h,data:n},{levels:["l2","l3"],locale:p}).text;r.push({id:T("series"),role:"series",level:2,label:`Series ${e}: ${t}`,children:E(n,3)})}x.children=[...q,...r]}else x.children=[...q,...E(A,2)];return k&&x.children.push(k),x}function K(e,t){const n=[],r=e=>{if(n.push(e),e.children&&e.children.length>0&&t.has(e.id))for(const t of e.children)r(t)};return r(e),n}function X(e){let t=1;if(e.children)for(const n of e.children)t+=X(n);return t}var _=new Set(["StreamPhysicsFrame","EventDropChart","GaltonBoardChart","UnitPileChart","CollisionSwarmChart","PacketFlowChart","ProcessFlowChart","PhysicsCustomChart"]);function W(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function Y(e){return W(e)?e:void 0}function Z(e){const t="number"==typeof e?e:"string"==typeof e&&e.trim()?Number(e):NaN;return Number.isFinite(t)?t:void 0}function ee(e){const t=Z(e);return null==t?void 0:Math.max(0,Math.floor(t))}function te(...e){return e.map(Y).find(Boolean)}function ne(...e){return e.find(Array.isArray)}function re(e){const t={};for(const[n,r]of Object.entries(e))void 0!==r&&(t[n]=r);return t}function oe(e,t,n){return e["string"==typeof t&&t?t:n]}function ae(e){return e instanceof Date?e.toISOString():"number"==typeof e?Number.isInteger(e)?e+"":Math.round(1e3*e)/1e3+"":(e??"—")+""}function ie(e,t){return 1!==e&&"body"===t?"bodies":1===e?t:t+"s"}function se(e){return Number.isInteger(e)?e+"":Math.round(1e3*e)/1e3+""}function le(e,t,n){const r=e?.filter(e=>!0===Y(e)?.sensor).length,o=Y(t?.observation),a=Y(o?.sensors),i=ne(n?.activeSensors);return Math.max(r??0,a?Object.keys(a).length:0,i?.length??0)||void 0}function ce(e,t,n={}){const{capability:r,audience:o,locale:a}=n,i=n.levels??["l1","l2","l3"],s=!1!==n.includeStructure,l=N(e,r),c=z(e,t,{levels:l?[...i,"l4"]:i,locale:a,capability:r,audience:o}),{l4:u,...h}=c.levels,d=["l1","l2","l3"].map(e=>c.levels[e]).filter(Boolean).join(" "),p={levels:h,text:c.annotations?`${c.annotations} ${d}`.trim():d,...c.annotations?{annotations:c.annotations}:{}};let f;if(l&&u){const e=(m=r)?"fits"in m||"buildProps"in m?{family:m.family}:{family:m.family,intentScores:m.intentScores}:{};f={act:l,sentence:u,family:e.family,intentScores:e.intentScores}}var m;const g=s?Q(e,t,{maxLeaves:n.maxLeaves,locale:a}):void 0,y=function(e,t,n){if(!1===n)return;const r=W(n)?n:void 0,o=Y(t.physics),a=te(r?.snapshot,o?.snapshot,t.physicsSnapshot,function(e){const t=Y(e);return!!t&&(W(t.world)||"simulationState"in t||"liveBodyOrder"in t)}(t.snapshot)?t.snapshot:void 0),i=te(r?.evidence,o?.evidence,t.physicsEvidence,t.settledEvidence),s=te(r?.config,o?.config,a?.config,t.config),l=te(Y(a?.world),Y(o?.world)),c=te(Y(s?.kernel),Y(l?.options)),u=ne(l?.bodies),h=ne(l?.colliders,s?.colliders),d=ne(a?.queue,o?.queue),p=ne(a?.liveBodyOrder),f=ne(l?.springs),m=ne(a?.activeSensorPairs),g=function(e){if(!e||0===e.length)return;const t=e.map((e,t)=>{const n=Y(e);if(!n)return;const r=Z(n.count??n.value??n.total??n.bodies??n.events);if(null==r)return;const o=(n.label??n.id??n.name??"container "+(t+1))+"",a=null==n.id?void 0:n.id+"",i=Z(n.secondary??n.secondaryCount),s=Z(n.observed??n.observedCount);return re({id:a,label:o,count:r,secondary:i,secondaryLabel:"string"==typeof n.secondaryLabel?n.secondaryLabel:void 0,observed:s})}).filter(e=>null!=e);if(0===t.length)return;const n=t.reduce((e,t)=>e+t.count,0),r=t.filter(e=>e.count>0).length,o=t.slice().sort((e,t)=>t.count-e.count)[0];return{rows:t,totalCount:n,populatedCount:r,...o?{leader:o}:{}}}(function(e,t,n,r){const o=Y(e.settledProjection),a=Y(t?.settledProjection);return ne(n?.projectionRows,n?.aggregates,e.settledProjectionRows,e.projectionRows,o?.rows,t?.settledProjectionRows,t?.projectionRows,a?.rows,r?.binCounts)}(t,o,r,i)),y=function(e,t){const n=e?.map((e,t)=>{const n=Y(e);if(!n)return;const r=Z(n.count)??0,o=Z(n.total),a={label:(n.label??n.id??"sediment "+(t+1))+"",count:r};return null!=n.id&&(a.id=n.id+""),null!=o&&(a.total=o),a}).filter(e=>null!=e),r=ee(t?.bins)??n?.length??0,o=Z(t?.count)??n?.reduce((e,t)=>e+t.count,0)??0,a=Z(t?.total)??n?.reduce((e,t)=>e+(t.total??0),0),i=n?.slice().sort((e,t)=>t.count-e.count)[0];if(0!==r||0!==o||a)return{bins:r,count:o,...null!=a&&a>0?{total:a}:{},...i?{leader:i}:{}}}(ne(r?.sediment,o?.sediment,a?.sediment),te(r?.sedimentTotals,o?.sedimentTotals)),b=p?.length??u?.length??ee(i?.bodyCount),$=function(e){if(e)return e.filter(e=>!0===Y(e)?.sleeping).length}(u)??ee(i?.sleepingCount),v=d?.length,C="string"==typeof a?.simulationState?a.simulationState:void 0,w="boolean"==typeof i?.settled?i.settled:C?"settled"===C:null!=b||null!=$||null!=v?null!=b&&$===b&&0===(v??0):void 0,S=Y(c?.gravity),x=Z(S?.x),k=Z(S?.y),A=re({state:C,settled:w,elapsedSeconds:Z(a?.elapsedSeconds),paused:"boolean"==typeof a?.paused?a.paused:void 0,visible:"boolean"==typeof a?.visible?a.visible:void 0,seed:Z(c?.seed),gravity:null!=x&&null!=k?{x:x,y:k}:void 0,fixedDt:Z(s?.fixedDt??c?.fixedDt),timeScale:Z(s?.timeScale),maxSubsteps:ee(s?.maxSubsteps),liveBodies:b,sleepingBodies:$,queued:v,bodyLimit:Z(s?.bodyLimit),eviction:"string"==typeof s?.eviction?s.eviction:void 0}),P=re({colliders:h?.length,sensors:le(h,s,l),springs:f?.length,activeSensorPairs:m?.length}),j=Object.keys(P).length>0,F=_.has(e);if(!(Object.keys(A).length>0||j||g||y)||!F&&null==n)return;const L={simulation:A,...j?{geometry:P}:{},...g?{aggregates:g}:{},...y?{sediment:y}:{}},D=function(e){const t=[],n=e.simulation,r=[n.state??(n.settled?"settled":void 0),null!=n.liveBodies?`${n.liveBodies} live ${ie(n.liveBodies,"body")}`:void 0,null!=n.sleepingBodies?n.sleepingBodies+" sleeping":void 0,null!=n.queued?n.queued+" queued":void 0,null!=n.seed?"seed "+se(n.seed):void 0,n.gravity?`gravity (${se(n.gravity.x)}, ${se(n.gravity.y)})`:void 0,null!=n.fixedDt?`fixed step ${se(n.fixedDt)}s`:void 0,null!=n.timeScale?se(n.timeScale)+"x time":void 0].filter(Boolean);r.length>0&&t.push(`Physics simulation: ${r.join("; ")}.`);const o=e.geometry;if(o){const e=[null!=o.colliders?`${o.colliders} ${ie(o.colliders,"collider")}`:void 0,null!=o.sensors?`${o.sensors} ${ie(o.sensors,"sensor")}`:void 0,null!=o.springs?`${o.springs} ${ie(o.springs,"spring")}`:void 0,null!=o.activeSensorPairs?`${o.activeSensorPairs} active sensor ${ie(o.activeSensorPairs,"pair")}`:void 0].filter(Boolean);e.length>0&&t.push(`Physics geometry: ${e.join("; ")}.`)}const a=e.aggregates;if(a){const e=a.leader,n=e?` Largest is ${e.label} with ${se(e.count)}.`:"";t.push(`Physics aggregates: ${se(a.totalCount)} settled ${ie(a.totalCount,"body")} across ${a.rows.length} ${ie(a.rows.length,"container")}; ${a.populatedCount} populated.${n}`)}const i=e.sediment;if(i){const e=null!=i.total?", value total "+se(i.total):"",n=i.leader?`; largest sediment bin is ${i.leader.label} with ${se(i.leader.count)}`:"";t.push(`Physics sediment: ${i.count} retained ${ie(i.count,"body")} in ${i.bins} ${ie(i.bins,"bin")}${e}${n}.`)}return t.join(" ")}(L);return{...L,text:D}}(e,t,n.physics),b=function(e,t,n){const r=[];if("GaugeChart"===e){"number"==typeof t.value&&Number.isFinite(t.value)&&r.push(`Current value is ${ae(t.value)}.`);const e="number"==typeof t.min&&Number.isFinite(t.min)?t.min:0,n="number"==typeof t.max&&Number.isFinite(t.max)?t.max:100;r.push(`The gauge scale runs from ${ae(e)} to ${ae(n)}.`)}if("SankeyDiagram"===e||"ProcessSankey"===e){const e=Array.isArray(t.edges)?t.edges:[];if(e.length>0){r.push(`${e.length} source flow${1===e.length?"":"s"} are supplied.`);for(const o of e.slice(0,n)){const e=oe(o,t.sourceAccessor,"source"),n=oe(o,t.targetAccessor,"target"),a=oe(o,t.valueAccessor,"value");r.push(`${ae(e)} to ${ae(n)} has value ${ae(a)}.`)}}}if("Treemap"===e||"CirclePack"===e||"TreeDiagram"===e||"OrbitDiagram"===e){const e=Y(t.data),o="string"==typeof t.childrenAccessor&&t.childrenAccessor?t.childrenAccessor:"children",a="string"==typeof t.valueAccessor&&t.valueAccessor?t.valueAccessor:"value",i="string"==typeof t.nodeIdAccessor&&t.nodeIdAccessor?t.nodeIdAccessor:"string"==typeof t.nodeIDAccessor&&t.nodeIDAccessor?t.nodeIDAccessor:"name",s=[],l=e=>{const t=Array.isArray(e[o])?e[o]:[];if(0!==t.length)for(const e of t){const t=Y(e);t&&l(t)}else s.push(e)};if(e&&l(e),s.length>0){r.push(s.length+" hierarchy leaves are supplied.");for(const e of s.slice(0,n))r.push(`${ae(e[i])} has value ${ae(e[a])}.`)}}if(_.has(e)&&Array.isArray(t.data)){const n=t.data;r.push(`${n.length} observed source row${1===n.length?"":"s"} are supplied.`);const o="CollisionSwarmChart"===e?t.xAccessor:t.valueAccessor,a="CollisionSwarmChart"===e?"x":"value",i=n.map(e=>Z(oe(e,o,a))).filter(e=>null!=e);i.length>0&&r.push(`Observed ${"string"==typeof o?o:a} ranges from ${ae(Math.min(...i))} to ${ae(Math.max(...i))}.`)}if(0!==r.length)return{source:"chart-props",statements:r,text:"Exact chart-prop facts: "+r.join(" ")}}(e,t,Math.max(1,n.maxLeaves??200)),$=[p.text,f?.sentence,y?.text,b?.text].filter(Boolean).join(" ");return{component:e,description:p,intent:f,structure:g,physics:y,facts:b,text:$}}var ue=["BarChart","StackedBarChart","GroupedBarChart","SwarmPlot","BoxPlot","Histogram","ViolinPlot","RidgelinePlot","DotPlot","PieChart","DonutChart","GaugeChart","FunnelChart","SwimlaneChart","LikertChart","LineChart","BumpChart","AreaChart","DifferenceChart","StackedAreaChart","Scatterplot","BubbleChart","Heatmap","QuadrantChart","MultiAxisLineChart","CandlestickChart","ConnectedScatterplot","ScatterplotMatrix","MinimapChart","ForceDirectedGraph","SankeyDiagram","ProcessSankey","ChordDiagram","TreeDiagram","Treemap","CirclePack","OrbitDiagram","ChoroplethMap","ProportionalSymbolMap","FlowMap","DistanceCartogram","RealtimeLineChart","RealtimeHistogram","TemporalHistogram","RealtimeSwarmChart","RealtimeWaterfallChart","RealtimeHeatmap","GaltonBoardChart","EventDropChart","UnitPileChart","CollisionSwarmChart","GauntletChart","CrucibleChart","ProcessFlowChart","PacketFlowChart","ChainReactionChart","BigNumber"],he=new Set(ue);function de(e){return he.has(e)}var pe=new Set(["tooltip","onObservation","xFormat","yFormat","valueFormat","svgAnnotationRules","tooltipContent","onHover","tickFormatTime","tickFormatValue","edgeSort","sortGroups","centerContent","frameProps","controls","oFormat","rFormat","oSort","pieceStyle","summaryStyle","nodeStyle","edgeStyle","customHoverBehavior","customClickBehavior","customDoubleClickBehavior","onBrush","onTopologyChange","backgroundGraphics","foregroundGraphics","legend","recipe","layout"]),fe=new Set(["data","nodes","edges","points","areas","lines","flows"]);function me(e){if(null==e)return e;if("function"==typeof e)return;if("object"!=typeof e)return e;if(e.$$typeof)return;if(Array.isArray(e))return e.map(me).filter(e=>void 0!==e);if(e instanceof Date)return e;const t={};for(const[n,r]of Object.entries(e)){if("function"==typeof r)continue;if(r&&"object"==typeof r&&r.$$typeof)continue;const e=me(r);void 0!==e&&(t[n]=e)}return t}function ge(e,t){return!!fe.has(e)&&("areas"!==e||"string"!=typeof t)}var ye="function"==typeof structuredClone?structuredClone:e=>JSON.parse(JSON.stringify(e));function be(e,t,n){const r=d(e)??p(t.recipe)??p(t.recipeId);if(r)return function(e,t,n){const r=function(e,t,n){const r={};for(const[o,a]of Object.entries(e))if(null!=a&&!pe.has(o)&&"recipeId"!==o&&(t||!ge(o,a)))if("function"==typeof a||a?.$$typeof){if(n)throw Error(`Portable recipe prop "${o}" is not JSON-safe.`)}else if(u(a))r[o]=ye(a);else if(n)throw Error(`Portable recipe prop "${o}" is not JSON-safe.`);return r}(t,!1!==n?.includeData,"portable"===e.portability),o=e.intents.map(f).filter(e=>!!e),a={name:e.name,intents:o,...e.audience?.primary?{audience:[e.audience.primary]}:{},frameFamily:e.frameFamily};if("portable"===e.portability){if(!u(r))throw Error(`Portable recipe "${e.id}" contains non-JSON-safe props or layoutConfig.`);return{component:"ChartRecipe",recipeId:e.id,portable:!0,props:r,manifest:a,version:"1",createdAt:(new Date).toISOString(),...n?.selections?{selections:n.selections}:{}}}return{component:"ChartRecipe",recipeId:e.id,portable:!1,reason:"Recipe contains or may depend on non-serializable local layout callbacks.",warnings:["This config is inspectable but cannot be rendered remotely by CLI or MCP."],props:r,manifest:a,version:"1",createdAt:(new Date).toISOString(),...n?.selections?{selections:n.selections}:{}}}(r,t,n);if(!de(e))throw Error(`Unknown component "${e}". Known components: ${ue.join(", ")}`);const o=!1!==n?.includeData,a={};for(const[e,n]of Object.entries(t))if(null!=n&&!pe.has(e)&&(o||!ge(e,n))&&"function"!=typeof n&&!n?.$$typeof)try{a[e]=ye(me(n))}catch{}return{component:e,props:a,version:"1",createdAt:(new Date).toISOString(),...n?.selections?{selections:n.selections}:{}}}function $e(e){if(!e.component||!e.props)throw Error("Invalid chart config: missing component or props");if("ChartRecipe"===e.component||"LocalChartRecipe"===e.component){if(!e.recipeId)throw Error("Invalid chart recipe config: missing recipeId");const t=d(e.recipeId);if(!t)throw Error(`Unknown chart recipe "${e.recipeId}". Register it before deserializing this config.`);if("LocalChartRecipe"!==e.component&&!1!==e.portable&&"portable"!==t.portability)throw Error(`Chart recipe "${e.recipeId}" is registered as local, not portable.`);return{componentName:"ChartRecipe",props:{...ye(e.props),recipeId:e.recipeId}}}if(!de(e.component))throw Error(`Unknown component "${e.component}". This config may require a newer version of semiotic.`);return{componentName:e.component,props:ye(e.props)}}function ve(e){const t=JSON.stringify(e);return"sc="+btoa(unescape(encodeURIComponent(t))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ce(e){const t=new URLSearchParams(e.includes("?")?e.split("?")[1]:e).get("sc");if(!t)throw Error("No chart config found in URL (missing 'sc' parameter)");const n=t.replace(/-/g,"+").replace(/_/g,"/"),r=decodeURIComponent(escape(atob(n)));return JSON.parse(r)}async function we(e,t="json"){const n="jsx"===t?Se(e):JSON.stringify(e,null,2);if("undefined"==typeof navigator||!navigator.clipboard)throw Error("Clipboard API not available. copyConfig requires a browser environment.");await navigator.clipboard.writeText(n)}function Se(e){const{props:t}=e,n=["<"+("LocalChartRecipe"===e.component?"ChartRecipe":e.component)];e.recipeId&&n.push(` recipeId="${e.recipeId}"`);for(const[e,r]of Object.entries(t))if("string"==typeof r)n.push(` ${e}="${r}"`);else if("boolean"==typeof r&&!0===r)n.push(" "+e);else if("boolean"==typeof r&&!1===r)n.push(` ${e}={false}`);else if("number"==typeof r)n.push(` ${e}={${r}}`);else{const t=JSON.stringify(r);n.push(80>t.length?` ${e}={${t}}`:` ${e}={${JSON.stringify(r,null,2)}}`)}return n.push("/>"),n.join("\n")}export{d as getChartRecipe,f as recipeIntentId,m as recipeConfig,b as fieldForRole,B as communicativeActForIntent,N as resolveCommunicativeAct,z as describeChart,Q as buildNavigationTree,K as flattenVisible,X as countNodes,ce as buildReaderGrounding,be as toConfig,$e as fromConfig,ve as toURL,Ce as fromURL,we as copyConfig,Se as configToJSX};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e={fresh:1,aging:1.5,stale:3};function t(e,t,n={}){return Number.isFinite(t)&&t>0?Number.isNaN(e)?"fresh":e===1/0?"expired":0>e||t*(n.fresh??1)>e?"fresh":t*(n.aging??1.5)>e?"aging":t*(n.stale??3)>e?"stale":"expired":"fresh"}function n(e,t){return e===t}function r(e,t){if("function"==typeof e)return t=>+e(t);const n=e||t;return e=>+e[n]}function s(e,t){if("function"==typeof e)return e;const n=e||t;return e=>e[n]}function o(e,t){return"function"==typeof e?e:e?t=>t[e]+"":t?e=>e[t]+"":void 0}function i(e,t={}){const n=!0===t.showRetractedAnnotations,r=!0===t.showSupersededAnnotations,s=new Set;for(const t of e){const e=t?.lifecycle?.supersedes;e&&"retracted"!==t?.lifecycle?.status&&s.add(e)}return e.filter(e=>{if("retracted"===e?.lifecycle?.status&&!n)return!1;const t=e?.provenance?.stableId;return!(t&&s.has(t)&&!r)})}export{n as accessorsEquivalent,r as resolveAccessor,s as resolveRawAccessor,o as resolveStringAccessor,e as DEFAULT_LIFECYCLE_THRESHOLDS,t as bandFromAge,i as filterAnnotationsByStatus};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import{StreamPhysicsFrame_default as t,buildCollisionSwarmPhysics as e,buildEventDropPhysics as o,buildGaltonBoardPhysics as i,buildPhysicalFlowPhysics as r,buildPhysicsPile as n,buildProcessFlowPhysics as s,composePhysicsFrameGraphics as a,createCapacityQueueController as c,generateGaltonMechanicalSamples as d,generatePhysicsPileMechanicalSamples as l,physicsChartArea as u,pileTubeGeometry as p,placeEventDropSpawn as h,projectionRowsToSemanticItems as m,renderPhysicsChartState as y,renderPhysicsFrame as f,resolvePhysicsFrameSharedProps as g,resolvePhysicsTooltipProps as v,styleFromColorAccessor as b,usePhysicsChartMode as x,usePhysicsHocHandle as I,usePhysicsRerun as w,usePhysicsSelection as k}from"./chunk-chunk-NW25WGLS.module.min.js";import{filterSparseArray as M,useResponsiveSize as S}from"./chunk-chunk-7ZDJSYKI.module.min.js";import{useWasHydratingFromSSR as A}from"./chunk-chunk-ACLDBMRH.module.min.js";import{useReducedMotion as $}from"./chunk-chunk-YHNZCPOZ.module.min.js";import{forwardRef as j,useCallback as C,useMemo as R,useRef as P}from"react";import{Fragment as B,jsx as N,jsxs as O}from"react/jsx-runtime";var E=j(function(e,o){const{data:r,valueAccessor:n="value",styleRules:s,bins:c=21,ballRadius:l,colorBy:p,branchProbability:h=.5,emptyContent:M,frameProps:S,loading:A,loadingContent:$,mechanicalCount:j,paused:E,pegRows:W,referenceLines:H,rerunMS:z,responsiveHeight:D,responsiveWidth:_,seed:Y=1,valueExtent:F}=e,L=x(e,[700,420],{hasSimulationMode:!0}),{chartSize:T,simulationMode:G,showProjection:X,className:q,title:U,chartMode:V,margin:K,enableHover:Q,description:Z,summary:J,accessibleTable:tt}=L,et=l??("sparkline"===V?1.5:"context"===V?4:6),ot=P(null),it=Math.max(1,Math.round(W??c-1)),rt=R(()=>"mechanical"===G?[0,it]:function(t){if(!t)return;const e=Number(t[0]),o=Number(t[1]);return Number.isFinite(e)&&Number.isFinite(o)?e>o?[o,e]:[e,o]:void 0}(F),[it,G,F]),nt=R(()=>"mechanical"===G?d({bins:c,branchProbability:h,count:j,pegRows:it,seed:Y}):r??[],[c,h,r,j,it,Y,G]),st=R(()=>i({data:nt,valueAccessor:n,bins:c,ballRadius:et,seed:Y,size:T,valueExtent:rt}),[c,nt,T,et,rt,Y,n]),at=w(st.config,z,E),ct=C((t,e)=>{const o=i({data:[t],valueAccessor:n,bins:c,ballRadius:et,seed:Y+e+1,size:T,valueExtent:rt}).initialSpawns[0]??{id:(t.id??"galton-push-"+e)+"",x:u(T).plot.x,y:u(T).plot.y,mass:1,shape:{type:"circle",radius:et},datum:t};return{datumId:(t.id??o.id)+"",spawns:[o]}},[c,T,et,rt,Y,n]);I(o,{frameRef:ot,spawnDatum:ct,seedRows:nt,seedSpawns:st.initialSpawns});const dt="mechanical"===G&&null==p?"side":p,lt=R(()=>b(dt,"#4e79a7",{styleRules:s,valueAccessor:n}),[dt,s,n]),ut=R(()=>m(st.projectionRows,T,"bin"),[T,st.projectionRows]),{selection:pt,onBodyHover:ht}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:p,chartType:"GaltonBoardChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:S?.onBodyHover,fallbackFields:"string"==typeof n?[n]:void 0}),mt=y({data:"mechanical"===G?nt:r,emptyContent:M,loading:A,loadingContent:$,size:T});if(mt)return mt;const yt=function(t,e,o,i,r){const n=Array.isArray(r)?r:r?[r]:[];if(!1!==o||0!==n.length)return({size:r})=>{const s=[Number(r[0])||700,Number(r[1])||420],a=u(s),c=Math.max(2,Math.round(e)),d=a.plot.width/c,l=a.plot.y+a.plot.height,p=Math.max(1,...t.map(t=>t.value)),h=!1!==o,[m,y]=i?.valueExtent??[0,c],f=y===m?1:y-m,g=t.map((t,e)=>{const o=l-t.value/p*a.plot.height*.9;return`${0===e?"M":"L"} ${(a.plot.x+(e+.5)*d).toFixed(1)} ${o.toFixed(1)}`}).join(" ");return O("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?O(B,{children:[Array.from({length:c+1},(t,e)=>{const o=a.plot.x+e*d;return N("line",{"data-testid":"galton-board-bin-wall",x1:o,x2:o,y1:a.plot.y,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.28,strokeWidth:1},"bin-wall-"+e)}),N("line",{x1:a.plot.x,x2:a.plot.x+a.plot.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),N("path",{d:g,fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.7,strokeWidth:2,strokeLinejoin:"round"}),t.map((t,e)=>t.value>0?N("text",{x:a.plot.x+(e+.5)*d,y:Math.max(a.plot.y+10,l-t.value/p*a.plot.height*.9-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:t.value},`${t.label}-${e}`):null)]}):null,n.map((t,e)=>{const o=Number(t.value);if(!Number.isFinite(o))return null;const i=a.plot.x+Math.max(0,Math.min(1,(o-m)/f))*a.plot.width,r=t.color??"var(--semiotic-warning, #f28e2b)",n="bottom"===t.labelPosition?Math.min(s[1]-8,l+16):a.plot.y+16;return O("g",{className:t.className,"data-testid":"galton-board-reference-line",children:[N("line",{x1:i,x2:i,y1:a.plot.y+8,y2:l-4,stroke:r,strokeDasharray:t.strokeDasharray??"6 5",strokeWidth:t.strokeWidth??2}),null==t.label?null:N("text",{x:Math.min(a.plot.x+a.plot.width-4,i+6),y:n,fill:r,fontSize:10,fontWeight:700,children:t.label})]},`galton-reference-${e}-${o}`)})]})}}(st.projectionRows,c,X,st.metadata,H),ft=v(e.tooltip,S),gt=g(e,S,ut,{selection:pt,chartMode:V,className:q,title:U,description:Z,summary:J,accessibleTable:tt,enableHover:Q,margin:K});return f("GaltonBoardChart",T,N(t,{...S,...ft,...gt,ref:ot,onBodyHover:ht,config:at.config,foregroundGraphics:a(yt,S?.foregroundGraphics),initialSpawns:st.initialSpawns,initialSpawnPacing:st.initialSpawnPacing,paused:E,responsiveHeight:D,responsiveWidth:_,size:T,bodyStyle:lt},at.rerunKey))});import{forwardRef as W,useCallback as H,useMemo as z,useRef as D}from"react";import{jsx as _,jsxs as Y}from"react/jsx-runtime";import{createElement as F}from"react";var L=W(function(e,i){const{arrivalAccessor:r="arrivalTime",ballRadius:n=7,colorBy:s,styleRules:c,data:d,emptyContent:l,frameProps:p,loading:M,loadingContent:S,paused:A,rerunMS:$,responsiveHeight:j,responsiveWidth:C,seed:R=1,timeAccessor:P="time",timeExtent:B,timeScale:N=1,watermark:O,windows:E={size:10}}=e,W=x(e,[760,360]),{chartSize:L,showProjection:T,className:G,title:X,chartMode:q,margin:U,enableHover:V,description:K,summary:Q,accessibleTable:Z}=W,J=D(null),tt=z(()=>d??[],[d]),et=z(()=>o({data:tt,timeAccessor:P,arrivalAccessor:r,windows:E,watermark:O,ballRadius:n,seed:R,size:L,timeExtent:B,timeScale:N}),[r,n,L,tt,R,P,B,N,O,E]),ot=w(et.config,$,A),it=et.metadata,rt=H((t,e)=>{const o=(it?h(t,e,it,{timeAccessor:P,arrivalAccessor:r,ballRadius:n}):null)??{id:(t.id??"event-push-"+e)+"",x:u(L).plot.x,y:u(L).plot.y,mass:1,shape:{type:"circle",radius:n},datum:t};return{datumId:(t.id??o.id)+"",spawns:[o]}},[r,n,L,it,P]);I(i,{frameRef:J,spawnDatum:rt,seedRows:tt,seedSpawns:et.initialSpawns});const nt=z(()=>b(s,"#4e79a7",{styleRules:c,valueAccessor:P}),[s,c,P]),st=z(()=>function(t,e,o){if(!e)return m(t,o,"window");const i=e.windowPlot.width/Math.max(1,t.length),r=Math.max(1,...t.map(t=>t.value+(t.secondary??0))),n=.62*e.windowPlot.height,s=e.windowPlot.y+e.windowPlot.height;return t.map((t,o)=>{const a=Math.max(8,(t.value+(t.secondary??0))/r*n),c=`window ${t.label}: ${t.value} on time${t.secondary?`, ${t.secondary} late`:""}`;return{id:"window-"+t.label,label:c,description:c,datum:t,x:e.windowPlot.x+(o+.5)*i,y:s-a/2,shape:"rect",width:Math.max(12,.58*i),height:a,group:"window"}})}(et.projectionRows,it,L),[L,et.projectionRows,it]),{selection:at,onBodyHover:ct}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"EventDropChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:p?.onBodyHover,fallbackFields:"string"==typeof P?[P]:void 0}),dt=y({data:d,emptyContent:l,loading:M,loadingContent:S,size:L});if(dt)return dt;const lt=function(t,e,o){if(!1!==o&&e)return({size:o})=>{const i=[Number(o[0])||760,Number(o[1])||360],r=u(i),n=Math.max(1,e.windowCount),s=e.plot??r.plot,a=e.gutter??{x:s.x,y:s.y,width:0,height:s.height},c=e.windowPlot??s,d=c.width/n,l=s.y+s.height,p=s.y+.48*s.height,h=e.lidSegments[0]?.y1??p,m=e.windowStart,y=e.windowStart+n*e.windowSize,f=c.x+Math.max(0,Math.min(1,y===m?0:(e.watermarkValue-m)/(y-m)))*c.width;return Y("svg",{"aria-hidden":"true","data-testid":"event-drop-window-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[_("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?Y("g",{children:[_("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}),_("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:n},(o,r)=>{const n=t[r],s=c.x+r*d,a=e.closedWindowCount>r,u=n?.secondary??0;return Y("g",{children:[_("rect",{x:s,y:p,width:d,height:l-p,fill:a?"var(--semiotic-danger, #e15759)":"var(--semiotic-primary, #4e79a7)",fillOpacity:a?.08:.06,stroke:"var(--semiotic-border, #d1d5db)",strokeOpacity:.68,strokeWidth:1}),a?e.lidSegments.filter(t=>t.windowIndex===r).map(t=>_("line",{x1:t.x1,x2:t.x2,y1:t.y1,y2:t.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.78,strokeWidth:2,strokeLinecap:"round"},t.id)):null,Y("text",{x:s+d/2,y:p-8,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:[n?.value??0,u?` / ${u} late`:""]}),_("text",{x:s+d/2,y:Math.min(i[1]-8,l+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:n?.label??""})]},"window-"+r)}),e.lidSegments.filter(t=>null==t.windowIndex).map(t=>_("line",{x1:t.x1,x2:t.x2,y1:t.y1,y2:t.y2,stroke:"var(--semiotic-danger, #e15759)",strokeOpacity:.62,strokeWidth:2,strokeLinecap:"round"},t.id)),_("line",{x1:s.x,x2:s.x+s.width,y1:l,y2:l,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1.5}),_("line",{"data-testid":"event-drop-watermark",x1:f,x2:f,y1:s.y+8,y2:l,stroke:"var(--semiotic-warning, #f28e2b)",strokeDasharray:"5 4",strokeWidth:2}),Y("text",{x:Math.min(s.x+s.width-4,f+6),y:s.y+16,fill:"var(--semiotic-warning, #f28e2b)",fontSize:10,fontWeight:700,children:["watermark ",Math.round(100*e.watermarkValue)/100]}),e.lateCount>0?Y("text",{x:a.x+a.width/2,y:s.y+32,textAnchor:"middle",fill:"var(--semiotic-danger, #e15759)",fontSize:10,fontWeight:700,children:[e.lateCount," late"]}):null]})}}(et.projectionRows,et.metadata,T),ut=v(e.tooltip,p),pt=g(e,p,st,{selection:at,chartMode:q,className:G,title:X,description:K,summary:Q,accessibleTable:Z,enableHover:V,margin:U});return f("EventDropChart",L,F(t,{...p,...ut,...pt,ref:J,onBodyHover:ct,key:ot.rerunKey,config:ot.config,foregroundGraphics:a(lt,p?.foregroundGraphics),initialSpawns:et.initialSpawns,initialSpawnPacing:et.initialSpawnPacing,paused:A,responsiveHeight:j,responsiveWidth:C,size:L,bodyStyle:nt}))});import{forwardRef as T,useCallback as G,useMemo as X,useRef as q}from"react";import{jsx as U,jsxs as V}from"react/jsx-runtime";import{createElement as K}from"react";var Q=T(function(e,o){const{ballRadius:i=8,categoryAccessor:r="category",colorBy:s,data:c,emptyContent:d,frameProps:h,loading:M,loadingContent:S,mechanicalCategories:A,mechanicalCount:$,paused:j,rerunMS:C,responsiveHeight:R,responsiveWidth:P,seed:B=1,unitValue:N=1,valueAccessor:O,styleRules:E}=e,W=x(e,[700,380],{hasSimulationMode:!0}),{chartSize:H,simulationMode:z,showProjection:D,className:_,title:Y,chartMode:F,margin:L,enableHover:T,description:Q,summary:Z,accessibleTable:J}=W,tt=q(null),et="mechanical"===z&&null==O?"value":O,ot=X(()=>"mechanical"===z?l({categories:A,count:$,seed:B,unitValue:N}):c??[],[c,A,$,B,z,N]),it=X(()=>n({data:ot,categoryAccessor:r,valueAccessor:et,unitValue:N,ballRadius:i,seed:B,size:H}),[i,r,H,ot,et,B,N]),rt=w(it.config,C,j),nt=G((t,e)=>{const o=n({data:[t],categoryAccessor:r,valueAccessor:et,unitValue:N,ballRadius:i,seed:B+e+1,size:H}),s={id:(t.id??"pile-push-"+e)+"",x:u(H).plot.x,y:u(H).plot.y,mass:1,shape:{type:"circle",radius:i},datum:t},a=o.initialSpawns.length?o.initialSpawns:[s];return{datumId:(t.id??a[0].id)+"",spawns:a}},[i,r,H,et,B,N]);I(o,{frameRef:tt,spawnDatum:nt,seedRows:ot,seedSpawns:it.initialSpawns});const st="mechanical"===z&&null==s?"category":s,at=X(()=>b(st,"#4e79a7",{styleRules:E,valueAccessor:O}),[st,E,O]),ct=X(()=>m(it.projectionRows,H,"category"),[H,it.projectionRows]),{selection:dt,onBodyHover:lt}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:s,chartType:"UnitPileChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover,fallbackFields:"string"==typeof r?[r]:void 0}),ut=y({data:"mechanical"===z?ot:c,emptyContent:d,loading:M,loadingContent:S,size:H});if(ut)return ut;const pt=function(t,e,o){if(!1!==o&&0!==t.length)return({size:o})=>{const i=[Number(o[0])||700,Number(o[1])||380],r=u(i),n=p(r.plot,t.length,e),s=r.plot.y+r.plot.height;return V("svg",{"aria-hidden":"true","data-testid":"physics-pile-projection-overlay",width:i[0],height:i[1],viewBox:`0 0 ${i[0]} ${i[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[U("line",{x1:r.plot.x,x2:r.plot.x+r.plot.width,y1:s,y2:s,stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:1}),t.map((t,e)=>{const o=Math.min(r.plot.height,n.pileHeight(t.value)),a=n.tubeWidth,c=n.centerX(e),d=s-o;return V("g",{children:[U("rect",{x:c-a/2,y:d,width:a,height:o,rx:3,fill:"var(--semiotic-primary, #4e79a7)",fillOpacity:.08,stroke:"var(--semiotic-primary, #4e79a7)",strokeOpacity:.42,strokeWidth:1,strokeDasharray:"4 3"}),U("text",{x:c,y:Math.max(r.plot.y+12,d-6),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:11,fontWeight:700,children:t.value}),U("text",{x:c,y:Math.min(i[1]-8,s+16),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:t.label})]},`${t.label}-${e}`)})]})}}(it.projectionRows,i,D),ht=v(e.tooltip,h),mt=g(e,h,ct,{selection:dt,chartMode:F,className:_,title:Y,description:Q,summary:Z,accessibleTable:J,enableHover:T,margin:L});return f("UnitPileChart",H,K(t,{...h,...ht,...mt,ref:tt,onBodyHover:lt,key:rt.rerunKey,config:rt.config,foregroundGraphics:a(pt,h?.foregroundGraphics),initialSpawns:it.initialSpawns,initialSpawnPacing:it.initialSpawnPacing,paused:j,responsiveHeight:R,responsiveWidth:P,size:H,bodyStyle:at}))}),Z=Q;import{forwardRef as J,useCallback as tt,useMemo as et,useRef as ot}from"react";import{jsx as it,jsxs as rt}from"react/jsx-runtime";function nt(t){return t.toLocaleString(void 0,Math.abs(t)>=1e3||.01>Math.abs(t)?{maximumFractionDigits:0}:{maximumFractionDigits:2})}var st=J(function(o,i){const{colorBy:r,styleRules:n,collisionIterations:s,data:c,emptyContent:d,frameProps:l,groupAccessor:p,loading:h,loadingContent:m,paused:M,pointRadius:S,radiusAccessor:A,rerunMS:$,responsiveHeight:j,responsiveWidth:C,seed:R=1,settle:P,xAccessor:B="x",xExtent:N}=o,O=x(o,[700,360]),{chartSize:E,showProjection:W,className:H,title:z,chartMode:D,margin:_,enableHover:Y,description:F,summary:L,accessibleTable:T}=O,G=S??("sparkline"===D?2:"context"===D?4:5),X=ot(null),q=et(()=>c??[],[c]),U=et(()=>e({data:q,xAccessor:B,groupAccessor:p,radiusAccessor:A,pointRadius:G,seed:R,size:E,xExtent:N,collisionIterations:s,settle:P}),[q,E,s,p,G,A,R,P,B,N]),V=w(U.config,$,M),K=tt((t,o)=>{const i=e({data:[t],xAccessor:B,groupAccessor:p,radiusAccessor:A,pointRadius:G,seed:R+o+1,size:E,xExtent:N,collisionIterations:s,settle:P}).initialSpawns[0]??{id:(t.id??"collision-swarm-push-"+o)+"",x:u(E).plot.x,y:u(E).plot.y,mass:1,shape:{type:"circle",radius:G},datum:t};return{datumId:(t.id??i.id)+"",spawns:[i]}},[E,s,p,G,A,R,P,B,N]);I(i,{frameRef:X,spawnDatum:K,seedRows:q,seedSpawns:U.initialSpawns});const Q=r??p,Z=et(()=>b(Q,"#4e79a7",{styleRules:n,valueAccessor:B}),[Q,n,B]),{selection:J,onBodyHover:st}=k({selection:o.selection,linkedHover:o.linkedHover,colorBy:Q,chartType:"CollisionSwarmChart",chartId:o.chartId,onObservation:o.onObservation,onClick:o.onClick,onBodyHover:l?.onBodyHover,fallbackFields:"string"==typeof B?[B]:void 0}),at=y({data:c,emptyContent:d,loading:h,loadingContent:m,size:E});if(at)return at;const ct=function(t,e){if(!1!==e&&t)return({size:e})=>{const o=[Number(e[0])||700,Number(e[1])||360],i=u(o),r=i.plot.y+i.plot.height,[n,s]=t.xExtent,a=n+(s-n)/2,c=[{label:nt(n),x:t.xRange[0]},{label:nt(a),x:t.xRange[0]+(t.xRange[1]-t.xRange[0])/2},{label:nt(s),x:t.xRange[1]}];return rt("svg",{"aria-hidden":"true","data-testid":"collision-swarm-projection-overlay",width:o[0],height:o[1],viewBox:`0 0 ${o[0]} ${o[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[t.groups.map(t=>rt("g",{children:[it("line",{x1:i.plot.x,x2:i.plot.x+i.plot.width,y1:t.y,y2:t.y,stroke:"var(--semiotic-border, #d1d5db)",strokeDasharray:"3 5",strokeWidth:1}),it("text",{x:i.plot.x+4,y:t.y-7,fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:t.label}),rt("text",{x:i.plot.x+i.plot.width-4,y:t.y-7,textAnchor:"end",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:["n=",t.count]})]},t.label)),it("line",{x1:t.xRange[0],x2:t.xRange[1],y1:r,y2:r,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),c.map(t=>rt("g",{children:[it("line",{x1:t.x,x2:t.x,y1:r,y2:r+5,stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1}),it("text",{x:t.x,y:Math.min(o[1]-8,r+18),textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,children:t.label})]},`${t.label}-${t.x}`))]})}}(U.metadata,W),dt=function(t){if(!t)return[];const e=Math.max(24,t.xRange[1]-t.xRange[0]),o=t.xRange[0]+e/2;return t.groups.map(t=>{const i=`${t.label} lane: ${t.count} points`;return{id:"collision-swarm-"+t.label,label:i,description:i,datum:t,x:o,y:t.y,shape:"rect",width:e,height:28,group:"lane"}})}(U.metadata),lt=v(o.tooltip,l),ut=g(o,l,dt,{selection:J,chartMode:D,className:H,title:z,description:F,summary:L,accessibleTable:T,enableHover:Y,margin:_});return f("CollisionSwarmChart",E,it(t,{...l,...lt,...ut,ref:X,onBodyHover:st,config:V.config,foregroundGraphics:a(ct,l?.foregroundGraphics),initialSpawns:U.initialSpawns,paused:M,responsiveHeight:j,responsiveWidth:C,size:E,bodyStyle:Z},V.rerunKey))}),at=1e-9;function ct(t,e){return e>t?-1:t>e?1:0}function dt(t){return{...t}}function lt(t){return t.map(t=>({...t,sourceIds:t.sourceIds?[...t.sourceIds]:void 0,productIds:t.productIds?[...t.productIds]:void 0,relationIds:t.relationIds?[...t.relationIds]:void 0,outletIds:t.outletIds?[...t.outletIds]:void 0}))}function ut(t){const e=Object.fromEntries(Object.entries(t.components).map(([t,e])=>[t,{...e,initialMetrics:dt(e.initialMetrics),metrics:dt(e.metrics),productIds:[...e.productIds],history:lt(e.history)}])),o=Object.fromEntries(Object.entries(t.products).map(([t,e])=>[t,{...e,metrics:dt(e.metrics),sourceIds:[...e.sourceIds],history:lt(e.history)}])),i=Object.fromEntries(Object.entries(t.relations).map(([t,e])=>[t,{...e,sourceIds:[...e.sourceIds],metrics:e.metrics?dt(e.metrics):void 0}]));return{...t,eventsApplied:[...t.eventsApplied],components:e,products:o,relations:i,input:{amount:t.input.amount,metrics:dt(t.input.metrics)},metrics:dt(t.metrics),loss:{amount:t.loss.amount,metrics:dt(t.loss.metrics)},history:lt(t.history)}}function pt(t,e,o,i,r){return{severity:t,code:e,message:o,path:i,ids:r?[...r]:void 0}}function ht(t){const e=new Set,o=new Set;for(const i of t)e.has(i)&&o.add(i),e.add(i);return[...o].sort(ct)}function mt(t,e){return t?Object.entries(t).flatMap(([t,o])=>Number.isFinite(o)?[]:[pt("error","invalid-metric",`Metric "${t}" must be a finite number.`,`${e}.${t}`)]):[]}function yt(t,e){for(const[o,i]of Object.entries(e))t[o]=Number(t[o]??0)+i}function ft(t,e,o="selector"){const i=[],r=Object.values(t.components),n=new Set(r.map(t=>t.id)),s=(e.ids??[]).filter(t=>!n.has(t));if(s.length&&i.push(pt("error","unknown-component",`Selector references unknown component id${1===s.length?"":"s"}: ${s.join(", ")}.`,o+".ids",s)),void 0===e.count||Number.isInteger(e.count)&&e.count>=0||i.push(pt("error","invalid-selector-count","Selector count must be a non-negative integer.",o+".count")),i.some(t=>"error"===t.severity))return{ids:[],diagnostics:i};const a=e.ids?new Set(e.ids):null,c=e.categories?new Set(e.categories):null,d=e.statuses?new Set(e.statuses):null,l=e.outletIds?new Set(e.outletIds):null;let u=r.filter(t=>!a||a.has(t.id)).filter(t=>!c||c.has(t.category)).filter(t=>!d||d.has(t.status)).filter(t=>!l||void 0!==t.outletId&&l.has(t.outletId)).map(t=>t.id).sort(ct);return void 0!==e.count&&(u=u.slice(0,e.count)),u.length||i.push(pt("warning","empty-selector","Selector matched no source components.",o)),{ids:u,diagnostics:i}}function gt(t,e,o={}){return{eventId:t.event.id,effectType:e.type,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt,label:t.event.label,summary:t.event.summary,...o}}function vt(t,e){const o={...e,eventId:t.event.id};t.materializations.push(o),t.observations.push({...o,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt})}function bt(t,e,o){return!(void 0!==e&&!t.outletIds.has(e)&&(t.diagnostics.push(pt("error","unknown-outlet",`Unknown outlet "${e}".`,o,[e])),1))}function xt(t,e,o){const i=ht(e);e.length||t.diagnostics.push(pt("error","empty-source-list","A product requires at least one source component.",o)),i.length&&t.diagnostics.push(pt("error","duplicate-source",`Source ids may appear only once: ${i.join(", ")}.`,o,i));const r=e.filter(e=>!t.state.components[e]);r.length&&t.diagnostics.push(pt("error","unknown-component",`Unknown source component id${1===r.length?"":"s"}: ${r.join(", ")}.`,o,r));const n=e.filter(e=>(t.state.components[e]?.productIds.length??0)>0);n.length&&t.diagnostics.push(pt("error","source-already-assigned",`Source component${1===n.length?" is":"s are"} already assigned: ${n.join(", ")}.`,o,n));const s=e.filter(e=>"consumed"===t.state.components[e]?.status&&!n.includes(e));return s.length&&t.diagnostics.push(pt("error","source-unavailable",`Consumed source component${1===s.length?" is":"s are"} unavailable: ${s.join(", ")}.`,o,s)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.components[e])}function It(t,e,o,i,r){const n=i?.amount??0;(!Number.isFinite(n)||0>n||n>e+at)&&t.diagnostics.push(pt("error","invalid-loss","Loss amount must be finite, non-negative, and no greater than its sources.",r+".amount")),t.diagnostics.push(...mt(i?.metrics,r+".metrics"));for(const[e,n]of Object.entries(i?.metrics??{}))(0>n||n>Number(o[e]??0)+at)&&t.diagnostics.push(pt("error","invalid-metric-loss",`Metric loss "${e}" must be non-negative and no greater than its sources.`,`${r}.metrics.${e}`));return!t.diagnostics.some(t=>"error"===t.severity)}function wt(t,e,o,i,r,n,s){return{id:t.id,label:t.label??t.id,description:t.description,category:t.category??"product",color:t.color,order:t.order,declaredAmount:t.amount,amount:n&&void 0!==t.amount?t.amount:o,metrics:n&&t.metrics?{...i,...t.metrics}:i,status:n?"complete":"forming",sourceIds:[...e],outletId:n?t.outletId??(r.outletIds.has("product")?"product":void 0):void 0,createdByEventId:r.event.id,createdAt:r.context.appliedAt,completedByEventId:n?r.event.id:void 0,completedAt:n?r.context.appliedAt:void 0,history:[s]}}function kt(t,e,o,i){void 0!==e.amount&&Math.abs(e.amount-o)>at&&t.diagnostics.push(pt("warning","declared-product-amount-mismatch",`Product "${e.id}" declares ${e.amount}, while its sources yield ${o}.`,i,[e.id]))}function Mt(t,e,o){const i=`events.${t.event.id}.effects.${o}`,r=t.state;if("set-state"===e.type){["queued","active","transformed","retained","ejected","failed","recovered"].includes(e.state)||t.diagnostics.push(pt("error","invalid-component-state",`set-state cannot assign "${e.state+""}".`,i+".state")),t.diagnostics.push(...mt(e.metricsDelta,i+".metricsDelta")),bt(t,e.outletId,i+".outletId");const o=ft(r,e.select,i+".select");t.diagnostics.push(...o.diagnostics);const n=o.ids.filter(t=>r.components[t].productIds.length);if(n.length&&t.diagnostics.push(pt("error","source-already-assigned",`Assigned source components cannot be retargeted: ${n.join(", ")}.`,i+".select",n)),t.diagnostics.some(t=>"error"===t.severity))return;const s=gt(t,e,{sourceIds:o.ids,outletIds:e.outletId?[e.outletId]:void 0});for(const t of o.ids){const o=r.components[t];o.status=e.state,o.outletId=e.outletId,o.reason=e.reason,e.metricsDelta&&yt(o.metrics,e.metricsDelta),o.history.push(s)}return r.history.push(s),void(o.ids.length&&vt(t,{type:"retarget-component",sourceIds:o.ids,outletIds:e.outletId?[e.outletId]:void 0}))}if("set-relation"===e.type){const{relation:o}=e;o.id&&!r.relations[o.id]||t.diagnostics.push(pt("error","duplicate-relation",`Relation id "${o.id}" is missing or already active.`,i+".relation.id",[o.id]));const n=function(t,e,o){const i=ht(e),r=e.filter(e=>!t.state.components[e]);return 2>e.length&&t.diagnostics.push(pt("error","insufficient-relation-sources","A relation requires at least two source components.",o)),i.length&&t.diagnostics.push(pt("error","duplicate-source",`Relation source ids must be unique: ${i.join(", ")}.`,o,i)),r.length&&t.diagnostics.push(pt("error","unknown-component",`Relation references unknown source component${1===r.length?"":"s"}: ${r.join(", ")}.`,o,r)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.components[e])}(t,o.sourceIds,i+".relation.sourceIds");if(t.diagnostics.push(...mt(o.metrics,i+".relation.metrics")),!n||t.diagnostics.some(t=>"error"===t.severity))return;r.relations[o.id]={...o,sourceIds:[...o.sourceIds],metrics:o.metrics?{...o.metrics}:void 0,status:"active",createdByEventId:t.event.id,createdAt:t.context.appliedAt};const s=gt(t,e,{sourceIds:[...o.sourceIds],relationIds:[o.id]});return r.history.push(s),void vt(t,{type:"activate-relation",sourceIds:[...o.sourceIds],relationIds:[o.id]})}if("resolve-relation"===e.type){const o=ht(e.relationIds),n=e.relationIds.filter(t=>!r.relations[t]),s=e.relationIds.filter(t=>"resolved"===r.relations[t]?.status);if(o.length&&t.diagnostics.push(pt("error","duplicate-relation","Relation ids must be unique.",i+".relationIds",o)),n.length&&t.diagnostics.push(pt("error","unknown-relation",`Unknown relation: ${n.join(", ")}.`,i+".relationIds",n)),s.length&&t.diagnostics.push(pt("error","resolved-relation",`Relation is already resolved: ${s.join(", ")}.`,i+".relationIds",s)),t.diagnostics.some(t=>"error"===t.severity))return;for(const o of e.relationIds){const i=r.relations[o];i.status="resolved",i.resolution=e.resolution,i.resolvedByEventId=t.event.id,i.resolvedAt=t.context.appliedAt,i.reason=e.reason}const a=gt(t,e,{relationIds:[...e.relationIds]});return r.history.push(a),void vt(t,{type:"resolve-relation",relationIds:[...e.relationIds]})}if("combine"===e.type||"contribute"===e.type){const o=t.productDefinitions.get(e.productId);o||t.diagnostics.push(pt("error","unknown-product",`Product "${e.productId}" has no declared mold.`,i+".productId",[e.productId]));const n=r.products[e.productId];"combine"===e.type&&n&&t.diagnostics.push(pt("error","duplicate-product",`Product "${e.productId}" has already been formed.`,i+".productId",[e.productId])),"contribute"!==e.type||n&&"forming"===n.status||t.diagnostics.push(pt("error","product-not-forming",`Contributions require an existing forming product "${e.productId}".`,i+".productId",[e.productId]));const s=xt(t,e.sourceIds,i+".sourceIds"),a="contribute"===e.type&&n?[...n.sourceIds,...e.sourceIds]:e.sourceIds,c=function(t,e,o,i){if(!e?.length)return[];const r=ht(e),n=e.filter(e=>!t.state.relations[e]),s=e.filter(e=>"resolved"===t.state.relations[e]?.status),a=new Set(o),c=e.filter(e=>(t.state.relations[e]?.sourceIds??[]).some(t=>!a.has(t)));return r.length&&t.diagnostics.push(pt("error","duplicate-relation","Basis relations must be unique.",i,r)),n.length&&t.diagnostics.push(pt("error","unknown-relation",`Unknown basis relation: ${n.join(", ")}.`,i,n)),s.length&&t.diagnostics.push(pt("error","resolved-relation",`Basis relation is already resolved: ${s.join(", ")}.`,i,s)),c.length&&t.diagnostics.push(pt("error","relation-source-mismatch",`Basis relation includes a source outside this product: ${c.join(", ")}.`,i,c)),t.diagnostics.some(t=>"error"===t.severity)?null:e.map(e=>t.state.relations[e])}(t,e.basisRelationIds,a,i+".basisRelationIds");if(!s||!c||!o||t.diagnostics.some(t=>"error"===t.severity))return;const d=s.reduce((t,e)=>t+e.amount,0),l=function(t){const e={};for(const o of t)yt(e,o.metrics);return e}(s);if(!It(t,d,l,e.loss,i+".loss"))return;const u=d-(e.loss?.amount??0);!function(t,e,o){t.state.loss.amount+=o?.amount??0;for(const[i,r]of Object.entries(o?.metrics??{}))e[i]=Number(e[i]??0)-r,t.state.loss.metrics[i]=Number(t.state.loss.metrics[i]??0)+r}(t,l,e.loss);const p="combine"===e.type&&!1!==e.complete,h=gt(t,e,{sourceIds:[...e.sourceIds],productIds:[e.productId],relationIds:e.basisRelationIds?[...e.basisRelationIds]:void 0});let m;if("combine"===e.type){if(p&&kt(t,o,u,i+".productId"),m=wt(o,e.sourceIds,u,l,t,p,h),p&&!bt(t,m.outletId,i+".productId"))return;r.products[e.productId]=m}else m=n,m.sourceIds.push(...e.sourceIds),m.amount+=u,yt(m.metrics,l),m.history.push(h);for(const t of s)t.productIds=[e.productId],t.status="consumed",t.outletId=void 0,t.history.push(h);return r.history.push(h),function(t,e){if(e.length){for(const o of e)o.status="resolved",o.resolution="combined",o.resolvedByEventId=t.event.id,o.resolvedAt=t.context.appliedAt;vt(t,{type:"resolve-relation",relationIds:e.map(t=>t.id)})}}(t,c),vt(t,{type:"combine"===e.type?"form-product":"update-product",sourceIds:[...e.sourceIds],productIds:[e.productId],relationIds:e.basisRelationIds?[...e.basisRelationIds]:void 0,outletIds:m.outletId?[m.outletId]:void 0}),void(p&&vt(t,{type:"complete-product",sourceIds:[...m.sourceIds],productIds:[m.id],outletIds:m.outletId?[m.outletId]:void 0}))}if("complete-product"===e.type){const o=r.products[e.productId];return o?void function(t,e,o,i,r,n){const s=t.productDefinitions.get(e.id),a=o??s?.outletId??(t.outletIds.has("product")?"product":void 0);if(!bt(t,a,n+".outletId"))return;if("complete"===e.status)return void t.diagnostics.push(pt("error","product-already-complete",`Product "${e.id}" is already complete.`,n,[e.id]));s&&(kt(t,s,e.amount,n+".productId"),void 0!==s.amount&&(e.amount=s.amount),s.metrics&&(e.metrics={...e.metrics,...s.metrics})),e.status="complete",e.outletId=a,e.reason=i,e.completedByEventId=t.event.id,e.completedAt=t.context.appliedAt;const c=gt(t,r,{sourceIds:[...e.sourceIds],productIds:[e.id],outletIds:a?[a]:void 0});e.history.push(c),t.state.history.push(c),vt(t,{type:"complete-product",sourceIds:[...e.sourceIds],productIds:[e.id],outletIds:a?[a]:void 0})}(t,o,e.outletId,e.reason,e,i):void t.diagnostics.push(pt("error","unknown-product-state",`Product "${e.productId}" has not been formed.`,i+".productId",[e.productId]))}if("split"===e.type){const o=xt(t,[e.sourceId],i+".sourceId");e.products.length||t.diagnostics.push(pt("error","empty-split","A split requires at least one product allocation.",i+".products"));const n=e.products.map(t=>t.productId),s=ht(n);s.length&&t.diagnostics.push(pt("error","duplicate-product","Split product ids must be unique.",i+".products",s));const a=n.map(e=>t.productDefinitions.get(e)),c=n.filter((t,e)=>!a[e]),d=n.filter(t=>r.products[t]);c.length&&t.diagnostics.push(pt("error","unknown-product",`Split references undeclared product molds: ${c.join(", ")}.`,i+".products",c)),d.length&&t.diagnostics.push(pt("error","duplicate-product",`Split products already exist: ${d.join(", ")}.`,i+".products",d));for(const[o,r]of e.products.entries())void 0===r.amount||Number.isFinite(r.amount)&&r.amount>=0||t.diagnostics.push(pt("error","invalid-product-amount","Split allocation amounts must be finite and non-negative.",`${i}.products.${o}.amount`)),t.diagnostics.push(...mt(r.metrics,`${i}.products.${o}.metrics`));if(!o?.length||t.diagnostics.some(t=>"error"===t.severity))return;const l=o[0];if(!It(t,l.amount,l.metrics,e.loss,i+".loss"))return;const u=l.amount-(e.loss?.amount??0),p=e.products.map((t,e)=>t.amount??a[e]?.amount),h=p.filter(t=>void 0!==t).length;if(0!==h&&h!==p.length)return void t.diagnostics.push(pt("error","partial-split-allocation","Either every split product must declare an amount or none may do so.",i+".products"));const m=h?p:e.products.map(()=>u/e.products.length),y=m.reduce((t,e)=>t+e,0);if(Math.abs(y-u)>at)return void t.diagnostics.push(pt("error","split-amount-mismatch",`Split allocations total ${y}, but ${u} remains after loss.`,i+".products"));const f={...l.metrics};for(const[t,o]of Object.entries(e.loss?.metrics??{}))f[t]=Number(f[t]??0)-o;const g=gt(t,e,{sourceIds:[l.id],productIds:n});if(e.products.forEach((o,n)=>{const s=a[n],c=u>at?m[n]/u:1/e.products.length,d=Object.fromEntries(Object.entries(f).map(([t,e])=>[t,e*c])),p=o.metrics??s.metrics??d,h=wt({...s,amount:m[n],metrics:p},[l.id],m[n],{...p},t,!0,g);bt(t,h.outletId,`${i}.products.${n}.productId`)&&(r.products[h.id]=h)}),t.diagnostics.some(t=>"error"===t.severity))return;l.productIds=n,l.status="consumed",l.outletId=void 0,l.history.push(g),r.loss.amount+=e.loss?.amount??0;for(const[t,o]of Object.entries(e.loss?.metrics??{}))r.loss.metrics[t]=Number(r.loss.metrics[t]??0)+o;r.history.push(g),vt(t,{type:"split-source",sourceIds:[l.id],productIds:n});for(const e of n)vt(t,{type:"complete-product",sourceIds:[l.id],productIds:[e],outletIds:r.products[e].outletId?[r.products[e].outletId]:void 0});return}if("eject"===e.type){bt(t,e.outletId,i+".outletId");const o=ft(r,e.select,i+".select");t.diagnostics.push(...o.diagnostics);const n=o.ids.filter(t=>r.components[t].productIds.length);if(n.length&&t.diagnostics.push(pt("error","source-already-assigned",`Assigned source components cannot be ejected: ${n.join(", ")}.`,i+".select",n)),t.diagnostics.some(t=>"error"===t.severity))return;const s=gt(t,e,{sourceIds:o.ids,outletIds:[e.outletId]});for(const t of o.ids){const o=r.components[t];o.status=e.state??"ejected",o.outletId=e.outletId,o.reason=e.reason,o.history.push(s)}return r.history.push(s),void(o.ids.length&&vt(t,{type:"retarget-component",sourceIds:o.ids,outletIds:[e.outletId]}))}if("set-metric"===e.type){if(t.diagnostics.push(...mt(e.metricsDelta,i+".metricsDelta")),t.diagnostics.some(t=>"error"===t.severity))return;let o,n;if("run"===e.target)yt(r.metrics,e.metricsDelta);else if("components"in e.target){const n=ft(r,e.target.components,i+".target.components");if(t.diagnostics.push(...n.diagnostics),t.diagnostics.some(t=>"error"===t.severity))return;o=n.ids;for(const t of n.ids)yt(r.components[t].metrics,e.metricsDelta)}else{n=[...e.target.productIds];const o=ht(n),s=n.filter(t=>!r.products[t]);if(o.length&&t.diagnostics.push(pt("error","duplicate-product","Metric target product ids must be unique.",i+".target.productIds",o)),s.length&&t.diagnostics.push(pt("error","unknown-product-state",`Metric target product has not formed: ${s.join(", ")}.`,i+".target.productIds",s)),t.diagnostics.some(t=>"error"===t.severity))return;for(const t of n)yt(r.products[t].metrics,e.metricsDelta)}return void r.history.push(gt(t,e,{sourceIds:o,productIds:n}))}e.outcome.trim()?(r.outcome=e.outcome,r.summary=e.summary,r.history.push(gt(t,e)),t.observations.push({type:"crucible-outcome",eventId:t.event.id,phaseId:t.context.phaseId,authoredAt:t.context.authoredAt,appliedAt:t.context.appliedAt,outcome:e.outcome})):t.diagnostics.push(pt("error","invalid-outcome","Outcome must be a non-empty string.",i+".outcome"))}function St(t,e,o){if(t.eventsApplied.includes(e.id))return{applied:!1,state:t,materializations:[],observations:[],diagnostics:[pt("warning","duplicate-event-application",`Event "${e.id}" has already been applied.`,"events."+e.id,[e.id])]};const i=ut(t),r={state:i,event:e,context:o,productDefinitions:new Map(o.products.map(t=>[t.id,t])),outletIds:new Set(o.outlets.map(t=>t.id)),diagnostics:[],materializations:[],observations:[]};for(const[o,i]of e.effects.entries())if(Mt(r,i,o),r.diagnostics.some(t=>"error"===t.severity))return{applied:!1,state:t,materializations:[],observations:[],diagnostics:r.diagnostics};return i.elapsed=Math.max(i.elapsed,o.appliedAt),i.phaseId=o.phaseId,i.eventsApplied.push(e.id),r.observations.unshift({type:"crucible-event",eventId:e.id,phaseId:o.phaseId,authoredAt:o.authoredAt,appliedAt:o.appliedAt}),{applied:!0,state:i,materializations:r.materializations,observations:r.observations,diagnostics:r.diagnostics}}function At(t,e={}){const o=e.groupBy??"outlet",i=new Map,r=t=>{const e=function(t,e){return"product"===e?"product"===t.kind?t.id:"unassigned":"outlet"===e?t.outletId??"unassigned":"category"===e?t.category:t.status}({...t,status:t.status??"active"},o),r=i.get(e);if(r)return r.count+=1,r.amount+=t.amount,void yt(r.metrics,t.metrics);i.set(e,{key:e,label:"product"===o&&"product"===t.kind?t.label:e,count:1,amount:t.amount,metrics:{...t.metrics},status:"status"===o?t.status:void 0,outletId:"outlet"===o?t.outletId:void 0,category:"category"===o?t.category:void 0,productId:"product"===o&&"product"===t.kind?t.id:void 0})};for(const e of Object.values(t.components))e.productIds.length||"consumed"===e.status||r({kind:"component",id:e.id,label:e.label,status:e.status,outletId:e.outletId,category:e.category,amount:e.amount,metrics:e.metrics});for(const e of Object.values(t.products))r({kind:"product",id:e.id,label:e.label,status:e.status,outletId:e.outletId,category:e.category,amount:e.amount,metrics:e.metrics});const n=new Map((e.order??[]).map((t,e)=>[t,e]));return[...i.values()].sort((t,e)=>(n.get(t.key)??Number.MAX_SAFE_INTEGER)-(n.get(e.key)??Number.MAX_SAFE_INTEGER)||ct(t.key,e.key))}var $t=At;function jt(t,e={}){const o=e.field??"amount",i=t=>"amount"===o?t.amount:Number(t.metrics[o]??0),r="amount"===o?t.input.amount:Number(t.input.metrics[o]??0),n=Object.values(t.products).reduce((t,e)=>t+i(e),0),s=Object.values(t.components).filter(t=>!t.productIds.length&&"consumed"!==t.status).reduce((t,e)=>t+i(e),0),a="amount"===o?t.loss.amount:Number(t.loss.metrics[o]??0),c=n+s+a,d=c-r;return{field:o,input:r,products:n,unassigned:s,loss:a,output:c,delta:d,conserved:Math.max(0,e.tolerance??1e-6)>=Math.abs(d)}}function Ct(t,e={}){return{history:lt(t.history),projection:At(t,e.projection),conservation:jt(t,e.conservation)}}var Rt=900,Pt=520,Bt=[900,520],Nt=[{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}],Ot=new Set(["queued","active","transformed","consumed","retained","ejected","failed","recovered"]),Et=1e-9;function Wt(t,e){return e>t?-1:t>e?1:0}function Ht(t,e,o,i,r){return{severity:t,code:e,message:o,path:i,ids:r?[...r]:void 0}}function zt(t){const e=new Set,o=new Set;for(const i of t)e.has(i)&&o.add(i),e.add(i);return[...o].sort(Wt)}function Dt(t){const e="number"==typeof t?t:Number(t);return Number.isFinite(e)?e:null}function _t(t,e,o,i,r,n){if(!o)return i;try{return("function"==typeof o?o(t,e):t[o])??i}catch(t){return r.push(Ht("error","accessor-error",`Accessor threw: ${t instanceof Error?t.message:t+""}.`,n)),i}}function Yt(t,e,o){if(!t||"object"!=typeof t||Array.isArray(t))return null!=t&&e.push(Ht("error","invalid-metrics","Metrics must be a numeric object.",o)),{};const i={};for(const[r,n]of Object.entries(t)){const t=Dt(n);null!=t?i[r]=t:e.push(Ht("error","invalid-metric",`Metric "${r}" must be finite.`,`${o}.${r}`))}return i}function Ft(t){const e=[],o={},i=[];let r=0;const n={};t.data.forEach((s,a)=>{const c=(s.id??"component-"+a)+"",d=((_t(s,a,t.idAccessor,c,e,`data.${a}.id`)??c)+"").trim();if(!d)return void e.push(Ht("error","invalid-component-id","Component ids may not be empty.",`data.${a}.id`));i.push(d);const l=Dt(_t(s,a,t.amountAccessor,1,e,`data.${a}.amount`)),u=null==l||0>l?0:l;(null==l||0>l)&&e.push(Ht("error","invalid-component-amount","Component amount must be finite and non-negative.",`data.${a}.amount`,[d]));const p=Yt(_t(s,a,t.metricsAccessor,{},e,`data.${a}.metrics`),e,`data.${a}.metrics`),h=_t(s,a,t.initialStateAccessor,"active",e,`data.${a}.status`),m=Ot.has(h)?h:"active";Ot.has(h)||e.push(Ht("error","invalid-component-status",`Unknown component status "${h+""}".`,`data.${a}.status`,[d]));const y=_t(s,a,t.labelAccessor,(s.label??s.name??d)+"",e,`data.${a}.label`)+"",f=_t(s,a,t.categoryAccessor,"component",e,`data.${a}.category`)+"";o[d]||(o[d]={id:d,label:y,category:f,datum:s,status:m,initialAmount:u,amount:u,initialMetrics:{...p},metrics:{...p},productIds:[],history:[]},r+=u,function(t,e){for(const[o,i]of Object.entries(e))t[o]=Number(t[o]??0)+i}(n,p))});const s=zt(i);s.length&&e.push(Ht("error","duplicate-component-id",`Component ids must be unique: ${s.join(", ")}.`,"data",s));const a=Yt(t.metrics??{},e,"metrics");return{state:{elapsed:0,phaseElapsed:0,phaseId:t.phases[0]?.id??"",phaseIndex:t.phases.length?0:-1,playing:!1,complete:0===t.phases.length,outcome:"in_process",eventsApplied:[],components:o,products:{},relations:{},input:{amount:r,metrics:n},metrics:a,loss:{amount:0,metrics:{}},history:[]},diagnostics:e}}function Lt(t){return t.map((t,e)=>({outlet:t,index:e})).sort((t,e)=>(t.outlet.order??t.index)-(e.outlet.order??e.index)||t.index-e.index).map(({outlet:t})=>({...t}))}function Tt(t=Bt,e=Nt){const o=Math.max(1,Dt(t[0])??900),i=Math.max(1,Dt(t[1])??520),r=360>o||260>i,n=r?Math.max(4,.035*Math.min(o,i)):20,s=r?Math.max(10,.075*i):34,a={x:n,y:n,width:Math.max(1,o-2*n),height:s},c=r?Math.max(16,.14*i):Math.min(78,.16*i),d={x:n,y:i-n-c,width:Math.max(1,o-2*n),height:c},l=r?Math.max(12,.08*o):Math.min(150,.17*o),u=a.y+a.height+(r?12:38),p=d.y-(r?10:34),h={x:l,y:u,width:Math.max(24,o-2*l),height:Math.max(24,p-u)},m=Math.max(18,Math.min(.32*h.width,r?84:180)),y={x:h.x+(h.width-m)/2,y:h.y-(r?10:24),width:m,height:r?12:28},f=Lt(e),g={left:f.filter(t=>"left"===(t.side??"bottom")),right:f.filter(t=>"right"===t.side),bottom:f.filter(t=>"bottom"===(t.side??"bottom"))},v=[],b=(t,e)=>{const i=Math.max(8,l-1.5*n),s=h.height/Math.max(1,e.length);e.forEach((e,a)=>{v.push({...e,side:t,x:"left"===t?n:o-n-i,y:h.y+a*s,width:i,height:Math.max(8,s-(r?2:8))})})};b("left",g.left),b("right",g.right);const x=h.width/Math.max(1,g.bottom.length);return g.bottom.forEach((t,e)=>{v.push({...t,side:"bottom",x:h.x+e*x,y:h.y+h.height+(r?2:7),width:Math.max(8,x-(r?2:8)),height:Math.max(8,d.y-h.y-h.height-(r?4:12))})}),v.sort((t,e)=>f.findIndex(e=>e.id===t.id)-f.findIndex(t=>t.id===e.id)),{width:o,height:i,phaseRail:a,chamber:h,mouth:y,projection:d,outlets:v}}function Gt(t){const{id:e,orientation:o,fixed:i,start:r,end:n,openings:s,thickness:a,friction:c,restitution:d}=t,l=function(t,e,o){const i=o.map(([o,i])=>[Math.max(t,Math.min(o,i)),Math.min(e,Math.max(o,i))]).filter(([t,e])=>e>t+Et).sort((t,e)=>t[0]-e[0]||t[1]-e[1]),r=[];let n=t;for(const[t,e]of i)t>n+Et&&r.push([n,t]),n=Math.max(n,e);return e>n+Et&&r.push([n,e]),r}(r,n,s);return l.map(([t,r],n)=>({id:1===l.length?e:`${e}:${n}`,friction:c,restitution:d,shape:"horizontal"===o?{type:"segment",x1:t,y1:i,x2:r,y2:i,thickness:a}:{type:"segment",x1:i,y1:t,x2:i,y2:r,thickness:a}}))}function Xt(t){const{chamber:e,mouth:o}=t,i=Math.max(2,Math.min(10,.018*Math.min(t.width,t.height))),r=Math.max(e.x,o.x),n=Math.min(e.x+e.width,o.x+o.width),s={left:t.outlets.filter(t=>"left"===t.side),right:t.outlets.filter(t=>"right"===t.side),bottom:t.outlets.filter(t=>"bottom"===t.side)},a=[{id:"crucible:wall:top-left",friction:.42,restitution:.1,shape:{type:"segment",x1:e.x,y1:e.y,x2:r,y2:e.y,thickness:i}},{id:"crucible:wall:top-right",friction:.42,restitution:.1,shape:{type:"segment",x1:n,y1:e.y,x2:e.x+e.width,y2:e.y,thickness:i}}];a.push(...Gt({id:"crucible:wall:left",orientation:"vertical",fixed:e.x,start:e.y,end:e.y+e.height,openings:s.left.map(t=>[t.y,t.y+t.height]),thickness:i,friction:.46,restitution:.12}),...Gt({id:"crucible:wall:right",orientation:"vertical",fixed:e.x+e.width,start:e.y,end:e.y+e.height,openings:s.right.map(t=>[t.y,t.y+t.height]),thickness:i,friction:.46,restitution:.12}),...Gt({id:"crucible:wall:bottom",orientation:"horizontal",fixed:e.y+e.height,start:e.x,end:e.x+e.width,openings:s.bottom.map(t=>[t.x,t.x+t.width]),thickness:i,friction:.5,restitution:.08}));for(const e of t.outlets)a.push({id:"crucible:outlet:"+encodeURIComponent(e.id),sensor:!0,shape:{type:"aabb",x:e.x+e.width/2,y:e.y+e.height/2,width:e.width,height:e.height}});return a}function qt(t){let e=2166136261;for(let o=0;t.length>o;o+=1)e^=t.charCodeAt(o),e=Math.imul(e,16777619);return e>>>0}function Ut(t){return"number"==typeof t&&Number.isFinite(t)?t>>>0:"string"==typeof t?qt(t):1}function Vt(t,e){return{fixedDt:1/120,maxSubsteps:8,settleStepLimit:7200,colliders:e.map(t=>({...t,shape:{...t.shape}})),observation:{chartType:"crucible"},kernel:{seed:Ut(t),gravity:{x:0,y:0},cellSize:42,collisionIterations:6,velocityDamping:.992,restitution:.12,friction:.42,sleepSpeed:4,sleepAfter:.5,maxVelocity:620}}}function Kt(t){return"crucible:component:"+encodeURIComponent(t)}function Qt(t){return"crucible:product:"+encodeURIComponent(t)}function Zt(t,e){return`crucible:bond:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Jt(t,e,o,i){if(void 0!==o&&Number.isFinite(o)&&o>0)return o;const r=Math.min(...e,t),n=Math.max(...e,t);return n-r>Et?i[0]+(i[1]-i[0])*Math.sqrt(Math.max(0,t-r)/(n-r)):(i[0]+i[1])/2}function te(t,e){const o=Math.max(.25,Math.min(1,e.width/900,e.height/520)),i=t?.[0]??7*o,r=t?.[1]??18*o,n=Math.max(1,Math.min(i,r));return[n,Math.max(n,Math.max(i,r))]}function ee(t,e,o={}){const i=Object.values(t.components).sort((t,e)=>Wt(t.id,e.id)),r=i.map(t=>t.amount),n=te(o.radiusRange,e),s=function(t){let e=t>>>0;return()=>{e+=1831565813;let t=e;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296}}(Ut(o.seed)),a=e.mouth.x+e.mouth.width/2,c=e.chamber.y+Math.max(18,.18*e.chamber.height),d=Math.max(4,.28*e.chamber.width),l=Math.max(4,.12*e.chamber.height);return i.map((t,e)=>{const u=e/Math.max(1,i.length)*Math.PI*2+.18*(s()-.5),p=Jt(t.amount,r,o.bodyRadius,n),h={__crucible:!0,kind:"component",semanticId:t.id,sourceDatum:t.datum};return{id:Kt(t.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,p*p*.015),restitution:.12,friction:.4,shape:{type:"circle",radius:p},datum:h}})}function oe(t,e){if(!t)return[];const o=Math.min(t,Math.max(1,Math.ceil(Math.sqrt(t*Math.max(.5,e.width/Math.max(1,e.height)))))),i=Math.max(1,Math.ceil(t/o));return Array.from({length:t},(t,r)=>({x:e.x+e.width/o*(r%o+.5),y:e.y+(Math.floor(r/o)+.5)*(e.height/i)}))}function ie(t){return t.outletId?t.outletId:"failed"===t.status?"failed":"recovered"===t.status?"recovered":"retained"===t.status?"retained":"ejected"===t.status?"residue":void 0}function re(t,e){return t.outlets.find(t=>t.id===e)||{x:t.chamber.x+.18*t.chamber.width,y:t.chamber.y+.2*t.chamber.height,width:.64*t.chamber.width,height:.6*t.chamber.height}}function ne(t,e,o={}){const i=Object.values(t.products).sort((t,e)=>Wt(t.id,e.id)),r=Object.values(t.components).sort((t,e)=>Wt(t.id,e.id)),n=[...r.map(t=>t.amount),...i.map(t=>t.amount)],s=te(o.radiusRange,e),a=function(t,e){const o=new Map;for(const e of t){const t=e.outletId??"__chamber__",i=o.get(t)??[];i.push(e),o.set(t,i)}const i=new Map;for(const[t,r]of o){r.sort((t,e)=>(t.order??Number.MAX_SAFE_INTEGER)-(e.order??Number.MAX_SAFE_INTEGER)||Wt(t.id,e.id));const o=oe(r.length,re(e,"__chamber__"===t?void 0:t));r.forEach((t,e)=>i.set(t.id,o[e]))}return i}(i,e),c=i.map(t=>{const i=a.get(t.id)??{x:e.chamber.x+e.chamber.width/2,y:e.chamber.y+e.chamber.height/2},r=1.28*Jt(t.amount,n,o.bodyRadius,s),c={__crucible:!0,kind:"product",semanticId:t.id,product:t};return{id:Qt(t.id),x:i.x,y:i.y,mass:Math.max(.25,r*r*.018),bodyCollisions:!1,shape:{type:"circle",radius:r},datum:c}}),d=new Map;for(const t of r.filter(t=>!t.productIds.length)){const e=ie(t)??"__chamber__",o=d.get(e)??[];o.push(t),d.set(e,o)}const l=new Map;for(const[t,o]of d){const i=oe(o.length,re(e,"__chamber__"===t?void 0:t));o.forEach((t,e)=>l.set(t.id,i[e]))}return[...r.map(t=>{let i=l.get(t.id);if(t.productIds.length){const o=t.productIds.map(t=>a.get(t)).filter(t=>!!t);if(o.length){i={x:o.reduce((t,e)=>t+e.x,0)/o.length,y:o.reduce((t,e)=>t+e.y,0)/o.length};const r=qt(t.id)/4294967295*Math.PI*2,n=Math.min(20,Math.max(4,.012*e.width));i={x:i.x+Math.cos(r)*n,y:i.y+Math.sin(r)*n}}}i??(i={x:e.chamber.x+e.chamber.width/2,y:e.chamber.y+e.chamber.height/2});const r=Jt(t.amount,n,o.bodyRadius,s),c={__crucible:!0,kind:"component",semanticId:t.id,sourceDatum:t.datum};return{id:Kt(t.id),x:i.x,y:i.y,mass:Math.max(.25,r*r*.015),shape:{type:"circle",radius:r},datum:c}}),...c]}var se=ne;function ae(t){return Array.isArray(t)?t.map(ae):t&&"object"==typeof t?Object.fromEntries(Object.entries(t).filter(([,t])=>void 0!==t&&"function"!=typeof t).sort(([t],[e])=>Wt(t,e)).map(([t,e])=>[t,ae(e)])):t}function ce(t){return JSON.stringify(ae(t))}function de(t,e){const o=Dt(e)??0,i=Math.max(0,Math.min(t.duration,o));if(!t.phases.length)return{elapsed:i,phaseId:"",phaseIndex:-1,phaseElapsed:0,complete:!0};const r=i>=t.duration-Et,n=r?t.phases[t.phases.length-1]:t.phases.find(t=>i>=t.start&&t.end>i)??t.phases[0];return{elapsed:i,phaseId:n.id,phaseIndex:n.index,phaseElapsed:r?n.duration:Math.max(0,i-n.start),complete:r}}function le(t,e){if(void 0===e)return t.duration;if("number"==typeof e)return Math.max(0,Math.min(t.duration,Dt(e)??0));const o=t.phases.find(t=>t.id===e.phaseId);if(!o)return t.duration;const i=Math.max(0,Math.min(1,Dt(e.progress??0)??0));return o.start+o.duration*i}function ue(t,e=t.duration){const o=de(t,e);let i=ut(t.initialState);const r=[],n=[],s=[];for(const e of t.events){if(e.authoredAt>o.elapsed+Et)break;const a=St(i,e,{phaseId:e.phaseId,authoredAt:e.authoredAt,appliedAt:e.authoredAt,products:t.products,outlets:t.outlets});r.push(...a.diagnostics),n.push(...a.materializations),s.push(...a.observations),a.applied&&(i=a.state)}return i.elapsed=o.elapsed,i.phaseId=o.phaseId,i.phaseIndex=o.phaseIndex,i.phaseElapsed=o.phaseElapsed,i.complete=o.complete,o.complete&&"in_process"===i.outcome&&(i.outcome="complete"),i.playing=!1,{state:i,diagnostics:r,materializations:n,observations:s}}function pe(t){const e=function(t){const e=[];t.length||e.push(Ht("error","empty-phase-program","CrucibleChart requires at least one phase.","phases"));const o=zt(t.map(t=>t.id));o.length&&e.push(Ht("error","duplicate-phase-id",`Phase ids must be unique: ${o.join(", ")}.`,"phases",o));let i=0;return{phases:t.map((t,o)=>{const r=Dt(t.duration),n=null!=r&&r>0?r:0;t.id.trim()||e.push(Ht("error","invalid-phase-id","Phase ids may not be empty.",`phases.${o}.id`)),null!=r&&r>0||e.push(Ht("error","invalid-phase-duration","Phase duration must be finite and greater than zero.",`phases.${o}.duration`,[t.id])),void 0===t.intensity||Number.isFinite(t.intensity)||e.push(Ht("error","invalid-phase-intensity","Phase intensity must be finite.",`phases.${o}.intensity`,[t.id]));const s={...t,duration:n,intensity:void 0===t.intensity?.5:Number.isFinite(t.intensity)?Math.max(0,Math.min(1,t.intensity)):.5,motion:t.motion??"hold",index:o,start:i,end:i+n};return i=s.end,s}),diagnostics:e}}(t.phases),o=e.phases.at(-1)?.end??0,i=Lt(t.outlets??Nt),r=(t.products??[]).map(t=>({...t,metrics:t.metrics?{...t.metrics}:void 0})),n=function(t,e,o){const i=[],r=zt(t.map(t=>t.id));r.length&&i.push(Ht("error","duplicate-event-id",`Event ids must be unique: ${r.join(", ")}.`,"events",r));const n=[];return t.forEach((t,r)=>{let s,a,c;if(t.id.trim()||i.push(Ht("error","invalid-event-id","Event ids may not be empty.",`events.${r}.id`)),"time"in t.at&&void 0!==t.at.time){const n=Dt(t.at.time);if(null==n||0>n||n>o+Et)return void i.push(Ht("error","event-time-out-of-range",`Event time must fall between 0 and ${o}.`,`events.${r}.at.time`,[t.id]));s=Math.max(0,Math.min(o,n));const d=function(t,e,o){const i=t.find(t=>Et>=Math.abs(t.start-o));if(i)return{phase:i,boundaryRank:1};const r=t.find(t=>o>=t.start&&t.end>o);return r?{phase:r,boundaryRank:0}:Et>=Math.abs(o-e)&&t.length?{phase:t[t.length-1],boundaryRank:0}:{phase:void 0,boundaryRank:1}}(e,o,s);a=d.phase,c=d.boundaryRank}else{if(a=e.find(e=>e.id===t.at.phaseId),!a)return void i.push(Ht("error","unknown-event-phase",`Event references unknown phase "${t.at.phaseId}".`,`events.${r}.at.phaseId`,[t.id,t.at.phaseId]));const o=t.at.progress??0;if(!Number.isFinite(o)||0>o||o>1)return void i.push(Ht("error","event-progress-out-of-range","Event phase progress must be between 0 and 1.",`events.${r}.at.progress`,[t.id]));s=a.start+a.duration*o,c=0===o?1:0}a?n.push({...t,index:r,authoredAt:s,phaseId:a.id,phaseIndex:a.index,boundaryRank:c}):i.push(Ht("error","event-without-phase","Event could not be assigned to a phase.",`events.${r}.at`,[t.id]))}),n.sort((t,e)=>t.authoredAt-e.authoredAt||t.boundaryRank-e.boundaryRank||t.index-e.index),{events:n,diagnostics:i}}(t.events??[],e.phases,o),s=Ft(t),a=Tt(t.size??Bt,i),c=Xt(a),d=function(t,e){const o=[],i=new Set(e.map(t=>t.id)),r=zt(e.map(t=>t.id)),n=zt(t.map(t=>t.id));return r.length&&o.push(Ht("error","duplicate-outlet-id",`Outlet ids must be unique: ${r.join(", ")}.`,"outlets",r)),n.length&&o.push(Ht("error","duplicate-product-id",`Product ids must be unique: ${n.join(", ")}.`,"products",n)),e.forEach((t,e)=>{t.id.trim()||o.push(Ht("error","invalid-outlet-id","Outlet ids may not be empty.",`outlets.${e}.id`)),void 0===t.order||Number.isFinite(t.order)||o.push(Ht("error","invalid-outlet-order","Outlet order must be finite.",`outlets.${e}.order`,[t.id]))}),t.forEach((t,e)=>{t.id.trim()||o.push(Ht("error","invalid-product-id","Product ids may not be empty.",`products.${e}.id`)),void 0===t.amount||Number.isFinite(t.amount)&&t.amount>=0||o.push(Ht("error","invalid-product-amount","Declared product amount must be finite and non-negative.",`products.${e}.amount`,[t.id])),void 0===t.outletId||i.has(t.outletId)||o.push(Ht("error","unknown-outlet",`Product "${t.id}" references unknown outlet "${t.outletId}".`,`products.${e}.outletId`,[t.outletId])),Yt(t.metrics??{},o,`products.${e}.metrics`)}),o}(r,i),l=ce({seed:t.seed??1,components:Object.values(s.state.components).sort((t,e)=>Wt(t.id,e.id)).map(t=>({id:t.id,label:t.label,category:t.category,amount:t.amount,metrics:t.metrics,status:t.status})),phases:e.phases.map(({id:t,duration:e,label:o,description:i,intensity:r,motion:n,color:s,metrics:a})=>({id:t,duration:e,label:o,description:i,intensity:r,motion:n,color:s,metrics:a})),products:r,outlets:i,events:n.events.map(({id:t,label:e,description:o,summary:i,authoredAt:r,phaseId:n,boundaryRank:s,effects:a})=>({id:t,label:e,description:o,summary:i,authoredAt:r,phaseId:n,boundaryRank:s,effects:a}))}),u=ee(s.state,a,{seed:t.seed,bodyRadius:t.bodyRadius,radiusRange:t.radiusRange}),p=[...e.diagnostics,...n.diagnostics,...s.diagnostics,...d],h={phases:e.phases,events:n.events,products:r,outlets:i,duration:o,initialState:s.state,terminalState:s.state,layout:a,colliders:c,config:Vt(t.seed,c),initialSpawns:u,terminalSpawns:[],semanticKey:l,diagnostics:p},m=ue(h),y=Object.values(m.state.products).filter(t=>"forming"===t.status).map(t=>t.id),f=y.length?[Ht("warning","forming-product-at-end",`Products remain forming at the end of the tape: ${y.join(", ")}.`,"events",y)]:[];return h.terminalState=m.state,h.terminalSpawns=se(m.state,a,{seed:t.seed,bodyRadius:t.bodyRadius,radiusRange:t.radiusRange}),h.diagnostics=[...p,...m.diagnostics,...f],h}function he(t,e,o){return{id:t.id??e,at:{...t.at},effects:o,...void 0===t.label?null:{label:t.label},...void 0===t.description?null:{description:t.description},...void 0===t.summary?null:{summary:t.summary}}}function me(t){if(t)return{...t,...t.metrics?{metrics:{...t.metrics}}:null}}function ye(t){const{productId:e,form:o,contributions:i=[],complete:r}=t,n=t.idPrefix??e,s=me(o.loss),a=[he(o,n+"-form",[{type:"combine",sourceIds:[...o.sourceIds],productId:e,...o.basisRelationIds?{basisRelationIds:[...o.basisRelationIds]}:null,...s?{loss:s}:null,complete:!1}])];return i.forEach((t,o)=>{const i=me(t.loss);a.push(he(t,`${n}-contribute-${o+1}`,[{type:"contribute",sourceIds:[...t.sourceIds],productId:e,...t.basisRelationIds?{basisRelationIds:[...t.basisRelationIds]}:null,...i?{loss:i}:null}]))}),a.push(he(r,n+"-complete",[{type:"complete-product",productId:e,...void 0===r.outletId?null:{outletId:r.outletId},...void 0===r.reason?null:{reason:r.reason}}])),a}import{forwardRef as fe,useCallback as ge,useEffect as ve,useImperativeHandle as be,useMemo as xe,useRef as Ie,useState as we}from"react";function ke(t,e){return t.playing=e&&!t.complete,t}function Me(t,e,o=!1){const i=ue(t,e);return{...i,state:ke(i.state,o)}}function Se(t,e,o,i=e.playing){const r=Me(t,o,i),n=new Set(e.eventsApplied);return{...r,observations:r.observations.filter(t=>!n.has(t.eventId)),materializations:r.materializations.filter(t=>!n.has(t.eventId))}}function Ae(t,e,o={}){return ne(e,t.layout,o)}function $e(t,e){return function(t){let e=2166136261;for(let o=0;t.length>o;o+=1)e^=t.charCodeAt(o),e=Math.imul(e,16777619);return e>>>0}(`${e}:${t}`)/4294967295}function je(t,e){return t.phases[e.phaseIndex]??t.phases.find(t=>t.id===e.phaseId)}function Ce(t,e,o={}){return new Map(Ae(t,e,o).flatMap(t=>{const e=t.datum;return e?.__crucible?[[`${e.kind}:${e.semanticId}`,{x:t.x,y:t.y}]]:[]}))}function Re(t,e){const o=Object.values(t.terminalState.products).map(t=>t.id).sort(),i=Math.max(0,o.indexOf(e))/Math.max(1,o.length)*Math.PI*2-Math.PI/2,r=Math.min(58,.19*t.layout.chamber.width),n=Math.min(38,.16*t.layout.chamber.height);return{x:t.layout.chamber.x+t.layout.chamber.width/2+Math.cos(i)*r,y:t.layout.chamber.y+.52*t.layout.chamber.height+Math.sin(i)*n}}import*as Pe from"react";import{jsx as Be,jsxs as Ne}from"react/jsx-runtime";function Oe(t,e,o){if("string"!=typeof e)return o;if("function"!=typeof getComputedStyle||!t.canvas)return e||o;const i=e.startsWith("var(")?e.match(/var\((--[^,\s)]+)/)?.[1]:e.startsWith("--")?e:null;return i?getComputedStyle(t.canvas).getPropertyValue(i).trim()||o:e||o}function Ee(t){return Number.isFinite(t)?1e3>Math.abs(t)?Number.isInteger(t)?t+"":t.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):t.toLocaleString():"0"}function We(t){const e=t.productIds.length?` Contributes to ${t.productIds.join(", ")}.`:t.outletId?` Routed to ${t.outletId}.`:"",o=t.reason?` ${t.reason}.`:"";return`${Ee(t.amount)} amount; ${t.status}.${e}${o}`}function He(t){const e=t.outletId?` Routed to ${t.outletId}.`:"";return`${t.status} product with ${t.sourceIds.length} source${1===t.sourceIds.length?"":"s"} and ${Ee(t.amount)} amount.${e}`}function ze(t,e,o){const i=e.datum;if(!i?.__crucible)return;const r="circle"===e.shape.type?e.shape.radius:8,n=Oe(t,o.fill,"product"===i.kind?"#b8792d":"#356b63"),s=Oe(t,o.stroke,"#26323a");if(t.save(),t.translate(e.x,e.y),t.globalAlpha="number"==typeof o.opacity?o.opacity:.96,t.fillStyle=n,t.strokeStyle=s,t.lineWidth="number"==typeof o.strokeWidth?o.strokeWidth:1.25,"product"===i.kind){t.shadowColor=n,t.shadowBlur=10,t.beginPath();for(let e=0;6>e;e+=1){const o=-Math.PI/2+e/6*Math.PI*2,i=Math.cos(o)*r,n=Math.sin(o)*r;0===e?t.moveTo(i,n):t.lineTo(i,n)}t.closePath(),t.fill(),t.shadowBlur=0,t.stroke(),t.beginPath(),t.arc(0,0,Math.max(2,.36*r),0,2*Math.PI),t.strokeStyle=Oe(t,"var(--semiotic-bg, #fffaf0)","#fffaf0"),t.globalAlpha*=.72,t.stroke()}else t.beginPath(),t.arc(0,0,r,0,2*Math.PI),t.fill(),t.stroke(),t.beginPath(),t.arc(.25*-r,.28*-r,Math.max(1,.18*r),0,2*Math.PI),t.fillStyle="rgba(255,255,255,0.34)",t.fill();t.restore()}import{Fragment as De,jsx as _e,jsxs as Ye}from"react/jsx-runtime";var Fe="var(--semiotic-text, #26323a)",Le="var(--semiotic-text-secondary, #6c7377)",Te="var(--semiotic-primary, #b8792d)",Ge="var(--semiotic-danger, #9f3d35)",Xe="var(--semiotic-success, #356b63)";function qe(t){const{x:e,y:o,width:i,height:r}=t.chamber,n=Math.min(.14*i,48),s=o+r;return[`M ${e} ${o}`,`L ${e+n} ${s-.16*r}`,`Q ${e+i/2} ${s+.1*r} ${e+i-n} ${s-.16*r}`,`L ${e+i} ${o}`].join(" ")}function Ue({layout:t,phases:e,state:o,compact:i=!1}){const r=Math.max(1,e.reduce((t,e)=>t+Math.max(0,e.duration),0));return Ye("svg",{"aria-hidden":"true","data-testid":"crucible-chrome",viewBox:`0 0 ${t.width} ${t.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:[Ye("defs",{children:[Ye("linearGradient",{id:"semiotic-crucible-heat",x1:"0",x2:"0",y1:"0",y2:"1",children:[_e("stop",{offset:"0",stopColor:Te,stopOpacity:"0.03"}),_e("stop",{offset:"0.66",stopColor:Te,stopOpacity:"0.1"}),_e("stop",{offset:"1",stopColor:Ge,stopOpacity:"0.18"})]}),_e("pattern",{id:"semiotic-crucible-hatch",width:"7",height:"7",patternUnits:"userSpaceOnUse",patternTransform:"rotate(20)",children:_e("line",{x1:"0",x2:"0",y1:"0",y2:"7",stroke:Fe,strokeOpacity:"0.08",strokeWidth:"1"})})]}),_e("rect",{x:t.chamber.x,y:t.chamber.y,width:t.chamber.width,height:t.chamber.height,rx:2,fill:"url(#semiotic-crucible-heat)",stroke:Fe,strokeOpacity:"0.52",strokeWidth:i?1:2.2}),_e("path",{d:qe(t),fill:"url(#semiotic-crucible-hatch)",stroke:"none"}),_e("line",{x1:t.mouth.x,x2:t.mouth.x+t.mouth.width,y1:t.mouth.y,y2:t.mouth.y,stroke:Fe,strokeLinecap:"round",strokeOpacity:"0.72",strokeWidth:i?2:5}),i?null:_e("g",{"data-testid":"crucible-phase-rail",children:e.map((i,n)=>{const s=e.slice(0,n).reduce((t,e)=>t+Math.max(0,e.duration),0),a=t.phaseRail.x+s/r*t.phaseRail.width,c=Math.max(0,i.duration)/r*t.phaseRail.width,d=i.id===o.phaseId,l=o.phaseIndex>n||o.complete;return Ye("g",{children:[_e("rect",{x:a,y:t.phaseRail.y,width:Math.max(1,c-2),height:t.phaseRail.height,rx:2,fill:d?i.color??Te:l?Xe:Fe,fillOpacity:d?.68:l?.28:.09}),46>c?null:_e("text",{x:a+c/2,y:t.phaseRail.y+t.phaseRail.height+13,fill:d?Fe:Le,fontFamily:"system-ui, sans-serif",fontSize:8.5,fontWeight:d?800:650,letterSpacing:"0.04em",textAnchor:"middle",children:(i.label??i.id).toUpperCase()})]},i.id)})}),t.outlets.map(t=>Ye("g",{children:[_e("rect",{x:t.x,y:t.y,width:t.width,height:t.height,rx:3,fill:t.color??("left"===t.side?Ge:Xe),fillOpacity:"0.1",stroke:t.color??("left"===t.side?Ge:Xe),strokeDasharray:"3 3",strokeOpacity:"0.62"}),i?null:_e("text",{x:t.x+t.width/2,y:t.y+Math.min(13,t.height/2+3),fill:Le,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:750,letterSpacing:"0.05em",textAnchor:"middle",children:(t.label??t.id).toUpperCase()})]},t.id))]})}function Ve(t,e){return"count"===e?t.count:"amount"===e?t.amount:Number(t.metrics[e]??0)}function Ke({rows:t,layout:e,projection:o,amountLabel:i}){if(!t.length)return null;const r=o.measure??"count",n=t.map(t=>Math.max(0,Ve(t,r))),s=Math.max(1,...n),a=e.projection.width/Math.max(1,t.length),c=e.projection.height>48?21:4,d=Math.max(5,e.projection.height-c-5);return _e("svg",{"aria-hidden":"true","data-testid":"crucible-projection-overlay",viewBox:`0 0 ${e.width} ${e.height}`,style:{inset:0,pointerEvents:"none",position:"absolute"},children:t.map((t,o)=>{const l=n[o],u=Math.max(l>0?2:0,l/s*d),p=e.projection.x+o*a+.18*a;return Ye("g",{children:[_e("rect",{x:p,y:e.projection.y+d-u,width:Math.max(3,.64*a),height:u,rx:2,fill:"failed"===t.status||"ejected"===t.status?Ge:"complete"===t.status?Te:Xe,fillOpacity:"0.68"}),c>4&&a>=34?Ye(De,{children:[_e("text",{x:p+.32*a,y:e.projection.y+d+10,fill:Le,fontFamily:"system-ui, sans-serif",fontSize:7.5,fontWeight:700,textAnchor:"middle",children:t.label.length>13?t.label.slice(0,12)+"…":t.label}),Ye("text",{x:p+.32*a,y:e.projection.y+d+19,fill:Fe,fontFamily:"system-ui, sans-serif",fontSize:8,fontWeight:850,textAnchor:"middle",children:[Ee(l),"amount"===r&&i?" "+i:""]})]}):null]},t.key)})})}function Qe({controls:t,duration:e,elapsed:o,phaseLabel:i,playing:r,complete:n,playbackRate:s,disabled:a,onPlayPause:c,onReset:d,onStepPhase:l,onPlaybackRateChange:u}){const p=e>0?Math.min(1,Math.max(0,o/e)):1;return Ye("div",{"aria-label":"Crucible replay controls",className:"semiotic-crucible-controls",style:{alignItems:"center",color:Fe,display:"flex",flexWrap:"wrap",fontFamily:"system-ui, sans-serif",fontSize:11,gap:6,marginBottom:7},children:[t.playPause?_e("button",{type:"button",disabled:a,onClick:c,"aria-pressed":r,children:r?"Pause":n?"Replay":"Play"}):null,t.stepPhase?_e("button",{type:"button",disabled:a,onClick:l,children:"Next phase"}):null,t.reset?_e("button",{type:"button",disabled:a,onClick:d,children:"Reset"}):null,t.timeline?Ye("div",{style:{alignItems:"center",display:"flex",flex:"1 1 150px",gap:7,minWidth:130},children:[_e("span",{style:{fontWeight:750,whiteSpace:"nowrap"},children:i}),_e("span",{"aria-hidden":"true",style:{background:"rgba(38,50,58,0.14)",borderRadius:2,flex:1,height:4,overflow:"hidden"},children:_e("span",{style:{background:Te,display:"block",height:"100%",transform:`scaleX(${p})`,transformOrigin:"left center"}})}),Ye("span",{style:{color:Le,fontVariantNumeric:"tabular-nums"},children:[o.toFixed(1),"s"]})]}):null,t.speed?Ye("label",{style:{alignItems:"center",display:"flex",gap:4},children:["Speed",Ye("select",{disabled:a,value:s,onChange:t=>u(Number(t.currentTarget.value)),children:[_e("option",{value:.25,children:"¼×"}),_e("option",{value:.5,children:"½×"}),_e("option",{value:1,children:"1×"}),_e("option",{value:2,children:"2×"})]})]}):null]})}function Ze(t,e,o,i){const r="function"==typeof i?i(e,o):i,n=e.datum;return{fill:t,stroke:"product"===n?.kind?"var(--semiotic-bg, #fffaf0)":Fe,strokeWidth:"product"===n?.kind?1.8:1.1,opacity:.96,...r}}var Je=["#356b63","#a34b43","#c08b38","#3e5f83","#785b7c","#6e7740","#8f5c3a","#41717b"];function to(t){let e=2166136261;for(let o=0;t.length>o;o+=1)e^=t.charCodeAt(o),e=Math.imul(e,16777619);return e>>>0}function eo(t){return"number"==typeof t&&Number.isFinite(t)?t:to((t??"crucible")+"")}function oo(t){const e=Number(t);return Number.isFinite(e)&&e>0?Math.max(.05,Math.min(8,e)):1}function io(t,e,o){return"category"===e?t.category:"status"===e?t.status:"outlet"===e?t.outletId??"in chamber":"product"===e?t.productIds[0]??"unalloyed":function(t,e,o){return(("function"==typeof t?t(e,o):e[t])??"unassigned")+""}(e,t.datum,o)}function ro(t){return Je[to(t)%Je.length]}function no(t,e){const o=Object.keys(t.components).length,i=Object.keys(t.products).length,r=Object.values(t.products).reduce((t,e)=>t+e.amount,0),n=e?" "+e:" amount",s=t.outcome?` Outcome: ${t.outcome}.`:"";return`${o} source component${1===o?"":"s"}; ${i} product${1===i?"":"s"}; ${r.toLocaleString()}${n} in products.${s}`}import{jsx as so,jsxs as ao}from"react/jsx-runtime";import{createElement as co}from"react";var lo=fe(function(e,o){const{amountAccessor:i,amountLabel:r,bodyRadius:n,categoryAccessor:s,colorBy:c="category",conservation:d,controls:l,data:u,emptyContent:p,events:h,frameProps:m={},idAccessor:b,initialStateAccessor:I,initialSpawnPacing:j,labelAccessor:C,loading:R,loadingContent:P,metrics:B,metricsAccessor:N,onClick:O,onConservation:E,onCrucibleObservation:W,onDiagnostic:H,onStateChange:z,outlets:D,paused:_,phases:Y,playback:F="replay",playbackRate:L=1,products:T,projection:G,radiusRange:X,rerunMS:q,responsiveHeight:U,responsiveWidth:V,seed:K,showBonds:Q=!0,snapshotAt:Z}=e,J=Ie(null),tt=Ie(_);tt.current=_;const et=$(),ot=A(),it=x(e,Bt),{chartMode:rt,chartSize:nt,showChrome:st,showProjection:at,className:ct,title:dt,description:lt,summary:pt,accessibleTable:ht,enableHover:mt,margin:yt}=it,[ft,gt]=S(nt,V,!1),vt=V?Math.max(1,gt[0]):nt[0],bt=nt[1],xt=xe(()=>[vt,bt],[bt,vt]),It=xe(()=>M(u??[]),[u]),wt=xe(()=>pe({data:It,phases:Y,products:T,outlets:D,events:h,idAccessor:b,labelAccessor:C,categoryAccessor:s,amountAccessor:i,metricsAccessor:N,initialStateAccessor:I,metrics:B,size:xt,seed:K,bodyRadius:n,radiusRange:X}),[i,n,s,h,b,I,C,B,N,D,Y,T,X,xt,It,K]),kt=Object.values(wt.initialState.components).map((t,e)=>io(t,c,e)).join("\0"),Mt=`${wt.semanticKey}:${xt[0]}x${xt[1]}:${(n??"auto")+""}:${X?.join(",")??"auto"}:${kt}`,St=Ie(wt),$t=Ie(Mt);$t.current!==Mt&&($t.current=Mt,St.current=wt);const Ct=St.current,Rt="snapshot"===F||et||ot,Pt=Rt?function(t,e){return le(t,e)}(Ct,Z):0,Nt=!Rt,Ot=xe(()=>Me(Ct,Pt,Nt&&!_),[$t.current,Pt,Nt]),[Et,Wt]=we(Ot),Ht=Ie(Et),[zt,Dt]=we(Nt),_t=Ie(zt),[Yt,Ft]=we(0),[Lt,Tt]=we(()=>oo(L)),Gt=Ie(Ce(Ct,Ot.state,{seed:K,bodyRadius:n,radiusRange:X})),Xt=Ie(""),qt=Ie(z),Ut=Ie(W),Vt=Ie(H),Kt=Ie(E);qt.current=z,Ut.current=W,Vt.current=H,Kt.current=E;const Qt=Ie({seed:K,bodyRadius:n,radiusRange:X});Qt.current={seed:K,bodyRadius:n,radiusRange:X};const Zt=ge((t,e=!1)=>{if(Ht.current=t,Gt.current=Ce(St.current,t.state,Qt.current),Wt(t),e)for(const e of t.observations)Ut.current?.(e)},[]);ve(()=>{Tt(oo(L))},[L]),ve(()=>{const t=!Rt,e=Me(Ct,Rt?Pt:0,t&&!tt.current);_t.current=t,Dt(t),Zt(e)},[Zt,Ct,Pt,Rt,Mt]),ve(()=>{const t=Ht.current,e=_t.current&&!_&&!t.state.complete;if(t.state.playing===e)return;const o={...t,state:ut(t.state)};o.state.playing=e,Zt(o)},[Zt,_]),ve(()=>{for(const t of Ct.diagnostics)Vt.current?.(t)},[Mt,Ct.diagnostics]),ve(()=>{if(qt.current?.(Et.state),d){const t=!0===d?{}:d;Kt.current?.(jt(Et.state,t))}},[d,Et.state]);const Jt=ge(()=>{Xt.current="";const t=!Rt,e=Me(St.current,0,t&&!_);_t.current=t,Dt(t),Zt(e)},[Zt,_,Rt]),te=xe(()=>({...Ct.config,...m.config,fixedDt:m.config?.fixedDt??Ct.config.fixedDt,maxSubsteps:m.config?.maxSubsteps??Ct.config.maxSubsteps,settleStepLimit:m.config?.settleStepLimit??Ct.config.settleStepLimit,timeScale:Lt,colliders:[...Ct.config.colliders??[],...m.config?.colliders??[]],kernel:{...Ct.config.kernel,...m.config?.kernel,gravity:m.config?.kernel?.gravity??Ct.config.kernel?.gravity??{x:0,y:0}},observation:{...Ct.config.observation,...m.config?.observation,chartType:"CrucibleChart"}}),[m.config,Lt,Ct.config]),ee=Rt||!!_||!zt&&!Et.state.complete,oe=w(te,q,ee,Jt),ie=ge(()=>{if("number"!=typeof q||!Number.isFinite(q)||0>q)return;const t=`${Mt}:${Yt}:${oe.rerunKey}`;Xt.current!==t&&(Xt.current=t,oe.config?.observation?.onSimulationStateChange?.("settled","running"))},[oe.config,oe.rerunKey,q,Yt,Mt]),re=ge(()=>{const t=Me(St.current,0,!1);_t.current=!1,Dt(!1),Zt(t),Ft(t=>t+1)},[Zt]),ne=ge(()=>{const t=St.current,e=Se(t,Ht.current.state,t.duration,!1);_t.current=!1,Dt(!1),Zt(e,!0);const o=Ae(t,e.state,Qt.current),i=J.current;i&&(i.clear(),i.pushMany(o),i.step(0),i.settle()),ie()},[Zt,ie]),se=ge(()=>{_t.current=!1,Dt(!1);const t={...Ht.current,state:ut(Ht.current.state)};t.state.playing=!1,Zt(t)},[Zt]),ae=ge(()=>{if(Xt.current="",Rt){const t=Me(St.current,Pt,!1);return _t.current=!1,Dt(!1),Zt(t),void Ft(t=>t+1)}const t=Me(St.current,0,!_);_t.current=!0,Dt(!0),Zt(t),Ft(t=>t+1)},[Zt,_,Pt,Rt]),ce=ge(()=>{if(Rt)return void ae();if(Ht.current.state.complete)return void ae();_t.current=!0,Dt(!0);const t={...Ht.current,state:ut(Ht.current.state)};t.state.playing=!_,Zt(t)},[Zt,_,ae,Rt]),de=ge(()=>{const t=St.current,e=function(t,e){const o=t.phases.find(t=>t.end>e+1e-7);return o?.end??t.duration}(t,Ht.current.state.elapsed),o=Se(t,Ht.current.state,e,!1);_t.current=!1,Dt(!1),Zt(o,!0);const i=J.current;i&&(i.clear(),i.pushMany(Ae(t,o.state,Qt.current)),i.step(0))},[Zt]);be(o,()=>({play:ce,pause:se,reset:re,replay:ae,stepPhase:de,settle:ne,getCrucibleState:()=>ut(Ht.current.state)}),[se,ce,ae,re,ne,de]);const ue=ge((t,e)=>{if(m.onTick?.(t,e),Rt||_||!_t.current)return;const o=Ht.current.state,i=Math.min(St.current.duration,t.elapsedSeconds);if(o.elapsed+.045>=i&&St.current.duration>i)return;const r=Se(St.current,o,i,St.current.duration>i),n=r.state.eventsApplied.length!==o.eventsApplied.length;if(n&&function(t,e){const o=new Set(t.readBodies().map(t=>t.id)),i=e.filter(t=>!o.has(t.id));i.length&&t.pushMany([...i]),i.map(t=>t.id)}(e,Ae(St.current,r.state,Qt.current)),r.state.complete){_t.current=!1,Dt(!1);const t=Ae(St.current,r.state,Qt.current);e.clear(),e.pushMany(t),e.step(0),e.settle()}Zt(r,n),r.state.complete&&ie()},[Zt,m,_,ie,Rt]),he=ge(({body:t})=>function(t){const e=function(t){const{body:e,plan:o,state:i,targets:r}=t,n=e.datum;if(!n?.__crucible)return null;let s=r.get(`${n.kind}:${n.semanticId}`);if(!s)return null;const a=je(o,i),c=Math.max(0,Math.min(2,Number(a?.intensity??.5))),d=a?.motion??"hold",l=i.elapsed;if("product"===n.kind){const t=i.products[n.semanticId];"forming"===t?.status&&(s=Re(o,t.id))}else{const t=i.components[n.semanticId],e=t?.productIds.map(t=>i.products[t]).find(t=>"forming"===t?.status);if(e){const i=Re(o,e.id),r=$e(t.id,17)*Math.PI*2,n=Math.max(5,Math.min(18,.026*o.layout.width));s={x:i.x+Math.cos(r)*n,y:i.y+Math.sin(r)*n}}}const u=n.semanticId,p=$e(u,23)*Math.PI*2;if(!i.complete&&!(o.layout.chamber.x>s.x||s.x>o.layout.chamber.x+o.layout.chamber.width||o.layout.chamber.y>s.y||s.y>o.layout.chamber.y+o.layout.chamber.height))if("mix"===d){const t=Math.min(34,.1*o.layout.chamber.width)*c,e=Math.min(24,.09*o.layout.chamber.height)*c;s={x:s.x+Math.cos(l*(1.4+$e(u,29))+p)*t,y:s.y+Math.sin(l*(1.8+$e(u,31))+p)*e}}else if("press"===d){const t=o.layout.chamber.x+o.layout.chamber.width/2,e=o.layout.chamber.y+.56*o.layout.chamber.height;s={x:t+(s.x-t)*Math.max(.3,1-.32*c),y:e+(s.y-e)*Math.max(.35,1-.26*c)}}else if("separate"===d){const t=.5>$e(u,41)?-1:1;s={x:s.x+t*Math.min(28,.075*o.layout.chamber.width)*c,y:s.y}}else if("bind"===d){const t=o.layout.chamber.x+o.layout.chamber.width/2,e=o.layout.chamber.y+.5*o.layout.chamber.height;s={x:t+.72*(s.x-t),y:e+.72*(s.y-e)}}else"charge"===d?s={x:s.x,y:s.y+4*Math.sin(2*l+p)*c}:"quench"===d&&(s={x:s.x+2*Math.sin(p)*c,y:s.y});return s}(t);if(!e)return null;const{body:o,state:i}=t,r=e.x-o.x,n=e.y-o.y,s=Math.hypot(r,n),a=Math.hypot(o.vx,o.vy);if(i.complete&&.7>s&&.45>a)return null;const c=!i.complete&&"pour"===je(t.plan,i)?.motion,d=i.complete?.68:c?.72:.5,l=i.complete?.22:c?.18:.14,u=i.complete?42:c?72:56;return{x:Math.max(-u,Math.min(u,r*d-o.vx*l)),y:Math.max(-u,Math.min(u,n*d-o.vy*l))}}({body:t,plan:St.current,state:Ht.current.state,targets:Gt.current}),[]),me=xe(()=>new Map(Object.keys(Ct.initialState.components).map((t,e)=>[t,e])),[Ct.initialState.components]),ye=ge(t=>{if(e.color)return e.color;const o=t.datum;if(!o?.__crucible)return"var(--semiotic-primary, #b8792d)";if("product"===o.kind){const t=Ht.current.state.products[o.semanticId];return t?.color??ro(t?.id??o.semanticId)}const i=Ht.current.state.components[o.semanticId];return i?ro(io(i,c,me.get(i.id)??0)):"var(--semiotic-primary, #356b63)"},[c,me,e.color]),fe=ge((t,o)=>({...Ze(ye(t),t,o,m.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}),[ye,m.bodyStyle,e.opacity,e.stroke,e.strokeWidth]),ke=ge((t,e)=>("function"==typeof m.bodySemanticItems?m.bodySemanticItems(t,e):void 0)??function(t,e){const o=t.datum;if(!o?.__crucible)return!1;if("component"===o.kind){const t=e.components[o.semanticId];return!!t&&{id:"crucible-component-"+t.id,label:t.label,description:We(t),group:"source component · "+t.status,datum:t}}const i=e.products[o.semanticId];return!!i&&{id:"crucible-product-"+i.id,label:i.label,description:He(i),group:"derived product · "+i.status,datum:i}}(t,Ht.current.state),[m]),Pe=ge(t=>{if(!O||!t||"object"!=typeof t)return;if(!t.__crucible)return;const e=Ht.current.state,o="component"===t.kind?e.components[t.semanticId]:e.products[t.semanticId];o&&O(o)},[O]),Be=ge((t,e)=>{m.beforePaint?.(t,e),Q&&function(t,e,o){const i=new Map;for(const t of e){const e=t.datum;e?.__crucible&&i.set(`${e.kind}:${e.semanticId}`,t)}t.save(),t.lineCap="round";for(const e of Object.values(o.relations)){if("active"!==e.status)continue;const o=e.sourceIds.map(t=>i.get("component:"+t)).filter(t=>!!t);2>o.length||(t.strokeStyle="rejected"===e.category?"#9f3d35":"#b8792d",t.globalAlpha=.4,t.lineWidth=Math.max(.8,1.3*Number(e.strength??1)),t.setLineDash([3,4]),t.beginPath(),o.forEach((e,o)=>{0===o?t.moveTo(e.x,e.y):t.lineTo(e.x,e.y)}),t.stroke())}t.setLineDash([]);for(const e of Object.values(o.products)){const o=i.get("product:"+e.id);if(o)for(const r of e.sourceIds){const n=i.get("component:"+r);n&&(t.strokeStyle=e.color??"#b8792d",t.globalAlpha="complete"===e.status?.5:.28,t.lineWidth="complete"===e.status?1.6:1,t.beginPath(),t.moveTo(n.x,n.y),t.lineTo(o.x,o.y),t.stroke())}}t.restore()}(t,e,Ht.current.state)},[m,Q]),Ne=xe(()=>G??{groupBy:"outlet",measure:"count"},[G]),Oe=xe(()=>At(Et.state,Ne),[Ne,Et.state]),De=xe(()=>at?function(t,e,o,i){if(!t.length)return[];const r=o.measure??"count",n=e.projection.width/Math.max(1,t.length);return t.map((t,o)=>{const s=Ve(t,r),a="amount"===r&&i?`${Ee(s)} ${i}`:`${Ee(s)} ${r}`;return{id:"crucible-projection-"+t.key,label:`${t.label}: ${a}`,description:`${t.count} source component${1===t.count?"":"s"}; ${Ee(t.amount)} amount.`,datum:t,group:"settled composition",x:e.projection.x+(o+.5)*n,y:e.projection.y+e.projection.height/2,shape:"rect",width:Math.max(12,.62*n),height:Math.max(8,e.projection.height-8)}})}(Oe,Ct.layout,Ne,r):[],[r,Ct.layout,Ne,Oe,at]),Fe=v(e.tooltip,m),{selection:Le,onBodyHover:Te}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:c,chartType:"CrucibleChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:m?.onBodyHover}),Ge=g({...e,onClick:void 0},m,De,{selection:Le,chartMode:rt,className:ct,title:dt??"Crucible",description:lt??"A bounded inventory is transformed by an authored phase and event tape; physics explains the motion but does not determine the outcome.",summary:pt??no(Et.state,r),accessibleTable:ht,enableHover:mt,margin:yt}),Xe=a(st?so(Ue,{layout:Ct.layout,phases:Ct.phases,state:Et.state,compact:it.compactMode||360>xt[0]||260>xt[1]}):void 0,m.backgroundGraphics),qe=a(at?so(Ke,{rows:Oe,layout:Ct.layout,projection:Ne,amountLabel:r}):void 0,m.foregroundGraphics),Je=ge(t=>function(t,e){const o=t.data;if(!o?.__crucible)return null;const i="component"===o.kind?e.components[o.semanticId]:e.products[o.semanticId];if(!i)return null;const r="product"===o.kind;return Ye("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:[_e("strong",{children:i.label}),_e("div",{style:{opacity:.78,fontSize:11,letterSpacing:"0.06em",textTransform:"uppercase"},children:r?"Product · "+i.status:"Source · "+i.status}),_e("div",{style:{marginTop:4},children:r?He(i):We(i)})]})}(t,Ht.current.state),[]),to=Rt?Ae(Ct,Et.state,Qt.current):Ct.initialSpawns,lo=function(t){return t?!0===t?{playPause:!0,reset:!0,stepPhase:!0,timeline:!0,speed:!0}:{playPause:t.playPause??!0,reset:t.reset??!0,stepPhase:t.stepPhase??!0,timeline:t.timeline??!0,speed:t.speed??!1}:{playPause:!1,reset:!1,stepPhase:!1,timeline:!1,speed:!1}}(l),uo=Object.values(lo).some(Boolean),po=Ct.phases[Et.state.phaseIndex],ho=y({data:u,emptyContent:p,loading:R,loadingContent:P,size:xt});if(ho)return ho;const mo=Ct.diagnostics.filter(t=>"error"===t.severity);return mo.length?ao("div",{className:ct,role:"alert",style:{maxWidth:"100%",width:xt[0]},children:[so("strong",{children:"CrucibleChart could not compile this treatment tape."}),so("ul",{children:mo.map((t,e)=>so("li",{children:t.message},`${t.code}-${e}`))})]}):f("CrucibleChart",xt,ao("div",{ref:ft,className:"semiotic-crucible-chart",style:{maxWidth:"100%",overflow:"hidden",position:"relative",width:V?"100%":xt[0]},children:[uo?so(Qe,{controls:lo,duration:Ct.duration,elapsed:Et.state.elapsed,phaseLabel:po?.label??po?.id??"Complete",playing:zt&&!_,complete:Et.state.complete,playbackRate:Lt,disabled:Rt,onPlayPause:zt?se:ce,onReset:re,onStepPhase:de,onPlaybackRateChange:Tt}):null,co(t,{...m,...Fe,...Ge,key:`${Mt}:${Yt}:${oe.rerunKey}:${Rt?Pt:"replay"}`,ref:J,onBodyHover:Te,accessibleTable:e.accessibleTable??m.accessibleTable,backgroundGraphics:Xe,bodyForces:he,bodySemanticItems:ke,bodyStyle:fe,beforePaint:Be,config:oe.config,continuous:!Rt&&zt&&!_&&!Et.state.complete,enableHover:Fe.enableHover??mt,foregroundGraphics:qe,hoverRadius:e.hoverRadius??m.hoverRadius??18,initialSpawns:to,initialSpawnPacing:j,onClick:O?Pe:Ge.onClick,onTick:ue,paused:ee,renderBody:m.renderBody??ze,responsiveHeight:U,responsiveWidth:!1,seed:eo(K),size:xt,tooltipContent:Fe.tooltipContent??Je})]}))});function uo(t,e={}){const o=e.id??"physics-process-boundary",i={bodyFilter:e.bodyFilter,friction:e.friction,restitution:e.restitution};if("segment"===t.type)return[{...i,id:o,shape:t}];const r=e.thickness??8,n=t.x-t.width/2,s=t.x+t.width/2,a=t.y-t.height/2,c=t.y+t.height/2;return[{...i,id:o+"-top",shape:{type:"segment",x1:n,y1:a,x2:s,y2:a,thickness:r}},{...i,id:o+"-right",shape:{type:"segment",x1:s,y1:a,x2:s,y2:c,thickness:r}},{...i,id:o+"-bottom",shape:{type:"segment",x1:s,y1:c,x2:n,y2:c,thickness:r}},{...i,id:o+"-left",shape:{type:"segment",x1:n,y1:c,x2:n,y2:a,thickness:r}}]}function po(t){if(!1===t.semanticItem)return null;const e=t.semanticItem??{},o=t.shape,i="aabb"===o.type?{id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"region",x:o.x,y:o.y,width:o.width,height:o.height}:{id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"region",x:(o.x1+o.x2)/2,y:(o.y1+o.y2)/2,pathData:`M ${o.x1} ${o.y1} L ${o.x2} ${o.y2}`};return{...i,...e,id:e.id??i.id}}function ho(t){return t.map(t=>({id:t.id,label:t.label??t.id,description:t.description,group:t.kind??"stage",x:t.x??0,y:t.y??0,width:t.width,height:t.height}))}function mo(t){return t.flatMap(t=>{if(!1===t.semanticItem)return[];const e=t.semanticItem??{},o={id:t.id,label:t.label??t.id,description:t.description,datum:t.datum,group:t.group??t.state??"body group",x:t.x??0,y:t.y??0,width:t.width,height:t.height};return[{...o,...e,id:e.id??o.id}]})}function yo(t){return t?Array.isArray(t)?[...t]:Object.entries(t).flatMap(([t,e])=>Array.from({length:Math.max(0,Math.round(Number(e)||0))},()=>t)):[]}function fo(t,e){return e?Array.isArray(e)?[...e]:e.ids?[...e.ids]:e.candidates?e.candidates.filter(e=>t.includes(e)).slice(0,e.count??1):[]:[]}function go(t,e){return fo(t.activePositiveIds,e.popPositive)}function vo(t){const e=Number(t.budget),o=Number.isFinite(e)?Math.max(0,e):0,i=t.properties instanceof Map?t.properties:new Map(t.properties.map(t=>[t.id,t])),r=t.candidates?new Set(t.candidates):null,n=t.attachedIds.map((t,e)=>{const o=i.get(t),r=Number(o?.work??1),n=Number(o?.priority??e);return{id:t,index:e,priority:Number.isFinite(n)?n:e,work:Number.isFinite(r)&&r>0?r:1}}).filter(t=>!r||r.has(t.id)).sort((t,e)=>t.priority-e.priority||t.index-e.index),s=[],a=[];let c=0;for(const t of n)c+t.work>o+Number.EPSILON?a.push(t.id):(s.push(t.id),c+=t.work);return{ids:s,used:c,budget:o,remaining:Math.max(0,o-c),skippedIds:a}}function bo(t,e){if(!e.from||!e.to||e.from===e.to)return{};const o=Math.max(0,Math.floor(Number(e.count??1)||0)),i=t.negativeIds.filter(t=>t===e.from).length,r=Math.min(o,i);return r?{addNegative:{[e.to]:r},popNegative:{ids:Array.from({length:r},()=>e.from)}}:{}}function xo(t,e){const o=fo(t.negativeIds,e.popNegative);if(!o.length)return[];const i=new Map;for(const t of o)i.set(t,(i.get(t)??0)+1);const r=[];return t.negativeIds.forEach((t,e)=>{const o=i.get(t)??0;o>0&&(r.push({propertyId:t,index:e}),i.set(t,o-1))}),r}function Io(t,e,o){if(e.when&&!e.when(o))return t;let i={...t};const r=go(i,e);r.length&&(i={...i,activePositiveIds:i.activePositiveIds.filter(t=>!r.includes(t)),poppedPositiveIds:Array.from(new Set([...i.poppedPositiveIds,...r]))});const n=xo(i,e);if(n.length){const t=new Set(n.map(t=>t.index));i={...i,negativeIds:i.negativeIds.filter((e,o)=>!t.has(o)),poppedNegativeIds:[...i.poppedNegativeIds,...n.map(t=>t.propertyId)]}}const s=yo(e.addPositive);s.length&&(i={...i,activePositiveIds:Array.from(new Set([...i.activePositiveIds,...s])),missingPositiveIds:i.missingPositiveIds.filter(t=>!s.includes(t))});const a=yo(e.addNegative);if(a.length&&(i={...i,negativeIds:[...i.negativeIds,...a]}),e.delayDelta&&(i={...i,delay:i.delay+e.delayDelta}),e.metricsDelta){const t={...i.metrics};for(const[o,i]of Object.entries(e.metricsDelta))t[o]=Number(t[o]??0)+i;i={...i,metrics:t}}return e.viabilityDelta&&(i={...i,viability:i.viability+e.viabilityDelta}),e.stage&&(i={...i,stage:e.stage}),e.outcome&&(i={...i,outcome:e.outcome}),i}function wo(t,e){return{id:t.id,label:t.label??t.id,summary:t.summary??e.find(t=>t.summary)?.summary,time:t.time}}function ko(t,e){return t.eventsApplied.includes(e.id)?t:{...t,eventsApplied:[...t.eventsApplied,e.id],eventHistory:[...t.eventHistory??[],e],lastEvent:e,stage:e.label??t.stage}}lo.displayName="CrucibleChart";import{forwardRef as Mo,useCallback as So,useEffect as Ao,useImperativeHandle as $o,useMemo as jo,useRef as Co,useState as Ro}from"react";var Po="gauntlet-core",Bo="gauntlet-positive",No="gauntlet-negative";function Oo(t){const e=Yo(t);return[{id:"gauntlet-left",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:e.top,x2:e.left,y2:t.floorY,thickness:e.thickness}},{id:"gauntlet-ceiling",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:e.top,x2:t.width-e.rightInset,y2:e.top,thickness:e.thickness}},{id:"gauntlet-floor",restitution:.12,friction:.42,shape:{type:"segment",x1:e.left,y1:t.floorY,x2:t.width-e.rightInset,y2:t.floorY,thickness:e.thickness}},{id:"gauntlet-right",restitution:.12,friction:.42,shape:{type:"segment",x1:t.width-e.rightInset,y1:e.top,x2:t.width-e.rightInset,y2:t.floorY,thickness:e.thickness}}]}function Eo(t,e,o,i){return o?"function"==typeof o?o(t,e):t[o]??i:i}function Wo(t){return t?.label??t?.id??"property"}function Ho(t){return`gauntlet:${t}:core`}function zo(t,e){return`gauntlet:${t}:positive:${e}`}function Do(t,e,o){return`gauntlet:${t}:negative:${e}:${o}`}var _o={left:28,top:76,rightInset:30,thickness:8};function Yo(t){const e=t.height??t.floorY+36;if(t.width>=220&&e>=160)return _o;const o=Math.max(1,Math.min(t.width,e)),i=Math.max(2,.04*t.width);return{left:i,top:Math.max(2,.08*e),rightInset:i,thickness:Math.max(1,Math.min(4,.04*o))}}function Fo(t){return Math.max(.12,Math.min(1,t.width/500,(t.height??t.floorY+36)/260))}function Lo(t,e,o,i){const r=Yo(i),n=Math.max(2,o+2),s=r.top+r.thickness/2+n,a=i.floorY-n,c=(t,e,o)=>e>o?(e+o)/2:Math.max(e,Math.min(o,t));return{x:c(t,r.left+r.thickness/2+n,i.width-r.rightInset-r.thickness/2-n),y:c(e,s,a)}}function To(t){return{graveyardX:t.graveyardX,graveyardY:t.graveyardY,routeY:t.routeY,socketX:t.socketX,socketY:t.routeY-4,startX:t.startX,startY:t.routeY}}function Go(t,e,o,i){const r=To(o),n=i?.(t,e,o)??{};return{...r,...n,startY:n.startY??n.routeY??r.startY,socketY:n.socketY??n.routeY??r.socketY,graveyardY:n.graveyardY??r.graveyardY}}function Xo(t,e,o=1){const i=[...t].sort((t,e)=>t.localeCompare(e)),r=Math.max(0,i.indexOf(e));return{angle:.82*-Math.PI+(i.length>1?r/(i.length-1):.5)*Math.PI*.64,index:r,radius:(48+r%2*6)*o}}function qo(t,e,o){const i=t.activePositiveIds.reduce((t,o)=>t+(e.get(o)?.value??1),0),r=t.missingPositiveIds.length+t.poppedPositiveIds.length,n=t.negativeIds.reduce((t,e)=>t+(o.get(e)?.load??1),0);return Math.max(0,Math.min(100,75+3*i-8*n-1.2*t.delay-5*r))}function Uo(t,e,o,i,r){const n=Eo(t,e,o.idAccessor,null!=t.id?t.id+"":"project-"+e)+"",s=i.map(t=>t.id),a=[...Eo(t,e,o.positiveAccessor,s)],c=[...Eo(t,e,o.negativeAccessor,[])].filter(t=>r.has(t));return{id:n,activePositiveIds:a,datum:t,delay:0,eventsApplied:[],eventHistory:[],killed:!1,metrics:{...Eo(t,e,o.metricsAccessor,{})},missingPositiveIds:s.filter(t=>!a.includes(t)),negativeIds:c,outcome:"in_process",poppedPositiveIds:[],poppedNegativeIds:[],startedAt:Math.max(0,Number(Eo(t,e,o.startTimeAccessor,0))||0),stage:"project filed",viability:Eo(t,e,o.initialViability,100)}}function Vo(t,e,o,i,r,n,s){const a=Fo(o),c=Math.max(3,28*a),d=i.startX,l=i.startY+(i.startY===o.routeY?38*e*a:0),u=s?.(t,e,o,i)??{},p=u.x??d,h=u.y??l,m={__gauntlet:!0,kind:Po,projectId:t.id,sourceDatum:t.datum},y=[{...u,id:Ho(t.id),x:p,y:h,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??t.startedAt,datum:m}],f=Lo(p,h,u.shape&&"radius"in u.shape&&Number(u.shape.radius)||c,o);y[0].x=f.x,y[0].y=f.y;for(const e of t.activePositiveIds){const i=r.get(e);if(!i)continue;const n=Xo(t.activePositiveIds,e,a),s=i.radius??Math.max(2,10*a),c=Lo(f.x+Math.cos(n.angle)*n.radius,f.y+Math.sin(n.angle)*n.radius,s,o);y.push({id:zo(t.id,e),x:c.x,y:c.y,vx:18*Math.cos(n.angle),vy:18*Math.sin(n.angle),mass:i.mass??.75,bodyCollisions:!1,shape:{type:"circle",radius:s},spawnAt:u.spawnAt??t.startedAt,datum:{__gauntlet:!0,kind:Bo,projectId:t.id,property:i,sourceDatum:t.datum},springs:!1===i.spring?[]:[{target:{type:"body",bodyId:Ho(t.id)},stiffness:.56,damping:.9,restLength:Math.max(6,(52+n.index%2*4)*a),...i.spring??{}}]})}return t.negativeIds.forEach((e,i)=>{const r=n.get(e);r&&y.push(Ko(t,r,i,f.x,f.y,o,u.spawnAt??t.startedAt))}),y}function Ko(t,e,o,i,r,n,s){const a=Fo(n),c=e.radius??Math.max(2,7.2*a),d=Lo(i+(o%4*12-12)*a,r+(54+12*Math.floor(o/4))*a,c,n);return{id:Do(t.id,e.id,o),x:d.x,y:d.y,vx:10,vy:6,mass:e.mass??.72,bodyCollisions:!1,shape:{type:"circle",radius:c},spawnAt:s,datum:{__gauntlet:!0,kind:No,projectId:t.id,property:e,sourceDatum:t.datum},springs:!1===e.spring?[]:[{target:{type:"body",bodyId:Ho(t.id)},stiffness:.62,damping:.92,restLength:Math.max(6,(52+o%4*3)*a),...e.spring??{}}]}}function Qo(t,e){const o=t.datum;return!(!o?.__gauntlet||o.projectId!==e||o.kind!==No)}function Zo(t){const e=t.id.slice(t.id.lastIndexOf(":")+1),o=Number(e);return Number.isFinite(o)?o:-1}function Jo(t,e){return 2>Math.hypot(t.vx,t.vy)&&4>Math.hypot(e.x,e.y)?null:e}import{Fragment as ti,jsx as ei,jsxs as oi}from"react/jsx-runtime";function ii(t){const e=t.data;return e?.__gauntlet?oi("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:[ei("strong",{children:e.kind===Po?"string"==typeof e.sourceDatum?.label?e.sourceDatum.label:e.projectId:Wo(e.property)}),ei("div",{children:e.kind===Bo?"Positive property":e.kind===No?"Negative property":"Project core"})]}):null}function ri(t,e,o){const i=e.datum;if(!i?.__gauntlet)return;const r="circle"===e.shape.type?e.shape.radius:8;if(t.save(),t.translate(e.x,e.y),i.kind===Po)t.fillStyle=ni(t,o.fill,"#0f766e"),t.strokeStyle=ni(t,o.stroke,"#f8fafc"),t.lineWidth=2.4,t.beginPath(),t.arc(0,0,r,0,2*Math.PI),t.fill(),t.stroke();else{const e=i.property;t.fillStyle=ni(t,o.fill??e?.color,"#38bdf8"),t.strokeStyle=ni(t,o.stroke,"#0f172a"),t.lineWidth=1.1,t.beginPath(),i.kind===No?t.rect(-r,-r,2*r,2*r):t.arc(0,0,r,0,2*Math.PI),t.fill(),t.stroke(),t.fillStyle=ni(t,"var(--semiotic-bg, #07111f)","#07111f"),t.font=`900 ${i.kind===No?9:8}px system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(e?.short??e?.id?.slice(0,1).toUpperCase()??"?",0,.5)}t.restore()}function ni(t,e,o){if("string"!=typeof e)return o;if("function"!=typeof getComputedStyle||!t.canvas)return e||o;const i=e.startsWith("var(")?e.match(/var\((--[^,\s)]+)/)?.[1]:e.startsWith("--")?e:null;return i?getComputedStyle(t.canvas).getPropertyValue(i).trim()||o:e||o}function si({layout:t,compact:e,showLabels:o}){const i=e?Math.round(.14*t.height):Math.max(80,t.routeY-180),r=e?Math.max(6,Math.round(.72*t.height)):Math.min(360,t.height-170);return ei(ti,{children:t.gates.map(n=>oi("g",{children:[ei("rect",{x:n.x-n.width/2,y:i,width:n.width,height:r,rx:e?2:12,fill:n.color??"var(--semiotic-primary, #38bdf8)",fillOpacity:.1,stroke:n.color??"var(--semiotic-primary, #38bdf8)",strokeDasharray:"5 5",strokeOpacity:.7}),o?ei("text",{x:n.x,y:Math.max(64,t.routeY-196),fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:n.label??n.id}):null]},n.id))})}function ai({layout:t,states:e,compact:o=!1}){return o?ei("svg",{"aria-hidden":"true",viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:ei(si,{layout:t,compact:!0,showLabels:!1})}):oi("svg",{"aria-hidden":"true",viewBox:`0 0 ${t.width} ${t.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[ei("path",{d:`M ${t.startX-42} ${t.routeY} C ${.24*t.width} ${t.routeY-70}, ${.42*t.width} ${t.routeY+78}, ${.58*t.width} ${t.routeY} S ${.78*t.width} ${t.routeY-82}, ${t.socketX+36} ${t.routeY}`,fill:"none",stroke:"var(--semiotic-primary, #38bdf8)",strokeDasharray:"18 12",strokeLinecap:"round",strokeOpacity:.45,strokeWidth:7}),ei("line",{x1:Math.round(.06*t.width),x2:Math.round(.94*t.width),y1:t.crashY,y2:t.crashY,stroke:"var(--semiotic-danger, #ef4444)",strokeDasharray:"3 7",strokeOpacity:.64}),ei("text",{x:Math.round(.07*t.width),y:t.crashY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:9,fontWeight:800,children:"CRASH LINE"}),ei(si,{layout:t,compact:!1,showLabels:!0}),oi("g",{children:[ei("rect",{x:t.socketX-52,y:t.routeY-56,width:104,height:112,rx:13,fill:"var(--semiotic-success, #22c55e)",fillOpacity:.12,stroke:"var(--semiotic-success, #22c55e)",strokeWidth:1.5}),ei("text",{x:t.socketX,y:t.routeY-72,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"SOCKET"})]}),oi("g",{children:[ei("rect",{x:t.graveyardX-82,y:t.graveyardY-34,width:164,height:58,rx:11,fill:"var(--semiotic-danger, #ef4444)",fillOpacity:.16,stroke:"var(--semiotic-danger, #ef4444)",strokeOpacity:.7}),ei("text",{x:t.graveyardX,y:t.graveyardY-8,fill:"var(--semiotic-danger, #ef4444)",fontSize:10,fontWeight:800,textAnchor:"middle",children:"GRAVEYARD"}),ei("text",{x:t.graveyardX,y:t.graveyardY+12,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,textAnchor:"middle",children:e.some(t=>t.killed)?"lift shut off":"too heavy or too small"})]})]})}function ci(t){const e=t.datum;return!!e?.__gauntlet&&(e.kind===Po?{label:e.projectId+" project core",group:"project",description:"Project core carrying positive and negative properties."}:{label:`${Wo(e.property)} ${e.kind===Bo?"positive":"negative"} property`,group:e.kind===Bo?"positive property":"negative property",description:`${Wo(e.property)} attached to ${e.projectId}.`})}function di({states:t,layout:e}){const o=function(t){return t.map(t=>({label:t.id,value:Math.max(0,Number(t.viability)||0),outcome:t.outcome||t.stage||"in-process"}))}(t);if(!o.length)return null;const i=Math.max(1,...o.map(t=>t.value)),r=Math.max(40,(e.width-80)/o.length);return oi("svg",{"aria-hidden":"true","data-testid":"gauntlet-projection-overlay",width:e.width,height:e.height,viewBox:`0 0 ${e.width} ${e.height}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[ei("text",{x:36,y:18,fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:800,children:"SETTLED · viability / outcome"}),o.map((t,e)=>{const o=40+e*r,n=Math.max(2,t.value/i*28),s=/kill|crash|block|grave/i.test(t.outcome);return oi("g",{children:[ei("rect",{x:o+.18*r,y:28-n+22,width:Math.max(10,.45*r),height:n,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}),ei("text",{x:o+.4*r,y:62,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #64748b)",fontSize:9,fontWeight:700,children:t.label})]},t.label)})]})}import{jsx as li}from"react/jsx-runtime";import{createElement as ui}from"react";var pi=[],hi=Mo(function(e,o){const{bodyGroups:i,coreBody:r,coreForceMode:n="route",crashDetection:s=!0,crashOffset:d=30,data:l,emptyContent:u,events:p,frameProps:h={},gates:m,initialSpawnPacing:b,loading:I,loadingContent:S,negativeProperties:A,onCapacityChange:$,onClick:j,onStateChange:C,outcome:R,paused:P,positiveProperties:B=pi,projectPlacement:N,rerunMS:O,responsiveHeight:E,responsiveWidth:W,seed:H,showTethers:z=!0,terminalBehavior:D="outcome",viability:_}=e,Y=Co(null),F=jo(()=>({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]),L=x(e,[900,520]),{chartSize:T,showProjection:G,showChrome:X,className:q,title:U,chartMode:V,margin:K,enableHover:Q,description:Z,summary:J,accessibleTable:tt}=L,{selection:et,onBodyHover:ot}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:void 0,chartType:"GauntletChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover,fallbackFields:"string"==typeof e.idAccessor?[e.idAccessor]:["id"],unwrapSourceDatum:!0}),it=y({data:l,emptyContent:u,loading:I,loadingContent:S,size:T}),rt=jo(()=>M(l??[]),[l]),nt=jo(()=>rt.map((t,e)=>Eo(t,e,F.idAccessor,null!=t.id?t.id+"":"project-"+e)+"").join("|"),[rt,F.idAccessor]),st=jo(()=>new Map(B.map(t=>[t.id,t])),[B]),at=jo(()=>new Map(A.map(t=>[t.id,t])),[A]),ct=jo(()=>function(t,e,o){const[i,r]=t,n=220>i||160>r,s=Math.round(.48*r),a=n?r-Math.max(3,Math.min(12,.1*r)):r-36,c=(e??[]).filter(t=>!1!==t.enabled),d=Math.max(1,c.length),l=.22*i,u=d>1?(.78*i-l)/(d-1):0,p=n?Math.max(Math.round(.12*i),.08*i+6):Math.max(Math.round(.14*i),110);return{crashY:a-(n?Math.min(o,Math.max(3,.22*r)):o),floorY:a,gates:c.map((t,e)=>({...t,id:t.id,x:t.x??Math.round(l+e*u),width:t.width??Math.max(n?8:54,Math.round(.07*i))})),graveyardX:Math.round(i*(n?.72:.84)),graveyardY:a-4,height:r,routeY:s,socketX:Math.round(i*(n?.82:.92)),startX:p,width:i}}(T,m,d),[T,d,m]),dt=jo(()=>new Map(ct.gates.map(t=>[t.id,t])),[ct.gates]),lt=jo(()=>ct.gates.map(t=>({kind:"force-field",damping:.035,force:{x:12,y:0},semanticItem:!1,...t.regionEffect,id:"gauntlet-gate-"+t.id,label:t.label??t.id,description:t.description,bodyFilter:t.capacity?{property:"datum.kind",equals:Po}:t.regionEffect?.bodyFilter,shape:{type:"aabb",x:t.x,y:ct.routeY,width:t.capacity?t.capacity.sensorWidth??Math.max(220>ct.width?12:96,t.width*(220>ct.width?2:6)):Math.max(t.width,220>ct.width?10:54),height:Math.max(4,Math.min(360,ct.height-(160>ct.height?8:170)))}})),[ct.gates,ct.height,ct.routeY,ct.width]),[ut,pt]=Ro(()=>rt.map((t,e)=>{const o=Uo(t,e,F,B,at);return{...o,viability:_?.(o,{negativeProperties:at,positiveProperties:st})??qo(o,st,at)}})),ht=Co(ut),mt=Co(0),yt=Co(new Map),ft=Co([]),gt=Co($);gt.current=$;const vt=Co(rt);vt.current=rt;const bt=Co(C);bt.current=C;const xt=Co({negativeById:at,positiveById:st,positiveProperties:B,stateAccessors:F,viability:_});xt.current={negativeById:at,positiveById:st,positiveProperties:B,stateAccessors:F,viability:_};const It=So((t,e,o=0)=>{const i=xt.current,r=Uo(t,e,i.stateAccessors,i.positiveProperties,i.negativeById);return i.stateAccessors.startTimeAccessor||(r.startedAt=Math.max(0,o)),{...r,viability:i.viability?.(r,{negativeProperties:i.negativeById,positiveProperties:i.positiveById})??qo(r,i.positiveById,i.negativeById)}},[]),wt=So(()=>{yt.current.clear(),ft.current=[],mt.current=0;const t=vt.current.map((t,e)=>It(t,e));ht.current=t,pt(t)},[It]),kt=jo(()=>({fixedDt:1/60,maxSubsteps:8,kernel:{gravity:{x:0,y:0},restitution:.16,friction:.44,velocityDamping:.982,maxVelocity:520,sleepAfter:.8,sleepSpeed:7,...null!=H&&{seed:H},...h.config?.kernel??{}},colliders:[...Oo(ct),...h.config?.colliders??[]]}),[h.config?.colliders,h.config?.kernel,ct,H]),Mt=w(kt,O,P,wt),St=jo(()=>function(t){const{dataKey:e,gates:o,statesRef:i,processedGateVisitsRef:r}=t;return o.flatMap(t=>t.capacity&&t.capacity.unitsPerSecond>0?[c({id:`gauntlet-capacity-${e}-${t.id}`,regionId:"gauntlet-gate-"+t.id,unitsPerSecond:t.capacity.unitsPerSecond,bodyFilter:{property:"datum.kind",equals:Po},maxQueue:t.capacity.maxQueue,queueLayout:t.capacity.queueLayout,queueSlotSpacing:t.capacity.queueSlotSpacing,queueStiffness:t.capacity.queueStiffness??24,releaseImpulse:{x:36,y:0},unitAccessor:e=>{const o=e.datum,r=o?.sourceDatum,n=t.capacity?.unitAccessor,s=i.current.find(t=>t.id===o?.projectId);let a;"function"==typeof n?a=s?n(s):void 0:n&&(a=r?.[n]);const c=Number(a??r?.reviewWork??r?.work??s?.metrics.reviewWork??r?.points);return Number.isFinite(c)&&c>0?c:1},onProcessed:e=>{const o=e.datum;if(!o?.projectId)return;const i=`${o.projectId}:${t.id}`;r.current.set(i,(r.current.get(i)??0)+1)}})]:[])}({dataKey:`${nt}:${Mt.rerunKey}`,gates:ct.gates,statesRef:ht,processedGateVisitsRef:yt}),[nt,ct.gates,Mt.rerunKey]),At=jo(()=>[...St,...h.controllers??[]],[St,h.controllers]);Ao(()=>{yt.current.clear(),ft.current=[],mt.current=0;const t=vt.current.map((t,e)=>It(t,e));ht.current=t,pt(t)},[It,nt]),Ao(()=>{ht.current=ut,bt.current?.(ut)},[ut]);const $t=So(t=>[...("function"==typeof p?p(t,ct):p)??[]].sort((t,e)=>t.time-e.time),[p,ct]),jt=So((t,e,o)=>{if(!e.gateId||!dt.get(e.gateId)?.capacity)return!0;const i=Number(e.gateVisit),r=Number.isFinite(i)&&i>0?Math.floor(i):o.filter(t=>t.gateId===e.gateId).findIndex(t=>t.id===e.id)+1;return r>0&&(yt.current.get(`${t.id}:${e.gateId}`)??0)>=r},[dt]),Ct=So(()=>{if(!St.length)return;const t=St.flatMap(t=>{const e=t.getSnapshot?.();return e?[e]:[]});var e,o;(e=ft.current).length===(o=t).length&&e.every((t,e)=>{const i=o[e];return!!i&&t.regionId===i.regionId&&t.queueDepth===i.queueDepth&&t.blockedDepth===i.blockedDepth&&t.processedCount===i.processedCount&&t.metricRevision===i.metricRevision})||(ft.current=t,gt.current?.(t))},[St]),Rt=jo(()=>ut.flatMap((t,e)=>{const o=Go(t,e,ct,N);return Vo(t,e,ct,o,st,at,r)}),[r,ct,at,st,N,ut]),Pt=So((t,e)=>{let o=!1;const i=ht.current.map(i=>{if(i.id!==t)return i;const r=e(i);return o=o||r!==i,r});o&&(ht.current=i,pt(i))},[]);$o(o,()=>function(t){const{statesRef:e,setStates:o,elapsedRef:i,frameRef:r,layout:n,projectPlacement:s,positiveById:a,negativeById:c,coreBody:d,createState:l}=t;return{push:t=>{const u=l(t,e.current.length,i.current),p=Go(u,e.current.length,n,s),h=Vo(u,e.current.length,n,p,a,c,d),m=[...e.current,u];e.current=m,o(m),r.current?.pushMany(h),r.current?.step(0)},pushMany:t=>{const u=[...e.current],p=[],h=i.current;t.forEach(t=>{const e=l(t,u.length,h),o=Go(e,u.length,n,s);p.push(...Vo(e,u.length,n,o,a,c,d)),u.push(e)}),e.current=u,o(u),p.length&&r.current?.pushMany(p),r.current?.step(0)},remove:t=>{const i=Array.isArray(t)?t:[t],n=[],s=[];for(const t of i){const o=e.current.find(e=>e.id===t);o&&(n.push(o.datum),s.push(Ho(o.id),...o.activePositiveIds.map(t=>zo(o.id,t))),o.negativeIds.forEach((t,e)=>{s.push(Do(o.id,t,e))}))}return e.current=e.current.filter(t=>!i.includes(t.id)),o(e.current),r.current?.remove(s),n},update:(t,u)=>{const p=Array.isArray(t)?t:[t],h=[];for(const t of p){const o=e.current.find(e=>e.id===t);if(!o)continue;const p=e.current.findIndex(e=>e.id===t);h.push(o.datum);const m=u(o.datum),y=l(m,0>p?e.current.length:p,o.startedAt??i.current),f=Go(y,0>p?e.current.length:p,n,s);r.current?.remove([Ho(o.id),...o.activePositiveIds.map(t=>zo(o.id,t)),...o.negativeIds.map((t,e)=>Do(o.id,t,e))]),r.current?.pushMany(Vo(y,0>p?e.current.length:p,n,f,a,c,d)),e.current=e.current.map(e=>e.id===t?y:e)}return o(e.current),h},clear:()=>{e.current=[],o([]),r.current?.clear()},getData:()=>e.current.map(t=>t.datum),getScales:()=>null,getCustomLayout:()=>r.current?.snapshot()??null,popBodies:(t,e)=>r.current?.popBodies(t,e)??[]}}({statesRef:ht,setStates:pt,elapsedRef:mt,frameRef:Y,layout:ct,projectPlacement:N,positiveById:st,negativeById:at,coreBody:r,createState:It}),[r,It,ct,at,st,N]);const Bt="sparkline"===V?.22:"mobile"===V?.55:1,Nt=So((t,e,o)=>{!function(t){const{project:e,effect:o,controls:i,layout:r,positiveById:n,negativeById:s,coreBody:a,popBodies:c,popScale:d}=t,l=i.readBodies().find(t=>t.id===Ho(e.id)),u=i.readBodies(),p=l?.x??r.startX,h=l?.y??r.routeY,m=function(t,e){let o=-1;for(const i of e)Qo(i,t.id)&&(o=Math.max(o,Zo(i)));return Math.max(t.negativeIds.length,o+1)}(e,u),y=yo(o.addNegative).flatMap((t,o)=>{const i=s.get(t);return i?[Ko(e,i,m+o,p,h,r)]:[]}),f=yo(o.addPositive).flatMap(t=>{if(!n.get(t)||e.activePositiveIds.includes(t))return[];const o={...To(r),routeY:h,socketY:h,startX:p,startY:h};return Vo({...e,activePositiveIds:[t],negativeIds:[]},0,r,o,n,s,a).filter(t=>t.id.includes(":positive:"))});(y.length||f.length)&&i.pushMany([...y,...f]);const g=go(e,o);for(const t of g){const o=n.get(t);c([zo(e.id,t)],{color:o?.popColor??o?.color,durationMs:900,radius:(o?.radius??10)+3,scale:d})}const v=xo(e,o),b=function(t,e,o){const i=e.filter(e=>Qo(e,t.id)).sort((t,e)=>Zo(t)-Zo(e)||t.id.localeCompare(e.id)),r=new Set;return o.map(e=>{const o=i.find(t=>!r.has(t.id)&&t.datum.property?.id===e.propertyId);return o?(r.add(o.id),o.id):Do(t.id,e.propertyId,e.index)})}(e,u,v);v.forEach((t,e)=>{const o=s.get(t.propertyId);c([b[e]],{color:o?.popColor??o?.color,durationMs:900,radius:(o?.radius??7)+3,scale:d})})}({project:t,effect:e,controls:o,layout:ct,positiveById:st,negativeById:at,coreBody:r,popBodies:(t,e)=>Y.current?.popBodies(t,e),popScale:Bt})},[r,ct,at,st,Bt]),Ot=So(({body:t,bodies:e})=>function(t){const{body:e,bodies:o,layout:i,states:r,projectPlacement:n,positiveById:s,negativeById:a,projectEvents:c,gateById:d,coreForceMode:l,terminalBehavior:u,elapsed:p}=t,h=e.datum;if(!h?.__gauntlet)return null;const m=r.findIndex(t=>t.id===h.projectId),y=0>m?void 0:r[m];if(!y)return null;const f=Go(y,m,i,n),g=o.find(t=>t.id===Ho(y.id)),v=Fo(i),b=y.negativeIds.reduce((t,e)=>t+(a.get(e)?.load??1),0),x=y.killed?0:58*Math.max(.25,v);if(h.kind!==Po){if(!g)return null;let t;const r=h.property;if(r?.target){const n=o.filter(t=>{const e=t.datum;return e?.__gauntlet&&e.projectId===y.id&&e.kind===h.kind}).sort((t,e)=>(t.id+"").localeCompare(e.id+"")),s=Math.max(0,n.findIndex(t=>t.id===e.id));t=r.target({body:e,bodies:o,core:g,index:s,layout:i,placement:f,project:y})??{x:g.x,y:g.y}}else if(h.kind===Bo&&h.property){const e=Xo(y.activePositiveIds,h.property.id,v);t={x:g.x+Math.cos(e.angle)*e.radius,y:g.y+Math.sin(e.angle)*e.radius-2}}else{const i=o.filter(t=>t.datum?.kind===No&&t.datum.projectId===y.id).sort((t,e)=>(t.id+"").localeCompare(e.id+"")),r=Math.max(0,i.findIndex(t=>t.id===e.id)),n=Math.floor(r/4);t={x:g.x+18*(r%4-(Math.min(4,i.length-4*n)-1)/2)*v,y:g.y+(54+13*n)*v}}const n="circle"===e.shape.type?e.shape.radius:8;t=Lo(t.x,t.y,n,i);const s=Lo(e.x,e.y,n,i);if(Math.abs(s.x-e.x)>.5||Math.abs(s.y-e.y)>.5)return{x:48*(s.x-e.x)-6*e.vx,y:48*(s.y-e.y)-6*e.vy};const a=h.kind!==Bo||y.killed?0:3.2*(r?.buoyancy??r?.value??1),c=h.kind===No?{x:.22*(r?.pull?.x??-8),y:.22*(r?.pull?.y??22)}:{x:0,y:0};return Jo(e,{x:28*(t.x-e.x)-3*(e.vx-g.vx)+c.x+.01*x,y:28*(t.y-e.y)-3*(e.vy-g.vy)+c.y-a})}if(y.killed)return Jo(e,{x:44*((y.crashX??y.metrics.lastX??e.x)-e.x)-9*e.vx,y:(160+12*b)*v-1.6*e.vy});const I=c(y),w=function(t,e,o,i,r,n,s){const a=Fo(o);if(e.killed)return{x:e.metrics.lastX??i.graveyardX,y:i.graveyardY};const c=r[r.length-1];if(!c)return{x:i.socketX,y:i.routeY};const d=r.find(o=>t>=o.time&&!e.eventsApplied.includes(o.id)&&!(!o.gateId||!n.get(o.gateId)?.capacity)),l=d?Math.min(t,d.time):t,u="built"===e.outcome||"built_diminished"===e.outcome;if(l>c.time+.85){if("hold-last"===s){const t=c.gateId?n.get(c.gateId):void 0;return{x:c.routeX??t?.x??i.socketX,y:c.routeY??i.routeY}}return u?{x:i.socketX,y:i.socketY}:{x:i.graveyardX,y:i.graveyardY-14}}const p=.85*e.delay+12*e.negativeIds.length+8*(e.poppedPositiveIds.length+e.missingPositiveIds.length),h=[{time:0,x:i.startX,y:i.startY},...r.map(t=>{const e=t.gateId?n.get(t.gateId):void 0;return{time:t.time,x:t.routeX??e?.x??i.startX,y:t.routeY??i.routeY+.28*Math.min(180,p)*a}})].sort((t,e)=>t.time-e.time);let m=h[0],y=h[h.length-1];for(let t=1;h.length>t;t+=1){if(h[t].time>=l){y=h[t];break}m=h[t]}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,p-(y.startedAt??0)),y,i,f,I,d,u),k=y.activePositiveIds.reduce((t,e)=>t+(s.get(e)?.buoyancy??s.get(e)?.value??1),0);return Jo(e,"net"===l?{x:15*(w.x-e.x)-1.8*e.vx+.18*x,y:1.25*(f.routeY-e.y)-1.4*e.vy+32*(b-k)}:{x:15*(w.x-e.x)-1.8*e.vx+.18*x,y:15*(w.y-e.y)-1.8*e.vy+13*b-2.2*k})}({body:t,bodies:e,layout:ct,states:ht.current,projectPlacement:N,positiveById:st,negativeById:at,projectEvents:$t,gateById:dt,coreForceMode:n,terminalBehavior:D,elapsed:mt.current}),[n,dt,ct,at,st,$t,N,D]),Et=So((t,e)=>{!function(t,e,o){const{frameProps:i,elapsedRef:r,statesRef:n,crashDetection:s,layout:a,projectEvents:c,gateById:d,capacityEventReady:l,addBodiesForEffect:u,updateProjectState:p,viability:h,positiveById:m,negativeById:y,outcome:f,reportCapacity:g}=o;i.onTick?.(t,e),r.current=t.elapsedSeconds??e.snapshot().elapsedSeconds,g();for(const t of n.current){const o=e.readBodies().find(e=>e.id===Ho(t.id));if(!o)continue;if(s&&!t.killed&&o.y+("circle"===o.shape.type?o.shape.radius:28)>=a.crashY){e.readBodies().forEach(o=>{const i=o.datum;i?.__gauntlet&&i.projectId===t.id&&e.applyImpulse(o.id,-o.vx*o.mass,0)}),p(t.id,t=>{const e={appliedAt:Math.max(0,r.current-(t.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,r.current-(t.startedAt??0))};return{...t,crashX:o.x,eventHistory:[...t.eventHistory??[],e],killed:!0,lastEvent:e,metrics:{...t.metrics,lastX:o.x},outcome:"bad_design_crash",stage:"Crash Line",viability:Math.min(0,t.viability)}});continue}if(t.killed)continue;const i=Math.max(0,r.current-(t.startedAt??0)),n=c(t),g=n.filter(e=>i>=e.time&&!t.eventsApplied.includes(e.id)&&l(t,e,n));let v=t;for(const o of g){const r=o.gateId?d.get(o.gateId):void 0,n=o.effects??[];for(const t of n){const i={event:o,gate:r,negativeProperties:y,positiveProperties:m,project:v};t.when&&!t.when(i)||(u(v,t,e),v=Io(v,t,i))}const s={...wo(o,n),appliedAt:i};v=ko(v,s),p(t.id,t=>{let e=ko(t,s);if(e===t)return t;for(const t of n)e=Io(e,t,{event:o,gate:r,negativeProperties:y,positiveProperties:m,project:e});const i=h?.(e,{negativeProperties:y,positiveProperties:m})??qo(e,m,y);return e={...e,viability:i},o.final&&(e={...e,outcome:o.outcome??f?.(e,{layout:a,negativeProperties:y,positiveProperties:m})??(e.viability>20?"built":"approved_not_built")}),e})}}}(t,e,{frameProps:h,elapsedRef:mt,statesRef:ht,crashDetection:s,layout:ct,projectEvents:$t,gateById:dt,capacityEventReady:jt,addBodiesForEffect:Nt,updateProjectState:Pt,viability:_,positiveById:st,negativeById:at,outcome:R,reportCapacity:Ct})},[Nt,jt,s,h,dt,ct,at,R,st,$t,Ct,Pt,_]),Wt=So((t,e)=>{const o="function"==typeof h.bodyStyle?h.bodyStyle(t,e):h.bodyStyle,i=t.datum;return i?.__gauntlet?{fill:i.kind===Po?"var(--semiotic-primary, #0f766e)":i.property?.color??"var(--semiotic-primary, #38bdf8)",stroke:i.kind===Po?"#f8fafc":"#0f172a",opacity:.96,...o}:o??{}},[h]),Ht=jo(()=>"function"==typeof i?i(ut,ct):i??[],[i,ct,ut]),zt=jo(()=>mo(Ht),[Ht]),Dt=jo(()=>G?function(t,e){if(!t.length)return[];const o=Math.max(40,(e.width-80)/t.length);return t.map((t,e)=>{const i=`${t.id}: viability ${Math.round(t.viability)}, ${t.outcome||t.stage}`;return{id:"gauntlet-projection-"+t.id,label:i,description:i,datum:t,x:40+(e+.5)*o,y:28,shape:"rect",width:Math.max(16,.55*o),height:22,group:"settled projection"}})}(ut,ct):[],[ct,G,ut]),_t=jo(()=>[...Dt,...zt],[zt,Dt]),Yt=So((t,e)=>{h.onBodyPointerDown?.(t,e)},[h]),Ft=So((t,e)=>{j&&(t&&"object"==typeof t&&t.__gauntlet?j(t.sourceDatum,{x:e.x,y:e.y}):t&&j(t,{x:e.x,y:e.y}))},[j]),Lt=So((t,e)=>{h.beforePaint?.(t,e),z&&function(t,e){const o=new Map(e.filter(t=>t.datum?.kind===Po).map(t=>[t.datum.projectId,t]));t.save(),t.lineWidth=1.1,t.setLineDash([3,4]);for(const i of e){const e=i.datum;if(!e?.__gauntlet||e.kind===Po)continue;const r=o.get(e.projectId);r&&(t.globalAlpha=e.kind===No?.24:.36,t.strokeStyle=e.kind===No?"#d94a45":"#7a8794",t.beginPath(),t.moveTo(r.x,r.y),t.lineTo(i.x,i.y),t.stroke())}t.restore()}(t,e)},[h,z]),Tt=jo(()=>[...lt,...h.regionEffects??[]],[h.regionEffects,lt]);if(it)return it;const Gt=v(e.tooltip,h),Xt=g(e,h,_t,{selection:et,chartMode:V,className:q,title:U,description:Z,summary:J,accessibleTable:tt,enableHover:Q,margin:K}),qt=G?li(di,{states:ut,layout:ct}):void 0,Ut=a(X?li(ai,{layout:ct,states:ut,compact:L.resolved.compactMode}):void 0,h.backgroundGraphics),Vt=a(qt,h.foregroundGraphics),Kt=h.renderBody??ri,Qt=Gt.tooltipContent??ii;return f("GauntletChart",T,ui(t,{...h,...Gt,...Xt,key:`${T[0]}x${T[1]}:${nt}:${Mt.rerunKey}`,ref:Y,onBodyHover:ot,accessibleTable:e.accessibleTable??h.accessibleTable,backgroundGraphics:Ut,bodyForces:Ot,bodySemanticItems:h.bodySemanticItems??ci,bodyStyle:Wt,beforePaint:Lt,onClick:j?Ft:Xt.onClick,config:Mt.config,controllers:At,enableHover:Gt.enableHover??!0,foregroundGraphics:Vt,hoverRadius:e.hoverRadius??h.hoverRadius??18,initialSpawns:Rt,initialSpawnPacing:b,onBodyPointerDown:Yt,onTick:Et,paused:P,regionEffects:Tt,renderBody:Kt,responsiveHeight:E,responsiveWidth:W,size:T,tooltipContent:Qt}))});hi.displayName="GauntletChart";var mi=hi;import{forwardRef as yi,useCallback as fi,useMemo as gi,useRef as vi}from"react";function bi(t){return t.toLocaleString(void 0,1e3>Math.abs(t)?{maximumFractionDigits:1}:{maximumFractionDigits:0})}function xi(t){return t.map((t,e)=>`${0===e?"M":"L"} ${t.x} ${t.y}`).join(" ")}import{jsx as Ii,jsxs as wi}from"react/jsx-runtime";import{createElement as ki}from"react";function Mi(t){if(!t||"object"!=typeof t)return null;const e=t,o=Number(e.x),i=Number(e.y);return Number.isFinite(o)&&Number.isFinite(i)?{x:o,y:i}:null}function Si(t){if(!t||"object"!=typeof t)return[];const e=t.flowPath;return Array.isArray(e)?e.map(Mi).filter(t=>null!=t):[]}function Ai(t,e){if(2>e.length)return null;let o=0;const i=[];for(let t=1;e.length>t;t+=1){const r=Math.hypot(e[t].x-e[t-1].x,e[t].y-e[t-1].y);i.push(r),o+=r}if(0>=o)return null;let r=null,n=0;for(let s=1;e.length>s;s+=1){const a=e[s-1],c=e[s],d=i[s-1];if(0>=d)continue;const l=c.x-a.x,u=c.y-a.y,p=Math.max(0,Math.min(1,((t.x-a.x)*l+(t.y-a.y)*u)/(d*d))),h={x:a.x+l*p,y:a.y+u*p},m={distance:Math.hypot(t.x-h.x,t.y-h.y),point:h,progress:(n+p*d)/o,tangent:{x:l/d,y:u/d},totalLength:o};r&&m.distance>=r.distance||(r=m),n+=d}return r}function $i(t,e,o){if(0===t.length)return{x:0,y:0};if(1===t.length||0>=o)return{...t[0]};let i=0;const r=Math.max(0,Math.min(1,e))*o;for(let e=1;t.length>e;e+=1){const o=t[e-1],n=t[e],s=Math.hypot(n.x-o.x,n.y-o.y);if(s>0){if(i+s>=r){const t=(r-i)/s;return{x:o.x+(n.x-o.x)*t,y:o.y+(n.y-o.y)*t}}i+=s}}return{...t[t.length-1]}}function ji(t){return"circle"===t.shape.type?t.shape.radius:Math.max(t.shape.width,t.shape.height)/2}function Ci(t,e,o){const i=Math.hypot(t,e);if(o>=i||0>=i)return[t,e];const r=o/i;return[t*r,e*r]}function Ri(t,e,o){const i=Ai({...t,x:e[0].x,y:e[0].y},e),r=i?.tangent??{x:e[1].x-e[0].x,y:e[1].y-e[0].y},n=Math.hypot(r.x,r.y)||1,s=r.x/n,a=r.y/n,c=ji(t),d=function(t,e){let o=0;for(let e=0;t.length>e;e+=1)o=31*o+t.charCodeAt(e)>>>0;return(o%1e3/1e3-.5)*e*1.4}(t.id,c);return{id:t.id,x:e[0].x+-a*d,y:e[0].y+s*d,vx:s*o,vy:a*o,mass:t.mass,shape:t.shape,datum:{...t.datum&&"object"==typeof t.datum?t.datum:{},routeProgress:0}}}var Pi=yi(function(e,o){const{chartId:i,colorBy:n,coordinateMode:s="auto",data:c,edges:d,emptyContent:l,flowSpeed:p=90,frameProps:h,links:m,loading:M,loadingContent:S,maxParticles:A=180,nodeIdAccessor:$="id",nodeXAccessor:j="x",nodeYAccessor:C="y",nodes:R,onObservation:P,particleRadius:B=4,particleRate:N=.16,pathAccessor:O="path",pathConstraint:E="path",paused:W,reducedMotion:H=!1,rerunMS:z,responsiveHeight:D,responsiveWidth:_,seed:Y=1,showNodeLabels:F=!0,showSensors:L=!1,showStaticFlow:T=!0,sourceAccessor:G="source",styleRules:X,targetAccessor:q="target",throughputAccessor:U="value"}=e,V=x(e,[760,420]),{chartSize:K,className:Q,title:Z,chartMode:J,margin:tt,enableHover:et,description:ot,summary:it,accessibleTable:rt}=V,nt=vi(null),st=gi(()=>R??[],[R]),at=gi(()=>m??d??c??[],[c,d,m]),ct=gi(()=>r({nodes:st,links:at,nodeIdAccessor:$,nodeXAccessor:j,nodeYAccessor:C,sourceAccessor:G,targetAccessor:q,throughputAccessor:U,pathAccessor:O,coordinateMode:s,particleRate:N,maxParticles:A,particleRadius:B,flowSpeed:p,pathConstraint:E,reducedMotion:H,seed:Y,size:K}),[at,st,K,s,p,A,$,j,C,B,N,O,E,H,Y,G,q,U]),dt=fi((t,e)=>{const o=r({nodes:st,links:[t],nodeIdAccessor:$,nodeXAccessor:j,nodeYAccessor:C,sourceAccessor:G,targetAccessor:q,throughputAccessor:U,pathAccessor:O,coordinateMode:s,particleRate:N,maxParticles:A,particleRadius:B,flowSpeed:p,pathConstraint:E,reducedMotion:H,seed:Y+e+1,size:K}),i={id:(t.id??"physical-flow-push-"+e)+"",x:u(K).plot.x,y:u(K).plot.y,mass:1,shape:{type:"circle",radius:B},datum:t},n=o.initialSpawns.length?o.initialSpawns:[i];return{datumId:(t.id??n[0].id)+"",spawns:n}},[st,K,s,p,A,$,j,C,B,N,O,E,H,Y,G,q,U]);I(o,{frameRef:nt,spawnDatum:dt,seedRows:at,seedSpawns:ct.initialSpawns});const lt=n??"source",ut=gi(()=>b(lt,"#2563eb",{styleRules:X,valueAccessor:U}),[lt,X,U]),pt=gi(()=>function(t,e,o){return{...t,observation:{...t.observation,chartId:e??t.observation?.chartId??"physical-flow",chartType:"PacketFlowChart",onObservation:o??t.observation?.onObservation}}}(ct.config,i,P),[i,ct.config,P]),ht=w(pt,z,W),mt=vi(h?.onTick);mt.current=h?.onTick;const yt=fi((t,e)=>{H||"none"===E||function(t,e){const o=t.readBodies(),i=[],r=[];for(const n of o){const o=Si(n.datum);if(2>o.length)continue;const s=Ai(n,o);if(!s)continue;const a=n.datum,c=Number(a?.flowSpeed),d=Number.isFinite(c)&&c>0?c:e;if(s.progress>=.985||s.distance>Math.max(90,14*ji(n))){i.push(n.id),r.push(Ri(n,o,d));continue}const l=$i(o,Math.min(1,s.progress+Math.max(.035,Math.min(.12,d/s.totalLength*.16))),s.totalLength),u=s.tangent,p=(u.x*d-n.vx)*n.mass*.16+(l.x-n.x)*n.mass*.045+(s.point.x-n.x)*n.mass*.08,h=(u.y*d-n.vy)*n.mass*.16+(l.y-n.y)*n.mass*.045+(s.point.y-n.y)*n.mass*.08,[m,y]=Ci(p,h,n.mass*d*.35);t.applyImpulse(n.id,m,y)}i.length&&t.remove(i),r.length&&t.pushMany(r)}(e,p),mt.current?.(t,e)},[p,E,H]),{selection:ft,onBodyHover:gt}=k({selection:e.selection,linkedHover:e.linkedHover,colorBy:n,chartType:"PacketFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:h?.onBodyHover,fallbackFields:"string"==typeof G?[G]:void 0}),vt=y({data:null==m&&null==d&&null==c?void 0:at,emptyContent:l,loading:M,loadingContent:S,size:K});if(vt)return vt;const bt=function(t,e){const{showNodeLabels:o,showSensors:i,showStaticFlow:r}=e;if(t&&(r||i))return({size:e})=>{const n=[Number(e[0])||760,Number(e[1])||420],s=Math.max(1,...t.links.map(t=>t.throughput)),a=new Set(t.nodes.map(t=>t.sensorId));return wi("svg",{"aria-hidden":"true","data-testid":"physical-flow-static-flow-overlay",width:n[0],height:n[1],viewBox:`0 0 ${n[0]} ${n[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:[r?t.links.map(t=>{const e=3+t.throughput/s*16,o=t.path[Math.floor(t.path.length/2)];return wi("g",{children:[Ii("path",{d:xi(t.path),fill:"none",stroke:"var(--semiotic-border, #d1d5db)",strokeWidth:e+5,strokeLinecap:"round",strokeLinejoin:"round",opacity:.26}),Ii("path",{d:xi(t.path),fill:"none",stroke:"var(--semiotic-primary, #4e79a7)",strokeWidth:e,strokeLinecap:"round",strokeLinejoin:"round",opacity:.16}),o?Ii("text",{x:o.x,y:o.y-e/2-5,textAnchor:"middle",fill:"var(--semiotic-text-secondary, #555)",fontSize:10,fontWeight:700,children:bi(t.throughput)}):null]},t.id)}):null,t.nodes.map(t=>wi("g",{children:[i&&a.has(t.sensorId)?Ii("rect",{"data-testid":"physical-flow-sensor-overlay",x:t.x-12,y:t.y-12,width:24,height:24,rx:4,fill:"none",stroke:"var(--semiotic-warning, #f59e0b)",strokeDasharray:"3 3",strokeWidth:1.5,opacity:.88}):null,r?Ii("circle",{cx:t.x,cy:t.y,r:6,fill:"var(--semiotic-bg, #fff)",stroke:"var(--semiotic-text-secondary, #555)",strokeWidth:1.2}):null,o?Ii("text",{x:t.x,y:t.y-14,textAnchor:"middle",fill:"var(--semiotic-text, #111827)",fontSize:11,fontWeight:800,children:t.label}):null]},t.id))]})}}(ct.metadata,{showNodeLabels:F,showSensors:L,showStaticFlow:T}),xt=(It=ct.metadata)?It.links.map(t=>{const e=t.path[Math.floor(t.path.length/2)]??t.path[0],o=`${t.sourceLabel} to ${t.targetLabel}: ${bi(t.throughput)} throughput, ${t.packetCount} packets`;return{id:t.id,label:o,description:o,datum:t,x:e?.x??0,y:e?.y??0,shape:"path",pathData:xi(t.path),group:"flow"}}):[];var It;const wt=v(e.tooltip,h),kt=g(e,h,xt,{selection:ft,chartMode:J,className:Q,title:Z,description:ot,summary:it,accessibleTable:rt,enableHover:et,margin:tt});return f("PacketFlowChart",K,ki(t,{...h,...wt,...kt,key:ht.rerunKey,ref:nt,onBodyHover:gt,config:ht.config,continuous:!H&&"none"!==E,foregroundGraphics:a(bt,h?.foregroundGraphics),initialSpawns:ct.initialSpawns,onTick:yt,paused:W||H,responsiveHeight:D,responsiveWidth:_,simulationExecution:"none"===E?h?.simulationExecution:"sync",size:K,bodyStyle:ut,workerBodyThreshold:h?.workerBodyThreshold??1/0}))});Pi.displayName="PacketFlowChart";var Bi=Pi;import{Fragment as Ni,jsx as Oi,jsxs as Ei}from"react/jsx-runtime";var Wi={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 Hi(t,e,o){return Math.max(e,Math.min(o,t))}function zi(t){return 6.2*t.length}function Di(t,e){const o=t.trim();if(e>=o.length)return o;if(1>=e)return o.slice(0,1);const i=o.split(/\s+/).filter(Boolean).map(t=>t[0]).join("").toUpperCase();return i.length>1&&e>=i.length?i:e>3?o.slice(0,Math.max(1,e-2))+"..":o.slice(0,e).toUpperCase()}function _i(t,e,o="auto"){const i=Math.max(1,Math.floor(e/6.2)),r="compact"===o?Di(t,i):"full"===o?t:zi(t)>e?Di(t,i):t;return{text:r,textLength:zi(r)>e?Math.max(4,e):void 0}}function Yi(t,e={}){const{showFlowSpine:o=!0,showStageCounts:i=!0,showCapacityBadges:r=!0,showGroupSockets:n=!0,stageLabelMode:s="auto",outlineStages:a=!1,testId:c="process-flow-chrome"}=e,{width:d,height:l,left:u,right:p,topY:h,bottomY:m,midY:y,stages:f,groups:g=[]}=t,v=m-h;return Ei("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:[Oi("defs",{children:Ei("linearGradient",{id:"semiotic-process-floor",x1:"0",x2:"0",y1:"0",y2:"1",children:[Oi("stop",{offset:"0%",stopColor:"var(--semiotic-process-floor, var(--semiotic-bg, #0f172a))",stopOpacity:"0.2"}),Oi("stop",{offset:"100%",stopColor:"var(--semiotic-process-lane, var(--semiotic-surface, #1e293b))",stopOpacity:"0.55"})]})}),Oi("rect",{x:0,y:0,width:d,height:l,fill:"url(#semiotic-process-floor)"}),Oi("rect",{x:u-6,y:h-8,width:p-u+12,height:v+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}),o?Oi("line",{x1:u+8,x2:p-8,y1:y,y2:y,stroke:"var(--semiotic-process-border, var(--semiotic-border, #475569))",strokeWidth:2,strokeDasharray:"6 8",opacity:.55}):null,f.map((t,e)=>{const o=function(t){return t.absorb?"absorb":t.portalTarget?"portal":null!=t.capacity?"capacity":"flow"}(t),n=Wi[o],c=Math.max(12,t.width-8),d=Hi(c-8,22,88),u=_i(t.label,Math.max(8,d-10),s),p="none"!==s&&c-8>=22,g=function(t){if(null!=t.capacity){const e=null!=t.queueDepth?" · q "+t.queueDepth:"";return t.capacityLabel?`${t.capacityLabel}${e}`:`cap ${Number.isInteger(t.capacity)?t.capacity+"":t.capacity.toFixed(1)}${e}`}return t.absorb?"absorb":t.portalTarget?"portal":"flow"}(t),b=_i(g,Math.max(16,c-10),"auto"),x=r&&!1!==t.showBadge&&c>=32,I=null!=t.count?`n=${t.count}${null!=t.processed?" done "+t.processed:""}`:"",w=_i(I,Math.max(16,c-8),"auto"),k=Math.max(30,h-15),M=k-13;return Ei("g",{"data-stage":t.id,"data-role":o,children:[Oi("rect",{className:"semiotic-process-chrome__stage-bay",x:t.x0+4,y:h+6,width:c,height:v-12,rx:10,fill:a?"none":n.fill,stroke:n.stroke,strokeWidth:a?1.85:"flow"===o?1:1.6}),f.length-1>e?Oi("polygon",{points:`${t.x1-2},${y-7} ${t.x1+8},${y} ${t.x1-2},${y+7}`,fill:n.accent,opacity:.85}):null,p?Ei(Ni,{children:[Oi("rect",{className:"semiotic-process-chrome__stage-label-bg",x:t.x-d/2,y:M,width:d,height:18,rx:9,fill:"var(--semiotic-bg, #0f172a)",fillOpacity:.75,stroke:n.stroke}),Ei("text",{x:t.x,y:k,textAnchor:"middle",fill:n.accent,fontSize:10,fontWeight:800,className:"semiotic-process-chrome__stage-label",textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[Oi("title",{children:t.label}),u.text]})]}):null,x?Ei("text",{x:t.x,y:h+22,textAnchor:"middle",fill:"var(--semiotic-process-muted, var(--semiotic-text-secondary, #94a3b8))",fontSize:9,fontWeight:700,textLength:b.textLength,lengthAdjust:b.textLength?"spacingAndGlyphs":void 0,children:[Oi("title",{children:g}),b.text]}):null,i&&null!=t.count?Ei("text",{x:t.x,y:Math.min(l-8,m+16),textAnchor:"middle",fill:"var(--semiotic-process-text, var(--semiotic-text, #e2e8f0))",fontSize:11,fontWeight:800,textLength:w.textLength,lengthAdjust:w.textLength?"spacingAndGlyphs":void 0,children:[Oi("title",{children:I}),w.text]}):null]},t.id)}),n?g.map((t,e)=>{const o=t.total??0,i=t.absorbed??0,r=t.complete??(o>0&&i>=o),n=!r&&o>0&&i/o>=.75,s=r?"rgba(52, 211, 153, 0.35)":n?"rgba(251, 191, 36, 0.28)":"rgba(15, 23, 42, 0.75)",a=r?"#34d399":n?"#fbbf24":"var(--semiotic-border, #64748b)",c=o>0?`${i}/${o}${r?" shipped":n?" almost":""}`:"feature "+(e+1),d=Hi(Math.max(54,zi(t.label)+18,zi(c)+16),54,104),l=_i(t.label,d-12,"auto"),u=_i(c,d-12,"auto");return Ei("g",{"data-group":t.id,children:[Oi("rect",{x:t.x-d/2,y:t.y-22,width:d,height:44,rx:10,fill:s,stroke:a,strokeWidth:1.5}),Ei("text",{x:t.x,y:t.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:[Oi("title",{children:t.label}),l.text]}),Ei("text",{x:t.x,y:t.y+12,textAnchor:"middle",fill:a,fontSize:9,fontWeight:700,textLength:u.textLength,lengthAdjust:u.textLength?"spacingAndGlyphs":void 0,children:[Oi("title",{children:c}),u.text]})]},t.id)}):null]})}import{forwardRef as Fi,useCallback as Li,useEffect as Ti,useMemo as Gi,useRef as Xi,useState as qi}from"react";import{jsx as Ui}from"react/jsx-runtime";var Vi=Fi(function(e,o){const{ballRadius:i=6,chromeOptions:r,colorBy:n,data:d,emptyContent:l,frameProps:p={},groupAnchorAlong:h,groupBy:S,groupCompletion:A,groupLabelAccessor:$,gravityX:j,gravityY:C,idAccessor:R,initialSpawnPacing:P,liveCapacity:B=!0,onCapacityChange:N,selection:O,bodyLimit:E,bodyMark:W,loading:H,loadingContent:z,paused:D,radiusAccessor:_,rerunMS:Y,responsiveHeight:F,responsiveWidth:L,route:T="horizontal",seed:G=1,settle:X,springDamping:q,springStiffness:U,stageAccessor:V="stage",stages:K,workAccessor:Q}=e,Z=x(e,[900,420]),{chartSize:J,showProjection:tt,showChrome:et,className:ot,title:it,chartMode:rt,margin:nt,enableHover:st,description:at,summary:ct,accessibleTable:dt}=Z,lt=Xi(null),ut=Gi(()=>M(d??[]),[d]),pt=Gi(()=>({data:ut,stages:K,size:J,idAccessor:R,stageAccessor:V,groupBy:S,groupLabelAccessor:$,workAccessor:Q,radiusAccessor:_,ballRadius:i,seed:G,route:T,groupCompletion:A,groupAnchorAlong:h,springStiffness:U,springDamping:q,gravityX:j,gravityY:C,settle:X}),[i,J,j,C,h,S,A,$,R,_,T,ut,G,X,q,U,V,K,Q]),ht=Gi(()=>s(pt),[pt]),mt=ht.metadata,yt=Li((t,e)=>{const o=s({...pt,data:[t],seed:G+e+1,settle:!0}).initialSpawns[0]??{id:(t.id??"process-flow-push-"+e)+"",x:u(J).plot.x,y:u(J).plot.y,mass:1,shape:{type:"circle",radius:i},datum:t};return{datumId:(t.id??o.id)+"",spawns:[o]}},[i,pt,J,G]);I(o,{frameRef:lt,spawnDatum:yt,seedRows:ut,seedSpawns:ht.initialSpawns});const ft=Gi(()=>b(n),[n]),gt=Gi(()=>{if(!B)return p.controllers;const t=[...K.filter(t=>t.capacity&&t.capacity.unitsPerSecond>0).map(t=>{const e=t.capacity.unitsPerSecond;return c({id:"process-capacity-"+t.id,regionId:"process-stage-"+t.id,unitsPerSecond:e,unitAccessor:t.capacity.unitAccessor??(Q?"string"==typeof Q?Q:t=>{const e=t.datum;if(!e)return 1;try{return Number(Q(e,0))||1}catch{return 1}}:"work"),releaseImpulse:{x:70+Math.min(40,2*e),y:0},queueLayout:"lane",continuous:!0})}),...p.controllers??[]];return t.length?t:void 0},[p.controllers,B,K,Q]),[vt,bt]=qi({}),xt=Xi(gt);xt.current=gt;const It=Xi(p.onTick);It.current=p.onTick;const wt=!1!==et||null!=N;Ti(()=>{if(!N)return;const t=Object.values(vt);t.length&&N(t)},[vt,N]);const kt=Li((t,e)=>{if(It.current?.(t,e),!wt)return;const o=xt.current;if(!o?.length)return;const i={};for(const t of o){const e=t.getSnapshot?.();e&&"string"==typeof e.regionId&&(i[e.regionId]=e)}bt(t=>function(t,e){const o=Object.keys(t),i=Object.keys(e);if(o.length!==i.length)return!1;for(const i of o){const o=t[i],r=e[i];if(!r)return!1;if(o.queueDepth!==r.queueDepth||o.blockedDepth!==r.blockedDepth||o.processedCount!==r.processedCount||o.unitsPerSecond!==r.unitsPerSecond||o.regionId!==r.regionId||o.metricRevision!==r.metricRevision)return!1}return!0}(t,i)?t:i)},[wt]),Mt=Gi(()=>{const t=ft,e=p.bodyStyle;return W||e?(o,i)=>{const r="function"==typeof e?e(o,i):e;return{..."function"==typeof t?t(o):t,...r,mark:r?.mark??o.datum?.__physicsMark??o.datum?.mark??W}}:t},[W,ft,p.bodyStyle]),St=Gi(()=>({...ht.config,...null!=E?{bodyLimit:E,eviction:"oldest"}:{},...p.config}),[E,p.config,ht.config]),At=w(St,Y,D),{selection:$t,onBodyHover:jt}=k({selection:O,linkedHover:e.linkedHover,colorBy:n,chartType:"ProcessFlowChart",chartId:e.chartId,onObservation:e.onObservation,onClick:e.onClick,onBodyHover:p?.onBodyHover,fallbackFields:"string"==typeof V?[V]:void 0}),Ct=y({data:d,emptyContent:l,loading:H,loadingContent:z,size:J});if(Ct)return Ct;if(!K?.length)return f("ProcessFlowChart",J,Ui("div",{role:"status",style:{width:J[0],height:J[1],display:"grid",placeItems:"center",color:"var(--semiotic-text-secondary, #64748b)"},children:"ProcessFlowChart requires a non-empty stages array."}));const Rt=function(t,e,o={},i){if(!1===e||!t)return;const{volume:r,stages:n,groups:s,groupCompletion:a}=t,c=new Map(r.stages.map(t=>[t.id,t])),d=new Map(a.map(t=>[t.id,t]));return({size:t})=>{const e=Number(t[0])||r.width,a=Number(t[1])||r.height,l=n.map(t=>{const e=c.get(t.id),i=o["process-stage-"+t.id];return{id:t.id,label:t.label,x0:e?.x0??t.x-t.width/2,x1:(e?.x0??t.x-t.width/2)+(e?.width??t.width),x:t.x,width:e?.width??t.width,count:t.count,capacity:t.capacity,absorb:t.absorb,portalTarget:t.portalTarget,queueDepth:i?.queueDepth,processed:i?.processedCount}}),u=s.map(t=>{const e=d.get(t.id);return{id:t.id,label:t.label??t.id,x:t.anchor?.x??t.x??0,y:t.anchor?.y??t.y??0,absorbed:e?.absorbed,total:e?.total,complete:e?.complete}});return Yi({width:e,height:a,left:r.left,right:r.right,topY:r.topY,bottomY:r.bottomY,midY:r.midY,stages:l,groups:u},{showCapacityBadges:!0,showGroupSockets:!0,...i})}}(mt,et,vt,r),Pt=function(t,e,o){if(!1===o||!e||0===t.length)return;const i=new Map(e.volume.stages.map(t=>[t.id,t]));return({size:o})=>{const r=[Number(o[0])||e.volume.width,Number(o[1])||e.volume.height],n=u(r),s=Math.max(1,...t.map(t=>t.value)),a=Math.min(48,.18*n.plot.height),c=n.plot.y+6;return Ui("svg",{"aria-hidden":"true","data-testid":"process-flow-projection-overlay",width:r[0],height:r[1],viewBox:`0 0 ${r[0]} ${r[1]}`,style:{position:"absolute",inset:0,pointerEvents:"none"},children:e.stages.map((e,o)=>{const r=t[o];if(!r)return null;const n=i.get(e.id);if(!n)return null;const d=Math.max(2,r.value/s*a),l=Math.max(8,.35*n.width);return Ui("rect",{x:n.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},e.id)})})}}(ht.projectionRows,mt,tt),Bt=[...m(ht.projectionRows,J,"stage"),...mo(mt?.groups??[])],Nt=v(e.tooltip,p),Ot=g(e,p,Bt,{chartMode:rt,className:ot,title:it,description:at,summary:ct,accessibleTable:dt,enableHover:st,margin:nt}),Et=[...mt?.regionEffects??[],...p.regionEffects??[]];return f("ProcessFlowChart",J,Ui(t,{...p,...Nt,...Ot,ref:lt,onBodyHover:jt,controllers:gt,regionEffects:Et,selection:$t??p.selection,backgroundGraphics:a(Rt,p.backgroundGraphics),foregroundGraphics:a(Pt,p.foregroundGraphics),initialSpawns:ht.initialSpawns,initialSpawnPacing:P??ht.initialSpawnPacing,onTick:kt,paused:D,responsiveHeight:F,responsiveWidth:L,size:J,bodyStyle:Mt,config:At.config}))});Vi.displayName="ProcessFlowChart";export{E as GaltonBoardChart,L as EventDropChart,Q as UnitPileChart,Z as PhysicsPileChart,st as CollisionSwarmChart,ut as cloneCrucibleState,ft as resolveCrucibleSelector,St as applyCrucibleEvent,At as buildCrucibleProjection,$t as crucibleProjectionRows,jt as evaluateCrucibleConservation,Ct as buildCrucibleEvidence,Rt as DEFAULT_CRUCIBLE_WIDTH,Pt as DEFAULT_CRUCIBLE_HEIGHT,Bt as DEFAULT_CRUCIBLE_SIZE,Nt as DEFAULT_CRUCIBLE_OUTLETS,Ft as createInitialCrucibleState,Tt as buildCrucibleLayout,Xt as crucibleBoundaryColliders,Vt as buildCruciblePhysicsConfig,Kt as crucibleComponentBodyId,Qt as crucibleProductBodyId,Zt as crucibleBondId,ee as buildCrucibleInitialSpawns,ne as buildCrucibleStateSpawns,se as buildCrucibleTerminalSpawns,ce as crucibleSemanticKey,de as resolveCrucibleTime,le as resolveCrucibleSnapshotAt,ue as replayCruciblePlan,pe as compileCruciblePlan,ye as buildCrucibleProductEvents,lo as CrucibleChart,uo as physicsProcessBoundaryColliders,po as physicsProcessRegionSemanticItem,ho as physicsProcessStageSemanticItems,mo as physicsProcessGroupSemanticItems,qo as defaultViability,vo as planGauntletPropertyWork,bo as replaceGauntletNegative,Io as applyGauntletEffect,wo as eventLogItem,ko as recordGauntletEvent,hi as GauntletChart,mi as GuantletChart,Pi as PacketFlowChart,Bi as PhysicalFlowChart,Yi as processChrome,Vi as ProcessFlowChart};
|