xstate 5.9.1 → 5.10.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.
Files changed (38) hide show
  1. package/actions/dist/xstate-actions.cjs.js +2 -2
  2. package/actions/dist/xstate-actions.development.cjs.js +2 -2
  3. package/actions/dist/xstate-actions.development.esm.js +2 -2
  4. package/actions/dist/xstate-actions.esm.js +2 -2
  5. package/actions/dist/xstate-actions.umd.min.js +1 -1
  6. package/actions/dist/xstate-actions.umd.min.js.map +1 -1
  7. package/actors/dist/xstate-actors.cjs.js +1 -1
  8. package/actors/dist/xstate-actors.development.cjs.js +1 -1
  9. package/actors/dist/xstate-actors.development.esm.js +1 -1
  10. package/actors/dist/xstate-actors.esm.js +1 -1
  11. package/actors/dist/xstate-actors.umd.min.js +1 -1
  12. package/actors/dist/xstate-actors.umd.min.js.map +1 -1
  13. package/dist/declarations/src/StateMachine.d.ts +2 -2
  14. package/dist/declarations/src/actions/raise.d.ts +2 -2
  15. package/dist/declarations/src/actions/send.d.ts +2 -2
  16. package/dist/declarations/src/guards.d.ts +4 -4
  17. package/dist/declarations/src/system.d.ts +3 -0
  18. package/dist/declarations/src/types.d.ts +6 -2
  19. package/dist/{log-a312ebfc.cjs.js → log-11d3f771.cjs.js} +6 -5
  20. package/dist/{log-28ea35fe.development.cjs.js → log-6380a394.development.cjs.js} +6 -5
  21. package/dist/{log-c48e8ab0.esm.js → log-cd22d72c.esm.js} +6 -5
  22. package/dist/{log-0fbf8cec.development.esm.js → log-f64de12b.development.esm.js} +6 -5
  23. package/dist/{raise-80cc66b2.development.esm.js → raise-03a786f4.development.esm.js} +11 -5
  24. package/dist/{raise-411df926.esm.js → raise-040ba012.esm.js} +11 -5
  25. package/dist/{raise-182bb5c9.cjs.js → raise-40b1a1f5.cjs.js} +11 -5
  26. package/dist/{raise-933cd731.development.cjs.js → raise-52a00e8f.development.cjs.js} +11 -5
  27. package/dist/xstate.cjs.js +2 -2
  28. package/dist/xstate.development.cjs.js +2 -2
  29. package/dist/xstate.development.esm.js +4 -4
  30. package/dist/xstate.esm.js +4 -4
  31. package/dist/xstate.umd.min.js +1 -1
  32. package/dist/xstate.umd.min.js.map +1 -1
  33. package/guards/dist/xstate-guards.cjs.js +1 -1
  34. package/guards/dist/xstate-guards.development.cjs.js +1 -1
  35. package/guards/dist/xstate-guards.development.esm.js +1 -1
  36. package/guards/dist/xstate-guards.esm.js +1 -1
  37. package/guards/dist/xstate-guards.umd.min.js.map +1 -1
  38. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var guards_dist_xstateGuards = require('../../dist/raise-182bb5c9.cjs.js');
5
+ var guards_dist_xstateGuards = require('../../dist/raise-40b1a1f5.cjs.js');
6
6
  require('../../dev/dist/xstate-dev.cjs.js');
7
7
 
