xstate 6.0.0-beta.1 → 6.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/dist/{createActor-551369be.development.esm.js → createActor-0250284a.development.esm.js} +244 -41
  2. package/dist/{createActor-cbe3abac.esm.js → createActor-20a97166.esm.js} +243 -40
  3. package/dist/{createActor-a49ae0ce.development.cjs.js → createActor-c029d29f.development.cjs.js} +245 -40
  4. package/dist/{createActor-25900f76.cjs.js → createActor-c91c9ffe.cjs.js} +244 -39
  5. package/dist/declarations/src/createActor.d.ts +3 -1
  6. package/dist/declarations/src/createMachine.d.ts +6 -3
  7. package/dist/declarations/src/durable/index.d.ts +43 -8
  8. package/dist/declarations/src/effectDescriptor.d.ts +2 -2
  9. package/dist/declarations/src/machineVersion.types.d.ts +2 -2
  10. package/dist/declarations/src/setup.d.ts +2 -2
  11. package/dist/declarations/src/systemTransition.d.ts +1 -1
  12. package/dist/declarations/src/types.d.ts +4 -2
  13. package/dist/declarations/src/types.v6.d.ts +37 -2
  14. package/dist/{effectDescriptor-f73da4ec.development.cjs.js → effectDescriptor-3fff5c51.development.cjs.js} +5 -5
  15. package/dist/{effectDescriptor-2fa27c54.cjs.js → effectDescriptor-47f73e7e.cjs.js} +5 -5
  16. package/dist/{effectDescriptor-321a8ce9.development.esm.js → effectDescriptor-5ac7dccb.development.esm.js} +5 -5
  17. package/dist/{effectDescriptor-d8b0f749.esm.js → effectDescriptor-e93df910.esm.js} +5 -5
  18. package/dist/{machineSchemas-88d01821.cjs.js → legacySnapshot-8d595687.cjs.js} +117 -1
  19. package/dist/{machineSchemas-45c21bc2.esm.js → legacySnapshot-9e06feb4.esm.js} +116 -2
  20. package/dist/{machineSchemas-b5736804.development.esm.js → legacySnapshot-ae6594a7.development.esm.js} +117 -3
  21. package/dist/{machineSchemas-6d96bef4.development.cjs.js → legacySnapshot-ebf0b2b8.development.cjs.js} +118 -2
  22. package/dist/xstate-actors.cjs.js +1 -1
  23. package/dist/xstate-actors.development.cjs.js +1 -1
  24. package/dist/xstate-actors.development.esm.js +2 -2
  25. package/dist/xstate-actors.esm.js +2 -2
  26. package/dist/xstate-actors.umd.min.js +1 -1
  27. package/dist/xstate-actors.umd.min.js.map +1 -1
  28. package/dist/xstate-durable.cjs.js +120 -10
  29. package/dist/xstate-durable.development.cjs.js +120 -10
  30. package/dist/xstate-durable.development.esm.js +120 -10
  31. package/dist/xstate-durable.esm.js +120 -10
  32. package/dist/xstate-durable.umd.min.js +1 -1
  33. package/dist/xstate-durable.umd.min.js.map +1 -1
  34. package/dist/xstate-fsm.cjs.js +4 -4
  35. package/dist/xstate-fsm.development.cjs.js +4 -4
  36. package/dist/xstate-fsm.development.esm.js +4 -4
  37. package/dist/xstate-fsm.esm.js +4 -4
  38. package/dist/xstate-fsm.umd.min.js +1 -1
  39. package/dist/xstate-fsm.umd.min.js.map +1 -1
  40. package/dist/xstate-graph.cjs.js +1 -1
  41. package/dist/xstate-graph.development.cjs.js +1 -1
  42. package/dist/xstate-graph.development.esm.js +2 -2
  43. package/dist/xstate-graph.esm.js +2 -2
  44. package/dist/xstate-graph.umd.min.js +1 -1
  45. package/dist/xstate-graph.umd.min.js.map +1 -1
  46. package/dist/xstate-persist.cjs.js +23 -12
  47. package/dist/xstate-persist.development.cjs.js +23 -12
  48. package/dist/xstate-persist.development.esm.js +17 -6
  49. package/dist/xstate-persist.esm.js +17 -6
  50. package/dist/xstate-persist.umd.min.js +1 -1
  51. package/dist/xstate-persist.umd.min.js.map +1 -1
  52. package/dist/xstate-validation.cjs.js +1 -1
  53. package/dist/xstate-validation.development.cjs.js +1 -1
  54. package/dist/xstate-validation.development.esm.js +1 -1
  55. package/dist/xstate-validation.esm.js +1 -1
  56. package/dist/xstate.cjs.js +63 -51
  57. package/dist/xstate.development.cjs.js +63 -51
  58. package/dist/xstate.development.esm.js +53 -41
  59. package/dist/xstate.esm.js +53 -41
  60. package/dist/xstate.umd.min.js +1 -1
  61. package/dist/xstate.umd.min.js.map +1 -1
  62. package/docs/api-stability.json +267 -249
  63. package/docs/backend-workflows.md +3 -3
  64. package/docs/durable-execution.md +72 -48
  65. package/docs/errors.md +2 -2
  66. package/docs/examples.md +34 -34
  67. package/docs/fsm.md +2 -1
  68. package/docs/guards.md +1 -1
  69. package/docs/index.md +1 -1
  70. package/docs/invoke.md +34 -2
  71. package/docs/persistence.md +16 -10
  72. package/docs/serialization.md +1 -1
  73. package/docs/setup-and-provide.md +3 -3
  74. package/docs/spawn.md +1 -1
  75. package/docs/system-transitions.md +6 -6
  76. package/docs/tutorial.md +5 -5
  77. package/docs/typescript.md +9 -0
  78. package/docs/xstate-v5-to-v6.md +17 -17
  79. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { _ as resolveRegisteredActorSource, $ as allocateChildId, a0 as assertChildIdFree, a1 as reserveChildId, a2 as hasUnescapedDot, a3 as STATE_DELIMITER, a4 as mapValues, t as toArray, a5 as createInvokeId, a6 as getDelayedTransitions, a7 as getCandidates, a8 as evaluateCandidate, a9 as formatTransition, aa as NULL_EVENT, ab as toTransitionConfigArray, ac as matchesActorSession, ad as describeMachine, g as getAllStateNodes, b as getStateNodes, r as resolveInvokedActorLogic, o as isSerializedActorRef, a as assertUnreservedSourceName, ae as formatRouteTransitions, af as resolveStateValue, e as createMachineSnapshot, ag as isInFinalState, ah as createInertActorScope, ai as setInertActorScopeSnapshot, Q as createDeadLetterEffect, aj as beginSpawnAllocation, ak as attachSnapshotActorRef, al as macrostep, am as isInertActorScope, an as setSnapshotActorRef, ao as cloneMachineSnapshot, ap as transitionNode, aq as XSTATE_TIMER, m as matchesEventDescriptor, ar as getTransitionResult, as as hasEffect, at as createErrorPlatformEvent, au as withActorSelf, av as resolveActionsWithContext, aw as freezeContext, ax as takeSpawnAllocationCounters, ay as mergeActorIdCounters, O as createInitEvent, az as createSpawnEffect, aA as initialMicrostep, aB as createStartEffect, aC as isStateId, aD as getPersistedSnapshot, aE as detachedScopes, aF as toStatePath, h as createActor } from './createActor-551369be.development.esm.js';
