@likec4/diagram 1.42.1 → 1.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (309) hide show
  1. package/bundle/index.js +6198 -4860
  2. package/dist/LikeC4Diagram.d.ts +1 -1
  3. package/dist/LikeC4Diagram.js +15 -12
  4. package/dist/LikeC4Diagram.props.d.ts +28 -14
  5. package/dist/LikeC4ProjectsProvider.js +1 -1
  6. package/dist/LikeC4View.d.ts +28 -4
  7. package/dist/LikeC4View.js +28 -17
  8. package/dist/ReactLikeC4.d.ts +1 -1
  9. package/dist/ReactLikeC4.js +5 -7
  10. package/dist/StaticLikeC4Diagram.js +2 -2
  11. package/dist/_virtual/_commonjsHelpers.js +3 -0
  12. package/dist/_virtual/assign-dea9f7c8.cjs.js +3 -0
  13. package/dist/_virtual/log-ec8d4df4.cjs.js +3 -0
  14. package/dist/_virtual/raise-da5b247f.cjs.js +3 -0
  15. package/dist/_virtual/xstate-actions.cjs.js +5 -0
  16. package/dist/_virtual/xstate-actions.cjs2.js +3 -0
  17. package/dist/_virtual/xstate-dev.cjs.js +3 -0
  18. package/dist/_virtual/xstate-guards.cjs.js +5 -0
  19. package/dist/_virtual/xstate-guards.cjs2.js +3 -0
  20. package/dist/base/Background.d.ts +2 -1
  21. package/dist/base/Background.js +11 -2
  22. package/dist/base/Base.d.ts +28 -0
  23. package/dist/base/BaseXYFlow.d.ts +5 -5
  24. package/dist/base/BaseXYFlow.js +38 -44
  25. package/dist/base/const.d.ts +1 -1
  26. package/dist/base/const.js +1 -1
  27. package/dist/base/index.d.ts +6 -2
  28. package/dist/base/types.d.ts +1 -28
  29. package/dist/base/updateEdges.js +4 -3
  30. package/dist/base/updateNodes.js +3 -2
  31. package/dist/base-primitives/compound/CompoundActionButton.js +1 -1
  32. package/dist/base-primitives/compound/CompoundDetailsButton.js +1 -1
  33. package/dist/base-primitives/edge/EdgeActionButton.js +1 -1
  34. package/dist/base-primitives/edge/EdgeContainer.d.ts +1 -1
  35. package/dist/base-primitives/edge/EdgeContainer.js +4 -0
  36. package/dist/base-primitives/edge/EdgeLabel.d.ts +1 -0
  37. package/dist/base-primitives/edge/EdgeLabel.js +2 -0
  38. package/dist/base-primitives/edge/EdgeLabelContainer.d.ts +1 -1
  39. package/dist/base-primitives/edge/EdgeLabelContainer.js +4 -0
  40. package/dist/base-primitives/edge/EdgePath.d.ts +4 -0
  41. package/dist/base-primitives/edge/EdgePath.js +9 -5
  42. package/dist/base-primitives/element/ElementActionButtons.d.ts +3 -2
  43. package/dist/base-primitives/element/ElementActionButtons.js +1 -1
  44. package/dist/base-primitives/element/ElementDetailsButton.js +2 -5
  45. package/dist/base-primitives/element/ElementNodeContainer.css.js +15 -27
  46. package/dist/base-primitives/element/ElementTags.js +2 -1
  47. package/dist/base-primitives/memoEdge.js +4 -2
  48. package/dist/base-primitives/memoNode.d.ts +1 -1
  49. package/dist/base-primitives/memoNode.js +3 -3
  50. package/dist/components/ErrorFallback.js +52 -35
  51. package/dist/components/Link.js +2 -2
  52. package/dist/context/DiagramEventHandlers.js +2 -1
  53. package/dist/context/DiagramFeatures.d.ts +24 -6
  54. package/dist/context/DiagramFeatures.js +28 -56
  55. package/dist/context/IconRenderer.js +6 -6
  56. package/dist/context/LikeC4ModelContext.js +3 -10
  57. package/dist/context/TagStylesContext.js +2 -18
  58. package/dist/context/index.d.ts +1 -1
  59. package/dist/custom/customNodes.js +3 -2
  60. package/dist/custom/hooks.d.ts +1 -1
  61. package/dist/custom/index.d.ts +1 -1
  62. package/dist/custom/index.js +4 -4
  63. package/dist/editor/LikeC4EditorContext.d.ts +21 -0
  64. package/dist/editor/index.d.ts +2 -0
  65. package/dist/hooks/index.d.ts +2 -1
  66. package/dist/hooks/safeContext.d.ts +6 -3
  67. package/dist/hooks/safeContext.js +10 -3
  68. package/dist/hooks/useCallbackRef.d.ts +1 -0
  69. package/dist/hooks/useCallbackRef.js +13 -0
  70. package/dist/hooks/useCurrentView.d.ts +11 -0
  71. package/dist/hooks/{useCurrentViewId.js → useCurrentView.js} +7 -3
  72. package/dist/hooks/useCurrentViewModel.js +4 -1
  73. package/dist/hooks/useDiagram.d.ts +7 -113
  74. package/dist/hooks/useDiagram.js +7 -127
  75. package/dist/hooks/useDiagramCompareLayout.d.ts +35 -0
  76. package/dist/hooks/useDiagramCompareLayout.js +60 -0
  77. package/dist/hooks/useUpdateEffect.js +2 -4
  78. package/dist/hooks/useXYFlow.d.ts +1 -0
  79. package/dist/hooks/useXYFlow.js +4 -7
  80. package/dist/index.d.ts +2 -2
  81. package/dist/index.js +4 -3
  82. package/dist/likec4diagram/DiagramUI.js +14 -7
  83. package/dist/likec4diagram/DiagramXYFlow.d.ts +2 -2
  84. package/dist/likec4diagram/DiagramXYFlow.js +54 -51
  85. package/dist/likec4diagram/convert-to-xyflow.d.ts +0 -1
  86. package/dist/likec4diagram/custom/edges/RelationshipEdge.js +249 -220
  87. package/dist/likec4diagram/custom/edges/SequenceStepEdge.js +7 -2
  88. package/dist/likec4diagram/custom/edges/edges.css.js +3 -4
  89. package/dist/likec4diagram/custom/edges/useControlPoints.d.ts +8 -0
  90. package/dist/likec4diagram/custom/edges/useControlPoints.js +58 -0
  91. package/dist/likec4diagram/custom/edges/useRelationshipEdgePath.d.ts +7 -0
  92. package/dist/likec4diagram/custom/edges/useRelationshipEdgePath.js +60 -0
  93. package/dist/likec4diagram/custom/edges/utils.d.ts +0 -12
  94. package/dist/likec4diagram/custom/nodes/CompoundActions.js +4 -1
  95. package/dist/likec4diagram/custom/nodes/ElementActions.d.ts +2 -1
  96. package/dist/likec4diagram/custom/nodes/ElementActions.js +15 -10
  97. package/dist/likec4diagram/custom/nodes/ElementNodeDrifts.d.ts +4 -0
  98. package/dist/likec4diagram/custom/nodes/ElementNodeDrifts.js +46 -0
  99. package/dist/likec4diagram/custom/nodes/SequenceActorNode.js +4 -1
  100. package/dist/likec4diagram/custom/nodes/nodes.d.ts +9 -1
  101. package/dist/likec4diagram/custom/nodes/nodes.js +13 -9
  102. package/dist/likec4diagram/custom/nodes/toolbar/ColorButton.d.ts +1 -1
  103. package/dist/likec4diagram/custom/nodes/toolbar/ColorButton.js +1 -1
  104. package/dist/likec4diagram/custom/nodes/toolbar/CompoundToolbar.js +2 -1
  105. package/dist/likec4diagram/custom/nodes/toolbar/ElementToolbar.js +4 -3
  106. package/dist/likec4diagram/custom/nodes/toolbar/_shared.d.ts +1 -11
  107. package/dist/likec4diagram/custom/nodes/toolbar/_shared.js +7 -51
  108. package/dist/likec4diagram/custom/nodes/toolbar/types.d.ts +5 -0
  109. package/dist/likec4diagram/custom/nodes/toolbar/types.js +7 -0
  110. package/dist/likec4diagram/custom/nodes/toolbar/useHandlers.d.ts +8 -0
  111. package/dist/likec4diagram/custom/nodes/toolbar/useHandlers.js +44 -0
  112. package/dist/likec4diagram/relationship-popover/RelationshipPopover.js +5 -7
  113. package/dist/likec4diagram/state/DiagramActorProvider.d.ts +3 -2
  114. package/dist/likec4diagram/state/DiagramActorProvider.js +96 -70
  115. package/dist/likec4diagram/state/assign.d.ts +4 -2
  116. package/dist/likec4diagram/state/assign.js +39 -103
  117. package/dist/likec4diagram/state/createViewChange.d.ts +3 -0
  118. package/dist/likec4diagram/state/createViewChange.js +90 -0
  119. package/dist/likec4diagram/state/diagram-api.d.ts +113 -0
  120. package/dist/likec4diagram/state/diagram-api.js +134 -0
  121. package/dist/likec4diagram/state/hotkeyActor.d.ts +7 -0
  122. package/dist/likec4diagram/state/hotkeyActor.js +17 -1
  123. package/dist/likec4diagram/state/machine.actions.d.ts +2099 -0
  124. package/dist/likec4diagram/state/machine.actions.js +735 -0
  125. package/dist/likec4diagram/state/machine.d.ts +3717 -0
  126. package/dist/likec4diagram/state/machine.js +141 -0
  127. package/dist/likec4diagram/state/machine.setup.d.ts +284 -0
  128. package/dist/likec4diagram/state/machine.setup.js +71 -0
  129. package/dist/likec4diagram/state/machine.state.initializing.d.ts +183 -0
  130. package/dist/likec4diagram/state/machine.state.initializing.js +55 -0
  131. package/dist/likec4diagram/state/machine.state.navigating.d.ts +117 -0
  132. package/dist/likec4diagram/state/machine.state.navigating.js +45 -0
  133. package/dist/likec4diagram/state/machine.state.ready.d.ts +3666 -0
  134. package/dist/likec4diagram/state/machine.state.ready.js +437 -0
  135. package/dist/likec4diagram/state/syncManualLayoutActor.d.ts +220 -63
  136. package/dist/likec4diagram/state/syncManualLayoutActor.js +218 -143
  137. package/dist/likec4diagram/state/types.d.ts +4 -7
  138. package/dist/likec4diagram/state/utils.d.ts +4 -2
  139. package/dist/likec4diagram/state/utils.js +4 -1
  140. package/dist/likec4diagram/types.d.ts +6 -1
  141. package/dist/likec4diagram/ui/LayoutDriftFrame.d.ts +2 -0
  142. package/dist/likec4diagram/ui/LayoutDriftFrame.js +66 -0
  143. package/dist/likec4diagram/ui/index.d.ts +1 -0
  144. package/dist/likec4diagram/ui/notation/NotationPanel.js +10 -12
  145. package/dist/likec4diagram/useLayoutConstraints.d.ts +10 -5
  146. package/dist/likec4diagram/useLayoutConstraints.js +225 -54
  147. package/dist/likec4diagram/xyflow-diagram/diagram-view.d.ts +0 -1
  148. package/dist/likec4diagram/xyflow-diagram/diagram-view.js +15 -15
  149. package/dist/navigationpanel/NavigationPanel.js +11 -7
  150. package/dist/navigationpanel/NavigationPanelControls.d.ts +2 -1
  151. package/dist/navigationpanel/NavigationPanelControls.js +23 -17
  152. package/dist/navigationpanel/NavigationPanelDropdown.d.ts +2 -1
  153. package/dist/navigationpanel/NavigationPanelDropdown.js +62 -42
  154. package/dist/navigationpanel/_common.d.ts +1 -1
  155. package/dist/navigationpanel/_common.js +4 -2
  156. package/dist/navigationpanel/actor.d.ts +11 -7
  157. package/dist/navigationpanel/actor.js +5 -4
  158. package/dist/navigationpanel/comparepanel/CompareActionsMenu.d.ts +3 -0
  159. package/dist/navigationpanel/comparepanel/CompareActionsMenu.js +59 -0
  160. package/dist/navigationpanel/comparepanel/ComparePanel.d.ts +2 -0
  161. package/dist/navigationpanel/comparepanel/ComparePanel.js +42 -0
  162. package/dist/navigationpanel/comparepanel/ComparePanelControls.d.ts +1 -0
  163. package/dist/navigationpanel/comparepanel/ComparePanelControls.js +60 -0
  164. package/dist/navigationpanel/comparepanel/LayoutTypeSwitcher.d.ts +5 -0
  165. package/dist/navigationpanel/comparepanel/LayoutTypeSwitcher.js +38 -0
  166. package/dist/navigationpanel/comparepanel/index.d.ts +1 -0
  167. package/dist/navigationpanel/controls/{ViewDetailsCard.d.ts → DetailsControls.d.ts} +1 -1
  168. package/dist/navigationpanel/controls/{ViewDetailsCard.js → DetailsControls.js} +18 -14
  169. package/dist/navigationpanel/controls/LayoutWarning.d.ts +2 -0
  170. package/dist/navigationpanel/controls/LayoutWarning.js +102 -0
  171. package/dist/navigationpanel/controls/NavigationButtons.js +4 -3
  172. package/dist/navigationpanel/controls/OpenSource.js +2 -2
  173. package/dist/navigationpanel/controls/SearchControl.d.ts +2 -1
  174. package/dist/navigationpanel/controls/SearchControl.js +15 -17
  175. package/dist/navigationpanel/controls/ToggleReadonly.d.ts +1 -1
  176. package/dist/navigationpanel/controls/ToggleReadonly.js +19 -16
  177. package/dist/navigationpanel/controls/index.d.ts +2 -1
  178. package/dist/navigationpanel/dropdown/ProjectsMenu.d.ts +2 -2
  179. package/dist/navigationpanel/dropdown/ProjectsMenu.js +5 -5
  180. package/dist/navigationpanel/editorpanel/CenterCamera.js +5 -2
  181. package/dist/navigationpanel/editorpanel/ChangeAutoLayoutButton.d.ts +1 -1
  182. package/dist/navigationpanel/editorpanel/ChangeAutoLayoutButton.js +21 -20
  183. package/dist/navigationpanel/editorpanel/EditorPanel.js +3 -3
  184. package/dist/navigationpanel/editorpanel/ManualLayoutToolsButton.d.ts +2 -2
  185. package/dist/navigationpanel/editorpanel/ManualLayoutToolsButton.js +16 -13
  186. package/dist/navigationpanel/editorpanel/ToggleReadonly.d.ts +1 -0
  187. package/dist/navigationpanel/editorpanel/ToggleReadonly.js +15 -0
  188. package/dist/navigationpanel/styles.css.d.ts +2 -2
  189. package/dist/navigationpanel/styles.css.js +4 -4
  190. package/dist/navigationpanel/walkthrough/ActiveWalkthroughControls.js +14 -8
  191. package/dist/navigationpanel/walkthrough/DynamicViewControls.d.ts +10 -10
  192. package/dist/navigationpanel/walkthrough/DynamicViewControls.js +31 -14
  193. package/dist/navigationpanel/walkthrough/WalkthroughPanel.d.ts +2 -1
  194. package/dist/navigationpanel/walkthrough/WalkthroughPanel.js +66 -49
  195. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/actions/dist/xstate-actions.cjs.js +37 -0
  196. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/dev/dist/xstate-dev.cjs.js +59 -0
  197. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/dist/assign-dea9f7c8.cjs.js +140 -0
  198. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/dist/log-ec8d4df4.cjs.js +401 -0
  199. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/dist/raise-da5b247f.cjs.js +2716 -0
  200. package/dist/node_modules/.pnpm/xstate@5.24.0_patch_hash_3a1bd6d012ec67bf6e38a00c3226d1be77089442f83aeb6e424b00ca2a11d21c/node_modules/xstate/guards/dist/xstate-guards.cjs.js +26 -0
  201. package/dist/overlays/element-details/ElementDetails.js +7 -7
  202. package/dist/overlays/element-details/ElementDetailsCard.js +18 -88
  203. package/dist/overlays/element-details/MetadataValue.d.ts +9 -0
  204. package/dist/overlays/element-details/MetadataValue.js +261 -0
  205. package/dist/overlays/element-details/TabPanelDeployments.js +6 -4
  206. package/dist/overlays/element-details/TabPanelRelationships.js +3 -3
  207. package/dist/overlays/element-details/TabPanelStructure.js +1 -1
  208. package/dist/overlays/element-details/actor.d.ts +3 -2
  209. package/dist/overlays/overlaysActor.d.ts +304 -62
  210. package/dist/overlays/overlaysActor.js +132 -131
  211. package/dist/overlays/relationship-details/RelationshipDetails.js +4 -3
  212. package/dist/overlays/relationship-details/SelectEdge.js +2 -2
  213. package/dist/overlays/relationship-details/actor.d.ts +14 -2
  214. package/dist/overlays/relationship-details/actor.js +23 -5
  215. package/dist/overlays/relationship-details/custom/ElementActions.js +8 -5
  216. package/dist/overlays/relationship-details/custom/edgeTypes.js +4 -1
  217. package/dist/overlays/relationship-details/custom/nodeTypes.js +4 -1
  218. package/dist/overlays/relationship-details/hooks.js +1 -1
  219. package/dist/overlays/relationships-browser/RelationshipsBrowser.js +6 -4
  220. package/dist/overlays/relationships-browser/SelectElement.js +2 -2
  221. package/dist/overlays/relationships-browser/actor.d.ts +239 -173
  222. package/dist/overlays/relationships-browser/actor.js +132 -110
  223. package/dist/overlays/relationships-browser/const.d.ts +3 -3
  224. package/dist/overlays/relationships-browser/const.js +3 -3
  225. package/dist/overlays/relationships-browser/custom/ElementActions.js +44 -37
  226. package/dist/overlays/relationships-browser/custom/edgeTypes.js +4 -1
  227. package/dist/overlays/relationships-browser/custom/nodeTypes.js +4 -1
  228. package/dist/overlays/relationships-browser/hooks.js +7 -6
  229. package/dist/search/Search.js +2 -1
  230. package/dist/search/components/ElementsColumn.js +5 -3
  231. package/dist/search/components/PickView.js +1 -1
  232. package/dist/search/components/SearchByTags.js +21 -44
  233. package/dist/search/components/SearchInput.js +1 -1
  234. package/dist/search/components/ViewsColum.js +6 -4
  235. package/dist/shadowroot/ShadowRoot.js +53 -12
  236. package/dist/shadowroot/styles.css.d.ts +0 -4
  237. package/dist/shadowroot/styles.css.js +1 -41
  238. package/dist/styles.css2.js +1 -1
  239. package/dist/utils/index.d.ts +4 -4
  240. package/dist/utils/vector.d.ts +78 -21
  241. package/dist/utils/vector.js +91 -24
  242. package/dist/utils/view-bounds.d.ts +8 -0
  243. package/dist/utils/view-bounds.js +57 -0
  244. package/dist/utils/xyflow.d.ts +49 -7
  245. package/dist/utils/xyflow.js +63 -11
  246. package/package.json +28 -27
  247. package/panda.buildinfo.json +140 -83
  248. package/styles-min.css +1 -1
  249. package/styles.css +1 -1
  250. package/dist/hooks/useCurrentViewId.d.ts +0 -6
  251. package/dist/likec4diagram/custom/edges/utils.js +0 -23
  252. package/dist/likec4diagram/state/diagram-machine.d.ts +0 -2590
  253. package/dist/likec4diagram/state/diagram-machine.js +0 -1180
  254. package/dist/navigationpanel/editorpanel/LayoutDriftNotification.d.ts +0 -1
  255. package/dist/navigationpanel/editorpanel/LayoutDriftNotification.js +0 -56
  256. package/dist/utils/get-view-bounds.d.ts +0 -3
  257. package/dist/utils/get-view-bounds.js +0 -14
  258. /package/dist/base/{types.js → Base.js} +0 -0
  259. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/createReactComponent.js +0 -0
  260. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/defaultAttributes.js +0 -0
  261. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconAlertTriangle.js +0 -0
  262. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconArrowDownRight.js +0 -0
  263. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconArrowLeft.js +0 -0
  264. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconArrowRight.js +0 -0
  265. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconBolt.js +0 -0
  266. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconBrowser.js +0 -0
  267. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconCheck.js +0 -0
  268. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconChevronDown.js +0 -0
  269. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconChevronLeft.js +0 -0
  270. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconChevronRight.js +0 -0
  271. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconCopy.js +0 -0
  272. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconCylinder.js +0 -0
  273. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconDeviceMobile.js +0 -0
  274. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconDirectionSignFilled.js +0 -0
  275. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconExternalLink.js +0 -0
  276. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconFileSymlink.js +0 -0
  277. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconFocusCentered.js +0 -0
  278. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconFolderFilled.js +0 -0
  279. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconHelpCircle.js +0 -0
  280. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconId.js +0 -0
  281. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconInfoCircle.js +0 -0
  282. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignBottom.js +0 -0
  283. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignCenter.js +0 -0
  284. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignLeft.js +0 -0
  285. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignMiddle.js +0 -0
  286. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignRight.js +0 -0
  287. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutAlignTop.js +0 -0
  288. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutBoardSplit.js +0 -0
  289. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutCollage.js +0 -0
  290. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutDashboard.js +0 -0
  291. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLink.js +0 -0
  292. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLock.js +0 -0
  293. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconLockOpen2.js +0 -0
  294. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconPlayerPlayFilled.js +0 -0
  295. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconPlayerSkipBackFilled.js +0 -0
  296. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconPlayerSkipForwardFilled.js +0 -0
  297. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconPlayerStopFilled.js +0 -0
  298. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconRectangularPrism.js +0 -0
  299. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconReorder.js +0 -0
  300. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconRouteOff.js +0 -0
  301. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconSearch.js +0 -0
  302. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconSelector.js +0 -0
  303. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconStack2.js +0 -0
  304. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconStarFilled.js +0 -0
  305. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconTarget.js +0 -0
  306. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconTransform.js +0 -0
  307. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconUser.js +0 -0
  308. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconX.js +0 -0
  309. /package/dist/node_modules/.pnpm/{@tabler_icons-react@3.35.0_react@19.1.1 → @tabler_icons-react@3.35.0_react@19.2.0}/node_modules/@tabler/icons-react/dist/esm/icons/IconZoomScan.js +0 -0
