xstate 5.17.4 → 5.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,6 +7,8 @@ interface WaitForOptions {
7
7
  * @defaultValue Infinity
8
8
  */
9
9
  timeout: number;
10
+ /** A signal which stops waiting when aborted. */
11
+ signal?: AbortSignal;
10
12
  }
11
13
  /**
12
14
  * Subscribes to an actor ref and waits for its emitted value to satisfy a
@@ -823,15 +823,25 @@ function waitFor(actorRef, predicate, options) {
823
823
  ...options
824
824
  };
825
825
  return new Promise((res, rej) => {
826
+ const {
827
+ signal
828
+ } = resolvedOptions;
829
+ if (signal?.aborted) {
830
+ rej(signal.reason);
831
+ return;
832
+ }
826
833
  let done = false;
827
834
  const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
828
- sub.unsubscribe();
835
+ dispose();
829
836
  rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
830
837
  }, resolvedOptions.timeout);
831
838
  const dispose = () => {
832
839
  clearTimeout(handle);
833
840
  done = true;
834
841
  sub?.unsubscribe();
842
+ if (abortListener) {
843
+ signal.removeEventListener('abort', abortListener);
844
+ }
835
845
  };
836
846
  function checkEmitted(emitted) {
837
847
  if (predicate(emitted)) {
@@ -839,6 +849,12 @@ function waitFor(actorRef, predicate, options) {
839
849
  res(emitted);
840
850
  }
841
851
  }
852
+
853
+ /**
854
+ * If the `signal` option is provided, this will be the listener for its
855
+ * `abort` event
856
+ */
857
+ let abortListener;
842
858
  let sub; // avoid TDZ when disposing synchronously
843
859
 
844
860
  // See if the current snapshot already matches the predicate
