xstate 6.0.0-beta.2 → 6.0.0-beta.3

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/README.md +4 -2
  2. package/dist/{createActor-20a97166.esm.js → createActor-49ea55ba.esm.js} +17 -8
  3. package/dist/{createActor-c91c9ffe.cjs.js → createActor-73aa92ba.cjs.js} +17 -7
  4. package/dist/{createActor-0250284a.development.esm.js → createActor-a085b20b.development.esm.js} +17 -8
  5. package/dist/{createActor-c029d29f.development.cjs.js → createActor-dfb6b790.development.cjs.js} +17 -7
  6. package/dist/declarations/src/fsm.d.ts +7 -7
  7. package/dist/{effectDescriptor-47f73e7e.cjs.js → effectDescriptor-3402f63e.cjs.js} +1 -1
  8. package/dist/{effectDescriptor-e93df910.esm.js → effectDescriptor-65821048.development.esm.js} +1 -1
  9. package/dist/{effectDescriptor-5ac7dccb.development.esm.js → effectDescriptor-72c62058.esm.js} +1 -1
  10. package/dist/{effectDescriptor-3fff5c51.development.cjs.js → effectDescriptor-d0ea44ad.development.cjs.js} +1 -1
  11. package/dist/{legacySnapshot-ae6594a7.development.esm.js → legacySnapshot-11aba2d2.development.esm.js} +1 -1
  12. package/dist/{legacySnapshot-ebf0b2b8.development.cjs.js → legacySnapshot-2e2c1d3b.development.cjs.js} +1 -1
  13. package/dist/{legacySnapshot-8d595687.cjs.js → legacySnapshot-a85dfbe2.cjs.js} +1 -1
  14. package/dist/{legacySnapshot-9e06feb4.esm.js → legacySnapshot-fffe81a0.esm.js} +1 -1
  15. package/dist/xstate-actors.cjs.js +30 -5
  16. package/dist/xstate-actors.development.cjs.js +30 -5
  17. package/dist/xstate-actors.development.esm.js +31 -6
  18. package/dist/xstate-actors.esm.js +31 -6
  19. package/dist/xstate-actors.umd.min.js +1 -1
  20. package/dist/xstate-actors.umd.min.js.map +1 -1
  21. package/dist/xstate-durable.cjs.js +3 -3
  22. package/dist/xstate-durable.development.cjs.js +3 -3
  23. package/dist/xstate-durable.development.esm.js +3 -3
  24. package/dist/xstate-durable.esm.js +3 -3
  25. package/dist/xstate-durable.umd.min.js +1 -1
  26. package/dist/xstate-durable.umd.min.js.map +1 -1
  27. package/dist/xstate-fsm.cjs.js +61 -31
  28. package/dist/xstate-fsm.development.cjs.js +61 -31
  29. package/dist/xstate-fsm.development.esm.js +61 -31
  30. package/dist/xstate-fsm.esm.js +61 -31
  31. package/dist/xstate-fsm.umd.min.js +1 -1
  32. package/dist/xstate-fsm.umd.min.js.map +1 -1
  33. package/dist/xstate-graph.cjs.js +1 -1
  34. package/dist/xstate-graph.development.cjs.js +1 -1
  35. package/dist/xstate-graph.development.esm.js +2 -2
  36. package/dist/xstate-graph.esm.js +2 -2
  37. package/dist/xstate-persist.cjs.js +2 -2
  38. package/dist/xstate-persist.development.cjs.js +2 -2
  39. package/dist/xstate-persist.development.esm.js +3 -3
  40. package/dist/xstate-persist.esm.js +3 -3
  41. package/dist/xstate-persist.umd.min.js +1 -1
  42. package/dist/xstate-persist.umd.min.js.map +1 -1
  43. package/dist/xstate-validation.cjs.js +1 -1
  44. package/dist/xstate-validation.development.cjs.js +1 -1
  45. package/dist/xstate-validation.development.esm.js +1 -1
  46. package/dist/xstate-validation.esm.js +1 -1
  47. package/dist/xstate.cjs.js +26 -8
  48. package/dist/xstate.development.cjs.js +26 -8
  49. package/dist/xstate.development.esm.js +28 -10
  50. package/dist/xstate.esm.js +28 -10
  51. package/dist/xstate.umd.min.js +1 -1
  52. package/dist/xstate.umd.min.js.map +1 -1
  53. package/docs/actor-logic.md +1 -1
  54. package/docs/api-stability.json +93 -81
  55. package/docs/faq.md +1 -1
  56. package/docs/fsm.md +53 -10
  57. package/docs/index.md +2 -1
  58. package/docs/inspect-actor-systems.md +20 -3
  59. package/docs/inspection.md +5 -1
  60. package/docs/invoke.md +2 -2
  61. package/docs/migrate-inspector.md +141 -0
  62. package/docs/system-transitions.md +2 -0
  63. package/docs/transitions.md +5 -1
  64. package/docs/xstate-v5-to-v6.md +6 -4
  65. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-c029d29f.development.cjs.js');
