xstate 6.0.0-alpha.12 → 6.0.0-alpha.13

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 (33) hide show
  1. package/dist/{StateMachine-8a9e6cb4.development.esm.js → StateMachine-193c2d4d.development.esm.js} +42 -1
  2. package/dist/{StateMachine-7af634f9.cjs.js → StateMachine-1b26c5de.cjs.js} +42 -1
  3. package/dist/{StateMachine-c7e1996c.development.cjs.js → StateMachine-3120a7ff.development.cjs.js} +42 -1
  4. package/dist/{StateMachine-97ef0e5e.esm.js → StateMachine-614c0f36.esm.js} +42 -1
  5. package/dist/declarations/src/StateMachine.d.ts +1 -0
  6. package/dist/declarations/src/fsm.d.ts +74 -0
  7. package/dist/declarations/src/index.d.ts +1 -0
  8. package/dist/declarations/src/setup.d.ts +29 -10
  9. package/dist/declarations/src/types.d.ts +9 -3
  10. package/dist/declarations/src/types.v6.d.ts +5 -5
  11. package/dist/{index-3d018b1e.development.cjs.js → index-08d86676.development.cjs.js} +21 -15
  12. package/dist/{index-698a3320.cjs.js → index-32631949.cjs.js} +21 -15
  13. package/dist/{index-45856a94.esm.js → index-603c1cda.esm.js} +18 -16
  14. package/dist/{index-be3d4c2d.development.esm.js → index-7081e0c9.development.esm.js} +18 -16
  15. package/dist/xstate-actors.cjs.js +1 -1
  16. package/dist/xstate-actors.development.cjs.js +1 -1
  17. package/dist/xstate-actors.development.esm.js +1 -1
  18. package/dist/xstate-actors.esm.js +1 -1
  19. package/dist/xstate-graph.cjs.js +2 -2
  20. package/dist/xstate-graph.development.cjs.js +2 -2
  21. package/dist/xstate-graph.development.esm.js +2 -2
  22. package/dist/xstate-graph.esm.js +2 -2
  23. package/dist/xstate-graph.umd.min.js +1 -1
  24. package/dist/xstate-graph.umd.min.js.map +1 -1
  25. package/dist/xstate.cjs.js +336 -2
  26. package/dist/xstate.cjs.mjs +1 -0
  27. package/dist/xstate.development.cjs.js +336 -2
  28. package/dist/xstate.development.cjs.mjs +1 -0
  29. package/dist/xstate.development.esm.js +339 -6
  30. package/dist/xstate.esm.js +339 -6
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/package.json +1 -1
@@ -1699,24 +1699,25 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
1699
1699
  * transition.
1700
1700
  */
