xstate 6.0.0-alpha.37 → 6.0.0-alpha.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/{StateMachine-7197482a.development.cjs.js → StateMachine-144215d2.development.cjs.js} +22 -2
  2. package/dist/{StateMachine-009b5bc4.esm.js → StateMachine-2f47d890.esm.js} +22 -2
  3. package/dist/{StateMachine-5d0aac92.cjs.js → StateMachine-94084ac7.cjs.js} +22 -2
  4. package/dist/{StateMachine-9da92cbf.development.esm.js → StateMachine-da29dd2e.development.esm.js} +22 -2
  5. package/dist/{createActor-164c86f5.development.esm.js → createActor-2a03d4b2.development.esm.js} +15 -3
  6. package/dist/{createActor-19e83fb9.esm.js → createActor-a211c276.esm.js} +15 -3
  7. package/dist/{createActor-8462b9cc.development.cjs.js → createActor-c0f78b8a.development.cjs.js} +14 -2
  8. package/dist/{createActor-fd53ec92.cjs.js → createActor-d5305cc9.cjs.js} +14 -2
  9. package/dist/declarations/src/createMachine.d.ts +3 -3
  10. package/dist/declarations/src/index.d.ts +3 -2
  11. package/dist/declarations/src/setup.d.ts +16 -12
  12. package/dist/declarations/src/types.d.ts +1 -1
  13. package/dist/declarations/src/types.v6.d.ts +11 -4
  14. package/dist/{index-acf2bd02.development.esm.js → index-17f889df.development.esm.js} +2 -2
  15. package/dist/{index-13e54113.cjs.js → index-21d08fff.cjs.js} +1 -1
  16. package/dist/{index-14478488.development.cjs.js → index-3d1368f7.development.cjs.js} +1 -1
  17. package/dist/{index-abf9ab72.esm.js → index-7020402e.esm.js} +2 -2
  18. package/dist/{transition-169651ca.cjs.js → transition-2dcabac8.cjs.js} +1 -1
  19. package/dist/{transition-a306226e.development.cjs.js → transition-4ba58b71.development.cjs.js} +1 -1
  20. package/dist/{transition-760b0fc6.esm.js → transition-e8a13c00.esm.js} +1 -1
  21. package/dist/{transition-61a126e0.development.esm.js → transition-f581ffa6.development.esm.js} +1 -1
  22. package/dist/xstate-actors.cjs.js +2 -2
  23. package/dist/xstate-actors.development.cjs.js +2 -2
  24. package/dist/xstate-actors.development.esm.js +2 -2
  25. package/dist/xstate-actors.esm.js +2 -2
  26. package/dist/xstate-actors.umd.min.js.map +1 -1
  27. package/dist/xstate-durable.cjs.js +2 -2
  28. package/dist/xstate-durable.development.cjs.js +2 -2
  29. package/dist/xstate-durable.development.esm.js +2 -2
  30. package/dist/xstate-durable.esm.js +2 -2
  31. package/dist/xstate-durable.umd.min.js.map +1 -1
  32. package/dist/xstate-graph.cjs.js +3 -3
  33. package/dist/xstate-graph.development.cjs.js +3 -3
  34. package/dist/xstate-graph.development.esm.js +3 -3
  35. package/dist/xstate-graph.esm.js +3 -3
  36. package/dist/xstate-graph.umd.min.js +1 -1
  37. package/dist/xstate-graph.umd.min.js.map +1 -1
  38. package/dist/xstate.cjs.js +7 -10
  39. package/dist/xstate.development.cjs.js +7 -10
  40. package/dist/xstate.development.esm.js +9 -12
  41. package/dist/xstate.esm.js +9 -12
  42. package/dist/xstate.umd.min.js +1 -1
  43. package/dist/xstate.umd.min.js.map +1 -1
  44. package/package.json +1 -1
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-fd53ec92.cjs.js');
6
- var dist_xstateActors = require('./index-13e54113.cjs.js');
7
- var StateMachine = require('./StateMachine-5d0aac92.cjs.js');
5
+ var createActor = require('./createActor-d5305cc9.cjs.js');
6
+ var dist_xstateActors = require('./index-21d08fff.cjs.js');
7
+ var StateMachine = require('./StateMachine-94084ac7.cjs.js');
8
8
 
