xstate 6.0.0-alpha.49 → 6.0.0-alpha.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/{StateMachine-0adb3a70.cjs.js → StateMachine-1e6ee14a.cjs.js} +18 -6
  2. package/dist/{StateMachine-29450e6d.development.cjs.js → StateMachine-70df737c.development.cjs.js} +18 -6
  3. package/dist/{StateMachine-2af31c11.esm.js → StateMachine-8cea8974.esm.js} +18 -6
  4. package/dist/{StateMachine-faf50c5c.development.esm.js → StateMachine-bc28e207.development.esm.js} +18 -6
  5. package/dist/{createActor-b4dd05ae.cjs.js → createActor-27fd819f.cjs.js} +80 -10
  6. package/dist/{createActor-88709f74.development.esm.js → createActor-74e185ee.development.esm.js} +80 -11
  7. package/dist/{createActor-268165d4.esm.js → createActor-ad3a1abe.esm.js} +80 -11
  8. package/dist/{createActor-a1e0dffb.development.cjs.js → createActor-ea9a560c.development.cjs.js} +80 -10
  9. package/dist/declarations/src/effectDescriptor.d.ts +9 -0
  10. package/dist/declarations/src/index.d.ts +1 -1
  11. package/dist/declarations/src/inspection.d.ts +24 -7
  12. package/dist/declarations/src/runtimeHelpers.d.ts +6 -3
  13. package/dist/declarations/src/system.d.ts +38 -3
  14. package/dist/declarations/src/types.d.ts +35 -2
  15. package/dist/{effectDescriptor-7ff6802f.development.cjs.js → effectDescriptor-16b6f3b4.cjs.js} +12 -1
  16. package/dist/{effectDescriptor-39d22100.development.esm.js → effectDescriptor-38598bd3.development.esm.js} +12 -1
  17. package/dist/{effectDescriptor-be348e50.cjs.js → effectDescriptor-40ca302f.development.cjs.js} +12 -1
  18. package/dist/{effectDescriptor-30c9a744.esm.js → effectDescriptor-7dac431a.esm.js} +12 -1
  19. package/dist/{fsm-e18a7cb4.development.esm.js → fsm-25f10f50.development.esm.js} +1 -1
  20. package/dist/{fsm-c1316948.development.cjs.js → fsm-697ffd89.development.cjs.js} +1 -1
  21. package/dist/{fsm-7a2e9697.cjs.js → fsm-7adaf0ea.cjs.js} +1 -1
  22. package/dist/{fsm-b804b3e9.esm.js → fsm-dc1bb88b.esm.js} +1 -1
  23. package/dist/{types-fbabaeee.cjs.js → types-a14db10c.development.cjs.js} +6 -1
  24. package/dist/{types-3c3455f7.esm.js → types-a313e7e2.esm.js} +6 -1
  25. package/dist/{types-b3fea5bd.development.cjs.js → types-bc22b358.cjs.js} +6 -1
  26. package/dist/{types-adda3842.development.esm.js → types-c37714eb.development.esm.js} +6 -1
  27. package/dist/xstate-actors.cjs.js +12 -3
  28. package/dist/xstate-actors.development.cjs.js +12 -3
  29. package/dist/xstate-actors.development.esm.js +13 -4
  30. package/dist/xstate-actors.esm.js +13 -4
  31. package/dist/xstate-actors.umd.min.js +1 -1
  32. package/dist/xstate-actors.umd.min.js.map +1 -1
  33. package/dist/xstate-durable.cjs.js +2 -2
  34. package/dist/xstate-durable.development.cjs.js +2 -2
  35. package/dist/xstate-durable.development.esm.js +2 -2
  36. package/dist/xstate-durable.esm.js +2 -2
  37. package/dist/xstate-durable.umd.min.js +1 -1
  38. package/dist/xstate-durable.umd.min.js.map +1 -1
  39. package/dist/xstate-fsm.cjs.js +2 -2
  40. package/dist/xstate-fsm.development.cjs.js +2 -2
  41. package/dist/xstate-fsm.development.esm.js +2 -2
  42. package/dist/xstate-fsm.esm.js +2 -2
  43. package/dist/xstate-graph.cjs.js +2 -2
  44. package/dist/xstate-graph.development.cjs.js +2 -2
  45. package/dist/xstate-graph.development.esm.js +2 -2
  46. package/dist/xstate-graph.esm.js +2 -2
  47. package/dist/xstate-graph.umd.min.js +1 -1
  48. package/dist/xstate-graph.umd.min.js.map +1 -1
  49. package/dist/xstate-scxml.cjs.js +3 -3
  50. package/dist/xstate-scxml.development.cjs.js +3 -3
  51. package/dist/xstate-scxml.development.esm.js +3 -3
  52. package/dist/xstate-scxml.esm.js +3 -3
  53. package/dist/xstate-scxml.umd.min.js +1 -1
  54. package/dist/xstate-scxml.umd.min.js.map +1 -1
  55. package/dist/xstate-validation.cjs.js +1 -1
  56. package/dist/xstate-validation.development.cjs.js +1 -1
  57. package/dist/xstate-validation.development.esm.js +1 -1
  58. package/dist/xstate-validation.esm.js +1 -1
  59. package/dist/xstate.cjs.js +5 -5
  60. package/dist/xstate.development.cjs.js +5 -5
  61. package/dist/xstate.development.esm.js +8 -8
  62. package/dist/xstate.esm.js +8 -8
  63. package/dist/xstate.umd.min.js +1 -1
  64. package/dist/xstate.umd.min.js.map +1 -1
  65. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { a5 as createInertActorScope, a6 as setInertActorScopeSnapshot, E as finalizeTransitionResult, a8 as attachSnapshotActorRef, y as createInitEvent, aw as hasAmbientInspector, a7 as beginSpawnAllocation, a9 as macrostep, al as createSpawnEffect, am as initialMicrostep, i as isAtomicStateNode, ax as getProperAncestors, ay as isRemoteActorRef, az as getActorIdPrefix } from './createActor-268165d4.esm.js';
