xstate 6.0.0-alpha.8 → 6.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +223 -78
- package/bin/agent.js +347 -0
- package/bin/xstate.js +52 -0
- package/dist/createActor-25900f76.cjs.js +7015 -0
- package/dist/createActor-551369be.development.esm.js +7175 -0
- package/dist/createActor-a49ae0ce.development.cjs.js +7289 -0
- package/dist/createActor-cbe3abac.esm.js +6902 -0
- package/dist/declarations/src/SimulatedClock.d.ts +2 -1
- package/dist/declarations/src/State.d.ts +66 -5
- package/dist/declarations/src/StateMachine.d.ts +107 -32
- package/dist/declarations/src/StateNode.d.ts +21 -16
- package/dist/declarations/src/actions.d.ts +11 -6
- package/dist/declarations/src/actors/callback.d.ts +11 -2
- package/dist/declarations/src/actors/index.d.ts +6 -5
- package/dist/declarations/src/actors/listener.d.ts +8 -3
- package/dist/declarations/src/actors/logic.d.ts +42 -52
- package/dist/declarations/src/actors/observable.d.ts +15 -2
- package/dist/declarations/src/actors/promise.d.ts +90 -22
- package/dist/declarations/src/actors/subscription.d.ts +9 -3
- package/dist/declarations/src/assert.d.ts +1 -0
- package/dist/declarations/src/base.types.d.ts +102 -0
- package/dist/declarations/src/createActor.d.ts +101 -27
- package/dist/declarations/src/createMachine.d.ts +38 -17
- package/dist/declarations/src/delay.d.ts +8 -0
- package/dist/declarations/src/durable/index.d.ts +231 -0
- package/dist/declarations/src/effectDescriptor.d.ts +95 -0
- package/dist/declarations/src/eventTypes.d.ts +9 -0
- package/dist/declarations/src/fsm/index.d.ts +2 -0
- package/dist/declarations/src/fsm.d.ts +169 -0
- package/dist/declarations/src/graph/adjacency.d.ts +6 -3
- package/dist/declarations/src/graph/graph.d.ts +6 -3
- package/dist/declarations/src/graph/index.d.ts +2 -3
- package/dist/declarations/src/graph/pathFromEvents.d.ts +5 -2
- package/dist/declarations/src/graph/shortestPaths.d.ts +5 -3
- package/dist/declarations/src/graph/simplePaths.d.ts +5 -3
- package/dist/declarations/src/graph/types.d.ts +113 -59
- package/dist/declarations/src/hotSwap.d.ts +18 -0
- package/dist/declarations/src/index.d.ts +28 -19
- package/dist/declarations/src/inspection.d.ts +24 -1
- package/dist/declarations/src/machineFromJSON.d.ts +171 -0
- package/dist/declarations/src/machineSchemas.d.ts +27 -0
- package/dist/declarations/src/machineVersion.types.d.ts +53 -0
- package/dist/declarations/src/machineVersions.d.ts +103 -0
- package/dist/declarations/src/mapState.d.ts +2 -0
- package/dist/declarations/src/persist/index.d.ts +36 -0
- package/dist/declarations/src/persistedSnapshotValidation.d.ts +18 -0
- package/dist/declarations/src/runtimeHelpers.d.ts +43 -0
- package/dist/declarations/src/schema.types.d.ts +31 -4
- package/dist/declarations/src/serialize.d.ts +39 -28
- package/dist/declarations/src/setup.d.ts +1086 -147
- package/dist/declarations/src/spawn.d.ts +6 -4
- package/dist/declarations/src/stateUtils.d.ts +57 -14
- package/dist/declarations/src/system.d.ts +178 -17
- package/dist/declarations/src/systemTransition.d.ts +108 -0
- package/dist/declarations/src/toPromise.d.ts +1 -0
- package/dist/declarations/src/transition.d.ts +48 -10
- package/dist/declarations/src/transitionActions.d.ts +22 -4
- package/dist/declarations/src/typeUtils.d.ts +51 -0
- package/dist/declarations/src/types.d.ts +835 -318
- package/dist/declarations/src/types.v6.d.ts +547 -104
- package/dist/declarations/src/utils.d.ts +38 -8
- package/dist/declarations/src/validation/index.d.ts +49 -0
- package/dist/declarations/src/validation.types.d.ts +29 -0
- package/dist/declarations/src/waitFor.d.ts +1 -0
- package/dist/effectDescriptor-2fa27c54.cjs.js +351 -0
- package/dist/effectDescriptor-321a8ce9.development.esm.js +343 -0
- package/dist/effectDescriptor-d8b0f749.esm.js +343 -0
- package/dist/effectDescriptor-f73da4ec.development.cjs.js +351 -0
- package/dist/machineSchemas-45c21bc2.esm.js +1292 -0
- package/dist/machineSchemas-6d96bef4.development.cjs.js +1379 -0
- package/dist/machineSchemas-88d01821.cjs.js +1300 -0
- package/dist/machineSchemas-b5736804.development.esm.js +1371 -0
- package/dist/schema.types-0ecd17b8.esm.js +71 -0
- package/dist/schema.types-15a68ddc.cjs.js +74 -0
- package/dist/schema.types-1c16f035.development.cjs.js +74 -0
- package/dist/schema.types-1cd4652e.development.esm.js +71 -0
- package/dist/validation-05f1d517.esm.js +8 -0
- package/dist/validation-4561b43c.cjs.js +10 -0
- package/dist/validation-e69470ad.development.esm.js +8 -0
- package/dist/validation-f2714a35.development.cjs.js +10 -0
- package/dist/xstate-actors.cjs.js +1068 -12
- package/dist/xstate-actors.cjs.mjs +2 -4
- package/dist/xstate-actors.development.cjs.js +1068 -12
- package/dist/xstate-actors.development.cjs.mjs +2 -4
- package/dist/xstate-actors.development.esm.js +1064 -1
- package/dist/xstate-actors.esm.js +1064 -1
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.d.mts +2 -0
- package/dist/xstate-durable.cjs.d.ts +2 -0
- package/dist/xstate-durable.cjs.js +513 -0
- package/dist/xstate-durable.cjs.mjs +5 -0
- package/dist/xstate-durable.development.cjs.js +513 -0
- package/dist/xstate-durable.development.cjs.mjs +5 -0
- package/dist/xstate-durable.development.esm.js +507 -0
- package/dist/xstate-durable.esm.js +507 -0
- package/dist/xstate-durable.umd.min.js +2 -0
- package/dist/xstate-durable.umd.min.js.map +1 -0
- package/dist/xstate-fsm.cjs.d.mts +2 -0
- package/dist/xstate-fsm.cjs.d.ts +2 -0
- package/dist/xstate-fsm.cjs.js +111 -0
- package/dist/xstate-fsm.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.cjs.js +111 -0
- package/dist/xstate-fsm.development.cjs.mjs +5 -0
- package/dist/xstate-fsm.development.esm.js +105 -0
- package/dist/xstate-fsm.esm.js +105 -0
- package/dist/xstate-fsm.umd.min.js +2 -0
- package/dist/xstate-fsm.umd.min.js.map +1 -0
- package/dist/xstate-graph.cjs.js +173 -457
- package/dist/xstate-graph.cjs.mjs +2 -5
- package/dist/xstate-graph.development.cjs.js +173 -457
- package/dist/xstate-graph.development.cjs.mjs +2 -5
- package/dist/xstate-graph.development.esm.js +171 -451
- package/dist/xstate-graph.esm.js +171 -451
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.d.mts +2 -0
- package/dist/xstate-persist.cjs.d.ts +2 -0
- package/dist/xstate-persist.cjs.js +314 -0
- package/dist/xstate-persist.cjs.mjs +6 -0
- package/dist/xstate-persist.development.cjs.js +325 -0
- package/dist/xstate-persist.development.cjs.mjs +6 -0
- package/dist/xstate-persist.development.esm.js +319 -0
- package/dist/xstate-persist.esm.js +308 -0
- package/dist/xstate-persist.umd.min.js +2 -0
- package/dist/xstate-persist.umd.min.js.map +1 -0
- package/dist/xstate-validation.cjs.d.mts +2 -0
- package/dist/xstate-validation.cjs.d.ts +2 -0
- package/dist/xstate-validation.cjs.js +330 -0
- package/dist/xstate-validation.cjs.mjs +5 -0
- package/dist/xstate-validation.development.cjs.js +330 -0
- package/dist/xstate-validation.development.cjs.mjs +5 -0
- package/dist/xstate-validation.development.esm.js +324 -0
- package/dist/xstate-validation.esm.js +324 -0
- package/dist/xstate-validation.umd.min.js +2 -0
- package/dist/xstate-validation.umd.min.js.map +1 -0
- package/dist/xstate.cjs.js +2486 -1430
- package/dist/xstate.cjs.mjs +23 -13
- package/dist/xstate.development.cjs.js +2486 -1430
- package/dist/xstate.development.cjs.mjs +23 -13
- package/dist/xstate.development.esm.js +2445 -1398
- package/dist/xstate.esm.js +2445 -1398
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/actions.md +75 -0
- package/docs/actor-logic.md +250 -0
- package/docs/actors.md +64 -0
- package/docs/agents.md +132 -0
- package/docs/api-stability.json +4287 -0
- package/docs/async-logic.md +75 -0
- package/docs/async-requests.md +157 -0
- package/docs/backend-workflows.md +124 -0
- package/docs/cancellation.md +42 -0
- package/docs/cheatsheet.md +563 -0
- package/docs/choice-states.md +109 -0
- package/docs/choose-xstate.md +47 -0
- package/docs/configuration.md +161 -0
- package/docs/context.md +67 -0
- package/docs/create-actor.md +159 -0
- package/docs/data-and-effects.md +48 -0
- package/docs/delays.md +81 -0
- package/docs/durable-execution.md +520 -0
- package/docs/emitted-events.md +146 -0
- package/docs/errors.md +812 -0
- package/docs/examples.md +75 -0
- package/docs/faq.md +60 -0
- package/docs/final-states.md +149 -0
- package/docs/forms-and-wizards.md +166 -0
- package/docs/frameworks.md +69 -0
- package/docs/fsm.md +164 -0
- package/docs/glossary.md +68 -0
- package/docs/guards.md +137 -0
- package/docs/history-states.md +161 -0
- package/docs/how-xstate-runs-machines.md +86 -0
- package/docs/index.md +74 -0
- package/docs/input-output.md +69 -0
- package/docs/inspect-actor-systems.md +118 -0
- package/docs/inspection.md +75 -0
- package/docs/internal-events.md +156 -0
- package/docs/invoke.md +371 -0
- package/docs/lifecycle-and-errors.md +48 -0
- package/docs/listen-and-subscribe.md +126 -0
- package/docs/model-based-testing.md +321 -0
- package/docs/modeling.md +40 -0
- package/docs/parallel-states.md +182 -0
- package/docs/persist-and-restore-actors.md +120 -0
- package/docs/persistence.md +312 -0
- package/docs/quick-start.md +55 -0
- package/docs/retries-and-timeouts.md +122 -0
- package/docs/route-states.md +104 -0
- package/docs/scxml.md +92 -0
- package/docs/selectors.md +99 -0
- package/docs/serialization.md +127 -0
- package/docs/setup-and-provide.md +273 -0
- package/docs/snapshots.md +134 -0
- package/docs/spawn.md +212 -0
- package/docs/state-input.md +162 -0
- package/docs/statecharts.md +54 -0
- package/docs/states-events-transitions.md +82 -0
- package/docs/states.md +168 -0
- package/docs/system-transitions.md +172 -0
- package/docs/systems.md +166 -0
- package/docs/testing.md +152 -0
- package/docs/timeouts.md +125 -0
- package/docs/transition-functions.md +89 -0
- package/docs/transitions.md +187 -0
- package/docs/troubleshooting.md +56 -0
- package/docs/tutorial.md +481 -0
- package/docs/typescript.md +213 -0
- package/docs/typestates.md +112 -0
- package/docs/utilities.md +39 -0
- package/docs/why-state-machines.md +59 -0
- package/docs/xstate-v5-to-v6.md +1923 -0
- package/docs/your-first-machine.md +79 -0
- package/durable/package.json +8 -0
- package/fsm/package.json +8 -0
- package/package.json +72 -10
- package/persist/package.json +8 -0
- package/validation/package.json +8 -0
- package/actions/package.json +0 -8
- package/dev/package.json +0 -8
- package/dist/StateMachine-0aa98f54.development.esm.js +0 -746
- package/dist/StateMachine-aef700df.cjs.js +0 -732
- package/dist/StateMachine-d4931336.esm.js +0 -729
- package/dist/StateMachine-da872dde.development.cjs.js +0 -749
- package/dist/declarations/src/createMachineFromConfig.d.ts +0 -177
- package/dist/declarations/src/getNextSnapshot.d.ts +0 -37
- package/dist/declarations/src/graph/TestModel.d.ts +0 -70
- package/dist/declarations/src/graph/pathGenerators.d.ts +0 -4
- package/dist/index-219cb621.development.cjs.js +0 -4476
- package/dist/index-2f2fbd9b.development.esm.js +0 -4421
- package/dist/index-559ceab3.cjs.js +0 -4437
- package/dist/index-8828376f.esm.js +0 -4382
- package/guards/package.json +0 -8
- package/invoke/package.json +0 -4
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",n="@xstate.stop";function o(t,e){return{type:`xstate.after.${t}.${e}`}}function i(t){return{type:`xstate.timeout.actor.${t}`}}function r(t,e){return{type:`xstate.done.state.${t}`,output:e}}function c(t){return{type:s,input:t}}function a(t){setTimeout(()=>{throw t})}const h="function"==typeof Symbol&&Symbol.observable||"@@observable",u={"@xstate.start":t=>{t.start()},"@xstate.raise":(t,e,s)=>{t.system.scheduler.schedule(t.self,t.self,e,s?.delay??0,s?.id)},"@xstate.sendTo":(t,e,s,n)=>{if("string"==typeof s)throw new Error("Only event objects may be used with sendTo");void 0!==n?.delay?t.system.scheduler.schedule(t.self,e,s,n?.delay??0,n?.id):t.defer(()=>{t.system._relay(t.self,e,s)})},"@xstate.cancel":(t,e)=>{t.system.scheduler.cancel(t.self,e)},"@xstate.stop":(t,e)=>{t.stopChild(e)}},f=new WeakMap;function p(t){const e=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{start:(e,{self:s,system:n})=>{const o=e.input.actor;if(!o||"stopped"===o.getSnapshot().status)return;const i=t(e.input,{self:s,system:n});if(!i)return;let r,c=!1;const a=()=>{c||(c=!0,i.unsubscribe(),r?.unsubscribe())},h=s._parent;h&&(r=h.subscribe({complete:a,error:a})),f.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===n?(f.get(s)?.unsubscribe(),f.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:e,getInitialSnapshot:(t,s)=>e(s)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function d(){return p(({actor:t,eventType:e,mapper:s},{self:n,system:o})=>{const i="*"!==e&&e.endsWith(".*");return t.on(i?"*":e,t=>{i&&!zt(t.type,e)||l(n,o,()=>s(t))})})}const y=d();function g(){return p(({actor:t,mappers:e},{self:s,system:n})=>{const{done:o,error:i,snapshot:r}=e;return t.subscribe({next:t=>{"done"===t.status&&o?l(s,n,()=>o(t.output)):"error"===t.status&&i?l(s,n,()=>i(t.error)):"active"===t.status&&r&&l(s,n,()=>r(t))},error:t=>{i&&l(s,n,()=>i(t))},complete:()=>{}})})}const v=g();function m(t,e){return{...t,...e}}function _(t,e,...s){t.push({action:e,args:s})}function S(t,e,s){_(t,u["@xstate.start"],e),t.push(function(t,e){return Object.assign(function(s){return{children:{...s.children,[e]:t}}},{_special:!0})}(e,s??e.id))}function x(t,e,s,n=!1){const o={cancel:s=>{_(e,u["@xstate.cancel"],t,s)},emit:t=>{e.push(t)},log:(...s)=>{_(e,t.logger,...s)},raise:(n,o)=>{if("string"==typeof n)throw new Error("Only event objects may be used with raise");void 0!==o?.delay?_(e,u["@xstate.raise"],t,n,o):s.push(n)},spawn:(s,n)=>{const o=Ht(s,{...n,parent:t.self});return S(e,o,n?.id),o},sendTo:(s,n,o)=>{s&&_(e,u["@xstate.sendTo"],t,s,n,o)},stop:s=>{s&&(_(e,u["@xstate.stop"],t,s),e.push(function(t){return Object.assign(function(e){const s={...e.children};for(const e of Object.keys(s))s[e]===t&&delete s[e];return{children:s}},{_special:!0})}(s)))}};return n&&Object.assign(o,{listen:(s,n,o)=>{const i=Ht(y,{input:{actor:s,eventType:n,mapper:o},parent:t.self});return _(e,u["@xstate.start"],i),i},subscribeTo:(s,n)=>{const o=Ht(v,{input:{actor:s,mappers:"function"==typeof n?{snapshot:n}:n},parent:t.self});return _(e,u["@xstate.start"],o),o}}),E(o,(t,...s)=>{_(e,t,...s)})}function b(t,e){switch(t){case u["@xstate.start"]:{const[t]=e;return{actor:t,id:t.id,logic:t.logic,src:t.src,input:t.options?.input}}case u["@xstate.raise"]:{const[,t,s]=e;return{event:t,id:s?.id,delay:s?.delay}}case u["@xstate.sendTo"]:{const[,t,s,n]=e;return{target:t,event:s,id:n?.id,delay:n?.delay}}case u["@xstate.cancel"]:{const[,t]=e;return{id:t}}case u["@xstate.stop"]:{const[,t]=e;return{actor:t}}default:return}}function w(t,e,s,n){let o=t;const i=[];for(const r of n){const n="function"==typeof r?r:"object"==typeof r&&"action"in r&&"function"==typeof r.action&&r.action.bind(null,...r.args),c={context:o.context,event:e,output:It(e),self:s.self,system:s.system,children:o.children,parent:s.self._parent,actions:t.machine.implementations.actions,actorSources:t.machine.implementations.actorSources};let a;if("object"==typeof r&&null!==r){const{type:t,...e}=r;a=e}if(n&&"_special"in n){i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type??"(anonymous)":r.name||"(anonymous)",params:a,args:[],exec:void 0});const t=n(c,k);t&&("context"in t||"children"in t)&&(o=_t(o,{...void 0!==t.context?{context:m(o.context,t.context)}:{},..."children"in t?{children:t.children}:{}}));continue}if(!n||!("resolve"in n)){const t="object"==typeof r&&null!==r&&"action"in r&&"function"==typeof r.action?b(r.action,r.args):void 0;i.push({type:"object"==typeof r?"action"in r&&"function"==typeof r.action?r.action.name??"(anonymous)":r.type:r.name||"(anonymous)",params:a,args:"object"==typeof r&&"action"in r?r.args:[],exec:n||("object"==typeof r&&null!==r?()=>s.defer(()=>s.emit(r)):void 0),...t});continue}}return[o,i]}function E(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}const k=E({},()=>{});function $(t,e){if("string"!=typeof t)return t;const s=e[t];return void 0!==s?s:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const n=e.match(/^(\d*)(\.?)(\d*)s$/i);if(n){const t=n[1]?parseInt(n[1],10):0,e=!!n[2],s=n[3]?parseInt(n[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const o=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!o?.groups)return;const{weeks:i,days:r,hours:c,minutes:a,seconds:h}=o.groups;if(!(i||r||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(i)*24*60*60*1e3+24*u(r)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)??t}function j(t,e,s){if("function"==typeof t)return t(s);const n=$(t,e);return"function"==typeof n?n(s):n}function I(t){return"atomic"===t.type||"final"===t.type||"choice"===t.type}function O(t){return Object.values(t.states).filter(t=>"history"!==t.type)}function T(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function M(t){const e=new Set(t),s=new Set;for(const t of e)t.parent&&s.add(t.parent);for(const t of e)if("compound"!==t.type||s.has(t)){if("parallel"===t.type)for(const s of O(t))if(!e.has(s)){const t=C(s);for(const s of t)e.add(s)}}else for(const s of C(t))e.add(s);for(const t of e){let s=t.parent;for(;s&&!e.has(s);)e.add(s),s=s.parent}return e}function A(t,e){const s=M(e),n=new Map;for(const t of s)n.has(t)||n.set(t,[]),t.parent&&(n.has(t.parent)||n.set(t.parent,[]),n.get(t.parent).push(t));const o=t=>{const e=n.get(t);if(!e)return{};if("compound"===t.type){const t=e[0];if(!t)return{};if(I(t))return t.key}const s={};for(const t of e)s[t.key]=o(t);return s};return o(t)}function P(t,e){return"compound"===e.type?O(e).some(e=>"final"===e.type&&t.has(e)):"parallel"===e.type?O(e).every(e=>P(t,e)):"final"===e.type}const N=t=>"#"===t[0];function z(t,e,s){const n=e.type,o=t.entry;t.entry=(t,i)=>(i.raise(e,{id:n,delay:s(t)}),"function"==typeof o?o(t,i):void 0);const i=t.exit;return t.exit=(t,e)=>(e.cancel(n),"function"==typeof i?i(t,e):void 0),n}function D(t,e,s){const n=Mt(s.target),o=s.reenter??!1,i=R(t,n),r={...s,target:i,source:t,reenter:o,eventType:e,toJSON:()=>({...r,source:`#${t.id}`,target:i?i.map(t=>`#${t.id}`):void 0})};return r}function R(t,e){if(void 0!==e)return e.map(e=>{if("string"!=typeof e)return e;if(N(e))return t.machine.getStateNodeById(e);const s="."===e[0];if(s&&!t.parent)return V(t,e.slice(1));const n=s?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}"`);try{return V(t.parent,n)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}})}function J(t){const e=Mt(t.config.target);return e?{target:e.map(e=>"string"==typeof e?V(t.parent,e):e),source:t,reenter:!1,eventType:""}:t.parent.initial}function K(t){return"history"===t.type}function C(t){const e=new Set;!function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of O(s))t(e)}(t);for(const s of e)for(const n of T(s,t))e.add(n);return e}function B(t,e){if(N(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function V(t,e){if("string"==typeof e&&N(e))try{return t.machine.getStateNodeById(e)}catch{}const s=wt(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=B(n,t)}return n}function W(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=new Array(s.length),o=[t.machine.root,t];for(let e=0;e<s.length;e++){const i=B(t,s[e]);n[e]=i,o.push(i)}for(let t=0;t<s.length;t++)o.push(...W(n[t],e[s[t]]));return o}function L(t,e,s,n,o){if("string"==typeof e){const i=B(t,e).next(s,n,o);return i&&i.length?i:t.next(s,n,o)}const i=Object.keys(e),r=i[0];if(1===i.length){const i=L(B(t,r),e[r],s,n,o);return i&&i.length?i:t.next(s,n,o)}const c=[];for(const r of i){const i=e[r];if(!i)continue;const a=L(B(t,r),i,s,n,o);a&&c.push(...a)}return c.length?c:t.next(s,n,o)}function q(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function F(t,e){for(const s of t)if(q(s,e))return!0;return!1}function G(t,e){const s=t instanceof Set?t.size:Array.isArray(t)?t.length:void 0,n=e instanceof Set?e.size:Array.isArray(e)?e.length:void 0;void 0!==s&&void 0!==n&&n<s&&([t,e]=[e,t]);const o=t instanceof Set?t:new Set(t);for(const t of e)if(o.has(t))return!0;return!1}function U(t,e,s,n,o){const i=new Set,r=new Map,c=t=>{let i=r.get(t);return i||(i=Q([t],e,s,n,o),r.set(t,i)),i};for(const e of t){let t=!1;const s=new Set;for(const n of i)if(G(c(e),c(n))){if(!q(e.source,n.source)){t=!0;break}s.add(n)}if(!t){for(const t of s)i.delete(t);i.add(e)}}return Array.from(i)}function H(t,e,s,n){const o=e.historyValue,{targets:i}=tt(t,e,s,n);if(!i)return[];const r=new Set;for(const t of i)if(K(t))if(o[t.id])for(const e of o[t.id])r.add(e);else for(const o of H(J(t),e,s,n))r.add(o);else r.add(t);return[...r]}function X(t,e,s,n){const o=H(t,e,s,n),{reenter:i}=tt(t,e,s,n);if(!i&&o.every(e=>e===t.source||q(e,t.source)))return t.source;const[r,...c]=o.concat(t.source);for(const t of T(r,void 0))if(c.every(e=>q(e,t)))return t;return i?void 0:t.source.machine.root}function Q(t,e,s,n,o){const i=new Set;for(const r of t){const{targets:t}=tt(r,s,n,o);if(t?.length){const t=X(r,s,n,o);r.reenter&&r.source===t&&i.add(t);for(const s of e)q(s,t)&&i.add(s)}}return[...i]}function Y(t,e){return{...t,...e}}function Z(t,e,s,n,o,i){const c=[];if(!t.length)return[e,c];{const a=new Set(e._nodes);let h=e.historyValue;const f=e.context,p=U(t,a,e,n,s),l=t=>tt(t,e,n,s),d=(t,o,i,r)=>{if(2===t.length){const c=[],a=[];let h;const u=x(s,c,a,!0),f=t({context:o,event:n,parent:s.self._parent,self:s.self,children:i,system:s.system,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays,input:r},u);return void 0!==f?.context&&(h=Y(o,f.context)),[c,h,a]}return[[Object.assign((e,s)=>t({...e,input:r},s),"_special"in t?{_special:!0}:{})],void 0,void 0]};let y=e;const g=()=>{const t=Q(p,a,e,n,s);let o;t.sort((t,e)=>e.order-t.order);const r=[...a];for(const e of t)for(const t of Object.values(e.states)){if("history"!==t.type)continue;const s="deep"===t.history?t=>I(t)&&q(t,e):t=>t.parent===e;o??={...h},o[t.id]=r.filter(s)}for(const o of t){const t=e._stateInputs?.[o.id],[r,h,u]=o.exit?d(o.exit,y.context,e.children,t):[[]];u?.length&&i.push(...u),h&&(y=_t(y,{context:h}));const[f,p]=w(y,n,s,r);y=f,c.push(...p);for(const t of o.invoke){const e=y.children[t.id];e&&!e._isExternal&&s.stopChild(e),delete y.children[t.id]}a.delete(o)}h=o||h};o||g();let v=y.context;const m=[],_=[];for(const t of p){t.actions&&m.push(...$t(t.actions));const e=l(t);void 0!==e.context&&(v=Y(v,e.context)),e.actions&&m.push(...e.actions),e.internalEvents&&_.push(...e.internalEvents)}_.length&&i.push(..._);const S=()=>{const t=t=>{const e=y.machine.root;if(void 0===e.output)return;let o;if(void 0!==t.output&&t.parent)o=jt(t.output,y.context,n,s.self);else if("parallel"===t.type){const e=`xstate.done.state.${t.id}`,s=i.find(t=>t.type===e);o=s?.output}return jt(e.output,y.context,r(t.id,o),s.self)},f=new Set,g=new Set,v=(t,e)=>{for(const s of t)if(e&&!q(s,e)||f.add(s),"parallel"===s.type)for(const t of O(s))F(f,t)||(f.add(t),m(t))},m=t=>{if(K(t))if(h[t.id]){const e=h[t.id];for(const t of e)f.add(t),m(t);for(const s of e)v(T(s,t.parent),void 0)}else{const e=J(t),{targets:s}=l(e);for(const n of s??[])f.add(n),e===t.parent?.initial&&g.add(t.parent),m(n);for(const e of s??[])v(T(e,t.parent),void 0)}else{if("compound"===t.type){const[e]=l(t.initial).targets;return K(e)||(f.add(e),g.add(e)),m(e),void v(T(e,t),void 0)}if("parallel"===t.type)for(const e of O(t))F(f,e)||(f.add(e),g.add(e),m(e))}};for(const t of p){const o=X(t,e,n,s),{targets:i,reenter:r}=l(t);for(const e of i??[])K(e)||t.source===e&&t.source===o&&!r||(f.add(e),g.add(e)),m(e);const c=H(t,e,n,s);for(const e of c){const s=T(e,o);"parallel"===o?.type&&s.push(o),v(s,!t.source.parent&&r?void 0:o)}}o&&g.add(e.machine.root);const _={...e._stateInputs};for(const t of p){const{targets:e,input:s}=l(t);if(s&&e)for(const t of e)_[t.id]=s}const S=new Set,x={...e.children};for(const o of[...f].sort((t,e)=>t.order-e.order)){a.add(o);const h=[];let f=!1;for(const t of o.invoke){f=!0;let o=t.logic;"function"==typeof o&&(o=o({actorSources:e.machine.implementations.actorSources,context:y.context,event:n,self:s.self}));const i="string"==typeof o?Pt(e.machine,o):o;if(!i)throw new Error(`Actor logic '${"string"==typeof o?o:"inline"}' not implemented in machine '${e.machine.id}'`);const r="function"==typeof t.input?t.input({self:s.self,context:y.context,event:n,output:It(n)}):t.input,c=Ht(i,{...t,input:r,parent:s.self,syncSnapshot:!!t.onSnapshot});h.push({action:u["@xstate.start"],args:[c]}),t.id&&(x[t.id]=c)}f&&(y=_t(y,{children:x}));let p=y.context,l=!1;const v=_[o.id];if(o.entry){const[t,e,s]=d(o.entry,p,x,v);h.push(...t),s?.length&&i.push(...s),e&&(p=e,l=!0)}if(l&&(y.context=p),g.has(o)){const{actions:t,input:e}=tt(o.initial,y,n,s);if(t&&h.push(...t),e&&o.initial?.target)for(const t of o.initial.target)_[t.id]=e}const[m,b]=w(y,n,s,h);if(y=m,h.length=0,c.push(...b),"final"!==o.type)continue;const E=o.parent;let k="parallel"===E?.type?E:E?.parent,$=k||o;for("compound"===E?.type&&i.push(r(E.id,void 0!==o.output?jt(o.output,y.context,n,s.self):void 0));"parallel"===k?.type&&!S.has(k)&&P(a,k);){S.add(k);const t={};for(const e of O(k)){if("final"===e.type){t[e.key]=void 0!==e.output?jt(e.output,y.context,n,s.self):void 0;continue}if("parallel"===e.type){const s=`xstate.done.state.${e.id}`,n=i.find(t=>t.type===s);t[e.key]=n?.output;continue}const o=O(e).find(t=>"final"===t.type&&a.has(t));t[e.key]=void 0!==o?.output?jt(o.output,y.context,n,s.self):void 0}i.push(r(k.id,t)),$=k,k=k.parent}k||(y=_t(y,{status:"done",output:t($)}))}JSON.stringify(_)!==JSON.stringify(e._stateInputs||{})&&(y=_t(y,{_stateInputs:_}))},[b,E]=w(y,n,s,m);y=b,c.push(...E),v&&v!==e.context&&(y=_t(y,{context:v})),S();const k=[...a];if("done"===y.status){const t=[];k.sort((t,e)=>e.order-t.order).forEach(e=>{if(e.exit){const s=y._stateInputs?.[e.id],[n,,o]=d(e.exit,y.context,y.children,s);t.push(...n),o?.length&&i.push(...o)}});const[e,o]=w(y,n,s,t);y=e,c.push(...o)}return h===e.historyValue&&e._nodes.length===a.size&&e._nodes.every(t=>a.has(t))?y.context!==f?[_t(y),c]:[y,c]:[_t(y,{_nodes:k,historyValue:h}),c]}}function tt(t,e,s,n){if(t.to){const o=[],i=[],r=x(n,o,i),c=t.to({context:e.context,event:s,output:It(s),value:e.value,children:e.children,system:n.system,parent:n.self._parent,self:n.self,actions:e.machine.implementations.actions,actorSources:e.machine.implementations.actorSources,guards:e.machine.implementations.guards,delays:e.machine.implementations.delays},r),a=c?.target?R(t.source,$t(c.target)):void 0,h="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input;return{targets:a,context:c?.context,reenter:c?.reenter,actions:o,internalEvents:i,input:h}}const o="function"==typeof t.input?t.input({context:e.context,event:s,output:It(s)}):t.input;return{targets:t.target,context:t.context,reenter:t.reenter,actions:void 0,internalEvents:void 0,input:o}}function et(t,e,o,i){let r=t;const c=[];function a(t,e){const s=o.self._collectedMicrosteps||[];s.push(...e),o.self._collectedMicrosteps=s,c.push(t)}if(e.type===n)return r=_t(ot(r,o),{status:"stopped"}),a([r,[]],[]),{snapshot:r,microsteps:c};let h=e;if(h.type!==s){const e=h,s=function(t){return t.type.startsWith("xstate.error.actor")}(e),n=r.machine.getTransitionData(r,e,o.self);if(s&&!n.length)return r=_t(t,{status:"error",error:e.error}),a([r,[]],[]),{snapshot:r,microsteps:c};const u=Z(n,t,o,h,!1,i);r=u[0],a(u,n)}let u=!0;const f=t.machine.options?.maxIterations??1/0;let p=0,l=0;for(;"active"===r.status;){if(l++,l>1e3)throw new Error("Microstep count exceeded 1000");if(p++,p>f)throw new Error(`Infinite loop detected (>${f} microsteps)`);let t=u?it(r,h,o):[];const e=t.length?r:void 0;if(!t.length){if(!i.length)break;h=i.shift(),t=r.machine.getTransitionData(r,h,o.self)}const s=Z(t,r,o,h,!1,i);r=s[0],u=r!==e,a(s,t)}return"active"!==r.status&&r.children&&ot(r,o),{snapshot:r,microsteps:c}}function st(t,e,s,n,o){return!!t.to&&nt(t.to,e,s,n,o,n.machine.implementations)}function nt(t,e,s,n,o,i){let r,c=!1;try{const a=()=>{throw c=!0,new Error("Effect triggered")};r=t({context:e,event:s,output:It(s),self:o,system:o.system,value:n.value,children:n.children,parent:{send:a},actions:i.actions,actorSources:i.actorSources,guards:i.guards,delays:i.delays},function(t,e){const s=(t,...s)=>{e(t,...s)};return Object.assign(s,{cancel:()=>{},emit:()=>{},log:()=>{},raise:()=>{},spawn:()=>({}),sendTo:()=>{},stop:()=>{},listen:()=>({}),subscribeTo:()=>({}),...t}),s}({emit:a,cancel:a,log:a,raise:a,spawn:a,sendTo:a,stop:a},a))}catch(t){if(c)return!0;throw t}return void 0!==r}function ot(t,e){let s;if(!t.children||0===(s=Object.values(t.children).filter(Boolean)).length)return t;for(const t of s)e.stopChild(t);return _t(t,{children:{}})}function it(t,e,s){const n=new Set,o=t._nodes.filter(I);for(const i of o)t:for(let o=i;o;o=o.parent)if(o.always)for(const i of o.always)if(rt(i,e,t,o,s.self)){n.add(i);break t}return U(Array.from(n),new Set(t._nodes),t,e,s)}function rt(t,e,s,n,o){if(t.guard){const i={context:s.context,event:e,output:It(e),self:o,parent:o._parent,children:s.children,actions:n.machine.implementations.actions,actorSources:n.machine.implementations.actorSources,guards:n.machine.implementations.guards,delays:n.machine.implementations.delays,_snapshot:s};if(!t.guard(i))return!1}return!t.to||nt(t.to,s.context,e,s,o,n.machine.implementations)}function ct(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}let at,ht;function ut(){return at??=Qt()}const ft=function(t){return bt(t,this.value)},pt=function(t){return this.tags.has(t)},lt=function(t){const e=ut(),s=function(){if(ht)return ht;const t=ut();return ht={self:t,logger:()=>{},id:"",sessionId:"",defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}},ht}(),n=this.machine.getTransitionData(this,t,e);if(!n?.length)return!1;for(const o of n){if(void 0!==o.target)return!0;const n=tt(o,this,t,s);if(n.targets?.length||n.context||st(o,this.context,t,this,e))return!0}return!1},dt=function(){const{_nodes:t,_stateInputs:e,tags:s,machine:n,getMeta:o,getInputs:i,toJSON:r,can:c,hasTag:a,matches:h,...u}=this;return{...u,tags:Array.from(s)}},yt=function(){const t={};for(const e of this._nodes)void 0!==e.meta&&(t[e.id]=e.meta);return t},gt=function(){return this._stateInputs};function vt(t){const e=new Set;for(const s of t)for(const t of s.tags)e.add(t);return e}function mt(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:t.value??A(e.root,t._nodes),tags:vt(t._nodes),children:t.children,historyValue:t.historyValue||{},_stateInputs:t._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}}function _t(t,e={}){const s={...t,...e};return(e._nodes??t._nodes)===t._nodes?{status:s.status,output:s.output,error:s.error,machine:t.machine,context:s.context,_nodes:t._nodes,value:t.value,tags:t.tags,children:s.children,historyValue:s.historyValue||{},_stateInputs:s._stateInputs||{},matches:ft,hasTag:pt,can:lt,getMeta:yt,getInputs:gt,toJSON:dt}:mt({...s,value:void 0},t.machine)}function St(t){const e={};for(const s in t){const n=t[s];Array.isArray(n)&&(e[s]=n.map(t=>({id:t.id})))}return e}function xt(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:Vt,id:n.id};else{const o=xt(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}function bt(t,e){const s=Et(t),n=Et(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every(t=>t in n&&bt(s[t],n[t]))}function wt(t){if(Ot(t))return t;const e=[];let s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function Et(t){if(ct(t))return t.value;if("string"!=typeof t)return t;return function(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}(wt(t))}function kt(t){return Ot(t)?t:[t]}function $t(t){return void 0===t?[]:kt(t)}function jt(t,e,s,n){if("function"==typeof t){return t({context:e,event:s,output:It(s),self:n})}return t}function It(t){if(function(t){return t.type.startsWith("xstate.done.actor.")||t.type.startsWith("xstate.done.state.")}(t)){return t.output}}function Ot(t){return Array.isArray(t)}function Tt(t){return kt(t).map(t=>void 0===t||"string"==typeof t?{target:t}:"function"==typeof t?{to:t}:t)}function Mt(t){if(void 0!==t&&""!==t)return $t(t)}function At(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function Pt(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actorSources[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke,r=(Array.isArray(i)?i[n]:i).src;return"string"==typeof r?t.implementations.actorSources[r]:r}function Nt(t){return[...new Set([...t._nodes.flatMap(t=>t.ownEvents)])]}function zt(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),n=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e){return t===s.length-1}if(e!==o)return!1}return!0}function Dt(t,e){return`${t.sessionId}.${e}`}const Rt=new WeakMap;function Jt(t){let e=Rt.get(t);return e||(e=new Map,Rt.set(t,e)),e}function Kt(t,e){if(t?.length)for(const s of t)switch(s.type){case"emit":e.emit(s.event);break;case"sendBack":{const t=e.self._parent;t&&e.system._relay(e.self,t,s.event);break}case"raise":e.system._relay(e.self,e.self,s.event);break;case"effect":{if(!s.key){const t=s.exec();"function"==typeof t&&Jt(e.self).set(Symbol(),{cleanup:t});break}const t=Jt(e.self);if(t.has(s.key))break;const n=s.exec();t.set(s.key,{cleanup:"function"==typeof n?n:void 0});break}case"cleanupEffects":{const t=Rt.get(e.self);if(!t)break;for(const{cleanup:e}of t.values())e?.();Rt.delete(e.self);break}}}function Ct(t){const e=(e,s,o)=>{if("active"!==e.status)return[e,[]];if(s.type===n)return[{...e,status:"stopped",input:void 0},[{type:"cleanupEffects"}]];if("xstate.logic.effect.start"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if("xstate.logic.effect.resolve"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if("xstate.logic.effect.reject"===s.type)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const i=[],r={},c={emit:t=>{i.push({type:"emit",event:t})},sendBack:t=>{i.push({type:"sendBack",event:t})},raise:t=>{i.push({type:"raise",event:t})},effect:(t,s)=>{if("string"==typeof t)return n=t,o=s,void(e.effects?.[n]||(i.push({type:"effect",key:n,exec:o}),r[n]={status:"active"}));var n,o;i.push({type:"effect",exec:t})}},a=t.run({context:e.context,event:s,input:e.input,system:o.system,self:o.self,emit:o.emit},c),h={...e,...a||{}};return("context"in e||void 0!==a?.context)&&(h.context=a?.context??e.context),(a?.effects||Object.keys(r).length)&&(h.effects={...e.effects,...a?.effects,...r}),[h,i]},s={id:t.id,config:t,transition:e,start:(t,s)=>{const[n,o]=e(t,c(t.input),s);Object.assign(t,n),Kt(o,s)},initialTransition:(e,s)=>{const n=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==n&&(o.context=n),[{...o},[]]},getInitialSnapshot:(t,e)=>s.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return s}let Bt=!1;const Vt=1;let Wt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Lt={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)};function qt(t){return"object"==typeof t&&null!==t&&"args"in t&&"exec"in t}function Ft(t,e){if(!t?.length)return[];const s=[];for(const n of t)qt(n)?e.actionExecutor(n):s.push(n);return s}class Gt{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=this._process.bind(this),this.mailbox=new e(this._boundProcess),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Wt.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[],this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this.system=void 0,this.trigger=void 0,this.src=void 0,this._deferred=[],this._pendingEffects=void 0;const n={...Lt,...s},{clock:o,logger:i,parent:r,syncSnapshot:c,id:h,registryKey:u,inspect:f}=n;this.system=r?r.system:n._systemRef?.current??function(t,e){let s=0;const n=new Map,o=new Map,i=new WeakMap,r=new Set,c={},{clock:a,logger:h}=e,u=(t,e,s,n,o)=>{r.size&&t&&(t._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:n,id:o})},f={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{u(t,e,s,n,o);const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},r=Dt(t,o);l._snapshot._scheduledEvents[r]=i;const h=a.setTimeout(()=>{delete c[r],delete l._snapshot._scheduledEvents[r],p(t,e,s)},n);c[r]=h},cancel:(t,e)=>{const s=Dt(t,e),n=c[s];delete c[s],delete l._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in l._snapshot._scheduledEvents){const s=l._snapshot._scheduledEvents[e];s.source===t&&f.cancel(t,s.id)}}},p=(t,e,s)=>{const n=e.logic;if("function"==typeof n?.isInternalEventType&&n.isInternalEventType(s.type)&&t!==e)throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`);e._lastSourceRef=t,e._send(s)},l={children:n,reverseKeyedActors:i,keyedActors:o,_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+s++,_register:(t,e)=>(n.set(t,e),t),_unregister:t=>{n.delete(t.sessionId);const e=i.get(t);void 0!==e&&(o.delete(e),i.delete(t))},get:t=>o.get(t),getAll:()=>Object.fromEntries(o.entries()),_set:(t,e)=>{const s=o.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);o.set(t,e),i.set(e,t)},inspect:t=>{const e=At(t);return r.add(e),{unsubscribe(){r.delete(e)}}},_sendInspectionEvent:e=>{if(!r.size)return;const s={...e,rootId:t.sessionId};r.forEach(t=>t.next?.(s))},_relay:(t,e,s)=>{u(t,e,s),p(t,e,s)},scheduler:f,getSnapshot:()=>({_scheduledEvents:{...l._snapshot._scheduledEvents}}),start:()=>{const t=l._snapshot._scheduledEvents;l._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];f.schedule(s,n,o,i,r)}},_clock:a,_logger:h,_timerStrategy:e.timers};return l}(this,{clock:o,logger:i,timers:n.timers}),r||!n._systemRef||n._systemRef.current||(n._systemRef.current=this.system),f&&!r&&this.system.inspect(At(f)),this.sessionId=this.system._bookId(),this.id=h??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=c,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(e||s){if(e)for(const s of e)try{s(t)}catch(t){a(t)}if(s)for(const e of s)try{e(t)}catch(t){a(t)}}},actionExecutor:t=>{const e=()=>{if(this._collectedActions.push({type:t.type,params:t.params}),!t.exec)return;const e=Bt;try{Bt=!0,t.exec()}finally{Bt=e}};this._processingStatus!==Wt.Running||this._forceDeferredActions?this._deferred.push(e):e()}},this.send=this.send.bind(this),this.trigger=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}});const p=u;p&&(this.registryKey=p,this.system._set(p,this)),this._collectedMicrosteps=[];let l=s?.snapshot??s?.state;if(l&&"object"==typeof l&&"_pendingEffects"in l){const{_pendingEffects:t,...e}=l;this._pendingEffects=t,l=e}try{if(l)this._snapshot=this.logic.restoreSnapshot?this.logic.restoreSnapshot(l,this._actorScope):l;else{const[t,e]=this.logic.initialTransition(this.options?.input,this._actorScope);this._snapshot=t,this._initialEffects=e}}catch(t){this._snapshot={status:"error",output:void 0,error:t},this._deferred.length=0}p&&"active"!==this._snapshot.status&&this.system._unregister(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_setErrorSnapshot(t,e=this._snapshot){this._snapshot={...e,status:"error",error:t}}_next(t){for(const e of this.observers)try{e.next?.(t)}catch(t){a(t)}}update(t,e){this._snapshot=t;for(let e=0;e<this._deferred.length;e++){const s=this._deferred[e];try{s()}catch(e){this._deferred.length=0,this._setErrorSnapshot(e,t);break}}switch(this._deferred.length=0,this._snapshot.status){case"active":this._next(t);break;case"done":{this._next(t),this._stopProcedure(),this._complete();const e=(s=this.id,n=this._snapshot.output,{type:`xstate.done.actor.${s}`,output:n,actorId:s});this._parent&&this.system._relay(this,this._parent,e);break}case"error":this._error(this._snapshot.error)}var s,n;this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps,actions:this._collectedActions,sent:this._collectedSent,eventType:e.type}),this._collectedMicrosteps=[],this._collectedActions=[],this._collectedSent=[]}_flushInitialEffects(){if(!this._initialEffects)return!0;this._forceDeferredActions=!0;try{return Kt(Ft(this._initialEffects,this._actorScope),this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred.length=0,this._setErrorSnapshot(t),this._error(t),!1}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const n=At(t,e,s);if(this._processingStatus!==Wt.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){a(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){a(t)}else a(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);return s||(s=new Set,this.eventListeners.set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,n,o)=>{const i=At(s,n,o);let r=t(this.getSnapshot());return this.subscribe({next:s=>{const n=t(s);e(r,n)||(r=n,i.next?.(n))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Wt.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Wt.Running;const t=c(this.options.input);this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._flushInitialEffects()?(this.update(this._snapshot,t),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(!this._flushInitialEffects())return this;if(this.update(this._snapshot,t),this._pendingEffects){const t=this.options.timers??this.system._timerStrategy??"resume";for(const e of this._pendingEffects)"@xstate.raise"===e.type&&this.system.scheduler.schedule(this,this,e.event,Ut(t,e),e.id);this._pendingEffects=void 0}return this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._setErrorSnapshot(t),void this._error(t)}try{const[s,n]=e,o=Ft(n,this._actorScope);this.update(s,t),Kt(o,this._actorScope)}catch(t){return this._setErrorSnapshot(t),void this._error(t)}t.type===n&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===Wt.Stopped?this:(this.mailbox.clear(),this._processingStatus===Wt.NotStarted?(this._processingStatus=Wt.Stopped,this):(this.mailbox.enqueue({type:n}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){a(t)}this.observers.clear(),this.eventListeners.clear()}_error(t){if(this._stopProcedure(),this.observers.size){let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){a(t)}}this.observers.clear(),this.eventListeners.clear(),e&&a(t)}else this._parent||a(t),this.eventListeners.clear();var e;this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${e=this.id}`,error:t,actorId:e})}_stopProcedure(){this._processingStatus===Wt.Running&&(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._boundProcess),this._processingStatus=Wt.Stopped,this.system._unregister(this))}_send(t){this._processingStatus!==Wt.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$$type:Vt,id:this.id}}getPersistedSnapshot(t){const e=this.logic.getPersistedSnapshot(this._snapshot,t),s=this.system._snapshot._scheduledEvents;let n;const o=Date.now();for(const t in s){const e=s[t];e.source===this&&e.target===this&&(n??=[]).push({type:"@xstate.raise",event:e.event,id:e.id,delay:e.delay,startedAt:e.startedAt,elapsed:Math.max(0,o-e.startedAt)})}return n??=this._pendingEffects,n?{...e,_pendingEffects:n}:e}[h](){return this}getSnapshot(){return this._snapshot}}function Ut(t,e){if("function"==typeof t)return t(e);switch(t){case"restart":return e.delay;case"absolute":return Math.max(0,e.startedAt+e.delay-Date.now());default:return Math.max(0,e.delay-e.elapsed)}}function Ht(t,e){return new Gt(t,e)}const Xt=Ct({context:void 0,run:()=>{}});function Qt(){return Ht(Xt)}function Yt(t,{machine:e,context:s},n,o){return(i,r)=>{const c=((i,r)=>{if("string"==typeof i){const c=Pt(e,i);if(!c)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const a=Ht(c,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:"function"==typeof r?.input?r.input({context:s,event:n,self:t.self}):r?.input,src:i,registryKey:r?.registryKey});return o[a.id]=a,a}return Ht(i,{id:r?.id,parent:t.self,syncSnapshot:r?.syncSnapshot,input:r?.input,src:i,registryKey:r?.registryKey})})(i,r);return o[c.id]=c,t.defer(()=>{c._processingStatus!==Wt.Stopped&&c.start()}),c}}const Zt=new WeakMap;function te(t,e,s){let n=Zt.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},Zt.set(t,n)),n[e]}const ee={},se=["invoke","after","on","entry","exit","always","states","initial","onDone","timeout","onTimeout","history","target","output"];class ne{constructor(t,e){this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.invoke=void 0,this.on=void 0,this.after=void 0,this.events=void 0,this.ownEvents=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[];const s=this.config.states?Object.keys(this.config.states)[0]:void 0;if(this.id=this.config.id||[this.machine.id,...this.path].join("."),this.type=this.config.type||(void 0!==s?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,function(t){const e=t.config;if("choice"!==t.type){if(void 0!==e.choice)throw new Error(`State "${t.id}" has \`choice\`, but \`choice\` can only be used with \`type: 'choice'\`.`);return}if("function"!=typeof e.choice)throw new Error(`Choice state "${t.id}" must declare a \`choice\` function.`);for(const s of se)if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\`.`)}(this),this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?function(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}(this.config.states,(t,e)=>new ne(t,{_parent:this,_key:e,_machine:this.machine})):ee,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}".`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=this.config.entry,this.exit=this.config.exit,this.entry&&(this.entry._special=!0),this.exit&&(this.exit._special=!0),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=$t(t.tags).slice(),this.invoke=$t(this.config.invoke).map((t,e)=>{const{src:s,registryKey:n}=t,o=(i=this.id,`${e}.${i}`);var i;const r=t.id??o,c="string"==typeof s?s:`xstate.invoke.${o}`;return{...t,src:c,logic:s,id:r,registryKey:n}})}_initialize(){this.after=function(t){const e=t.config.after,s=t.config.timeout,n=t.config.onTimeout,r=t.invoke.filter(t=>void 0!==t.timeout);if(!e&&void 0===s&&0===r.length)return[];const c=[];if(e)for(const s of Object.keys(e)){const n=Number.isNaN(+s)?s:+s;c.push({event:o(n,t.id),delay:n,transitions:e[s],fromDelaysMap:!0})}var a;void 0!==s&&n&&c.push({event:(a=t.id,{type:`xstate.timeout.${a}`}),delay:s,transitions:n,fromDelaysMap:!0});for(const t of r)c.push({event:i(t.id),delay:t.timeout,transitions:t.onTimeout,fromDelaysMap:!1});const h=[];for(const{event:e,delay:s,transitions:n,fromDelaysMap:o}of c){const i=z(t,e,e=>j(s,o?e.delays:{},{context:e.context,event:e.event,stateNode:t}));for(const t of Tt(n))h.push({...t,event:i,delay:s})}return h.map(e=>({...D(t,e.event,e),delay:e.delay}))}(this),this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(""===s)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,oe(n,e=>D(t,s,e)))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,oe(t.config.onDone,e=>D(t,s,e)))}const s=(e,s)=>D(t,e,{to:(t,e)=>(e.cancel(s),{})}),n=(e,s,n)=>{const{target:o,to:i,reenter:r,...c}=s;return D(t,e,{...c,reenter:r,to:(t,e)=>{if(i){let s=!1;const o=new Proxy(e,{apply:(t,e,n)=>(s=!0,Reflect.apply(t,e,n)),get(t,e,n){const o=Reflect.get(t,e,n);return"function"!=typeof o?o:(...e)=>(s=!0,o.apply(t,e))}}),r=i(t,o);return(void 0!==r||s)&&e.cancel(n),r}return e.cancel(n),{target:o,reenter:r}}})};for(const o of t.invoke){const r=void 0!==o.timeout?i(o.id).type:void 0;if(o.onDone){const i=`xstate.done.actor.${o.id}`,c=oe(o.onDone,e=>r?n(i,e,r):D(t,i,e));r&&c.push(s(i,r)),e.set(i,c)}else if(r){const t=`xstate.done.actor.${o.id}`;e.set(t,[s(t,r)])}if(o.onError){const s=`xstate.error.actor.${o.id}`;e.set(s,oe(o.onError,e=>r?n(s,e,r):D(t,s,e)))}if(o.onSnapshot){const s=`xstate.snapshot.${o.id}`;e.set(s,oe(o.onSnapshot,e=>D(t,s,e)))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),"choice"===this.type?this.always=function(t){const e=t.config.choice,s=e=>{if(!e||void 0===e.target)throw new Error(`Choice state "${t.id}" must resolve to a target.`);for(const s of["actions","to","context"])if(void 0!==e[s])throw new Error(`Choice state "${t.id}" cannot declare \`${s}\` on a choice.`);return e};return[D(t,"",{to:t=>s(e(t))})]}(this):this.config.always&&(this.always=oe(this.config.always,t=>D(this,"",t)));for(const t of Object.keys(this.states))this.states[t]._initialize();this._refreshEventMetadata()}_refreshEventMetadata(){const t={},e=[];for(const[s,n]of this.transitions)t[s]=n.slice(),n.some(t=>t.target||t.reenter||t.to)&&e.push(s);this.on=t,this.ownEvents=e;const s=new Set(e);for(const t of Object.values(this.states))for(const e of t.events)s.add(e);this.events=Array.from(s)}get initial(){return te(this,"initial",()=>function(t,e){const s="object"==typeof e&&null!==e?e.target:e,n="object"==typeof e&&null!==e?e.input:void 0,o="string"==typeof s?t.states[s]:void 0;if(!o&&s)throw new Error(`Initial state node "${s}" not found on parent state node #${t.id}`);return{source:t,target:o?[o]:void 0,input:n}}(this,this.config.initial))}next(t,e,s){const n=e.type,o=te(this,`candidates-${n}`,()=>function(t,e){const s=t.transitions.get(e),n=[...t.transitions.keys()].filter(t=>t!==e&&zt(e,t)).sort((t,e)=>e.length-t.length).flatMap(e=>t.transitions.get(e));return s?[...s,...n]:n}(this,n));for(const n of o){if(rt(n,e,t,this,s))return[n]}}}function oe(t,e){const s=Tt(t),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=e(s[t]);return n}class ie{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.options=void 0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.internalEventDescriptors=void 0,this._json=void 0,this.id=t.id||"(machine)",this.implementations={actorSources:t.actorSources??{},actions:t.actions??{},delays:t.delays??{},guards:t.guards??{},...e},this.version=this.config.version,this.schemas=this.config.schemas,this.internalEventDescriptors=this.config.internalEvents??[],this.options={maxIterations:1/0,...this.config.options},this.transition=this.transition.bind(this),this.initialTransition=this.initialTransition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new ne(t,{_key:this.id,_machine:this}),this.root._initialize(),function(t){const e=[],s=n=>{Object.values(n).forEach(n=>{if(n.config.route&&n.config.id){const o=n.config.id,i=n.config.route,r=({event:t})=>t.to===`#${o}`;if("function"==typeof i)return e.push(D(t,"xstate.route",{guard:r,to:t=>{const e=i(t);if(e)return{...!0===e?{}:e,target:`#${o}`}}})),void(n.states&&s(n.states));if("$unserializable"in i)throw new Error(`State "${n.id}" has a route that is not serializable. Re-provide the route function when reviving this machine.`);const{guard:c,...a}=i,h={...a,guard:r,target:`#${o}`};e.push(D(t,"xstate.route",h))}n.states&&s(n.states)})};s(t.states),e.length>0&&t.transitions.set("xstate.route",e)}(this.root),this.root._refreshEventMetadata(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actorSources:n,delays:o}=this.implementations,i=new ie(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actorSources:{...n,...t.actorSources},delays:{...o,...t.delays}});return i._json=this._json,i}resolveState(t){const e=(s=this.root,n=t.value,A(s,M(W(s,n))));var s,n;const o=M(W(this.root,e));return mt({_nodes:[...o],value:e,context:t.context||{},children:{},status:P(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){const{snapshot:n,microsteps:o}=et(t,e,s,[]);return[n,o.flatMap(([,t])=>t)]}microstep(t,e,s){const{microsteps:n}=et(t,e,s,[]),o=new Array(n.length);for(let t=0;t<n.length;t++)o[t]=n[t][0];return o}getTransitionData(t,e,s){return L(this.root,t.value,t,e,s)||[]}isInternalEventType(t){for(const e of this.internalEventDescriptors)if(zt(t,e))return!0;return!1}_getPreInitialState(t,e){const{context:s}=this.config,n=mt({context:"function"!=typeof s&&s?s:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof s){const o={},i=s({spawn:Yt(t,n,e,o),input:e.input,self:t.self,actorSources:this.implementations.actorSources}),[r]=w(n,e,t,[]);return i&&(r.context=i),Object.keys(o).length>0&&(r.children={...r.children,...o}),r}return n}getInitialSnapshot(t,e){return this.initialTransition(e,t)[0]}initialTransition(t,e){const s=c(t),n=[],o=this._getPreInitialState(e,s),[i,r]=function(t,e,s,n,o){return Z([{target:[...C(t)],source:t,reenter:!0,eventType:null,toJSON:null}],e,s,n,!0,o)}(this.root,o,e,s,n),{snapshot:a,microsteps:h}=et(i,s,e,n);return[a,[...r,...h.flatMap(([,t])=>t)]]}start(t){if(t?.children)for(const e of Object.values(t.children))e._rehydrated&&"active"===e.getSnapshot?.().status&&e.start()}getStateNodeById(t){const e=wt(t),s=e.slice(1),n=N(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return V(o,s)}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,_stateInputs:n,tags:o,machine:i,children:r,context:c,can:a,hasTag:h,matches:u,getMeta:f,getInputs:p,toJSON:l,...d}=t,y={};for(const t in r){const s=r[t];y[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,registryKey:s.registryKey,syncSnapshot:s._syncSnapshot}}const g={...d,context:xt(c),children:y,historyValue:St(d.historyValue)};return void 0!==i.version&&(g.version=i.version),g}(t,e)}restoreSnapshot(t,e){const s=t.version;if(s!==this.version){const e=this.config.migrate;if("function"!=typeof e)throw new Error(`Persisted snapshot version '${s}' does not match machine version '${this.version}'.`);t=e(t,s)}const n=t,o={},i=n.children;for(const t of Object.keys(i)){const s=i[t],n=s.snapshot,r=s.src,c="string"==typeof r?Pt(this,r):r;if(!c)continue;const a=Ht(c,{id:t,parent:e.self,syncSnapshot:s.syncSnapshot,snapshot:n,src:r,registryKey:s.registryKey});a._rehydrated=!0,o[t]=a}const r=(t=>{if(!t||"object"!=typeof t)return{};const e={};for(const s of Object.keys(t)){const n=t[s];for(const t of n){let n;if(t instanceof ne)n=t;else try{n=this.root.machine.getStateNodeById(t.id)}catch{}n&&(e[s]??=[],e[s].push(n))}}return e})(n.historyValue),c=Array.from(M(W(this.root,n.value))),{version:a,...h}=t,u=mt({...h,children:o,_nodes:c,value:n.value,historyValue:r},this),f=new WeakSet;return function t(e){if(!f.has(e)){f.add(e);for(const s of Object.keys(e)){const n=e[s];if(n&&"object"==typeof n){if("xstate$$type"in n&&n.xstate$$type===Vt){e[s]=o[n.id];continue}t(n)}}}}(u.context),u}}function re(t){return JSON.stringify(t)}function ce(t){const e=Object.keys(t.context).length?`(${JSON.stringify(t.context)})`:"",s=t._nodes.filter(t=>"atomic"===t.type||"final"===t.type).map(({id:e,path:s})=>{const n=t.getMeta()[e];if(!n)return`"${s.join(".")}"`;const{description:o}=n;return"function"==typeof o?o(t):o?`"${o}"`:JSON.stringify(t.value)});return`state${1===s.length?"":"s"} `+s.join(", ")+` ${e}`.trim()}const ae=()=>(t,e)=>ke(t,e),he=()=>(t,e)=>$e(t,e);class ue{getDefaultOptions(){return{serializeState:t=>re(t),serializeEvent:t=>re(t),serializeTransition:(t,e)=>`${re(t)}|${e?.type}`,events:[],stateMatcher:(t,e)=>"*"===e,logger:{log:console.log.bind(console),error:console.error.bind(console)}}}constructor(t,e){this.testLogic=t,this.options=void 0,this.defaultTraversalOptions=void 0,this._toTestPath=t=>{const e=t.steps.map(t=>function(t){const{type:e,...s}=t;return`${e}${Object.keys(s).length?` (${JSON.stringify(s)})`:""}`}(t.event)).join(" → ");return{...t,test:e=>this.testPath(t,e),description:ct(t.state)?`Reaches ${ce(t.state).trim()}: ${e}`:JSON.stringify(t.state)}},this.options={...this.getDefaultOptions(),...e}}getPaths(t,e){const s=e?.allowDuplicatePaths??!1,n=t(this.testLogic,this._resolveOptions(e));return(s?n:((t,e=re)=>{const s=[];t.forEach(t=>{s.push({path:t,eventSequence:t.steps.map(t=>e(t.event))})}),s.sort((t,e)=>e.path.steps.length-t.path.steps.length);const n=[];t:for(const t of s){e:for(const e of n){for(const s in t.eventSequence)if(t.eventSequence[s]!==e.eventSequence[s])continue e;continue t}n.push(t)}return n.map(t=>t.path)})(n)).map(this._toTestPath)}getShortestPaths(t){return this.getPaths(ae(),t)}getShortestPathsFrom(t,e){const s=[];for(const n of t){const t=this.getShortestPaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getSimplePaths(t){return this.getPaths(he(),t)}getSimplePathsFrom(t,e){const s=[];for(const n of t){const t=this.getSimplePaths({...e,fromState:n.state});for(const e of t)s.push(this._toTestPath(Se(n,e)))}return s}getPathsFromEvents(t,e){return Ee(this.testLogic,t,e).map(this._toTestPath)}getAdjacencyMap(){return be(this.testLogic,this.options)}async testPath(t,e,s){const n={steps:[],state:{error:null}};try{for(const o of t.steps){const t={step:o,state:{error:null},event:{error:null}};n.steps.push(t);try{await this.testTransition(e,o)}catch(e){throw t.event.error=e,e}try{await this.testState(e,o.state,s)}catch(e){throw t.state.error=e,e}}}catch(e){throw e.message+=function(t,e,s){const n={formatColor:(t,e)=>e,serializeState:re,serializeEvent:re,...s},{formatColor:o,serializeState:i,serializeEvent:r}=n,{state:c}=t,a=i(c,t.steps.length?t.steps[t.steps.length-1].event:void 0);let h="",u=!1;return h+="\nPath:\n"+e.steps.map((t,e,s)=>{const n=i(t.step.state,e>0?s[e-1].step.event:void 0),c=r(t.step.event);return[`\tState: ${u?o("gray",n):t.state.error?(u=!0,o("redBright",n)):o("greenBright",n)}`,`\tEvent: ${u?o("gray",c):t.event.error?(u=!0,o("red",c)):o("green",c)}`].join("\n")}).concat(`\tState: ${u?o("gray",a):e.state.error?o("red",a):o("green",a)}`).join("\n\n"),h}(t,n,this.options),e}return n}async testState(t,e,s){const n=this._resolveOptions(s),o=this._getStateTestKeys(t,e,n);for(const s of o)await(t.states?.[s](e))}_getStateTestKeys(t,e,s){const n=t.states||{},o=Object.keys(n).filter(t=>s.stateMatcher(e,t));return!o.length&&"*"in n&&o.push("*"),o}_getEventExec(t,e){const s=t.events?.[e.event.type];return s}async testTransition(t,e){const s=this._getEventExec(t,e);await(s?.(e))}_resolveOptions(t){return{...this.defaultTraversalOptions,...this.options,...t}}}function fe(t,e){if(t===e)return!0;if(void 0===t||void 0===e)return!1;if("string"==typeof t||"string"==typeof e)return t===e;const s=Object.keys(t),n=Object.keys(e);return s.length===n.length&&s.every(s=>fe(t[s],e[s]))}function pe(t,e,s,{serializeEvent:n}){if(!e||s&&fe(s.value,t.value))return"";const o=s?` from ${re(s.value)}`:"";return` via ${n(e)}${o}`}function le(){const t=Qt();return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function de(t){if(!t.states)return[];return Object.keys(t.states).map(e=>t.states[e])}function ye(t){const{value:e,context:s}=t;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0})}function ge(t){return JSON.stringify(t)}function ve(t,e){const{events:s,...n}=e??{};return{serializeState:ye,serializeEvent:ge,events:t=>{const e="function"==typeof s?s(t):s??[];return Nt(t).flatMap(t=>{const s=e.filter(e=>e.type===t);return s.length?s:[{type:t}]})},fromState:t.getInitialSnapshot(le(),e?.input),...n}}function me(){return{serializeState:t=>JSON.stringify(t),serializeEvent:ge}}function _e(t,e,s){const n=s??(function(t){return"getStateNodeById"in t}(t)?ve(t,e):void 0);return{serializeState:e?.serializeState??n?.serializeState??(t=>JSON.stringify(t)),serializeEvent:ge,events:[],filterEvents:void 0,limit:1/0,fromState:void 0,toState:void 0,stopWhen:e?.toState,...n,...e}}function Se(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}}function xe(t){return Array.isArray(t)?t[0]:t}function be(t,e){const{transition:s}=t,{serializeEvent:n,serializeState:o,events:i,filterEvents:r,limit:c,fromState:a,stopWhen:h}=_e(t,e),u=le(),f={};let p=0;const l=[{nextState:a??t.getInitialSnapshot(u,e.input),event:void 0,prevState:void 0}],d=new Map;for(;l.length;){const{nextState:t,event:e,prevState:a}=l.shift();if(p++>c)throw new Error("Traversal limit exceeded");const y=o(t,e,a);if(f[y])continue;if(d.set(y,t),f[y]={state:t,transitions:{}},h&&h(t))continue;const g="function"==typeof i?i(t):i;for(const e of g){if(r&&!r(t,e))continue;const o=xe(s(t,e,u));f[y].transitions[n(e)]={event:e,state:o},l.push({nextState:o,event:e,prevState:t})}}return f}function we(t){let e=[];if(t.steps.length){for(let n=0;n<t.steps.length;n++){const o=t.steps[n];e.push({state:o.state,event:0===n?{type:s}:t.steps[n-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:s}}];return{...t,steps:e}}function Ee(t,e,s){const n=_e(t,{events:e,...s},(o=t)&&o instanceof ie?ve(t):me());var o;const i=le(),r=n.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:c,serializeEvent:a}=n,h=be(t,n),u=new Map,f=[],p=c(r,void 0,void 0);u.set(p,r);let l=p,d=r;for(const t of e){f.push({state:u.get(l),event:t});const e=a(t),{state:s,event:n}=h[l].transitions[e];if(!s)throw new Error(`Invalid transition from ${l} with ${e}`);const o=c(s,t,u.get(l));u.set(o,s),l=o,d=s}return n.toState&&!n.toState(d)?[]:[we({state:d,steps:f,weight:f.length})]}function ke(t,e){const s=_e(t,e),n=s.serializeState,o=s.fromState??t.getInitialSnapshot(le(),e?.input),i=be(t,s),r=new Map,c=new Map,a=n(o,void 0,void 0);c.set(a,o),r.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=r.get(t);for(const o of Object.keys(i[t].transitions)){const{state:a,event:f}=i[t].transitions[o],p=n(a,f,e);if(c.set(p,a),r.has(p)){const{weight:e}=r.get(p);e>s+1&&r.set(p,{weight:s+1,state:t,event:f})}else r.set(p,{weight:s+1,state:t,event:f});u.has(p)||h.add(p)}u.add(t),h.delete(t)}const f={},p=[];return r.forEach(({weight:t,state:e,event:s},n)=>{const o=c.get(n),i=e?f[e].paths[0].steps.concat({state:c.get(e),event:s}):[];p.push({state:o,steps:i,weight:t}),f[n]={state:o,paths:[{state:o,steps:i,weight:t}]}}),s.toState?p.filter(t=>s.toState(t.state)).map(we):p.map(we)}function $e(t,e){const s=_e(t,e),n=le(),o=s.fromState??t.getInitialSnapshot(n,e?.input),i=s.serializeState,r=be(t,s),c=new Map,a={vertices:new Set,edges:new Set},h=[],u={};function f(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],n={state:s,weight:h.length,steps:[...h]};t.paths.push(n)}else{if(!r[t])return;for(const s of Object.keys(r[t].transitions)){const{state:n,event:o}=r[t].transitions[s];if(!(s in r[t].transitions))continue;const u=c.get(t),p=i(n,o,u);c.set(p,n),a.vertices.has(p)||(a.edges.add(s),h.push({state:c.get(t),event:o}),f(p,e))}}h.pop(),a.vertices.delete(t)}const p=i(o,void 0);c.set(p,o);for(const t of Object.keys(r))f(p,t);const l=Object.values(u).flatMap(t=>t.paths);return s.toState?l.filter(t=>s.toState(t.state)).map(we):l.map(we)}t.TestModel=ue,t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.createShortestPathsGen=ae,t.createSimplePathsGen=he,t.createTestModel=function(t,e){(t=>{t.root})(t);const s=e?.serializeEvent??re,n=e?.serializeTransition??pe,{events:o,...i}=e??{};return new ue(t,{serializeState:(t,e,o)=>`${ye(t)}${n(t,e,o,{serializeEvent:s})}`,stateMatcher:(e,s)=>s.startsWith("#")?e._nodes.includes(t.getStateNodeById(s)):e.matches(s),events:t=>{const e="function"==typeof o?o(t):o??[];return Nt(t).flatMap(t=>e.some(e=>e.type===t)?e.filter(e=>e.type===t):[{type:t}])},...i})},t.getAdjacencyMap=be,t.getPathsFromEvents=Ee,t.getShortestPaths=ke,t.getSimplePaths=$e,t.getStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,n)=>{const o=s[n],i=t(o);return e.push(o,...i),e},[])},t.joinPaths=Se,t.serializeSnapshot=ye,t.toDirectedGraph=function t(e){const s=e instanceof ie?e.root:e,n=[...s.transitions.values()].flat().flatMap((t,e)=>(t.target?t.target:[s]).map((n,o)=>{const i={id:`${s.id}:${e}:${o}`,source:s,target:n,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=i;return{source:s.id,target:n.id,label:t}}};return i})),o={id:s.id,stateNode:s,children:de(s).map(t),edges:n,toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateGraph={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const r="xstate.init",i="xstate.stop",n="@xstate.terminate",o="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",h="xstate.logic.effect.start";function u(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function d(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function l(t){return new Error(e(50,...void 0===t.incarnation?[t.$actor]:[t.$actor,t.incarnation]))}function p(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function f(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const _=new WeakMap;async function v(t,s,r,i=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const o=_.get(t)?.get(s);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let u,d;const l=new Promise((t,e)=>{u=t,d=e});let p,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,l);const v=()=>{p?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return l.then(v,v),p=t.subscribe({error:d,complete:()=>d(new Error(e(72,s)))}),(async()=>{try{i({type:h,key:s});const e=await r();"active"===t.getSnapshot().status&&(i({type:c,key:s,output:e}),u(e))}catch(e){"active"===t.getSnapshot().status&&i({type:a,key:s,error:e}),d(e)}})().catch(d),l}function y(t,s,r){const i=function(t,s,r){const i=s;if(t!==s&&i.logic?.isInternalEventType?.(r.type))return new Error(e(73,r.type,s.id))}(t,s,r);return!!i&&(s.system.deadLetter(t,s,r,"internalEvent",{error:i}),!0)}class g{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}}function m(t){return{type:r,input:t}}function S(t){setTimeout(()=>{throw t})}const b="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],w=new Error("Transition effect");function A(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function E(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:A(t.event)??t.event}}function O(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",A(t.event)??t.event])}(e)}`}function k(t=this.source.system){return f(this.source,this.event,t)}function I(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function j(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:I,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function T(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function R(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 M(t=this.source.system){return function(t){if("string"==typeof t)throw new Error(e(70,t))}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,E(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function $(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:M,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function z(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const r="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},i=[t.self,r];return{kind:"builtin",exec:R,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function P(t,e,[s,r]){const i="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===n);return!i||o||c?[s,r]:[s,[...r,z(t,s)]]}const L=new WeakMap,N=new WeakMap,K=new Map;function q(t){t._snapshotVersion++}function U(t){return t._snapshotVersion}function D(t){const e=L.get(t);if(e)return e;const s=N.get(t);if(!s)return;const r=s();return L.set(t,r),N.delete(t),r}function C(t,e,s=e.system,r){N.delete(t);const i=U(s),n=r?D(r):void 0,o=n?.actor===e?n:D(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void L.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??K:t.keyedActors}(s);let u=h.size?new Map(h):K;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(u===K&&(u=new Map),u.set(t,e))}L.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function J(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}function V(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}function W(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function B(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function F(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),r=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],i=r[t];if("*"===e){return t===s.length-1}if(e!==i)return!1}return!0}let H;Object.freeze({}),Object.freeze([]);let G=0;function X(){return H??=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)}`}(),`${H}:${(G++).toString(36)}`}function Q(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Y(t,e){return`${t?t.address:""}|${e}`}function Z(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},q(t))}function tt(t,e,s){if(void 0!==e){const r=function(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}(e);return r?Z(t,Y(s?.parent,r.prefix),r.index+1):s?.parent||Z(t,Y(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Y(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return Z(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const et=Object.freeze({});function st(t,e){return O(t,e)}function rt(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class it{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={executionId:X(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=void 0;this._snapshot={_scheduledTimers:et,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=st(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}const n=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:n,dueAt:n+s};this._snapshot._scheduledTimers===et&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,q(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],q(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=st(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==et&&delete this._snapshot._scheduledTimers[s],q(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(u(e)){const r=e,i=t?.system,n=i&&p(i,r);if(!n){const e=l(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:d(r.$actor),error:e})}e=n}if(y(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),q(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_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&&q(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const r=this._keyedActors?.get(t);if(r&&r!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),r!==s&&q(this)}inspect(t){const e=V(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){S(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){S(t)}})}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);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(u(e)){const r=p(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:d(e.$actor),error:l(e)})}if(y(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(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,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){S(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):v(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(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(!function(t){let e=!1,s=!1;for(const r of x)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw w;return e}(e))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:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let nt=!1;const ot=Object.freeze([]),ct={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[o]:!0};let at=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ht=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ut(t,e){try{t?.(e)}catch(t){S(t)}}function dt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new pt(t,e)}class pt{get address(){return this._address??=this._parent?`${this._parent.address}/${Q(this.id)}`:Q(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._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=at.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,this._warnedUnhandledTypes=void 0;const s=e?{...ht,...e}:ht,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new it(t,e)}(this,{clock:r,logger:i,createActorRef:lt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(V(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=tt(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=s._restore;this._restored=void 0!==d;try{if(d)this._setSnapshot(d.restore(this._actorScope));else if(e?._inert);else{const[t,e]=P(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(d?.error?.(t)??{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=>f(this,t,this.system);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===at.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=nt;try{nt=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==at.Stopped&&this._recoverOrError(t)})}finally{nt=e}};this._processingStatus!==at.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,C(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=P(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),dt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??ot)ut(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}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??ot,actions:this._collectedActions??ot,sent:this._collectedSent??ot,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 dt(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 r=V(t,e,s);if(this._processingStatus!==at.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":ut(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),ut(r.error,t)):S(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}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,r,i)=>{const n=V(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===at.Running)return this;if(this._processingStatus===at.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}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=at.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;case"stopped":return this._stopProcedure(),this._complete(),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 r=L.get(t),i=U(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!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 r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,E(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=P(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let o=this._snapshot;try{const[n,c]=r;n!==s||c.length||!("machine"in s)||t.type===i||e&&Object.hasOwn(ct,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),dt(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===i&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){ut(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ut(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,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===at.Stopped?this:(this.mailbox?.clear(),this._processingStatus===at.NotStarted?(this._processingStatus=at.Stopped,this.system._unregister(this),this):(this._send({type:i}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??ot)ut(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||S(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(S)}catch(i){S(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),ut(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===at.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=at.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===at.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new g(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[b](){return this}getSnapshot(){return this._snapshot}}function ft(t,...[r]){return function(t){if(t&&"object"==typeof t)for(const r of Object.keys(t))if(!s.has(r))throw new Error(e(8,r))}(r),new pt(t,r)}function _t(t,e){const s=t.check(e);if(s)throw s}const vt=new WeakMap;function yt(t,e,s){const r=function(t){let e=vt.get(t);return e||(e=new Map,vt.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function gt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[T("@xstate.cleanup",()=>function(t){const e=vt.get(t);if(!e)return;let s;vt.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===h)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=[],u=Object.create(null),d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:k,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push($(n,e,t))},raise:t=>{o.push($(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const c=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!c||s.type===r&&"active"===c.status)&&(o.push(T("@xstate.effect",(e=n.self.system)=>yt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(T("@xstate.effect",(t=n.self.system)=>yt(n.self,void 0,()=>c(t))))}},l=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),p={...e,...l||{}};return("context"in e||void 0!==l?.context)&&(p.context=l?.context??e.context),(l?.effects||Object.keys(u).length)&&(p.effects={...e.effects,...l?.effects,...u}),P(n,e,[p,o])},s=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:o});if(c)return[s,[j(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&_t(t.validator,{kind:"result",logic:n,snapshot:o[0],effects:o[1]}),o},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,m(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&_t(t.validator,{kind:"input",logic:n,input:e});const i=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==i&&(o.context=i),s({...o},m(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const mt=gt({context:void 0,run:()=>{}});function St(){const t=ft(mt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function bt(t){const{value:e,context:s}=t,r=J(t)?t:void 0,i=r?.getInputs(),n=r?.historyValue;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0,stateInputs:i&&Object.keys(i).length?i:void 0,historyValue:n&&Object.keys(n).length?Object.fromEntries(Object.entries(n).map(([t,e])=>[t,e.map(t=>t.id)])):void 0})}function xt(t){return JSON.stringify(t)}function wt(t){if(!t||"object"!=typeof t)return!1;const e=t,s=e.root;return!!s&&"object"==typeof s&&"string"==typeof s.id&&"object"==typeof s.states&&"function"==typeof s.transitions?.values&&"function"==typeof e.getStateNodeById&&"function"==typeof e.resolveState&&"function"==typeof e.getTransitionData}function At(t,e,s){const r=s??(wt(t)?(i=t,n=e,{serializeState:bt,serializeEvent:xt,...n,events:t=>W(t),fromState:n?.fromState??i.getInitialSnapshot(St(),n?.input)}):void 0);var i,n;const o=e?.serializeState??r?.serializeState??(t=>JSON.stringify(t)),c=e?.events??r?.events??[];return{serializeState:o,serializeEvent:xt,filterEvents:void 0,limit:1/0,toState:void 0,stopWhen:e?.toState,...r,...e,events:"function"==typeof c||Array.isArray(c)?c:t=>function(t,e,s){const r=[],i=t,n=Object.entries(i).filter(([,t])=>void 0!==t),o=t=>!s||s.some(e=>F(t,e.type));for(const[t,i]of n){if(!o(t))continue;const n="function"==typeof i?i(e):i;if(!Array.isArray(n)||!n.length)throw new Error(`Event cases for "${t}" must be a non-empty array`);for(const e of n){const i={...e,type:t};s&&!s.some(({type:e,...s})=>F(t,e)&&B(i,s))||r.push(i)}}return[...r,...s?.filter(t=>!n.some(([e])=>e===t.type))??[]]}(c,t,J(t)?W(t):void 0),fromState:e?.fromState??r?.fromState}}function Et(t,e,s){return new Error(`Unable to evaluate graph transition from state ${t} with event ${e}. If the transition needs event payloads, provide representative events using the "events" option.`,{cause:s})}function Ot(t){return Array.isArray(t)?t[0]:t}function kt(t,e){const{transition:s}=t,{serializeEvent:r,serializeState:i,events:n,filterEvents:o,limit:c,fromState:a,stopWhen:h}=At(t,e),u=St(),d=a??t.getInitialSnapshot(u,e?.input),l=Object.create(null);let p=0;const f=[{nextState:d,event:void 0,prevState:void 0}];for(let t=0;t<f.length;t++){const{nextState:e,event:a,prevState:d}=f[t];if(t>4096&&2*t>f.length&&(f.splice(0,t+1),t=-1),p++>c)throw new Error("Traversal limit exceeded");const _=i(e,a,d);if(l[_])continue;if(l[_]={state:e,transitions:Object.create(null)},h&&h(e))continue;const v="function"==typeof n?n(e):n;for(const t of v){if(o&&!o(e,t))continue;const i=r(t);let n;try{n=Ot(s(e,t,u))}catch(t){throw Et(_,i,t)}l[_].transitions[i]={event:t,state:n},f.push({nextState:n,event:t,prevState:e})}}return l}function It(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const i=t.steps[s];e.push({state:i.state,event:0===s?{type:r}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:r}}];return{...t,steps:e}}t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.getAdjacencyMap=kt,t.getAllOwnEvents=W,t.getDescendantStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,r)=>{const i=s[r],n=t(i);return e.push(i,...n),e},[])},t.getPathsFromEvents=function(t,e,s){const r=At(t,{events:e,...s}),i=St(),n=r.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:o,serializeEvent:c,filterEvents:a,stopWhen:h,limit:u}=r,d=[];let l=n,p=o(l,void 0,void 0);for(const r of e){if(d.length>=u)throw new Error("Traversal limit exceeded");const e=c(r);let n,f=r;if(void 0!==s?.events){const t="function"==typeof s.events?s.events(l):s.events;f=void 0;for(let s=t.length-1;s>=0;s--){const r=t[s];if((!a||a(l,r))&&c(r)===e){f=r;break}}}else a&&!a(l,r)&&(f=void 0);if(!f||h?.(l))throw new Error(`Invalid transition from ${p} with ${e}`);d.push({state:l,event:r});try{n=t.transition(l,f,i)}catch(t){throw Et(p,e,t)}const _=Array.isArray(n)?n[0]:n;p=o(_,r,l),l=_}return r.toState&&!r.toState(l)?[]:[It({state:l,steps:d,weight:d.length})]},t.getShortestPaths=function(t,e){const s=At(t,e),r=s.serializeState,i=s.fromState??t.getInitialSnapshot(St(),e?.input),n=kt(t,{...s,fromState:i}),o=new Map,c=new Map,a=r(i,void 0,void 0);c.set(a,i),o.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=o.get(t);for(const i of Object.keys(n[t].transitions)){const{state:a,event:d}=n[t].transitions[i],l=r(a,d,e);if(c.set(l,a),o.has(l)){const{weight:e}=o.get(l);e>s+1&&o.set(l,{weight:s+1,state:t,event:d})}else o.set(l,{weight:s+1,state:t,event:d});u.has(l)||h.add(l)}u.add(t),h.delete(t)}const d=Object.create(null),l=[];return o.forEach(({weight:t,state:e,event:s},r)=>{const i=c.get(r),n=void 0===e?[]:d[e].paths[0].steps.concat({state:c.get(e),event:s});l.push({state:i,steps:n,weight:t}),d[r]={state:i,paths:[{state:i,steps:n,weight:t}]}}),s.toState?l.filter(t=>s.toState(t.state)).map(It):l.map(It)},t.getSimplePaths=function(t,e){const s=At(t,e),r=St(),i=s.fromState??t.getInitialSnapshot(r,e?.input),n=s.serializeState,o=kt(t,{...s,fromState:i}),c=new Map,a={vertices:new Set,edges:new Set},h=[],u=Object.create(null);function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],r={state:s,weight:h.length,steps:[...h]};t.paths.push(r)}else{if(!o[t])return;for(const s of Object.keys(o[t].transitions)){const{state:r,event:i}=o[t].transitions[s];if(!(s in o[t].transitions))continue;const u=c.get(t),l=n(r,i,u);c.set(l,r),a.vertices.has(l)||(a.edges.add(s),h.push({state:c.get(t),event:i}),d(l,e))}}h.pop(),a.vertices.delete(t)}const l=n(i,void 0);c.set(l,i);for(const t of Object.keys(o))d(l,t);const p=Object.values(u).flatMap(t=>t.paths);return s.toState?p.filter(t=>s.toState(t.state)).map(It):p.map(It)},t.joinPaths=function(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}},t.serializeSnapshot=bt,t.toDirectedGraph=function t(e){const s=wt(e)?e.root:e,r=[],i=[...[...s.transitions.values()].flat(),...s.always??[]].flatMap((t,e)=>{t.to&&r.push({code:"dynamic-target",stateId:s.id,eventType:t.eventType,transitionId:`${s.id}:${e}`,message:"Transition function destinations require execution or source analysis."});return(t.target??(t.to?[]:[s])).map((r,i)=>{const n={id:`${s.id}:${e}:${i}`,source:s,target:r,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=n;return{source:s.id,target:r.id,label:t}}};return n})}),n=function(t){return t.states?Object.keys(t.states).map(e=>t.states[e]):[]}(s).map(t);r.push(...n.flatMap(t=>t.analysis.diagnostics));const o={id:s.id,stateNode:s,children:n,edges:i,analysis:{transitionTargetsComplete:0===r.length,diagnostics:r},toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s,analysis:o.analysis}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-graph.umd.min.js.map
|