5
+ var createActor = require('./createActor-dfb6b790.development.cjs.js');
6
6
  var validation = require('./validation-f2714a35.development.cjs.js');
7
7
 
8
8
  /** @public */
@@ -253,6 +253,7 @@ function createStepLogic(config) {
253
253
  }
254
254
 
255
255
  const instanceStates = /* #__PURE__ */new WeakMap();
256
+ const XSTATE_CALLBACK_SEND_BACK = 'xstate.callback.sendBack';
256
257
 
257
258
  /** @public */
258
259
 
@@ -372,8 +373,10 @@ function createCallbackLogic(callbackOrConfig) {
372
373
  const callback = typeof callbackOrConfig === 'function' ? callbackOrConfig : callbackOrConfig.run;
373
374
  const schemas = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.schemas;
374
375
  const validator = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.validator;
375
- return createStepLogic({
376
- validator,
376
+ const logic = createStepLogic({
377
+ validator: validator && {
378
+ check: request => request.kind === 'event' && request.event.type === XSTATE_CALLBACK_SEND_BACK ? undefined : validator.check(request)
379
+ },
377
380
  schemas,
378
381
  context: undefined,
379
382
  run: (args, enq) => {
@@ -383,6 +386,10 @@ function createCallbackLogic(callbackOrConfig) {
383
386
  self,
384
387
  system
385
388
  } = args;
389
+ if (event.type === XSTATE_CALLBACK_SEND_BACK) {
390
+ enq.sendBack(event.event);
391
+ return;
392
+ }
386
393
  const emit = args.emit;
387
394
  const callbackState = instanceStates.get(self);
388
395
  callbackState?.receivers?.forEach(receiver => receiver(event));
@@ -402,7 +409,10 @@ function createCallbackLogic(callbackOrConfig) {
402
409
  }
403
410
  const parent = self._parent;
404
411
  if (parent) {
405
- system._relay(self, parent, event);
412
+ system._relay(self, self, {
413
+ type: XSTATE_CALLBACK_SEND_BACK,
414
+ event
415
+ });
406
416
  }
407
417
  },
408
418
  receive: listener => {
@@ -419,6 +429,10 @@ function createCallbackLogic(callbackOrConfig) {
419
429
  });
420
430
  }
421
431
  });
432
+ Object.assign(logic, {
433
+ isInternalEventType: eventType => eventType === XSTATE_CALLBACK_SEND_BACK
434
+ });
435
+ return logic;
422
436
  }
423
437
 
424
438
  const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
@@ -667,6 +681,11 @@ function createEventObservableLogic(lazyObservableOrConfig) {
667
681
  return [state, []];
668
682
  }
669
683
  switch (event.type) {
684
+ case XSTATE_OBSERVABLE_NEXT:
685
+ {
686
+ const parent = actorScope.self._parent;
687
+ return [state, parent ? [createActor.createSendToEffect(actorScope, parent, event.data)] : []];
688
+ }
670
689
  case XSTATE_OBSERVABLE_ERROR:
671
690
  return createActor.finalizeTransitionResult(actorScope, state, [{
672
691
  ...state,
@@ -732,7 +751,10 @@ function createEventObservableLogic(lazyObservableOrConfig) {
732
751
  }).subscribe({
733
752
  next: value => {
734
753
  if (self._parent) {
735
- system._relay(self, self._parent, value);
754
+ system._relay(self, self, {
755
+ type: XSTATE_OBSERVABLE_NEXT,
756
+ data: value
757
+ });
736
758
  }
737
759
  },
738
760
  error: err => {
@@ -757,6 +779,9 @@ function createEventObservableLogic(lazyObservableOrConfig) {
757
779
  _subscription: undefined
758
780
  })
759
781
  };
782
+ Object.assign(logic, {
783
+ isInternalEventType: eventType => eventType === XSTATE_OBSERVABLE_NEXT || eventType === XSTATE_OBSERVABLE_ERROR || eventType === XSTATE_OBSERVABLE_COMPLETE
784
+ });
760
785
  return logic;
761
786
  }
762
787
 
@@ -1,5 +1,5 @@
1
- import { O as createInitEvent, Q as createDeadLetterEffect, u as XSTATE_STOP, R as createCustomEffect, S as XSTATE_LOGIC_EFFECT_START, T as XSTATE_LOGIC_EFFECT_RESOLVE, U as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, V as createEmitEffect, W as createSendToEffect, Y as XSTATE_INIT, Z as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, L as runStep, h as createActor } from './createActor-0250284a.development.esm.js';
2
- export { C as createListenerLogic, D as createSubscriptionLogic } from './createActor-0250284a.development.esm.js';
1
+ import { Q as createInitEvent, R as createDeadLetterEffect, v as XSTATE_STOP, S as createCustomEffect, T as XSTATE_LOGIC_EFFECT_START, U as XSTATE_LOGIC_EFFECT_RESOLVE, V as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, W as createEmitEffect, Y as createSendToEffect, Z as XSTATE_INIT, _ as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, M as runStep, h as createActor } from './createActor-a085b20b.development.esm.js';
2
+ export { D as createListenerLogic, E as createSubscriptionLogic } from './createActor-a085b20b.development.esm.js';
3
3
  import { a as assertValid } from './validation-e69470ad.development.esm.js';
4
4
 
5
5
  /** @public */
@@ -250,6 +250,7 @@ function createStepLogic(config) {
250
250
  }
251
251
 
252
252
  const instanceStates = /* #__PURE__ */new WeakMap();
253
+ const XSTATE_CALLBACK_SEND_BACK = 'xstate.callback.sendBack';
253
254
 
254
255
  /** @public */
255
256
 
@@ -369,8 +370,10 @@ function createCallbackLogic(callbackOrConfig) {
369
370
  const callback = typeof callbackOrConfig === 'function' ? callbackOrConfig : callbackOrConfig.run;
370
371
  const schemas = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.schemas;
371
372
  const validator = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.validator;
372
- return createStepLogic({
373
- validator,
373
+ const logic = createStepLogic({
374
+ validator: validator && {
375
+ check: request => request.kind === 'event' && request.event.type === XSTATE_CALLBACK_SEND_BACK ? undefined : validator.check(request)
376
+ },
374
377
  schemas,
375
378
  context: undefined,
376
379
  run: (args, enq) => {
@@ -380,6 +383,10 @@ function createCallbackLogic(callbackOrConfig) {
380
383
  self,
381
384
  system
382
385
  } = args;
386
+ if (event.type === XSTATE_CALLBACK_SEND_BACK) {
387
+ enq.sendBack(event.event);
388
+ return;
389
+ }
383
390
  const emit = args.emit;
384
391
  const callbackState = instanceStates.get(self);
385
392
  callbackState?.receivers?.forEach(receiver => receiver(event));
@@ -399,7 +406,10 @@ function createCallbackLogic(callbackOrConfig) {
399
406
  }
400
407
  const parent = self._parent;
401
408
  if (parent) {
402
- system._relay(self, parent, event);
409
+ system._relay(self, self, {
410
+ type: XSTATE_CALLBACK_SEND_BACK,
411
+ event
412
+ });
403
413
  }
404
414
  },
405
415
  receive: listener => {
@@ -416,6 +426,10 @@ function createCallbackLogic(callbackOrConfig) {
416
426
  });
417
427
  }
418
428
  });
429
+ Object.assign(logic, {
430
+ isInternalEventType: eventType => eventType === XSTATE_CALLBACK_SEND_BACK
431
+ });
432
+ return logic;
419
433
  }
420
434
 
421
435
  const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
@@ -664,6 +678,11 @@ function createEventObservableLogic(lazyObservableOrConfig) {
664
678
  return [state, []];
665
679
  }
666
680
  switch (event.type) {
681
+ case XSTATE_OBSERVABLE_NEXT:
682
+ {
683
+ const parent = actorScope.self._parent;
684
+ return [state, parent ? [createSendToEffect(actorScope, parent, event.data)] : []];
685
+ }
667
686
  case XSTATE_OBSERVABLE_ERROR:
668
687
  return finalizeTransitionResult(actorScope, state, [{
669
688
  ...state,
@@ -729,7 +748,10 @@ function createEventObservableLogic(lazyObservableOrConfig) {
729
748
  }).subscribe({
730
749
  next: value => {
731
750
  if (self._parent) {
732
- system._relay(self, self._parent, value);
751
+ system._relay(self, self, {
752
+ type: XSTATE_OBSERVABLE_NEXT,
753
+ data: value
754
+ });
733
755
  }
734
756
  },
735
757
  error: err => {
@@ -754,6 +776,9 @@ function createEventObservableLogic(lazyObservableOrConfig) {
754
776
  _subscription: undefined
755
777
  })
756
778
  };
779
+ Object.assign(logic, {
780
+ isInternalEventType: eventType => eventType === XSTATE_OBSERVABLE_NEXT || eventType === XSTATE_OBSERVABLE_ERROR || eventType === XSTATE_OBSERVABLE_COMPLETE
781
+ });
757
782
  return logic;
758
783
  }
759
784
 
@@ -1,5 +1,5 @@
1
- import { Q as createInitEvent, R as createDeadLetterEffect, u as XSTATE_STOP, S as createCustomEffect, T as XSTATE_LOGIC_EFFECT_START, U as XSTATE_LOGIC_EFFECT_RESOLVE, V as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, W as createEmitEffect, Y as createSendToEffect, Z as XSTATE_INIT, _ as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, M as runStep, h as createActor } from './createActor-20a97166.esm.js';
2
- export { D as createListenerLogic, E as createSubscriptionLogic } from './createActor-20a97166.esm.js';
1
+ import { R as createInitEvent, S as createDeadLetterEffect, v as XSTATE_STOP, T as createCustomEffect, U as XSTATE_LOGIC_EFFECT_START, V as XSTATE_LOGIC_EFFECT_RESOLVE, W as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, Y as createEmitEffect, Z as createSendToEffect, _ as XSTATE_INIT, $ as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, N as runStep, h as createActor } from './createActor-49ea55ba.esm.js';
2
+ export { E as createListenerLogic, F as createSubscriptionLogic } from './createActor-49ea55ba.esm.js';
3
3
  import { a as assertValid } from './validation-05f1d517.esm.js';
4
4
 
5
5
  /** @public */
@@ -250,6 +250,7 @@ function createStepLogic(config) {
250
250
  }
251
251
 
252
252
  const instanceStates = /* #__PURE__ */new WeakMap();
253
+ const XSTATE_CALLBACK_SEND_BACK = 'xstate.callback.sendBack';
253
254
 
254
255
  /** @public */
255
256
 
@@ -369,8 +370,10 @@ function createCallbackLogic(callbackOrConfig) {
369
370
  const callback = typeof callbackOrConfig === 'function' ? callbackOrConfig : callbackOrConfig.run;
370
371
  const schemas = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.schemas;
371
372
  const validator = typeof callbackOrConfig === 'function' ? undefined : callbackOrConfig.validator;
372
- return createStepLogic({
373
- validator,
373
+ const logic = createStepLogic({
374
+ validator: validator && {
375
+ check: request => request.kind === 'event' && request.event.type === XSTATE_CALLBACK_SEND_BACK ? undefined : validator.check(request)
376
+ },
374
377
  schemas,
375
378
  context: undefined,
376
379
  run: (args, enq) => {
@@ -380,6 +383,10 @@ function createCallbackLogic(callbackOrConfig) {
380
383
  self,
381
384
  system
382
385
  } = args;
386
+ if (event.type === XSTATE_CALLBACK_SEND_BACK) {
387
+ enq.sendBack(event.event);
388
+ return;
389
+ }
383
390
  const emit = args.emit;
384
391
  const callbackState = instanceStates.get(self);
385
392
  callbackState?.receivers?.forEach(receiver => receiver(event));
@@ -399,7 +406,10 @@ function createCallbackLogic(callbackOrConfig) {
399
406
  }
400
407
  const parent = self._parent;
401
408
  if (parent) {
402
- system._relay(self, parent, event);
409
+ system._relay(self, self, {
410
+ type: XSTATE_CALLBACK_SEND_BACK,
411
+ event
412
+ });
403
413
  }
404
414
  },
405
415
  receive: listener => {
@@ -416,6 +426,10 @@ function createCallbackLogic(callbackOrConfig) {
416
426
  });
417
427
  }
418
428
  });
429
+ Object.assign(logic, {
430
+ isInternalEventType: eventType => eventType === XSTATE_CALLBACK_SEND_BACK
431
+ });
432
+ return logic;
419
433
  }
420
434
 
421
435
  const XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';
@@ -664,6 +678,11 @@ function createEventObservableLogic(lazyObservableOrConfig) {
664
678
  return [state, []];
665
679
  }
666
680
  switch (event.type) {
681
+ case XSTATE_OBSERVABLE_NEXT:
682
+ {
683
+ const parent = actorScope.self._parent;
684
+ return [state, parent ? [createSendToEffect(actorScope, parent, event.data)] : []];
685
+ }
667
686
  case XSTATE_OBSERVABLE_ERROR:
668
687
  return finalizeTransitionResult(actorScope, state, [{
669
688
  ...state,
@@ -729,7 +748,10 @@ function createEventObservableLogic(lazyObservableOrConfig) {
729
748
  }).subscribe({
730
749
  next: value => {
731
750
  if (self._parent) {
732
- system._relay(self, self._parent, value);
751
+ system._relay(self, self, {
752
+ type: XSTATE_OBSERVABLE_NEXT,
753
+ data: value
754
+ });
733
755
  }
734
756
  },
735
757
  error: err => {
@@ -754,6 +776,9 @@ function createEventObservableLogic(lazyObservableOrConfig) {
754
776
  _subscription: undefined
755
777
  })
756
778
  };
779
+ Object.assign(logic, {
780
+ isInternalEventType: eventType => eventType === XSTATE_OBSERVABLE_NEXT || eventType === XSTATE_OBSERVABLE_ERROR || eventType === XSTATE_OBSERVABLE_COMPLETE
781
+ });
757
782
  return logic;
758
783
  }
759
784
 
@@ -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";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 p(t){return new Error(e(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function l(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 p=new Promise((t,e)=>{u=t,d=e});let l,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,p);const v=()=>{l?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return p.then(v,v),l=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),p}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 m{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 g(t){return{type:r,input:t}}function b(t){setTimeout(()=>{throw t})}const S="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],A=new Error("Transition effect");function w(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:w(t.event)??t.event}}function k(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",w(t.event)??t.event])}(e)}`}const T=Symbol("xstate.systemLogicMetadata"),I=new WeakMap;function O(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],r={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})),I.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===i?(I.get(s)?.unsubscribe(),I.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(r,T,{value:{kind:e}}),r}function R(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function M(t=this.source.system){return f(this.source,this.event,t)}function j(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function L(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:j,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function P(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(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 z(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 K(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:z,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function q(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:$,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function U(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,q(t,s)]]}function N(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)}const C=new WeakMap,D=new WeakMap,W=new Map;function V(t){t._snapshotVersion++}function B(t){return t._snapshotVersion}function J(t){const e=C.get(t);if(e)return e;const s=D.get(t);if(!s)return;const r=s();return C.set(t,r),D.delete(t),r}function H(t,e,s=e.system,r){D.delete(t);const i=B(s),n=r?J(r):void 0,o=n?.actor===e?n:J(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void C.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)??W:t.keyedActors}(s);let u=h.size?new Map(h):W;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===W&&(u=new Map),u.set(t,e))}C.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function F(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}:{}}}let X,G=0;function Q(){return X??=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)}`}(),`${X}:${(G++).toString(36)}`}function Y(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Z(t,e){return`${t?t.address:""}|${e}`}function tt(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},V(t))}function et(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?tt(t,Z(s?.parent,r.prefix),r.index+1):s?.parent||tt(t,Z(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=Z(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return tt(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const st=Object.freeze({});function rt(t,e){return k(t,e)}function it(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 nt{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:Q(),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:st,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;if(!n._inTransition)return;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=rt(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=it(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===st&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,V(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],V(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=rt(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==st&&delete this._snapshot._scheduledTimers[s],V(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&&l(i,r);if(!n){const e=p(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),V(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&&V(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&&V(this)}inspect(t){const e=F(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){b(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){b(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=l(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:p(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){b(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=it(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 A;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 ot=!1;const ct=Object.freeze([]),at={"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 ht=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ut=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function dt(t,e){try{t?.(e)}catch(t){b(t)}}function pt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new ft(t,e)}class ft{get address(){return this._address??=this._parent?`${this._parent.address}/${Y(this.id)}`:Y(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=ht.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._inTransition=!1,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?{...ut,...e}:ut,{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 nt(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(F(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=et(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{this._inTransition=!0;try{const[t,e]=U(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}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===ht.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=ot;try{ot=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ht.Stopped&&this._recoverOrError(t)})}finally{ot=e}};this._processingStatus!==ht.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,H(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;const r=this._inTransition;this._inTransition=!0;try{const[t,r]=U(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),pt(r,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=r}}_next(t){for(const e of this.observers??ct)dt(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??ct,actions:this._collectedActions??ct,sent:this._collectedSent??ct,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 pt(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=F(t,e,s);if(this._processingStatus!==ht.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":dt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),dt(r.error,t)):b(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=F(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(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===ht.Running)return this;if(this._processingStatus===ht.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=ht.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,g(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,g(this.options.input)):(function(t,e,s){const r=C.get(t),i=B(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(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=U(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(at,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),pt(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){dt(()=>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)dt(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===ht.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ht.NotStarted?(this._processingStatus=ht.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??ct)dt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||b(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(b)}catch(i){b(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),dt(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===ht.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ht.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ht.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 m(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)}[S](){return this}getSnapshot(){return this._snapshot}}function _t(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 ft(t,r)}function vt(t,e){const s=t.check(e);if(s)throw s}const yt=new WeakMap;function mt(t,e,s){const r=function(t){let e=yt.get(t);return e||(e=new Map,yt.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},[P("@xstate.cleanup",()=>function(t){const e=yt.get(t);if(!e)return;let s;yt.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:M,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(K(n,e,t))},raise:t=>{o.push(K(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(P("@xstate.effect",(e=n.self.system)=>mt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(P("@xstate.effect",(t=n.self.system)=>mt(n.self,void 0,()=>c(t))))}},p=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),U(n,e,[l,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,[L(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&vt(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,g(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&vt(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},g(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const bt=new WeakMap;const St="xstate.observable.next",xt="xstate.observable.error",At="xstate.observable.complete";const wt="xstate.async.resolve",Et="xstate.async.reject";class kt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Tt=gt({context:void 0,run:()=>{}});t.TimeoutError=kt,t.createAsyncLogic=function(t){const e=t,s=gt({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:i,system:n},o)=>{switch(t.type){case wt:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Et:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===r)return o.effect((t=n)=>{const r=i,o=e=>{t.sendEvent(r,r,e)},c=new AbortController,a=e.timeout,h=N(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:Et,data:new kt(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},p=()=>{try{return Promise.resolve(e.run({input:s,system:n,self:i,signal:c.signal},{emit:e=>{f(r,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(r,e,s)):v(r,e,s,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(r,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:wt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:Et,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,T,{value:{kind:"async",timeout:e.timeout}}),s},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({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=bt.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return bt.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}),()=>{bt.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return _t(Tt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,r={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case xt:return U(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case At:return U(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case i:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&vt(s,{kind:"input",logic:r,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>r.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:xt,data:t})},complete:()=>{r._relay(s,s,{type:At})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return r},t.createListenerLogic=function(){return O(({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)||R(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case St:return{context:i.data};case xt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case At:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===r&&s.effect((t=c)=>{const s=o,r=e=>{t.sendEvent(s,s,e)},i=e({input:n,system:c,self:o,emit:e=>{f(s,e,t)}}).subscribe({next:t=>{r({type:St,data:t})},error:t=>{r({type:xt,data:t})},complete:()=>{r({type:At})}});return()=>i.unsubscribe()})}})},t.createStepLogic=gt,t.createSubscriptionLogic=function(){return O(({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?R(s,r,()=>i(t.output)):"error"===t.status&&n?R(s,r,()=>n(t.error)):"active"===t.status&&o&&R(s,r,()=>o(t))},error:t=>{n&&R(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},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";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 p(t){return new Error(e(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function l(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 p=new Promise((t,e)=>{u=t,d=e});let l,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,p);const v=()=>{l?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return p.then(v,v),l=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),p}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 m{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 g(t){return{type:r,input:t}}function b(t){setTimeout(()=>{throw t})}const S="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],A=new Error("Transition effect");function w(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:w(t.event)??t.event}}function k(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",w(t.event)??t.event])}(e)}`}const T=Symbol("xstate.systemLogicMetadata"),I=new WeakMap,O="xstate.attached.forward";function R(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],r={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})),I.set(s,{unsubscribe:a})},transition:(t,e,s)=>{const r=s.self;return e.type===O?[t,"active"===t.status&&r._parent?[q(s,r._parent,e.event)]:[]]:e.type===i?(I.get(r)?.unsubscribe(),I.delete(r),[{...t,status:"stopped",error:void 0},[]]):[t,[]]},initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t,isInternalEventType:t=>t===O};return Object.defineProperty(r,T,{value:{kind:e}}),r}function j(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t,{type:O,event:s()})}function M(t=this.source.system){return f(this.source,this.event,t)}function L(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function P(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:L,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function $(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function z(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function K(t=this.source.system){return 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 q(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:K,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function U(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:z,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function N(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,U(t,s)]]}function C(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)}const D=new WeakMap,W=new WeakMap,V=new Map;function B(t){t._snapshotVersion++}function J(t){return t._snapshotVersion}function H(t){const e=D.get(t);if(e)return e;const s=W.get(t);if(!s)return;const r=s();return D.set(t,r),W.delete(t),r}function F(t,e,s=e.system,r){W.delete(t);const i=J(s),n=r?H(r):void 0,o=n?.actor===e?n:H(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void D.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)??V:t.keyedActors}(s);let u=h.size?new Map(h):V;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===V&&(u=new Map),u.set(t,e))}D.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function X(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}:{}}}let G,Q=0;function Y(){return G??=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)}`}(),`${G}:${(Q++).toString(36)}`}function Z(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function tt(t,e){return`${t?t.address:""}|${e}`}function et(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},B(t))}function st(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?et(t,tt(s?.parent,r.prefix),r.index+1):s?.parent||et(t,tt(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=tt(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return et(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const rt=Object.freeze({});function it(t,e){return k(t,e)}function nt(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 ot{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:Y(),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:rt,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;if(!n._inTransition)return;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=it(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=nt(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===rt&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,B(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],B(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=it(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==rt&&delete this._snapshot._scheduledTimers[s],B(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&&l(i,r);if(!n){const e=p(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),B(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&&B(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&&B(this)}inspect(t){const e=X(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){b(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){b(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=l(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:p(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){b(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=nt(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 A;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 ct=!1;const at=Object.freeze([]),ht={"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 ut=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const dt=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function pt(t,e){try{t?.(e)}catch(t){b(t)}}function lt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function ft(t,e){return new _t(t,e)}class _t{get address(){return this._address??=this._parent?`${this._parent.address}/${Z(this.id)}`:Z(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=ut.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._inTransition=!1,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?{...dt,...e}:dt,{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 ot(t,e)}(this,{clock:r,logger:i,createActorRef:ft}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(X(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=st(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{this._inTransition=!0;try{const[t,e]=N(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}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===ut.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=ct;try{ct=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ut.Stopped&&this._recoverOrError(t)})}finally{ct=e}};this._processingStatus!==ut.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,F(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;const r=this._inTransition;this._inTransition=!0;try{const[t,r]=N(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),lt(r,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=r}}_next(t){for(const e of this.observers??at)pt(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??at,actions:this._collectedActions??at,sent:this._collectedSent??at,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 lt(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=X(t,e,s);if(this._processingStatus!==ut.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":pt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),pt(r.error,t)):b(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=X(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(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===ut.Running)return this;if(this._processingStatus===ut.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=ut.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,g(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,g(this.options.input)):(function(t,e,s){const r=D.get(t),i=J(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(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=N(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(ht,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),lt(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){pt(()=>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)pt(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===ut.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ut.NotStarted?(this._processingStatus=ut.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??at)pt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||b(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(b)}catch(i){b(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),pt(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===ut.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ut.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ut.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 m(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)}[S](){return this}getSnapshot(){return this._snapshot}}function vt(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 _t(t,r)}function yt(t,e){const s=t.check(e);if(s)throw s}const mt=new WeakMap;function gt(t,e,s){const r=function(t){let e=mt.get(t);return e||(e=new Map,mt.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 bt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[$("@xstate.cleanup",()=>function(t){const e=mt.get(t);if(!e)return;let s;mt.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:M,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(q(n,e,t))},raise:t=>{o.push(q(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($("@xstate.effect",(e=n.self.system)=>gt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push($("@xstate.effect",(t=n.self.system)=>gt(n.self,void 0,()=>c(t))))}},p=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),N(n,e,[l,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,[P(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&yt(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,g(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&yt(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},g(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const St=new WeakMap,xt="xstate.callback.sendBack";const At="xstate.observable.next",wt="xstate.observable.error",Et="xstate.observable.complete";const kt="xstate.async.resolve",Tt="xstate.async.reject";class It extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Ot=bt({context:void 0,run:()=>{}});t.TimeoutError=It,t.createAsyncLogic=function(t){const e=t,s=bt({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:i,system:n},o)=>{switch(t.type){case kt:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Tt:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===r)return o.effect((t=n)=>{const r=i,o=e=>{t.sendEvent(r,r,e)},c=new AbortController,a=e.timeout,h=C(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:Tt,data:new It(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},p=()=>{try{return Promise.resolve(e.run({input:s,system:n,self:i,signal:c.signal},{emit:e=>{f(r,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(r,e,s)):v(r,e,s,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(r,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:kt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:Tt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,T,{value:{kind:"async",timeout:e.timeout}}),s},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas,r="function"==typeof t?void 0:t.validator,i=bt({validator:r&&{check:t=>"event"===t.kind&&t.event.type===xt?void 0:r.check(t)},schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t;if(r.type===xt)return void s.sendBack(r.event);const c=t.emit,a=St.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return St.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;n._parent&&o._relay(n,n,{type:xt,event:t})},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{St.delete(n),t.receivers?.clear(),t.dispose?.()}})}});return Object.assign(i,{isInternalEventType:t=>t===xt}),i},t.createEmptyActor=function(){return vt(Ot)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,r={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case At:{const r=s.self._parent;return[t,r?[q(s,r,e.data)]:[]]}case wt:return N(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case Et:return N(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case i:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&yt(s,{kind:"input",logic:r,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>r.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,{type:At,data:t})},error:t=>{r._relay(s,s,{type:wt,data:t})},complete:()=>{r._relay(s,s,{type:Et})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return Object.assign(r,{isInternalEventType:t=>t===At||t===wt||t===Et}),r},t.createListenerLogic=function(){return R(({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)||j(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return bt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case At:return{context:i.data};case wt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case Et:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===r&&s.effect((t=c)=>{const s=o,r=e=>{t.sendEvent(s,s,e)},i=e({input:n,system:c,self:o,emit:e=>{f(s,e,t)}}).subscribe({next:t=>{r({type:At,data:t})},error:t=>{r({type:wt,data:t})},complete:()=>{r({type:Et})}});return()=>i.unsubscribe()})}})},t.createStepLogic=bt,t.createSubscriptionLogic=function(){return R(({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?j(s,r,()=>i(t.output)):"error"===t.status&&n?j(s,r,()=>n(t.error)):"active"===t.status&&o&&j(s,r,()=>o(t))},error:t=>{n&&j(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map