1
+ import { a6 as createInertActorScope, a7 as setInertActorScopeSnapshot, F as finalizeTransitionResult, a9 as attachSnapshotActorRef, y as createInitEvent, ax as hasAmbientInspector, a8 as beginSpawnAllocation, aa as macrostep, am as createSpawnEffect, an as initialMicrostep, i as isAtomicStateNode, ay as getProperAncestors, az as isRemoteActorRef, aA as getActorIdPrefix } from './createActor-ad3a1abe.esm.js';
2
2
 
3
3
  function attachMicrostepActorRefs(microsteps, actorScope, inputSnapshot) {
4
4
  if (!microsteps.length) {
@@ -265,6 +265,17 @@ function getEffectDescriptor(effect) {
265
265
  output: effect.output,
266
266
  error: effect.error
267
267
  };
268
+ case '@xstate.deadLetter':
269
+ return {
270
+ kind: 'builtin',
271
+ type: '@xstate.deadLetter',
272
+ source: effect.source?.address,
273
+ target: effect.target.address,
274
+ event: effect.event,
275
+ reason: effect.reason,
276
+ issues: effect.detail?.issues,
277
+ error: effect.detail?.error
278
+ };
268
279
  }
269
280
  }
270
281
 
@@ -1,4 +1,4 @@
1
- import { l as listenerLogic, s as subscriptionLogic, H as XSTATE_INIT, I as withActorScope, X as XSTATE_STOP, J as XSTATE_TIMER, K as isLazyActorScope } from './createActor-88709f74.development.esm.js';
1
+ import { l as listenerLogic, s as subscriptionLogic, I as XSTATE_INIT, J as withActorScope, X as XSTATE_STOP, K as XSTATE_TIMER, L as isLazyActorScope } from './createActor-74e185ee.development.esm.js';
2
2
 
3
3
  const allocations = new WeakMap();
