xstate 5.29.0 → 5.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -71,9 +71,10 @@ export interface SerializationConfig<TSnapshot extends Snapshot<unknown>, TEvent
71
71
  type SerializationOptions<TSnapshot extends Snapshot<unknown>, TEvent extends EventObject> = Partial<Pick<SerializationConfig<TSnapshot, TEvent>, 'serializeState' | 'serializeEvent'>>;
72
72
  export type TraversalOptions<TSnapshot extends Snapshot<unknown>, TEvent extends EventObject, TInput> = {
73
73
  input?: TInput;
74
- } & SerializationOptions<TSnapshot, TEvent> & Partial<Pick<TraversalConfig<TSnapshot, TEvent>, 'events' | 'limit' | 'fromState' | 'stopWhen' | 'toState'>>;
74
+ } & SerializationOptions<TSnapshot, TEvent> & Partial<Pick<TraversalConfig<TSnapshot, TEvent>, 'events' | 'filterEvents' | 'limit' | 'fromState' | 'stopWhen' | 'toState'>>;
75
75
  export interface TraversalConfig<TSnapshot extends Snapshot<unknown>, TEvent extends EventObject> extends SerializationConfig<TSnapshot, TEvent> {
76
76
  events: readonly TEvent[] | ((state: TSnapshot) => readonly TEvent[]);
77
+ filterEvents: ((snapshot: TSnapshot, event: TEvent) => boolean) | undefined;
77
78
  /**
78
79
  * The maximum number of traversals to perform when calculating the state
79
80
  * transition adjacency map.
@@ -546,6 +546,7 @@ function resolveTraversalOptions(logic, traversalOptions, defaultOptions) {
546
546
  serializeState,
547
547
  serializeEvent,
548
548
  events: [],
549
+ filterEvents: undefined,
549
550
  limit: Infinity,
550
551
  fromState: undefined,
551
552
  toState: undefined,
@@ -578,6 +579,7 @@ function getAdjacencyMap(logic, options) {
578
579
  serializeEvent,
579
580
  serializeState,
580
581
  events: getEvents,
582
+ filterEvents,
581
583
  limit,
582
584
  fromState: customFromState,
583
585
  stopWhen
@@ -617,6 +619,9 @@ function getAdjacencyMap(logic, options) {
617
619
  }
618
620
  const events = typeof getEvents === 'function' ? getEvents(state) : getEvents;
619
621
  for (const nextEvent of events) {
622
+ if (filterEvents && !filterEvents(state, nextEvent)) {
623
+ continue;
624
+ }
620
625
  const nextSnapshot = transition(state, nextEvent, actorScope);
621
626
  adj[serializedState].transitions[serializeEvent(nextEvent)] = {
622
627
  event: nextEvent,
@@ -546,6 +546,7 @@ function resolveTraversalOptions(logic, traversalOptions, defaultOptions) {
546
546
  serializeState,
547
547
  serializeEvent,
548
548
  events: [],
549
+ filterEvents: undefined,
549
550
  limit: Infinity,
550
551
  fromState: undefined,
551
552
  toState: undefined,
@@ -578,6 +579,7 @@ function getAdjacencyMap(logic, options) {
578
579
  serializeEvent,
579
580
  serializeState,
580
581
  events: getEvents,
582
+ filterEvents,
581
583
  limit,
582
584
  fromState: customFromState,
583
585
  stopWhen
@@ -617,6 +619,9 @@ function getAdjacencyMap(logic, options) {
617
619
  }
618
620
  const events = typeof getEvents === 'function' ? getEvents(state) : getEvents;
619
621
  for (const nextEvent of events) {
622
+ if (filterEvents && !filterEvents(state, nextEvent)) {
623
+ continue;
624
+ }
620
625
  const nextSnapshot = transition(state, nextEvent, actorScope);
621
626
  adj[serializedState].transitions[serializeEvent(nextEvent)] = {
622
627
  event: nextEvent,
@@ -542,6 +542,7 @@ function resolveTraversalOptions(logic, traversalOptions, defaultOptions) {
542
542
  serializeState,
543
543
  serializeEvent,
544
544
  events: [],
545
+ filterEvents: undefined,
545
546
  limit: Infinity,
546
547
  fromState: undefined,
547
548
  toState: undefined,
@@ -574,6 +575,7 @@ function getAdjacencyMap(logic, options) {
574
575
  serializeEvent,
575
576
  serializeState,
576
577
  events: getEvents,
578
+ filterEvents,
577
579
  limit,
578
580
  fromState: customFromState,
579
581
  stopWhen
@@ -613,6 +615,9 @@ function getAdjacencyMap(logic, options) {
613
615
  }
614
616
  const events = typeof getEvents === 'function' ? getEvents(state) : getEvents;
615
617
  for (const nextEvent of events) {
618
+ if (filterEvents && !filterEvents(state, nextEvent)) {
619
+ continue;
620
+ }
616
621
  const nextSnapshot = transition(state, nextEvent, actorScope);
617
622
  adj[serializedState].transitions[serializeEvent(nextEvent)] = {
618
623
  event: nextEvent,
@@ -542,6 +542,7 @@ function resolveTraversalOptions(logic, traversalOptions, defaultOptions) {
542
542
  serializeState,
543
543
  serializeEvent,
544
544
  events: [],
545
+ filterEvents: undefined,
545
546
  limit: Infinity,
546
547
  fromState: undefined,
547
548
  toState: undefined,
@@ -574,6 +575,7 @@ function getAdjacencyMap(logic, options) {
574
575
  serializeEvent,
575
576
  serializeState,
576
577
  events: getEvents,
578
+ filterEvents,
577
579
  limit,
578
580
  fromState: customFromState,
579
581
  stopWhen
@@ -613,6 +615,9 @@ function getAdjacencyMap(logic, options) {
613
615
  }
614
616
  const events = typeof getEvents === 'function' ? getEvents(state) : getEvents;
615
617
  for (const nextEvent of events) {
618
+ if (filterEvents && !filterEvents(state, nextEvent)) {
619
+ continue;
620
+ }
616
621
  const nextSnapshot = transition(state, nextEvent, actorScope);
617
622
  adj[serializedState].transitions[serializeEvent(nextEvent)] = {
618
623
  event: nextEvent,
@@ -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(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function u(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&u(s[t],n[t]))}function f(t){if(v(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 p(t){if($t(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}(f(t))}function d(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}function l(t){return v(t)?t:[t]}function y(t){return void 0===t?[]:l(t)}function g(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function v(t){return Array.isArray(t)}function m(t){return l(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function _(t){if(void 0!==t&&""!==t)return y(t)}function S(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 x(t,e){return`${e}.${t}`}function w(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function b(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function E(t,e){return`${t.sessionId}.${e}`}let $=0;let k=!1;let I=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const O={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class j{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=I.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...O,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:h,systemId:u,inspect:f}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,h={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=E(t,o);u._snapshot._scheduledEvents[c]=i;const h=a.setTimeout(()=>{delete r[c],delete u._snapshot._scheduledEvents[c],u._relay(t,e,s)},n);r[c]=h},cancel:(t,e)=>{const s=E(t,e),n=r[s];delete r[s],delete u._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in u._snapshot._scheduledEvents){const s=u._snapshot._scheduledEvents[e];s.source===t&&h.cancel(t,s.id)}}},u={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];h.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return u}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(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=a,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)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){c(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=k;try{k=!0,t.exec(t.info,t.params)}finally{k=e}};this._processingStatus===I.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(s?.snapshot??s?.state),u&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==I.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe(s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===I.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.systemId&&this.system._set(this.systemId,this),this._processingStatus=I.Running;const t=a(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),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._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),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._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===I.Stopped?this:(this.mailbox.clear(),this._processingStatus===I.NotStarted?(this._processingStatus=I.Stopped,this):(this.mailbox.enqueue({type:n}),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){c(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||c(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}_error(t){var e;this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){return this._processingStatus!==I.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=I.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==I.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function T(t,...[e]){return new j(t,e)}function M(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function N(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function P(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const h="string"==typeof r?w(e.machine,r):r,u="function"==typeof o?o(s):o;let f,p;return h&&(p="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=T(h,{id:u,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:p})),[Nt(e,{children:{...e.children,[u]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:p},void 0]}function z(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==I.Stopped&&e.start()})}function A(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=P,i.execute=z,i}function J(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[Nt(e,{children:a}),r,void 0]}function R(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))R(t,e);t.system._unregister(e)}function D(t,e){e&&(R(t,e),e._processingStatus===I.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function C(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=J,e.execute=D,e}function L(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return L(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function V(t){return"atomic"===t.type||"final"===t.type}function B(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function q(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 W(t){const e=new Set(t),s=F(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of B(t))if("history"!==s.type&&!e.has(s)){const t=tt(s);for(const s of t)e.add(s)}}else tt(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function G(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(V(t))return t.key}const n={};for(const t of s)n[t.key]=G(t,e);return n}function F(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function U(t,e){return G(t,F(W(e)))}function K(t,e){return"compound"===e.type?B(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?B(e).every(e=>K(t,e)):"final"===e.type}const Q=t=>"#"===t[0];function X(t){const e=t.config.after;if(!e)return[];const s=e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(function(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Dt,s.execute=Ct,s}(s,{id:i,delay:e})),t.exit.push(function(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=M,e.execute=N,e}(i)),i};return Object.keys(e).flatMap(t=>{const n=e[t],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+t)?t:+t,r=s(i);return y(o).map(t=>({...t,event:r,delay:i}))}).map(e=>{const{delay:s}=e;return{...H(t,e.event,e),delay:s}})}function H(t,e,s){const n=_(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(Q(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return nt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return nt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:y(s.actions),guard:s.guard,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 Y(t){const e=_(t.config.target);return e?{target:e.map(e=>"string"==typeof e?nt(t.parent,e):e)}:t.parent.initial}function Z(t){return"history"===t.type}function tt(t){const e=et(t);for(const s of e)for(const n of q(s,t))e.add(n);return e}function et(t){const e=new Set;return 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 B(s))t(e)}(t),e}function st(t,e){if(Q(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 nt(t,e){if("string"==typeof e&&Q(e))try{return t.machine.getStateNodeById(e)}catch{}const s=f(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=st(n,t)}return n}function ot(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=s.map(e=>st(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=st(t,n);if(!o)return s;const i=ot(o,e[n]);return s.concat(i)},[]))}function it(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=st(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=it(st(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=it(st(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function rt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function at(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function ct(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function ht(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(ct(pt([o],e,s),pt([r],e,s))){if(!at(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function ut(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(Z(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of ut(Y(n),e))s.add(t);else s.add(n);return[...s]}function ft(t,e){const s=ut(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||at(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of q(e,void 0))if(s.every(e=>at(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function pt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=ft(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)at(s,t)&&n.add(s)}return[...n]}function dt(t,e,s,n,o,i){const a=[];if(!t.length)return[e,a];const c=s.actionExecutor;s.actionExecutor=t=>{a.push(t),c(t)};try{const c=new Set(e._nodes);let h=e.historyValue;const u=ht(t,c,h);let f=e;o||([f,h]=function(t,e,s,n,o,i,r){let a=t;const c=pt(n,o,i);let h;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of rt(t)){let s;s="deep"===e.history?e=>V(e)&&at(e,t):e=>e.parent===t,h??={...i},h[e.id]=Array.from(o).filter(s)}for(const t of c)a=St(a,e,s,[...t.exit,...t.invoke.map(t=>C(t.id))],r,void 0),o.delete(t);return[a,h||i]}(f,n,s,u,c,h,i,s.actionExecutor)),f=St(f,n,s,u.flatMap(t=>t.actions),i,void 0),f=function(t,e,s,n,o,i,a,c){let h=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=ft(o,e);for(const i of o.target||[])Z(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),yt(i,e,s,n);const i=ut(o,e);for(const r of i){const i=q(r,t);"parallel"===t?.type&&i.push(t),gt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,u),c&&f.add(t.machine.root);const p=new Set;for(const t of[...u].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(A(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(h=St(h,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?g(t.output,h.context,e,s.self):void 0));"parallel"===a?.type&&!p.has(a)&&K(o,a);)p.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;h=Nt(h,{status:"done",output:lt(h,e,s,h.machine.root,c)})}}return h}(f,n,s,u,c,i,h,o);const p=[...c];"done"===f.status&&(f=St(f,n,s,p.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return h===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,c)?[f,a]:[Nt(f,{_nodes:p,historyValue:h}),a]}catch(t){throw t}}finally{s.actionExecutor=c}}function lt(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?g(o.output,t.context,e,s.self):void 0);return g(n.output,t.context,i,s.self)}function yt(t,e,s,n){if(Z(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),yt(t,e,s,n);for(const i of o)vt(i,t.parent,n,e,s)}else{const o=Y(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),yt(i,e,s,n);for(const i of o.target)vt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;Z(o)||(n.add(o),s.add(o)),yt(o,e,s,n),vt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of B(t).filter(t=>!Z(t)))[...n].some(t=>at(t,o))||(Z(o)||(n.add(o),s.add(o)),yt(o,e,s,n))}function gt(t,e,s,n,o){for(const i of n)if(o&&!at(i,o)||t.add(i),"parallel"===i.type)for(const n of B(i).filter(t=>!Z(t)))[...t].some(t=>at(t,n))||(t.add(n),yt(n,e,s,t))}function vt(t,e,s,n,o){gt(s,n,o,q(t,e))}function mt(t,e){return t.implementations.actions[e]}function _t(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:mt(r,"string"==typeof t?t:t.type),h={context:a.context,event:e,self:s.self,system:s.system},u=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:h,params:u,exec:c});continue}const f=c,[p,d,l]=f.resolve(s,a,h,u,c,o);a=p,"retryResolve"in f&&i?.push([f,d]),"execute"in f&&s.actionExecutor({type:f.type,info:h,params:d,exec:f.execute.bind(null,s,d)}),l&&(a=_t(a,e,s,l,o,i))}return a}function St(t,e,s,n,o,i){const r=i?[]:void 0,a=_t(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function xt(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t[0],_transitions:s}),a.push(t)}if(e.type===n)return r=Nt(wt(r,e,o),{status:"stopped"}),c([r,[]],e,[]),{snapshot:r,microsteps:a};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=bt(e,r);if(s&&!n.length)return r=Nt(t,{status:"error",error:e.error}),c([r,[]],e,[]),{snapshot:r,microsteps:a};const u=dt(n,t,o,h,!1,i);r=u[0],c(u,e,n)}let u=!0;for(;"active"===r.status;){let t=u?Et(r,h):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=bt(h,r)}const s=dt(t,r,o,h,!1,i);r=s[0],u=r!==e,c(s,h,t)}return"active"!==r.status&&wt(r,h,o),{snapshot:r,microsteps:a}}function wt(t,e,s){return St(t,e,s,Object.values(t.children).map(t=>C(t)),[],void 0)}function bt(t,e){return e.machine.getTransitionData(e,t)}function Et(t,e){const s=new Set,n=t._nodes.filter(V);for(const o of n)t:for(const n of[o].concat(q(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||L(o.guard,t.context,e,t)){s.add(o);break t}return ht(Array.from(s),new Set(t._nodes),t.historyValue)}function $t(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const kt=function(t){return u(t,this.value)},It=function(t){return this.tags.has(t)},Ot=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},jt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Tt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Mt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:U(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:kt,hasTag:It,can:Ot,getMeta:Tt,toJSON:jt}}function Nt(t,e={}){return Mt({...t,...e},t.machine)}function Pt(t){if("object"!=typeof t||null===t)return{};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 zt(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:1,id:n.id};else{const o=zt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function At(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=w(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=T(a,{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,systemId:r?.systemId});return o[c.id]=c,c}return T(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==I.Stopped&&a.start()}),a}}function Jt(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:At(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[Nt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Rt(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Jt,e}function Dt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const h="function"==typeof o?o(s,n):o;let u;if("string"==typeof r){const t=c&&c[r];u="function"==typeof t?t(s,n):t}else u="function"==typeof r?r(s,n):r;return"number"!=typeof u&&a.push(h),[e,{event:h,id:i,delay:u},void 0]}function Ct(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}const Lt=(Bt=void 0,{config:Vt=t=>{},transition:(t,e,s)=>({...t,context:Vt(t.context,e,s)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof Bt?Bt({input:e}):Bt}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t});var Vt,Bt;const qt=new WeakMap;function Wt(t,e,s){let n=qt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},qt.set(t,n)),n[e]}const Gt={},Ft=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ut{constructor(t,e){if(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.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?d(this.config.states,(t,e)=>new Ut(t,{_parent:this,_key:e,_machine:this.machine})):Gt,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=y(this.config.entry).slice(),this.exit=y(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=y(t.tags).slice()}_initialize(){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,m(n).map(e=>H(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,m(t.config.onDone).map(e=>H(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,m(s.onDone).map(e=>H(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,m(s.onError).map(e=>H(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,m(s.onSnapshot).map(e=>H(t,n,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),this.config.always&&(this.always=m(this.config.always).map(t=>H(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Ft),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Ft),eventType:null})}:void 0,history:this.history,states:d(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Ft)})),entry:this.entry.map(Ft),exit:this.exit.map(Ft),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Wt(this,"invoke",()=>y(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??x(this.id,e),i="string"==typeof s?s:`xstate.invoke.${x(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return Wt(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return Wt(this,"delayedTransitions",()=>X(this))}get initial(){return Wt(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?y(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=Wt(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>function(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}(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||L(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return Wt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(e)}}class Kt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.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 Ut(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 s=n.config.id,o=n.config.route.guard,i=(t,e)=>t.event.to===`#${s}`&&(!o||"function"!=typeof o||o(t,e)),r={...n.config.route,guard:i,target:`#${s}`};e.push(H(t,"xstate.route",r))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new Kt(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,U(s,[...W(ot(s,n))]));var s,n;const o=W(ot(this.root,e));return Mt({_nodes:[...o],context:t.context||{},children:{},status:K(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return xt(t,e,s,[]).snapshot}microstep(t,e,s){return xt(t,e,s,[]).microsteps.map(([t])=>t)}getTransitionData(t,e){return it(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Mt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return St(o,e,t,[Rt(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this._getPreInitialState(t,s,n),[i]=function(t,e,s,n,o){return dt([{target:[...et(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:r}=xt(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=f(t),s=e.slice(1),n=Q(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 nt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:h,getMeta:u,toJSON:f,...p}=t,d={};for(const t in i){const s=i[t];d[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...p,context:zt(r),children:d,historyValue:Pt(p.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Ut)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?w(this,r):r;if(!a)return;const c=T(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Mt({...t,children:s,_nodes:Array.from(W(ot(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Qt(t){return JSON.stringify(t)}function Xt(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 Ht=()=>(t,e)=>le(t,e),Yt=()=>(t,e)=>ye(t,e),Zt=t=>{if(t.invoke.length>0)throw new Error("Invocations on test machines are not supported");if(t.after.length>0)throw new Error("After events on test machines are not supported");[...t.entry,...t.exit,...[...t.transitions.values()].flatMap(t=>t.flatMap(t=>t.actions))].forEach(t=>{if("function"==typeof t&&"resolve"in t&&"number"==typeof t.delay)throw new Error("Delayed actions on test machines are not supported")});for(const e of Object.values(t.states))Zt(e)};class te{getDefaultOptions(){return{serializeState:t=>Qt(t),serializeEvent:t=>Qt(t),serializeTransition:(t,e)=>`${Qt(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:$t(t.state)?`Reaches ${Xt(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=Qt)=>{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(Ht(),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(ue(n,e)))}return s}getSimplePaths(t){return this.getPaths(Yt(),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(ue(n,e)))}return s}getPathsFromEvents(t,e){return de(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return fe(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:Qt,serializeEvent:Qt,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:a}=t,c=i(a,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),a=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",a):t.event.error?(u=!0,o("red",a)):o("green",a)}`].join("\n")}).concat(`\tState: ${u?o("gray",c):e.state.error?o("red",c):o("green",c)}`).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 ee(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=>ee(t[s],e[s]))}function se(t,e,s,{serializeEvent:n}){if(!e||s&&ee(s.value,t.value))return"";const o=s?` from ${Qt(s.value)}`:"";return` via ${n(e)}${o}`}function ne(){const t=T(Lt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function oe(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ie(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function re(t){return JSON.stringify(t)}function ae(t,e){const{events:s,...n}=e??{};return{serializeState:ie,serializeEvent:re,events:t=>{const e="function"==typeof s?s(t):s??[];return b(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ne(),e?.input),...n}}function ce(){return{serializeState:t=>JSON.stringify(t),serializeEvent:re}}function he(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?ae(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:re,events:[],limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function ue(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 fe(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,limit:r,fromState:a,stopWhen:c}=he(t,e),h=ne(),u={};let f=0;const p=[{nextState:a??t.getInitialSnapshot(h,e.input),event:void 0,prevState:void 0}],d=new Map;for(;p.length;){const{nextState:t,event:e,prevState:a}=p.shift();if(f++>r)throw new Error("Traversal limit exceeded");const l=o(t,e,a);if(u[l])continue;if(d.set(l,t),u[l]={state:t,transitions:{}},c&&c(t))continue;const y="function"==typeof i?i(t):i;for(const e of y){const o=s(t,e,h);u[l].transitions[n(e)]={event:e,state:o},p.push({nextState:o,event:e,prevState:t})}}return u}function pe(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const n=t.steps[s];e.push({state:n.state,event:0===s?{type:"xstate.init"}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:"xstate.init"}}];return{...t,steps:e}}function de(t,e,s){const n=he(t,{events:e,...s},(o=t)&&"__xstatenode"in o?ae(t):ce());var o;const i=ne(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:a,serializeEvent:c}=n,h=fe(t,n),u=new Map,f=[],p=a(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=c(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=a(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[pe({state:l,steps:f,weight:f.length})]}function le(t,e){const s=he(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ne(),e?.input),i=fe(t,s),r=new Map,a=new Map,c=n(o,void 0,void 0);a.set(c,o),r.set(c,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(c);for(const t of h){const e=a.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:c,event:f}=i[t].transitions[o],p=n(c,f,e);if(a.set(p,c),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=a.get(n),i=e?f[e].paths[0].steps.concat({state:a.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(pe):p.map(pe)}function ye(t,e){const s=he(t,e),n=ne(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=fe(t,s),a=new Map,c={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=a.get(t);if(c.vertices.add(t),t===e){u[e]||(u[e]={state:a.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else 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=a.get(t),p=i(n,o,u);a.set(p,n),c.vertices.has(p)||(c.edges.add(s),h.push({state:a.get(t),event:o}),f(p,e))}h.pop(),c.vertices.delete(t)}const p=i(o,void 0);a.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(pe):d.map(pe)}t.TestModel=te,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=Ht,t.createSimplePathsGen=Yt,t.createTestModel=function(t,e){(t=>{Zt(t.root)})(t);const s=e?.serializeEvent??Qt,n=e?.serializeTransition??se,{events:o,...i}=e??{};return new te(t,{serializeState:(t,e,o)=>`${ie(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 b(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=fe,t.getPathsFromEvents=de,t.getShortestPaths=le,t.getSimplePaths=ye,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=ue,t.serializeSnapshot=ie,t.toDirectedGraph=function t(e){const s=e instanceof Kt?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:oe(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(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const i=t=>{const e=o();e&&e.register(t)};function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function a(t){return{type:s,input:t}}function c(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable";function u(t,e){const s=p(t),n=p(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&u(s[t],n[t]))}function f(t){if(v(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 p(t){if($t(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}(f(t))}function d(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}function l(t){return v(t)?t:[t]}function y(t){return void 0===t?[]:l(t)}function g(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function v(t){return Array.isArray(t)}function m(t){return l(t).map(t=>void 0===t||"string"==typeof t?{target:t}:t)}function _(t){if(void 0!==t&&""!==t)return y(t)}function S(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 x(t,e){return`${e}.${t}`}function w(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function b(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function E(t,e){return`${t.sessionId}.${e}`}let $=0;let k=!1;let I=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const O={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class j{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=I.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...O,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:h,systemId:u,inspect:f}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,h={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=E(t,o);u._snapshot._scheduledEvents[c]=i;const h=a.setTimeout(()=>{delete r[c],delete u._snapshot._scheduledEvents[c],u._relay(t,e,s)},n);r[c]=h},cancel:(t,e)=>{const s=E(t,e),n=r[s];delete r[s],delete u._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in u._snapshot._scheduledEvents){const s=u._snapshot._scheduledEvents[e];s.source===t&&h.cancel(t,s.id)}}},u={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+$++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),getAll:()=>Object.fromEntries(n.entries()),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=S(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:h,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];h.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return u}(this,{clock:o,logger:i}),f&&!r&&this.system.inspect(S(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=a,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)return;const n=[...e?e.values():[],...s?s.values():[]];for(const e of n)try{e(t)}catch(t){c(t)}},actionExecutor:t=>{const e=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:t.type,params:t.params}}),!t.exec)return;const e=k;try{k=!0,t.exec(t.info,t.params)}finally{k=e}};this._processingStatus===I.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this.systemId=u,this.system._set(u,this)),this._initState(s?.snapshot??s?.state),u&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){c(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=S(t,e,s);if(this._processingStatus!==I.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){c(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){c(t)}else c(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}select(t,e=Object.is){return{subscribe:s=>{const n=S(s),o=this.getSnapshot();let i=t(o);return this.subscribe(s=>{const o=t(s);e(i,o)||(i=o,n.next?.(o))})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===I.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.systemId&&this.system._set(this.systemId,this),this._processingStatus=I.Running;const t=a(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),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._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),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._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===I.Stopped?this:(this.mailbox.clear(),this._processingStatus===I.NotStarted?(this._processingStatus=I.Stopped,this):(this.mailbox.enqueue({type:n}),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){c(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(t){if(!this.observers.size)return this._parent||c(t),void this.eventListeners.clear();let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){c(t)}}this.observers.clear(),this.eventListeners.clear(),e&&c(t)}_error(t){var e;this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){return this._processingStatus!==I.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=I.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==I.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:i)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[h](){return this}getSnapshot(){return this._snapshot}}function T(t,...[e]){return new j(t,e)}function M(t,e,s,n,{sendId:o}){return[e,{sendId:"function"==typeof o?o(s,n):o},void 0]}function N(t,e){t.defer(()=>{t.system.scheduler.cancel(t.self,e.sendId)})}function P(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const h="string"==typeof r?w(e.machine,r):r,u="function"==typeof o?o(s):o;let f,p;return h&&(p="function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a,f=T(h,{id:u,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:p})),[Nt(e,{children:{...e.children,[u]:f}}),{id:o,systemId:i,actorRef:f,src:r,input:p},void 0]}function z(t,{actorRef:e}){e&&t.defer(()=>{e._processingStatus!==I.Stopped&&e.start()})}function A(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="xstate.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=P,i.execute=z,i}function J(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[Nt(e,{children:a}),r,void 0]}function R(t,e){const s=e.getSnapshot();if(s&&"children"in s)for(const e of Object.values(s.children))R(t,e);t.system._unregister(e)}function D(t,e){e&&(R(t,e),e._processingStatus===I.Running?t.defer(()=>{t.stopChild(e)}):t.stopChild(e))}function C(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=J,e.execute=D,e}function L(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return L(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function V(t){return"atomic"===t.type||"final"===t.type}function B(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function q(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 W(t){const e=new Set(t),s=F(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of B(t))if("history"!==s.type&&!e.has(s)){const t=tt(s);for(const s of t)e.add(s)}}else tt(t).forEach(t=>e.add(t));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function G(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(V(t))return t.key}const n={};for(const t of s)n[t.key]=G(t,e);return n}function F(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function U(t,e){return G(t,F(W(e)))}function K(t,e){return"compound"===e.type?B(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?B(e).every(e=>K(t,e)):"final"===e.type}const Q=t=>"#"===t[0];function X(t){const e=t.config.after;if(!e)return[];const s=e=>{const s=(n=e,o=t.id,{type:`xstate.after.${n}.${o}`});var n,o;const i=s.type;return t.entry.push(function(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=Dt,s.execute=Ct,s}(s,{id:i,delay:e})),t.exit.push(function(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=M,e.execute=N,e}(i)),i};return Object.keys(e).flatMap(t=>{const n=e[t],o="string"==typeof n?{target:n}:n,i=Number.isNaN(+t)?t:+t,r=s(i);return y(o).map(t=>({...t,event:r,delay:i}))}).map(e=>{const{delay:s}=e;return{...H(t,e.event,e),delay:s}})}function H(t,e,s){const n=_(s.target),o=s.reenter??!1,i=function(t,e){if(void 0===e)return;return e.map(e=>{if("string"!=typeof e)return e;if(Q(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return nt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return nt(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}(t,n),r={...s,actions:y(s.actions),guard:s.guard,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 Y(t){const e=_(t.config.target);return e?{target:e.map(e=>"string"==typeof e?nt(t.parent,e):e)}:t.parent.initial}function Z(t){return"history"===t.type}function tt(t){const e=et(t);for(const s of e)for(const n of q(s,t))e.add(n);return e}function et(t){const e=new Set;return 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 B(s))t(e)}(t),e}function st(t,e){if(Q(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 nt(t,e){if("string"==typeof e&&Q(e))try{return t.machine.getStateNodeById(e)}catch{}const s=f(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=st(n,t)}return n}function ot(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=s.map(e=>st(t,e)).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce((s,n)=>{const o=st(t,n);if(!o)return s;const i=ot(o,e[n]);return s.concat(i)},[]))}function it(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=st(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=it(st(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=it(st(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function rt(t){return Object.keys(t.states).map(e=>t.states[e]).filter(t=>"history"===t.type)}function at(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function ct(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function ht(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(ct(pt([o],e,s),pt([r],e,s))){if(!at(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function ut(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(Z(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of ut(Y(n),e))s.add(t);else s.add(n);return[...s]}function ft(t,e){const s=ut(t,e);if(!s)return;if(!t.reenter&&s.every(e=>e===t.source||at(e,t.source)))return t.source;const n=function(t){const[e,...s]=t;for(const t of q(e,void 0))if(s.every(e=>at(e,t)))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function pt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=ft(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)at(s,t)&&n.add(s)}return[...n]}function dt(t,e,s,n,o,i){const a=[];if(!t.length)return[e,a];const c=s.actionExecutor;s.actionExecutor=t=>{a.push(t),c(t)};try{const c=new Set(e._nodes);let h=e.historyValue;const u=ht(t,c,h);let f=e;o||([f,h]=function(t,e,s,n,o,i,r){let a=t;const c=pt(n,o,i);let h;c.sort((t,e)=>e.order-t.order);for(const t of c)for(const e of rt(t)){let s;s="deep"===e.history?e=>V(e)&&at(e,t):e=>e.parent===t,h??={...i},h[e.id]=Array.from(o).filter(s)}for(const t of c)a=St(a,e,s,[...t.exit,...t.invoke.map(t=>C(t.id))],r,void 0),o.delete(t);return[a,h||i]}(f,n,s,u,c,h,i,s.actionExecutor)),f=St(f,n,s,u.flatMap(t=>t.actions),i,void 0),f=function(t,e,s,n,o,i,a,c){let h=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=ft(o,e);for(const i of o.target||[])Z(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),yt(i,e,s,n);const i=ut(o,e);for(const r of i){const i=q(r,t);"parallel"===t?.type&&i.push(t),gt(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,a,f,u),c&&f.add(t.machine.root);const p=new Set;for(const t of[...u].sort((t,e)=>t.order-e.order)){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(A(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(h=St(h,e,s,n,i,t.invoke.map(t=>t.id)),"final"===t.type){const n=t.parent;let a="parallel"===n?.type?n:n?.parent,c=a||t;for("compound"===n?.type&&i.push(r(n.id,void 0!==t.output?g(t.output,h.context,e,s.self):void 0));"parallel"===a?.type&&!p.has(a)&&K(o,a);)p.add(a),i.push(r(a.id)),c=a,a=a.parent;if(a)continue;h=Nt(h,{status:"done",output:lt(h,e,s,h.machine.root,c)})}}return h}(f,n,s,u,c,i,h,o);const p=[...c];"done"===f.status&&(f=St(f,n,s,p.sort((t,e)=>e.order-t.order).flatMap(t=>t.exit),i,void 0));try{return h===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,c)?[f,a]:[Nt(f,{_nodes:p,historyValue:h}),a]}catch(t){throw t}}finally{s.actionExecutor=c}}function lt(t,e,s,n,o){if(void 0===n.output)return;const i=r(o.id,void 0!==o.output&&o.parent?g(o.output,t.context,e,s.self):void 0);return g(n.output,t.context,i,s.self)}function yt(t,e,s,n){if(Z(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),yt(t,e,s,n);for(const i of o)vt(i,t.parent,n,e,s)}else{const o=Y(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),yt(i,e,s,n);for(const i of o.target)vt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;Z(o)||(n.add(o),s.add(o)),yt(o,e,s,n),vt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of B(t).filter(t=>!Z(t)))[...n].some(t=>at(t,o))||(Z(o)||(n.add(o),s.add(o)),yt(o,e,s,n))}function gt(t,e,s,n,o){for(const i of n)if(o&&!at(i,o)||t.add(i),"parallel"===i.type)for(const n of B(i).filter(t=>!Z(t)))[...t].some(t=>at(t,n))||(t.add(n),yt(n,e,s,t))}function vt(t,e,s,n,o){gt(s,n,o,q(t,e))}function mt(t,e){return t.implementations.actions[e]}function _t(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const t of n){const n="function"==typeof t,c=n?t:mt(r,"string"==typeof t?t:t.type),h={context:a.context,event:e,self:s.self,system:s.system},u=n||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:a.context,event:e}):t.params:void 0;if(!c||!("resolve"in c)){s.actionExecutor({type:"string"==typeof t?t:"object"==typeof t?t.type:t.name||"(anonymous)",info:h,params:u,exec:c});continue}const f=c,[p,d,l]=f.resolve(s,a,h,u,c,o);a=p,"retryResolve"in f&&i?.push([f,d]),"execute"in f&&s.actionExecutor({type:f.type,info:h,params:d,exec:f.execute.bind(null,s,d)}),l&&(a=_t(a,e,s,l,o,i))}return a}function St(t,e,s,n,o,i){const r=i?[]:void 0,a=_t(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach(([t,e])=>{t.retryResolve(s,a,e)}),a}function xt(t,e,o,i){let r=t;const a=[];function c(t,e,s){o.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:o.self,event:e,snapshot:t[0],_transitions:s}),a.push(t)}if(e.type===n)return r=Nt(wt(r,e,o),{status:"stopped"}),c([r,[]],e,[]),{snapshot:r,microsteps:a};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=bt(e,r);if(s&&!n.length)return r=Nt(t,{status:"error",error:e.error}),c([r,[]],e,[]),{snapshot:r,microsteps:a};const u=dt(n,t,o,h,!1,i);r=u[0],c(u,e,n)}let u=!0;for(;"active"===r.status;){let t=u?Et(r,h):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=bt(h,r)}const s=dt(t,r,o,h,!1,i);r=s[0],u=r!==e,c(s,h,t)}return"active"!==r.status&&wt(r,h,o),{snapshot:r,microsteps:a}}function wt(t,e,s){return St(t,e,s,Object.values(t.children).map(t=>C(t)),[],void 0)}function bt(t,e){return e.machine.getTransitionData(e,t)}function Et(t,e){const s=new Set,n=t._nodes.filter(V);for(const o of n)t:for(const n of[o].concat(q(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||L(o.guard,t.context,e,t)){s.add(o);break t}return ht(Array.from(s),new Set(t._nodes),t.historyValue)}function $t(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const kt=function(t){return u(t,this.value)},It=function(t){return this.tags.has(t)},Ot=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some(t=>void 0!==t.target||t.actions.length)},jt=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},Tt=function(){return this._nodes.reduce((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t),{})};function Mt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:U(e.root,t._nodes),tags:new Set(t._nodes.flatMap(t=>t.tags)),children:t.children,historyValue:t.historyValue||{},matches:kt,hasTag:It,can:Ot,getMeta:Tt,toJSON:jt}}function Nt(t,e={}){return Mt({...t,...e},t.machine)}function Pt(t){if("object"!=typeof t||null===t)return{};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 zt(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:1,id:n.id};else{const o=zt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function At(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r)=>{if("string"==typeof i){const a=w(e,i);if(!a)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const c=T(a,{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,systemId:r?.systemId});return o[c.id]=c,c}return T(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[a.id]=a,t.defer(()=>{a._processingStatus!==I.Stopped&&a.start()}),a}}function Jt(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:At(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[Nt(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children}),void 0,void 0]}function Rt(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=Jt,e}function Dt(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const h="function"==typeof o?o(s,n):o;let u;if("string"==typeof r){const t=c&&c[r];u="function"==typeof t?t(s,n):t}else u="function"==typeof r?r(s,n):r;return"number"!=typeof u&&a.push(h),[e,{event:h,id:i,delay:u},void 0]}function Ct(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer(()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)})}const Lt=(Bt=void 0,{config:Vt=t=>{},transition:(t,e,s)=>({...t,context:Vt(t.context,e,s)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof Bt?Bt({input:e}):Bt}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t});var Vt,Bt;const qt=new WeakMap;function Wt(t,e,s){let n=qt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},qt.set(t,n)),n[e]}const Gt={},Ft=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class Ut{constructor(t,e){if(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.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?d(this.config.states,(t,e)=>new Ut(t,{_parent:this,_key:e,_machine:this.machine})):Gt,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=y(this.config.entry).slice(),this.exit=y(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=y(t.tags).slice()}_initialize(){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,m(n).map(e=>H(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,m(t.config.onDone).map(e=>H(t,s,e)))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,m(s.onDone).map(e=>H(t,n,e)))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,m(s.onError).map(e=>H(t,n,e)))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,m(s.onSnapshot).map(e=>H(t,n,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),this.config.always&&(this.always=m(this.config.always).map(t=>H(this,"",t))),Object.keys(this.states).forEach(t=>{this.states[t]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(Ft),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(t=>`#${t.id}`),source:`#${this.id}`,actions:this.initial.actions.map(Ft),eventType:null})}:void 0,history:this.history,states:d(this.states,t=>t.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(t=>({...t,actions:t.actions.map(Ft)})),entry:this.entry.map(Ft),exit:this.exit.map(Ft),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Wt(this,"invoke",()=>y(this.config.invoke).map((t,e)=>{const{src:s,systemId:n}=t,o=t.id??x(this.id,e),i="string"==typeof s?s:`xstate.invoke.${x(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))}get on(){return Wt(this,"on",()=>[...this.transitions].flatMap(([t,e])=>e.map(e=>[t,e])).reduce((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t),{}))}get after(){return Wt(this,"delayedTransitions",()=>X(this))}get initial(){return Wt(this,"initial",()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?y(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial))}next(t,e){const s=e.type,n=[];let o;const i=Wt(this,`candidates-${s}`,()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter(t=>function(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}(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));var t,e});for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||L(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return Wt(this,"events",()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)})}get ownEvents(){const t=Object.keys(Object.fromEntries(this.transitions)),e=new Set(t.filter(t=>this.transitions.get(t).some(t=>!(!t.target&&!t.actions.length&&!t.reenter))));return Array.from(e)}}class Kt{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.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 Ut(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 s=n.config.id,o=n.config.route.guard,i=(t,e)=>t.event.to===`#${s}`&&(!o||"function"!=typeof o||o(t,e)),r={...n.config.route,guard:i,target:`#${s}`};e.push(H(t,"xstate.route",r))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new Kt(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,U(s,[...W(ot(s,n))]));var s,n;const o=W(ot(this.root,e));return Mt({_nodes:[...o],context:t.context||{},children:{},status:K(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return xt(t,e,s,[]).snapshot}microstep(t,e,s){return xt(t,e,s,[]).microsteps.map(([t])=>t)}getTransitionData(t,e){return it(this.root,t.value,t,e)||[]}_getPreInitialState(t,e,s){const{context:n}=this.config,o=Mt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return St(o,e,t,[Rt(({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s}))],s,void 0)}return o}getInitialSnapshot(t,e){const s=a(e),n=[],o=this._getPreInitialState(t,s,n),[i]=function(t,e,s,n,o){return dt([{target:[...et(t)],source:t,reenter:!0,actions:[],eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,t,s,n),{snapshot:r}=xt(i,s,t,n);return r}start(t){Object.values(t.children).forEach(t=>{"active"===t.getSnapshot().status&&t.start()})}getStateNodeById(t){const e=f(t),s=e.slice(1),n=Q(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 nt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:h,getMeta:u,toJSON:f,...p}=t,d={};for(const t in i){const s=i[t];d[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s.systemId,syncSnapshot:s._syncSnapshot}}return{...p,context:zt(r),children:d,historyValue:Pt(p.historyValue)}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;function o(t,e){if(e instanceof Ut)return e;try{return t.machine.getStateNodeById(e.id)}catch{}}Object.keys(n).forEach(t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?w(this,r):r;if(!a)return;const c=T(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c});const i=function(t,e){if(!e||"object"!=typeof e)return{};const s={};for(const n in e){const i=e[n];for(const e of i){const i=o(t,e);i&&(s[n]??=[],s[n].push(i))}}return s}(this.root,t.historyValue),r=Mt({...t,children:s,_nodes:Array.from(W(ot(this.root,t.value))),historyValue:i},this),a=new Set;return function t(e,s){if(!a.has(e)){a.add(e);for(const n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&1===o.xstate$$type){e[n]=s[o.id];continue}t(o,s)}}}}(r.context,s),r}}function Qt(t){return JSON.stringify(t)}function Xt(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 Ht=()=>(t,e)=>le(t,e),Yt=()=>(t,e)=>ye(t,e),Zt=t=>{if(t.invoke.length>0)throw new Error("Invocations on test machines are not supported");if(t.after.length>0)throw new Error("After events on test machines are not supported");[...t.entry,...t.exit,...[...t.transitions.values()].flatMap(t=>t.flatMap(t=>t.actions))].forEach(t=>{if("function"==typeof t&&"resolve"in t&&"number"==typeof t.delay)throw new Error("Delayed actions on test machines are not supported")});for(const e of Object.values(t.states))Zt(e)};class te{getDefaultOptions(){return{serializeState:t=>Qt(t),serializeEvent:t=>Qt(t),serializeTransition:(t,e)=>`${Qt(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:$t(t.state)?`Reaches ${Xt(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=Qt)=>{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(Ht(),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(ue(n,e)))}return s}getSimplePaths(t){return this.getPaths(Yt(),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(ue(n,e)))}return s}getPathsFromEvents(t,e){return de(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return fe(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:Qt,serializeEvent:Qt,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:a}=t,c=i(a,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),a=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",a):t.event.error?(u=!0,o("red",a)):o("green",a)}`].join("\n")}).concat(`\tState: ${u?o("gray",c):e.state.error?o("red",c):o("green",c)}`).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 ee(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=>ee(t[s],e[s]))}function se(t,e,s,{serializeEvent:n}){if(!e||s&&ee(s.value,t.value))return"";const o=s?` from ${Qt(s.value)}`:"";return` via ${n(e)}${o}`}function ne(){const t=T(Lt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function oe(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ie(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function re(t){return JSON.stringify(t)}function ae(t,e){const{events:s,...n}=e??{};return{serializeState:ie,serializeEvent:re,events:t=>{const e="function"==typeof s?s(t):s??[];return b(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(ne(),e?.input),...n}}function ce(){return{serializeState:t=>JSON.stringify(t),serializeEvent:re}}function he(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?ae(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:re,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function ue(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 fe(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:a,fromState:c,stopWhen:h}=he(t,e),u=ne(),f={};let p=0;const d=[{nextState:c??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],l=new Map;for(;d.length;){const{nextState:t,event:e,prevState:c}=d.shift();if(p++>a)throw new Error("Traversal limit exceeded");const y=o(t,e,c);if(f[y])continue;if(l.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=s(t,e,u);f[y].transitions[n(e)]={event:e,state:o},d.push({nextState:o,event:e,prevState:t})}}return f}function pe(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const n=t.steps[s];e.push({state:n.state,event:0===s?{type:"xstate.init"}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:"xstate.init"}}];return{...t,steps:e}}function de(t,e,s){const n=he(t,{events:e,...s},(o=t)&&"__xstatenode"in o?ae(t):ce());var o;const i=ne(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:a,serializeEvent:c}=n,h=fe(t,n),u=new Map,f=[],p=a(r,void 0,void 0);u.set(p,r);let d=p,l=r;for(const t of e){f.push({state:u.get(d),event:t});const e=c(t),{state:s,event:n}=h[d].transitions[e];if(!s)throw new Error(`Invalid transition from ${d} with ${e}`);const o=a(s,t,u.get(d));u.set(o,s),d=o,l=s}return n.toState&&!n.toState(l)?[]:[pe({state:l,steps:f,weight:f.length})]}function le(t,e){const s=he(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(ne(),e?.input),i=fe(t,s),r=new Map,a=new Map,c=n(o,void 0,void 0);a.set(c,o),r.set(c,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(c);for(const t of h){const e=a.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:c,event:f}=i[t].transitions[o],p=n(c,f,e);if(a.set(p,c),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=a.get(n),i=e?f[e].paths[0].steps.concat({state:a.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(pe):p.map(pe)}function ye(t,e){const s=he(t,e),n=ne(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=fe(t,s),a=new Map,c={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=a.get(t);if(c.vertices.add(t),t===e){u[e]||(u[e]={state:a.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else 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=a.get(t),p=i(n,o,u);a.set(p,n),c.vertices.has(p)||(c.edges.add(s),h.push({state:a.get(t),event:o}),f(p,e))}h.pop(),c.vertices.delete(t)}const p=i(o,void 0);a.set(p,o);for(const t of Object.keys(r))f(p,t);const d=Object.values(u).flatMap(t=>t.paths);return s.toState?d.filter(t=>s.toState(t.state)).map(pe):d.map(pe)}t.TestModel=te,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=Ht,t.createSimplePathsGen=Yt,t.createTestModel=function(t,e){(t=>{Zt(t.root)})(t);const s=e?.serializeEvent??Qt,n=e?.serializeTransition??se,{events:o,...i}=e??{};return new te(t,{serializeState:(t,e,o)=>`${ie(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 b(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=fe,t.getPathsFromEvents=de,t.getShortestPaths=le,t.getSimplePaths=ye,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=ue,t.serializeSnapshot=ie,t.toDirectedGraph=function t(e){const s=e instanceof Kt?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:oe(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