1
+ import { _ as resolveRegisteredActorSource, $ as allocateChildId, a0 as assertChildIdFree, a1 as reserveChildId, a2 as hasUnescapedDot, a3 as STATE_DELIMITER, a4 as mapValues, t as toArray, a5 as createInvokeId, a6 as getDelayedTransitions, a7 as getCandidates, a8 as evaluateCandidate, a9 as formatTransition, aa as NULL_EVENT, ab as toTransitionConfigArray, ac as matchesActorSession, ad as describeMachine, g as getAllStateNodes, b as getStateNodes, r as resolveInvokedActorLogic, o as isSerializedActorRef, a as assertUnreservedSourceName, ae as formatRouteTransitions, af as resolveStateValue, e as createMachineSnapshot, ag as isInFinalState, ah as createInertActorScope, ai as setInertActorScopeSnapshot, Q as createDeadLetterEffect, aj as beginSpawnAllocation, ak as attachSnapshotActorRef, al as macrostep, am as isInertActorScope, an as setSnapshotActorRef, ao as cloneMachineSnapshot, ap as transitionNode, aq as XSTATE_TIMER, m as matchesEventDescriptor, ar as getTransitionResult, as as hasEffect, at as createErrorPlatformEvent, au as withActorSelf, av as resolveActionsWithContext, aw as freezeContext, ax as takeSpawnAllocationCounters, ay as mergeActorIdCounters, O as createInitEvent, az as createSpawnEffect, aA as initialMicrostep, aB as createStartEffect, aC as isStateId, aD as getPersistedSnapshot, aE as detachedScopes, aF as toStatePath, h as createActor } from './createActor-0250284a.development.esm.js';
2
2
  import { a as assertValid } from './validation-e69470ad.development.esm.js';
3
3
 
4
4
  var isDevelopment = true;
@@ -129,7 +129,7 @@ class StateNode {
129
129
  this.machine = options._machine;
130
130
  if (this.parent && hasUnescapedDot(this.key)) {
131
131
  throw new Error(// The suggestion is written as a JS string literal.
132
- `State key "${this.key}" contains "." — nest the states or escape it as "${this.key.replaceAll(/(?<!\\)\./g, '\\\\.')}".` );
132
+ `State key "${this.key}" contains ".". Nest the states or escape it as "${this.key.replaceAll(/(?<!\\)\./g, '\\\\.')}".` );
133
133
  }
134
134
  this.path = this.parent ? this.parent.path.concat(this.key) : [];
135
135
  const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
