xstate 6.0.0-alpha.43 → 6.0.0-alpha.45

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 (54) hide show
  1. package/dist/{StateMachine-fcc48e11.cjs.js → StateMachine-2eecedfe.cjs.js} +2 -2
  2. package/dist/{StateMachine-1ea29688.development.esm.js → StateMachine-4bf86161.development.esm.js} +2 -2
  3. package/dist/{StateMachine-16d7ee93.development.cjs.js → StateMachine-5b915fb1.development.cjs.js} +2 -2
  4. package/dist/{StateMachine-b13b4b09.esm.js → StateMachine-d2fcf2e8.esm.js} +2 -2
  5. package/dist/{createActor-9538c7f8.cjs.js → createActor-48401456.cjs.js} +56 -4
  6. package/dist/{createActor-1a3a1d14.development.cjs.js → createActor-5c9fa117.development.cjs.js} +56 -4
  7. package/dist/{createActor-f9cc6590.development.esm.js → createActor-60ee6b5b.development.esm.js} +55 -5
  8. package/dist/{createActor-973c72ad.esm.js → createActor-641ab5f7.esm.js} +55 -5
  9. package/dist/declarations/src/createActor.d.ts +0 -1
  10. package/dist/declarations/src/createMachine.d.ts +3 -3
  11. package/dist/declarations/src/durable/index.d.ts +51 -16
  12. package/dist/declarations/src/inspectionAmbient.d.ts +1 -0
  13. package/dist/declarations/src/schema.types.d.ts +2 -0
  14. package/dist/declarations/src/setup.d.ts +33 -5
  15. package/dist/declarations/src/system.d.ts +1 -1
  16. package/dist/declarations/src/types.d.ts +1 -0
  17. package/dist/declarations/src/types.v6.d.ts +15 -1
  18. package/dist/{effectDescriptor-f8c9337f.cjs.js → effectDescriptor-0cba79a1.development.cjs.js} +19 -1
  19. package/dist/{effectDescriptor-7d6f945a.development.cjs.js → effectDescriptor-adb27412.cjs.js} +19 -1
  20. package/dist/{effectDescriptor-416ca00a.esm.js → effectDescriptor-dffb91a8.esm.js} +19 -1
  21. package/dist/{effectDescriptor-e6730c9a.development.esm.js → effectDescriptor-fed26db6.development.esm.js} +19 -1
  22. package/dist/{index-f284cc7b.development.esm.js → index-158e7c37.development.esm.js} +1 -1
  23. package/dist/{index-e0ba4813.development.cjs.js → index-662114ff.development.cjs.js} +1 -1
  24. package/dist/{index-b478f443.esm.js → index-8f19f242.esm.js} +1 -1
  25. package/dist/{index-ba7170ba.cjs.js → index-fce4ea5c.cjs.js} +1 -1
  26. package/dist/xstate-actors.cjs.js +2 -2
  27. package/dist/xstate-actors.development.cjs.js +2 -2
  28. package/dist/xstate-actors.development.esm.js +2 -2
  29. package/dist/xstate-actors.esm.js +2 -2
  30. package/dist/xstate-actors.umd.min.js +1 -1
  31. package/dist/xstate-actors.umd.min.js.map +1 -1
  32. package/dist/xstate-durable.cjs.js +80 -20
  33. package/dist/xstate-durable.development.cjs.js +80 -20
  34. package/dist/xstate-durable.development.esm.js +80 -20
  35. package/dist/xstate-durable.esm.js +80 -20
  36. package/dist/xstate-durable.umd.min.js +1 -1
  37. package/dist/xstate-durable.umd.min.js.map +1 -1
  38. package/dist/xstate-graph.cjs.js +3 -3
  39. package/dist/xstate-graph.development.cjs.js +3 -3
  40. package/dist/xstate-graph.development.esm.js +3 -3
  41. package/dist/xstate-graph.esm.js +3 -3
  42. package/dist/xstate-graph.umd.min.js +1 -1
  43. package/dist/xstate-graph.umd.min.js.map +1 -1
  44. package/dist/xstate-validation.cjs.js +1 -1
  45. package/dist/xstate-validation.development.cjs.js +1 -1
  46. package/dist/xstate-validation.development.esm.js +1 -1
  47. package/dist/xstate-validation.esm.js +1 -1
  48. package/dist/xstate.cjs.js +19 -5
  49. package/dist/xstate.development.cjs.js +19 -5
  50. package/dist/xstate.development.esm.js +21 -7
  51. package/dist/xstate.esm.js +21 -7
  52. package/dist/xstate.umd.min.js +1 -1
  53. package/dist/xstate.umd.min.js.map +1 -1
  54. package/package.json +1 -1
@@ -5,7 +5,7 @@ import { type Actor, type RequiredActorOptionsKeys } from "./createActor.js";
5
5
  import { AnyActorRef, AnyActorLogic, ActorRefFromLogic, AnyStateNode, EventObject, AnyEventObject, EventDescriptor, ExtractEvent, MachineContext, ProvidedActor, RoutableStateId, StateSchema, StateValue, StateValueFromStateSchema, ToChildren, MetaObject, Cast, Compute, EnqueueObject, DoneActorEvent, DoneStateEvent, ErrorActorEvent, SystemRegistry, RegistryKeyForLogic, ActorOptions, Observer, Subscription, OutputArg, SnapshotEvent, SingleOrArray, AfterEvent, TimeoutEvent, ErrorEvent } from "./types.js";
6
6
  import { AnyActorSystem } from "./system.js";
7
7
  import { InspectionEvent } from "./inspection.js";