4
4
  function beginFSMEffects(scope, snapshot) {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-a1e0dffb.development.cjs.js');
3
+ var createActor = require('./createActor-ea9a560c.development.cjs.js');
4
4
 
5
5
  const allocations = new WeakMap();
6
6
  function beginFSMEffects(scope, snapshot) {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-b4dd05ae.cjs.js');
3
+ var createActor = require('./createActor-27fd819f.cjs.js');
4
4
 
5
5
  const allocations = new WeakMap();
6
6
  function beginFSMEffects(scope, snapshot) {
@@ -1,4 +1,4 @@
1
- import { l as listenerLogic, s as subscriptionLogic, H as XSTATE_INIT, I as withActorScope, X as XSTATE_STOP, J as XSTATE_TIMER, K as isLazyActorScope } from './createActor-268165d4.esm.js';
1
+ import { l as listenerLogic, s as subscriptionLogic, I as XSTATE_INIT, J as withActorScope, X as XSTATE_STOP, K as XSTATE_TIMER, L as isLazyActorScope } from './createActor-ad3a1abe.esm.js';
2
2
 
3
3
  const allocations = new WeakMap();
4
4
  function beginFSMEffects(scope, snapshot) {
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var StateMachine = require('./StateMachine-0adb3a70.cjs.js');
3
+ var StateMachine = require('./StateMachine-70df737c.development.cjs.js');
4
4
 
5
5
  /**
6
6
  * Creates a state machine (statechart) with the given configuration.
@@ -182,6 +182,11 @@ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
182
182
 
183
183
  /** An executable effect that publishes an actor's terminal result. */
184
184
 
185
+ /**
186
+ * An executable effect that reports an event rejected at the delivery boundary
187
+ * (a dead letter). The snapshot paired with this effect is unchanged.
188
+ */
189
+
185
190
  /** Mappers for subscribeTo - maps lifecycle events to machine events */
186
191
 
187
192
  exports.SpecialTargets = SpecialTargets;
@@ -1,4 +1,4 @@
1
- import { S as StateMachine } from './StateMachine-2af31c11.esm.js';
1
+ import { S as StateMachine } from './StateMachine-8cea8974.esm.js';
2
2
 
3
3
  /**
4
4
  * Creates a state machine (statechart) with the given configuration.
@@ -180,6 +180,11 @@ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
180
180
 
181
181
  /** An executable effect that publishes an actor's terminal result. */
182
182
 
183
+ /**
184
+ * An executable effect that reports an event rejected at the delivery boundary
185
+ * (a dead letter). The snapshot paired with this effect is unchanged.
186
+ */
187
+
183
188
  /** Mappers for subscribeTo - maps lifecycle events to machine events */
184
189
 
185
190
  export { SpecialTargets as S, createStateConfig as a, createMachine as c };
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var StateMachine = require('./StateMachine-29450e6d.development.cjs.js');
3
+ var StateMachine = require('./StateMachine-1e6ee14a.cjs.js');
4
4
 
5
5
  /**
6
6
  * Creates a state machine (statechart) with the given configuration.
@@ -182,6 +182,11 @@ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
182
182
 
183
183
  /** An executable effect that publishes an actor's terminal result. */
184
184
 
185
+ /**
186
+ * An executable effect that reports an event rejected at the delivery boundary
187
+ * (a dead letter). The snapshot paired with this effect is unchanged.
188
+ */
189
+
185
190
  /** Mappers for subscribeTo - maps lifecycle events to machine events */
186
191
 
187
192
  exports.SpecialTargets = SpecialTargets;
@@ -1,4 +1,4 @@
1
- import { S as StateMachine } from './StateMachine-faf50c5c.development.esm.js';
1
+ import { S as StateMachine } from './StateMachine-bc28e207.development.esm.js';
2
2
 
3
3
  /**
4
4
  * Creates a state machine (statechart) with the given configuration.
@@ -180,6 +180,11 @@ let SpecialTargets = /*#__PURE__*/function (SpecialTargets) {
180
180
 
181
181
  /** An executable effect that publishes an actor's terminal result. */
182
182
 
183
+ /**
184
+ * An executable effect that reports an event rejected at the delivery boundary
185
+ * (a dead letter). The snapshot paired with this effect is unchanged.
186
+ */
187
+
183
188
  /** Mappers for subscribeTo - maps lifecycle events to machine events */
184
189
 
185
190
  export { SpecialTargets as S, createStateConfig as a, createMachine as c };
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-b4dd05ae.cjs.js');
5
+ var createActor = require('./createActor-27fd819f.cjs.js');
6
6
  var validation = require('./validation-4561b43c.cjs.js');
7
7
 
8
8
  const effectStates = new WeakMap();
@@ -149,12 +149,21 @@ function createLogic(config) {
149
149
  };
150
150
  const transition = (snapshot, event, actorScope) => {
151
151
  if (config.validator) {
152
- validation.assertValid(config.validator, {
152
+ const sourceRef = actorScope.self._lastSourceRef;
153
+ const eventOrigin = sourceRef ? 'actor' : 'external';
154
+ const error = config.validator.check({
153
155
  kind: 'event',
154
156
  logic,
155
157
  event,
156
- eventOrigin: actorScope.self._lastSourceRef ? 'actor' : 'external'
158
+ eventOrigin
157
159
  });
160
+ if (error) {
161
+ // Boundary fault: rejected (never delivered), not an actor error.
162
+ return [snapshot, [createActor.createDeadLetterEffect(actorScope, sourceRef, event, 'invalidEvent', {
163
+ issues: error.issues,
164
+ error
165
+ })]];
166
+ }
158
167
  }
159
168
  const result = calculateTransition(snapshot, event, actorScope);
160
169
  if (config.validator) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-a1e0dffb.development.cjs.js');
5
+ var createActor = require('./createActor-ea9a560c.development.cjs.js');
6
6
  var validation = require('./validation-f2714a35.development.cjs.js');
7
7
 
8
8
  const effectStates = new WeakMap();
@@ -149,12 +149,21 @@ function createLogic(config) {
149
149
  };
150
150
  const transition = (snapshot, event, actorScope) => {
151
151
  if (config.validator) {
152
- validation.assertValid(config.validator, {
152
+ const sourceRef = actorScope.self._lastSourceRef;
153
+ const eventOrigin = sourceRef ? 'actor' : 'external';
154
+ const error = config.validator.check({
153
155
  kind: 'event',
154
156
  logic,
155
157
  event,
156
- eventOrigin: actorScope.self._lastSourceRef ? 'actor' : 'external'
158
+ eventOrigin
157
159
  });
160
+ if (error) {
161
+ // Boundary fault: rejected (never delivered), not an actor error.
162
+ return [snapshot, [createActor.createDeadLetterEffect(actorScope, sourceRef, event, 'invalidEvent', {
163
+ issues: error.issues,
164
+ error
165
+ })]];
166
+ }
158
167
  }
159
168
  const result = calculateTransition(snapshot, event, actorScope);
160
169
  if (config.validator) {
@@ -1,5 +1,5 @@
1
- import { y as createInitEvent, X as XSTATE_STOP, z as createCustomEffect, B as XSTATE_LOGIC_EFFECT_START, C as XSTATE_LOGIC_EFFECT_RESOLVE, D as XSTATE_LOGIC_EFFECT_REJECT, E as finalizeTransitionResult, F as createEmitEffect, G as createSendToEffect, H as XSTATE_INIT, p as parseDelayToMilliseconds, v as runStep, c as createActor } from './createActor-88709f74.development.esm.js';
2
- export { a as createListenerLogic, b as createSubscriptionLogic, l as listenerLogic, s as subscriptionLogic } from './createActor-88709f74.development.esm.js';
1
+ import { y as createInitEvent, z as createDeadLetterEffect, X as XSTATE_STOP, B as createCustomEffect, C as XSTATE_LOGIC_EFFECT_START, D as XSTATE_LOGIC_EFFECT_RESOLVE, E as XSTATE_LOGIC_EFFECT_REJECT, F as finalizeTransitionResult, G as createEmitEffect, H as createSendToEffect, I as XSTATE_INIT, p as parseDelayToMilliseconds, v as runStep, c as createActor } from './createActor-74e185ee.development.esm.js';
2
+ export { a as createListenerLogic, b as createSubscriptionLogic, l as listenerLogic, s as subscriptionLogic } from './createActor-74e185ee.development.esm.js';
3
3
  import { a as assertValid } from './validation-e69470ad.development.esm.js';
4
4
 
5
5
  const effectStates = new WeakMap();
@@ -146,12 +146,21 @@ function createLogic(config) {
146
146
  };
147
147
  const transition = (snapshot, event, actorScope) => {
148
148
  if (config.validator) {
149
- assertValid(config.validator, {
149
+ const sourceRef = actorScope.self._lastSourceRef;
150
+ const eventOrigin = sourceRef ? 'actor' : 'external';
151
+ const error = config.validator.check({
150
152
  kind: 'event',
151
153
  logic,
152
154
  event,
153
- eventOrigin: actorScope.self._lastSourceRef ? 'actor' : 'external'
155
+ eventOrigin
154
156
  });
157
+ if (error) {
158
+ // Boundary fault: rejected (never delivered), not an actor error.
159
+ return [snapshot, [createDeadLetterEffect(actorScope, sourceRef, event, 'invalidEvent', {
160
+ issues: error.issues,
161
+ error
162
+ })]];
163
+ }
155
164
  }
156
165
  const result = calculateTransition(snapshot, event, actorScope);
157
166
  if (config.validator) {
@@ -1,5 +1,5 @@
1
- import { y as createInitEvent, X as XSTATE_STOP, z as createCustomEffect, B as XSTATE_LOGIC_EFFECT_START, C as XSTATE_LOGIC_EFFECT_RESOLVE, D as XSTATE_LOGIC_EFFECT_REJECT, E as finalizeTransitionResult, F as createEmitEffect, G as createSendToEffect, H as XSTATE_INIT, p as parseDelayToMilliseconds, v as runStep, c as createActor } from './createActor-268165d4.esm.js';
2
- export { a as createListenerLogic, b as createSubscriptionLogic, l as listenerLogic, s as subscriptionLogic } from './createActor-268165d4.esm.js';
1
+ import { y as createInitEvent, z as createDeadLetterEffect, X as XSTATE_STOP, B as createCustomEffect, C as XSTATE_LOGIC_EFFECT_START, D as XSTATE_LOGIC_EFFECT_RESOLVE, E as XSTATE_LOGIC_EFFECT_REJECT, F as finalizeTransitionResult, G as createEmitEffect, H as createSendToEffect, I as XSTATE_INIT, p as parseDelayToMilliseconds, v as runStep, c as createActor } from './createActor-ad3a1abe.esm.js';
2
+ export { a as createListenerLogic, b as createSubscriptionLogic, l as listenerLogic, s as subscriptionLogic } from './createActor-ad3a1abe.esm.js';
3
3
  import { a as assertValid } from './validation-05f1d517.esm.js';
4
4
 
5
5
  const effectStates = new WeakMap();
@@ -146,12 +146,21 @@ function createLogic(config) {
146
146
  };
147
147
  const transition = (snapshot, event, actorScope) => {
148
148
  if (config.validator) {
149
- assertValid(config.validator, {
149
+ const sourceRef = actorScope.self._lastSourceRef;
150
+ const eventOrigin = sourceRef ? 'actor' : 'external';
151
+ const error = config.validator.check({
150
152
  kind: 'event',
151
153
  logic,
152
154
  event,
153
- eventOrigin: actorScope.self._lastSourceRef ? 'actor' : 'external'
155
+ eventOrigin
154
156
  });
157
+ if (error) {
158
+ // Boundary fault: rejected (never delivered), not an actor error.
159
+ return [snapshot, [createDeadLetterEffect(actorScope, sourceRef, event, 'invalidEvent', {
160
+ issues: error.issues,
161
+ error
162
+ })]];
163
+ }
155
164
  }
156
165
  const result = calculateTransition(snapshot, event, actorScope);
157
166
  if (config.validator) {
@@ -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).XStateActors={})}(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",r="@xstate.stop",i="@xstate.terminate",o="xstate.logic.effect.resolve",n="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=new WeakMap;function p(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const o=t(e.input,{self:s,system:r});if(!o)return;let n,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),n?.unsubscribe())},h=s._parent;h&&(n=h.subscribe({complete:a,error:a})),d.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(d.get(s)?.unsubscribe(),d.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[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 _(){return p(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!function(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}(t.type,e)||l(r,i,()=>s(t))})},"xstate.listener")}const f=_();function v(){return p(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:o,snapshot:n}=e;return t.subscribe({next:t=>{"done"===t.status&&i?l(s,r,()=>i(t.output)):"error"===t.status&&o?l(s,r,()=>o(t.error)):"active"===t.status&&n&&l(s,r,()=>n(t))},error:t=>{o&&l(s,r,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const y=v();function m(t=this.source.system){return t.emitEvent(this.source,this.event)}function g(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function b(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 S(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function x(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:S,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function A(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:b,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function k(t,e,[s,r]){const o="done"===s.status||"error"===s.status,n="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||n||c?[s,r]:[s,[...r,A(t,s)]]}const w=()=>{},E=()=>({});function I(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=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(!i?.groups)return;const{weeks:o,days:n,hours:c,minutes:a,seconds:h}=i.groups;if(!(o||n||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(o)*24*60*60*1e3+24*u(n)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:w,emit:w,log:w,raise:w,spawn:E,sendTo:w,stop:w,listen:E,subscribeTo:E,...t})}({},w);const T=new WeakMap,R=new WeakMap,M=new Map;function O(t){t._snapshotVersion++}function P(t){return t._snapshotVersion}function L(t){const e=T.get(t);if(e)return e;const s=R.get(t);if(!s)return;const r=s();return T.set(t,r),R.delete(t),r}function j(t,e,s=e.system,r){R.delete(t);const i=P(s),o=r?L(r):void 0,n=o?.actor===e?o:L(t);if(n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion===i)return void T.set(t,n);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)??M:t.keyedActors}(s);let u=h.size?new Map(h):M;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===M&&(u=new Map),u.set(t,e))}T.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function $(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)}}async function K(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;if("active"===i?.status)return function(t,e){return new Promise((s,r)=>{const i=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(i.unsubscribe(),s(o.output)):"error"===o?.status&&(i.unsubscribe(),r(o.error))})})}(t,e);r({type:c,key:e});try{const t=await s();return r({type:o,key:e,output:t}),t}catch(t){throw r({type:n,key:e,error:t}),t}}function C(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}let z,D=0;const W=new Error("Transition effect"),V=[];function N(){return z??=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)}`}(),`${z}:${(D++).toString(36)}`}function U(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function H(t,e){return`${t?t.address:""}|${e}`}function q(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},O(t))}function B(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?q(t,H(s?.parent,r.prefix),r.index+1):s?.parent||q(t,H(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&&"(machine)"!==e?e:"x"}(s?.src),i=H(s?.parent,r),o=t._snapshot._nextActorIds[i]??0;return q(t,i,o+1),s?.parent||"x"===r||0!==o?`${r}:${o}`:r}const F=Object.freeze({});function J(t,e){return`${t.sessionId}.${e}`}class X{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={systemId:N(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const r=void 0;this._snapshot={_scheduledTimers:s?.scheduler??F,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=J(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const o=this._clock.now?.()??Date.now(),n={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},c=J(t,e);this._snapshot._scheduledTimers===F&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=n,O(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],O(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=J(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==F&&delete this._snapshot._scheduledTimers[s],O(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.id)}}_deliver(t,e,s){!function(t,e,s){C(t,e,s);const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),O(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&O(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&O(this)}inspect(t){const e=$(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!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){C(t,e,s),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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:r});const i=this.runtime?.deadLetter;if(i)return i(t,e,s,r)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):K(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(V.length&&V.includes(e))throw W;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,id:o}=t[s];this.scheduleTimer(r,o,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let G=!1;const Q=Object.freeze([]);let Y=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Z=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function tt(t,e){try{t?.(e)}catch(t){h(t)}}function et(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function st(t,e){return new rt(t,e)}class rt{get address(){return this._address??=this._parent?`${this._parent.address}/${U(this.id)}`:U(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=Y.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1;const s=e?{...Z,...e}:Z,{clock:r,logger:i,parent:o,syncSnapshot:n,id:c,registryKey:a,inspect:h}=s;var u;this.system=o?o.system:s._systemRef?.current??function(t,e){return new X(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot??s.state,createActorRef:st}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!o&&this.system.inspect($(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=B(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=n,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=k(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>this.system.emitEvent(this,t);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===Y.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=G;try{G=!0,t.exec()}finally{G=e}};this._processingStatus!==Y.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,j(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=k(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),et(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Q)tt(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??Q,actions:this._collectedActions??Q,sent:this._collectedSent??Q,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 et(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=$(t,e,s);if(this._processingStatus!==Y.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":tt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?tt(r.error,t):h(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 o=$(s,r,i);let n=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(n,r)||(n=r,o.next?.(r))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Y.Running)return this;if(this._processingStatus===Y.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Y.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,a(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,a(this.options.input)):(function(t,e,s){const r=T.get(t),i=P(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=k(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let i=this._snapshot;try{const[s,r]=e;i=s,this._setSnapshot(i),et(r,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)tt(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===Y.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Y.NotStarted?(this._processingStatus=Y.Stopped,this.system._unregister(this),this):(this._send({type:r}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??Q)tt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const r=s.error;e||=!r,tt(r,t)}this.observers.clear(),e&&h(t)}else this._parent||h(t);var e,s,r;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,r=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:r}))}_stopProcedure(){this._processingStatus===Y.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Y.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Y.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function it(t,e){const s=t.check(e);if(s)throw s}const ot=new WeakMap;function nt(t,e,s){const r=function(t){let e=ot.get(t);return e||(e=new Map,ot.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 ct(t){const e=(e,s,i)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[g("xstate.logic.cleanup",()=>function(t){const e=ot.get(t);if(e){for(const{cleanup:t}of e.values())t?.();ot.delete(t)}}(i.self))]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===o)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===n)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const a=[],h={},u={emit:t=>{a.push(function(t,e){return{kind:"emit",exec:m,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(i,t))},sendBack:t=>{const e=i.self._parent;e&&a.push(x(i,e,t))},raise:t=>{a.push(x(i,i.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(a.push(g("xstate.logic.effect",(e=i.self.system)=>nt(i.self,t,()=>s(e)),{key:t})),h[t]={status:"active"})})(t,s);const r=t;a.push(g("xstate.logic.effect",(t=i.self.system)=>nt(i.self,void 0,()=>r(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:i.system,self:i.self,emit:i.emit},u),p={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(p.context=d?.context??e.context),(d?.effects||Object.keys(h).length)&&(p.effects={...e.effects,...d?.effects,...h}),k(i,e,[p,a])},s=(s,r,o)=>{t.validator&&it(t.validator,{kind:"event",logic:i,event:r,eventOrigin:o.self._lastSourceRef?"actor":"external"});const n=e(s,r,o);return t.validator&&it(t.validator,{kind:"result",logic:i,snapshot:n[0],effects:n[1]}),n},i={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,o]=s(t,a(t.input),e);Object.assign(t,i);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&it(t.validator,{kind:"input",logic:i,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),n={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(n.context=o),s({...n},a(e),r)},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return i}const at=new WeakMap;const ht="xstate.observable.next",ut="xstate.observable.error",dt="xstate.observable.complete";const pt="xstate.async.resolve",lt="xstate.async.reject";class _t extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const ft=ct({context:void 0,run:()=>{}});t.TimeoutError=_t,t.createAsyncLogic=function(t){const e=t;return ct({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:o},n)=>{switch(t.type){case pt:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case lt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return n.effect((t=o)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=I(a),u=void 0===h?void 0:o._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),n({type:lt,data:new _t(a)}))},h),d=()=>{void 0!==u&&o._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:o,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):K(s,e,r,n)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&n({type:pt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&n({type:lt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:o,system:n}=t,c=t.emit,a=at.get(o);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return at.set(o,t),t.dispose=e({input:i,system:n,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&n._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{at.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return new rt(ft,t);var t},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case ut:return k(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case dt:return k(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&it(s,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:ut,data:t})},complete:()=>{r._relay(s,s,{type:dt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=_,t.createLogic=ct,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:o,self:n,system:c}=t;switch(i.type){case ht:return{context:i.data};case ut:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case dt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=n,r=e=>{t.sendEvent(s,s,e)},i=e({input:o,system:c,self:n,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:ht,data:t})},error:t=>{r({type:ut,data:t})},complete:()=>{r({type:dt})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=v,t.listenerLogic=f,t.subscriptionLogic=y,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).XStateActors={})}(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",r="@xstate.stop",i="@xstate.terminate",n="xstate.logic.effect.resolve",o="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=new WeakMap;function p(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const n=t(e.input,{self:s,system:r});if(!n)return;let o,c=!1;const a=()=>{c||(c=!0,n.unsubscribe(),o?.unsubscribe())},h=s._parent;h&&(o=h.subscribe({complete:a,error:a})),d.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(d.get(s)?.unsubscribe(),d.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[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 f(){return p(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const n="*"!==e&&e.endsWith(".*");return t.on(n?"*":e,t=>{n&&!function(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}(t.type,e)||l(r,i,()=>s(t))})},"xstate.listener")}const _=f();function v(){return p(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:n,snapshot:o}=e;return t.subscribe({next:t=>{"done"===t.status&&i?l(s,r,()=>i(t.output)):"error"===t.status&&n?l(s,r,()=>n(t.error)):"active"===t.status&&o&&l(s,r,()=>o(t))},error:t=>{n&&l(s,r,()=>n(t))},complete:()=>{}})},"xstate.subscription")}const y=v();function m(t=this.source.system){return t.emitEvent(this.source,this.event)}function g(t=this.target.system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function b(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:g,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function S(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function x(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 A(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function k(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:A,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function E(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:x,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function w(t,e,[s,r]){const n="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===i);return!n||o||c?[s,r]:[s,[...r,E(t,s)]]}const I=()=>{},T=()=>({});function R(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=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(!i?.groups)return;const{weeks:n,days:o,hours:c,minutes:a,seconds:h}=i.groups;if(!(n||o||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(n)*24*60*60*1e3+24*u(o)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:I,emit:I,log:I,raise:I,spawn:T,sendTo:I,stop:I,listen:T,subscribeTo:T,...t})}({},I);const M=new WeakMap,O=new WeakMap,j=new Map;function L(t){t._snapshotVersion++}function P(t){return t._snapshotVersion}function $(t){const e=M.get(t);if(e)return e;const s=O.get(t);if(!s)return;const r=s();return M.set(t,r),O.delete(t),r}function K(t,e,s=e.system,r){O.delete(t);const i=P(s),n=r?$(r):void 0,o=n?.actor===e?n:$(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void M.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)??j:t.keyedActors}(s);let u=h.size?new Map(h):j;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===j&&(u=new Map),u.set(t,e))}M.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function C(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)}}async function z(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;if("active"===i?.status)return function(t,e){return new Promise((s,r)=>{const i=t.subscribe(t=>{const n=t.effects?.[e];"done"===n?.status?(i.unsubscribe(),s(n.output)):"error"===n?.status&&(i.unsubscribe(),r(n.error))})})}(t,e);r({type:c,key:e});try{const t=await s();return r({type:n,key:e,output:t}),t}catch(t){throw r({type:o,key:e,error:t}),t}}function D(t,e,s){const r=function(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!r&&(e.system.deadLetter(t,e,s,"internalEvent",{error:r}),!0)}let W,V=0;const N=new Error("Transition effect"),U=[];function H(){return W??=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)}`}(),`${W}:${(V++).toString(36)}`}function q(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function B(t,e){return`${t?t.address:""}|${e}`}function F(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},L(t))}function J(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?F(t,B(s?.parent,r.prefix),r.index+1):s?.parent||F(t,B(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&&"(machine)"!==e?e:"x"}(s?.src),i=B(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return F(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const X=Object.freeze({});function G(t,e){return`${t.sessionId}.${e}`}class Q{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={systemId:H(),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._onRejectedEvent=e.onRejectedEvent;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const r=void 0;this._snapshot={_scheduledTimers:s?.scheduler??X,_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=G(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const n=this._clock.now?.()??Date.now(),o={source:t,delay:s,id:e,scheduledAt:n,dueAt:n+s},c=G(t,e);this._snapshot._scheduledTimers===X&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=o,L(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],L(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=G(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==X&&delete this._snapshot._scheduledTimers[s],L(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.id)}}_deliver(t,e,s){!function(t,e,s){if(D(t,e,s))return;const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),L(this),t}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&L(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&L(this)}inspect(t){const e=C(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!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(D(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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:r,issues:i?.issues,error:i?.error}),this._onRejectedEvent?.({event:s,targetRef:e,targetId:e.id,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error});const n=this.runtime?.deadLetter;if(n)return n(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):z(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(U.length&&U.includes(e))throw N;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,id:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let Y=!1;const Z=Object.freeze([]);let tt=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const et=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function st(t,e){try{t?.(e)}catch(t){h(t)}}function rt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function it(t,e){return new nt(t,e)}class nt{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.eventListeners=void 0,this.logger=void 0,this._processingStatus=tt.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1;const s=e?{...et,...e}:et,{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 Q(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot??s.state,createActorRef:it,onRejectedEvent:s.onRejectedEvent}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!n&&this.system.inspect(C(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=J(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=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=w(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot({status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>this.system.emitEvent(this,t);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===tt.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=Y;try{Y=!0,t.exec()}finally{Y=e}};this._processingStatus!==tt.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,K(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=w(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),rt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Z)st(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??Z,actions:this._collectedActions??Z,sent:this._collectedSent??Z,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 rt(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=C(t,e,s);if(this._processingStatus!==tt.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":st(r.complete);break;case"error":{const t=this._snapshot.error;r.error?st(r.error,t):h(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=C(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===tt.Running)return this;if(this._processingStatus===tt.Stopped)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=tt.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,a(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,a(this.options.input)):(function(t,e,s){const r=M.get(t),i=P(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=w(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let i=this._snapshot;try{const[s,r]=e;i=s,this._setSnapshot(i),rt(r,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)st(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===tt.Stopped?this:(this.mailbox?.clear(),this._processingStatus===tt.NotStarted?(this._processingStatus=tt.Stopped,this.system._unregister(this),this):(this._send({type:r}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??Z)st(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const r=s.error;e||=!r,st(r,t)}this.observers.clear(),e&&h(t)}else this._parent||h(t);var e,s,r;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,r=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:r}))}_stopProcedure(){this._processingStatus===tt.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=tt.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===tt.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function ot(t,e){const s=t.check(e);if(s)throw s}const ct=new WeakMap;function at(t,e,s){const r=function(t){let e=ct.get(t);return e||(e=new Map,ct.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 ht(t){const e=(e,s,i)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[S("xstate.logic.cleanup",()=>function(t){const e=ct.get(t);if(e){for(const{cleanup:t}of e.values())t?.();ct.delete(t)}}(i.self))]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===n)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===o)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const a=[],h={},u={emit:t=>{a.push(function(t,e){return{kind:"emit",exec:m,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(i,t))},sendBack:t=>{const e=i.self._parent;e&&a.push(k(i,e,t))},raise:t=>{a.push(k(i,i.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(a.push(S("xstate.logic.effect",(e=i.self.system)=>at(i.self,t,()=>s(e)),{key:t})),h[t]={status:"active"})})(t,s);const r=t;a.push(S("xstate.logic.effect",(t=i.self.system)=>at(i.self,void 0,()=>r(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:i.system,self:i.self,emit:i.emit},u),p={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(p.context=d?.context??e.context),(d?.effects||Object.keys(h).length)&&(p.effects={...e.effects,...d?.effects,...h}),w(i,e,[p,a])},s=(s,r,n)=>{if(t.validator){const e=n.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:i,event:r,eventOrigin:o});if(c)return[s,[b(n,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,n);return t.validator&&ot(t.validator,{kind:"result",logic:i,snapshot:o[0],effects:o[1]}),o},i={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,a(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&ot(t.validator,{kind:"input",logic:i,input:e});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),s({...o},a(e),r)},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return i}const ut=new WeakMap;const dt="xstate.observable.next",pt="xstate.observable.error",lt="xstate.observable.complete";const ft="xstate.async.resolve",_t="xstate.async.reject";class vt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const yt=ht({context:void 0,run:()=>{}});t.TimeoutError=vt,t.createAsyncLogic=function(t){const e=t;return ht({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:n},o)=>{switch(t.type){case ft:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case _t:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return o.effect((t=n)=>{const s=i,o=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=R(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:_t,data:new vt(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:n,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):z(s,e,r,o)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:ft,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:_t,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return ht({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t,c=t.emit,a=ut.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return ut.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;const e=n._parent;e&&o._relay(n,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{ut.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return new nt(yt,t);var t},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case pt:return w(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case lt:return w(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&ot(s,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:pt,data:t})},complete:()=>{r._relay(s,s,{type:lt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=f,t.createLogic=ht,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return ht({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case dt:return{context:i.data};case pt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case lt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=o,r=e=>{t.sendEvent(s,s,e)},i=e({input:n,system:c,self:o,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:dt,data:t})},error:t=>{r({type:pt,data:t})},complete:()=>{r({type:lt})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=v,t.listenerLogic=_,t.subscriptionLogic=y,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map