@@ -0,0 +1,2716 @@
1
+ import { __exports as raiseDa5b247f_cjs } from '../../../../../../_virtual/raise-da5b247f.cjs.js';
2
+ import { __require as requireXstateDev_cjs } from '../dev/dist/xstate-dev.cjs.js';
3
+
4
+ var hasRequiredRaiseDa5b247f_cjs;
5
+
6
+ function requireRaiseDa5b247f_cjs () {
7
+ if (hasRequiredRaiseDa5b247f_cjs) return raiseDa5b247f_cjs;
8
+ hasRequiredRaiseDa5b247f_cjs = 1;
9
+
10
+ var dev_dist_xstateDev = requireXstateDev_cjs();
11
+
12
+ class Mailbox {
13
+ constructor(_process) {
14
+ this._process = _process;
15
+ this._active = false;
16
+ this._current = null;
17
+ this._last = null;
18
+ }
19
+ start() {
20
+ this._active = true;
21
+ this.flush();
22
+ }
23
+ clear() {
24
+ // we can't set _current to null because we might be currently processing
25
+ // and enqueue following clear shouldn't start processing the enqueued item immediately
26
+ if (this._current) {
27
+ this._current.next = null;
28
+ this._last = this._current;
29
+ }
30
+ }
31
+ enqueue(event) {
32
+ const enqueued = {
33
+ value: event,
34
+ next: null
35
+ };
36
+ if (this._current) {
37
+ this._last.next = enqueued;
38
+ this._last = enqueued;
39
+ return;
40
+ }
41
+ this._current = enqueued;
42
+ this._last = enqueued;
43
+ if (this._active) {
44
+ this.flush();
45
+ }
46
+ }
47
+ flush() {
48
+ while (this._current) {
49
+ // atm the given _process is responsible for implementing proper try/catch handling
50
+ // we assume here that this won't throw in a way that can affect this mailbox
51
+ const consumed = this._current;
52
+ this._process(consumed.value);
53
+ this._current = consumed.next;
54
+ }
55
+ this._last = null;
56
+ }
57
+ }
58
+
59
+ const STATE_DELIMITER = '.';
60
+ const TARGETLESS_KEY = '';
61
+ const NULL_EVENT = '';
62
+ const STATE_IDENTIFIER = '#';
63
+ const WILDCARD = '*';
64
+ const XSTATE_INIT = 'xstate.init';
65
+ const XSTATE_ERROR = 'xstate.error';
66
+ const XSTATE_STOP = 'xstate.stop';
67
+
68
+ /**
69
+ * Returns an event that represents an implicit event that is sent after the
70
+ * specified `delay`.
71
+ *
72
+ * @param delayRef The delay in milliseconds
73
+ * @param id The state node ID where this event is handled
74
+ */
75
+ function createAfterEvent(delayRef, id) {
76
+ return {
77
+ type: `xstate.after.${delayRef}.${id}`
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Returns an event that represents that a final state node has been reached in
83
+ * the parent state node.
84
+ *
85
+ * @param id The final state node's parent state node `id`
86
+ * @param output The data to pass into the event
87
+ */
88
+ function createDoneStateEvent(id, output) {
89
+ return {
90
+ type: `xstate.done.state.${id}`,
91
+ output
92
+ };
93
+ }
94
+
95
+ /**
96
+ * Returns an event that represents that an invoked service has terminated.
97
+ *
98
+ * An invoked service is terminated when it has reached a top-level final state
99
+ * node, but not when it is canceled.
100
+ *
101
+ * @param invokeId The invoked service ID
102
+ * @param output The data to pass into the event
103
+ */
104
+ function createDoneActorEvent(invokeId, output) {
105
+ return {
106
+ type: `xstate.done.actor.${invokeId}`,
107
+ output,
108
+ actorId: invokeId
109
+ };
110
+ }
111
+ function createErrorActorEvent(id, error) {
112
+ return {
113
+ type: `xstate.error.actor.${id}`,
114
+ error,
115
+ actorId: id
116
+ };
117
+ }
118
+ function createInitEvent(input) {
119
+ return {
120
+ type: XSTATE_INIT,
121
+ input
122
+ };
123
+ }
124
+
125
+ /**
126
+ * This function makes sure that unhandled errors are thrown in a separate
127
+ * macrotask. It allows those errors to be detected by global error handlers and
128
+ * reported to bug tracking services without interrupting our own stack of
129
+ * execution.
130
+ *
131
+ * @param err Error to be thrown
132
+ */
133
+ function reportUnhandledError(err) {
134
+ setTimeout(() => {
135
+ throw err;
136
+ });
137
+ }
138
+
139
+ const symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();
140
+
141
+ function matchesState(parentStateId, childStateId) {
142
+ const parentStateValue = toStateValue(parentStateId);
143
+ const childStateValue = toStateValue(childStateId);
144
+ if (typeof childStateValue === 'string') {
145
+ if (typeof parentStateValue === 'string') {
146
+ return childStateValue === parentStateValue;
147
+ }
148
+
149
+ // Parent more specific than child
150
+ return false;
151
+ }
152
+ if (typeof parentStateValue === 'string') {
153
+ return parentStateValue in childStateValue;
154
+ }
155
+ return Object.keys(parentStateValue).every(key => {
156
+ if (!(key in childStateValue)) {
157
+ return false;
158
+ }
159
+ return matchesState(parentStateValue[key], childStateValue[key]);
160
+ });
161
+ }
162
+ function toStatePath(stateId) {
163
+ if (isArray(stateId)) {
164
+ return stateId;
165
+ }
166
+ const result = [];
167
+ let segment = '';
168
+ for (let i = 0; i < stateId.length; i++) {
169
+ const char = stateId.charCodeAt(i);
170
+ switch (char) {
171
+ // \
172
+ case 92:
173
+ // consume the next character
174
+ segment += stateId[i + 1];
175
+ // and skip over it
176
+ i++;
177
+ continue;
178
+ // .
179
+ case 46:
180
+ result.push(segment);
181
+ segment = '';
182
+ continue;
183
+ }
184
+ segment += stateId[i];
185
+ }
186
+ result.push(segment);
187
+ return result;
188
+ }
189
+ function toStateValue(stateValue) {
190
+ if (isMachineSnapshot(stateValue)) {
191
+ return stateValue.value;
192
+ }
193
+ if (typeof stateValue !== 'string') {
194
+ return stateValue;
195
+ }
196
+ const statePath = toStatePath(stateValue);
197
+ return pathToStateValue(statePath);
198
+ }
199
+ function pathToStateValue(statePath) {
200
+ if (statePath.length === 1) {
201
+ return statePath[0];
202
+ }
203
+ const value = {};
204
+ let marker = value;
205
+ for (let i = 0; i < statePath.length - 1; i++) {
206
+ if (i === statePath.length - 2) {
207
+ marker[statePath[i]] = statePath[i + 1];
208
+ } else {
209
+ const previous = marker;
210
+ marker = {};
211
+ previous[statePath[i]] = marker;
212
+ }
213
+ }
214
+ return value;
215
+ }
216
+ function mapValues(collection, iteratee) {
217
+ const result = {};
218
+ const collectionKeys = Object.keys(collection);
219
+ for (let i = 0; i < collectionKeys.length; i++) {
220
+ const key = collectionKeys[i];
221
+ result[key] = iteratee(collection[key], key, collection, i);
222
+ }
223
+ return result;
224
+ }
225
+ function toArrayStrict(value) {
226
+ if (isArray(value)) {
227
+ return value;
228
+ }
229
+ return [value];
230
+ }
231
+ function toArray(value) {
232
+ if (value === undefined) {
233
+ return [];
234
+ }
235
+ return toArrayStrict(value);
236
+ }
237
+ function resolveOutput(mapper, context, event, self) {
238
+ if (typeof mapper === 'function') {
239
+ return mapper({
240
+ context,
241
+ event,
242
+ self
243
+ });
244
+ }
245
+ return mapper;
246
+ }
247
+ function isArray(value) {
248
+ return Array.isArray(value);
249
+ }
250
+ function isErrorActorEvent(event) {
251
+ return event.type.startsWith('xstate.error.actor');
252
+ }
253
+ function toTransitionConfigArray(configLike) {
254
+ return toArrayStrict(configLike).map(transitionLike => {
255
+ if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {
256
+ return {
257
+ target: transitionLike
258
+ };
259
+ }
260
+ return transitionLike;
261
+ });
262
+ }
263
+ function normalizeTarget(target) {
264
+ if (target === undefined || target === TARGETLESS_KEY) {
265
+ return undefined;
266
+ }
267
+ return toArray(target);
268
+ }
269
+ function toObserver(nextHandler, errorHandler, completionHandler) {
270
+ const isObserver = typeof nextHandler === 'object';
271
+ const self = isObserver ? nextHandler : undefined;
272
+ return {
273
+ next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),
274
+ error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),
275
+ complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)
276
+ };
277
+ }
278
+ function createInvokeId(stateNodeId, index) {
279
+ return `${index}.${stateNodeId}`;
280
+ }
281
+ function resolveReferencedActor(machine, src) {
282
+ const match = src.match(/^xstate\.invoke\.(\d+)\.(.*)/);
283
+ if (!match) {
284
+ return machine.implementations.actors[src];
285
+ }
286
+ const [, indexStr, nodeId] = match;
287
+ const node = machine.getStateNodeById(nodeId);
288
+ const invokeConfig = node.config.invoke;
289
+ return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;
290
+ }
291
+ function getAllOwnEventDescriptors(snapshot) {
292
+ return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];
293
+ }
294
+
295
+ function createScheduledEventId(actorRef, id) {
296
+ return `${actorRef.sessionId}.${id}`;
297
+ }
298
+ let idCounter = 0;
299
+ function createSystem(rootActor, options) {
300
+ const children = new Map();
301
+ const keyedActors = new Map();
302
+ const reverseKeyedActors = new WeakMap();
303
+ const inspectionObservers = new Set();
304
+ const timerMap = {};
305
+ const {
306
+ clock,
307
+ logger
308
+ } = options;
309
+ const scheduler = {
310
+ schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {
311
+ const scheduledEvent = {
312
+ source,
313
+ target,
314
+ event,
315
+ delay,
316
+ id,
317
+ startedAt: Date.now()
318
+ };
319
+ const scheduledEventId = createScheduledEventId(source, id);
320
+ system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;
321
+ const timeout = clock.setTimeout(() => {
322
+ delete timerMap[scheduledEventId];
323
+ delete system._snapshot._scheduledEvents[scheduledEventId];
324
+ system._relay(source, target, event);
325
+ }, delay);
326
+ timerMap[scheduledEventId] = timeout;
327
+ },
328
+ cancel: (source, id) => {
329
+ const scheduledEventId = createScheduledEventId(source, id);
330
+ const timeout = timerMap[scheduledEventId];
331
+ delete timerMap[scheduledEventId];
332
+ delete system._snapshot._scheduledEvents[scheduledEventId];
333
+ if (timeout !== undefined) {
334
+ clock.clearTimeout(timeout);
335
+ }
336
+ },
337
+ cancelAll: actorRef => {
338
+ for (const scheduledEventId in system._snapshot._scheduledEvents) {
339
+ const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];
340
+ if (scheduledEvent.source === actorRef) {
341
+ scheduler.cancel(actorRef, scheduledEvent.id);
342
+ }
343
+ }
344
+ }
345
+ };
346
+ const sendInspectionEvent = event => {
347
+ if (!inspectionObservers.size) {
348
+ return;
349
+ }
350
+ const resolvedInspectionEvent = {
351
+ ...event,
352
+ rootId: rootActor.sessionId
353
+ };
354
+ inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));
355
+ };
356
+ const system = {
357
+ _snapshot: {
358
+ _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}
359
+ },
360
+ _bookId: () => `x:${idCounter++}`,
361
+ _register: (sessionId, actorRef) => {
362
+ children.set(sessionId, actorRef);
363
+ return sessionId;
364
+ },
365
+ _unregister: actorRef => {
366
+ children.delete(actorRef.sessionId);
367
+ const systemId = reverseKeyedActors.get(actorRef);
368
+ if (systemId !== undefined) {
369
+ keyedActors.delete(systemId);
370
+ reverseKeyedActors.delete(actorRef);
371
+ }
372
+ },
373
+ get: systemId => {
374
+ return keyedActors.get(systemId);
375
+ },
376
+ getAll: () => {
377
+ return Object.fromEntries(keyedActors.entries());
378
+ },
379
+ _set: (systemId, actorRef) => {
380
+ const existing = keyedActors.get(systemId);
381
+ if (existing && existing !== actorRef) {
382
+ throw new Error(`Actor with system ID '${systemId}' already exists.`);
383
+ }
384
+ keyedActors.set(systemId, actorRef);
385
+ reverseKeyedActors.set(actorRef, systemId);
386
+ },
387
+ inspect: observerOrFn => {
388
+ const observer = toObserver(observerOrFn);
389
+ inspectionObservers.add(observer);
390
+ return {
391
+ unsubscribe() {
392
+ inspectionObservers.delete(observer);
393
+ }
394
+ };
395
+ },
396
+ _sendInspectionEvent: sendInspectionEvent,
397
+ _relay: (source, target, event) => {
398
+ system._sendInspectionEvent({
399
+ type: '@xstate.event',
400
+ sourceRef: source,
401
+ actorRef: target,
402
+ event
403
+ });
404
+ target._send(event);
405
+ },
406
+ scheduler,
407
+ getSnapshot: () => {
408
+ return {
409
+ _scheduledEvents: {
410
+ ...system._snapshot._scheduledEvents
411
+ }
412
+ };
413
+ },
414
+ start: () => {
415
+ const scheduledEvents = system._snapshot._scheduledEvents;
416
+ system._snapshot._scheduledEvents = {};
417
+ for (const scheduledId in scheduledEvents) {
418
+ const {
419
+ source,
420
+ target,
421
+ event,
422
+ delay,
423
+ id
424
+ } = scheduledEvents[scheduledId];
425
+ scheduler.schedule(source, target, event, delay, id);
426
+ }
427
+ },
428
+ _clock: clock,
429
+ _logger: logger
430
+ };
431
+ return system;
432
+ }
433
+
434
+ // those are needed to make JSDoc `@link` work properly
435
+
436
+ let executingCustomAction = false;
437
+ const $$ACTOR_TYPE = 1;
438
+
439
+ // those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync
440
+ let ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {
441
+ ProcessingStatus[ProcessingStatus["NotStarted"] = 0] = "NotStarted";
442
+ ProcessingStatus[ProcessingStatus["Running"] = 1] = "Running";
443
+ ProcessingStatus[ProcessingStatus["Stopped"] = 2] = "Stopped";
444
+ return ProcessingStatus;
445
+ }({});
446
+ const defaultOptions = {
447
+ clock: {
448
+ setTimeout: (fn, ms) => {
449
+ return setTimeout(fn, ms);
450
+ },
451
+ clearTimeout: id => {
452
+ return clearTimeout(id);
453
+ }
454
+ },
455
+ logger: console.log.bind(console),
456
+ devTools: false
457
+ };
458
+
459
+ /**
460
+ * An Actor is a running process that can receive events, send events and change
461
+ * its behavior based on the events it receives, which can cause effects outside
462
+ * of the actor. When you run a state machine, it becomes an actor.
463
+ */
464
+ class Actor {
465
+ /**
466
+ * Creates a new actor instance for the given logic with the provided options,
467
+ * if any.
468
+ *
469
+ * @param logic The logic to create an actor from
470
+ * @param options Actor options
471
+ */
472
+ constructor(logic, options) {
473
+ this.logic = logic;
474
+ /** The current internal state of the actor. */
475
+ this._snapshot = void 0;
476
+ /**
477
+ * The clock that is responsible for setting and clearing timeouts, such as
478
+ * delayed events and transitions.
479
+ */
480
+ this.clock = void 0;
481
+ this.options = void 0;
482
+ /** The unique identifier for this actor relative to its parent. */
483
+ this.id = void 0;
484
+ this.mailbox = new Mailbox(this._process.bind(this));
485
+ this.observers = new Set();
486
+ this.eventListeners = new Map();
487
+ this.logger = void 0;
488
+ /** @internal */
489
+ this._processingStatus = ProcessingStatus.NotStarted;
490
+ // Actor Ref
491
+ this._parent = void 0;
492
+ /** @internal */
493
+ this._syncSnapshot = void 0;
494
+ this.ref = void 0;
495
+ // TODO: add typings for system
496
+ this._actorScope = void 0;
497
+ this.systemId = void 0;
498
+ /** The globally unique process ID for this invocation. */
499
+ this.sessionId = void 0;
500
+ /** The system to which this actor belongs. */
501
+ this.system = void 0;
502
+ this._doneEvent = void 0;
503
+ this.src = void 0;
504
+ // array of functions to defer
505
+ this._deferred = [];
506
+ const resolvedOptions = {
507
+ ...defaultOptions,
508
+ ...options
509
+ };
510
+ const {
511
+ clock,
512
+ logger,
513
+ parent,
514
+ syncSnapshot,
515
+ id,
516
+ systemId,
517
+ inspect
518
+ } = resolvedOptions;
519
+ this.system = parent ? parent.system : createSystem(this, {
520
+ clock,
521
+ logger
522
+ });
523
+ if (inspect && !parent) {
524
+ // Always inspect at the system-level
525
+ this.system.inspect(toObserver(inspect));
526
+ }
527
+ this.sessionId = this.system._bookId();
528
+ this.id = id ?? this.sessionId;
529
+ this.logger = options?.logger ?? this.system._logger;
530
+ this.clock = options?.clock ?? this.system._clock;
531
+ this._parent = parent;
532
+ this._syncSnapshot = syncSnapshot;
533
+ this.options = resolvedOptions;
534
+ this.src = resolvedOptions.src ?? logic;
535
+ this.ref = this;
536
+ this._actorScope = {
537
+ self: this,
538
+ id: this.id,
539
+ sessionId: this.sessionId,
540
+ logger: this.logger,
541
+ defer: fn => {
542
+ this._deferred.push(fn);
543
+ },
544
+ system: this.system,
545
+ stopChild: child => {
546
+ if (child._parent !== this) {
547
+ throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);
548
+ }
549
+ child._stop();
550
+ },
551
+ emit: emittedEvent => {
552
+ const listeners = this.eventListeners.get(emittedEvent.type);
553
+ const wildcardListener = this.eventListeners.get('*');
554
+ if (!listeners && !wildcardListener) {
555
+ return;
556
+ }
557
+ const allListeners = [...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])];
558
+ for (const handler of allListeners) {
559
+ try {
560
+ handler(emittedEvent);
561
+ } catch (err) {
562
+ reportUnhandledError(err);
563
+ }
564
+ }
565
+ },
566
+ actionExecutor: action => {
567
+ const exec = () => {
568
+ this._actorScope.system._sendInspectionEvent({
569
+ type: '@xstate.action',
570
+ actorRef: this,
571
+ action: {
572
+ type: action.type,
573
+ params: action.params
574
+ }
575
+ });
576
+ if (!action.exec) {
577
+ return;
578
+ }
579
+ const saveExecutingCustomAction = executingCustomAction;
580
+ try {
581
+ executingCustomAction = true;
582
+ action.exec(action.info, action.params);
583
+ } finally {
584
+ executingCustomAction = saveExecutingCustomAction;
585
+ }
586
+ };
587
+ if (this._processingStatus === ProcessingStatus.Running) {
588
+ exec();
589
+ } else {
590
+ this._deferred.push(exec);
591
+ }
592
+ }
593
+ };
594
+
595
+ // Ensure that the send method is bound to this Actor instance
596
+ // if destructured
597
+ this.send = this.send.bind(this);
598
+ this.system._sendInspectionEvent({
599
+ type: '@xstate.actor',
600
+ actorRef: this
601
+ });
602
+ if (systemId) {
603
+ this.systemId = systemId;
604
+ this.system._set(systemId, this);
605
+ }
606
+ this._initState(options?.snapshot ?? options?.state);
607
+ if (systemId && this._snapshot.status !== 'active') {
608
+ this.system._unregister(this);
609
+ }
610
+ }
611
+ _initState(persistedState) {
612
+ try {
613
+ this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);
614
+ } catch (err) {
615
+ // if we get here then it means that we assign a value to this._snapshot that is not of the correct type
616
+ // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible
617
+ // so right now this is a lie of sorts
618
+ this._snapshot = {
619
+ status: 'error',
620
+ output: undefined,
621
+ error: err
622
+ };
623
+ }
624
+ }
625
+ update(snapshot, event) {
626
+ // Update state
627
+ this._snapshot = snapshot;
628
+
629
+ // Execute deferred effects
630
+ let deferredFn;
631
+ while (deferredFn = this._deferred.shift()) {
632
+ try {
633
+ deferredFn();
634
+ } catch (err) {
635
+ // this error can only be caught when executing *initial* actions
636
+ // it's the only time when we call actions provided by the user through those deferreds
637
+ // when the actor is already running we always execute them synchronously while transitioning
638
+ // no "builtin deferred" should actually throw an error since they are either safe
639
+ // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox
640
+ this._deferred.length = 0;
641
+ this._snapshot = {
642
+ ...snapshot,
643
+ status: 'error',
644
+ error: err
645
+ };
646
+ }
647
+ }
648
+ switch (this._snapshot.status) {
649
+ case 'active':
650
+ for (const observer of this.observers) {
651
+ try {
652
+ observer.next?.(snapshot);
653
+ } catch (err) {
654
+ reportUnhandledError(err);
655
+ }
656
+ }
657
+ break;
658
+ case 'done':
659
+ // next observers are meant to be notified about done snapshots
660
+ // this can be seen as something that is different from how observable work
661
+ // but with observables `complete` callback is called without any arguments
662
+ // it's more ergonomic for XState to treat a done snapshot as a "next" value
663
+ // and the completion event as something that is separate,
664
+ // something that merely follows emitting that done snapshot
665
+ for (const observer of this.observers) {
666
+ try {
667
+ observer.next?.(snapshot);
668
+ } catch (err) {
669
+ reportUnhandledError(err);
670
+ }
671
+ }
672
+ this._stopProcedure();
673
+ this._complete();
674
+ this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);
675
+ if (this._parent) {
676
+ this.system._relay(this, this._parent, this._doneEvent);
677
+ }
678
+ break;
679
+ case 'error':
680
+ this._error(this._snapshot.error);
681
+ break;
682
+ }
683
+ this.system._sendInspectionEvent({
684
+ type: '@xstate.snapshot',
685
+ actorRef: this,
686
+ event,
687
+ snapshot
688
+ });
689
+ }
690
+
691
+ /**
692
+ * Subscribe an observer to an actor’s snapshot values.
693
+ *
694
+ * @remarks
695
+ * The observer will receive the actor’s snapshot value when it is emitted.
696
+ * The observer can be:
697
+ *
698
+ * - A plain function that receives the latest snapshot, or
699
+ * - An observer object whose `.next(snapshot)` method receives the latest
700
+ * snapshot
701
+ *
702
+ * @example
703
+ *
704
+ * ```ts
705
+ * // Observer as a plain function
706
+ * const subscription = actor.subscribe((snapshot) => {
707
+ * console.log(snapshot);
708
+ * });
709
+ * ```
710
+ *
711
+ * @example
712
+ *
713
+ * ```ts
714
+ * // Observer as an object
715
+ * const subscription = actor.subscribe({
716
+ * next(snapshot) {
717
+ * console.log(snapshot);
718
+ * },
719
+ * error(err) {
720
+ * // ...
721
+ * },
722
+ * complete() {
723
+ * // ...
724
+ * }
725
+ * });
726
+ * ```
727
+ *
728
+ * The return value of `actor.subscribe(observer)` is a subscription object
729
+ * that has an `.unsubscribe()` method. You can call
730
+ * `subscription.unsubscribe()` to unsubscribe the observer:
731
+ *
732
+ * @example
733
+ *
734
+ * ```ts
735
+ * const subscription = actor.subscribe((snapshot) => {
736
+ * // ...
737
+ * });
738
+ *
739
+ * // Unsubscribe the observer
740
+ * subscription.unsubscribe();
741
+ * ```
742
+ *
743
+ * When the actor is stopped, all of its observers will automatically be
744
+ * unsubscribed.
745
+ *
746
+ * @param observer - Either a plain function that receives the latest
747
+ * snapshot, or an observer object whose `.next(snapshot)` method receives
748
+ * the latest snapshot
749
+ */
750
+
751
+ subscribe(nextListenerOrObserver, errorListener, completeListener) {
752
+ const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);
753
+ if (this._processingStatus !== ProcessingStatus.Stopped) {
754
+ this.observers.add(observer);
755
+ } else {
756
+ switch (this._snapshot.status) {
757
+ case 'done':
758
+ try {
759
+ observer.complete?.();
760
+ } catch (err) {
761
+ reportUnhandledError(err);
762
+ }
763
+ break;
764
+ case 'error':
765
+ {
766
+ const err = this._snapshot.error;
767
+ if (!observer.error) {
768
+ reportUnhandledError(err);
769
+ } else {
770
+ try {
771
+ observer.error(err);
772
+ } catch (err) {
773
+ reportUnhandledError(err);
774
+ }
775
+ }
776
+ break;
777
+ }
778
+ }
779
+ }
780
+ return {
781
+ unsubscribe: () => {
782
+ this.observers.delete(observer);
783
+ }
784
+ };
785
+ }
786
+ on(type, handler) {
787
+ let listeners = this.eventListeners.get(type);
788
+ if (!listeners) {
789
+ listeners = new Set();
790
+ this.eventListeners.set(type, listeners);
791
+ }
792
+ const wrappedHandler = handler.bind(undefined);
793
+ listeners.add(wrappedHandler);
794
+ return {
795
+ unsubscribe: () => {
796
+ listeners.delete(wrappedHandler);
797
+ }
798
+ };
799
+ }
800
+
801
+ /** Starts the Actor from the initial state */
802
+ start() {
803
+ if (this._processingStatus === ProcessingStatus.Running) {
804
+ // Do not restart the service if it is already started
805
+ return this;
806
+ }
807
+ if (this._syncSnapshot) {
808
+ this.subscribe({
809
+ next: snapshot => {
810
+ if (snapshot.status === 'active') {
811
+ this.system._relay(this, this._parent, {
812
+ type: `xstate.snapshot.${this.id}`,
813
+ snapshot
814
+ });
815
+ }
816
+ },
817
+ error: () => {}
818
+ });
819
+ }
820
+ this.system._register(this.sessionId, this);
821
+ if (this.systemId) {
822
+ this.system._set(this.systemId, this);
823
+ }
824
+ this._processingStatus = ProcessingStatus.Running;
825
+
826
+ // TODO: this isn't correct when rehydrating
827
+ const initEvent = createInitEvent(this.options.input);
828
+ this.system._sendInspectionEvent({
829
+ type: '@xstate.event',
830
+ sourceRef: this._parent,
831
+ actorRef: this,
832
+ event: initEvent
833
+ });
834
+ const status = this._snapshot.status;
835
+ switch (status) {
836
+ case 'done':
837
+ // a state machine can be "done" upon initialization (it could reach a final state using initial microsteps)
838
+ // we still need to complete observers, flush deferreds etc
839
+ this.update(this._snapshot, initEvent);
840
+ // TODO: rethink cleanup of observers, mailbox, etc
841
+ return this;
842
+ case 'error':
843
+ this._error(this._snapshot.error);
844
+ return this;
845
+ }
846
+ if (!this._parent) {
847
+ this.system.start();
848
+ }
849
+ if (this.logic.start) {
850
+ try {
851
+ this.logic.start(this._snapshot, this._actorScope);
852
+ } catch (err) {
853
+ this._snapshot = {
854
+ ...this._snapshot,
855
+ status: 'error',
856
+ error: err
857
+ };
858
+ this._error(err);
859
+ return this;
860
+ }
861
+ }
862
+
863
+ // TODO: this notifies all subscribers but usually this is redundant
864
+ // there is no real change happening here
865
+ // we need to rethink if this needs to be refactored
866
+ this.update(this._snapshot, initEvent);
867
+ if (this.options.devTools) {
868
+ this.attachDevTools();
869
+ }
870
+ this.mailbox.start();
871
+ return this;
872
+ }
873
+ _process(event) {
874
+ let nextState;
875
+ let caughtError;
876
+ try {
877
+ nextState = this.logic.transition(this._snapshot, event, this._actorScope);
878
+ } catch (err) {
879
+ // we wrap it in a box so we can rethrow it later even if falsy value gets caught here
880
+ caughtError = {
881
+ err
882
+ };
883
+ }
884
+ if (caughtError) {
885
+ const {
886
+ err
887
+ } = caughtError;
888
+ this._snapshot = {
889
+ ...this._snapshot,
890
+ status: 'error',
891
+ error: err
892
+ };
893
+ this._error(err);
894
+ return;
895
+ }
896
+ this.update(nextState, event);
897
+ if (event.type === XSTATE_STOP) {
898
+ this._stopProcedure();
899
+ this._complete();
900
+ }
901
+ }
902
+ _stop() {
903
+ if (this._processingStatus === ProcessingStatus.Stopped) {
904
+ return this;
905
+ }
906
+ this.mailbox.clear();
907
+ if (this._processingStatus === ProcessingStatus.NotStarted) {
908
+ this._processingStatus = ProcessingStatus.Stopped;
909
+ return this;
910
+ }
911
+ this.mailbox.enqueue({
912
+ type: XSTATE_STOP
913
+ });
914
+ return this;
915
+ }
916
+
917
+ /** Stops the Actor and unsubscribe all listeners. */
918
+ stop() {
919
+ if (this._parent) {
920
+ throw new Error('A non-root actor cannot be stopped directly.');
921
+ }
922
+ return this._stop();
923
+ }
924
+ _complete() {
925
+ for (const observer of this.observers) {
926
+ try {
927
+ observer.complete?.();
928
+ } catch (err) {
929
+ reportUnhandledError(err);
930
+ }
931
+ }
932
+ this.observers.clear();
933
+ }
934
+ _reportError(err) {
935
+ if (!this.observers.size) {
936
+ if (!this._parent) {
937
+ reportUnhandledError(err);
938
+ }
939
+ return;
940
+ }
941
+ let reportError = false;
942
+ for (const observer of this.observers) {
943
+ const errorListener = observer.error;
944
+ reportError ||= !errorListener;
945
+ try {
946
+ errorListener?.(err);
947
+ } catch (err2) {
948
+ reportUnhandledError(err2);
949
+ }
950
+ }
951
+ this.observers.clear();
952
+ if (reportError) {
953
+ reportUnhandledError(err);
954
+ }
955
+ }
956
+ _error(err) {
957
+ this._stopProcedure();
958
+ this._reportError(err);
959
+ if (this._parent) {
960
+ this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));
961
+ }
962
+ }
963
+ // TODO: atm children don't belong entirely to the actor so
964
+ // in a way - it's not even super aware of them
965
+ // so we can't stop them from here but we really should!
966
+ // right now, they are being stopped within the machine's transition
967
+ // but that could throw and leave us with "orphaned" active actors
968
+ _stopProcedure() {
969
+ if (this._processingStatus !== ProcessingStatus.Running) {
970
+ // Actor already stopped; do nothing
971
+ return this;
972
+ }
973
+
974
+ // Cancel all delayed events
975
+ this.system.scheduler.cancelAll(this);
976
+
977
+ // TODO: mailbox.reset
978
+ this.mailbox.clear();
979
+ // TODO: after `stop` we must prepare ourselves for receiving events again
980
+ // events sent *after* stop signal must be queued
981
+ // it seems like this should be the common behavior for all of our consumers
982
+ // so perhaps this should be unified somehow for all of them
983
+ this.mailbox = new Mailbox(this._process.bind(this));
984
+ this._processingStatus = ProcessingStatus.Stopped;
985
+ this.system._unregister(this);
986
+ return this;
987
+ }
988
+
989
+ /** @internal */
990
+ _send(event) {
991
+ if (this._processingStatus === ProcessingStatus.Stopped) {
992
+ return;
993
+ }
994
+ this.mailbox.enqueue(event);
995
+ }
996
+
997
+ /**
998
+ * Sends an event to the running Actor to trigger a transition.
999
+ *
1000
+ * @param event The event to send
1001
+ */
1002
+ send(event) {
1003
+ this.system._relay(undefined, this, event);
1004
+ }
1005
+ attachDevTools() {
1006
+ const {
1007
+ devTools
1008
+ } = this.options;
1009
+ if (devTools) {
1010
+ const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : dev_dist_xstateDev.devToolsAdapter;
1011
+ resolvedDevToolsAdapter(this);
1012
+ }
1013
+ }
1014
+ toJSON() {
1015
+ return {
1016
+ xstate$$type: $$ACTOR_TYPE,
1017
+ id: this.id
1018
+ };
1019
+ }
1020
+
1021
+ /**
1022
+ * Obtain the internal state of the actor, which can be persisted.
1023
+ *
1024
+ * @remarks
1025
+ * The internal state can be persisted from any actor, not only machines.
1026
+ *
1027
+ * Note that the persisted state is not the same as the snapshot from
1028
+ * {@link Actor.getSnapshot}. Persisted state represents the internal state of
1029
+ * the actor, while snapshots represent the actor's last emitted value.
1030
+ *
1031
+ * Can be restored with {@link ActorOptions.state}
1032
+ * @see https://stately.ai/docs/persistence
1033
+ */
1034
+
1035
+ getPersistedSnapshot(options) {
1036
+ return this.logic.getPersistedSnapshot(this._snapshot, options);
1037
+ }
1038
+ [symbolObservable]() {
1039
+ return this;
1040
+ }
1041
+
1042
+ /**
1043
+ * Read an actor’s snapshot synchronously.
1044
+ *
1045
+ * @remarks
1046
+ * The snapshot represent an actor's last emitted value.
1047
+ *
1048
+ * When an actor receives an event, its internal state may change. An actor
1049
+ * may emit a snapshot when a state transition occurs.
1050
+ *
1051
+ * Note that some actors, such as callback actors generated with
1052
+ * `fromCallback`, will not emit snapshots.
1053
+ * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.
1054
+ * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).
1055
+ */
1056
+ getSnapshot() {
1057
+ return this._snapshot;
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Creates a new actor instance for the given actor logic with the provided
1062
+ * options, if any.
1063
+ *
1064
+ * @remarks
1065
+ * When you create an actor from actor logic via `createActor(logic)`, you
1066
+ * implicitly create an actor system where the created actor is the root actor.
1067
+ * Any actors spawned from this root actor and its descendants are part of that
1068
+ * actor system.
1069
+ * @example
1070
+ *
1071
+ * ```ts
1072
+ * import { createActor } from 'xstate';
1073
+ * import { someActorLogic } from './someActorLogic.ts';
1074
+ *
1075
+ * // Creating the actor, which implicitly creates an actor system with itself as the root actor
1076
+ * const actor = createActor(someActorLogic);
1077
+ *
1078
+ * actor.subscribe((snapshot) => {
1079
+ * console.log(snapshot);
1080
+ * });
1081
+ *
1082
+ * // Actors must be started by calling `actor.start()`, which will also start the actor system.
1083
+ * actor.start();
1084
+ *
1085
+ * // Actors can receive events
1086
+ * actor.send({ type: 'someEvent' });
1087
+ *
1088
+ * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.
1089
+ * actor.stop();
1090
+ * ```
1091
+ *
1092
+ * @param logic - The actor logic to create an actor from. For a state machine
1093
+ * actor logic creator, see {@link createMachine}. Other actor logic creators
1094
+ * include {@link fromCallback}, {@link fromEventObservable},
1095
+ * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.
1096
+ * @param options - Actor options
1097
+ */
1098
+ function createActor(logic, ...[options]) {
1099
+ return new Actor(logic, options);
1100
+ }
1101
+
1102
+ /**
1103
+ * Creates a new Interpreter instance for the given machine with the provided
1104
+ * options, if any.
1105
+ *
1106
+ * @deprecated Use `createActor` instead
1107
+ * @alias
1108
+ */
1109
+ const interpret = createActor;
1110
+
1111
+ /**
1112
+ * @deprecated Use `Actor` instead.
1113
+ * @alias
1114
+ */
1115
+
1116
+ function resolveCancel(_, snapshot, actionArgs, actionParams, {
1117
+ sendId
1118
+ }) {
1119
+ const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;
1120
+ return [snapshot, {
1121
+ sendId: resolvedSendId
1122
+ }, undefined];
1123
+ }
1124
+ function executeCancel(actorScope, params) {
1125
+ actorScope.defer(() => {
1126
+ actorScope.system.scheduler.cancel(actorScope.self, params.sendId);
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The
1131
+ * canceled `sendTo(...)` action will not send its event or execute, unless the
1132
+ * `delay` has already elapsed before `cancel(...)` is called.
1133
+ *
1134
+ * @example
1135
+ *
1136
+ * ```ts
1137
+ * import { createMachine, sendTo, cancel } from 'xstate';
1138
+ *
1139
+ * const machine = createMachine({
1140
+ * // ...
1141
+ * on: {
1142
+ * sendEvent: {
1143
+ * actions: sendTo(
1144
+ * 'some-actor',
1145
+ * { type: 'someEvent' },
1146
+ * {
1147
+ * id: 'some-id',
1148
+ * delay: 1000
1149
+ * }
1150
+ * )
1151
+ * },
1152
+ * cancelEvent: {
1153
+ * actions: cancel('some-id')
1154
+ * }
1155
+ * }
1156
+ * });
1157
+ * ```
1158
+ *
1159
+ * @param sendId The `id` of the `sendTo(...)` action to cancel.
1160
+ */
1161
+ function cancel(sendId) {
1162
+ function cancel(_args, _params) {
1163
+ }
1164
+ cancel.type = 'xstate.cancel';
1165
+ cancel.sendId = sendId;
1166
+ cancel.resolve = resolveCancel;
1167
+ cancel.execute = executeCancel;
1168
+ return cancel;
1169
+ }
1170
+
1171
+ function resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {
1172
+ id,
1173
+ systemId,
1174
+ src,
1175
+ input,
1176
+ syncSnapshot
1177
+ }) {
1178
+ const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;
1179
+ const resolvedId = typeof id === 'function' ? id(actionArgs) : id;
1180
+ let actorRef;
1181
+ let resolvedInput = undefined;
1182
+ if (logic) {
1183
+ resolvedInput = typeof input === 'function' ? input({
1184
+ context: snapshot.context,
1185
+ event: actionArgs.event,
1186
+ self: actorScope.self
1187
+ }) : input;
1188
+ actorRef = createActor(logic, {
1189
+ id: resolvedId,
1190
+ src,
1191
+ parent: actorScope.self,
1192
+ syncSnapshot,
1193
+ systemId,
1194
+ input: resolvedInput
1195
+ });
1196
+ }
1197
+ return [cloneMachineSnapshot(snapshot, {
1198
+ children: {
1199
+ ...snapshot.children,
1200
+ [resolvedId]: actorRef
1201
+ }
1202
+ }), {
1203
+ id,
1204
+ systemId,
1205
+ actorRef,
1206
+ src,
1207
+ input: resolvedInput
1208
+ }, undefined];
1209
+ }
1210
+ function executeSpawn(actorScope, {
1211
+ actorRef
1212
+ }) {
1213
+ if (!actorRef) {
1214
+ return;
1215
+ }
1216
+ actorScope.defer(() => {
1217
+ if (actorRef._processingStatus === ProcessingStatus.Stopped) {
1218
+ return;
1219
+ }
1220
+ actorRef.start();
1221
+ });
1222
+ }
1223
+ function spawnChild(...[src, {
1224
+ id,
1225
+ systemId,
1226
+ input,
1227
+ syncSnapshot = false
1228
+ } = {}]) {
1229
+ function spawnChild(_args, _params) {
1230
+ }
1231
+ spawnChild.type = 'xstate.spawnChild';
1232
+ spawnChild.id = id;
1233
+ spawnChild.systemId = systemId;
1234
+ spawnChild.src = src;
1235
+ spawnChild.input = input;
1236
+ spawnChild.syncSnapshot = syncSnapshot;
1237
+ spawnChild.resolve = resolveSpawn;
1238
+ spawnChild.execute = executeSpawn;
1239
+ return spawnChild;
1240
+ }
1241
+
1242
+ function resolveStop(_, snapshot, args, actionParams, {
1243
+ actorRef
1244
+ }) {
1245
+ const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;
1246
+ const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;
1247
+ let children = snapshot.children;
1248
+ if (resolvedActorRef) {
1249
+ children = {
1250
+ ...children
1251
+ };
1252
+ delete children[resolvedActorRef.id];
1253
+ }
1254
+ return [cloneMachineSnapshot(snapshot, {
1255
+ children
1256
+ }), resolvedActorRef, undefined];
1257
+ }
1258
+ function executeStop(actorScope, actorRef) {
1259
+ if (!actorRef) {
1260
+ return;
1261
+ }
1262
+
1263
+ // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately
1264
+ // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)
1265
+ // this could throw on `systemId` collision, for example, when dealing with reentering transitions
1266
+ actorScope.system._unregister(actorRef);
1267
+
1268
+ // this allows us to prevent an actor from being started if it gets stopped within the same macrostep
1269
+ // this can happen, for example, when the invoking state is being exited immediately by an always transition
1270
+ if (actorRef._processingStatus !== ProcessingStatus.Running) {
1271
+ actorScope.stopChild(actorRef);
1272
+ return;
1273
+ }
1274
+ // stopping a child enqueues a stop event in the child actor's mailbox
1275
+ // we need for all of the already enqueued events to be processed before we stop the child
1276
+ // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)
1277
+ // and we don't want to ignore those events
1278
+ actorScope.defer(() => {
1279
+ actorScope.stopChild(actorRef);
1280
+ });
1281
+ }
1282
+ /**
1283
+ * Stops a child actor.
1284
+ *
1285
+ * @param actorRef The actor to stop.
1286
+ */
1287
+ function stopChild(actorRef) {
1288
+ function stop(_args, _params) {
1289
+ }
1290
+ stop.type = 'xstate.stopChild';
1291
+ stop.actorRef = actorRef;
1292
+ stop.resolve = resolveStop;
1293
+ stop.execute = executeStop;
1294
+ return stop;
1295
+ }
1296
+
1297
+ /**
1298
+ * Stops a child actor.
1299
+ *
1300
+ * @deprecated Use `stopChild(...)` instead
1301
+ * @alias
1302
+ */
1303
+ const stop = stopChild;
1304
+
1305
+ function checkStateIn(snapshot, _, {
1306
+ stateValue
1307
+ }) {
1308
+ if (typeof stateValue === 'string' && isStateId(stateValue)) {
1309
+ const target = snapshot.machine.getStateNodeById(stateValue);
1310
+ return snapshot._nodes.some(sn => sn === target);
1311
+ }
1312
+ return snapshot.matches(stateValue);
1313
+ }
1314
+ function stateIn(stateValue) {
1315
+ function stateIn() {
1316
+ return false;
1317
+ }
1318
+ stateIn.check = checkStateIn;
1319
+ stateIn.stateValue = stateValue;
1320
+ return stateIn;
1321
+ }
1322
+ function checkNot(snapshot, {
1323
+ context,
1324
+ event
1325
+ }, {
1326
+ guards
1327
+ }) {
1328
+ return !evaluateGuard(guards[0], context, event, snapshot);
1329
+ }
1330
+
1331
+ /**
1332
+ * Higher-order guard that evaluates to `true` if the `guard` passed to it
1333
+ * evaluates to `false`.
1334
+ *
1335
+ * @category Guards
1336
+ * @example
1337
+ *
1338
+ * ```ts
1339
+ * import { setup, not } from 'xstate';
1340
+ *
1341
+ * const machine = setup({
1342
+ * guards: {
1343
+ * someNamedGuard: () => false
1344
+ * }
1345
+ * }).createMachine({
1346
+ * on: {
1347
+ * someEvent: {
1348
+ * guard: not('someNamedGuard'),
1349
+ * actions: () => {
1350
+ * // will be executed if guard in `not(...)`
1351
+ * // evaluates to `false`
1352
+ * }
1353
+ * }
1354
+ * }
1355
+ * });
1356
+ * ```
1357
+ *
1358
+ * @returns A guard
1359
+ */
1360
+ function not(guard) {
1361
+ function not(_args, _params) {
1362
+ return false;
1363
+ }
1364
+ not.check = checkNot;
1365
+ not.guards = [guard];
1366
+ return not;
1367
+ }
1368
+ function checkAnd(snapshot, {
1369
+ context,
1370
+ event
1371
+ }, {
1372
+ guards
1373
+ }) {
1374
+ return guards.every(guard => evaluateGuard(guard, context, event, snapshot));
1375
+ }
1376
+
1377
+ /**
1378
+ * Higher-order guard that evaluates to `true` if all `guards` passed to it
1379
+ * evaluate to `true`.
1380
+ *
1381
+ * @category Guards
1382
+ * @example
1383
+ *
1384
+ * ```ts
1385
+ * import { setup, and } from 'xstate';
1386
+ *
1387
+ * const machine = setup({
1388
+ * guards: {
1389
+ * someNamedGuard: () => true
1390
+ * }
1391
+ * }).createMachine({
1392
+ * on: {
1393
+ * someEvent: {
1394
+ * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),
1395
+ * actions: () => {
1396
+ * // will be executed if all guards in `and(...)`
1397
+ * // evaluate to true
1398
+ * }
1399
+ * }
1400
+ * }
1401
+ * });
1402
+ * ```
1403
+ *
1404
+ * @returns A guard action object
1405
+ */
1406
+ function and(guards) {
1407
+ function and(_args, _params) {
1408
+ return false;
1409
+ }
1410
+ and.check = checkAnd;
1411
+ and.guards = guards;
1412
+ return and;
1413
+ }
1414
+ function checkOr(snapshot, {
1415
+ context,
1416
+ event
1417
+ }, {
1418
+ guards
1419
+ }) {
1420
+ return guards.some(guard => evaluateGuard(guard, context, event, snapshot));
1421
+ }
1422
+
1423
+ /**
1424
+ * Higher-order guard that evaluates to `true` if any of the `guards` passed to
1425
+ * it evaluate to `true`.
1426
+ *
1427
+ * @category Guards
1428
+ * @example
1429
+ *
1430
+ * ```ts
1431
+ * import { setup, or } from 'xstate';
1432
+ *
1433
+ * const machine = setup({
1434
+ * guards: {
1435
+ * someNamedGuard: () => true
1436
+ * }
1437
+ * }).createMachine({
1438
+ * on: {
1439
+ * someEvent: {
1440
+ * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),
1441
+ * actions: () => {
1442
+ * // will be executed if any of the guards in `or(...)`
1443
+ * // evaluate to true
1444
+ * }
1445
+ * }
1446
+ * }
1447
+ * });
1448
+ * ```
1449
+ *
1450
+ * @returns A guard action object
1451
+ */
1452
+ function or(guards) {
1453
+ function or(_args, _params) {
1454
+ return false;
1455
+ }
1456
+ or.check = checkOr;
1457
+ or.guards = guards;
1458
+ return or;
1459
+ }
1460
+
1461
+ // TODO: throw on cycles (depth check should be enough)
1462
+ function evaluateGuard(guard, context, event, snapshot) {
1463
+ const {
1464
+ machine
1465
+ } = snapshot;
1466
+ const isInline = typeof guard === 'function';
1467
+ const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];
1468
+ if (!isInline && !resolved) {
1469
+ throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);
1470
+ }
1471
+ if (typeof resolved !== 'function') {
1472
+ return evaluateGuard(resolved, context, event, snapshot);
1473
+ }
1474
+ const guardArgs = {
1475
+ context,
1476
+ event
1477
+ };
1478
+ const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({
1479
+ context,
1480
+ event
1481
+ }) : guard.params : undefined;
1482
+ if (!('check' in resolved)) {
1483
+ // the existing type of `.guards` assumes non-nullable `TExpressionGuard`
1484
+ // inline guards expect `TExpressionGuard` to be set to `undefined`
1485
+ // it's fine to cast this here, our logic makes sure that we call those 2 "variants" correctly
1486
+ return resolved(guardArgs, guardParams);
1487
+ }
1488
+ const builtinGuard = resolved;
1489
+ return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params
1490
+ );
1491
+ }
1492
+
1493
+ const isAtomicStateNode = stateNode => stateNode.type === 'atomic' || stateNode.type === 'final';
1494
+ function getChildren(stateNode) {
1495
+ return Object.values(stateNode.states).filter(sn => sn.type !== 'history');
1496
+ }
1497
+ function getProperAncestors(stateNode, toStateNode) {
1498
+ const ancestors = [];
1499
+ if (toStateNode === stateNode) {
1500
+ return ancestors;
1501
+ }
1502
+
1503
+ // add all ancestors
1504
+ let m = stateNode.parent;
1505
+ while (m && m !== toStateNode) {
1506
+ ancestors.push(m);
1507
+ m = m.parent;
1508
+ }
1509
+ return ancestors;
1510
+ }
1511
+ function getAllStateNodes(stateNodes) {
1512
+ const nodeSet = new Set(stateNodes);
1513
+ const adjList = getAdjList(nodeSet);
1514
+
1515
+ // add descendants
1516
+ for (const s of nodeSet) {
1517
+ // if previously active, add existing child nodes
1518
+ if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {
1519
+ getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));
1520
+ } else {
1521
+ if (s.type === 'parallel') {
1522
+ for (const child of getChildren(s)) {
1523
+ if (child.type === 'history') {
1524
+ continue;
1525
+ }
1526
+ if (!nodeSet.has(child)) {
1527
+ const initialStates = getInitialStateNodesWithTheirAncestors(child);
1528
+ for (const initialStateNode of initialStates) {
1529
+ nodeSet.add(initialStateNode);
1530
+ }
1531
+ }
1532
+ }
1533
+ }
1534
+ }
1535
+ }
1536
+
1537
+ // add all ancestors
1538
+ for (const s of nodeSet) {
1539
+ let m = s.parent;
1540
+ while (m) {
1541
+ nodeSet.add(m);
1542
+ m = m.parent;
1543
+ }
1544
+ }
1545
+ return nodeSet;
1546
+ }
1547
+ function getValueFromAdj(baseNode, adjList) {
1548
+ const childStateNodes = adjList.get(baseNode);
1549
+ if (!childStateNodes) {
1550
+ return {}; // todo: fix?
1551
+ }
1552
+ if (baseNode.type === 'compound') {
1553
+ const childStateNode = childStateNodes[0];
1554
+ if (childStateNode) {
1555
+ if (isAtomicStateNode(childStateNode)) {
1556
+ return childStateNode.key;
1557
+ }
1558
+ } else {
1559
+ return {};
1560
+ }
1561
+ }
1562
+ const stateValue = {};
1563
+ for (const childStateNode of childStateNodes) {
1564
+ stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);
1565
+ }
1566
+ return stateValue;
1567
+ }
1568
+ function getAdjList(stateNodes) {
1569
+ const adjList = new Map();
1570
+ for (const s of stateNodes) {
1571
+ if (!adjList.has(s)) {
1572
+ adjList.set(s, []);
1573
+ }
1574
+ if (s.parent) {
1575
+ if (!adjList.has(s.parent)) {
1576
+ adjList.set(s.parent, []);
1577
+ }
1578
+ adjList.get(s.parent).push(s);
1579
+ }
1580
+ }
1581
+ return adjList;
1582
+ }
1583
+ function getStateValue(rootNode, stateNodes) {
1584
+ const config = getAllStateNodes(stateNodes);
1585
+ return getValueFromAdj(rootNode, getAdjList(config));
1586
+ }
1587
+ function isInFinalState(stateNodeSet, stateNode) {
1588
+ if (stateNode.type === 'compound') {
1589
+ return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));
1590
+ }
1591
+ if (stateNode.type === 'parallel') {
1592
+ return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));
1593
+ }
1594
+ return stateNode.type === 'final';
1595
+ }
1596
+ const isStateId = str => str[0] === STATE_IDENTIFIER;
1597
+ function getCandidates(stateNode, receivedEventType) {
1598
+ const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => {
1599
+ // check if transition is a wildcard transition,
1600
+ // which matches any non-transient events
1601
+ if (eventDescriptor === WILDCARD) {
1602
+ return true;
1603
+ }
1604
+ if (!eventDescriptor.endsWith('.*')) {
1605
+ return false;
1606
+ }
1607
+ const partialEventTokens = eventDescriptor.split('.');
1608
+ const eventTokens = receivedEventType.split('.');
1609
+ for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {
1610
+ const partialEventToken = partialEventTokens[tokenIndex];
1611
+ const eventToken = eventTokens[tokenIndex];
1612
+ if (partialEventToken === '*') {
1613
+ const isLastToken = tokenIndex === partialEventTokens.length - 1;
1614
+ return isLastToken;
1615
+ }
1616
+ if (partialEventToken !== eventToken) {
1617
+ return false;
1618
+ }
1619
+ }
1620
+ return true;
1621
+ }).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));
1622
+ return candidates;
1623
+ }
1624
+
1625
+ /** All delayed transitions from the config. */
1626
+ function getDelayedTransitions(stateNode) {
1627
+ const afterConfig = stateNode.config.after;
1628
+ if (!afterConfig) {
1629
+ return [];
1630
+ }
1631
+ const mutateEntryExit = delay => {
1632
+ const afterEvent = createAfterEvent(delay, stateNode.id);
1633
+ const eventType = afterEvent.type;
1634
+ stateNode.entry.push(raise(afterEvent, {
1635
+ id: eventType,
1636
+ delay
1637
+ }));
1638
+ stateNode.exit.push(cancel(eventType));
1639
+ return eventType;
1640
+ };
1641
+ const delayedTransitions = Object.keys(afterConfig).flatMap(delay => {
1642
+ const configTransition = afterConfig[delay];
1643
+ const resolvedTransition = typeof configTransition === 'string' ? {
1644
+ target: configTransition
1645
+ } : configTransition;
1646
+ const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;
1647
+ const eventType = mutateEntryExit(resolvedDelay);
1648
+ return toArray(resolvedTransition).map(transition => ({
1649
+ ...transition,
1650
+ event: eventType,
1651
+ delay: resolvedDelay
1652
+ }));
1653
+ });
1654
+ return delayedTransitions.map(delayedTransition => {
1655
+ const {
1656
+ delay
1657
+ } = delayedTransition;
1658
+ return {
1659
+ ...formatTransition(stateNode, delayedTransition.event, delayedTransition),
1660
+ delay
1661
+ };
1662
+ });
1663
+ }
1664
+ function formatTransition(stateNode, descriptor, transitionConfig) {
1665
+ const normalizedTarget = normalizeTarget(transitionConfig.target);
1666
+ const reenter = transitionConfig.reenter ?? false;
1667
+ const target = resolveTarget(stateNode, normalizedTarget);
1668
+ const transition = {
1669
+ ...transitionConfig,
1670
+ actions: toArray(transitionConfig.actions),
1671
+ guard: transitionConfig.guard,
1672
+ target,
1673
+ source: stateNode,
1674
+ reenter,
1675
+ eventType: descriptor,
1676
+ toJSON: () => ({
1677
+ ...transition,
1678
+ source: `#${stateNode.id}`,
1679
+ target: target ? target.map(t => `#${t.id}`) : undefined
1680
+ })
1681
+ };
1682
+ return transition;
1683
+ }
1684
+ function formatTransitions(stateNode) {
1685
+ const transitions = new Map();
1686
+ if (stateNode.config.on) {
1687
+ for (const descriptor of Object.keys(stateNode.config.on)) {
1688
+ if (descriptor === NULL_EVENT) {
1689
+ throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');
1690
+ }
1691
+ const transitionsConfig = stateNode.config.on[descriptor];
1692
+ transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));
1693
+ }
1694
+ }
1695
+ if (stateNode.config.onDone) {
1696
+ const descriptor = `xstate.done.state.${stateNode.id}`;
1697
+ transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1698
+ }
1699
+ for (const invokeDef of stateNode.invoke) {
1700
+ if (invokeDef.onDone) {
1701
+ const descriptor = `xstate.done.actor.${invokeDef.id}`;
1702
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));
1703
+ }
1704
+ if (invokeDef.onError) {
1705
+ const descriptor = `xstate.error.actor.${invokeDef.id}`;
1706
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));
1707
+ }
1708
+ if (invokeDef.onSnapshot) {
1709
+ const descriptor = `xstate.snapshot.${invokeDef.id}`;
1710
+ transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));
1711
+ }
1712
+ }
1713
+ for (const delayedTransition of stateNode.after) {
1714
+ let existing = transitions.get(delayedTransition.eventType);
1715
+ if (!existing) {
1716
+ existing = [];
1717
+ transitions.set(delayedTransition.eventType, existing);
1718
+ }
1719
+ existing.push(delayedTransition);
1720
+ }
1721
+ return transitions;
1722
+ }
1723
+ function formatInitialTransition(stateNode, _target) {
1724
+ const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;
1725
+ if (!resolvedTarget && _target) {
1726
+ throw new Error(
1727
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string
1728
+ `Initial state node "${_target}" not found on parent state node #${stateNode.id}`);
1729
+ }
1730
+ const transition = {
1731
+ source: stateNode,
1732
+ actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),
1733
+ eventType: null,
1734
+ reenter: false,
1735
+ target: resolvedTarget ? [resolvedTarget] : [],
1736
+ toJSON: () => ({
1737
+ ...transition,
1738
+ source: `#${stateNode.id}`,
1739
+ target: resolvedTarget ? [`#${resolvedTarget.id}`] : []
1740
+ })
1741
+ };
1742
+ return transition;
1743
+ }
1744
+ function resolveTarget(stateNode, targets) {
1745
+ if (targets === undefined) {
1746
+ // an undefined target signals that the state node should not transition from that state when receiving that event
1747
+ return undefined;
1748
+ }
1749
+ return targets.map(target => {
1750
+ if (typeof target !== 'string') {
1751
+ return target;
1752
+ }
1753
+ if (isStateId(target)) {
1754
+ return stateNode.machine.getStateNodeById(target);
1755
+ }
1756
+ const isInternalTarget = target[0] === STATE_DELIMITER;
1757
+ // If internal target is defined on machine,
1758
+ // do not include machine key on target
1759
+ if (isInternalTarget && !stateNode.parent) {
1760
+ return getStateNodeByPath(stateNode, target.slice(1));
1761
+ }
1762
+ const resolvedTarget = isInternalTarget ? stateNode.key + target : target;
1763
+ if (stateNode.parent) {
1764
+ try {
1765
+ const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);
1766
+ return targetStateNode;
1767
+ } catch (err) {
1768
+ throw new Error(`Invalid transition definition for state node '${stateNode.id}':\n${err.message}`);
1769
+ }
1770
+ } else {
1771
+ throw new Error(`Invalid target: "${target}" is not a valid target from the root node. Did you mean ".${target}"?`);
1772
+ }
1773
+ });
1774
+ }
1775
+ function resolveHistoryDefaultTransition(stateNode) {
1776
+ const normalizedTarget = normalizeTarget(stateNode.config.target);
1777
+ if (!normalizedTarget) {
1778
+ return stateNode.parent.initial;
1779
+ }
1780
+ return {
1781
+ target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)
1782
+ };
1783
+ }
1784
+ function isHistoryNode(stateNode) {
1785
+ return stateNode.type === 'history';
1786
+ }
1787
+ function getInitialStateNodesWithTheirAncestors(stateNode) {
1788
+ const states = getInitialStateNodes(stateNode);
1789
+ for (const initialState of states) {
1790
+ for (const ancestor of getProperAncestors(initialState, stateNode)) {
1791
+ states.add(ancestor);
1792
+ }
1793
+ }
1794
+ return states;
1795
+ }
1796
+ function getInitialStateNodes(stateNode) {
1797
+ const set = new Set();
1798
+ function iter(descStateNode) {
1799
+ if (set.has(descStateNode)) {
1800
+ return;
1801
+ }
1802
+ set.add(descStateNode);
1803
+ if (descStateNode.type === 'compound') {
1804
+ iter(descStateNode.initial.target[0]);
1805
+ } else if (descStateNode.type === 'parallel') {
1806
+ for (const child of getChildren(descStateNode)) {
1807
+ iter(child);
1808
+ }
1809
+ }
1810
+ }
1811
+ iter(stateNode);
1812
+ return set;
1813
+ }
1814
+ /** Returns the child state node from its relative `stateKey`, or throws. */
1815
+ function getStateNode(stateNode, stateKey) {
1816
+ if (isStateId(stateKey)) {
1817
+ return stateNode.machine.getStateNodeById(stateKey);
1818
+ }
1819
+ if (!stateNode.states) {
1820
+ throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);
1821
+ }
1822
+ const result = stateNode.states[stateKey];
1823
+ if (!result) {
1824
+ throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);
1825
+ }
1826
+ return result;
1827
+ }
1828
+
1829
+ /**
1830
+ * Returns the relative state node from the given `statePath`, or throws.
1831
+ *
1832
+ * @param statePath The string or string array relative path to the state node.
1833
+ */
1834
+ function getStateNodeByPath(stateNode, statePath) {
1835
+ if (typeof statePath === 'string' && isStateId(statePath)) {
1836
+ try {
1837
+ return stateNode.machine.getStateNodeById(statePath);
1838
+ } catch {
1839
+ // try individual paths
1840
+ // throw e;
1841
+ }
1842
+ }
1843
+ const arrayStatePath = toStatePath(statePath).slice();
1844
+ let currentStateNode = stateNode;
1845
+ while (arrayStatePath.length) {
1846
+ const key = arrayStatePath.shift();
1847
+ if (!key.length) {
1848
+ break;
1849
+ }
1850
+ currentStateNode = getStateNode(currentStateNode, key);
1851
+ }
1852
+ return currentStateNode;
1853
+ }
1854
+
1855
+ /**
1856
+ * Returns the state nodes represented by the current state value.
1857
+ *
1858
+ * @param stateValue The state value or State instance
1859
+ */
1860
+ function getStateNodes(stateNode, stateValue) {
1861
+ if (typeof stateValue === 'string') {
1862
+ const childStateNode = stateNode.states[stateValue];
1863
+ if (!childStateNode) {
1864
+ throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);
1865
+ }
1866
+ return [stateNode, childStateNode];
1867
+ }
1868
+ const childStateKeys = Object.keys(stateValue);
1869
+ const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);
1870
+ return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {
1871
+ const subStateNode = getStateNode(stateNode, subStateKey);
1872
+ if (!subStateNode) {
1873
+ return allSubStateNodes;
1874
+ }
1875
+ const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);
1876
+ return allSubStateNodes.concat(subStateNodes);
1877
+ }, []));
1878
+ }
1879
+ function transitionAtomicNode(stateNode, stateValue, snapshot, event) {
1880
+ const childStateNode = getStateNode(stateNode, stateValue);
1881
+ const next = childStateNode.next(snapshot, event);
1882
+ if (!next || !next.length) {
1883
+ return stateNode.next(snapshot, event);
1884
+ }
1885
+ return next;
1886
+ }
1887
+ function transitionCompoundNode(stateNode, stateValue, snapshot, event) {
1888
+ const subStateKeys = Object.keys(stateValue);
1889
+ const childStateNode = getStateNode(stateNode, subStateKeys[0]);
1890
+ const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);
1891
+ if (!next || !next.length) {
1892
+ return stateNode.next(snapshot, event);
1893
+ }
1894
+ return next;
1895
+ }
1896
+ function transitionParallelNode(stateNode, stateValue, snapshot, event) {
1897
+ const allInnerTransitions = [];
1898
+ for (const subStateKey of Object.keys(stateValue)) {
1899
+ const subStateValue = stateValue[subStateKey];
1900
+ if (!subStateValue) {
1901
+ continue;
1902
+ }
1903
+ const subStateNode = getStateNode(stateNode, subStateKey);
1904
+ const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);
1905
+ if (innerTransitions) {
1906
+ allInnerTransitions.push(...innerTransitions);
1907
+ }
1908
+ }
1909
+ if (!allInnerTransitions.length) {
1910
+ return stateNode.next(snapshot, event);
1911
+ }
1912
+ return allInnerTransitions;
1913
+ }
1914
+ function transitionNode(stateNode, stateValue, snapshot, event) {
1915
+ // leaf node
1916
+ if (typeof stateValue === 'string') {
1917
+ return transitionAtomicNode(stateNode, stateValue, snapshot, event);
1918
+ }
1919
+
1920
+ // compound node
1921
+ if (Object.keys(stateValue).length === 1) {
1922
+ return transitionCompoundNode(stateNode, stateValue, snapshot, event);
1923
+ }
1924
+
1925
+ // parallel node
1926
+ return transitionParallelNode(stateNode, stateValue, snapshot, event);
1927
+ }
1928
+ function getHistoryNodes(stateNode) {
1929
+ return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');
1930
+ }
1931
+ function isDescendant(childStateNode, parentStateNode) {
1932
+ let marker = childStateNode;
1933
+ while (marker.parent && marker.parent !== parentStateNode) {
1934
+ marker = marker.parent;
1935
+ }
1936
+ return marker.parent === parentStateNode;
1937
+ }
1938
+ function hasIntersection(s1, s2) {
1939
+ const set1 = new Set(s1);
1940
+ const set2 = new Set(s2);
1941
+ for (const item of set1) {
1942
+ if (set2.has(item)) {
1943
+ return true;
1944
+ }
1945
+ }
1946
+ for (const item of set2) {
1947
+ if (set1.has(item)) {
1948
+ return true;
1949
+ }
1950
+ }
1951
+ return false;
1952
+ }
1953
+ function removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {
1954
+ const filteredTransitions = new Set();
1955
+ for (const t1 of enabledTransitions) {
1956
+ let t1Preempted = false;
1957
+ const transitionsToRemove = new Set();
1958
+ for (const t2 of filteredTransitions) {
1959
+ if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {
1960
+ if (isDescendant(t1.source, t2.source)) {
1961
+ transitionsToRemove.add(t2);
1962
+ } else {
1963
+ t1Preempted = true;
1964
+ break;
1965
+ }
1966
+ }
1967
+ }
1968
+ if (!t1Preempted) {
1969
+ for (const t3 of transitionsToRemove) {
1970
+ filteredTransitions.delete(t3);
1971
+ }
1972
+ filteredTransitions.add(t1);
1973
+ }
1974
+ }
1975
+ return Array.from(filteredTransitions);
1976
+ }
1977
+ function findLeastCommonAncestor(stateNodes) {
1978
+ const [head, ...tail] = stateNodes;
1979
+ for (const ancestor of getProperAncestors(head, undefined)) {
1980
+ if (tail.every(sn => isDescendant(sn, ancestor))) {
1981
+ return ancestor;
1982
+ }
1983
+ }
1984
+ }
1985
+ function getEffectiveTargetStates(transition, historyValue) {
1986
+ if (!transition.target) {
1987
+ return [];
1988
+ }
1989
+ const targets = new Set();
1990
+ for (const targetNode of transition.target) {
1991
+ if (isHistoryNode(targetNode)) {
1992
+ if (historyValue[targetNode.id]) {
1993
+ for (const node of historyValue[targetNode.id]) {
1994
+ targets.add(node);
1995
+ }
1996
+ } else {
1997
+ for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {
1998
+ targets.add(node);
1999
+ }
2000
+ }
2001
+ } else {
2002
+ targets.add(targetNode);
2003
+ }
2004
+ }
2005
+ return [...targets];
2006
+ }
2007
+ function getTransitionDomain(transition, historyValue) {
2008
+ const targetStates = getEffectiveTargetStates(transition, historyValue);
2009
+ if (!targetStates) {
2010
+ return;
2011
+ }
2012
+ if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {
2013
+ return transition.source;
2014
+ }
2015
+ const lca = findLeastCommonAncestor(targetStates.concat(transition.source));
2016
+ if (lca) {
2017
+ return lca;
2018
+ }
2019
+
2020
+ // at this point we know that it's a root transition since LCA couldn't be found
2021
+ if (transition.reenter) {
2022
+ return;
2023
+ }
2024
+ return transition.source.machine.root;
2025
+ }
2026
+ function computeExitSet(transitions, stateNodeSet, historyValue) {
2027
+ const statesToExit = new Set();
2028
+ for (const t of transitions) {
2029
+ if (t.target?.length) {
2030
+ const domain = getTransitionDomain(t, historyValue);
2031
+ if (t.reenter && t.source === domain) {
2032
+ statesToExit.add(domain);
2033
+ }
2034
+ for (const stateNode of stateNodeSet) {
2035
+ if (isDescendant(stateNode, domain)) {
2036
+ statesToExit.add(stateNode);
2037
+ }
2038
+ }
2039
+ }
2040
+ }
2041
+ return [...statesToExit];
2042
+ }
2043
+ function areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {
2044
+ if (prevStateNodes.length !== nextStateNodeSet.size) {
2045
+ return false;
2046
+ }
2047
+ for (const node of prevStateNodes) {
2048
+ if (!nextStateNodeSet.has(node)) {
2049
+ return false;
2050
+ }
2051
+ }
2052
+ return true;
2053
+ }
2054
+
2055
+ /** https://www.w3.org/TR/scxml/#microstepProcedure */
2056
+ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {
2057
+ if (!transitions.length) {
2058
+ return currentSnapshot;
2059
+ }
2060
+ const mutStateNodeSet = new Set(currentSnapshot._nodes);
2061
+ let historyValue = currentSnapshot.historyValue;
2062
+ const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);
2063
+ let nextState = currentSnapshot;
2064
+
2065
+ // Exit states
2066
+ if (!isInitial) {
2067
+ [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);
2068
+ }
2069
+
2070
+ // Execute transition content
2071
+ nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue, undefined);
2072
+
2073
+ // Enter states
2074
+ nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);
2075
+ const nextStateNodes = [...mutStateNodeSet];
2076
+ if (nextState.status === 'done') {
2077
+ nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue, undefined);
2078
+ }
2079
+
2080
+ // eslint-disable-next-line no-useless-catch
2081
+ try {
2082
+ if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {
2083
+ return nextState;
2084
+ }
2085
+ return cloneMachineSnapshot(nextState, {
2086
+ _nodes: nextStateNodes,
2087
+ historyValue
2088
+ });
2089
+ } catch (e) {
2090
+ // TODO: Refactor this once proper error handling is implemented.
2091
+ // See https://github.com/statelyai/rfcs/pull/4
2092
+ throw e;
2093
+ }
2094
+ }
2095
+ function getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {
2096
+ if (rootNode.output === undefined) {
2097
+ return;
2098
+ }
2099
+ const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);
2100
+ return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);
2101
+ }
2102
+ function enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {
2103
+ let nextSnapshot = currentSnapshot;
2104
+ const statesToEnter = new Set();
2105
+ // those are states that were directly targeted or indirectly targeted by the explicit target
2106
+ // in other words, those are states for which initial actions should be executed
2107
+ // when we target `#deep_child` initial actions of its ancestors shouldn't be executed
2108
+ const statesForDefaultEntry = new Set();
2109
+ computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);
2110
+
2111
+ // In the initial state, the root state node is "entered".
2112
+ if (isInitial) {
2113
+ statesForDefaultEntry.add(currentSnapshot.machine.root);
2114
+ }
2115
+ const completedNodes = new Set();
2116
+ for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {
2117
+ mutStateNodeSet.add(stateNodeToEnter);
2118
+ const actions = [];
2119
+
2120
+ // Add entry actions
2121
+ actions.push(...stateNodeToEnter.entry);
2122
+ for (const invokeDef of stateNodeToEnter.invoke) {
2123
+ actions.push(spawnChild(invokeDef.src, {
2124
+ ...invokeDef,
2125
+ syncSnapshot: !!invokeDef.onSnapshot
2126
+ }));
2127
+ }
2128
+ if (statesForDefaultEntry.has(stateNodeToEnter)) {
2129
+ const initialActions = stateNodeToEnter.initial.actions;
2130
+ actions.push(...initialActions);
2131
+ }
2132
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));
2133
+ if (stateNodeToEnter.type === 'final') {
2134
+ const parent = stateNodeToEnter.parent;
2135
+ let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;
2136
+ let rootCompletionNode = ancestorMarker || stateNodeToEnter;
2137
+ if (parent?.type === 'compound') {
2138
+ internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));
2139
+ }
2140
+ while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {
2141
+ completedNodes.add(ancestorMarker);
2142
+ internalQueue.push(createDoneStateEvent(ancestorMarker.id));
2143
+ rootCompletionNode = ancestorMarker;
2144
+ ancestorMarker = ancestorMarker.parent;
2145
+ }
2146
+ if (ancestorMarker) {
2147
+ continue;
2148
+ }
2149
+ nextSnapshot = cloneMachineSnapshot(nextSnapshot, {
2150
+ status: 'done',
2151
+ output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)
2152
+ });
2153
+ }
2154
+ }
2155
+ return nextSnapshot;
2156
+ }
2157
+ function computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {
2158
+ for (const t of transitions) {
2159
+ const domain = getTransitionDomain(t, historyValue);
2160
+ for (const s of t.target || []) {
2161
+ if (!isHistoryNode(s) && (
2162
+ // if the target is different than the source then it will *definitely* be entered
2163
+ t.source !== s ||
2164
+ // we know that the domain can't lie within the source
2165
+ // if it's different than the source then it's outside of it and it means that the target has to be entered as well
2166
+ t.source !== domain ||
2167
+ // reentering transitions always enter the target, even if it's the source itself
2168
+ t.reenter)) {
2169
+ statesToEnter.add(s);
2170
+ statesForDefaultEntry.add(s);
2171
+ }
2172
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2173
+ }
2174
+ const targetStates = getEffectiveTargetStates(t, historyValue);
2175
+ for (const s of targetStates) {
2176
+ const ancestors = getProperAncestors(s, domain);
2177
+ if (domain?.type === 'parallel') {
2178
+ ancestors.push(domain);
2179
+ }
2180
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);
2181
+ }
2182
+ }
2183
+ }
2184
+ function addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {
2185
+ if (isHistoryNode(stateNode)) {
2186
+ if (historyValue[stateNode.id]) {
2187
+ const historyStateNodes = historyValue[stateNode.id];
2188
+ for (const s of historyStateNodes) {
2189
+ statesToEnter.add(s);
2190
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2191
+ }
2192
+ for (const s of historyStateNodes) {
2193
+ addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2194
+ }
2195
+ } else {
2196
+ const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);
2197
+ for (const s of historyDefaultTransition.target) {
2198
+ statesToEnter.add(s);
2199
+ if (historyDefaultTransition === stateNode.parent?.initial) {
2200
+ statesForDefaultEntry.add(stateNode.parent);
2201
+ }
2202
+ addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);
2203
+ }
2204
+ for (const s of historyDefaultTransition.target) {
2205
+ addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);
2206
+ }
2207
+ }
2208
+ } else {
2209
+ if (stateNode.type === 'compound') {
2210
+ const [initialState] = stateNode.initial.target;
2211
+ if (!isHistoryNode(initialState)) {
2212
+ statesToEnter.add(initialState);
2213
+ statesForDefaultEntry.add(initialState);
2214
+ }
2215
+ addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);
2216
+ addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);
2217
+ } else {
2218
+ if (stateNode.type === 'parallel') {
2219
+ for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {
2220
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2221
+ if (!isHistoryNode(child)) {
2222
+ statesToEnter.add(child);
2223
+ statesForDefaultEntry.add(child);
2224
+ }
2225
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2226
+ }
2227
+ }
2228
+ }
2229
+ }
2230
+ }
2231
+ }
2232
+ function addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {
2233
+ for (const anc of ancestors) {
2234
+ if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {
2235
+ statesToEnter.add(anc);
2236
+ }
2237
+ if (anc.type === 'parallel') {
2238
+ for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {
2239
+ if (![...statesToEnter].some(s => isDescendant(s, child))) {
2240
+ statesToEnter.add(child);
2241
+ addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);
2242
+ }
2243
+ }
2244
+ }
2245
+ }
2246
+ }
2247
+ function addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {
2248
+ addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));
2249
+ }
2250
+ function exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {
2251
+ let nextSnapshot = currentSnapshot;
2252
+ const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);
2253
+ statesToExit.sort((a, b) => b.order - a.order);
2254
+ let changedHistory;
2255
+
2256
+ // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates
2257
+ for (const exitStateNode of statesToExit) {
2258
+ for (const historyNode of getHistoryNodes(exitStateNode)) {
2259
+ let predicate;
2260
+ if (historyNode.history === 'deep') {
2261
+ predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);
2262
+ } else {
2263
+ predicate = sn => {
2264
+ return sn.parent === exitStateNode;
2265
+ };
2266
+ }
2267
+ changedHistory ??= {
2268
+ ...historyValue
2269
+ };
2270
+ changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);
2271
+ }
2272
+ }
2273
+ for (const s of statesToExit) {
2274
+ nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue, undefined);
2275
+ mutStateNodeSet.delete(s);
2276
+ }
2277
+ return [nextSnapshot, changedHistory || historyValue];
2278
+ }
2279
+ function getAction(machine, actionType) {
2280
+ return machine.implementations.actions[actionType];
2281
+ }
2282
+ function resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {
2283
+ const {
2284
+ machine
2285
+ } = currentSnapshot;
2286
+ let intermediateSnapshot = currentSnapshot;
2287
+ for (const action of actions) {
2288
+ const isInline = typeof action === 'function';
2289
+ const resolvedAction = isInline ? action :
2290
+ // the existing type of `.actions` assumes non-nullable `TExpressionAction`
2291
+ // it's fine to cast this here to get a common type and lack of errors in the rest of the code
2292
+ // our logic below makes sure that we call those 2 "variants" correctly
2293
+
2294
+ getAction(machine, typeof action === 'string' ? action : action.type);
2295
+ const actionArgs = {
2296
+ context: intermediateSnapshot.context,
2297
+ event,
2298
+ self: actorScope.self,
2299
+ system: actorScope.system
2300
+ };
2301
+ const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({
2302
+ context: intermediateSnapshot.context,
2303
+ event
2304
+ }) : action.params : undefined;
2305
+ if (!resolvedAction || !('resolve' in resolvedAction)) {
2306
+ actorScope.actionExecutor({
2307
+ type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',
2308
+ info: actionArgs,
2309
+ params: actionParams,
2310
+ exec: resolvedAction
2311
+ });
2312
+ continue;
2313
+ }
2314
+ const builtinAction = resolvedAction;
2315
+ const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,
2316
+ // this holds all params
2317
+ extra);
2318
+ intermediateSnapshot = nextState;
2319
+ if ('retryResolve' in builtinAction) {
2320
+ retries?.push([builtinAction, params]);
2321
+ }
2322
+ if ('execute' in builtinAction) {
2323
+ actorScope.actionExecutor({
2324
+ type: builtinAction.type,
2325
+ info: actionArgs,
2326
+ params,
2327
+ exec: builtinAction.execute.bind(null, actorScope, params)
2328
+ });
2329
+ }
2330
+ if (actions) {
2331
+ intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);
2332
+ }
2333
+ }
2334
+ return intermediateSnapshot;
2335
+ }
2336
+ function resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {
2337
+ const retries = deferredActorIds ? [] : undefined;
2338
+ const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {
2339
+ internalQueue,
2340
+ deferredActorIds
2341
+ }, retries);
2342
+ retries?.forEach(([builtinAction, params]) => {
2343
+ builtinAction.retryResolve(actorScope, nextState, params);
2344
+ });
2345
+ return nextState;
2346
+ }
2347
+ function macrostep(snapshot, event, actorScope, internalQueue) {
2348
+ let nextSnapshot = snapshot;
2349
+ const microstates = [];
2350
+ function addMicrostate(microstate, event, transitions) {
2351
+ actorScope.system._sendInspectionEvent({
2352
+ type: '@xstate.microstep',
2353
+ actorRef: actorScope.self,
2354
+ event,
2355
+ snapshot: microstate,
2356
+ _transitions: transitions
2357
+ });
2358
+ microstates.push(microstate);
2359
+ }
2360
+
2361
+ // Handle stop event
2362
+ if (event.type === XSTATE_STOP) {
2363
+ nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {
2364
+ status: 'stopped'
2365
+ });
2366
+ addMicrostate(nextSnapshot, event, []);
2367
+ return {
2368
+ snapshot: nextSnapshot,
2369
+ microstates
2370
+ };
2371
+ }
2372
+ let nextEvent = event;
2373
+
2374
+ // Assume the state is at rest (no raised events)
2375
+ // Determine the next state based on the next microstep
2376
+ if (nextEvent.type !== XSTATE_INIT) {
2377
+ const currentEvent = nextEvent;
2378
+ const isErr = isErrorActorEvent(currentEvent);
2379
+ const transitions = selectTransitions(currentEvent, nextSnapshot);
2380
+ if (isErr && !transitions.length) {
2381
+ // TODO: we should likely only allow transitions selected by very explicit descriptors
2382
+ // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either
2383
+ // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too
2384
+ nextSnapshot = cloneMachineSnapshot(snapshot, {
2385
+ status: 'error',
2386
+ error: currentEvent.error
2387
+ });
2388
+ addMicrostate(nextSnapshot, currentEvent, []);
2389
+ return {
2390
+ snapshot: nextSnapshot,
2391
+ microstates
2392
+ };
2393
+ }
2394
+ nextSnapshot = microstep(transitions, snapshot, actorScope, nextEvent, false,
2395
+ // isInitial
2396
+ internalQueue);
2397
+ addMicrostate(nextSnapshot, currentEvent, transitions);
2398
+ }
2399
+ let shouldSelectEventlessTransitions = true;
2400
+ while (nextSnapshot.status === 'active') {
2401
+ let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];
2402
+
2403
+ // eventless transitions should always be selected after selecting *regular* transitions
2404
+ // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case
2405
+ const previousState = enabledTransitions.length ? nextSnapshot : undefined;
2406
+ if (!enabledTransitions.length) {
2407
+ if (!internalQueue.length) {
2408
+ break;
2409
+ }
2410
+ nextEvent = internalQueue.shift();
2411
+ enabledTransitions = selectTransitions(nextEvent, nextSnapshot);
2412
+ }
2413
+ nextSnapshot = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);
2414
+ shouldSelectEventlessTransitions = nextSnapshot !== previousState;
2415
+ addMicrostate(nextSnapshot, nextEvent, enabledTransitions);
2416
+ }
2417
+ if (nextSnapshot.status !== 'active') {
2418
+ stopChildren(nextSnapshot, nextEvent, actorScope);
2419
+ }
2420
+ return {
2421
+ snapshot: nextSnapshot,
2422
+ microstates
2423
+ };
2424
+ }
2425
+ function stopChildren(nextState, event, actorScope) {
2426
+ return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), [], undefined);
2427
+ }
2428
+ function selectTransitions(event, nextState) {
2429
+ return nextState.machine.getTransitionData(nextState, event);
2430
+ }
2431
+ function selectEventlessTransitions(nextState, event) {
2432
+ const enabledTransitionSet = new Set();
2433
+ const atomicStates = nextState._nodes.filter(isAtomicStateNode);
2434
+ for (const stateNode of atomicStates) {
2435
+ loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {
2436
+ if (!s.always) {
2437
+ continue;
2438
+ }
2439
+ for (const transition of s.always) {
2440
+ if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {
2441
+ enabledTransitionSet.add(transition);
2442
+ break loop;
2443
+ }
2444
+ }
2445
+ }
2446
+ }
2447
+ return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);
2448
+ }
2449
+
2450
+ /**
2451
+ * Resolves a partial state value with its full representation in the state
2452
+ * node's machine.
2453
+ *
2454
+ * @param stateValue The partial state value to resolve.
2455
+ */
2456
+ function resolveStateValue(rootNode, stateValue) {
2457
+ const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));
2458
+ return getStateValue(rootNode, [...allStateNodes]);
2459
+ }
2460
+
2461
+ function isMachineSnapshot(value) {
2462
+ return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;
2463
+ }
2464
+ const machineSnapshotMatches = function matches(testValue) {
2465
+ return matchesState(testValue, this.value);
2466
+ };
2467
+ const machineSnapshotHasTag = function hasTag(tag) {
2468
+ return this.tags.has(tag);
2469
+ };
2470
+ const machineSnapshotCan = function can(event) {
2471
+ const transitionData = this.machine.getTransitionData(this, event);
2472
+ return !!transitionData?.length &&
2473
+ // Check that at least one transition is not forbidden
2474
+ transitionData.some(t => t.target !== undefined || t.actions.length);
2475
+ };
2476
+ const machineSnapshotToJSON = function toJSON() {
2477
+ const {
2478
+ _nodes: nodes,
2479
+ tags,
2480
+ machine,
2481
+ getMeta,
2482
+ toJSON,
2483
+ can,
2484
+ hasTag,
2485
+ matches,
2486
+ ...jsonValues
2487
+ } = this;
2488
+ return {
2489
+ ...jsonValues,
2490
+ tags: Array.from(tags)
2491
+ };
2492
+ };
2493
+ const machineSnapshotGetMeta = function getMeta() {
2494
+ return this._nodes.reduce((acc, stateNode) => {
2495
+ if (stateNode.meta !== undefined) {
2496
+ acc[stateNode.id] = stateNode.meta;
2497
+ }
2498
+ return acc;
2499
+ }, {});
2500
+ };
2501
+ function createMachineSnapshot(config, machine) {
2502
+ return {
2503
+ status: config.status,
2504
+ output: config.output,
2505
+ error: config.error,
2506
+ machine,
2507
+ context: config.context,
2508
+ _nodes: config._nodes,
2509
+ value: getStateValue(machine.root, config._nodes),
2510
+ tags: new Set(config._nodes.flatMap(sn => sn.tags)),
2511
+ children: config.children,
2512
+ historyValue: config.historyValue || {},
2513
+ matches: machineSnapshotMatches,
2514
+ hasTag: machineSnapshotHasTag,
2515
+ can: machineSnapshotCan,
2516
+ getMeta: machineSnapshotGetMeta,
2517
+ toJSON: machineSnapshotToJSON
2518
+ };
2519
+ }
2520
+ function cloneMachineSnapshot(snapshot, config = {}) {
2521
+ return createMachineSnapshot({
2522
+ ...snapshot,
2523
+ ...config
2524
+ }, snapshot.machine);
2525
+ }
2526
+ function serializeHistoryValue(historyValue) {
2527
+ if (typeof historyValue !== 'object' || historyValue === null) {
2528
+ return {};
2529
+ }
2530
+ const result = {};
2531
+ for (const key in historyValue) {
2532
+ const value = historyValue[key];
2533
+ if (Array.isArray(value)) {
2534
+ result[key] = value.map(item => ({
2535
+ id: item.id
2536
+ }));
2537
+ }
2538
+ }
2539
+ return result;
2540
+ }
2541
+ function getPersistedSnapshot(snapshot, options) {
2542
+ const {
2543
+ _nodes: nodes,
2544
+ tags,
2545
+ machine,
2546
+ children,
2547
+ context,
2548
+ can,
2549
+ hasTag,
2550
+ matches,
2551
+ getMeta,
2552
+ toJSON,
2553
+ ...jsonValues
2554
+ } = snapshot;
2555
+ const childrenJson = {};
2556
+ for (const id in children) {
2557
+ const child = children[id];
2558
+ childrenJson[id] = {
2559
+ snapshot: child.getPersistedSnapshot(options),
2560
+ src: child.src,
2561
+ systemId: child.systemId,
2562
+ syncSnapshot: child._syncSnapshot
2563
+ };
2564
+ }
2565
+ const persisted = {
2566
+ ...jsonValues,
2567
+ context: persistContext(context),
2568
+ children: childrenJson,
2569
+ historyValue: serializeHistoryValue(jsonValues.historyValue)
2570
+ };
2571
+ return persisted;
2572
+ }
2573
+ function persistContext(contextPart) {
2574
+ let copy;
2575
+ for (const key in contextPart) {
2576
+ const value = contextPart[key];
2577
+ if (value && typeof value === 'object') {
2578
+ if ('sessionId' in value && 'send' in value && 'ref' in value) {
2579
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2580
+ ...contextPart
2581
+ };
2582
+ copy[key] = {
2583
+ xstate$$type: $$ACTOR_TYPE,
2584
+ id: value.id
2585
+ };
2586
+ } else {
2587
+ const result = persistContext(value);
2588
+ if (result !== value) {
2589
+ copy ??= Array.isArray(contextPart) ? contextPart.slice() : {
2590
+ ...contextPart
2591
+ };
2592
+ copy[key] = result;
2593
+ }
2594
+ }
2595
+ }
2596
+ }
2597
+ return copy ?? contextPart;
2598
+ }
2599
+
2600
+ function resolveRaise(_, snapshot, args, actionParams, {
2601
+ event: eventOrExpr,
2602
+ id,
2603
+ delay
2604
+ }, {
2605
+ internalQueue
2606
+ }) {
2607
+ const delaysMap = snapshot.machine.implementations.delays;
2608
+ if (typeof eventOrExpr === 'string') {
2609
+ throw new Error(
2610
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2611
+ `Only event objects may be used with raise; use raise({ type: "${eventOrExpr}" }) instead`);
2612
+ }
2613
+ const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;
2614
+ let resolvedDelay;
2615
+ if (typeof delay === 'string') {
2616
+ const configDelay = delaysMap && delaysMap[delay];
2617
+ resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;
2618
+ } else {
2619
+ resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;
2620
+ }
2621
+ if (typeof resolvedDelay !== 'number') {
2622
+ internalQueue.push(resolvedEvent);
2623
+ }
2624
+ return [snapshot, {
2625
+ event: resolvedEvent,
2626
+ id,
2627
+ delay: resolvedDelay
2628
+ }, undefined];
2629
+ }
2630
+ function executeRaise(actorScope, params) {
2631
+ const {
2632
+ event,
2633
+ delay,
2634
+ id
2635
+ } = params;
2636
+ if (typeof delay === 'number') {
2637
+ actorScope.defer(() => {
2638
+ const self = actorScope.self;
2639
+ actorScope.system.scheduler.schedule(self, self, event, delay, id);
2640
+ });
2641
+ return;
2642
+ }
2643
+ }
2644
+ /**
2645
+ * Raises an event. This places the event in the internal event queue, so that
2646
+ * the event is immediately consumed by the machine in the current step.
2647
+ *
2648
+ * @param eventType The event to raise.
2649
+ */
2650
+ function raise(eventOrExpr, options) {
2651
+ function raise(_args, _params) {
2652
+ }
2653
+ raise.type = 'xstate.raise';
2654
+ raise.event = eventOrExpr;
2655
+ raise.id = options?.id;
2656
+ raise.delay = options?.delay;
2657
+ raise.resolve = resolveRaise;
2658
+ raise.execute = executeRaise;
2659
+ return raise;
2660
+ }
2661
+
2662
+ raiseDa5b247f_cjs.$$ACTOR_TYPE = $$ACTOR_TYPE;
2663
+ raiseDa5b247f_cjs.Actor = Actor;
2664
+ raiseDa5b247f_cjs.NULL_EVENT = NULL_EVENT;
2665
+ raiseDa5b247f_cjs.ProcessingStatus = ProcessingStatus;
2666
+ raiseDa5b247f_cjs.STATE_DELIMITER = STATE_DELIMITER;
2667
+ raiseDa5b247f_cjs.XSTATE_ERROR = XSTATE_ERROR;
2668
+ raiseDa5b247f_cjs.XSTATE_STOP = XSTATE_STOP;
2669
+ raiseDa5b247f_cjs.and = and;
2670
+ raiseDa5b247f_cjs.cancel = cancel;
2671
+ raiseDa5b247f_cjs.cloneMachineSnapshot = cloneMachineSnapshot;
2672
+ raiseDa5b247f_cjs.createActor = createActor;
2673
+ raiseDa5b247f_cjs.createErrorActorEvent = createErrorActorEvent;
2674
+ raiseDa5b247f_cjs.createInitEvent = createInitEvent;
2675
+ raiseDa5b247f_cjs.createInvokeId = createInvokeId;
2676
+ raiseDa5b247f_cjs.createMachineSnapshot = createMachineSnapshot;
2677
+ raiseDa5b247f_cjs.evaluateGuard = evaluateGuard;
2678
+ raiseDa5b247f_cjs.formatInitialTransition = formatInitialTransition;
2679
+ raiseDa5b247f_cjs.formatTransition = formatTransition;
2680
+ raiseDa5b247f_cjs.formatTransitions = formatTransitions;
2681
+ raiseDa5b247f_cjs.getAllOwnEventDescriptors = getAllOwnEventDescriptors;
2682
+ raiseDa5b247f_cjs.getAllStateNodes = getAllStateNodes;
2683
+ raiseDa5b247f_cjs.getCandidates = getCandidates;
2684
+ raiseDa5b247f_cjs.getDelayedTransitions = getDelayedTransitions;
2685
+ raiseDa5b247f_cjs.getInitialStateNodes = getInitialStateNodes;
2686
+ raiseDa5b247f_cjs.getPersistedSnapshot = getPersistedSnapshot;
2687
+ raiseDa5b247f_cjs.getStateNodeByPath = getStateNodeByPath;
2688
+ raiseDa5b247f_cjs.getStateNodes = getStateNodes;
2689
+ raiseDa5b247f_cjs.interpret = interpret;
2690
+ raiseDa5b247f_cjs.isInFinalState = isInFinalState;
2691
+ raiseDa5b247f_cjs.isMachineSnapshot = isMachineSnapshot;
2692
+ raiseDa5b247f_cjs.isStateId = isStateId;
2693
+ raiseDa5b247f_cjs.macrostep = macrostep;
2694
+ raiseDa5b247f_cjs.mapValues = mapValues;
2695
+ raiseDa5b247f_cjs.matchesState = matchesState;
2696
+ raiseDa5b247f_cjs.microstep = microstep;
2697
+ raiseDa5b247f_cjs.not = not;
2698
+ raiseDa5b247f_cjs.or = or;
2699
+ raiseDa5b247f_cjs.pathToStateValue = pathToStateValue;
2700
+ raiseDa5b247f_cjs.raise = raise;
2701
+ raiseDa5b247f_cjs.resolveActionsAndContext = resolveActionsAndContext;
2702
+ raiseDa5b247f_cjs.resolveReferencedActor = resolveReferencedActor;
2703
+ raiseDa5b247f_cjs.resolveStateValue = resolveStateValue;
2704
+ raiseDa5b247f_cjs.spawnChild = spawnChild;
2705
+ raiseDa5b247f_cjs.stateIn = stateIn;
2706
+ raiseDa5b247f_cjs.stop = stop;
2707
+ raiseDa5b247f_cjs.stopChild = stopChild;
2708
+ raiseDa5b247f_cjs.toArray = toArray;
2709
+ raiseDa5b247f_cjs.toObserver = toObserver;
2710
+ raiseDa5b247f_cjs.toStatePath = toStatePath;
2711
+ raiseDa5b247f_cjs.toTransitionConfigArray = toTransitionConfigArray;
2712
+ raiseDa5b247f_cjs.transitionNode = transitionNode;
2713
+ return raiseDa5b247f_cjs;
2714
+ }
2715
+
2716
+ export { requireRaiseDa5b247f_cjs as __require };