8
- import { ActionSchemas, DelayMapFromNames, GuardSchemas, InferChildren, InferActions, InferGuards, Sources, InferOutput, InferEvents, InferInternalEvents, Next_MachineConfig, Next_InvokeConfig, Next_StateNodeConfig, Next_TransitionConfigOrTarget, ValidateHistoryDefaults, ValidateStateTargets, WithDefault } from "./types.v6.js";
8
+ import { ActionSchemas, DelayMapFromNames, GuardSchemas, InferChildren, InferActions, InferGuards, Sources, InferOutput, InferEvents, InferInternalEvents, Next_MachineConfig, Next_InvokeConfig, Next_StateNodeConfig, Next_TransitionConfigOrTarget, OutputFromConfig, ValidateHistoryDefaults, ValidateStateTargets, WithDefault } from "./types.v6.js";
9
9
  export type SetupConfig<TSchemas extends SetupSchemas, TStates extends Record<string, SetupStateSchema>, TActionMap extends Sources['actions'], TActorMap extends Sources['actors'], TGuardMap extends Sources['guards'], TDelayMap extends Sources['delays'], TValidator extends ActorLogicValidator | undefined = ActorLogicValidator | undefined> = {
10
10
  validator?: TValidator;
11
11
  schemas?: TSchemas & SetupSchemas;
@@ -140,7 +140,7 @@ export type SetupSchemas = {
140
140
  tags?: StandardSchemaV1;
141
141
  children?: Record<string, StandardSchemaV1>;
142
142
  };
143
- /** State schema with optional schemas.input and nested states */
143
+ /** State schema with optional input/output schemas and nested states */
144
144
  export interface SetupStateSchema {
145
145
  schemas?: SetupStateSchemas;
146
146
  states?: Record<string, SetupStateSchema>;
@@ -199,6 +199,20 @@ type SetupInput<TSchemas, TInputSchema extends StandardSchemaV1> = [
199
199
  type SetupOutput<TSchemas, TOutputSchema extends StandardSchemaV1> = [
200
200
  SetupSchema<TSchemas, 'output'>
201
201
  ] extends [never] ? InferOutput<TOutputSchema, unknown> : InferOutput<SetupSchema<TSchemas, 'output'>, unknown>;
202
+ /**
203
+ * Whether an output schema was declared, either in `setup({ schemas })` or in
204
+ * the machine config's own `schemas.output`. A declared schema is always
205
+ * authoritative for the machine's output type.
206
+ */
207
+ type HasOutputSchema<TSchemas, TOutputSchema extends StandardSchemaV1> = [
208
+ SetupSchema<TSchemas, 'output'>
209
+ ] extends [never] ? StandardSchemaV1 extends TOutputSchema ? false : true : true;
210
+ /**
211
+ * The machine's output type. A declared output schema wins; otherwise the type
212
+ * is inferred from the config's `output` property (a mapper's return type, or
213
+ * the static value's type).
214
+ */
215
+ type SetupOrConfigOutput<TSchemas, TOutputSchema extends StandardSchemaV1, TConfig> = HasOutputSchema<TSchemas, TOutputSchema> extends true ? SetupOutput<TSchemas, TOutputSchema> : OutputFromConfig<TConfig, SetupOutput<TSchemas, TOutputSchema>>;
202
216
  type SetupEmitted<TSchemas, TEmittedSchemaMap extends Record<string, StandardSchemaV1>> = [SetupSchemaMap<TSchemas, 'emitted'>] extends [never] ? WithDefault<InferEvents<TEmittedSchemaMap>, AnyEventObject> : WithDefault<InferEvents<SetupSchemaMap<TSchemas, 'emitted'>>, AnyEventObject>;
203
217
  type SetupMeta<TSchemas, TMetaSchema extends StandardSchemaV1> = [
204
218
  SetupSchema<TSchemas, 'meta'>
@@ -236,6 +250,11 @@ type ValidateSetupDelayReferences<TConfig, TSetupDelays extends string> = string
236
250
  type StateInput<TStateSchema extends SetupStateSchema> = TStateSchema['schemas'] extends {
237
251
  input: infer TInputSchema;
238
252
  } ? TInputSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TInputSchema> : undefined : undefined;
253
+ /** Extracts the completion output type from a state schema. */
254
+ type StateOutput<TStateSchema extends SetupStateSchema, TFallback> = TStateSchema['schemas'] extends {
255
+ output: infer TOutputSchema;
256
+ } ? TOutputSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TOutputSchema> : TFallback : TFallback;
257
+ type StateCompletionOutput<TStateSchema extends SetupStateSchema> = StateOutput<TStateSchema, unknown>;
239
258
  type StateContext<TStateSchema extends SetupStateSchema, TFallbackContext extends MachineContext> = TStateSchema['schemas'] extends {
240
259
  context: infer TContextSchema;
241
260
  } ? TContextSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TContextSchema> & MachineContext & RootContextMarker<TFallbackContext> : RootContext<TFallbackContext> : RootContext<TFallbackContext>;
@@ -262,6 +281,9 @@ type SetupStateSchemaToStateSchema<TSetupSchema extends SetupStateSchema> = {
262
281
  contextSchema: TSetupSchema['schemas'] extends {
263
282
  context: infer TContextSchema;
264
283
  } ? TContextSchema extends StandardSchemaV1 ? TContextSchema : undefined : undefined;
284
+ outputSchema: TSetupSchema['schemas'] extends {
285
+ output: infer TOutputSchema;
286
+ } ? TOutputSchema extends StandardSchemaV1 ? TOutputSchema : undefined : undefined;
265
287
  states: TSetupSchema['states'] extends Record<string, SetupStateSchema> ? {
266
288
  [K in keyof TSetupSchema['states'] & string]: SetupStateSchemaToStateSchema<TSetupSchema['states'][K]>;
267
289
  } : undefined;
@@ -286,11 +308,17 @@ type StateSchemaContextSchema<TConfig extends StateSchema, TSetup extends StateS
286
308
  } ? TContextSchema extends StandardSchemaV1 ? TContextSchema : undefined : TConfig extends {
287
309
  contextSchema: infer TContextSchema;
288
310
  } ? TContextSchema extends StandardSchemaV1 ? TContextSchema : undefined : undefined;
311
+ type StateSchemaOutputSchema<TConfig extends StateSchema, TSetup extends StateSchema> = TSetup extends {
312
+ outputSchema: infer TOutputSchema;
313
+ } ? TOutputSchema extends StandardSchemaV1 ? TOutputSchema : undefined : TConfig extends {
314
+ outputSchema: infer TOutputSchema;
315
+ } ? TOutputSchema extends StandardSchemaV1 ? TOutputSchema : undefined : undefined;
289
316
  type StateSchemaChild<TSetup extends StateSchema, K extends string> = TSetup extends {
290
317
  states: infer TStates;
291
318
  } ? K extends keyof TStates ? Cast<TStates[K], StateSchema> : EmptyStateSchema : EmptyStateSchema;
292
319
  type MergeStateSchema<TConfig extends StateSchema, TSetup extends StateSchema> = Omit<TConfig, 'contextSchema' | 'input' | 'states'> & {
293
320
  contextSchema: StateSchemaContextSchema<TConfig, TSetup>;
321
+ outputSchema: StateSchemaOutputSchema<TConfig, TSetup>;
294
322
  input: StateSchemaInput<TConfig, TSetup>;
295
323
  states: TConfig extends {
296
324
  states: infer TStates;
@@ -321,7 +349,7 @@ type StatesWithInput<TRootStateSchemas extends Record<string, SetupStateSchema>,
321
349
  [K in TStateKeys]?: StateNodeConfigWithNestedInput<StateSchemasWithKeys<TRootStateSchemas, TStateKeys>, K extends keyof TStateSchemas ? TStateSchemas[K] : {}, TContext, TContextShape, TEvent, TChildren, TDelays, TTag, TOutput, TEmitted, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry>;
322
350
  };
323
351
  /** State node config that recursively applies typed input for nested states */
324
- type StateNodeConfigWithNestedInput<TSiblingStateSchemas extends Record<string, SetupStateSchema>, TStateSchema extends SetupStateSchema, TContext extends MachineContext, TContextShape, TEvent extends EventObject, TChildren extends Record<string, AnyActorRef | undefined>, TDelays extends string, TTag extends string, TOutput, TEmitted extends EventObject, TMeta extends MetaObject, TActionMap extends Sources['actions'], TActorMap extends Sources['actors'], TGuardMap extends Sources['guards'], TDelayMap extends Sources['delays'], TSystemRegistry extends SystemRegistry> = WithNestedStates<Omit<Next_StateNodeConfig<StateContext<TStateSchema, TContext>, TEvent, TDelays, TTag, TOutput, TEmitted, TMeta, TChildren, TActionMap, TActorMap, TGuardMap, TDelayMap, StateInput<TStateSchema>, Record<string, unknown>, TSystemRegistry>, 'on' | 'always' | 'initial' | 'invoke' | 'onDone' | 'onError' | 'onTimeout' | 'after'> & {
352
+ type StateNodeConfigWithNestedInput<TSiblingStateSchemas extends Record<string, SetupStateSchema>, TStateSchema extends SetupStateSchema, TContext extends MachineContext, TContextShape, TEvent extends EventObject, TChildren extends Record<string, AnyActorRef | undefined>, TDelays extends string, TTag extends string, TOutput, TEmitted extends EventObject, TMeta extends MetaObject, TActionMap extends Sources['actions'], TActorMap extends Sources['actors'], TGuardMap extends Sources['guards'], TDelayMap extends Sources['delays'], TSystemRegistry extends SystemRegistry> = WithNestedStates<Omit<Next_StateNodeConfig<StateContext<TStateSchema, TContext>, TEvent, TDelays, TTag, StateOutput<TStateSchema, TOutput>, TEmitted, TMeta, TChildren, TActionMap, TActorMap, TGuardMap, TDelayMap, StateInput<TStateSchema>, Record<string, unknown>, TSystemRegistry, StateCompletionOutput<TStateSchema>>, 'on' | 'always' | 'initial' | 'invoke' | 'onDone' | 'onError' | 'onTimeout' | 'after'> & {
325
353
  initial?: TStateSchema['states'] extends Record<string, SetupStateSchema> ? SetupStateKey<TStateSchema['states']> | (string & {}) | InitialTransitionWithInput<TStateSchema['states'], StateContext<TStateSchema, TContext>, TEvent> : string | {
326
354
  target: string;
327
355
  input?: Record<string, unknown>;
@@ -329,7 +357,7 @@ type StateNodeConfigWithNestedInput<TSiblingStateSchemas extends Record<string,
329
357
  on?: StateTransitions<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
330
358
  always?: StateTransitionConfigOrTarget<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, TEvent, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
331
359
  invoke?: SingleOrArray<SetupInvokeConfig<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry>>;
332
- onDone?: StateTransitionConfigOrTarget<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, DoneStateEvent, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
360
+ onDone?: StateTransitionConfigOrTarget<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, DoneStateEvent<StateCompletionOutput<TStateSchema>>, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
333
361
  onError?: StateTransitionConfigOrTarget<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, ErrorEvent, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
334
362
  onTimeout?: StateTransitionConfigOrTarget<TSiblingStateSchemas, StateContext<TStateSchema, TContext>, StateContextShape<TStateSchema, TContextShape>, TimeoutEvent, TEvent, TEmitted, TChildren, TMeta, TActionMap, TActorMap, TGuardMap, TDelayMap, TSystemRegistry, StateInput<TStateSchema>>;
335
363
  after?: {
@@ -471,7 +499,7 @@ export interface SetupReturn<TStates extends Record<string, SetupStateSchema> =
471
499
  to: RoutableStateId<Cast<TConfig, StateSchema>>;
472
500
  }), Cast<MergeChildren<SetupChildren<TSchemas, TChildrenSchemaMap>, TActor>, Record<string, AnyActorRef | undefined>>, StateValueFromStateSchema<MergeStateSchema<Cast<TConfig, StateSchema>, SetupStatesToStateSchema<TStates>>>, TTag & string, [
473
501
  SetupSchema<TSchemas, 'input'>
474
- ] extends [never] ? TInput : SetupInput<TSchemas, TInputSchema>, SetupOutput<TSchemas, TOutputSchema>, SetupEmitted<TSchemas, TEmittedSchemaMap>, SetupMeta<TSchemas, TMetaSchema>, MergeStateSchema<Cast<TConfig, StateSchema>, SetupStatesToStateSchema<TStates>>, MergeSourceMaps<SetupActions<TSchemas, TSetupActionMap>, MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>>, MergeSourceMaps<TSetupActorMap, TActorMap>, MergeSourceMaps<SetupGuards<TSchemas, TSetupGuardMap>, MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>>, DelayMapFromNames<TSetupDelays | TDelays, MergeSourceMaps<TSetupDelayMap, TDelayMap>>, SetupInternalEvents<TSchemas, TInternalEventSchemaMap>> & MachineIdentity<TConfig>;
502
+ ] extends [never] ? TInput : SetupInput<TSchemas, TInputSchema>, SetupOrConfigOutput<TSchemas, TOutputSchema, TConfig>, SetupEmitted<TSchemas, TEmittedSchemaMap>, SetupMeta<TSchemas, TMetaSchema>, MergeStateSchema<Cast<TConfig, StateSchema>, SetupStatesToStateSchema<TStates>>, MergeSourceMaps<SetupActions<TSchemas, TSetupActionMap>, MergeSourceMaps<InferActions<TActionSchemaMap>, TActionMap>>, MergeSourceMaps<TSetupActorMap, TActorMap>, MergeSourceMaps<SetupGuards<TSchemas, TSetupGuardMap>, MergeSourceMaps<InferGuards<TGuardSchemaMap>, TGuardMap>>, DelayMapFromNames<TSetupDelays | TDelays, MergeSourceMaps<TSetupDelayMap, TDelayMap>>, SetupInternalEvents<TSchemas, TInternalEventSchemaMap>> & MachineIdentity<TConfig>;
475
503
  /**
476
504
  * Creates a state node config bound to a specific setup-declared state,
477
505
  * addressed by a dotted path (e.g. `'loading'` or `'parent.child'`). The
@@ -31,6 +31,7 @@ export interface ExecutionIdentity {
31
31
  systemId: string;
32
32
  nextSessionId: number;
33
33
  }
34
+ export { hasAmbientInspector, withSystemInspector } from "./inspectionAmbient.js";
34
35
  /**
35
36
  * Runtime operations used to execute effects.
36
37
  *
@@ -124,4 +125,3 @@ export declare function createRuntimeSystem<T extends ActorSystemInfo>(rootActor
124
125
  snapshot?: unknown;
125
126
  createActorRef: ActorSystem<T>['createActorRef'];
126
127
  }): ActorSystem<T>;
127
- export {};
@@ -1003,6 +1003,7 @@ export type StateSchema = {
1003
1003
  route?: unknown;
1004
1004
  states?: Record<string, StateSchema>;
1005
1005
  contextSchema?: StandardSchemaV1;
1006
+ outputSchema?: StandardSchemaV1;
1006
1007
  input?: unknown;
1007
1008
  type?: unknown;
1008
1009
  history?: unknown;
@@ -5,6 +5,20 @@ import { MachineContext, Mapper } from "./types.js";
5
5
  import { LowInfer } from "./types.js";
6
6
  import { DoneStateEvent } from "./types.js";
7
7
  export type InferOutput<T extends StandardSchemaV1, U> = Compute<StandardSchemaV1.InferOutput<T> extends U ? StandardSchemaV1.InferOutput<T> : never>;
8
+ /**
9
+ * Extracts the machine output type from the config's `output` property: the
10
+ * return type of an output mapper, or the type of a static output value.
11
+ * Falls back to `TFallback` when the config declares no `output`.
12
+ */
13
+ export type OutputFromConfig<TConfig, TFallback> = TConfig extends {
14
+ output: infer TOutput;
15
+ } ? TOutput extends (...args: never[]) => infer TResult ? TResult : TOutput : TFallback;
16
+ /**
17
+ * The machine's output type when no output schema is declared in `setup()`: a
18
+ * declared `schemas.output` is authoritative, otherwise the output type is
19
+ * inferred from the config's `output` property.
20
+ */
21
+ export type SchemaOrConfigOutput<TOutputSchema extends StandardSchemaV1, TConfig> = StandardSchemaV1 extends TOutputSchema ? OutputFromConfig<TConfig, InferOutput<TOutputSchema, unknown>> : InferOutput<TOutputSchema, unknown>;
8
22
  /**
9
23
  * Event payloads from schemas (e.g. Zod) are often inferred as optional in
10
24
  * output types. Wrapping in Required<> ensures properties defined in the schema
@@ -388,7 +402,7 @@ interface Next_RegularStateNodeConfig<TContext extends MachineContext, TEvent ex
388
402
  * This is equivalent to defining a `[done(id)]` transition on this state
389
403
  * node's `on` property.
390
404
  */
391
- onDone?: Next_TransitionConfigOrTarget<TContext, DoneStateEvent, TEvent, TEmitted, TActionMap, TActorMap, TGuardMap, TDelayMap, TMeta>;
405
+ onDone?: Next_TransitionConfigOrTarget<TContext, DoneStateEvent<TChildOutput>, TEvent, TEmitted, TActionMap, TActorMap, TGuardMap, TDelayMap, TMeta>;
392
406
  /**
393
407
  * The transition to take when an `xstate.error.*` event is raised while this
394
408
  * state node or one of its descendants is active.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-9538c7f8.cjs.js');
3
+ var createActor = require('./createActor-5c9fa117.development.cjs.js');
4
4
 
5
5
  function attachMicrostepActorRefs(microsteps, actorScope, inputSnapshot) {
6
6
  if (!microsteps.length) {
@@ -33,6 +33,7 @@ function transition(logic, snapshot, event) {
33
33
  const [nextSnapshot, effects] = createActor.finalizeTransitionResult(actorScope, snapshot, logic.transition(snapshot, event, actorScope));
34
34
  createActor.setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
35
35
  const returnedSnapshot = nextSnapshot === snapshot ? nextSnapshot : createActor.attachSnapshotActorRef(actorScope, nextSnapshot);
36
+ inspectPureTransition(actorScope, returnedSnapshot, event);
36
37
  return [returnedSnapshot, effects];
37
38
  }
38
39
 
@@ -48,9 +49,26 @@ function initialTransition(logic, ...[input]) {
48
49
  const [nextSnapshot, executableActions] = createActor.finalizeTransitionResult(actorScope, undefined, logic.initialTransition(input, actorScope));
49
50
  createActor.setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
50
51
  const returnedSnapshot = createActor.attachSnapshotActorRef(actorScope, nextSnapshot);
52
+ inspectPureTransition(actorScope, returnedSnapshot, createActor.createInitEvent(input));
51
53
  return [returnedSnapshot, executableActions];
52
54
  }
53
55
 
56
+ /**
57
+ * Emits the `@xstate.transition` inspection event for a snapshot produced by
58
+ * the pure transition path, where no live actor loop does it. Free unless an
59
+ * inspector is ambiently installed (a durable execution created with
60
+ * `inspect`): only then is the snapshot's actor ref materialized to emit.
61
+ */
62
+ function inspectPureTransition(actorScope, snapshot, event) {
63
+ if (!createActor.hasAmbientInspector()) {
64
+ return;
65
+ }
66
+ const self = actorScope.self;
67
+ if (self?.system._hasInspectionObservers?.()) {
68
+ self._inspectTransition(snapshot, event);
69
+ }
70
+ }
71
+
54
72
  /**
55
73
  * Given a state `machine`, a `snapshot`, and an `event`, returns an array of
56
74
  * microsteps, where each microstep is a tuple of `[snapshot, actions]`.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-1a3a1d14.development.cjs.js');
3
+ var createActor = require('./createActor-48401456.cjs.js');
4
4
 
5
5
  function attachMicrostepActorRefs(microsteps, actorScope, inputSnapshot) {
6
6
  if (!microsteps.length) {
@@ -33,6 +33,7 @@ function transition(logic, snapshot, event) {
33
33
  const [nextSnapshot, effects] = createActor.finalizeTransitionResult(actorScope, snapshot, logic.transition(snapshot, event, actorScope));
34
34
  createActor.setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
35
35
  const returnedSnapshot = nextSnapshot === snapshot ? nextSnapshot : createActor.attachSnapshotActorRef(actorScope, nextSnapshot);
36
+ inspectPureTransition(actorScope, returnedSnapshot, event);
36
37
  return [returnedSnapshot, effects];
37
38
  }
38
39
 
@@ -48,9 +49,26 @@ function initialTransition(logic, ...[input]) {
48
49
  const [nextSnapshot, executableActions] = createActor.finalizeTransitionResult(actorScope, undefined, logic.initialTransition(input, actorScope));
49
50
  createActor.setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
50
51
  const returnedSnapshot = createActor.attachSnapshotActorRef(actorScope, nextSnapshot);
52
+ inspectPureTransition(actorScope, returnedSnapshot, createActor.createInitEvent(input));
51
53
  return [returnedSnapshot, executableActions];
52
54
  }
53
55
 
56
+ /**
57
+ * Emits the `@xstate.transition` inspection event for a snapshot produced by
58
+ * the pure transition path, where no live actor loop does it. Free unless an
59
+ * inspector is ambiently installed (a durable execution created with
60
+ * `inspect`): only then is the snapshot's actor ref materialized to emit.
61
+ */
62
+ function inspectPureTransition(actorScope, snapshot, event) {
63
+ if (!createActor.hasAmbientInspector()) {
64
+ return;
65
+ }
66
+ const self = actorScope.self;
67
+ if (self?.system._hasInspectionObservers?.()) {
68
+ self._inspectTransition(snapshot, event);
69
+ }
70
+ }
71
+
54
72
  /**
55
73
  * Given a state `machine`, a `snapshot`, and an `event`, returns an array of
56
74
  * microsteps, where each microstep is a tuple of `[snapshot, actions]`.
@@ -1,4 +1,4 @@
1
- import { a9 as createInertActorScope, aa as setInertActorScopeSnapshot, f as finalizeTransitionResult, ab as attachSnapshotActorRef, a as beginSpawnAllocation, ac as macrostep, K as createInitEvent, an as createSpawnEffect, ao as initialMicrostep, j as isAtomicStateNode, ay as getProperAncestors, az as isRemoteActorRef, aA as getActorIdPrefix } from './createActor-973c72ad.esm.js';
1
+ import { a9 as createInertActorScope, aa as setInertActorScopeSnapshot, f as finalizeTransitionResult, ab as attachSnapshotActorRef, K as createInitEvent, ay as hasAmbientInspector, a as beginSpawnAllocation, ac as macrostep, an as createSpawnEffect, ao as initialMicrostep, j as isAtomicStateNode, az as getProperAncestors, aA as isRemoteActorRef, aB as getActorIdPrefix } from './createActor-641ab5f7.esm.js';
2
2
 
3
3
  function attachMicrostepActorRefs(microsteps, actorScope, inputSnapshot) {
4
4
  if (!microsteps.length) {
@@ -31,6 +31,7 @@ function transition(logic, snapshot, event) {
31
31
  const [nextSnapshot, effects] = finalizeTransitionResult(actorScope, snapshot, logic.transition(snapshot, event, actorScope));
32
32
  setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
33
33
  const returnedSnapshot = nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(actorScope, nextSnapshot);
34
+ inspectPureTransition(actorScope, returnedSnapshot, event);
34
35
  return [returnedSnapshot, effects];
35
36
  }
36
37
 
@@ -46,9 +47,26 @@ function initialTransition(logic, ...[input]) {
46
47
  const [nextSnapshot, executableActions] = finalizeTransitionResult(actorScope, undefined, logic.initialTransition(input, actorScope));
47
48
  setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
48
49
  const returnedSnapshot = attachSnapshotActorRef(actorScope, nextSnapshot);
50
+ inspectPureTransition(actorScope, returnedSnapshot, createInitEvent(input));
49
51
  return [returnedSnapshot, executableActions];
50
52
  }
51
53
 
54
+ /**
55
+ * Emits the `@xstate.transition` inspection event for a snapshot produced by
56
+ * the pure transition path, where no live actor loop does it. Free unless an
57
+ * inspector is ambiently installed (a durable execution created with
58
+ * `inspect`): only then is the snapshot's actor ref materialized to emit.
59
+ */
60
+ function inspectPureTransition(actorScope, snapshot, event) {
61
+ if (!hasAmbientInspector()) {
62
+ return;
63
+ }
64
+ const self = actorScope.self;
65
+ if (self?.system._hasInspectionObservers?.()) {
66
+ self._inspectTransition(snapshot, event);
67
+ }
68
+ }
69
+
52
70
  /**
53
71
  * Given a state `machine`, a `snapshot`, and an `event`, returns an array of
54
72
  * microsteps, where each microstep is a tuple of `[snapshot, actions]`.
@@ -1,4 +1,4 @@
1
- import { a9 as createInertActorScope, aa as setInertActorScopeSnapshot, f as finalizeTransitionResult, ab as attachSnapshotActorRef, a as beginSpawnAllocation, ac as macrostep, K as createInitEvent, an as createSpawnEffect, ao as initialMicrostep, j as isAtomicStateNode, ay as getProperAncestors, az as isRemoteActorRef, aA as getActorIdPrefix } from './createActor-f9cc6590.development.esm.js';
1
+ import { a9 as createInertActorScope, aa as setInertActorScopeSnapshot, f as finalizeTransitionResult, ab as attachSnapshotActorRef, K as createInitEvent, ay as hasAmbientInspector, a as beginSpawnAllocation, ac as macrostep, an as createSpawnEffect, ao as initialMicrostep, j as isAtomicStateNode, az as getProperAncestors, aA as isRemoteActorRef, aB as getActorIdPrefix } from './createActor-60ee6b5b.development.esm.js';
2
2
 
3
3
  function attachMicrostepActorRefs(microsteps, actorScope, inputSnapshot) {
4
4
  if (!microsteps.length) {
@@ -31,6 +31,7 @@ function transition(logic, snapshot, event) {
31
31
  const [nextSnapshot, effects] = finalizeTransitionResult(actorScope, snapshot, logic.transition(snapshot, event, actorScope));
32
32
  setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
33
33
  const returnedSnapshot = nextSnapshot === snapshot ? nextSnapshot : attachSnapshotActorRef(actorScope, nextSnapshot);
34
+ inspectPureTransition(actorScope, returnedSnapshot, event);
34
35
  return [returnedSnapshot, effects];
35
36
  }
36
37
 
@@ -46,9 +47,26 @@ function initialTransition(logic, ...[input]) {
46
47
  const [nextSnapshot, executableActions] = finalizeTransitionResult(actorScope, undefined, logic.initialTransition(input, actorScope));
47
48
  setInertActorScopeSnapshot(actorScope, nextSnapshot, false);
48
49
  const returnedSnapshot = attachSnapshotActorRef(actorScope, nextSnapshot);
50
+ inspectPureTransition(actorScope, returnedSnapshot, createInitEvent(input));
49
51
  return [returnedSnapshot, executableActions];
50
52
  }
51
53
 
54
+ /**
55
+ * Emits the `@xstate.transition` inspection event for a snapshot produced by
56
+ * the pure transition path, where no live actor loop does it. Free unless an
57
+ * inspector is ambiently installed (a durable execution created with
58
+ * `inspect`): only then is the snapshot's actor ref materialized to emit.
59
+ */
60
+ function inspectPureTransition(actorScope, snapshot, event) {
61
+ if (!hasAmbientInspector()) {
62
+ return;
63
+ }
64
+ const self = actorScope.self;
65
+ if (self?.system._hasInspectionObservers?.()) {
66
+ self._inspectTransition(snapshot, event);
67
+ }
68
+ }
69
+
52
70
  /**
53
71
  * Given a state `machine`, a `snapshot`, and an `event`, returns an array of
54
72
  * microsteps, where each microstep is a tuple of `[snapshot, actions]`.
@@ -1,4 +1,4 @@
1
- import { K as createInitEvent, e as XSTATE_STOP, L as createCustomEffect, M as XSTATE_LOGIC_EFFECT_START, N as XSTATE_LOGIC_EFFECT_RESOLVE, O as XSTATE_LOGIC_EFFECT_REJECT, f as finalizeTransitionResult, P as createEmitEffect, h as createSendToEffect, X as XSTATE_INIT, p as parseDelayToMilliseconds, H as runStep, k as createActor } from './createActor-f9cc6590.development.esm.js';
1
+ import { K as createInitEvent, e as XSTATE_STOP, L as createCustomEffect, M as XSTATE_LOGIC_EFFECT_START, N as XSTATE_LOGIC_EFFECT_RESOLVE, O as XSTATE_LOGIC_EFFECT_REJECT, f as finalizeTransitionResult, P as createEmitEffect, h as createSendToEffect, X as XSTATE_INIT, p as parseDelayToMilliseconds, H as runStep, k as createActor } from './createActor-60ee6b5b.development.esm.js';
2
2
 
3
3
  function assertValid(validator, request) {
4
4
  const error = validator.check(request);
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-1a3a1d14.development.cjs.js');
3
+ var createActor = require('./createActor-5c9fa117.development.cjs.js');
4
4
 
5
5
  function assertValid(validator, request) {
6
6
  const error = validator.check(request);
@@ -1,4 +1,4 @@
1
- import { K as createInitEvent, e as XSTATE_STOP, L as createCustomEffect, M as XSTATE_LOGIC_EFFECT_START, N as XSTATE_LOGIC_EFFECT_RESOLVE, O as XSTATE_LOGIC_EFFECT_REJECT, f as finalizeTransitionResult, P as createEmitEffect, h as createSendToEffect, X as XSTATE_INIT, p as parseDelayToMilliseconds, H as runStep, k as createActor } from './createActor-973c72ad.esm.js';
1
+ import { K as createInitEvent, e as XSTATE_STOP, L as createCustomEffect, M as XSTATE_LOGIC_EFFECT_START, N as XSTATE_LOGIC_EFFECT_RESOLVE, O as XSTATE_LOGIC_EFFECT_REJECT, f as finalizeTransitionResult, P as createEmitEffect, h as createSendToEffect, X as XSTATE_INIT, p as parseDelayToMilliseconds, H as runStep, k as createActor } from './createActor-641ab5f7.esm.js';
2
2
 
3
3
  function assertValid(validator, request) {
4
4
  const error = validator.check(request);
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var createActor = require('./createActor-9538c7f8.cjs.js');
3
+ var createActor = require('./createActor-48401456.cjs.js');
4
4
 
5
5
  function assertValid(validator, request) {
6
6
  const error = validator.check(request);
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-9538c7f8.cjs.js');
6
- var dist_xstateActors = require('./index-ba7170ba.cjs.js');
5
+ var createActor = require('./createActor-48401456.cjs.js');
6
+ var dist_xstateActors = require('./index-fce4ea5c.cjs.js');
7
7
 
8
8
 
9
9
 
@@ -2,8 +2,8 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var createActor = require('./createActor-1a3a1d14.development.cjs.js');
6
- var dist_xstateActors = require('./index-e0ba4813.development.cjs.js');
5
+ var createActor = require('./createActor-5c9fa117.development.cjs.js');
6
+ var dist_xstateActors = require('./index-662114ff.development.cjs.js');
7
7
 
8
8
 
9
9
 
@@ -1,2 +1,2 @@
1
- export { l as createListenerLogic, n as createSubscriptionLogic, o as listenerLogic, s as subscriptionLogic } from './createActor-f9cc6590.development.esm.js';
2
- export { T as TimeoutError, c as createAsyncLogic, a as createCallbackLogic, b as createEmptyActor, d as createEventObservableLogic, e as createLogic, f as createObservableLogic } from './index-f284cc7b.development.esm.js';
1
+ export { l as createListenerLogic, n as createSubscriptionLogic, o as listenerLogic, s as subscriptionLogic } from './createActor-60ee6b5b.development.esm.js';
2
+ export { T as TimeoutError, c as createAsyncLogic, a as createCallbackLogic, b as createEmptyActor, d as createEventObservableLogic, e as createLogic, f as createObservableLogic } from './index-158e7c37.development.esm.js';
@@ -1,2 +1,2 @@
1
- export { l as createListenerLogic, n as createSubscriptionLogic, o as listenerLogic, s as subscriptionLogic } from './createActor-973c72ad.esm.js';
2
- export { T as TimeoutError, c as createAsyncLogic, a as createCallbackLogic, b as createEmptyActor, d as createEventObservableLogic, e as createLogic, f as createObservableLogic } from './index-b478f443.esm.js';
1
+ export { l as createListenerLogic, n as createSubscriptionLogic, o as listenerLogic, s as subscriptionLogic } from './createActor-641ab5f7.esm.js';
2
+ export { T as TimeoutError, c as createAsyncLogic, a as createCallbackLogic, b as createEmptyActor, d as createEventObservableLogic, e as createLogic, f as createObservableLogic } from './index-8f19f242.esm.js';
@@ -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";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",r="@xstate.stop",i="@xstate.terminate",o="xstate.logic.effect.resolve",n="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=new WeakMap;function p(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const o=t(e.input,{self:s,system:r});if(!o)return;let n,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),n?.unsubscribe())},h=s._parent;h&&(n=h.subscribe({complete:a,error:a})),d.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(d.get(s)?.unsubscribe(),d.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function _(){return p(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!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)||l(r,i,()=>s(t))})},"xstate.listener")}const f=_();function v(){return p(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:o,snapshot:n}=e;return t.subscribe({next:t=>{"done"===t.status&&i?l(s,r,()=>i(t.output)):"error"===t.status&&o?l(s,r,()=>o(t.error)):"active"===t.status&&n&&l(s,r,()=>n(t))},error:t=>{o&&l(s,r,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const y=v();function m(t=this.source.system){return t.emitEvent(this.source,this.event)}function g(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function b(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 S(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function x(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:S,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function A(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:b,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function k(t,e,[s,r]){const o="done"===s.status||"error"===s.status,n="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||n||c?[s,r]:[s,[...r,A(t,s)]]}const w=()=>{},E=()=>({});function I(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:o,days:n,hours:c,minutes:a,seconds:h}=i.groups;if(!(o||n||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(o)*24*60*60*1e3+24*u(n)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:w,emit:w,log:w,raise:w,spawn:E,sendTo:w,stop:w,listen:E,subscribeTo:E,...t})}({},w);const T=new WeakMap,R=new WeakMap,M=new Map;function O(t){t._snapshotVersion++}function P(t){return t._snapshotVersion}function L(t){const e=T.get(t);if(e)return e;const s=R.get(t);if(!s)return;const r=s();return T.set(t,r),R.delete(t),r}function j(t,e,s=e.system,r){R.delete(t);const i=P(s),o=r?L(r):void 0,n=o?.actor===e?o:L(t);if(n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion===i)return void T.set(t,n);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)??M:t.keyedActors}(s);let u=h.size?new Map(h):M;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===M&&(u=new Map),u.set(t,e))}T.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function $(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)}}async function K(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;if("active"===i?.status)return function(t,e){return new Promise((s,r)=>{const i=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(i.unsubscribe(),s(o.output)):"error"===o?.status&&(i.unsubscribe(),r(o.error))})})}(t,e);r({type:c,key:e});try{const t=await s();return r({type:o,key:e,output:t}),t}catch(t){throw r({type:n,key:e,error:t}),t}}function C(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}let z,D=0;const W=new Error("Transition effect"),V=[];function N(){return z??=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)}`}(),`${z}:${(D++).toString(36)}`}function U(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function H(t,e){return`${t?t.address:""}|${e}`}function q(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},O(t))}function B(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?q(t,H(s?.parent,r.prefix),r.index+1):s?.parent||q(t,H(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&&"(machine)"!==e?e:"x"}(s?.src),i=H(s?.parent,r),o=t._snapshot._nextActorIds[i]??0;return q(t,i,o+1),s?.parent||"x"===r||0!==o?`${r}:${o}`:r}const F=Object.freeze({});function J(t,e){return`${t.sessionId}.${e}`}class X{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={systemId:N(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef,this._snapshot={_scheduledTimers:s?.scheduler??F,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=J(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const o=this._clock.now?.()??Date.now(),n={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},c=J(t,e);this._snapshot._scheduledTimers===F&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=n,O(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],O(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=J(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==F&&delete this._snapshot._scheduledTimers[s],O(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.id)}}_deliver(t,e,s){!function(t,e,s){C(t,e,s);const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),O(this),t}_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&&O(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&O(this)}inspect(t){const e=$(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}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){C(t,e,s),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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:r});const i=this.runtime?.deadLetter;if(i)return i(t,e,s,r)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):K(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(V.length&&V.includes(e))throw W;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,id:o}=t[s];this.scheduleTimer(r,o,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let G=!1;const Q=Object.freeze([]);let Y=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Z=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function tt(t,e){try{t?.(e)}catch(t){h(t)}}function et(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function st(t,e){return new rt(t,e)}class rt{get address(){return this._address??=this._parent?`${this._parent.address}/${U(this.id)}`:U(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.eventListeners=void 0,this.logger=void 0,this._processingStatus=Y.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;const s=e?{...Z,...e}:Z,{clock:r,logger:i,parent:o,syncSnapshot:n,id:c,registryKey:a,inspect:h}=s;var u;this.system=o?o.system:s._systemRef?.current??function(t,e){return new X(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot??s.state,createActorRef:st}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!o&&this.system.inspect($(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=B(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=n,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=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=k(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({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=>this.system.emitEvent(this,t);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===Y.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=G;try{G=!0,t.exec()}finally{G=e}};this._processingStatus!==Y.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,j(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=k(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),et(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Q)tt(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??Q,actions:this._collectedActions??Q,sent:this._collectedSent??Q,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 et(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=$(t,e,s);if(this._processingStatus!==Y.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":tt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?tt(r.error,t):h(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 o=$(s,r,i);let n=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(n,r)||(n=r,o.next?.(r))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Y.Running)return this;if(this._processingStatus===Y.Stopped)return this;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=Y.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,a(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),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,a(this.options.input)):(function(t,e,s){const r=T.get(t),i=P(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=k(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let i=this._snapshot;try{const[s,r]=e;i=s,this._setSnapshot(i),et(r,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)tt(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===Y.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Y.NotStarted?(this._processingStatus=Y.Stopped,this.system._unregister(this),this):(this._send({type:r}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??Q)tt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const r=s.error;e||=!r,tt(r,t)}this.observers.clear(),e&&h(t)}else this._parent||h(t);var e,s,r;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,r=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:r}))}_stopProcedure(){this._processingStatus===Y.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Y.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Y.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function it(t,e){const s=t.check(e);if(s)throw s}const ot=new WeakMap;function nt(t,e,s){const r=function(t){let e=ot.get(t);return e||(e=new Map,ot.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 ct(t){const e=(e,s,i)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[g("xstate.logic.cleanup",()=>function(t){const e=ot.get(t);if(e){for(const{cleanup:t}of e.values())t?.();ot.delete(t)}}(i.self))]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===o)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===n)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const a=[],h={},u={emit:t=>{a.push(function(t,e){return{kind:"emit",exec:m,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(i,t))},sendBack:t=>{const e=i.self._parent;e&&a.push(x(i,e,t))},raise:t=>{a.push(x(i,i.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(a.push(g("xstate.logic.effect",(e=i.self.system)=>nt(i.self,t,()=>s(e)),{key:t})),h[t]={status:"active"})})(t,s);const r=t;a.push(g("xstate.logic.effect",(t=i.self.system)=>nt(i.self,void 0,()=>r(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:i.system,self:i.self,emit:i.emit},u),p={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(p.context=d?.context??e.context),(d?.effects||Object.keys(h).length)&&(p.effects={...e.effects,...d?.effects,...h}),k(i,e,[p,a])},s=(s,r,o)=>{t.validator&&it(t.validator,{kind:"event",logic:i,event:r,eventOrigin:o.self._lastSourceRef?"actor":"external"});const n=e(s,r,o);return t.validator&&it(t.validator,{kind:"result",logic:i,snapshot:n[0],effects:n[1]}),n},i={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,o]=s(t,a(t.input),e);Object.assign(t,i);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&it(t.validator,{kind:"input",logic:i,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),n={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(n.context=o),s({...n},a(e),r)},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return i}const at=new WeakMap;const ht="xstate.observable.next",ut="xstate.observable.error",dt="xstate.observable.complete";const pt="xstate.async.resolve",lt="xstate.async.reject";class _t extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const ft=ct({context:void 0,run:()=>{}});t.TimeoutError=_t,t.createAsyncLogic=function(t){const e=t;return ct({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:o},n)=>{switch(t.type){case pt:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case lt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return n.effect((t=o)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=I(a),u=void 0===h?void 0:o._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),n({type:lt,data:new _t(a)}))},h),d=()=>{void 0!==u&&o._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:o,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):K(s,e,r,n)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&n({type:pt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&n({type:lt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:o,system:n}=t,c=t.emit,a=at.get(o);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return at.set(o,t),t.dispose=e({input:i,system:n,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&n._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{at.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return new rt(ft,t);var t},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case ut:return k(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case dt:return k(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&it(s,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.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:ut,data:t})},complete:()=>{r._relay(s,s,{type:dt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=_,t.createLogic=ct,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:o,self:n,system:c}=t;switch(i.type){case ht:return{context:i.data};case ut:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case dt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=n,r=e=>{t.sendEvent(s,s,e)},i=e({input:o,system:c,self:n,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:ht,data:t})},error:t=>{r({type:ut,data:t})},complete:()=>{r({type:dt})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=v,t.listenerLogic=f,t.subscriptionLogic=y,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";class e{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}const s="@xstate.init",r="@xstate.stop",i="@xstate.terminate",o="xstate.logic.effect.resolve",n="xstate.logic.effect.reject",c="xstate.logic.effect.start";function a(t){return{type:s,input:t}}function h(t){setTimeout(()=>{throw t})}const u="function"==typeof Symbol&&Symbol.observable||"@@observable";const d=new WeakMap;function p(t,e){const s=(t,e)=>[{status:"active",output:void 0,error:void 0,input:t},[]];return{id:e,start:(e,{self:s,system:r})=>{const i=e.input.actor;if(!i||"stopped"===i.getSnapshot().status)return;const o=t(e.input,{self:s,system:r});if(!o)return;let n,c=!1;const a=()=>{c||(c=!0,o.unsubscribe(),n?.unsubscribe())},h=s._parent;h&&(n=h.subscribe({complete:a,error:a})),d.set(s,{unsubscribe:a})},transition:(t,e,{self:s})=>e.type===r?(d.get(s)?.unsubscribe(),d.delete(s),[{...t,status:"stopped",error:void 0},[]]):[t,[]],initialTransition:s,getInitialSnapshot:(t,e)=>s(e)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t}}function l(t,e,s){"stopped"!==t.getSnapshot().status&&t._parent&&e._relay(t,t._parent,s())}function _(){return p(({actor:t,eventType:e,mapper:s},{self:r,system:i})=>{const o="*"!==e&&e.endsWith(".*");return t.on(o?"*":e,t=>{o&&!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)||l(r,i,()=>s(t))})},"xstate.listener")}const f=_();function v(){return p(({actor:t,mappers:e},{self:s,system:r})=>{const{done:i,error:o,snapshot:n}=e;return t.subscribe({next:t=>{"done"===t.status&&i?l(s,r,()=>i(t.output)):"error"===t.status&&o?l(s,r,()=>o(t.error)):"active"===t.status&&n&&l(s,r,()=>n(t))},error:t=>{o&&l(s,r,()=>o(t))},complete:()=>{}})},"xstate.subscription")}const y=v();function m(t=this.source.system){return t.emitEvent(this.source,this.event)}function g(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function b(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 S(t=this.source.system){return function(t){if("string"==typeof t)throw new Error("Only event objects may be used with sendTo")}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,this.id,this.delay):t.sendEvent(this.source,this.target,this.event)}function x(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:S,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function A(t,e){if("done"!==e.status&&"error"!==e.status)throw new Error("Cannot terminate an active or stopped actor");const s="done"===e.status?{status:"done",output:e.output,error:void 0}:{status:"error",output:void 0,error:e.error},r=[t.self,s];return{kind:"builtin",exec:b,type:i,source:t.self,actor:t.self,id:t.self.id,...s,params:void 0,args:r}}function k(t,e,[s,r]){const o="done"===s.status||"error"===s.status,n="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===i);return!o||n||c?[s,r]:[s,[...r,A(t,s)]]}const w=()=>{},E=()=>({});function I(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:o,days:n,hours:c,minutes:a,seconds:h}=i.groups;if(!(o||n||c||a||h))return;const u=t=>t?Number(t.replace(",",".")):0;return 7*u(o)*24*60*60*1e3+24*u(n)*60*60*1e3+60*u(c)*60*1e3+60*u(a)*1e3+1e3*u(h)}(t)}!function(t,e){const s=(t,...s)=>{e(t,...s)};Object.assign(s,{cancel:w,emit:w,log:w,raise:w,spawn:E,sendTo:w,stop:w,listen:E,subscribeTo:E,...t})}({},w);const T=new WeakMap,R=new WeakMap,M=new Map;function O(t){t._snapshotVersion++}function P(t){return t._snapshotVersion}function L(t){const e=T.get(t);if(e)return e;const s=R.get(t);if(!s)return;const r=s();return T.set(t,r),R.delete(t),r}function j(t,e,s=e.system,r){R.delete(t);const i=P(s),o=r?L(r):void 0,n=o?.actor===e?o:L(t);if(n?.actor===e&&n.systemState.sourceSystem===s&&n.systemState.sourceVersion===i)return void T.set(t,n);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)??M:t.keyedActors}(s);let u=h.size?new Map(h):M;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===M&&(u=new Map),u.set(t,e))}T.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function $(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)}}async function K(t,e,s,r=e=>{t.system.sendEvent(t,t,e)}){const i=function(t,e){return t.getSnapshot().effects?.[e]}(t,e);if("done"===i?.status)return i.output;if("error"===i?.status)throw i.error;if("active"===i?.status)return function(t,e){return new Promise((s,r)=>{const i=t.subscribe(t=>{const o=t.effects?.[e];"done"===o?.status?(i.unsubscribe(),s(o.output)):"error"===o?.status&&(i.unsubscribe(),r(o.error))})})}(t,e);r({type:c,key:e});try{const t=await s();return r({type:o,key:e,output:t}),t}catch(t){throw r({type:n,key:e,error:t}),t}}function C(t,e,s){const r=e;if(t!==e&&r.logic?.isInternalEventType?.(s.type))throw new Error(`Internal event "${s.type}" cannot be sent to actor "${e.id}" from outside.`)}let z,D=0;const W=new Error("Transition effect"),V=[];function N(){return z??=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)}`}(),`${z}:${(D++).toString(36)}`}function U(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function H(t,e){return`${t?t.address:""}|${e}`}function q(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},O(t))}function B(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?q(t,H(s?.parent,r.prefix),r.index+1):s?.parent||q(t,H(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&&"(machine)"!==e?e:"x"}(s?.src),i=H(s?.parent,r),o=t._snapshot._nextActorIds[i]??0;return q(t,i,o+1),s?.parent||"x"===r||0!==o?`${r}:${o}`:r}const F=Object.freeze({});function J(t,e){return`${t.sessionId}.${e}`}class X{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={systemId:N(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0;const s="object"==typeof e.snapshot&&null!==e.snapshot?e.snapshot:void 0;this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const r=void 0;this._snapshot={_scheduledTimers:s?.scheduler??F,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const o=t;(o._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=J(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}const o=this._clock.now?.()??Date.now(),n={source:t,delay:s,id:e,scheduledAt:o,dueAt:o+s},c=J(t,e);this._snapshot._scheduledTimers===F&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[c]=n,O(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[c],delete this._snapshot._scheduledTimers[c],O(this),this._deliver(t,t,{type:"xstate.timer",id:e})},s);(this._timerMap??={})[c]=a}cancel(t,e){const s=J(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==F&&delete this._snapshot._scheduledTimers[s],O(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.id)}}_deliver(t,e,s){!function(t,e,s){C(t,e,s);const r=e;r._lastSourceRef=t,r._send(s)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),O(this),t}_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&&O(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,e){const s=this._keyedActors?.get(t);if(s&&s!==e)throw new Error(`Actor with registry key '${t}' already exists.`);(this._keyedActors??=new Map).set(t,e),(this._reverseKeyedActors??=new WeakMap).set(e,t),s!==e&&O(this)}inspect(t){const e=$(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>t.next?.(e))}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){C(t,e,s),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){this._sendInspectionEvent({type:"@xstate.deadletter",actorRef:e,sourceRef:t,event:s,reason:r});const i=this.runtime?.deadLetter;if(i)return i(t,e,s,r)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):K(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=t.getSnapshot()?.timers?.[e];if(i){const r="self"===i.target?t:i.target;this._recordSent(t,r,i.event,s,e)}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(V.length&&V.includes(e))throw W;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,id:o}=t[s];this.scheduleTimer(r,o,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let G=!1;const Q=Object.freeze([]);let Y=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Z=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function tt(t,e){try{t?.(e)}catch(t){h(t)}}function et(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function st(t,e){return new rt(t,e)}class rt{get address(){return this._address??=this._parent?`${this._parent.address}/${U(this.id)}`:U(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.eventListeners=void 0,this.logger=void 0,this._processingStatus=Y.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;const s=e?{...Z,...e}:Z,{clock:r,logger:i,parent:o,syncSnapshot:n,id:c,registryKey:a,inspect:h}=s;var u;this.system=o?o.system:s._systemRef?.current??function(t,e){return new X(t,e)}(this,{clock:r,logger:i,snapshot:s.snapshot??s.state,createActorRef:st}),o||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system),h&&!o&&this.system.inspect($(h)),this.sessionId=s._sessionId??`${(u=this.system)._identity.systemId}:${u._identity.nextSessionId++}`,this.id=B(this.system,c,{parent:o,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=o,this._syncSnapshot=n,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=e?.snapshot??e?.state;this._restored=void 0!==d;try{if(d)this._setSnapshot(this.logic.restoreSnapshot?this.logic.restoreSnapshot(d,this._actorScope):d);else if(e?._inert);else{const[t,e]=k(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({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=>this.system.emitEvent(this,t);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===Y.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(`Cannot stop non-child actor ${t.id}`);t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=G;try{G=!0,t.exec()}finally{G=e}};this._processingStatus!==Y.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,j(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=k(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),et(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??Q)tt(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??Q,actions:this._collectedActions??Q,sent:this._collectedSent??Q,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 et(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=$(t,e,s);if(this._processingStatus!==Y.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":tt(r.complete);break;case"error":{const t=this._snapshot.error;r.error?tt(r.error,t):h(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 o=$(s,r,i);let n=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(n,r)||(n=r,o.next?.(r))},error:o.error,complete:o.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===Y.Running)return this;if(this._processingStatus===Y.Stopped)return this;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=Y.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,a(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),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,a(this.options.input)):(function(t,e,s){const r=T.get(t),i=P(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 Object.values(t)){const t=e&&void 0!==r.startedAt?Math.min(r.delay,Math.max(0,r.startedAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,r.id,t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){let e,s;try{e=k(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){s={err:t}}if(s)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(s.err)||this._inspectTransition(this._snapshot,t));if(!e)return;let i=this._snapshot;try{const[s,r]=e;i=s,this._setSnapshot(i),et(r,this._actorScope),this.update(i,t)}catch(e){return void(this._recoverOrError(e,i)||this._inspectTransition(this._snapshot,t))}t.type===r&&(this._stopProcedure(),this._complete())}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)tt(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===Y.Stopped?this:(this.mailbox?.clear(),this._processingStatus===Y.NotStarted?(this._processingStatus=Y.Stopped,this.system._unregister(this),this):(this._send({type:r}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const t of this.observers??Q)tt(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_error(t){if(this._stopProcedure(),this.observers?.size){let e=!1;for(const s of this.observers){const r=s.error;e||=!r,tt(r,t)}this.observers.clear(),e&&h(t)}else this._parent||h(t);var e,s,r;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(e=this.id,s=t,r=this.sessionId,{type:"xstate.error.actor",error:s,actorId:e,sessionId:r}))}_stopProcedure(){this._processingStatus===Y.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=Y.Stopped,this.system._unregister(this))}_send(t){if(this._processingStatus===Y.Stopped)return void this.system.deadLetter(this._lastSourceRef,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new e(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue(t)}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{xstate$type:"actorRef",id:this.id,address:this.address,src:"string"==typeof this.src?this.src:void 0}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[u](){return this}getSnapshot(){return this._snapshot}}function it(t,e){const s=t.check(e);if(s)throw s}const ot=new WeakMap;function nt(t,e,s){const r=function(t){let e=ot.get(t);return e||(e=new Map,ot.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 ct(t){const e=(e,s,i)=>{if("active"!==e.status)return[e,[]];if(s.type===r)return[{...e,status:"stopped",input:void 0},[g("xstate.logic.cleanup",()=>function(t){const e=ot.get(t);if(e){for(const{cleanup:t}of e.values())t?.();ot.delete(t)}}(i.self))]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===o)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===n)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const a=[],h={},u={emit:t=>{a.push(function(t,e){return{kind:"emit",exec:m,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(i,t))},sendBack:t=>{const e=i.self._parent;e&&a.push(x(i,e,t))},raise:t=>{a.push(x(i,i.self,t))},effect:(t,s)=>{if("string"==typeof t)return void((t,s)=>{e.effects?.[t]||(a.push(g("xstate.logic.effect",(e=i.self.system)=>nt(i.self,t,()=>s(e)),{key:t})),h[t]={status:"active"})})(t,s);const r=t;a.push(g("xstate.logic.effect",(t=i.self.system)=>nt(i.self,void 0,()=>r(t))))}},d=t.run({context:e.context,event:s,input:e.input,system:i.system,self:i.self,emit:i.emit},u),p={...e,...d||{}};return("context"in e||void 0!==d?.context)&&(p.context=d?.context??e.context),(d?.effects||Object.keys(h).length)&&(p.effects={...e.effects,...d?.effects,...h}),k(i,e,[p,a])},s=(s,r,o)=>{t.validator&&it(t.validator,{kind:"event",logic:i,event:r,eventOrigin:o.self._lastSourceRef?"actor":"external"});const n=e(s,r,o);return t.validator&&it(t.validator,{kind:"result",logic:i,snapshot:n[0],effects:n[1]}),n},i={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,o]=s(t,a(t.input),e);Object.assign(t,i);for(const t of o)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&it(t.validator,{kind:"input",logic:i,input:e});const o=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),n={status:"active",output:void 0,error:void 0,input:e};return void 0!==o&&(n.context=o),s({...n},a(e),r)},getInitialSnapshot:(t,e)=>i.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return i}const at=new WeakMap;const ht="xstate.observable.next",ut="xstate.observable.error",dt="xstate.observable.complete";const pt="xstate.async.resolve",lt="xstate.async.reject";class _t extends Error{constructor(t){super(`Async logic timed out after ${t}.`),this.name="TimeoutError"}}const ft=ct({context:void 0,run:()=>{}});t.TimeoutError=_t,t.createAsyncLogic=function(t){const e=t;return ct({id:e.id,validator:e.validator,schemas:e.schemas,context:void 0,run:({event:t,input:r,self:i,system:o},n)=>{switch(t.type){case pt:{const e=t.data??t.output;return{status:"done",output:e,input:void 0,effects:{async:{status:"done",output:e}}}}case lt:{const e=t.data??t.error;return{status:"error",error:e,input:void 0,effects:{async:{status:"error",error:e}}}}}if(t.type===s)return n.effect((t=o)=>{const s=i,n=e=>{t.sendEvent(s,s,e)},c=new AbortController,a=e.timeout,h=I(a),u=void 0===h?void 0:o._clock.setTimeout(()=>{"active"===i.getSnapshot().status&&(c.abort(),n({type:lt,data:new _t(a)}))},h),d=()=>{void 0!==u&&o._clock.clearTimeout(u)},p=()=>Promise.resolve(e.run({input:r,system:o,self:i,signal:c.signal},{emit:e=>{t.emitEvent(s,e)},step:(e,r)=>t.runStep?Promise.resolve(t.runStep(s,e,r)):K(s,e,r,n)}));return(t.runLogic?Promise.resolve(t.runLogic(s,p)):p()).then(t=>{d(),"active"===i.getSnapshot().status&&n({type:pt,data:t})},t=>{d(),"active"===i.getSnapshot().status&&n({type:lt,data:t})}),()=>{c.abort(),d()}}),{effects:{async:{status:"active"}}}}})},t.createCallbackLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:s,context:void 0,run:(t,s)=>{const{event:r,input:i,self:o,system:n}=t,c=t.emit,a=at.get(o);a?.receivers?.forEach(t=>t(r)),s.effect("callback",()=>{const t={receivers:void 0,dispose:void 0};return at.set(o,t),t.dispose=e({input:i,system:n,self:o,sendBack:t=>{if("stopped"===o.getSnapshot().status)return;const e=o._parent;e&&n._relay(o,e,t)},receive:e=>{t.receivers??=new Set,t.receivers.add(e)},emit:c}),()=>{at.delete(o),t.receivers?.clear(),t.dispose?.()}})}})},t.createEmptyActor=function(){return new rt(ft,t);var t},t.createEventObservableLogic=function(t){const e="function"==typeof t?t:t.run,s="function"==typeof t?void 0:t.validator,i={config:t,validator:s,transition:(t,e,s)=>{if("active"!==t.status)return[t,[]];switch(e.type){case ut:return k(s,t,[{...t,status:"error",error:e.data,input:void 0,_subscription:void 0},[]]);case dt:return k(s,t,[{...t,status:"done",input:void 0,_subscription:void 0},[]]);case r:return t._subscription.unsubscribe(),[{...t,status:"stopped",input:void 0,_subscription:void 0},[]];default:return[t,[]]}},initialTransition:(t,e)=>{s&&it(s,{kind:"input",logic:i,input:t});return[{status:"active",output:void 0,error:void 0,context:void 0,input:t,_subscription:void 0},[]]},getInitialSnapshot:(t,e)=>i.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:ut,data:t})},complete:()=>{r._relay(s,s,{type:dt})}}))},getPersistedSnapshot:({_subscription:t,...e})=>e,restoreSnapshot:t=>({...t,_subscription:void 0})};return i},t.createListenerLogic=_,t.createLogic=ct,t.createObservableLogic=function(t){const e="function"==typeof t?t:t.run,r="function"==typeof t?void 0:t.schemas;return ct({validator:"function"==typeof t?void 0:t.validator,schemas:r,context:void 0,run:(t,r)=>{const{event:i,input:o,self:n,system:c}=t;switch(i.type){case ht:return{context:i.data};case ut:return{status:"error",error:i.data,input:void 0,effects:{observable:{status:"error",error:i.data}}};case dt:return{status:"done",input:void 0,effects:{observable:{status:"done"}}}}i.type===s&&r.effect((t=c)=>{const s=n,r=e=>{t.sendEvent(s,s,e)},i=e({input:o,system:c,self:n,emit:e=>{t.emitEvent(s,e)}}).subscribe({next:t=>{r({type:ht,data:t})},error:t=>{r({type:ut,data:t})},complete:()=>{r({type:dt})}});return()=>i.unsubscribe()})}})},t.createSubscriptionLogic=v,t.listenerLogic=f,t.subscriptionLogic=y,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=xstate-actors.umd.min.js.map