xstate 6.0.0-alpha.47 → 6.0.0-alpha.49

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 (84) hide show
  1. package/README.md +30 -1
  2. package/dist/{StateMachine-7046f677.cjs.js → StateMachine-0adb3a70.cjs.js} +15 -12
  3. package/dist/{StateMachine-70c06bdd.development.cjs.js → StateMachine-29450e6d.development.cjs.js} +15 -12
  4. package/dist/{StateMachine-74929087.esm.js → StateMachine-2af31c11.esm.js} +10 -7
  5. package/dist/{StateMachine-ee10f67e.development.esm.js → StateMachine-faf50c5c.development.esm.js} +10 -7
  6. package/dist/{createActor-915ea40c.esm.js → createActor-268165d4.esm.js} +79 -23
  7. package/dist/{createActor-ff132afa.development.esm.js → createActor-88709f74.development.esm.js} +79 -23
  8. package/dist/{createActor-6736cbbe.development.cjs.js → createActor-a1e0dffb.development.cjs.js} +78 -25
  9. package/dist/{createActor-bfe8b6bd.cjs.js → createActor-b4dd05ae.cjs.js} +78 -25
  10. package/dist/declarations/src/createMachineFromConfig.d.ts +5 -77
  11. package/dist/declarations/src/fsm/createFSMActor.d.ts +67 -0
  12. package/dist/declarations/src/fsm/index.d.ts +2 -0
  13. package/dist/declarations/src/fsm.d.ts +5 -4
  14. package/dist/declarations/src/scxml/index.d.ts +1 -0
  15. package/dist/declarations/src/scxml/runtime.d.ts +251 -0
  16. package/dist/declarations/src/scxml/scxml.d.ts +19 -0
  17. package/dist/declarations/src/types.d.ts +1 -0
  18. package/dist/{effectDescriptor-8be60443.esm.js → effectDescriptor-30c9a744.esm.js} +1 -1
  19. package/dist/{effectDescriptor-fbe67d5a.development.esm.js → effectDescriptor-39d22100.development.esm.js} +1 -1
  20. package/dist/{effectDescriptor-3c699328.development.cjs.js → effectDescriptor-7ff6802f.development.cjs.js} +1 -1
  21. package/dist/{effectDescriptor-a7e2d4d1.cjs.js → effectDescriptor-be348e50.cjs.js} +1 -1
  22. package/dist/fsm-7a2e9697.cjs.js +777 -0
  23. package/dist/fsm-b804b3e9.esm.js +775 -0
  24. package/dist/fsm-c1316948.development.cjs.js +777 -0
  25. package/dist/fsm-e18a7cb4.development.esm.js +775 -0
  26. package/dist/types-3c3455f7.esm.js +185 -0
  27. package/dist/types-adda3842.development.esm.js +185 -0
  28. package/dist/types-b3fea5bd.development.cjs.js +189 -0
  29. package/dist/types-fbabaeee.cjs.js +189 -0
  30. package/dist/validation-05f1d517.esm.js +8 -0
  31. package/dist/validation-4561b43c.cjs.js +10 -0
  32. package/dist/validation-e69470ad.development.esm.js +8 -0
  33. package/dist/validation-f2714a35.development.cjs.js +10 -0
  34. package/dist/xstate-actors.cjs.js +934 -9
  35. package/dist/xstate-actors.development.cjs.js +934 -9
  36. package/dist/xstate-actors.development.esm.js +932 -2
  37. package/dist/xstate-actors.esm.js +932 -2
  38. package/dist/xstate-durable.cjs.js +2 -2
  39. package/dist/xstate-durable.development.cjs.js +2 -2
  40. package/dist/xstate-durable.development.esm.js +2 -2
  41. package/dist/xstate-durable.esm.js +2 -2
  42. package/dist/xstate-fsm.cjs.d.mts +2 -0
  43. package/dist/xstate-fsm.cjs.d.ts +2 -0
  44. package/dist/xstate-fsm.cjs.js +409 -0
  45. package/dist/xstate-fsm.cjs.mjs +5 -0
  46. package/dist/xstate-fsm.development.cjs.js +409 -0
  47. package/dist/xstate-fsm.development.cjs.mjs +5 -0
  48. package/dist/xstate-fsm.development.esm.js +403 -0
  49. package/dist/xstate-fsm.esm.js +403 -0
  50. package/dist/xstate-fsm.umd.min.js +2 -0
  51. package/dist/xstate-fsm.umd.min.js.map +1 -0
  52. package/dist/xstate-graph.cjs.js +4 -3
  53. package/dist/xstate-graph.development.cjs.js +4 -3
  54. package/dist/xstate-graph.development.esm.js +4 -3
  55. package/dist/xstate-graph.esm.js +4 -3
  56. package/dist/xstate-graph.umd.min.js +1 -1
  57. package/dist/xstate-graph.umd.min.js.map +1 -1
  58. package/dist/xstate-scxml.cjs.d.mts +2 -0
  59. package/dist/xstate-scxml.cjs.d.ts +2 -0
  60. package/dist/xstate-scxml.cjs.js +2387 -0
  61. package/dist/xstate-scxml.cjs.mjs +3 -0
  62. package/dist/xstate-scxml.development.cjs.js +2387 -0
  63. package/dist/xstate-scxml.development.cjs.mjs +3 -0
  64. package/dist/xstate-scxml.development.esm.js +2383 -0
  65. package/dist/xstate-scxml.esm.js +2383 -0
  66. package/dist/xstate-scxml.umd.min.js +26 -0
  67. package/dist/xstate-scxml.umd.min.js.map +1 -0
  68. package/dist/xstate-validation.cjs.js +1 -1
  69. package/dist/xstate-validation.development.cjs.js +1 -1
  70. package/dist/xstate-validation.development.esm.js +1 -1
  71. package/dist/xstate-validation.esm.js +1 -1
  72. package/dist/xstate.cjs.js +143 -1412
  73. package/dist/xstate.development.cjs.js +143 -1412
  74. package/dist/xstate.development.esm.js +143 -1411
  75. package/dist/xstate.esm.js +143 -1411
  76. package/dist/xstate.umd.min.js +1 -1
  77. package/dist/xstate.umd.min.js.map +1 -1
  78. package/fsm/package.json +8 -0
  79. package/package.json +37 -3
  80. package/scxml/package.json +8 -0
  81. package/dist/index-0f498ef2.development.cjs.js +0 -946
  82. package/dist/index-70d56425.development.esm.js +0 -937
  83. package/dist/index-b051c924.esm.js +0 -937
  84. package/dist/index-b3fe59bc.cjs.js +0 -946
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";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",r="@xstate.stop",o="@xstate.terminate",i="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",u="xstate.logic.effect.start";function d(t,e){return{type:"xstate.after",delay:t,stateId:e}}function h(t,e){return`xstate.after.${t}.${e}`}function f(t){return`xstate.timeout.${t}`}function l(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function p(t){return`xstate.timeout.actor.${t}`}function y(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function v(t,e){return{type:`xstate.error.${t}`,error:e}}function m(t){return{type:s,input:t}}function g(t){setTimeout(()=>{throw t})}const _="function"==typeof Symbol&&Symbol.observable||"@@observable";function x(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const b={"@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)=>(x(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)},w=new WeakMap;function $(t,e){let s=w.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}w.set(t,s)}return s.get(e)}const S=new WeakMap;function E(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),S.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(S.get(s)?.unsubscribe(),S.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function I(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function k(){return E(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!hs(t.type,e)||I(n,r,()=>s(t))})},"xstate.listener")}const A=k();function j(){return E(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?I(s,n,()=>r(t.output)):"error"===t.status&&o?I(s,n,()=>o(t.error)):"active"===t.status&&i&&I(s,n,()=>i(t))},error:t=>{o&&I(s,n,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const T=j(),O=Symbol();function M(t){return!!t[O]}function N(t){return M(t)?t._parent:t.self._parent}function P(t,e){if(!M(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:()=>N(e)}}),t}function R(){return this.action?.(...this.args)}function C(t=this.source.system){return t.emitEvent(this.source,this.event)}function D(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function K(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function z(t=this.actor.system){return t.startActor(this.actor)}function V(t=this.source.system){return t.stopActor(this.actor)}function W(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 L(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function U(t=this.source.system){return x(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function B(t=this.source.system){return t.cancelTimer(this.source,this.id)}function J(t,e,s){if(!lt(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 r=e.id??"xstate.timer.auto."+n++;e.id=r;const o="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[r]:{id:r,delay:e.delay,type:e.type,event:e.event,target:o}},_nextTimerId:n}}function F(t,e){return{...t,...e}}function q(t,e,...s){const n={action:e,args:s};return t.push(n),n}function H(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function G(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:H(t._nextActorIds,e.counters)}};const n={...t.children};let r=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(r=!0,delete n[t]);if(!r)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function X(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Z=new WeakMap,Q=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function Y(t){Z.set(t,Q())}function tt(t){return t.self._snapshot}function et(t,e,s){return Math.max(e.counters.get(s)??0,tt(t)?._nextActorIds?.[s]??0)}function st(t,e,s){const n=Z.get(t)??s??Q(),r=ws(e),o=et(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function nt(t,e,s){const n=Z.get(t)??s??Q(),r=tt(t)?.children?.[e],o=void 0!==r&&!n.stoppedIds.has(e)&&"active"===r.getSnapshot().status;if(n.explicitIds.has(e)||o)throw new Error(`Child actor id '${e}' is already in use`);n.explicitIds.add(e)}function rt(t,e,s){const n=Ss(e);if(!n)return;n.prefix;const r=Z.get(t)??s??Q(),o=Math.max(et(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}function ot(t,e,s,n=!1,r=!0){const o=Z.get(t)??Q(),i={cancel:s=>{q(e,b["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{q(e,t.logger,...s)},raise:(n,r)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==r?.delay?q(e,b["@xstate.raise"],t,n,r):s.push(n)},spawn:(s,n)=>{const{logic:i,src:c}=function(t,e){const s=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof e){const t=s?.[e];if(!t)throw new Error(`Actor source '${e}' is not provided`);return{logic:t,src:e}}return s?{logic:e,src:$(s,e)}:{logic:e,src:void 0}}(t,s);if(!r)return{id:n?.id??n?.registryKey??c??i.id};let a,u=n?.id;void 0===u?({id:u,counters:a}=st(t,c??i,o)):(nt(t,u,o),a=rt(t,u,o));const d=t.system.createActorRef(i,{...n,...void 0!==c&&{src:c},id:u,parent:t.self});return function(t,e,s,n){q(t,b["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,d,u,a),d},sendTo:(n,r,o)=>{n?q(e,b["@xstate.sendTo"],t,n,r,o):s.push(v("communication",{message:"Unable to send event to an undefined actor",event:r}))},stop:s=>{if(s){const n=s;q(e,b["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Z.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};return n&&Object.assign(i,{listen:(s,n,o)=>{if(!r)return{id:void 0};const i={actor:s,eventType:n,mapper:o},c=t.system.createActorRef(A,{input:i,parent:t.self});return q(e,b["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!r)return{id:void 0};const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(T,{input:o,parent:t.self});return q(e,b["@xstate.spawn"],i),i}}),yt(i,(t,...s)=>{q(e,t,...s)})}function it(t,e){switch(t){case b["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:K,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case b["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:L,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case b["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:U,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case b["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:B,source:e[0].self,id:t}}case b["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:V,source:e[0].self,actor:t,id:t.id}}default:return}}function ct(t){const e=[t];return{kind:"builtin",exec:z,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function at(t){const e=[t];return{kind:"builtin",exec:K,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}}function ut(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:U,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function dt(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:W,type:o,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function ht(t,e,[s,n]){const r="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===o);return!r||i||c?[s,n]:[s,[...n,dt(t,s)]]}function ft(t){const e=[],s=[];for(const r of t){if(!lt(r)||r.type!==n)continue;const{actor:t,logic:o}=r,i=ct(t);o===A||o===T?e.push(i):s.push(i)}return[...e,...s]}function lt(t){return"builtin"===t.kind}function pt(t,e,s,n){let r=t;const o=[];for(const i of n){const n=M(s)?P({context:r.context,event:e,output:os(e),children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:r.context,event:e,output:os(e),self:s.self,system:s.system,parent:s.self._parent,children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=X(i),u=c?i:!!a&&a.action.bind(null,...a.args);let d;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;d=s}if(a?.childUpdate&&(r=G(r,a.childUpdate,s)),u&&"_special"in u){o.push({kind:"action",exec:R,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:d,args:[],action:void 0});const t=u(n,gt);t&&("context"in t||"children"in t)&&(r={...r,...void 0!==t.context?{context:F(r.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?it(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:d,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?C:R},...t};r=J(r,n,s),o.push(n);continue}}return[r,o]}function yt(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:vt,emit:vt,log:vt,raise:vt,spawn:mt,sendTo:vt,stop:vt,listen:mt,subscribeTo:mt,...t}),s}const vt=()=>{},mt=()=>({}),gt=yt({},vt);function _t(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 r=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(!r?.groups)return;const{weeks:o,days:i,hours:c,minutes:a,seconds:u}=r.groups;if(!(o||i||c||a||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(c)*60*1e3+60*d(a)*1e3+1e3*d(u)}function xt(t){if(void 0!==t)return"number"==typeof t?t:_t(t)}const bt=new WeakMap,wt=new WeakMap,$t=new Map;function St(t){const e=t._peekKeyedActors;return e?e.call(t)??$t:t.keyedActors}function Et(t){t._snapshotVersion++}function It(t){return t._snapshotVersion}function kt(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),r=new Map(s?.keyedActors??St(t)),o=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:r,reverseKeyedActors:o,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),Et(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=o.get(t);void 0!==e&&r.get(e)===t&&r.delete(e),o.delete(t),Et(i)},_set:(t,e)=>{const s=r.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);r.set(t,e),o.set(e,t),Et(i)},get:t=>r.get(t),getAll:()=>Object.fromEntries(r),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of r)e&&o.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&&(r.set(e,t),o.set(t,e))}return i}function At(t){const e=bt.get(t);if(e)return e;const s=wt.get(t);if(!s)return;const n=s();return bt.set(t,n),wt.delete(t),n}function jt(t,e){const s=bt.get(t);if(s)return bt.set(e,s),!0;const n=wt.get(t);return!!n&&(wt.set(e,n),!0)}function Tt(t,e,s=e.system,n){wt.delete(t);const r=It(s),o=n?At(n):void 0,i=o?.actor===e?o:At(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void bt.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 u=St(s);let d=u.size?new Map(u):$t;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&&(d===$t&&(d=new Map),d.set(t,e))}bt.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}function Ot(t,e,s=!0){const n=Ct(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&Tt(e,t.self),e}function Mt(t){return!!Ct(t)||!!t.self.options?._inert}function Nt(t,e){Ot(t,e,!1);const s=Ct(t);Rt.set(e,t);const n=()=>(Tt(e,t.self,t.system),At(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){bt.delete(t),wt.set(t,e)}(e,n),e}const Pt=Symbol(),Rt=new WeakMap;function Ct(t){return t[Pt]}function Dt(t){return Ct(t).materialize()}const Kt={[O]:!0,get _parent(){const t=Ct(this);return t.parentKnown?t.parent:Dt(this).self._parent},get self(){return Dt(this).self},get defer(){return Dt(this).defer},get id(){return Dt(this).id},get logger(){return Dt(this).logger},get sessionId(){return Dt(this).sessionId},get stopChild(){return Dt(this).stopChild},get system(){return Dt(this).system},get emit(){return Dt(this).emit},get actionExecutor(){return Dt(this).actionExecutor}};function zt(t,e,s,n,r){const o=e?.(),i=r??o?.actor,c=i?.system,a=i&&c?kt(c,s,r?void 0:o?.systemState):void 0,u=zs(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(u._parent=i._parent,u._address=void 0),n&&(u._snapshot=n),Object.create(u._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function Vt(t,e,s,n){const r=n??(e&&"object"==typeof e?Rt.get(e):void 0),o=r?Ct(r):void 0,i=e&&"object"==typeof e?function(t){return bt.get(t)}(e):void 0,c=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=bt.get(t);return e?()=>e:wt.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:Ve(e)?e.children:{},identityProvider:o?.identityProvider??c,parent:s?._parent??o?.parent??i?.actor._parent,parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>a.materialized??=zt(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,r=a.sourceChildren;let o,i;const c=()=>o??=zt(t,n,r,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 Tt(e,t.self,t.system),i=At(e)}}const u=Object.create(Kt);return u[Pt]=a,u}function Wt(t,e,s){if("function"==typeof t)return t(s);const n=function(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:_t(t)??t}(t,e);return"function"==typeof n?n(s):n}function Lt(t,e){return t._stateInputs?.[e]}function Ut(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Bt(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Jt(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 Ft(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 Bt(t))if(!e.has(s)){const t=ce(s);for(const s of t)e.add(s)}}else for(const s of ce(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 qt(t,e){const s=Ft(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 r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Ut(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function Ht(t,e){return"compound"===e.type?Bt(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Bt(e).every(e=>Ht(t,e)):"final"===e.type}const Gt=t=>"#"===t[0];function Xt(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 Zt(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Qt(t,e){const s=function(t){const e=Xt(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),r=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>hs(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...r]:r}function Yt(t,e,s,n){const r=t.entry;t.entry=(t,o)=>(o.raise(s(t),{id:e,delay:n(t)}),"function"==typeof r?r(t,o):void 0);const o=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof o?o(t,s):void 0)}function te(t,e,s){const n=as(s.target),r=s.reenter??!1,o=re(t,n);ne(t,o);const i={...s,target:o,source:t,reenter:r,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:o?o.map(t=>`#${t.id}`):void 0})};return i}function ee(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function se(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 ne(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 r=e[s],o=e[n],i=se(r,o);if(r===o||ee(r,o)||ee(o,r)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function re(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(Gt(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ue(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ue(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function oe(t){const e=as(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?ue(t.parent,e):e);return ne(t,s),{target:s,source:t,reenter:!1,eventType:""}}function ie(t){return"history"===t.type}function ce(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 Bt(s))t(e)}(t);for(const s of e)for(const n of Jt(s,t))e.add(n);return e}function ae(t,e){if(Gt(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 ue(t,e){if("string"==typeof e&&Gt(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Ye(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ae(n,t)}return n}function de(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),r=[t.machine.root,t];for(let e=0;e<s.length;e++){const o=ae(t,s[e]);n[e]=o,r.push(o)}for(let t=0;t<s.length;t++)r.push(...de(n[t],e[s[t]]));return r}function he(t,e,s,n,r,o){if("string"==typeof e){const i=ae(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=he(ae(t,c),e[c],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const u=he(ae(t,c),i,s,n,r,o);u&&a.push(...u)}return a.length?a:t.next(s,n,r,o)}function fe(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function le(t,e){for(const s of t)if(fe(s,e))return!0;return!1}function pe(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 r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function ye(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=xe([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(pe(i(e),i(n)))if(fe(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)r.delete(t);r.add(e)}}return Array.from(r)}function ve(t,e,s,n,r){let o;return i=>{if(!i.to)return $e(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)});let c=o?.get(i);return c||(c=$e(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,c)),c}}function me(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(ie(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of me(oe(t),e,s))o.add(n);else o.add(t);return[...o]}function ge(t,e){let s=t;for(;"parallel"===s.type;){const t=Bt(s).find(t=>e.every(e=>e===t||fe(e,t)));if(!t)break;s=t}return s}function _e(t,e,s){const n=me(t,e,s),{targets:r,reenter:o}=s(t);if(!(r?.some(ie)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||fe(e,t.source)))return o?t.source:ge(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Jt(i,void 0))if(c.every(e=>fe(e,t)))return o?t:ge(t,n);return o?void 0:ge(t.source.machine.root,n)}function xe(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=_e(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)fe(s,t)&&r.add(s)}}return[...r]}function be(t,e,s,n,r){return we([{target:[...ce(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,r)}function we(t,e,s,n,r,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let u=e.historyValue;const d=e.context,h=1===t.length?t:ye(t,a,e,ve(e,n,s,!1,i)),f=ve(e,n,s,!0,i),l=h.some(t=>{const{targets:e,reenter:s}=f(t);return!!e?.length||!!s}),p=(t,r,o,i)=>{if(2===t.length){const c=[],a=[];let u;const d=ot(s,c,a,!0),h=M(s)?P({context:r,event:n,children:o,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},s):{context:r,event:n,parent:s.self._parent,self:s.self,children:o,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(h,d);return void 0!==f?.context&&(u=F(r,f.context)),[c,u,a]}return[[Object.assign((e,n)=>t(M(s)?P({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 v=e;const m=(t,e)=>{const n=[],r=ot(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return n},g=()=>{const t=xe(h,a,e,f);let r;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=>Ut(t)&&fe(t,e):t=>t.parent===e;r??={...u},r[t.id]=i.filter(s)}for(const r of t){const t=Lt(e,r.id),[i,u,d]=r.exit?p(r.exit,v.context,e.children,t):[[],void 0,void 0];d?.length&&o.push(...d),u&&(v=Ge(v,{context:u}));const[h,f]=pt(v,n,s,i);v=h,c.push(...f);const l=m(r,v.children);if(l.length){const[t,e]=pt(v,n,s,l);v=t,c.push(...e)}a.delete(r)}u=r||u};!r&&l&&g();let _=v.context;const x=[],w=[];for(const t of h){t.actions&&x.push(...ns(t.actions));const e=f(t);void 0!==e.context&&(_=F(_,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&w.push(...e.internalEvents)}w.length&&o.push(...w);const $=()=>{const t=t=>{const e=v.machine.root;let r;if(void 0!==t.output&&t.parent){const i=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);r=i&&t.parent===e?i.output:rs(t.output,v.context,n,s.self,g[t.id])}else if("parallel"===t.type){const e=o.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);r=e?.output}return void 0===e.output?t.parent===e?r:void 0:rs(e.output,v.context,y(t.id,r),s.self)},i=new Set,d=new Set,l=(t,e)=>{for(const s of t)if(e&&!fe(s,e)||i.add(s),"parallel"===s.type)for(const t of Bt(s))le(i,t)||(i.add(t),m(t))},m=t=>{if(ie(t))if(u[t.id]){const e=u[t.id];for(const t of e)i.add(t),m(t);for(const s of e)l(Jt(s,t.parent),void 0)}else{const e=oe(t),{targets:s}=f(e);for(const n of s??[])i.add(n),e===t.parent?.initial&&d.add(t.parent),m(n);for(const e of s??[])l(Jt(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=f(t.initial).targets;return ie(e)||(i.add(e),d.add(e)),m(e),void l(Jt(e,t),void 0)}if("parallel"===t.type)for(const e of Bt(t))le(i,e)||(i.add(e),d.add(e),m(e))}};for(const t of h){const s=_e(t,e,f),{targets:n,reenter:r}=f(t);for(const e of n??[])ie(e)||t.source===e&&t.source===s&&!r||(i.add(e),d.add(e)),m(e);const o=me(t,e,f);for(const e of o){const n=Jt(e,s);"parallel"===s?.type&&n.push(s),l(n,!t.source.parent&&r?void 0:s)}r&&s===t.source&&i.add(t.source)}r&&d.add(e.machine.root);const g={...e._stateInputs};let _=!1;for(const t of h){const{targets:e,input:s}=f(t);if(s&&e)for(const t of e)g[t.id]=s,_=!0}const x=new Set,w={...v.children};for(const r of[...i].sort((t,e)=>t.order-e.order)){a.add(r);const i=[];let u=!1;for(const t of r.invoke){u=!0;let r=t.logic;"function"==typeof r&&(r=r({actors:e.machine.sources.actors,context:v.context,event:n,self:s.self}));const o="string"==typeof r?ds(e.machine,r):r;if(!o)throw new Error(`Actor logic '${"string"==typeof r?r:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:v.context,event:n,output:os(n)}):t.input;nt(s,t.id);const a=s.system.createActorRef(o,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:b["@xstate.spawn"],args:[a]}),t.id&&(w[t.id]=a)}u&&(v=Ge(v,{children:w}));let h=v.context,f=!1;const l=g[r.id];if(r.entry){const[t,e,s]=p(r.entry,h,w,l);i.push(...t),s?.length&&o.push(...s),e&&(h=e,f=!0)}if(f&&(v.context=h),d.has(r)){const{actions:t,input:e}=$e(r.initial,v,n,s);if(t&&i.push(...t),e&&r.initial?.target)for(const t of r.initial.target)g[t.id]=e,_=!0}const[m,$]=pt(v,n,s,i);if(v=m,i.length=0,c.push(...$),"final"!==r.type)continue;const S=r.parent;let E="parallel"===S?.type?S:S?.parent,I=E||r;for("compound"===S?.type&&o.push(y(S.id,void 0!==r.output?rs(r.output,v.context,n,s.self,l):void 0));"parallel"===E?.type&&!x.has(E)&&Ht(a,E);){x.add(E);const t={};for(const e of Bt(E)){if("final"===e.type){t[e.key]=void 0!==e.output?rs(e.output,v.context,n,s.self,g[e.id]):void 0;continue}if("parallel"===e.type){const s=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const r=Bt(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==r?.output?rs(r.output,v.context,n,s.self,g[r.id]):void 0}o.push(y(E.id,t)),I=E,E=E.parent}E||(v=Ge(v,{status:"done",output:t(I)}))}_&&(v=Ge(v,{_stateInputs:g}))},[S,E]=pt(v,n,s,x);v=S,c.push(...E),_&&_!==e.context&&(v=Ge(v,{context:_})),(r||l)&&$();const I=[...a];if("done"===v.status){const t=[];I.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Lt(v,e.id),[n,,r]=p(e.exit,v.context,v.children,s);t.push(...n),r?.length&&o.push(...r)}});const[e,r]=pt(v,n,s,t);v=e,c.push(...r);const[i,a]=je(v,n,s);v=i,c.push(...a);const[u,d]=Te(v,n,s);v=u,c.push(...d)}return u===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?v.context!==d?[v===e?Ge(v):v,c]:[v,c]:[Ge(v,{_nodes:I,historyValue:u}),c]}}function $e(t,e,s,n,r){let o;const i=()=>o??=M(n)?P({context:e.context,event:s,output:os(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:Lt(e,t.source.id)},n):{context:e.context,event:s,output:os(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:Lt(e,t.source.id)};if(t.to){const o=[],c=[],a=r?.selectionResult?.reusable?r.selectionResult.result:t.to(i(),ot(n,o,c,!0,r?.resolveActions??!0)),u=a?.target?re(t.source,ns(a.target)):void 0,d=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:os(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:o,internalEvents:c,input:d}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:os(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 Se(t,e,n,o,c=[]){let a=t;const u=c.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 r=a.children[e];if(!r)return;if(void 0!==r.sessionId&&r.sessionId!==s)return;const o={...a.children};if(delete o[e],n.system._unregister(r),a=Ge(a,{children:o}),u.length){const[,t]=u.at(-1);u[u.length-1]=[a,t]}else u.push([a,[]])}function h(){const e=ft(u.flatMap(([,t])=>t)),s=("active"===t.status||c.length>0)&&("done"===a.status||"error"===a.status);if(e.length||s){const t=s?[...e,dt(n,a)]:e;if(u.length){const[e,s]=u.at(-1);u[u.length-1]=[e,[...s,...t]]}else u.push([a,t])}return{snapshot:a,microsteps:u}}function f(t,r){if(!Mt(n)&&(e.type===s||(n.system._hasInspectionObservers?.()??1))){const t=n.self._collectedMicrosteps||[];t.push(...r),n.self._collectedMicrosteps=t}u.push(t)}if(e.type===r){const[t,s]=je(a,e,n),[r,o]=Te(t,e,n);return a=Ge(r,{status:"stopped"}),f([a,[...s,...o]],[]),h()}let l=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 r="xstate.after.";if(!t.type.startsWith(r))return t;const o=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!o)return t;const i=t.type.slice(13,-o.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:o}}(e,t.machine);if(e.type===i){const t=a.timers[e.id];if(!t)return h();const s={...a.timers};if(delete s[t.id],a=Ge(a,{timers:s}),"@xstate.raise"===t.type)o.push(t.event),f([a,[]],[]);else{const e="self"===t.target?n.self:t.target;f([a,[ut(n,e,t.event)]],[])}}if(l.type!==s&&l.type!==i){const e=l,s=function(t){return t.type.startsWith("xstate.error.")}(e),r=new Map,i=a.machine.getTransitionData(a,e,n,r);if(s&&!i.length)return"xstate.error.actor"!==e.type||Zt(e,a,e.actorId)?(a=Ge(t,{status:"error",error:e.error}),f([a,[]],[]),d(e),h()):h();const c=we(i,t,n,l,!1,o,r);a=c[0],f(c,i),d(e)}if(!o.length&&!1===t.machine._hasEventlessTransitions)return h();let p=!0;const y=t.machine.options?.maxIterations??1/0;let v=0,m=0;for(;"active"===a.status;){if(m++,m>1e3)throw new Error("Microstep count exceeded 1000");if(v++,v>y)throw new Error(`Infinite loop detected (>${y} microsteps)`);let t,e=p?Oe(a,l,n):[];const s=e.length?a:void 0;if(!e.length){if(!o.length)break;l=o.shift(),t=new Map,e=a.machine.getTransitionData(a,l,n,t)}const r=we(e,a,n,l,!1,o,t);a=r[0],p=a!==s,f(r,e),d(l)}return h()}function Ee(t,e,s,n,r){return!!t.to&&Ae(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}const Ie=()=>{throw _s};let ke;function Ae(t,e,s,n,r,o,i){let c;const a=N(r);a&&xs.push(a);try{c=t(P({context:e,event:s,output:os(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:Lt(n,i)},r),ke??=yt({emit:Ie,cancel:Ie,log:Ie,raise:Ie,spawn:Ie,sendTo:Ie,stop:Ie,listen:Ie,subscribeTo:Ie},Ie))}catch(t){if(t===_s)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&xs.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function je(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=ot(s,r,[]);for(const t of n)o.stop(t);return pt(t,e,s,r)}function Te(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const r=[],o=ot(s,r,[]);for(const t of n)o.cancel(t);return pt(t,e,s,r)}function Oe(t,e,s){const n=new Set,r=t.nodes.filter(Ut);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(Me(o,e,t,r,s)){n.add(o);break t}return ye(Array.from(n),new Set(t.nodes),t,ve(t,e,s,!1))}function Me(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!M(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:()=>N(e)}}),t}({context:s.context,event:e,output:os(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},r);if(!t.guard(o))return!1}if(t.to){const i=Ae(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const Ne={unsubscribe(){}},Pe="or restore this snapshot with embedded children on the runtime that owns them.";function Re(t){return!0===t._remote}const Ce=Object.freeze({status:"active",output:void 0,error:void 0});function De(t,e){const s={_remote:!0,ref:void 0,id:e.id,address:e.address,src:e.src,registryKey:e.registryKey,sessionId:e.incarnation,system:t,_parent:e.parent,_syncSnapshot:e.syncSnapshot,send(e){t.sendEvent(void 0,n,e)},_send(t){throw new Error(`Remote actor '${e.address}' has no local mailbox to receive "${t.type}". Its state lives with another runtime; install a runtime that can reach it (via \`createDurable\`'s adapter runtime operations, or \`system.runtime\`) before sending, ${Pe}`)},getSnapshot:()=>Ce,getPersistedSnapshot(){throw new Error(`Cannot persist remote actor '${e.address}' from here: its state lives with the runtime that owns it. Persist it there, ${Pe}`)},start(){},_stop(){},stop(){throw new Error(`Cannot stop remote actor '${e.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\`system.stopActor(ref)\`), ${Pe}`)},select(){throw new Error(`Cannot select from remote actor '${e.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${Pe}`)},get trigger(){throw new Error(`Remote actor '${e.address}' has no \`trigger\` shorthand: it requires a co-located actor. Use \`send(...)\`, which routes through the system runtime.`)},subscribe:()=>Ne,on:()=>Ne,_isRunning:()=>!1,toJSON:()=>({xstate$type:Os,id:e.id,address:e.address,src:e.src})},n=s;return s.ref=n,n}const Ke=Object.freeze({});function ze(t){return t===Ke||t&&Object.keys(t).length?t:Ke}function Ve(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const We=function(t){return Qe(t,this.value)},Le=function(t){return this.tags.has(t)},Ue=function(t){return this.machine?._canTransition(this,t)??!1},Be=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:r,getInputs:o,toJSON:i,can:c,hasTag:a,matches:u,...d}=this;return{...d,tags:Array.from(s)}},Je=function(){const t={};for(const e of this.nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},Fe=function(){return this._stateInputs};function qe(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function He(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??qt(e.root,t._nodes),tags:qe(t._nodes),children:ze(t.children),timers:ze(t.timers),historyValue:ze(t.historyValue),_stateInputs:ze(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:We,hasTag:Le,can:Ue,getMeta:Je,getInputs:Fe,toJSON:Be};return s&&Tt(n,s),n}function Ge(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:ze(s.children),timers:ze(s.timers),historyValue:ze(s.historyValue),_stateInputs:ze(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:We,hasTag:Le,can:Ue,getMeta:Je,getInputs:Fe,toJSON:Be};return jt(t,e),e}const n=He({...s,value:void 0},t.machine);return jt(t,n),n}function Xe(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 Ze(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:Os,id:n.id};else{const r=Ze(n);r!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=r)}}return e??t}function Qe(t,e){const s=ts(t),n=ts(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Qe(s[t],n[t]))}function Ye(t){if(is(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 ts(t){if(Ve(t))return t.value;if("string"!=typeof t)return t;return es(Ye(t))}function es(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}function ss(t){return is(t)?t:[t]}function ns(t){return void 0===t?[]:ss(t)}function rs(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:os(s),self:n,input:r})}return t}function os(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function is(t){return Array.isArray(t)}function cs(t){return ss(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function as(t){if(void 0!==t&&""!==t)return ns(t)}function us(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r)}}function ds(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,r]=s,o=t.getStateNodeById(r).config.invoke,i=(Array.isArray(o)?o[n]:o).src;return"string"==typeof i?t.sources.actors[i]:i}function hs(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],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}async function fs(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const r=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===r?.status)return r.output;if("error"===r?.status)throw r.error;if("active"===r?.status)return function(t,e){return new Promise((s,n)=>{const r=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(r.unsubscribe(),s(o.output)):"error"===o?.status&&(r.unsubscribe(),n(o.error))})})}(t,e);n({type:u,key:e});try{const t=await s();return n({type:c,key:e,output:t}),t}catch(t){throw n({type:a,key:e,error:t}),t}}function ls(t,e,s){ps(t,e,s);const n=e;n._lastSourceRef=t,n._send(s)}function ps(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}function ys(t,e){t._terminate(e)}function vs(t){t._stop()}let ms,gs=0;const _s=new Error("Transition effect"),xs=[];function bs(){return ms??=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)}`}(),`${ms}:${(gs++).toString(36)}`}function ws(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length&&"(machine)"!==e?e:"x"}function $s(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Ss(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function Es(t,e){return`${t?t.address:""}|${e}`}function Is(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},Et(t))}const ks=Object.freeze({});function As(t,e){return`${t.sessionId}.${e}`}class js{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:bs(),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??ks,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=As(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}const o=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},a=As(t,e);this._snapshot._scheduledTimers===ks&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,Et(this);const u=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],Et(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=u}cancel(t,e){const s=As(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==ks&&delete this._snapshot._scheduledTimers[s],Et(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){ls(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),Et(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(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&&Et(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&&Et(this)}inspect(t){const e=us(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(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);vs(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);ys(t,e)}sendEvent(t,e,s){ps(t,e,s),this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:n});const r=this.runtime?.deadLetter;if(r)return r(t,e,s,n)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):fs(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(xs.length&&xs.includes(e))throw _s;return 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:r,id:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let Ts=!1;const Os="actorRef",Ms=Object.freeze([]);let Ns=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Ps=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function Rs(t,e){try{t?.(e)}catch(t){g(t)}}function Cs(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function Ds(t,e){return new Ks(t,e)}class Ks{get address(){return this._address??=this._parent?`${this._parent.address}/${$s(this.id)}`:$s(this.id)}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=Ns.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._address=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?{...Ps,...e}:Ps,{clock:n,logger:r,parent:o,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new js(t,e)}(this,{clock:n,logger:r,snapshot:s.snapshot??s.state,createActorRef:Ds}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),u&&!o&&this.system.inspect(us(u)),this.sessionId=s._sessionId??`${(d=this.system)._identity.systemId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=Ss(e);return n?Is(t,Es(s?.parent,n.prefix),n.index+1):s?.parent||Is(t,Es(void 0,e),1),e}const n=ws(s?.src),r=Es(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return Is(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,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 h=e?.snapshot??e?.state;this._restored=void 0!==h;try{if(h)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(h,this._actorScope):h);else if(e?._inert);else{const[t,e]=ht(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===Ns.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=Ts;try{Ts=!0,t.exec()}finally{Ts=e}};this._processingStatus!==Ns.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,Tt(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]=ht(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),Cs(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Ms)Rs(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??Ms,actions:this._collectedActions??Ms,sent:this._collectedSent??Ms,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 Cs(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=us(t,e,s);if(this._processingStatus!==Ns.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":Rs(n.complete);break;case"error":{const t=this._snapshot.error;n.error?Rs(n.error,t):g(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,r)=>{const o=us(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Ns.Running)return this;if(this._processingStatus===Ns.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=Ns.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,m(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,m(this.options.input)):(function(t,e,s){const n=bt.get(t),r=It(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!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??{},e=!this.system._clock.now,s=Date.now();for(const n of Object.values(t)){const t=e&&void 0!==n.startedAt?Math.min(n.delay,Math.max(0,n.startedAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,n.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=ht(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,r]=e;n=s,this._setSnapshot(n),Cs(r,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===r&&(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)Rs(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===Ns.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Ns.NotStarted?(this._processingStatus=Ns.Stopped,this.system._unregister(this),this):(this._send({type:r}),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??Ms)Rs(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,Rs(n,t)}this.observers.clear(),e&&g(t)}else this._parent||g(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===Ns.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Ns.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Ns.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");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:Os,id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[_](){return this}getSnapshot(){return this._snapshot}}function zs(t,e){return new Ks(t,e)}function Vs(t,e){const s=t.check(e);if(s)throw s}const Ws=new WeakMap;function Ls(t,e,s){const n=function(t){let e=Ws.get(t);return e||(e=new Map,Ws.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const r=s();n.set(e??Symbol(),{cleanup:"function"==typeof r?r:void 0})}function Us(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[D("xstate.logic.cleanup",()=>function(t){const e=Ws.get(t);if(e){for(const{cleanup:t}of e.values())t?.();Ws.delete(t)}}(n.self))]];if(s.type===u)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],i={},d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:C,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(ut(n,e,t))},raise:t=>{o.push(ut(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(o.push(D("xstate.logic.effect",(e=n.self.system)=>Ls(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const r=t;o.push(D("xstate.logic.effect",(t=n.self.system)=>Ls(n.self,void 0,()=>r(t))))}},h=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),f={...e,...h||{}};return("context"in e||void 0!==h?.context)&&(f.context=h?.context??e.context),(h?.effects||Object.keys(i).length)&&(f.effects={...e.effects,...h?.effects,...i}),ht(n,e,[f,o])},s=(s,r,o)=>{t.validator&&Vs(t.validator,{kind:"event",logic:n,event:r,eventOrigin:o.self._lastSourceRef?"actor":"external"});const i=e(s,r,o);return t.validator&&Vs(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[r,o]=s(t,m(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&Vs(t.validator,{kind:"input",logic:n,input:e});const o=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!==o&&(i.context=o),s({...i},m(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const Bs=new WeakMap;const Js="xstate.observable.next",Fs="xstate.observable.error",qs="xstate.observable.complete";const Hs="xstate.async.resolve",Gs="xstate.async.reject";class Xs extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Zs=Us({context:void 0,run:()=>{}});const Qs=new WeakMap;const Ys={};class tn{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 r=0;r<n.length;r++){const o=n[r];s[o]=e(t[o],o,t,r)}return s}(this.config.states,(t,e)=>new tn(t,{_parent:this,_key:e,_machine:this.machine})):Ys,"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=ns(t.tags).slice(),this.invoke=ns(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=(o=this.id,`${e}.${o}`);var o;const i=t.id??r,c="string"==typeof s?s:`xstate.invoke.${r}`;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,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:d(n,t.id),timerId:h(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:f(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)o.push({event:l(t.id),timerId:p(t.id),resolveEvent:({children:e})=>l(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Zt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const c=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:r,delay:i,transitions:a,fromDelaysMap:u}of o){Yt(t,s,n??(()=>e),e=>Wt(i,u?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const t of cs(a))c.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:i,_eventMatcher:r})}return c.map(e=>({...te(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,en(n,e=>te(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,en(t.config.onDone,s=>te(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,en(t.config.onError,e=>te(t,s,e)))}const n=(e,s,n)=>te(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Zt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),r=(e,s,n)=>{const{target:r,to:o,reenter:i,...c}=s;return te(t,e,{...c,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const o=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Zt(t,s,e.id)}),i=void 0!==e.timeout?p(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=en(e.onDone,e=>{const s=o(e);return i?r(c,s,i):te(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,en(e.onError,e=>{const s=o(e);return i?r(n,s,i):te(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,en(e.onSnapshot,e=>te(t,n,o(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[te(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=en(this.config.always,t=>te(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=Qs.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Qs.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,r="string"==typeof s?t.states[s]:void 0;if(!r&&s)throw new Error(`Initial state "${s}" not found on "#${t.id}"`);const o={source:t,target:r?[r]:void 0,input:n};return o}(this,this.config.initial))}next(t,e,s,n){const r=function(t){const e=Xt(t);return e?`${t.type}|${e}`:t.type}(e);let o=this._candidateCache?.get(r);o||(o=Qt(this,e),(this._candidateCache??=new Map).set(r,o));for(const r of o){if(Me(r,e,t,this,s,n))return[r]}}}function en(t,e){const s=cs(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}function sn(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>hs(e,t));return void 0===s?void 0:t[s]}let nn,rn;function on(){if(rn)return rn;const t=nn??=zs({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 rn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},rn}class cn{constructor(t,e,s){this.config=t,this.validator=s,this._internalEventType=void 0,this.version=void 0,this.schemas=void 0,this.snapshotSchema=void 0,this.eventSchema=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.snapshotSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t)return{issues:[{message:"Expected a persisted snapshot."}]};const e={historyValue:{},timers:{},...t},s=this.schemas?.context;let n=e.context;if(s){const t=await s["~standard"].validate(n);if(t.issues)return{issues:[{message:`Invalid context for machine '${this.id}' version '${this.version}': ${t.issues[0]?.message}`}]};n=t.value}for(const t of["value","children"])if(!(t in e))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(e.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};for(const t of["children","historyValue","timers"])if(null===e[t]||"object"!=typeof e[t]||Array.isArray(e[t]))return{issues:[{message:`Persisted snapshot has invalid '${t}'.`}]};try{this.resolveState({value:e.value,context:n})}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...e,context:n}}}}},this.eventSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t||"string"!=typeof t.type)return{issues:[{message:"Expected an event object."}]};const e=t,s=this.schemas?.events,n=this.schemas?.internalEvents,r=e.type.startsWith("xstate.")||e.type.startsWith("@xstate."),o=sn(n,e.type)??sn(s,e.type);if((s||n)&&!o&&!r)return{issues:[{message:`Unknown event '${e.type}' for machine '${this.id}' version '${this.version}'.`}]};if(!o)return{value:e};const{type:i,...c}=e,a=await o["~standard"].validate(c);return a.issues?a:null===a.value||"object"!=typeof a.value?{issues:[{message:"Expected an event payload."}]}:{value:{...a.value,type:i}}}}},this.internalEventDescriptors=[...Object.keys(this.schemas?.internalEvents??{}),...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 tn(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 r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(te(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=o,u={...a,guard:i,target:`#${r}`};e.push(te(t,"xstate.route",u))}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:r}=this.sources,o=new cn(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o}resolveState(t){const e=(s=this.root,n=t.value,qt(s,Ft(de(s,n))));var s,n;const r=Ft(de(this.root,e));return He({_nodes:[...r],value:e,context:t.context||{},children:{},status:Ht(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??Vt(this,t);this.validator&&Vs(this.validator,{kind:"event",logic:this,event:e,eventOrigin:s&&s.self._lastSourceRef?"actor":"external"}),n&&Ot(r,t,!1),Y(r);const o=this._transitionFast(t,e,r);if(o){n&&Ot(r,o,!1);const e=n&&o!==t?Nt(r,o):this._attachPureActorRef(o,r);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=Se(t,e,r,[]);n&&Ot(r,i,!1);const a=n?i===t?i:Nt(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(c);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:a,effects:u}),[a,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return Mt(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||Tt(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 r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.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!==o.context?{...t.context,...o.context}:t.context;if(!Mt(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}return Ge(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=Se(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return he(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(hs(t,e))return!0;return!1}_canTransition(t,e){const s=on(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=$e(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||Ee(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return v("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=He({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=$(e,n),i=r?.id??st(t,o??n).id;void 0!==r?.id&&(nt(t,r.id),rt(t,r.id));const c=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[c.id]=c,c}}(t,this.sources.actors,r),i=s(function(t,e){return M(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[c]=pt(n,e,t,[]);if(i&&(c.context=i),Object.keys(r).length>0){c.children={...c.children,...r};const e=function(t){const e=Z.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=H(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&Vs(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??Vt(this);Y(n);const r=m(t),o=[],i=this._getPreInitialState(n,r),c=Object.values(i.children).filter(Boolean).map(t=>at(t)),a=(t,e)=>{s&&Ot(n,t,!1);const r=s?Nt(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};try{const[t,e]=be(this.root,i,n,r,o),{snapshot:s,microsteps:u}=Se(t,r,n,o,[[t,[...c,...e]]]);return a(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=Se(i,v("execution",t),n,[],[[i,c]]);return a(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=Ye(t),s=e.slice(1),n=Gt(e[0])?e[0].slice(1):e[0],r=this.idMap.get(n);if(!r)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ue(r,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:r,machine:o,children:i,timers:c,context:a,can:u,hasTag:d,matches:h,getMeta:f,getInputs:l,toJSON:p,...y}=t,v={},m={},g=!1!==e?.embedChildren;for(const t in i){const s=i[t];if(!("string"==typeof s.src||e&&"__unsafeAllowInlineActors"in e))throw new Error("An inline child actor cannot be persisted.");const n=g&&!Re(s);if(!n&&"string"!=typeof s.src)throw new Error(`Unable to persist child '${t}' by address: it requires a registered source key.`);v[t]={address:s.address,...n?{snapshot:s.getPersistedSnapshot(e)}:{remote:!0,incarnation:Re(s)?s.sessionId:void 0},src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const _=At(t)?.actor,x=_?.system?._clock?.now?void 0:_?.system?._snapshot?._scheduledTimers;for(const e in c){const s=c[e];let n,r=s.event;if("xstate.timeout.actor"===r.type&&(r={...r},delete r.sessionId),"self"===s.target)n="self";else{const r=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(r)n=r;else{if(s.target!==At(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"}}}const o=x?.[`${_.sessionId}.${e}`],a=o?o.dueAt-s.delay:s.startedAt;m[e]={id:s.id,delay:s.delay,type:s.type,event:r,target:n,...void 0!==a&&{startedAt:a}}}const b={...y,context:Ze(a),children:v,timers:m,historyValue:Xe(y.historyValue)};return n&&Object.keys(n).length>0&&(b.stateInputs=n),void 0!==o.version&&(b.machine={id:o.id,version:o.version},b.version=o.version),b}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Vt(this),r=t.machine,o=r&&"object"==typeof r&&"function"==typeof r.transition&&"root"in r?void 0:r,i=t.version,c="string"==typeof o?.version?o.version:i;if(void 0!==i&&void 0!==o?.version&&o.version!==i)throw new Error(`Persisted snapshot version '${i}' 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(c!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${c}' does not match machine version '${this.version}'.`);t=e(t,c)}const a=t,u={},d=a.children;for(const t of Object.keys(d)){const e=d[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(`Unable to restore remote child '${t}': a child referenced by address requires a registered source key.`);const s=De(n.system,{id:t,address:e.address,src:e.src,parent:n.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&n.system._set(e.registryKey,s),u[t]=s;continue}const s=e.snapshot,r=e.src,o="string"==typeof r?ds(this,r):r;if(!o){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof r?r:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(o,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:r,registryKey:e.registryKey});i._rehydrated=!0,u[t]=i}const h={},f=a.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=u[t];e&&(s=l(t,e.sessionId))}const r="string"==typeof e.target?"self"===e.target?"self":u[e.target]:n.self._parent;if(!r){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}h[t]={...e,event:s,target:r}}const p=(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 tn)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(a.historyValue),y=(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 r of Object.keys(t)){const o=e.states[r];if(!o)throw n(s.concat(r));y(t[r],o,s.concat(r))}}else if(!e.states[t])throw n(s.concat(t))};y(a.value,this.root,[]);const v=Array.from(Ft(de(this.root,a.value))),{version:m,_nextActorId:g,..._}=t;let x=_._nextActorIds;for(const t of Object.keys(d)){const e=Ss(t);e&&(x?.[e.prefix]??0)<=e.index&&(x={...x,[e.prefix]:e.index+1})}const b=He({..._,children:u,timers:h,_nextActorIds:x,_nodes:v,value:a.value,historyValue:p,_stateInputs:a.stateInputs??{}},this,n.self),w=new WeakSet;return function t(e){if(!w.has(e)){w.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===Os){e[s]=u[n.id];continue}t(n)}}}}(b.context),s?(Ot(n,b,!1),Nt(n,b)):this._attachPureActorRef(b,n)}}function an(t){return new cn(t)}const un={actions:{},actors:{},guards:{},delays:{}},dn=[],hn=[],fn=new Set(Object.values(b));function ln(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function pn(t,e){return"function"==typeof t?t(e):t}function yn(t,e,s){return"function"==typeof t?t({context:e,event:s}):t}function vn(t,e){for(const s of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(t[s],e[s]))return{...t,...e};return t}function mn(t,e,s,n){return{status:t.status,output:t.output,error:t.error,value:e,context:s,input:t.input,children:t.children,timers:t.timers,_nextTimerId:t._nextTimerId,_nextActorIds:t._nextActorIds,_stateInput:n,machine:t.machine}}function gn(t){return{status:"stopped",output:void 0,error:void 0,value:t.value,context:t.context,input:void 0,children:t.children,timers:t.timers,_nextTimerId:t._nextTimerId,_nextActorIds:t._nextActorIds,_stateInput:t._stateInput,machine:t.machine}}function _n(t){const e=xt(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function xn(t){return/^error(\.|$)/.test(t)?`xstate.${t}`:t}function bn(t){return t.startsWith("xstate.error.")?t.slice(7):t}function wn(t){return!!t&&"object"==typeof t&&"string"==typeof t["@expr"]}function $n(t){return wn(t)||function(t){return!!t&&"object"==typeof t&&"string"==typeof t["@code"]}(t)}function Sn(t,e){return"number"==typeof e?`${t}[${e}]`:`${t}.${e}`}function En(t){const e={};if(!t)return e;for(const s of Object.keys(t)){const n=t[s];"number"==typeof n?e[s]=n:n&&"object"==typeof n&&"number"==typeof n.duration&&(e[s]=n.duration)}return e}function In(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function kn(t,e){Array.isArray(t)&&t.forEach((s,n)=>{if(void 0===s.when&&n!==t.length-1)throw new Error(`Choice fallback branch at ${e}[${n}] must be last.`)})}let An="session_scxml",jn="";function Tn(t,e,s,n){const r=`\nwith (context) {\n return (${e});\n}\n `.trim(),o=new Function("context","_event","_sessionid","_name","_ioprocessors","In",r),i=`#_scxml_${An}`,c=s&&s._scxmlExternal,a=s&&"@xstate.init"===s.type,u=s&&"string"==typeof s.type&&s.type.startsWith("xstate.done."),d=s&&s._scxmlEventType;return o(t,s&&!a?{name:s._scxmlEventName??bn(s.type),type:d||(c?"external":"internal"),sendid:s._scxmlSendId,origin:c?i:void 0,origintype:c?"http://www.w3.org/TR/scxml/#SCXMLEventProcessor":void 0,invokeid:s._scxmlInvokeId,data:u?s.output:void 0!==s._scxmlEventData?s._scxmlEventData:s}:void 0,An,jn,{scxml:{location:`#_scxml_${An}`}},t=>{if(!n)return!1;try{const e=n.getSnapshot?.();if(e?.nodes){const s=t.replace(/\./g,"$");return e.nodes.some(t=>t.id===s||t.id.endsWith("."+s))}}catch{}return!1})}function On(t,e){const s=Object.keys(t),n=s.map(t=>`let ${t} = context.${t};`).join("\n"),r=s.map(t=>`updates.${t} = ${t};`).join("\n");return new Function("context","updates",`\n${n}\n${e}\n${r}\nreturn updates;\n `)(t,{})}function Mn(t){return!$n(t)&&t.type.startsWith("@xstate.")}function Nn(t){if("function"==typeof t)return{"@code":t.toString(),"@lang":"ts"};if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?void 0:t;if(function(t){return!!t&&"object"==typeof t&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}(t))return;if(function(t){return!!t&&"object"==typeof t&&"~standard"in t}(t))return;if(Array.isArray(t))return t.map(Nn).filter(t=>void 0!==t);if(t.constructor!==Object&&void 0!==t.constructor)return;const e={};for(const s of Object.keys(t)){const n=t[s];if(void 0!==n){const t=Nn(n);void 0!==t&&(e[s]=t)}}return e}function Pn(t){if(Array.isArray(t)){const e=t.map(Pn).filter(t=>void 0!==t);return e.length?e:void 0}const e=t,s={};for(const t of Object.keys(e)){const n=e[t];void 0!==n&&(s[t]="src"===t&&"string"!=typeof n?n.id:Nn(n),void 0===s[t]&&delete s[t])}return void 0===s.src?void 0:s}function Rn(t){if(!t)return;const e={};for(const s of Object.keys(t)){const n=t[s];e[s]="function"==typeof n?void 0:Nn(n),void 0===e[s]&&delete e[s]}return e}function Cn(t){const e={};for(const s of Object.keys(t)){if("states"===s||"invoke"===s)continue;const n=t[s];void 0!==n&&(e[s]=Nn(n))}if(void 0!==t.invoke){const s=Pn(t.invoke);void 0!==s&&(e.invoke=s)}if(t.states){const s={};for(const e of Object.keys(t.states))s[e]=Cn(t.states[e]);e.states=s}return e}function Dn(t){const e=Cn(t);if(void 0!==t.internalEvents&&(e.internalEvents=Nn(t.internalEvents)),t.schemas){const s={};for(const e of Object.keys(t.schemas)){const n=t.schemas[e];s[e]=n&&"object"==typeof n&&!("~standard"in n)?Rn(n):Nn(n),void 0===s[e]&&delete s[e]}e.schemas=s}for(const s of["actions","guards","actors","delays"])if(t[s]){const n=Rn(t[s]);n&&Object.keys(n).length?e[s]=n:delete e[s]}return e}function Kn(t){return null!==t&&"object"==typeof t}function zn(t){return"transition"in t&&"function"==typeof t.transition}async function Vn(t,e,s){if(!t)return e;const n=await t["~standard"].validate(e);if(n.issues)throw new Error(`Invalid ${s}: ${n.issues[0]?.message}`);return n.value}async function Wn(t,e){return await Vn(e.snapshotSchema,{...t,machine:{id:e.id,version:e.version},version:e.version},`snapshot for machine '${e.id}' version '${e.version}'`)}async function Ln(t,e){return Promise.all(t.map(async(t,s)=>{const n=await e.eventSchema["~standard"].validate(t);if(n.issues){const e=n.issues[0]?.message;if(e?.startsWith("Unknown event "))throw new Error(e);const r=Kn(t)?t.type:void 0;throw new Error("string"==typeof r?`Invalid event '${r}' at index ${s}${e?`: ${e}`:"."}`:`Invalid event at index ${s}${e?`: ${e}`:"."}`)}const r=n.value;if(!Kn(r)||"string"!=typeof r.type)throw new Error(`Invalid event at index ${s}.`);return r}))}const Un=function(t={}){const{validator:e,states:s={},schemas:n,actions:r,actors:o,guards:i,delays:c}=t;return{extend:e=>Un(function(t,e){return{...t,...e,schemas:Jn(t.schemas,e.schemas),states:Bn(t.states,e.states),actions:Bn(t.actions,e.actions),actors:Bn(t.actors,e.actors),guards:Bn(t.guards,e.guards),delays:Bn(t.delays,e.delays)}}(t,e)),createMachine(t){const a=Jn(t.schemas,n),u=Fn(t.states,s),d=Bn(r,t.actions),h=Bn(o,t.actors),f=Bn(i,t.guards),l=Bn(c,t.delays);return new cn({...t,...a?{schemas:a}:void 0,...u?{states:u}:void 0,...d?{actions:d}:void 0,...h?{actors:h}:void 0,...f?{guards:f}:void 0,...l?{delays:l}:void 0},void 0,e)},createStateConfig:(...t)=>t.length>1?t[1]:t[0],states:s,schemas:n??{}}};function Bn(t,e){return t||e?{...t,...e}:void 0}function Jn(t,e){if(t||e)return{...t,...e,events:Bn(t?.events,e?.events),internalEvents:Bn(t?.internalEvents,e?.internalEvents),actions:Bn(t?.actions,e?.actions),guards:Bn(t?.guards,e?.guards),emitted:Bn(t?.emitted,e?.emitted),children:Bn(t?.children,e?.children)}}function Fn(t,e){return t&&e?Object.fromEntries(Object.entries(t).map(([t,s])=>{const n=e[t];if(!n)return[t,s];const r=Bn(s.schemas,n.schemas),o=Fn(s.states,n.states);return[t,{...s,...r?{schemas:r}:void 0,...o?{states:o}:void 0}]})):t}let qn=function(t){return t.Internal="#_internal",t}({});function Hn(t,e,s){if(!t.length)return t;const n=t.slice(),r=n.at(-1)[0];Ot(e,r,!1),r!==s&&Nt(e,r);for(const[t]of n)if(t!==s&&t!==r){Nt(Vt(t.machine,t,void 0,e),t)}return n}function Gn(t,e,s){}const Xn={timeout:1/0};t.Actor=Ks,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const r=e.start+e.timeout;return n.start+n.timeout>r?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1,this._flushingInvalidated&&(this._flushingInvalidated=!1,this.flushTimeouts())}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=qn,t.StateMachine=cn,t.StateNode=tn,t.TimeoutError=Xs,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t.nodes.flatMap(t=>t.ownEvents)])]},t.assertEvent=function(t,e){const s=ns(e);if(!s.some(e=>hs(t.type,e))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.checkStateIn=function(t,e){if("string"==typeof e&&Gt(e)){const s=t.machine.getStateNodeById(e);return t.nodes.some(t=>t===s)}return t.matches(e)},t.createActor=zs,t.createAsyncLogic=function(t){const e=t;return Us({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:n,self:r,system:o},i)=>{switch(t.type){case Hs:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Gs:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return i.effect((t=o)=>{const s=r,i=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,u=xt(a),d=void 0===u?void 0:o._clock.setTimeout(()=>{"active"===r.getSnapshot().status&&(c.abort(),i({type:Gs,data:new Xs(a)}))},u),h=()=>{void 0!==d&&o._clock.clearTimeout(d)},f=()=>Promise.resolve(e.run({input:n,system:o,self:r,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,n)=>t.runStep?Promise.resolve(t.runStep(s,e,n)):fs(s,e,n,i)}));return(t.runLogic?Promise.resolve(t.runLogic(s,f)):f()).then(t=>{h(),"active"===r.getSnapshot().status&&i({type:Hs,data:t})},t=>{h(),"active"===r.getSnapshot().status&&i({type:Gs,data:t})}),()=>{c.abort(),h()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return Us({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t,c=t.emit,a=Bs.get(o);a?.receivers?.forEach(t=>t(n)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return Bs.set(o,t),t.dispose=e({input:r,system:i,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&i._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{Bs.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return zs(Zs)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,n={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case Fs:return ht(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case qs:return ht(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&Vs(s,{kind:"input",logic:n,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],start:(t,{self:s,system:n,emit:r})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:n,self:s,emit:t=>{r(t)}}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:Fs,data:t})},complete:()=>{n._relay(s,s,{type:qs})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return n},t.createFSM=function(t){const e={id:t.id??"(fsm)",sources:un};!function(t){for(const[e,s]of Object.entries(t.states))for(const[t,n]of Object.entries(s.on??{}))for(const s of ln(n))if("string"==typeof s)throw new Error(`Invalid transition for "${e}.${t}": use { target: "${s}" } instead of a string target.`)}(t);const n=(t,e,s,n)=>{if(!n?.length)return[t,dn];const r=function(t){const e=[];for(const s of t){if(!s||"object"!=typeof s||!("action"in s)||"function"!=typeof s.action||fn.has(s.action)||"_special"in s.action)return;e.push({kind:"action",type:s.action.name||"(anonymous)",params:void 0,args:s.args,action:s.action,exec(){return this.action?.(...this.args)}})}return e}(n);return r?[t,r]:pt(t,e,s,n)},o=(t,e,s,r,o,i)=>{if(!r)return[t,dn];const c=[],a=ot(s,c,i,!0);let u;const d=Array.isArray(r)?r.length:1;for(let n=0;n<d;n++){const i=(Array.isArray(r)?r[n]:r)(P({context:u??t.context,event:e,input:o,value:t.value,children:t.children},s),a);if(void 0!==i?.context){const e=u??t.context,s=vn(e,i.context);s!==e&&(u=s)}}const h=void 0!==u?mn(t,t.value,u,t._stateInput):t;return n(h,e,s,c)},c=(e,s,n,r)=>{const o=t.states[e.value],i=o?.on?.[s.type];if(!i)return;const c=Array.isArray(i)?i.length:1;for(let t=0;t<c;t++){const o=Array.isArray(i)?i[t]:i,c=P({context:e.context,event:s,input:e.input,value:e.value,children:e.children},n);if("function"==typeof o){const t=[],e=o(c,ot(n,t,r,!0));if(!e){if(t.length)return{actions:t};continue}return{target:e.target,context:e.context,input:e.input,actions:t}}if(!("guard"in o)||!o.guard||o.guard(c))return{target:o.target,context:pn(o.context,c),input:o.input,actions:"actions"in o&&o.actions?ln(o.actions):hn}}},a=(e,s,u)=>{if("active"!==e.status)return[e,[]];if(s.type===r){const t=[],n=ot(u,t,[]);for(const t of Object.keys(e.timers))n.cancel(t);const[r,o]=pt(e,s,u,t);return[gn(r),o]}if(s.type===i){const t=e.timers[s.id];if(!t)return[e,dn];const n={...e.timers};delete n[t.id];const r={...e,timers:n};if("@xstate.raise"===t.type)return a(r,t.event,u);return[r,[ut(u,"self"===t.target?u.self:t.target,t.event)]]}const d=t.states[e.value],h=d?.on?.[s.type];if(!h)return[e,dn];if(!(Array.isArray(h)||"function"==typeof h||"guard"in h||"actions"in h&&h.actions||"function"==typeof h.input)){const n=h.target??e.value,r=n!==e.value;if(!r||!d.exit&&!t.states[n]?.entry){const t=void 0!==h.context,o=void 0!==h.input,i=M(u)?"function"==typeof h.context?h.context(P({context:e.context,event:s,input:e.input,value:e.value,children:e.children},u)):h.context:pn(h.context,{context:e.context,event:s,input:e.input,value:e.value,self:u.self,system:u.system,parent:u.self._parent,children:e.children}),c=t&&i?vn(e.context,i):e.context;return r||c!==e.context||o||void 0!==e._stateInput?[mn(e,n,c,o?yn(h.input,c,s):void 0),dn]:[e,dn]}}if("function"==typeof h&&h.length<2&&!d?.exit){const n=h(P({context:e.context,event:s,input:e.input,value:e.value,children:e.children},u),void 0);if(n){const r=n.target??e.value;if(!t.states[r]?.entry){const t=void 0!==n.context,o=void 0!==n.input,i=t&&n.context?vn(e.context,n.context):e.context;return r!==e.value||i!==e.context||o||void 0!==e._stateInput?[mn(e,r,i,o?yn(n.input,i,s):void 0),dn]:[e,dn]}}}let f=e;const l=[],p=[s];let y=0;for(;p.length;){if(++y>1e3)throw new Error("FSM microstep count exceeded 1000");const e=p.shift(),s=c(f,e,u,p);if(!s)continue;const r=s.target??f.value,i=r!==f.value;if(i){const[s,n]=o(f,e,u,t.states[f.value]?.exit,f._stateInput,p);f=s,l.push(...n)}let a=f.context;void 0!==s.context&&(a=vn(a,s.context));const d=void 0!==s.input,h=d?yn(s.input,a,e):void 0;(i||a!==f.context||d||void 0!==f._stateInput)&&(f=mn(f,r,a,h));const[v,m]=n(f,e,u,s.actions);if(f=v,l.push(...m),i){const[s,n]=o(f,e,u,t.states[r]?.entry,h,p);f=s,l.push(...n)}}return[f,l]},u={id:t.id,config:t,transition:(...t)=>{Y(t[2]);const[e,s]=a(...t);return ht(t[2],t[0],[e,[...s,...ft(s)]])},initialTransition:(n,r)=>{Y(r);const i=function(t,e){return"function"==typeof t?t({input:e}):t??{}}(t.context,n),c=function(t,e,s,n,r){return{status:"active",output:void 0,error:void 0,value:t,context:e,input:s,children:{},timers:{},_nextTimerId:0,_stateInput:r,machine:n}}(t.initial,i,n,e),u=[];let[d,h]=o(c,{type:s},r,t.states[t.initial]?.entry,void 0,u);for(h.length||(h=[]);u.length;){const[t,e]=a(d,u.shift(),r);d=t,h.push(...e)}return ht(r,void 0,[d,[...h,...ft(h)]])},getInitialSnapshot:(t,e)=>u.initialTransition(e,t)[0],getPersistedSnapshot:({machine:t,...e})=>e,restoreSnapshot:t=>({...t,machine:e})};return u},t.createListenerLogic=k,t.createLogic=Us,t.createMachine=an,t.createMachineFromConfig=function t(e,s={}){const n=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...En(t.delays),...e.delays??{}},evaluators:e.evaluators??{}}}(e,s),r=function(t,e){function s(s,n){const r=s["@lang"]??t;if(!r)throw new Error(`Missing @exprLang for expression at ${n}`);const o=e.evaluators[r];if(!o)throw new Error(`Missing evaluator for @lang '${r}' at ${n}`);return o}function n(t,e,n,r){const o=wn(t)?"expr":"code",i=wn(t)?t["@expr"]:t["@code"];return s(t,r)({source:i,kind:o,slot:e,scope:n,path:r})}function r(t,e,s,o){if($n(t))return n(t,e,s,o);if(Array.isArray(t))return t.map((t,n)=>r(t,e,s,Sn(o,n)));if(!t||"object"!=typeof t)return t;const i={};for(const n of Object.keys(t))i[n]=r(t[n],e,s,Sn(o,n));return i}function o(t,e){return{context:t.context,event:t.event,input:t.input,self:t.self,children:t.children,params:t.params,...e}}return{evaluateResolvable:n,resolveValue:r,makeScope:o,getDurationConfig:function(t,e){return $n(t)?s=>_n(r(t,"delay",o(s),e)):t},assertResolvable:function t(e,n){if($n(e))s(e,n);else if(Array.isArray(e))e.forEach((e,s)=>t(e,Sn(n,s)));else if(e&&"object"==typeof e)for(const s of Object.keys(e))t(e[s],Sn(n,s))}}}(e["@exprLang"],n),{evaluateResolvable:o,resolveValue:i,makeScope:c,getDurationConfig:a}=r;function u(t,s,n){if(t)return $n(t)?e=>!!o(t,s,c(e),n):r=>{const o=i(t.params,s,c(r),`${n}.params`),a=e.guards?.[t.type];if(a){const e=u(a.when,"guard",`$.guards.${t.type}.when`);return!!e?.({...r,params:o})}const d=r.guards?.[t.type];if(!d)throw new Error((h=t.type,f=r.guards??{},`Guard '${h}' is not implemented in machine '${e.id??"(machine)"}'. Available guards: ${Object.keys(f).map(t=>`'${t}'`).join(", ")||"(none)"}.`));var h,f;return d(r,o)}}function d(t,e){if(t)return $n(t)?s=>o(t,"choice",c(s),e):(kn(t,e),s=>{for(let n=0;n<t.length;n++){const r=t[n],o=u(r.when,"choice",`${e}[${n}].when`);if(!o||o(s))return{target:r.target,context:r.context?i(r.context,"transitionContext",c(s),`${e}[${n}].context`):void 0,input:void 0!==r.input?i(r.input,"input",c(s),`${e}[${n}].input`):void 0,description:r.description,reenter:r.reenter,meta:r.meta}}throw new Error(`Choice state at ${e} did not match any branch.`)})}const h={},f=[];let l=null;const p=[];function y(t,e){if(!t||"function"==typeof t)return t;if($n(t))return s=>o(t,"transition",c(s),e);const{guard:s,...n}=t;if(!s)return n;const r=u({type:s},"guard",e);return t=>r(t)?n:void 0}function v(e){return(Array.isArray(e)?e:[e]).map(e=>{const s=e;let r;return r=s._nestedMachineJSON?t(s._nestedMachineJSON,n):n.actors[e.src]??e.src,{src:r,id:e.id,registryKey:e.registryKey,input:void 0!==e.input?t=>i(e.input,"input",c(t),"$.invoke.input"):void 0,onDone:e.onDone?x(e.onDone):void 0,onError:e.onError?x(e.onError):void 0,onSnapshot:e.onSnapshot?x(e.onSnapshot):void 0,timeout:a(e.timeout,"$.invoke.timeout"),onTimeout:e.onTimeout?x(e.onTimeout):void 0}})}function m(t,e,s){const n=s instanceof Error?s.message:"string"==typeof s?s:"unknown error";t.enq.raise({type:"xstate.error.execution",error:{tagname:e,message:n,line:NaN,column:NaN,reason:n},_scxmlEventType:"platform",_scxmlEventName:"error.execution",_scxmlEventData:{tagname:e,message:n,line:NaN,column:NaN,reason:n}}),t.errored=!0}function g(t,s,n,r,o,i){const c=e.actions?.[t.type];if(!c)return n(s.actions[t.type],r),{context:void 0,errored:o.errored};if(i.includes(t.type))return m(o,"action",new Error(`Circular action reference: ${i.concat(t.type).join(" -> ")}`)),{context:void 0,errored:!0};return _(Array.isArray(c)?c:[c],{...s,params:r},n,o,i.concat(t.type))}function _(t,e,s,n,r=[]){const a=n??{enq:s,errored:!1};let u;for(const n of t){if(a.errored)break;if($n(n)){const t=o(n,"action",c(e,{params:e.params,enq:s}),"$.actions");t&&"object"==typeof t&&"context"in t&&t.context&&(u??={},Object.assign(u,t.context))}else if(Mn(n))switch(n.type){case"@xstate.raise":{const t=void 0!==n.delay,r=i(n.event,"actionParams",c(e,{params:e.params}),"$.actions.event"),o=t||void 0!==n.id?{...r,...t?{_scxmlExternal:!0}:{},...void 0!==n.id?{_scxmlSendId:n.id}:{}}:r;s.raise(o,{id:n.id,delay:n.delay});break}case"@xstate.cancel":s.cancel(n.id);break;case"@xstate.log":s.log(...n.args);break;case"@xstate.emit":s.emit(i(n.event,"actionParams",c(e,{params:e.params}),"$.actions.event"));break;case"@xstate.assign":u??={},Object.assign(u,i(n.context,"transitionContext",c(e,{params:e.params}),"$.actions.context"));break;default:throw new Error(`Unknown built-in action: ${n.type}`)}else if("scxml.assign"===n.type){const t=n,s={...e.context,...u};let r;try{r=Tn(s,t.expr,e.event,e.self)}catch(t){m(a,"assign",t);continue}if(t.location.includes(".")){m(a,"assign",new Error(`Invalid assign location: ${t.location}`));continue}u??={},u[t.location]=r}else if("scxml.raise"===n.type){const t=n,r={...e.context,...u};let o,i,c,d;try{if(o=t.eventexpr?Tn(r,t.eventexpr,e.event,e.self):t.event||"unknown",o=xn(o),i={type:o,_scxmlEventName:bn(o)},t.params)for(const s of t.params)i[s.name]=Tn(r,s.expr,e.event,e.self);c=t.targetexpr?Tn(r,t.targetexpr,e.event,e.self):t.target;const s="#_internal"===c;d=t.delayexpr?_n(Tn(r,t.delayexpr,e.event,e.self)):s?void 0:t.delay}catch(t){m(a,"send",t);continue}const h="#_internal"===c,f="#_parent"===c;if("string"==typeof c&&c.length>0&&!c.startsWith("#_")){m(a,"send",new Error(`Invalid send target: ${c}`));continue}if(void 0!==t.id&&(i._scxmlSendId=t.id),f&&e.parent)s.sendTo(e.parent,i,void 0!==d?{delay:d}:void 0);else if("string"!=typeof c||!c.startsWith("#_")||f||h)h?s.raise(i,{id:t.id,delay:d}):(i._scxmlExternal=!0,s.sendTo(e.self,i,{id:t.id,delay:d}));else{const n=c.slice(2),r=e.children?.[n];if(r)s.sendTo(r,i);else if(n.startsWith("scxml_")&&n!==`scxml_${An}`){const t=`Unable to dispatch event to target: ${c}`;s.raise({type:"xstate.error.communication",error:{tagname:"send",message:t,line:NaN,column:NaN,reason:t},_scxmlEventType:"platform",_scxmlEventName:"error.communication",_scxmlEventData:{tagname:"send",message:t,line:NaN,column:NaN,reason:t}})}else i._scxmlExternal=!0,s.sendTo(e.self,i,{id:t.id,delay:d})}}else if("scxml.cancel"===n.type){const t=n,r={...e.context,...u};try{const n=Tn(r,t.sendidexpr,e.event,e.self);n&&s.cancel(n)}catch{}}else if("scxml.script"===n.type){const t=n,s={...e.context,...u};try{const e=On(s,t.code);u??={},Object.assign(u,e)}catch(t){m(a,"script",t)}}else if("scxml.foreach"===n.type){const t=n,r={...e.context,...u},o=t=>/^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(t);if(!o(t.item)||t.index&&!o(t.index)){m(a,"foreach",new Error("foreach item/index is not a legal location"));continue}let i;try{i=Tn(r,t.array,e.event,e.self)}catch(t){m(a,"foreach",t);continue}if(!Array.isArray(i)){m(a,"foreach",new Error("foreach array is not iterable"));continue}u??={};for(let n=0;n<i.length;n++){u[t.item]=i[n],t.index&&(u[t.index]=n);const r={...e,context:{...e.context,...u}},o=_(t.actions,r,s,a);if(o.context&&Object.assign(u,o.context),a.errored)break}}else if("scxml.block"===n.type){const t=n,r={...e,context:{...e.context,...u}},o=_(t.actions,r,s);if(o.context){u??={};for(const t of Object.keys(o.context))o.context[t]!==e.context[t]&&(u[t]=o.context[t])}}else if("scxml.if"===n.type){const t=n,r={...e.context,...u};for(const n of t.branches){let t;if(n.cond)try{t=!!Tn(r,n.cond,e.event,e.self)}catch(e){m(a,"if",e),t=!1}else t=!0;if(t){if(n.actions.length){const t={...e,context:r},o=_(n.actions,t,s,a);if(o.context){u??={};for(const t of Object.keys(o.context))o.context[t]!==e.context[t]&&(u[t]=o.context[t])}}break}}}else{const t=g(n,e,s,i(n.params,"actionParams",c(e,{params:e.params}),"$.actions.params"),a,r);t.context&&(u??={},Object.assign(u,t.context))}}return{context:u?{...e.context,...u}:void 0,errored:a.errored}}function x(t){const e=Array.isArray(t)?t:[t];return e.map((t,s)=>{if($n(t))return(n,r)=>o(t,"transition",c(n,{enq:r}),"$.transition"+(e.length>1?`[${s}]`:""));const n=Array.isArray(t.target)?t.target[0]:t.target,r=t.target,a=u(t.guard,"guard","$.transition.guard"),d=e=>t.context?i(t.context,"transitionContext",c(e),"$.transition.context"):void 0,p=e=>void 0!==t.input?i(t.input,"input",c(e),"$.transition.input"):void 0;return a||t.actions?.length?a&&!t.actions?.length?t.context?{matches:t.matches,guard:a,to:e=>({target:r,context:d(e),reenter:t.reenter}),description:t.description,meta:t.meta,input:void 0!==t.input?p:void 0}:{matches:t.matches,target:r,guard:a,description:t.description,reenter:t.reenter,meta:t.meta,input:void 0!==t.input?p:void 0}:n?{matches:t.matches,guard:a,description:t.description,reenter:t.reenter,meta:t.meta,input:void 0!==t.input?p:void 0,to:(e,s)=>{const o=d(e);if(t.actions?.length){const e=n.replace(/^#/,"");h[e]=t.actions,f.includes(t.actions)||f.push(t.actions)}return{target:r,context:o,reenter:t.reenter}}}:{matches:t.matches,guard:a,description:t.description,reenter:t.reenter,meta:t.meta,input:void 0!==t.input?p:void 0,to:(e,s)=>{const n=d(e);if(t.actions?.length){f.includes(t.actions)||f.push(t.actions),l??=e.context;const r=_(t.actions,e,s);if(r.context)return{context:{...n,...r.context}}}return n?{context:n}:{}}}:t.context?{matches:t.matches,to:e=>({target:r,context:d(e),reenter:t.reenter}),description:t.description,meta:t.meta,input:void 0!==t.input?p:void 0}:{matches:t.matches,target:r,description:t.description,reenter:t.reenter,meta:t.meta,input:void 0!==t.input?p:void 0}})}if(e.delays)for(const t of Object.keys(e.delays)){const s=e.delays[t];"number"==typeof s?n.delays[t]=s:"string"==typeof s?n.delays[t]=_n(s):s&&"object"==typeof s&&(n.delays[t]=e=>_n(i(s.duration,"delay",c(e),`$.delays.${t}.duration`)))}!function(t,e,s){const{assertResolvable:n}=s;function r(s,o){if(s)if($n(s))n(s,o);else if(n(s.params,`${o}.params`),t.guards?.[s.type])r(t.guards[s.type].when,`$.guards.${s.type}.when`);else if(!e.guards[s.type]&&!["scxml.cond","xstate.stateIn","xstate.not"].includes(s.type))throw new Error(`Missing guard source "${s.type}"`)}function o(s,r,i=[]){if($n(s))return void n(s,r);if(!s||"string"!=typeof s.type)throw new Error(`Invalid action at ${r}`);if(n(s.params,`${r}.params`),s.type.startsWith("@xstate.")||s.type.startsWith("scxml."))return void n(s,r);const c=t.actions?.[s.type];if(c){if(i.includes(s.type))throw new Error(`Circular action reference: ${i.concat(s.type).join(" -> ")}`);const t=Array.isArray(c)?c:[c];return void t.forEach((e,n)=>o(e,`${r}.actions.${s.type}${t.length>1?`[${n}]`:""}`,i.concat(s.type)))}if(!e.actions[s.type])throw new Error(`Missing action source "${s.type}"`)}function i(t,e){In(t).forEach((t,s)=>o(t,`${e}[${s}]`))}function c(t,e){(Array.isArray(t)?t:t?[t]:[]).forEach((s,o)=>{const c=Array.isArray(t)?`${e}[${o}]`:e;$n(s)?n(s,c):(r(s.guard,`${c}.guard`),i(s.actions,`${c}.actions`),n(s.context,`${c}.context`),n(s.input,`${c}.input`))})}if(t.actions)for(const e of Object.keys(t.actions)){const s=Array.isArray(t.actions[e])?t.actions[e]:[t.actions[e]];s.forEach((t,n)=>o(t,`$.actions.${e}${s.length>1?`[${n}]`:""}`,[e]))}if(t.guards)for(const e of Object.keys(t.guards))r(t.guards[e].when,`$.guards.${e}.when`);if(t.delays)for(const e of Object.keys(t.delays)){const s=t.delays[e];n(s&&"object"==typeof s&&"duration"in s?s.duration:s,`$.delays.${e}`)}!function s(o,a){if(("history"===o.type||void 0!==o.history)&&!("string"==typeof o.target&&o.target.trim().length>0||Array.isArray(o.target)&&o.target.length>0&&o.target.every(t=>t.trim().length>0)))throw new Error(`History state at ${a} must declare a non-empty target.`);if(n(o.context,`${a}.context`),n(o.input,`${a}.input`),n(o.output,`${a}.output`),n(o.timeout,`${a}.timeout`),i(o.entry,`${a}.entry`),i(o.exit,`${a}.exit`),"choice"===o.type){if(!o.choice)throw new Error(`Choice state at ${a} must declare choice.`);Array.isArray(o.choice)?(kn(o.choice,`${a}.choice`),o.choice.forEach((t,e)=>{r(t.when,`${a}.choice[${e}].when`),n(t.context,`${a}.choice[${e}].context`),n(t.input,`${a}.choice[${e}].input`)})):n(o.choice,`${a}.choice`)}if($n(o.route)&&n(o.route,`${a}.route`),o.invoke&&(Array.isArray(o.invoke)?o.invoke:[o.invoke]).forEach((t,s)=>{const r=`${a}.invoke${Array.isArray(o.invoke)?`[${s}]`:""}`;if(!t._nestedMachineJSON&&!e.actors[t.src])throw new Error(`Missing actor source "${t.src}"`);n(t.input,`${r}.input`),n(t.timeout,`${r}.timeout`),c(t.onDone,`${r}.onDone`),c(t.onError,`${r}.onError`),c(t.onSnapshot,`${r}.onSnapshot`),c(t.onTimeout,`${r}.onTimeout`)}),o.on)for(const t of Object.keys(o.on))c(o.on[t],`${a}.on.${t}`);if(o.after)for(const s of Object.keys(o.after)){if(Number.isNaN(Number(s))&&void 0===xt(s)&&!t.delays?.[s]&&!e.delays[s])throw new Error(`Missing delay source "${s}"`);c(o.after[s],`${a}.after.${s}`)}if(c(o.always,`${a}.always`),c(o.onError,`${a}.onError`),c(o.onTimeout,`${a}.onTimeout`),o.states)for(const t of Object.keys(o.states))s(o.states[t],`${a}.states.${t}`)}(t,"$")}(e,n,r);const b=function t(e,s){const n=In(e.entry),r=e.id||s;var i,c;return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:a(e.timeout,`$.states.${s}.timeout`),states:e.states?Object.entries(e.states).reduce((e,[s,n])=>(e[s]=t(n,s),e),{}):void 0,on:e.on?Object.entries(e.on).reduce((t,[e,s])=>(t[e]=x(s),t),{}):void 0,always:e.always?x(e.always):void 0,onError:e.onError?x(e.onError):void 0,choice:d(e.choice,`$.states.${s}.choice`),route:y(e.route,`$.states.${s}.route`),after:e.after?Object.entries(e.after).reduce((t,[e,s])=>(t[e]=x(s),t),{}):void 0,onTimeout:e.onTimeout?x(e.onTimeout):void 0,entry:"choice"===e.type?void 0:(t,e)=>{for(;p.length;){const t=p.shift();e.raise({type:"xstate.error.execution",error:t,_scxmlEventType:"platform",_scxmlEventName:"error.execution",_scxmlEventData:t})}let s;if(l&&f.length>0&&Object.keys(h).length>0){let n=l;for(const s of f){const r=_(s,{...t,context:n},e);r.context&&(n=r.context)}f.length=0,l=null;for(const t of Object.keys(h))delete h[t];s=n}else{const n=r?h[r]:void 0;if(n){delete h[r];const o=_(n,t,e);o.context&&(s=o.context)}l=null,f.length=0}if(n.length){const r=s?{...t,context:s}:t,o=_(n,r,e);o.context&&(s=o.context)}return{context:s}},exit:e.exit?(c=In(e.exit),(t,e)=>_(c,t,e)):void 0,invoke:e.invoke?v(e.invoke):void 0,meta:e.meta,output:e._scxmlDonedata?(i=e._scxmlDonedata,({context:t,event:e,self:s})=>{try{if(i.params&&i.params.length){const n={};for(const r of i.params)n[r.name]=Tn(t,r.expr,e,s);return n}if(void 0!==i.contentExpr)return Tn(t,i.contentExpr,e,s);if(void 0!==i.contentText)try{return Tn(t,i.contentText,e,s)}catch{return i.contentText}}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";p.push({tagname:"donedata",message:e,line:NaN,column:NaN,reason:e})}}):$n(e.output)?({context:t,event:n,self:r})=>o(e.output,"output",{context:t,event:n,self:r},`$.states.${s}.output`):e.output}}(e),w=e.context?{context:t=>i(e.context,"context",t,"$.context")}:{};jn=e.id||"",An="session_scxml";const $={"scxml.cond":({context:t,event:e,self:s},n)=>{const r=n?.expr;if(!r)return!0;try{return!!Tn(t,r,e,s)}catch(t){const e=t instanceof Error?t.message:"string"==typeof t?t:"unknown error";return p.push({tagname:"cond",message:e,line:NaN,column:NaN,reason:e}),!1}},"xstate.stateIn":(t,e)=>{const s=e?.stateId;if(!s)return!1;const n=s.replace(/^#/,""),r=t._snapshot;return!!r?.nodes&&r.nodes.some(t=>t.id===n)},"xstate.not":(t,e)=>{const s=e?.guard,n=s&&t.guards?.[s.type];if(!n)throw new Error(`Guard '${s?.type}' referenced by 'xstate.not' is not implemented.`);return!n(t,s.params)}},S=an({...b,...w,version:e.version}).provide({actions:n.actions,actors:n.actors,guards:{...$,...n.guards},delays:n.delays});return S._json=e,S},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,n="function"==typeof t?void 0:t.schemas;return Us({validator:"function"==typeof t?void 0:t.validator,schemas:n,context:void 0,run:(t,n)=>{const{event:r,input:o,self:i,system:c}=t;switch(r.type){case Js:return{context:r.data};case Fs:return{status:"error",error:r.data,input:void 0,effects:{observable:{status:"error",error:r.data}}};case qs:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}r.type===s&&n.effect((t=c)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},r=e({input:o,system:c,self:i,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{n({type:Js,data:t})},error:t=>{n({type:Fs,data:t})},complete:()=>{n({type:qs})}});return()=>r.unsubscribe()})}})},t.createStateConfig=function(t){return t},t.createSubscriptionLogic=j,t.createSystem=function(t={}){const e={},s=[];return{createActor(t,n){const r=zs(t,{...n,_systemRef:e});return(()=>{const t=e.current;if(t)for(const e of s)e.active&&!e.subscription&&(e.subscription=t.inspect(e.observer))})(),r},get:t=>e.current?.get(t),getAll:()=>e.current?.getAll()??{},inspect(t){const n=e.current;if(n)return n.inspect(t);const r={observer:t,active:!0};return s.push(r),{unsubscribe(){r.active=!1,r.subscription?.unsubscribe()}}},setup:Un}},t.deliverEvent=ls,t.executeEffects=async function(t,e){for(const s of t)await s.exec(e)},t.getEffectDescriptor=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:t.source.address,event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source?.address,actor:t.actor.address,id:t.id,src:ws(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source?.address,actor:t.actor.address,id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:t.source.address,event:t.event,id:t.id,delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:t.source.address,target:t.target.address,incarnation:Re(t.target)?t.target.sessionId:void 0,event:t.event,id:t.id,delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:t.source.address,id:t.id};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:t.source.address,actor:t.actor.address,id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:t.source.address,actor:t.actor.address,id:t.id,status:t.status,output:t.output,error:t.error}}},t.getInitialMicrosteps=function(t,...[e]){const s=Vt(t);Y(s);const n=m(e),r=[],o=t._getPreInitialState(s,n),i=Object.values(o.children).filter(Boolean).map(t=>at(t)),c=be(t.root,o,s,n,r),{microsteps:a}=Se(c[0],n,s,r,[[c[0],[...i,...c[1]]]]);return Hn(a,s)},t.getInitialSnapshot=function(t,...[e]){const s=Vt(t);return t.initialTransition(e,s)[0]},t.getMicrosteps=function(t,e,s){const n=Vt(t,e);Y(n);const{microsteps:r}=Se(e,s,n,[]);return Hn(r,n,e)},t.getNextSnapshot=function(t,e,s){const n=Vt(t,e),r=t.transition(e,s,n),o=Array.isArray(r)?r[0]:r;return Ot(n,o,!1),o===e?o:Nt(n,o)},t.getNextTransitions=function(t){if("active"!==t.status)return[];const e=[],s=t.nodes.filter(Ut),n=new Set;for(const t of s)for(const s of[t].concat(Jt(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions.entries())e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=de,t.initialTransition=function(t,...[e]){const s=Vt(t),[n,r]=ht(s,void 0,t.initialTransition(e,s));Ot(s,n,!1);const o=Nt(s,n);return Gn(s,o,m(e)),[o,r]},t.isBuiltInExecutableAction=lt,t.isMachineSnapshot=Ve,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.listenerLogic=A,t.machineConfigToJSON=Dn,t.machineVersions=function(t,e){const s=new Map,n=new Map,r=t[0].id;for(const e of t){if(void 0===e.version)throw new Error(`Machine '${e.id}' must define a version.`);if("*"===e.version)throw new Error("Machine version '*' is reserved for wildcard migrations.");if(e.id!==r)throw new Error(`Machine '${e.id}' does not match machine ID '${r}'.`);const t=`${e.id}\0${e.version}`;if(s.has(t))throw new Error(`Duplicate machine identity '${e.id}' version '${e.version}'.`);s.set(t,e),zn(e)&&n.set(t,e)}if(void 0!==e?.unversioned&&!s.has(`${r}\0${e.unversioned}`))throw new Error(`Unversioned snapshot version '${e.unversioned}' is not retained for machine '${r}'.`);const o=async t=>{if(!Kn(t))throw new Error("Persisted snapshot is missing machine identity.");let n,o;if(Kn(t.machine)){if(({id:n,version:o}=t.machine),"string"!=typeof n||"string"!=typeof o)throw new Error("Persisted snapshot has an invalid machine identity.")}else if("string"==typeof t.version)n=r,o=t.version;else{if(void 0!==t.version||void 0===e?.unversioned)throw new Error("Persisted snapshot is missing machine identity.");n=r,o=e.unversioned}if(void 0!==t.version&&"string"!=typeof t.version)throw new Error("Persisted snapshot has an invalid version.");if(void 0!==t.version&&t.version!==o)throw new Error(`Persisted snapshot version '${t.version}' conflicts with machine version '${o}'.`);const i=s.get(`${n}\0${o}`);if(!i)throw new Error(`Unknown machine identity '${n}' version '${o}'.`);if(!("snapshotSchema"in(c=i))||void 0===c.snapshotSchema)throw new Error(`Machine version '${o}' does not define a snapshot schema.`);var c;const a=await Vn(i.snapshotSchema,t,`snapshot for machine '${n}' version '${o}'`);return{source:i,...zn(i)&&{machine:i},snapshot:{...a,machine:{id:n,version:o}}}};return{parseSnapshot:o,async adaptEvents(t,e){const o=n.get(`${r}\0${e.to}`);if(!o)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);const i=e.from.id??r,c=s.get(`${i}\0${e.from.version}`);let a,u=!1;const d=c&&("eventSchema"in(h=c)&&void 0!==h.eventSchema);var h;if(d){let s;try{s=await Ln(t,c)}catch(t){a=t,u=!0}if(s){if(c===o)return s;const t=e.adapters[c.version];if(t)return Ln(await t(s),o)}}const f=e.adapters["*"];if(f)return Ln(await f(t,e.from),o);if(d){if(u)throw a instanceof Error?a:new Error(`Unable to validate event history for machine '${c.id}' version '${c.version}'.`,{cause:a});throw new Error(`No event adapter from version '${c.version}' to '${o.version}' for machine '${o.id}'.`)}if(c)throw new Error(`Machine version '${c.version}' does not define an event schema; only the '*' adapter can handle its event history.`);throw new Error(`Unknown event history source '${i}' version '${e.from.version}'.`)},async migrateSnapshot(t,e){const s=n.get(`${r}\0${e.to}`);if(!s)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);let i,c;try{i=await o(t)}catch(t){c=t}if(i){if(i.source.version===s.version)return Wn(i.snapshot,s);const t=e.migrations[i.source.version];if(t)return Wn(await t(i.snapshot),s)}const a=e.migrations["*"];if(!a){if(i)throw new Error(`No snapshot migration from version '${i.source.version}' to '${s.version}' for machine '${s.id}'.`);throw c}const u=await a(t,function(t,e){return Kn(t)?Kn(t.machine)?{id:"string"==typeof t.machine.id?t.machine.id:void 0,version:"string"==typeof t.machine.version?t.machine.version:void 0}:{id:"string"==typeof t.version?e:void 0,version:"string"==typeof t.version?t.version:void 0}:{}}(t,r));return Wn(u,s)}}},t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},r=new Set;for(const o of t.nodes.filter(Ut)){let i=o;for(;i&&!r.has(i);){r.add(i);const o=n(e,i.path);o?.map&&s.push({stateNode:i,result:o.map(t)}),i=i.parent}}return s},t.matchesState=Qe,t.pathToStateValue=es,t.runStep=fs,t.serializeMachine=function(t){return t._json??Dn(t.config)},t.setup=Un,t.stopActor=vs,t.subscriptionLogic=T,t.terminateActor=ys,t.toObserver=us,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=Vt(t,e);Ot(n,e,!1);const[r,o]=ht(n,e,t.transition(e,s,n));Ot(n,r,!1);const i=r===e?r:Nt(n,r);return Gn(n,i,s),[i,o]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,e,s){const n={...Xn,...s};return new Promise((s,r)=>{const{signal:o}=n;if(o?.aborted)return void r(o.reason);let i=!1;const c=n.timeout===1/0?void 0:setTimeout(()=>{a(),r(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),a=()=>{clearTimeout(c),i=!0,h?.unsubscribe(),d&&o.removeEventListener("abort",d)};function u(t){e(t)&&(a(),s(t))}let d,h;u(t.getSnapshot()),i||(o&&(d=()=>{a(),r(o.reason)},o.addEventListener("abort",d)),h=t.subscribe({next:u,error:t=>{a(),r(t)},complete:()=>{a(),r(new Error("Actor terminated without satisfying predicate"))}}),i&&h.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,function(t){"use strict";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",r="@xstate.stop",o="@xstate.terminate",i="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",u="xstate.logic.effect.start";function d(t,e){return{type:"xstate.after",delay:t,stateId:e}}function h(t,e){return`xstate.after.${t}.${e}`}function f(t){return`xstate.timeout.${t}`}function l(t,e){return{type:"xstate.timeout.actor",actorId:t,sessionId:e}}function p(t){return`xstate.timeout.actor.${t}`}function y(t,e){return{type:"xstate.done.state",stateId:t,output:e}}function v(t,e){return{type:`xstate.error.${t}`,error:e}}function m(t){return{type:s,input:t}}function g(t){setTimeout(()=>{throw t})}const _="function"==typeof Symbol&&Symbol.observable||"@@observable";function x(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}const w={"@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)=>(x(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)},b=new WeakMap;function $(t,e){let s=b.get(t);if(!s){s=new Map;for(const e of Object.keys(t)){const n=t[e];s.has(n)||s.set(n,e)}b.set(t,s)}return s.get(e)}const S=new WeakMap;function E(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:n})=>{const r=e.input.actor;if(!r||"stopped"===r.getSnapshot().status)return;const o=t(e.input,{self:s,system:n});if(!o)return;let i,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),i?.unsubscribe())},u=s._parent;u&&(i=u.subscribe({complete:a,error:a})),S.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(S.get(s)?.unsubscribe(),S.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function I(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function A(){return E(({actor:t,eventType:e,mapper:s},{self:n,system:r})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!ds(t.type,e)||I(n,r,()=>s(t))})},"xstate.listener")}const k=A();function j(){return E(({actor:t,mappers:e},{self:s,system:n})=>{const{done:r,error:o,snapshot:i}=e;return t.subscribe({next:t=>{"done"===t.status&&r?I(s,n,()=>r(t.output)):"error"===t.status&&o?I(s,n,()=>o(t.error)):"active"===t.status&&i&&I(s,n,()=>i(t))},error:t=>{o&&I(s,n,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const T=j(),O=Symbol();function M(t){return!!t[O]}function P(t){return M(t)?t._parent:t.self._parent}function R(t,e){if(!M(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:()=>P(e)}}),t}function C(){return this.action?.(...this.args)}function D(t=this.source.system){return t.emitEvent(this.source,this.event)}function N(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function K(t=this.actor.system){return t.spawnActor(this.source,this.actor)}function V(t=this.actor.system){return t.startActor(this.actor)}function z(t=this.source.system){return t.stopActor(this.actor)}function L(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 U(t=this.source.system){return t.scheduleTimer(this.source,this.id,this.delay??0)}function W(t=this.source.system){return x(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function B(t=this.source.system){return t.cancelTimer(this.source,this.id)}function F(t,e,s){if(!ft(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 r=e.id??"xstate.timer.auto."+n++;e.id=r;const o="@xstate.raise"===e.type||e.target===s.self?"self":e.target;return{...t,timers:{...t.timers,[r]:{id:r,delay:e.delay,type:e.type,event:e.event,target:o}},_nextTimerId:n}}function J(t,e){return{...t,...e}}function q(t,e,...s){const n={action:e,args:s};return t.push(n),n}function H(t,e){const s={...t};for(const t of Object.keys(e))s[t]=Math.max(s[t]??0,e[t]);return s}function G(t,e,s){if("add"===e.type)return{...t,children:{...t.children,[e.id]:e.actor},...e.counters&&{_nextActorIds:H(t._nextActorIds,e.counters)}};const n={...t.children};let r=e.actor._parent===s.self;for(const t of Object.keys(n))n[t]===e.actor&&(r=!0,delete n[t]);if(!r)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);return s.system._unregister(e.actor),{...t,children:n}}function X(t){if("object"==typeof t&&null!==t&&"action"in t&&"function"==typeof t.action)return t}const Q=new WeakMap,Y=()=>({counters:new Map,explicitIds:new Set,stoppedIds:new Set});function Z(t){Q.set(t,Y())}function tt(t){return t.self._snapshot}function et(t,e,s){return Math.max(e.counters.get(s)??0,tt(t)?._nextActorIds?.[s]??0)}function st(t,e,s){const n=Q.get(t)??s??Y(),r=ws(e),o=et(t,n,r);return n.counters.set(r,o+1),{id:`${r}:${o}`,counters:{[r]:o+1}}}function nt(t,e,s){const n=Q.get(t)??s??Y(),r=tt(t)?.children?.[e],o=void 0!==r&&!n.stoppedIds.has(e)&&"active"===r.getSnapshot().status;if(n.explicitIds.has(e)||o)throw new Error(`Child actor id '${e}' is already in use`);n.explicitIds.add(e)}function rt(t,e,s){const n=$s(e);if(!n)return;n.prefix;const r=Q.get(t)??s??Y(),o=Math.max(et(t,r,n.prefix),n.index+1);return r.counters.set(n.prefix,o),{[n.prefix]:o}}function ot(t,e,s,n=!1,r=!0){const o=Q.get(t)??Y(),i={cancel:s=>{q(e,w["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{q(e,t.logger,...s)},raise:(n,r)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==r?.delay?q(e,w["@xstate.raise"],t,n,r):s.push(n)},spawn:(s,n)=>{const{logic:i,src:c}=function(t,e){const s=function(t){return t.self.logic?.sources?.actors}(t);if("string"==typeof e){const t=s?.[e];if(!t)throw new Error(`Actor source '${e}' is not provided`);return{logic:t,src:e}}return s?{logic:e,src:$(s,e)}:{logic:e,src:void 0}}(t,s);if(!r)return{id:n?.id??n?.registryKey??c??i.id};let a,u=n?.id;void 0===u?({id:u,counters:a}=st(t,c??i,o)):(nt(t,u,o),a=rt(t,u,o));const d=t.system.createActorRef(i,{...n,...void 0!==c&&{src:c},id:u,parent:t.self});return function(t,e,s,n){q(t,w["@xstate.spawn"],e).childUpdate={type:"add",actor:e,id:s,counters:n}}(e,d,u,a),d},sendTo:(n,r,o)=>{n?q(e,w["@xstate.sendTo"],t,n,r,o):s.push(v("communication",{message:"Unable to send event to an undefined actor",event:r}))},stop:s=>{if(s){const n=s;q(e,w["@xstate.stop"],t,n).childUpdate={type:"remove",actor:n},function(t,e){const s=Q.get(t);s&&(s.stoppedIds.add(e.id),s.explicitIds.delete(e.id))}(t,n)}}};return n&&Object.assign(i,{listen:(s,n,o)=>{if(!r)return{id:void 0};const i={actor:s,eventType:n,mapper:o},c=t.system.createActorRef(k,{input:i,parent:t.self});return q(e,w["@xstate.spawn"],c),c},subscribeTo:(s,n)=>{if(!r)return{id:void 0};const o={actor:s,mappers:"function"==typeof n?{snapshot:n}:n},i=t.system.createActorRef(T,{input:o,parent:t.self});return q(e,w["@xstate.spawn"],i),i}}),pt(i,(t,...s)=>{q(e,t,...s)})}function it(t,e){switch(t){case w["@xstate.spawn"]:{const[t]=e;return{kind:"builtin",exec:K,source:t._parent,actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case w["@xstate.raise"]:{const[,t,s]=e;return{kind:"builtin",exec:U,source:e[0].self,event:t,id:s?.id,delay:s?.delay}}case w["@xstate.sendTo"]:{const[,t,s,n]=e;return{kind:"builtin",exec:W,source:e[0].self,target:t,event:s,id:n?.id,delay:n?.delay}}case w["@xstate.cancel"]:{const[,t]=e;return{kind:"builtin",exec:B,source:e[0].self,id:t}}case w["@xstate.stop"]:{const[,t]=e;return{kind:"builtin",exec:z,source:e[0].self,actor:t,id:t.id}}default:return}}function ct(t){const e=[t];return{kind:"builtin",exec:V,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function at(t){const e=[t];return{kind:"builtin",exec:K,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}}function ut(t,e,s){const n=[t,e,s,{}];return{kind:"builtin",exec:W,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:n}}function dt(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:L,type:o,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:n}}function ht(t,e,[s,n]){const r="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===o);return!r||i||c?[s,n]:[s,[...n,dt(t,s)]]}function ft(t){return"builtin"===t.kind}function lt(t,e,s,n){let r=t;const o=[];for(const i of n){const n=M(s)?R({context:r.context,event:e,output:rs(e),children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},s):{context:r.context,event:e,output:rs(e),self:s.self,system:s.system,parent:s.self._parent,children:r.children,actions:t.machine.sources.actions,actors:t.machine.sources.actors},c="function"==typeof i,a=X(i),u=c?i:!!a&&a.action.bind(null,...a.args);let d;if("object"==typeof i&&null!==i){const{type:t,childUpdate:e,...s}=i;d=s}if(a?.childUpdate&&(r=G(r,a.childUpdate,s)),u&&"_special"in u){o.push({kind:"action",exec:C,type:"object"==typeof i?"action"in i&&"function"==typeof i.action?i.action.name??"(anonymous)":i.type??"(anonymous)":i.name||"(anonymous)",params:d,args:[],action:void 0});const t=u(n,mt);t&&("context"in t||"children"in t)&&(r={...r,...void 0!==t.context?{context:J(r.context,t.context)}:{},..."children"in t?{children:t.children}:{}});continue}if(!u||!("resolve"in u)){const t="object"==typeof i&&null!==i&&"action"in i&&"function"==typeof i.action?it(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:d,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?D:C},...t};r=F(r,n,s),o.push(n);continue}}return[r,o]}function pt(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:yt,emit:yt,log:yt,raise:yt,spawn:vt,sendTo:yt,stop:yt,listen:vt,subscribeTo:vt,...t}),s}const yt=()=>{},vt=()=>({}),mt=pt({},yt);function gt(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 r=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(!r?.groups)return;const{weeks:o,days:i,hours:c,minutes:a,seconds:u}=r.groups;if(!(o||i||c||a||u))return;const d=t=>t?Number(t.replace(",",".")):0;return 7*d(o)*24*60*60*1e3+24*d(i)*60*60*1e3+60*d(c)*60*1e3+60*d(a)*1e3+1e3*d(u)}function _t(t){if(void 0!==t)return"number"==typeof t?t:gt(t)}const xt=new WeakMap,wt=new WeakMap,bt=new Map;function $t(t){const e=t._peekKeyedActors;return e?e.call(t)??bt:t.keyedActors}function St(t){t._snapshotVersion++}function Et(t){return t._snapshotVersion}function It(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),r=new Map(s?.keyedActors??$t(t)),o=new WeakMap,i=Object.assign(Object.create(t),{children:n,keyedActors:r,reverseKeyedActors:o,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),St(i),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=o.get(t);void 0!==e&&r.get(e)===t&&r.delete(e),o.delete(t),St(i)},_set:(t,e)=>{const s=r.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);r.set(t,e),o.set(e,t),St(i)},get:t=>r.get(t),getAll:()=>Object.fromEntries(r),_hasInspectionObservers:()=>!1,_sendInspectionEvent:()=>{}});for(const[t,e]of r)e&&o.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&&(r.set(e,t),o.set(t,e))}return i}function At(t){const e=xt.get(t);if(e)return e;const s=wt.get(t);if(!s)return;const n=s();return xt.set(t,n),wt.delete(t),n}function kt(t,e){const s=xt.get(t);if(s)return xt.set(e,s),!0;const n=wt.get(t);return!!n&&(wt.set(e,n),!0)}function jt(t,e,s=e.system,n){wt.delete(t);const r=Et(s),o=n?At(n):void 0,i=o?.actor===e?o:At(t);if(i?.actor===e&&i.systemState.sourceSystem===s&&i.systemState.sourceVersion===r)return void xt.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 u=$t(s);let d=u.size?new Map(u):bt;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&&(d===bt&&(d=new Map),d.set(t,e))}xt.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:r}})}function Tt(t,e,s=!0){const n=Ct(t);return n?(n.snapshot=e,n.materialized&&(n.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&jt(e,t.self),e}function Ot(t){return!!Ct(t)||!!t.self.options?._inert}function Mt(t,e){Tt(t,e,!1);const s=Ct(t);Rt.set(e,t);const n=()=>(jt(e,t.self,t.system),At(e));return s&&(s.materialized?s.identityProvider=n:s.identityProvider??=n),function(t,e){xt.delete(t),wt.set(t,e)}(e,n),e}const Pt=Symbol(),Rt=new WeakMap;function Ct(t){return t[Pt]}function Dt(t){return Ct(t).materialize()}const Nt={[O]:!0,get _parent(){const t=Ct(this);return t.parentKnown?t.parent:Dt(this).self._parent},get self(){return Dt(this).self},get defer(){return Dt(this).defer},get id(){return Dt(this).id},get logger(){return Dt(this).logger},get sessionId(){return Dt(this).sessionId},get stopChild(){return Dt(this).stopChild},get system(){return Dt(this).system},get emit(){return Dt(this).emit},get actionExecutor(){return Dt(this).actionExecutor}};function Kt(t,e,s,n,r){const o=e?.(),i=r??o?.actor,c=i?.system,a=i&&c?It(c,s,r?void 0:o?.systemState):void 0,u=Ks(t,{_inert:!0,...i?{id:i.id,_sessionId:i.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return i?._parent&&(u._parent=i._parent,u._address=void 0),n&&(u._snapshot=n),Object.create(u._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function Vt(t,e,s,n){const r=n??(e&&"object"==typeof e?Rt.get(e):void 0),o=r?Ct(r):void 0,i=e&&"object"==typeof e?function(t){return xt.get(t)}(e):void 0,c=o?.identityProvider??(e&&"object"==typeof e?function(t){const e=xt.get(t);return e?()=>e:wt.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:Ve(e)?e.children:{},identityProvider:o?.identityProvider??c,parent:s?._parent??o?.parent??i?.actor._parent,parentKnown:!(!s&&!o?.parentKnown&&!i&&e),materialize:()=>a.materialized??=Kt(t,a.sourceRef,a.sourceChildren,a.snapshot,s)};if(!a.identityProvider&&!e){const e={},n=a.sourceRef,r=a.sourceChildren;let o,i;const c=()=>o??=Kt(t,n,r,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 jt(e,t.self,t.system),i=At(e)}}const u=Object.create(Nt);return u[Pt]=a,u}function zt(t,e,s){if("function"==typeof t)return t(s);const n=function(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:gt(t)??t}(t,e);return"function"==typeof n?n(s):n}function Lt(t,e){return t._stateInputs?.[e]}function Ut(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function Wt(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function Bt(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 Ft(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 Wt(t))if(!e.has(s)){const t=ie(s);for(const s of t)e.add(s)}}else for(const s of ie(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 Jt(t,e){const s=Ft(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 r=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(Ut(t))return t.key}const s={};for(const t of e)s[t.key]=r(t);return s};return r(t)}function qt(t,e){return"compound"===e.type?Wt(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?Wt(e).every(e=>qt(t,e)):"final"===e.type}const Ht=t=>"#"===t[0];function Gt(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 Xt(t,e,s){const n=e.children[s];return!n||!("sessionId"in t)||(void 0===n.sessionId||n.sessionId===t.sessionId)}function Qt(t,e){const s=function(t){const e=Gt(t);return e?[t.type,e]:[t.type]}(e),n=s.flatMap(e=>t.transitions.get(e)??[]),r=[...t.transitions.keys()].filter(t=>!s.includes(t)&&s.some(e=>ds(e,t))).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return n.length?[...n,...r]:r}function Yt(t,e,s,n){const r=t.entry;t.entry=(t,o)=>(o.raise(s(t),{id:e,delay:n(t)}),"function"==typeof r?r(t,o):void 0);const o=t.exit;t.exit=(t,s)=>(s.cancel(e),"function"==typeof o?o(t,s):void 0)}function Zt(t,e,s){const n=cs(s.target),r=s.reenter??!1,o=ne(t,n);se(t,o);const i={...s,target:o,source:t,reenter:r,eventType:e,toJSON:()=>({...i,source:`#${t.id}`,target:o?o.map(t=>`#${t.id}`):void 0})};return i}function te(t,e){for(let s=t.parent;s;s=s.parent)if(s===e)return!0;return!1}function ee(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 se(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 r=e[s],o=e[n],i=ee(r,o);if(r===o||te(r,o)||te(o,r)||"parallel"!==i?.type)throw new Error(`Invalid target set for '${t.id}'`)}}function ne(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(Ht(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return ae(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return ae(t.parent,n)}catch(e){throw new Error(`Invalid transition for '${t.id}': ${e.message}`)}})}function re(t){const e=cs(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?ae(t.parent,e):e);return se(t,s),{target:s,source:t,reenter:!1,eventType:"",to:t.config._historyDefaultTransition}}function oe(t){return"history"===t.type}function ie(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)for(const e of s.initial.target??[])t(e);else if("parallel"===s.type)for(const e of Wt(s))t(e)}(t);for(const s of e)for(const n of Bt(s,t))e.add(n);return e}function ce(t,e){if(Ht(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 ae(t,e){if("string"==typeof e&&Ht(e))try{return t.machine.getStateNodeById(e)}catch{}const s=Ye(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=ce(n,t)}return n}function ue(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),r=[t.machine.root,t];for(let e=0;e<s.length;e++){const o=ce(t,s[e]);n[e]=o,r.push(o)}for(let t=0;t<s.length;t++)r.push(...ue(n[t],e[s[t]]));return r}function de(t,e,s,n,r,o){if("string"==typeof e){const i=ce(t,e).next(s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const i=Object.keys(e),c=i[0];if(1===i.length){const i=de(ce(t,c),e[c],s,n,r,o);return i&&i.length?i:t.next(s,n,r,o)}const a=[];for(const c of i){const i=e[c];if(!i)continue;const u=de(ce(t,c),i,s,n,r,o);u&&a.push(...u)}return a.length?a:t.next(s,n,r,o)}function he(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function fe(t,e){for(const s of t)if(he(s,e))return!0;return!1}function le(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 r=t instanceof Set?t:new Set(t);for(const t of e)if(r.has(t))return!0;return!1}function pe(t,e,s,n){const r=new Set,o=new Map,i=t=>{let r=o.get(t);return r||(r=_e([t],e,s,n),o.set(t,r)),r};for(const e of t){let t=!1;const s=new Set;for(const n of r)if(le(i(e),i(n)))if(he(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)r.delete(t);r.add(e)}}return Array.from(r)}function ye(t,e,s,n,r){let o;return i=>{if(!i.to)return be(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)});let c=o?.get(i);return c||(c=be(i,t,e,s,{resolveActions:n,selectionResult:r?.get(i)}),(o??=new Map).set(i,c)),c}}function ve(t,e,s){const n=e.historyValue,{targets:r}=s(t);if(!r)return[];const o=new Set;for(const t of r)if(oe(t))if(n[t.id])for(const e of n[t.id])o.add(e);else for(const n of ve(re(t),e,s))o.add(n);else o.add(t);return[...o]}function me(t,e){let s=t;for(;"parallel"===s.type;){const t=Wt(s).find(t=>e.every(e=>e===t||he(e,t)));if(!t)break;s=t}return s}function ge(t,e,s){const n=ve(t,e,s),{targets:r,reenter:o}=s(t);if(t._transitionDomain){if("internal"===t._transitionDomain&&"compound"===t.source.type&&n.every(e=>he(e,t.source)))return t.source;const[e,...s]=n.concat(t.source);for(const t of Bt(e,void 0))if("compound"===t.type&&s.every(e=>he(e,t)))return t;return}if(!(r?.some(oe)&&n.some(e=>e===t.source))&&n.every(e=>e===t.source||he(e,t.source)))return o?t.source:me(t.source,n);const[i,...c]=n.concat(t.source);for(const t of Bt(i,void 0))if(c.every(e=>he(e,t)))return o?t:me(t,n);return o?void 0:me(t.source.machine.root,n)}function _e(t,e,s,n){const r=new Set;for(const o of t){const{targets:t,reenter:i}=n(o);if(t?.length){const t=ge(o,s,n);i&&o.source===t&&r.add(t);for(const s of e)he(s,t)&&r.add(s)}}return[...r]}function xe(t,e,s,n,r){const o=[...ie(t)],i=new Set,c=t=>{if("compound"===t.type){i.add(t);for(const e of t.initial.target??[])c(e)}else if("parallel"===t.type)for(const e of Wt(t))c(e)};return c(t),we([{target:o.filter(t=>!o.some(e=>e!==t&&he(e,t))),source:t,reenter:!0,eventType:null,toJSON:null,_statesForDefaultEntry:[...i]}],e,s,n,!0,r)}function we(t,e,s,n,r,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e.nodes);let u=e.historyValue;const d=e.context,h=1===t.length?t:pe(t,a,e,ye(e,n,s,!1,i)),f=ye(e,n,s,!0,i),l=h.some(t=>{const{targets:e,reenter:s}=f(t);return!!e?.length||!!s}),p=(t,r,o,i)=>{if(2===t.length){const c=[],a=[];let u;const d=ot(s,c,a,!0),h=M(s)?R({context:r,event:n,children:o,actions:e.machine.sources.actions,actors:e.machine.sources.actors,guards:e.machine.sources.guards,delays:e.machine.sources.delays,input:i},s):{context:r,event:n,parent:s.self._parent,self:s.self,children:o,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(h,d);return void 0!==f?.context&&(u=J(r,f.context)),[c,u,a]}return[[Object.assign((e,n)=>t(M(s)?R({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 v=e;const m=(t,e)=>{const n=[],r=ot(s,n,[]);for(const s of t.invoke){const t=e[s.id];t&&r.stop(t)}return n},g=()=>{const t=_e(h,a,e,f);let r;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=>Ut(t)&&he(t,e):t=>t.parent===e;r??={...u},r[t.id]=i.filter(s)}for(const r of t){const t=Lt(e,r.id),[i,u,d]=r.exit?p(r.exit,v.context,e.children,t):[[],void 0,void 0];d?.length&&o.push(...d),u&&(v=He(v,{context:u}));const[h,f]=lt(v,n,s,i);v=h,c.push(...f);const l=m(r,v.children);if(l.length){const[t,e]=lt(v,n,s,l);v=t,c.push(...e)}a.delete(r)}u=r||u};!r&&l&&g();let _=v.context;const x=[],b=[];for(const t of h){t.actions&&x.push(...ss(t.actions));const e=f(t);void 0!==e.context&&(_=J(_,e.context)),e.actions&&x.push(...e.actions),e.internalEvents&&b.push(...e.internalEvents)}b.length&&o.push(...b);const $=()=>{const t=t=>{const e=v.machine.root;let r;if(void 0!==t.output&&t.parent){const i=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);r=i&&t.parent===e?i.output:ns(t.output,v.context,n,s.self,_[t.id])}else if("parallel"===t.type){const e=o.find(e=>"xstate.done.state"===e.type&&e.stateId===t.id);r=e?.output}return void 0===e.output?t.parent===e?r:void 0:ns(e.output,v.context,y(t.id,r),s.self)},i=new Set,d=new Set,l=new Map,m=(t,e)=>{for(const s of t)if(e&&!he(s,e)||i.add(s),"parallel"===s.type)for(const t of Wt(s))fe(i,t)||(i.add(t),g(t))},g=t=>{if(oe(t))if(u[t.id]){const e=u[t.id];for(const t of e)i.add(t),g(t);for(const s of e)m(Bt(s,t.parent),void 0)}else{const e=re(t),s=t.parent;d.add(s);const n=l.get(s)??[];n.push(e),l.set(s,n);const{targets:r}=f(e);for(const s of r??[])i.add(s),e===t.parent?.initial&&d.add(t.parent),g(s);for(const e of r??[])m(Bt(e,t.parent),void 0)}else{if("compound"===t.type){const e=f(t.initial).targets??[];for(const t of e)oe(t)||i.add(t);d.add(t);for(const t of e)g(t);for(const s of e)m(Bt(s,t),void 0);return}if("parallel"===t.type)for(const e of Wt(t))fe(i,e)||(i.add(e),d.add(e),g(e))}};for(const t of h){const s=ge(t,e,f),{targets:n,reenter:r}=f(t);for(const e of n??[])oe(e)||t.source===e&&t.source===s&&!r||(i.add(e),d.add(e)),g(e);const o=ve(t,e,f);for(const e of o){const n=Bt(e,s);"parallel"===s?.type&&n.push(s),m(n,!t.source.parent&&r?void 0:s)}r&&s===t.source&&i.add(t.source)}if(r)for(const t of h[0]._statesForDefaultEntry??[e.machine.root])d.add(t);const _={...e._stateInputs};let x=!1;for(const t of h){const{targets:e,input:s}=f(t);if(s&&e)for(const t of e)_[t.id]=s,x=!0}const b=new Set,$={...v.children};for(const r of[...i].sort((t,e)=>t.order-e.order)){a.add(r);const i=[];let u=!1;for(const t of r.invoke){u=!0;let r=t.logic;"function"==typeof r&&(r=r({actors:e.machine.sources.actors,context:v.context,event:n,self:s.self}));const o="string"==typeof r?us(e.machine,r):r;if(!o)throw new Error(`Actor logic '${"string"==typeof r?r:"inline"}' not implemented`);const c="function"==typeof t.input?t.input({self:s.self,context:v.context,event:n,output:rs(n)}):t.input;nt(s,t.id);const a=s.system.createActorRef(o,{...t,input:c,parent:s.self,syncSnapshot:!!t.onSnapshot});i.push({action:w["@xstate.spawn"],args:[a]}),t.id&&($[t.id]=a)}u&&(v=He(v,{children:$}));let h=v.context,f=!1;const m=_[r.id];if(r.entry){const[t,e,s]=p(r.entry,h,$,m);i.push(...t),s?.length&&o.push(...s),e&&(h=e,f=!0)}if(f&&(v.context=h),d.has(r)){const t=[r.initial,...l.get(r)??[]].filter(Boolean);for(const e of t){const{actions:t,context:r,input:c,internalEvents:a}=be(e,v,n,s);if(t&&i.push(...t),a?.length&&o.push(...a),void 0!==r&&(v.context=J(v.context,r)),c&&e.target)for(const t of e.target)_[t.id]=c,x=!0}}const[g,S]=lt(v,n,s,i);if(v=g,i.length=0,c.push(...S),"final"!==r.type)continue;const E=r.parent;let I="parallel"===E?.type?E:E?.parent,A=I||r;for("compound"===E?.type&&o.push(y(E.id,void 0!==r.output?ns(r.output,v.context,n,s.self,m):void 0));"parallel"===I?.type&&!b.has(I)&&qt(a,I);){b.add(I);const t={};for(const e of Wt(I)){if("final"===e.type){t[e.key]=void 0!==e.output?ns(e.output,v.context,n,s.self,_[e.id]):void 0;continue}if("parallel"===e.type){const s=o.find(t=>"xstate.done.state"===t.type&&t.stateId===e.id);t[e.key]=s?.output;continue}const r=Wt(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==r?.output?ns(r.output,v.context,n,s.self,_[r.id]):void 0}o.push(y(I.id,t)),A=I,I=I.parent}I||(v=He(v,{status:"done",output:t(A)}))}x&&(v=He(v,{_stateInputs:_}))},[S,E]=lt(v,n,s,x);v=S,c.push(...E),_&&_!==e.context&&(v=He(v,{context:_})),(r||l)&&$();const I=[...a];if("done"===v.status){const t=[];I.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=Lt(v,e.id),[n,,r]=p(e.exit,v.context,v.children,s);t.push(...n),r?.length&&o.push(...r)}});const[e,r]=lt(v,n,s,t);v=e,c.push(...r);const[i,a]=ke(v,n,s);v=i,c.push(...a);const[u,d]=je(v,n,s);v=u,c.push(...d)}return u===e.historyValue&&e.nodes.length===a.size&&e.nodes.every(t=>a.has(t))?v.context!==d?[v===e?He(v):v,c]:[v,c]:[He(v,{_nodes:I,historyValue:u}),c]}}function be(t,e,s,n,r){let o;const i=()=>o??=M(n)?R({context:e.context,event:s,output:rs(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:Lt(e,t.source.id)},n):{context:e.context,event:s,output:rs(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:Lt(e,t.source.id)};if(t.to){const o=[],c=[],a=r?.selectionResult?.reusable?r.selectionResult.result:t.to(i(),ot(n,o,c,!0,r?.resolveActions??!0)),u=a?.target?ne(t.source,ss(a.target)):void 0,d=a?.input??("function"==typeof t.input?t.input({context:e.context,event:s,output:rs(s)}):t.input);return{targets:u,context:a?.context,reenter:a?.reenter,actions:o,internalEvents:c,input:d}}const c="function"==typeof t.input?t.input({context:e.context,event:s,output:rs(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 $e(t,e,o,c,a=[]){let u=t;const d=a.slice();function h(t){if("xstate.done.actor"!==t.type&&"xstate.error.actor"!==t.type)return;const{actorId:e,sessionId:s}=t;if(!e)return;const n=u.children[e];if(!n)return;if(void 0!==n.sessionId&&n.sessionId!==s)return;const r={...u.children};if(delete r[e],o.system._unregister(n),u=He(u,{children:r}),d.length){const[,t]=d.at(-1);d[d.length-1]=[u,t]}else d.push([u,[]])}function f(){const e=function(t){const e=[],s=[];for(const r of t){if(!ft(r)||r.type!==n)continue;const{actor:t,logic:o}=r,i=ct(t);o===k||o===T?e.push(i):s.push(i)}return[...e,...s]}(d.flatMap(([,t])=>t)),s=("active"===t.status||a.length>0)&&("done"===u.status||"error"===u.status);if(e.length||s){const t=s?[...e,dt(o,u)]:e;if(d.length){const[e,s]=d.at(-1);d[d.length-1]=[e,[...s,...t]]}else d.push([u,t])}return{snapshot:u,microsteps:d}}function l(t,n){if(!Ot(o)&&(e.type===s||(o.system._hasInspectionObservers?.()??1))){const t=o.self._collectedMicrosteps||[];t.push(...n),o.self._collectedMicrosteps=t}d.push(t)}if(e.type===r){const[t,s]=ke(u,e,o),[n,r]=je(t,e,o);return u=He(n,{status:"stopped"}),l([u,[...s,...r]],[]),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 r="xstate.after.";if(!t.type.startsWith(r))return t;const o=[...e.idMap.keys()].sort((t,e)=>e.length-t.length).find(e=>t.type.endsWith(`.${e}`));if(!o)return t;const i=t.type.slice(13,-o.length-1);return{...t,type:"xstate.after",delay:Number.isNaN(+i)?i:+i,stateId:o}}(e,t.machine);if(e.type===i){const t=u.timers[e.id];if(!t)return f();const s={...u.timers};if(delete s[t.id],u=He(u,{timers:s}),"@xstate.raise"===t.type)c.push(t.event),l([u,[]],[]);else{const e="self"===t.target?o.self:t.target;l([u,[ut(o,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,r=u.machine.getTransitionData(u,e,o,n);if(s&&!r.length)return"xstate.error.actor"!==e.type||Xt(e,u,e.actorId)?(u=He(t,{status:"error",error:e.error}),l([u,[]],[]),h(e),f()):f();const i=we(r,t,o,p,!1,c,n);u=i[0],l(i,r),h(e)}if(!c.length&&!1===t.machine._hasEventlessTransitions)return f();let y=!0;const v=t.machine.options?.maxIterations??1/0;let m=0,g=0;for(;"active"===u.status;){if(g++,g>1e3)throw new Error("Microstep count exceeded 1000");if(m++,m>v)throw new Error(`Infinite loop detected (>${v} microsteps)`);let t,e=y?Te(u,p,o):[];const s=e.length?u:void 0;if(!e.length){if(!c.length)break;p=c.shift(),t=new Map,e=u.machine.getTransitionData(u,p,o,t)}const n=we(e,u,o,p,!1,c,t);u=n[0],y=u!==s,l(n,e),h(p)}return f()}function Se(t,e,s,n,r){return!!t.to&&Ae(t.to,e,s,n,r,n.machine.sources,t.source.id).enabled}const Ee=()=>{throw gs};let Ie;function Ae(t,e,s,n,r,o,i){let c;const a=P(r);a&&_s.push(a);try{c=t(R({context:e,event:s,output:rs(s),value:n.value,children:n.children,actions:o.actions,actors:o.actors,guards:o.guards,delays:o.delays,input:Lt(n,i)},r),Ie??=pt({emit:Ee,cancel:Ee,log:Ee,raise:Ee,spawn:Ee,sendTo:Ee,stop:Ee,listen:Ee,subscribeTo:Ee},Ee))}catch(t){if(t===gs)return{enabled:!0,result:void 0,reusable:!1};throw t}finally{a&&_s.pop()}return{enabled:void 0!==c,result:c,reusable:!0}}function ke(t,e,s){let n;if(!t.children||0===(n=Object.values(t.children).filter(Boolean)).length)return[t,[]];const r=[],o=ot(s,r,[]);for(const t of n)o.stop(t);return lt(t,e,s,r)}function je(t,e,s){const n=Object.keys(t.timers);if(!n.length)return[t,[]];const r=[],o=ot(s,r,[]);for(const t of n)o.cancel(t);return lt(t,e,s,r)}function Te(t,e,s){const n=new Set,r=t.nodes.filter(Ut);for(const o of r)t:for(let r=o;r;r=r.parent)if(r.always)for(const o of r.always)if(Oe(o,e,t,r,s)){n.add(o);break t}return pe(Array.from(n),new Set(t.nodes),t,ye(t,e,s,!1))}function Oe(t,e,s,n,r,o){if(t.matches&&!function(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}(e,t.matches))return!1;if(t._eventMatcher&&!t._eventMatcher(e,s))return!1;if(t.guard){const o=function(t,e){if(!M(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:()=>P(e)}}),t}({context:s.context,event:e,output:rs(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},r);if(!t.guard(o))return!1}if(t.to){const i=Ae(t.to,s.context,e,s,r,n.machine.sources,t.source.id);return o?.set(t,i),i.enabled}return!0}const Me={unsubscribe(){}},Pe="or restore this snapshot with embedded children on the runtime that owns them.";function Re(t){return!0===t._remote}const Ce=Object.freeze({status:"active",output:void 0,error:void 0});function De(t,e){const s={_remote:!0,ref:void 0,id:e.id,address:e.address,src:e.src,registryKey:e.registryKey,sessionId:e.incarnation,system:t,_parent:e.parent,_syncSnapshot:e.syncSnapshot,send(e){t.sendEvent(void 0,n,e)},_send(t){throw new Error(`Remote actor '${e.address}' has no local mailbox to receive "${t.type}". Its state lives with another runtime; install a runtime that can reach it (via \`createDurable\`'s adapter runtime operations, or \`system.runtime\`) before sending, ${Pe}`)},getSnapshot:()=>Ce,getPersistedSnapshot(){throw new Error(`Cannot persist remote actor '${e.address}' from here: its state lives with the runtime that owns it. Persist it there, ${Pe}`)},start(){},_stop(){},stop(){throw new Error(`Cannot stop remote actor '${e.address}' directly: stopping is a co-located operation. Stop it through the system runtime that owns it (\`system.stopActor(ref)\`), ${Pe}`)},select(){throw new Error(`Cannot select from remote actor '${e.address}': its snapshot is not synchronously readable because its state lives with another runtime. Read it on the runtime that owns it, ${Pe}`)},get trigger(){throw new Error(`Remote actor '${e.address}' has no \`trigger\` shorthand: it requires a co-located actor. Use \`send(...)\`, which routes through the system runtime.`)},subscribe:()=>Me,on:()=>Me,_isRunning:()=>!1,toJSON:()=>({xstate$type:Ts,id:e.id,address:e.address,src:e.src})},n=s;return s.ref=n,n}const Ne=Object.freeze({});function Ke(t){return t===Ne||t&&Object.keys(t).length?t:Ne}function Ve(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const ze=function(t){return Qe(t,this.value)},Le=function(t){return this.tags.has(t)},Ue=function(t){return this.machine?._canTransition(this,t)??!1},We=function(){const{nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:r,getInputs:o,toJSON:i,can:c,hasTag:a,matches:u,...d}=this;return{...d,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},Fe=function(){return this._stateInputs};function Je(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function qe(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??Jt(e.root,t._nodes),tags:Je(t._nodes),children:Ke(t.children),timers:Ke(t.timers),historyValue:Ke(t.historyValue),_stateInputs:Ke(t._stateInputs),_nextTimerId:t._nextTimerId??0,_nextActorIds:t._nextActorIds,matches:ze,hasTag:Le,can:Ue,getMeta:Be,getInputs:Fe,toJSON:We};return s&&jt(n,s),n}function He(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:Ke(s.children),timers:Ke(s.timers),historyValue:Ke(s.historyValue),_stateInputs:Ke(s._stateInputs),_nextTimerId:s._nextTimerId??0,_nextActorIds:s._nextActorIds,matches:ze,hasTag:Le,can:Ue,getMeta:Be,getInputs:Fe,toJSON:We};return kt(t,e),e}const n=qe({...s,value:void 0},t.machine);return kt(t,n),n}function Ge(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 Xe(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:Ts,id:n.id};else{const r=Xe(n);r!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=r)}}return e??t}function Qe(t,e){const s=Ze(t),n=Ze(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&Qe(s[t],n[t]))}function Ye(t){if(os(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 Ze(t){if(Ve(t))return t.value;if("string"!=typeof t)return t;return ts(Ye(t))}function ts(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}function es(t){return os(t)?t:[t]}function ss(t){return void 0===t?[]:es(t)}function ns(t,e,s,n,r){if("function"==typeof t){return t({context:e,event:s,output:rs(s),self:n,input:r})}return t}function rs(t){if(function(t){return"xstate.done.actor"===t.type||"xstate.done.state"===t.type}(t)){return t.output}}function os(t){return Array.isArray(t)}function is(t){return es(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function cs(t){if(void 0!==t&&""!==t)return ss(t)}function as(t,e,s){const n="object"==typeof t,r=n?t:void 0;return{next:(n?t.next:t)?.bind(r),error:(n?t.error:e)?.bind(r),complete:(n?t.complete:s)?.bind(r)}}function us(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.sources.actors[e];const[,n,r]=s,o=t.getStateNodeById(r).config.invoke,i=(Array.isArray(o)?o[n]:o).src;return"string"==typeof i?t.sources.actors[i]:i}function ds(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],r=n[t];if("*"===e){return t===s.length-1}if(e!==r)return!1}return!0}async function hs(t,e,s,n=e=>{t.system.sendEvent(t,t,e)}){const r=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===r?.status)return r.output;if("error"===r?.status)throw r.error;if("active"===r?.status)return function(t,e){return new Promise((s,n)=>{const r=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(r.unsubscribe(),s(o.output)):"error"===o?.status&&(r.unsubscribe(),n(o.error))})})}(t,e);n({type:u,key:e});try{const t=await s();return n({type:c,key:e,output:t}),t}catch(t){throw n({type:a,key:e,error:t}),t}}function fs(t,e,s){ls(t,e,s);const n=e;n._lastSourceRef=t,n._send(s)}function ls(t,e,s){const n=e;if(t!==e&&n.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}function ps(t,e){t._terminate(e)}function ys(t){t._stop()}let vs,ms=0;const gs=new Error("Transition effect"),_s=[];function xs(){return vs??=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)}`}(),`${vs}:${(ms++).toString(36)}`}function ws(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length&&"(machine)"!==e?e:"x"}function bs(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function $s(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}function Ss(t,e){return`${t?t.address:""}|${e}`}function Es(t,e,s){const n=t._snapshot._nextActorIds;(n[e]??0)>=s||(t._snapshot._nextActorIds={...n,[e]:s},St(t))}const Is=Object.freeze({});function As(t,e){return`${t.sessionId}.${e}`}class ks{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:xs(),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??Is,_nextActorIds:{}}}_recordSent(t,e,s,n,r){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:r})}schedule(t,e,s){const n=As(t,e);void 0!==this._timerMap?.[n]&&this.cancel(t,e);const r=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}const o=this._clock.now?.()??Date.now(),c={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},a=As(t,e);this._snapshot._scheduledTimers===Is&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[a]=c,St(this);const u=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[a],delete this._snapshot._scheduledTimers[a],St(this),this._deliver(t,t,{type:i,id:e})},s);(this._timerMap??={})[a]=u}cancel(t,e){const s=As(t,e),n=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==Is&&delete this._snapshot._scheduledTimers[s],St(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){fs(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),St(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(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&&St(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&&St(this)}inspect(t){const e=as(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(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);ys(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);ps(t,e)}sendEvent(t,e,s){ls(t,e,s),this._recordSent(t,e,s);const n=this.runtime?.sendEvent;if(n)return n(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,n){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:n});const r=this.runtime?.deadLetter;if(r)return r(t,e,s,n)}runStep(t,e,s){const n=this.runtime?.runStep;return n?n(t,e,s):hs(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const n=this.runtime?.scheduleTimer;if(n){const r=t.getSnapshot()?.timers?.[e];if(r){const n="self"===r.target?t:r.target;this._recordSent(t,n,r.event,s,e)}return n(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(_s.length&&_s.includes(e))throw gs;return 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:r,id:o}=t[s];this.scheduleTimer(n,o,Math.max(0,r-(this._clock.now?.()??Date.now())))}}}let js=!1;const Ts="actorRef",Os=Object.freeze([]);let Ms=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Ps=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function Rs(t,e){try{t?.(e)}catch(t){g(t)}}function Cs(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function Ds(t,e){return new Ns(t,e)}class Ns{get address(){return this._address??=this._parent?`${this._parent.address}/${bs(this.id)}`:bs(this.id)}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=Ms.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._address=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?{...Ps,...e}:Ps,{clock:n,logger:r,parent:o,syncSnapshot:i,id:c,registryKey:a,inspect:u}=s;var d;this.system=o?o.system:s._systemRef?.current??function(t,e){return new ks(t,e)}(this,{clock:n,logger:r,snapshot:s.snapshot??s.state,createActorRef:Ds}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),u&&!o&&this.system.inspect(as(u)),this.sessionId=s._sessionId??`${(d=this.system)._identity.systemId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const n=$s(e);return n?Es(t,Ss(s?.parent,n.prefix),n.index+1):s?.parent||Es(t,Ss(void 0,e),1),e}const n=ws(s?.src),r=Ss(s?.parent,n),o=t._snapshot._nextActorIds[r]??0;return Es(t,r,o+1),s?.parent||"x"===n||0!==o?`${n}:${o}`:n}(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,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 h=e?.snapshot??e?.state;this._restored=void 0!==h;try{if(h)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(h,this._actorScope):h);else if(e?._inert);else{const[t,e]=ht(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===Ms.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=js;try{js=!0,t.exec()}finally{js=e}};this._processingStatus!==Ms.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,jt(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]=ht(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),Cs(n,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Os)Rs(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??Os,actions:this._collectedActions??Os,sent:this._collectedSent??Os,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 Cs(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=as(t,e,s);if(this._processingStatus!==Ms.Stopped)(this.observers??=new Set).add(n);else switch(this._snapshot.status){case"done":Rs(n.complete);break;case"error":{const t=this._snapshot.error;n.error?Rs(n.error,t):g(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,r)=>{const o=as(s,n,r);let i=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(i,n)||(i=n,o.next?.(n))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Ms.Running)return this;if(this._processingStatus===Ms.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=Ms.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,m(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,m(this.options.input)):(function(t,e,s){const n=xt.get(t),r=Et(s);return n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion+1===r&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(n.systemState.root=e,n.systemState.sourceVersion=r,!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??{},e=!this.system._clock.now,s=Date.now();for(const n of Object.values(t)){const t=e&&void 0!==n.startedAt?Math.min(n.delay,Math.max(0,n.startedAt+n.delay-s)):n.delay;this.system.scheduleTimer(this,n.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=ht(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,r]=e;n=s,this._setSnapshot(n),Cs(r,this._actorScope),this.update(n,t)}catch(e){return void(this._recoverOrError(e,n)||this._inspectTransition(this._snapshot,t))}t.type===r&&(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)Rs(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===Ms.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Ms.NotStarted?(this._processingStatus=Ms.Stopped,this.system._unregister(this),this):(this._send({type:r}),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??Os)Rs(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,Rs(n,t)}this.observers.clear(),e&&g(t)}else this._parent||g(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===Ms.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Ms.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Ms.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");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:Ts,id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[_](){return this}getSnapshot(){return this._snapshot}}function Ks(t,e){return new Ns(t,e)}function Vs(t,e){const s=t.check(e);if(s)throw s}const zs=new WeakMap;function Ls(t,e,s){const n=function(t){let e=zs.get(t);return e||(e=new Map,zs.set(t,e)),e}(t);if(void 0!==e&&n.has(e))return;const r=s();n.set(e??Symbol(),{cleanup:"function"==typeof r?r:void 0})}function Us(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[N("xstate.logic.cleanup",()=>function(t){const e=zs.get(t);if(e){for(const{cleanup:t}of e.values())t?.();zs.delete(t)}}(n.self))]];if(s.type===u)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],i={},d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:D,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(ut(n,e,t))},raise:t=>{o.push(ut(n,n.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(o.push(N("xstate.logic.effect",(e=n.self.system)=>Ls(n.self,t,()=>s(e)),{key:t})),i[t]={status:"active"})})(t,s);const r=t;o.push(N("xstate.logic.effect",(t=n.self.system)=>Ls(n.self,void 0,()=>r(t))))}},h=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),f={...e,...h||{}};return("context"in e||void 0!==h?.context)&&(f.context=h?.context??e.context),(h?.effects||Object.keys(i).length)&&(f.effects={...e.effects,...h?.effects,...i}),ht(n,e,[f,o])},s=(s,r,o)=>{t.validator&&Vs(t.validator,{kind:"event",logic:n,event:r,eventOrigin:o.self._lastSourceRef?"actor":"external"});const i=e(s,r,o);return t.validator&&Vs(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[r,o]=s(t,m(t.input),e);Object.assign(t,r);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&Vs(t.validator,{kind:"input",logic:n,input:e});const o=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!==o&&(i.context=o),s({...i},m(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const Ws=new WeakMap;const Bs="xstate.observable.next",Fs="xstate.observable.error",Js="xstate.observable.complete";const qs="xstate.async.resolve",Hs="xstate.async.reject";class Gs extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Xs=Us({context:void 0,run:()=>{}});const Qs=new WeakMap;const Ys={};class Zs{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 r=0;r<n.length;r++){const o=n[r];s[o]=e(t[o],o,t,r)}return s}(this.config.states,(t,e)=>new Zs(t,{_parent:this,_key:e,_machine:this.machine})):Ys,"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=ss(t.tags).slice(),this.invoke=ss(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,r=(o=this.id,`${e}.${o}`);var o;const i=t.id??r,c="string"==typeof s?s:`xstate.invoke.${r}`;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,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const o=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;o.push({event:d(n,t.id),timerId:h(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var i;void 0!==s&&n&&o.push({event:(i=t.id,{type:"xstate.timeout",stateId:i}),timerId:f(t.id),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)o.push({event:l(t.id),timerId:p(t.id),resolveEvent:({children:e})=>l(t.id,e[t.id]?.sessionId),eventMatcher:(e,s)=>Xt(e,s,t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const c=[];for(const{event:e,timerId:s,resolveEvent:n,eventMatcher:r,delay:i,transitions:a,fromDelaysMap:u}of o){Yt(t,s,n??(()=>e),e=>zt(i,u?e.delays:{},{context:e.context,event:e.event,stateNode:t,input:e.input}));const{type:o,...d}=e;for(const t of is(a))c.push({...t,matches:{...t.matches,...Object.fromEntries(Object.entries(d).filter(([,t])=>void 0!==t))},event:o,delay:i,_eventMatcher:r})}return c.map(e=>({...Zt(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,tn(n,e=>Zt(t,s,e)))}if(t.config.onDone){const e="xstate.done.state";s(e,tn(t.config.onDone,s=>Zt(t,e,{...s,matches:{...s.matches,stateId:t.id}})))}if(t.config.onError){const s="xstate.error.*";e.set(s,tn(t.config.onError,e=>Zt(t,s,e)))}const n=(e,s,n)=>Zt(t,e,{matches:{actorId:n},_eventMatcher:(t,e)=>Xt(t,e,n),to:(t,e)=>(e.cancel(s),{})}),r=(e,s,n)=>{const{target:r,to:o,reenter:i,...c}=s;return Zt(t,e,{...c,reenter:i,to:(t,e)=>{if(o){let s=!1;const r=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const r=Reflect.get(t,e,n);return"function"!=typeof r?r:(...e)=>(s=!0,r.apply(t,e))}}),i=o(t,r);return(void 0!==i||s)&&e.cancel(n),i}return e.cancel(n),{target:r,reenter:i}}})};for(const e of t.invoke){const o=t=>({...t,matches:{...t.matches,actorId:e.id},_eventMatcher:(t,s)=>Xt(t,s,e.id)}),i=void 0!==e.timeout?p(e.id):void 0;if(e.onDone){const c="xstate.done.actor",a=tn(e.onDone,e=>{const s=o(e);return i?r(c,s,i):Zt(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,tn(e.onError,e=>{const s=o(e);return i?r(n,s,i):Zt(t,n,s)}))}if(e.onSnapshot){const n="xstate.snapshot.actor";s(n,tn(e.onSnapshot,e=>Zt(t,n,o(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[Zt(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=tn(this.config.always,t=>Zt(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=Qs.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Qs.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,r="object"==typeof e&&null!==e?e.to:void 0,o=(Array.isArray(s)?s:s?[s]:[]).map(e=>e.startsWith("#")?t.machine.getStateNodeById(e.slice(1)):t.states[e]);if(o.some(t=>!t))throw new Error(`Initial state not found on "#${t.id}"`);const i={source:t,target:o.length?o:void 0,input:n,to:r};return i}(this,this.config.initial))}next(t,e,s,n){const r=function(t){const e=Gt(t);return e?`${t.type}|${e}`:t.type}(e);let o=this._candidateCache?.get(r);o||(o=Qt(this,e),(this._candidateCache??=new Map).set(r,o));for(const r of o){if(Oe(r,e,t,this,s,n))return[r]}}}function tn(t,e){const s=is(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}function en(t,e){if(!t)return;if(Object.hasOwn(t,e))return t[e];const s=Object.keys(t).find(t=>ds(e,t));return void 0===s?void 0:t[s]}let sn,nn;function rn(){if(nn)return nn;const t=sn??=Ks({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 nn={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},nn}class on{constructor(t,e,s){this.config=t,this.validator=s,this._internalEventType=void 0,this.version=void 0,this.schemas=void 0,this.snapshotSchema=void 0,this.eventSchema=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.snapshotSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t)return{issues:[{message:"Expected a persisted snapshot."}]};const e={historyValue:{},timers:{},...t},s=this.schemas?.context;let n=e.context;if(s){const t=await s["~standard"].validate(n);if(t.issues)return{issues:[{message:`Invalid context for machine '${this.id}' version '${this.version}': ${t.issues[0]?.message}`}]};n=t.value}for(const t of["value","children"])if(!(t in e))return{issues:[{message:`Persisted snapshot is missing '${t}'.`}]};if(!["active","done","error","stopped"].includes(e.status))return{issues:[{message:"Persisted snapshot has invalid status."}]};for(const t of["children","historyValue","timers"])if(null===e[t]||"object"!=typeof e[t]||Array.isArray(e[t]))return{issues:[{message:`Persisted snapshot has invalid '${t}'.`}]};try{this.resolveState({value:e.value,context:n})}catch(t){return{issues:[{message:t instanceof Error?t.message:"Persisted snapshot has invalid state value."}]}}return{value:{...e,context:n}}}}},this.eventSchema={"~standard":{version:1,vendor:"xstate",validate:async t=>{if(null===t||"object"!=typeof t||"string"!=typeof t.type)return{issues:[{message:"Expected an event object."}]};const e=t,s=this.schemas?.events,n=this.schemas?.internalEvents,r=e.type.startsWith("xstate.")||e.type.startsWith("@xstate."),o=en(n,e.type)??en(s,e.type);if((s||n)&&!o&&!r)return{issues:[{message:`Unknown event '${e.type}' for machine '${this.id}' version '${this.version}'.`}]};if(!o)return{value:e};const{type:i,...c}=e,a=await o["~standard"].validate(c);return a.issues?a:null===a.value||"object"!=typeof a.value?{issues:[{message:"Expected an event payload."}]}:{value:{...a.value,type:i}}}}},this.internalEventDescriptors=[...Object.keys(this.schemas?.internalEvents??{}),...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 Zs(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 r=n.config.id,o=n.config.route,i=({event:t})=>t.to===`#${r}`;if("function"==typeof o)return e.push(Zt(t,"xstate.route",{guard:i,to:t=>{const e=o(t);if(e)return{...!0===e?{}:e,target:`#${r}`}}})),void(n.states&&s(n.states));const{guard:c,...a}=o,u={...a,guard:i,target:`#${r}`};e.push(Zt(t,"xstate.route",u))}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:r}=this.sources,o=new on(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...r,...t.delays}},this.validator);return o._json=this._json,o}resolveState(t){const e=(s=this.root,n=t.value,Jt(s,Ft(ue(s,n))));var s,n;const r=Ft(ue(this.root,e));return qe({_nodes:[...r],value:e,context:t.context||{},children:{},status:qt(r,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const n=!s,r=s??Vt(this,t);this.validator&&Vs(this.validator,{kind:"event",logic:this,event:e,eventOrigin:s&&s.self._lastSourceRef?"actor":"external"}),n&&Tt(r,t,!1),Z(r);const o=this._transitionFast(t,e,r);if(o){n&&Tt(r,o,!1);const e=n&&o!==t?Mt(r,o):this._attachPureActorRef(o,r);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:e,effects:[]}),[e,[]]}const{snapshot:i,microsteps:c}=$e(t,e,r,[]);n&&Tt(r,i,!1);const a=n?i===t?i:Mt(r,i):this._attachPureActorRef(i,r),u=this._collectEffects(c);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:a,effects:u}),[a,u]}_collectEffects(t){return t.flatMap(([,t])=>t)}_attachPureActorRef(t,e,s=!1){return Ot(e)||s&&e.self._actorScope===e&&void 0===e.self._snapshot||jt(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 r=n.transitions.get(e.type);if(1!==r?.length)return;const o=r[0];if(o.guard||o.actions||o.to||o.reenter||o.input||"function"==typeof o.context||o.target&&1!==o.target.length)return;const i=o.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!==o.context?{...t.context,...o.context}:t.context;if(!Ot(s)&&(s.system._hasInspectionObservers?.()??1)){const t=s.self._collectedMicrosteps||[];t.push(o),s.self._collectedMicrosteps=t}return He(t,{...a!==t.context?{context:a}:{},...c?{_nodes:[this.root,i]}:{}})}microstep(t,e,s){const{microsteps:n}=$e(t,e,s,[]),r=new Array(n.length);for(let t=0;t<n.length;t++)r[t]=n[t][0];return r}getTransitionData(t,e,s,n){return de(this.root,t.value,t,e,s,n)||[]}isInternalEventType(t){if(t===i)return!0;for(const e of this.internalEventDescriptors)if(ds(t,e))return!0;return!1}_canTransition(t,e){const s=rn(),n=this.getTransitionData(t,e,s);if(!n?.length)return!1;for(const r of n){if(void 0!==r.target)return!0;const n=be(r,t,e,s,{resolveActions:!1});if(n.targets?.length||n.context||Se(r,t.context,e,t,s))return!0}return!1}getExecutionErrorEvent(t,e){if("active"===t?.status&&t.nodes?.some(t=>t.config.onError))return v("execution",e)}_getPreInitialState(t,e){const{context:s}=this.config,n=qe({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const r={},o=function(t,e,s){return(n,r)=>{const o=$(e,n),i=r?.id??st(t,o??n).id;void 0!==r?.id&&(nt(t,r.id),rt(t,r.id));const c=t.system.createActorRef(n,{id:i,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:o??n,registryKey:r?.registryKey});return s[c.id]=c,c}}(t,this.sources.actors,r),i=s(function(t,e){return M(e)?(Object.defineProperty(t,"self",{enumerable:!0,get:()=>e.self}),t):Object.assign(t,{self:e.self})}({spawn:o,input:e.input,actors:this.sources.actors},t)),[c]=lt(n,e,t,[]);if(i&&(c.context=i),Object.keys(r).length>0){c.children={...c.children,...r};const e=function(t){const e=Q.get(t)?.counters;if(e?.size)return Object.fromEntries(e)}(t);e&&(c._nextActorIds=H(c._nextActorIds,e))}return c}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){this.validator&&Vs(this.validator,{kind:"input",logic:this,input:t});const s=!e,n=e??Vt(this);Z(n);const r=m(t),o=[],i=this._getPreInitialState(n,r),c=Object.values(i.children).filter(Boolean).map(t=>at(t)),a=(t,e)=>{s&&Tt(n,t,!1);const r=s?Mt(n,t):this._attachPureActorRef(t,n,!0),o=this._collectEffects(e);return this.validator&&Vs(this.validator,{kind:"result",logic:this,snapshot:r,effects:o}),[r,o]};try{const[t,e]=xe(this.root,i,n,r,o),{snapshot:s,microsteps:u}=$e(t,r,n,o,[[t,[...c,...e]]]);return a(s,u)}catch(t){if(!this.root.config.onError)throw t;const e=$e(i,v("execution",t),n,[],[[i,c]]);return a(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=Ye(t),s=e.slice(1),n=Ht(e[0])?e[0].slice(1):e[0],r=this.idMap.get(n);if(!r)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return ae(r,s)}getPersistedSnapshot(t,e){return function(t,e){const{nodes:s,_stateInputs:n,tags:r,machine:o,children:i,timers:c,context:a,can:u,hasTag:d,matches:h,getMeta:f,getInputs:l,toJSON:p,...y}=t,v={},m={},g=!1!==e?.embedChildren;for(const t in i){const s=i[t];if(!("string"==typeof s.src||e&&"__unsafeAllowInlineActors"in e))throw new Error("An inline child actor cannot be persisted.");const n=g&&!Re(s);if(!n&&"string"!=typeof s.src)throw new Error(`Unable to persist child '${t}' by address: it requires a registered source key.`);v[t]={address:s.address,...n?{snapshot:s.getPersistedSnapshot(e)}:{remote:!0,incarnation:Re(s)?s.sessionId:void 0},src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const _=At(t)?.actor,x=_?.system?._clock?.now?void 0:_?.system?._snapshot?._scheduledTimers;for(const e in c){const s=c[e];let n,r=s.event;if("xstate.timeout.actor"===r.type&&(r={...r},delete r.sessionId),"self"===s.target)n="self";else{const r=Object.entries(i).find(([,t])=>t===s.target)?.[0];if(r)n=r;else{if(s.target!==At(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"}}}const o=x?.[`${_.sessionId}.${e}`],a=o?o.dueAt-s.delay:s.startedAt;m[e]={id:s.id,delay:s.delay,type:s.type,event:r,target:n,...void 0!==a&&{startedAt:a}}}const w={...y,context:Xe(a),children:v,timers:m,historyValue:Ge(y.historyValue)};return n&&Object.keys(n).length>0&&(w.stateInputs=n),void 0!==o.version&&(w.machine={id:o.id,version:o.version},w.version=o.version),w}(t,e)}restoreSnapshot(t,e){const s=!e,n=e??Vt(this),r=t.machine,o=r&&"object"==typeof r&&"function"==typeof r.transition&&"root"in r?void 0:r,i=t.version,c="string"==typeof o?.version?o.version:i;if(void 0!==i&&void 0!==o?.version&&o.version!==i)throw new Error(`Persisted snapshot version '${i}' 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(c!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${c}' does not match machine version '${this.version}'.`);t=e(t,c)}const a=t,u={},d=a.children;for(const t of Object.keys(d)){const e=d[t];if(!0===e.remote&&void 0!==e.address){if("string"!=typeof e.src)throw new Error(`Unable to restore remote child '${t}': a child referenced by address requires a registered source key.`);const s=De(n.system,{id:t,address:e.address,src:e.src,parent:n.self,registryKey:e.registryKey,syncSnapshot:e.syncSnapshot,incarnation:e.incarnation});e.registryKey&&n.system._set(e.registryKey,s),u[t]=s;continue}const s=e.snapshot,r=e.src,o="string"==typeof r?us(this,r):r;if(!o){throw new Error(`Unable to restore child actor '${t}': child source '${"string"==typeof r?r:"<unknown>"}' is not provided in machine '${this.id}'.`)}const i=n.system.createActorRef(o,{id:t,parent:n.self,syncSnapshot:e.syncSnapshot,snapshot:s,src:r,registryKey:e.registryKey});i._rehydrated=!0,u[t]=i}const h={},f=a.timers??{};for(const[t,e]of Object.entries(f)){let s=e.event;if("xstate.timeout.actor"===s.type){const t=s.actorId,e=u[t];e&&(s=l(t,e.sessionId))}const r="string"==typeof e.target?"self"===e.target?"self":u[e.target]:n.self._parent;if(!r){const s="string"==typeof e.target?e.target:e.target.type;throw new Error(`Unable to restore timer '${t}': target actor '${s}' is unavailable.`)}h[t]={...e,event:s,target:r}}const p=(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 Zs)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(a.historyValue),y=(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 r of Object.keys(t)){const o=e.states[r];if(!o)throw n(s.concat(r));y(t[r],o,s.concat(r))}}else if(!e.states[t])throw n(s.concat(t))};y(a.value,this.root,[]);const v=Array.from(Ft(ue(this.root,a.value))),{version:m,_nextActorId:g,..._}=t;let x=_._nextActorIds;for(const t of Object.keys(d)){const e=$s(t);e&&(x?.[e.prefix]??0)<=e.index&&(x={...x,[e.prefix]:e.index+1})}const w=qe({..._,children:u,timers:h,_nextActorIds:x,_nodes:v,value:a.value,historyValue:p,_stateInputs:a.stateInputs??{}},this,n.self),b=new WeakSet;return function t(e){if(!b.has(e)){b.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===Ts){e[s]=u[n.id];continue}t(n)}}}}(w.context),s?(Tt(n,w,!1),Mt(n,w)):this._attachPureActorRef(w,n)}}function cn(t){return new on(t)}const an=new WeakMap;function un(t,e){an.set(t,{ids:new Set(Object.keys(e.children)),counters:{...e._nextActorIds}})}function dn(t=this.source?.system??this.actor?.system){switch(this.type){case"@xstate.spawn":return t.spawnActor(this.source,this.actor);case"@xstate.start":return t.startActor(this.actor);case"@xstate.stop":return t.stopActor(this.actor);case"@xstate.terminate":return t.terminateActor(this.actor,this);case"@xstate.raise":case"@xstate.sendTo":{if(void 0===this.delay)return t.sendEvent(this.source,this.target,this.event);const e=this.source.getSnapshot().timers[this.id];return e&&!t._clock.now&&(e.startedAt=Date.now()),t.scheduleTimer(this.source,this.id,this.delay)}case"@xstate.cancel":return t.cancelTimer(this.source,this.id);case"@xstate.emit":return t.emitEvent(this.source,this.event);default:return this.action?.(...this.args)}}function hn(t,e={}){return{kind:"builtin",type:t,params:void 0,args:[],exec:dn,...e}}function fn(t,e,s){const n=(t,...s)=>{e.push(hn(t.name||"(anonymous)",{kind:"action",action:t,args:s}))};n.cancel=s=>{e.push(hn("@xstate.cancel",{source:t.self,id:s}))},n.emit=s=>{e.push(hn("@xstate.emit",{kind:"emit",type:"@xstate.emit",source:t.self,event:s}))},n.log=(...e)=>{n(t.logger,...e)},n.raise=(n,r)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0===r?.delay?s.push(n):e.push(hn("@xstate.raise",{source:t.self,event:n,id:r.id,delay:r.delay}))},n.sendTo=(n,r,o)=>{n?e.push(hn("@xstate.sendTo",{source:t.self,target:n,event:r,id:o?.id,delay:o?.delay})):s.push({type:"xstate.error.communication",error:{message:"Unable to send event to an undefined actor",event:r}})};n.spawn=(s,n={})=>{if("string"==typeof s)throw new Error(`Actor source "${s}" not found`);const r=an.get(t);let o,i,c=n.id;if(void 0===c){o=s.id??"x","(machine)"===o&&(o="x"),i=r.counters[o]??0;do{c=`${o}:${i++}`}while(r.ids.has(c));r.counters[o]=i}if(r.ids.has(c))throw new Error(`Actor with id "${c}" already exists`);r.ids.add(c);const a=t.system.createActorRef(s,{...n,id:c,parent:t.self});return e.push(hn("@xstate.spawn",{source:t.self,actor:a,id:c,logic:s,src:s,input:n.input,childUpdate:{type:"add",actor:a,id:c,prefix:o,next:i}})),a},n.stop=s=>{s&&(an.get(t)?.ids.delete(s.id),e.push(hn("@xstate.stop",{source:t.self,actor:s,id:s.id,childUpdate:{type:"remove",actor:s}})))};const r=(s,n)=>{const r=t.system.createActorRef(s,{input:n,parent:t.self});return e.push(hn("@xstate.spawn",{source:t.self,actor:r,id:r.id,logic:s,src:s,input:n})),r};return n.listen=(t,e,s)=>r(k,{actor:t,eventType:e,mapper:s}),n.subscribeTo=(t,e)=>r(T,{actor:t,mappers:"function"==typeof e?{snapshot:e}:e}),n}function ln(t,e,s){let n=t;for(const t of e){const e=t.childUpdate;if("add"===e?.type)n={...n,children:{...n.children,[e.id]:e.actor},...e.prefix&&{_nextActorIds:{...n._nextActorIds,[e.prefix]:Math.max(n._nextActorIds?.[e.prefix]??0,e.next)}}};else if("remove"===e?.type){const t={...n.children};let r=e.actor._parent===s.self;for(const s of Object.keys(t))t[s]===e.actor&&(r=!0,delete t[s]);if(!r)throw new Error(`Cannot stop non-child actor ${e.actor.id}`);n={...n,children:t}}if("@xstate.cancel"===t.type){if(n.timers[t.id]){const e={...n.timers};delete e[t.id],n={...n,timers:e}}}else if(("@xstate.raise"===t.type||"@xstate.sendTo"===t.type)&&void 0!==t.delay){const e=t,r=void 0===e.id,o=e.id??`xstate.timer.auto.${n._nextTimerId}`;e.id=o,n={...n,timers:{...n.timers,[o]:{id:o,delay:e.delay,type:e.type,event:e.event,target:"@xstate.raise"===e.type||e.target===s.self?"self":e.target}},_nextTimerId:r?n._nextTimerId+1:n._nextTimerId}}}return[n,e]}function pn(t){const e=[],s=[],n=[];for(const r of t){if("@xstate.stop"===r.type)for(const t of[s,n]){const s=t.findIndex(t=>t.actor===r.actor);-1!==s&&e.push(t.splice(s,1)[0])}if(e.push(r),"@xstate.spawn"!==r.type)continue;const t=hn("@xstate.start",{actor:r.actor,id:r.id,source:r.source});(r.logic===k||r.logic===T?s:n).push(t)}return e.concat(s,n)}function yn(t,e,s){return hn("@xstate.sendTo",{source:t.self,target:e,event:s})}function vn(t,e,s){const[n,r]=s;return"done"!==n.status&&"error"!==n.status||"done"===e?.status||"error"===e?.status||r.push(hn("@xstate.terminate",{source:t.self,actor:t.self,id:t.self.id,status:n.status,output:n.output,error:n.error})),[n,r]}const mn={actions:{},actors:{},guards:{},delays:{}},gn=[],_n=[];function xn(t,e){if(Object.keys(t).length)throw new Error("FSM child persistence requires registered sources.");for(const t in e)if("self"!==e[t].target)throw new Error(`FSM timer '${t}' must target self to be persisted.`)}function wn(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function bn(t,e){return"function"==typeof t?t(e):t}function $n(t,e,s){return"function"==typeof t?t({context:e,event:s}):t}function Sn(t,e){for(const s of Object.keys(e))if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(t[s],e[s]))return{...t,...e};return t}function En(t,e,s,n){return{status:t.status,output:t.output,error:t.error,value:e,context:s,input:t.input,children:t.children,timers:t.timers,_nextTimerId:t._nextTimerId,_nextActorIds:t._nextActorIds,_stateInput:n,machine:t.machine}}function In(t){return{status:"stopped",output:void 0,error:void 0,value:t.value,context:t.context,input:void 0,children:t.children,timers:t.timers,_nextTimerId:t._nextTimerId,_nextActorIds:t._nextActorIds,_stateInput:t._stateInput,machine:t.machine}}function An(t,e){const s=[],n=fn(e,s,[]);for(const e of Object.values(t.children))n.stop(e);for(const e of Object.keys(t.timers))n.cancel(e);return ln(t,s,e)}function kn(t,e,s,n,r,o){const i={...t,status:"done",output:void 0,error:void 0},[c,a]=o(i,e,s,r[i.value]?.exit,i._stateInput,n),[u,d]=An(c,s);return[u,[...a,...d]]}function jn(t,e){throw new Error(`Invalid transition for "${t}": use { target: "${e}" } instead of a string target.`)}function Tn(t){const e=_t(t);return void 0!==e?e:"string"==typeof t?parseFloat(t)||0:t}function On(t){return!!t&&"object"==typeof t&&"string"==typeof t["@expr"]}function Mn(t){return On(t)||function(t){return!!t&&"object"==typeof t&&"string"==typeof t["@code"]}(t)}function Pn(t,e){return"number"==typeof e?`${t}[${e}]`:`${t}.${e}`}function Rn(t){const e={};if(!t)return e;for(const s of Object.keys(t)){const n=t[s];"number"==typeof n?e[s]=n:n&&"object"==typeof n&&"number"==typeof n.duration&&(e[s]=n.duration)}return e}function Cn(t){return void 0===t?[]:Array.isArray(t)?t:[t]}function Dn(t,e){Array.isArray(t)&&t.forEach((s,n)=>{if(void 0===s.when&&n!==t.length-1)throw new Error(`Choice fallback branch at ${e}[${n}] must be last.`)})}function Nn(t){return!Mn(t)&&t.type.startsWith("@xstate.")}function Kn(t){if("function"==typeof t)return{"@code":t.toString(),"@lang":"ts"};if(null===t||"object"!=typeof t)return"bigint"==typeof t||"symbol"==typeof t?void 0:t;if(function(t){return!!t&&"object"==typeof t&&"function"==typeof t.transition&&"function"==typeof t.getInitialSnapshot}(t))return;if(function(t){return!!t&&"object"==typeof t&&"~standard"in t}(t))return;if(Array.isArray(t))return t.map(Kn).filter(t=>void 0!==t);if(t.constructor!==Object&&void 0!==t.constructor)return;const e={};for(const s of Object.keys(t)){const n=t[s];if(void 0!==n){const t=Kn(n);void 0!==t&&(e[s]=t)}}return e}function Vn(t){if(Array.isArray(t)){const e=t.map(Vn).filter(t=>void 0!==t);return e.length?e:void 0}const e=t,s={};for(const t of Object.keys(e)){const n=e[t];void 0!==n&&(s[t]="src"===t&&"string"!=typeof n?n.id:Kn(n),void 0===s[t]&&delete s[t])}return void 0===s.src?void 0:s}function zn(t){if(!t)return;const e={};for(const s of Object.keys(t)){const n=t[s];e[s]="function"==typeof n?void 0:Kn(n),void 0===e[s]&&delete e[s]}return e}function Ln(t){const e={};for(const s of Object.keys(t)){if("states"===s||"invoke"===s)continue;const n=t[s];void 0!==n&&(e[s]=Kn(n))}if(void 0!==t.invoke){const s=Vn(t.invoke);void 0!==s&&(e.invoke=s)}if(t.states){const s={};for(const e of Object.keys(t.states))s[e]=Ln(t.states[e]);e.states=s}return e}function Un(t){const e=Ln(t);if(void 0!==t.internalEvents&&(e.internalEvents=Kn(t.internalEvents)),t.schemas){const s={};for(const e of Object.keys(t.schemas)){const n=t.schemas[e];s[e]=n&&"object"==typeof n&&!("~standard"in n)?zn(n):Kn(n),void 0===s[e]&&delete s[e]}e.schemas=s}for(const s of["actions","guards","actors","delays"])if(t[s]){const n=zn(t[s]);n&&Object.keys(n).length?e[s]=n:delete e[s]}return e}function Wn(t){return null!==t&&"object"==typeof t}function Bn(t){return"transition"in t&&"function"==typeof t.transition}async function Fn(t,e,s){if(!t)return e;const n=await t["~standard"].validate(e);if(n.issues)throw new Error(`Invalid ${s}: ${n.issues[0]?.message}`);return n.value}async function Jn(t,e){return await Fn(e.snapshotSchema,{...t,machine:{id:e.id,version:e.version},version:e.version},`snapshot for machine '${e.id}' version '${e.version}'`)}async function qn(t,e){return Promise.all(t.map(async(t,s)=>{const n=await e.eventSchema["~standard"].validate(t);if(n.issues){const e=n.issues[0]?.message;if(e?.startsWith("Unknown event "))throw new Error(e);const r=Wn(t)?t.type:void 0;throw new Error("string"==typeof r?`Invalid event '${r}' at index ${s}${e?`: ${e}`:"."}`:`Invalid event at index ${s}${e?`: ${e}`:"."}`)}const r=n.value;if(!Wn(r)||"string"!=typeof r.type)throw new Error(`Invalid event at index ${s}.`);return r}))}const Hn=function(t={}){const{validator:e,states:s={},schemas:n,actions:r,actors:o,guards:i,delays:c}=t;return{extend:e=>Hn(function(t,e){return{...t,...e,schemas:Xn(t.schemas,e.schemas),states:Gn(t.states,e.states),actions:Gn(t.actions,e.actions),actors:Gn(t.actors,e.actors),guards:Gn(t.guards,e.guards),delays:Gn(t.delays,e.delays)}}(t,e)),createMachine(t){const a=Xn(t.schemas,n),u=Qn(t.states,s),d=Gn(r,t.actions),h=Gn(o,t.actors),f=Gn(i,t.guards),l=Gn(c,t.delays);return new on({...t,...a?{schemas:a}:void 0,...u?{states:u}:void 0,...d?{actions:d}:void 0,...h?{actors:h}:void 0,...f?{guards:f}:void 0,...l?{delays:l}:void 0},void 0,e)},createStateConfig:(...t)=>t.length>1?t[1]:t[0],states:s,schemas:n??{}}};function Gn(t,e){return t||e?{...t,...e}:void 0}function Xn(t,e){if(t||e)return{...t,...e,events:Gn(t?.events,e?.events),internalEvents:Gn(t?.internalEvents,e?.internalEvents),actions:Gn(t?.actions,e?.actions),guards:Gn(t?.guards,e?.guards),emitted:Gn(t?.emitted,e?.emitted),children:Gn(t?.children,e?.children)}}function Qn(t,e){return t&&e?Object.fromEntries(Object.entries(t).map(([t,s])=>{const n=e[t];if(!n)return[t,s];const r=Gn(s.schemas,n.schemas),o=Qn(s.states,n.states);return[t,{...s,...r?{schemas:r}:void 0,...o?{states:o}:void 0}]})):t}let Yn=function(t){return t.Internal="#_internal",t}({});function Zn(t,e,s){if(!t.length)return t;const n=t.slice(),r=n.at(-1)[0];Tt(e,r,!1),r!==s&&Mt(e,r);for(const[t]of n)if(t!==s&&t!==r){Mt(Vt(t.machine,t,void 0,e),t)}return n}function tr(t,e,s){}const er={timeout:1/0};t.Actor=Ns,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort(([t,e],[s,n])=>{const r=e.start+e.timeout;return n.start+n.timeout>r?-1:1});for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1,this._flushingInvalidated&&(this._flushingInvalidated=!1,this.flushTimeouts())}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=Yn,t.StateMachine=on,t.StateNode=Zs,t.TimeoutError=Gs,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t.nodes.flatMap(t=>t.ownEvents)])]},t.assertEvent=function(t,e){const s=ss(e);if(!s.some(e=>ds(t.type,e))){const e=1===s.length?`type matching "${s[0]}"`:`one of types matching "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.checkStateIn=function(t,e){if("string"==typeof e&&Ht(e)){const s=t.machine.getStateNodeById(e);return t.nodes.some(t=>t===s)}return t.matches(e)},t.createActor=Ks,t.createAsyncLogic=function(t){const e=t;return Us({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:n,self:r,system:o},i)=>{switch(t.type){case qs:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Hs:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return i.effect((t=o)=>{const s=r,i=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,u=_t(a),d=void 0===u?void 0:o._clock.setTimeout(()=>{"active"===r.getSnapshot().status&&(c.abort(),i({type:Hs,data:new Gs(a)}))},u),h=()=>{void 0!==d&&o._clock.clearTimeout(d)},f=()=>Promise.resolve(e.run({input:n,system:o,self:r,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,n)=>t.runStep?Promise.resolve(t.runStep(s,e,n)):hs(s,e,n,i)}));return(t.runLogic?Promise.resolve(t.runLogic(s,f)):f()).then(t=>{h(),"active"===r.getSnapshot().status&&i({type:qs,data:t})},t=>{h(),"active"===r.getSnapshot().status&&i({type:Hs,data:t})}),()=>{c.abort(),h()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return Us({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:n,input:r,self:o,system:i}=t,c=t.emit,a=Ws.get(o);a?.receivers?.forEach(t=>t(n)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return Ws.set(o,t),t.dispose=e({input:r,system:i,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&i._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{Ws.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return Ks(Xs)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,n={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case Fs:return ht(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case Js:return ht(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&Vs(s,{kind:"input",logic:n,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],start:(t,{self:s,system:n,emit:r})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:n,self:s,emit:t=>{r(t)}}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:Fs,data:t})},complete:()=>{n._relay(s,s,{type:Js})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return n},t.createFSM=function(t){const e={id:t.id??"(fsm)",sources:mn};!function(t){for(const[e,s]of Object.entries(t.states)){for(const[t,n]of Object.entries(s.on??{}))for(const s of wn(n))"string"==typeof s&&jn(`${e}.${t}`,s);if(s.always)for(const t of wn(s.always))"string"==typeof t&&jn(`${e}.always`,t)}}(t);const n=(t,e,s,n,r)=>{if(!n)return[t,gn];const o=[],i=fn(s,o,r);let c=t.context;for(const r of wn(n)){const n=r(R({context:c,event:e,input:t._stateInput,value:t.value,children:t.children},s),i);n?.context&&(c=Sn(c,n.context))}return ln(c===t.context?t:En(t,t.value,c,t._stateInput),o,s)},o=(t,e,s,n,r,o)=>{if(!n)return[t,gn];const i=[],c=fn(s,i,o);let a;const u=Array.isArray(n)?n.length:1;for(let o=0;o<u;o++){const i=(Array.isArray(n)?n[o]:n)(R({context:a??t.context,event:e,input:r,value:t.value,children:t.children},s),c);if(void 0!==i?.context){const e=a??t.context,s=Sn(e,i.context);s!==e&&(a=s)}}return ln(void 0!==a?En(t,t.value,a,t._stateInput):t,i,s)},c=(e,s,n,r)=>{const o=t.states[e.value],i=""===s.type?o?.always:o?.on?.[s.type];if(!i)return;const c=Array.isArray(i)?i.length:1;for(let t=0;t<c;t++){const o=Array.isArray(i)?i[t]:i,c=R({context:e.context,event:s,input:e.input,value:e.value,children:e.children},n);if("function"==typeof o){const t=[],e=o(c,fn(n,t,r));if(!e){if(t.length)return{effects:t};continue}return{target:e.target,context:e.context,input:e.input,effects:t}}if(!("guard"in o)||!o.guard||o.guard(c))return{target:o.target,context:bn(o.context,c),input:o.input,actions:"actions"in o&&o.actions?wn(o.actions):_n}}},a=(e,s,u)=>{if("active"!==e.status)return[e,[]];if(s.type===r){const[t,s]=An(e,u);return[In(t),s]}if(s.type===i){const t=e.timers[s.id];if(!t)return[e,gn];const n={...e.timers};delete n[t.id];const r={...e,timers:n};if("@xstate.raise"===t.type)return a(r,t.event,u);return[r,[yn(u,"self"===t.target?u.self:t.target,t.event)]]}const d=t.states[e.value],h=""===s.type?d?.always:d?.on?.[s.type];if(!h)return[e,gn];if(!(Array.isArray(h)||"function"==typeof h||"guard"in h||"actions"in h&&h.actions||"function"==typeof h.input)){const n=h.target??e.value,r=t.states[n],o=n!==e.value;if(!(r?.always||o&&(d.exit||r?.entry||"final"===r?.type))){const t=void 0!==h.context,r=void 0!==h.input,i=M(u)?"function"==typeof h.context?h.context(R({context:e.context,event:s,input:e.input,value:e.value,children:e.children},u)):h.context:bn(h.context,{context:e.context,event:s,input:e.input,value:e.value,self:u.self,system:u.system,parent:u.self._parent,children:e.children}),c=t&&i?Sn(e.context,i):e.context;return o||c!==e.context||r||void 0!==e._stateInput?[En(e,n,c,r?$n(h.input,c,s):void 0),gn]:[e,gn]}}let f;if("function"==typeof h&&h.length<2&&!d?.exit){const n=h(R({context:e.context,event:s,input:e.input,value:e.value,children:e.children},u),void 0);if(!n)return[e,gn];const r=n.target??e.value,o=t.states[r];if(!o?.entry&&!o?.always&&"final"!==o?.type){const t=void 0!==n.context,o=void 0!==n.input,i=t&&n.context?Sn(e.context,n.context):e.context;return r!==e.value||i!==e.context||o||void 0!==e._stateInput?[En(e,r,i,o?$n(n.input,i,s):void 0),gn]:[e,gn]}f={target:n.target,context:n.context,input:n.input,actions:_n}}let l=e;const p=[],y=[s];let v=0;for(;y.length;){if(++v>1e3)throw new Error("FSM microstep count exceeded 1000");const e=y.shift(),s=f??c(l,e,u,y);if(f=void 0,!s)continue;const r=s.target??l.value,i=t.states[r],a=r!==l.value;if(a){const[s,n]=o(l,e,u,t.states[l.value]?.exit,l._stateInput,y);l=s,p.push(...n)}let d=l.context;void 0!==s.context&&(d=Sn(d,s.context));const h=void 0!==s.input,m=h?$n(s.input,d,e):void 0;(a||d!==l.context||h||void 0!==l._stateInput)&&(l=En(l,r,d,m));const g=s.effects?ln(l,s.effects,u):n(l,e,u,s.actions,y),[_,x]=g;if(l=_,p.push(...x),a){const[t,s]=o(l,e,u,i?.entry,m,y);l=t,p.push(...s)}if("final"===i?.type){const[s,n]=kn(l,e,u,y,t.states,o);l=s,p.push(...n);break}i?.always&&y.unshift({type:""})}return[l,p]},u={id:t.id,config:t,transition:(...t)=>{un(t[2],t[0]);const[e,s]=a(...t);return vn(t[2],t[0],[e,pn(s)])},initialTransition:(n,r)=>{const i=t.states[t.initial],c=function(t,e){return"function"==typeof t?t({input:e}):t??{}}(t.context,n),u=function(t,e,s,n,r){return{status:"active",output:void 0,error:void 0,value:t,context:e,input:s,children:{},timers:{},_nextTimerId:0,_stateInput:r,machine:n}}(t.initial,c,n,e);un(r,u);const d=[];let[h,f]=o(u,{type:s},r,i?.entry,void 0,d);if(f.length||(f=[]),"final"===i?.type){const[e,n]=kn(h,{type:s},r,d,t.states,o);h=e,f.push(...n)}else for(i?.always&&d.unshift({type:""});d.length;){const[t,e]=a(h,d.shift(),r);h=t,f.push(...e)}return vn(r,void 0,[h,pn(f)])},getInitialSnapshot:(t,e)=>u.initialTransition(e,t)[0],getPersistedSnapshot:t=>{const{machine:e,children:s,...n}=t;return xn(s,n.timers),{...n,children:{}}},restoreSnapshot:t=>{const s=t,n=s.children??{},r=s.timers??{};xn(n,r);return{...s,children:{},timers:r,machine:e}}};return u},t.createListenerLogic=A,t.createLogic=Us,t.createMachine=cn,t.createMachineFromConfig=function(t,e={}){const s=function(t,e){return{actions:e.actions??{},guards:e.guards??{},actors:e.actors??{},delays:{...Rn(t.delays),...e.delays??{}},evaluators:e.evaluators??{}}}(t,e),n=function(t,e){function s(s,n){const r=s["@lang"]??t;if(!r)throw new Error(`Missing @exprLang for expression at ${n}`);const o=e.evaluators[r];if(!o)throw new Error(`Missing evaluator for @lang '${r}' at ${n}`);return o}function n(t,e,n,r){const o=On(t)?"expr":"code",i=On(t)?t["@expr"]:t["@code"];return s(t,r)({source:i,kind:o,slot:e,scope:n,path:r})}function r(t,e,s,o){if(Mn(t))return n(t,e,s,o);if(Array.isArray(t))return t.map((t,n)=>r(t,e,s,Pn(o,n)));if(!t||"object"!=typeof t)return t;const i={};for(const n of Object.keys(t))i[n]=r(t[n],e,s,Pn(o,n));return i}function o(t,e){return{context:t.context,event:t.event,input:t.input,self:t.self,children:t.children,params:t.params,...e}}return{evaluateResolvable:n,resolveValue:r,makeScope:o,getDurationConfig:function(t,e){return Mn(t)?s=>Tn(r(t,"delay",o(s),e)):t},assertResolvable:function t(e,n){if(Mn(e))s(e,n);else if(Array.isArray(e))e.forEach((e,s)=>t(e,Pn(n,s)));else if(e&&"object"==typeof e)for(const s of Object.keys(e))t(e[s],Pn(n,s))}}}(t["@exprLang"],s),{evaluateResolvable:r,resolveValue:o,makeScope:i,getDurationConfig:c}=n;function a(e,s,n){if(e)return Mn(e)?t=>!!r(e,s,i(t),n):r=>{const c=o(e.params,s,i(r),`${n}.params`),u=t.guards?.[e.type];if(u){const t=a(u.when,"guard",`$.guards.${e.type}.when`);return!!t?.({...r,params:c})}const d=r.guards?.[e.type];if(!d)throw new Error((h=e.type,f=r.guards??{},`Guard '${h}' is not implemented in machine '${t.id??"(machine)"}'. Available guards: ${Object.keys(f).map(t=>`'${t}'`).join(", ")||"(none)"}.`));var h,f;return d(r,c)}}function u(t,e){if(t)return Mn(t)?s=>r(t,"choice",i(s),e):(Dn(t,e),s=>{for(let n=0;n<t.length;n++){const r=t[n],c=a(r.when,"choice",`${e}[${n}].when`);if(!c||c(s))return{target:r.target,context:r.context?o(r.context,"transitionContext",i(s),`${e}[${n}].context`):void 0,input:void 0!==r.input?o(r.input,"input",i(s),`${e}[${n}].input`):void 0,description:r.description,reenter:r.reenter,meta:r.meta}}throw new Error(`Choice state at ${e} did not match any branch.`)})}function d(t,e){if(!t||"function"==typeof t)return t;if(Mn(t))return s=>r(t,"transition",i(s),e);const{guard:s,...n}=t;if(!s)return n;const o=a({type:s},"guard",e);return t=>o(t)?n:void 0}function h(e,s,n,c=[]){let a;for(const u of e){if(Mn(u)){const t=r(u,"action",i(s,{params:s.params,enq:n}),"$.actions");t&&"object"==typeof t&&"context"in t&&t.context&&(a??={},Object.assign(a,t.context));continue}if(Nn(u)){switch(u.type){case"@xstate.raise":n.raise(o(u.event,"actionParams",i(s,{params:s.params}),"$.actions.event"),{id:u.id,delay:u.delay});break;case"@xstate.cancel":n.cancel(u.id);break;case"@xstate.log":n.log(...u.args);break;case"@xstate.emit":n.emit(o(u.event,"actionParams",i(s,{params:s.params}),"$.actions.event"));break;case"@xstate.assign":a??={},Object.assign(a,o(u.context,"transitionContext",i(s,{params:s.params}),"$.actions.context"))}continue}const e=o(u.params,"actionParams",i(s,{params:s.params}),"$.actions.params"),d=t.actions?.[u.type];if(!d){n(s.actions[u.type],e);continue}if(c.includes(u.type))throw new Error(`Circular action reference: ${c.concat(u.type).join(" -> ")}`);const f=h(Array.isArray(d)?d:[d],{...s,context:{...s.context,...a},params:e},n,c.concat(u.type));f.context&&(a=f.context)}return{context:a?{...s.context,...a}:void 0}}function f(t){const e=Cn(t);return(t,s)=>h(e,t,s)}function l(t){const e=Array.isArray(t)?t:[t];return e.map((t,s)=>{if(Mn(t))return(n,o)=>r(t,"transition",i(n,{enq:o}),"$.transition"+(e.length>1?`[${s}]`:""));const n=t.context?e=>o(t.context,"transitionContext",i(e),"$.transition.context"):void 0,c=void 0!==t.input?e=>o(t.input,"input",i(e),"$.transition.input"):void 0,u=!!n||!!t.actions?.length;return{matches:t.matches,target:u?void 0:t.target,to:u?(e,s)=>{const r=n?.(e),o=t.actions?.length?h(t.actions,r?{...e,context:{...e.context,...r}}:e,s):void 0;return{target:t.target,context:o?.context??r,reenter:t.reenter}}:void 0,guard:a(t.guard,"guard","$.transition.guard"),description:t.description,reenter:t.reenter,meta:t.meta,input:c}})}if(t.delays)for(const[e,n]of Object.entries(t.delays))"number"==typeof n?s.delays[e]=n:"string"==typeof n?s.delays[e]=Tn(n):n&&"object"==typeof n&&(s.delays[e]=t=>Tn(o(n.duration,"delay",i(t),`$.delays.${e}.duration`)));!function(t,e,s){const{assertResolvable:n}=s;function r(s,o){if(s)if(Mn(s))n(s,o);else if(n(s.params,`${o}.params`),t.guards?.[s.type])r(t.guards[s.type].when,`$.guards.${s.type}.when`);else if(!e.guards[s.type]&&!["xstate.stateIn","xstate.not"].includes(s.type))throw new Error(`Missing guard source "${s.type}"`)}function o(s,r,i=[]){if(Mn(s))return void n(s,r);if(!s||"string"!=typeof s.type)throw new Error(`Invalid action at ${r}`);if(n(s.params,`${r}.params`),s.type.startsWith("@xstate."))return void n(s,r);const c=t.actions?.[s.type];if(c){if(i.includes(s.type))throw new Error(`Circular action reference: ${i.concat(s.type).join(" -> ")}`);const t=Array.isArray(c)?c:[c];return void t.forEach((e,n)=>o(e,`${r}.actions.${s.type}${t.length>1?`[${n}]`:""}`,i.concat(s.type)))}if(!e.actions[s.type])throw new Error(`Missing action source "${s.type}"`)}function i(t,e){Cn(t).forEach((t,s)=>o(t,`${e}[${s}]`))}function c(t,e){(Array.isArray(t)?t:t?[t]:[]).forEach((s,o)=>{const c=Array.isArray(t)?`${e}[${o}]`:e;Mn(s)?n(s,c):(r(s.guard,`${c}.guard`),i(s.actions,`${c}.actions`),n(s.context,`${c}.context`),n(s.input,`${c}.input`))})}if(t.actions)for(const e of Object.keys(t.actions)){const s=Array.isArray(t.actions[e])?t.actions[e]:[t.actions[e]];s.forEach((t,n)=>o(t,`$.actions.${e}${s.length>1?`[${n}]`:""}`,[e]))}if(t.guards)for(const e of Object.keys(t.guards))r(t.guards[e].when,`$.guards.${e}.when`);if(t.delays)for(const e of Object.keys(t.delays)){const s=t.delays[e];n(s&&"object"==typeof s&&"duration"in s?s.duration:s,`$.delays.${e}`)}!function s(o,a){if(("history"===o.type||void 0!==o.history)&&!("string"==typeof o.target&&o.target.trim().length>0||Array.isArray(o.target)&&o.target.length>0&&o.target.every(t=>t.trim().length>0)))throw new Error(`History state at ${a} must declare a non-empty target.`);if(n(o.context,`${a}.context`),n(o.input,`${a}.input`),n(o.output,`${a}.output`),n(o.timeout,`${a}.timeout`),i(o.entry,`${a}.entry`),i(o.exit,`${a}.exit`),"choice"===o.type){if(!o.choice)throw new Error(`Choice state at ${a} must declare choice.`);Array.isArray(o.choice)?(Dn(o.choice,`${a}.choice`),o.choice.forEach((t,e)=>{r(t.when,`${a}.choice[${e}].when`),n(t.context,`${a}.choice[${e}].context`),n(t.input,`${a}.choice[${e}].input`)})):n(o.choice,`${a}.choice`)}if(Mn(o.route)&&n(o.route,`${a}.route`),o.invoke&&(Array.isArray(o.invoke)?o.invoke:[o.invoke]).forEach((t,s)=>{const r=`${a}.invoke${Array.isArray(o.invoke)?`[${s}]`:""}`;if(!e.actors[t.src])throw new Error(`Missing actor source "${t.src}"`);n(t.input,`${r}.input`),n(t.timeout,`${r}.timeout`),c(t.onDone,`${r}.onDone`),c(t.onError,`${r}.onError`),c(t.onSnapshot,`${r}.onSnapshot`),c(t.onTimeout,`${r}.onTimeout`)}),o.on)for(const t of Object.keys(o.on))c(o.on[t],`${a}.on.${t}`);if(o.after)for(const s of Object.keys(o.after)){if(Number.isNaN(Number(s))&&void 0===_t(s)&&!t.delays?.[s]&&!e.delays[s])throw new Error(`Missing delay source "${s}"`);c(o.after[s],`${a}.after.${s}`)}if(c(o.always,`${a}.always`),c(o.onError,`${a}.onError`),c(o.onTimeout,`${a}.onTimeout`),o.states)for(const t of Object.keys(o.states))s(o.states[t],`${a}.states.${t}`)}(t,"$")}(t,s,n);const p=t.context?{context:e=>o(t.context,"context",e,"$.context")}:{},y=cn({...function t(e,n){return{id:e.id,initial:e.initial,type:e.type,history:e.history,target:e.target,description:e.description,tags:e.tags,input:e.input,timeout:c(e.timeout,`$.states.${n}.timeout`),states:e.states?Object.fromEntries(Object.entries(e.states).map(([e,s])=>[e,t(s,e)])):void 0,on:e.on?Object.fromEntries(Object.entries(e.on).map(([t,e])=>[t,l(e)])):void 0,always:e.always?l(e.always):void 0,onError:e.onError?l(e.onError):void 0,choice:u(e.choice,`$.states.${n}.choice`),route:d(e.route,`$.states.${n}.route`),after:e.after?Object.fromEntries(Object.entries(e.after).map(([t,e])=>[t,l(e)])):void 0,onTimeout:e.onTimeout?l(e.onTimeout):void 0,entry:e.entry?f(e.entry):void 0,exit:e.exit?f(e.exit):void 0,invoke:e.invoke?(a=e.invoke,(Array.isArray(a)?a:[a]).map(t=>({src:s.actors[t.src]??t.src,id:t.id,registryKey:t.registryKey,input:void 0!==t.input?e=>o(t.input,"input",i(e),"$.invoke.input"):void 0,onDone:t.onDone?l(t.onDone):void 0,onError:t.onError?l(t.onError):void 0,onSnapshot:t.onSnapshot?l(t.onSnapshot):void 0,timeout:c(t.timeout,"$.invoke.timeout"),onTimeout:t.onTimeout?l(t.onTimeout):void 0}))):void 0,meta:e.meta,output:Mn(e.output)?({context:t,event:s,self:o})=>r(e.output,"output",{context:t,event:s,self:o},`$.states.${n}.output`):e.output};var a}(t),...p,version:t.version}).provide({actions:s.actions,actors:s.actors,guards:{"xstate.stateIn":(t,e)=>{const s=e?.stateId,n=t._snapshot;return!!s&&!!n?.nodes?.some(t=>t.id===s.replace(/^#/,""))},"xstate.not":(t,e)=>{const s=e?.guard,n=s&&t.guards?.[s.type];if(!n)throw new Error(`Guard '${s?.type}' referenced by 'xstate.not' is not implemented.`);return!n(t,s.params)},...s.guards},delays:s.delays});return y._json=t,y},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,n="function"==typeof t?void 0:t.schemas;return Us({validator:"function"==typeof t?void 0:t.validator,schemas:n,context:void 0,run:(t,n)=>{const{event:r,input:o,self:i,system:c}=t;switch(r.type){case Bs:return{context:r.data};case Fs:return{status:"error",error:r.data,input:void 0,effects:{observable:{status:"error",error:r.data}}};case Js:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}r.type===s&&n.effect((t=c)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},r=e({input:o,system:c,self:i,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{n({type:Bs,data:t})},error:t=>{n({type:Fs,data:t})},complete:()=>{n({type:Js})}});return()=>r.unsubscribe()})}})},t.createStateConfig=function(t){return t},t.createSubscriptionLogic=j,t.createSystem=function(t={}){const e={},s=[];return{createActor(t,n){const r=Ks(t,{...n,_systemRef:e});return(()=>{const t=e.current;if(t)for(const e of s)e.active&&!e.subscription&&(e.subscription=t.inspect(e.observer))})(),r},get:t=>e.current?.get(t),getAll:()=>e.current?.getAll()??{},inspect(t){const n=e.current;if(n)return n.inspect(t);const r={observer:t,active:!0};return s.push(r),{unsubscribe(){r.active=!1,r.subscription?.unsubscribe()}}},setup:Hn}},t.deliverEvent=fs,t.executeEffects=async function(t,e){for(const s of t)await s.exec(e)},t.getEffectDescriptor=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:t.source.address,event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source?.address,actor:t.actor.address,id:t.id,src:ws(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source?.address,actor:t.actor.address,id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:t.source.address,event:t.event,id:t.id,delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:t.source.address,target:t.target.address,incarnation:Re(t.target)?t.target.sessionId:void 0,event:t.event,id:t.id,delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:t.source.address,id:t.id};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:t.source.address,actor:t.actor.address,id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:t.source.address,actor:t.actor.address,id:t.id,status:t.status,output:t.output,error:t.error}}},t.getInitialMicrosteps=function(t,...[e]){const s=Vt(t);Z(s);const n=m(e),r=[],o=t._getPreInitialState(s,n),i=Object.values(o.children).filter(Boolean).map(t=>at(t)),c=xe(t.root,o,s,n,r),{microsteps:a}=$e(c[0],n,s,r,[[c[0],[...i,...c[1]]]]);return Zn(a,s)},t.getInitialSnapshot=function(t,...[e]){const s=Vt(t);return t.initialTransition(e,s)[0]},t.getMicrosteps=function(t,e,s){const n=Vt(t,e);Z(n);const{microsteps:r}=$e(e,s,n,[]);return Zn(r,n,e)},t.getNextSnapshot=function(t,e,s){const n=Vt(t,e),r=t.transition(e,s,n),o=Array.isArray(r)?r[0]:r;return Tt(n,o,!1),o===e?o:Mt(n,o)},t.getNextTransitions=function(t){if("active"!==t.status)return[];const e=[],s=t.nodes.filter(Ut),n=new Set;for(const t of s)for(const s of[t].concat(Bt(t,void 0)))if(!n.has(s.id)){n.add(s.id);for(const[,t]of s.transitions.entries())e.push(...t);s.always&&e.push(...s.always)}return e},t.getStateNodes=ue,t.initialTransition=function(t,...[e]){const s=Vt(t),[n,r]=ht(s,void 0,t.initialTransition(e,s));Tt(s,n,!1);const o=Mt(s,n);return tr(s,o,m(e)),[o,r]},t.isBuiltInExecutableAction=ft,t.isMachineSnapshot=Ve,t.isTypeSchema=function(t){return!!t&&"object"==typeof t&&"~standard"in t&&"xstate.types"===t["~standard"].vendor},t.listenerLogic=k,t.machineConfigToJSON=Un,t.machineVersions=function(t,e){const s=new Map,n=new Map,r=t[0].id;for(const e of t){if(void 0===e.version)throw new Error(`Machine '${e.id}' must define a version.`);if("*"===e.version)throw new Error("Machine version '*' is reserved for wildcard migrations.");if(e.id!==r)throw new Error(`Machine '${e.id}' does not match machine ID '${r}'.`);const t=`${e.id}\0${e.version}`;if(s.has(t))throw new Error(`Duplicate machine identity '${e.id}' version '${e.version}'.`);s.set(t,e),Bn(e)&&n.set(t,e)}if(void 0!==e?.unversioned&&!s.has(`${r}\0${e.unversioned}`))throw new Error(`Unversioned snapshot version '${e.unversioned}' is not retained for machine '${r}'.`);const o=async t=>{if(!Wn(t))throw new Error("Persisted snapshot is missing machine identity.");let n,o;if(Wn(t.machine)){if(({id:n,version:o}=t.machine),"string"!=typeof n||"string"!=typeof o)throw new Error("Persisted snapshot has an invalid machine identity.")}else if("string"==typeof t.version)n=r,o=t.version;else{if(void 0!==t.version||void 0===e?.unversioned)throw new Error("Persisted snapshot is missing machine identity.");n=r,o=e.unversioned}if(void 0!==t.version&&"string"!=typeof t.version)throw new Error("Persisted snapshot has an invalid version.");if(void 0!==t.version&&t.version!==o)throw new Error(`Persisted snapshot version '${t.version}' conflicts with machine version '${o}'.`);const i=s.get(`${n}\0${o}`);if(!i)throw new Error(`Unknown machine identity '${n}' version '${o}'.`);if(!("snapshotSchema"in(c=i))||void 0===c.snapshotSchema)throw new Error(`Machine version '${o}' does not define a snapshot schema.`);var c;const a=await Fn(i.snapshotSchema,t,`snapshot for machine '${n}' version '${o}'`);return{source:i,...Bn(i)&&{machine:i},snapshot:{...a,machine:{id:n,version:o}}}};return{parseSnapshot:o,async adaptEvents(t,e){const o=n.get(`${r}\0${e.to}`);if(!o)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);const i=e.from.id??r,c=s.get(`${i}\0${e.from.version}`);let a,u=!1;const d=c&&("eventSchema"in(h=c)&&void 0!==h.eventSchema);var h;if(d){let s;try{s=await qn(t,c)}catch(t){a=t,u=!0}if(s){if(c===o)return s;const t=e.adapters[c.version];if(t)return qn(await t(s),o)}}const f=e.adapters["*"];if(f)return qn(await f(t,e.from),o);if(d){if(u)throw a instanceof Error?a:new Error(`Unable to validate event history for machine '${c.id}' version '${c.version}'.`,{cause:a});throw new Error(`No event adapter from version '${c.version}' to '${o.version}' for machine '${o.id}'.`)}if(c)throw new Error(`Machine version '${c.version}' does not define an event schema; only the '*' adapter can handle its event history.`);throw new Error(`Unknown event history source '${i}' version '${e.from.version}'.`)},async migrateSnapshot(t,e){const s=n.get(`${r}\0${e.to}`);if(!s)throw new Error(`Target version '${e.to}' is not backed by a machine for '${r}'.`);let i,c;try{i=await o(t)}catch(t){c=t}if(i){if(i.source.version===s.version)return Jn(i.snapshot,s);const t=e.migrations[i.source.version];if(t)return Jn(await t(i.snapshot),s)}const a=e.migrations["*"];if(!a){if(i)throw new Error(`No snapshot migration from version '${i.source.version}' to '${s.version}' for machine '${s.id}'.`);throw c}const u=await a(t,function(t,e){return Wn(t)?Wn(t.machine)?{id:"string"==typeof t.machine.id?t.machine.id:void 0,version:"string"==typeof t.machine.version?t.machine.version:void 0}:{id:"string"==typeof t.version?e:void 0,version:"string"==typeof t.version?t.version:void 0}:{}}(t,r));return Jn(u,s)}}},t.mapState=function(t,e){const s=[],n=(t,e)=>{let s=t;for(const t of e){if(!s?.states)return;const e=s.states;if(!(t in e))return;s=e[t]}return s},r=new Set;for(const o of t.nodes.filter(Ut)){let i=o;for(;i&&!r.has(i);){r.add(i);const o=n(e,i.path);o?.map&&s.push({stateNode:i,result:o.map(t)}),i=i.parent}}return s},t.matchesState=Qe,t.pathToStateValue=ts,t.runStep=hs,t.serializeMachine=function(t){return t._json??Un(t.config)},t.setup=Hn,t.stopActor=ys,t.subscriptionLogic=T,t.terminateActor=ps,t.toObserver=as,t.toPromise=function(t){return new Promise((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})})},t.transition=function(t,e,s){const n=Vt(t,e);Tt(n,e,!1);const[r,o]=ht(n,e,t.transition(e,s,n));Tt(n,r,!1);const i=r===e?r:Mt(n,r);return tr(n,i,s),[i,o]},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},t.waitFor=function(t,e,s){const n={...er,...s};return new Promise((s,r)=>{const{signal:o}=n;if(o?.aborted)return void r(o.reason);let i=!1;const c=n.timeout===1/0?void 0:setTimeout(()=>{a(),r(new Error(`Timeout of ${n.timeout} ms exceeded`))},n.timeout),a=()=>{clearTimeout(c),i=!0,h?.unsubscribe(),d&&o.removeEventListener("abort",d)};function u(t){e(t)&&(a(),s(t))}let d,h;u(t.getSnapshot()),i||(o&&(d=()=>{a(),r(o.reason)},o.addEventListener("abort",d)),h=t.subscribe({next:u,error:t=>{a(),r(t)},complete:()=>{a(),r(new Error("Actor terminated without satisfying predicate"))}}),i&&h.unsubscribe())})},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate.umd.min.js.map