8
8
  /**
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var guards_dist_xstateGuards = require('../../dist/raise-933cd731.development.cjs.js');
5
+ var guards_dist_xstateGuards = require('../../dist/raise-52a00e8f.development.cjs.js');
6
6
  require('../../dev/dist/xstate-dev.development.cjs.js');
7
7
 
8
8
  /**
@@ -1,4 +1,4 @@
1
- import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-80cc66b2.development.esm.js';
1
+ import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-03a786f4.development.esm.js';
2
2
  import '../../dev/dist/xstate-dev.development.esm.js';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-411df926.esm.js';
1
+ import { X as XSTATE_STOP, A as createActor } from '../../dist/raise-040ba012.esm.js';
2
2
  import '../../dev/dist/xstate-dev.esm.js';
3
3
 
4
4
  /**
@@ -1,2 +1,2 @@
1
- !function(t,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports):"function"==typeof define&&define.amd?define(["exports"],s):s((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";class s{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 s={value:t,next:null};if(this._current)return this._last.next=s,void(this._last=s);this._current=s,this._last=s,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const e="xstate.stop";function i(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const r=t=>{const s=i();s&&s.register(t)};function o(t){setTimeout((()=>{throw t}))}const n="function"==typeof Symbol&&Symbol.observable||"@@observable";function a(t,s){return`${t.sessionId}.${s}`}let h=0;function c(t,s,e){const i="object"==typeof t,r=i?t:void 0;return{next:(i?t.next:t)?.bind(r),error:(i?t.error:s)?.bind(r),complete:(i?t.complete:e)?.bind(r)}}let p=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const u={clock:{setTimeout:(t,s)=>setTimeout(t,s),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class d{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new s(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=p.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 i={...u,...e},{clock:r,logger:o,parent:n,syncSnapshot:d,id:_,systemId:l,inspect:v}=i;this.system=n?n.system:function(t,s){const e=new Map,i=new Map,r=new WeakMap,o=new Set,n={},c=s.clock,p={schedule:(t,s,e,i,r=Math.random().toString(36).slice(2))=>{const o={source:t,target:s,event:e,delay:i,id:r,startedAt:Date.now()},h=a(t,r);u._snapshot._scheduledEvents[h]=o;const p=c.setTimeout((()=>{delete n[h],delete u._snapshot._scheduledEvents[h],u._relay(t,s,e)}),i);n[h]=p},cancel:(t,s)=>{const e=a(t,s),i=n[e];delete n[e],delete u._snapshot._scheduledEvents[e],c.clearTimeout(i)},cancelAll:t=>{for(const s in u._snapshot._scheduledEvents){const e=u._snapshot._scheduledEvents[s];e.source===t&&p.cancel(t,e.id)}}},u={_snapshot:{_scheduledEvents:(s?.snapshot&&s.snapshot.scheduler)??{}},_bookId:()=>"x:"+h++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const s=r.get(t);void 0!==s&&(i.delete(s),r.delete(t))},get:t=>i.get(t),_set:(t,s)=>{const e=i.get(t);if(e&&e!==s)throw new Error(`Actor with system ID '${t}' already exists.`);i.set(t,s),r.set(s,t)},inspect:t=>{o.add(t)},_sendInspectionEvent:s=>{if(!o.size)return;const e={...s,rootId:t.sessionId};o.forEach((t=>t.next?.(e)))},_relay:(t,s,e)=>{u._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:s,event:e}),s._send(e)},scheduler:p,getSnapshot:()=>({_scheduledEvents:{...u._snapshot._scheduledEvents}}),start:()=>{const t=u._snapshot._scheduledEvents;u._snapshot._scheduledEvents={};for(const s in t){const{source:e,target:i,event:r,delay:o,id:n}=t[s];p.schedule(e,i,r,o,n)}}};return u}(this,{clock:r}),v&&!n&&this.system.inspect(c(v)),this.sessionId=this.system._bookId(),this.id=_??this.sessionId,this.logger=o,this.clock=r,this._parent=n,this._syncSnapshot=d,this.options=i,this.src=i.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 s=this.eventListeners.get(t.type);if(s)for(const e of Array.from(s))e(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),l&&(this._systemId=l,this.system._set(l,this)),this._initState(e?.snapshot??e?.state),l&&"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,s){let e;for(this._snapshot=t;e=this._deferred.shift();)try{e()}catch(s){this._deferred.length=0,this._snapshot={...t,status:"error",error:s}}switch(this._snapshot.status){case"active":for(const s of this.observers)try{s.next?.(t)}catch(t){o(t)}break;case"done":for(const s of this.observers)try{s.next?.(t)}catch(t){o(t)}this._stopProcedure(),this._complete(),this._doneEvent=(i=this.id,r=this._snapshot.output,{type:`xstate.done.actor.${i}`,output:r}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var i,r;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:s,snapshot:t})}subscribe(t,s,e){const i=c(t,s,e);if(this._processingStatus!==p.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(t){o(t)}break;case"error":{const t=this._snapshot.error;if(i.error)try{i.error(t)}catch(t){o(t)}else o(t);break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,s){let e=this.eventListeners.get(t);e||(e=new Set,this.eventListeners.set(t,e));const i=s.bind(void 0);return e.add(i),{unsubscribe:()=>{e.delete(i)}}}start(){if(this._processingStatus===p.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=p.Running;const t={type:"xstate.init",input: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 s,i;try{s=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){i={err:t}}if(i){const{err:t}=i;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(s,t),t.type===e&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===p.Stopped?this:(this.mailbox.clear(),this._processingStatus===p.NotStarted?(this._processingStatus=p.Stopped,this):(this.mailbox.enqueue({type:e}),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){o(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||o(t));let s=!1;for(const e of this.observers){const i=e.error;s||=!i;try{i?.(t)}catch(t){o(t)}}this.observers.clear(),s&&o(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${this.id}`,error:t})}_stopProcedure(){return this._processingStatus!==p.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new s(this._process.bind(this)),this._processingStatus=p.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==p.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:r)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[n](){return this}getSnapshot(){return this._snapshot}}function _(t,s){return{config:t,transition:(s,e,i)=>({...s,context:t(s.context,e,i)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof s?s({input:e}):s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const l=new WeakMap;const v="xstate.observable.next",f="xstate.observable.error",y="xstate.observable.complete";const b="xstate.promise.resolve",g="xstate.promise.reject";const m=_((t=>{}),void 0);t.createEmptyActor=function(){return function(t,...[s]){return new d(t,s)}(m)},t.fromCallback=function(t){return{config:t,start:(s,e)=>{const{self:i,system:r}=e,o={receivers:void 0,dispose:void 0};l.set(i,o),o.dispose=t({input:s.input,system:r,self:i,sendBack:t=>{"stopped"!==i.getSnapshot().status&&i._parent&&r._relay(i,i._parent,t)},receive:t=>{o.receivers??=new Set,o.receivers.add(t)}})},transition:(t,s,i)=>{const r=l.get(i.self);return s.type===e?(t={...t,status:"stopped",error:void 0},r.dispose?.(),t):(r.receivers?.forEach((t=>t(s))),t)},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromEventObservable=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case f:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case y:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{e._parent&&i._relay(e,e._parent,t)},error:t=>{i._relay(e,e,{type:f,data:t})},complete:()=>{i._relay(e,e,{type:y})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromObservable=function(t){return{config:t,transition:(t,s,{self:i,id:r,defer:o,system:n})=>{if("active"!==t.status)return t;switch(s.type){case v:return{...t,context:s.data};case f:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case y:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{i._relay(e,e,{type:v,data:t})},error:t=>{i._relay(e,e,{type:f,data:t})},complete:()=>{i._relay(e,e,{type:y})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case b:{const e=s.data;return{...t,status:"done",output:e,input:void 0}}case g:return{...t,status:"error",error:s.data,input:void 0};case e:return{...t,status:"stopped",input:void 0};default:return t}},start:(s,{self:e,system:i})=>{if("active"!==s.status)return;Promise.resolve(t({input:s.input,system:i,self:e})).then((t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:b,data:t})}),(t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:g,data:t})}))},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromTransition=_,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports):"function"==typeof define&&define.amd?define(["exports"],s):s((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,(function(t){"use strict";class s{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 s={value:t,next:null};if(this._current)return this._last.next=s,void(this._last=s);this._current=s,this._last=s,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const e="xstate.stop";function i(){const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:window;if(t.__xstate__)return t.__xstate__}const o=t=>{const s=i();s&&s.register(t)};function r(t){setTimeout((()=>{throw t}))}const n="function"==typeof Symbol&&Symbol.observable||"@@observable";function a(t,s){return`${t.sessionId}.${s}`}let h=0;function c(t,s,e){const i="object"==typeof t,o=i?t:void 0;return{next:(i?t.next:t)?.bind(o),error:(i?t.error:s)?.bind(o),complete:(i?t.complete:e)?.bind(o)}}let p=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const u={clock:{setTimeout:(t,s)=>setTimeout(t,s),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class d{constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new s(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=p.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 i={...u,...e},{clock:o,logger:r,parent:n,syncSnapshot:d,id:l,systemId:_,inspect:v}=i;this.system=n?n.system:function(t,s){const e=new Map,i=new Map,o=new WeakMap,r=new Set,n={},{clock:c,logger:p}=s,u={schedule:(t,s,e,i,o=Math.random().toString(36).slice(2))=>{const r={source:t,target:s,event:e,delay:i,id:o,startedAt:Date.now()},h=a(t,o);d._snapshot._scheduledEvents[h]=r;const p=c.setTimeout((()=>{delete n[h],delete d._snapshot._scheduledEvents[h],d._relay(t,s,e)}),i);n[h]=p},cancel:(t,s)=>{const e=a(t,s),i=n[e];delete n[e],delete d._snapshot._scheduledEvents[e],c.clearTimeout(i)},cancelAll:t=>{for(const s in d._snapshot._scheduledEvents){const e=d._snapshot._scheduledEvents[s];e.source===t&&u.cancel(t,e.id)}}},d={_snapshot:{_scheduledEvents:(s?.snapshot&&s.snapshot.scheduler)??{}},_bookId:()=>"x:"+h++,_register:(t,s)=>(e.set(t,s),t),_unregister:t=>{e.delete(t.sessionId);const s=o.get(t);void 0!==s&&(i.delete(s),o.delete(t))},get:t=>i.get(t),_set:(t,s)=>{const e=i.get(t);if(e&&e!==s)throw new Error(`Actor with system ID '${t}' already exists.`);i.set(t,s),o.set(s,t)},inspect:t=>{r.add(t)},_sendInspectionEvent:s=>{if(!r.size)return;const e={...s,rootId:t.sessionId};r.forEach((t=>t.next?.(e)))},_relay:(t,s,e)=>{d._sendInspectionEvent({type:"@xstate.event",sourceRef:t,actorRef:s,event:e}),s._send(e)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...d._snapshot._scheduledEvents}}),start:()=>{const t=d._snapshot._scheduledEvents;d._snapshot._scheduledEvents={};for(const s in t){const{source:e,target:i,event:o,delay:r,id:n}=t[s];u.schedule(e,i,o,r,n)}},_clock:c,_logger:p};return d}(this,{clock:o,logger:r}),v&&!n&&this.system.inspect(c(v)),this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=d,this.options=i,this.src=i.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 s=this.eventListeners.get(t.type);if(s)for(const e of Array.from(s))e(t)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),_&&(this._systemId=_,this.system._set(_,this)),this._initState(e?.snapshot??e?.state),_&&"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,s){let e;for(this._snapshot=t;e=this._deferred.shift();)try{e()}catch(s){this._deferred.length=0,this._snapshot={...t,status:"error",error:s}}switch(this._snapshot.status){case"active":for(const s of this.observers)try{s.next?.(t)}catch(t){r(t)}break;case"done":for(const s of this.observers)try{s.next?.(t)}catch(t){r(t)}this._stopProcedure(),this._complete(),this._doneEvent=(i=this.id,o=this._snapshot.output,{type:`xstate.done.actor.${i}`,output:o}),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error)}var i,o;this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:s,snapshot:t})}subscribe(t,s,e){const i=c(t,s,e);if(this._processingStatus!==p.Stopped)this.observers.add(i);else switch(this._snapshot.status){case"done":try{i.complete?.()}catch(t){r(t)}break;case"error":{const t=this._snapshot.error;if(i.error)try{i.error(t)}catch(t){r(t)}else r(t);break}}return{unsubscribe:()=>{this.observers.delete(i)}}}on(t,s){let e=this.eventListeners.get(t);e||(e=new Set,this.eventListeners.set(t,e));const i=s.bind(void 0);return e.add(i),{unsubscribe:()=>{e.delete(i)}}}start(){if(this._processingStatus===p.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=p.Running;const t={type:"xstate.init",input: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 s,i;try{s=this.logic.transition(this._snapshot,t,this._actorScope)}catch(t){i={err:t}}if(i){const{err:t}=i;return this._snapshot={...this._snapshot,status:"error",error:t},void this._error(t)}this.update(s,t),t.type===e&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===p.Stopped?this:(this.mailbox.clear(),this._processingStatus===p.NotStarted?(this._processingStatus=p.Stopped,this):(this.mailbox.enqueue({type:e}),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){r(t)}this.observers.clear()}_reportError(t){if(!this.observers.size)return void(this._parent||r(t));let s=!1;for(const e of this.observers){const i=e.error;s||=!i;try{i?.(t)}catch(t){r(t)}}this.observers.clear(),s&&r(t)}_error(t){this._stopProcedure(),this._reportError(t),this._parent&&this.system._relay(this,this._parent,{type:`xstate.error.actor.${this.id}`,error:t})}_stopProcedure(){return this._processingStatus!==p.Running||(this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new s(this._process.bind(this)),this._processingStatus=p.Stopped,this.system._unregister(this)),this}_send(t){this._processingStatus!==p.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:o)(this)}}toJSON(){return{xstate$$type:1,id:this.id}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[n](){return this}getSnapshot(){return this._snapshot}}function l(t,s){return{config:t,transition:(s,e,i)=>({...s,context:t(s.context,e,i)}),getInitialSnapshot:(t,e)=>({status:"active",output:void 0,error:void 0,context:"function"==typeof s?s({input:e}):s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}const _=new WeakMap;const v="xstate.observable.next",f="xstate.observable.error",y="xstate.observable.complete";const g="xstate.promise.resolve",b="xstate.promise.reject";const m=l((t=>{}),void 0);t.createEmptyActor=function(){return function(t,...[s]){return new d(t,s)}(m)},t.fromCallback=function(t){return{config:t,start:(s,e)=>{const{self:i,system:o}=e,r={receivers:void 0,dispose:void 0};_.set(i,r),r.dispose=t({input:s.input,system:o,self:i,sendBack:t=>{"stopped"!==i.getSnapshot().status&&i._parent&&o._relay(i,i._parent,t)},receive:t=>{r.receivers??=new Set,r.receivers.add(t)}})},transition:(t,s,i)=>{const o=_.get(i.self);return s.type===e?(t={...t,status:"stopped",error:void 0},o.dispose?.(),t):(o.receivers?.forEach((t=>t(s))),t)},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromEventObservable=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case f:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case y:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{e._parent&&i._relay(e,e._parent,t)},error:t=>{i._relay(e,e,{type:f,data:t})},complete:()=>{i._relay(e,e,{type:y})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromObservable=function(t){return{config:t,transition:(t,s,{self:i,id:o,defer:r,system:n})=>{if("active"!==t.status)return t;switch(s.type){case v:return{...t,context:s.data};case f:return{...t,status:"error",error:s.data,input:void 0,_subscription:void 0};case y:return{...t,status:"done",input:void 0,_subscription:void 0};case e:return t._subscription.unsubscribe(),{...t,status:"stopped",input:void 0,_subscription:void 0};default:return t}},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,context:void 0,input:s,_subscription:void 0}),start:(s,{self:e,system:i})=>{"done"!==s.status&&(s._subscription=t({input:s.input,system:i,self:e}).subscribe({next:t=>{i._relay(e,e,{type:v,data:t})},error:t=>{i._relay(e,e,{type:f,data:t})},complete:()=>{i._relay(e,e,{type:y})}}))},getPersistedSnapshot:({_subscription:t,...s})=>s,restoreSnapshot:t=>({...t,_subscription:void 0})}},t.fromPromise=function(t){return{config:t,transition:(t,s)=>{if("active"!==t.status)return t;switch(s.type){case g:{const e=s.data;return{...t,status:"done",output:e,input:void 0}}case b:return{...t,status:"error",error:s.data,input:void 0};case e:return{...t,status:"stopped",input:void 0};default:return t}},start:(s,{self:e,system:i})=>{if("active"!==s.status)return;Promise.resolve(t({input:s.input,system:i,self:e})).then((t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:g,data:t})}),(t=>{"active"===e.getSnapshot().status&&i._relay(e,e,{type:b,data:t})}))},getInitialSnapshot:(t,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}},t.fromTransition=l,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"xstate-actors.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/dev/index.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/system.ts","../../src/utils.ts","../../src/createActor.ts","../../src/eventUtils.ts","../../src/actors/transition.ts","../../src/actors/callback.ts","../../src/actors/observable.ts","../../src/actors/promise.ts","../../src/actors/index.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if (!!(w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","/**\n * This function makes sure that unhandled errors are thrown in a separate macrotask.\n * It allows those errors to be detected by global error handlers and reported to bug tracking services\n * without interrupting our own stack of execution.\n *\n * @param err error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import { InspectionEvent } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n Snapshot,\n HomomorphicOmit,\n EventObject,\n AnyTransitionDefinition\n} from './types.ts';\n\nexport interface ScheduledEvent {\n id: string;\n event: EventObject;\n startedAt: number; // timestamp\n delay: number;\n source: AnyActorRef;\n target: AnyActorRef;\n}\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\nexport interface Scheduler {\n schedule(\n source: AnyActorRef,\n target: AnyActorRef,\n event: EventObject,\n delay: number,\n id: string | undefined\n ): void;\n cancel(source: AnyActorRef, id: string): void;\n cancelAll(actorRef: AnyActorRef): void;\n}\n\ntype ScheduledEventId = string & { __scheduledEventId: never };\n\nfunction createScheduledEventId(\n actorRef: AnyActorRef,\n id: string\n): ScheduledEventId {\n return `${actorRef.sessionId}.${id}` as ScheduledEventId;\n}\n\nexport interface ActorSystem<T extends ActorSystemInfo> {\n /**\n * @internal\n */\n _bookId: () => string;\n /**\n * @internal\n */\n _register: (sessionId: string, actorRef: AnyActorRef) => string;\n /**\n * @internal\n */\n _unregister: (actorRef: AnyActorRef) => void;\n /**\n * @internal\n */\n _set: <K extends keyof T['actors']>(key: K, actorRef: T['actors'][K]) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n inspect: (observer: Observer<InspectionEvent>) => void;\n /**\n * @internal\n */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /**\n * @internal\n */\n _relay: (\n source: AnyActorRef | undefined,\n target: AnyActorRef,\n event: AnyEventObject\n ) => void;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledEvents: Record<string, ScheduledEvent>;\n };\n /**\n * @internal\n */\n _snapshot: {\n _scheduledEvents: Record<ScheduledEventId, ScheduledEvent>;\n };\n start: () => void;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef,\n options: {\n clock: Clock;\n snapshot?: unknown;\n }\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const inspectionObservers = new Set<Observer<InspectionEvent>>();\n const timerMap: { [id: ScheduledEventId]: number } = {};\n const clock = options.clock;\n\n const scheduler: Scheduler = {\n schedule: (\n source,\n target,\n event,\n delay,\n id = Math.random().toString(36).slice(2)\n ) => {\n const scheduledEvent: ScheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n system._relay(source, target, event);\n }, delay);\n\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id: string) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n clock.clearTimeout(timeout);\n },\n cancelAll: (actorRef) => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent =\n system._snapshot._scheduledEvents[\n scheduledEventId as ScheduledEventId\n ];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = (event: InspectionEvent) => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach(\n (observer) => observer.next?.(resolvedInspectionEvent)\n );\n };\n\n const system: ActorSystem<T> = {\n _snapshot: {\n _scheduledEvents:\n (options?.snapshot && (options.snapshot as any).scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observer) => {\n inspectionObservers.add(observer);\n },\n _sendInspectionEvent: sendInspectionEvent as any,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: { ...system._snapshot._scheduledEvents }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const { source, target, event, delay, id } =\n scheduledEvents[scheduledId as ScheduledEventId];\n scheduler.schedule(source, target, event, delay, id);\n }\n }\n };\n\n return system;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY } from './constants.ts';\nimport type {\n AnyActorLogic,\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n ErrorActorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n let result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nexport function toStateValue(\n stateValue: StateLike<any> | StateValue\n): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nexport function toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([key, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function isActorLogic(value: any): value is AnyActorLogic {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transition' in value &&\n typeof value.transition === 'function'\n );\n}\n\nexport function isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n return (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<any, any, any, any, any, any, any>)\n ).src;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])];\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { AnyActorSystem, Clock, createSystem } from './system.ts';\n\nimport type {\n ActorScope,\n AnyActorLogic,\n AnyActorRef,\n ConditionalRequired,\n DoneActorEvent,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n IsNotNever,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport {\n ActorOptions,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\n\nexport type SnapshotListener<TLogic extends AnyActorLogic> = (\n snapshot: SnapshotFrom<TLogic>\n) => void;\n\nexport type EventListener<TEvent extends EventObject = EventObject> = (\n event: TEvent\n) => void;\n\nexport type Listener = () => void;\nexport type ErrorListener = (error: any) => void;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.\n */\nexport class Actor<TLogic extends AnyActorLogic>\n implements\n ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic>>\n{\n /**\n * The current internal state of the actor.\n */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /**\n * The unique identifier for this actor relative to its parent.\n */\n public id: string;\n\n private mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private eventListeners: Map<\n string,\n Set<(emittedEvent: EmittedFrom<TLogic>) => void>\n > = new Map();\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n\n // Actor Ref\n public _parent?: AnyActorRef;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>\n >;\n\n private _systemId: string | undefined;\n\n /**\n * The globally unique process ID for this invocation.\n */\n public sessionId: string;\n\n /**\n * The system to which this actor belongs.\n */\n public system: AnyActorSystem;\n private _doneEvent?: DoneActorEvent;\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options, if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n };\n\n const { clock, logger, parent, syncSnapshot, id, systemId, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : createSystem(this, {\n clock\n });\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = logger;\n this.clock = clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n },\n emit: (emittedEvent) => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n if (!listeners) {\n return;\n }\n for (const handler of Array.from(listeners)) {\n handler(emittedEvent);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n\n this._initState(options?.snapshot ?? options?.state);\n\n if (systemId && (this._snapshot as any).status !== 'active') {\n this.system._unregister(this);\n }\n }\n\n private _initState(persistedState?: Snapshot<unknown>) {\n try {\n this._snapshot = persistedState\n ? this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n } as any;\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n this._deferred.length = 0;\n this._snapshot = {\n ...(snapshot as any),\n status: 'error',\n error: err\n };\n }\n }\n\n switch ((this._snapshot as any).status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._snapshot as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._error((this._snapshot as any).error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest snapshot\n *\n * @example\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * },\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n switch ((this._snapshot as any).status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error': {\n const err = (this._snapshot as any).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type']>(\n type: TType,\n handler: (emitted: EmittedFrom<TLogic> & { type: TType }) => void\n ): Subscription {\n let listeners = this.eventListeners.get(type);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n\n return {\n unsubscribe: () => {\n listeners!.delete(wrappedHandler);\n }\n };\n }\n\n /**\n * Starts the Actor from the initial state\n */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: `xstate.snapshot.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n\n const status = (this._snapshot as any).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(\n this._snapshot,\n initEvent as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as any).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(\n this._snapshot,\n event,\n this._actorScope\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n const { err } = caughtError;\n\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\n\n return this;\n }\n\n /**\n * Stops the Actor and unsubscribe all listeners.\n */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _reportError(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _error(err: unknown): void {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): this {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /**\n * @internal\n */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n public send(event: EventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from {@link Actor.getSnapshot}. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n *\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change.\n * An actor may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.\n *\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\ntype RequiredOptions<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that actor system.\n *\n * @example\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine actor logic creator, see {@link createMachine}. Other actor logic creators include {@link fromCallback}, {@link fromEventObservable}, {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: ActorOptions<TLogic> & {\n [K in RequiredOptions<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredOptions<TLogic>>\n >\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\n *\n * @deprecated Use `createActor` instead\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n */\nexport type Interpreter = typeof Actor;\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that\n * is sent after the specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(delayRef: number | string, id: string) {\n return { type: `xstate.after.${delayRef}.${id}` } as const;\n}\n\n/**\n * Returns an event that represents that a final state node\n * has been reached in the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state node,\n * but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n ActorScope,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type TransitionSnapshot<TContext> = Snapshot<undefined> & {\n context: TContext;\n};\n\nexport type TransitionActorLogic<\n TContext,\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n TransitionSnapshot<TContext>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type TransitionActorRef<\n TContext,\n TEvent extends EventObject\n> = ActorRefFrom<\n TransitionActorLogic<TransitionSnapshot<TContext>, TEvent, unknown>\n>;\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and received `event` object as arguments, and returns the next state, similar to a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.\n *\n * @param transition The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:\n * - `state` - the current state.\n * - `event` - the received event.\n * - `actorScope` - the actor scope object, with properties like `self` and `system`.\n * @param initialContext The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:\n * - `input` - the `input` provided to its parent transition actor.\n * - `self` - a reference to its parent transition actor.\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n * @returns Actor logic\n *\n * @example\n * ```ts\n * const transitionLogic = fromTransition(\n * (state, event) => {\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + 1,\n * };\n * }\n * return state;\n * },\n * { count: 0 },\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * // status: 'active',\n * // context: { count: 0 },\n * // ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * // status: 'active',\n * // context: { count: 1 },\n * // ...\n * // }\n * ```\n */\nexport function fromTransition<\n TContext,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n transition: (\n snapshot: TContext,\n event: TEvent,\n actorScope: ActorScope<TransitionSnapshot<TContext>, TEvent, TSystem>\n ) => TContext,\n initialContext:\n | TContext\n | (({\n input,\n self\n }: {\n input: TInput;\n self: TransitionActorRef<TContext, TEvent>;\n }) => TContext) // TODO: type\n): TransitionActorLogic<TContext, TEvent, TInput, TEmitted> {\n return {\n config: transition,\n transition: (snapshot, event, actorScope) => {\n return {\n ...snapshot,\n context: transition(\n snapshot.context,\n event as TEvent,\n actorScope as any\n )\n };\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context:\n typeof initialContext === 'function'\n ? (initialContext as any)({ input })\n : initialContext\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFrom<CallbackActorLogic<TEvent, TInput>>;\n\nexport type Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type InvokeCallback<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown\n> = ({\n input,\n system,\n self,\n sendBack,\n receive\n}: {\n /**\n * Data that was provided to the callback actor\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /**\n * The actor system to which the callback actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the callback actor\n */\n self: CallbackActorRef<TEvent>;\n /**\n * A function that can send events back to the parent actor\n */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument;\n * the listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n}) => (() => void) | void;\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @param invokeCallback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n * - `receive` - A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs\n * The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.\n * @see {@link InvokeCallback} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n\n * @returns Callback logic\n *\n * @example\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n */\nexport function fromCallback<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n>(\n invokeCallback: InvokeCallback<TEvent, AnyEventObject, TInput>\n): CallbackActorLogic<TEvent, TInput> {\n const logic: CallbackActorLogic<TEvent, TInput> = {\n config: invokeCallback,\n start: (state, actorScope) => {\n const { self, system } = actorScope;\n\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self, callbackState);\n\n callbackState.dispose = invokeCallback({\n input: state.input,\n system,\n self,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n if (self._parent) {\n system._relay(self, self._parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n }\n });\n },\n transition: (state, event, actorScope) => {\n const callbackState: CallbackInstanceState<TEvent> = instanceStates.get(\n actorScope.self\n )!;\n\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n\n callbackState.dispose?.();\n return state;\n }\n\n callbackState.receivers?.forEach((receiver) => receiver(event));\n\n return state;\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type ObservableActorRef<TContext> = ActorRefFrom<\n ObservableActorLogic<TContext, any>\n>;\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @param observableCreator A function that creates an observable. It receives one argument, an object with the following properties:\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.\n *\n * @example\n * ```ts\n * import { fromObservable, createActor } from 'xstate'\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function fromObservable<TContext, TInput extends NonReducibleUnknown>(\n observableCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<TContext>;\n }) => Subscribable<TContext>\n): ObservableActorLogic<TContext, TInput> {\n // TODO: add event types\n const logic: ObservableActorLogic<TContext, TInput> = {\n config: observableCreator,\n transition: (snapshot, event, { self, id, defer, system }) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n const newSnapshot = {\n ...snapshot,\n context: event.data as TContext\n };\n return newSnapshot;\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...snapshot,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription!.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...state }) => state,\n restoreSnapshot: (state) => ({\n ...(state as any),\n _subscription: undefined\n })\n };\n\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers event objects.\n *\n * Event observable actor logic is described by an observable stream of {@link https://stately.ai/docs/transitions#event-objects | event objects}. Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @param lazyObservable A function that creates an observable that delivers event objects. It receives one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.\n *\n * @example\n * ```ts\n * import {\n * fromEventObservable,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(() =>\n * fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic,\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n */\nexport function fromEventObservable<\n T extends EventObject,\n TInput extends NonReducibleUnknown\n>(\n lazyObservable: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<T>;\n }) => Subscribable<T>\n): ObservableActorLogic<T, TInput> {\n // TODO: event types\n const logic: ObservableActorLogic<T, TInput> = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type PromiseSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n};\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\nexport type PromiseActorLogic<TOutput, TInput = unknown> = ActorLogic<\n PromiseSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput, // input\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type PromiseActorRef<TOutput> = ActorRefFrom<\n PromiseActorLogic<TOutput, unknown>\n>;\n\n/**\n * An actor logic creator which returns promise logic as defined by an async process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @param promiseCreator\n * A function which returns a Promise, and accepts an object with the following properties:\n * - `input` - Data that was provided to the promise actor\n * - `self` - The parent actor of the promise actor\n * - `system` - The actor system to which the promise actor belongs\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n *\n * @example\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n * const result = await fetch('https://example.com/...')\n * .then((data) => data.json());\n *\n * return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n */\nexport function fromPromise<TOutput, TInput = NonReducibleUnknown>(\n promiseCreator: ({\n input,\n system\n }: {\n /**\n * Data that was provided to the promise actor\n */\n input: TInput;\n /**\n * The actor system to which the promise actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the promise actor\n */\n self: PromiseActorRef<TOutput>;\n }) => PromiseLike<TOutput>\n): PromiseActorLogic<TOutput, TInput> {\n const logic: PromiseActorLogic<TOutput, TInput> = {\n config: promiseCreator,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case XSTATE_PROMISE_RESOLVE: {\n const resolvedValue = (event as any).data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case XSTATE_PROMISE_REJECT:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined\n };\n case XSTATE_STOP:\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n default:\n return state;\n }\n },\n start: (state, { self, system }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n\n const resolvedPromise = Promise.resolve(\n promiseCreator({ input: state.input!, system, self })\n );\n\n resolvedPromise.then(\n (response) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, {\n type: XSTATE_PROMISE_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, {\n type: XSTATE_PROMISE_REJECT,\n data: errorData\n });\n }\n );\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorRef, AnyEventObject, Snapshot } from '../types.ts';\nimport { fromTransition } from './transition.ts';\nexport {\n fromCallback,\n type CallbackActorLogic,\n type CallbackSnapshot\n} from './callback.ts';\nexport {\n fromEventObservable,\n fromObservable,\n type ObservableActorLogic,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n fromPromise,\n type PromiseActorLogic,\n type PromiseSnapshot\n} from './promise.ts';\nexport {\n fromTransition,\n type TransitionActorLogic,\n type TransitionSnapshot\n} from './transition.ts';\n\nconst emptyLogic = fromTransition((_) => undefined, undefined);\n\nexport function createEmptyActor(): ActorRef<\n Snapshot<undefined>,\n AnyEventObject\n> {\n return createActor(emptyLogic);\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","createScheduledEventId","actorRef","id","sessionId","idCounter","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","error","complete","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_snapshot","mailbox","observers","Set","eventListeners","Map","_processingStatus","NotStarted","_parent","_syncSnapshot","ref","_actorScope","_systemId","system","_doneEvent","src","_deferred","resolvedOptions","parent","syncSnapshot","systemId","inspect","rootActor","children","keyedActors","reverseKeyedActors","WeakMap","inspectionObservers","timerMap","scheduler","schedule","source","target","delay","Math","random","toString","slice","scheduledEvent","startedAt","Date","now","scheduledEventId","_scheduledEvents","timeout","_relay","cancel","cancelAll","snapshot","_bookId","_register","set","_unregister","delete","get","_set","existing","Error","observer","add","_sendInspectionEvent","size","resolvedInspectionEvent","rootId","forEach","type","sourceRef","_send","getSnapshot","scheduledEvents","scheduledId","createSystem","defer","push","stopChild","child","_stop","emit","emittedEvent","listeners","handler","Array","from","send","_initState","state","status","persistedState","restoreSnapshot","getInitialSnapshot","input","output","update","deferredFn","shift","length","_stopProcedure","_complete","invokeId","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","unsubscribe","on","wrappedHandler","Running","initEvent","attachDevTools","nextState","caughtError","transition","stop","_reportError","reportError","err2","toJSON","xstate$$type","getPersistedSnapshot","fromTransition","initialContext","config","actorScope","context","_","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_PROMISE_RESOLVE","XSTATE_PROMISE_REJECT","emptyLogic","createActor","invokeCallback","callbackState","receivers","dispose","sendBack","receive","listener","receiver","lazyObservable","data","_subscription","observableCreator","promiseCreator","resolvedValue","Promise","resolve","then","response","errorData"],"mappings":"oPAKO,MAAMA,EAKXC,YAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,QACLJ,KAAKC,SAAU,EACfD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,EAAMC,OACR,OAAOD,EAGT,OAAQpI,EAAMgH,MACZ,KAAKkE,EAAwB,CAC3B,MAAMiB,EAAiBnM,EAAc+L,KACrC,MAAO,IACF3D,EACHC,OAAQ,OACRK,OAAQyD,EACR1D,WAAO1G,EAEX,CACA,KAAKoJ,EACH,MAAO,IACF/C,EACHC,OAAQ,QACRpG,MAAQjC,EAAc+L,KACtBtD,WAAO1G,GAEX,KAAK3B,EACH,MAAO,IACFgI,EACHC,OAAQ,UACRI,WAAO1G,GAEX,QACE,OAAOqG,EACX,EAEFzI,MAAOA,CAACyI,GAAS5H,OAAMoD,aAGrB,GAAqB,WAAjBwE,EAAMC,OACR,OAGsB+D,QAAQC,QAC9BH,EAAe,CAAEzD,MAAOL,EAAMK,MAAQ7E,SAAQpD,UAGhC8L,MACbC,IACmC,WAA9B/L,EAAK2G,cAAckB,QAGvBzE,EAAOgC,OAAOpF,EAAMA,EAAM,CACxBwG,KAAMkE,EACNa,KAAMQ,GACN,IAEHC,IACmC,WAA9BhM,EAAK2G,cAAckB,QAGvBzE,EAAOgC,OAAOpF,EAAMA,EAAM,CACxBwG,KAAMmE,EACNY,KAAMS,GACN,GAEL,EAEHhE,mBAAoBA,CAACqC,EAAGpC,KACf,CACLJ,OAAQ,SACRK,YAAQ3G,EACRE,WAAOF,EACP0G,UAGJ8B,qBAAuBxE,GAAaA,EACpCwC,gBAAkBxC,GAAkBA,EAIxC"}
1
+ {"version":3,"file":"xstate-actors.umd.min.js","sources":["../../src/Mailbox.ts","../../src/constants.ts","../../src/dev/index.ts","../../src/reportUnhandledError.ts","../../src/symbolObservable.ts","../../src/system.ts","../../src/utils.ts","../../src/createActor.ts","../../src/eventUtils.ts","../../src/actors/transition.ts","../../src/actors/callback.ts","../../src/actors/observable.ts","../../src/actors/promise.ts","../../src/actors/index.ts"],"sourcesContent":["interface MailboxItem<T> {\n value: T;\n next: MailboxItem<T> | null;\n}\n\nexport class Mailbox<T> {\n private _active: boolean = false;\n private _current: MailboxItem<T> | null = null;\n private _last: MailboxItem<T> | null = null;\n\n constructor(private _process: (ev: T) => void) {}\n\n public start() {\n this._active = true;\n this.flush();\n }\n\n public clear(): void {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldnt start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n\n public enqueue(event: T): void {\n const enqueued = {\n value: event,\n next: null\n };\n\n if (this._current) {\n this._last!.next = enqueued;\n this._last = enqueued;\n return;\n }\n\n this._current = enqueued;\n this._last = enqueued;\n\n if (this._active) {\n this.flush();\n }\n }\n\n private flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n","export const STATE_DELIMITER = '.';\nexport const TARGETLESS_KEY = '';\nexport const NULL_EVENT = '';\nexport const STATE_IDENTIFIER = '#';\nexport const WILDCARD = '*';\nexport const XSTATE_INIT = 'xstate.init';\nexport const XSTATE_ERROR = 'xstate.error';\nexport const XSTATE_STOP = 'xstate.stop';\n","import isDevelopment from '#is-development';\nimport { AnyActor, DevToolsAdapter } from '../types.ts';\n\ninterface DevInterface {\n services: Set<AnyActor>;\n register(service: AnyActor): void;\n onRegister(listener: ServiceListener): void;\n}\ntype ServiceListener = (service: AnyActor) => void;\n\nexport interface XStateDevInterface {\n register: (service: AnyActor) => void;\n unregister: (service: AnyActor) => void;\n onRegister: (listener: ServiceListener) => {\n unsubscribe: () => void;\n };\n services: Set<AnyActor>;\n}\n\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nexport function getGlobal(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (isDevelopment) {\n console.warn(\n 'XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues'\n );\n }\n}\n\nfunction getDevTools(): DevInterface | undefined {\n const w = getGlobal();\n if (!!(w as any).__xstate__) {\n return (w as any).__xstate__;\n }\n\n return undefined;\n}\n\nexport function registerService(service: AnyActor) {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport const devToolsAdapter: DevToolsAdapter = (service) => {\n if (typeof window === 'undefined') {\n return;\n }\n\n const devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n};\n","/**\n * This function makes sure that unhandled errors are thrown in a separate macrotask.\n * It allows those errors to be detected by global error handlers and reported to bug tracking services\n * without interrupting our own stack of execution.\n *\n * @param err error to be thrown\n */\nexport function reportUnhandledError(err: unknown) {\n setTimeout(() => {\n throw err;\n });\n}\n","export const symbolObservable: typeof Symbol.observable = (() =>\n (typeof Symbol === 'function' && Symbol.observable) ||\n '@@observable')() as any;\n","import { InspectionEvent } from './inspection.ts';\nimport {\n AnyEventObject,\n ActorSystemInfo,\n AnyActorRef,\n Observer,\n Snapshot,\n HomomorphicOmit,\n EventObject,\n AnyTransitionDefinition\n} from './types.ts';\n\nexport interface ScheduledEvent {\n id: string;\n event: EventObject;\n startedAt: number; // timestamp\n delay: number;\n source: AnyActorRef;\n target: AnyActorRef;\n}\n\nexport interface Clock {\n setTimeout(fn: (...args: any[]) => void, timeout: number): any;\n clearTimeout(id: any): void;\n}\n\nexport interface Scheduler {\n schedule(\n source: AnyActorRef,\n target: AnyActorRef,\n event: EventObject,\n delay: number,\n id: string | undefined\n ): void;\n cancel(source: AnyActorRef, id: string): void;\n cancelAll(actorRef: AnyActorRef): void;\n}\n\ntype ScheduledEventId = string & { __scheduledEventId: never };\n\nfunction createScheduledEventId(\n actorRef: AnyActorRef,\n id: string\n): ScheduledEventId {\n return `${actorRef.sessionId}.${id}` as ScheduledEventId;\n}\n\nexport interface ActorSystem<T extends ActorSystemInfo> {\n /**\n * @internal\n */\n _bookId: () => string;\n /**\n * @internal\n */\n _register: (sessionId: string, actorRef: AnyActorRef) => string;\n /**\n * @internal\n */\n _unregister: (actorRef: AnyActorRef) => void;\n /**\n * @internal\n */\n _set: <K extends keyof T['actors']>(key: K, actorRef: T['actors'][K]) => void;\n get: <K extends keyof T['actors']>(key: K) => T['actors'][K] | undefined;\n inspect: (observer: Observer<InspectionEvent>) => void;\n /**\n * @internal\n */\n _sendInspectionEvent: (\n event: HomomorphicOmit<InspectionEvent, 'rootId'>\n ) => void;\n /**\n * @internal\n */\n _relay: (\n source: AnyActorRef | undefined,\n target: AnyActorRef,\n event: AnyEventObject\n ) => void;\n scheduler: Scheduler;\n getSnapshot: () => {\n _scheduledEvents: Record<string, ScheduledEvent>;\n };\n /**\n * @internal\n */\n _snapshot: {\n _scheduledEvents: Record<ScheduledEventId, ScheduledEvent>;\n };\n start: () => void;\n _clock: Clock;\n _logger: (...args: any[]) => void;\n}\n\nexport type AnyActorSystem = ActorSystem<any>;\n\nlet idCounter = 0;\nexport function createSystem<T extends ActorSystemInfo>(\n rootActor: AnyActorRef,\n options: {\n clock: Clock;\n logger: (...args: any[]) => void;\n snapshot?: unknown;\n }\n): ActorSystem<T> {\n const children = new Map<string, AnyActorRef>();\n const keyedActors = new Map<keyof T['actors'], AnyActorRef | undefined>();\n const reverseKeyedActors = new WeakMap<AnyActorRef, keyof T['actors']>();\n const inspectionObservers = new Set<Observer<InspectionEvent>>();\n const timerMap: { [id: ScheduledEventId]: number } = {};\n const { clock, logger } = options;\n\n const scheduler: Scheduler = {\n schedule: (\n source,\n target,\n event,\n delay,\n id = Math.random().toString(36).slice(2)\n ) => {\n const scheduledEvent: ScheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n system._relay(source, target, event);\n }, delay);\n\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id: string) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n\n clock.clearTimeout(timeout);\n },\n cancelAll: (actorRef) => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent =\n system._snapshot._scheduledEvents[\n scheduledEventId as ScheduledEventId\n ];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = (event: InspectionEvent) => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent: InspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach(\n (observer) => observer.next?.(resolvedInspectionEvent)\n );\n };\n\n const system: ActorSystem<T> = {\n _snapshot: {\n _scheduledEvents:\n (options?.snapshot && (options.snapshot as any).scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: (actorRef) => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: (systemId) => {\n return keyedActors.get(systemId) as T['actors'][any];\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(\n `Actor with system ID '${systemId as string}' already exists.`\n );\n }\n\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: (observer) => {\n inspectionObservers.add(observer);\n },\n _sendInspectionEvent: sendInspectionEvent as any,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: { ...system._snapshot._scheduledEvents }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const { source, target, event, delay, id } =\n scheduledEvents[scheduledId as ScheduledEventId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n\n return system;\n}\n","import isDevelopment from '#is-development';\nimport { isMachineSnapshot } from './State.ts';\nimport type { StateNode } from './StateNode.ts';\nimport { TARGETLESS_KEY } from './constants.ts';\nimport type {\n AnyActorLogic,\n AnyActorRef,\n AnyEventObject,\n AnyMachineSnapshot,\n AnyStateMachine,\n AnyTransitionConfig,\n ErrorActorEvent,\n EventObject,\n InvokeConfig,\n MachineContext,\n Mapper,\n NonReducibleUnknown,\n Observer,\n SingleOrArray,\n StateLike,\n StateValue,\n TransitionConfigTarget\n} from './types.ts';\n\nexport function matchesState(\n parentStateId: StateValue,\n childStateId: StateValue\n): boolean {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every((key) => {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key]!, childStateValue[key]!);\n });\n}\n\nexport function toStatePath(stateId: string | string[]): string[] {\n if (isArray(stateId)) {\n return stateId;\n }\n\n let result: string[] = [];\n let segment = '';\n\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n\n result.push(segment);\n\n return result;\n}\n\nexport function toStateValue(\n stateValue: StateLike<any> | StateValue\n): StateValue {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue as StateValue;\n }\n\n const statePath = toStatePath(stateValue);\n\n return pathToStateValue(statePath);\n}\n\nexport function pathToStateValue(statePath: string[]): StateValue {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n const value: StateValue = {};\n let marker = value;\n\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n\n return value;\n}\n\nexport function mapValues<P, O extends Record<string, unknown>>(\n collection: O,\n iteratee: (item: O[keyof O], key: keyof O, collection: O, i: number) => P\n): { [key in keyof O]: P };\nexport function mapValues(\n collection: Record<string, unknown>,\n iteratee: (\n item: unknown,\n key: string,\n collection: Record<string, unknown>,\n i: number\n ) => unknown\n) {\n const result: Record<string, unknown> = {};\n\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\n\nexport function toArrayStrict<T>(value: readonly T[] | T): readonly T[] {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\n\nexport function toArray<T>(value: readonly T[] | T | undefined): readonly T[] {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\n\nexport function resolveOutput<\n TContext extends MachineContext,\n TExpressionEvent extends EventObject\n>(\n mapper:\n | Mapper<TContext, TExpressionEvent, unknown, EventObject>\n | NonReducibleUnknown,\n context: TContext,\n event: TExpressionEvent,\n self: AnyActorRef\n): unknown {\n if (typeof mapper === 'function') {\n return mapper({ context, event, self });\n }\n\n if (\n isDevelopment &&\n !!mapper &&\n typeof mapper === 'object' &&\n Object.values(mapper).some((val) => typeof val === 'function')\n ) {\n console.warn(\n `Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.\\nFound object containing properties whose values are possibly mapping functions: ${Object.entries(\n mapper\n )\n .filter(([key, value]) => typeof value === 'function')\n .map(\n ([key, value]) =>\n `\\n - ${key}: ${(value as () => any)\n .toString()\n .replace(/\\n\\s*/g, '')}`\n )\n .join('')}`\n );\n }\n\n return mapper;\n}\n\nexport function isActorLogic(value: any): value is AnyActorLogic {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'transition' in value &&\n typeof value.transition === 'function'\n );\n}\n\nexport function isArray(value: any): value is readonly any[] {\n return Array.isArray(value);\n}\n\nexport function isErrorActorEvent(\n event: AnyEventObject\n): event is ErrorActorEvent {\n return event.type.startsWith('xstate.error.actor');\n}\n\nexport function toTransitionConfigArray<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n configLike: SingleOrArray<AnyTransitionConfig | TransitionConfigTarget>\n): Array<AnyTransitionConfig> {\n return toArrayStrict(configLike).map((transitionLike) => {\n if (\n typeof transitionLike === 'undefined' ||\n typeof transitionLike === 'string'\n ) {\n return { target: transitionLike };\n }\n\n return transitionLike;\n });\n}\n\nexport function normalizeTarget<\n TContext extends MachineContext,\n TEvent extends EventObject\n>(\n target: SingleOrArray<string | StateNode<TContext, TEvent>> | undefined\n): ReadonlyArray<string | StateNode<TContext, TEvent>> | undefined {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\n\nexport function toObserver<T>(\n nextHandler?: Observer<T> | ((value: T) => void),\n errorHandler?: (error: any) => void,\n completionHandler?: () => void\n): Observer<T> {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(\n self\n )\n };\n}\n\nexport function createInvokeId(stateNodeId: string, index: number): string {\n return `${index}.${stateNodeId}`;\n}\n\nexport function resolveReferencedActor(machine: AnyStateMachine, src: string) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/)!;\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke!;\n return (\n Array.isArray(invokeConfig)\n ? invokeConfig[indexStr as any]\n : (invokeConfig as InvokeConfig<any, any, any, any, any, any, any>)\n ).src;\n}\n\nexport function getAllOwnEventDescriptors(snapshot: AnyMachineSnapshot) {\n return [...new Set([...snapshot._nodes.flatMap((sn) => sn.ownEvents)])];\n}\n","import isDevelopment from '#is-development';\nimport { Mailbox } from './Mailbox.ts';\nimport { XSTATE_STOP } from './constants.ts';\nimport { devToolsAdapter } from './dev/index.ts';\nimport {\n createDoneActorEvent,\n createErrorActorEvent,\n createInitEvent\n} from './eventUtils.ts';\nimport { reportUnhandledError } from './reportUnhandledError.ts';\nimport { symbolObservable } from './symbolObservable.ts';\nimport { AnyActorSystem, Clock, createSystem } from './system.ts';\n\nimport type {\n ActorScope,\n AnyActorLogic,\n AnyActorRef,\n ConditionalRequired,\n DoneActorEvent,\n EmittedFrom,\n EventFromLogic,\n InputFrom,\n IsNotNever,\n Snapshot,\n SnapshotFrom\n} from './types.ts';\nimport {\n ActorOptions,\n ActorRef,\n EventObject,\n InteropSubscribable,\n Observer,\n Subscription\n} from './types.ts';\nimport { toObserver } from './utils.ts';\n\nexport const $$ACTOR_TYPE = 1;\n\nexport type SnapshotListener<TLogic extends AnyActorLogic> = (\n snapshot: SnapshotFrom<TLogic>\n) => void;\n\nexport type EventListener<TEvent extends EventObject = EventObject> = (\n event: TEvent\n) => void;\n\nexport type Listener = () => void;\nexport type ErrorListener = (error: any) => void;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nexport enum ProcessingStatus {\n NotStarted = 0,\n Running = 1,\n Stopped = 2\n}\n\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: (id) => {\n return clearTimeout(id);\n }\n } as Clock,\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change its behavior based on the events it receives, which can cause effects outside of the actor. When you run a state machine, it becomes an actor.\n */\nexport class Actor<TLogic extends AnyActorLogic>\n implements\n ActorRef<SnapshotFrom<TLogic>, EventFromLogic<TLogic>, EmittedFrom<TLogic>>\n{\n /**\n * The current internal state of the actor.\n */\n private _snapshot!: SnapshotFrom<TLogic>;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as delayed events and transitions.\n */\n public clock: Clock;\n public options: Readonly<ActorOptions<TLogic>>;\n\n /**\n * The unique identifier for this actor relative to its parent.\n */\n public id: string;\n\n private mailbox: Mailbox<EventFromLogic<TLogic>> = new Mailbox(\n this._process.bind(this)\n );\n\n private observers: Set<Observer<SnapshotFrom<TLogic>>> = new Set();\n private eventListeners: Map<\n string,\n Set<(emittedEvent: EmittedFrom<TLogic>) => void>\n > = new Map();\n private logger: (...args: any[]) => void;\n\n /** @internal */\n public _processingStatus: ProcessingStatus = ProcessingStatus.NotStarted;\n\n // Actor Ref\n public _parent?: AnyActorRef;\n /** @internal */\n public _syncSnapshot?: boolean;\n public ref: ActorRef<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n EmittedFrom<TLogic>\n >;\n // TODO: add typings for system\n private _actorScope: ActorScope<\n SnapshotFrom<TLogic>,\n EventFromLogic<TLogic>,\n AnyActorSystem,\n EmittedFrom<TLogic>\n >;\n\n private _systemId: string | undefined;\n\n /**\n * The globally unique process ID for this invocation.\n */\n public sessionId: string;\n\n /**\n * The system to which this actor belongs.\n */\n public system: AnyActorSystem;\n private _doneEvent?: DoneActorEvent;\n\n public src: string | AnyActorLogic;\n\n /**\n * Creates a new actor instance for the given logic with the provided options, if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(\n public logic: TLogic,\n options?: ActorOptions<TLogic>\n ) {\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n };\n\n const { clock, logger, parent, syncSnapshot, id, systemId, inspect } =\n resolvedOptions;\n\n this.system = parent\n ? parent.system\n : createSystem(this, {\n clock,\n logger\n });\n\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions as ActorOptions<TLogic> &\n typeof defaultOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: (fn) => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: (child) => {\n if (child._parent !== this) {\n throw new Error(\n `Cannot stop child actor ${child.id} of ${this.id} because it is not a child`\n );\n }\n (child as any)._stop();\n },\n emit: (emittedEvent) => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n if (!listeners) {\n return;\n }\n for (const handler of Array.from(listeners)) {\n handler(emittedEvent);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n\n if (systemId) {\n this._systemId = systemId;\n this.system._set(systemId, this);\n }\n\n this._initState(options?.snapshot ?? options?.state);\n\n if (systemId && (this._snapshot as any).status !== 'active') {\n this.system._unregister(this);\n }\n }\n\n private _initState(persistedState?: Snapshot<unknown>) {\n try {\n this._snapshot = persistedState\n ? this.logic.restoreSnapshot\n ? this.logic.restoreSnapshot(persistedState, this._actorScope)\n : persistedState\n : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n } as any;\n }\n }\n\n // array of functions to defer\n private _deferred: Array<() => void> = [];\n\n private update(snapshot: SnapshotFrom<TLogic>, event: EventObject): void {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn: (typeof this._deferred)[number] | undefined;\n\n while ((deferredFn = this._deferred.shift())) {\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n this._deferred.length = 0;\n this._snapshot = {\n ...(snapshot as any),\n status: 'error',\n error: err\n };\n }\n }\n\n switch ((this._snapshot as any).status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(\n this.id,\n (this._snapshot as any).output\n );\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n\n break;\n case 'error':\n this._error((this._snapshot as any).error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted. The observer can be:\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest snapshot\n *\n * @example\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * },\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object that has an `.unsubscribe()` method. You can call `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest snapshot, or an observer object whose `.next(snapshot)` method receives the latest snapshot\n */\n public subscribe(observer: Observer<SnapshotFrom<TLogic>>): Subscription;\n public subscribe(\n nextListener?: (snapshot: SnapshotFrom<TLogic>) => void,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription;\n public subscribe(\n nextListenerOrObserver?:\n | ((snapshot: SnapshotFrom<TLogic>) => void)\n | Observer<SnapshotFrom<TLogic>>,\n errorListener?: (error: any) => void,\n completeListener?: () => void\n ): Subscription {\n const observer = toObserver(\n nextListenerOrObserver,\n errorListener,\n completeListener\n );\n\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n switch ((this._snapshot as any).status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error': {\n const err = (this._snapshot as any).error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n }\n }\n }\n\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n\n public on<TType extends EmittedFrom<TLogic>['type']>(\n type: TType,\n handler: (emitted: EmittedFrom<TLogic> & { type: TType }) => void\n ): Subscription {\n let listeners = this.eventListeners.get(type);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n\n return {\n unsubscribe: () => {\n listeners!.delete(wrappedHandler);\n }\n };\n }\n\n /**\n * Starts the Actor from the initial state\n */\n public start(): this {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n\n if (this._syncSnapshot) {\n this.subscribe({\n next: (snapshot: Snapshot<unknown>) => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent!, {\n type: `xstate.snapshot.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n\n this.system._register(this.sessionId, this);\n if (this._systemId) {\n this.system._set(this._systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n\n const status = (this._snapshot as any).status;\n\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(\n this._snapshot,\n initEvent as unknown as EventFromLogic<TLogic>\n );\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error((this._snapshot as any).error);\n return this;\n }\n\n if (!this._parent) {\n this.system.start();\n }\n\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent as unknown as EventFromLogic<TLogic>);\n\n if (this.options.devTools) {\n this.attachDevTools();\n }\n\n this.mailbox.start();\n\n return this;\n }\n\n private _process(event: EventFromLogic<TLogic>) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(\n this._snapshot,\n event,\n this._actorScope\n );\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = { err };\n }\n\n if (caughtError) {\n const { err } = caughtError;\n\n this._snapshot = {\n ...(this._snapshot as any),\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n\n private _stop(): this {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({ type: XSTATE_STOP } as any);\n\n return this;\n }\n\n /**\n * Stops the Actor and unsubscribe all listeners.\n */\n public stop(): this {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n private _complete(): void {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n }\n private _reportError(err: unknown): void {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n return;\n }\n let reportError = false;\n\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n private _error(err: unknown): void {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(\n this,\n this._parent,\n createErrorActorEvent(this.id, err)\n );\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n private _stopProcedure(): this {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n\n return this;\n }\n\n /**\n * @internal\n */\n public _send(event: EventFromLogic<TLogic>) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n // do nothing\n if (isDevelopment) {\n const eventString = JSON.stringify(event);\n\n console.warn(\n `Event \"${event.type}\" was sent to stopped actor \"${this.id} (${this.sessionId})\". This actor has already reached its final state, and will not transition.\\nEvent: ${eventString}`\n );\n }\n return;\n }\n\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n public send(event: EventFromLogic<TLogic>) {\n if (isDevelopment && typeof event === 'string') {\n throw new Error(\n `Only event objects may be sent to actors; use .send({ type: \"${event}\" }) instead`\n );\n }\n this.system._relay(undefined, this, event);\n }\n\n private attachDevTools(): void {\n const { devTools } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter =\n typeof devTools === 'function' ? devTools : devToolsAdapter;\n\n resolvedDevToolsAdapter(this);\n }\n }\n public toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from {@link Actor.getSnapshot}. Persisted state represents the internal state of the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n *\n * @see https://stately.ai/docs/persistence\n */\n public getPersistedSnapshot(): Snapshot<unknown>;\n public getPersistedSnapshot(options?: unknown): Snapshot<unknown> {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\n }\n\n public [symbolObservable](): InteropSubscribable<SnapshotFrom<TLogic>> {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change.\n * An actor may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with `fromCallback`, will not emit snapshots.\n *\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n public getSnapshot(): SnapshotFrom<TLogic> {\n if (isDevelopment && !this._snapshot) {\n throw new Error(\n `Snapshot can't be read while the actor initializes itself`\n );\n }\n return this._snapshot;\n }\n}\n\ntype RequiredOptions<TLogic extends AnyActorLogic> =\n undefined extends InputFrom<TLogic> ? never : 'input';\n\n/**\n * Creates a new actor instance for the given actor logic with the provided options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that actor system.\n *\n * @example\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine actor logic creator, see {@link createMachine}. Other actor logic creators include {@link fromCallback}, {@link fromEventObservable}, {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nexport function createActor<TLogic extends AnyActorLogic>(\n logic: TLogic,\n ...[options]: ConditionalRequired<\n [\n options?: ActorOptions<TLogic> & {\n [K in RequiredOptions<TLogic>]: unknown;\n }\n ],\n IsNotNever<RequiredOptions<TLogic>>\n >\n): Actor<TLogic> {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\n *\n * @deprecated Use `createActor` instead\n */\nexport const interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n */\nexport type Interpreter = typeof Actor;\n","import { XSTATE_INIT } from './constants.ts';\nimport { DoneActorEvent, DoneStateEvent, ErrorActorEvent } from './types.ts';\n\n/**\n * Returns an event that represents an implicit event that\n * is sent after the specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nexport function createAfterEvent(delayRef: number | string, id: string) {\n return { type: `xstate.after.${delayRef}.${id}` } as const;\n}\n\n/**\n * Returns an event that represents that a final state node\n * has been reached in the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nexport function createDoneStateEvent(\n id: string,\n output?: unknown\n): DoneStateEvent {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state node,\n * but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nexport function createDoneActorEvent(\n invokeId: string,\n output?: unknown\n): DoneActorEvent {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output\n };\n}\n\nexport function createErrorActorEvent(\n id: string,\n error?: unknown\n): ErrorActorEvent {\n return { type: `xstate.error.actor.${id}`, error };\n}\n\nexport function createInitEvent(input: unknown) {\n return { type: XSTATE_INIT, input } as const;\n}\n","import { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n ActorScope,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type TransitionSnapshot<TContext> = Snapshot<undefined> & {\n context: TContext;\n};\n\nexport type TransitionActorLogic<\n TContext,\n TEvent extends EventObject,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n> = ActorLogic<\n TransitionSnapshot<TContext>,\n TEvent,\n TInput,\n AnyActorSystem,\n TEmitted\n>;\n\nexport type TransitionActorRef<\n TContext,\n TEvent extends EventObject\n> = ActorRefFrom<\n TransitionActorLogic<TransitionSnapshot<TContext>, TEvent, unknown>\n>;\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and received `event` object as arguments, and returns the next state, similar to a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial state argument, and is not the same as the State object of an actor or a state within a machine configuration.\n *\n * @param transition The transition function used to describe the transition logic. It should return the next state given the current state and event. It receives the following arguments:\n * - `state` - the current state.\n * - `event` - the received event.\n * - `actorScope` - the actor scope object, with properties like `self` and `system`.\n * @param initialContext The initial state of the transition function, either an object representing the state, or a function which returns a state object. If a function, it will receive as its only argument an object with the following properties:\n * - `input` - the `input` provided to its parent transition actor.\n * - `self` - a reference to its parent transition actor.\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n * @returns Actor logic\n *\n * @example\n * ```ts\n * const transitionLogic = fromTransition(\n * (state, event) => {\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + 1,\n * };\n * }\n * return state;\n * },\n * { count: 0 },\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * // status: 'active',\n * // context: { count: 0 },\n * // ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * // status: 'active',\n * // context: { count: 1 },\n * // ...\n * // }\n * ```\n */\nexport function fromTransition<\n TContext,\n TEvent extends EventObject,\n TSystem extends AnyActorSystem,\n TInput extends NonReducibleUnknown,\n TEmitted extends EventObject = EventObject\n>(\n transition: (\n snapshot: TContext,\n event: TEvent,\n actorScope: ActorScope<TransitionSnapshot<TContext>, TEvent, TSystem>\n ) => TContext,\n initialContext:\n | TContext\n | (({\n input,\n self\n }: {\n input: TInput;\n self: TransitionActorRef<TContext, TEvent>;\n }) => TContext) // TODO: type\n): TransitionActorLogic<TContext, TEvent, TInput, TEmitted> {\n return {\n config: transition,\n transition: (snapshot, event, actorScope) => {\n return {\n ...snapshot,\n context: transition(\n snapshot.context,\n event as TEvent,\n actorScope as any\n )\n };\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context:\n typeof initialContext === 'function'\n ? (initialContext as any)({ input })\n : initialContext\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n AnyActorRef,\n AnyEventObject,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types';\n\ninterface CallbackInstanceState<TEvent extends EventObject> {\n receivers: Set<(e: TEvent) => void> | undefined;\n dispose: (() => void) | void;\n}\n\nconst instanceStates = /* #__PURE__ */ new WeakMap<\n AnyActorRef,\n CallbackInstanceState<any>\n>();\n\nexport type CallbackSnapshot<TInput> = Snapshot<undefined> & {\n input: TInput;\n};\n\nexport type CallbackActorLogic<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorLogic<\n CallbackSnapshot<TInput>,\n TEvent,\n TInput,\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type CallbackActorRef<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n> = ActorRefFrom<CallbackActorLogic<TEvent, TInput>>;\n\nexport type Receiver<TEvent extends EventObject> = (\n listener: {\n bivarianceHack(event: TEvent): void;\n }['bivarianceHack']\n) => void;\n\nexport type InvokeCallback<\n TEvent extends EventObject = AnyEventObject,\n TSentEvent extends EventObject = AnyEventObject,\n TInput = NonReducibleUnknown\n> = ({\n input,\n system,\n self,\n sendBack,\n receive\n}: {\n /**\n * Data that was provided to the callback actor\n * @see {@link https://stately.ai/docs/input | Input docs}\n */\n input: TInput;\n /**\n * The actor system to which the callback actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the callback actor\n */\n self: CallbackActorRef<TEvent>;\n /**\n * A function that can send events back to the parent actor\n */\n sendBack: (event: TSentEvent) => void;\n /**\n * A function that can be called with a listener function argument;\n * the listener is then called whenever events are received by the callback actor\n */\n receive: Receiver<TEvent>;\n}) => (() => void) | void;\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @param invokeCallback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n * - `receive` - A function that can send events back to the parent actor; the listener is then called whenever events are received by the callback actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs\n * The callback function can (optionally) return a cleanup function, which is called when the actor is stopped.\n * @see {@link InvokeCallback} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n\n * @returns Callback logic\n *\n * @example\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n */\nexport function fromCallback<\n TEvent extends EventObject,\n TInput = NonReducibleUnknown\n>(\n invokeCallback: InvokeCallback<TEvent, AnyEventObject, TInput>\n): CallbackActorLogic<TEvent, TInput> {\n const logic: CallbackActorLogic<TEvent, TInput> = {\n config: invokeCallback,\n start: (state, actorScope) => {\n const { self, system } = actorScope;\n\n const callbackState: CallbackInstanceState<TEvent> = {\n receivers: undefined,\n dispose: undefined\n };\n\n instanceStates.set(self, callbackState);\n\n callbackState.dispose = invokeCallback({\n input: state.input,\n system,\n self,\n sendBack: (event) => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n if (self._parent) {\n system._relay(self, self._parent, event);\n }\n },\n receive: (listener) => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n }\n });\n },\n transition: (state, event, actorScope) => {\n const callbackState: CallbackInstanceState<TEvent> = instanceStates.get(\n actorScope.self\n )!;\n\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n\n callbackState.dispose?.();\n return state;\n }\n\n callbackState.receivers?.forEach((receiver) => receiver(event));\n\n return state;\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n EventObject,\n NonReducibleUnknown,\n Snapshot,\n Subscribable,\n Subscription\n} from '../types';\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\nexport type ObservableSnapshot<\n TContext,\n TInput extends NonReducibleUnknown\n> = Snapshot<undefined> & {\n context: TContext | undefined;\n input: TInput | undefined;\n _subscription: Subscription | undefined;\n};\n\nexport type ObservableActorLogic<\n TContext,\n TInput extends NonReducibleUnknown\n> = ActorLogic<\n ObservableSnapshot<TContext, TInput>,\n { type: string; [k: string]: unknown },\n TInput,\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type ObservableActorRef<TContext> = ActorRefFrom<\n ObservableActorLogic<TContext, any>\n>;\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @param observableCreator A function that creates an observable. It receives one argument, an object with the following properties:\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.\n *\n * @example\n * ```ts\n * import { fromObservable, createActor } from 'xstate'\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nexport function fromObservable<TContext, TInput extends NonReducibleUnknown>(\n observableCreator: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<TContext>;\n }) => Subscribable<TContext>\n): ObservableActorLogic<TContext, TInput> {\n // TODO: add event types\n const logic: ObservableActorLogic<TContext, TInput> = {\n config: observableCreator,\n transition: (snapshot, event, { self, id, defer, system }) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT: {\n const newSnapshot = {\n ...snapshot,\n context: event.data as TContext\n };\n return newSnapshot;\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...snapshot,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription!.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...state }) => state,\n restoreSnapshot: (state) => ({\n ...(state as any),\n _subscription: undefined\n })\n };\n\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers event objects.\n *\n * Event observable actor logic is described by an observable stream of {@link https://stately.ai/docs/transitions#event-objects | event objects}. Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @param lazyObservable A function that creates an observable that delivers event objects. It receives one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS Observable, although RxJS is not required to create them.\n *\n * @example\n * ```ts\n * import {\n * fromEventObservable,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(() =>\n * fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic,\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n */\nexport function fromEventObservable<\n T extends EventObject,\n TInput extends NonReducibleUnknown\n>(\n lazyObservable: ({\n input,\n system\n }: {\n input: TInput;\n system: AnyActorSystem;\n self: ObservableActorRef<T>;\n }) => Subscribable<T>\n): ObservableActorLogic<T, TInput> {\n // TODO: event types\n const logic: ObservableActorLogic<T, TInput> = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription!.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, { self, system }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n\n state._subscription = lazyObservable({\n input: state.input!,\n system,\n self\n }).subscribe({\n next: (value) => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: (err) => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, { type: XSTATE_OBSERVABLE_COMPLETE });\n }\n });\n },\n getPersistedSnapshot: ({ _subscription, ...snapshot }) => snapshot,\n restoreSnapshot: (snapshot: any) => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n\n return logic;\n}\n","import { XSTATE_STOP } from '../constants.ts';\nimport { AnyActorSystem } from '../system.ts';\nimport {\n ActorLogic,\n ActorRefFrom,\n EventObject,\n NonReducibleUnknown,\n Snapshot\n} from '../types.ts';\n\nexport type PromiseSnapshot<TOutput, TInput> = Snapshot<TOutput> & {\n input: TInput | undefined;\n};\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\nexport type PromiseActorLogic<TOutput, TInput = unknown> = ActorLogic<\n PromiseSnapshot<TOutput, TInput>,\n { type: string; [k: string]: unknown },\n TInput, // input\n AnyActorSystem,\n EventObject // TEmitted\n>;\n\nexport type PromiseActorRef<TOutput> = ActorRefFrom<\n PromiseActorLogic<TOutput, unknown>\n>;\n\n/**\n * An actor logic creator which returns promise logic as defined by an async process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @param promiseCreator\n * A function which returns a Promise, and accepts an object with the following properties:\n * - `input` - Data that was provided to the promise actor\n * - `self` - The parent actor of the promise actor\n * - `system` - The actor system to which the promise actor belongs\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n *\n * @example\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n * const result = await fetch('https://example.com/...')\n * .then((data) => data.json());\n *\n * return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n */\nexport function fromPromise<TOutput, TInput = NonReducibleUnknown>(\n promiseCreator: ({\n input,\n system\n }: {\n /**\n * Data that was provided to the promise actor\n */\n input: TInput;\n /**\n * The actor system to which the promise actor belongs\n */\n system: AnyActorSystem;\n /**\n * The parent actor of the promise actor\n */\n self: PromiseActorRef<TOutput>;\n }) => PromiseLike<TOutput>\n): PromiseActorLogic<TOutput, TInput> {\n const logic: PromiseActorLogic<TOutput, TInput> = {\n config: promiseCreator,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n\n switch (event.type) {\n case XSTATE_PROMISE_RESOLVE: {\n const resolvedValue = (event as any).data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case XSTATE_PROMISE_REJECT:\n return {\n ...state,\n status: 'error',\n error: (event as any).data,\n input: undefined\n };\n case XSTATE_STOP:\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n default:\n return state;\n }\n },\n start: (state, { self, system }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n\n const resolvedPromise = Promise.resolve(\n promiseCreator({ input: state.input!, system, self })\n );\n\n resolvedPromise.then(\n (response) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, {\n type: XSTATE_PROMISE_RESOLVE,\n data: response\n });\n },\n (errorData) => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n system._relay(self, self, {\n type: XSTATE_PROMISE_REJECT,\n data: errorData\n });\n }\n );\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: (snapshot) => snapshot,\n restoreSnapshot: (snapshot: any) => snapshot\n };\n\n return logic;\n}\n","import { createActor } from '../createActor.ts';\nimport type { ActorRef, AnyEventObject, Snapshot } from '../types.ts';\nimport { fromTransition } from './transition.ts';\nexport {\n fromCallback,\n type CallbackActorLogic,\n type CallbackSnapshot\n} from './callback.ts';\nexport {\n fromEventObservable,\n fromObservable,\n type ObservableActorLogic,\n type ObservableSnapshot\n} from './observable.ts';\nexport {\n fromPromise,\n type PromiseActorLogic,\n type PromiseSnapshot\n} from './promise.ts';\nexport {\n fromTransition,\n type TransitionActorLogic,\n type TransitionSnapshot\n} from './transition.ts';\n\nconst emptyLogic = fromTransition((_) => undefined, undefined);\n\nexport function createEmptyActor(): ActorRef<\n Snapshot<undefined>,\n AnyEventObject\n> {\n return createActor(emptyLogic);\n}\n"],"names":["Mailbox","constructor","_process","this","_active","_current","_last","start","flush","clear","next","enqueue","event","enqueued","value","consumed","XSTATE_STOP","getDevTools","w","globalThis","self","window","__xstate__","devToolsAdapter","service","devTools","register","reportUnhandledError","err","setTimeout","symbolObservable","Symbol","observable","createScheduledEventId","actorRef","id","sessionId","idCounter","toObserver","nextHandler","errorHandler","completionHandler","isObserver","undefined","bind","error","complete","ProcessingStatus","defaultOptions","clock","fn","ms","clearTimeout","logger","console","log","Actor","logic","options","_snapshot","mailbox","observers","Set","eventListeners","Map","_processingStatus","NotStarted","_parent","_syncSnapshot","ref","_actorScope","_systemId","system","_doneEvent","src","_deferred","resolvedOptions","parent","syncSnapshot","systemId","inspect","rootActor","children","keyedActors","reverseKeyedActors","WeakMap","inspectionObservers","timerMap","scheduler","schedule","source","target","delay","Math","random","toString","slice","scheduledEvent","startedAt","Date","now","scheduledEventId","_scheduledEvents","timeout","_relay","cancel","cancelAll","snapshot","_bookId","_register","set","_unregister","delete","get","_set","existing","Error","observer","add","_sendInspectionEvent","size","resolvedInspectionEvent","rootId","forEach","type","sourceRef","_send","getSnapshot","scheduledEvents","scheduledId","_clock","_logger","createSystem","defer","push","stopChild","child","_stop","emit","emittedEvent","listeners","handler","Array","from","send","_initState","state","status","persistedState","restoreSnapshot","getInitialSnapshot","input","output","update","deferredFn","shift","length","_stopProcedure","_complete","invokeId","_error","subscribe","nextListenerOrObserver","errorListener","completeListener","Stopped","unsubscribe","on","wrappedHandler","Running","initEvent","attachDevTools","nextState","caughtError","transition","stop","_reportError","reportError","err2","toJSON","xstate$$type","getPersistedSnapshot","fromTransition","initialContext","config","actorScope","context","_","instanceStates","XSTATE_OBSERVABLE_NEXT","XSTATE_OBSERVABLE_ERROR","XSTATE_OBSERVABLE_COMPLETE","XSTATE_PROMISE_RESOLVE","XSTATE_PROMISE_REJECT","emptyLogic","createActor","invokeCallback","callbackState","receivers","dispose","sendBack","receive","listener","receiver","lazyObservable","data","_subscription","observableCreator","promiseCreator","resolvedValue","Promise","resolve","then","response","errorData"],"mappings":"oPAKO,MAAMA,EAKXC,YAAoBC,GAA2BC,KAA3BD,SAAAA,EAAyBC,KAJrCC,SAAmB,EAAKD,KACxBE,SAAkC,KAAIF,KACtCG,MAA+B,IAES,CAEzCC,QACLJ,KAAKC,SAAU,EACfD,KAAKK,OACP,CAEOC,QAGDN,KAAKE,WACPF,KAAKE,SAASK,KAAO,KACrBP,KAAKG,MAAQH,KAAKE,SAEtB,CAEOM,QAAQC,GACb,MAAMC,EAAW,CACfC,MAAOF,EACPF,KAAM,MAGR,GAAIP,KAAKE,SAGP,OAFAF,KAAKG,MAAOI,KAAOG,OACnBV,KAAKG,MAAQO,GAIfV,KAAKE,SAAWQ,EAChBV,KAAKG,MAAQO,EAETV,KAAKC,SACPD,KAAKK,OAET,CAEQA,QACN,KAAOL,KAAKE,UAAU,CAGpB,MAAMU,EAAWZ,KAAKE,SACtBF,KAAKD,SAASa,EAASD,OACvBX,KAAKE,SAAWU,EAASL,IAC3B,CACAP,KAAKG,MAAQ,IACf,EClDK,MAEMU,EAAc,cCiC3B,SAASC,IACP,MAAMC,EApBoB,oBAAfC,WACFA,WAEW,oBAATC,KACFA,KAGAC,OAcT,GAAOH,EAAUI,WACf,OAAQJ,EAAUI,UAItB,CAcO,MAAMC,EAAoCC,IAK/C,MAAMC,EAAWR,IAEbQ,GACFA,EAASC,SAASF,EACpB,EC/DK,SAASG,EAAqBC,GACnCC,YAAW,KACT,MAAMD,CAAG,GAEb,CCXO,MAAME,EACQ,mBAAXC,QAA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G,cAAcoB,QAGvB3E,EAAOgC,OAAOpF,EAAMA,EAAM,CACxBwG,KAAMqE,EACNY,KAAMS,GACN,GAEL,EAEHhE,mBAAoBA,CAACqC,EAAGpC,KACf,CACLJ,OAAQ,SACRK,YAAQ7G,EACRE,WAAOF,EACP4G,UAGJ8B,qBAAuB1E,GAAaA,EACpC0C,gBAAkB1C,GAAkBA,EAIxC"}
@@ -2,11 +2,11 @@ import { MachineSnapshot } from "./State.js";
2
2
  import { StateNode } from "./StateNode.js";
3
3
  import { AnyActorSystem } from "./system.js";
4
4
  import { ResolveTypegenMeta, TypegenDisabled } from "./typegenTypes.js";
5
- import type { ActorLogic, ActorScope, AnyActorRef, AnyActorScope, Equals, EventDescriptor, EventObject, HistoryValue, InternalMachineImplementations, MachineConfig, MachineContext, MachineImplementationsSimplified, NoInfer, ParameterizedObject, ProvidedActor, Snapshot, StateMachineDefinition, StateValue, TransitionDefinition } from "./types.js";
5
+ import type { ActorLogic, ActorScope, AnyActorRef, AnyActorScope, DoNotInfer, Equals, EventDescriptor, EventObject, HistoryValue, InternalMachineImplementations, MachineConfig, MachineContext, MachineImplementationsSimplified, ParameterizedObject, ProvidedActor, Snapshot, StateMachineDefinition, StateValue, TransitionDefinition } from "./types.js";
6
6
  export declare const STATE_IDENTIFIER = "#";
7
7
  export declare const WILDCARD = "*";
8
8
  export declare class StateMachine<TContext extends MachineContext, TEvent extends EventObject, TChildren extends Record<string, AnyActorRef | undefined>, TActor extends ProvidedActor, TAction extends ParameterizedObject, TGuard extends ParameterizedObject, TDelay extends string, TStateValue extends StateValue, TTag extends string, TInput, TOutput, TEmitted extends EventObject = EventObject, // TODO: remove default
9
- TResolvedTypesMeta = ResolveTypegenMeta<TypegenDisabled, NoInfer<TEvent>, TActor, TAction, TGuard, TDelay, TTag, TEmitted>> implements ActorLogic<MachineSnapshot<TContext, TEvent, TChildren, TStateValue, TTag, TOutput>, TEvent, TInput, AnyActorSystem, TEmitted> {
9
+ TResolvedTypesMeta = ResolveTypegenMeta<TypegenDisabled, DoNotInfer<TEvent>, TActor, TAction, TGuard, TDelay, TTag, TEmitted>> implements ActorLogic<MachineSnapshot<TContext, TEvent, TChildren, TStateValue, TTag, TOutput>, TEvent, TInput, AnyActorSystem, TEmitted> {
10
10
  /**
11
11
  * The raw config used to create the machine.
12
12
  */
@@ -1,4 +1,4 @@
1
- import { ActionArgs, ActionFunction, EventObject, MachineContext, NoInfer, ParameterizedObject, RaiseActionOptions, SendExpr } from "../types.js";
1
+ import { ActionArgs, ActionFunction, DoNotInfer, EventObject, MachineContext, ParameterizedObject, RaiseActionOptions, SendExpr } from "../types.js";
2
2
  export interface RaiseAction<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> {
3
3
  (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
4
4
  _out_TEvent?: TEvent;
@@ -10,4 +10,4 @@ export interface RaiseAction<TContext extends MachineContext, TExpressionEvent e
10
10
  *
11
11
  * @param eventType The event to raise.
12
12
  */
13
- export declare function raise<TContext extends MachineContext, TExpressionEvent extends EventObject, TEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TDelay extends string = never, TUsedDelay extends TDelay = never>(eventOrExpr: NoInfer<TEvent> | SendExpr<TContext, TExpressionEvent, TParams, NoInfer<TEvent>, TEvent>, options?: RaiseActionOptions<TContext, TExpressionEvent, TParams, NoInfer<TEvent>, TUsedDelay>): ActionFunction<TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
13
+ export declare function raise<TContext extends MachineContext, TExpressionEvent extends EventObject, TEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TDelay extends string = never, TUsedDelay extends TDelay = never>(eventOrExpr: DoNotInfer<TEvent> | SendExpr<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TEvent>, options?: RaiseActionOptions<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TUsedDelay>): ActionFunction<TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
@@ -1,4 +1,4 @@
1
- import { ActionArgs, ActionFunction, AnyActorRef, AnyEventObject, Cast, EventFrom, EventObject, InferEvent, MachineContext, NoInfer, ParameterizedObject, SendExpr, SendToActionOptions } from "../types.js";
1
+ import { ActionArgs, ActionFunction, AnyActorRef, AnyEventObject, Cast, DoNotInfer, EventFrom, EventObject, InferEvent, MachineContext, ParameterizedObject, SendExpr, SendToActionOptions } from "../types.js";
2
2
  export interface SendToAction<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TEvent extends EventObject, TDelay extends string> {
3
3
  (args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams): void;
4
4
  _out_TDelay?: TDelay;
@@ -12,7 +12,7 @@ export interface SendToAction<TContext extends MachineContext, TExpressionEvent
12
12
  * - `id` - The unique send event identifier (used with `cancel()`).
13
13
  * - `delay` - The number of milliseconds to delay the sending of the event.
14
14
  */
15
- export declare function sendTo<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TTargetActor extends AnyActorRef, TEvent extends EventObject, TDelay extends string = never, TUsedDelay extends TDelay = never>(to: TTargetActor | string | ((args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams) => TTargetActor | string), eventOrExpr: EventFrom<TTargetActor> | SendExpr<TContext, TExpressionEvent, TParams, InferEvent<Cast<EventFrom<TTargetActor>, EventObject>>, TEvent>, options?: SendToActionOptions<TContext, TExpressionEvent, TParams, NoInfer<TEvent>, TUsedDelay>): ActionFunction<TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
15
+ export declare function sendTo<TContext extends MachineContext, TExpressionEvent extends EventObject, TParams extends ParameterizedObject['params'] | undefined, TTargetActor extends AnyActorRef, TEvent extends EventObject, TDelay extends string = never, TUsedDelay extends TDelay = never>(to: TTargetActor | string | ((args: ActionArgs<TContext, TExpressionEvent, TEvent>, params: TParams) => TTargetActor | string), eventOrExpr: EventFrom<TTargetActor> | SendExpr<TContext, TExpressionEvent, TParams, InferEvent<Cast<EventFrom<TTargetActor>, EventObject>>, TEvent>, options?: SendToActionOptions<TContext, TExpressionEvent, TParams, DoNotInfer<TEvent>, TUsedDelay>): ActionFunction<TContext, TExpressionEvent, TEvent, TParams, never, never, never, TDelay, never>;
16
16
  /**
17
17
  * Sends an event to this machine's parent.
18
18
  *