xstate 6.0.0-alpha.1 → 6.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-f0d7107d.cjs.js');
6
- var StateMachine = require('./StateMachine-48dcad8f.cjs.js');
5
+ var dist_xstateActors = require('./index-9cb3b3a0.cjs.js');
6
+ var StateMachine = require('./StateMachine-64813f46.cjs.js');
7
7
 
8
8
  /**
9
9
  * Asserts that the given event object is of the specified type or types. Throws
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var dist_xstateActors = require('./index-c35824b4.development.cjs.js');
6
- var StateMachine = require('./StateMachine-6e063ac1.development.cjs.js');
5
+ var dist_xstateActors = require('./index-f6ef20d1.development.cjs.js');
6
+ var StateMachine = require('./StateMachine-8d22a79c.development.cjs.js');
7
7
 
8
8
  /**
9
9
  * Asserts that the given event object is of the specified type or types. Throws
@@ -1,7 +1,7 @@
1
- import { m as matchesEventDescriptor, t as toArray, p as parseDelayToMilliseconds, i as isAtomicStateNode, c as createActor, a as macrostep, b as createInitEvent, d as initialMicrostep, g as getProperAncestors } from './index-39259ea4.development.esm.js';
2
- export { A as Actor, T as TimeoutError, o as __unsafe_getAllOwnEventDescriptors, r as checkStateIn, c as createActor, h as createAsyncAtom, B as createAsyncLogic, e as createAtom, f as createAtomConfig, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, j as createReducerAtom, E as createSubscriptionLogic, n as getStateNodes, k as isAtom, l as isMachineSnapshot, D as listenerLogic, q as matchesState, s as pathToStateValue, F as subscriptionLogic, u as toObserver } from './index-39259ea4.development.esm.js';
3
- import { S as StateMachine } from './StateMachine-6ec50e21.development.esm.js';
4
- export { S as StateMachine, a as StateNode } from './StateMachine-6ec50e21.development.esm.js';
1
+ import { m as matchesEventDescriptor, t as toArray, p as parseDelayToMilliseconds, i as isAtomicStateNode, c as createActor, a as macrostep, b as createInitEvent, d as initialMicrostep, g as getProperAncestors } from './index-e61170ba.development.esm.js';
2
+ export { A as Actor, T as TimeoutError, o as __unsafe_getAllOwnEventDescriptors, r as checkStateIn, c as createActor, h as createAsyncAtom, B as createAsyncLogic, e as createAtom, f as createAtomConfig, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, j as createReducerAtom, E as createSubscriptionLogic, n as getStateNodes, k as isAtom, l as isMachineSnapshot, D as listenerLogic, q as matchesState, s as pathToStateValue, F as subscriptionLogic, u as toObserver } from './index-e61170ba.development.esm.js';
3
+ import { S as StateMachine } from './StateMachine-2ea0a7fa.development.esm.js';
4
+ export { S as StateMachine, a as StateNode } from './StateMachine-2ea0a7fa.development.esm.js';
5
5
 
6
6
  /**
7
7
  * Asserts that the given event object is of the specified type or types. Throws
@@ -1,7 +1,7 @@
1
- import { m as matchesEventDescriptor, t as toArray, p as parseDelayToMilliseconds, i as isAtomicStateNode, c as createActor, a as macrostep, b as createInitEvent, d as initialMicrostep, g as getProperAncestors } from './index-688701ed.esm.js';
2
- export { A as Actor, T as TimeoutError, o as __unsafe_getAllOwnEventDescriptors, r as checkStateIn, c as createActor, h as createAsyncAtom, B as createAsyncLogic, e as createAtom, f as createAtomConfig, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, j as createReducerAtom, E as createSubscriptionLogic, n as getStateNodes, k as isAtom, l as isMachineSnapshot, D as listenerLogic, q as matchesState, s as pathToStateValue, F as subscriptionLogic, u as toObserver } from './index-688701ed.esm.js';
3
- import { S as StateMachine } from './StateMachine-47e60715.esm.js';
4
- export { S as StateMachine, a as StateNode } from './StateMachine-47e60715.esm.js';
1
+ import { m as matchesEventDescriptor, t as toArray, p as parseDelayToMilliseconds, i as isAtomicStateNode, c as createActor, a as macrostep, b as createInitEvent, d as initialMicrostep, g as getProperAncestors } from './index-93edd3bd.esm.js';
2
+ export { A as Actor, T as TimeoutError, o as __unsafe_getAllOwnEventDescriptors, r as checkStateIn, c as createActor, h as createAsyncAtom, B as createAsyncLogic, e as createAtom, f as createAtomConfig, w as createCallbackLogic, v as createEmptyActor, y as createEventObservableLogic, C as createListenerLogic, z as createLogic, x as createObservableLogic, j as createReducerAtom, E as createSubscriptionLogic, n as getStateNodes, k as isAtom, l as isMachineSnapshot, D as listenerLogic, q as matchesState, s as pathToStateValue, F as subscriptionLogic, u as toObserver } from './index-93edd3bd.esm.js';
3
+ import { S as StateMachine } from './StateMachine-2dcdb1f5.esm.js';
4
+ export { S as StateMachine, a as StateNode } from './StateMachine-2dcdb1f5.esm.js';
5
5
 
6
6
  /**
7
7
  * Asserts that the given event object is of the specified type or types. Throws
@@ -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).XState={})}(this,function(t){"use strict";let e;class n{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",o="@xstate.stop";function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t){return{type:s,input:t}}function a(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable",f={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,n)=>{t.system.scheduler.schedule(t.self,t.self,e,n?.delay??0,n?.id)},"@xstate.sendTo":(t,e,n,s)=>{if("string"==typeof n)throw new Error("Only event objects may be used with sendTo");void 0!==s?.delay?t.system.scheduler.schedule(t.self,e,n,s?.delay??0,s?.id):t.defer(()=>{t.system._relay(t.self,e,n)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stopChild":(t,e)=>{t.stopChild(e)}},d=new WeakMap;function h(t){return{start:(e,{self:n,system:s})=>{const o=e.input.actor;if(!o||"function"==typeof o.getSnapshot&&"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:n,system:s});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},u=n._parent;u&&(r=u.subscribe({complete:a,error:a})),d.set(n,{unsubscribe:a})},transition:(t,e,{self:n})=>e.type===o?(d.get(n)?.unsubscribe(),d.delete(n),{...t,status:"stopped",error:void 0}):t,getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,n){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,n())}function p(){return h(({actor:t,eventType:e,mapper:n},{self:s,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!ne(t.type,e)||l(s,o,()=>n(t))})})}const y=p();let g=function(t){return t[t.None=0]="None",t[t.Mutable=1]="Mutable",t[t.Watching=2]="Watching",t[t.RecursedCheck=4]="RecursedCheck",t[t.Recursed=8]="Recursed",t[t.Dirty=16]="Dirty",t[t.Pending=32]="Pending",t}({});const v=Symbol.for("xstate.atom");function m(t){return!!t&&"object"==typeof t&&v in t}const _=[];let x,b,w,S,k,E=0,$=!1;function I(){$||($=!0,({link:x,unlink:b,propagate:w,checkDirty:S,shallowPropagate:k}=function({update:t,notify:e,unwatched:n}){return{link:function(t,e,n){const s=e.depsTail;if(void 0!==s&&s.dep===t)return;const o=void 0!==s?s.nextDep:e.deps;if(void 0!==o&&o.dep===t)return o.version=n,void(e.depsTail=o);const i=t.subsTail;if(void 0!==i&&i.version===n&&i.sub===e)return;const r=e.depsTail=t.subsTail={version:n,dep:t,sub:e,prevDep:s,nextDep:o,prevSub:i,nextSub:void 0};void 0!==o&&(o.prevDep=r),void 0!==s?s.nextDep=r:e.deps=r,void 0!==i?i.nextSub=r:t.subs=r},unlink:function(t,e=t.sub){const s=t.dep,o=t.prevDep,i=t.nextDep,r=t.nextSub,c=t.prevSub;return void 0!==i?i.prevDep=o:e.depsTail=o,void 0!==o?o.nextDep=i:e.deps=i,void 0!==r?r.prevSub=c:s.subsTail=c,void 0!==c?c.nextSub=r:void 0===(s.subs=r)&&n(s),i},propagate:function(t){let n,s=t.nextSub;t:for(;;){const i=t.sub;let r=i.flags;if(r&(g.RecursedCheck|g.Recursed|g.Dirty|g.Pending)?r&(g.RecursedCheck|g.Recursed)?r&g.RecursedCheck?r&(g.Dirty|g.Pending)||!o(t,i)?r=g.None:(i.flags=r|g.Recursed|g.Pending,r&=g.Mutable):i.flags=r&~g.Recursed|g.Pending:r=g.None:i.flags=r|g.Pending,r&g.Watching&&e(i),r&g.Mutable){const e=i.subs;if(void 0!==e){const o=(t=e).nextSub;void 0!==o&&(n={value:s,prev:n},s=o);continue}}if(void 0===(t=s)){for(;void 0!==n;)if(t=n.value,n=n.prev,void 0!==t){s=t.nextSub;continue t}break}s=t.nextSub}},checkDirty:function(e,n){let o,i=0,r=!1;t:for(;;){const c=e.dep,a=c.flags;if(n.flags&g.Dirty)r=!0;else if((a&(g.Mutable|g.Dirty))===(g.Mutable|g.Dirty)){if(t(c)){const t=c.subs;void 0!==t.nextSub&&s(t),r=!0}}else if((a&(g.Mutable|g.Pending))===(g.Mutable|g.Pending)){void 0===e.nextSub&&void 0===e.prevSub||(o={value:e,prev:o}),e=c.deps,n=c,++i;continue}if(!r){const t=e.nextDep;if(void 0!==t){e=t;continue}}for(;i--;){const i=n.subs,c=void 0!==i.nextSub;if(c?(e=o.value,o=o.prev):e=i,r){if(t(n)){c&&s(i),n=e.sub;continue}r=!1}else n.flags&=~g.Pending;n=e.sub;const a=e.nextDep;if(void 0!==a){e=a;continue t}}return r}},shallowPropagate:s};function s(t){do{const n=t.sub,s=n.flags;(s&(g.Pending|g.Dirty))===g.Pending&&(n.flags=s|g.Dirty,(s&(g.Watching|g.RecursedCheck))===g.Watching&&e(n))}while(void 0!==(t=t.nextSub))}function o(t,e){let n=e.depsTail;for(;void 0!==n;){if(n===t)return!0;n=n.prevDep}return!1}}({update:t=>t._update(),notify(t){_[A++]=t,t.flags&=~g.Watching},unwatched(t){void 0!==t.depsTail&&(t.depsTail=void 0,t.flags=g.Mutable|g.Dirty,O(t))}})))}let T,j=0,A=0;function O(t){const e=t.depsTail;let n=void 0!==e?e.nextDep:t.deps;for(;void 0!==n;)n=b(n,t)}function M(){for(;j<A;){const t=_[j];_[j++]=void 0,t.notify()}j=0,A=0}function D(t,e){return t.status===e.status&&("done"===t.status&&"done"===e.status?Object.is(t.data,e.data):"error"!==t.status||"error"!==e.status||Object.is(t.error,e.error))}function N(t,e){if(t._update(e)){const e=t.subs;void 0!==e&&(w(e),k(e),M())}}let P=!1;function R(){if(P)return;P=!0;const t=new WeakMap;e=e=>{if(void 0===T)return;let n=t.get(e);void 0===n&&(n=C(0),t.set(e,n),e.subscribe({next:()=>n.set(t=>t+1),error:()=>{}})),n.get()}}function C(t,e){I(),R();const n="function"==typeof t,s=t,o={_snapshot:n?void 0:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?g.None:g.Mutable,get:()=>(void 0!==T&&x(o,T,E),o._snapshot),subscribe(t){const e="function"==typeof t?{next:t}:t,n={current:!1},s=function(t){const e=()=>{const e=T;T=n,++E,n.depsTail=void 0,n.flags=g.Watching|g.RecursedCheck;try{return t()}finally{T=e,n.flags&=~g.RecursedCheck,O(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:g.Watching|g.RecursedCheck,notify(){const t=this.flags;t&g.Dirty||t&g.Pending&&S(this.deps,this)?e():this.flags=g.Watching},stop(){this.flags=g.None,this.depsTail=void 0,O(this)}};return e(),n}(()=>{if(o.get(),n.current){const t=T;T=void 0;try{e.next?.(o._snapshot)}catch(t){a(t)}finally{T=t}o.get()}else n.current=!0});return{unsubscribe:()=>{s.stop()}}},_update(t){const i=T,r=e?.compare??Object.is;T=o,++E,o.depsTail=void 0,n&&(o.flags=g.Mutable|g.RecursedCheck);try{const e=o._snapshot,i="function"==typeof t?t(e):void 0===t&&n?s(e):t;return(void 0===e||!r(e,i))&&(o._snapshot=i,!0)}finally{T=i,n&&(o.flags&=~g.RecursedCheck),O(o)}}};return n?(o.flags=g.Mutable|g.Dirty,o.get=function(){const t=o.flags;if(t&g.Dirty||t&g.Pending&&S(o.deps,o)){if(o._update()){const t=o.subs;void 0!==t&&k(t)}}else t&g.Pending&&(o.flags=t&~g.Pending);return void 0!==T&&x(o,T,E),o._snapshot}):o.set=function(t){if(o._update(t)){const t=o.subs;void 0!==t&&(w(t),k(t),M())}},o[v]=!0,o}function W(){return h(({actor:t,mappers:e},{self:n,system:s})=>{const{done:o,error:i,snapshot:r}=e;if(m(t)){if(!r)return;return t.subscribe(t=>l(n,s,()=>r(t)))}return t.subscribe({next:t=>{"done"===t.status&&o?l(n,s,()=>o(t.output)):"error"===t.status&&i?l(n,s,()=>i(t.error)):"active"===t.status&&r&&l(n,s,()=>r(t))},error:t=>{i&&l(n,s,()=>i(t))},complete:()=>{}})})}const L=W();function z(t,e,...n){t.push({action:e,args:n})}function V(t,e,n){z(t,f["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(n){return{children:{...n.children,[e]:t}}},{_special:!0})}(e,n??e.id))}function J(t,e,n,s=!1){const o={cancel:n=>{z(e,f["@xstate.cancel"],t,n)},emit:t=>{e.push(t)},log:(...n)=>{z(e,t.logger,...n)},raise:(s,o)=>{if("string"==typeof s)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?z(e,f["@xstate.raise"],t,s,o):n.push(s)},spawn:(n,s)=>{const o=ve(n,{...s,parent:t.self});return V(e,o,s?.id),o},sendTo:(n,s,o)=>{n&&z(e,f["@xstate.sendTo"],t,n,s,o)},stop:n=>{n&&(z(e,f["@xstate.stopChild"],t,n),e.push(function(t){return Object.assign(function(e){const n={...e.children};for(const e of Object.keys(n))n[e]===t&&delete n[e];return{children:n}},{_special:!0})}(n)))}};return s&&Object.assign(o,{listen:(n,s,o)=>{const i=ve(y,{input:{actor:n,eventType:s,mapper:o},parent:t.self});return z(e,f["@xstate.start"],i),i},subscribeTo:(n,s)=>{const o=ve(L,{input:{actor:n,mappers:"function"==typeof s?{snapshot:s}:s},parent:t.self});return z(e,f["@xstate.start"],o),o}}),q(o,(t,...n)=>{z(e,t,...n)})}function B(t,e,n,s){let o=t;for(const i of s){const s="function"==typeof i?i:"object"==typeof i&&"action"in i&&"function"==typeof i.action&&i.action.bind(null,...i.args);s||"object"!=typeof i||null===i||n.defer(()=>{n.emit(i)});const r={context:o.context,event:e,self:n.self,system:n.system,children:o.children,parent:n.self._parent,actions:t.machine.implementations.actions,actors:t.machine.implementations.actors};let c;if("object"==typeof i&&null!==i){const{type:t,...e}=i;c=e}if(s&&"_special"in s){n.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:c,args:[],exec:void 0});const t=s(r,F);t&&("context"in t||"children"in t)&&(o=Vt(o,{..."context"in t?{context:t.context}:{},..."children"in t?{children:t.children}:{}}));continue}s&&"resolve"in s||n.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:c,args:"object"==typeof i&&"action"in i?i.args:[],exec:s})}return o}function q(t,e){const n=(t,...n)=>{e(t,...n)};return Object.assign(n,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),n}const F=q({},()=>{});function U(t){const e=t.trim(),n=e.match(/^(\d+)ms$/i);if(n)return parseInt(n[1],10);const s=e.match(/^(\d*)(\.?)(\d*)s$/i);if(s){const t=s[1]?parseInt(s[1],10):0,e=!!s[2],n=s[3]?parseInt(s[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?n:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:u}=o.groups;if(!(i||r||c||a||u))return;const f=t=>t?Number(t.replace(",",".")):0;return 7*f(i)*24*60*60*1e3+24*f(r)*60*60*1e3+60*f(c)*60*1e3+60*f(a)*1e3+1e3*f(u)}function G(t){if(void 0!==t)return"number"==typeof t?t:U(t)}function X(t,e){if("string"!=typeof t)return t;const n=e[t];return void 0!==n?n:U(t)??t}function Z(t,e,n){if("function"==typeof t)return t(n);const s=X(t,e);return"function"==typeof s?s(n):s}function H(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function K(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Q(t,e){const n=[];if(e===t)return n;let s=t.parent;for(;s&&s!==e;)n.push(s),s=s.parent;return n}function Y(t){const e=new Set(t),n=new Set;for(const t of e)t.parent&&n.add(t.parent);for(const t of e)if("compound"!==t.type||n.has(t)){if("parallel"===t.type)for(const n of K(t))if(!e.has(n)){const t=at(n);for(const n of t)e.add(n)}}else for(const n of at(t))e.add(n);for(const t of e){let n=t.parent;for(;n&&!e.has(n);)e.add(n),n=n.parent}return e}function tt(t,e){const n=Y(e),s=new Map;for(const t of n)s.has(t)||s.set(t,[]),t.parent&&(s.has(t.parent)||s.set(t.parent,[]),s.get(t.parent).push(t));const o=t=>{const e=s.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(H(t))return t.key}const n={};for(const t of e)n[t.key]=o(t);return n};return o(t)}function et(t,e){return"compound"===e.type?K(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?K(e).every(e=>et(t,e)):"final"===e.type}const nt=t=>"#"===t[0];function st(t,e,n){const s=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:s,delay:n(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(s),"function"==typeof i?i(t,e):void 0),s}function ot(t,e,n){const s=Yt(n.target),o=n.reenter??!1,i=it(t,s),r={...n,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 it(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(nt(e))return t.machine.getStateNodeById(e);const n="."===e[0];if(n&&!t.parent)return ft(t,e.slice(1));const s=n?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ft(t.parent,s)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function rt(t){const e=Yt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?ft(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function ct(t){return"history"===t.type}function at(t){const e=new Set;!function t(n){if(!e.has(n))if(e.add(n),"compound"===n.type)t(n.initial.target[0]);else if("parallel"===n.type)for(const e of K(n))t(e)}(t);for(const n of e)for(const s of Q(n,t))e.add(s);return e}function ut(t,e){if(nt(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 n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function ft(t,e){if("string"==typeof e&&nt(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Ft(e).slice();let s=t;for(;n.length;){const t=n.shift();if(!t.length)break;s=ut(s,t)}return s}function dt(t,e){if("string"==typeof e){const n=t.states[e];if(!n)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,n]}const n=Object.keys(e),s=new Array(n.length),o=[t.machine.root,t];for(let e=0;e<n.length;e++){const i=ut(t,n[e]);s[e]=i,o.push(i)}for(let t=0;t<n.length;t++)o.push(...dt(s[t],e[n[t]]));return o}function ht(t,e,n,s,o){if("string"==typeof e){const i=ut(t,e).next(n,s,o);return i&&i.length?i:t.next(n,s,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=ht(ut(t,r),e[r],n,s,o);return i&&i.length?i:t.next(n,s,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=ht(ut(t,r),i,n,s,o);a&&c.push(...a)}return c.length?c:t.next(n,s,o)}function lt(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function pt(t,e){for(const n of t)if(lt(n,e))return!0;return!1}function yt(t,e){const n=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,s=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==n&&void 0!==s&&s<n&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function gt(t,e,n,s,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=_t([t],e,n,s,o),r.set(t,i)),i};for(const e of t){let t=!1;const n=new Set;for(const s of i)if(yt(c(e),c(s))){if(!lt(e.source,s.source)){t=!0;break}n.add(s)}if(!t){for(const t of n)i.delete(t);i.add(e)}}return Array.from(i)}function vt(t,e,n,s){const o=e.historyValue,{targets:i}=wt(t,e,n,s);if(!i)return[];const r=new Set;for(const t of i)if(ct(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of vt(rt(t),e,n,s))r.add(o);else r.add(t);return[...r]}function mt(t,e,n,s){const o=vt(t,e,n,s),{reenter:i}=wt(t,e,n,s);if(!i&&o.every(e=>e===t.source||lt(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of Q(r,void 0))if(c.every(e=>lt(e,t)))return t;return i?void 0:t.source.machine.root}function _t(t,e,n,s,o){const i=new Set;for(const r of t){const{targets:t}=wt(r,n,s,o);if(t?.length){const t=mt(r,n,s,o);r.reenter&&r.source===t&&i.add(t);for(const n of e)lt(n,t)&&i.add(n)}}return[...i]}function xt(t,e,n,s,o){return bt([{target:[...at(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,n,s,!0,o)}function bt(t,e,n,s,o,i){const c=[];if(!t.length)return[e,c];const a=n.actionExecutor;n.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const d=e.context,h=gt(t,a,e,s,n),l=t=>wt(t,e,s,n),p=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let u;const f=J(n,c,a,!0),d=t({context:o,event:s,parent:n.self._parent,self:n.self,children:i,system:n.system,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},f);return d?.context&&(u=d.context),[c,u,a]}return[[Object.assign((e,n)=>t({...e,input:r},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=_t(h,a,e,s,n);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const n="deep"===t.history?t=>H(t)&&lt(t,e):t=>t.parent===e;o??={...u},o[t.id]=r.filter(n)}for(const o of t){const t=e._stateInputs?.[o.id],[r,c,u]=o.exit?p(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),c&&(y=Vt(y,{context:c})),y=B(y,s,n,r);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&n.stopChild(e),delete y.children[t.id]}a.delete(o)}u=o||u};o||g();let v=y.context;const m=[],_=[];for(const t of h){t.actions&&m.push(...Zt(t.actions));const e=l(t);e.context&&(v=e.context),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const x=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=Ht(t.output,y.context,s,n.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,n=i.find(t=>t.type===e);o=n?.output}return Ht(e.output,y.context,r(t.id,o),n.self)},c=new Set,d=new Set,g=(t,e)=>{for(const n of t)if(e&&!lt(n,e)||c.add(n),"parallel"===n.type)for(const t of K(n))pt(c,t)||(c.add(t),v(t))},v=t=>{if(ct(t))if(u[t.id]){const e=u[t.id];for(const t of e)c.add(t),v(t);for(const n of e)g(Q(n,t.parent),void 0)}else{const e=rt(t),{targets:n}=l(e);for(const s of n??[])c.add(s),e===t.parent?.initial&&d.add(t.parent),v(s);for(const e of n??[])g(Q(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return ct(e)||(c.add(e),d.add(e)),v(e),void g(Q(e,t),void 0)}if("parallel"===t.type)for(const e of K(t))pt(c,e)||(c.add(e),d.add(e),v(e))}};for(const t of h){const o=mt(t,e,s,n),{targets:i,reenter:r}=l(t);for(const e of i??[])ct(e)||t.source===e&&t.source===o&&!r||(c.add(e),d.add(e)),v(e);const a=vt(t,e,s,n);for(const e of a){const n=Q(e,o);"parallel"===o?.type&&n.push(o),g(n,!t.source.parent&&r?void 0:o)}}o&&d.add(e.machine.root);const m={...e._stateInputs};for(const t of h){const{targets:e,input:n}=l(t);if(n&&e)for(const t of e)m[t.id]=n}const _=new Set,x={...e.children};for(const o of[...c].sort((t,e)=>t.order-e.order)){a.add(o);const c=[];let u,h=!1;for(const t of o.invoke){h=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.implementations.actors,context:e.context,event:s,self:n.self}));const i="string"==typeof o?ee(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:n.self,context:e.context,event:s}):t.input,a=ve(i,{...t,input:r,parent:n.self,syncSnapshot:!!t.onSnapshot});c.push({action:f["@xstate.start"],args:[a]}),t.id&&(x[t.id]=a)}h&&(y=Vt(y,{children:x}));const l=m[o.id];if(o.entry){const[t,e,n]=p(o.entry,y.context,x,l);c.push(...t),n?.length&&i.push(...n),e&&(u=e)}if(d.has(o)){const{actions:t,input:e}=wt(o.initial,y,s,n);if(t&&c.push(...t),e&&o.initial?.target)for(const t of o.initial.target)m[t.id]=e}if(y=B(y,s,n,c),u&&(y.context=u),"final"!==o.type)continue;const g=o.parent;let v="parallel"===g?.type?g:g?.parent,b=v||o;for("compound"===g?.type&&i.push(r(g.id,void 0!==o.output?Ht(o.output,y.context,s,n.self):void 0));"parallel"===v?.type&&!_.has(v)&&et(a,v);){_.add(v);const t={};for(const e of K(v)){if("final"===e.type){t[e.key]=void 0!==e.output?Ht(e.output,y.context,s,n.self):void 0;continue}if("parallel"===e.type){const n=`xstate.done.state.${e.id}`,s=i.find(t=>t.type===n);t[e.key]=s?.output;continue}const o=K(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Ht(o.output,y.context,s,n.self):void 0}i.push(r(v.id,t)),b=v,v=v.parent}v||(y=Vt(y,{status:"done",output:t(b)}))}JSON.stringify(m)!==JSON.stringify(e._stateInputs||{})&&(y=Vt(y,{_stateInputs:m}))};y=B(y,s,n,m),v&&v!==e.context&&(y=Vt(y,{context:v})),x();const b=[...a];if("done"===y.status){const t=[];b.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const n=y._stateInputs?.[e.id],[s,,o]=p(e.exit,y.context,y.children,n);t.push(...s),o?.length&&i.push(...o)}}),y=B(y,s,n,t)}return u===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==d?[Vt(y),c]:[y,c]:[Vt(y,{_nodes:b,historyValue:u}),c]}finally{n.actionExecutor=a}}function wt(t,e,n,s){if(t.to){const o=[],i=[],r=J(s,o,i),c=t.to({context:e.context,event:n,value:e.value,children:e.children,parent:s.self._parent,self:s.self,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?it(t.source,Zt(c.target)):void 0,u="function"==typeof t.input?t.input({context:e.context,event:n}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:u}}const o="function"==typeof t.input?t.input({context:e.context,event:n}):t.input;return{targets:t.target,context:void 0,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function St(t,e,n,i){let r=t;const c=[];function a(t,e){const s=n.self._collectedMicrosteps||[];s.push(...e),n.self._collectedMicrosteps=s,c.push(t)}if(e.type===o)return r=Vt($t(r,n),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),o=r.machine.getTransitionData(r,e,n.self);if(s&&!o.length)return r=Vt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const f=bt(o,t,n,u,!1,i);r=f[0],a(f,o)}let f=!0;const d=t.machine.options?.maxIterations??1/0;let h=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(h++,h>d)throw new Error(`Infinite loop detected (>${d} microsteps)`);let t=f?It(r,u,n):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=r.machine.getTransitionData(r,u,n.self)}const s=bt(t,r,n,u,!1,i);r=s[0],f=r!==e,a(s,t)}return"active"!==r.status&&r.children&&$t(r,n),{snapshot:r,microsteps:c}}function kt(t,e,n,s,o){return!!t.to&&Et(t.to,e,n,s,o,s.machine.implementations)}function Et(t,e,n,s,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:n,self:o,value:s.value,children:s.children,parent:{send:a},actions:i.actions,actors:i.actors,guards:i.guards,delays:i.delays},function(t,e){const n=(t,...n)=>{e(t,...n)};return Object.assign(n,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),n}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function $t(t,e){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return t;for(const t of n)e.stopChild(t);return Vt(t,{children:{}})}function It(t,e,n){const s=new Set,o=t._nodes.filter(H);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(Tt(i,e,t,o,n.self)){s.add(i);break t}return gt(Array.from(s),new Set(t._nodes),t,e,n)}function Tt(t,e,n,s,o){if(t.guard){const i={context:n.context,event:e,self:o,parent:o._parent,children:n.children,actions:s.machine.implementations.actions,actors:s.machine.implementations.actors,guards:s.machine.implementations.guards,delays:s.machine.implementations.delays,_snapshot:n},r=t.guard,c="function"==typeof r?.params?r.params({context:n.context,event:e}):r?.params;let a=!0;if("function"==typeof r)a=r(i,c);else if("string"==typeof r?.type){const t=s.machine.implementations.guards[r.type];if(!t)throw new Error(`Guard '${r.type}' is not implemented in machine '${s.machine.id}'.`);a=t(i,c)}if(!a)return!1}return!t.to||Et(t.to,n.context,e,n,o,s.machine.implementations)}function jt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let At,Ot;function Mt(){return At??=$e()}const Dt=function(t){return qt(t,this.value)},Nt=function(t){return this.tags.has(t)},Pt=function(t){const e=Mt(),n=function(){if(Ot)return Ot;const t=Mt();return Ot={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Ot}(),s=this.machine.getTransitionData(this,t,e);if(!s?.length)return!1;for(const o of s){if(void 0!==o.target)return!0;const s=wt(o,this,t,n);if(s.targets?.length||s.context||kt(o,this.context,t,this,e))return!0}return!1},Rt=function(){const{_nodes:t,_stateInputs:e,tags:n,machine:s,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:u,...f}=this;return{...f,tags:Array.from(n)}},Ct=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Wt=function(){return this._stateInputs};function Lt(t){const e=new Set;for(const n of t)for(const t of n.tags)e.add(t);return e}function zt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??tt(e.root,t._nodes),tags:Lt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:Dt,hasTag:Nt,can:Pt,getMeta:Ct,getInputs:Wt,toJSON:Rt}}function Vt(t,e={}){const n={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:n.status,output:n.output,error:n.error,machine:t.machine,context:n.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:n.children,historyValue:n.historyValue||{},_stateInputs:n._stateInputs||{},matches:Dt,hasTag:Nt,can:Pt,getMeta:Ct,getInputs:Wt,toJSON:Rt}:zt({...n,value:void 0},t.machine)}function Jt(t){const e={};for(const n in t){const s=t[n];Array.isArray(s)&&(e[n]=s.map(t=>({id:t.id})))}return e}function Bt(t){let e;for(const n in t){const s=t[n];if(s&&"object"==typeof s)if("sessionId"in s&&"send"in s&&"ref"in s)e??=Array.isArray(t)?t.slice():{...t},e[n]={xstate$$type:he,id:s.id};else{const o=Bt(s);o!==s&&(e??=Array.isArray(t)?t.slice():{...t},e[n]=o)}}return e??t}function qt(t,e){const n=Ut(t),s=Ut(e);return"string"==typeof s?"string"==typeof n&&s===n:"string"==typeof n?n in s:Object.keys(n).every(t=>t in s&&qt(n[t],s[t]))}function Ft(t){if(Kt(t))return t;const e=[];let n="";for(let s=0;s<t.length;s++){switch(t.charCodeAt(s)){case 92:n+=t[s+1],s++;continue;case 46:e.push(n),n="";continue}n+=t[s]}return e.push(n),e}function Ut(t){if(jt(t))return t.value;if("string"!=typeof t)return t;return Gt(Ft(t))}function Gt(t){if(1===t.length)return t[0];const e={};let n=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)n[t[e]]=t[e+1];else{const s=n;n={},s[t[e]]=n}return e}function Xt(t){return Kt(t)?t:[t]}function Zt(t){return void 0===t?[]:Xt(t)}function Ht(t,e,n,s){return"function"==typeof t?t({context:e,event:n,self:s}):t}function Kt(t){return Array.isArray(t)}function Qt(t){return Xt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function Yt(t){if(void 0!==t&&""!==t)return Zt(t)}function te(t,e,n){const s="object"==typeof t,o=s?t:void 0;return{next:(s?t.next:t)?.bind(o),error:(s?t.error:e)?.bind(o),complete:(s?t.complete:n)?.bind(o)}}function ee(t,e){const n=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return t.implementations.actors[e];const[,s,o]=n,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[s]:i).src;return"string"==typeof r?t.implementations.actors[r]:r}function ne(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const n=e.split("."),s=t.split(".");for(let t=0;t<n.length;t++){const e=n[t],o=s[t];if("*"===e){return t===n.length-1}if(e!==o)return!1}return!0}function se(t,e){return`${t.sessionId}.${e}`}const oe=new WeakMap,ie="xstate.logic.effect.resolve",re="xstate.logic.effect.reject",ce="xstate.logic.effect.start";function ae(t){let e=oe.get(t);return e||(e=new Map,oe.set(t,e)),e}function ue(t,e){if(t?.length)for(const n of t)switch(n.type){case"emit":e.emit(n.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,n.event);break}case"raise":e.system._relay(e.self,e.self,n.event);break;case"effect":{if(!n.key){const t=n.exec();"function"==typeof t&&ae(e.self).set(Symbol(),{cleanup:t});break}const t=ae(e.self);if(t.has(n.key))break;const s=n.exec();t.set(n.key,{cleanup:"function"==typeof s?s:void 0});break}case"cleanupEffects":{const t=oe.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();oe.delete(e.self);break}}}function fe(t){const e=(e,n,s)=>{if("active"!==e.status)return[e,[]];if(n.type===o)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if(n.type===ce)return[{...e,effects:{...e.effects,[n.key]:{status:"active"}}},[]];if(n.type===ie)return[{...e,effects:{...e.effects,[n.key]:{status:"done",output:n.output}}},[]];if(n.type===re)return[{...e,effects:{...e.effects,[n.key]:{status:"error",error:n.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,n)=>{if("string"==typeof t)return s=t,o=n,void(e.effects?.[s]||(i.push({type:"effect",key:s,exec:o}),r[s]={status:"active"}));var s,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:n,input:e.input,system:s.system,self:s.self,emit:s.emit},c),u={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(u.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(u.effects={...e.effects,...a?.effects,...r}),[u,i]};return{id:t.id,config:t,transition:e,start:(t,n)=>{const[s,o]=e(t,c(t.input),n);Object.assign(t,s),ue(o,n)},getInitialSnapshot:(e,n)=>{const s=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,n),o={status:"active",output:void 0,error:void 0,input:n};return void 0!==s&&(o.context=s),{...o}},getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}let de=!1;const he=1;let le=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const pe={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};class ye{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new n(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=le.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const s={...pe,...e},{clock:o,logger:i,parent:r,syncSnapshot:c,id:u,systemId:f,inspect:d}=s;this.system=r?r.system:function(t,e){let n=0;const s=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:u}=e,f=(t,e,n,s,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:n,delay:s,id:o})},d={schedule:(t,e,n,s,o=Math.random().toString(36).slice(2))=>{f(t,e,n,s,o);const i={source:t,target:e,event:n,delay:s,id:o,startedAt:Date.now()},r=se(t,o);l._snapshot._scheduledEvents[r]=i;const u=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],h(t,e,n)},s);c[r]=u},cancel:(t,e)=>{const n=se(t,e),s=c[n];delete c[n],delete l._snapshot._scheduledEvents[n],void 0!==s&&a.clearTimeout(s)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const n=l._snapshot._scheduledEvents[e];n.source===t&&d.cancel(t,n.id)}}},h=(t,e,n)=>{const s=e.logic;if("function"==typeof s?.isInternalEventType&&s.isInternalEventType(n.type)&&t!==e)throw new Error(`Internal event "${n.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(n)},l={children:s,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+n++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const n=o.get(t);if(n&&n!==e)throw new Error(`Actor with system ID '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=te(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const n={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(n))},_relay:(t,e,n)=>{f(t,e,n),h(t,e,n)},scheduler:d,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:n,target:s,event:o,delay:i,id:r}=t[e];d.schedule(n,s,o,i,r)}},_clock:a,_logger:u,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:s.timers}),d&&!r&&this.system.inspect(te(d)),this.sessionId=this.system._bookId(),this.id=u??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=s,this.src=s.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),n=this.eventListeners.get("*");if(e||n){if(e)for(const n of e)try{n(t)}catch(t){a(t)}if(n)for(const e of n)try{e(t)}catch(t){a(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=de;try{de=!0,t.exec()}finally{de=e}};this._processingStatus===le.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),f&&(this.systemId=f,this.system._set(f,this)),this._collectedMicrosteps=[];let h=e?.snapshot??e?.state;if(h&&"object"==typeof h&&"_pendingEffects"in h){const{_pendingEffects:t,...e}=h;this._pendingEffects=t,h=e}try{this._snapshot=h?this.logic.restoreSnapshot?this.logic.restoreSnapshot(h,this._actorScope):h:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}f&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){a(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const n=this._deferred[e];try{n()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(n=this.id,s=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:s,actorId:n});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var n,s;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}subscribe(t,e,n){const s=te(t,e,n);if(this._processingStatus!==le.Stopped)this.observers.add(s);else switch(this._snapshot.status){case"done":try{s.complete?.()}catch(t){a(t)}break;case"error":{const t=this._snapshot.error;if(s.error)try{s.error(t)}catch(t){a(t)}else a(t);break}}return{unsubscribe:()=>{this.observers.delete(s)}}}on(t,e){let n=this.eventListeners.get(t);return n||(n=new Set,this.eventListeners.set(t,n)),n.add(e),{unsubscribe:()=>{n.delete(e)}}}select(t,e=Object.is){return{subscribe:(n,s,o)=>{const i=te(n,s,o);let r=t(this.getSnapshot());return this.subscribe({next:n=>{const s=t(n);e(r,s)||(r=s,i.next?.(s))},error:i.error,complete:i.complete})},get:()=>t(this.get())}}start(){if(this._processingStatus===le.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=le.Running;const t=c(this.options.input);this._lastSourceRef=this._parent;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._setErrorSnapshot(t),this._error(t),this}if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,ge(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){n={err:t}}if(n){const{err:t}=n;return this._setErrorSnapshot(t),void this._error(t)}const[s,i]=Array.isArray(e)?e:[e,void 0];this.update(s,t),ue(i,this._actorScope),t.type===o&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===le.Stopped?this:(this.mailbox.clear(),this._processingStatus===le.NotStarted?(this._processingStatus=le.Stopped,this):(this.mailbox.enqueue({type:o}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){a(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const n of this.observers){const s=n.error;e||=!s;try{s?.(t)}catch(t){a(t)}}this.observers.clear(),this.eventListeners.clear(),e&&a(t)}else this._parent||a(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===le.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new n(this._boundProcess),this._processingStatus=le.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==le.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:he,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),n=this.system._snapshot._scheduledEvents;let s;const o=Date.now();for(const t in n){const e=n[t];e.source===this&&e.target===this&&(s??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return s??=this._pendingEffects,s?{...e,_pendingEffects:s}:e}[u](){return this}getSnapshot(){return this.get()}get(){return e?.(this),this._snapshot}}function ge(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function ve(t,e){return new ye(t,e)}const me=new WeakMap;const _e="xstate.observable.next",xe="xstate.observable.error",be="xstate.observable.complete";const we="xstate.async.resolve",Se="xstate.async.reject";class ke extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Ee=fe({context:void 0,run:()=>{}});function $e(){return ve(Ee)}function Ie(t,{machine:e,context:n},s,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=ee(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=ve(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:n,event:s,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return ve(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==le.Stopped&&c.start()}),c}}const Te=new WeakMap;function je(t,e,n){let s=Te.get(t);return s?e in s||(s[e]=n()):(s={[e]:n()},Te.set(t,s)),s[e]}const Ae={},Oe=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class Me{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const n=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==n?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const n of Oe)if(void 0!==e[n])throw new Error(`Choice state "${t.id}" cannot declare \`${n}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const n={},s=Object.keys(t);for(let o=0;o<s.length;o++){const i=s[o];n[i]=e(t[i],i,t,o)}return n}(this.config.states,(t,e)=>new Me(t,{_parent:this,_key:e,_machine:this.machine})):Ae,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Zt(t.tags).slice(),this.invoke=Zt(this.config.invoke).map((t,e)=>{const{src:n,systemId:s}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof n?n:`xstate.invoke.${o}`;return{...t,src:c,logic:n,id:r,systemId:s}})}_initialize(){this.after=function(t){const e=t.config.after,n=t.config.timeout,s=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===n&&0===o.length)return[];const r=e=>{const n={type:`xstate.after.${e}.${t.id}`};return st(t,n,n=>Z(e,n.delays,{context:n.context,event:n.event,stateNode:t}))},c=[],a=(t,e,n)=>{for(const s of Qt(t))c.push({...s,event:e,delay:n})};if(e)for(const n of Object.keys(e)){const s=e[n],o=Number.isNaN(+n)?n:+n;a(s,r(o),X(o,t.machine.implementations.delays))}if(void 0!==n&&s){const e={type:`xstate.timeout.${t.id}`};a(s,st(t,e,e=>Z(n,e.delays,{context:e.context,event:e.event,stateNode:t})),"function"==typeof n?n:X(n,t.machine.implementations.delays))}for(const e of o){const n=i(e.id),s=e.timeout,o=st(t,n,e=>Z(s,{},{context:e.context,event:e.event,stateNode:t}));a(e.onTimeout,o,s)}return c.map(e=>({...ot(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(""===n)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=t.config.on[n];e.set(n,De(s,e=>ot(t,n,e)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,De(t.config.onDone,e=>ot(t,n,e)))}const n=(e,n)=>ot(t,e,{to:(t,e)=>(e.cancel(n),{})}),s=(e,n,s)=>{const{target:o,to:i,reenter:r,...c}=n;return ot(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let n=!1;const o=new Proxy(e,{apply:(t,e,s)=>(n=!0,Reflect.apply(t,e,s)),get(t,e,s){const o=Reflect.get(t,e,s);return"function"!=typeof o?o:(...e)=>(n=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||n)&&e.cancel(s),r}return e.cancel(s),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=De(o.onDone,e=>r?s(i,e,r):ot(t,i,e));r&&c.push(n(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[n(t,r)])}if(o.onError){const n=`xstate.error.actor.${o.id}`;e.set(n,De(o.onError,e=>r?s(n,e,r):ot(t,n,e)))}if(o.onSnapshot){const n=`xstate.snapshot.${o.id}`;e.set(n,De(o.onSnapshot,e=>ot(t,n,e)))}}for(const n of t.after){let t=e.get(n.eventType);t||(t=[],e.set(n.eventType,t)),t.push(n)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,n=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const n of["actions","to","context"])if(void 0!==e[n])throw new Error(`Choice state "${t.id}" cannot declare \`${n}\` on a choice.`);return e};return[ot(t,"",{to:t=>n(e(t))})]}(this):this.config.always&&(this.always=De(this.config.always,t=>ot(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[n,s]of this.transitions)t[n]=s.slice(),s.some(t=>t.target||t.reenter||t.to)&&e.push(n);this.on=t,this.ownEvents=e;const n=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)n.add(e);this.events=Array.from(n)}get initial(){return je(this,"initial",()=>function(t,e){const n="object"==typeof e&&null!==e?e.target:e,s="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof n?t.states[n]:void 0;if(!o&&n)throw new Error(`Initial state node "${n}" not found on parent state node #${t.id}`);const i={source:t,target:o?[o]:void 0,input:s};return i}(this,this.config.initial))}next(t,e,n){const s=e.type,o=je(this,`candidates-${s}`,()=>function(t,e){const n=t.transitions.get(e);if(n)return n;const s=[];for(const n of t.transitions.keys())ne(e,n)&&s.push(n);s.sort((t,e)=>e.length-t.length);const o=[];for(const e of s)o.push(...t.transitions.get(e));return o}(this,s));for(const s of o){if(Tt(s,e,t,this,n))return[s]}}}function De(t,e){const n=Qt(t),s=new Array(n.length);for(let t=0;t<n.length;t++)s[t]=e(n[t]);return s}class Ne{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.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 Me(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],n=s=>{Object.values(s).forEach(s=>{if(s.config.route&&s.config.id){const o=s.config.id,i=s.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(ot(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(s.states&&n(s.states));if("$unserializable"in i)throw new Error(`State "${s.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const c=i.guard,a={...i,guard:c?e=>{if(!r(e))return!1;if("function"==typeof c)return c(e);if("string"==typeof c){const n=e.guards?.[c];if(!n)throw new Error(`Guard '${c}' is not implemented in machine '${t.machine.id}'.`);return n(e)}return!0}:r,target:`#${o}`};e.push(ot(t,"xstate.route",a))}s.states&&n(s.states)})};n(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:n,actors:s,delays:o}=this.implementations,i=new Ne(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...s,...t.actors},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(n=this.root,s=t.value,tt(n,Y(dt(n,s))));var n,s;const o=Y(dt(this.root,e));return zt({_nodes:[...o],value:e,context:t.context||{},children:{},status:et(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return St(t,e,n,[]).snapshot}microstep(t,e,n){const{microsteps:s}=St(t,e,n,[]),o=new Array(s.length);for(let t=0;t<s.length;t++)o[t]=s[t][0];return o}getTransitionData(t,e,n){return ht(this.root,t.value,t,e,n)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(ne(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:n}=this.config,s=zt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){const o={},i=n({spawn:Ie(t,s,e,o),input:e.input,self:t.self,actors:this.implementations.actors}),r=B(s,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return s}getInitialSnapshot(t,e){const n=c(e),s=[],o=this._getPreInitialState(t,n),[i]=xt(this.root,o,t,n,s),{snapshot:r}=St(i,n,t,s);return r}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=Ft(t),n=e.slice(1),s=nt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(s);if(!o)throw new Error(`Child state node '#${s}' does not exist on machine '${this.id}'`);return ft(o,n)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:n,_stateInputs:s,tags:o,machine:i,children:r,context:c,can:a,hasTag:u,matches:f,getMeta:d,getInputs:h,toJSON:l,...p}=t,y={};for(const t in r){const n=r[t];y[t]={snapshot:n.getPersistedSnapshot(e),src:n.src,systemId:n.systemId,syncSnapshot:n._syncSnapshot}}const g={...p,context:Bt(c),children:y,historyValue:Jt(p.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const n=t.version;if(n!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${n}' does not match machine version '${this.version}'.`);t=e(t,n)}const s=t,o={},i=s.children;for(const t of Object.keys(i)){const n=i[t],s=n.snapshot,r=n.src,c="string"==typeof r?ee(this,r):r;if(!c)continue;const a=ve(c,{id:t,parent:e.self,syncSnapshot:n.syncSnapshot,snapshot:s,src:r,systemId:n.systemId});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const n of Object.keys(t)){const s=t[n];for(const t of s){let s;if(t instanceof Me)s=t;else try{s=this.root.machine.getStateNodeById(t.id)}catch{}s&&(e[n]??=[],e[n].push(s))}}return e})(s.historyValue),c=Array.from(Y(dt(this.root,s.value))),{version:a,...u}=t,f=zt({...u,children:o,_nodes:c,value:s.value,historyValue:r},this),d=new WeakSet;return function t(e){if(!d.has(e)){d.add(e);for(const n of Object.keys(e)){const s=e[n];if(s&&"object"==typeof s){if("xstate$$type"in s&&s.xstate$$type===he){e[n]=o[s.id];continue}t(s)}}}}(f.context),f}}function Pe(t){return new Ne(t)}function Re(t){const e=G(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function Ce(t){return!!t&&"object"==typeof t&&"$unserializable"in t&&"string"==typeof t.$unserializable}function We(t,e="$"){if(Ce(t)){if("actor"===t.$unserializable&&e.endsWith(".src"))return;throw new Error(`Unresolved ${t.$unserializable} at ${e}`)}if(t&&"object"==typeof t)if(Array.isArray(t))t.forEach((t,n)=>We(t,`${e}[${n}]`));else for(const n of Object.keys(t)){const s=t[n];"$"===e&&("actions"===n||"guards"===n||"actors"===n||"delays"===n||"schemas"===n)||We(s,`${e}.${n}`)}}function Le(t){const e={};if(!t)return e;for(const n of Object.keys(t)){const s=t[n];"number"==typeof s&&(e[n]=s)}return e}let ze="session_"+Math.random().toString(36).slice(2),Ve="";function Je(t,e,n,s){const o=`\nwith (context) {\n return (${e});\n}\n `.trim(),i=new Function("context","_event","_sessionid","_name","_ioprocessors","In",o),r=n&&n._scxmlExternal,c=n&&"@xstate.init"===n.type,a=n&&"string"==typeof n.type&&n.type.startsWith("xstate.done."),u=n&&n._scxmlEventType;return i(t,n&&!c?{name:n.type,type:u||(r?"external":"internal"),sendid:n._scxmlSendId,origin:r?"#_scxml_session":void 0,origintype:r?"http://www.w3.org/TR/scxml/#SCXMLEventProcessor":void 0,invokeid:n._scxmlInvokeId,data:a?n.output:void 0!==n._scxmlEventData?n._scxmlEventData:n}:void 0,ze,Ve,{scxml:{location:`#_scxml_${ze}`}},t=>{if(!s)return!1;try{const e=s.getSnapshot?.();if(e?._nodes){const n=t.replace(/\./g,"$");return e._nodes.some(t=>t.id===n||t.id.endsWith("."+n))}}catch{}return!1})}function Be(t,e){const n=Object.keys(t),s=n.map(t=>`let ${t} = context.${t};`).join("\n"),o=n.map(t=>`updates.${t} = ${t};`).join("\n");return new Function("context","updates",`\n${s}\n${e}\n${o}\nreturn updates;\n `)(t,{})}function qe(t){return t.type.startsWith("@xstate.")}const Fe=["id","key","type","history","description","target","version","initial","context","on","after","always","choice","route","onTimeout","timeout","entry","exit","meta","output","tags","input","_scxmlDonedata"];function Ue(t,e){const n={$unserializable:t};return e&&(n.id=e),n}function Ge(t){if("function"==typeof t)return Ue("function",t.name||void 0);if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?Ue("value"):t;if(Array.isArray(t))return t.map(Ge);if(t.constructor!==Object&&void 0!==t.constructor)return Ue("value");const e={};for(const n of Object.keys(t)){const s=t[n];void 0!==s&&(e[n]=Ge(s))}return e}function Xe(t){if(Array.isArray(t))return t.map(Xe);const e=t,n={};for(const t of Object.keys(e)){const s=e[t];void 0!==s&&(n[t]="src"===t&&"string"!=typeof s?Ue("actor",s.id):Ge(s))}return n}function Ze(t,e){if(!t)return;const n={};for(const s of Object.keys(t)){const o=t[s];n[s]="function"==typeof o?Ue("function",s):o&&"object"==typeof o?Ue(e,s):o}return n}function He(t){const e={};for(const n of Fe){const s=t[n];void 0!==s&&(e[n]=Ge(s))}if(void 0!==t.invoke&&(e.invoke=Xe(t.invoke)),t.states){const n={};for(const e of Object.keys(t.states))n[e]=He(t.states[e]);e.states=n}return e}function Ke(t){const e=He(t);if(void 0!==t.internalEvents&&(e.internalEvents=Ge(t.internalEvents)),t.schemas){const n={};for(const e of Object.keys(t.schemas)){const s=t.schemas[e];n[e]=s&&"object"==typeof s&&!("~standard"in s)?Ze(s,"schema"):Ue("schema",e)}e.schemas=n}for(const n of["actions","guards","actors","delays"])t[n]&&(e[n]=Ze(t[n],"actors"===n?"actor":"function"));return e}function Qe(t){const e=ve(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}let Ye=function(t){return t.Internal="#_internal",t}({});const tn={timeout:1/0};t.Actor=ye,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const n=this.getId();return this.timeouts.set(n,{start:this.now(),timeout:e,fn:t}),n}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[n,s])=>{const o=e.start+e.timeout;return s.start+s.timeout>o?-1:1});for(const[e,n]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-n.start>=n.timeout&&(this.timeouts.delete(e),n.fn.call(null))}this._flushing=!1,this._flushingInvalidated&&(this._flushingInvalidated=!1,this.flushTimeouts())}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=Ye,t.StateMachine=Ne,t.StateNode=Me,t.TimeoutError=ke,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.assertEvent=function(t,e){const n=Zt(e);if(!n.some(e=>ne(t.type,e))){const e=1===n.length?`type matching "${n[0]}"`:`one of types matching "${n.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.checkStateIn=function(t,e){if("string"==typeof e&&nt(e)){const n=t.machine.getStateNodeById(e);return t._nodes.some(t=>t===n)}return t.matches(e)},t.createActor=ve,t.createAsyncAtom=function(t,e){const n={};let s,o=0;const i=C(()=>{s?.abort();const e=new AbortController,i=++o;return s=e,t({signal:e.signal}).then(t=>{i!==o||e.signal.aborted||N(n.current,{status:"done",data:t})},t=>{i!==o||e.signal.aborted||N(n.current,{status:"error",error:t})}),{status:"pending"}},{compare:D,...e});return n.current=i,i},t.createAsyncLogic=function(t){const e=t;return fe({id:e.id,schemas:e.schemas,context:void 0,run:({event:t,input:n,self:o,system:i},r)=>{switch(t.type){case we:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Se:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return r.effect(()=>{const t=o,s=new AbortController,c=e.timeout,a=G(c),u=void 0===a?void 0:i._clock.setTimeout(()=>{"active"===o.getSnapshot().status&&(s.abort(),i._relay(t,t,{type:Se,data:new ke(c)}))},a),f=()=>{void 0!==u&&i._clock.clearTimeout(u)},d=Promise.resolve(e.run({input:n,system:i,self:o,signal:s.signal},{emit:r.emit,step:async(e,n)=>{const s=o.getSnapshot().effects?.[e];if("done"===s?.status)return s.output;if("error"===s?.status)throw s.error;if("active"===s?.status)return function(t,e){return new Promise((n,s)=>{const o=t.subscribe(t=>{const i=t.effects?.[e];"done"===i?.status?(o.unsubscribe(),n(i.output)):"error"===i?.status&&(o.unsubscribe(),s(i.error))})})}(o,e);i._relay(t,t,{type:ce,key:e});try{const s=await n();return i._relay(t,t,{type:ie,key:e,output:s}),s}catch(n){throw i._relay(t,t,{type:re,key:e,error:n}),n}}}));return d.then(e=>{f(),"active"===o.getSnapshot().status&&i._relay(t,t,{type:we,data:e})},e=>{f(),"active"===o.getSnapshot().status&&i._relay(t,t,{type:Se,data:e})}),()=>{s.abort(),f()}}),{effects:{async:{status:"active"}}}}})},t.createAtom=C,t.createAtomConfig=function(t,e){return{createAtom:n=>C("function"==typeof t?t(n):t,e)}},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run;return fe({schemas:"function"==typeof t?void 0:t.schemas,context:void 0,run:(t,n)=>{const{event:s,input:o,self:i,system:r}=t,c=t.emit,a=me.get(i);a?.receivers?.forEach(t=>t(s)),n.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return me.set(i,t),t.dispose=e({input:o,system:r,self:i,sendBack:t=>{if("stopped"===i.getSnapshot().status)return;const e=i._parent;e&&r._relay(i,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{me.delete(i),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=$e,t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run;return{config:e,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case xe:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case be:return{...t,status:"done",input:void 0,_subscription:void 0};case o:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(t,{self:n,system:s,emit:o})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:s,self:n,emit:o}).subscribe({next:t=>{n._parent&&s._relay(n,n._parent,t)},error:t=>{s._relay(n,n,{type:xe,data:t})},complete:()=>{s._relay(n,n,{type:be})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.createListenerLogic=p,t.createLogic=fe,t.createMachine=Pe,t.createMachineFromConfig=function t(e,n={}){!function(t,e){for(const n of["actions","guards","actors","delays"]){const s=t[n];if(s)for(const t of Object.keys(s))if(Ce(s[t])&&!e[n]?.[t])throw new Error(`Missing ${n}.${t}`)}}(e,n),We(e);const s=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...Le(t.delays),...e.delays??{}}}}(e,n),o={},i=[];let r=null;const c=[];function a(e){return(Array.isArray(e)?e:[e]).map(e=>{const n=e;let o;if(n._nestedMachineJSON)o=t(n._nestedMachineJSON,s);else if(Ce(e.src)){if(o=e.src.id?s.actors[e.src.id]:void 0,!o)throw new Error(`Missing actors.${e.src.id??""}`)}else o=e.src;return{src:o,id:e.id,systemId:e.systemId,input:e.input,onDone:e.onDone?d(e.onDone):void 0,onError:e.onError?d(e.onError):void 0,onSnapshot:e.onSnapshot?d(e.onSnapshot):void 0,timeout:e.timeout,onTimeout:e.onTimeout?d(e.onTimeout):void 0}})}function u(t,e,n){const s=n instanceof Error?n.message:"string"==typeof n?n:"unknown error";t.enq.raise({type:"error.execution",_scxmlEventType:"platform",_scxmlEventData:{tagname:e,message:s,line:NaN,column:NaN,reason:s}}),t.errored=!0}function f(t,e,n,s){const o=s??{enq:n,errored:!1};let i;for(const s of t){if(o.errored)break;if(qe(s))switch(s.type){case"@xstate.raise":{const t=void 0!==s.delay,e=t||void 0!==s.id?{...s.event,...t?{_scxmlExternal:!0}:{},...void 0!==s.id?{_scxmlSendId:s.id}:{}}:s.event;n.raise(e,{id:s.id,delay:s.delay});break}case"@xstate.cancel":n.cancel(s.id);break;case"@xstate.log":n.log(...s.args);break;case"@xstate.emit":n.emit(s.event);break;case"@xstate.assign":i??={},Object.assign(i,s.context);break;default:throw new Error(`Unknown built-in action: ${s.type}`)}else if("scxml.assign"===s.type){const t=s,n={...e.context,...i};let r;try{r=Je(n,t.expr,e.event,e.self)}catch(t){u(o,"assign",t);continue}if(t.location.includes(".")){u(o,"assign",new Error(`Invalid assign location: ${t.location}`));continue}i??={},i[t.location]=r}else if("scxml.raise"===s.type){const t=s,r={...e.context,...i};let c,a,f,d;try{if(c=t.eventexpr?Je(r,t.eventexpr,e.event,e.self):t.event||"unknown",a={type:c},t.params)for(const n of t.params)a[n.name]=Je(r,n.expr,e.event,e.self);f=t.targetexpr?Je(r,t.targetexpr,e.event,e.self):t.target;const n="#_internal"===f;d=t.delayexpr?Re(Je(r,t.delayexpr,e.event,e.self)):n?void 0:t.delay}catch(t){u(o,"send",t);continue}const h="#_internal"===f,l="#_parent"===f;if("string"==typeof f&&f.length>0&&!f.startsWith("#_")){u(o,"send",new Error(`Invalid send target: ${f}`));continue}if(void 0!==t.id&&(a._scxmlSendId=t.id),l&&e.parent)n.sendTo(e.parent,a,void 0!==d?{delay:d}:void 0);else if("string"!=typeof f||!f.startsWith("#_")||l||h)void 0!==d&&(a._scxmlExternal=!0),n.raise(a,{id:t.id,delay:d});else{const s=f.slice(2),o=e.children?.[s];o?n.sendTo(o,a):(void 0!==d&&(a._scxmlExternal=!0),n.raise(a,{id:t.id,delay:d}))}}else if("scxml.cancel"===s.type){const t=s,o={...e.context,...i};try{const s=Je(o,t.sendidexpr,e.event,e.self);s&&n.cancel(s)}catch{}}else if("scxml.script"===s.type){const t=s,n={...e.context,...i};try{const e=Be(n,t.code);i??={},Object.assign(i,e)}catch(t){u(o,"script",t)}}else if("scxml.foreach"===s.type){const t=s,r={...e.context,...i},c=t=>/^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(t);if(!c(t.item)||t.index&&!c(t.index)){u(o,"foreach",new Error("foreach item/index is not a legal location"));continue}let a;try{a=Je(r,t.array,e.event,e.self)}catch(t){u(o,"foreach",t);continue}if(!Array.isArray(a)){u(o,"foreach",new Error("foreach array is not iterable"));continue}i??={};for(let s=0;s<a.length;s++){i[t.item]=a[s],t.index&&(i[t.index]=s);const r={...e,context:{...e.context,...i}},c=f(t.actions,r,n,o);if(c.context&&Object.assign(i,c.context),o.errored)break}}else if("scxml.block"===s.type){const t=s,o={...e,context:{...e.context,...i}},r=f(t.actions,o,n);if(r.context){i??={};for(const t of Object.keys(r.context))r.context[t]!==e.context[t]&&(i[t]=r.context[t])}}else if("scxml.if"===s.type){const t=s,r={...e.context,...i};for(const s of t.branches){let t;if(s.cond)try{t=!!Je(r,s.cond,e.event,e.self)}catch(e){u(o,"if",e),t=!1}else t=!0;if(t){if(s.actions.length){const t={...e,context:r},c=f(s.actions,t,n,o);if(c.context){i??={};for(const t of Object.keys(c.context))c.context[t]!==e.context[t]&&(i[t]=c.context[t])}}break}}}else n(e.actions[s.type],s.params)}return{context:i?{...e.context,...i}:void 0,errored:o.errored}}function d(t){return(Array.isArray(t)?t:[t]).map(t=>{const e=Array.isArray(t.target)?t.target[0]:t.target,n=t.target;return t.guard||t.actions?.length?t.guard&&!t.actions?.length?{target:n,guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input}:e?{guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input,to:(s,r)=>{if(t.actions?.length){const n=e.replace(/^#/,"");o[n]=t.actions,i.includes(t.actions)||i.push(t.actions)}return{target:n,reenter:t.reenter}}}:{guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input,to:(e,n)=>{if(t.actions?.length){i.includes(t.actions)||i.push(t.actions),r??=e.context;const s=f(t.actions,e,n);if(s.context)return{context:s.context}}return{}}}:{target:n,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input}})}const h=function t(e,n){const s=e.entry,u=e.id||n;var h,l;return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:e.timeout,states:e.states?Object.entries(e.states).reduce((e,[n,s])=>(e[n]=t(s,n),e),{}):void 0,on:e.on?Object.entries(e.on).reduce((t,[e,n])=>(t[e]=d(n),t),{}):void 0,always:e.always?d(e.always):void 0,choice:e.choice?d(e.choice):void 0,route:e.route,after:e.after?Object.entries(e.after).reduce((t,[e,n])=>(t[e]=d(n),t),{}):void 0,onTimeout:e.onTimeout?d(e.onTimeout):void 0,entry:(t,e)=>{for(;c.length;){const t=c.shift();e.raise({type:"error.execution",_scxmlEventType:"platform",_scxmlEventData:t})}let n;if(r&&i.length>0&&Object.keys(o).length>0){let s=r;for(const n of i){const o=f(n,{...t,context:s},e);o.context&&(s=o.context)}i.length=0,r=null;for(const t of Object.keys(o))delete o[t];n=s}else{const s=u?o[u]:void 0;if(s){delete o[u];const i=f(s,t,e);i.context&&(n=i.context)}r=null,i.length=0}if(s?.length){const o=n?{...t,context:n}:t,i=f(s,o,e);i.context&&(n=i.context)}return{context:n}},exit:e.exit?(l=e.exit,(t,e)=>f(l,t,e)):void 0,invoke:e.invoke?a(e.invoke):void 0,meta:e.meta,output:e._scxmlDonedata?(h=e._scxmlDonedata,({context:t,event:e,self:n})=>{try{if(h.params&&h.params.length){const s={};for(const o of h.params)s[o.name]=Je(t,o.expr,e,n);return s}if(void 0!==h.contentExpr)return Je(t,h.contentExpr,e,n);if(void 0!==h.contentText)try{return Je(t,h.contentText,e,n)}catch{return h.contentText}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";c.push({tagname:"donedata",message:e,line:NaN,column:NaN,reason:e})}}):e.output}}(e),l=e.context?{context:e.context}:{};Ve=e.id||"",ze="session_"+Math.random().toString(36).slice(2);const p=Pe({...h,...l,version:e.version}),y={"scxml.cond":({context:t,event:e,self:n},s)=>{const o=s?.expr;if(!o)return!0;try{return!!Je(t,o,e,n)}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";return c.push({tagname:"cond",message:e,line:NaN,column:NaN,reason:e}),!1}},"xstate.stateIn":(t,e)=>{const n=e?.stateId;if(!n)return!1;const s=n.replace(/^#/,""),o=t._snapshot;return!!o?._nodes&&o._nodes.some(t=>t.id===s)},"xstate.not":(t,e)=>{const n=e?.guard,s=n&&y[n.type];if(!s)throw new Error(`Guard '${n?.type}' referenced by 'xstate.not' is not implemented.`);return!s(t,n.params)}},g=p.provide({actions:s.actions,actors:s.actors,guards:{...y,...s.guards},delays:s.delays});return g._json=e,g},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run;return fe({schemas:"function"==typeof t?void 0:t.schemas,context:void 0,run:(t,n)=>{const{event:s,input:o,self:i,system:r}=t,c=t.emit;switch(s.type){case _e:return{context:s.data};case xe:return{status:"error",error:s.data,input:void 0,effects:{observable:{status:"error",error:s.data}}};case be:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}n.effect("observable",()=>{const t=i,n=e({input:o,system:r,self:i,emit:c}).subscribe({next:e=>{r._relay(t,t,{type:_e,data:e})},error:e=>{r._relay(t,t,{type:xe,data:e})},complete:()=>{r._relay(t,t,{type:be})}});return()=>n.unsubscribe()})}})},t.createReducerAtom=function(t,e,n){const s=C(t,n);return{[v]:!0,get:s.get.bind(s),subscribe:s.subscribe.bind(s),send(t){const n=T;let o;T=void 0;try{o=e(s.get(),t)}finally{T=n}s.set(o)}}},t.createStateConfig=function(t){return t},t.createSubscriptionLogic=W,t.getInitialMicrosteps=function(t,...[e]){const n=Qe(t),s=c(e),o=[],i=t._getPreInitialState(n,s),r=xt(t.root,i,n,s,o),{microsteps:a}=St(r[0],s,n,o);return[r,...a]},t.getInitialSnapshot=function(t,...[e]){const n=Qe(t);return t.getInitialSnapshot(n,e)},t.getMicrosteps=function(t,e,n){const s=Qe(t),{microsteps:o}=St(e,n,s,[]);return o},t.getNextSnapshot=function(t,e,n){const s=Qe(t);s.self._snapshot=e;const o=t.transition(e,n,s);return Array.isArray(o)?o[0]:o},t.getNextTransitions=function(t){const e=[],n=t._nodes.filter(H),s=new Set;for(const t of n)for(const n of[t].concat(Q(t,void 0)))if(!s.has(n.id)){s.add(n.id);for(const[,t]of n.transitions.entries())e.push(...t);n.always&&e.push(...n.always)}return e},t.getStateNodes=dt,t.initialTransition=function(t,...[e]){const n=[],s=Qe(t);return s.actionExecutor=t=>{n.push(t)},[t.getInitialSnapshot(s,e),n]},t.isAtom=m,t.isMachineSnapshot=jt,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.listenerLogic=y,t.machineConfigToJSON=Ke,t.mapState=function(t,e){const n=[],s=(t,e)=>{let n=t;for(const t of e){if(!n?.states)return;const e=n.states;if(!(t in e))return;n=e[t]}return n},o=new Set;for(const i of t._nodes.filter(H)){let r=i;for(;r&&!o.has(r);){o.add(r);const i=s(e,r.path);i?.map&&n.push({stateNode:r,result:i.map(t)}),r=r.parent}}return n},t.matchesState=qt,t.pathToStateValue=Gt,t.serializeMachine=function(t){return t._json??Ke(t.config)},t.setup=function(t={}){const{states:e={},schemas:n}=t;return{createMachine(t){const e=t.schemas,s=n||e?{...e,...n}:void 0;return new Ne(s?{...t,schemas:s}:t)},createStateConfig:t=>t,states:e}},t.subscriptionLogic=L,t.toObserver=te,t.toPromise=function(t){return new Promise((e,n)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:n})})},t.transition=function(t,e,n){const s=[],o=Qe(t);o.actionExecutor=t=>{s.push(t)};const i=t.transition(e,n,o),[r,c]=Array.isArray(i)?i:[i,[]];return[r,s.concat(c)]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,e,n){const s={...tn,...n};return new Promise((n,o)=>{const{signal:i}=s;if(i?.aborted)return void o(i.reason);let r=!1;const c=s.timeout===1/0?void 0:setTimeout(()=>{a(),o(new Error(`Timeout of ${s.timeout} ms exceeded`))},s.timeout),a=()=>{clearTimeout(c),r=!0,d?.unsubscribe(),f&&i.removeEventListener("abort",f)};function u(t){e(t)&&(a(),n(t))}let f,d;u(t.getSnapshot()),r||(i&&(f=()=>{a(),o(i.reason)},i.addEventListener("abort",f)),d=t.subscribe({next:u,error:t=>{a(),o(t)},complete:()=>{a(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&d.unsubscribe())})},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).XState={})}(this,function(t){"use strict";let e;class n{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",o="@xstate.stop";function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t){return{type:s,input:t}}function a(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable",f={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,n)=>{t.system.scheduler.schedule(t.self,t.self,e,n?.delay??0,n?.id)},"@xstate.sendTo":(t,e,n,s)=>{if("string"==typeof n)throw new Error("Only event objects may be used with sendTo");void 0!==s?.delay?t.system.scheduler.schedule(t.self,e,n,s?.delay??0,s?.id):t.defer(()=>{t.system._relay(t.self,e,n)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stopChild":(t,e)=>{t.stopChild(e)}},d=new WeakMap;function h(t){return{start:(e,{self:n,system:s})=>{const o=e.input.actor;if(!o||"function"==typeof o.getSnapshot&&"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:n,system:s});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},u=n._parent;u&&(r=u.subscribe({complete:a,error:a})),d.set(n,{unsubscribe:a})},transition:(t,e,{self:n})=>e.type===o?(d.get(n)?.unsubscribe(),d.delete(n),{...t,status:"stopped",error:void 0}):t,getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,n){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,n())}function p(){return h(({actor:t,eventType:e,mapper:n},{self:s,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!ne(t.type,e)||l(s,o,()=>n(t))})})}const y=p();let g=function(t){return t[t.None=0]="None",t[t.Mutable=1]="Mutable",t[t.Watching=2]="Watching",t[t.RecursedCheck=4]="RecursedCheck",t[t.Recursed=8]="Recursed",t[t.Dirty=16]="Dirty",t[t.Pending=32]="Pending",t}({});const v=Symbol.for("xstate.atom");function m(t){return!!t&&"object"==typeof t&&v in t}const _=[];let x,b,w,S,k,E=0,$=!1;function I(){$||($=!0,({link:x,unlink:b,propagate:w,checkDirty:S,shallowPropagate:k}=function({update:t,notify:e,unwatched:n}){return{link:function(t,e,n){const s=e.depsTail;if(void 0!==s&&s.dep===t)return;const o=void 0!==s?s.nextDep:e.deps;if(void 0!==o&&o.dep===t)return o.version=n,void(e.depsTail=o);const i=t.subsTail;if(void 0!==i&&i.version===n&&i.sub===e)return;const r=e.depsTail=t.subsTail={version:n,dep:t,sub:e,prevDep:s,nextDep:o,prevSub:i,nextSub:void 0};void 0!==o&&(o.prevDep=r),void 0!==s?s.nextDep=r:e.deps=r,void 0!==i?i.nextSub=r:t.subs=r},unlink:function(t,e=t.sub){const s=t.dep,o=t.prevDep,i=t.nextDep,r=t.nextSub,c=t.prevSub;return void 0!==i?i.prevDep=o:e.depsTail=o,void 0!==o?o.nextDep=i:e.deps=i,void 0!==r?r.prevSub=c:s.subsTail=c,void 0!==c?c.nextSub=r:void 0===(s.subs=r)&&n(s),i},propagate:function(t){let n,s=t.nextSub;t:for(;;){const i=t.sub;let r=i.flags;if(r&(g.RecursedCheck|g.Recursed|g.Dirty|g.Pending)?r&(g.RecursedCheck|g.Recursed)?r&g.RecursedCheck?r&(g.Dirty|g.Pending)||!o(t,i)?r=g.None:(i.flags=r|g.Recursed|g.Pending,r&=g.Mutable):i.flags=r&~g.Recursed|g.Pending:r=g.None:i.flags=r|g.Pending,r&g.Watching&&e(i),r&g.Mutable){const e=i.subs;if(void 0!==e){const o=(t=e).nextSub;void 0!==o&&(n={value:s,prev:n},s=o);continue}}if(void 0===(t=s)){for(;void 0!==n;)if(t=n.value,n=n.prev,void 0!==t){s=t.nextSub;continue t}break}s=t.nextSub}},checkDirty:function(e,n){let o,i=0,r=!1;t:for(;;){const c=e.dep,a=c.flags;if(n.flags&g.Dirty)r=!0;else if((a&(g.Mutable|g.Dirty))===(g.Mutable|g.Dirty)){if(t(c)){const t=c.subs;void 0!==t.nextSub&&s(t),r=!0}}else if((a&(g.Mutable|g.Pending))===(g.Mutable|g.Pending)){void 0===e.nextSub&&void 0===e.prevSub||(o={value:e,prev:o}),e=c.deps,n=c,++i;continue}if(!r){const t=e.nextDep;if(void 0!==t){e=t;continue}}for(;i--;){const i=n.subs,c=void 0!==i.nextSub;if(c?(e=o.value,o=o.prev):e=i,r){if(t(n)){c&&s(i),n=e.sub;continue}r=!1}else n.flags&=~g.Pending;n=e.sub;const a=e.nextDep;if(void 0!==a){e=a;continue t}}return r}},shallowPropagate:s};function s(t){do{const n=t.sub,s=n.flags;(s&(g.Pending|g.Dirty))===g.Pending&&(n.flags=s|g.Dirty,(s&(g.Watching|g.RecursedCheck))===g.Watching&&e(n))}while(void 0!==(t=t.nextSub))}function o(t,e){let n=e.depsTail;for(;void 0!==n;){if(n===t)return!0;n=n.prevDep}return!1}}({update:t=>t._update(),notify(t){_[A++]=t,t.flags&=~g.Watching},unwatched(t){void 0!==t.depsTail&&(t.depsTail=void 0,t.flags=g.Mutable|g.Dirty,O(t))}})))}let T,j=0,A=0;function O(t){const e=t.depsTail;let n=void 0!==e?e.nextDep:t.deps;for(;void 0!==n;)n=b(n,t)}function M(){for(;j<A;){const t=_[j];_[j++]=void 0,t.notify()}j=0,A=0}function D(t,e){return t.status===e.status&&("done"===t.status&&"done"===e.status?Object.is(t.data,e.data):"error"!==t.status||"error"!==e.status||Object.is(t.error,e.error))}function N(t,e){if(t._update(e)){const e=t.subs;void 0!==e&&(w(e),k(e),M())}}let P=!1;function R(){if(P)return;P=!0;const t=new WeakMap;e=e=>{if(void 0===T)return;let n=t.get(e);void 0===n&&(n=C(0),t.set(e,n),e.subscribe({next:()=>n.set(t=>t+1),error:()=>{}})),n.get()}}function C(t,e){I(),R();const n="function"==typeof t,s=t,o={_snapshot:n?void 0:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:n?g.None:g.Mutable,get:()=>(void 0!==T&&x(o,T,E),o._snapshot),subscribe(t){const e="function"==typeof t?{next:t}:t,n={current:!1},s=function(t){const e=()=>{const e=T;T=n,++E,n.depsTail=void 0,n.flags=g.Watching|g.RecursedCheck;try{return t()}finally{T=e,n.flags&=~g.RecursedCheck,O(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:g.Watching|g.RecursedCheck,notify(){const t=this.flags;t&g.Dirty||t&g.Pending&&S(this.deps,this)?e():this.flags=g.Watching},stop(){this.flags=g.None,this.depsTail=void 0,O(this)}};return e(),n}(()=>{if(o.get(),n.current){const t=T;T=void 0;try{e.next?.(o._snapshot)}catch(t){a(t)}finally{T=t}o.get()}else n.current=!0});return{unsubscribe:()=>{s.stop()}}},_update(t){const i=T,r=e?.compare??Object.is;T=o,++E,o.depsTail=void 0,n&&(o.flags=g.Mutable|g.RecursedCheck);try{const e=o._snapshot,i="function"==typeof t?t(e):void 0===t&&n?s(e):t;return(void 0===e||!r(e,i))&&(o._snapshot=i,!0)}finally{T=i,n&&(o.flags&=~g.RecursedCheck),O(o)}}};return n?(o.flags=g.Mutable|g.Dirty,o.get=function(){const t=o.flags;if(t&g.Dirty||t&g.Pending&&S(o.deps,o)){if(o._update()){const t=o.subs;void 0!==t&&k(t)}}else t&g.Pending&&(o.flags=t&~g.Pending);return void 0!==T&&x(o,T,E),o._snapshot}):o.set=function(t){if(o._update(t)){const t=o.subs;void 0!==t&&(w(t),k(t),M())}},o[v]=!0,o}function W(){return h(({actor:t,mappers:e},{self:n,system:s})=>{const{done:o,error:i,snapshot:r}=e;if(m(t)){if(!r)return;return t.subscribe(t=>l(n,s,()=>r(t)))}return t.subscribe({next:t=>{"done"===t.status&&o?l(n,s,()=>o(t.output)):"error"===t.status&&i?l(n,s,()=>i(t.error)):"active"===t.status&&r&&l(n,s,()=>r(t))},error:t=>{i&&l(n,s,()=>i(t))},complete:()=>{}})})}const L=W();function z(t,e,...n){t.push({action:e,args:n})}function V(t,e,n){z(t,f["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(n){return{children:{...n.children,[e]:t}}},{_special:!0})}(e,n??e.id))}function J(t,e,n,s=!1){const o={cancel:n=>{z(e,f["@xstate.cancel"],t,n)},emit:t=>{e.push(t)},log:(...n)=>{z(e,t.logger,...n)},raise:(s,o)=>{if("string"==typeof s)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?z(e,f["@xstate.raise"],t,s,o):n.push(s)},spawn:(n,s)=>{const o=ve(n,{...s,parent:t.self});return V(e,o,s?.id),o},sendTo:(n,s,o)=>{n&&z(e,f["@xstate.sendTo"],t,n,s,o)},stop:n=>{n&&(z(e,f["@xstate.stopChild"],t,n),e.push(function(t){return Object.assign(function(e){const n={...e.children};for(const e of Object.keys(n))n[e]===t&&delete n[e];return{children:n}},{_special:!0})}(n)))}};return s&&Object.assign(o,{listen:(n,s,o)=>{const i=ve(y,{input:{actor:n,eventType:s,mapper:o},parent:t.self});return z(e,f["@xstate.start"],i),i},subscribeTo:(n,s)=>{const o=ve(L,{input:{actor:n,mappers:"function"==typeof s?{snapshot:s}:s},parent:t.self});return z(e,f["@xstate.start"],o),o}}),q(o,(t,...n)=>{z(e,t,...n)})}function B(t,e,n,s){let o=t;for(const i of s){const s="function"==typeof i?i:"object"==typeof i&&"action"in i&&"function"==typeof i.action&&i.action.bind(null,...i.args);s||"object"!=typeof i||null===i||n.defer(()=>{n.emit(i)});const r={context:o.context,event:e,self:n.self,system:n.system,children:o.children,parent:n.self._parent,actions:t.machine.implementations.actions,actors:t.machine.implementations.actors};let c;if("object"==typeof i&&null!==i){const{type:t,...e}=i;c=e}if(s&&"_special"in s){n.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:c,args:[],exec:void 0});const t=s(r,F);t&&("context"in t||"children"in t)&&(o=Vt(o,{..."context"in t?{context:t.context}:{},..."children"in t?{children:t.children}:{}}));continue}s&&"resolve"in s||n.actionExecutor({type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:c,args:"object"==typeof i&&"action"in i?i.args:[],exec:s})}return o}function q(t,e){const n=(t,...n)=>{e(t,...n)};return Object.assign(n,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),n}const F=q({},()=>{});function U(t){const e=t.trim(),n=e.match(/^(\d+)ms$/i);if(n)return parseInt(n[1],10);const s=e.match(/^(\d*)(\.?)(\d*)s$/i);if(s){const t=s[1]?parseInt(s[1],10):0,e=!!s[2],n=s[3]?parseInt(s[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?n:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:u}=o.groups;if(!(i||r||c||a||u))return;const f=t=>t?Number(t.replace(",",".")):0;return 7*f(i)*24*60*60*1e3+24*f(r)*60*60*1e3+60*f(c)*60*1e3+60*f(a)*1e3+1e3*f(u)}function G(t){if(void 0!==t)return"number"==typeof t?t:U(t)}function X(t,e){if("string"!=typeof t)return t;const n=e[t];return void 0!==n?n:U(t)??t}function Z(t,e,n){if("function"==typeof t)return t(n);const s=X(t,e);return"function"==typeof s?s(n):s}function H(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function K(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Q(t,e){const n=[];if(e===t)return n;let s=t.parent;for(;s&&s!==e;)n.push(s),s=s.parent;return n}function Y(t){const e=new Set(t),n=new Set;for(const t of e)t.parent&&n.add(t.parent);for(const t of e)if("compound"!==t.type||n.has(t)){if("parallel"===t.type)for(const n of K(t))if(!e.has(n)){const t=at(n);for(const n of t)e.add(n)}}else for(const n of at(t))e.add(n);for(const t of e){let n=t.parent;for(;n&&!e.has(n);)e.add(n),n=n.parent}return e}function tt(t,e){const n=Y(e),s=new Map;for(const t of n)s.has(t)||s.set(t,[]),t.parent&&(s.has(t.parent)||s.set(t.parent,[]),s.get(t.parent).push(t));const o=t=>{const e=s.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(H(t))return t.key}const n={};for(const t of e)n[t.key]=o(t);return n};return o(t)}function et(t,e){return"compound"===e.type?K(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?K(e).every(e=>et(t,e)):"final"===e.type}const nt=t=>"#"===t[0];function st(t,e,n){const s=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:s,delay:n(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(s),"function"==typeof i?i(t,e):void 0),s}function ot(t,e,n){const s=Yt(n.target),o=n.reenter??!1,i=it(t,s),r={...n,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 it(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(nt(e))return t.machine.getStateNodeById(e);const n="."===e[0];if(n&&!t.parent)return ft(t,e.slice(1));const s=n?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ft(t.parent,s)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function rt(t){const e=Yt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?ft(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function ct(t){return"history"===t.type}function at(t){const e=new Set;!function t(n){if(!e.has(n))if(e.add(n),"compound"===n.type)t(n.initial.target[0]);else if("parallel"===n.type)for(const e of K(n))t(e)}(t);for(const n of e)for(const s of Q(n,t))e.add(s);return e}function ut(t,e){if(nt(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 n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function ft(t,e){if("string"==typeof e&&nt(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Ft(e).slice();let s=t;for(;n.length;){const t=n.shift();if(!t.length)break;s=ut(s,t)}return s}function dt(t,e){if("string"==typeof e){const n=t.states[e];if(!n)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,n]}const n=Object.keys(e),s=new Array(n.length),o=[t.machine.root,t];for(let e=0;e<n.length;e++){const i=ut(t,n[e]);s[e]=i,o.push(i)}for(let t=0;t<n.length;t++)o.push(...dt(s[t],e[n[t]]));return o}function ht(t,e,n,s,o){if("string"==typeof e){const i=ut(t,e).next(n,s,o);return i&&i.length?i:t.next(n,s,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=ht(ut(t,r),e[r],n,s,o);return i&&i.length?i:t.next(n,s,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=ht(ut(t,r),i,n,s,o);a&&c.push(...a)}return c.length?c:t.next(n,s,o)}function lt(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function pt(t,e){for(const n of t)if(lt(n,e))return!0;return!1}function yt(t,e){const n=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,s=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==n&&void 0!==s&&s<n&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function gt(t,e,n,s,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=_t([t],e,n,s,o),r.set(t,i)),i};for(const e of t){let t=!1;const n=new Set;for(const s of i)if(yt(c(e),c(s))){if(!lt(e.source,s.source)){t=!0;break}n.add(s)}if(!t){for(const t of n)i.delete(t);i.add(e)}}return Array.from(i)}function vt(t,e,n,s){const o=e.historyValue,{targets:i}=wt(t,e,n,s);if(!i)return[];const r=new Set;for(const t of i)if(ct(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of vt(rt(t),e,n,s))r.add(o);else r.add(t);return[...r]}function mt(t,e,n,s){const o=vt(t,e,n,s),{reenter:i}=wt(t,e,n,s);if(!i&&o.every(e=>e===t.source||lt(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of Q(r,void 0))if(c.every(e=>lt(e,t)))return t;return i?void 0:t.source.machine.root}function _t(t,e,n,s,o){const i=new Set;for(const r of t){const{targets:t}=wt(r,n,s,o);if(t?.length){const t=mt(r,n,s,o);r.reenter&&r.source===t&&i.add(t);for(const n of e)lt(n,t)&&i.add(n)}}return[...i]}function xt(t,e,n,s,o){return bt([{target:[...at(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,n,s,!0,o)}function bt(t,e,n,s,o,i){const c=[];if(!t.length)return[e,c];const a=n.actionExecutor;n.actionExecutor=t=>{c.push(t),a(t)};try{const a=new Set(e._nodes);let u=e.historyValue;const d=e.context,h=gt(t,a,e,s,n),l=t=>wt(t,e,s,n),p=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let u;const f=J(n,c,a,!0),d=t({context:o,event:s,parent:n.self._parent,self:n.self,children:i,system:n.system,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},f);return d?.context&&(u=d.context),[c,u,a]}return[[Object.assign((e,n)=>t({...e,input:r},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=_t(h,a,e,s,n);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const n="deep"===t.history?t=>H(t)&&lt(t,e):t=>t.parent===e;o??={...u},o[t.id]=r.filter(n)}for(const o of t){const t=e._stateInputs?.[o.id],[r,c,u]=o.exit?p(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),c&&(y=Vt(y,{context:c})),y=B(y,s,n,r);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&n.stopChild(e),delete y.children[t.id]}a.delete(o)}u=o||u};o||g();let v=y.context;const m=[],_=[];for(const t of h){t.actions&&m.push(...Zt(t.actions));const e=l(t);e.context&&(v=e.context),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const x=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=Ht(t.output,y.context,s,n.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,n=i.find(t=>t.type===e);o=n?.output}return Ht(e.output,y.context,r(t.id,o),n.self)},c=new Set,d=new Set,g=(t,e)=>{for(const n of t)if(e&&!lt(n,e)||c.add(n),"parallel"===n.type)for(const t of K(n))pt(c,t)||(c.add(t),v(t))},v=t=>{if(ct(t))if(u[t.id]){const e=u[t.id];for(const t of e)c.add(t),v(t);for(const n of e)g(Q(n,t.parent),void 0)}else{const e=rt(t),{targets:n}=l(e);for(const s of n??[])c.add(s),e===t.parent?.initial&&d.add(t.parent),v(s);for(const e of n??[])g(Q(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return ct(e)||(c.add(e),d.add(e)),v(e),void g(Q(e,t),void 0)}if("parallel"===t.type)for(const e of K(t))pt(c,e)||(c.add(e),d.add(e),v(e))}};for(const t of h){const o=mt(t,e,s,n),{targets:i,reenter:r}=l(t);for(const e of i??[])ct(e)||t.source===e&&t.source===o&&!r||(c.add(e),d.add(e)),v(e);const a=vt(t,e,s,n);for(const e of a){const n=Q(e,o);"parallel"===o?.type&&n.push(o),g(n,!t.source.parent&&r?void 0:o)}}o&&d.add(e.machine.root);const m={...e._stateInputs};for(const t of h){const{targets:e,input:n}=l(t);if(n&&e)for(const t of e)m[t.id]=n}const _=new Set,x={...e.children};for(const o of[...c].sort((t,e)=>t.order-e.order)){a.add(o);const c=[];let u,h=!1;for(const t of o.invoke){h=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.implementations.actors,context:y.context,event:s,self:n.self}));const i="string"==typeof o?ee(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:n.self,context:y.context,event:s}):t.input,a=ve(i,{...t,input:r,parent:n.self,syncSnapshot:!!t.onSnapshot});c.push({action:f["@xstate.start"],args:[a]}),t.id&&(x[t.id]=a)}h&&(y=Vt(y,{children:x}));const l=m[o.id];if(o.entry){const[t,e,n]=p(o.entry,y.context,x,l);c.push(...t),n?.length&&i.push(...n),e&&(u=e)}if(d.has(o)){const{actions:t,input:e}=wt(o.initial,y,s,n);if(t&&c.push(...t),e&&o.initial?.target)for(const t of o.initial.target)m[t.id]=e}if(y=B(y,s,n,c),u&&(y.context=u),"final"!==o.type)continue;const g=o.parent;let v="parallel"===g?.type?g:g?.parent,b=v||o;for("compound"===g?.type&&i.push(r(g.id,void 0!==o.output?Ht(o.output,y.context,s,n.self):void 0));"parallel"===v?.type&&!_.has(v)&&et(a,v);){_.add(v);const t={};for(const e of K(v)){if("final"===e.type){t[e.key]=void 0!==e.output?Ht(e.output,y.context,s,n.self):void 0;continue}if("parallel"===e.type){const n=`xstate.done.state.${e.id}`,s=i.find(t=>t.type===n);t[e.key]=s?.output;continue}const o=K(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Ht(o.output,y.context,s,n.self):void 0}i.push(r(v.id,t)),b=v,v=v.parent}v||(y=Vt(y,{status:"done",output:t(b)}))}JSON.stringify(m)!==JSON.stringify(e._stateInputs||{})&&(y=Vt(y,{_stateInputs:m}))};y=B(y,s,n,m),v&&v!==e.context&&(y=Vt(y,{context:v})),x();const b=[...a];if("done"===y.status){const t=[];b.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const n=y._stateInputs?.[e.id],[s,,o]=p(e.exit,y.context,y.children,n);t.push(...s),o?.length&&i.push(...o)}}),y=B(y,s,n,t)}return u===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==d?[Vt(y),c]:[y,c]:[Vt(y,{_nodes:b,historyValue:u}),c]}finally{n.actionExecutor=a}}function wt(t,e,n,s){if(t.to){const o=[],i=[],r=J(s,o,i),c=t.to({context:e.context,event:n,value:e.value,children:e.children,parent:s.self._parent,self:s.self,actions:e.machine.implementations.actions,actors:e.machine.implementations.actors,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?it(t.source,Zt(c.target)):void 0,u="function"==typeof t.input?t.input({context:e.context,event:n}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:u}}const o="function"==typeof t.input?t.input({context:e.context,event:n}):t.input;return{targets:t.target,context:void 0,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function St(t,e,n,i){let r=t;const c=[];function a(t,e){const s=n.self._collectedMicrosteps||[];s.push(...e),n.self._collectedMicrosteps=s,c.push(t)}if(e.type===o)return r=Vt($t(r,n),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let u=e;if(u.type!==s){const e=u,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),o=r.machine.getTransitionData(r,e,n.self);if(s&&!o.length)return r=Vt(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const f=bt(o,t,n,u,!1,i);r=f[0],a(f,o)}let f=!0;const d=t.machine.options?.maxIterations??1/0;let h=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(h++,h>d)throw new Error(`Infinite loop detected (>${d} microsteps)`);let t=f?It(r,u,n):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;u=i.shift(),t=r.machine.getTransitionData(r,u,n.self)}const s=bt(t,r,n,u,!1,i);r=s[0],f=r!==e,a(s,t)}return"active"!==r.status&&r.children&&$t(r,n),{snapshot:r,microsteps:c}}function kt(t,e,n,s,o){return!!t.to&&Et(t.to,e,n,s,o,s.machine.implementations)}function Et(t,e,n,s,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:n,self:o,value:s.value,children:s.children,parent:{send:a},actions:i.actions,actors:i.actors,guards:i.guards,delays:i.delays},function(t,e){const n=(t,...n)=>{e(t,...n)};return Object.assign(n,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),n}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function $t(t,e){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return t;for(const t of n)e.stopChild(t);return Vt(t,{children:{}})}function It(t,e,n){const s=new Set,o=t._nodes.filter(H);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(Tt(i,e,t,o,n.self)){s.add(i);break t}return gt(Array.from(s),new Set(t._nodes),t,e,n)}function Tt(t,e,n,s,o){if(t.guard){const i={context:n.context,event:e,self:o,parent:o._parent,children:n.children,actions:s.machine.implementations.actions,actors:s.machine.implementations.actors,guards:s.machine.implementations.guards,delays:s.machine.implementations.delays,_snapshot:n},r=t.guard,c="function"==typeof r?.params?r.params({context:n.context,event:e}):r?.params;let a=!0;if("function"==typeof r)a=r(i,c);else if("string"==typeof r?.type){const t=s.machine.implementations.guards[r.type];if(!t)throw new Error(`Guard '${r.type}' is not implemented in machine '${s.machine.id}'.`);a=t(i,c)}if(!a)return!1}return!t.to||Et(t.to,n.context,e,n,o,s.machine.implementations)}function jt(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let At,Ot;function Mt(){return At??=$e()}const Dt=function(t){return qt(t,this.value)},Nt=function(t){return this.tags.has(t)},Pt=function(t){const e=Mt(),n=function(){if(Ot)return Ot;const t=Mt();return Ot={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},Ot}(),s=this.machine.getTransitionData(this,t,e);if(!s?.length)return!1;for(const o of s){if(void 0!==o.target)return!0;const s=wt(o,this,t,n);if(s.targets?.length||s.context||kt(o,this.context,t,this,e))return!0}return!1},Rt=function(){const{_nodes:t,_stateInputs:e,tags:n,machine:s,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:u,...f}=this;return{...f,tags:Array.from(n)}},Ct=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Wt=function(){return this._stateInputs};function Lt(t){const e=new Set;for(const n of t)for(const t of n.tags)e.add(t);return e}function zt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??tt(e.root,t._nodes),tags:Lt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:Dt,hasTag:Nt,can:Pt,getMeta:Ct,getInputs:Wt,toJSON:Rt}}function Vt(t,e={}){const n={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:n.status,output:n.output,error:n.error,machine:t.machine,context:n.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:n.children,historyValue:n.historyValue||{},_stateInputs:n._stateInputs||{},matches:Dt,hasTag:Nt,can:Pt,getMeta:Ct,getInputs:Wt,toJSON:Rt}:zt({...n,value:void 0},t.machine)}function Jt(t){const e={};for(const n in t){const s=t[n];Array.isArray(s)&&(e[n]=s.map(t=>({id:t.id})))}return e}function Bt(t){let e;for(const n in t){const s=t[n];if(s&&"object"==typeof s)if("sessionId"in s&&"send"in s&&"ref"in s)e??=Array.isArray(t)?t.slice():{...t},e[n]={xstate$$type:he,id:s.id};else{const o=Bt(s);o!==s&&(e??=Array.isArray(t)?t.slice():{...t},e[n]=o)}}return e??t}function qt(t,e){const n=Ut(t),s=Ut(e);return"string"==typeof s?"string"==typeof n&&s===n:"string"==typeof n?n in s:Object.keys(n).every(t=>t in s&&qt(n[t],s[t]))}function Ft(t){if(Kt(t))return t;const e=[];let n="";for(let s=0;s<t.length;s++){switch(t.charCodeAt(s)){case 92:n+=t[s+1],s++;continue;case 46:e.push(n),n="";continue}n+=t[s]}return e.push(n),e}function Ut(t){if(jt(t))return t.value;if("string"!=typeof t)return t;return Gt(Ft(t))}function Gt(t){if(1===t.length)return t[0];const e={};let n=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)n[t[e]]=t[e+1];else{const s=n;n={},s[t[e]]=n}return e}function Xt(t){return Kt(t)?t:[t]}function Zt(t){return void 0===t?[]:Xt(t)}function Ht(t,e,n,s){return"function"==typeof t?t({context:e,event:n,self:s}):t}function Kt(t){return Array.isArray(t)}function Qt(t){return Xt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function Yt(t){if(void 0!==t&&""!==t)return Zt(t)}function te(t,e,n){const s="object"==typeof t,o=s?t:void 0;return{next:(s?t.next:t)?.bind(o),error:(s?t.error:e)?.bind(o),complete:(s?t.complete:n)?.bind(o)}}function ee(t,e){const n=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return t.implementations.actors[e];const[,s,o]=n,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[s]:i).src;return"string"==typeof r?t.implementations.actors[r]:r}function ne(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const n=e.split("."),s=t.split(".");for(let t=0;t<n.length;t++){const e=n[t],o=s[t];if("*"===e){return t===n.length-1}if(e!==o)return!1}return!0}function se(t,e){return`${t.sessionId}.${e}`}const oe=new WeakMap,ie="xstate.logic.effect.resolve",re="xstate.logic.effect.reject",ce="xstate.logic.effect.start";function ae(t){let e=oe.get(t);return e||(e=new Map,oe.set(t,e)),e}function ue(t,e){if(t?.length)for(const n of t)switch(n.type){case"emit":e.emit(n.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,n.event);break}case"raise":e.system._relay(e.self,e.self,n.event);break;case"effect":{if(!n.key){const t=n.exec();"function"==typeof t&&ae(e.self).set(Symbol(),{cleanup:t});break}const t=ae(e.self);if(t.has(n.key))break;const s=n.exec();t.set(n.key,{cleanup:"function"==typeof s?s:void 0});break}case"cleanupEffects":{const t=oe.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();oe.delete(e.self);break}}}function fe(t){const e=(e,n,s)=>{if("active"!==e.status)return[e,[]];if(n.type===o)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if(n.type===ce)return[{...e,effects:{...e.effects,[n.key]:{status:"active"}}},[]];if(n.type===ie)return[{...e,effects:{...e.effects,[n.key]:{status:"done",output:n.output}}},[]];if(n.type===re)return[{...e,effects:{...e.effects,[n.key]:{status:"error",error:n.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,n)=>{if("string"==typeof t)return s=t,o=n,void(e.effects?.[s]||(i.push({type:"effect",key:s,exec:o}),r[s]={status:"active"}));var s,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:n,input:e.input,system:s.system,self:s.self,emit:s.emit},c),u={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(u.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(u.effects={...e.effects,...a?.effects,...r}),[u,i]};return{id:t.id,config:t,transition:e,start:(t,n)=>{const[s,o]=e(t,c(t.input),n);Object.assign(t,s),ue(o,n)},getInitialSnapshot:(e,n)=>{const s=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,n),o={status:"active",output:void 0,error:void 0,input:n};return void 0!==s&&(o.context=s),{...o}},getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}let de=!1;const he=1;let le=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const pe={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};class ye{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new n(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=le.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const s={...pe,...e},{clock:o,logger:i,parent:r,syncSnapshot:c,id:u,systemId:f,inspect:d}=s;this.system=r?r.system:function(t,e){let n=0;const s=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:u}=e,f=(t,e,n,s,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:n,delay:s,id:o})},d={schedule:(t,e,n,s,o=Math.random().toString(36).slice(2))=>{f(t,e,n,s,o);const i={source:t,target:e,event:n,delay:s,id:o,startedAt:Date.now()},r=se(t,o);l._snapshot._scheduledEvents[r]=i;const u=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],h(t,e,n)},s);c[r]=u},cancel:(t,e)=>{const n=se(t,e),s=c[n];delete c[n],delete l._snapshot._scheduledEvents[n],void 0!==s&&a.clearTimeout(s)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const n=l._snapshot._scheduledEvents[e];n.source===t&&d.cancel(t,n.id)}}},h=(t,e,n)=>{const s=e.logic;if("function"==typeof s?.isInternalEventType&&s.isInternalEventType(n.type)&&t!==e)throw new Error(`Internal event "${n.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(n)},l={children:s,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+n++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const n=o.get(t);if(n&&n!==e)throw new Error(`Actor with system ID '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=te(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const n={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(n))},_relay:(t,e,n)=>{f(t,e,n),h(t,e,n)},scheduler:d,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:n,target:s,event:o,delay:i,id:r}=t[e];d.schedule(n,s,o,i,r)}},_clock:a,_logger:u,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:s.timers}),d&&!r&&this.system.inspect(te(d)),this.sessionId=this.system._bookId(),this.id=u??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=s,this.src=s.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),n=this.eventListeners.get("*");if(e||n){if(e)for(const n of e)try{n(t)}catch(t){a(t)}if(n)for(const e of n)try{e(t)}catch(t){a(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=de;try{de=!0,t.exec()}finally{de=e}};this._processingStatus===le.Running?e():this._deferred.push(e)}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}}),f&&(this.systemId=f,this.system._set(f,this)),this._collectedMicrosteps=[];let h=e?.snapshot??e?.state;if(h&&"object"==typeof h&&"_pendingEffects"in h){const{_pendingEffects:t,...e}=h;this._pendingEffects=t,h=e}try{this._snapshot=h?this.logic.restoreSnapshot?this.logic.restoreSnapshot(h,this._actorScope):h:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}f&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){a(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const n=this._deferred[e];try{n()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(n=this.id,s=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:s,actorId:n});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var n,s;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}subscribe(t,e,n){const s=te(t,e,n);if(this._processingStatus!==le.Stopped)this.observers.add(s);else switch(this._snapshot.status){case"done":try{s.complete?.()}catch(t){a(t)}break;case"error":{const t=this._snapshot.error;if(s.error)try{s.error(t)}catch(t){a(t)}else a(t);break}}return{unsubscribe:()=>{this.observers.delete(s)}}}on(t,e){let n=this.eventListeners.get(t);return n||(n=new Set,this.eventListeners.set(t,n)),n.add(e),{unsubscribe:()=>{n.delete(e)}}}select(t,e=Object.is){return{subscribe:(n,s,o)=>{const i=te(n,s,o);let r=t(this.getSnapshot());return this.subscribe({next:n=>{const s=t(n);e(r,s)||(r=s,i.next?.(s))},error:i.error,complete:i.complete})},get:()=>t(this.get())}}start(){if(this._processingStatus===le.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=le.Running;const t=c(this.options.input);this._lastSourceRef=this._parent;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._setErrorSnapshot(t),this._error(t),this}if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,ge(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,n;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){n={err:t}}if(n){const{err:t}=n;return this._setErrorSnapshot(t),void this._error(t)}const[s,i]=Array.isArray(e)?e:[e,void 0];this.update(s,t),ue(i,this._actorScope),t.type===o&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===le.Stopped?this:(this.mailbox.clear(),this._processingStatus===le.NotStarted?(this._processingStatus=le.Stopped,this):(this.mailbox.enqueue({type:o}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){a(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const n of this.observers){const s=n.error;e||=!s;try{s?.(t)}catch(t){a(t)}}this.observers.clear(),this.eventListeners.clear(),e&&a(t)}else this._parent||a(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===le.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new n(this._boundProcess),this._processingStatus=le.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==le.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:he,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),n=this.system._snapshot._scheduledEvents;let s;const o=Date.now();for(const t in n){const e=n[t];e.source===this&&e.target===this&&(s??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return s??=this._pendingEffects,s?{...e,_pendingEffects:s}:e}[u](){return this}getSnapshot(){return this.get()}get(){return e?.(this),this._snapshot}}function ge(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function ve(t,e){return new ye(t,e)}const me=new WeakMap;const _e="xstate.observable.next",xe="xstate.observable.error",be="xstate.observable.complete";const we="xstate.async.resolve",Se="xstate.async.reject";class ke extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Ee=fe({context:void 0,run:()=>{}});function $e(){return ve(Ee)}function Ie(t,{machine:e,context:n},s,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=ee(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=ve(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:n,event:s,self:t.self}):r?.input,src:i,systemId:r?.systemId});return o[a.id]=a,a}return ve(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,systemId:r?.systemId})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==le.Stopped&&c.start()}),c}}const Te=new WeakMap;function je(t,e,n){let s=Te.get(t);return s?e in s||(s[e]=n()):(s={[e]:n()},Te.set(t,s)),s[e]}const Ae={},Oe=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class Me{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const n=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==n?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const n of Oe)if(void 0!==e[n])throw new Error(`Choice state "${t.id}" cannot declare \`${n}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const n={},s=Object.keys(t);for(let o=0;o<s.length;o++){const i=s[o];n[i]=e(t[i],i,t,o)}return n}(this.config.states,(t,e)=>new Me(t,{_parent:this,_key:e,_machine:this.machine})):Ae,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=Zt(t.tags).slice(),this.invoke=Zt(this.config.invoke).map((t,e)=>{const{src:n,systemId:s}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof n?n:`xstate.invoke.${o}`;return{...t,src:c,logic:n,id:r,systemId:s}})}_initialize(){this.after=function(t){const e=t.config.after,n=t.config.timeout,s=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===n&&0===o.length)return[];const r=e=>{const n={type:`xstate.after.${e}.${t.id}`};return st(t,n,n=>Z(e,n.delays,{context:n.context,event:n.event,stateNode:t}))},c=[],a=(t,e,n)=>{for(const s of Qt(t))c.push({...s,event:e,delay:n})};if(e)for(const n of Object.keys(e)){const s=e[n],o=Number.isNaN(+n)?n:+n;a(s,r(o),X(o,t.machine.implementations.delays))}if(void 0!==n&&s){const e={type:`xstate.timeout.${t.id}`};a(s,st(t,e,e=>Z(n,e.delays,{context:e.context,event:e.event,stateNode:t})),"function"==typeof n?n:X(n,t.machine.implementations.delays))}for(const e of o){const n=i(e.id),s=e.timeout,o=st(t,n,e=>Z(s,{},{context:e.context,event:e.event,stateNode:t}));a(e.onTimeout,o,s)}return c.map(e=>({...ot(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(""===n)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=t.config.on[n];e.set(n,De(s,e=>ot(t,n,e)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,De(t.config.onDone,e=>ot(t,n,e)))}const n=(e,n)=>ot(t,e,{to:(t,e)=>(e.cancel(n),{})}),s=(e,n,s)=>{const{target:o,to:i,reenter:r,...c}=n;return ot(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let n=!1;const o=new Proxy(e,{apply:(t,e,s)=>(n=!0,Reflect.apply(t,e,s)),get(t,e,s){const o=Reflect.get(t,e,s);return"function"!=typeof o?o:(...e)=>(n=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||n)&&e.cancel(s),r}return e.cancel(s),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=De(o.onDone,e=>r?s(i,e,r):ot(t,i,e));r&&c.push(n(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[n(t,r)])}if(o.onError){const n=`xstate.error.actor.${o.id}`;e.set(n,De(o.onError,e=>r?s(n,e,r):ot(t,n,e)))}if(o.onSnapshot){const n=`xstate.snapshot.${o.id}`;e.set(n,De(o.onSnapshot,e=>ot(t,n,e)))}}for(const n of t.after){let t=e.get(n.eventType);t||(t=[],e.set(n.eventType,t)),t.push(n)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,n=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const n of["actions","to","context"])if(void 0!==e[n])throw new Error(`Choice state "${t.id}" cannot declare \`${n}\` on a choice.`);return e};return[ot(t,"",{to:t=>n(e(t))})]}(this):this.config.always&&(this.always=De(this.config.always,t=>ot(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[n,s]of this.transitions)t[n]=s.slice(),s.some(t=>t.target||t.reenter||t.to)&&e.push(n);this.on=t,this.ownEvents=e;const n=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)n.add(e);this.events=Array.from(n)}get initial(){return je(this,"initial",()=>function(t,e){const n="object"==typeof e&&null!==e?e.target:e,s="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof n?t.states[n]:void 0;if(!o&&n)throw new Error(`Initial state node "${n}" not found on parent state node #${t.id}`);const i={source:t,target:o?[o]:void 0,input:s};return i}(this,this.config.initial))}next(t,e,n){const s=e.type,o=je(this,`candidates-${s}`,()=>function(t,e){const n=t.transitions.get(e);if(n)return n;const s=[];for(const n of t.transitions.keys())ne(e,n)&&s.push(n);s.sort((t,e)=>e.length-t.length);const o=[];for(const e of s)o.push(...t.transitions.get(e));return o}(this,s));for(const s of o){if(Tt(s,e,t,this,n))return[s]}}}function De(t,e){const n=Qt(t),s=new Array(n.length);for(let t=0;t<n.length;t++)s[t]=e(n[t]);return s}class Ne{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actors:t.actors??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.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 Me(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],n=s=>{Object.values(s).forEach(s=>{if(s.config.route&&s.config.id){const o=s.config.id,i=s.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(ot(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(s.states&&n(s.states));if("$unserializable"in i)throw new Error(`State "${s.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const c=i.guard,a={...i,guard:c?e=>{if(!r(e))return!1;if("function"==typeof c)return c(e);if("string"==typeof c){const n=e.guards?.[c];if(!n)throw new Error(`Guard '${c}' is not implemented in machine '${t.machine.id}'.`);return n(e)}return!0}:r,target:`#${o}`};e.push(ot(t,"xstate.route",a))}s.states&&n(s.states)})};n(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:n,actors:s,delays:o}=this.implementations,i=new Ne(this.config,{actions:{...e,...t.actions},guards:{...n,...t.guards},actors:{...s,...t.actors},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(n=this.root,s=t.value,tt(n,Y(dt(n,s))));var n,s;const o=Y(dt(this.root,e));return zt({_nodes:[...o],value:e,context:t.context||{},children:{},status:et(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,n){return St(t,e,n,[]).snapshot}microstep(t,e,n){const{microsteps:s}=St(t,e,n,[]),o=new Array(s.length);for(let t=0;t<s.length;t++)o[t]=s[t][0];return o}getTransitionData(t,e,n){return ht(this.root,t.value,t,e,n)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(ne(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:n}=this.config,s=zt({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){const o={},i=n({spawn:Ie(t,s,e,o),input:e.input,self:t.self,actors:this.implementations.actors}),r=B(s,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return s}getInitialSnapshot(t,e){const n=c(e),s=[],o=this._getPreInitialState(t,n),[i]=xt(this.root,o,t,n,s),{snapshot:r}=St(i,n,t,s);return r}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=Ft(t),n=e.slice(1),s=nt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(s);if(!o)throw new Error(`Child state node '#${s}' does not exist on machine '${this.id}'`);return ft(o,n)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:n,_stateInputs:s,tags:o,machine:i,children:r,context:c,can:a,hasTag:u,matches:f,getMeta:d,getInputs:h,toJSON:l,...p}=t,y={};for(const t in r){const n=r[t];y[t]={snapshot:n.getPersistedSnapshot(e),src:n.src,systemId:n.systemId,syncSnapshot:n._syncSnapshot}}const g={...p,context:Bt(c),children:y,historyValue:Jt(p.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const n=t.version;if(n!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${n}' does not match machine version '${this.version}'.`);t=e(t,n)}const s=t,o={},i=s.children;for(const t of Object.keys(i)){const n=i[t],s=n.snapshot,r=n.src,c="string"==typeof r?ee(this,r):r;if(!c)continue;const a=ve(c,{id:t,parent:e.self,syncSnapshot:n.syncSnapshot,snapshot:s,src:r,systemId:n.systemId});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const n of Object.keys(t)){const s=t[n];for(const t of s){let s;if(t instanceof Me)s=t;else try{s=this.root.machine.getStateNodeById(t.id)}catch{}s&&(e[n]??=[],e[n].push(s))}}return e})(s.historyValue),c=Array.from(Y(dt(this.root,s.value))),{version:a,...u}=t,f=zt({...u,children:o,_nodes:c,value:s.value,historyValue:r},this),d=new WeakSet;return function t(e){if(!d.has(e)){d.add(e);for(const n of Object.keys(e)){const s=e[n];if(s&&"object"==typeof s){if("xstate$$type"in s&&s.xstate$$type===he){e[n]=o[s.id];continue}t(s)}}}}(f.context),f}}function Pe(t){return new Ne(t)}function Re(t){const e=G(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function Ce(t){return!!t&&"object"==typeof t&&"$unserializable"in t&&"string"==typeof t.$unserializable}function We(t,e="$"){if(Ce(t)){if("actor"===t.$unserializable&&e.endsWith(".src"))return;throw new Error(`Unresolved ${t.$unserializable} at ${e}`)}if(t&&"object"==typeof t)if(Array.isArray(t))t.forEach((t,n)=>We(t,`${e}[${n}]`));else for(const n of Object.keys(t)){const s=t[n];"$"===e&&("actions"===n||"guards"===n||"actors"===n||"delays"===n||"schemas"===n)||We(s,`${e}.${n}`)}}function Le(t){const e={};if(!t)return e;for(const n of Object.keys(t)){const s=t[n];"number"==typeof s&&(e[n]=s)}return e}let ze="session_"+Math.random().toString(36).slice(2),Ve="";function Je(t,e,n,s){const o=`\nwith (context) {\n return (${e});\n}\n `.trim(),i=new Function("context","_event","_sessionid","_name","_ioprocessors","In",o),r=n&&n._scxmlExternal,c=n&&"@xstate.init"===n.type,a=n&&"string"==typeof n.type&&n.type.startsWith("xstate.done."),u=n&&n._scxmlEventType;return i(t,n&&!c?{name:n.type,type:u||(r?"external":"internal"),sendid:n._scxmlSendId,origin:r?"#_scxml_session":void 0,origintype:r?"http://www.w3.org/TR/scxml/#SCXMLEventProcessor":void 0,invokeid:n._scxmlInvokeId,data:a?n.output:void 0!==n._scxmlEventData?n._scxmlEventData:n}:void 0,ze,Ve,{scxml:{location:`#_scxml_${ze}`}},t=>{if(!s)return!1;try{const e=s.getSnapshot?.();if(e?._nodes){const n=t.replace(/\./g,"$");return e._nodes.some(t=>t.id===n||t.id.endsWith("."+n))}}catch{}return!1})}function Be(t,e){const n=Object.keys(t),s=n.map(t=>`let ${t} = context.${t};`).join("\n"),o=n.map(t=>`updates.${t} = ${t};`).join("\n");return new Function("context","updates",`\n${s}\n${e}\n${o}\nreturn updates;\n `)(t,{})}function qe(t){return t.type.startsWith("@xstate.")}const Fe=["id","key","type","history","description","target","version","initial","context","on","after","always","choice","route","onTimeout","timeout","entry","exit","meta","output","tags","input","_scxmlDonedata"];function Ue(t,e){const n={$unserializable:t};return e&&(n.id=e),n}function Ge(t){if("function"==typeof t)return Ue("function",t.name||void 0);if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?Ue("value"):t;if(Array.isArray(t))return t.map(Ge);if(t.constructor!==Object&&void 0!==t.constructor)return Ue("value");const e={};for(const n of Object.keys(t)){const s=t[n];void 0!==s&&(e[n]=Ge(s))}return e}function Xe(t){if(Array.isArray(t))return t.map(Xe);const e=t,n={};for(const t of Object.keys(e)){const s=e[t];void 0!==s&&(n[t]="src"===t&&"string"!=typeof s?Ue("actor",s.id):Ge(s))}return n}function Ze(t,e){if(!t)return;const n={};for(const s of Object.keys(t)){const o=t[s];n[s]="function"==typeof o?Ue("function",s):o&&"object"==typeof o?Ue(e,s):o}return n}function He(t){const e={};for(const n of Fe){const s=t[n];void 0!==s&&(e[n]=Ge(s))}if(void 0!==t.invoke&&(e.invoke=Xe(t.invoke)),t.states){const n={};for(const e of Object.keys(t.states))n[e]=He(t.states[e]);e.states=n}return e}function Ke(t){const e=He(t);if(void 0!==t.internalEvents&&(e.internalEvents=Ge(t.internalEvents)),t.schemas){const n={};for(const e of Object.keys(t.schemas)){const s=t.schemas[e];n[e]=s&&"object"==typeof s&&!("~standard"in s)?Ze(s,"schema"):Ue("schema",e)}e.schemas=n}for(const n of["actions","guards","actors","delays"])t[n]&&(e[n]=Ze(t[n],"actors"===n?"actor":"function"));return e}function Qe(t){const e=ve(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{},actionExecutor:()=>{}}}let Ye=function(t){return t.Internal="#_internal",t}({});const tn={timeout:1/0};t.Actor=ye,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const n=this.getId();return this.timeouts.set(n,{start:this.now(),timeout:e,fn:t}),n}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[n,s])=>{const o=e.start+e.timeout;return s.start+s.timeout>o?-1:1});for(const[e,n]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-n.start>=n.timeout&&(this.timeouts.delete(e),n.fn.call(null))}this._flushing=!1,this._flushingInvalidated&&(this._flushingInvalidated=!1,this.flushTimeouts())}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=Ye,t.StateMachine=Ne,t.StateNode=Me,t.TimeoutError=ke,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]},t.assertEvent=function(t,e){const n=Zt(e);if(!n.some(e=>ne(t.type,e))){const e=1===n.length?`type matching "${n[0]}"`:`one of types matching "${n.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.checkStateIn=function(t,e){if("string"==typeof e&&nt(e)){const n=t.machine.getStateNodeById(e);return t._nodes.some(t=>t===n)}return t.matches(e)},t.createActor=ve,t.createAsyncAtom=function(t,e){const n={};let s,o=0;const i=C(()=>{s?.abort();const e=new AbortController,i=++o;return s=e,t({signal:e.signal}).then(t=>{i!==o||e.signal.aborted||N(n.current,{status:"done",data:t})},t=>{i!==o||e.signal.aborted||N(n.current,{status:"error",error:t})}),{status:"pending"}},{compare:D,...e});return n.current=i,i},t.createAsyncLogic=function(t){const e=t;return fe({id:e.id,schemas:e.schemas,context:void 0,run:({event:t,input:n,self:o,system:i},r)=>{switch(t.type){case we:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Se:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return r.effect(()=>{const t=o,s=new AbortController,c=e.timeout,a=G(c),u=void 0===a?void 0:i._clock.setTimeout(()=>{"active"===o.getSnapshot().status&&(s.abort(),i._relay(t,t,{type:Se,data:new ke(c)}))},a),f=()=>{void 0!==u&&i._clock.clearTimeout(u)},d=Promise.resolve(e.run({input:n,system:i,self:o,signal:s.signal},{emit:r.emit,step:async(e,n)=>{const s=o.getSnapshot().effects?.[e];if("done"===s?.status)return s.output;if("error"===s?.status)throw s.error;if("active"===s?.status)return function(t,e){return new Promise((n,s)=>{const o=t.subscribe(t=>{const i=t.effects?.[e];"done"===i?.status?(o.unsubscribe(),n(i.output)):"error"===i?.status&&(o.unsubscribe(),s(i.error))})})}(o,e);i._relay(t,t,{type:ce,key:e});try{const s=await n();return i._relay(t,t,{type:ie,key:e,output:s}),s}catch(n){throw i._relay(t,t,{type:re,key:e,error:n}),n}}}));return d.then(e=>{f(),"active"===o.getSnapshot().status&&i._relay(t,t,{type:we,data:e})},e=>{f(),"active"===o.getSnapshot().status&&i._relay(t,t,{type:Se,data:e})}),()=>{s.abort(),f()}}),{effects:{async:{status:"active"}}}}})},t.createAtom=C,t.createAtomConfig=function(t,e){return{createAtom:n=>C("function"==typeof t?t(n):t,e)}},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run;return fe({schemas:"function"==typeof t?void 0:t.schemas,context:void 0,run:(t,n)=>{const{event:s,input:o,self:i,system:r}=t,c=t.emit,a=me.get(i);a?.receivers?.forEach(t=>t(s)),n.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return me.set(i,t),t.dispose=e({input:o,system:r,self:i,sendBack:t=>{if("stopped"===i.getSnapshot().status)return;const e=i._parent;e&&r._relay(i,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{me.delete(i),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=$e,t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run;return{config:e,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case xe:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case be:return{...t,status:"done",input:void 0,_subscription:void 0};case o:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(t,{self:n,system:s,emit:o})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:s,self:n,emit:o}).subscribe({next:t=>{n._parent&&s._relay(n,n._parent,t)},error:t=>{s._relay(n,n,{type:xe,data:t})},complete:()=>{s._relay(n,n,{type:be})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.createListenerLogic=p,t.createLogic=fe,t.createMachine=Pe,t.createMachineFromConfig=function t(e,n={}){!function(t,e){for(const n of["actions","guards","actors","delays"]){const s=t[n];if(s)for(const t of Object.keys(s))if(Ce(s[t])&&!e[n]?.[t])throw new Error(`Missing ${n}.${t}`)}}(e,n),We(e);const s=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...Le(t.delays),...e.delays??{}}}}(e,n),o={},i=[];let r=null;const c=[];function a(e){return(Array.isArray(e)?e:[e]).map(e=>{const n=e;let o;if(n._nestedMachineJSON)o=t(n._nestedMachineJSON,s);else if(Ce(e.src)){if(o=e.src.id?s.actors[e.src.id]:void 0,!o)throw new Error(`Missing actors.${e.src.id??""}`)}else o=e.src;return{src:o,id:e.id,systemId:e.systemId,input:e.input,onDone:e.onDone?d(e.onDone):void 0,onError:e.onError?d(e.onError):void 0,onSnapshot:e.onSnapshot?d(e.onSnapshot):void 0,timeout:e.timeout,onTimeout:e.onTimeout?d(e.onTimeout):void 0}})}function u(t,e,n){const s=n instanceof Error?n.message:"string"==typeof n?n:"unknown error";t.enq.raise({type:"error.execution",_scxmlEventType:"platform",_scxmlEventData:{tagname:e,message:s,line:NaN,column:NaN,reason:s}}),t.errored=!0}function f(t,e,n,s){const o=s??{enq:n,errored:!1};let i;for(const s of t){if(o.errored)break;if(qe(s))switch(s.type){case"@xstate.raise":{const t=void 0!==s.delay,e=t||void 0!==s.id?{...s.event,...t?{_scxmlExternal:!0}:{},...void 0!==s.id?{_scxmlSendId:s.id}:{}}:s.event;n.raise(e,{id:s.id,delay:s.delay});break}case"@xstate.cancel":n.cancel(s.id);break;case"@xstate.log":n.log(...s.args);break;case"@xstate.emit":n.emit(s.event);break;case"@xstate.assign":i??={},Object.assign(i,s.context);break;default:throw new Error(`Unknown built-in action: ${s.type}`)}else if("scxml.assign"===s.type){const t=s,n={...e.context,...i};let r;try{r=Je(n,t.expr,e.event,e.self)}catch(t){u(o,"assign",t);continue}if(t.location.includes(".")){u(o,"assign",new Error(`Invalid assign location: ${t.location}`));continue}i??={},i[t.location]=r}else if("scxml.raise"===s.type){const t=s,r={...e.context,...i};let c,a,f,d;try{if(c=t.eventexpr?Je(r,t.eventexpr,e.event,e.self):t.event||"unknown",a={type:c},t.params)for(const n of t.params)a[n.name]=Je(r,n.expr,e.event,e.self);f=t.targetexpr?Je(r,t.targetexpr,e.event,e.self):t.target;const n="#_internal"===f;d=t.delayexpr?Re(Je(r,t.delayexpr,e.event,e.self)):n?void 0:t.delay}catch(t){u(o,"send",t);continue}const h="#_internal"===f,l="#_parent"===f;if("string"==typeof f&&f.length>0&&!f.startsWith("#_")){u(o,"send",new Error(`Invalid send target: ${f}`));continue}if(void 0!==t.id&&(a._scxmlSendId=t.id),l&&e.parent)n.sendTo(e.parent,a,void 0!==d?{delay:d}:void 0);else if("string"!=typeof f||!f.startsWith("#_")||l||h)void 0!==d&&(a._scxmlExternal=!0),n.raise(a,{id:t.id,delay:d});else{const s=f.slice(2),o=e.children?.[s];o?n.sendTo(o,a):(void 0!==d&&(a._scxmlExternal=!0),n.raise(a,{id:t.id,delay:d}))}}else if("scxml.cancel"===s.type){const t=s,o={...e.context,...i};try{const s=Je(o,t.sendidexpr,e.event,e.self);s&&n.cancel(s)}catch{}}else if("scxml.script"===s.type){const t=s,n={...e.context,...i};try{const e=Be(n,t.code);i??={},Object.assign(i,e)}catch(t){u(o,"script",t)}}else if("scxml.foreach"===s.type){const t=s,r={...e.context,...i},c=t=>/^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(t);if(!c(t.item)||t.index&&!c(t.index)){u(o,"foreach",new Error("foreach item/index is not a legal location"));continue}let a;try{a=Je(r,t.array,e.event,e.self)}catch(t){u(o,"foreach",t);continue}if(!Array.isArray(a)){u(o,"foreach",new Error("foreach array is not iterable"));continue}i??={};for(let s=0;s<a.length;s++){i[t.item]=a[s],t.index&&(i[t.index]=s);const r={...e,context:{...e.context,...i}},c=f(t.actions,r,n,o);if(c.context&&Object.assign(i,c.context),o.errored)break}}else if("scxml.block"===s.type){const t=s,o={...e,context:{...e.context,...i}},r=f(t.actions,o,n);if(r.context){i??={};for(const t of Object.keys(r.context))r.context[t]!==e.context[t]&&(i[t]=r.context[t])}}else if("scxml.if"===s.type){const t=s,r={...e.context,...i};for(const s of t.branches){let t;if(s.cond)try{t=!!Je(r,s.cond,e.event,e.self)}catch(e){u(o,"if",e),t=!1}else t=!0;if(t){if(s.actions.length){const t={...e,context:r},c=f(s.actions,t,n,o);if(c.context){i??={};for(const t of Object.keys(c.context))c.context[t]!==e.context[t]&&(i[t]=c.context[t])}}break}}}else n(e.actions[s.type],s.params)}return{context:i?{...e.context,...i}:void 0,errored:o.errored}}function d(t){return(Array.isArray(t)?t:[t]).map(t=>{const e=Array.isArray(t.target)?t.target[0]:t.target,n=t.target;return t.guard||t.actions?.length?t.guard&&!t.actions?.length?{target:n,guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input}:e?{guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input,to:(s,r)=>{if(t.actions?.length){const n=e.replace(/^#/,"");o[n]=t.actions,i.includes(t.actions)||i.push(t.actions)}return{target:n,reenter:t.reenter}}}:{guard:t.guard,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input,to:(e,n)=>{if(t.actions?.length){i.includes(t.actions)||i.push(t.actions),r??=e.context;const s=f(t.actions,e,n);if(s.context)return{context:s.context}}return{}}}:{target:n,description:t.description,reenter:t.reenter,meta:t.meta,input:t.input}})}const h=function t(e,n){const s=e.entry,u=e.id||n;var h,l;return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:e.timeout,states:e.states?Object.entries(e.states).reduce((e,[n,s])=>(e[n]=t(s,n),e),{}):void 0,on:e.on?Object.entries(e.on).reduce((t,[e,n])=>(t[e]=d(n),t),{}):void 0,always:e.always?d(e.always):void 0,choice:e.choice?d(e.choice):void 0,route:e.route,after:e.after?Object.entries(e.after).reduce((t,[e,n])=>(t[e]=d(n),t),{}):void 0,onTimeout:e.onTimeout?d(e.onTimeout):void 0,entry:(t,e)=>{for(;c.length;){const t=c.shift();e.raise({type:"error.execution",_scxmlEventType:"platform",_scxmlEventData:t})}let n;if(r&&i.length>0&&Object.keys(o).length>0){let s=r;for(const n of i){const o=f(n,{...t,context:s},e);o.context&&(s=o.context)}i.length=0,r=null;for(const t of Object.keys(o))delete o[t];n=s}else{const s=u?o[u]:void 0;if(s){delete o[u];const i=f(s,t,e);i.context&&(n=i.context)}r=null,i.length=0}if(s?.length){const o=n?{...t,context:n}:t,i=f(s,o,e);i.context&&(n=i.context)}return{context:n}},exit:e.exit?(l=e.exit,(t,e)=>f(l,t,e)):void 0,invoke:e.invoke?a(e.invoke):void 0,meta:e.meta,output:e._scxmlDonedata?(h=e._scxmlDonedata,({context:t,event:e,self:n})=>{try{if(h.params&&h.params.length){const s={};for(const o of h.params)s[o.name]=Je(t,o.expr,e,n);return s}if(void 0!==h.contentExpr)return Je(t,h.contentExpr,e,n);if(void 0!==h.contentText)try{return Je(t,h.contentText,e,n)}catch{return h.contentText}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";c.push({tagname:"donedata",message:e,line:NaN,column:NaN,reason:e})}}):e.output}}(e),l=e.context?{context:e.context}:{};Ve=e.id||"",ze="session_"+Math.random().toString(36).slice(2);const p=Pe({...h,...l,version:e.version}),y={"scxml.cond":({context:t,event:e,self:n},s)=>{const o=s?.expr;if(!o)return!0;try{return!!Je(t,o,e,n)}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";return c.push({tagname:"cond",message:e,line:NaN,column:NaN,reason:e}),!1}},"xstate.stateIn":(t,e)=>{const n=e?.stateId;if(!n)return!1;const s=n.replace(/^#/,""),o=t._snapshot;return!!o?._nodes&&o._nodes.some(t=>t.id===s)},"xstate.not":(t,e)=>{const n=e?.guard,s=n&&y[n.type];if(!s)throw new Error(`Guard '${n?.type}' referenced by 'xstate.not' is not implemented.`);return!s(t,n.params)}},g=p.provide({actions:s.actions,actors:s.actors,guards:{...y,...s.guards},delays:s.delays});return g._json=e,g},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run;return fe({schemas:"function"==typeof t?void 0:t.schemas,context:void 0,run:(t,n)=>{const{event:s,input:o,self:i,system:r}=t,c=t.emit;switch(s.type){case _e:return{context:s.data};case xe:return{status:"error",error:s.data,input:void 0,effects:{observable:{status:"error",error:s.data}}};case be:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}n.effect("observable",()=>{const t=i,n=e({input:o,system:r,self:i,emit:c}).subscribe({next:e=>{r._relay(t,t,{type:_e,data:e})},error:e=>{r._relay(t,t,{type:xe,data:e})},complete:()=>{r._relay(t,t,{type:be})}});return()=>n.unsubscribe()})}})},t.createReducerAtom=function(t,e,n){const s=C(t,n);return{[v]:!0,get:s.get.bind(s),subscribe:s.subscribe.bind(s),send(t){const n=T;let o;T=void 0;try{o=e(s.get(),t)}finally{T=n}s.set(o)}}},t.createStateConfig=function(t){return t},t.createSubscriptionLogic=W,t.getInitialMicrosteps=function(t,...[e]){const n=Qe(t),s=c(e),o=[],i=t._getPreInitialState(n,s),r=xt(t.root,i,n,s,o),{microsteps:a}=St(r[0],s,n,o);return[r,...a]},t.getInitialSnapshot=function(t,...[e]){const n=Qe(t);return t.getInitialSnapshot(n,e)},t.getMicrosteps=function(t,e,n){const s=Qe(t),{microsteps:o}=St(e,n,s,[]);return o},t.getNextSnapshot=function(t,e,n){const s=Qe(t);s.self._snapshot=e;const o=t.transition(e,n,s);return Array.isArray(o)?o[0]:o},t.getNextTransitions=function(t){const e=[],n=t._nodes.filter(H),s=new Set;for(const t of n)for(const n of[t].concat(Q(t,void 0)))if(!s.has(n.id)){s.add(n.id);for(const[,t]of n.transitions.entries())e.push(...t);n.always&&e.push(...n.always)}return e},t.getStateNodes=dt,t.initialTransition=function(t,...[e]){const n=[],s=Qe(t);return s.actionExecutor=t=>{n.push(t)},[t.getInitialSnapshot(s,e),n]},t.isAtom=m,t.isMachineSnapshot=jt,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.listenerLogic=y,t.machineConfigToJSON=Ke,t.mapState=function(t,e){const n=[],s=(t,e)=>{let n=t;for(const t of e){if(!n?.states)return;const e=n.states;if(!(t in e))return;n=e[t]}return n},o=new Set;for(const i of t._nodes.filter(H)){let r=i;for(;r&&!o.has(r);){o.add(r);const i=s(e,r.path);i?.map&&n.push({stateNode:r,result:i.map(t)}),r=r.parent}}return n},t.matchesState=qt,t.pathToStateValue=Gt,t.serializeMachine=function(t){return t._json??Ke(t.config)},t.setup=function(t={}){const{states:e={},schemas:n}=t;return{createMachine(t){const e=t.schemas,s=n||e?{...e,...n}:void 0;return new Ne(s?{...t,schemas:s}:t)},createStateConfig:t=>t,states:e}},t.subscriptionLogic=L,t.toObserver=te,t.toPromise=function(t){return new Promise((e,n)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:n})})},t.transition=function(t,e,n){const s=[],o=Qe(t);o.actionExecutor=t=>{s.push(t)};const i=t.transition(e,n,o),[r,c]=Array.isArray(i)?i:[i,[]];return[r,s.concat(c)]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,e,n){const s={...tn,...n};return new Promise((n,o)=>{const{signal:i}=s;if(i?.aborted)return void o(i.reason);let r=!1;const c=s.timeout===1/0?void 0:setTimeout(()=>{a(),o(new Error(`Timeout of ${s.timeout} ms exceeded`))},s.timeout),a=()=>{clearTimeout(c),r=!0,d?.unsubscribe(),f&&i.removeEventListener("abort",f)};function u(t){e(t)&&(a(),n(t))}let f,d;u(t.getSnapshot()),r||(i&&(f=()=>{a(),o(i.reason)},i.addEventListener("abort",f)),d=t.subscribe({next:u,error:t=>{a(),o(t)},complete:()=>{a(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&d.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate.umd.min.js.map