@@ -672,6 +672,15 @@ class StateMachine {
672
672
  /** @internal */
673
673
  this.idMap = new Map();
674
674
  this.root = void 0;
675
+ /**
676
+ * Returns the machine itself, never a Proxy wrapped around it (a function
677
+ * member is not wrapped by reactive proxies, so it still closes over the raw
678
+ * instance). Persistence resolves state nodes through it, matching the
679
+ * bound `transition` / `getInitialSnapshot`.
680
+ *
681
+ * @internal
682
+ */
683
+ this._raw = () => this;
675
684
  /**
676
685
  * The machine's `id`, or the empty string when the config declares none.
677
686
  * The root state node has this id; a machine without one has no `#id` root.
@@ -1368,4 +1377,109 @@ function eventSchema(machine) {
1368
1377
  }));
1369
1378
  }
1370
1379
 
1371
- export { InvalidSnapshotError as I, StateMachine as S, StateNode as a, eventSchema as e, historicalEventSchema as h, snapshotSchema as s, validatePersistedSnapshot as v };
1380
+ // TODO(v7): remove this module and its callers. It reads snapshots written by
1381
+ // 6.0.0-beta.1, which used `$`- and `_`-prefixed field names that stores such
1382
+ // as Convex reject. Snapshots are written with the new names only.
1383
+
1384
+ // Legacy marker key -> [new key, other keys the marker object may have].
1385
+ const markers = {
1386
+ $actor: ['@actor', ['incarnation']],
1387
+ $error: ['@error', ['message']],
1388
+ $stateNode: ['@stateNode', []],
1389
+ $systemMapper: ['@systemMapper', []]
1390
+ };
1391
+ const fields = {
1392
+ _stateInputs: 'stateInputs',
1393
+ _nextTimerId: 'nextTimerId',
1394
+ _nextActorIds: 'nextActorIds'
1395
+ };
1396
+
1397
+ // Persisted snapshots are JSON; live objects (actors, state nodes, errors)
1398
+ // are left alone.
1399
+ function isPlain(value) {
1400
+ if (!value || typeof value !== 'object') return false;
1401
+ const proto = Object.getPrototypeOf(value);
1402
+ return proto === Object.prototype || proto === null || Array.isArray(value);
1403
+ }
1404
+ function renameMarkers(value, allowed) {
1405
+ if (!isPlain(value)) return value;
1406
+ if (Array.isArray(value)) {
1407
+ const items = value.map(item => renameMarkers(item, allowed));
1408
+ return items.some((item, i) => item !== value[i]) ? items : value;
1409
+ }
1410
+ const keys = Object.keys(value);
1411
+ const legacy = keys.find(key => allowed.includes(key));
1412
+ if (legacy && typeof value[legacy] === 'string' && keys.every(key => key === legacy || markers[legacy][1].includes(key))) {
1413
+ const {
1414
+ [legacy]: name,
1415
+ ...rest
1416
+ } = value;
1417
+ return {
1418
+ [markers[legacy][0]]: name,
1419
+ ...rest
1420
+ };
1421
+ }
1422
+ let copy;
1423
+ for (const key of keys) {
1424
+ const item = renameMarkers(value[key], allowed);
1425
+ if (item !== value[key]) (copy ??= {
1426
+ ...value
1427
+ })[key] = item;
1428
+ }
1429
+ return copy ?? value;
1430
+ }
1431
+
1432
+ // beta.1 always wrote `_nextTimerId` on machine snapshots. Current snapshots
1433
+ // write `nextTimerId`, so marker-shaped data in them is left alone.
1434
+ function isLegacyEnvelope(envelope) {
1435
+ return isPlain(envelope) && '_nextTimerId' in envelope && !('nextTimerId' in envelope);
1436
+ }
1437
+ function renameFields(envelope) {
1438
+ // A live machine snapshot keeps its `_`-prefixed in-memory fields.
1439
+ if (!isPlain(envelope) || typeof envelope.matches === 'function') return envelope;
1440
+ let copy;
1441
+ for (const [legacy, name] of Object.entries(fields)) {
1442
+ if (legacy in envelope && !(name in envelope)) {
1443
+ const {
1444
+ [legacy]: value,
1445
+ ...rest
1446
+ } = copy ?? envelope;
1447
+ copy = {
1448
+ ...rest,
1449
+ [name]: value
1450
+ };
1451
+ }
1452
+ }
1453
+ return copy ?? envelope;
1454
+ }
1455
+
1456
+ /** Upgrades a persisted machine snapshot written by 6.0.0-beta.1. */
1457
+ function upgradeLegacyPersistedSnapshot(snapshot) {
1458
+ if (snapshot?.machine && typeof snapshot.matches === 'function') return snapshot;
1459
+ if (!isLegacyEnvelope(snapshot)) return snapshot;
1460
+ return renameMarkers(renameFields(snapshot), ['$actor']);
1461
+ }
1462
+
1463
+ /** Upgrades a `systemTransition` snapshot written by 6.0.0-beta.1. */
1464
+ function upgradeLegacySystemSnapshot(snapshot) {
1465
+ const actors = Object.values(snapshot?.actors ?? {});
1466
+ if (!actors.some(actor => isLegacyEnvelope(actor?.snapshot))) return snapshot;
1467
+ const upgraded = renameMarkers(snapshot, Object.keys(markers));
1468
+ if (!upgraded?.actors) return upgraded;
1469
+ let renamed;
1470
+ for (const [address, actor] of Object.entries(upgraded.actors)) {
1471
+ const data = renameFields(actor?.snapshot);
1472
+ if (data !== actor?.snapshot) (renamed ??= {
1473
+ ...upgraded.actors
1474
+ })[address] = {
1475
+ ...actor,
1476
+ snapshot: data
1477
+ };
1478
+ }
1479
+ return renamed ? {
1480
+ ...upgraded,
1481
+ actors: renamed
1482
+ } : upgraded;
1483
+ }
1484
+
1485
+ export { InvalidSnapshotError as I, StateMachine as S, StateNode as a, upgradeLegacyPersistedSnapshot as b, eventSchema as e, historicalEventSchema as h, snapshotSchema as s, upgradeLegacySystemSnapshot as u, validatePersistedSnapshot as v };
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-a49ae0ce.development.cjs.js');
3
+ var createActor = require('./createActor-c029d29f.development.cjs.js');
4
4
  var validation = require('./validation-f2714a35.development.cjs.js');
5
5
 
6
6
  var isDevelopment = true;
@@ -131,7 +131,7 @@ class StateNode {
131
131
  this.machine = options._machine;
132
132
  if (this.parent && createActor.hasUnescapedDot(this.key)) {
133
133
  throw new Error(// The suggestion is written as a JS string literal.
134
- `State key "${this.key}" contains "." — nest the states or escape it as "${this.key.replaceAll(/(?<!\\)\./g, '\\\\.')}".` );
134
+ `State key "${this.key}" contains ".". Nest the states or escape it as "${this.key.replaceAll(/(?<!\\)\./g, '\\\\.')}".` );
135
135
  }
136
136
  this.path = this.parent ? this.parent.path.concat(this.key) : [];
137
137
  const firstStateKey = this.config.states ? Object.keys(this.config.states)[0] : undefined;
@@ -674,6 +674,15 @@ class StateMachine {
674
674
  /** @internal */
675
675
  this.idMap = new Map();
676
676
  this.root = void 0;
677
+ /**
678
+ * Returns the machine itself, never a Proxy wrapped around it (a function
679
+ * member is not wrapped by reactive proxies, so it still closes over the raw
680
+ * instance). Persistence resolves state nodes through it, matching the
681
+ * bound `transition` / `getInitialSnapshot`.
682
+ *
683
+ * @internal
684
+ */
685
+ this._raw = () => this;
677
686
  /**
678
687
  * The machine's `id`, or the empty string when the config declares none.
679
688
  * The root state node has this id; a machine without one has no `#id` root.
@@ -1370,10 +1379,117 @@ function eventSchema(machine) {
1370
1379
  }));
1371
1380
  }
1372
1381
 
1382
+ // TODO(v7): remove this module and its callers. It reads snapshots written by
1383
+ // 6.0.0-beta.1, which used `$`- and `_`-prefixed field names that stores such
1384
+ // as Convex reject. Snapshots are written with the new names only.
1385
+
1386
+ // Legacy marker key -> [new key, other keys the marker object may have].
1387
+ const markers = {
1388
+ $actor: ['@actor', ['incarnation']],
1389
+ $error: ['@error', ['message']],
1390
+ $stateNode: ['@stateNode', []],
1391
+ $systemMapper: ['@systemMapper', []]
1392
+ };
1393
+ const fields = {
1394
+ _stateInputs: 'stateInputs',
1395
+ _nextTimerId: 'nextTimerId',
1396
+ _nextActorIds: 'nextActorIds'
1397
+ };
1398
+
1399
+ // Persisted snapshots are JSON; live objects (actors, state nodes, errors)
1400
+ // are left alone.
1401
+ function isPlain(value) {
1402
+ if (!value || typeof value !== 'object') return false;
1403
+ const proto = Object.getPrototypeOf(value);
1404
+ return proto === Object.prototype || proto === null || Array.isArray(value);
1405
+ }
1406
+ function renameMarkers(value, allowed) {
1407
+ if (!isPlain(value)) return value;
1408
+ if (Array.isArray(value)) {
1409
+ const items = value.map(item => renameMarkers(item, allowed));
1410
+ return items.some((item, i) => item !== value[i]) ? items : value;
1411
+ }
1412
+ const keys = Object.keys(value);
1413
+ const legacy = keys.find(key => allowed.includes(key));
1414
+ if (legacy && typeof value[legacy] === 'string' && keys.every(key => key === legacy || markers[legacy][1].includes(key))) {
1415
+ const {
1416
+ [legacy]: name,
1417
+ ...rest
1418
+ } = value;
1419
+ return {
1420
+ [markers[legacy][0]]: name,
1421
+ ...rest
1422
+ };
1423
+ }
1424
+ let copy;
1425
+ for (const key of keys) {
1426
+ const item = renameMarkers(value[key], allowed);
1427
+ if (item !== value[key]) (copy ??= {
1428
+ ...value
1429
+ })[key] = item;
1430
+ }
1431
+ return copy ?? value;
1432
+ }
1433
+
1434
+ // beta.1 always wrote `_nextTimerId` on machine snapshots. Current snapshots
1435
+ // write `nextTimerId`, so marker-shaped data in them is left alone.
1436
+ function isLegacyEnvelope(envelope) {
1437
+ return isPlain(envelope) && '_nextTimerId' in envelope && !('nextTimerId' in envelope);
1438
+ }
1439
+ function renameFields(envelope) {
1440
+ // A live machine snapshot keeps its `_`-prefixed in-memory fields.
1441
+ if (!isPlain(envelope) || typeof envelope.matches === 'function') return envelope;
1442
+ let copy;
1443
+ for (const [legacy, name] of Object.entries(fields)) {
1444
+ if (legacy in envelope && !(name in envelope)) {
1445
+ const {
1446
+ [legacy]: value,
1447
+ ...rest
1448
+ } = copy ?? envelope;
1449
+ copy = {
1450
+ ...rest,
1451
+ [name]: value
1452
+ };
1453
+ }
1454
+ }
1455
+ return copy ?? envelope;
1456
+ }
1457
+
1458
+ /** Upgrades a persisted machine snapshot written by 6.0.0-beta.1. */
1459
+ function upgradeLegacyPersistedSnapshot(snapshot) {
1460
+ if (snapshot?.machine && typeof snapshot.matches === 'function') return snapshot;
1461
+ if (!isLegacyEnvelope(snapshot)) return snapshot;
1462
+ return renameMarkers(renameFields(snapshot), ['$actor']);
1463
+ }
1464
+
1465
+ /** Upgrades a `systemTransition` snapshot written by 6.0.0-beta.1. */
1466
+ function upgradeLegacySystemSnapshot(snapshot) {
1467
+ const actors = Object.values(snapshot?.actors ?? {});
1468
+ if (!actors.some(actor => isLegacyEnvelope(actor?.snapshot))) return snapshot;
1469
+ const upgraded = renameMarkers(snapshot, Object.keys(markers));
1470
+ if (!upgraded?.actors) return upgraded;
1471
+ let renamed;
1472
+ for (const [address, actor] of Object.entries(upgraded.actors)) {
1473
+ const data = renameFields(actor?.snapshot);
1474
+ if (data !== actor?.snapshot) (renamed ??= {
1475
+ ...upgraded.actors
1476
+ })[address] = {
1477
+ ...actor,
1478
+ snapshot: data
1479
+ };
1480
+ }
1481
+ return renamed ? {
1482
+ ...upgraded,
1483
+ actors: renamed
1484
+ } : upgraded;
1485
+ }
1486
+
1373
1487
  exports.InvalidSnapshotError = InvalidSnapshotError;
1374
1488
  exports.StateMachine = StateMachine;
1375
1489
  exports.StateNode = StateNode;
1376
1490
  exports.eventSchema = eventSchema;
1377
1491
  exports.historicalEventSchema = historicalEventSchema;
1378
1492
  exports.snapshotSchema = snapshotSchema;
1493
+ exports.upgradeLegacyPersistedSnapshot = upgradeLegacyPersistedSnapshot;
1494
+ exports.upgradeLegacySystemSnapshot = upgradeLegacySystemSnapshot;
1379
1495
  exports.validatePersistedSnapshot = validatePersistedSnapshot;
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-25900f76.cjs.js');
5
+ var createActor = require('./createActor-c91c9ffe.cjs.js');
6
6
  var validation = require('./validation-4561b43c.cjs.js');
7
7
 
8
8
  /** @public */
@@ -2,7 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-a49ae0ce.development.cjs.js');
5
+ var createActor = require('./createActor-c029d29f.development.cjs.js');
6
6
  var validation = require('./validation-f2714a35.development.cjs.js');
7
7
 
8
8
  /** @public */
@@ -1,5 +1,5 @@
1
- import { O as createInitEvent, Q as createDeadLetterEffect, u as XSTATE_STOP, R as createCustomEffect, S as XSTATE_LOGIC_EFFECT_START, T as XSTATE_LOGIC_EFFECT_RESOLVE, U as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, V as createEmitEffect, W as createSendToEffect, Y as XSTATE_INIT, Z as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, L as runStep, h as createActor } from './createActor-551369be.development.esm.js';
2
- export { C as createListenerLogic, D as createSubscriptionLogic } from './createActor-551369be.development.esm.js';
1
+ import { O as createInitEvent, Q as createDeadLetterEffect, u as XSTATE_STOP, R as createCustomEffect, S as XSTATE_LOGIC_EFFECT_START, T as XSTATE_LOGIC_EFFECT_RESOLVE, U as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, V as createEmitEffect, W as createSendToEffect, Y as XSTATE_INIT, Z as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, L as runStep, h as createActor } from './createActor-0250284a.development.esm.js';
2
+ export { C as createListenerLogic, D as createSubscriptionLogic } from './createActor-0250284a.development.esm.js';
3
3
  import { a as assertValid } from './validation-e69470ad.development.esm.js';
4
4
 
5
5
  /** @public */
@@ -1,5 +1,5 @@
1
- import { Q as createInitEvent, R as createDeadLetterEffect, u as XSTATE_STOP, S as createCustomEffect, T as XSTATE_LOGIC_EFFECT_START, U as XSTATE_LOGIC_EFFECT_RESOLVE, V as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, W as createEmitEffect, Y as createSendToEffect, Z as XSTATE_INIT, _ as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, M as runStep, h as createActor } from './createActor-cbe3abac.esm.js';
2
- export { D as createListenerLogic, E as createSubscriptionLogic } from './createActor-cbe3abac.esm.js';
1
+ import { Q as createInitEvent, R as createDeadLetterEffect, u as XSTATE_STOP, S as createCustomEffect, T as XSTATE_LOGIC_EFFECT_START, U as XSTATE_LOGIC_EFFECT_RESOLVE, V as XSTATE_LOGIC_EFFECT_REJECT, l as finalizeTransitionResult, W as createEmitEffect, Y as createSendToEffect, Z as XSTATE_INIT, _ as publishEmittedEvent, p as parseDelayToMilliseconds, s as systemLogicMetadata, M as runStep, h as createActor } from './createActor-20a97166.esm.js';
2
+ export { D as createListenerLogic, E as createSubscriptionLogic } from './createActor-20a97166.esm.js';
3
3
  import { a as assertValid } from './validation-05f1d517.esm.js';
4
4
 
5
5
  /** @public */
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const r="xstate.init",i="xstate.stop",n="@xstate.terminate",o="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",h="xstate.logic.effect.start";function u(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function d(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function p(t){return new Error(e(50,...void 0===t.incarnation?[t.$actor]:[t.$actor,t.incarnation]))}function l(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function f(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const _=new WeakMap;async function v(t,s,r,i=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const o=_.get(t)?.get(s);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let u,d;const p=new Promise((t,e)=>{u=t,d=e});let l,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,p);const v=()=>{l?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return p.then(v,v),l=t.subscribe({error:d,complete:()=>d(new Error(e(72,s)))}),(async()=>{try{i({type:h,key:s});const e=await r();"active"===t.getSnapshot().status&&(i({type:c,key:s,output:e}),u(e))}catch(e){"active"===t.getSnapshot().status&&i({type:a,key:s,error:e}),d(e)}})().catch(d),p}function y(t,s,r){const i=function(t,s,r){const i=s;if(t!==s&&i.logic?.isInternalEventType?.(r.type))return new Error(e(73,r.type,s.id))}(t,s,r);return!!i&&(s.system.deadLetter(t,s,r,"internalEvent",{error:i}),!0)}class m{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function g(t){return{type:r,input:t}}function b(t){setTimeout(()=>{throw t})}const S="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],A=new Error("Transition effect");function w(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function E(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:w(t.event)??t.event}}function k(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",w(t.event)??t.event])}(e)}`}const I=Symbol("xstate.systemLogicMetadata"),O=new WeakMap;function T(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],r={id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const n=t(e.input,{self:s,system:r});if(!n)return;let o,c=!1;const a=()=>{c||(c=!0,n.unsubscribe(),o?.unsubscribe())},h=s._parent;h&&(o=h.subscribe({complete:a,error:a})),O.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===i?(O.get(s)?.unsubscribe(),O.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(r,I,{value:{kind:e}}),r}function R(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function M(t=this.source.system){return f(this.source,this.event,t)}function j(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function L(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:j,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function P(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function z(t=this.source.system){return function(t){if("string"==typeof t)throw new Error(e(70,t))}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,E(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function K(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:z,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function q(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const r="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},i=[t.self,r];return{kind:"builtin",exec:$,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function U(t,e,[s,r]){const i="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===n);return!i||o||c?[s,r]:[s,[...r,q(t,s)]]}function N(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!i?.groups)return;const{weeks:n,days:o,hours:c,minutes:a,seconds:h}=i.groups;if(!(n||o||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(n)*24*60*60*1e3+24*u(o)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}const C=new WeakMap,D=new WeakMap,W=new Map;function V(t){t._snapshotVersion++}function B(t){return t._snapshotVersion}function J(t){const e=C.get(t);if(e)return e;const s=D.get(t);if(!s)return;const r=s();return C.set(t,r),D.delete(t),r}function H(t,e,s=e.system,r){D.delete(t);const i=B(s),n=r?J(r):void 0,o=n?.actor===e?n:J(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void C.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??W:t.keyedActors}(s);let u=h.size?new Map(h):W;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(u===W&&(u=new Map),u.set(t,e))}C.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function F(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}let X,G=0;function Q(){return X??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${X}:${(G++).toString(36)}`}function Y(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Z(t,e){return`${t?t.address:""}|${e}`}function tt(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},V(t))}function et(t,e,s){if(void 0!==e){const r=function(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}(e);return r?tt(t,Z(s?.parent,r.prefix),r.index+1):s?.parent||tt(t,Z(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Z(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return tt(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const st=Object.freeze({});function rt(t,e){return k(t,e)}function it(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class nt{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:Q(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=void 0;this._snapshot={_scheduledTimers:st,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=rt(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=it(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}const n=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:n,dueAt:n+s};this._snapshot._scheduledTimers===st&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,V(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],V(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=rt(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==st&&delete this._snapshot._scheduledTimers[s],V(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(u(e)){const r=e,i=t?.system,n=i&&l(i,r);if(!n){const e=p(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:d(r.$actor),error:e})}e=n}if(y(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),V(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&V(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const r=this._keyedActors?.get(t);if(r&&r!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),r!==s&&V(this)}inspect(t){const e=F(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){b(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){b(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(u(e)){const r=l(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:d(e.$actor),error:p(e)})}if(y(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){b(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):v(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=it(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of x)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw A;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let ot=!1;const ct=Object.freeze([]),at={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[o]:!0};let ht=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ut=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function dt(t,e){try{t?.(e)}catch(t){b(t)}}function pt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new ft(t,e)}class ft{get address(){return this._address??=this._parent?`${this._parent.address}/${Y(this.id)}`:Y(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=ht.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...ut,...e}:ut,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new nt(t,e)}(this,{clock:r,logger:i,createActorRef:lt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(F(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=et(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=s._restore;this._restored=void 0!==d;try{if(d)this._setSnapshot(d.restore(this._actorScope));else if(e?._inert);else{const[t,e]=U(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot(d?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>f(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===ht.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=ot;try{ot=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ht.Stopped&&this._recoverOrError(t)})}finally{ot=e}};this._processingStatus!==ht.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,H(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=U(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),pt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??ct)dt(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??ct,actions:this._collectedActions??ct,sent:this._collectedSent??ct,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return pt(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const r=F(t,e,s);if(this._processingStatus!==ht.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":dt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),dt(r.error,t)):b(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,i)=>{const n=F(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===ht.Running)return this;if(this._processingStatus===ht.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=ht.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,g(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,g(this.options.input)):(function(t,e,s){const r=C.get(t),i=B(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,E(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=U(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let o=this._snapshot;try{const[n,c]=r;n!==s||c.length||!("machine"in s)||t.type===i||e&&Object.hasOwn(at,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),pt(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===i&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){dt(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)dt(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===ht.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ht.NotStarted?(this._processingStatus=ht.Stopped,this.system._unregister(this),this):(this._send({type:i}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??ct)dt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||b(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(b)}catch(i){b(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),dt(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===ht.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ht.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ht.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new m(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[S](){return this}getSnapshot(){return this._snapshot}}function _t(t,...[r]){return function(t){if(t&&"object"==typeof t)for(const r of Object.keys(t))if(!s.has(r))throw new Error(e(8,r))}(r),new ft(t,r)}function vt(t,e){const s=t.check(e);if(s)throw s}const yt=new WeakMap;function mt(t,e,s){const r=function(t){let e=yt.get(t);return e||(e=new Map,yt.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function gt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[P("@xstate.cleanup",()=>function(t){const e=yt.get(t);if(!e)return;let s;yt.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===h)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],u=Object.create(null),d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:M,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(K(n,e,t))},raise:t=>{o.push(K(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const c=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!c||s.type===r&&"active"===c.status)&&(o.push(P("@xstate.effect",(e=n.self.system)=>mt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(P("@xstate.effect",(t=n.self.system)=>mt(n.self,void 0,()=>c(t))))}},p=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),U(n,e,[l,o])},s=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:o});if(c)return[s,[L(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&vt(t.validator,{kind:"result",logic:n,snapshot:o[0],effects:o[1]}),o},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,g(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&vt(t.validator,{kind:"input",logic:n,input:e});const i=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==i&&(o.context=i),s({...o},g(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const bt=new WeakMap;const St="xstate.observable.next",xt="xstate.observable.error",At="xstate.observable.complete";const wt="xstate.async.resolve",Et="xstate.async.reject";class kt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const It=gt({context:void 0,run:()=>{}});t.TimeoutError=kt,t.createAsyncLogic=function(t){const e=t,s=gt({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:i,system:n},o)=>{switch(t.type){case wt:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Et:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===r)return o.effect((t=n)=>{const r=i,o=e=>{t.sendEvent(r,r,e)},c=new AbortController,a=e.timeout,h=N(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:Et,data:new kt(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},p=()=>{try{return Promise.resolve(e.run({input:s,system:n,self:i,signal:c.signal},{emit:e=>{f(r,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(r,e,s)):v(r,e,s,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(r,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:wt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:Et,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,I,{value:{kind:"async",timeout:e.timeout}}),s},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t,c=t.emit,a=bt.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return bt.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;const e=n._parent;e&&o._relay(n,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{bt.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return _t(It)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,r={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case xt:return U(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case At:return U(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case i:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&vt(s,{kind:"input",logic:r,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>r.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:xt,data:t})},complete:()=>{r._relay(s,s,{type:At})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return r},t.createListenerLogic=function(){return T(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const n="*"!==e&&e.endsWith(".*");return t.on(n?"*":e,t=>{n&&!function(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),r=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],i=r[t];if("*"===e){return t===s.length-1}if(e!==i)return!1}return!0}(t.type,e)||R(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case St:return{context:i.data};case xt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case At:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===r&&s.effect((t=c)=>{const s=o,r=e=>{t.sendEvent(s,s,e)},i=e({input:n,system:c,self:o,emit:e=>{f(s,e,t)}}).subscribe({next:t=>{r({type:St,data:t})},error:t=>{r({type:xt,data:t})},complete:()=>{r({type:At})}});return()=>i.unsubscribe()})}})},t.createStepLogic=gt,t.createSubscriptionLogic=function(){return T(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:n,snapshot:o}=e;return t.subscribe({next:t=>{"done"===t.status&&i?R(s,r,()=>i(t.output)):"error"===t.status&&n?R(s,r,()=>n(t.error)):"active"===t.status&&o&&R(s,r,()=>o(t))},error:t=>{n&&R(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},Object.defineProperty(t,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateActors={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const r="xstate.init",i="xstate.stop",n="@xstate.terminate",o="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",h="xstate.logic.effect.start";function u(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t["@actor"])return!1;for(const e in t)if("@actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function d(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function p(t){return new Error(e(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function l(t,e){const s=t._getByAddress?.(e["@actor"]);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function f(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const _=new WeakMap;async function v(t,s,r,i=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const o=_.get(t)?.get(s);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let u,d;const p=new Promise((t,e)=>{u=t,d=e});let l,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,p);const v=()=>{l?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return p.then(v,v),l=t.subscribe({error:d,complete:()=>d(new Error(e(72,s)))}),(async()=>{try{i({type:h,key:s});const e=await r();"active"===t.getSnapshot().status&&(i({type:c,key:s,output:e}),u(e))}catch(e){"active"===t.getSnapshot().status&&i({type:a,key:s,error:e}),d(e)}})().catch(d),p}function y(t,s,r){const i=function(t,s,r){const i=s;if(t!==s&&i.logic?.isInternalEventType?.(r.type))return new Error(e(73,r.type,s.id))}(t,s,r);return!!i&&(s.system.deadLetter(t,s,r,"internalEvent",{error:i}),!0)}class m{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function g(t){return{type:r,input:t}}function b(t){setTimeout(()=>{throw t})}const S="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],A=new Error("Transition effect");function w(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function E(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:w(t.event)??t.event}}function k(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",w(t.event)??t.event])}(e)}`}const T=Symbol("xstate.systemLogicMetadata"),I=new WeakMap;function O(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]],r={id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const n=t(e.input,{self:s,system:r});if(!n)return;let o,c=!1;const a=()=>{c||(c=!0,n.unsubscribe(),o?.unsubscribe())},h=s._parent;h&&(o=h.subscribe({complete:a,error:a})),I.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===i?(I.get(s)?.unsubscribe(),I.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return Object.defineProperty(r,T,{value:{kind:e}}),r}function R(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function M(t=this.source.system){return f(this.source,this.event,t)}function j(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function L(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:j,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function P(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function $(t=this.actor.system){const e="done"===this.status?{status:"done",output:this.output,error:void 0}:{status:"error",output:void 0,error:this.error};return t.terminateActor(this.actor,e)}function z(t=this.source.system){return function(t){if("string"==typeof t)throw new Error(e(70,t))}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,E(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function K(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:z,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function q(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const r="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},i=[t.self,r];return{kind:"builtin",exec:$,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function U(t,e,[s,r]){const i="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===n);return!i||o||c?[s,r]:[s,[...r,q(t,s)]]}function N(t){if(void 0!==t)return"number"==typeof t?t:function(t){const e=t.trim(),s=e.match(/^(\d+)ms$/i);if(s)return parseInt(s[1],10);const r=e.match(/^(\d*)(\.?)(\d*)s$/i);if(r){const t=r[1]?parseInt(r[1],10):0,e=!!r[2],s=r[3]?parseInt(r[3].padEnd(3,"0").slice(0,3),10):0;return 1e3*t+(e?s:0)}const i=e.match(/^P(?:(?<weeks>\d+(?:[.,]\d+)?)W)?(?:(?<days>\d+(?:[.,]\d+)?)D)?(?:T(?:(?<hours>\d+(?:[.,]\d+)?)H)?(?:(?<minutes>\d+(?:[.,]\d+)?)M)?(?:(?<seconds>\d+(?:[.,]\d+)?)S)?)?$/i);if(!i?.groups)return;const{weeks:n,days:o,hours:c,minutes:a,seconds:h}=i.groups;if(!(n||o||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(n)*24*60*60*1e3+24*u(o)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}const C=new WeakMap,D=new WeakMap,W=new Map;function V(t){t._snapshotVersion++}function B(t){return t._snapshotVersion}function J(t){const e=C.get(t);if(e)return e;const s=D.get(t);if(!s)return;const r=s();return C.set(t,r),D.delete(t),r}function H(t,e,s=e.system,r){D.delete(t);const i=B(s),n=r?J(r):void 0,o=n?.actor===e?n:J(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void C.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??W:t.keyedActors}(s);let u=h.size?new Map(h):W;for(const e of Object.values(function(t){return"children"in t&&t.children?t.children:{}}(t))){if(!e)continue;e.sessionId&&(a??=new Map).set(e.sessionId,e);const t=e.registryKey;t&&(u===W&&(u=new Map),u.set(t,e))}C.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function F(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}let X,G=0;function Q(){return X??=function(){let t;try{t=globalThis.crypto}catch{}if(t?.getRandomValues)try{const e=new Uint32Array(4);return t.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(7,"0")).join("")}catch{}if(t?.randomUUID)try{return t.randomUUID().replaceAll("-","")}catch{}return`xstate-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),`${X}:${(G++).toString(36)}`}function Y(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Z(t,e){return`${t?t.address:""}|${e}`}function tt(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},V(t))}function et(t,e,s){if(void 0!==e){const r=function(t){const e=t.lastIndexOf(":");if(e<=0||e===t.length-1)return;const s=Number(t.slice(e+1));return Number.isSafeInteger(s)&&s>=0?{prefix:t.slice(0,e),index:s}:void 0}(e);return r?tt(t,Z(s?.parent,r.prefix),r.index+1):s?.parent||tt(t,Z(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Z(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return tt(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const st=Object.freeze({});function rt(t,e){return k(t,e)}function it(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class nt{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:Q(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=void 0;this._snapshot={_scheduledTimers:st,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;if(!n._inTransition)return;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=rt(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=it(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}const n=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:n,dueAt:n+s};this._snapshot._scheduledTimers===st&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,V(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],V(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=rt(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==st&&delete this._snapshot._scheduledTimers[s],V(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(u(e)){const r=e,i=t?.system,n=i&&l(i,r);if(!n){const e=p(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:d(r["@actor"]),error:e})}e=n}if(y(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),V(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&V(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const r=this._keyedActors?.get(t);if(r&&r!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),r!==s&&V(this)}inspect(t){const e=F(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){b(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){b(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(u(e)){const r=l(this,e);if(r)e=r;else if(this._getByAddress(e["@actor"])||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:d(e["@actor"]),error:p(e)})}if(y(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){b(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):v(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=it(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of x)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw A;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let ot=!1;const ct=Object.freeze([]),at={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[o]:!0};let ht=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ut=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function dt(t,e){try{t?.(e)}catch(t){b(t)}}function pt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new ft(t,e)}class ft{get address(){return this._address??=this._parent?`${this._parent.address}/${Y(this.id)}`:Y(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=ht.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._inTransition=!1,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...ut,...e}:ut,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new nt(t,e)}(this,{clock:r,logger:i,createActorRef:lt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(F(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=et(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=s._restore;this._restored=void 0!==d;try{if(d)this._setSnapshot(d.restore(this._actorScope));else if(e?._inert);else{this._inTransition=!0;try{const[t,e]=U(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}catch(t){this._setSnapshot(d?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>f(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===ht.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=ot;try{ot=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==ht.Stopped&&this._recoverOrError(t)})}finally{ot=e}};this._processingStatus!==ht.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,H(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;const r=this._inTransition;this._inTransition=!0;try{const[t,r]=U(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),pt(r,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=r}}_next(t){for(const e of this.observers??ct)dt(e.next,t)}update(t,e){this._setSnapshot(t);const s=this._deferred;for(let e=0;e<(s?.length??0);e++){const r=s[e];try{r()}catch(e){if(s.length=0,this._tryHandleExecutionError(e,t))return;this._setErrorSnapshot(e,t),this._error(e);break}}if(s&&(s.length=0),"active"===this._snapshot.status)this._next(t);this._inspectTransition(this._snapshot,e)}_inspectTransition(t,e){(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.transition",actorRef:this,event:e,sourceRef:this._lastSourceRef,targetRef:this,snapshot:t,microsteps:this._collectedMicrosteps??ct,actions:this._collectedActions??ct,sent:this._collectedSent??ct,eventType:e.type}),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0}_flushInitialEffects(){if(!this._initialEffects?.length)return!0;this._forceDeferredActions=!0;try{return pt(this._initialEffects,this._actorScope),this._initialEffects=void 0,!0}catch(t){return this._initialEffects=void 0,this._deferred&&(this._deferred.length=0),this._recoverOrError(t),"active"===this._snapshot.status}finally{this._forceDeferredActions=!1}}subscribe(t,e,s){const r=F(t,e,s);if(this._processingStatus!==ht.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":dt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),dt(r.error,t)):b(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,i)=>{const n=F(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===ht.Running)return this;if(this._processingStatus===ht.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=ht.Running,this._lastSourceRef=this._parent;switch(this._snapshot.status){case"done":return this._restored?(this._next(this._snapshot),this._stopProcedure(),this._complete(),this):this._flushInitialEffects()?(this.update(this._snapshot,g(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,g(this.options.input)):(function(t,e,s){const r=C.get(t),i=B(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,E(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=U(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let o=this._snapshot;try{const[n,c]=r;n!==s||c.length||!("machine"in s)||t.type===i||e&&Object.hasOwn(at,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),pt(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===i&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){dt(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)dt(s,t)}_terminate(t){if("done"===t.status)return this._next(this._snapshot),this._stopProcedure(),this._complete(),void(this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t.output,r=this.sessionId,{type:"xstate.done.actor",output:s,actorId:e,sessionId:r})));var e,s,r;"error"===t.status&&this._error(t.error)}_stop(){return this._processingStatus===ht.Stopped?this:(this.mailbox?.clear(),this._processingStatus===ht.NotStarted?(this._processingStatus=ht.Stopped,this.system._unregister(this),this):(this._send({type:i}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??ct)dt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||b(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(b)}catch(i){b(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),dt(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===ht.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=ht.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===ht.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new m(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{"@actor":this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[S](){return this}getSnapshot(){return this._snapshot}}function _t(t,...[r]){return function(t){if(t&&"object"==typeof t)for(const r of Object.keys(t))if(!s.has(r))throw new Error(e(8,r))}(r),new ft(t,r)}function vt(t,e){const s=t.check(e);if(s)throw s}const yt=new WeakMap;function mt(t,e,s){const r=function(t){let e=yt.get(t);return e||(e=new Map,yt.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function gt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[P("@xstate.cleanup",()=>function(t){const e=yt.get(t);if(!e)return;let s;yt.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===h)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],u=Object.create(null),d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:M,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(K(n,e,t))},raise:t=>{o.push(K(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const c=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!c||s.type===r&&"active"===c.status)&&(o.push(P("@xstate.effect",(e=n.self.system)=>mt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(P("@xstate.effect",(t=n.self.system)=>mt(n.self,void 0,()=>c(t))))}},p=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),l={...e,...p||{}};return("context"in e||void 0!==p?.context)&&(l.context=p?.context??e.context),(p?.effects||Object.keys(u).length)&&(l.effects={...e.effects,...p?.effects,...u}),U(n,e,[l,o])},s=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:o});if(c)return[s,[L(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&vt(t.validator,{kind:"result",logic:n,snapshot:o[0],effects:o[1]}),o},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,g(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&vt(t.validator,{kind:"input",logic:n,input:e});const i=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==i&&(o.context=i),s({...o},g(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const bt=new WeakMap;const St="xstate.observable.next",xt="xstate.observable.error",At="xstate.observable.complete";const wt="xstate.async.resolve",Et="xstate.async.reject";class kt extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const Tt=gt({context:void 0,run:()=>{}});t.TimeoutError=kt,t.createAsyncLogic=function(t){const e=t,s=gt({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:s,self:i,system:n},o)=>{switch(t.type){case wt:{const e="data"in t?t.data:t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case Et:{const e="data"in t?t.data:t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===r)return o.effect((t=n)=>{const r=i,o=e=>{t.sendEvent(r,r,e)},c=new AbortController,a=e.timeout,h=N(a),u=void 0===h?void 0:n._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),o({type:Et,data:new kt(a)}))},h),d=()=>{void 0!==u&&n._clock.clearTimeout(u)},p=()=>{try{return Promise.resolve(e.run({input:s,system:n,self:i,signal:c.signal},{emit:e=>{f(r,e,t)},step:(e,s)=>t.runStep?Promise.resolve(t.runStep(r,e,s)):v(r,e,s,o)}))}catch(t){return Promise.reject(t)}};return(t.runLogic?Promise.resolve(t.runLogic(r,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&o({type:wt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&o({type:Et,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}});return Object.defineProperty(s,T,{value:{kind:"async",timeout:e.timeout}}),s},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:n,system:o}=t,c=t.emit,a=bt.get(n);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return bt.set(n,t),t.dispose=e({input:i,system:o,self:n,sendBack:t=>{if("stopped"===n.getSnapshot().status)return;const e=n._parent;e&&o._relay(n,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{bt.delete(n),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return _t(Tt)},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,r={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case xt:return U(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case At:return U(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case i:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&vt(s,{kind:"input",logic:r,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>r.initialTransition(e,t)[0],start:(t,{self:s,system:r,emit:i})=>{"done"!==t.status&&(t._subscription=e({input:t.input,system:r,self:s,emit:t=>{i(t)}}).subscribe({next:t=>{s._parent&&r._relay(s,s._parent,t)},error:t=>{r._relay(s,s,{type:xt,data:t})},complete:()=>{r._relay(s,s,{type:At})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return r},t.createListenerLogic=function(){return O(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const n="*"!==e&&e.endsWith(".*");return t.on(n?"*":e,t=>{n&&!function(t,e){if(e===t)return!0;if("*"===e)return!0;if(!e.endsWith(".*"))return!1;const s=e.split("."),r=t.split(".");for(let t=0;t<s.length;t++){const e=s[t],i=r[t];if("*"===e){return t===s.length-1}if(e!==i)return!1}return!0}(t.type,e)||R(r,i,()=>s(t))})},"@xstate.listener")},t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return gt({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:i,input:n,self:o,system:c}=t;switch(i.type){case St:return{context:i.data};case xt:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case At:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===r&&s.effect((t=c)=>{const s=o,r=e=>{t.sendEvent(s,s,e)},i=e({input:n,system:c,self:o,emit:e=>{f(s,e,t)}}).subscribe({next:t=>{r({type:St,data:t})},error:t=>{r({type:xt,data:t})},complete:()=>{r({type:At})}});return()=>i.unsubscribe()})}})},t.createStepLogic=gt,t.createSubscriptionLogic=function(){return O(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:n,snapshot:o}=e;return t.subscribe({next:t=>{"done"===t.status&&i?R(s,r,()=>i(t.output)):"error"===t.status&&n?R(s,r,()=>n(t.error)):"active"===t.status&&o&&R(s,r,()=>o(t))},error:t=>{n&&R(s,r,()=>n(t))},complete:()=>{}})},"@xstate.subscription")},Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map