@@ -846,6 +862,16 @@ function waitFor(actorRef, predicate, options) {
846
862
  if (done) {
847
863
  return;
848
864
  }
865
+
866
+ // only define the `abortListener` if the `signal` option is provided
867
+ if (signal) {
868
+ abortListener = () => {
869
+ dispose();
870
+ // XState does not "own" the signal, so we should reject with its reason (if any)
871
+ rej(signal.reason);
872
+ };
873
+ signal.addEventListener('abort', abortListener);
874
+ }
849
875
  sub = actorRef.subscribe({
850
876
  next: checkEmitted,
851
877
  error: err => {
@@ -826,18 +826,28 @@ function waitFor(actorRef, predicate, options) {
826
826
  ...options
827
827
  };
828
828
  return new Promise((res, rej) => {
829
+ const {
830
+ signal
831
+ } = resolvedOptions;
832
+ if (signal?.aborted) {
833
+ rej(signal.reason);
834
+ return;
835
+ }
829
836
  let done = false;
830
837
  if (resolvedOptions.timeout < 0) {
831
838
  console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
832
839
  }
833
840
  const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
834
- sub.unsubscribe();
841
+ dispose();
835
842
  rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
836
843
  }, resolvedOptions.timeout);
837
844
  const dispose = () => {
838
845
  clearTimeout(handle);
839
846
  done = true;
840
847
  sub?.unsubscribe();
848
+ if (abortListener) {
849
+ signal.removeEventListener('abort', abortListener);
850
+ }
841
851
  };
842
852
  function checkEmitted(emitted) {
843
853
  if (predicate(emitted)) {
@@ -845,6 +855,12 @@ function waitFor(actorRef, predicate, options) {
845
855
  res(emitted);
846
856
  }
847
857
  }
858
+
859
+ /**
860
+ * If the `signal` option is provided, this will be the listener for its
861
+ * `abort` event
862
+ */
863
+ let abortListener;
848
864
  let sub; // avoid TDZ when disposing synchronously
849
865
 
850
866
  // See if the current snapshot already matches the predicate
@@ -852,6 +868,16 @@ function waitFor(actorRef, predicate, options) {
852
868
  if (done) {
853
869
  return;
854
870
  }
871
+
872
+ // only define the `abortListener` if the `signal` option is provided
873
+ if (signal) {
874
+ abortListener = () => {
875
+ dispose();
876
+ // XState does not "own" the signal, so we should reject with its reason (if any)
877
+ rej(signal.reason);
878
+ };
879
+ signal.addEventListener('abort', abortListener);
880
+ }
855
881
  sub = actorRef.subscribe({
856
882
  next: checkEmitted,
857
883
  error: err => {
@@ -824,18 +824,28 @@ function waitFor(actorRef, predicate, options) {
824
824
  ...options
825
825
  };
826
826
  return new Promise((res, rej) => {
827
+ const {
828
+ signal
829
+ } = resolvedOptions;
830
+ if (signal?.aborted) {
831
+ rej(signal.reason);
832
+ return;
833
+ }
827
834
  let done = false;
828
835
  if (resolvedOptions.timeout < 0) {
829
836
  console.error('`timeout` passed to `waitFor` is negative and it will reject its internal promise immediately.');
830
837
  }
831
838
  const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
832
- sub.unsubscribe();
839
+ dispose();
833
840
  rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
834
841
  }, resolvedOptions.timeout);
835
842
  const dispose = () => {
836
843
  clearTimeout(handle);
837
844
  done = true;
838
845
  sub?.unsubscribe();
846
+ if (abortListener) {
847
+ signal.removeEventListener('abort', abortListener);
848
+ }
839
849
  };
840
850
  function checkEmitted(emitted) {
841
851
  if (predicate(emitted)) {
@@ -843,6 +853,12 @@ function waitFor(actorRef, predicate, options) {
843
853
  res(emitted);
844
854
  }
845
855
  }
856
+
857
+ /**
858
+ * If the `signal` option is provided, this will be the listener for its
859
+ * `abort` event
860
+ */
861
+ let abortListener;
846
862
  let sub; // avoid TDZ when disposing synchronously
847
863
 
848
864
  // See if the current snapshot already matches the predicate
@@ -850,6 +866,16 @@ function waitFor(actorRef, predicate, options) {
850
866
  if (done) {
851
867
  return;
852
868
  }
869
+
870
+ // only define the `abortListener` if the `signal` option is provided
871
+ if (signal) {
872
+ abortListener = () => {
873
+ dispose();
874
+ // XState does not "own" the signal, so we should reject with its reason (if any)
875
+ rej(signal.reason);
876
+ };
877
+ signal.addEventListener('abort', abortListener);
878
+ }
853
879
  sub = actorRef.subscribe({
854
880
  next: checkEmitted,
855
881
  error: err => {
@@ -821,15 +821,25 @@ function waitFor(actorRef, predicate, options) {
821
821
  ...options
822
822
  };
823
823
  return new Promise((res, rej) => {
824
+ const {
825
+ signal
826
+ } = resolvedOptions;
827
+ if (signal?.aborted) {
828
+ rej(signal.reason);
829
+ return;
830
+ }
824
831
  let done = false;
825
832
  const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {
826
- sub.unsubscribe();
833
+ dispose();
827
834
  rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));
828
835
  }, resolvedOptions.timeout);
829
836
  const dispose = () => {
830
837
  clearTimeout(handle);
831
838
  done = true;
832
839
  sub?.unsubscribe();
840
+ if (abortListener) {
841
+ signal.removeEventListener('abort', abortListener);
842
+ }
833
843
  };
834
844
  function checkEmitted(emitted) {
835
845
  if (predicate(emitted)) {
@@ -837,6 +847,12 @@ function waitFor(actorRef, predicate, options) {
837
847
  res(emitted);
838
848
  }
839
849
  }
850
+
851
+ /**
852
+ * If the `signal` option is provided, this will be the listener for its
853
+ * `abort` event
854
+ */
855
+ let abortListener;
840
856
  let sub; // avoid TDZ when disposing synchronously
841
857
 
842
858
  // See if the current snapshot already matches the predicate
@@ -844,6 +860,16 @@ function waitFor(actorRef, predicate, options) {
844
860
  if (done) {
845
861
  return;
846
862
  }
863
+
864
+ // only define the `abortListener` if the `signal` option is provided
865
+ if (signal) {
866
+ abortListener = () => {
867
+ dispose();
868
+ // XState does not "own" the signal, so we should reject with its reason (if any)
869
+ rej(signal.reason);
870
+ };
871
+ signal.addEventListener('abort', abortListener);
872
+ }
847
873
  sub = actorRef.subscribe({
848
874
  next: checkEmitted,
849
875
  error: err => {
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,(function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s=".",n="",o="",i="xstate.init",r="xstate.error",a="xstate.stop";function c(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const u=t=>{const e=c();e&&e.register(t)};function h(t,e){return{type:`xstate.done.state.${t}`,output:e}}function f(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function d(t){return{type:i,input:t}}function p(t){setTimeout((()=>{throw t}))}const l="function"==typeof Symbol&&Symbol.observable||"@@observable";function y(t,e){const s=v(t),n=v(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every((t=>t in n&&y(s[t],n[t])))}function g(t){if(w(t))return t;let e=[],s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function v(t){if(te(t))return t.value;if("string"!=typeof t)return t;return m(g(t))}function m(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function _(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function b(t){return w(t)?t:[t]}function S(t){return void 0===t?[]:b(t)}function x(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function w(t){return Array.isArray(t)}function I(t){return b(t).map((t=>void 0===t||"string"==typeof t?{target:t}:t))}function k(t){if(void 0!==t&&t!==n)return S(t)}function $(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function E(t,e){return`${e}.${t}`}function T(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function O(t,e){return`${t.sessionId}.${e}`}let j=0;const A=1;let M=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const N={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class P{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=M.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...N,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:u,inspect:h}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=O(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout((()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)}),n);r[c]=u},cancel:(t,e)=>{const s=O(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+j++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=$(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),h&&!r&&this.system.inspect($(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=new Set([...e?e.values():[],...s?s.values():[]]);for(const e of Array.from(n))e(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState(s?.snapshot??s?.state),u&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){p(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){p(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=$(t,e,s);if(this._processingStatus!==M.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){p(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){p(t)}else p(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===M.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=M.Running;const t=d(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===a&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===M.Stopped?this:(this.mailbox.clear(),this._processingStatus===M.NotStarted?(this._processingStatus=M.Stopped,this):(this.mailbox.enqueue({type:a}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){p(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||p(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){p(t)}}this.observers.clear(),e&&p(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,f(this.id,t))}_stopProcedure(){return this._processingStatus!==M.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=M.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==M.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:u)(this)}}toJSON(){return{xstate$$type:A,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[l](){return this}getSnapshot(){return this._snapshot}}function R(t,...[e]){return new P(t,e)}const C=R;function D(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r={})=>{const{systemId:a,input:c}=r;if("string"==typeof i){const u=T(e,i);if(!u)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const h=R(u,{id:r.id,parent:t.self,syncSnapshot:r.syncSnapshot,input:"function"==typeof c?c({context:s,event:n,self:t.self}):c,src:i,systemId:a});return o[h.id]=h,h}return R(i,{id:r.id,parent:t.self,syncSnapshot:r.syncSnapshot,input:r.input,src:i,systemId:a})})(i,r);return o[a.id]=a,t.defer((()=>{a._processingStatus!==M.Stopped&&a.start()})),a}}function J(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:D(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[ae(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children})]}function V(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=J,e}function B(t,e,s,n,{sendId:o}){return[e,"function"==typeof o?o(s,n):o]}function z(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e)}))}function W(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=B,e.execute=z,e}function q(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o}]}function L(t,{event:e}){t.defer((()=>t.emit(e)))}function U(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=q,e.execute=L,e}function Q(t,e,{stateValue:s}){if("string"==typeof s&&It(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some((t=>t===e))}return t.matches(s)}function F(t,{context:e,event:s},{guards:n}){return!H(n[0],e,s,t)}function G(t,{context:e,event:s},{guards:n}){return n.every((n=>H(n,e,s,t)))}function X(t,{context:e,event:s},{guards:n}){return n.some((n=>H(n,e,s,t)))}function H(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return H(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function K(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h}]}function Y(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}function Z(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=K,s.execute=Y,s}let tt=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function et(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let f;if("string"==typeof a){const t=u&&u[a];f="function"==typeof t?t(s,n):t}else f="function"==typeof a?a(s,n):a;const d="function"==typeof o?o(s,n):o;let p;if("string"==typeof d){if(p=d===tt.Parent?t.self._parent:d===tt.Internal?t.self:d.startsWith("#_")?e.children[d.slice(2)]:c.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,event:h,id:r,delay:f}]}function st(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function nt(t,e){t.defer((()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,n.type===r?f(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)}))}function ot(t,e,s){function n(t,e){}return n.type="xsnapshot.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=et,n.retryResolve=st,n.execute=nt,n}function it(t,e){return ot(tt.Parent,t,e)}function rt(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?T(e.machine,r):r,h="function"==typeof o?o(s):o;let f;return u&&(f=R(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:"function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a})),[ae(e,{children:{...e.children,[h]:f}}),{id:o,actorRef:f}]}function at(t,{id:e,actorRef:s}){s&&t.defer((()=>{s._processingStatus!==M.Stopped&&s.start()}))}function ct(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="snapshot.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=rt,i.execute=at,i}function ut(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[ae(e,{children:a}),r]}function ht(t,e){e&&(t.system._unregister(e),e._processingStatus===M.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function ft(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=ut,e.execute=ht,e}const dt=ft;function pt(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(V(...t))},r.cancel=(...t)=>{i.push(W(...t))},r.raise=(...t)=>{i.push(Z(...t))},r.sendTo=(...t)=>{i.push(ot(...t))},r.sendParent=(...t)=>{i.push(it(...t))},r.spawnChild=(...t)=>{i.push(ct(...t))},r.stopChild=(...t)=>{i.push(ft(...t))},r.emit=(...t)=>{i.push(U(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>H(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function lt(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i}]}function yt({logger:t},{value:e,label:s}){s?t(s,e):t(e)}const gt=t=>"atomic"===t.type||"final"===t.type;function vt(t){return Object.values(t.states).filter((t=>"history"!==t.type))}function mt(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function _t(t){const e=new Set(t),s=St(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of vt(t))if("history"!==s.type&&!e.has(s)){const t=Ot(s);for(const s of t)e.add(s)}}else Ot(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function bt(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(gt(t))return t.key}const n={};for(const t of s)n[t.key]=bt(t,e);return n}function St(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function xt(t,e){return bt(t,St(_t(e)))}function wt(t,e){return"compound"===e.type?vt(e).some((e=>"final"===e.type&&t.has(e))):"parallel"===e.type?vt(e).every((e=>wt(t,e))):"final"===e.type}const It=t=>"#"===t[0];function kt(t){const e=t.config.after;if(!e)return[];return Object.keys(e).flatMap(((s,n)=>{const o=e[s],i="string"==typeof o?{target:o}:o,r=Number.isNaN(+s)?s:+s,a=((e,s)=>{const n=(o=e,i=t.id,{type:`xstate.after.${o}.${i}`});var o,i;const r=n.type;return t.entry.push(Z(n,{id:r,delay:e})),t.exit.push(W(r)),r})(r);return S(i).map((t=>({...t,event:a,delay:r})))})).map((e=>{const{delay:s}=e;return{...$t(t,e.event,e),delay:s}}))}function $t(t,e,n){const o=k(n.target),i=n.reenter??!1,r=function(t,e){if(void 0===e)return;return e.map((e=>{if("string"!=typeof e)return e;if(It(e))return t.machine.getStateNodeById(e);const n=e[0]===s;if(n&&!t.parent)return Mt(t,e.slice(1));const o=n?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return Mt(t.parent,o)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}}))}(t,o),a={...n,actions:S(n.actions),guard:n.guard,target:r,source:t,reenter:i,eventType:e,toJSON:()=>({...a,source:`#${t.id}`,target:r?r.map((t=>`#${t.id}`)):void 0})};return a}function Et(t){const e=k(t.config.target);return e?{target:e.map((e=>"string"==typeof e?Mt(t.parent,e):e))}:t.parent.initial}function Tt(t){return"history"===t.type}function Ot(t){const e=jt(t);for(const s of e)for(const n of mt(s,t))e.add(n);return e}function jt(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of vt(s))t(e)}(t),e}function At(t,e){if(It(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function Mt(t,e){if("string"==typeof e&&It(e))try{return t.machine.getStateNodeById(e)}catch(t){}const s=g(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=At(n,t)}return n}function Nt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map((e=>At(t,e))).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce(((s,n)=>{const o=At(t,n);if(!o)return s;const i=Nt(o,e[n]);return s.concat(i)}),[]))}function Pt(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=At(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=Pt(At(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=Pt(At(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function Rt(t){return Object.keys(t.states).map((e=>t.states[e])).filter((t=>"history"===t.type))}function Ct(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Dt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function Jt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(Dt(zt([o],e,s),zt([r],e,s))){if(!Ct(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function Vt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(Tt(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of Vt(Et(n),e))s.add(t);else s.add(n);return[...s]}function Bt(t,e){const s=Vt(t,e);if(!s)return;if(!t.reenter&&s.every((e=>e===t.source||Ct(e,t.source))))return t.source;const n=function(t){const[e,...s]=t;for(const t of mt(e,void 0))if(s.every((e=>Ct(e,t))))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function zt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=Bt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)Ct(s,t)&&n.add(s)}return[...n]}function Wt(t,e,s,n,o,i){if(!t.length)return e;const r=new Set(e._nodes);let a=e.historyValue;const c=Jt(t,r,a);let u=e;o||([u,a]=function(t,e,s,n,o,i,r){let a=t;const c=zt(n,o,i);let u;c.sort(((t,e)=>e.order-t.order));for(const t of c)for(const e of Rt(t)){let s;s="deep"===e.history?e=>gt(e)&&Ct(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=Xt(a,e,s,[...t.exit,...t.invoke.map((t=>ft(t.id)))],r),o.delete(t);return[a,u||i]}(u,n,s,c,r,a,i)),u=Xt(u,n,s,c.flatMap((t=>t.actions)),i),u=function(t,e,s,n,o,i,r,a){let c=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=Bt(o,e);for(const i of o.target||[])Tt(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),Lt(i,e,s,n);const i=Vt(o,e);for(const r of i){const i=mt(r,t);"parallel"===t?.type&&i.push(t),Ut(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,r,f,u),a&&f.add(t.machine.root);const d=new Set;for(const t of[...u].sort(((t,e)=>t.order-e.order))){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(ct(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(c=Xt(c,e,s,n,i,t.invoke.map((t=>t.id))),"final"===t.type){const n=t.parent;let r="parallel"===n?.type?n:n?.parent,a=r||t;for("compound"===n?.type&&i.push(h(n.id,void 0!==t.output?x(t.output,c.context,e,s.self):void 0));"parallel"===r?.type&&!d.has(r)&&wt(o,r);)d.add(r),i.push(h(r.id)),a=r,r=r.parent;if(r)continue;c=ae(c,{status:"done",output:qt(c,e,s,c.machine.root,a)})}}return c}(u,n,s,c,r,i,a,o);const f=[...r];"done"===u.status&&(u=Xt(u,n,s,f.sort(((t,e)=>e.order-t.order)).flatMap((t=>t.exit)),i));try{return a===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,r)?u:ae(u,{_nodes:f,historyValue:a})}catch(t){throw t}}function qt(t,e,s,n,o){if(void 0===n.output)return;const i=h(o.id,void 0!==o.output&&o.parent?x(o.output,t.context,e,s.self):void 0);return x(n.output,t.context,i,s.self)}function Lt(t,e,s,n){if(Tt(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),Lt(t,e,s,n);for(const i of o)Qt(i,t.parent,n,e,s)}else{const o=Et(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),Lt(i,e,s,n);for(const i of o.target)Qt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;Tt(o)||(n.add(o),s.add(o)),Lt(o,e,s,n),Qt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of vt(t).filter((t=>!Tt(t))))[...n].some((t=>Ct(t,o)))||(Tt(o)||(n.add(o),s.add(o)),Lt(o,e,s,n))}function Ut(t,e,s,n,o){for(const i of n)if(o&&!Ct(i,o)||t.add(i),"parallel"===i.type)for(const n of vt(i).filter((t=>!Tt(t))))[...t].some((t=>Ct(t,n)))||(t.add(n),Lt(n,e,s,t))}function Qt(t,e,s,n,o){Ut(s,n,o,mt(t,e))}let Ft=!1;function Gt(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const c of n){const u="function"==typeof c,h=u?c:r.implementations.actions["string"==typeof c?c:c.type];if(!h)continue;const f={context:a.context,event:e,self:s.self,system:s.system},d=u||"string"==typeof c?void 0:"params"in c?"function"==typeof c.params?c.params({context:a.context,event:e}):c.params:void 0;function p(){s.system._sendInspectionEvent({type:"@xstate.action",actorRef:s.self,action:{type:"string"==typeof c?c:"object"==typeof c?c.type:c.name||"(anonymous)",params:d}});try{Ft=h,h(f,d)}finally{Ft=!1}}if(!("resolve"in h)){s.self._processingStatus===M.Running?p():s.defer((()=>{p()}));continue}const l=h,[y,g,v]=l.resolve(s,a,f,d,h,o);a=y,"retryResolve"in l&&i?.push([l,g]),"execute"in l&&(s.self._processingStatus===M.Running?l.execute(s,g):s.defer(l.execute.bind(null,s,g))),v&&(a=Gt(a,e,s,v,o,i))}return a}function Xt(t,e,s,n,o,i){const r=i?[]:void 0,a=Gt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach((([t,e])=>{t.retryResolve(s,a,e)})),a}function Ht(t,e,s,n=[]){let o=t;const r=[];function c(t,e,n){s.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:s.self,event:e,snapshot:t,_transitions:n}),r.push(t)}if(e.type===a)return o=ae(Kt(o,e,s),{status:"stopped"}),c(o,e,[]),{snapshot:o,microstates:r};let u=e;if(u.type!==i){const e=u,i=function(t){return t.type.startsWith("xstate.error.actor")}(e),a=Yt(e,o);if(i&&!a.length)return o=ae(t,{status:"error",error:e.error}),c(o,e,[]),{snapshot:o,microstates:r};o=Wt(a,t,s,u,!1,n),c(o,e,a)}let h=!0;for(;"active"===o.status;){let t=h?Zt(o,u):[];const e=t.length?o:void 0;if(!t.length){if(!n.length)break;u=n.shift(),t=Yt(u,o)}o=Wt(t,o,s,u,!1,n),h=o!==e,c(o,u,t)}return"active"!==o.status&&Kt(o,u,s),{snapshot:o,microstates:r}}function Kt(t,e,s){return Xt(t,e,s,Object.values(t.children).map((t=>ft(t))),[])}function Yt(t,e){return e.machine.getTransitionData(e,t)}function Zt(t,e){const s=new Set,n=t._nodes.filter(gt);for(const o of n)t:for(const n of[o].concat(mt(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||H(o.guard,t.context,e,t)){s.add(o);break t}return Jt(Array.from(s),new Set(t._nodes),t.historyValue)}function te(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const ee=function(t){return y(t,this.value)},se=function(t){return this.tags.has(t)},ne=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},oe=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},ie=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function re(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:xt(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:ee,hasTag:se,can:ne,getMeta:ie,toJSON:oe}}function ae(t,e={}){return re({...t,...e},t.machine)}function ce(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:A,id:n.id};else{const o=ce(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}const ue=new WeakMap;function he(t,e,s){let n=ue.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ue.set(t,n)),n[e]}const fe={},de=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class pe{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(s),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?_(this.config.states,((t,e)=>new pe(t,{_parent:this,_key:e,_machine:this.machine}))):fe,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=S(this.config.entry).slice(),this.exit=S(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=S(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(s===o)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,I(n).map((e=>$t(t,s,e))))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,I(t.config.onDone).map((e=>$t(t,s,e))))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,I(s.onDone).map((e=>$t(t,n,e))))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,I(s.onError).map((e=>$t(t,n,e))))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,I(s.onSnapshot).map((e=>$t(t,n,e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=I(this.config.always).map((t=>$t(this,o,t)))),Object.keys(this.states).forEach((t=>{this.states[t]._initialize()}))}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(de),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((t=>`#${t.id}`)),source:`#${this.id}`,actions:this.initial.actions.map(de),eventType:null})}:void 0,history:this.history,states:_(this.states,(t=>t.definition)),on:this.on,transitions:[...this.transitions.values()].flat().map((t=>({...t,actions:t.actions.map(de)}))),entry:this.entry.map(de),exit:this.exit.map(de),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return he(this,"invoke",(()=>S(this.config.invoke).map(((t,e)=>{const{src:s,systemId:n}=t,o=t.id??E(this.id,e),i="string"==typeof s?s:`xstate.invoke.${E(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))))}get on(){return he(this,"on",(()=>[...this.transitions].flatMap((([t,e])=>e.map((e=>[t,e])))).reduce(((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t)),{})))}get after(){return he(this,"delayedTransitions",(()=>kt(this)))}get initial(){return he(this,"initial",(()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?S(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial)))}next(t,e){const s=e.type,n=[];let o;const i=he(this,`candidates-${s}`,(()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter((t=>{if("*"===t)return!0;if(!t.endsWith(".*"))return!1;const s=t.split("."),n=e.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e)return t===s.length-1;if(e!==o)return!1}return!0})).sort(((t,e)=>e.length-t.length)).flatMap((e=>t.transitions.get(e)));var t,e}));for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||H(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return he(this,"events",(()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)}))}get ownEvents(){const t=new Set([...this.transitions.keys()].filter((t=>this.transitions.get(t).some((t=>!(!t.target&&!t.actions.length&&!t.reenter))))));return Array.from(t)}}class le{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new pe(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new le(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,xt(s,[..._t(Nt(s,n))]));var s,n;const o=_t(Nt(this.root,e));return re({_nodes:[...o],context:t.context||{},children:{},status:wt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ht(t,e,s).snapshot}microstep(t,e,s){return Ht(t,e,s).microstates}getTransitionData(t,e){return Pt(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:n}=this.config,o=re({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return Xt(o,e,t,[V((({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s})))],s)}return o}getInitialSnapshot(t,e){const s=d(e),n=[],o=this.getPreInitialState(t,s,n),i=Wt([{target:[...jt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,s,!0,n),{snapshot:r}=Ht(i,s,t,n);return r}start(t){Object.values(t.children).forEach((t=>{"active"===t.getSnapshot().status&&t.start()}))}getStateNodeById(t){const e=g(t),s=e.slice(1),n=It(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return Mt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s._systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:ce(r),children:p}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;Object.keys(n).forEach((t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?T(this,r):r;if(!a)return;const c=R(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c}));const o=re({...t,children:s,_nodes:Array.from(_t(Nt(this.root,t.value)))},this);let i=new Set;return function t(e,s){if(!i.has(e)){i.add(e);for(let n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&o.xstate$$type===A){e[n]=s[o.id];continue}t(o,s)}}}}(o.context,s),o}}function ye(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const ge=new WeakMap;const ve="xstate.observable.next",me="xstate.observable.error",_e="xstate.observable.complete";const be="xstate.promise.resolve",Se="xstate.promise.reject",xe=new WeakMap;const we=ye((t=>{}),void 0);function Ie(t,e){return new le(t,e)}function ke(t){const e=R(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{}}}const $e={timeout:1/0};t.Actor=P,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort((([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1}));for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=tt,t.StateMachine=le,t.StateNode=pe,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap((t=>t.ownEvents))])]},t.and=function(t){function e(t,e){return!1}return e.check=G,e.guards=t,e},t.assertEvent=function(t,e){const s=S(e);if(!s.includes(t.type)){const e=1===s.length?`type "${s[0]}"`:`one of types "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=V,t.cancel=W,t.createActor=R,t.createEmptyActor=function(){return R(we)},t.createMachine=Ie,t.emit=U,t.enqueueActions=function(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=pt,e},t.forwardTo=function(t,e){return ot(t,(({event:t})=>t),e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};ge.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const n=ge.get(s.self);return e.type===a?(t={...t,status:"stopped",error:void 0},n.dispose?.(),t):(n.receivers?.forEach((t=>t(e))),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case me:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case _e:return{...t,status:"done",input:void 0,_subscription:void 0};case a:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:me,data:t})},complete:()=>{n._relay(s,s,{type:_e})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case ve:return{...t,context:e.data};case me:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case _e:return{...t,status:"done",input:void 0,_subscription:void 0};case a:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:ve,data:t})},error:t=>{n._relay(s,s,{type:me,data:t})},complete:()=>{n._relay(s,s,{type:_e})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case be:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case Se:return{...t,status:"error",error:e.data,input:void 0};case a:return xe.get(s.self)?.abort(),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;xe.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then((t=>{"active"===s.getSnapshot().status&&(xe.delete(s),n._relay(s,s,{type:be,data:t}))}),(t=>{"active"===s.getSnapshot().status&&(xe.delete(s),n._relay(s,s,{type:Se,data:t}))}))},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=ye,t.getInitialSnapshot=function(t,...[e]){const s=ke(t);return t.getInitialSnapshot(s,e)},t.getNextSnapshot=function(t,e,s){const n=ke(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getStateNodes=Nt,t.interpret=C,t.isMachineSnapshot=te,t.log=function(t=(({context:t,event:e})=>({context:t,event:e})),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=lt,s.execute=yt,s},t.matchesState=y,t.not=function(t){function e(t,e){return!1}return e.check=F,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=X,e.guards=t,e},t.pathToStateValue=m,t.raise=Z,t.sendParent=it,t.sendTo=ot,t.setup=function({schemas:t,actors:e,actions:s,guards:n,delays:o}){return{createMachine:i=>Ie({...i,schemas:t},{actors:e,actions:s,guards:n,delays:o})}},t.spawnChild=ct,t.stateIn=function(t){function e(t,e){return!1}return e.check=Q,e.stateValue=t,e},t.stop=dt,t.stopChild=ft,t.toObserver=$,t.toPromise=function(t){return new Promise(((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})}))},t.waitFor=function(t,e,s){const n={...$e,...s};return new Promise(((s,o)=>{let i=!1;const r=n.timeout===1/0?void 0:setTimeout((()=>{u.unsubscribe(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))}),n.timeout),a=()=>{clearTimeout(r),i=!0,u?.unsubscribe()};function c(t){e(t)&&(a(),s(t))}let u;c(t.getSnapshot()),i||(u=t.subscribe({next:c,error:t=>{a(),o(t)},complete:()=>{a(),o(new Error("Actor terminated without satisfying predicate"))}}),i&&u.unsubscribe())}))},Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XState={})}(this,(function(t){"use strict";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s=".",n="",o="",i="xstate.init",r="xstate.error",a="xstate.stop";function c(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const u=t=>{const e=c();e&&e.register(t)};function h(t,e){return{type:`xstate.done.state.${t}`,output:e}}function f(t,e){return{type:`xstate.error.actor.${t}`,error:e,actorId:t}}function d(t){return{type:i,input:t}}function p(t){setTimeout((()=>{throw t}))}const l="function"==typeof Symbol&&Symbol.observable||"@@observable";function y(t,e){const s=v(t),n=v(e);return"string"==typeof n?"string"==typeof s&&n===s:"string"==typeof s?s in n:Object.keys(s).every((t=>t in n&&y(s[t],n[t])))}function g(t){if(w(t))return t;let e=[],s="";for(let n=0;n<t.length;n++){switch(t.charCodeAt(n)){case 92:s+=t[n+1],n++;continue;case 46:e.push(s),s="";continue}s+=t[n]}return e.push(s),e}function v(t){if(te(t))return t.value;if("string"!=typeof t)return t;return m(g(t))}function m(t){if(1===t.length)return t[0];const e={};let s=e;for(let e=0;e<t.length-1;e++)if(e===t.length-2)s[t[e]]=t[e+1];else{const n=s;s={},n[t[e]]=s}return e}function _(t,e){const s={},n=Object.keys(t);for(let o=0;o<n.length;o++){const i=n[o];s[i]=e(t[i],i,t,o)}return s}function b(t){return w(t)?t:[t]}function S(t){return void 0===t?[]:b(t)}function x(t,e,s,n){return"function"==typeof t?t({context:e,event:s,self:n}):t}function w(t){return Array.isArray(t)}function I(t){return b(t).map((t=>void 0===t||"string"==typeof t?{target:t}:t))}function k(t){if(void 0!==t&&t!==n)return S(t)}function $(t,e,s){const n="object"==typeof t,o=n?t:void 0;return{next:(n?t.next:t)?.bind(o),error:(n?t.error:e)?.bind(o),complete:(n?t.complete:s)?.bind(o)}}function E(t,e){return`${e}.${t}`}function T(t,e){const s=e.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!s)return t.implementations.actors[e];const[,n,o]=s,i=t.getStateNodeById(o).config.invoke;return(Array.isArray(i)?i[n]:i).src}function O(t,e){return`${t.sessionId}.${e}`}let j=0;const A=1;let M=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const N={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class P{constructor(t,s){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new e(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=M.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const n={...N,...s},{clock:o,logger:i,parent:r,syncSnapshot:a,id:c,systemId:u,inspect:h}=n;this.system=r?r.system:function(t,e){const s=new Map,n=new Map,o=new WeakMap,i=new Set,r={},{clock:a,logger:c}=e,u={schedule:(t,e,s,n,o=Math.random().toString(36).slice(2))=>{const i={source:t,target:e,event:s,delay:n,id:o,startedAt:Date.now()},c=O(t,o);h._snapshot._scheduledEvents[c]=i;const u=a.setTimeout((()=>{delete r[c],delete h._snapshot._scheduledEvents[c],h._relay(t,e,s)}),n);r[c]=u},cancel:(t,e)=>{const s=O(t,e),n=r[s];delete r[s],delete h._snapshot._scheduledEvents[s],void 0!==n&&a.clearTimeout(n)},cancelAll:t=>{for(const e in h._snapshot._scheduledEvents){const s=h._snapshot._scheduledEvents[e];s.source===t&&u.cancel(t,s.id)}}},h={_snapshot:{_scheduledEvents:(e?.snapshot&&e.snapshot.scheduler)??{}},_bookId:()=>"x:"+j++,_register:(t,e)=>(s.set(t,e),t),_unregister:t=>{s.delete(t.sessionId);const e=o.get(t);void 0!==e&&(n.delete(e),o.delete(t))},get:t=>n.get(t),_set:(t,e)=>{const s=n.get(t);if(s&&s!==e)throw new Error(`Actor with system ID '${t}' already exists.`);n.set(t,e),o.set(e,t)},inspect:t=>{const e=$(t);return i.add(e),{unsubscribe(){i.delete(e)}}},_sendInspectionEvent:e=>{if(!i.size)return;const s={...e,rootId:t.sessionId};i.forEach((t=>t.next?.(s)))},_relay:(t,e,s)=>{h._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:e,event:s}),e._send(s)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...h._snapshot._scheduledEvents}}),start:()=>{const t=h._snapshot._scheduledEvents;h._snapshot._scheduledEvents={};for(const e in t){const{source:s,target:n,event:o,delay:i,id:r}=t[e];u.schedule(s,n,o,i,r)}},_clock:a,_logger:c};return h}(this,{clock:o,logger:i}),h&&!r&&this.system.inspect($(h)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=s?.logger??this.system._logger,this.clock=s?.clock??this.system._clock,this._parent=r,this._syncSnapshot=a,this.options=n,this.src=n.src??t,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:t=>{this._deferred.push(t)},system:this.system,stopChild:t=>{if(t._parent!==this)throw new Error(`Cannot stop child actor ${t.id} of ${this.id} because it is not a child`);t._stop()},emit:t=>{const e=this.eventListeners.get(t.type),s=this.eventListeners.get("*");if(!e&&!s)return;const n=new Set([...e?e.values():[],...s?s.values():[]]);for(const e of Array.from(n))e(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState(s?.snapshot??s?.state),u&&"active"!==this._snapshot.status&&this.system._unregister(this)}_initState(t){try{this._snapshot=t?this.logic.restoreSnapshot?this.logic.restoreSnapshot(t,this._actorScope):t:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(t,e){let s;for(this._snapshot=t;s=this._deferred.shift();)try{s()}catch(e){this._deferred.length=0,this._snapshot={...t,status:"error",error:e}}switch(this._snapshot.status){case"active":for(const e of this.observers)try{e.next?.(t)}catch(t){p(t)}break;case"done":for(const e of this.observers)try{e.next?.(t)}catch(t){p(t)}this._stopProcedure(),this._complete(),this._doneEvent=(n=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${n}`,output:o,actorId:n}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var n,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:e,snapshot:t})}subscribe(t,e,s){const n=$(t,e,s);if(this._processingStatus!==M.Stopped)this.observers.add(n);else switch(this._snapshot.status){case"done":try{n.complete?.()}catch(t){p(t)}break;case"error":{const t=this._snapshot.error;if(n.error)try{n.error(t)}catch(t){p(t)}else p(t);break}}return{unsubscribe:()=>{this.observers.delete(n)}}}on(t,e){let s=this.eventListeners.get(t);s||(s=new Set,this.eventListeners.set(t,s));const n=e.bind(void 0);return s.add(n),{unsubscribe:()=>{s.delete(n)}}}start(){if(this._processingStatus===M.Running)return this;this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=M.Running;const t=d(this.options.input);this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:t});switch(this._snapshot.status){case"done":return this.update(this._snapshot,t),this;case"error":return this._error(this._snapshot.error),this}if(this._parent||this.system.start(),this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(t){return this._snapshot={...this._snapshot,status:"error",error:t},this._error(t),this}return this.update(this._snapshot,t),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(t){let e,s;try{e=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){s={err:t}}if(s){const{err:t}=s;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(e,t),t.type===a&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===M.Stopped?this:(this.mailbox.clear(),this._processingStatus===M.NotStarted?(this._processingStatus=M.Stopped,this):(this.mailbox.enqueue({type:a}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers)try{t.complete?.()}catch(t){p(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||p(t));let e=!1;for(const s of this.observers){const n=s.error;e||=!n;try{n?.(t)}catch(t){p(t)}}this.observers.clear(),e&&p(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,f(this.id,t))}_stopProcedure(){return this._processingStatus!==M.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new e(this._process.bind(this)),this._processingStatus=M.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==M.Stopped&&this.mailbox.enqueue(t)}send(t){this.system._relay(void 0,this,t)}attachDevTools(){const{devTools:t}=this.options;if(t){("function"==typeof t?t:u)(this)}}toJSON(){return{xstate$$type:A,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[l](){return this}getSnapshot(){return this._snapshot}}function R(t,...[e]){return new P(t,e)}const C=R;function D(t,{machine:e,context:s},n,o){return(i,r)=>{const a=((i,r={})=>{const{systemId:a,input:c}=r;if("string"==typeof i){const u=T(e,i);if(!u)throw new Error(`Actor logic '${i}' not implemented in machine '${e.id}'`);const h=R(u,{id:r.id,parent:t.self,syncSnapshot:r.syncSnapshot,input:"function"==typeof c?c({context:s,event:n,self:t.self}):c,src:i,systemId:a});return o[h.id]=h,h}return R(i,{id:r.id,parent:t.self,syncSnapshot:r.syncSnapshot,input:r.input,src:i,systemId:a})})(i,r);return o[a.id]=a,t.defer((()=>{a._processingStatus!==M.Stopped&&a.start()})),a}}function J(t,e,s,n,{assignment:o}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const i={},r={context:e.context,event:s.event,spawn:D(t,e,s.event,i),self:t.self,system:t.system};let a={};if("function"==typeof o)a=o(r,n);else for(const t of Object.keys(o)){const e=o[t];a[t]="function"==typeof e?e(r,n):e}return[ae(e,{context:Object.assign({},e.context,a),children:Object.keys(i).length?{...e.children,...i}:e.children})]}function V(t){function e(t,e){}return e.type="xstate.assign",e.assignment=t,e.resolve=J,e}function B(t,e,s,n,{sendId:o}){return[e,"function"==typeof o?o(s,n):o]}function z(t,e){t.defer((()=>{t.system.scheduler.cancel(t.self,e)}))}function L(t){function e(t,e){}return e.type="xstate.cancel",e.sendId=t,e.resolve=B,e.execute=z,e}function W(t,e,s,n,{event:o}){return[e,{event:"function"==typeof o?o(s,n):o}]}function q(t,{event:e}){t.defer((()=>t.emit(e)))}function U(t){function e(t,e){}return e.type="xstate.emit",e.event=t,e.resolve=W,e.execute=q,e}function Q(t,e,{stateValue:s}){if("string"==typeof s&&It(s)){const e=t.machine.getStateNodeById(s);return t._nodes.some((t=>t===e))}return t.matches(s)}function F(t,{context:e,event:s},{guards:n}){return!H(n[0],e,s,t)}function G(t,{context:e,event:s},{guards:n}){return n.every((n=>H(n,e,s,t)))}function X(t,{context:e,event:s},{guards:n}){return n.some((n=>H(n,e,s,t)))}function H(t,e,s,n){const{machine:o}=n,i="function"==typeof t,r=i?t:o.implementations.guards["string"==typeof t?t:t.type];if(!i&&!r)throw new Error(`Guard '${"string"==typeof t?t:t.type}' is not implemented.'.`);if("function"!=typeof r)return H(r,e,s,n);const a={context:e,event:s},c=i||"string"==typeof t?void 0:"params"in t?"function"==typeof t.params?t.params({context:e,event:s}):t.params:void 0;if(!("check"in r))return r(a,c);return r.check(n,a,r)}function K(t,e,s,n,{event:o,id:i,delay:r},{internalQueue:a}){const c=e.machine.implementations.delays;if("string"==typeof o)throw new Error(`Only event objects may be used with raise; use raise({ type: "${o}" }) instead`);const u="function"==typeof o?o(s,n):o;let h;if("string"==typeof r){const t=c&&c[r];h="function"==typeof t?t(s,n):t}else h="function"==typeof r?r(s,n):r;return"number"!=typeof h&&a.push(u),[e,{event:u,id:i,delay:h}]}function Y(t,e){const{event:s,delay:n,id:o}=e;"number"!=typeof n||t.defer((()=>{const e=t.self;t.system.scheduler.schedule(e,e,s,n,o)}))}function Z(t,e){function s(t,e){}return s.type="xstate.raise",s.event=t,s.id=e?.id,s.delay=e?.delay,s.resolve=K,s.execute=Y,s}let tt=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function et(t,e,s,n,{to:o,event:i,id:r,delay:a},c){const u=e.machine.implementations.delays;if("string"==typeof i)throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${i}" }) instead`);const h="function"==typeof i?i(s,n):i;let f;if("string"==typeof a){const t=u&&u[a];f="function"==typeof t?t(s,n):t}else f="function"==typeof a?a(s,n):a;const d="function"==typeof o?o(s,n):o;let p;if("string"==typeof d){if(p=d===tt.Parent?t.self._parent:d===tt.Internal?t.self:d.startsWith("#_")?e.children[d.slice(2)]:c.deferredActorIds?.includes(d)?d:e.children[d],!p)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else p=d||t.self;return[e,{to:p,event:h,id:r,delay:f}]}function st(t,e,s){"string"==typeof s.to&&(s.to=e.children[s.to])}function nt(t,e){t.defer((()=>{const{to:s,event:n,delay:o,id:i}=e;"number"!=typeof o?t.system._relay(t.self,s,n.type===r?f(t.self.id,n.data):n):t.system.scheduler.schedule(t.self,s,n,o,i)}))}function ot(t,e,s){function n(t,e){}return n.type="xsnapshot.sendTo",n.to=t,n.event=e,n.id=s?.id,n.delay=s?.delay,n.resolve=et,n.retryResolve=st,n.execute=nt,n}function it(t,e){return ot(tt.Parent,t,e)}function rt(t,e,s,n,{id:o,systemId:i,src:r,input:a,syncSnapshot:c}){const u="string"==typeof r?T(e.machine,r):r,h="function"==typeof o?o(s):o;let f;return u&&(f=R(u,{id:h,src:r,parent:t.self,syncSnapshot:c,systemId:i,input:"function"==typeof a?a({context:e.context,event:s.event,self:t.self}):a})),[ae(e,{children:{...e.children,[h]:f}}),{id:o,actorRef:f}]}function at(t,{id:e,actorRef:s}){s&&t.defer((()=>{s._processingStatus!==M.Stopped&&s.start()}))}function ct(...[t,{id:e,systemId:s,input:n,syncSnapshot:o=!1}={}]){function i(t,e){}return i.type="snapshot.spawnChild",i.id=e,i.systemId=s,i.src=t,i.input=n,i.syncSnapshot=o,i.resolve=rt,i.execute=at,i}function ut(t,e,s,n,{actorRef:o}){const i="function"==typeof o?o(s,n):o,r="string"==typeof i?e.children[i]:i;let a=e.children;return r&&(a={...a},delete a[r.id]),[ae(e,{children:a}),r]}function ht(t,e){e&&(t.system._unregister(e),e._processingStatus===M.Running?t.defer((()=>{t.stopChild(e)})):t.stopChild(e))}function ft(t){function e(t,e){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=ut,e.execute=ht,e}const dt=ft;function pt(t,e,s,n,{collect:o}){const i=[],r=function(t){i.push(t)};return r.assign=(...t)=>{i.push(V(...t))},r.cancel=(...t)=>{i.push(L(...t))},r.raise=(...t)=>{i.push(Z(...t))},r.sendTo=(...t)=>{i.push(ot(...t))},r.sendParent=(...t)=>{i.push(it(...t))},r.spawnChild=(...t)=>{i.push(ct(...t))},r.stopChild=(...t)=>{i.push(ft(...t))},r.emit=(...t)=>{i.push(U(...t))},o({context:s.context,event:s.event,enqueue:r,check:t=>H(t,e.context,s.event,e),self:t.self,system:t.system},n),[e,void 0,i]}function lt(t,e,s,n,{value:o,label:i}){return[e,{value:"function"==typeof o?o(s,n):o,label:i}]}function yt({logger:t},{value:e,label:s}){s?t(s,e):t(e)}const gt=t=>"atomic"===t.type||"final"===t.type;function vt(t){return Object.values(t.states).filter((t=>"history"!==t.type))}function mt(t,e){const s=[];if(e===t)return s;let n=t.parent;for(;n&&n!==e;)s.push(n),n=n.parent;return s}function _t(t){const e=new Set(t),s=St(e);for(const t of e)if("compound"!==t.type||s.get(t)&&s.get(t).length){if("parallel"===t.type)for(const s of vt(t))if("history"!==s.type&&!e.has(s)){const t=Ot(s);for(const s of t)e.add(s)}}else Ot(t).forEach((t=>e.add(t)));for(const t of e){let s=t.parent;for(;s;)e.add(s),s=s.parent}return e}function bt(t,e){const s=e.get(t);if(!s)return{};if("compound"===t.type){const t=s[0];if(!t)return{};if(gt(t))return t.key}const n={};for(const t of s)n[t.key]=bt(t,e);return n}function St(t){const e=new Map;for(const s of t)e.has(s)||e.set(s,[]),s.parent&&(e.has(s.parent)||e.set(s.parent,[]),e.get(s.parent).push(s));return e}function xt(t,e){return bt(t,St(_t(e)))}function wt(t,e){return"compound"===e.type?vt(e).some((e=>"final"===e.type&&t.has(e))):"parallel"===e.type?vt(e).every((e=>wt(t,e))):"final"===e.type}const It=t=>"#"===t[0];function kt(t){const e=t.config.after;if(!e)return[];return Object.keys(e).flatMap(((s,n)=>{const o=e[s],i="string"==typeof o?{target:o}:o,r=Number.isNaN(+s)?s:+s,a=((e,s)=>{const n=(o=e,i=t.id,{type:`xstate.after.${o}.${i}`});var o,i;const r=n.type;return t.entry.push(Z(n,{id:r,delay:e})),t.exit.push(L(r)),r})(r);return S(i).map((t=>({...t,event:a,delay:r})))})).map((e=>{const{delay:s}=e;return{...$t(t,e.event,e),delay:s}}))}function $t(t,e,n){const o=k(n.target),i=n.reenter??!1,r=function(t,e){if(void 0===e)return;return e.map((e=>{if("string"!=typeof e)return e;if(It(e))return t.machine.getStateNodeById(e);const n=e[0]===s;if(n&&!t.parent)return Mt(t,e.slice(1));const o=n?t.key+e:e;if(!t.parent)throw new Error(`Invalid target: "${e}" is not a valid target from the root node. Did you mean ".${e}"?`);try{return Mt(t.parent,o)}catch(e){throw new Error(`Invalid transition definition for state node '${t.id}':\n${e.message}`)}}))}(t,o),a={...n,actions:S(n.actions),guard:n.guard,target:r,source:t,reenter:i,eventType:e,toJSON:()=>({...a,source:`#${t.id}`,target:r?r.map((t=>`#${t.id}`)):void 0})};return a}function Et(t){const e=k(t.config.target);return e?{target:e.map((e=>"string"==typeof e?Mt(t.parent,e):e))}:t.parent.initial}function Tt(t){return"history"===t.type}function Ot(t){const e=jt(t);for(const s of e)for(const n of mt(s,t))e.add(n);return e}function jt(t){const e=new Set;return function t(s){if(!e.has(s))if(e.add(s),"compound"===s.type)t(s.initial.target[0]);else if("parallel"===s.type)for(const e of vt(s))t(e)}(t),e}function At(t,e){if(It(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const s=t.states[e];if(!s)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return s}function Mt(t,e){if("string"==typeof e&&It(e))try{return t.machine.getStateNodeById(e)}catch(t){}const s=g(e).slice();let n=t;for(;s.length;){const t=s.shift();if(!t.length)break;n=At(n,t)}return n}function Nt(t,e){if("string"==typeof e){const s=t.states[e];if(!s)throw new Error(`State '${e}' does not exist on '${t.id}'`);return[t,s]}const s=Object.keys(e),n=s.map((e=>At(t,e))).filter(Boolean);return[t.machine.root,t].concat(n,s.reduce(((s,n)=>{const o=At(t,n);if(!o)return s;const i=Nt(o,e[n]);return s.concat(i)}),[]))}function Pt(t,e,s,n){return"string"==typeof e?function(t,e,s,n){const o=At(t,e).next(s,n);return o&&o.length?o:t.next(s,n)}(t,e,s,n):1===Object.keys(e).length?function(t,e,s,n){const o=Object.keys(e),i=Pt(At(t,o[0]),e[o[0]],s,n);return i&&i.length?i:t.next(s,n)}(t,e,s,n):function(t,e,s,n){const o=[];for(const i of Object.keys(e)){const r=e[i];if(!r)continue;const a=Pt(At(t,i),r,s,n);a&&o.push(...a)}return o.length?o:t.next(s,n)}(t,e,s,n)}function Rt(t){return Object.keys(t.states).map((e=>t.states[e])).filter((t=>"history"===t.type))}function Ct(t,e){let s=t;for(;s.parent&&s.parent!==e;)s=s.parent;return s.parent===e}function Dt(t,e){const s=new Set(t),n=new Set(e);for(const t of s)if(n.has(t))return!0;for(const t of n)if(s.has(t))return!0;return!1}function Jt(t,e,s){const n=new Set;for(const o of t){let t=!1;const i=new Set;for(const r of n)if(Dt(zt([o],e,s),zt([r],e,s))){if(!Ct(o.source,r.source)){t=!0;break}i.add(r)}if(!t){for(const t of i)n.delete(t);n.add(o)}}return Array.from(n)}function Vt(t,e){if(!t.target)return[];const s=new Set;for(const n of t.target)if(Tt(n))if(e[n.id])for(const t of e[n.id])s.add(t);else for(const t of Vt(Et(n),e))s.add(t);else s.add(n);return[...s]}function Bt(t,e){const s=Vt(t,e);if(!s)return;if(!t.reenter&&s.every((e=>e===t.source||Ct(e,t.source))))return t.source;const n=function(t){const[e,...s]=t;for(const t of mt(e,void 0))if(s.every((e=>Ct(e,t))))return t}(s.concat(t.source));return n||(t.reenter?void 0:t.source.machine.root)}function zt(t,e,s){const n=new Set;for(const o of t)if(o.target?.length){const t=Bt(o,s);o.reenter&&o.source===t&&n.add(t);for(const s of e)Ct(s,t)&&n.add(s)}return[...n]}function Lt(t,e,s,n,o,i){if(!t.length)return e;const r=new Set(e._nodes);let a=e.historyValue;const c=Jt(t,r,a);let u=e;o||([u,a]=function(t,e,s,n,o,i,r){let a=t;const c=zt(n,o,i);let u;c.sort(((t,e)=>e.order-t.order));for(const t of c)for(const e of Rt(t)){let s;s="deep"===e.history?e=>gt(e)&&Ct(e,t):e=>e.parent===t,u??={...i},u[e.id]=Array.from(o).filter(s)}for(const t of c)a=Xt(a,e,s,[...t.exit,...t.invoke.map((t=>ft(t.id)))],r),o.delete(t);return[a,u||i]}(u,n,s,c,r,a,i)),u=Xt(u,n,s,c.flatMap((t=>t.actions)),i),u=function(t,e,s,n,o,i,r,a){let c=t;const u=new Set,f=new Set;(function(t,e,s,n){for(const o of t){const t=Bt(o,e);for(const i of o.target||[])Tt(i)||o.source===i&&o.source===t&&!o.reenter||(n.add(i),s.add(i)),qt(i,e,s,n);const i=Vt(o,e);for(const r of i){const i=mt(r,t);"parallel"===t?.type&&i.push(t),Ut(n,e,s,i,!o.source.parent&&o.reenter?void 0:t)}}})(n,r,f,u),a&&f.add(t.machine.root);const d=new Set;for(const t of[...u].sort(((t,e)=>t.order-e.order))){o.add(t);const n=[];n.push(...t.entry);for(const e of t.invoke)n.push(ct(e.src,{...e,syncSnapshot:!!e.onSnapshot}));if(f.has(t)){const e=t.initial.actions;n.push(...e)}if(c=Xt(c,e,s,n,i,t.invoke.map((t=>t.id))),"final"===t.type){const n=t.parent;let r="parallel"===n?.type?n:n?.parent,a=r||t;for("compound"===n?.type&&i.push(h(n.id,void 0!==t.output?x(t.output,c.context,e,s.self):void 0));"parallel"===r?.type&&!d.has(r)&&wt(o,r);)d.add(r),i.push(h(r.id)),a=r,r=r.parent;if(r)continue;c=ae(c,{status:"done",output:Wt(c,e,s,c.machine.root,a)})}}return c}(u,n,s,c,r,i,a,o);const f=[...r];"done"===u.status&&(u=Xt(u,n,s,f.sort(((t,e)=>e.order-t.order)).flatMap((t=>t.exit)),i));try{return a===e.historyValue&&function(t,e){if(t.length!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;return!0}(e._nodes,r)?u:ae(u,{_nodes:f,historyValue:a})}catch(t){throw t}}function Wt(t,e,s,n,o){if(void 0===n.output)return;const i=h(o.id,void 0!==o.output&&o.parent?x(o.output,t.context,e,s.self):void 0);return x(n.output,t.context,i,s.self)}function qt(t,e,s,n){if(Tt(t))if(e[t.id]){const o=e[t.id];for(const t of o)n.add(t),qt(t,e,s,n);for(const i of o)Qt(i,t.parent,n,e,s)}else{const o=Et(t);for(const i of o.target)n.add(i),o===t.parent?.initial&&s.add(t.parent),qt(i,e,s,n);for(const i of o.target)Qt(i,t.parent,n,e,s)}else if("compound"===t.type){const[o]=t.initial.target;Tt(o)||(n.add(o),s.add(o)),qt(o,e,s,n),Qt(o,t,n,e,s)}else if("parallel"===t.type)for(const o of vt(t).filter((t=>!Tt(t))))[...n].some((t=>Ct(t,o)))||(Tt(o)||(n.add(o),s.add(o)),qt(o,e,s,n))}function Ut(t,e,s,n,o){for(const i of n)if(o&&!Ct(i,o)||t.add(i),"parallel"===i.type)for(const n of vt(i).filter((t=>!Tt(t))))[...t].some((t=>Ct(t,n)))||(t.add(n),qt(n,e,s,t))}function Qt(t,e,s,n,o){Ut(s,n,o,mt(t,e))}let Ft=!1;function Gt(t,e,s,n,o,i){const{machine:r}=t;let a=t;for(const c of n){const u="function"==typeof c,h=u?c:r.implementations.actions["string"==typeof c?c:c.type];if(!h)continue;const f={context:a.context,event:e,self:s.self,system:s.system},d=u||"string"==typeof c?void 0:"params"in c?"function"==typeof c.params?c.params({context:a.context,event:e}):c.params:void 0;function p(){s.system._sendInspectionEvent({type:"@xstate.action",actorRef:s.self,action:{type:"string"==typeof c?c:"object"==typeof c?c.type:c.name||"(anonymous)",params:d}});try{Ft=h,h(f,d)}finally{Ft=!1}}if(!("resolve"in h)){s.self._processingStatus===M.Running?p():s.defer((()=>{p()}));continue}const l=h,[y,g,v]=l.resolve(s,a,f,d,h,o);a=y,"retryResolve"in l&&i?.push([l,g]),"execute"in l&&(s.self._processingStatus===M.Running?l.execute(s,g):s.defer(l.execute.bind(null,s,g))),v&&(a=Gt(a,e,s,v,o,i))}return a}function Xt(t,e,s,n,o,i){const r=i?[]:void 0,a=Gt(t,e,s,n,{internalQueue:o,deferredActorIds:i},r);return r?.forEach((([t,e])=>{t.retryResolve(s,a,e)})),a}function Ht(t,e,s,n=[]){let o=t;const r=[];function c(t,e,n){s.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:s.self,event:e,snapshot:t,_transitions:n}),r.push(t)}if(e.type===a)return o=ae(Kt(o,e,s),{status:"stopped"}),c(o,e,[]),{snapshot:o,microstates:r};let u=e;if(u.type!==i){const e=u,i=function(t){return t.type.startsWith("xstate.error.actor")}(e),a=Yt(e,o);if(i&&!a.length)return o=ae(t,{status:"error",error:e.error}),c(o,e,[]),{snapshot:o,microstates:r};o=Lt(a,t,s,u,!1,n),c(o,e,a)}let h=!0;for(;"active"===o.status;){let t=h?Zt(o,u):[];const e=t.length?o:void 0;if(!t.length){if(!n.length)break;u=n.shift(),t=Yt(u,o)}o=Lt(t,o,s,u,!1,n),h=o!==e,c(o,u,t)}return"active"!==o.status&&Kt(o,u,s),{snapshot:o,microstates:r}}function Kt(t,e,s){return Xt(t,e,s,Object.values(t.children).map((t=>ft(t))),[])}function Yt(t,e){return e.machine.getTransitionData(e,t)}function Zt(t,e){const s=new Set,n=t._nodes.filter(gt);for(const o of n)t:for(const n of[o].concat(mt(o,void 0)))if(n.always)for(const o of n.always)if(void 0===o.guard||H(o.guard,t.context,e,t)){s.add(o);break t}return Jt(Array.from(s),new Set(t._nodes),t.historyValue)}function te(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}const ee=function(t){return y(t,this.value)},se=function(t){return this.tags.has(t)},ne=function(t){const e=this.machine.getTransitionData(this,t);return!!e?.length&&e.some((t=>void 0!==t.target||t.actions.length))},oe=function(){const{_nodes:t,tags:e,machine:s,getMeta:n,toJSON:o,can:i,hasTag:r,matches:a,...c}=this;return{...c,tags:Array.from(e)}},ie=function(){return this._nodes.reduce(((t,e)=>(void 0!==e.meta&&(t[e.id]=e.meta),t)),{})};function re(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:xt(e.root,t._nodes),tags:new Set(t._nodes.flatMap((t=>t.tags))),children:t.children,historyValue:t.historyValue||{},matches:ee,hasTag:se,can:ne,getMeta:ie,toJSON:oe}}function ae(t,e={}){return re({...t,...e},t.machine)}function ce(t){let e;for(const s in t){const n=t[s];if(n&&"object"==typeof n)if("sessionId"in n&&"send"in n&&"ref"in n)e??=Array.isArray(t)?t.slice():{...t},e[s]={xstate$$type:A,id:n.id};else{const o=ce(n);o!==n&&(e??=Array.isArray(t)?t.slice():{...t},e[s]=o)}}return e??t}const ue=new WeakMap;function he(t,e,s){let n=ue.get(t);return n?e in n||(n[e]=s()):(n={[e]:s()},ue.set(t,n)),n[e]}const fe={},de=t=>"string"==typeof t?{type:t}:"function"==typeof t?"resolve"in t?{type:t.type}:{type:t.name}:t;class pe{constructor(t,e){if(this.config=t,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=e._parent,this.key=e._key,this.machine=e._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(s),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?_(this.config.states,((t,e)=>new pe(t,{_parent:this,_key:e,_machine:this.machine}))):fe,"compound"===this.type&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=!0===this.config.history?"shallow":this.config.history||!1,this.entry=S(this.config.entry).slice(),this.exit=S(this.config.exit).slice(),this.meta=this.config.meta,this.output="final"!==this.type&&this.parent?void 0:this.config.output,this.tags=S(t.tags).slice()}_initialize(){this.transitions=function(t){const e=new Map;if(t.config.on)for(const s of Object.keys(t.config.on)){if(s===o)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const n=t.config.on[s];e.set(s,I(n).map((e=>$t(t,s,e))))}if(t.config.onDone){const s=`xstate.done.state.${t.id}`;e.set(s,I(t.config.onDone).map((e=>$t(t,s,e))))}for(const s of t.invoke){if(s.onDone){const n=`xstate.done.actor.${s.id}`;e.set(n,I(s.onDone).map((e=>$t(t,n,e))))}if(s.onError){const n=`xstate.error.actor.${s.id}`;e.set(n,I(s.onError).map((e=>$t(t,n,e))))}if(s.onSnapshot){const n=`xstate.snapshot.${s.id}`;e.set(n,I(s.onSnapshot).map((e=>$t(t,n,e))))}}for(const s of t.after){let t=e.get(s.eventType);t||(t=[],e.set(s.eventType,t)),t.push(s)}return e}(this),this.config.always&&(this.always=I(this.config.always).map((t=>$t(this,o,t)))),Object.keys(this.states).forEach((t=>{this.states[t]._initialize()}))}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(de),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((t=>`#${t.id}`)),source:`#${this.id}`,actions:this.initial.actions.map(de),eventType:null})}:void 0,history:this.history,states:_(this.states,(t=>t.definition)),on:this.on,transitions:[...this.transitions.values()].flat().map((t=>({...t,actions:t.actions.map(de)}))),entry:this.entry.map(de),exit:this.exit.map(de),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return he(this,"invoke",(()=>S(this.config.invoke).map(((t,e)=>{const{src:s,systemId:n}=t,o=t.id??E(this.id,e),i="string"==typeof s?s:`xstate.invoke.${E(this.id,e)}`;return{...t,src:i,id:o,systemId:n,toJSON(){const{onDone:e,onError:s,...n}=t;return{...n,type:"xstate.invoke",src:i,id:o}}}}))))}get on(){return he(this,"on",(()=>[...this.transitions].flatMap((([t,e])=>e.map((e=>[t,e])))).reduce(((t,[e,s])=>(t[e]=t[e]||[],t[e].push(s),t)),{})))}get after(){return he(this,"delayedTransitions",(()=>kt(this)))}get initial(){return he(this,"initial",(()=>function(t,e){const s="string"==typeof e?t.states[e]:e?t.states[e.target]:void 0;if(!s&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const n={source:t,actions:e&&"string"!=typeof e?S(e.actions):[],eventType:null,reenter:!1,target:s?[s]:[],toJSON:()=>({...n,source:`#${t.id}`,target:s?[`#${s.id}`]:[]})};return n}(this,this.config.initial)))}next(t,e){const s=e.type,n=[];let o;const i=he(this,`candidates-${s}`,(()=>{return e=s,(t=this).transitions.get(e)||[...t.transitions.keys()].filter((t=>{if("*"===t)return!0;if(!t.endsWith(".*"))return!1;const s=t.split("."),n=e.split(".");for(let t=0;t<s.length;t++){const e=s[t],o=n[t];if("*"===e)return t===s.length-1;if(e!==o)return!1}return!0})).sort(((t,e)=>e.length-t.length)).flatMap((e=>t.transitions.get(e)));var t,e}));for(const r of i){const{guard:i}=r,a=t.context;let c=!1;try{c=!i||H(i,a,e,t)}catch(t){const e="string"==typeof i?i:"object"==typeof i?i.type:void 0;throw new Error(`Unable to evaluate guard ${e?`'${e}' `:""}in transition for event '${s}' in state node '${this.id}':\n${t.message}`)}if(c){n.push(...r.actions),o=r;break}}return o?[o]:void 0}get events(){return he(this,"events",(()=>{const{states:t}=this,e=new Set(this.ownEvents);if(t)for(const s of Object.keys(t)){const n=t[s];if(n.states)for(const t of n.events)e.add(`${t}`)}return Array.from(e)}))}get ownEvents(){const t=new Set([...this.transitions.keys()].filter((t=>this.transitions.get(t).some((t=>!(!t.target&&!t.actions.length&&!t.reenter))))));return Array.from(t)}}class le{constructor(t,e){this.config=t,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=t.id||"(machine)",this.implementations={actors:e?.actors??{},actions:e?.actions??{},delays:e?.delays??{},guards:e?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new pe(t,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(t){const{actions:e,guards:s,actors:n,delays:o}=this.implementations;return new le(this.config,{actions:{...e,...t.actions},guards:{...s,...t.guards},actors:{...n,...t.actors},delays:{...o,...t.delays}})}resolveState(t){const e=(s=this.root,n=t.value,xt(s,[..._t(Nt(s,n))]));var s,n;const o=_t(Nt(this.root,e));return re({_nodes:[...o],context:t.context||{},children:{},status:wt(o,this.root)?"done":t.status||"active",output:t.output,error:t.error,historyValue:t.historyValue},this)}transition(t,e,s){return Ht(t,e,s).snapshot}microstep(t,e,s){return Ht(t,e,s).microstates}getTransitionData(t,e){return Pt(this.root,t.value,t,e)||[]}getPreInitialState(t,e,s){const{context:n}=this.config,o=re({context:"function"!=typeof n&&n?n:{},_nodes:[this.root],children:{},status:"active"},this);if("function"==typeof n){return Xt(o,e,t,[V((({spawn:t,event:e,self:s})=>n({spawn:t,input:e.input,self:s})))],s)}return o}getInitialSnapshot(t,e){const s=d(e),n=[],o=this.getPreInitialState(t,s,n),i=Lt([{target:[...jt(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],o,t,s,!0,n),{snapshot:r}=Ht(i,s,t,n);return r}start(t){Object.values(t.children).forEach((t=>{"active"===t.getSnapshot().status&&t.start()}))}getStateNodeById(t){const e=g(t),s=e.slice(1),n=It(e[0])?e[0].slice(1):e[0],o=this.idMap.get(n);if(!o)throw new Error(`Child state node '#${n}' does not exist on machine '${this.id}'`);return Mt(o,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(t,e){return function(t,e){const{_nodes:s,tags:n,machine:o,children:i,context:r,can:a,hasTag:c,matches:u,getMeta:h,toJSON:f,...d}=t,p={};for(const t in i){const s=i[t];p[t]={snapshot:s.getPersistedSnapshot(e),src:s.src,systemId:s._systemId,syncSnapshot:s._syncSnapshot}}return{...d,context:ce(r),children:p}}(t,e)}restoreSnapshot(t,e){const s={},n=t.children;Object.keys(n).forEach((t=>{const o=n[t],i=o.snapshot,r=o.src,a="string"==typeof r?T(this,r):r;if(!a)return;const c=R(a,{id:t,parent:e.self,syncSnapshot:o.syncSnapshot,snapshot:i,src:r,systemId:o.systemId});s[t]=c}));const o=re({...t,children:s,_nodes:Array.from(_t(Nt(this.root,t.value)))},this);let i=new Set;return function t(e,s){if(!i.has(e)){i.add(e);for(let n in e){const o=e[n];if(o&&"object"==typeof o){if("xstate$$type"in o&&o.xstate$$type===A){e[n]=s[o.id];continue}t(o,s)}}}}(o.context,s),o}}function ye(t,e){return{config:t,transition:(e,s,n)=>({...e,context:t(e.context,s,n)}),getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof e?e({input:s}):e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const ge=new WeakMap;const ve="xstate.observable.next",me="xstate.observable.error",_e="xstate.observable.complete";const be="xstate.promise.resolve",Se="xstate.promise.reject",xe=new WeakMap;const we=ye((t=>{}),void 0);function Ie(t,e){return new le(t,e)}function ke(t){const e=R(t);return{self:e,defer:()=>{},id:"",logger:()=>{},sessionId:"",stopChild:()=>{},system:e.system,emit:()=>{}}}const $e={timeout:1/0};t.Actor=P,t.SimulatedClock=class{constructor(){this.timeouts=new Map,this._now=0,this._id=0,this._flushing=!1,this._flushingInvalidated=!1}now(){return this._now}getId(){return this._id++}setTimeout(t,e){this._flushingInvalidated=this._flushing;const s=this.getId();return this.timeouts.set(s,{start:this.now(),timeout:e,fn:t}),s}clearTimeout(t){this._flushingInvalidated=this._flushing,this.timeouts.delete(t)}set(t){if(this._now>t)throw new Error("Unable to travel back in time");this._now=t,this.flushTimeouts()}flushTimeouts(){if(this._flushing)return void(this._flushingInvalidated=!0);this._flushing=!0;const t=[...this.timeouts].sort((([t,e],[s,n])=>{const o=e.start+e.timeout;return n.start+n.timeout>o?-1:1}));for(const[e,s]of t){if(this._flushingInvalidated)return this._flushingInvalidated=!1,this._flushing=!1,void this.flushTimeouts();this.now()-s.start>=s.timeout&&(this.timeouts.delete(e),s.fn.call(null))}this._flushing=!1}increment(t){this._now+=t,this.flushTimeouts()}},t.SpecialTargets=tt,t.StateMachine=le,t.StateNode=pe,t.__unsafe_getAllOwnEventDescriptors=function(t){return[...new Set([...t._nodes.flatMap((t=>t.ownEvents))])]},t.and=function(t){function e(t,e){return!1}return e.check=G,e.guards=t,e},t.assertEvent=function(t,e){const s=S(e);if(!s.includes(t.type)){const e=1===s.length?`type "${s[0]}"`:`one of types "${s.join('", "')}"`;throw new Error(`Expected event ${JSON.stringify(t)} to have ${e}`)}},t.assign=V,t.cancel=L,t.createActor=R,t.createEmptyActor=function(){return R(we)},t.createMachine=Ie,t.emit=U,t.enqueueActions=function(t){function e(t,e){}return e.type="xstate.enqueueActions",e.collect=t,e.resolve=pt,e},t.forwardTo=function(t,e){return ot(t,(({event:t})=>t),e)},t.fromCallback=function(t){const e={config:t,start:(e,s)=>{const{self:n,system:o,emit:i}=s,r={receivers:void 0,dispose:void 0};ge.set(n,r),r.dispose=t({input:e.input,system:o,self:n,sendBack:t=>{"stopped"!==n.getSnapshot().status&&n._parent&&o._relay(n,n._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)},emit:i})},transition:(t,e,s)=>{const n=ge.get(s.self);return e.type===a?(t={...t,status:"stopped",error:void 0},n.dispose?.(),t):(n.receivers?.forEach((t=>t(e))),t)},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromEventObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case me:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case _e:return{...t,status:"done",input:void 0,_subscription:void 0};case a:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{s._parent&&n._relay(s,s._parent,t)},error:t=>{n._relay(s,s,{type:me,data:t})},complete:()=>{n._relay(s,s,{type:_e})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromObservable=function(t){const e={config:t,transition:(t,e)=>{if("active"!==t.status)return t;switch(e.type){case ve:return{...t,context:e.data};case me:return{...t,status:"error",error:e.data,input:void 0,_subscription:void 0};case _e:return{...t,status:"done",input:void 0,_subscription:void 0};case a:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:void 0,input:e,_subscription:void 0}),start:(e,{self:s,system:n,emit:o})=>{"done"!==e.status&&(e._subscription=t({input:e.input,system:n,self:s,emit:o}).subscribe({next:t=>{n._relay(s,s,{type:ve,data:t})},error:t=>{n._relay(s,s,{type:me,data:t})},complete:()=>{n._relay(s,s,{type:_e})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return e},t.fromPromise=function(t){const e={config:t,transition:(t,e,s)=>{if("active"!==t.status)return t;switch(e.type){case be:{const s=e.data;return{...t,status:"done",output:s,input:void 0}}case Se:return{...t,status:"error",error:e.data,input:void 0};case a:return xe.get(s.self)?.abort(),{...t,status:"stopped",input:void 0};default:return t}},start:(e,{self:s,system:n,emit:o})=>{if("active"!==e.status)return;const i=new AbortController;xe.set(s,i);Promise.resolve(t({input:e.input,system:n,self:s,signal:i.signal,emit:o})).then((t=>{"active"===s.getSnapshot().status&&(xe.delete(s),n._relay(s,s,{type:be,data:t}))}),(t=>{"active"===s.getSnapshot().status&&(xe.delete(s),n._relay(s,s,{type:Se,data:t}))}))},getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,input:e}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return e},t.fromTransition=ye,t.getInitialSnapshot=function(t,...[e]){const s=ke(t);return t.getInitialSnapshot(s,e)},t.getNextSnapshot=function(t,e,s){const n=ke(t);return n.self._snapshot=e,t.transition(e,s,n)},t.getStateNodes=Nt,t.interpret=C,t.isMachineSnapshot=te,t.log=function(t=(({context:t,event:e})=>({context:t,event:e})),e){function s(t,e){}return s.type="xstate.log",s.value=t,s.label=e,s.resolve=lt,s.execute=yt,s},t.matchesState=y,t.not=function(t){function e(t,e){return!1}return e.check=F,e.guards=[t],e},t.or=function(t){function e(t,e){return!1}return e.check=X,e.guards=t,e},t.pathToStateValue=m,t.raise=Z,t.sendParent=it,t.sendTo=ot,t.setup=function({schemas:t,actors:e,actions:s,guards:n,delays:o}){return{createMachine:i=>Ie({...i,schemas:t},{actors:e,actions:s,guards:n,delays:o})}},t.spawnChild=ct,t.stateIn=function(t){function e(t,e){return!1}return e.check=Q,e.stateValue=t,e},t.stop=dt,t.stopChild=ft,t.toObserver=$,t.toPromise=function(t){return new Promise(((e,s)=>{t.subscribe({complete:()=>{e(t.getSnapshot().output)},error:s})}))},t.waitFor=function(t,e,s){const n={...$e,...s};return new Promise(((s,o)=>{const{signal:i}=n;if(i?.aborted)return void o(i.reason);let r=!1;const a=n.timeout===1/0?void 0:setTimeout((()=>{c(),o(new Error(`Timeout of ${n.timeout} ms exceeded`))}),n.timeout),c=()=>{clearTimeout(a),r=!0,f?.unsubscribe(),h&&i.removeEventListener("abort",h)};function u(t){e(t)&&(c(),s(t))}let h,f;u(t.getSnapshot()),r||(i&&(h=()=>{c(),o(i.reason)},i.addEventListener("abort",h)),f=t.subscribe({next:u,error:t=>{c(),o(t)},complete:()=>{c(),o(new Error("Actor terminated without satisfying predicate"))}}),r&&f.unsubscribe())}))},Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=xstate.umd.min.js.map