9
9
  function simpleStringify(value) {
10
10
  return JSON.stringify(value);
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-8462b9cc.development.cjs.js');
6
- var dist_xstateActors = require('./index-14478488.development.cjs.js');
7
- var StateMachine = require('./StateMachine-7197482a.development.cjs.js');
5
+ var createActor = require('./createActor-c0f78b8a.development.cjs.js');
6
+ var dist_xstateActors = require('./index-3d1368f7.development.cjs.js');
7
+ var StateMachine = require('./StateMachine-144215d2.development.cjs.js');
8
8
 
9
9
  function simpleStringify(value) {
10
10
  return JSON.stringify(value);
@@ -1,6 +1,6 @@
1
- import { n as isMachineSnapshot, ak as getAllOwnEvents, al as matchesEvent, X as XSTATE_INIT } from './createActor-164c86f5.development.esm.js';
2
- import { c as createEmptyActor } from './index-acf2bd02.development.esm.js';
3
- import { S as StateMachine } from './StateMachine-9da92cbf.development.esm.js';
1
+ import { u as isMachineSnapshot, ak as getAllOwnEvents, al as matchesEvent, X as XSTATE_INIT } from './createActor-2a03d4b2.development.esm.js';
2
+ import { b as createEmptyActor } from './index-17f889df.development.esm.js';
3
+ import { S as StateMachine } from './StateMachine-da29dd2e.development.esm.js';
4
4
 
5
5
  function simpleStringify(value) {
6
6
  return JSON.stringify(value);
@@ -1,6 +1,6 @@
1
- import { n as isMachineSnapshot, ak as getAllOwnEvents, al as matchesEvent, X as XSTATE_INIT } from './createActor-19e83fb9.esm.js';
2
- import { c as createEmptyActor } from './index-abf9ab72.esm.js';
3
- import { S as StateMachine } from './StateMachine-009b5bc4.esm.js';
1
+ import { u as isMachineSnapshot, ak as getAllOwnEvents, al as matchesEvent, X as XSTATE_INIT } from './createActor-a211c276.esm.js';
2
+ import { b as createEmptyActor } from './index-7020402e.esm.js';
3
+ import { S as StateMachine } from './StateMachine-2f47d890.esm.js';
4
4
 
5
5
  function simpleStringify(value) {
6
6
  return JSON.stringify(value);
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",o="@xstate.stop",r="@xstate.terminate",i="xstate.timer";function c(t,e){return{type:"xstate.after",delay:t,stateId:e}}function a(t,e){return`xstate.after.${t}.${e}`}function h(t){return`xstate.timeout.${t}`}function u(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function d(t){return`xstate.timeout.actor.${t}`}function f(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function l(t,e){return{type:`xstate.error.${t}`,error:e}}function p(t){return{type:s,input:t}}function y(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable";function v(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const m={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(v(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},_=new WeakMap;function x(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const r=t(e.input,{self:s,system:n});if(!r)return;let i,c=!1;const a=()=>{c||(c=!0,r.unsubscribe(),i?.unsubscribe())},h=s._parent;h&&(i=h.subscribe({complete:a,error:a})),_.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(_.get(s)?.unsubscribe(),_.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function S(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function b(){return x(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const r="*"!==e&&e.endsWith(".*");return t.on(r?"*":e,t=>{r&&!Ue(t.type,e)||S(n,o,()=>s(t))})})}const w=b();function I(){return x(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:r,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&o?S(s,n,()=>o(t.output)):"error"===t.status&&r?S(s,n,()=>r(t.error)):"active"===t.status&&i&&S(s,n,()=>i(t))},error:t=>{r&&S(s,n,()=>r(t))},complete:()=>{}})})}const k=I(),E=Symbol();function A(t){return!!t[E]}function O(t){return A(t)?t._parent:t.self._parent}function j(t,e){if(!A(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>O(e)}}),t}function T(){return this.action?.(...this.args)}function M(t=this.source.system){return t.emitEvent(this.source,this.event)}function $(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function P(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function R(t=this.actor.system){return t.startActor(this.actor)}function z(t=this.source.system){return t.stopActor(this.actor)}function N(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function K(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function D(t=this.source.system){return v(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function C(t=this.source.system){return t.cancelTimer(this.source,this.id)}function V(t,e,s){if(!Q(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const o=e.id??"xstate.timer.auto."+n++;e.id=o;const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:r}},_nextTimerId:n}}function W(t,e){return{...t,...e}}function J(t,e,...s){const n={action:e,args:s};return t.push(n),n}function U(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor}};const n={...t.children};let o=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(o=!0,delete n[t]);if(!o)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function B(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}function L(t,e,s,n=!1,o=!0){const r={cancel:s=>{J(e,m["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{J(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?J(e,m["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const r=t.system.createActorRef(s,{...n,parent:t.self});return function(t,e,s){J(t,m["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s??e.id}}(e,r,n?.id),r},sendTo:(n,o,r)=>{n?J(e,m["@xstate.sendTo"],t,n,o,r):s.push(l("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){J(e,m["@xstate.stop"],t,s).childUpdate={type:"remove",actor:s}}}};return n&&Object.assign(r,{listen:(s,n,o)=>{const r={actor:s,eventType:n,mapper:o},i=t.system.createActorRef(w,{input:r,parent:t.self});return J(e,m["@xstate.spawn"],i),i},subscribeTo:(s,n)=>{const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},r=t.system.createActorRef(k,{input:o,parent:t.self});return J(e,m["@xstate.spawn"],r),r}}),Z(r,(t,...s)=>{J(e,t,...s)})}function q(t,e){switch(t){case m["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:P,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case m["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:K,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case m["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:D,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case m["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:C,source:e[0].self,id:t}}case m["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:z,source:e[0].self,actor:t,id:t.id}}default:return}}function F(t){const e=[t];return{kind:"builtin",exec:R,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function G(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:D,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function H(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:N,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function X(t,e,[s,n]){const o="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!o||i||c?[s,n]:[s,[...n,H(t,s)]]}function Q(t){return"builtin"===t.kind}function Y(t,e,s,n){let o=t;const r=[];for(const i of n){const n=A(s)?j({context:o.context,event:e,output:ze(e),children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:o.context,event:e,output:ze(e),self:s.self,system:s.system,parent:s.self._parent,children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=B(i),h=c?i:!!a&&a.action.bind(null,...a.args);let u;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;u=s}if(a?.childUpdate&&(o=U(o,a.childUpdate,s)),h&&"_special"in h){r.push({kind:"action",exec:T,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:u,args:[],action:void 0});const t=h(n,st);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:W(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!h||!("resolve"in h)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?q(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:u,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?M:T},...t};o=V(o,n,s),r.push(n);continue}}return[o,r]}function Z(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:tt,emit:tt,log:tt,raise:tt,spawn:et,sendTo:tt,stop:tt,listen:et,subscribeTo:et,...t}),s}const tt=()=>{},et=()=>({}),st=Z({},tt);const nt=new WeakMap,ot=new WeakMap,rt=new Map;function it(t){const e=t._peekKeyedActors;return e?e.call(t)??rt:t.keyedActors}function ct(t){t._snapshotVersion++}function at(t){return t._snapshotVersion}function ht(t,e,s){const n=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),o=new Map(s?.keyedActors??it(t)),r=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:o,reverseKeyedActors:r,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),ct(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=r.get(t);void 0!==e&&o.get(e)===t&&o.delete(e),r.delete(t),ct(i)},_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);o.set(t,e),r.set(e,t),ct(i)},get:t=>o.get(t),getAll:()=>Object.fromEntries(o),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of o)e&&r.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(o.set(e,t),r.set(t,e))}return i}function ut(t){const e=nt.get(t);if(e)return e;const s=ot.get(t);if(!s)return;const n=s();return nt.set(t,n),ot.delete(t),n}function dt(t,e){const s=nt.get(t);if(s)return nt.set(e,s),!0;const n=ot.get(t);return!!n&&(ot.set(e,n),!0)}function ft(t,e,s=e.system,n){ot.delete(t);const o=at(s),r=n?ut(n):void 0,i=r?.actor===e?r:ut(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===o)return void nt.set(t,i);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=it(s);let u=h.size?new Map(h):rt;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(u===rt&&(u=new Map),u.set(t,e))}nt.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:o}})}function lt(t,e,s=!0){const n=mt(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&ft(e,t.self),e}function pt(t){return!!mt(t)||!!t.self.options?._inert}function yt(t,e){lt(t,e,!1);const s=mt(t);vt.set(e,t);const n=()=>(ft(e,t.self,t.system),ut(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){nt.delete(t),ot.set(t,e)}(e,n),e}const gt=Symbol(),vt=new WeakMap;function mt(t){return t[gt]}function _t(t){return mt(t).materialize()}const xt={[E]:!0,get _parent(){const t=mt(this);return t.parentKnown?t.parent:_t(this).self._parent},get self(){return _t(this).self},get defer(){return _t(this).defer},get id(){return _t(this).id},get logger(){return _t(this).logger},get sessionId(){return _t(this).sessionId},get stopChild(){return _t(this).stopChild},get system(){return _t(this).system},get emit(){return _t(this).emit},get actionExecutor(){return _t(this).actionExecutor}};function St(t,e,s,n,o){const r=e?.(),i=o??r?.actor,c=i?.system,a=i&&c?ht(c,s,o?void 0:r?.systemState):void 0,h=cs(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(h._parent=i._parent),n&&(h._snapshot=n),Object.create(h._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function bt(t,e,s,n){const o=n??(e&&"object"==typeof e?vt.get(e):void 0),r=o?mt(o):void 0,i=e&&"object"==typeof e?function(t){return nt.get(t)}(e):void 0,c=r?.identityProvider??(e&&"object"==typeof e?function(t){const e=nt.get(t);return e?()=>e:ot.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:ve(e)?e.children:{},identityProvider:r?.identityProvider??c,parent:s?._parent??r?.parent??i?.actor._parent,parentKnown:!(!s&&!r?.parentKnown&&!i&&e),materialize:()=>a.materialized??=St(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,o=a.sourceChildren;let r,i;const c=()=>r??=St(t,n,o,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(i)return i;const t=c();return ft(e,t.self,t.system),i=ut(e)}}const h=Object.create(xt);return h[gt]=a,h}function wt(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:r,days:i,hours:c,minutes:a,seconds:h}=o.groups;if(!(r||i||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(r)*24*60*60*1e3+24*u(i)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function It(t,e,s){if("function"==typeof t)return t(s);const n=wt(t,e);return"function"==typeof n?n(s):n}function kt(t,e){return t._stateInputs?.[e]}function Et(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function At(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Ot(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function jt(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of At(t))if(!e.has(s)){const t=Bt(s);for(const s of t)e.add(s)}}else for(const s of Bt(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function Tt(t,e){const s=jt(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Et(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function Mt(t,e){return"compound"===e.type?At(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?At(e).every(e=>Mt(t,e)):"final"===e.type}const $t=t=>"#"===t[0];function Pt(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}function Rt(t,e,s){return!e.children[s]||!("sessionId"in t)||e.children[s]?.sessionId===t.sessionId}function zt(t,e){const s=function(t){const e=Pt(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),o=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>Ue(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...o]:o}function Nt(t,e,s,n){const o=t.entry;t.entry=(t,r)=>(r.raise(s(t),{id:e,delay:n(t)}),"function"==typeof o?o(t,r):void 0);const r=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof r?r(t,s):void 0)}function Kt(t,e,s){const n=De(s.target),o=s.reenter??!1,r=Wt(t,n);Vt(t,r);const i={...s,target:r,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:r?r.map(t=>`#${t.id}`):void 0})};return i}function Dt(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Ct(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function Vt(t,e){if(e&&!(e.length<2))for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){const o=e[s],r=e[n],i=Ct(o,r);if(o===r||Dt(o,r)||Dt(r,o)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function Wt(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if($t(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return qt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return qt(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function Jt(t){const e=De(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?qt(t.parent,e):e);return Vt(t,s),{target:s,source:t,reenter:!1,eventType:""}}function Ut(t){return"history"===t.type}function Bt(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of At(s))t(e)}(t);for(const s of e)for(const n of Ot(s,t))e.add(n);return e}function Lt(t,e){if($t(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function qt(t,e){if("string"==typeof e&&$t(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Te(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=Lt(n,t)}return n}function Ft(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const r=Lt(t,s[e]);n[e]=r,o.push(r)}for(let t=0;t<s.length;t++)o.push(...Ft(n[t],e[s[t]]));return o}function Gt(t,e,s,n,o,r){if("string"==typeof e){const i=Lt(t,e).next(s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=Gt(Lt(t,c),e[c],s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const h=Gt(Lt(t,c),i,s,n,o,r);h&&a.push(...h)}return a.length?a:t.next(s,n,o,r)}function Ht(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Xt(t,e){for(const s of t)if(Ht(s,e))return!0;return!1}function Qt(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function Yt(t,e,s,n){const o=new Set,r=new Map,i=t=>{let o=r.get(t);return o||(o=ne([t],e,s,n),r.set(t,o)),o};for(const e of t){let t=!1;const s=new Set;for(const n of o)if(Qt(i(e),i(n)))if(Ht(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)o.delete(t);o.add(e)}}return Array.from(o)}function Zt(t,e,s,n,o){let r;return i=>{if(!i.to)return re(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)});let c=r?.get(i);return c||(c=re(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)}),(r??=new Map).set(i,c)),c}}function te(t,e,s){const n=e.historyValue,{targets:o}=s(t);if(!o)return[];const r=new Set;for(const t of o)if(Ut(t))if(n[t.id])for(const e of n[t.id])r.add(e);else for(const n of te(Jt(t),e,s))r.add(n);else r.add(t);return[...r]}function ee(t,e){let s=t;for(;"parallel"===s.type;){const t=At(s).find(t=>e.every(e=>e===t||Ht(e,t)));if(!t)break;s=t}return s}function se(t,e,s){const n=te(t,e,s),{reenter:o}=s(t);if(n.every(e=>e===t.source||Ht(e,t.source)))return o?t.source:ee(t.source,n);const[r,...i]=n.concat(t.source);for(const t of Ot(r,void 0))if(i.every(e=>Ht(e,t)))return o?t:ee(t,n);return o?void 0:ee(t.source.machine.root,n)}function ne(t,e,s,n){const o=new Set;for(const r of t){const{targets:t,reenter:i}=n(r);if(t?.length){const t=se(r,s,n);i&&r.source===t&&o.add(t);for(const s of e)Ht(s,t)&&o.add(s)}}return[...o]}function oe(t,e,s,n,o,r,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let h=e.historyValue;const u=e.context,d=1===t.length?t:Yt(t,a,e,Zt(e,n,s,!1,i)),l=Zt(e,n,s,!0,i),p=d.some(t=>{const{targets:e,reenter:s}=l(t);return!!e?.length||!!s}),y=(t,o,r,i)=>{if(2===t.length){const c=[],a=[];let h;const u=L(s,c,a,!0),d=A(s)?j({context:o,event:n,children:r,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},s):{context:o,event:n,parent:s.self._parent,self:s.self,children:r,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},f=t(d,u);return void 0!==f?.context&&(h=W(o,f.context)),[c,h,a]}return[[Object.assign((e,n)=>t(A(s)?j({context:e.context,event:e.event,output:e.output,children:e.children,actions:e.actions,actors:e.actors,input:i},s):{...e,input:i},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let g=e;const v=(t,e)=>{const n=[],o=L(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},_=()=>{const t=ne(d,a,e,l);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>Et(t)&&Ht(t,e):t=>t.parent===e;o??={...h},o[t.id]=i.filter(s)}for(const o of t){const t=kt(e,o.id),[i,h,u]=o.exit?y(o.exit,g.context,e.children,t):[[],void 0,void 0];u?.length&&r.push(...u),h&&(g=Ee(g,{context:h}));const[d,f]=Y(g,n,s,i);g=d,c.push(...f);const l=v(o,g.children);if(l.length){const[t,e]=Y(g,n,s,l);g=t,c.push(...e)}a.delete(o)}h=o||h};!o&&p&&_();let x=g.context;const S=[],b=[];for(const t of d){t.actions&&S.push(...Pe(t.actions));const e=l(t);void 0!==e.context&&(x=W(x,e.context)),e.actions&&S.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&r.push(...b);const w=()=>{const t=t=>{const e=g.machine.root;let o;if(void 0!==t.output&&t.parent){const i=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);o=i&&t.parent===e?i.output:Re(t.output,g.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=r.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);o=e?.output}return void 0===e.output?t.parent===e?o:void 0:Re(e.output,g.context,f(t.id,o),s.self)},i=new Set,u=new Set,p=(t,e)=>{for(const s of t)if(e&&!Ht(s,e)||i.add(s),"parallel"===s.type)for(const t of At(s))Xt(i,t)||(i.add(t),v(t))},v=t=>{if(Ut(t))if(h[t.id]){const e=h[t.id];for(const t of e)i.add(t),v(t);for(const s of e)p(Ot(s,t.parent),void 0)}else{const e=Jt(t),{targets:s}=l(e);for(const n of s??[])i.add(n),e===t.parent?.initial&&u.add(t.parent),v(n);for(const e of s??[])p(Ot(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return Ut(e)||(i.add(e),u.add(e)),v(e),void p(Ot(e,t),void 0)}if("parallel"===t.type)for(const e of At(t))Xt(i,e)||(i.add(e),u.add(e),v(e))}};for(const t of d){const s=se(t,e,l),{targets:n,reenter:o}=l(t);for(const e of n??[])Ut(e)||t.source===e&&t.source===s&&!o||(i.add(e),u.add(e)),v(e);const r=te(t,e,l);for(const e of r){const n=Ot(e,s);"parallel"===s?.type&&n.push(s),p(n,!t.source.parent&&o?void 0:s)}o&&s===t.source&&i.add(t.source)}o&&u.add(e.machine.root);const _={...e._stateInputs};let x=!1;for(const t of d){const{targets:e,input:s}=l(t);if(s&&e)for(const t of e)_[t.id]=s,x=!0}const S=new Set,b={...g.children};for(const o of[...i].sort((t,e)=>t.order-e.order)){a.add(o);const i=[];let h=!1;for(const t of o.invoke){h=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:g.context,event:n,self:s.self}));const r="string"==typeof o?Ve(e.machine,o):o;if(!r)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:g.context,event:n,output:ze(n)}):t.input,a=s.system.createActorRef(r,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:m["@xstate.spawn"],args:[a]}),t.id&&(b[t.id]=a)}h&&(g=Ee(g,{children:b}));let d=g.context,l=!1;const p=_[o.id];if(o.entry){const[t,e,s]=y(o.entry,d,b,p);i.push(...t),s?.length&&r.push(...s),e&&(d=e,l=!0)}if(l&&(g.context=d),u.has(o)){const{actions:t,input:e}=re(o.initial,g,n,s);if(t&&i.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,x=!0}const[v,w]=Y(g,n,s,i);if(g=v,i.length=0,c.push(...w),"final"!==o.type)continue;const I=o.parent;let k="parallel"===I?.type?I:I?.parent,E=k||o;for("compound"===I?.type&&r.push(f(I.id,void 0!==o.output?Re(o.output,g.context,n,s.self,p):void 0));"parallel"===k?.type&&!S.has(k)&&Mt(a,k);){S.add(k);const t={};for(const e of At(k)){if("final"===e.type){t[e.key]=void 0!==e.output?Re(e.output,g.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const o=At(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Re(o.output,g.context,n,s.self,_[o.id]):void 0}r.push(f(k.id,t)),E=k,k=k.parent}k||(g=Ee(g,{status:"done",output:t(E)}))}x&&(g=Ee(g,{_stateInputs:_}))},[I,k]=Y(g,n,s,S);g=I,c.push(...k),x&&x!==e.context&&(g=Ee(g,{context:x})),(o||p)&&w();const E=[...a];if("done"===g.status){const t=[];E.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=kt(g,e.id),[n,,o]=y(e.exit,g.context,g.children,s);t.push(...n),o?.length&&r.push(...o)}});const[e,o]=Y(g,n,s,t);g=e,c.push(...o);const[i,a]=de(g,n,s);g=i,c.push(...a);const[h,u]=fe(g,n,s);g=h,c.push(...u)}return h===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?g.context!==u?[g===e?Ee(g):g,c]:[g,c]:[Ee(g,{_nodes:E,historyValue:h}),c]}}function re(t,e,s,n,o){let r;const i=()=>r??=A(n)?j({context:e.context,event:s,output:ze(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:kt(e,t.source.id)},n):{context:e.context,event:s,output:ze(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:kt(e,t.source.id)};if(t.to){const r=[],c=[],a=o?.selectionResult?.reusable?o.selectionResult.result:t.to(i(),L(n,r,c,!1,o?.resolveActions??!0)),h=a?.target?Wt(t.source,Pe(a.target)):void 0,u=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:ze(s)}):t.input);return{targets:h,context:a?.context,reenter:a?.reenter,actions:r,internalEvents:c,input:u}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:ze(s)}):t.input,a="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:a,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:c}}function ie(t,e,r,c,a=[]){let h=t;const u=a.slice();function d(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=h.children[e];if(!n||n.sessionId!==s)return;const o={...h.children};if(delete o[e],r.system._unregister(n),h=Ee(h,{children:o}),u.length){const[,t]=u.at(-1);u[u.length-1]=[h,t]}else u.push([h,[]])}function f(){const e=function(t){const e=[],s=[];for(const o of t){if(!Q(o)||o.type!==n)continue;const{actor:t,logic:r}=o,i=F(t);r===w||r===k?e.push(i):s.push(i)}return[...e,...s]}(u.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===h.status||"error"===h.status);if(e.length||s){const t=s?[...e,H(r,h)]:e;if(u.length){const[e,s]=u.at(-1);u[u.length-1]=[e,[...s,...t]]}else u.push([h,t])}return{snapshot:h,microsteps:u}}function l(t,n){if(!pt(r)&&(e.type===s||(r.system._hasInspectionObservers?.()??1))){const t=r.self._collectedMicrosteps||[];t.push(...n),r.self._collectedMicrosteps=t}u.push(t)}if(e.type===o){const[t,s]=de(h,e,r),[n,o]=fe(t,e,r);return h=Ee(n,{status:"stopped"}),l([h,[...s,...o]],[]),f()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const o="xstate.after.";if(!t.type.startsWith(o))return t;const r=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!r)return t;const i=t.type.slice(13,-r.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:r}}(e,t.machine);if(e.type===i){const t=h.timers[e.id];if(!t)return f();const s={...h.timers};if(delete s[t.id],h=Ee(h,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([h,[]],[]);else{const e="self"===t.target?r.self:t.target;l([h,[G(r,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=new Map,o=h.machine.getTransitionData(h,e,r,n);if(s&&!o.length)return"xstate.error.actor"!==e.type||Rt(e,h,e.actorId)?(h=Ee(t,{status:"error",error:e.error}),l([h,[]],[]),d(e),f()):f();const i=oe(o,t,r,p,!1,c,n);h=i[0],l(i,o),d(e)}if(!c.length&&!1===t.machine._hasEventlessTransitions)return f();let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===h.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t,e=y?le(h,p,r):[];const s=e.length?h:void 0;if(!e.length){if(!c.length)break;p=c.shift(),t=new Map,e=h.machine.getTransitionData(h,p,r,t)}const n=oe(e,h,r,p,!1,c,t);h=n[0],y=h!==s,l(n,e),d(p)}return f()}function ce(t,e,s,n,o){return!!t.to&&ue(t.to,e,s,n,o,n.machine.sources,t.source.id).enabled}const ae=()=>{throw qe};let he;function ue(t,e,s,n,o,r,i){let c;const a=O(o);a&&Fe.push(a);try{c=t(j({context:e,event:s,output:ze(s),value:n.value,children:n.children,actions:r.actions,actors:r.actors,guards:r.guards,delays:r.delays,input:kt(n,i)},o),he??=Z({emit:ae,cancel:ae,log:ae,raise:ae,spawn:ae,sendTo:ae,stop:ae},ae))}catch(t){if(t===qe)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&Fe.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function de(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],r=L(s,o,[]);for(const t of n)r.stop(t);return Y(t,e,s,o)}function fe(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],r=L(s,o,[]);for(const t of n)r.cancel(t);return Y(t,e,s,o)}function le(t,e,s){const n=new Set,o=t.nodes.filter(Et);for(const r of o)t:for(let o=r;o;o=o.parent)if(o.always)for(const r of o.always)if(pe(r,e,t,o,s)){n.add(r);break t}return Yt(Array.from(n),new Set(t.nodes),t,Zt(t,e,s,!1))}function pe(t,e,s,n,o,r){if(t.matches&&!Je(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const r=function(t,e){if(!A(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>O(e)}}),t}({context:s.context,event:e,output:ze(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},o);if(!t.guard(r))return!1}if(t.to){const i=ue(t.to,s.context,e,s,o,n.machine.sources,t.source.id);return r?.set(t,i),i.enabled}return!0}const ye=Object.freeze({});function ge(t){return t===ye||t&&Object.keys(t).length?t:ye}function ve(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const me=function(t){return je(t,this.value)},_e=function(t){return this.tags.has(t)},xe=function(t){return this.machine?._canTransition(this,t)??!1},Se=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:r,toJSON:i,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},be=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},we=function(){return this._stateInputs};function Ie(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function ke(t,e,s){const n={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:Ie(t._nodes),children:ge(t.children),timers:ge(t.timers),historyValue:ge(t.historyValue),_stateInputs:ge(t._stateInputs),_nextTimerId:t._nextTimerId??0,matches:me,hasTag:_e,can:xe,getMeta:be,getInputs:we,toJSON:Se};return s&&ft(n,s),n}function Ee(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,nodes:t.nodes,value:t.value,tags:t.tags,children:ge(s.children),timers:ge(s.timers),historyValue:ge(s.historyValue),_stateInputs:ge(s._stateInputs),_nextTimerId:s._nextTimerId??0,matches:me,hasTag:_e,can:xe,getMeta:be,getInputs:we,toJSON:Se};return dt(t,e),e}const n=ke({...s,value:void 0},t.machine);return dt(t,n),n}function Ae(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function Oe(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Ze,id:n.id};else{const o=Oe(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function je(t,e){const s=Me(t),n=Me(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&je(s[t],n[t]))}function Te(t){if(Ne(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Me(t){if(ve(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(Te(t))}function $e(t){return Ne(t)?t:[t]}function Pe(t){return void 0===t?[]:$e(t)}function Re(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:ze(s),self:n,input:o})}return t}function ze(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Ne(t){return Array.isArray(t)}function Ke(t){return $e(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function De(t){if(void 0!==t&&""!==t)return Pe(t)}function Ce(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Ve(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,o]=s,r=t.getStateNodeById(o).config.invoke,i=(Array.isArray(r)?r[n]:r).src;return"string"==typeof i?t.sources.actors[i]:i}function We(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function Je(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function Ue(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}let Be,Le=0;const qe=new Error("Transition effect"),Fe=[];function Ge(){return Be??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${Be}:${(Le++).toString(36)}`}const He=Object.freeze({});function Xe(t,e){return`${t.sessionId}.${e}`}class Qe{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={systemId:Ge(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef,this._snapshot={_scheduledTimers:s?.scheduler??He,_nextActorId:s?._nextActorId??0}}_recordSent(t,e,s,n,o){if(!this._inspectionObservers?.size||!t)return;const r=t;(r._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})}schedule(t,e,s){const n=Xe(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;this._recordSent(t,n,o.event,s,e)}const r=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:r,dueAt:r+s},a=Xe(t,e);this._snapshot._scheduledTimers===He&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,ct(this);const h=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],ct(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=h}cancel(t,e){const s=Xe(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==He&&delete this._snapshot._scheduledTimers[s],ct(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.id)}}_deliver(t,e,s){const n=e,o=n.logic;if("function"==typeof o?.isInternalEventType&&o.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);n._lastSourceRef=t,e._send(s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),ct(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=(this._children?.delete(t.sessionId)??!1)||e):e=this._children?.delete(t.sessionId)??!1;const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&ct(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&ct(this)}inspect(t){const e=Ce(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}spawnActor(){}startActor(t){t.start()}stopActor(t){t._stop()}terminateActor(t,e){t._terminate(e)}sendEvent(t,e,s){this._recordSent(t,e,s),this._deliver(t,e,s)}emitEvent(t,e){t._emit(e)}scheduleTimer(t,e,s){this.schedule(t,e,s)}cancelTimer(t,e){this.cancel(t,e)}cancelAllTimers(t){this.cancelAll(t)}_relay(t,e,s){if(Fe.length&&Fe.includes(e))throw qe;this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:o,id:r}=t[s];this.scheduleTimer(n,r,Math.max(0,o-(this._clock.now?.()??Date.now())))}}}let Ye=!1;const Ze=1,ts=Object.freeze([]);let es=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ss=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ns(t,e){try{t?.(e)}catch(t){y(t)}}function os(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function rs(t,e){return new is(t,e)}class is{get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=es.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1;const s=e?{...ss,...e}:ss,{clock:n,logger:o,parent:r,syncSnapshot:i,id:c,registryKey:a,inspect:h}=s;var u;this.system=r?r.system:s._systemRef?.current??function(t,e){return new Qe(t,e)}(this,{clock:n,logger:o,snapshot:s.snapshot??s.state,createActorRef:rs}),r||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!r&&this.system.inspect(Ce(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=function(t,e){if(void 0!==e){const s=/^x:(\d+)$/.exec(e),n=s?Number(s[1]):void 0;if(void 0!==n&&Number.isSafeInteger(n)){const e=Math.max(t._snapshot._nextActorId,n+1);e!==t._snapshot._nextActorId&&(t._snapshot._nextActorId=e,ct(t))}return e}const s="x:"+t._snapshot._nextActorId++;return ct(t),s}(this.system,c),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=X(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>this.system.emitEvent(this,t);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===es.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=Ye;try{Ye=!0,t.exec()}finally{Ye=e}};this._processingStatus!==es.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,ft(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=X(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),os(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??ts)ns(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??ts,actions:this._collectedActions??ts,sent:this._collectedSent??ts,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return os(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Ce(t,e,s);if(this._processingStatus!==es.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":ns(n.complete);break;case"error":{const t=this._snapshot.error;n.error?ns(n.error,t):y(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const r=Ce(s,n,o);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,r.next?.(n))},error:r.error,complete:r.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===es.Running)return this;if(this._processingStatus===es.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=es.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,p(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,p(this.options.input)):(function(t,e,s){const n=nt.get(t),o=at(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===o&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=o,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??{};for(const e of Object.values(t))this.system.scheduleTimer(this,e.id,e.delay);this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=X(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let n=this._snapshot;try{const[s,o]=e;n=s,this._setSnapshot(n),os(o,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===o&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ns(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===es.Stopped?this:(this.mailbox?.clear(),this._processingStatus===es.NotStarted?(this._processingStatus=es.Stopped,this.system._unregister(this),this):(this._send({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??ts)ns(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,ns(n,t)}this.observers.clear(),e&&y(t)}else this._parent||y(t);var e,s,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===es.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=es.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===es.Stopped)return;let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Ze,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function cs(t,e){return new is(t,e)}function as(t,e){const s=t.check(e);if(s)throw s}const hs=new WeakMap;function us(t,e,s){const n=function(t){let e=hs.get(t);return e||(e=new Map,hs.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const o=s();n.set(e??Symbol(),{cleanup:"function"==typeof o?o:void 0})}function ds(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[$("xstate.logic.cleanup",()=>function(t){const e=hs.get(t);if(e){for(const{cleanup:t}of e.values())t?.();hs.delete(t)}}(n.self))]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],i={},c={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:M,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(G(n,e,t))},raise:t=>{r.push(G(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(r.push($("xstate.logic.effect",(e=n.self.system)=>us(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const o=t;r.push($("xstate.logic.effect",(t=n.self.system)=>us(n.self,void 0,()=>o(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(i).length)&&(h.effects={...e.effects,...a?.effects,...i}),X(n,e,[h,r])},s=(s,o,r)=>{t.validator&&as(t.validator,{kind:"event",logic:n,event:o,eventOrigin:r.self._lastSourceRef?"actor":"external"});const i=e(s,o,r);return t.validator&&as(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[o,r]=s(t,p(t.input),e);Object.assign(t,o);for(const t of r)e.actionExecutor(t)},initialTransition:(e,o)=>{t.validator&&as(t.validator,{kind:"input",logic:n,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(i.context=r),s({...i},p(e),o)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const fs=ds({context:void 0,run:()=>{}});const ls=new WeakMap;const ps={};class ys{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.schemas=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._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("history"===t.type&&!("string"==typeof e.target&&e.target.trim().length>0||Array.isArray(e.target)&&e.target.length>0&&e.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(`Missing history target on "${t.id}"`);if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const r=n[o];s[r]=e(t[r],r,t,o)}return s}(this.config.states,(t,e)=>new ys(t,{_parent:this,_key:e,_machine:this.machine})):ps,"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=Pe(t.tags).slice(),this.invoke=Pe(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(r=this.id,`${e}.${r}`);var r;const i=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===o.length)return[];const r=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;r.push({event:c(n,t.id),timerId:a(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&r.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:h(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)r.push({event:u(t.id),timerId:d(t.id),resolveEvent:({children:e})=>u(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Rt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const f=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:o,delay:i,transitions:c,fromDelaysMap:a}of r){Nt(t,s,n??(()=>e),e=>It(i,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:r,...h}=e;for(const t of Ke(c))f.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(h).filter(([,t])=>void 0!==t))},event:r,delay:i,_eventMatcher:o})}return f.map(e=>({...Kt(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,gs(n,e=>Kt(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,gs(t.config.onDone,s=>Kt(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,gs(t.config.onError,e=>Kt(t,s,e)))}const n=(e,s,n)=>Kt(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Rt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:o,to:r,reenter:i,...c}=s;return Kt(t,e,{...c,reenter:i,to:(t,e)=>{if(r){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),i=r(t,o);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:o,reenter:i}}})};for(const e of t.invoke){const r=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Rt(t,s,e.id)}),i=void 0!==e.timeout?d(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=gs(e.onDone,e=>{const s=r(e);return i?o(c,s,i):Kt(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,gs(e.onError,e=>{const s=r(e);return i?o(n,s,i):Kt(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,gs(e.onSnapshot,e=>Kt(t,n,r(e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[Kt(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=gs(this.config.always,t=>Kt(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return function(t,e,s){let n=ls.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ls.set(t,n)),n[e]}(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state "${s}" not found on "#${t.id}"`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s,n){const o=function(t){const e=Pt(t);return e?`${t.type}|${e}`:t.type}(e);let r=this._candidateCache?.get(o);r||(r=zt(this,e),(this._candidateCache??=new Map).set(o,r));for(const o of r){if(pe(o,e,t,this,s,n))return[o]}}}function gs(t,e){const s=Ke(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let vs,ms;function _s(){if(ms)return ms;const t=vs??=cs({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return ms={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},ms}class xs{constructor(t,e,s){this.config=t,this.validator=s,this.version=void 0,this.schemas=void 0,this.sources=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._hasEventlessTransitions=void 0,this._json=void 0,this.id=t.id||"(machine)",this.sources={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.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ys(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,r=n.config.route,i=({event:t})=>t.to===`#${o}`;if("function"==typeof r)return e.push(Kt(t,"xstate.route",{guard:i,to:t=>{const e=r(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=r,h={...a,guard:i,target:`#${o}`};e.push(Kt(t,"xstate.route",h))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.sources,r=new xs(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}},this.validator);return r._json=this._json,r}resolveState(t){const e=(s=this.root,n=t.value,Tt(s,jt(Ft(s,n))));var s,n;const o=jt(Ft(this.root,e));return ke({_nodes:[...o],value:e,context:t.context||{},children:{},status:Mt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??bt(this,t);this.validator&&as(this.validator,{kind:"event",logic:this,event:e,eventOrigin:s&&s.self._lastSourceRef?"actor":"external"}),n&&lt(o,t,!1);const r=this._transitionFast(t,e,o);if(r){n&&lt(o,r,!1);const e=n&&r!==t?yt(o,r):this._attachPureActorRef(r,o);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=ie(t,e,o,[]);n&&lt(o,i,!1);const a=n?i===t?i:yt(o,i):this._attachPureActorRef(i,o),h=this._collectEffects(c);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:a,effects:h}),[a,h]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return pt(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||ft(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const o=n.transitions.get(e.type);if(1!==o?.length)return;const r=o[0];if(r.guard||r.actions||r.to||r.reenter||r.input||"function"==typeof r.context||r.target&&1!==r.target.length)return;const i=r.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==r.context?{...t.context,...r.context}:t.context;if(!pt(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(r),s.self._collectedMicrosteps=t}return Ee(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=ie(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s,n){return Gt(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(Ue(t,e))return!0;return!1}_canTransition(t,e){const s=_s(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=re(o,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||ce(o,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return l("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=ke({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},r=function(t,e,s){return(n,o)=>{const r=Object.entries(e).find(([,t])=>t===n)?.[0],i=t.system.createActorRef(n,{id:o?.id,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:r??n,registryKey:o?.registryKey});return s[i.id]=i,i}}(t,this.sources.actors,o),i=s(function(t,e){return A(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:r,input:e.input,actors:this.sources.actors},t)),[c]=Y(n,e,t,[]);return i&&(c.context=i),Object.keys(o).length>0&&(c.children={...c.children,...o}),c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&as(this.validator,{kind:"input",logic:this,input:t});const s=!e,o=e??bt(this),r=p(t),i=[],c=this._getPreInitialState(o,r),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:P,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t)),h=(t,e)=>{s&&lt(o,t,!1);const n=s?yt(o,t):this._attachPureActorRef(t,o,!0),r=this._collectEffects(e);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:n,effects:r}),[n,r]};try{const[t,e]=function(t,e,s,n,o){return oe([{target:[...Bt(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,c,o,r,i),{snapshot:s,microsteps:n}=ie(t,r,o,i,[[t,[...a,...e]]]);return h(s,n)}catch(t){if(!this.root.config.onError)throw t;const e=ie(c,l("execution",t),o,[],[[c,a]]);return h(e.snapshot,e.microsteps)}}start(t){if(!t?.children)return;const e=t.children;for(const t in e){if(!Object.hasOwn(e,t))continue;const s=e[t];s._rehydrated&&"active"===s.getSnapshot?.().status&&s.start()}}getStateNodeById(t){const e=Te(t),s=e.slice(1),n=$t(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return qt(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:o,machine:r,children:i,timers:c,context:a,can:h,hasTag:u,matches:d,getMeta:f,getInputs:l,toJSON:p,...y}=t,g={},v={};for(const t in i){const s=i[t];g[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}for(const e in c){const s=c[e];let n,o=s.event;if("xstate.timeout.actor"===o.type&&(o={...o},delete o.sessionId),"self"===s.target)n="self";else{const o=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==ut(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}v[e]={id:s.id,delay:s.delay,type:s.type,event:o,target:n}}const m={...y,_nextActorId:ut(t)?.systemState.snapshot._nextActorId,context:Oe(a),children:g,timers:v,historyValue:Ae(y.historyValue)};return n&&Object.keys(n).length>0&&(m.stateInputs=n),void 0!==r.version&&(m.machine={id:r.id,version:r.version},m.version=r.version),m}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??bt(this),o=t.machine,r=t.version,i="string"==typeof o?.version?o.version:r;if(void 0!==r&&void 0!==o?.version&&o.version!==r)throw new Error(`Persisted snapshot version '${r}' conflicts with machine version '${o.version}'.`);if(o&&"string"==typeof o.id&&o.id!==this.id)throw new Error(`Machine ID mismatch: persisted snapshot machine '${o.id}' does not match '${this.id}'.`);if(i!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${i}' does not match machine version '${this.version}'.`);t=e(t,i)}const c=t,a={},h=c.children;for(const t of Object.keys(h)){const e=h[t],s=e.snapshot,o=e.src,r="string"==typeof o?Ve(this,o):o;if(!r){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof o?o:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(r,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});i._rehydrated=!0,a[t]=i}const d={},f=c.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=a[t];e&&(s=u(t,e.sessionId))}const o="string"==typeof e.target?"self"===e.target?"self":a[e.target]:n.self._parent;if(!o){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}d[t]={...e,event:s,target:o}}const l=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof ys)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(c.historyValue),p=Array.from(jt(Ft(this.root,c.value))),{version:y,...g}=t,v=ke({...g,children:a,timers:d,_nodes:p,value:c.value,historyValue:l,_stateInputs:c.stateInputs??{}},this,n.self),m=new WeakSet;return function t(e){if(!m.has(e)){m.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Ze){e[s]=a[n.id];continue}t(n)}}}}(v.context),s?(lt(n,v,!1),yt(n,v)):this._attachPureActorRef(v,n)}}function Ss(t){return JSON.stringify(t)}function bs(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t.nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const ws=()=>(t,e)=>Vs(t,e),Is=()=>(t,e)=>Ws(t,e);class ks{getDefaultOptions(){return{serializeState:t=>Ss(t),serializeEvent:t=>Ss(t),serializeTransition:(t,e)=>`${Ss(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ve(t.state)?`Reaches ${bs(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=Ss)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(ws(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(zs(n,e)))}return s}getSimplePaths(t){return this.getPaths(Is(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(zs(n,e)))}return s}getPathsFromEvents(t,e){return Cs(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return Ks(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:Ss,serializeEvent:Ss,...s},{formatColor:o,serializeState:r,serializeEvent:i}=n,{state:c}=t,a=r(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=r(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function Es(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>Es(t[s],e[s]))}function As(t,e,s,{serializeEvent:n}){if(!e||s&&Es(s.value,t.value))return"";const o=s?` from ${Ss(s.value)}`:"";return` via ${n(e)}${o}`}function Os(){const t=cs(fs);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function js(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function Ts(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function Ms(t){return JSON.stringify(t)}function $s(t,e){const{events:s,...n}=e??{};return{serializeState:Ts,serializeEvent:Ms,events:t=>{const e="function"==typeof s?s(t):s??[];return We(t).flatMap(t=>{const s=e.filter(e=>Je(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(Os(),e?.input),...n}}function Ps(){return{serializeState:t=>JSON.stringify(t),serializeEvent:Ms}}function Rs(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?$s(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:Ms,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function zs(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function Ns(t){return Array.isArray(t)?t[0]:t}function Ks(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:r,filterEvents:i,limit:c,fromState:a,stopWhen:h}=Rs(t,e),u=Os(),d={};let f=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(f++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(d[y])continue;if(p.set(y,t),d[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof r?r(t):r;for(const e of g){if(i&&!i(t,e))continue;const o=Ns(s(t,e,u));d[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return d}function Ds(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function Cs(t,e,s){const n=Rs(t,{events:e,...s},(o=t)&&o instanceof xs?$s(t):Ps());var o;const r=Os(),i=n.fromState??t.getInitialSnapshot(r,s?.input),{serializeState:c,serializeEvent:a}=n,h=Ks(t,n),u=new Map,d=[],f=c(i,void 0,void 0);u.set(f,i);let l=f,p=i;for(const t of e){d.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,p=s}return n.toState&&!n.toState(p)?[]:[Ds({state:p,steps:d,weight:d.length})]}function Vs(t,e){const s=Rs(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(Os(),e?.input),r=Ks(t,s),i=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),i.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=i.get(t);for(const o of Object.keys(r[t].transitions)){const{state:a,event:d}=r[t].transitions[o],f=n(a,d,e);if(c.set(f,a),i.has(f)){const{weight:e}=i.get(f);e>s+1&&i.set(f,{weight:s+1,state:t,event:d})}else i.set(f,{weight:s+1,state:t,event:d});u.has(f)||h.add(f)}u.add(t),h.delete(t)}const d={},f=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),r=e?d[e].paths[0].steps.concat({state:c.get(e),event:s}):[];f.push({state:o,steps:r,weight:t}),d[n]={state:o,paths:[{state:o,steps:r,weight:t}]}}),s.toState?f.filter(t=>s.toState(t.state)).map(Ds):f.map(Ds)}function Ws(t,e){const s=Rs(t,e),n=Os(),o=s.fromState??t.getInitialSnapshot(n,e?.input),r=s.serializeState,i=Ks(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:o}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const u=c.get(t),f=r(n,o,u);c.set(f,n),a.vertices.has(f)||(a.edges.add(s),h.push({state:c.get(t),event:o}),d(f,e))}}h.pop(),a.vertices.delete(t)}const f=r(o,void 0);c.set(f,o);for(const t of Object.keys(i))d(f,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(Ds):l.map(Ds)}t.TestModel=ks,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=ws,t.createSimplePathsGen=Is,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??Ss,n=e?.serializeTransition??As,{events:o,...r}=e??{};return new ks(t,{serializeState:(t,e,o)=>`${Ts(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e.nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return We(t).flatMap(t=>e.some(e=>Je(e,t))?e.filter(e=>Je(e,t)):[t])},...r})},t.getAdjacencyMap=Ks,t.getPathsFromEvents=Cs,t.getShortestPaths=Vs,t.getSimplePaths=Ws,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],r=t(o);return e.push(o,...r),e},[])},t.joinPaths=zs,t.serializeSnapshot=Ts,t.toDirectedGraph=function t(e){const s=e instanceof xs?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const r={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=r;return{source:s.id,target:n.id,label:t}}};return r})),o={id:s.id,stateNode:s,children:js(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.spawn",o="@xstate.stop",r="@xstate.terminate",i="xstate.timer";function c(t,e){return{type:"xstate.after",delay:t,stateId:e}}function a(t,e){return`xstate.after.${t}.${e}`}function h(t){return`xstate.timeout.${t}`}function u(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function d(t){return`xstate.timeout.actor.${t}`}function f(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function l(t,e){return{type:`xstate.error.${t}`,error:e}}function p(t){return{type:s,input:t}}function y(t){setTimeout(()=>{throw t})}const g="function"==typeof Symbol&&Symbol.observable||"@@observable";function v(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const m={"@xstate.spawn":t=>t.system.spawnActor(t._parent,t),"@xstate.start":t=>t.system.startActor(t),"@xstate.raise":(t,e,s)=>t.system.scheduleTimer(t.self,s.id,s?.delay??0),"@xstate.sendTo":(t,e,s,n)=>(v(s),void 0!==n?.delay?t.system.scheduleTimer(t.self,n.id,n?.delay??0):t.system._relay(t.self,e,s)),"@xstate.cancel":(t,e)=>t.system.cancelTimer(t.self,e),"@xstate.stop":(t,e)=>t.system.stopActor(e),"@xstate.terminate":(t,e)=>t.system.terminateActor(t,e)},_=new WeakMap;function x(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const r=t(e.input,{self:s,system:n});if(!r)return;let i,c=!1;const a=()=>{c||(c=!0,r.unsubscribe(),i?.unsubscribe())},h=s._parent;h&&(i=h.subscribe({complete:a,error:a})),_.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===o?(_.get(s)?.unsubscribe(),_.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function S(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function b(){return x(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const r="*"!==e&&e.endsWith(".*");return t.on(r?"*":e,t=>{r&&!Ue(t.type,e)||S(n,o,()=>s(t))})})}const w=b();function I(){return x(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:r,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&o?S(s,n,()=>o(t.output)):"error"===t.status&&r?S(s,n,()=>r(t.error)):"active"===t.status&&i&&S(s,n,()=>i(t))},error:t=>{r&&S(s,n,()=>r(t))},complete:()=>{}})})}const k=I(),E=Symbol();function A(t){return!!t[E]}function O(t){return A(t)?t._parent:t.self._parent}function j(t,e){if(!A(e)){const s=t,n=e.self;return s.self=n,s.system=e.system,s.parent=n._parent,s}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},system:{enumerable:!0,get:()=>e.system},parent:{enumerable:!0,get:()=>O(e)}}),t}function T(){return this.action?.(...this.args)}function $(t=this.source.system){return t.emitEvent(this.source,this.event)}function M(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function P(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function R(t=this.actor.system){return t.startActor(this.actor)}function z(t=this.source.system){return t.stopActor(this.actor)}function N(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function K(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function D(t=this.source.system){return v(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function C(t=this.source.system){return t.cancelTimer(this.source,this.id)}function V(t,e,s){if(!Q(e))return t;if("@xstate.cancel"===e.type){if(!t.timers?.[e.id])return t;const s={...t.timers};return delete s[e.id],{...t,timers:s}}if("@xstate.raise"!==e.type&&"@xstate.sendTo"!==e.type||void 0===e.delay)return t;let n=t._nextTimerId??0;const o=e.id??"xstate.timer.auto."+n++;e.id=o;const r="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:r}},_nextTimerId:n}}function W(t,e){return{...t,...e}}function J(t,e,...s){const n={action:e,args:s};return t.push(n),n}function U(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor}};const n={...t.children};let o=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(o=!0,delete n[t]);if(!o)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function B(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}function L(t,e,s,n=!1,o=!0){const r={cancel:s=>{J(e,m["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{J(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?J(e,m["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{if(!o)return{id:n?.id??n?.registryKey??s.id};const r=t.system.createActorRef(s,{...n,parent:t.self});return function(t,e,s){J(t,m["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s??e.id}}(e,r,n?.id),r},sendTo:(n,o,r)=>{n?J(e,m["@xstate.sendTo"],t,n,o,r):s.push(l("communication",{message:"Unable to send event to an undefined actor",event:o}))},stop:s=>{if(s){J(e,m["@xstate.stop"],t,s).childUpdate={type:"remove",actor:s}}}};return n&&Object.assign(r,{listen:(s,n,r)=>{if(!o)return{id:void 0};const i={actor:s,eventType:n,mapper:r},c=t.system.createActorRef(w,{input:i,parent:t.self});return J(e,m["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!o)return{id:void 0};const r={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(k,{input:r,parent:t.self});return J(e,m["@xstate.spawn"],i),i}}),Z(r,(t,...s)=>{J(e,t,...s)})}function q(t,e){switch(t){case m["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:P,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case m["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:K,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case m["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:D,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case m["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:C,source:e[0].self,id:t}}case m["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:z,source:e[0].self,actor:t,id:t.id}}default:return}}function F(t){const e=[t];return{kind:"builtin",exec:R,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function G(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:D,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function H(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},n=[t.self,s];return{kind:"builtin",exec:N,type:r,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function X(t,e,[s,n]){const o="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,c=n.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===r);return!o||i||c?[s,n]:[s,[...n,H(t,s)]]}function Q(t){return"builtin"===t.kind}function Y(t,e,s,n){let o=t;const r=[];for(const i of n){const n=A(s)?j({context:o.context,event:e,output:ze(e),children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:o.context,event:e,output:ze(e),self:s.self,system:s.system,parent:s.self._parent,children:o.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=B(i),h=c?i:!!a&&a.action.bind(null,...a.args);let u;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;u=s}if(a?.childUpdate&&(o=U(o,a.childUpdate,s)),h&&"_special"in h){r.push({kind:"action",exec:T,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:u,args:[],action:void 0});const t=h(n,st);t&&("context"in t||"children"in t)&&(o={...o,...void 0!==t.context?{context:W(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!h||!("resolve"in h)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?q(i.action,i.args):void 0,e="object"==typeof i&&null!==i&&!a,n={kind:t?"builtin":e?"emit":"action",type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type:i.name||"(anonymous)",params:t?void 0:u,args:"object"==typeof i&&"action"in i?i.args:[],...t?{}:e?{source:s.self,event:i}:{action:a?.action??(c?i:void 0)},...t?{}:{exec:e?$:T},...t};o=V(o,n,s),r.push(n);continue}}return[o,r]}function Z(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:tt,emit:tt,log:tt,raise:tt,spawn:et,sendTo:tt,stop:tt,listen:et,subscribeTo:et,...t}),s}const tt=()=>{},et=()=>({}),st=Z({},tt);const nt=new WeakMap,ot=new WeakMap,rt=new Map;function it(t){const e=t._peekKeyedActors;return e?e.call(t)??rt:t.keyedActors}function ct(t){t._snapshotVersion++}function at(t){return t._snapshotVersion}function ht(t,e,s){const n=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),o=new Map(s?.keyedActors??it(t)),r=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:o,reverseKeyedActors:r,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),ct(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=r.get(t);void 0!==e&&o.get(e)===t&&o.delete(e),r.delete(t),ct(i)},_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);o.set(t,e),r.set(e,t),ct(i)},get:t=>o.get(t),getAll:()=>Object.fromEntries(o),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of o)e&&r.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(o.set(e,t),r.set(t,e))}return i}function ut(t){const e=nt.get(t);if(e)return e;const s=ot.get(t);if(!s)return;const n=s();return nt.set(t,n),ot.delete(t),n}function dt(t,e){const s=nt.get(t);if(s)return nt.set(e,s),!0;const n=ot.get(t);return!!n&&(ot.set(e,n),!0)}function ft(t,e,s=e.system,n){ot.delete(t);const o=at(s),r=n?ut(n):void 0,i=r?.actor===e?r:ut(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===o)return void nt.set(t,i);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=it(s);let u=h.size?new Map(h):rt;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(u===rt&&(u=new Map),u.set(t,e))}nt.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:o}})}function lt(t,e,s=!0){const n=mt(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&ft(e,t.self),e}function pt(t){return!!mt(t)||!!t.self.options?._inert}function yt(t,e){lt(t,e,!1);const s=mt(t);vt.set(e,t);const n=()=>(ft(e,t.self,t.system),ut(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){nt.delete(t),ot.set(t,e)}(e,n),e}const gt=Symbol(),vt=new WeakMap;function mt(t){return t[gt]}function _t(t){return mt(t).materialize()}const xt={[E]:!0,get _parent(){const t=mt(this);return t.parentKnown?t.parent:_t(this).self._parent},get self(){return _t(this).self},get defer(){return _t(this).defer},get id(){return _t(this).id},get logger(){return _t(this).logger},get sessionId(){return _t(this).sessionId},get stopChild(){return _t(this).stopChild},get system(){return _t(this).system},get emit(){return _t(this).emit},get actionExecutor(){return _t(this).actionExecutor}};function St(t,e,s,n,o){const r=e?.(),i=o??r?.actor,c=i?.system,a=i&&c?ht(c,s,o?void 0:r?.systemState):void 0,h=cs(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(h._parent=i._parent),n&&(h._snapshot=n),Object.create(h._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function bt(t,e,s,n){const o=n??(e&&"object"==typeof e?vt.get(e):void 0),r=o?mt(o):void 0,i=e&&"object"==typeof e?function(t){return nt.get(t)}(e):void 0,c=r?.identityProvider??(e&&"object"==typeof e?function(t){const e=nt.get(t);return e?()=>e:ot.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:ve(e)?e.children:{},identityProvider:r?.identityProvider??c,parent:s?._parent??r?.parent??i?.actor._parent,parentKnown:!(!s&&!r?.parentKnown&&!i&&e),materialize:()=>a.materialized??=St(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,o=a.sourceChildren;let r,i;const c=()=>r??=St(t,n,o,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(i)return i;const t=c();return ft(e,t.self,t.system),i=ut(e)}}const h=Object.create(xt);return h[gt]=a,h}function wt(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:r,days:i,hours:c,minutes:a,seconds:h}=o.groups;if(!(r||i||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(r)*24*60*60*1e3+24*u(i)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function It(t,e,s){if("function"==typeof t)return t(s);const n=wt(t,e);return"function"==typeof n?n(s):n}function kt(t,e){return t._stateInputs?.[e]}function Et(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function At(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Ot(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function jt(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of At(t))if(!e.has(s)){const t=Bt(s);for(const s of t)e.add(s)}}else for(const s of Bt(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function Tt(t,e){const s=jt(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Et(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function $t(t,e){return"compound"===e.type?At(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?At(e).every(e=>$t(t,e)):"final"===e.type}const Mt=t=>"#"===t[0];function Pt(t){switch(t.type){case"xstate.done.actor":case"xstate.error.actor":return`${t.type}.${t.actorId}`;case"xstate.snapshot.actor":return`xstate.snapshot.${t.actorId}`;case"xstate.done.state":return`xstate.done.state.${t.stateId}`;case"xstate.after":return`xstate.after.${t.delay}.${t.stateId}`;case"xstate.timeout":return`xstate.timeout.${t.stateId}`;case"xstate.timeout.actor":return`xstate.timeout.actor.${t.actorId}`;default:return}}function Rt(t,e,s){return!e.children[s]||!("sessionId"in t)||e.children[s]?.sessionId===t.sessionId}function zt(t,e){const s=function(t){const e=Pt(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),o=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>Ue(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...o]:o}function Nt(t,e,s,n){const o=t.entry;t.entry=(t,r)=>(r.raise(s(t),{id:e,delay:n(t)}),"function"==typeof o?o(t,r):void 0);const r=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof r?r(t,s):void 0)}function Kt(t,e,s){const n=De(s.target),o=s.reenter??!1,r=Wt(t,n);Vt(t,r);const i={...s,target:r,source:t,reenter:o,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:r?r.map(t=>`#${t.id}`):void 0})};return i}function Dt(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function Ct(t,e){const s=new Set;for(let e=t;e;e=e.parent)s.add(e);for(let t=e;t;t=t.parent)if(s.has(t))return t}function Vt(t,e){if(e&&!(e.length<2))for(let s=0;s<e.length;s++)for(let n=s+1;n<e.length;n++){const o=e[s],r=e[n],i=Ct(o,r);if(o===r||Dt(o,r)||Dt(r,o)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function Wt(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(Mt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return qt(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return qt(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function Jt(t){const e=De(t.config.target);if(!e)return"parallel"===t.parent.type?{target:[t.parent],source:t,reenter:!1,eventType:""}:t.parent.initial;const s=e.map(e=>"string"==typeof e?qt(t.parent,e):e);return Vt(t,s),{target:s,source:t,reenter:!1,eventType:""}}function Ut(t){return"history"===t.type}function Bt(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of At(s))t(e)}(t);for(const s of e)for(const n of Ot(s,t))e.add(n);return e}function Lt(t,e){if(Mt(e))return t.machine.getStateNodeById(e);const s=t.states?.[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function qt(t,e){if("string"==typeof e&&Mt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Te(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=Lt(n,t)}return n}function Ft(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const r=Lt(t,s[e]);n[e]=r,o.push(r)}for(let t=0;t<s.length;t++)o.push(...Ft(n[t],e[s[t]]));return o}function Gt(t,e,s,n,o,r){if("string"==typeof e){const i=Lt(t,e).next(s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=Gt(Lt(t,c),e[c],s,n,o,r);return i&&i.length?i:t.next(s,n,o,r)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const h=Gt(Lt(t,c),i,s,n,o,r);h&&a.push(...h)}return a.length?a:t.next(s,n,o,r)}function Ht(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Xt(t,e){for(const s of t)if(Ht(s,e))return!0;return!1}function Qt(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function Yt(t,e,s,n){const o=new Set,r=new Map,i=t=>{let o=r.get(t);return o||(o=ne([t],e,s,n),r.set(t,o)),o};for(const e of t){let t=!1;const s=new Set;for(const n of o)if(Qt(i(e),i(n)))if(Ht(e.source,n.source))s.add(n);else{if("final"!==n.source.type||"final"===e.source.type){t=!0;break}s.add(n)}if(!t){for(const t of s)o.delete(t);o.add(e)}}return Array.from(o)}function Zt(t,e,s,n,o){let r;return i=>{if(!i.to)return re(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)});let c=r?.get(i);return c||(c=re(i,t,e,s,{resolveActions:n,selectionResult:o?.get(i)}),(r??=new Map).set(i,c)),c}}function te(t,e,s){const n=e.historyValue,{targets:o}=s(t);if(!o)return[];const r=new Set;for(const t of o)if(Ut(t))if(n[t.id])for(const e of n[t.id])r.add(e);else for(const n of te(Jt(t),e,s))r.add(n);else r.add(t);return[...r]}function ee(t,e){let s=t;for(;"parallel"===s.type;){const t=At(s).find(t=>e.every(e=>e===t||Ht(e,t)));if(!t)break;s=t}return s}function se(t,e,s){const n=te(t,e,s),{reenter:o}=s(t);if(n.every(e=>e===t.source||Ht(e,t.source)))return o?t.source:ee(t.source,n);const[r,...i]=n.concat(t.source);for(const t of Ot(r,void 0))if(i.every(e=>Ht(e,t)))return o?t:ee(t,n);return o?void 0:ee(t.source.machine.root,n)}function ne(t,e,s,n){const o=new Set;for(const r of t){const{targets:t,reenter:i}=n(r);if(t?.length){const t=se(r,s,n);i&&r.source===t&&o.add(t);for(const s of e)Ht(s,t)&&o.add(s)}}return[...o]}function oe(t,e,s,n,o,r,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let h=e.historyValue;const u=e.context,d=1===t.length?t:Yt(t,a,e,Zt(e,n,s,!1,i)),l=Zt(e,n,s,!0,i),p=d.some(t=>{const{targets:e,reenter:s}=l(t);return!!e?.length||!!s}),y=(t,o,r,i)=>{if(2===t.length){const c=[],a=[];let h;const u=L(s,c,a,!0),d=A(s)?j({context:o,event:n,children:r,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},s):{context:o,event:n,parent:s.self._parent,self:s.self,children:r,system:s.system,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},f=t(d,u);return void 0!==f?.context&&(h=W(o,f.context)),[c,h,a]}return[[Object.assign((e,n)=>t(A(s)?j({context:e.context,event:e.event,output:e.output,children:e.children,actions:e.actions,actors:e.actors,input:i},s):{...e,input:i},n),"_special"in t?{_special:!0}:{})],void 0,void 0]};let g=e;const v=(t,e)=>{const n=[],o=L(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&o.stop(t)}return n},_=()=>{const t=ne(d,a,e,l);let o;t.sort((t,e)=>e.order-t.order);const i=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>Et(t)&&Ht(t,e):t=>t.parent===e;o??={...h},o[t.id]=i.filter(s)}for(const o of t){const t=kt(e,o.id),[i,h,u]=o.exit?y(o.exit,g.context,e.children,t):[[],void 0,void 0];u?.length&&r.push(...u),h&&(g=Ee(g,{context:h}));const[d,f]=Y(g,n,s,i);g=d,c.push(...f);const l=v(o,g.children);if(l.length){const[t,e]=Y(g,n,s,l);g=t,c.push(...e)}a.delete(o)}h=o||h};!o&&p&&_();let x=g.context;const S=[],b=[];for(const t of d){t.actions&&S.push(...Pe(t.actions));const e=l(t);void 0!==e.context&&(x=W(x,e.context)),e.actions&&S.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&r.push(...b);const w=()=>{const t=t=>{const e=g.machine.root;let o;if(void 0!==t.output&&t.parent){const i=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);o=i&&t.parent===e?i.output:Re(t.output,g.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=r.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);o=e?.output}return void 0===e.output?t.parent===e?o:void 0:Re(e.output,g.context,f(t.id,o),s.self)},i=new Set,u=new Set,p=(t,e)=>{for(const s of t)if(e&&!Ht(s,e)||i.add(s),"parallel"===s.type)for(const t of At(s))Xt(i,t)||(i.add(t),v(t))},v=t=>{if(Ut(t))if(h[t.id]){const e=h[t.id];for(const t of e)i.add(t),v(t);for(const s of e)p(Ot(s,t.parent),void 0)}else{const e=Jt(t),{targets:s}=l(e);for(const n of s??[])i.add(n),e===t.parent?.initial&&u.add(t.parent),v(n);for(const e of s??[])p(Ot(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return Ut(e)||(i.add(e),u.add(e)),v(e),void p(Ot(e,t),void 0)}if("parallel"===t.type)for(const e of At(t))Xt(i,e)||(i.add(e),u.add(e),v(e))}};for(const t of d){const s=se(t,e,l),{targets:n,reenter:o}=l(t);for(const e of n??[])Ut(e)||t.source===e&&t.source===s&&!o||(i.add(e),u.add(e)),v(e);const r=te(t,e,l);for(const e of r){const n=Ot(e,s);"parallel"===s?.type&&n.push(s),p(n,!t.source.parent&&o?void 0:s)}o&&s===t.source&&i.add(t.source)}o&&u.add(e.machine.root);const _={...e._stateInputs};let x=!1;for(const t of d){const{targets:e,input:s}=l(t);if(s&&e)for(const t of e)_[t.id]=s,x=!0}const S=new Set,b={...g.children};for(const o of[...i].sort((t,e)=>t.order-e.order)){a.add(o);const i=[];let h=!1;for(const t of o.invoke){h=!0;let o=t.logic;"function"==typeof o&&(o=o({actors:e.machine.sources.actors,context:g.context,event:n,self:s.self}));const r="string"==typeof o?Ve(e.machine,o):o;if(!r)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:g.context,event:n,output:ze(n)}):t.input,a=s.system.createActorRef(r,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:m["@xstate.spawn"],args:[a]}),t.id&&(b[t.id]=a)}h&&(g=Ee(g,{children:b}));let d=g.context,l=!1;const p=_[o.id];if(o.entry){const[t,e,s]=y(o.entry,d,b,p);i.push(...t),s?.length&&r.push(...s),e&&(d=e,l=!0)}if(l&&(g.context=d),u.has(o)){const{actions:t,input:e}=re(o.initial,g,n,s);if(t&&i.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e,x=!0}const[v,w]=Y(g,n,s,i);if(g=v,i.length=0,c.push(...w),"final"!==o.type)continue;const I=o.parent;let k="parallel"===I?.type?I:I?.parent,E=k||o;for("compound"===I?.type&&r.push(f(I.id,void 0!==o.output?Re(o.output,g.context,n,s.self,p):void 0));"parallel"===k?.type&&!S.has(k)&&$t(a,k);){S.add(k);const t={};for(const e of At(k)){if("final"===e.type){t[e.key]=void 0!==e.output?Re(e.output,g.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=r.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const o=At(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?Re(o.output,g.context,n,s.self,_[o.id]):void 0}r.push(f(k.id,t)),E=k,k=k.parent}k||(g=Ee(g,{status:"done",output:t(E)}))}x&&(g=Ee(g,{_stateInputs:_}))},[I,k]=Y(g,n,s,S);g=I,c.push(...k),x&&x!==e.context&&(g=Ee(g,{context:x})),(o||p)&&w();const E=[...a];if("done"===g.status){const t=[];E.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=kt(g,e.id),[n,,o]=y(e.exit,g.context,g.children,s);t.push(...n),o?.length&&r.push(...o)}});const[e,o]=Y(g,n,s,t);g=e,c.push(...o);const[i,a]=de(g,n,s);g=i,c.push(...a);const[h,u]=fe(g,n,s);g=h,c.push(...u)}return h===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?g.context!==u?[g===e?Ee(g):g,c]:[g,c]:[Ee(g,{_nodes:E,historyValue:h}),c]}}function re(t,e,s,n,o){let r;const i=()=>r??=A(n)?j({context:e.context,event:s,output:ze(s),value:e.value,children:e.children,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:kt(e,t.source.id)},n):{context:e.context,event:s,output:ze(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:kt(e,t.source.id)};if(t.to){const r=[],c=[],a=o?.selectionResult?.reusable?o.selectionResult.result:t.to(i(),L(n,r,c,!0,o?.resolveActions??!0)),h=a?.target?Wt(t.source,Pe(a.target)):void 0,u=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:ze(s)}):t.input);return{targets:h,context:a?.context,reenter:a?.reenter,actions:r,internalEvents:c,input:u}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:ze(s)}):t.input,a="function"==typeof t.context?t.context(i()):t.context;return{targets:t.target,context:a,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:c}}function ie(t,e,r,c,a=[]){let h=t;const u=a.slice();function d(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=h.children[e];if(!n||n.sessionId!==s)return;const o={...h.children};if(delete o[e],r.system._unregister(n),h=Ee(h,{children:o}),u.length){const[,t]=u.at(-1);u[u.length-1]=[h,t]}else u.push([h,[]])}function f(){const e=function(t){const e=[],s=[];for(const o of t){if(!Q(o)||o.type!==n)continue;const{actor:t,logic:r}=o,i=F(t);r===w||r===k?e.push(i):s.push(i)}return[...e,...s]}(u.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===h.status||"error"===h.status);if(e.length||s){const t=s?[...e,H(r,h)]:e;if(u.length){const[e,s]=u.at(-1);u[u.length-1]=[e,[...s,...t]]}else u.push([h,t])}return{snapshot:h,microsteps:u}}function l(t,n){if(!pt(r)&&(e.type===s||(r.system._hasInspectionObservers?.()??1))){const t=r.self._collectedMicrosteps||[];t.push(...n),r.self._collectedMicrosteps=t}u.push(t)}if(e.type===o){const[t,s]=de(h,e,r),[n,o]=fe(t,e,r);return h=Ee(n,{status:"stopped"}),l([h,[...s,...o]],[]),f()}let p=function(t,e){if("xstate.done.actor"===t.type||"xstate.error.actor"===t.type||"xstate.snapshot.actor"===t.type||"xstate.done.state"===t.type||"xstate.after"===t.type||"xstate.timeout"===t.type||"xstate.timeout.actor"===t.type)return t;const s=(e,s,n)=>t.type.startsWith(e)?{...t,type:s,[n]:t[n]??t.type.slice(e.length)}:void 0,n=s("xstate.done.actor.","xstate.done.actor","actorId")??s("xstate.error.actor.","xstate.error.actor","actorId")??s("xstate.snapshot.","xstate.snapshot.actor","actorId")??s("xstate.done.state.","xstate.done.state","stateId")??s("xstate.timeout.actor.","xstate.timeout.actor","actorId")??s("xstate.timeout.","xstate.timeout","stateId");if(n)return n;const o="xstate.after.";if(!t.type.startsWith(o))return t;const r=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!r)return t;const i=t.type.slice(13,-r.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:r}}(e,t.machine);if(e.type===i){const t=h.timers[e.id];if(!t)return f();const s={...h.timers};if(delete s[t.id],h=Ee(h,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([h,[]],[]);else{const e="self"===t.target?r.self:t.target;l([h,[G(r,e,t.event)]],[])}}if(p.type!==s&&p.type!==i){const e=p,s=function(t){return t.type.startsWith("xstate.error.")}(e),n=new Map,o=h.machine.getTransitionData(h,e,r,n);if(s&&!o.length)return"xstate.error.actor"!==e.type||Rt(e,h,e.actorId)?(h=Ee(t,{status:"error",error:e.error}),l([h,[]],[]),d(e),f()):f();const i=oe(o,t,r,p,!1,c,n);h=i[0],l(i,o),d(e)}if(!c.length&&!1===t.machine._hasEventlessTransitions)return f();let y=!0;const g=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===h.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>g)throw new Error(`Infinite loop detected (>${g} microsteps)`);let t,e=y?le(h,p,r):[];const s=e.length?h:void 0;if(!e.length){if(!c.length)break;p=c.shift(),t=new Map,e=h.machine.getTransitionData(h,p,r,t)}const n=oe(e,h,r,p,!1,c,t);h=n[0],y=h!==s,l(n,e),d(p)}return f()}function ce(t,e,s,n,o){return!!t.to&&ue(t.to,e,s,n,o,n.machine.sources,t.source.id).enabled}const ae=()=>{throw qe};let he;function ue(t,e,s,n,o,r,i){let c;const a=O(o);a&&Fe.push(a);try{c=t(j({context:e,event:s,output:ze(s),value:n.value,children:n.children,actions:r.actions,actors:r.actors,guards:r.guards,delays:r.delays,input:kt(n,i)},o),he??=Z({emit:ae,cancel:ae,log:ae,raise:ae,spawn:ae,sendTo:ae,stop:ae,listen:ae,subscribeTo:ae},ae))}catch(t){if(t===qe)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&Fe.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function de(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const o=[],r=L(s,o,[]);for(const t of n)r.stop(t);return Y(t,e,s,o)}function fe(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const o=[],r=L(s,o,[]);for(const t of n)r.cancel(t);return Y(t,e,s,o)}function le(t,e,s){const n=new Set,o=t.nodes.filter(Et);for(const r of o)t:for(let o=r;o;o=o.parent)if(o.always)for(const r of o.always)if(pe(r,e,t,o,s)){n.add(r);break t}return Yt(Array.from(n),new Set(t.nodes),t,Zt(t,e,s,!1))}function pe(t,e,s,n,o,r){if(t.matches&&!Je(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const r=function(t,e){if(!A(e)){const s=e.self;return Object.assign(t,{self:s,parent:s._parent})}return Object.defineProperties(t,{self:{enumerable:!0,get:()=>e.self},parent:{enumerable:!0,get:()=>O(e)}}),t}({context:s.context,event:e,output:ze(e),children:s.children,actions:n.machine.sources.actions,actors:n.machine.sources.actors,guards:n.machine.sources.guards,delays:n.machine.sources.delays,_snapshot:s},o);if(!t.guard(r))return!1}if(t.to){const i=ue(t.to,s.context,e,s,o,n.machine.sources,t.source.id);return r?.set(t,i),i.enabled}return!0}const ye=Object.freeze({});function ge(t){return t===ye||t&&Object.keys(t).length?t:ye}function ve(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const me=function(t){return je(t,this.value)},_e=function(t){return this.tags.has(t)},xe=function(t){return this.machine?._canTransition(this,t)??!1},Se=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:r,toJSON:i,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},be=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},we=function(){return this._stateInputs};function Ie(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function ke(t,e,s){const n={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:Ie(t._nodes),children:ge(t.children),timers:ge(t.timers),historyValue:ge(t.historyValue),_stateInputs:ge(t._stateInputs),_nextTimerId:t._nextTimerId??0,matches:me,hasTag:_e,can:xe,getMeta:be,getInputs:we,toJSON:Se};return s&&ft(n,s),n}function Ee(t,e={}){const s={...t,...e};if((e._nodes??t.nodes)===t.nodes){const e={status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,nodes:t.nodes,value:t.value,tags:t.tags,children:ge(s.children),timers:ge(s.timers),historyValue:ge(s.historyValue),_stateInputs:ge(s._stateInputs),_nextTimerId:s._nextTimerId??0,matches:me,hasTag:_e,can:xe,getMeta:be,getInputs:we,toJSON:Se};return dt(t,e),e}const n=ke({...s,value:void 0},t.machine);return dt(t,n),n}function Ae(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function Oe(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Ze,id:n.id};else{const o=Oe(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function je(t,e){const s=$e(t),n=$e(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&je(s[t],n[t]))}function Te(t){if(Ne(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function $e(t){if(ve(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(Te(t))}function Me(t){return Ne(t)?t:[t]}function Pe(t){return void 0===t?[]:Me(t)}function Re(t,e,s,n,o){if("function"==typeof t){return t({context:e,event:s,output:ze(s),self:n,input:o})}return t}function ze(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function Ne(t){return Array.isArray(t)}function Ke(t){return Me(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function De(t){if(void 0!==t&&""!==t)return Pe(t)}function Ce(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Ve(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,o]=s,r=t.getStateNodeById(o).config.invoke,i=(Array.isArray(r)?r[n]:r).src;return"string"==typeof i?t.sources.actors[i]:i}function We(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function Je(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function Ue(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}let Be,Le=0;const qe=new Error("Transition effect"),Fe=[];function Ge(){return Be??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${Be}:${(Le++).toString(36)}`}const He=Object.freeze({});function Xe(t,e){return`${t.sessionId}.${e}`}class Qe{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={systemId:Ge(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef,this._snapshot={_scheduledTimers:s?.scheduler??He,_nextActorId:s?._nextActorId??0}}_recordSent(t,e,s,n,o){if(!this._inspectionObservers?.size||!t)return;const r=t;(r._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})}schedule(t,e,s){const n=Xe(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const o=t.getSnapshot()?.timers?.[e];if(o){const n="self"===o.target?t:o.target;this._recordSent(t,n,o.event,s,e)}const r=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:r,dueAt:r+s},a=Xe(t,e);this._snapshot._scheduledTimers===He&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,ct(this);const h=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],ct(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=h}cancel(t,e){const s=Xe(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==He&&delete this._snapshot._scheduledTimers[s],ct(this),void 0!==n&&this._clock.clearTimeout(n)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.id)}}_deliver(t,e,s){const n=e,o=n.logic;if("function"==typeof o?.isInternalEventType&&o.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);n._lastSourceRef=t,e._send(s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),ct(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=(this._children?.delete(t.sessionId)??!1)||e):e=this._children?.delete(t.sessionId)??!1;const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&ct(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&ct(this)}inspect(t){const e=Ce(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}spawnActor(){}startActor(t){t.start()}stopActor(t){t._stop()}terminateActor(t,e){t._terminate(e)}sendEvent(t,e,s){this._recordSent(t,e,s),this._deliver(t,e,s)}emitEvent(t,e){t._emit(e)}scheduleTimer(t,e,s){this.schedule(t,e,s)}cancelTimer(t,e){this.cancel(t,e)}cancelAllTimers(t){this.cancelAll(t)}_relay(t,e,s){if(Fe.length&&Fe.includes(e))throw qe;this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:n,dueAt:o,id:r}=t[s];this.scheduleTimer(n,r,Math.max(0,o-(this._clock.now?.()??Date.now())))}}}let Ye=!1;const Ze=1,ts=Object.freeze([]);let es=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ss=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ns(t,e){try{t?.(e)}catch(t){y(t)}}function os(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function rs(t,e){return new is(t,e)}class is{get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=es.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1;const s=e?{...ss,...e}:ss,{clock:n,logger:o,parent:r,syncSnapshot:i,id:c,registryKey:a,inspect:h}=s;var u;this.system=r?r.system:s._systemRef?.current??function(t,e){return new Qe(t,e)}(this,{clock:n,logger:o,snapshot:s.snapshot??s.state,createActorRef:rs}),r||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!r&&this.system.inspect(Ce(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=function(t,e){if(void 0!==e){const s=/^x:(\d+)$/.exec(e),n=s?Number(s[1]):void 0;if(void 0!==n&&Number.isSafeInteger(n)){const e=Math.max(t._snapshot._nextActorId,n+1);e!==t._snapshot._nextActorId&&(t._snapshot._nextActorId=e,ct(t))}return e}const s="x:"+t._snapshot._nextActorId++;return ct(t),s}(this.system,c),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=r,this._syncSnapshot=i,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=X(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>this.system.emitEvent(this,t);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===es.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=Ye;try{Ye=!0,t.exec()}finally{Ye=e}};this._processingStatus!==es.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,ft(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,n]=X(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),os(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??ts)ns(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const n=s[e];try{n()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??ts,actions:this._collectedActions??ts,sent:this._collectedSent??ts,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return os(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=Ce(t,e,s);if(this._processingStatus!==es.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":ns(n.complete);break;case"error":{const t=this._snapshot.error;n.error?ns(n.error,t):y(t);break}}return{unsubscribe:()=>{this.observers?.delete(n)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const r=Ce(s,n,o);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,r.next?.(n))},error:r.error,complete:r.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===es.Running)return this;if(this._processingStatus===es.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=es.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,p(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,p(this.options.input)):(function(t,e,s){const n=nt.get(t),o=at(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===o&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=o,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??{};for(const e of Object.values(t))this.system.scheduleTimer(this,e.id,e.delay);this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=X(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let n=this._snapshot;try{const[s,o]=e;n=s,this._setSnapshot(n),os(o,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===o&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ns(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,n=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:n})));var e,s,n;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===es.Stopped?this:(this.mailbox?.clear(),this._processingStatus===es.NotStarted?(this._processingStatus=es.Stopped,this.system._unregister(this),this):(this._send({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??ts)ns(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n,ns(n,t)}this.observers.clear(),e&&y(t)}else this._parent||y(t);var e,s,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,n=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:n}))}_stopProcedure(){this._processingStatus===es.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=es.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===es.Stopped)return;let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Ze,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[g](){return this}getSnapshot(){return this._snapshot}}function cs(t,e){return new is(t,e)}function as(t,e){const s=t.check(e);if(s)throw s}const hs=new WeakMap;function us(t,e,s){const n=function(t){let e=hs.get(t);return e||(e=new Map,hs.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const o=s();n.set(e??Symbol(),{cleanup:"function"==typeof o?o:void 0})}function ds(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===o)return[{...e,status:"stopped",input:void 0},[M("xstate.logic.cleanup",()=>function(t){const e=hs.get(t);if(e){for(const{cleanup:t}of e.values())t?.();hs.delete(t)}}(n.self))]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const r=[],i={},c={emit:t=>{r.push(function(t,e){return{kind:"emit",exec:$,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&r.push(G(n,e,t))},raise:t=>{r.push(G(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(r.push(M("xstate.logic.effect",(e=n.self.system)=>us(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const o=t;r.push(M("xstate.logic.effect",(t=n.self.system)=>us(n.self,void 0,()=>o(t))))}},a=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(i).length)&&(h.effects={...e.effects,...a?.effects,...i}),X(n,e,[h,r])},s=(s,o,r)=>{t.validator&&as(t.validator,{kind:"event",logic:n,event:o,eventOrigin:r.self._lastSourceRef?"actor":"external"});const i=e(s,o,r);return t.validator&&as(t.validator,{kind:"result",logic:n,snapshot:i[0],effects:i[1]}),i},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,n)=>{if(!n?.restored)return;const[o,r]=s(t,p(t.input),e);Object.assign(t,o);for(const t of r)e.actionExecutor(t)},initialTransition:(e,o)=>{t.validator&&as(t.validator,{kind:"input",logic:n,input:e});const r=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),i={status:"active",output:void 0,error:void 0,input:e};return void 0!==r&&(i.context=r),s({...i},p(e),o)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const fs=ds({context:void 0,run:()=>{}});const ls=new WeakMap;const ps={};class ys{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.schemas=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._candidateCache=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.schemas=this.config.schemas,function(t){const e=t.config;if("history"===t.type&&!("string"==typeof e.target&&e.target.trim().length>0||Array.isArray(e.target)&&e.target.length>0&&e.target.every(t=>"string"==typeof t&&t.trim().length>0)))throw new Error(`Missing history target on "${t.id}"`);if("choice"!==t.type)return;if("function"!=typeof e.choice)throw new Error(`Missing \`choice\` function on "${t.id}"`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const r=n[o];s[r]=e(t[r],r,t,o)}return s}(this.config.states,(t,e)=>new ys(t,{_parent:this,_key:e,_machine:this.machine})):ps,"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=Pe(t.tags).slice(),this.invoke=Pe(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(r=this.id,`${e}.${r}`);var r;const i=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:i,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,o=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===o.length)return[];const r=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;r.push({event:c(n,t.id),timerId:a(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&r.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:h(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of o)r.push({event:u(t.id),timerId:d(t.id),resolveEvent:({children:e})=>u(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Rt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const f=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:o,delay:i,transitions:c,fromDelaysMap:a}of r){Nt(t,s,n??(()=>e),e=>It(i,a?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:r,...h}=e;for(const t of Ke(c))f.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(h).filter(([,t])=>void 0!==t))},event:r,delay:i,_eventMatcher:o})}return f.map(e=>({...Kt(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map,s=(t,s)=>{e.set(t,[...e.get(t)??[],...s])};if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error("Null event transition key");const n=t.config.on[s];e.set(s,gs(n,e=>Kt(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,gs(t.config.onDone,s=>Kt(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,gs(t.config.onError,e=>Kt(t,s,e)))}const n=(e,s,n)=>Kt(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Rt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),o=(e,s,n)=>{const{target:o,to:r,reenter:i,...c}=s;return Kt(t,e,{...c,reenter:i,to:(t,e)=>{if(r){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),i=r(t,o);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:o,reenter:i}}})};for(const e of t.invoke){const r=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Rt(t,s,e.id)}),i=void 0!==e.timeout?d(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=gs(e.onDone,e=>{const s=r(e);return i?o(c,s,i):Kt(t,c,s)});i&&a.push(n(c,i,e.id)),s(c,a)}else if(i){const t="xstate.done.actor";s(t,[n(t,i,e.id)])}if(e.onError){const n="xstate.error.actor";s(n,gs(e.onError,e=>{const s=r(e);return i?o(n,s,i):Kt(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,gs(e.onSnapshot,e=>Kt(t,n,r(e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice "${t.id}" has no target`);return e};return[Kt(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=gs(this.config.always,t=>Kt(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return function(t,e,s){let n=ls.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ls.set(t,n)),n[e]}(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state "${s}" not found on "#${t.id}"`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s,n){const o=function(t){const e=Pt(t);return e?`${t.type}|${e}`:t.type}(e);let r=this._candidateCache?.get(o);r||(r=zt(this,e),(this._candidateCache??=new Map).set(o,r));for(const o of r){if(pe(o,e,t,this,s,n))return[o]}}}function gs(t,e){const s=Ke(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}let vs,ms;function _s(){if(ms)return ms;const t=vs??=cs({transition:t=>[t,[]],initialTransition:()=>[{status:"active",output:void 0,error:void 0},[]],getInitialSnapshot:()=>({status:"active",output:void 0,error:void 0}),getPersistedSnapshot:t=>t});return ms={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},ms}class xs{constructor(t,e,s){this.config=t,this.validator=s,this.version=void 0,this.schemas=void 0,this.sources=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._hasEventlessTransitions=void 0,this._json=void 0,this.id=t.id||"(machine)",this.sources={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.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ys(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,r=n.config.route,i=({event:t})=>t.to===`#${o}`;if("function"==typeof r)return e.push(Kt(t,"xstate.route",{guard:i,to:t=>{const e=r(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=r,h={...a,guard:i,target:`#${o}`};e.push(Kt(t,"xstate.route",h))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this._hasEventlessTransitions=Array.from(this.idMap.values()).some(t=>!!t.always?.length),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.sources,r=new xs(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}},this.validator);return r._json=this._json,r}resolveState(t){const e=(s=this.root,n=t.value,Tt(s,jt(Ft(s,n))));var s,n;const o=jt(Ft(this.root,e));return ke({_nodes:[...o],value:e,context:t.context||{},children:{},status:$t(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,o=s??bt(this,t);this.validator&&as(this.validator,{kind:"event",logic:this,event:e,eventOrigin:s&&s.self._lastSourceRef?"actor":"external"}),n&&lt(o,t,!1);const r=this._transitionFast(t,e,o);if(r){n&&lt(o,r,!1);const e=n&&r!==t?yt(o,r):this._attachPureActorRef(r,o);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=ie(t,e,o,[]);n&&lt(o,i,!1);const a=n?i===t?i:yt(o,i):this._attachPureActorRef(i,o),h=this._collectEffects(c);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:a,effects:h}),[a,h]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return pt(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||ft(t,e.self,e.system),t}_transitionFast(t,e,s){if("active"!==t.status||"string"!=typeof t.value||this.root.always?.length)return;const n=this.root.states[t.value];if(!n||"atomic"!==n.type||n.exit||n.invoke.length||n.always?.length||n.after?.length)return;const o=n.transitions.get(e.type);if(1!==o?.length)return;const r=o[0];if(r.guard||r.actions||r.to||r.reenter||r.input||"function"==typeof r.context||r.target&&1!==r.target.length)return;const i=r.target?.[0]??n,c=i!==n;if(i.parent!==this.root||"atomic"!==i.type||c&&(i.entry||i.invoke.length||i.always?.length||i.after?.length))return;const a=void 0!==r.context?{...t.context,...r.context}:t.context;if(!pt(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(r),s.self._collectedMicrosteps=t}return Ee(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=ie(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s,n){return Gt(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(Ue(t,e))return!0;return!1}_canTransition(t,e){const s=_s(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=re(o,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||ce(o,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return l("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=ke({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},r=function(t,e,s){return(n,o)=>{const r=Object.entries(e).find(([,t])=>t===n)?.[0],i=t.system.createActorRef(n,{id:o?.id,parent:t.self,syncSnapshot:o?.syncSnapshot,input:o?.input,src:r??n,registryKey:o?.registryKey});return s[i.id]=i,i}}(t,this.sources.actors,o),i=s(function(t,e){return A(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:r,input:e.input,actors:this.sources.actors},t)),[c]=Y(n,e,t,[]);return i&&(c.context=i),Object.keys(o).length>0&&(c.children={...c.children,...o}),c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&as(this.validator,{kind:"input",logic:this,input:t});const s=!e,o=e??bt(this),r=p(t),i=[],c=this._getPreInitialState(o,r),a=Object.values(c.children).filter(Boolean).map(t=>function(t){const e=[t];return{kind:"builtin",exec:P,type:n,source:t._parent,params:void 0,args:e,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}(t)),h=(t,e)=>{s&&lt(o,t,!1);const n=s?yt(o,t):this._attachPureActorRef(t,o,!0),r=this._collectEffects(e);return this.validator&&as(this.validator,{kind:"result",logic:this,snapshot:n,effects:r}),[n,r]};try{const[t,e]=function(t,e,s,n,o){return oe([{target:[...Bt(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,c,o,r,i),{snapshot:s,microsteps:n}=ie(t,r,o,i,[[t,[...a,...e]]]);return h(s,n)}catch(t){if(!this.root.config.onError)throw t;const e=ie(c,l("execution",t),o,[],[[c,a]]);return h(e.snapshot,e.microsteps)}}start(t){if(!t?.children)return;const e=t.children;for(const t in e){if(!Object.hasOwn(e,t))continue;const s=e[t];s._rehydrated&&"active"===s.getSnapshot?.().status&&s.start()}}getStateNodeById(t){const e=Te(t),s=e.slice(1),n=Mt(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return qt(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:o,machine:r,children:i,timers:c,context:a,can:h,hasTag:u,matches:d,getMeta:f,getInputs:l,toJSON:p,...y}=t,g={},v={};for(const t in i){const s=i[t];g[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}for(const e in c){const s=c[e];let n,o=s.event;if("xstate.timeout.actor"===o.type&&(o={...o},delete o.sessionId),"self"===s.target)n="self";else{const o=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(o)n=o;else{if(s.target!==ut(t)?.actor._parent)throw new Error(`Unable to persist timer '${e}': target actor '${s.target.id}' is no longer addressable from this snapshot.`);n={type:"parent"}}}v[e]={id:s.id,delay:s.delay,type:s.type,event:o,target:n}}const m={...y,_nextActorId:ut(t)?.systemState.snapshot._nextActorId,context:Oe(a),children:g,timers:v,historyValue:Ae(y.historyValue)};return n&&Object.keys(n).length>0&&(m.stateInputs=n),void 0!==r.version&&(m.machine={id:r.id,version:r.version},m.version=r.version),m}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??bt(this),o=t.machine,r=t.version,i="string"==typeof o?.version?o.version:r;if(void 0!==r&&void 0!==o?.version&&o.version!==r)throw new Error(`Persisted snapshot version '${r}' conflicts with machine version '${o.version}'.`);if(o&&"string"==typeof o.id&&o.id!==this.id)throw new Error(`Machine ID mismatch: persisted snapshot machine '${o.id}' does not match '${this.id}'.`);if(i!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${i}' does not match machine version '${this.version}'.`);t=e(t,i)}const c=t,a={},h=c.children;for(const t of Object.keys(h)){const e=h[t],s=e.snapshot,o=e.src,r="string"==typeof o?Ve(this,o):o;if(!r){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof o?o:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(r,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:o,registryKey:e.registryKey});i._rehydrated=!0,a[t]=i}const d={},f=c.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=a[t];e&&(s=u(t,e.sessionId))}const o="string"==typeof e.target?"self"===e.target?"self":a[e.target]:n.self._parent;if(!o){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}d[t]={...e,event:s,target:o}}const l=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof ys)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(c.historyValue),p=(t,e,s)=>{const n=t=>new Error(`Persisted snapshot references state '${t.join(".")}' which does not exist on machine '${this.id}'.`);if("string"!=typeof t){if(t&&"object"==typeof t)for(const o of Object.keys(t)){const r=e.states[o];if(!r)throw n(s.concat(o));p(t[o],r,s.concat(o))}}else if(!e.states[t])throw n(s.concat(t))};p(c.value,this.root,[]);const y=Array.from(jt(Ft(this.root,c.value))),{version:g,...v}=t,m=ke({...v,children:a,timers:d,_nodes:y,value:c.value,historyValue:l,_stateInputs:c.stateInputs??{}},this,n.self),_=new WeakSet;return function t(e){if(!_.has(e)){_.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Ze){e[s]=a[n.id];continue}t(n)}}}}(m.context),s?(lt(n,m,!1),yt(n,m)):this._attachPureActorRef(m,n)}}function Ss(t){return JSON.stringify(t)}function bs(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t.nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const ws=()=>(t,e)=>Vs(t,e),Is=()=>(t,e)=>Ws(t,e);class ks{getDefaultOptions(){return{serializeState:t=>Ss(t),serializeEvent:t=>Ss(t),serializeTransition:(t,e)=>`${Ss(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ve(t.state)?`Reaches ${bs(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=Ss)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(ws(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(zs(n,e)))}return s}getSimplePaths(t){return this.getPaths(Is(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(zs(n,e)))}return s}getPathsFromEvents(t,e){return Cs(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return Ks(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:Ss,serializeEvent:Ss,...s},{formatColor:o,serializeState:r,serializeEvent:i}=n,{state:c}=t,a=r(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=r(t.step.state,e>0?s[e-1].step.event:void 0),c=i(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function Es(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>Es(t[s],e[s]))}function As(t,e,s,{serializeEvent:n}){if(!e||s&&Es(s.value,t.value))return"";const o=s?` from ${Ss(s.value)}`:"";return` via ${n(e)}${o}`}function Os(){const t=cs(fs);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function js(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function Ts(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function $s(t){return JSON.stringify(t)}function Ms(t,e){const{events:s,...n}=e??{};return{serializeState:Ts,serializeEvent:$s,events:t=>{const e="function"==typeof s?s(t):s??[];return We(t).flatMap(t=>{const s=e.filter(e=>Je(e,t));return s.length?s:[t]})},fromState:t.getInitialSnapshot(Os(),e?.input),...n}}function Ps(){return{serializeState:t=>JSON.stringify(t),serializeEvent:$s}}function Rs(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?Ms(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:$s,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function zs(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function Ns(t){return Array.isArray(t)?t[0]:t}function Ks(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:r,filterEvents:i,limit:c,fromState:a,stopWhen:h}=Rs(t,e),u=Os(),d={};let f=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],p=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(f++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(d[y])continue;if(p.set(y,t),d[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof r?r(t):r;for(const e of g){if(i&&!i(t,e))continue;const o=Ns(s(t,e,u));d[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return d}function Ds(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function Cs(t,e,s){const n=Rs(t,{events:e,...s},(o=t)&&o instanceof xs?Ms(t):Ps());var o;const r=Os(),i=n.fromState??t.getInitialSnapshot(r,s?.input),{serializeState:c,serializeEvent:a}=n,h=Ks(t,n),u=new Map,d=[],f=c(i,void 0,void 0);u.set(f,i);let l=f,p=i;for(const t of e){d.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,p=s}return n.toState&&!n.toState(p)?[]:[Ds({state:p,steps:d,weight:d.length})]}function Vs(t,e){const s=Rs(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(Os(),e?.input),r=Ks(t,s),i=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),i.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=i.get(t);for(const o of Object.keys(r[t].transitions)){const{state:a,event:d}=r[t].transitions[o],f=n(a,d,e);if(c.set(f,a),i.has(f)){const{weight:e}=i.get(f);e>s+1&&i.set(f,{weight:s+1,state:t,event:d})}else i.set(f,{weight:s+1,state:t,event:d});u.has(f)||h.add(f)}u.add(t),h.delete(t)}const d={},f=[];return i.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),r=e?d[e].paths[0].steps.concat({state:c.get(e),event:s}):[];f.push({state:o,steps:r,weight:t}),d[n]={state:o,paths:[{state:o,steps:r,weight:t}]}}),s.toState?f.filter(t=>s.toState(t.state)).map(Ds):f.map(Ds)}function Ws(t,e){const s=Rs(t,e),n=Os(),o=s.fromState??t.getInitialSnapshot(n,e?.input),r=s.serializeState,i=Ks(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!i[t])return;for(const s of Object.keys(i[t].transitions)){const{state:n,event:o}=i[t].transitions[s];if(!(s in i[t].transitions))continue;const u=c.get(t),f=r(n,o,u);c.set(f,n),a.vertices.has(f)||(a.edges.add(s),h.push({state:c.get(t),event:o}),d(f,e))}}h.pop(),a.vertices.delete(t)}const f=r(o,void 0);c.set(f,o);for(const t of Object.keys(i))d(f,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(Ds):l.map(Ds)}t.TestModel=ks,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=ws,t.createSimplePathsGen=Is,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??Ss,n=e?.serializeTransition??As,{events:o,...r}=e??{};return new ks(t,{serializeState:(t,e,o)=>`${Ts(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e.nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return We(t).flatMap(t=>e.some(e=>Je(e,t))?e.filter(e=>Je(e,t)):[t])},...r})},t.getAdjacencyMap=Ks,t.getPathsFromEvents=Cs,t.getShortestPaths=Vs,t.getSimplePaths=Ws,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],r=t(o);return e.push(o,...r),e},[])},t.joinPaths=zs,t.serializeSnapshot=Ts,t.toDirectedGraph=function t(e){const s=e instanceof xs?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const r={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=r;return{source:s.id,target:n.id,label:t}}};return r})),o={id:s.id,stateNode:s,children:js(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-graph.umd.min.js.map