xstate 6.0.0-alpha.71 → 6.0.0-alpha.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/declarations/src/durable/index.d.ts +16 -7
- package/dist/xstate-durable.cjs.js +9 -12
- package/dist/xstate-durable.development.cjs.js +9 -12
- package/dist/xstate-durable.development.esm.js +9 -12
- package/dist/xstate-durable.esm.js +9 -12
- package/dist/xstate-durable.umd.min.js +1 -1
- package/dist/xstate-durable.umd.min.js.map +1 -1
- package/docs/api-stability.json +4 -4
- package/docs/durable-execution.md +10 -2
- package/docs/index.md +1 -1
- package/package.json +1 -1
|
@@ -47,10 +47,9 @@ export interface DurableEffect<TEffect> extends DurableEffectMetadata {
|
|
|
47
47
|
* timers, terminations) route to them without any per-actor wiring; omitted
|
|
48
48
|
* operations keep their default local behavior.
|
|
49
49
|
*
|
|
50
|
-
*
|
|
51
|
-
* during `executeEffects`: the execution captures and retains
|
|
52
|
-
*
|
|
53
|
-
* adapter. While the loop is parked, a root-addressed event reaches
|
|
50
|
+
* By default, events addressed to this execution's root actor do not reach
|
|
51
|
+
* `sendEvent` during `executeEffects`: the execution captures and retains
|
|
52
|
+
* them, and `waitForEvent()` hands them out before deferring to this adapter. While the loop is parked, a root-addressed event reaches
|
|
54
53
|
* `enqueueRootEvent`, or the broader `sendEvent` override when implemented,
|
|
55
54
|
* so the host can place it in its own mailbox.
|
|
56
55
|
*
|
|
@@ -72,7 +71,8 @@ export interface DurableExecutionAdapter<TLogic extends AnyActorLogic> extends P
|
|
|
72
71
|
scheduleTimer?: ActorSystemRuntime['scheduleTimer'];
|
|
73
72
|
/**
|
|
74
73
|
* Enqueues an event addressed to this execution's root while the durable
|
|
75
|
-
* loop is parked in `waitForEvent()
|
|
74
|
+
* loop is parked in `waitForEvent()`, or at any time with
|
|
75
|
+
* `captureRootEvents: false`. Use this when the host only owns the
|
|
76
76
|
* root mailbox; implementing `sendEvent` instead takes ownership of delivery
|
|
77
77
|
* for every target and must use `deliverEvent` for co-located actors.
|
|
78
78
|
*/
|
|
@@ -185,7 +185,7 @@ export interface DurableExecution<TLogic extends AnyActorLogic> {
|
|
|
185
185
|
* failed operation rejects it. Operations are handed to the runtime one at
|
|
186
186
|
* a time, in initiation order.
|
|
187
187
|
*
|
|
188
|
-
*
|
|
188
|
+
* By default, events addressed to this execution's root actor produced along
|
|
189
189
|
* the way are retained, in order, and handed out by `waitForEvent()`
|
|
190
190
|
* before it defers to the adapter — so the drive loop is just
|
|
191
191
|
* `transition(snapshot, await waitForEvent())` + `executeEffects`.
|
|
@@ -195,7 +195,8 @@ export interface DurableExecution<TLogic extends AnyActorLogic> {
|
|
|
195
195
|
* Resolves with the next event addressed to this execution's root actor:
|
|
196
196
|
* an event a prior `executeEffects` batch captured (an invoked actor
|
|
197
197
|
* completing, a child reporting up), or — once none are queued — whatever
|
|
198
|
-
* the adapter's durable wait produces.
|
|
198
|
+
* the adapter's durable wait produces. With `captureRootEvents: false`,
|
|
199
|
+
* always delegates to the adapter's wait.
|
|
199
200
|
*/
|
|
200
201
|
waitForEvent(): Promise<EventFromLogic<TLogic>>;
|
|
201
202
|
run(...[input]: undefined extends InputFrom<TLogic> ? [input?: InputFrom<TLogic>] : [input: InputFrom<TLogic>]): Promise<OutputFrom<TLogic>>;
|
|
@@ -210,6 +211,14 @@ export interface DurableExecution<TLogic extends AnyActorLogic> {
|
|
|
210
211
|
* @experimental
|
|
211
212
|
*/
|
|
212
213
|
export interface DurableExecutionOptions {
|
|
214
|
+
/**
|
|
215
|
+
* Retains root-addressed events produced during `executeEffects` until the
|
|
216
|
+
* batch succeeds. Defaults to `true`. Set to `false` for a live host that
|
|
217
|
+
* owns a single FIFO mailbox: all root events then reach the adapter's
|
|
218
|
+
* `sendEvent` or `enqueueRootEvent`, including during effect execution.
|
|
219
|
+
* The host owns their ordering and must handle events from failed batches.
|
|
220
|
+
*/
|
|
221
|
+
captureRootEvents?: boolean;
|
|
213
222
|
/**
|
|
214
223
|
* Observes the execution's inspection events — actor lifecycle, event
|
|
215
224
|
* routing, transitions — across the whole live actor tree. The host-side
|
|
@@ -30,10 +30,9 @@ var effectDescriptor = require('./effectDescriptor-a6247f92.cjs.js');
|
|
|
30
30
|
* timers, terminations) route to them without any per-actor wiring; omitted
|
|
31
31
|
* operations keep their default local behavior.
|
|
32
32
|
*
|
|
33
|
-
*
|
|
34
|
-
* during `executeEffects`: the execution captures and retains
|
|
35
|
-
*
|
|
36
|
-
* adapter. While the loop is parked, a root-addressed event reaches
|
|
33
|
+
* By default, events addressed to this execution's root actor do not reach
|
|
34
|
+
* `sendEvent` during `executeEffects`: the execution captures and retains
|
|
35
|
+
* them, and `waitForEvent()` hands them out before deferring to this adapter. While the loop is parked, a root-addressed event reaches
|
|
37
36
|
* `enqueueRootEvent`, or the broader `sendEvent` override when implemented,
|
|
38
37
|
* so the host can place it in its own mailbox.
|
|
39
38
|
*
|
|
@@ -238,19 +237,17 @@ function createDurable(logic, adapter, options) {
|
|
|
238
237
|
wrapped.runLogic = runtime.runLogic;
|
|
239
238
|
}
|
|
240
239
|
wrapped.sendEvent = (source, target, event) => {
|
|
241
|
-
|
|
240
|
+
const captureBatch = options?.captureRootEvents !== false ? currentBatch : undefined;
|
|
241
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent && adapter.enqueueRootEvent) {
|
|
242
242
|
return dispatch(() => adapter.enqueueRootEvent(source, event));
|
|
243
243
|
}
|
|
244
|
-
if (!
|
|
244
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent) {
|
|
245
245
|
// The root actor is inert; delivering locally would enqueue into a
|
|
246
246
|
// mailbox that never runs, silently losing the event.
|
|
247
|
-
throw new Error(`A root-addressed event ("${event.type}") was produced while the durable loop was parked, but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
247
|
+
throw new Error(`A root-addressed event ("${event.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
248
248
|
}
|
|
249
|
-
if (
|
|
250
|
-
|
|
251
|
-
// root-addressed send while the loop is parked is an ordinary host
|
|
252
|
-
// delivery that belongs in the host's mailbox.
|
|
253
|
-
currentBatch.rootEvents.push({
|
|
249
|
+
if (captureBatch && target.address === rootAddress) {
|
|
250
|
+
captureBatch.rootEvents.push({
|
|
254
251
|
event,
|
|
255
252
|
source
|
|
256
253
|
});
|
|
@@ -30,10 +30,9 @@ var effectDescriptor = require('./effectDescriptor-e41e1627.development.cjs.js')
|
|
|
30
30
|
* timers, terminations) route to them without any per-actor wiring; omitted
|
|
31
31
|
* operations keep their default local behavior.
|
|
32
32
|
*
|
|
33
|
-
*
|
|
34
|
-
* during `executeEffects`: the execution captures and retains
|
|
35
|
-
*
|
|
36
|
-
* adapter. While the loop is parked, a root-addressed event reaches
|
|
33
|
+
* By default, events addressed to this execution's root actor do not reach
|
|
34
|
+
* `sendEvent` during `executeEffects`: the execution captures and retains
|
|
35
|
+
* them, and `waitForEvent()` hands them out before deferring to this adapter. While the loop is parked, a root-addressed event reaches
|
|
37
36
|
* `enqueueRootEvent`, or the broader `sendEvent` override when implemented,
|
|
38
37
|
* so the host can place it in its own mailbox.
|
|
39
38
|
*
|
|
@@ -238,19 +237,17 @@ function createDurable(logic, adapter, options) {
|
|
|
238
237
|
wrapped.runLogic = runtime.runLogic;
|
|
239
238
|
}
|
|
240
239
|
wrapped.sendEvent = (source, target, event) => {
|
|
241
|
-
|
|
240
|
+
const captureBatch = options?.captureRootEvents !== false ? currentBatch : undefined;
|
|
241
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent && adapter.enqueueRootEvent) {
|
|
242
242
|
return dispatch(() => adapter.enqueueRootEvent(source, event));
|
|
243
243
|
}
|
|
244
|
-
if (!
|
|
244
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent) {
|
|
245
245
|
// The root actor is inert; delivering locally would enqueue into a
|
|
246
246
|
// mailbox that never runs, silently losing the event.
|
|
247
|
-
throw new Error(`A root-addressed event ("${event.type}") was produced while the durable loop was parked, but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
247
|
+
throw new Error(`A root-addressed event ("${event.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
248
248
|
}
|
|
249
|
-
if (
|
|
250
|
-
|
|
251
|
-
// root-addressed send while the loop is parked is an ordinary host
|
|
252
|
-
// delivery that belongs in the host's mailbox.
|
|
253
|
-
currentBatch.rootEvents.push({
|
|
249
|
+
if (captureBatch && target.address === rootAddress) {
|
|
250
|
+
captureBatch.rootEvents.push({
|
|
254
251
|
event,
|
|
255
252
|
source
|
|
256
253
|
});
|
|
@@ -26,10 +26,9 @@ import { a as initialTransition, t as transition, d as describeExecutableEffect
|
|
|
26
26
|
* timers, terminations) route to them without any per-actor wiring; omitted
|
|
27
27
|
* operations keep their default local behavior.
|
|
28
28
|
*
|
|
29
|
-
*
|
|
30
|
-
* during `executeEffects`: the execution captures and retains
|
|
31
|
-
*
|
|
32
|
-
* adapter. While the loop is parked, a root-addressed event reaches
|
|
29
|
+
* By default, events addressed to this execution's root actor do not reach
|
|
30
|
+
* `sendEvent` during `executeEffects`: the execution captures and retains
|
|
31
|
+
* them, and `waitForEvent()` hands them out before deferring to this adapter. While the loop is parked, a root-addressed event reaches
|
|
33
32
|
* `enqueueRootEvent`, or the broader `sendEvent` override when implemented,
|
|
34
33
|
* so the host can place it in its own mailbox.
|
|
35
34
|
*
|
|
@@ -234,19 +233,17 @@ function createDurable(logic, adapter, options) {
|
|
|
234
233
|
wrapped.runLogic = runtime.runLogic;
|
|
235
234
|
}
|
|
236
235
|
wrapped.sendEvent = (source, target, event) => {
|
|
237
|
-
|
|
236
|
+
const captureBatch = options?.captureRootEvents !== false ? currentBatch : undefined;
|
|
237
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent && adapter.enqueueRootEvent) {
|
|
238
238
|
return dispatch(() => adapter.enqueueRootEvent(source, event));
|
|
239
239
|
}
|
|
240
|
-
if (!
|
|
240
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent) {
|
|
241
241
|
// The root actor is inert; delivering locally would enqueue into a
|
|
242
242
|
// mailbox that never runs, silently losing the event.
|
|
243
|
-
throw new Error(`A root-addressed event ("${event.type}") was produced while the durable loop was parked, but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
243
|
+
throw new Error(`A root-addressed event ("${event.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
244
244
|
}
|
|
245
|
-
if (
|
|
246
|
-
|
|
247
|
-
// root-addressed send while the loop is parked is an ordinary host
|
|
248
|
-
// delivery that belongs in the host's mailbox.
|
|
249
|
-
currentBatch.rootEvents.push({
|
|
245
|
+
if (captureBatch && target.address === rootAddress) {
|
|
246
|
+
captureBatch.rootEvents.push({
|
|
250
247
|
event,
|
|
251
248
|
source
|
|
252
249
|
});
|
|
@@ -26,10 +26,9 @@ import { a as initialTransition, t as transition, d as describeExecutableEffect
|
|
|
26
26
|
* timers, terminations) route to them without any per-actor wiring; omitted
|
|
27
27
|
* operations keep their default local behavior.
|
|
28
28
|
*
|
|
29
|
-
*
|
|
30
|
-
* during `executeEffects`: the execution captures and retains
|
|
31
|
-
*
|
|
32
|
-
* adapter. While the loop is parked, a root-addressed event reaches
|
|
29
|
+
* By default, events addressed to this execution's root actor do not reach
|
|
30
|
+
* `sendEvent` during `executeEffects`: the execution captures and retains
|
|
31
|
+
* them, and `waitForEvent()` hands them out before deferring to this adapter. While the loop is parked, a root-addressed event reaches
|
|
33
32
|
* `enqueueRootEvent`, or the broader `sendEvent` override when implemented,
|
|
34
33
|
* so the host can place it in its own mailbox.
|
|
35
34
|
*
|
|
@@ -234,19 +233,17 @@ function createDurable(logic, adapter, options) {
|
|
|
234
233
|
wrapped.runLogic = runtime.runLogic;
|
|
235
234
|
}
|
|
236
235
|
wrapped.sendEvent = (source, target, event) => {
|
|
237
|
-
|
|
236
|
+
const captureBatch = options?.captureRootEvents !== false ? currentBatch : undefined;
|
|
237
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent && adapter.enqueueRootEvent) {
|
|
238
238
|
return dispatch(() => adapter.enqueueRootEvent(source, event));
|
|
239
239
|
}
|
|
240
|
-
if (!
|
|
240
|
+
if (!captureBatch && target.address === rootAddress && !runtime.sendEvent) {
|
|
241
241
|
// The root actor is inert; delivering locally would enqueue into a
|
|
242
242
|
// mailbox that never runs, silently losing the event.
|
|
243
|
-
throw new Error(`A root-addressed event ("${event.type}") was produced while the durable loop was parked, but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
243
|
+
throw new Error(`A root-addressed event ("${event.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);
|
|
244
244
|
}
|
|
245
|
-
if (
|
|
246
|
-
|
|
247
|
-
// root-addressed send while the loop is parked is an ordinary host
|
|
248
|
-
// delivery that belongs in the host's mailbox.
|
|
249
|
-
currentBatch.rootEvents.push({
|
|
245
|
+
if (captureBatch && target.address === rootAddress) {
|
|
246
|
+
captureBatch.rootEvents.push({
|
|
250
247
|
event,
|
|
251
248
|
source
|
|
252
249
|
});
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateDurable={})}(this,function(t){"use strict";const e=new WeakMap;function s(t){return e.get(t)??t.scheduledAt}function r(t,s){e.set(t,s)}function n(t){return!0===t._remote}function i(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function o(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function c(t){return new Error(void 0===t.incarnation?`Unable to send event to actor '${t.$actor}': no live actor has that address`:`Unable to send event to actor '${t.$actor}' (incarnation '${t.incarnation}'): no live actor has that address and incarnation`)}function a(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}Object.freeze({status:"active",output:void 0,error:void 0});const h=[],d=new Error("Transition effect");const u="xstate.stop",l="@xstate.terminate",p="xstate.timer";function f(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function _(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:f(t.event)??t.event}}function v(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function y(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}function m(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",f(t.event)??t.event])}(e)}`}function g(t){return{type:"xstate.init",input:t}}const b=new WeakMap;async function x(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const i=b.get(t)?.get(e);if(i)return i;if("active"!==t.getSnapshot().status)throw new Error(`Actor terminated before step "${e}" completed`);let o,c;const a=new Promise((t,e)=>{o=t,c=e});let h,d=b.get(t);d||(d=new Map,b.set(t,d)),d.set(e,a);const u=()=>{h?.unsubscribe(),d.delete(e),d.size||b.delete(t)};return a.then(u,u),h=t.subscribe({error:c,complete:()=>c(new Error(`Actor terminated before step "${e}" completed`))}),(async()=>{try{r({type:"xstate.logic.effect.start",key:e});const n=await s();"active"===t.getSnapshot().status&&(r({type:"xstate.logic.effect.resolve",key:e,output:n}),o(n))}catch(s){"active"===t.getSnapshot().status&&r({type:"xstate.logic.effect.reject",key:e,error:s}),c(s)}})().catch(c),a}function S(t,e,s){if(i(e)){const r=e,n=t?.system,i=n&&a(n,r);if(!i){const e=c(r);if(!n)throw e;return void n.deadLetter(t,void 0,s,"missingTarget",{targetId:o(r.$actor),error:e})}e=i}if(w(t,e,s))return;e._send(s,t)}function w(t,e,s){const r=function(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!r&&(e.system.deadLetter(t,e,s,"internalEvent",{error:r}),!0)}function E(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function A(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function I(t=this.source.system){return t.scheduleTimer(this.source,_(this),this.delay??0)}function k(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,_(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function O(t){const e=[t];return{kind:"builtin",exec:E,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function T(t,e,s){const r=t.self,n={id:e.id,seq:e.seq,delay:s};if("@xstate.raise"===e.type)return{kind:"builtin",type:e.type,source:r,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,e.event,n],exec:I};const i="self"===e.target?r:e.target;return{kind:"builtin",type:e.type,source:r,target:i,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,i,e.event,n],exec:k}}function R(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:A,type:l,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function j(t,e,[s,r]){const n="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,o=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===l);return!n||i||o?[s,r]:[s,[...r,R(t,s)]]}class M{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function $(t){setTimeout(()=>{throw t})}const q="function"==typeof Symbol&&Symbol.observable||"@@observable";let P;function L(){return void 0!==P}function z(){return P}function C(t,e){if(!t)return e();const s=P;P=t;try{return e()}finally{P=s}}const K=new WeakMap,D=new WeakMap,U=new Map;function V(t){const e=t._peekKeyedActors;return e?e.call(t)??U:t.keyedActors}function N(t){t._snapshotVersion++}function W(t){return t._snapshotVersion}function F(t,e,s){const r=L(),n=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),i=new Map(s?.keyedActors??V(t)),o=new WeakMap,c=Object.assign(Object.create(t),{children:n,keyedActors:i,reverseKeyedActors:o,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),N(c),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=o.get(t);void 0!==e&&i.get(e)===t&&i.delete(e),o.delete(t),N(c)},_set:(t,e)=>{const s=i.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);i.set(t,e),o.set(e,t),N(c)},get:t=>i.get(t),getAll:()=>Object.fromEntries(i),onEmitted:e=>t.onEmitted(e),_notifyEmitted:(e,s)=>t._notifyEmitted(e,s),_hasInspectionObservers:r?()=>t._hasInspectionObservers?.()??!1:()=>!1,_sendInspectionEvent:r?e=>t._sendInspectionEvent(e):()=>{}});for(const[t,e]of i)e&&o.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(i.set(e,t),o.set(t,e))}return c}function J(t){const e=K.get(t);if(e)return e;const s=D.get(t);if(!s)return;const r=s();return K.set(t,r),D.delete(t),r}function B(t,e,s=e.system,r){D.delete(t);const n=W(s),i=r?J(r):void 0,o=i?.actor===e?i:J(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===n)return void K.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=V(s);let d=h.size?new Map(h):U;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===U&&(d=new Map),d.set(t,e))}K.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:n}})}let H=!1;const X=Object.freeze([]),G={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[p]:!0};let Q=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Y=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function Z(t,e){try{t?.(e)}catch(t){$(t)}}function tt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function et(t,e){return new st(t,e)}class st{get address(){return this._address??=this._parent?`${this._parent.address}/${bt(this.id)}`:bt(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=Q.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...Y,...e}:Y,{clock:r,logger:n,parent:i,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var d;this.system=i?i.system:s._systemRef?.current??function(t,e){return new kt(t,e)}(this,{clock:r,logger:n,snapshot:s.snapshot,createActorRef:et}),i||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!i&&this.system.inspect(pt(h)),s.onRejectedEvent&&!i&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const r=function(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}(e);return r?St(t,xt(s?.parent,r.prefix),r.index+1):s?.parent||St(t,xt(void 0,e),1),e}const r=gt(s?.src),n=xt(s?.parent,r),i=t._snapshot._nextActorIds[n]??0;return St(t,n,i+1),s?.parent||"x"===r||0!==i?`${r}:${i}`:r}(this.system,c,{parent:i,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=i,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const u=e?.snapshot;this._restored=void 0!==u;try{if(void 0!==u){if(!this.logic.restoreSnapshot&&null===u)throw new Error("Persisted snapshot must be an object.");this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(u,this._actorScope):u)}else if(e?._inert);else{const[t,e]=j(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){const e=void 0===u?void 0:this.logic._createRestoreErrorSnapshot?.(u,t);this._setSnapshot(e??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>function(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===Q.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=H;try{H=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==Q.Stopped&&this._recoverOrError(t)})}finally{H=e}};this._processingStatus!==Q.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,B(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=j(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),tt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??X)Z(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??X,actions:this._collectedActions??X,sent:this._collectedSent??X,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return tt(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const r=pt(t,e,s);if(this._processingStatus!==Q.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":Z(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),Z(r.error,t)):$(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,n)=>{const i=pt(s,r,n);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,i.next?.(r))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Q.Running)return this;if(this._processingStatus===Q.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(`Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`)}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Q.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,g(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,g(this.options.input)):(function(t,e,s){const r=K.get(t),n=W(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===n&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=n,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,_(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=j(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let i=this._snapshot;try{const[n,o]=r;n!==s||o.length||!("machine"in s)||t.type===u||e&&Object.hasOwn(G,t.type)||this._reportUnhandledEvent(t),i=n,this._setSnapshot(i),tt(o,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i,s)||this._inspectTransition(this._snapshot,t))}t.type===u&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){Z(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)Z(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===Q.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Q.NotStarted?(this._processingStatus=Q.Stopped,this.system._unregister(this),this):(this._send({type:u}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??X)Z(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||$(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch($)}catch(n){$(n)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const n=r.error;r.passive||(e||=!n,s||=!!n),Z(n,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,n,i;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,n=t,i=this.sessionId,{type:"xstate.error.actor",error:n,actorId:r,sessionId:i}))}_stopProcedure(){this._processingStatus===Q.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Q.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===Q.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new M(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[q](){return this}getSnapshot(){return this._snapshot}}const rt=Symbol();function nt(t,e,s=!0){const r=at(t);return r?(r.snapshot=e,r.materialized&&(r.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&B(e,t.self),e}function it(t,e){nt(t,e,!1);const s=at(t);ct.set(e,t);const r=()=>(B(e,t.self,t.system),J(e));return s&&(s.materialized?s.identityProvider=r:s.identityProvider??=r),function(t,e){K.delete(t),D.set(t,e)}(e,r),e}const ot=Symbol(),ct=new WeakMap;function at(t){return t[ot]}function ht(t){return at(t).materialize()}const dt={[rt]:!0,get _parent(){const t=at(this);return t.parentKnown?t.parent:ht(this).self._parent},get self(){return ht(this).self},get defer(){return ht(this).defer},get id(){return ht(this).id},get logger(){return ht(this).logger},get sessionId(){return ht(this).sessionId},get stopChild(){return ht(this).stopChild},get system(){return ht(this).system},get emit(){return ht(this).emit},get actionExecutor(){return ht(this).actionExecutor}};function ut(t,e,s,r,n){const i=e?.(),o=n??i?.actor,c=o?.system,a=o&&c?F(c,s,n?void 0:i?.systemState):void 0,h=function(t,...[e]){if(e&&"parent"in e)throw new Error('The "parent" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.');return new st(t,e)}(t,{_inert:!0,...o?{id:o.id,_sessionId:o.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return o?._parent&&(h._parent=o._parent,h._address=void 0),r&&(h._snapshot=r),Object.create(h._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function lt(t,e,s,r){const n=r??(e&&"object"==typeof e?ct.get(e):void 0),i=n?at(n):void 0,o=e&&"object"==typeof e?function(t){return K.get(t)}(e):void 0,c=i?.identityProvider??(e&&"object"==typeof e?function(t){const e=K.get(t);return e?()=>e:D.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:(h=e,h&&"object"==typeof h&&"machine"in h&&"value"in h?e.children:{}),identityProvider:i?.identityProvider??c,parent:s?._parent??i?.parent??o?.actor._parent,parentKnown:!(!s&&!i?.parentKnown&&!o&&e)};var h;if(a.materialize=()=>a.materialized??=ut(t,a.sourceRef,a.sourceChildren,a.snapshot,s),!a.identityProvider&&!e){const e={},r=a.sourceRef,n=a.sourceChildren;let i,o;const c=()=>i??=ut(t,r,n,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(o)return o;const t=c();return B(e,t.self,t.system),o=J(e)}}const d=Object.create(dt);return d[ot]=a,d}function pt(t,e,s){const r="object"==typeof t,n=r?t:void 0;return{next:(r?t.next:t)?.bind(n),error:(r?t.error:e)?.bind(n),complete:(r?t.complete:s)?.bind(n),...r&&t.passive?{passive:!0}:{}}}let ft;Object.freeze({}),Object.freeze([]);let _t,vt=0;function yt(){return ft??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${ft}:${(vt++).toString(36)}`}function mt(t,e){if(!t)return e();const s=_t;_t=t;try{return e()}finally{_t=s}}function gt(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function bt(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function xt(t,e){return`${t?t.address:""}|${e}`}function St(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},N(t))}const wt=["spawnActor","startActor","stopActor","terminateActor","emitEvent","scheduleTimer","cancelTimer","cancelAllTimers","deadLetter"],Et=Object.freeze({});function At(t,e){return m(t,e)}function It(t,e){return t.getSnapshot()?.timers?.find(t=>y(t,e))}class kt{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity=_t??{executionId:yt(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const r=z();r&&this.inspect(r),this._snapshot={_scheduledTimers:s?.scheduler??Et,_nextActorIds:{}}}_recordSent(t,e,s,r,n){if(!this._inspectionObservers?.size||!t)return;const i=t;(i._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:n})}schedule(t,e,s){const r=At(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const n=It(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}const i=this._clock.now?.()??Date.now(),o={source:t,delay:s,key:e,scheduledAt:i,dueAt:i+s};this._snapshot._scheduledTimers===Et&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=o,N(this);const c=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],N(this),this._deliver(t,t,{type:p,...e})},s);(this._timerMap??={})[r]=c}cancel(t,e){const s=At(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==Et&&delete this._snapshot._scheduledTimers[s],N(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){S(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),N(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&N(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&N(this)}inspect(t){const e=pt(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){$(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){$(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(i(e)){const r=a(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:o(e.$actor),error:c(e)})}if(w(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,n){const i=this._rejectionListeners;if(i?.size){const o={event:s,targetRef:e,targetId:e?.id??n?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:n?.issues,error:n?.error};for(const t of[...i])try{t(o)}catch(t){$(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,n)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):x(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const n=It(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of h)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw d;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:n,key:i}=t[s];this.scheduleTimer(r,i,Math.max(0,n-(this._clock.now?.()??Date.now())))}}}function Ot(t){if(i(t))return{...t};const e=n(t)?t.sessionId:void 0;return void 0===e?{$actor:t.address}:{$actor:t.address,incarnation:e}}function Tt(t,e,s){if(!L())return;const r=t.self;r?.system._hasInspectionObservers?.()&&r._inspectTransition(e,s)}class Rt extends Error{constructor(){super("Durable execution was stopped"),this.name="DurableExecutionCancelledError"}}class jt extends Error{constructor(){super("run() can only start a fresh durable execution; resume checkpoints with restore() and the explicit transition loop"),this.name="DurableExecutionResumeError"}}t.DurableExecutionCancelledError=Rt,t.DurableExecutionResumeError=jt,t.createDurable=function(t,e,i){let o=e.transitionIndex??0;const c=o;let a=!1;const h=()=>e.now?.()??Date.now(),d=new WeakSet;let u=0===o?void 0:o-1;const l=new WeakMap;if(!Number.isSafeInteger(o)||o<0)throw new RangeError("transitionIndex must be a non-negative safe integer");const p=(t,e=!1)=>{const s=e?o:o++;return u=e?u??s:s,t.map((t,r)=>{const n={id:`${e?"restore:":""}${s}:${r}`,transitionIndex:s,effectIndex:r,effect:t};let i;return Object.defineProperty(n,"descriptor",{enumerable:!0,get:()=>i??=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:Ot(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&Ot(t.source),actor:Ot(t.actor),id:t.id,src:gt(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&Ot(t.source),actor:Ot(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:Ot(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:Ot(t.source),target:t.target&&Ot(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:Ot(t.source),...v(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:Ot(t.source),actor:Ot(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:Ot(t.source),actor:Ot(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&Ot(t.source),target:t.target&&Ot(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}}(t)}),n})},f=bt(function(t){const e=gt(t);return"x"===e?"x:0":e}(t)),_=t.id??f,m=t.version,b=e.executionId?{executionId:e.executionId,nextSessionId:0}:void 0,x={};for(const t of[...wt,"sendEvent","runStep","runLogic"]){const s=e[t];s&&(x[t]=s.bind(e))}const w=Object.keys(x).length>0||!!e.enqueueRootEvent;let E;const A=[];let I=Promise.resolve();const k=t=>E?((t,e)=>{const s=I.then(e).then(()=>{});return I=s.catch(()=>{}),((t,e)=>(t.pending.add(e),e.catch(e=>{t.failures.push(e)}).then(()=>t.pending.delete(e)),e))(t,s)})(E,t):t(),R=async t=>{for(;t.pending.size;)await Promise.allSettled([...t.pending])};function M(t,n,i=!1,o){const c={};for(const e of wt){const n=t[e]??(i?(...t)=>("spawnActor"===e?t[1]:t[0]).system[e](...t):void 0);n&&(c[e]=(...t)=>k(()=>{if("scheduleTimer"===e&&o&&(t[2]=Math.min(o.delay,Math.max(0,o.deadline-h()))),"scheduleTimer"===e){const e=t[0],i=t[1],c=e.getSnapshot()?.timers?.find(t=>y(t,i));if(c){const e=s(c);void 0===e||o||(t[2]=Math.min(c.delay,Math.max(0,e+c.delay-h())));const i=n(...t);return i?Promise.resolve(i).then(()=>{r(c,e??h())}):void r(c,e??h())}}return n(...t)}))}return t.runStep&&(c.runStep=t.runStep),t.runLogic&&(c.runLogic=t.runLogic),c.sendEvent=(s,r,i)=>{if(!E&&r.address===f&&!t.sendEvent&&e.enqueueRootEvent)return k(()=>e.enqueueRootEvent(s,i));if(!E&&r.address===f&&!t.sendEvent)throw new Error(`A root-addressed event ("${i.type}") was produced while the durable loop was parked, but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);if(E&&r.address===f)return void E.rootEvents.push({event:i,source:s});const o=t.sendEvent;if(o)return k(()=>o(s,r,i));if(n)return k(()=>S(s,r,i));throw new TypeError(`The durable runtime does not support the sendEvent operation (target '${r.address}')`)},c}const $=w?M(x,!0):void 0;function q(t,e){if(t.address===e)return t;if(!e.startsWith(`${t.address}/`))return;const s=t.getSnapshot().children;for(const t of Object.values(s??{})){const s=t&&q(t,e);if(s)return s}}const P=i?.inspect;function L(t,e=!1){if("error"===t.status){const e=J(t)?.actor;e&&!d.has(e)&&(e.subscribe({error(){}}),d.add(e))}if($||P){const s=J(t)?.actor,r=new Set,n=t=>{var s;if(r.has(t.system)||(r.add(t.system),$&&(t.system.runtime=$),s=t.system,P&&!s._hasInspectionObservers?.()&&s.inspect(P)),e){const e=t.getSnapshot().children;for(const t of Object.values(e??{}))t&&n(t)}};if(s&&n(s),!e||!s){const e=t.children;for(const t of Object.values(e??{}))t&&n(t)}}return t}const z={rootAddress:f,machineId:_,machineVersion:m,get nextTransitionIndex(){return o},restore(e){if(a||o!==c||E)throw new Error("restore() requires a fresh durable execution");const{snapshot:s,scope:r}=C(P,()=>mt(b,()=>{const s=lt(t),r=t.restoreSnapshot?t.restoreSnapshot(e,s):e;return nt(s,r,!1),{snapshot:L(it(s,r),!0),scope:s}})),i=[];if("active"===s.status){const{children:t,timers:e}=s;for(const e of Object.values(t??{}))e&&!n(e)&&"active"===e.getSnapshot().status&&i.push(O(e));for(const t of e??[]){const e=T(r,t,t.delay);void 0!==t.scheduledAt&&l.set(e,{deadline:t.scheduledAt+t.delay,delay:t.delay}),i.push(e)}}return a=!0,[s,p(i,!0)]},initialTransition(...e){if(a)throw new Error("initialTransition() cannot initialize a restored execution");const[s,r]=C(P,()=>mt(b,()=>function(t,...[e]){const s=lt(t),[r,n]=j(s,void 0,t.initialTransition(e,s));nt(s,r,!1);const i=it(s,r);return Tt(s,i,g(e)),[i,n]}(t,...e)));return[L(s),p(r)]},transition(e,s){const[r,n]=C(P,()=>mt(b,()=>function(t,e,s){const r=lt(t,e);nt(r,e,!1);const[n,i]=j(r,e,t.transition(e,s,r));nt(r,n,!1);const o=n===e?n:it(r,n);return Tt(r,o,s),[o,i]}(t,e,s)));return[L(r),p(n)]},getActorRef(t,e){const s=J(t)?.actor;return s&&void 0!==e?q(s,e):s},async executeEffects(t){if(E)throw new Error("executeEffects calls must not overlap: await the previous call before starting the next batch.");const s={rootEvents:[],failures:[],pending:new Set};E=s;const r=w?void 0:{};try{for(const s of t){const{effect:t}=s,n={id:s.id,transitionIndex:s.transitionIndex,effectIndex:s.effectIndex},i=e.runtime?.(n,t),o=l.get(t),c=i||o?M({...x,...i},w,!!i||w,o):r;"action"===t.kind?await e.executeAction(t,n,c??$??{}):await t.exec(c)}await(async t=>{if(await R(t),t.failures.length)throw t.failures[0]})(s),A.push(...s.rootEvents)}catch(t){throw await R(s),t}finally{E=void 0}},async waitForEvent(){if(void 0===u)throw new Error("Cannot wait for an event before the first transition or restore");const t=A.shift();return t?t.event:e.waitForEvent({id:a&&0===o?"event:restore:0":`event:${u}`,transitionIndex:u})},async run(...t){if(a||0!==c||o!==c)throw new jt;let[e,s]=z.initialTransition(...t);for(await z.executeEffects(s);"active"===e.status;){const t=await z.waitForEvent();[e,s]=z.transition(e,t),await z.executeEffects(s)}const r=e;if("done"===r.status)return r.output;if("error"===r.status)throw r.error;throw new Rt}};return z},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateDurable={})}(this,function(t){"use strict";const e=new WeakMap;function s(t){return e.get(t)??t.scheduledAt}function r(t,s){e.set(t,s)}function n(t){return!0===t._remote}function i(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function o(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function c(t){return new Error(void 0===t.incarnation?`Unable to send event to actor '${t.$actor}': no live actor has that address`:`Unable to send event to actor '${t.$actor}' (incarnation '${t.incarnation}'): no live actor has that address and incarnation`)}function a(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}Object.freeze({status:"active",output:void 0,error:void 0});const h=[],d=new Error("Transition effect");const u="xstate.stop",l="@xstate.terminate",p="xstate.timer";function f(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function _(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:f(t.event)??t.event}}function v(t){const e=t;return"string"==typeof e.id?{id:e.id}:"number"==typeof e.seq?{seq:e.seq}:e.event&&"object"==typeof e.event&&"string"==typeof e.event.type?{event:e.event}:void 0}function y(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}function m(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",f(t.event)??t.event])}(e)}`}function g(t){return{type:"xstate.init",input:t}}const b=new WeakMap;async function x(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,e);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const i=b.get(t)?.get(e);if(i)return i;if("active"!==t.getSnapshot().status)throw new Error(`Actor terminated before step "${e}" completed`);let o,c;const a=new Promise((t,e)=>{o=t,c=e});let h,d=b.get(t);d||(d=new Map,b.set(t,d)),d.set(e,a);const u=()=>{h?.unsubscribe(),d.delete(e),d.size||b.delete(t)};return a.then(u,u),h=t.subscribe({error:c,complete:()=>c(new Error(`Actor terminated before step "${e}" completed`))}),(async()=>{try{r({type:"xstate.logic.effect.start",key:e});const n=await s();"active"===t.getSnapshot().status&&(r({type:"xstate.logic.effect.resolve",key:e,output:n}),o(n))}catch(s){"active"===t.getSnapshot().status&&r({type:"xstate.logic.effect.reject",key:e,error:s}),c(s)}})().catch(c),a}function S(t,e,s){if(i(e)){const r=e,n=t?.system,i=n&&a(n,r);if(!i){const e=c(r);if(!n)throw e;return void n.deadLetter(t,void 0,s,"missingTarget",{targetId:o(r.$actor),error:e})}e=i}if(w(t,e,s))return;e._send(s,t)}function w(t,e,s){const r=function(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))return new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}(t,e,s);return!!r&&(e.system.deadLetter(t,e,s,"internalEvent",{error:r}),!0)}function E(t=this.actor.system){if(2!==this.actor._processingStatus)return t.startActor(this.actor)}function A(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function I(t=this.source.system){return t.scheduleTimer(this.source,_(this),this.delay??0)}function k(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,_(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function O(t){const e=[t];return{kind:"builtin",exec:E,type:"@xstate.start",source:t._parent,params:void 0,args:e,actor:t,id:t.id}}function R(t,e,s){const r=t.self,n={id:e.id,seq:e.seq,delay:s};if("@xstate.raise"===e.type)return{kind:"builtin",type:e.type,source:r,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,e.event,n],exec:I};const i="self"===e.target?r:e.target;return{kind:"builtin",type:e.type,source:r,target:i,event:e.event,id:e.id,...void 0!==e.seq&&{seq:e.seq},delay:s,params:void 0,args:[t,i,e.event,n],exec:k}}function T(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:A,type:l,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function j(t,e,[s,r]){const n="done"===s.status||"error"===s.status,i="done"===e?.status||"error"===e?.status,o=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===l);return!n||i||o?[s,r]:[s,[...r,T(t,s)]]}class M{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function $(t){setTimeout(()=>{throw t})}const q="function"==typeof Symbol&&Symbol.observable||"@@observable";let P;function L(){return void 0!==P}function z(){return P}function C(t,e){if(!t)return e();const s=P;P=t;try{return e()}finally{P=s}}const K=new WeakMap,D=new WeakMap,U=new Map;function V(t){const e=t._peekKeyedActors;return e?e.call(t)??U:t.keyedActors}function N(t){t._snapshotVersion++}function W(t){return t._snapshotVersion}function F(t,e,s){const r=L(),n=function(t,e){if(e){const t=new Map(e.children);return e.root?.sessionId&&t.set(e.root.sessionId,e.root),t}return new Map(t.children)}(t,s),i=new Map(s?.keyedActors??V(t)),o=new WeakMap,c=Object.assign(Object.create(t),{children:n,keyedActors:i,reverseKeyedActors:o,_snapshot:{...s?.snapshot??t._snapshot},_snapshotVersion:s?.sourceVersion??t._snapshotVersion,_register:(t,e)=>(n.set(t,e),N(c),t),_unregister:t=>{t.sessionId&&n.delete(t.sessionId);const e=o.get(t);void 0!==e&&i.get(e)===t&&i.delete(e),o.delete(t),N(c)},_set:(t,e)=>{const s=i.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${String(t)}' already exists.`);i.set(t,e),o.set(e,t),N(c)},get:t=>i.get(t),getAll:()=>Object.fromEntries(i),onEmitted:e=>t.onEmitted(e),_notifyEmitted:(e,s)=>t._notifyEmitted(e,s),_hasInspectionObservers:r?()=>t._hasInspectionObservers?.()??!1:()=>!1,_sendInspectionEvent:r?e=>t._sendInspectionEvent(e):()=>{}});for(const[t,e]of i)e&&o.set(e,t);for(const t of Object.values(e)){if(!t)continue;t.sessionId&&n.set(t.sessionId,t);const e=t.registryKey;e&&(i.set(e,t),o.set(t,e))}return c}function J(t){const e=K.get(t);if(e)return e;const s=D.get(t);if(!s)return;const r=s();return K.set(t,r),D.delete(t),r}function B(t,e,s=e.system,r){D.delete(t);const n=W(s),i=r?J(r):void 0,o=i?.actor===e?i:J(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===n)return void K.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=V(s);let d=h.size?new Map(h):U;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(d===U&&(d=new Map),d.set(t,e))}K.set(t,{actor:e,systemState:{...c,children:a,keyedActors:d,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:n}})}let H=!1;const X=Object.freeze([]),G={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[p]:!0};let Q=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Y=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function Z(t,e){try{t?.(e)}catch(t){$(t)}}function tt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function et(t,e){return new st(t,e)}class st{get address(){return this._address??=this._parent?`${this._parent.address}/${bt(this.id)}`:bt(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=Q.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...Y,...e}:Y,{clock:r,logger:n,parent:i,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var d;this.system=i?i.system:s._systemRef?.current??function(t,e){return new kt(t,e)}(this,{clock:r,logger:n,snapshot:s.snapshot,createActorRef:et}),i||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!i&&this.system.inspect(pt(h)),s.onRejectedEvent&&!i&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(d=this.system)._identity.executionId}:${d._identity.nextSessionId++}`,this.id=function(t,e,s){if(void 0!==e){const r=function(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}(e);return r?St(t,xt(s?.parent,r.prefix),r.index+1):s?.parent||St(t,xt(void 0,e),1),e}const r=gt(s?.src),n=xt(s?.parent,r),i=t._snapshot._nextActorIds[n]??0;return St(t,n,i+1),s?.parent||"x"===r||0!==i?`${r}:${i}`:r}(this.system,c,{parent:i,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=i,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const u=e?.snapshot;this._restored=void 0!==u;try{if(void 0!==u){if(!this.logic.restoreSnapshot&&null===u)throw new Error("Persisted snapshot must be an object.");this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(u,this._actorScope):u)}else if(e?._inert);else{const[t,e]=j(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){const e=void 0===u?void 0:this.logic._createRestoreErrorSnapshot?.(u,t);this._setSnapshot(e??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>function(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===Q.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=H;try{H=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==Q.Stopped&&this._recoverOrError(t)})}finally{H=e}};this._processingStatus!==Q.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,B(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=j(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),tt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??X)Z(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??X,actions:this._collectedActions??X,sent:this._collectedSent??X,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return tt(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const r=pt(t,e,s);if(this._processingStatus!==Q.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":Z(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),Z(r.error,t)):$(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,n)=>{const i=pt(s,r,n);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,i.next?.(r))},error:i.error,complete:i.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Q.Running)return this;if(this._processingStatus===Q.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(`Actor ${this.id} was stopped and cannot be restarted. Create a new actor with createActor().`)}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=Q.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,g(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,g(this.options.input)):(function(t,e,s){const r=K.get(t),n=W(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===n&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=n,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,_(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=j(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let i=this._snapshot;try{const[n,o]=r;n!==s||o.length||!("machine"in s)||t.type===u||e&&Object.hasOwn(G,t.type)||this._reportUnhandledEvent(t),i=n,this._setSnapshot(i),tt(o,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i,s)||this._inspectTransition(this._snapshot,t))}t.type===u&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){Z(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)Z(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===Q.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Q.NotStarted?(this._processingStatus=Q.Stopped,this.system._unregister(this),this):(this._send({type:u}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??X)Z(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||$(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch($)}catch(n){$(n)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const n=r.error;r.passive||(e||=!n,s||=!!n),Z(n,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,n,i;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,n=t,i=this.sessionId,{type:"xstate.error.actor",error:n,actorId:r,sessionId:i}))}_stopProcedure(){this._processingStatus===Q.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Q.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===Q.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new M(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[q](){return this}getSnapshot(){return this._snapshot}}const rt=Symbol();function nt(t,e,s=!0){const r=at(t);return r?(r.snapshot=e,r.materialized&&(r.materialized.self._snapshot=e)):t.self._snapshot=e,s&&e&&"object"==typeof e&&B(e,t.self),e}function it(t,e){nt(t,e,!1);const s=at(t);ct.set(e,t);const r=()=>(B(e,t.self,t.system),J(e));return s&&(s.materialized?s.identityProvider=r:s.identityProvider??=r),function(t,e){K.delete(t),D.set(t,e)}(e,r),e}const ot=Symbol(),ct=new WeakMap;function at(t){return t[ot]}function ht(t){return at(t).materialize()}const dt={[rt]:!0,get _parent(){const t=at(this);return t.parentKnown?t.parent:ht(this).self._parent},get self(){return ht(this).self},get defer(){return ht(this).defer},get id(){return ht(this).id},get logger(){return ht(this).logger},get sessionId(){return ht(this).sessionId},get stopChild(){return ht(this).stopChild},get system(){return ht(this).system},get emit(){return ht(this).emit},get actionExecutor(){return ht(this).actionExecutor}};function ut(t,e,s,r,n){const i=e?.(),o=n??i?.actor,c=o?.system,a=o&&c?F(c,s,n?void 0:i?.systemState):void 0,h=function(t,...[e]){if(e&&"parent"in e)throw new Error('The "parent" actor option was removed. Create child actors through invoke, spawn, or enq.spawn instead.');return new st(t,e)}(t,{_inert:!0,...o?{id:o.id,_sessionId:o.sessionId}:{},...a?{_systemRef:{current:a}}:{}});return o?._parent&&(h._parent=o._parent,h._address=void 0),r&&(h._snapshot=r),Object.create(h._actorScope,{defer:{value:()=>{}},stopChild:{value:t=>t._stop()},actionExecutor:{value:()=>{}}})}function lt(t,e,s,r){const n=r??(e&&"object"==typeof e?ct.get(e):void 0),i=n?at(n):void 0,o=e&&"object"==typeof e?function(t){return K.get(t)}(e):void 0,c=i?.identityProvider??(e&&"object"==typeof e?function(t){const e=K.get(t);return e?()=>e:D.get(t)}(e):void 0),a={snapshot:e,sourceRef:c,sourceChildren:(h=e,h&&"object"==typeof h&&"machine"in h&&"value"in h?e.children:{}),identityProvider:i?.identityProvider??c,parent:s?._parent??i?.parent??o?.actor._parent,parentKnown:!(!s&&!i?.parentKnown&&!o&&e)};var h;if(a.materialize=()=>a.materialized??=ut(t,a.sourceRef,a.sourceChildren,a.snapshot,s),!a.identityProvider&&!e){const e={},r=a.sourceRef,n=a.sourceChildren;let i,o;const c=()=>i??=ut(t,r,n,void 0,s);a.materialize=()=>{const t=c();return void 0!==a.snapshot&&(t.self._snapshot=a.snapshot),a.materialized=t},a.identityProvider=()=>{if(o)return o;const t=c();return B(e,t.self,t.system),o=J(e)}}const d=Object.create(dt);return d[ot]=a,d}function pt(t,e,s){const r="object"==typeof t,n=r?t:void 0;return{next:(r?t.next:t)?.bind(n),error:(r?t.error:e)?.bind(n),complete:(r?t.complete:s)?.bind(n),...r&&t.passive?{passive:!0}:{}}}let ft;Object.freeze({}),Object.freeze([]);let _t,vt=0;function yt(){return ft??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${ft}:${(vt++).toString(36)}`}function mt(t,e){if(!t)return e();const s=_t;_t=t;try{return e()}finally{_t=s}}function gt(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}function bt(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function xt(t,e){return`${t?t.address:""}|${e}`}function St(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},N(t))}const wt=["spawnActor","startActor","stopActor","terminateActor","emitEvent","scheduleTimer","cancelTimer","cancelAllTimers","deadLetter"],Et=Object.freeze({});function At(t,e){return m(t,e)}function It(t,e){return t.getSnapshot()?.timers?.find(t=>y(t,e))}class kt{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity=_t??{executionId:yt(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const r=z();r&&this.inspect(r),this._snapshot={_scheduledTimers:s?.scheduler??Et,_nextActorIds:{}}}_recordSent(t,e,s,r,n){if(!this._inspectionObservers?.size||!t)return;const i=t;(i._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:n})}schedule(t,e,s){const r=At(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const n=It(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}const i=this._clock.now?.()??Date.now(),o={source:t,delay:s,key:e,scheduledAt:i,dueAt:i+s};this._snapshot._scheduledTimers===Et&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=o,N(this);const c=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],N(this),this._deliver(t,t,{type:p,...e})},s);(this._timerMap??={})[r]=c}cancel(t,e){const s=At(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==Et&&delete this._snapshot._scheduledTimers[s],N(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){S(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),N(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&N(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&N(this)}inspect(t){const e=pt(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){$(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){$(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(i(e)){const r=a(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:o(e.$actor),error:c(e)})}if(w(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,n){const i=this._rejectionListeners;if(i?.size){const o={event:s,targetRef:e,targetId:e?.id??n?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:n?.issues,error:n?.error};for(const t of[...i])try{t(o)}catch(t){$(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,n)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):x(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const n=It(t,e);if(n){const e="self"===n.target?t:n.target;this._recordSent(t,e,n.event,s,n.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of h)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw d;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:n,key:i}=t[s];this.scheduleTimer(r,i,Math.max(0,n-(this._clock.now?.()??Date.now())))}}}function Ot(t){if(i(t))return{...t};const e=n(t)?t.sessionId:void 0;return void 0===e?{$actor:t.address}:{$actor:t.address,incarnation:e}}function Rt(t,e,s){if(!L())return;const r=t.self;r?.system._hasInspectionObservers?.()&&r._inspectTransition(e,s)}class Tt extends Error{constructor(){super("Durable execution was stopped"),this.name="DurableExecutionCancelledError"}}class jt extends Error{constructor(){super("run() can only start a fresh durable execution; resume checkpoints with restore() and the explicit transition loop"),this.name="DurableExecutionResumeError"}}t.DurableExecutionCancelledError=Tt,t.DurableExecutionResumeError=jt,t.createDurable=function(t,e,i){let o=e.transitionIndex??0;const c=o;let a=!1;const h=()=>e.now?.()??Date.now(),d=new WeakSet;let u=0===o?void 0:o-1;const l=new WeakMap;if(!Number.isSafeInteger(o)||o<0)throw new RangeError("transitionIndex must be a non-negative safe integer");const p=(t,e=!1)=>{const s=e?o:o++;return u=e?u??s:s,t.map((t,r)=>{const n={id:`${e?"restore:":""}${s}:${r}`,transitionIndex:s,effectIndex:r,effect:t};let i;return Object.defineProperty(n,"descriptor",{enumerable:!0,get:()=>i??=function(t){if("action"===t.kind)return{kind:"action",type:t.type,params:t.params};if("emit"===t.kind)return{kind:"emit",type:t.type,source:Ot(t.source),event:t.event};switch(t.type){case"@xstate.spawn":return{kind:"builtin",type:"@xstate.spawn",source:t.source&&Ot(t.source),actor:Ot(t.actor),id:t.id,src:gt(t.src),input:t.input};case"@xstate.start":return{kind:"builtin",type:"@xstate.start",source:t.source&&Ot(t.source),actor:Ot(t.actor),id:t.id};case"@xstate.raise":return{kind:"builtin",type:"@xstate.raise",source:Ot(t.source),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.sendTo":return{kind:"builtin",type:"@xstate.sendTo",source:Ot(t.source),target:t.target&&Ot(t.target),event:t.event,id:t.id,...void 0!==t.seq&&{seq:t.seq},delay:t.delay};case"@xstate.cancel":return{kind:"builtin",type:"@xstate.cancel",source:Ot(t.source),...v(t)};case"@xstate.stop":return{kind:"builtin",type:"@xstate.stop",source:Ot(t.source),actor:Ot(t.actor),id:t.id};case"@xstate.terminate":return{kind:"builtin",type:"@xstate.terminate",source:Ot(t.source),actor:Ot(t.actor),id:t.id,status:t.status,output:t.output,error:t.error};case"@xstate.deadLetter":return{kind:"builtin",type:"@xstate.deadLetter",source:t.source&&Ot(t.source),target:t.target&&Ot(t.target),event:t.event,reason:t.reason,issues:t.detail?.issues,error:t.detail?.error}}}(t)}),n})},f=bt(function(t){const e=gt(t);return"x"===e?"x:0":e}(t)),_=t.id??f,m=t.version,b=e.executionId?{executionId:e.executionId,nextSessionId:0}:void 0,x={};for(const t of[...wt,"sendEvent","runStep","runLogic"]){const s=e[t];s&&(x[t]=s.bind(e))}const w=Object.keys(x).length>0||!!e.enqueueRootEvent;let E;const A=[];let I=Promise.resolve();const k=t=>E?((t,e)=>{const s=I.then(e).then(()=>{});return I=s.catch(()=>{}),((t,e)=>(t.pending.add(e),e.catch(e=>{t.failures.push(e)}).then(()=>t.pending.delete(e)),e))(t,s)})(E,t):t(),T=async t=>{for(;t.pending.size;)await Promise.allSettled([...t.pending])};function M(t,n,o=!1,c){const a={};for(const e of wt){const n=t[e]??(o?(...t)=>("spawnActor"===e?t[1]:t[0]).system[e](...t):void 0);n&&(a[e]=(...t)=>k(()=>{if("scheduleTimer"===e&&c&&(t[2]=Math.min(c.delay,Math.max(0,c.deadline-h()))),"scheduleTimer"===e){const e=t[0],i=t[1],o=e.getSnapshot()?.timers?.find(t=>y(t,i));if(o){const e=s(o);void 0===e||c||(t[2]=Math.min(o.delay,Math.max(0,e+o.delay-h())));const i=n(...t);return i?Promise.resolve(i).then(()=>{r(o,e??h())}):void r(o,e??h())}}return n(...t)}))}return t.runStep&&(a.runStep=t.runStep),t.runLogic&&(a.runLogic=t.runLogic),a.sendEvent=(s,r,o)=>{const c=!1!==i?.captureRootEvents?E:void 0;if(!c&&r.address===f&&!t.sendEvent&&e.enqueueRootEvent)return k(()=>e.enqueueRootEvent(s,o));if(!c&&r.address===f&&!t.sendEvent)throw new Error(`A root-addressed event ("${o.type}") was produced outside batch capture (for example, while the durable loop was parked), but the adapter has no enqueueRootEvent or sendEvent to receive it. Implement enqueueRootEvent to place root-addressed events in the host's mailbox.`);if(c&&r.address===f)return void c.rootEvents.push({event:o,source:s});const a=t.sendEvent;if(a)return k(()=>a(s,r,o));if(n)return k(()=>S(s,r,o));throw new TypeError(`The durable runtime does not support the sendEvent operation (target '${r.address}')`)},a}const $=w?M(x,!0):void 0;function q(t,e){if(t.address===e)return t;if(!e.startsWith(`${t.address}/`))return;const s=t.getSnapshot().children;for(const t of Object.values(s??{})){const s=t&&q(t,e);if(s)return s}}const P=i?.inspect;function L(t,e=!1){if("error"===t.status){const e=J(t)?.actor;e&&!d.has(e)&&(e.subscribe({error(){}}),d.add(e))}if($||P){const s=J(t)?.actor,r=new Set,n=t=>{var s;if(r.has(t.system)||(r.add(t.system),$&&(t.system.runtime=$),s=t.system,P&&!s._hasInspectionObservers?.()&&s.inspect(P)),e){const e=t.getSnapshot().children;for(const t of Object.values(e??{}))t&&n(t)}};if(s&&n(s),!e||!s){const e=t.children;for(const t of Object.values(e??{}))t&&n(t)}}return t}const z={rootAddress:f,machineId:_,machineVersion:m,get nextTransitionIndex(){return o},restore(e){if(a||o!==c||E)throw new Error("restore() requires a fresh durable execution");const{snapshot:s,scope:r}=C(P,()=>mt(b,()=>{const s=lt(t),r=t.restoreSnapshot?t.restoreSnapshot(e,s):e;return nt(s,r,!1),{snapshot:L(it(s,r),!0),scope:s}})),i=[];if("active"===s.status){const{children:t,timers:e}=s;for(const e of Object.values(t??{}))e&&!n(e)&&"active"===e.getSnapshot().status&&i.push(O(e));for(const t of e??[]){const e=R(r,t,t.delay);void 0!==t.scheduledAt&&l.set(e,{deadline:t.scheduledAt+t.delay,delay:t.delay}),i.push(e)}}return a=!0,[s,p(i,!0)]},initialTransition(...e){if(a)throw new Error("initialTransition() cannot initialize a restored execution");const[s,r]=C(P,()=>mt(b,()=>function(t,...[e]){const s=lt(t),[r,n]=j(s,void 0,t.initialTransition(e,s));nt(s,r,!1);const i=it(s,r);return Rt(s,i,g(e)),[i,n]}(t,...e)));return[L(s),p(r)]},transition(e,s){const[r,n]=C(P,()=>mt(b,()=>function(t,e,s){const r=lt(t,e);nt(r,e,!1);const[n,i]=j(r,e,t.transition(e,s,r));nt(r,n,!1);const o=n===e?n:it(r,n);return Rt(r,o,s),[o,i]}(t,e,s)));return[L(r),p(n)]},getActorRef(t,e){const s=J(t)?.actor;return s&&void 0!==e?q(s,e):s},async executeEffects(t){if(E)throw new Error("executeEffects calls must not overlap: await the previous call before starting the next batch.");const s={rootEvents:[],failures:[],pending:new Set};E=s;const r=w?void 0:{};try{for(const s of t){const{effect:t}=s,n={id:s.id,transitionIndex:s.transitionIndex,effectIndex:s.effectIndex},i=e.runtime?.(n,t),o=l.get(t),c=i||o?M({...x,...i},w,!!i||w,o):r;"action"===t.kind?await e.executeAction(t,n,c??$??{}):await t.exec(c)}await(async t=>{if(await T(t),t.failures.length)throw t.failures[0]})(s),A.push(...s.rootEvents)}catch(t){throw await T(s),t}finally{E=void 0}},async waitForEvent(){if(void 0===u)throw new Error("Cannot wait for an event before the first transition or restore");const t=A.shift();return t?t.event:e.waitForEvent({id:a&&0===o?"event:restore:0":`event:${u}`,transitionIndex:u})},async run(...t){if(a||0!==c||o!==c)throw new jt;let[e,s]=z.initialTransition(...t);for(await z.executeEffects(s);"active"===e.status;){const t=await z.waitForEvent();[e,s]=z.transition(e,t),await z.executeEffects(s)}const r=e;if("done"===r.status)return r.output;if("error"===r.status)throw r.error;throw new Tt}};return z},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-durable.umd.min.js.map
|