1701
1701
  function getTransitionResult(transition, snapshot, event, actorScope, options) {
1702
+ const transitionArgs = {
1703
+ context: snapshot.context,
1704
+ event,
1705
+ output: getEventOutput(event),
1706
+ value: snapshot.value,
1707
+ children: snapshot.children,
1708
+ system: actorScope.system,
1709
+ parent: actorScope.self._parent,
1710
+ self: actorScope.self,
1711
+ actions: snapshot.machine.implementations.actions,
1712
+ actorSources: snapshot.machine.implementations.actorSources,
1713
+ guards: snapshot.machine.implementations.guards,
1714
+ delays: snapshot.machine.implementations.delays
1715
+ };
1702
1716
  if (transition.to) {
1703
1717
  const actions = [];
1704
1718
  const internalEvents = [];
1705
1719
  const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, false, options?.resolveActions ?? true);
1706
- const res = transition.to({
1707
- context: snapshot.context,
1708
- event,
1709
- output: getEventOutput(event),
1710
- value: snapshot.value,
1711
- children: snapshot.children,
1712
- system: actorScope.system,
1713
- parent: actorScope.self._parent,
1714
- self: actorScope.self,
1715
- actions: snapshot.machine.implementations.actions,
1716
- actorSources: snapshot.machine.implementations.actorSources,
1717
- guards: snapshot.machine.implementations.guards,
1718
- delays: snapshot.machine.implementations.delays
1719
- }, enqueue);
1720
+ const res = transition.to(transitionArgs, enqueue);
1720
1721
  const targets = res?.target ? resolveTarget(transition.source, toArray(res.target)) : undefined;
1721
1722
  // Resolve input for .to transitions
1722
1723
  const resolvedInput = typeof transition.input === 'function' ? transition.input({
@@ -1740,9 +1741,10 @@ function getTransitionResult(transition, snapshot, event, actorScope, options) {
1740
1741
  event,
1741
1742
  output: getEventOutput(event)
1742
1743
  }) : transition.input;
1744
+ const resolvedContext = typeof transition.context === 'function' ? transition.context(transitionArgs) : transition.context;
1743
1745
  return {
1744
1746
  targets: transition.target,
1745
- context: transition.context,
1747
+ context: resolvedContext,
1746
1748
  reenter: transition.reenter,
1747
1749
  actions: undefined,
1748
1750
  internalEvents: undefined,
@@ -4403,7 +4405,10 @@ exports.ProcessingStatus = ProcessingStatus;
4403
4405
  exports.STATE_DELIMITER = STATE_DELIMITER;
4404
4406
  exports.TimeoutError = TimeoutError;
4405
4407
  exports.XSTATE_INIT = XSTATE_INIT;
4408
+ exports.XSTATE_STOP = XSTATE_STOP;
4409
+ exports.builtInActions = builtInActions;
4406
4410
  exports.checkStateIn = checkStateIn;
4411
+ exports.cloneMachineSnapshot = cloneMachineSnapshot;
4407
4412
  exports.createActor = createActor;
4408
4413
  exports.createAsyncLogic = createAsyncLogic;
4409
4414
  exports.createCallbackLogic = createCallbackLogic;
@@ -4417,6 +4422,7 @@ exports.createLogic = createLogic;
4417
4422
  exports.createMachineSnapshot = createMachineSnapshot;
4418
4423
  exports.createObservableLogic = createObservableLogic;
4419
4424
  exports.createSubscriptionLogic = createSubscriptionLogic;
4425
+ exports.createTransitionEnqueue = createTransitionEnqueue;
4420
4426
  exports.evaluateCandidate = evaluateCandidate;
4421
4427
  exports.formatRouteTransitions = formatRouteTransitions;
4422
4428
  exports.formatTransition = formatTransition;
@@ -1697,24 +1697,25 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
1697
1697
  * transition.
1698
1698
  */
1699
1699
  function getTransitionResult(transition, snapshot, event, actorScope, options) {
1700
+ const transitionArgs = {
1701
+ context: snapshot.context,
1702
+ event,
1703
+ output: getEventOutput(event),
1704
+ value: snapshot.value,
1705
+ children: snapshot.children,
1706
+ system: actorScope.system,
1707
+ parent: actorScope.self._parent,
1708
+ self: actorScope.self,
1709
+ actions: snapshot.machine.implementations.actions,
1710
+ actorSources: snapshot.machine.implementations.actorSources,
1711
+ guards: snapshot.machine.implementations.guards,
1712
+ delays: snapshot.machine.implementations.delays
1713
+ };
1700
1714
  if (transition.to) {
1701
1715
  const actions = [];
1702
1716
  const internalEvents = [];
1703
1717
  const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, false, options?.resolveActions ?? true);
1704
- const res = transition.to({
1705
- context: snapshot.context,
1706
- event,
1707
- output: getEventOutput(event),
1708
- value: snapshot.value,
1709
- children: snapshot.children,
1710
- system: actorScope.system,
1711
- parent: actorScope.self._parent,
1712
- self: actorScope.self,
1713
- actions: snapshot.machine.implementations.actions,
1714
- actorSources: snapshot.machine.implementations.actorSources,
1715
- guards: snapshot.machine.implementations.guards,
1716
- delays: snapshot.machine.implementations.delays
1717
- }, enqueue);
1718
+ const res = transition.to(transitionArgs, enqueue);
1718
1719
  const targets = res?.target ? resolveTarget(transition.source, toArray(res.target)) : undefined;
1719
1720
  // Resolve input for .to transitions
1720
1721
  const resolvedInput = typeof transition.input === 'function' ? transition.input({
@@ -1738,9 +1739,10 @@ function getTransitionResult(transition, snapshot, event, actorScope, options) {
1738
1739
  event,
1739
1740
  output: getEventOutput(event)
1740
1741
  }) : transition.input;
1742
+ const resolvedContext = typeof transition.context === 'function' ? transition.context(transitionArgs) : transition.context;
1741
1743
  return {
1742
1744
  targets: transition.target,
1743
- context: transition.context,
1745
+ context: resolvedContext,
1744
1746
  reenter: transition.reenter,
1745
1747
  actions: undefined,
1746
1748
  internalEvents: undefined,
@@ -4394,4 +4396,4 @@ function createEmptyActor() {
4394
4396
  return createActor(emptyLogic);
4395
4397
  }
4396
4398
 
4397
- export { $$ACTOR_TYPE as $, Actor as A, subscriptionLogic as B, resolveReferencedActor as C, mapValues as D, createInvokeId as E, getDelayedTransitions as F, evaluateCandidate as G, formatTransition as H, toTransitionConfigArray as I, createInvokeTimeoutEvent as J, getCandidates as K, formatRouteTransitions as L, resolveStateValue as M, NULL_EVENT as N, getAllStateNodes as O, ProcessingStatus as P, createMachineSnapshot as Q, isInFinalState as R, STATE_DELIMITER as S, TimeoutError as T, transitionNode as U, resolveActionsWithContext as V, toStatePath as W, isStateId as X, getStateNodeByPath as Y, getPersistedSnapshot as Z, XSTATE_INIT as _, macrostep as a, createInitEvent as b, createActor as c, initialMicrostep as d, isMachineSnapshot as e, getStateNodes as f, getProperAncestors as g, getAllOwnEventDescriptors as h, isAtomicStateNode as i, matchesState as j, checkStateIn as k, pathToStateValue as l, matchesEventDescriptor as m, toObserver as n, isBuiltInExecutableAction as o, parseDelayToMilliseconds as p, createEmptyActor as q, createCallbackLogic as r, createObservableLogic as s, toArray as t, createEventObservableLogic as u, createLogic as v, createAsyncLogic as w, createListenerLogic as x, listenerLogic as y, createSubscriptionLogic as z };
4399
+ export { toStatePath as $, Actor as A, createAsyncLogic as B, createListenerLogic as C, listenerLogic as D, createSubscriptionLogic as E, subscriptionLogic as F, resolveReferencedActor as G, mapValues as H, createInvokeId as I, getDelayedTransitions as J, evaluateCandidate as K, formatTransition as L, toTransitionConfigArray as M, NULL_EVENT as N, createInvokeTimeoutEvent as O, ProcessingStatus as P, getCandidates as Q, formatRouteTransitions as R, STATE_DELIMITER as S, TimeoutError as T, resolveStateValue as U, getAllStateNodes as V, createMachineSnapshot as W, XSTATE_INIT as X, isInFinalState as Y, cloneMachineSnapshot as Z, transitionNode as _, XSTATE_STOP as a, isStateId as a0, getStateNodeByPath as a1, getPersistedSnapshot as a2, $$ACTOR_TYPE as a3, builtInActions as b, createTransitionEnqueue as c, createActor as d, macrostep as e, createInitEvent as f, initialMicrostep as g, getProperAncestors as h, isAtomicStateNode as i, isMachineSnapshot as j, getStateNodes as k, getAllOwnEventDescriptors as l, matchesEventDescriptor as m, matchesState as n, checkStateIn as o, parseDelayToMilliseconds as p, pathToStateValue as q, resolveActionsWithContext as r, toObserver as s, toArray as t, isBuiltInExecutableAction as u, createEmptyActor as v, createCallbackLogic as w, createObservableLogic as x, createEventObservableLogic as y, createLogic as z };
@@ -1708,24 +1708,25 @@ function microstep(transitions, currentSnapshot, actorScope, event, isInitial, i
1708
1708
  * transition.
1709
1709
  */
1710
1710
  function getTransitionResult(transition, snapshot, event, actorScope, options) {
1711
+ const transitionArgs = {
1712
+ context: snapshot.context,
1713
+ event,
1714
+ output: getEventOutput(event),
1715
+ value: snapshot.value,
1716
+ children: snapshot.children,
1717
+ system: actorScope.system,
1718
+ parent: actorScope.self._parent,
1719
+ self: actorScope.self,
1720
+ actions: snapshot.machine.implementations.actions,
1721
+ actorSources: snapshot.machine.implementations.actorSources,
1722
+ guards: snapshot.machine.implementations.guards,
1723
+ delays: snapshot.machine.implementations.delays
1724
+ };
1711
1725
  if (transition.to) {
1712
1726
  const actions = [];
1713
1727
  const internalEvents = [];
1714
1728
  const enqueue = createTransitionEnqueue(actorScope, actions, internalEvents, false, options?.resolveActions ?? true);
1715
- const res = transition.to({
1716
- context: snapshot.context,
1717
- event,
1718
- output: getEventOutput(event),
1719
- value: snapshot.value,
1720
- children: snapshot.children,
1721
- system: actorScope.system,
1722
- parent: actorScope.self._parent,
1723
- self: actorScope.self,
1724
- actions: snapshot.machine.implementations.actions,
1725
- actorSources: snapshot.machine.implementations.actorSources,
1726
- guards: snapshot.machine.implementations.guards,
1727
- delays: snapshot.machine.implementations.delays
1728
- }, enqueue);
1729
+ const res = transition.to(transitionArgs, enqueue);
1729
1730
  const targets = res?.target ? resolveTarget(transition.source, toArray(res.target)) : undefined;
1730
1731
  // Resolve input for .to transitions
1731
1732
  const resolvedInput = typeof transition.input === 'function' ? transition.input({
@@ -1749,9 +1750,10 @@ function getTransitionResult(transition, snapshot, event, actorScope, options) {
1749
1750
  event,
1750
1751
  output: getEventOutput(event)
1751
1752
  }) : transition.input;
1753
+ const resolvedContext = typeof transition.context === 'function' ? transition.context(transitionArgs) : transition.context;
1752
1754
  return {
1753
1755
  targets: transition.target,
1754
- context: transition.context,
1756
+ context: resolvedContext,
1755
1757
  reenter: transition.reenter,
1756
1758
  actions: undefined,
1757
1759
  internalEvents: undefined,
@@ -4433,4 +4435,4 @@ function createEmptyActor() {
4433
4435
  return createActor(emptyLogic);
4434
4436
  }
4435
4437
 
4436
- export { $$ACTOR_TYPE as $, Actor as A, subscriptionLogic as B, resolveReferencedActor as C, mapValues as D, createInvokeId as E, getDelayedTransitions as F, evaluateCandidate as G, formatTransition as H, toTransitionConfigArray as I, createInvokeTimeoutEvent as J, getCandidates as K, formatRouteTransitions as L, resolveStateValue as M, NULL_EVENT as N, getAllStateNodes as O, ProcessingStatus as P, createMachineSnapshot as Q, isInFinalState as R, STATE_DELIMITER as S, TimeoutError as T, transitionNode as U, resolveActionsWithContext as V, toStatePath as W, isStateId as X, getStateNodeByPath as Y, getPersistedSnapshot as Z, XSTATE_INIT as _, macrostep as a, createInitEvent as b, createActor as c, initialMicrostep as d, isMachineSnapshot as e, getStateNodes as f, getProperAncestors as g, getAllOwnEventDescriptors as h, isAtomicStateNode as i, matchesState as j, checkStateIn as k, pathToStateValue as l, matchesEventDescriptor as m, toObserver as n, isBuiltInExecutableAction as o, parseDelayToMilliseconds as p, createEmptyActor as q, createCallbackLogic as r, createObservableLogic as s, toArray as t, createEventObservableLogic as u, createLogic as v, createAsyncLogic as w, createListenerLogic as x, listenerLogic as y, createSubscriptionLogic as z };
4438
+ export { toStatePath as $, Actor as A, createAsyncLogic as B, createListenerLogic as C, listenerLogic as D, createSubscriptionLogic as E, subscriptionLogic as F, resolveReferencedActor as G, mapValues as H, createInvokeId as I, getDelayedTransitions as J, evaluateCandidate as K, formatTransition as L, toTransitionConfigArray as M, NULL_EVENT as N, createInvokeTimeoutEvent as O, ProcessingStatus as P, getCandidates as Q, formatRouteTransitions as R, STATE_DELIMITER as S, TimeoutError as T, resolveStateValue as U, getAllStateNodes as V, createMachineSnapshot as W, XSTATE_INIT as X, isInFinalState as Y, cloneMachineSnapshot as Z, transitionNode as _, XSTATE_STOP as a, isStateId as a0, getStateNodeByPath as a1, getPersistedSnapshot as a2, $$ACTOR_TYPE as a3, builtInActions as b, createTransitionEnqueue as c, createActor as d, macrostep as e, createInitEvent as f, initialMicrostep as g, getProperAncestors as h, isAtomicStateNode as i, isMachineSnapshot as j, getStateNodes as k, getAllOwnEventDescriptors as l, matchesEventDescriptor as m, matchesState as n, checkStateIn as o, parseDelayToMilliseconds as p, pathToStateValue as q, resolveActionsWithContext as r, toObserver as s, toArray as t, isBuiltInExecutableAction as u, createEmptyActor as v, createCallbackLogic as w, createObservableLogic as x, createEventObservableLogic as y, createLogic as z };
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-698a3320.cjs.js');
5
+ var dist_xstateActors = require('./index-32631949.cjs.js');
6
6
 
7
7
 
8
8
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-3d018b1e.development.cjs.js');
5
+ var dist_xstateActors = require('./index-08d86676.development.cjs.js');
6
6
 
7
7
 
8
8
 
@@ -1 +1 @@
1
- export { T as TimeoutError, w as createAsyncLogic, r as createCallbackLogic, q as createEmptyActor, u as createEventObservableLogic, x as createListenerLogic, v as createLogic, s as createObservableLogic, z as createSubscriptionLogic, y as listenerLogic, B as subscriptionLogic } from './index-be3d4c2d.development.esm.js';
1
+ export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-7081e0c9.development.esm.js';
@@ -1 +1 @@
1
- export { T as TimeoutError, w as createAsyncLogic, r as createCallbackLogic, q as createEmptyActor, u as createEventObservableLogic, x as createListenerLogic, v as createLogic, s as createObservableLogic, z as createSubscriptionLogic, y as listenerLogic, B as subscriptionLogic } from './index-45856a94.esm.js';
1
+ export { T as TimeoutError, B as createAsyncLogic, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, E as createSubscriptionLogic, D as listenerLogic, F as subscriptionLogic } from './index-603c1cda.esm.js';
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-698a3320.cjs.js');
6
- var StateMachine = require('./StateMachine-7af634f9.cjs.js');
5
+ var dist_xstateActors = require('./index-32631949.cjs.js');
6
+ var StateMachine = require('./StateMachine-1b26c5de.cjs.js');
7
7
 
8
8
  function simpleStringify(value) {
9
9
  return JSON.stringify(value);
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-3d018b1e.development.cjs.js');
6
- var StateMachine = require('./StateMachine-c7e1996c.development.cjs.js');
5
+ var dist_xstateActors = require('./index-08d86676.development.cjs.js');
6
+ var StateMachine = require('./StateMachine-3120a7ff.development.cjs.js');
7
7
 
8
8
  function simpleStringify(value) {
9
9
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { e as isMachineSnapshot, h as getAllOwnEventDescriptors, q as createEmptyActor, _ as XSTATE_INIT } from './index-be3d4c2d.development.esm.js';
2
- import { S as StateMachine } from './StateMachine-8a9e6cb4.development.esm.js';
1
+ import { j as isMachineSnapshot, l as getAllOwnEventDescriptors, v as createEmptyActor, X as XSTATE_INIT } from './index-7081e0c9.development.esm.js';
2
+ import { S as StateMachine } from './StateMachine-193c2d4d.development.esm.js';
3
3
 
4
4
  function simpleStringify(value) {
5
5
  return JSON.stringify(value);
@@ -1,5 +1,5 @@
1
- import { e as isMachineSnapshot, h as getAllOwnEventDescriptors, q as createEmptyActor, _ as XSTATE_INIT } from './index-45856a94.esm.js';
2
- import { S as StateMachine } from './StateMachine-97ef0e5e.esm.js';
1
+ import { j as isMachineSnapshot, l as getAllOwnEventDescriptors, v as createEmptyActor, X as XSTATE_INIT } from './index-603c1cda.esm.js';
2
+ import { S as StateMachine } from './StateMachine-614c0f36.esm.js';
3
3
 
4
4
  function simpleStringify(value) {
5
5
  return JSON.stringify(value);
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.stop";function o(t,e){return{type:`xstate.after.${t}.${e}`}}function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t){return{type:s,input:t}}function a(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable",u={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stop":(t,e)=>{t.stopChild(e)}},f=new WeakMap;function p(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),f.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(f.get(s)?.unsubscribe(),f.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return p(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!zt(t.type,e)||l(n,o,()=>s(t))})})}const y=d();function g(){return p(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;return t.subscribe({next:t=>{"done"===t.status&&o?l(s,n,()=>o(t.output)):"error"===t.status&&i?l(s,n,()=>i(t.error)):"active"===t.status&&r&&l(s,n,()=>r(t))},error:t=>{i&&l(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e){return{...t,...e}}function _(t,e,...s){t.push({action:e,args:s})}function S(t,e,s){_(t,u["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function x(t,e,s,n=!1,o=!0){const i={cancel:s=>{_(e,u["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{_(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?_(e,u["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const i=Ht(s,{...n,parent:t.self});return S(e,i,n?.id),i},sendTo:(s,n,o)=>{s&&_(e,u["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(_(e,u["@xstate.stop"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(i,{listen:(s,n,o)=>{const i=Ht(y,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return _(e,u["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Ht(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return _(e,u["@xstate.start"],o),o}}),E(i,(t,...s)=>{_(e,t,...s)})}function b(t,e){switch(t){case u["@xstate.start"]:{const[t]=e;return{actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case u["@xstate.raise"]:{const[,t,s]=e;return{event:t,id:s?.id,delay:s?.delay}}case u["@xstate.sendTo"]:{const[,t,s,n]=e;return{target:t,event:s,id:n?.id,delay:n?.delay}}case u["@xstate.cancel"]:{const[,t]=e;return{id:t}}case u["@xstate.stop"]:{const[,t]=e;return{actor:t}}default:return}}function w(t,e,s,n){let o=t;const i=[];for(const r of n){const n="function"==typeof r?r:"object"==typeof r&&"action"in r&&"function"==typeof r.action&&r.action.bind(null,...r.args),c={context:o.context,event:e,output:It(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actorSources:t.machine.implementations.actorSources};let a;if("object"==typeof r&&null!==r){const{type:t,...e}=r;a=e}if(n&&"_special"in n){i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type??"(anonymous)":r.name||"(anonymous)",params:a,args:[],exec:void 0});const t=n(c,k);t&&("context"in t||"children"in t)&&(o=_t(o,{...void 0!==t.context?{context:m(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}}));continue}if(!n||!("resolve"in n)){const t="object"==typeof r&&null!==r&&"action"in r&&"function"==typeof r.action?b(r.action,r.args):void 0;i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type:r.name||"(anonymous)",params:a,args:"object"==typeof r&&"action"in r?r.args:[],exec:n||("object"==typeof r&&null!==r?()=>s.defer(()=>s.emit(r)):void 0),...t});continue}}return[o,i]}function E(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const k=E({},()=>{});function $(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function j(t,e,s){if("function"==typeof t)return t(s);const n=$(t,e);return"function"==typeof n?n(s):n}function I(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function O(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function T(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function M(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of O(t))if(!e.has(s)){const t=C(s);for(const s of t)e.add(s)}}else for(const s of C(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function A(t,e){const s=M(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(I(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function P(t,e){return"compound"===e.type?O(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?O(e).every(e=>P(t,e)):"final"===e.type}const N=t=>"#"===t[0];function z(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function D(t,e,s){const n=Mt(s.target),o=s.reenter??!1,i=R(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function R(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(N(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return V(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return V(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function J(t){const e=Mt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?V(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function K(t){return"history"===t.type}function C(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of O(s))t(e)}(t);for(const s of e)for(const n of T(s,t))e.add(n);return e}function B(t,e){if(N(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function V(t,e){if("string"==typeof e&&N(e))try{return t.machine.getStateNodeById(e)}catch{}const s=wt(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=B(n,t)}return n}function W(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=B(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...W(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=B(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(B(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(B(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function q(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function F(t,e){for(const s of t)if(q(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function U(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=Q([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!q(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function H(t,e,s,n){const o=e.historyValue,{targets:i}=tt(t,e,s,n,{resolveActions:!1});if(!i)return[];const r=new Set;for(const t of i)if(K(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of H(J(t),e,s,n))r.add(o);else r.add(t);return[...r]}function X(t,e,s,n){const o=H(t,e,s,n),{reenter:i}=tt(t,e,s,n,{resolveActions:!1});if(!i&&o.every(e=>e===t.source||q(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of T(r,void 0))if(c.every(e=>q(e,t)))return t;return i?void 0:t.source.machine.root}function Q(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=tt(r,s,n,o,{resolveActions:!1});if(t?.length){const t=X(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)q(s,t)&&i.add(s)}}return[...i]}function Y(t,e){return{...t,...e}}function Z(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e._nodes);let h=e.historyValue;const f=e.context,p=U(t,a,e,n,s),l=t=>tt(t,e,n,s),d=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=x(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return void 0!==f?.context&&(h=Y(o,f.context)),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=Q(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>I(t)&&q(t,e):t=>t.parent===e;o??={...h},o[t.id]=r.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[r,h,u]=o.exit?d(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),h&&(y=_t(y,{context:h}));const[f,p]=w(y,n,s,r);y=f,c.push(...p);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}h=o||h};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...$t(t.actions));const e=l(t);void 0!==e.context&&(v=Y(v,e.context)),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const S=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=jt(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=i.find(t=>t.type===e);o=s?.output}return jt(e.output,y.context,r(t.id,o),s.self)},f=new Set,g=new Set,v=(t,e)=>{for(const s of t)if(e&&!q(s,e)||f.add(s),"parallel"===s.type)for(const t of O(s))F(f,t)||(f.add(t),m(t))},m=t=>{if(K(t))if(h[t.id]){const e=h[t.id];for(const t of e)f.add(t),m(t);for(const s of e)v(T(s,t.parent),void 0)}else{const e=J(t),{targets:s}=l(e);for(const n of s??[])f.add(n),e===t.parent?.initial&&g.add(t.parent),m(n);for(const e of s??[])v(T(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return K(e)||(f.add(e),g.add(e)),m(e),void v(T(e,t),void 0)}if("parallel"===t.type)for(const e of O(t))F(f,e)||(f.add(e),g.add(e),m(e))}};for(const t of p){const o=X(t,e,n,s),{targets:i,reenter:r}=tt(t,e,n,s,{resolveActions:!1});for(const e of i??[])K(e)||t.source===e&&t.source===o&&!r||(f.add(e),g.add(e)),m(e);const c=H(t,e,n,s);for(const e of c){const s=T(e,o);"parallel"===o?.type&&s.push(o),v(s,!t.source.parent&&r?void 0:o)}}o&&g.add(e.machine.root);const _={...e._stateInputs};for(const t of p){const{targets:o,input:i}=tt(t,e,n,s,{resolveActions:!1});if(i&&o)for(const t of o)_[t.id]=i}const S=new Set,x={...e.children};for(const o of[...f].sort((t,e)=>t.order-e.order)){a.add(o);const h=[];let f=!1;for(const t of o.invoke){f=!0;let o=t.logic;"function"==typeof o&&(o=o({actorSources:e.machine.implementations.actorSources,context:y.context,event:n,self:s.self}));const i="string"==typeof o?Pt(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:y.context,event:n,output:It(n)}):t.input,c=Ht(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});h.push({action:u["@xstate.start"],args:[c]}),t.id&&(x[t.id]=c)}f&&(y=_t(y,{children:x}));let p=y.context,l=!1;const v=_[o.id];if(o.entry){const[t,e,s]=d(o.entry,p,x,v);h.push(...t),s?.length&&i.push(...s),e&&(p=e,l=!0)}if(l&&(y.context=p),g.has(o)){const{actions:t,input:e}=tt(o.initial,y,n,s);if(t&&h.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e}const[m,b]=w(y,n,s,h);if(y=m,h.length=0,c.push(...b),"final"!==o.type)continue;const E=o.parent;let k="parallel"===E?.type?E:E?.parent,$=k||o;for("compound"===E?.type&&i.push(r(E.id,void 0!==o.output?jt(o.output,y.context,n,s.self):void 0));"parallel"===k?.type&&!S.has(k)&&P(a,k);){S.add(k);const t={};for(const e of O(k)){if("final"===e.type){t[e.key]=void 0!==e.output?jt(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=i.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=O(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?jt(o.output,y.context,n,s.self):void 0}i.push(r(k.id,t)),$=k,k=k.parent}k||(y=_t(y,{status:"done",output:t($)}))}JSON.stringify(_)!==JSON.stringify(e._stateInputs||{})&&(y=_t(y,{_stateInputs:_}))},[b,E]=w(y,n,s,m);y=b,c.push(...E),v&&v!==e.context&&(y=_t(y,{context:v})),S();const k=[...a];if("done"===y.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=d(e.exit,y.context,y.children,s);t.push(...n),o?.length&&i.push(...o)}});const[e,o]=w(y,n,s,t);y=e,c.push(...o)}return h===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[_t(y),c]:[y,c]:[_t(y,{_nodes:k,historyValue:h}),c]}}function tt(t,e,s,n,o){if(t.to){const i=[],r=[],c=x(n,i,r,!1,o?.resolveActions??!0),a=t.to({context:e.context,event:s,output:It(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},c),h=a?.target?R(t.source,$t(a.target)):void 0,u="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input;return{targets:h,context:a?.context,reenter:a?.reenter,actions:i,internalEvents:r,input:u}}const i="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input;return{targets:t.target,context:t.context,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:i}}function et(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=_t(ot(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=_t(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=Z(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?it(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=Z(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&ot(r,o),{snapshot:r,microsteps:c}}function st(t,e,s,n,o){return!!t.to&&nt(t.to,e,s,n,o,n.machine.implementations)}function nt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,output:It(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actorSources:i.actorSources,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function ot(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return _t(t,{children:{}})}function it(t,e,s){const n=new Set,o=t._nodes.filter(I);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(rt(i,e,t,o,s.self)){n.add(i);break t}return U(Array.from(n),new Set(t._nodes),t,e,s)}function rt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,output:It(e),self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actorSources:n.machine.implementations.actorSources,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s};if(!t.guard(i))return!1}return!t.to||nt(t.to,s.context,e,s,o,n.machine.implementations)}function ct(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let at,ht;function ut(){return at??=Qt()}const ft=function(t){return bt(t,this.value)},pt=function(t){return this.tags.has(t)},lt=function(t){const e=ut(),s=function(){if(ht)return ht;const t=ut();return ht={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},ht}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=tt(o,this,t,s,{resolveActions:!1});if(n.targets?.length||n.context||st(o,this.context,t,this,e))return!0}return!1},dt=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},yt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},gt=function(){return this._stateInputs};function vt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function mt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??A(e.root,t._nodes),tags:vt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}}function _t(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}:mt({...s,value:void 0},t.machine)}function St(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function xt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Vt,id:n.id};else{const o=xt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function bt(t,e){const s=Et(t),n=Et(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&bt(s[t],n[t]))}function wt(t){if(Ot(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Et(t){if(ct(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(wt(t))}function kt(t){return Ot(t)?t:[t]}function $t(t){return void 0===t?[]:kt(t)}function jt(t,e,s,n){if("function"==typeof t){return t({context:e,event:s,output:It(s),self:n})}return t}function It(t){if(function(t){return t.type.startsWith("xstate.done.actor.")||t.type.startsWith("xstate.done.state.")}(t)){return t.output}}function Ot(t){return Array.isArray(t)}function Tt(t){return kt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function Mt(t){if(void 0!==t&&""!==t)return $t(t)}function At(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Pt(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actorSources[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actorSources[r]:r}function Nt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function zt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function Dt(t,e){return`${t.sessionId}.${e}`}const Rt=new WeakMap;function Jt(t){let e=Rt.get(t);return e||(e=new Map,Rt.set(t,e)),e}function Kt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Jt(e.self).set(Symbol(),{cleanup:t});break}const t=Jt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Rt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Rt.delete(e.self);break}}}function Ct(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]},s={id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,c(t.input),s);Object.assign(t,n),Kt(o,s)},initialTransition:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==n&&(o.context=n),[{...o},[]]},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}let Bt=!1;const Vt=1;let Wt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Lt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function qt(t){return"object"==typeof t&&null!==t&&"args"in t&&"exec"in t}function Ft(t,e){if(!t?.length)return[];const s=[];for(const n of t)qt(n)?e.actionExecutor(n):s.push(n);return s}class Gt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Wt.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Lt,...s},{clock:o,logger:i,parent:r,syncSnapshot:c,id:h,registryKey:u,inspect:f}=n;this.system=r?r.system:n._systemRef?.current??function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=Dt(t,o);l._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=Dt(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const s=l._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=At(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:n.timers}),r||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!r&&this.system.inspect(At(f)),this.sessionId=this.system._bookId(),this.id=h??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(e||s){if(e)for(const s of e)try{s(t)}catch(t){a(t)}if(s)for(const e of s)try{e(t)}catch(t){a(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Bt;try{Bt=!0,t.exec()}finally{Bt=e}};this._processingStatus!==Wt.Running||this._forceDeferredActions?this._deferred.push(e):e()}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}});const p=u;p&&(this.registryKey=p,this.system._set(p,this)),this._collectedMicrosteps=[];let l=s?.snapshot??s?.state;if(l&&"object"==typeof l&&"_pendingEffects"in l){const{_pendingEffects:t,...e}=l;this._pendingEffects=t,l=e}try{if(l)this._snapshot=this.logic.restoreSnapshot?this.logic.restoreSnapshot(l,this._actorScope):l;else{const[t,e]=this.logic.initialTransition(this.options?.input,this._actorScope);this._snapshot=t,this._initialEffects=e}}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}p&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){a(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{return Kt(Ft(this._initialEffects,this._actorScope),this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred.length=0,this._setErrorSnapshot(t),this._error(t),!1}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=At(t,e,s);if(this._processingStatus!==Wt.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){a(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){a(t)}else a(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=At(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Wt.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Wt.Running;const t=c(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._flushInitialEffects()?(this.update(this._snapshot,t),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(!this._flushInitialEffects())return this;if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Ut(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._setErrorSnapshot(t),void this._error(t)}try{const[s,n]=e,o=Ft(n,this._actorScope);this.update(s,t),Kt(o,this._actorScope)}catch(t){return this._setErrorSnapshot(t),void this._error(t)}t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Wt.Stopped?this:(this.mailbox.clear(),this._processingStatus===Wt.NotStarted?(this._processingStatus=Wt.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){a(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){a(t)}}this.observers.clear(),this.eventListeners.clear(),e&&a(t)}else this._parent||a(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Wt.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Wt.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Wt.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Vt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[h](){return this}getSnapshot(){return this._snapshot}}function Ut(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Ht(t,e){return new Gt(t,e)}const Xt=Ct({context:void 0,run:()=>{}});function Qt(){return Ht(Xt)}function Yt(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Pt(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Ht(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,registryKey:r?.registryKey});return o[a.id]=a,a}return Ht(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,registryKey:r?.registryKey})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Wt.Stopped&&c.start()}),c}}const Zt=new WeakMap;function te(t,e,s){let n=Zt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Zt.set(t,n)),n[e]}const ee={},se=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class ne{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of se)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new ne(t,{_parent:this,_key:e,_machine:this.machine})):ee,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=$t(t.tags).slice(),this.invoke=$t(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const c=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;c.push({event:o(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var a;void 0!==s&&n&&c.push({event:(a=t.id,{type:`xstate.timeout.${a}`}),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)c.push({event:i(t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const h=[];for(const{event:e,delay:s,transitions:n,fromDelaysMap:o}of c){const i=z(t,e,e=>j(s,o?e.delays:{},{context:e.context,event:e.event,stateNode:t}));for(const t of Tt(n))h.push({...t,event:i,delay:s})}return h.map(e=>({...D(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,oe(n,e=>D(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,oe(t.config.onDone,e=>D(t,s,e)))}const s=(e,s)=>D(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return D(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=oe(o.onDone,e=>r?n(i,e,r):D(t,i,e));r&&c.push(s(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[s(t,r)])}if(o.onError){const s=`xstate.error.actor.${o.id}`;e.set(s,oe(o.onError,e=>r?n(s,e,r):D(t,s,e)))}if(o.onSnapshot){const s=`xstate.snapshot.${o.id}`;e.set(s,oe(o.onSnapshot,e=>D(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[D(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=oe(this.config.always,t=>D(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return te(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=te(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e),n=[...t.transitions.keys()].filter(t=>t!==e&&zt(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s?[...s,...n]:n}(this,n));for(const n of o){if(rt(n,e,t,this,s))return[n]}}}function oe(t,e){const s=Tt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class ie{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actorSources:t.actorSources??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ne(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(D(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=i,h={...a,guard:r,target:`#${o}`};e.push(D(t,"xstate.route",h))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actorSources:n,delays:o}=this.implementations,i=new ie(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actorSources:{...n,...t.actorSources},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,A(s,M(W(s,n))));var s,n;const o=M(W(this.root,e));return mt({_nodes:[...o],value:e,context:t.context||{},children:{},status:P(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const{snapshot:n,microsteps:o}=et(t,e,s,[]);return[n,o.flatMap(([,t])=>t)]}microstep(t,e,s){const{microsteps:n}=et(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(zt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=mt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Yt(t,n,e,o),input:e.input,self:t.self,actorSources:this.implementations.actorSources}),[r]=w(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=c(t),n=[],o=this._getPreInitialState(e,s),[i,r]=function(t,e,s,n,o){return Z([{target:[...C(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,e,s,n),{snapshot:a,microsteps:h}=et(i,s,e,n);return[a,[...r,...h.flatMap(([,t])=>t)]]}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=wt(t),s=e.slice(1),n=N(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return V(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:l,...d}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const g={...d,context:xt(c),children:y,historyValue:St(d.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Pt(this,r):r;if(!c)continue;const a=Ht(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,registryKey:s.registryKey});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof ne)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(M(W(this.root,n.value))),{version:a,...h}=t,u=mt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Vt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function re(t){return JSON.stringify(t)}function ce(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const ae=()=>(t,e)=>ke(t,e),he=()=>(t,e)=>$e(t,e);class ue{getDefaultOptions(){return{serializeState:t=>re(t),serializeEvent:t=>re(t),serializeTransition:(t,e)=>`${re(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ct(t.state)?`Reaches ${ce(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=re)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(ae(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getSimplePaths(t){return this.getPaths(he(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getPathsFromEvents(t,e){return Ee(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return be(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:re,serializeEvent:re,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function fe(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>fe(t[s],e[s]))}function pe(t,e,s,{serializeEvent:n}){if(!e||s&&fe(s.value,t.value))return"";const o=s?` from ${re(s.value)}`:"";return` via ${n(e)}${o}`}function le(){const t=Qt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function de(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ye(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ge(t){return JSON.stringify(t)}function ve(t,e){const{events:s,...n}=e??{};return{serializeState:ye,serializeEvent:ge,events:t=>{const e="function"==typeof s?s(t):s??[];return Nt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(le(),e?.input),...n}}function me(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ge}}function _e(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?ve(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ge,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function Se(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function xe(t){return Array.isArray(t)?t[0]:t}function be(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=_e(t,e),u=le(),f={};let p=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],d=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(d.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=xe(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function we(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function Ee(t,e,s){const n=_e(t,{events:e,...s},(o=t)&&o instanceof ie?ve(t):me());var o;const i=le(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=be(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let l=p,d=r;for(const t of e){f.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,d=s}return n.toState&&!n.toState(d)?[]:[we({state:d,steps:f,weight:f.length})]}function ke(t,e){const s=_e(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(le(),e?.input),i=be(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(we):p.map(we)}function $e(t,e){const s=_e(t,e),n=le(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=be(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(we):l.map(we)}t.TestModel=ue,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=ae,t.createSimplePathsGen=he,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??re,n=e?.serializeTransition??pe,{events:o,...i}=e??{};return new ue(t,{serializeState:(t,e,o)=>`${ye(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Nt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=be,t.getPathsFromEvents=Ee,t.getShortestPaths=ke,t.getSimplePaths=$e,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=Se,t.serializeSnapshot=ye,t.toDirectedGraph=function t(e){const s=e instanceof ie?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:de(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.stop";function o(t,e){return{type:`xstate.after.${t}.${e}`}}function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t){return{type:s,input:t}}function a(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable",u={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stop":(t,e)=>{t.stopChild(e)}},f=new WeakMap;function p(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),f.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(f.get(s)?.unsubscribe(),f.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return p(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!zt(t.type,e)||l(n,o,()=>s(t))})})}const y=d();function g(){return p(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;return t.subscribe({next:t=>{"done"===t.status&&o?l(s,n,()=>o(t.output)):"error"===t.status&&i?l(s,n,()=>i(t.error)):"active"===t.status&&r&&l(s,n,()=>r(t))},error:t=>{i&&l(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e){return{...t,...e}}function _(t,e,...s){t.push({action:e,args:s})}function S(t,e,s){_(t,u["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function x(t,e,s,n=!1,o=!0){const i={cancel:s=>{_(e,u["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{_(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?_(e,u["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const i=Ht(s,{...n,parent:t.self});return S(e,i,n?.id),i},sendTo:(s,n,o)=>{s&&_(e,u["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(_(e,u["@xstate.stop"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(i,{listen:(s,n,o)=>{const i=Ht(y,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return _(e,u["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Ht(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return _(e,u["@xstate.start"],o),o}}),E(i,(t,...s)=>{_(e,t,...s)})}function b(t,e){switch(t){case u["@xstate.start"]:{const[t]=e;return{actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case u["@xstate.raise"]:{const[,t,s]=e;return{event:t,id:s?.id,delay:s?.delay}}case u["@xstate.sendTo"]:{const[,t,s,n]=e;return{target:t,event:s,id:n?.id,delay:n?.delay}}case u["@xstate.cancel"]:{const[,t]=e;return{id:t}}case u["@xstate.stop"]:{const[,t]=e;return{actor:t}}default:return}}function w(t,e,s,n){let o=t;const i=[];for(const r of n){const n="function"==typeof r?r:"object"==typeof r&&"action"in r&&"function"==typeof r.action&&r.action.bind(null,...r.args),c={context:o.context,event:e,output:It(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actorSources:t.machine.implementations.actorSources};let a;if("object"==typeof r&&null!==r){const{type:t,...e}=r;a=e}if(n&&"_special"in n){i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type??"(anonymous)":r.name||"(anonymous)",params:a,args:[],exec:void 0});const t=n(c,k);t&&("context"in t||"children"in t)&&(o=_t(o,{...void 0!==t.context?{context:m(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}}));continue}if(!n||!("resolve"in n)){const t="object"==typeof r&&null!==r&&"action"in r&&"function"==typeof r.action?b(r.action,r.args):void 0;i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type:r.name||"(anonymous)",params:a,args:"object"==typeof r&&"action"in r?r.args:[],exec:n||("object"==typeof r&&null!==r?()=>s.defer(()=>s.emit(r)):void 0),...t});continue}}return[o,i]}function E(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const k=E({},()=>{});function $(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function j(t,e,s){if("function"==typeof t)return t(s);const n=$(t,e);return"function"==typeof n?n(s):n}function I(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function O(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function T(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function M(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of O(t))if(!e.has(s)){const t=C(s);for(const s of t)e.add(s)}}else for(const s of C(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function A(t,e){const s=M(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(I(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function P(t,e){return"compound"===e.type?O(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?O(e).every(e=>P(t,e)):"final"===e.type}const N=t=>"#"===t[0];function z(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function D(t,e,s){const n=Mt(s.target),o=s.reenter??!1,i=R(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function R(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(N(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return V(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return V(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function J(t){const e=Mt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?V(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function K(t){return"history"===t.type}function C(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of O(s))t(e)}(t);for(const s of e)for(const n of T(s,t))e.add(n);return e}function B(t,e){if(N(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function V(t,e){if("string"==typeof e&&N(e))try{return t.machine.getStateNodeById(e)}catch{}const s=wt(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=B(n,t)}return n}function W(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=B(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...W(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=B(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(B(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(B(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function q(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function F(t,e){for(const s of t)if(q(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function U(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=Q([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!q(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function H(t,e,s,n){const o=e.historyValue,{targets:i}=tt(t,e,s,n,{resolveActions:!1});if(!i)return[];const r=new Set;for(const t of i)if(K(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of H(J(t),e,s,n))r.add(o);else r.add(t);return[...r]}function X(t,e,s,n){const o=H(t,e,s,n),{reenter:i}=tt(t,e,s,n,{resolveActions:!1});if(!i&&o.every(e=>e===t.source||q(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of T(r,void 0))if(c.every(e=>q(e,t)))return t;return i?void 0:t.source.machine.root}function Q(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=tt(r,s,n,o,{resolveActions:!1});if(t?.length){const t=X(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)q(s,t)&&i.add(s)}}return[...i]}function Y(t,e){return{...t,...e}}function Z(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e._nodes);let h=e.historyValue;const f=e.context,p=U(t,a,e,n,s),l=t=>tt(t,e,n,s),d=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=x(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return void 0!==f?.context&&(h=Y(o,f.context)),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=Q(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>I(t)&&q(t,e):t=>t.parent===e;o??={...h},o[t.id]=r.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[r,h,u]=o.exit?d(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),h&&(y=_t(y,{context:h}));const[f,p]=w(y,n,s,r);y=f,c.push(...p);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}h=o||h};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...$t(t.actions));const e=l(t);void 0!==e.context&&(v=Y(v,e.context)),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const S=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=jt(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=i.find(t=>t.type===e);o=s?.output}return jt(e.output,y.context,r(t.id,o),s.self)},f=new Set,g=new Set,v=(t,e)=>{for(const s of t)if(e&&!q(s,e)||f.add(s),"parallel"===s.type)for(const t of O(s))F(f,t)||(f.add(t),m(t))},m=t=>{if(K(t))if(h[t.id]){const e=h[t.id];for(const t of e)f.add(t),m(t);for(const s of e)v(T(s,t.parent),void 0)}else{const e=J(t),{targets:s}=l(e);for(const n of s??[])f.add(n),e===t.parent?.initial&&g.add(t.parent),m(n);for(const e of s??[])v(T(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return K(e)||(f.add(e),g.add(e)),m(e),void v(T(e,t),void 0)}if("parallel"===t.type)for(const e of O(t))F(f,e)||(f.add(e),g.add(e),m(e))}};for(const t of p){const o=X(t,e,n,s),{targets:i,reenter:r}=tt(t,e,n,s,{resolveActions:!1});for(const e of i??[])K(e)||t.source===e&&t.source===o&&!r||(f.add(e),g.add(e)),m(e);const c=H(t,e,n,s);for(const e of c){const s=T(e,o);"parallel"===o?.type&&s.push(o),v(s,!t.source.parent&&r?void 0:o)}}o&&g.add(e.machine.root);const _={...e._stateInputs};for(const t of p){const{targets:o,input:i}=tt(t,e,n,s,{resolveActions:!1});if(i&&o)for(const t of o)_[t.id]=i}const S=new Set,x={...e.children};for(const o of[...f].sort((t,e)=>t.order-e.order)){a.add(o);const h=[];let f=!1;for(const t of o.invoke){f=!0;let o=t.logic;"function"==typeof o&&(o=o({actorSources:e.machine.implementations.actorSources,context:y.context,event:n,self:s.self}));const i="string"==typeof o?Pt(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:y.context,event:n,output:It(n)}):t.input,c=Ht(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});h.push({action:u["@xstate.start"],args:[c]}),t.id&&(x[t.id]=c)}f&&(y=_t(y,{children:x}));let p=y.context,l=!1;const v=_[o.id];if(o.entry){const[t,e,s]=d(o.entry,p,x,v);h.push(...t),s?.length&&i.push(...s),e&&(p=e,l=!0)}if(l&&(y.context=p),g.has(o)){const{actions:t,input:e}=tt(o.initial,y,n,s);if(t&&h.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e}const[m,b]=w(y,n,s,h);if(y=m,h.length=0,c.push(...b),"final"!==o.type)continue;const E=o.parent;let k="parallel"===E?.type?E:E?.parent,$=k||o;for("compound"===E?.type&&i.push(r(E.id,void 0!==o.output?jt(o.output,y.context,n,s.self):void 0));"parallel"===k?.type&&!S.has(k)&&P(a,k);){S.add(k);const t={};for(const e of O(k)){if("final"===e.type){t[e.key]=void 0!==e.output?jt(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=i.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=O(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?jt(o.output,y.context,n,s.self):void 0}i.push(r(k.id,t)),$=k,k=k.parent}k||(y=_t(y,{status:"done",output:t($)}))}JSON.stringify(_)!==JSON.stringify(e._stateInputs||{})&&(y=_t(y,{_stateInputs:_}))},[b,E]=w(y,n,s,m);y=b,c.push(...E),v&&v!==e.context&&(y=_t(y,{context:v})),S();const k=[...a];if("done"===y.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=d(e.exit,y.context,y.children,s);t.push(...n),o?.length&&i.push(...o)}});const[e,o]=w(y,n,s,t);y=e,c.push(...o)}return h===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[_t(y),c]:[y,c]:[_t(y,{_nodes:k,historyValue:h}),c]}}function tt(t,e,s,n,o){const i={context:e.context,event:s,output:It(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays};if(t.to){const r=[],c=[],a=x(n,r,c,!1,o?.resolveActions??!0),h=t.to(i,a),u=h?.target?R(t.source,$t(h.target)):void 0,f="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input;return{targets:u,context:h?.context,reenter:h?.reenter,actions:r,internalEvents:c,input:f}}const r="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input,c="function"==typeof t.context?t.context(i):t.context;return{targets:t.target,context:c,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:r}}function et(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=_t(ot(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=_t(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=Z(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?it(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=Z(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&ot(r,o),{snapshot:r,microsteps:c}}function st(t,e,s,n,o){return!!t.to&&nt(t.to,e,s,n,o,n.machine.implementations)}function nt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,output:It(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actorSources:i.actorSources,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function ot(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return _t(t,{children:{}})}function it(t,e,s){const n=new Set,o=t._nodes.filter(I);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(rt(i,e,t,o,s.self)){n.add(i);break t}return U(Array.from(n),new Set(t._nodes),t,e,s)}function rt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,output:It(e),self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actorSources:n.machine.implementations.actorSources,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s};if(!t.guard(i))return!1}return!t.to||nt(t.to,s.context,e,s,o,n.machine.implementations)}function ct(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let at,ht;function ut(){return at??=Qt()}const ft=function(t){return bt(t,this.value)},pt=function(t){return this.tags.has(t)},lt=function(t){const e=ut(),s=function(){if(ht)return ht;const t=ut();return ht={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},ht}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=tt(o,this,t,s,{resolveActions:!1});if(n.targets?.length||n.context||st(o,this.context,t,this,e))return!0}return!1},dt=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},yt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},gt=function(){return this._stateInputs};function vt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function mt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??A(e.root,t._nodes),tags:vt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}}function _t(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}:mt({...s,value:void 0},t.machine)}function St(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function xt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Vt,id:n.id};else{const o=xt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function bt(t,e){const s=Et(t),n=Et(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&bt(s[t],n[t]))}function wt(t){if(Ot(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Et(t){if(ct(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(wt(t))}function kt(t){return Ot(t)?t:[t]}function $t(t){return void 0===t?[]:kt(t)}function jt(t,e,s,n){if("function"==typeof t){return t({context:e,event:s,output:It(s),self:n})}return t}function It(t){if(function(t){return t.type.startsWith("xstate.done.actor.")||t.type.startsWith("xstate.done.state.")}(t)){return t.output}}function Ot(t){return Array.isArray(t)}function Tt(t){return kt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function Mt(t){if(void 0!==t&&""!==t)return $t(t)}function At(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Pt(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actorSources[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actorSources[r]:r}function Nt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function zt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function Dt(t,e){return`${t.sessionId}.${e}`}const Rt=new WeakMap;function Jt(t){let e=Rt.get(t);return e||(e=new Map,Rt.set(t,e)),e}function Kt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Jt(e.self).set(Symbol(),{cleanup:t});break}const t=Jt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Rt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Rt.delete(e.self);break}}}function Ct(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]},s={id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,c(t.input),s);Object.assign(t,n),Kt(o,s)},initialTransition:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==n&&(o.context=n),[{...o},[]]},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}let Bt=!1;const Vt=1;let Wt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Lt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function qt(t){return"object"==typeof t&&null!==t&&"args"in t&&"exec"in t}function Ft(t,e){if(!t?.length)return[];const s=[];for(const n of t)qt(n)?e.actionExecutor(n):s.push(n);return s}class Gt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Wt.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Lt,...s},{clock:o,logger:i,parent:r,syncSnapshot:c,id:h,registryKey:u,inspect:f}=n;this.system=r?r.system:n._systemRef?.current??function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=Dt(t,o);l._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=Dt(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const s=l._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=At(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:n.timers}),r||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!r&&this.system.inspect(At(f)),this.sessionId=this.system._bookId(),this.id=h??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(e||s){if(e)for(const s of e)try{s(t)}catch(t){a(t)}if(s)for(const e of s)try{e(t)}catch(t){a(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Bt;try{Bt=!0,t.exec()}finally{Bt=e}};this._processingStatus!==Wt.Running||this._forceDeferredActions?this._deferred.push(e):e()}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}});const p=u;p&&(this.registryKey=p,this.system._set(p,this)),this._collectedMicrosteps=[];let l=s?.snapshot??s?.state;if(l&&"object"==typeof l&&"_pendingEffects"in l){const{_pendingEffects:t,...e}=l;this._pendingEffects=t,l=e}try{if(l)this._snapshot=this.logic.restoreSnapshot?this.logic.restoreSnapshot(l,this._actorScope):l;else{const[t,e]=this.logic.initialTransition(this.options?.input,this._actorScope);this._snapshot=t,this._initialEffects=e}}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}p&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){a(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{return Kt(Ft(this._initialEffects,this._actorScope),this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred.length=0,this._setErrorSnapshot(t),this._error(t),!1}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=At(t,e,s);if(this._processingStatus!==Wt.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){a(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){a(t)}else a(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=At(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Wt.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Wt.Running;const t=c(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._flushInitialEffects()?(this.update(this._snapshot,t),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(!this._flushInitialEffects())return this;if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Ut(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._setErrorSnapshot(t),void this._error(t)}try{const[s,n]=e,o=Ft(n,this._actorScope);this.update(s,t),Kt(o,this._actorScope)}catch(t){return this._setErrorSnapshot(t),void this._error(t)}t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Wt.Stopped?this:(this.mailbox.clear(),this._processingStatus===Wt.NotStarted?(this._processingStatus=Wt.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){a(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){a(t)}}this.observers.clear(),this.eventListeners.clear(),e&&a(t)}else this._parent||a(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Wt.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Wt.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Wt.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Vt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[h](){return this}getSnapshot(){return this._snapshot}}function Ut(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Ht(t,e){return new Gt(t,e)}const Xt=Ct({context:void 0,run:()=>{}});function Qt(){return Ht(Xt)}function Yt(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Pt(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Ht(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,registryKey:r?.registryKey});return o[a.id]=a,a}return Ht(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,registryKey:r?.registryKey})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Wt.Stopped&&c.start()}),c}}const Zt=new WeakMap;function te(t,e,s){let n=Zt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Zt.set(t,n)),n[e]}const ee={},se=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class ne{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of se)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new ne(t,{_parent:this,_key:e,_machine:this.machine})):ee,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=$t(t.tags).slice(),this.invoke=$t(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const c=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;c.push({event:o(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var a;void 0!==s&&n&&c.push({event:(a=t.id,{type:`xstate.timeout.${a}`}),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)c.push({event:i(t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const h=[];for(const{event:e,delay:s,transitions:n,fromDelaysMap:o}of c){const i=z(t,e,e=>j(s,o?e.delays:{},{context:e.context,event:e.event,stateNode:t}));for(const t of Tt(n))h.push({...t,event:i,delay:s})}return h.map(e=>({...D(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,oe(n,e=>D(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,oe(t.config.onDone,e=>D(t,s,e)))}const s=(e,s)=>D(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return D(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=oe(o.onDone,e=>r?n(i,e,r):D(t,i,e));r&&c.push(s(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[s(t,r)])}if(o.onError){const s=`xstate.error.actor.${o.id}`;e.set(s,oe(o.onError,e=>r?n(s,e,r):D(t,s,e)))}if(o.onSnapshot){const s=`xstate.snapshot.${o.id}`;e.set(s,oe(o.onSnapshot,e=>D(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[D(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=oe(this.config.always,t=>D(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return te(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=te(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e),n=[...t.transitions.keys()].filter(t=>t!==e&&zt(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s?[...s,...n]:n}(this,n));for(const n of o){if(rt(n,e,t,this,s))return[n]}}}function oe(t,e){const s=Tt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class ie{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actorSources:t.actorSources??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ne(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(D(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=i,h={...a,guard:r,target:`#${o}`};e.push(D(t,"xstate.route",h))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actorSources:n,delays:o}=this.implementations,i=new ie(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actorSources:{...n,...t.actorSources},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,A(s,M(W(s,n))));var s,n;const o=M(W(this.root,e));return mt({_nodes:[...o],value:e,context:t.context||{},children:{},status:P(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=this._transitionFast(t,e,s);if(n)return[n,[]];const{snapshot:o,microsteps:i}=et(t,e,s,[]);return[o,i.flatMap(([,t])=>t)]}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const o=n.transitions.get(e.type);if(1!==o?.length)return;const i=o[0];if(i.guard||i.actions||i.to||i.reenter||i.input||"function"==typeof i.context||i.target&&1!==i.target.length)return;const r=i.target?.[0]??n,c=r!==n;if(r.parent!==this.root||"atomic"!==r.type||c&&(r.entry||r.invoke.length||r.always?.length||r.after?.length))return;const a=void 0!==i.context?{...t.context,...i.context}:t.context,h=s.self._collectedMicrosteps||[];return h.push(i),s.self._collectedMicrosteps=h,_t(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,r]}:{}})}microstep(t,e,s){const{microsteps:n}=et(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(zt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=mt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Yt(t,n,e,o),input:e.input,self:t.self,actorSources:this.implementations.actorSources}),[r]=w(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=c(t),n=[],o=this._getPreInitialState(e,s),[i,r]=function(t,e,s,n,o){return Z([{target:[...C(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,e,s,n),{snapshot:a,microsteps:h}=et(i,s,e,n);return[a,[...r,...h.flatMap(([,t])=>t)]]}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=wt(t),s=e.slice(1),n=N(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return V(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:l,...d}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const g={...d,context:xt(c),children:y,historyValue:St(d.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Pt(this,r):r;if(!c)continue;const a=Ht(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,registryKey:s.registryKey});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof ne)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(M(W(this.root,n.value))),{version:a,...h}=t,u=mt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Vt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function re(t){return JSON.stringify(t)}function ce(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const ae=()=>(t,e)=>ke(t,e),he=()=>(t,e)=>$e(t,e);class ue{getDefaultOptions(){return{serializeState:t=>re(t),serializeEvent:t=>re(t),serializeTransition:(t,e)=>`${re(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ct(t.state)?`Reaches ${ce(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=re)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(ae(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getSimplePaths(t){return this.getPaths(he(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getPathsFromEvents(t,e){return Ee(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return be(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:re,serializeEvent:re,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function fe(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>fe(t[s],e[s]))}function pe(t,e,s,{serializeEvent:n}){if(!e||s&&fe(s.value,t.value))return"";const o=s?` from ${re(s.value)}`:"";return` via ${n(e)}${o}`}function le(){const t=Qt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function de(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ye(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ge(t){return JSON.stringify(t)}function ve(t,e){const{events:s,...n}=e??{};return{serializeState:ye,serializeEvent:ge,events:t=>{const e="function"==typeof s?s(t):s??[];return Nt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(le(),e?.input),...n}}function me(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ge}}function _e(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?ve(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ge,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function Se(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function xe(t){return Array.isArray(t)?t[0]:t}function be(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=_e(t,e),u=le(),f={};let p=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],d=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(d.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=xe(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function we(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function Ee(t,e,s){const n=_e(t,{events:e,...s},(o=t)&&o instanceof ie?ve(t):me());var o;const i=le(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=be(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let l=p,d=r;for(const t of e){f.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,d=s}return n.toState&&!n.toState(d)?[]:[we({state:d,steps:f,weight:f.length})]}function ke(t,e){const s=_e(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(le(),e?.input),i=be(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(we):p.map(we)}function $e(t,e){const s=_e(t,e),n=le(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=be(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(we):l.map(we)}t.TestModel=ue,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=ae,t.createSimplePathsGen=he,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??re,n=e?.serializeTransition??pe,{events:o,...i}=e??{};return new ue(t,{serializeState:(t,e,o)=>`${ye(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Nt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=be,t.getPathsFromEvents=Ee,t.getShortestPaths=ke,t.getSimplePaths=$e,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=Se,t.serializeSnapshot=ye,t.toDirectedGraph=function t(e){const s=e instanceof ie?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:de(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-graph.umd.min.js.map