xstate 6.0.0-beta.1 → 6.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{createActor-551369be.development.esm.js → createActor-0250284a.development.esm.js} +244 -41
- package/dist/{createActor-cbe3abac.esm.js → createActor-20a97166.esm.js} +243 -40
- package/dist/{createActor-a49ae0ce.development.cjs.js → createActor-c029d29f.development.cjs.js} +245 -40
- package/dist/{createActor-25900f76.cjs.js → createActor-c91c9ffe.cjs.js} +244 -39
- package/dist/declarations/src/createActor.d.ts +3 -1
- package/dist/declarations/src/createMachine.d.ts +6 -3
- package/dist/declarations/src/durable/index.d.ts +43 -8
- package/dist/declarations/src/effectDescriptor.d.ts +2 -2
- package/dist/declarations/src/machineVersion.types.d.ts +2 -2
- package/dist/declarations/src/setup.d.ts +2 -2
- package/dist/declarations/src/systemTransition.d.ts +1 -1
- package/dist/declarations/src/types.d.ts +4 -2
- package/dist/declarations/src/types.v6.d.ts +37 -2
- package/dist/{effectDescriptor-f73da4ec.development.cjs.js → effectDescriptor-3fff5c51.development.cjs.js} +5 -5
- package/dist/{effectDescriptor-2fa27c54.cjs.js → effectDescriptor-47f73e7e.cjs.js} +5 -5
- package/dist/{effectDescriptor-321a8ce9.development.esm.js → effectDescriptor-5ac7dccb.development.esm.js} +5 -5
- package/dist/{effectDescriptor-d8b0f749.esm.js → effectDescriptor-e93df910.esm.js} +5 -5
- package/dist/{machineSchemas-88d01821.cjs.js → legacySnapshot-8d595687.cjs.js} +117 -1
- package/dist/{machineSchemas-45c21bc2.esm.js → legacySnapshot-9e06feb4.esm.js} +116 -2
- package/dist/{machineSchemas-b5736804.development.esm.js → legacySnapshot-ae6594a7.development.esm.js} +117 -3
- package/dist/{machineSchemas-6d96bef4.development.cjs.js → legacySnapshot-ebf0b2b8.development.cjs.js} +118 -2
- package/dist/xstate-actors.cjs.js +1 -1
- package/dist/xstate-actors.development.cjs.js +1 -1
- package/dist/xstate-actors.development.esm.js +2 -2
- package/dist/xstate-actors.esm.js +2 -2
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.js +120 -10
- package/dist/xstate-durable.development.cjs.js +120 -10
- package/dist/xstate-durable.development.esm.js +120 -10
- package/dist/xstate-durable.esm.js +120 -10
- package/dist/xstate-durable.umd.min.js +1 -1
- package/dist/xstate-durable.umd.min.js.map +1 -1
- package/dist/xstate-fsm.cjs.js +4 -4
- package/dist/xstate-fsm.development.cjs.js +4 -4
- package/dist/xstate-fsm.development.esm.js +4 -4
- package/dist/xstate-fsm.esm.js +4 -4
- package/dist/xstate-fsm.umd.min.js +1 -1
- package/dist/xstate-fsm.umd.min.js.map +1 -1
- package/dist/xstate-graph.cjs.js +1 -1
- package/dist/xstate-graph.development.cjs.js +1 -1
- package/dist/xstate-graph.development.esm.js +2 -2
- package/dist/xstate-graph.esm.js +2 -2
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.js +23 -12
- package/dist/xstate-persist.development.cjs.js +23 -12
- package/dist/xstate-persist.development.esm.js +17 -6
- package/dist/xstate-persist.esm.js +17 -6
- package/dist/xstate-persist.umd.min.js +1 -1
- package/dist/xstate-persist.umd.min.js.map +1 -1
- package/dist/xstate-validation.cjs.js +1 -1
- package/dist/xstate-validation.development.cjs.js +1 -1
- package/dist/xstate-validation.development.esm.js +1 -1
- package/dist/xstate-validation.esm.js +1 -1
- package/dist/xstate.cjs.js +63 -51
- package/dist/xstate.development.cjs.js +63 -51
- package/dist/xstate.development.esm.js +53 -41
- package/dist/xstate.esm.js +53 -41
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/api-stability.json +267 -249
- package/docs/backend-workflows.md +3 -3
- package/docs/durable-execution.md +72 -48
- package/docs/errors.md +2 -2
- package/docs/examples.md +34 -34
- package/docs/fsm.md +2 -1
- package/docs/guards.md +1 -1
- package/docs/index.md +1 -1
- package/docs/invoke.md +34 -2
- package/docs/persistence.md +16 -10
- package/docs/serialization.md +1 -1
- package/docs/setup-and-provide.md +3 -3
- package/docs/spawn.md +1 -1
- package/docs/system-transitions.md +6 -6
- package/docs/tutorial.md +5 -5
- package/docs/typescript.md +9 -0
- package/docs/xstate-v5-to-v6.md +17 -17
- package/package.json +1 -1
package/dist/xstate-fsm.cjs.js
CHANGED
|
@@ -76,7 +76,7 @@ function createFSM(config) {
|
|
|
76
76
|
value,
|
|
77
77
|
context
|
|
78
78
|
} = snapshot;
|
|
79
|
-
const transitions = config.states[value]?.on;
|
|
79
|
+
const transitions = (Object.hasOwn(config.states, value) ? config.states[value] : undefined)?.on;
|
|
80
80
|
const transition = Object.hasOwn(transitions || {}, event.type) && transitions[event.type];
|
|
81
81
|
const {
|
|
82
82
|
target = value,
|
|
@@ -91,10 +91,10 @@ function createFSM(config) {
|
|
|
91
91
|
// current snapshot. After the first copy every key matches. Iterate a
|
|
92
92
|
// spread copy so inherited keys, which the spread below ignores, are
|
|
93
93
|
// skipped.
|
|
94
|
-
for (const key
|
|
94
|
+
for (const key of Reflect.ownKeys({
|
|
95
95
|
...patch
|
|
96
|
-
}) {
|
|
97
|
-
if (patch[key]
|
|
96
|
+
})) {
|
|
97
|
+
if (!Object.hasOwn(context, key) || !Object.is(patch[key], context[key])) {
|
|
98
98
|
context = {
|
|
99
99
|
...context,
|
|
100
100
|
...patch
|
|
@@ -76,7 +76,7 @@ function createFSM(config) {
|
|
|
76
76
|
value,
|
|
77
77
|
context
|
|
78
78
|
} = snapshot;
|
|
79
|
-
const transitions = config.states[value]?.on;
|
|
79
|
+
const transitions = (Object.hasOwn(config.states, value) ? config.states[value] : undefined)?.on;
|
|
80
80
|
const transition = Object.hasOwn(transitions || {}, event.type) && transitions[event.type];
|
|
81
81
|
const {
|
|
82
82
|
target = value,
|
|
@@ -91,10 +91,10 @@ function createFSM(config) {
|
|
|
91
91
|
// current snapshot. After the first copy every key matches. Iterate a
|
|
92
92
|
// spread copy so inherited keys, which the spread below ignores, are
|
|
93
93
|
// skipped.
|
|
94
|
-
for (const key
|
|
94
|
+
for (const key of Reflect.ownKeys({
|
|
95
95
|
...patch
|
|
96
|
-
}) {
|
|
97
|
-
if (patch[key]
|
|
96
|
+
})) {
|
|
97
|
+
if (!Object.hasOwn(context, key) || !Object.is(patch[key], context[key])) {
|
|
98
98
|
context = {
|
|
99
99
|
...context,
|
|
100
100
|
...patch
|
|
@@ -72,7 +72,7 @@ function createFSM(config) {
|
|
|
72
72
|
value,
|
|
73
73
|
context
|
|
74
74
|
} = snapshot;
|
|
75
|
-
const transitions = config.states[value]?.on;
|
|
75
|
+
const transitions = (Object.hasOwn(config.states, value) ? config.states[value] : undefined)?.on;
|
|
76
76
|
const transition = Object.hasOwn(transitions || {}, event.type) && transitions[event.type];
|
|
77
77
|
const {
|
|
78
78
|
target = value,
|
|
@@ -87,10 +87,10 @@ function createFSM(config) {
|
|
|
87
87
|
// current snapshot. After the first copy every key matches. Iterate a
|
|
88
88
|
// spread copy so inherited keys, which the spread below ignores, are
|
|
89
89
|
// skipped.
|
|
90
|
-
for (const key
|
|
90
|
+
for (const key of Reflect.ownKeys({
|
|
91
91
|
...patch
|
|
92
|
-
}) {
|
|
93
|
-
if (patch[key]
|
|
92
|
+
})) {
|
|
93
|
+
if (!Object.hasOwn(context, key) || !Object.is(patch[key], context[key])) {
|
|
94
94
|
context = {
|
|
95
95
|
...context,
|
|
96
96
|
...patch
|
package/dist/xstate-fsm.esm.js
CHANGED
|
@@ -72,7 +72,7 @@ function createFSM(config) {
|
|
|
72
72
|
value,
|
|
73
73
|
context
|
|
74
74
|
} = snapshot;
|
|
75
|
-
const transitions = config.states[value]?.on;
|
|
75
|
+
const transitions = (Object.hasOwn(config.states, value) ? config.states[value] : undefined)?.on;
|
|
76
76
|
const transition = Object.hasOwn(transitions || {}, event.type) && transitions[event.type];
|
|
77
77
|
const {
|
|
78
78
|
target = value,
|
|
@@ -87,10 +87,10 @@ function createFSM(config) {
|
|
|
87
87
|
// current snapshot. After the first copy every key matches. Iterate a
|
|
88
88
|
// spread copy so inherited keys, which the spread below ignores, are
|
|
89
89
|
// skipped.
|
|
90
|
-
for (const key
|
|
90
|
+
for (const key of Reflect.ownKeys({
|
|
91
91
|
...patch
|
|
92
|
-
}) {
|
|
93
|
-
if (patch[key]
|
|
92
|
+
})) {
|
|
93
|
+
if (!Object.hasOwn(context, key) || !Object.is(patch[key], context[key])) {
|
|
94
94
|
context = {
|
|
95
95
|
...context,
|
|
96
96
|
...patch
|
|
@@ -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).XStateFSM={})}(this,function(t){"use strict";function e(t){const e=(t,e)=>({status:"active",value:t,context:e,output:void 0,error:void 0}),n=e(t.initial,t.context??{});return{id:t.id,config:t,initialState:n,initialTransition:()=>[n,[]],getInitialSnapshot:()=>n,getPersistedSnapshot:t=>t,transition(n,o){let{value:i,context:s}=n;const a=t.states[i]?.on,r=Object.hasOwn(a||{},o.type)&&a[o.type],{target:c=i,context:
|
|
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).XStateFSM={})}(this,function(t){"use strict";function e(t){const e=(t,e)=>({status:"active",value:t,context:e,output:void 0,error:void 0}),n=e(t.initial,t.context??{});return{id:t.id,config:t,initialState:n,initialTransition:()=>[n,[]],getInitialSnapshot:()=>n,getPersistedSnapshot:t=>t,transition(n,o){let{value:i,context:s}=n;const a=(Object.hasOwn(t.states,i)?t.states[i]:void 0)?.on,r=Object.hasOwn(a||{},o.type)&&a[o.type],{target:c=i,context:f}=("string"==typeof r?{target:r}:"function"==typeof r?r({context:s,event:o}):r)||{};for(const t of Reflect.ownKeys({...f}))Object.hasOwn(s,t)&&Object.is(f[t],s[t])||(s={...s,...f});return[c===i&&s===n.context?n:e(c,s),[]]}}}t.createFSM=e,t.setup=function(t={}){return{createFSM:t=>e(t)}},t.types=function(){return{"~standard":{version:1,vendor:"xstate.types",validate:t=>({value:t})}}},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-fsm.umd.min.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xstate-fsm.umd.min.js","sources":["../src/fsm.ts","../src/schema.types.ts"],"sourcesContent":["import type {\n EventObject,\n InferEvents,\n MachineContext,\n SetupSchemas,\n SetupStateSchema\n} from './base.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\n\n/** @public */\nexport type FSMArgs<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TEvent;\n};\n\n/** @public */\nexport type FSMContextPatch<TContext extends MachineContext> =\n Partial<TContext>;\n\n/** @public */\nexport type FSMTransitionConfig<\n TContext extends MachineContext,\n TState extends string\n> = {\n target?: TState;\n context?: FSMContextPatch<TContext>;\n};\n\n/** @public */\nexport type FSMTransitionFunction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = (\n args: FSMArgs<TContext, TEvent>\n) => FSMTransitionConfig<TTransitionContext, TState> | undefined;\n\ntype EventForType<TEvent extends EventObject, TType extends string> = [\n Extract<TEvent, { type: TType }>\n] extends [never]\n ? TEvent\n : Extract<TEvent, { type: TType }>;\n\n/** @public */\nexport type FSMTransition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> =\n | TState\n | FSMTransitionConfig<TTransitionContext, TState>\n | FSMTransitionFunction<TContext, TEvent, TState, TTransitionContext>;\n\ntype FSMOn<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = {\n [TType in TEvent['type'] & string]?: FSMTransition<\n TContext,\n EventForType<TEvent, TType>,\n TState,\n TTransitionContext\n >;\n};\n\n/** @public */\nexport type FSMStateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = {\n on?: FSMOn<TContext, TEvent, TState, TTransitionContext>;\n};\n\ntype FSMContextConfig<TContext extends MachineContext> =\n string extends keyof TContext\n ? { context?: TContext }\n : keyof TContext extends never\n ? { context?: TContext }\n : { context: TContext };\n\n/** @public */\nexport type FSMConfig<\n TContext extends MachineContext = {},\n TEvent extends EventObject = EventObject,\n TState extends string = string\n> = {\n id?: string;\n initial: TState;\n states: { [K in TState]: FSMStateConfig<TContext, TEvent, TState> };\n} & FSMContextConfig<TContext>;\n\ntype FSMConfigForStates<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends Record<string, unknown>\n> = Omit<\n FSMConfig<TContext, TEvent, keyof TStates & string>,\n 'initial' | 'states'\n> & {\n initial: keyof TStates & string;\n states: {\n [K in keyof TStates]: FSMStateConfig<\n TContext,\n TEvent,\n keyof TStates & string\n >;\n };\n};\n\n/**\n * A snapshot of a compact FSM. `status`, `output`, and `error` match the\n * snapshot shape shared by all actor logic, so an FSM can run in\n * `createActor`. An FSM snapshot is always `'active'`.\n *\n * @public\n */\nexport type FSMSnapshot<\n TContext extends MachineContext,\n TState extends string\n> = {\n status: 'active';\n value: TState;\n context: TContext;\n output: undefined;\n error: undefined;\n};\n\n/**\n * The result of an FSM transition: `[nextSnapshot, effects]`. FSMs have no\n * effects, so `effects` is always empty. The tuple matches the\n * `(snapshot, event) => [snapshot, effects]` protocol shared with full XState\n * actor logic.\n *\n * @public\n */\nexport type FSMTransitionResult<TSnapshot> = [\n nextSnapshot: TSnapshot,\n effects: never[]\n];\n\n/**\n * Pure logic returned by `createFSM`. It structurally satisfies `ActorLogic`,\n * so it works with `createActor`, `transition`, and `initialTransition` from\n * `xstate`.\n *\n * @public\n */\nexport type FSM<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TSnapshot extends FSMSnapshot<MachineContext, TState> = FSMSnapshot<\n TContext,\n TState\n >,\n TConfig = FSMConfig<TContext, TEvent, TState>\n> = {\n readonly id: string | undefined;\n readonly config: TConfig;\n readonly initialState: TSnapshot;\n transition(\n snapshot: TSnapshot,\n event: TEvent\n ): FSMTransitionResult<TSnapshot>;\n initialTransition(input?: unknown): FSMTransitionResult<TSnapshot>;\n getInitialSnapshot(actorScope?: unknown, input?: unknown): TSnapshot;\n getPersistedSnapshot(snapshot: TSnapshot): TSnapshot;\n};\n\ntype FSMSetupSchemas = Pick<SetupSchemas, 'context' | 'events'>;\ntype FSMSetupStates = Record<string, SetupStateSchema>;\n\ntype FSMSchemaContext<TSchema extends StandardSchemaV1> =\n StandardSchemaV1.InferOutput<TSchema> extends MachineContext\n ? StandardSchemaV1.InferOutput<TSchema>\n : MachineContext;\n\ntype FSMSetupContext<TSchemas extends FSMSetupSchemas> = TSchemas extends {\n context: infer TSchema extends StandardSchemaV1;\n}\n ? FSMSchemaContext<TSchema>\n : MachineContext;\n\ntype FSMSetupEvents<TSchemas extends FSMSetupSchemas> = TSchemas extends {\n events: infer TEventSchemas extends Record<string, StandardSchemaV1>;\n}\n ? InferEvents<TEventSchemas>\n : EventObject;\n\ntype FSMStateContext<\n TStateSchema,\n TGlobalContext extends MachineContext\n> = TStateSchema extends { schemas?: infer TSchemas }\n ? TSchemas extends {\n context?: infer TSchema extends StandardSchemaV1;\n }\n ? FSMSchemaContext<TSchema> &\n ([MachineContext] extends [TGlobalContext] ? unknown : TGlobalContext)\n : TGlobalContext\n : TGlobalContext;\n\ntype FSMContextFromDeclaredStates<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = {\n [K in keyof TStates & string]: FSMStateContext<TStates[K], TGlobalContext>;\n}[keyof TStates & string];\n\ntype FSMContextFromStates<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = [keyof TStates] extends [never]\n ? TGlobalContext\n : [MachineContext] extends [TGlobalContext]\n ? FSMContextFromDeclaredStates<TStates, TGlobalContext>\n : TGlobalContext | FSMContextFromDeclaredStates<TStates, TGlobalContext>;\n\ntype FSMSetupStateContext<\n TState extends string,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = TState extends keyof TStates\n ? FSMStateContext<TStates[TState], TGlobalContext>\n : TGlobalContext;\n\ntype FSMSetupSnapshot<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = [keyof TStates] extends [never]\n ? FSMSnapshot<TGlobalContext, keyof TMachineStates & string>\n : {\n [K in keyof TMachineStates & string]: FSMSnapshot<\n FSMSetupStateContext<K, TStates, TGlobalContext>,\n K\n >;\n }[keyof TMachineStates & string];\n\ntype FSMSetupTargetTransitionConfig<\n TSourceContext extends MachineContext,\n TTarget extends string,\n TTargetContext extends MachineContext\n> = [FSMRequiredTargetContextKeys<TSourceContext, TTargetContext>] extends [\n never\n]\n ? {\n target: TTarget;\n context?: FSMTargetContextPatch<TSourceContext, TTargetContext>;\n }\n : {\n target: TTarget;\n context: FSMTargetContextPatch<TSourceContext, TTargetContext>;\n };\n\ntype FSMRequiredTargetContextKeys<TSourceContext, TTargetContext> = {\n [K in keyof TTargetContext]-?: K extends keyof TSourceContext\n ? [TSourceContext[K]] extends [TTargetContext[K]]\n ? never\n : K\n : K;\n}[keyof TTargetContext];\n\ntype FSMTargetContextPatch<TSourceContext, TTargetContext> =\n Partial<TTargetContext> &\n Pick<\n TTargetContext,\n Extract<\n FSMRequiredTargetContextKeys<TSourceContext, TTargetContext>,\n string\n >\n >;\n\ntype FSMSetupTransitionConfig<\n TSourceContext extends MachineContext,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> =\n | { target?: undefined; context?: FSMContextPatch<TSourceContext> }\n | {\n [TTarget in keyof TStates & string]: FSMSetupTargetTransitionConfig<\n TSourceContext,\n TTarget,\n FSMSetupStateContext<TTarget, TStates, TGlobalContext>\n >;\n }[keyof TStates & string];\n\ntype FSMSetupStringTransition<\n TSourceContext extends MachineContext,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = {\n [TTarget in keyof TStates & string]: [TSourceContext] extends [\n FSMSetupStateContext<TTarget, TStates, TGlobalContext>\n ]\n ? TTarget\n : never;\n}[keyof TStates & string];\n\ntype FSMSetupTransitionFunction<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = (\n args: FSMArgs<TSourceContext, TEvent>\n) =>\n | FSMSetupTransitionConfig<TSourceContext, TStates, TGlobalContext>\n | undefined;\n\ntype FSMSetupTransition<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = [keyof TStates] extends [never]\n ? FSMTransition<TSourceContext, TEvent, keyof TMachineStates & string>\n :\n | FSMSetupStringTransition<TSourceContext, TStates, TGlobalContext>\n | FSMSetupTransitionConfig<TSourceContext, TStates, TGlobalContext>\n | FSMSetupTransitionFunction<\n TSourceContext,\n TEvent,\n TStates,\n TGlobalContext\n >;\n\ntype FSMSetupStateConfig<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = {\n on?: {\n [TType in TEvent['type'] & string]?: FSMSetupTransition<\n TSourceContext,\n EventForType<TEvent, TType>,\n TStates,\n TGlobalContext,\n TMachineStates\n >;\n };\n};\n\ntype FSMSetupMachineConfig<\n TSchemas extends FSMSetupSchemas,\n TStates extends FSMSetupStates,\n TMachineStates extends Record<string, unknown>\n> = {\n id?: string;\n initial: keyof TMachineStates & string;\n states: {\n [K in keyof TMachineStates]: FSMSetupStateConfig<\n FSMStateContext<\n K extends keyof TStates ? TStates[K] : {},\n FSMSetupContext<TSchemas>\n >,\n FSMSetupEvents<TSchemas>,\n TStates,\n FSMSetupContext<TSchemas>,\n TMachineStates\n >;\n };\n} & FSMContextConfig<FSMContextFromStates<TStates, FSMSetupContext<TSchemas>>>;\n\n/** @public */\nexport type FSMSetupConfig<\n TSchemas extends FSMSetupSchemas = {},\n TStates extends FSMSetupStates = {}\n> = {\n schemas?: TSchemas;\n states?: TStates;\n};\n\n/** @public */\nexport type FSMSetupReturn<\n TSchemas extends FSMSetupSchemas,\n TStates extends FSMSetupStates\n> = {\n createFSM<const TMachineStates extends Record<string, unknown>>(\n config: FSMSetupMachineConfig<TSchemas, TStates, TMachineStates>\n ): FSM<\n FSMContextFromStates<TStates, FSMSetupContext<TSchemas>>,\n FSMSetupEvents<TSchemas>,\n keyof TMachineStates & string,\n FSMSetupSnapshot<TStates, FSMSetupContext<TSchemas>, TMachineStates>,\n FSMSetupMachineConfig<TSchemas, TStates, TMachineStates>\n >;\n};\n\n/** @public */\nexport function setup<\n const TSchemas extends FSMSetupSchemas = {},\n const TStates extends FSMSetupStates = {}\n>(\n _config: FSMSetupConfig<TSchemas, TStates> = {}\n): FSMSetupReturn<TSchemas, TStates> {\n return {\n createFSM: (config: FSMConfig) => createFSM(config)\n } as unknown as FSMSetupReturn<TSchemas, TStates>;\n}\n\n/** @public */\nexport function createFSM<\n TContext extends MachineContext = {},\n TEvent extends EventObject = EventObject,\n const TStates extends Record<string, unknown> = Record<string, unknown>\n>(\n config: FSMConfigForStates<TContext, TEvent, TStates>\n): FSM<\n TContext,\n TEvent,\n keyof TStates & string,\n FSMSnapshot<TContext, keyof TStates & string>,\n FSMConfigForStates<TContext, TEvent, TStates>\n> {\n type TState = keyof TStates & string;\n type TSnapshot = FSMSnapshot<TContext, TState>;\n const createSnapshot = (value: TState, context: TContext) =>\n ({\n status: 'active',\n value,\n context,\n output: undefined,\n error: undefined\n }) as TSnapshot;\n const initialState = createSnapshot(\n config.initial,\n config.context ?? ({} as TContext)\n );\n\n return {\n id: config.id,\n config,\n initialState,\n initialTransition: () => [initialState, []],\n getInitialSnapshot: () => initialState,\n getPersistedSnapshot: (snapshot) => snapshot,\n transition(snapshot, event) {\n let { value, context } = snapshot;\n const transitions = config.states[value]?.on as\n | Record<string, FSMTransition<TContext, TEvent, TState> | undefined>\n | undefined;\n const transition =\n Object.hasOwn(transitions || {}, event.type) &&\n transitions![event.type];\n const { target = value, context: patch } =\n (typeof transition === 'string'\n ? { target: transition }\n : typeof transition === 'function'\n ? transition({ context, event })\n : transition) || {};\n // Copy only when the patch changes a value, so a no-op patch keeps the\n // current snapshot. After the first copy every key matches. Iterate a\n // spread copy so inherited keys, which the spread below ignores, are\n // skipped.\n for (const key in { ...patch }) {\n if (patch![key] !== context[key]) {\n context = { ...context, ...patch };\n }\n }\n\n return [\n target === value && context === snapshot.context\n ? snapshot\n : createSnapshot(target, context),\n []\n ];\n }\n };\n}\n","/**\n * The Standard Schema interface.\n *\n * @public\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\n/**\n * Schemas that can be declared for an individual state node.\n *\n * @public\n */\nexport type SetupStateSchemas = {\n /** Refines the machine's root context schema while this state is active. */\n context?: StandardSchemaV1;\n input?: StandardSchemaV1;\n /** The output emitted when this state node completes. */\n output?: StandardSchemaV1;\n};\n\n/**\n * A type-only Standard Schema produced by {@link types}.\n *\n * @public\n */\nexport interface TypeSchema<T> extends StandardSchemaV1<T, T> {\n readonly '~standard': StandardSchemaV1.Props<T, T> & {\n readonly vendor: 'xstate.types';\n };\n}\n\n/**\n * Declares schema types for inference only — no runtime validation.\n *\n * Use in a machine's `schemas` when you want TypeScript types without pulling\n * in a schema library like Zod. The returned value is a valid Standard Schema\n * whose validation is the identity function, so it carries types but never\n * rejects input.\n *\n * @example\n *\n * ```ts\n * import { createMachine, types } from 'xstate';\n *\n * const machine = createMachine({\n * schemas: {\n * context: types<{ count: number }>(),\n * events: {\n * inc: types<{ by: number }>(),\n * reset: types<void>()\n * }\n * },\n * context: { count: 0 }\n * // ...\n * });\n * ```\n *\n * Use `types<void>()` for events without a payload.\n * @public\n */\nexport function types<T>(): TypeSchema<T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'xstate.types',\n validate: (value) => ({ value: value as T })\n }\n };\n}\n\n/**\n * Returns true if the value is a type-only schema created by {@link types}.\n *\n * @public\n */\nexport function isTypeSchema(value: unknown): value is TypeSchema<unknown> {\n return (\n !!value &&\n typeof value === 'object' &&\n '~standard' in value &&\n (value as StandardSchemaV1)['~standard'].vendor === 'xstate.types'\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1;\n /** The vendor name of the schema library. */\n readonly vendor: string;\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>;\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined;\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output;\n /** The non-existent issues. */\n readonly issues?: undefined;\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>;\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string;\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey;\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input;\n /** The output type of the schema. */\n readonly output: Output;\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input'];\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output'];\n}\n"],"names":["createFSM","config","createSnapshot","value","context","status","output","undefined","error","initialState","initial","id","initialTransition","getInitialSnapshot","getPersistedSnapshot","snapshot","transition","event","transitions","states","on","Object","hasOwn","type","target","patch","key","_config","version","vendor","validate"],"mappings":"gPA6ZO,SAASA,EAKdC,GAUA,MAAMC,EAAiBA,CAACC,EAAeC,KACpC,CACCC,OAAQ,SACRF,QACAC,UACAE,YAAQC,EACRC,WAAOD,IAELE,EAAeP,EACnBD,EAAOS,QACPT,EAAOG,SAAY,CAAA,GAGrB,MAAO,CACLO,GAAIV,EAAOU,GACXV,SACAQ,eACAG,kBAAmBA,IAAM,CAACH,EAAc,IACxCI,mBAAoBA,IAAMJ,EAC1BK,qBAAuBC,GAAaA,EACpCC,UAAAA,CAAWD,EAAUE,GACnB,IAAId,MAAEA,EAAKC,QAAEA,GAAYW,EACzB,MAAMG,EAAcjB,EAAOkB,OAAOhB,IAAQiB,GAGpCJ,EACJK,OAAOC,OAAOJ,GAAe,CAAE,EAAED,EAAMM,OACvCL,EAAaD,EAAMM,OACfC,OAAEA,EAASrB,EAAOC,QAASqB,IACR,iBAAfT,EACJ,CAAEQ,OAAQR,GACY,mBAAfA,EACLA,EAAW,CAAEZ,UAASa,UACtBD,IAAe,GAKvB,IAAK,MAAMU,IAAO,IAAKD,GACjBA,EAAOC,KAAStB,EAAQsB,KAC1BtB,EAAU,IAAKA,KAAYqB,IAI/B,MAAO,CACLD,IAAWrB,GAASC,IAAYW,EAASX,QACrCW,EACAb,EAAesB,EAAQpB,GAC3B,GAEJ,EAEJ,uBA/EO,SAILuB,EAA6C,IAE7C,MAAO,CACL3B,UAAYC,GAAsBD,EAAUC,GAEhD,UC3VO,WACL,MAAO,CACL,YAAa,CACX2B,QAAS,EACTC,OAAQ,eACRC,SAAW3B,IAAW,CAAEA,MAAOA,KAGrC"}
|
|
1
|
+
{"version":3,"file":"xstate-fsm.umd.min.js","sources":["../src/fsm.ts","../src/schema.types.ts"],"sourcesContent":["import type {\n EventObject,\n InferEvents,\n MachineContext,\n SetupSchemas,\n SetupStateSchema\n} from './base.types.ts';\nimport type { StandardSchemaV1 } from './schema.types.ts';\n\n/** @public */\nexport type FSMArgs<\n TContext extends MachineContext,\n TEvent extends EventObject\n> = {\n context: TContext;\n event: TEvent;\n};\n\n/** @public */\nexport type FSMContextPatch<TContext extends MachineContext> =\n Partial<TContext>;\n\n/** @public */\nexport type FSMTransitionConfig<\n TContext extends MachineContext,\n TState extends string\n> = {\n target?: TState;\n context?: FSMContextPatch<TContext>;\n};\n\n/** @public */\nexport type FSMTransitionFunction<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = (\n args: FSMArgs<TContext, TEvent>\n) => FSMTransitionConfig<TTransitionContext, TState> | undefined;\n\ntype EventForType<TEvent extends EventObject, TType extends string> = [\n Extract<TEvent, { type: TType }>\n] extends [never]\n ? TEvent\n : Extract<TEvent, { type: TType }>;\n\n/** @public */\nexport type FSMTransition<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> =\n | TState\n | FSMTransitionConfig<TTransitionContext, TState>\n | FSMTransitionFunction<TContext, TEvent, TState, TTransitionContext>;\n\ntype FSMOn<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = {\n [TType in TEvent['type'] & string]?: FSMTransition<\n TContext,\n EventForType<TEvent, TType>,\n TState,\n TTransitionContext\n >;\n};\n\n/** @public */\nexport type FSMStateConfig<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TTransitionContext extends MachineContext = TContext\n> = {\n on?: FSMOn<TContext, TEvent, TState, TTransitionContext>;\n};\n\ntype FSMContextConfig<TContext extends MachineContext> =\n string extends keyof TContext\n ? { context?: TContext }\n : keyof TContext extends never\n ? { context?: TContext }\n : { context: TContext };\n\n/** @public */\nexport type FSMConfig<\n TContext extends MachineContext = {},\n TEvent extends EventObject = EventObject,\n TState extends string = string\n> = {\n id?: string;\n initial: TState;\n states: { [K in TState]: FSMStateConfig<TContext, TEvent, TState> };\n} & FSMContextConfig<TContext>;\n\ntype FSMConfigForStates<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends Record<string, unknown>\n> = Omit<\n FSMConfig<TContext, TEvent, keyof TStates & string>,\n 'initial' | 'states'\n> & {\n initial: keyof TStates & string;\n states: {\n [K in keyof TStates]: FSMStateConfig<\n TContext,\n TEvent,\n keyof TStates & string\n >;\n };\n};\n\n/**\n * A snapshot of a compact FSM. `status`, `output`, and `error` match the\n * snapshot shape shared by all actor logic, so an FSM can run in\n * `createActor`. An FSM snapshot is always `'active'`.\n *\n * @public\n */\nexport type FSMSnapshot<\n TContext extends MachineContext,\n TState extends string\n> = {\n status: 'active';\n value: TState;\n context: TContext;\n output: undefined;\n error: undefined;\n};\n\n/**\n * The result of an FSM transition: `[nextSnapshot, effects]`. FSMs have no\n * effects, so `effects` is always empty. The tuple matches the\n * `(snapshot, event) => [snapshot, effects]` protocol shared with full XState\n * actor logic.\n *\n * @public\n */\nexport type FSMTransitionResult<TSnapshot> = [\n nextSnapshot: TSnapshot,\n effects: never[]\n];\n\n/**\n * Pure logic returned by `createFSM`. It structurally satisfies `ActorLogic`,\n * so it works with `createActor`, `transition`, and `initialTransition` from\n * `xstate`.\n *\n * @public\n */\nexport type FSM<\n TContext extends MachineContext,\n TEvent extends EventObject,\n TState extends string,\n TSnapshot extends FSMSnapshot<MachineContext, TState> = FSMSnapshot<\n TContext,\n TState\n >,\n TConfig = FSMConfig<TContext, TEvent, TState>\n> = {\n readonly id: string | undefined;\n readonly config: TConfig;\n readonly initialState: TSnapshot;\n transition(\n snapshot: TSnapshot,\n event: TEvent\n ): FSMTransitionResult<TSnapshot>;\n initialTransition(input?: unknown): FSMTransitionResult<TSnapshot>;\n getInitialSnapshot(actorScope?: unknown, input?: unknown): TSnapshot;\n getPersistedSnapshot(snapshot: TSnapshot): TSnapshot;\n};\n\ntype FSMSetupSchemas = Pick<SetupSchemas, 'context' | 'events'>;\ntype FSMSetupStates = Record<string, SetupStateSchema>;\n\ntype FSMSchemaContext<TSchema extends StandardSchemaV1> =\n StandardSchemaV1.InferOutput<TSchema> extends MachineContext\n ? StandardSchemaV1.InferOutput<TSchema>\n : MachineContext;\n\ntype FSMSetupContext<TSchemas extends FSMSetupSchemas> = TSchemas extends {\n context: infer TSchema extends StandardSchemaV1;\n}\n ? FSMSchemaContext<TSchema>\n : MachineContext;\n\ntype FSMSetupEvents<TSchemas extends FSMSetupSchemas> = TSchemas extends {\n events: infer TEventSchemas extends Record<string, StandardSchemaV1>;\n}\n ? InferEvents<TEventSchemas>\n : EventObject;\n\ntype FSMStateContext<\n TStateSchema,\n TGlobalContext extends MachineContext\n> = TStateSchema extends { schemas?: infer TSchemas }\n ? TSchemas extends {\n context?: infer TSchema extends StandardSchemaV1;\n }\n ? FSMSchemaContext<TSchema> &\n ([MachineContext] extends [TGlobalContext] ? unknown : TGlobalContext)\n : TGlobalContext\n : TGlobalContext;\n\ntype FSMContextFromDeclaredStates<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = {\n [K in keyof TStates & string]: FSMStateContext<TStates[K], TGlobalContext>;\n}[keyof TStates & string];\n\ntype FSMContextFromStates<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = [keyof TStates] extends [never]\n ? TGlobalContext\n : [MachineContext] extends [TGlobalContext]\n ? FSMContextFromDeclaredStates<TStates, TGlobalContext>\n : TGlobalContext | FSMContextFromDeclaredStates<TStates, TGlobalContext>;\n\ntype FSMSetupStateContext<\n TState extends string,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = TState extends keyof TStates\n ? FSMStateContext<TStates[TState], TGlobalContext>\n : TGlobalContext;\n\ntype FSMSetupSnapshot<\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = [keyof TStates] extends [never]\n ? FSMSnapshot<TGlobalContext, keyof TMachineStates & string>\n : {\n [K in keyof TMachineStates & string]: FSMSnapshot<\n FSMSetupStateContext<K, TStates, TGlobalContext>,\n K\n >;\n }[keyof TMachineStates & string];\n\ntype FSMSetupTargetTransitionConfig<\n TSourceContext extends MachineContext,\n TTarget extends string,\n TTargetContext extends MachineContext\n> = [FSMRequiredTargetContextKeys<TSourceContext, TTargetContext>] extends [\n never\n]\n ? {\n target: TTarget;\n context?: FSMTargetContextPatch<TSourceContext, TTargetContext>;\n }\n : {\n target: TTarget;\n context: FSMTargetContextPatch<TSourceContext, TTargetContext>;\n };\n\ntype FSMRequiredTargetContextKeys<TSourceContext, TTargetContext> = {\n [K in keyof TTargetContext]-?: K extends keyof TSourceContext\n ? [TSourceContext[K]] extends [TTargetContext[K]]\n ? never\n : K\n : K;\n}[keyof TTargetContext];\n\ntype FSMTargetContextPatch<TSourceContext, TTargetContext> =\n Partial<TTargetContext> &\n Pick<\n TTargetContext,\n Extract<\n FSMRequiredTargetContextKeys<TSourceContext, TTargetContext>,\n string\n >\n >;\n\ntype FSMSetupTransitionConfig<\n TSourceContext extends MachineContext,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> =\n | { target?: undefined; context?: FSMContextPatch<TSourceContext> }\n | {\n [TTarget in keyof TStates & string]: FSMSetupTargetTransitionConfig<\n TSourceContext,\n TTarget,\n FSMSetupStateContext<TTarget, TStates, TGlobalContext>\n >;\n }[keyof TStates & string];\n\ntype FSMSetupStringTransition<\n TSourceContext extends MachineContext,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = {\n [TTarget in keyof TStates & string]: [TSourceContext] extends [\n FSMSetupStateContext<TTarget, TStates, TGlobalContext>\n ]\n ? TTarget\n : never;\n}[keyof TStates & string];\n\ntype FSMSetupTransitionFunction<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext\n> = (\n args: FSMArgs<TSourceContext, TEvent>\n) =>\n | FSMSetupTransitionConfig<TSourceContext, TStates, TGlobalContext>\n | undefined;\n\ntype FSMSetupTransition<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = [keyof TStates] extends [never]\n ? FSMTransition<TSourceContext, TEvent, keyof TMachineStates & string>\n :\n | FSMSetupStringTransition<TSourceContext, TStates, TGlobalContext>\n | FSMSetupTransitionConfig<TSourceContext, TStates, TGlobalContext>\n | FSMSetupTransitionFunction<\n TSourceContext,\n TEvent,\n TStates,\n TGlobalContext\n >;\n\ntype FSMSetupStateConfig<\n TSourceContext extends MachineContext,\n TEvent extends EventObject,\n TStates extends FSMSetupStates,\n TGlobalContext extends MachineContext,\n TMachineStates extends Record<string, unknown>\n> = {\n on?: {\n [TType in TEvent['type'] & string]?: FSMSetupTransition<\n TSourceContext,\n EventForType<TEvent, TType>,\n TStates,\n TGlobalContext,\n TMachineStates\n >;\n };\n};\n\ntype FSMSetupMachineConfig<\n TSchemas extends FSMSetupSchemas,\n TStates extends FSMSetupStates,\n TMachineStates extends Record<string, unknown>\n> = {\n id?: string;\n initial: keyof TMachineStates & string;\n states: {\n [K in keyof TMachineStates]: FSMSetupStateConfig<\n FSMStateContext<\n K extends keyof TStates ? TStates[K] : {},\n FSMSetupContext<TSchemas>\n >,\n FSMSetupEvents<TSchemas>,\n TStates,\n FSMSetupContext<TSchemas>,\n TMachineStates\n >;\n };\n} & FSMContextConfig<FSMContextFromStates<TStates, FSMSetupContext<TSchemas>>>;\n\n/** @public */\nexport type FSMSetupConfig<\n TSchemas extends FSMSetupSchemas = {},\n TStates extends FSMSetupStates = {}\n> = {\n schemas?: TSchemas;\n states?: TStates;\n};\n\n/** @public */\nexport type FSMSetupReturn<\n TSchemas extends FSMSetupSchemas,\n TStates extends FSMSetupStates\n> = {\n createFSM<const TMachineStates extends Record<string, unknown>>(\n config: FSMSetupMachineConfig<TSchemas, TStates, TMachineStates>\n ): FSM<\n FSMContextFromStates<TStates, FSMSetupContext<TSchemas>>,\n FSMSetupEvents<TSchemas>,\n keyof TMachineStates & string,\n FSMSetupSnapshot<TStates, FSMSetupContext<TSchemas>, TMachineStates>,\n FSMSetupMachineConfig<TSchemas, TStates, TMachineStates>\n >;\n};\n\n/** @public */\nexport function setup<\n const TSchemas extends FSMSetupSchemas = {},\n const TStates extends FSMSetupStates = {}\n>(\n _config: FSMSetupConfig<TSchemas, TStates> = {}\n): FSMSetupReturn<TSchemas, TStates> {\n return {\n createFSM: (config: FSMConfig) => createFSM(config)\n } as unknown as FSMSetupReturn<TSchemas, TStates>;\n}\n\n/** @public */\nexport function createFSM<\n TContext extends MachineContext = {},\n TEvent extends EventObject = EventObject,\n const TStates extends Record<string, unknown> = Record<string, unknown>\n>(\n config: FSMConfigForStates<TContext, TEvent, TStates>\n): FSM<\n TContext,\n TEvent,\n keyof TStates & string,\n FSMSnapshot<TContext, keyof TStates & string>,\n FSMConfigForStates<TContext, TEvent, TStates>\n> {\n type TState = keyof TStates & string;\n type TSnapshot = FSMSnapshot<TContext, TState>;\n const createSnapshot = (value: TState, context: TContext) =>\n ({\n status: 'active',\n value,\n context,\n output: undefined,\n error: undefined\n }) as TSnapshot;\n const initialState = createSnapshot(\n config.initial,\n config.context ?? ({} as TContext)\n );\n\n return {\n id: config.id,\n config,\n initialState,\n initialTransition: () => [initialState, []],\n getInitialSnapshot: () => initialState,\n getPersistedSnapshot: (snapshot) => snapshot,\n transition(snapshot, event) {\n let { value, context } = snapshot;\n const transitions = (\n Object.hasOwn(config.states, value) ? config.states[value] : undefined\n )?.on as\n | Record<string, FSMTransition<TContext, TEvent, TState> | undefined>\n | undefined;\n const transition =\n Object.hasOwn(transitions || {}, event.type) &&\n transitions![event.type];\n const { target = value, context: patch } =\n (typeof transition === 'string'\n ? { target: transition }\n : typeof transition === 'function'\n ? transition({ context, event })\n : transition) || {};\n // Copy only when the patch changes a value, so a no-op patch keeps the\n // current snapshot. After the first copy every key matches. Iterate a\n // spread copy so inherited keys, which the spread below ignores, are\n // skipped.\n for (const key of Reflect.ownKeys({ ...patch }) as (keyof TContext)[]) {\n if (\n !Object.hasOwn(context, key) ||\n !Object.is(patch![key], context[key])\n ) {\n context = { ...context, ...patch };\n }\n }\n\n return [\n target === value && context === snapshot.context\n ? snapshot\n : createSnapshot(target, context),\n []\n ];\n }\n };\n}\n","/**\n * The Standard Schema interface.\n *\n * @public\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties. */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\n/**\n * Schemas that can be declared for an individual state node.\n *\n * @public\n */\nexport type SetupStateSchemas = {\n /** Refines the machine's root context schema while this state is active. */\n context?: StandardSchemaV1;\n input?: StandardSchemaV1;\n /** The output emitted when this state node completes. */\n output?: StandardSchemaV1;\n};\n\n/**\n * A type-only Standard Schema produced by {@link types}.\n *\n * @public\n */\nexport interface TypeSchema<T> extends StandardSchemaV1<T, T> {\n readonly '~standard': StandardSchemaV1.Props<T, T> & {\n readonly vendor: 'xstate.types';\n };\n}\n\n/**\n * Declares schema types for inference only — no runtime validation.\n *\n * Use in a machine's `schemas` when you want TypeScript types without pulling\n * in a schema library like Zod. The returned value is a valid Standard Schema\n * whose validation is the identity function, so it carries types but never\n * rejects input.\n *\n * @example\n *\n * ```ts\n * import { createMachine, types } from 'xstate';\n *\n * const machine = createMachine({\n * schemas: {\n * context: types<{ count: number }>(),\n * events: {\n * inc: types<{ by: number }>(),\n * reset: types<void>()\n * }\n * },\n * context: { count: 0 }\n * // ...\n * });\n * ```\n *\n * Use `types<void>()` for events without a payload.\n * @public\n */\nexport function types<T>(): TypeSchema<T> {\n return {\n '~standard': {\n version: 1,\n vendor: 'xstate.types',\n validate: (value) => ({ value: value as T })\n }\n };\n}\n\n/**\n * Returns true if the value is a type-only schema created by {@link types}.\n *\n * @public\n */\nexport function isTypeSchema(value: unknown): value is TypeSchema<unknown> {\n return (\n !!value &&\n typeof value === 'object' &&\n '~standard' in value &&\n (value as StandardSchemaV1)['~standard'].vendor === 'xstate.types'\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace StandardSchemaV1 {\n /** The Standard Schema properties interface. */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the standard. */\n readonly version: 1;\n /** The vendor name of the schema library. */\n readonly vendor: string;\n /** Validates unknown input values. */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>;\n /** Inferred types associated with the schema. */\n readonly types?: Types<Input, Output> | undefined;\n }\n\n /** The result interface of the validate function. */\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n /** The result interface if validation succeeds. */\n export interface SuccessResult<Output> {\n /** The typed output value. */\n readonly value: Output;\n /** The non-existent issues. */\n readonly issues?: undefined;\n }\n\n /** The result interface if validation fails. */\n export interface FailureResult {\n /** The issues of failed validation. */\n readonly issues: ReadonlyArray<Issue>;\n }\n\n /** The issue interface of the failure output. */\n export interface Issue {\n /** The error message of the issue. */\n readonly message: string;\n /** The path of the issue, if any. */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n /** The path segment interface of the issue. */\n export interface PathSegment {\n /** The key representing a path segment. */\n readonly key: PropertyKey;\n }\n\n /** The Standard Schema types interface. */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type of the schema. */\n readonly input: Input;\n /** The output type of the schema. */\n readonly output: Output;\n }\n\n /** Infers the input type of a Standard Schema. */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input'];\n\n /** Infers the output type of a Standard Schema. */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output'];\n}\n"],"names":["createFSM","config","createSnapshot","value","context","status","output","undefined","error","initialState","initial","id","initialTransition","getInitialSnapshot","getPersistedSnapshot","snapshot","transition","event","transitions","Object","hasOwn","states","on","type","target","patch","key","Reflect","ownKeys","is","_config","version","vendor","validate"],"mappings":"gPA6ZO,SAASA,EAKdC,GAUA,MAAMC,EAAiBA,CAACC,EAAeC,KACpC,CACCC,OAAQ,SACRF,QACAC,UACAE,YAAQC,EACRC,WAAOD,IAELE,EAAeP,EACnBD,EAAOS,QACPT,EAAOG,SAAY,CAAA,GAGrB,MAAO,CACLO,GAAIV,EAAOU,GACXV,SACAQ,eACAG,kBAAmBA,IAAM,CAACH,EAAc,IACxCI,mBAAoBA,IAAMJ,EAC1BK,qBAAuBC,GAAaA,EACpCC,UAAAA,CAAWD,EAAUE,GACnB,IAAId,MAAEA,EAAKC,QAAEA,GAAYW,EACzB,MAAMG,GACJC,OAAOC,OAAOnB,EAAOoB,OAAQlB,GAASF,EAAOoB,OAAOlB,QAASI,IAC5De,GAGGN,EACJG,OAAOC,OAAOF,GAAe,CAAE,EAAED,EAAMM,OACvCL,EAAaD,EAAMM,OACfC,OAAEA,EAASrB,EAAOC,QAASqB,IACR,iBAAfT,EACJ,CAAEQ,OAAQR,GACY,mBAAfA,EACLA,EAAW,CAAEZ,UAASa,UACtBD,IAAe,GAKvB,IAAK,MAAMU,KAAOC,QAAQC,QAAQ,IAAKH,IAElCN,OAAOC,OAAOhB,EAASsB,IACvBP,OAAOU,GAAGJ,EAAOC,GAAMtB,EAAQsB,MAEhCtB,EAAU,IAAKA,KAAYqB,IAI/B,MAAO,CACLD,IAAWrB,GAASC,IAAYW,EAASX,QACrCW,EACAb,EAAesB,EAAQpB,GAC3B,GAEJ,EAEJ,uBApFO,SAIL0B,EAA6C,IAE7C,MAAO,CACL9B,UAAYC,GAAsBD,EAAUC,GAEhD,UC3VO,WACL,MAAO,CACL,YAAa,CACX8B,QAAS,EACTC,OAAQ,eACRC,SAAW9B,IAAW,CAAEA,MAAOA,KAGrC"}
|
package/dist/xstate-graph.cjs.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
var dist_xstateActors = require('./xstate-actors.cjs.js');
|
|
6
|
-
var createActor = require('./createActor-
|
|
6
|
+
var createActor = require('./createActor-c91c9ffe.cjs.js');
|
|
7
7
|
require('./validation-4561b43c.cjs.js');
|
|
8
8
|
|
|
9
9
|
function createMockActorScope() {
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
5
|
var dist_xstateActors = require('./xstate-actors.development.cjs.js');
|
|
6
|
-
var createActor = require('./createActor-
|
|
6
|
+
var createActor = require('./createActor-c029d29f.development.cjs.js');
|
|
7
7
|
require('./validation-f2714a35.development.cjs.js');
|
|
8
8
|
|
|
9
9
|
function createMockActorScope() {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createEmptyActor } from './xstate-actors.development.esm.js';
|
|
2
|
-
import { z as isMachineSnapshot, aJ as getAllOwnEvents, m as matchesEventDescriptor, aK as matchesEvent, Y as XSTATE_INIT } from './createActor-
|
|
3
|
-
export { aJ as getAllOwnEvents } from './createActor-
|
|
2
|
+
import { z as isMachineSnapshot, aJ as getAllOwnEvents, m as matchesEventDescriptor, aK as matchesEvent, Y as XSTATE_INIT } from './createActor-0250284a.development.esm.js';
|
|
3
|
+
export { aJ as getAllOwnEvents } from './createActor-0250284a.development.esm.js';
|
|
4
4
|
import './validation-e69470ad.development.esm.js';
|
|
5
5
|
|
|
6
6
|
function createMockActorScope() {
|
package/dist/xstate-graph.esm.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createEmptyActor } from './xstate-actors.esm.js';
|
|
2
|
-
import { A as isMachineSnapshot, aI as getAllOwnEvents, m as matchesEventDescriptor, aJ as matchesEvent, Z as XSTATE_INIT } from './createActor-
|
|
3
|
-
export { aI as getAllOwnEvents } from './createActor-
|
|
2
|
+
import { A as isMachineSnapshot, aI as getAllOwnEvents, m as matchesEventDescriptor, aJ as matchesEvent, Z as XSTATE_INIT } from './createActor-20a97166.esm.js';
|
|
3
|
+
export { aI as getAllOwnEvents } from './createActor-20a97166.esm.js';
|
|
4
4
|
import './validation-05f1d517.esm.js';
|
|
5
5
|
|
|
6
6
|
function createMockActorScope() {
|
|
@@ -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).XStateGraph={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const r="xstate.init",i="xstate.stop",n="@xstate.terminate",o="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",h="xstate.logic.effect.start";function u(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t.$actor)return!1;for(const e in t)if("$actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function d(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function l(t){return new Error(e(50,...void 0===t.incarnation?[t.$actor]:[t.$actor,t.incarnation]))}function p(t,e){const s=t._getByAddress?.(e.$actor);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function f(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const _=new WeakMap;async function v(t,s,r,i=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const o=_.get(t)?.get(s);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let u,d;const l=new Promise((t,e)=>{u=t,d=e});let p,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,l);const v=()=>{p?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return l.then(v,v),p=t.subscribe({error:d,complete:()=>d(new Error(e(72,s)))}),(async()=>{try{i({type:h,key:s});const e=await r();"active"===t.getSnapshot().status&&(i({type:c,key:s,output:e}),u(e))}catch(e){"active"===t.getSnapshot().status&&i({type:a,key:s,error:e}),d(e)}})().catch(d),l}function y(t,s,r){const i=function(t,s,r){const i=s;if(t!==s&&i.logic?.isInternalEventType?.(r.type))return new Error(e(73,r.type,s.id))}(t,s,r);return!!i&&(s.system.deadLetter(t,s,r,"internalEvent",{error:i}),!0)}class g{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function m(t){return{type:r,input:t}}function S(t){setTimeout(()=>{throw t})}const b="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],w=new Error("Transition effect");function A(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function E(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:A(t.event)??t.event}}function O(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",A(t.event)??t.event])}(e)}`}function k(t=this.source.system){return f(this.source,this.event,t)}function I(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function j(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:I,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function T(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function R(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 M(t=this.source.system){return function(t){if("string"==typeof t)throw new Error(e(70,t))}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,E(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function $(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:M,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function z(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const r="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},i=[t.self,r];return{kind:"builtin",exec:R,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function P(t,e,[s,r]){const i="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===n);return!i||o||c?[s,r]:[s,[...r,z(t,s)]]}const L=new WeakMap,N=new WeakMap,K=new Map;function q(t){t._snapshotVersion++}function U(t){return t._snapshotVersion}function D(t){const e=L.get(t);if(e)return e;const s=N.get(t);if(!s)return;const r=s();return L.set(t,r),N.delete(t),r}function C(t,e,s=e.system,r){N.delete(t);const i=U(s),n=r?D(r):void 0,o=n?.actor===e?n:D(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void L.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??K:t.keyedActors}(s);let u=h.size?new Map(h):K;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===K&&(u=new Map),u.set(t,e))}L.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function J(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}function V(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}function W(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function B(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function F(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}let H;Object.freeze({}),Object.freeze([]);let G=0;function X(){return H??=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)}`}(),`${H}:${(G++).toString(36)}`}function Q(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Y(t,e){return`${t?t.address:""}|${e}`}function Z(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},q(t))}function tt(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?Z(t,Y(s?.parent,r.prefix),r.index+1):s?.parent||Z(t,Y(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Y(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return Z(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const et=Object.freeze({});function st(t,e){return O(t,e)}function rt(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class it{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:X(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=void 0;this._snapshot={_scheduledTimers:et,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=st(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}const n=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:n,dueAt:n+s};this._snapshot._scheduledTimers===et&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,q(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],q(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=st(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==et&&delete this._snapshot._scheduledTimers[s],q(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(u(e)){const r=e,i=t?.system,n=i&&p(i,r);if(!n){const e=l(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:d(r.$actor),error:e})}e=n}if(y(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),q(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&q(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const r=this._keyedActors?.get(t);if(r&&r!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),r!==s&&q(this)}inspect(t){const e=V(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){S(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){S(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(u(e)){const r=p(this,e);if(r)e=r;else if(this._getByAddress(e.$actor)||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:d(e.$actor),error:l(e)})}if(y(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){S(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):v(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of x)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw w;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let nt=!1;const ot=Object.freeze([]),ct={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[o]:!0};let at=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ht=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ut(t,e){try{t?.(e)}catch(t){S(t)}}function dt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new pt(t,e)}class pt{get address(){return this._address??=this._parent?`${this._parent.address}/${Q(this.id)}`:Q(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=at.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...ht,...e}:ht,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new it(t,e)}(this,{clock:r,logger:i,createActorRef:lt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(V(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=tt(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=s._restore;this._restored=void 0!==d;try{if(d)this._setSnapshot(d.restore(this._actorScope));else if(e?._inert);else{const[t,e]=P(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}}catch(t){this._setSnapshot(d?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>f(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===at.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=nt;try{nt=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==at.Stopped&&this._recoverOrError(t)})}finally{nt=e}};this._processingStatus!==at.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,C(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;try{const[t,r]=P(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),dt(r,this._actorScope),this.update(t,s),!0}catch{return!1}}_next(t){for(const e of this.observers??ot)ut(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??ot,actions:this._collectedActions??ot,sent:this._collectedSent??ot,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 dt(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=V(t,e,s);if(this._processingStatus!==at.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":ut(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),ut(r.error,t)):S(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,i)=>{const n=V(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){if(this._processingStatus===at.Running)return this;if(this._processingStatus===at.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=at.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,m(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,m(this.options.input)):(function(t,e,s){const r=L.get(t),i=U(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,E(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=P(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let o=this._snapshot;try{const[n,c]=r;n!==s||c.length||!("machine"in s)||t.type===i||e&&Object.hasOwn(ct,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),dt(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===i&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){ut(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ut(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===at.Stopped?this:(this.mailbox?.clear(),this._processingStatus===at.NotStarted?(this._processingStatus=at.Stopped,this.system._unregister(this),this):(this._send({type:i}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??ot)ut(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||S(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(S)}catch(i){S(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),ut(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===at.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=at.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===at.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new g(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{$actor:this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[b](){return this}getSnapshot(){return this._snapshot}}function ft(t,...[r]){return function(t){if(t&&"object"==typeof t)for(const r of Object.keys(t))if(!s.has(r))throw new Error(e(8,r))}(r),new pt(t,r)}function _t(t,e){const s=t.check(e);if(s)throw s}const vt=new WeakMap;function yt(t,e,s){const r=function(t){let e=vt.get(t);return e||(e=new Map,vt.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function gt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[T("@xstate.cleanup",()=>function(t){const e=vt.get(t);if(!e)return;let s;vt.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===h)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],u=Object.create(null),d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:k,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push($(n,e,t))},raise:t=>{o.push($(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const c=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!c||s.type===r&&"active"===c.status)&&(o.push(T("@xstate.effect",(e=n.self.system)=>yt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(T("@xstate.effect",(t=n.self.system)=>yt(n.self,void 0,()=>c(t))))}},l=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),p={...e,...l||{}};return("context"in e||void 0!==l?.context)&&(p.context=l?.context??e.context),(l?.effects||Object.keys(u).length)&&(p.effects={...e.effects,...l?.effects,...u}),P(n,e,[p,o])},s=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:o});if(c)return[s,[j(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&_t(t.validator,{kind:"result",logic:n,snapshot:o[0],effects:o[1]}),o},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,m(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&_t(t.validator,{kind:"input",logic:n,input:e});const i=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==i&&(o.context=i),s({...o},m(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const mt=gt({context:void 0,run:()=>{}});function St(){const t=ft(mt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function bt(t){const{value:e,context:s}=t,r=J(t)?t:void 0,i=r?.getInputs(),n=r?.historyValue;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0,stateInputs:i&&Object.keys(i).length?i:void 0,historyValue:n&&Object.keys(n).length?Object.fromEntries(Object.entries(n).map(([t,e])=>[t,e.map(t=>t.id)])):void 0})}function xt(t){return JSON.stringify(t)}function wt(t){if(!t||"object"!=typeof t)return!1;const e=t,s=e.root;return!!s&&"object"==typeof s&&"string"==typeof s.id&&"object"==typeof s.states&&"function"==typeof s.transitions?.values&&"function"==typeof e.getStateNodeById&&"function"==typeof e.resolveState&&"function"==typeof e.getTransitionData}function At(t,e,s){const r=s??(wt(t)?(i=t,n=e,{serializeState:bt,serializeEvent:xt,...n,events:t=>W(t),fromState:n?.fromState??i.getInitialSnapshot(St(),n?.input)}):void 0);var i,n;const o=e?.serializeState??r?.serializeState??(t=>JSON.stringify(t)),c=e?.events??r?.events??[];return{serializeState:o,serializeEvent:xt,filterEvents:void 0,limit:1/0,toState:void 0,stopWhen:e?.toState,...r,...e,events:"function"==typeof c||Array.isArray(c)?c:t=>function(t,e,s){const r=[],i=t,n=Object.entries(i).filter(([,t])=>void 0!==t),o=t=>!s||s.some(e=>F(t,e.type));for(const[t,i]of n){if(!o(t))continue;const n="function"==typeof i?i(e):i;if(!Array.isArray(n)||!n.length)throw new Error(`Event cases for "${t}" must be a non-empty array`);for(const e of n){const i={...e,type:t};s&&!s.some(({type:e,...s})=>F(t,e)&&B(i,s))||r.push(i)}}return[...r,...s?.filter(t=>!n.some(([e])=>e===t.type))??[]]}(c,t,J(t)?W(t):void 0),fromState:e?.fromState??r?.fromState}}function Et(t,e,s){return new Error(`Unable to evaluate graph transition from state ${t} with event ${e}. If the transition needs event payloads, provide representative events using the "events" option.`,{cause:s})}function Ot(t){return Array.isArray(t)?t[0]:t}function kt(t,e){const{transition:s}=t,{serializeEvent:r,serializeState:i,events:n,filterEvents:o,limit:c,fromState:a,stopWhen:h}=At(t,e),u=St(),d=a??t.getInitialSnapshot(u,e?.input),l=Object.create(null);let p=0;const f=[{nextState:d,event:void 0,prevState:void 0}];for(let t=0;t<f.length;t++){const{nextState:e,event:a,prevState:d}=f[t];if(t>4096&&2*t>f.length&&(f.splice(0,t+1),t=-1),p++>c)throw new Error("Traversal limit exceeded");const _=i(e,a,d);if(l[_])continue;if(l[_]={state:e,transitions:Object.create(null)},h&&h(e))continue;const v="function"==typeof n?n(e):n;for(const t of v){if(o&&!o(e,t))continue;const i=r(t);let n;try{n=Ot(s(e,t,u))}catch(t){throw Et(_,i,t)}l[_].transitions[i]={event:t,state:n},f.push({nextState:n,event:t,prevState:e})}}return l}function It(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const i=t.steps[s];e.push({state:i.state,event:0===s?{type:r}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:r}}];return{...t,steps:e}}t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.getAdjacencyMap=kt,t.getAllOwnEvents=W,t.getDescendantStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,r)=>{const i=s[r],n=t(i);return e.push(i,...n),e},[])},t.getPathsFromEvents=function(t,e,s){const r=At(t,{events:e,...s}),i=St(),n=r.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:o,serializeEvent:c,filterEvents:a,stopWhen:h,limit:u}=r,d=[];let l=n,p=o(l,void 0,void 0);for(const r of e){if(d.length>=u)throw new Error("Traversal limit exceeded");const e=c(r);let n,f=r;if(void 0!==s?.events){const t="function"==typeof s.events?s.events(l):s.events;f=void 0;for(let s=t.length-1;s>=0;s--){const r=t[s];if((!a||a(l,r))&&c(r)===e){f=r;break}}}else a&&!a(l,r)&&(f=void 0);if(!f||h?.(l))throw new Error(`Invalid transition from ${p} with ${e}`);d.push({state:l,event:r});try{n=t.transition(l,f,i)}catch(t){throw Et(p,e,t)}const _=Array.isArray(n)?n[0]:n;p=o(_,r,l),l=_}return r.toState&&!r.toState(l)?[]:[It({state:l,steps:d,weight:d.length})]},t.getShortestPaths=function(t,e){const s=At(t,e),r=s.serializeState,i=s.fromState??t.getInitialSnapshot(St(),e?.input),n=kt(t,{...s,fromState:i}),o=new Map,c=new Map,a=r(i,void 0,void 0);c.set(a,i),o.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=o.get(t);for(const i of Object.keys(n[t].transitions)){const{state:a,event:d}=n[t].transitions[i],l=r(a,d,e);if(c.set(l,a),o.has(l)){const{weight:e}=o.get(l);e>s+1&&o.set(l,{weight:s+1,state:t,event:d})}else o.set(l,{weight:s+1,state:t,event:d});u.has(l)||h.add(l)}u.add(t),h.delete(t)}const d=Object.create(null),l=[];return o.forEach(({weight:t,state:e,event:s},r)=>{const i=c.get(r),n=void 0===e?[]:d[e].paths[0].steps.concat({state:c.get(e),event:s});l.push({state:i,steps:n,weight:t}),d[r]={state:i,paths:[{state:i,steps:n,weight:t}]}}),s.toState?l.filter(t=>s.toState(t.state)).map(It):l.map(It)},t.getSimplePaths=function(t,e){const s=At(t,e),r=St(),i=s.fromState??t.getInitialSnapshot(r,e?.input),n=s.serializeState,o=kt(t,{...s,fromState:i}),c=new Map,a={vertices:new Set,edges:new Set},h=[],u=Object.create(null);function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],r={state:s,weight:h.length,steps:[...h]};t.paths.push(r)}else{if(!o[t])return;for(const s of Object.keys(o[t].transitions)){const{state:r,event:i}=o[t].transitions[s];if(!(s in o[t].transitions))continue;const u=c.get(t),l=n(r,i,u);c.set(l,r),a.vertices.has(l)||(a.edges.add(s),h.push({state:c.get(t),event:i}),d(l,e))}}h.pop(),a.vertices.delete(t)}const l=n(i,void 0);c.set(l,i);for(const t of Object.keys(o))d(l,t);const p=Object.values(u).flatMap(t=>t.paths);return s.toState?p.filter(t=>s.toState(t.state)).map(It):p.map(It)},t.joinPaths=function(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}},t.serializeSnapshot=bt,t.toDirectedGraph=function t(e){const s=wt(e)?e.root:e,r=[],i=[...[...s.transitions.values()].flat(),...s.always??[]].flatMap((t,e)=>{t.to&&r.push({code:"dynamic-target",stateId:s.id,eventType:t.eventType,transitionId:`${s.id}:${e}`,message:"Transition function destinations require execution or source analysis."});return(t.target??(t.to?[]:[s])).map((r,i)=>{const n={id:`${s.id}:${e}:${i}`,source:s,target:r,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=n;return{source:s.id,target:r.id,label:t}}};return n})}),n=function(t){return t.states?Object.keys(t.states).map(e=>t.states[e]):[]}(s).map(t);r.push(...n.flatMap(t=>t.analysis.diagnostics));const o={id:s.id,stateNode:s,children:n,edges:i,analysis:{transitionTargetsComplete:0===r.length,diagnostics:r},toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s,analysis:o.analysis}}};return o},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).XStateGraph={})}(this,function(t){"use strict";function e(t,...e){return`XState error E${t}${e.length?` (${e.map(t=>"string"==typeof t?JSON.stringify(t):String(t)).join(", ")})`:""}. See https://github.com/statelyai/xstate/blob/next/docs/errors.md#e${t}`}const s=new Set(["clock","logger","syncSnapshot","id","registryKey","input","src","inspect","onRejectedEvent","onUnhandledEvent","_systemRef","_sessionId","_inert","_restore"]);const r="xstate.init",i="xstate.stop",n="@xstate.terminate",o="xstate.timer",c="xstate.logic.effect.resolve",a="xstate.logic.effect.reject",h="xstate.logic.effect.start";function u(t){if("object"!=typeof t||null===t||Array.isArray(t)||"string"!=typeof t["@actor"])return!1;for(const e in t)if("@actor"!==e&&"incarnation"!==e)return!1;const e=t.incarnation;return void 0===e||"string"==typeof e}function d(t){const e=t.slice(t.lastIndexOf("/")+1);return e.includes("%")?e.replaceAll("%2F","/").replaceAll("%25","%"):e}function l(t){return new Error(e(50,...void 0===t.incarnation?[t["@actor"]]:[t["@actor"],t.incarnation]))}function p(t,e){const s=t._getByAddress?.(e["@actor"]);return!s||void 0!==e.incarnation&&s.sessionId!==e.incarnation?void 0:s}function f(t,e,s){return t.system._notifyEmitted(t,e),s.emitEvent(t,e)}Object.freeze({status:"active",output:void 0,error:void 0});const _=new WeakMap;async function v(t,s,r,i=e=>{t.system.sendEvent(t,t,e)}){const n=function(t,e){const s=t.getSnapshot().effects;return s&&Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0}(t,s);if("done"===n?.status)return n.output;if("error"===n?.status)throw n.error;const o=_.get(t)?.get(s);if(o)return o;if("active"!==t.getSnapshot().status)throw new Error(e(72,s));let u,d;const l=new Promise((t,e)=>{u=t,d=e});let p,f=_.get(t);f||(f=new Map,_.set(t,f)),f.set(s,l);const v=()=>{p?.unsubscribe(),f.delete(s),f.size||_.delete(t)};return l.then(v,v),p=t.subscribe({error:d,complete:()=>d(new Error(e(72,s)))}),(async()=>{try{i({type:h,key:s});const e=await r();"active"===t.getSnapshot().status&&(i({type:c,key:s,output:e}),u(e))}catch(e){"active"===t.getSnapshot().status&&i({type:a,key:s,error:e}),d(e)}})().catch(d),l}function y(t,s,r){const i=function(t,s,r){const i=s;if(t!==s&&i.logic?.isInternalEventType?.(r.type))return new Error(e(73,r.type,s.id))}(t,s,r);return!!i&&(s.system.deadLetter(t,s,r,"internalEvent",{error:i}),!0)}class g{constructor(t){this._process=t,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(t){const e={value:t,next:null};if(this._current)return this._last.next=e,void(this._last=e);this._current=e,this._last=e,this._active&&this.flush()}flush(){for(;this._current;){const t=this._current;this._process(t.value),this._current=t.next}this._last=null}}function m(t){return{type:r,input:t}}function S(t){setTimeout(()=>{throw t})}const b="function"==typeof Symbol&&Symbol.observable||"@@observable",x=[],w=new Error("Transition effect");function A(t){const{stateId:e,delay:s,actorId:r}=t;switch(t.type){case"xstate.after":return{type:t.type,delay:s,stateId:e};case"xstate.timeout.state":return{type:t.type,stateId:e};case"xstate.timeout.actor":return{type:t.type,actorId:r}}}function E(t){return void 0!==t.id?{id:t.id}:void 0!==t.seq?{seq:t.seq}:{event:A(t.event)??t.event}}function O(t,e){return`${t.sessionId}|${function(t){return"id"in t?JSON.stringify(["id",t.id]):"seq"in t?JSON.stringify(["seq",t.seq]):JSON.stringify(["event",A(t.event)??t.event])}(e)}`}function k(t=this.source.system){return f(this.source,this.event,t)}function I(t=(this.target??this.source).system){return t.deadLetter(this.source,this.target,this.event,this.reason,this.detail)}function T(t,e,s,r,i){return{kind:"builtin",type:"@xstate.deadLetter",exec:I,source:e,target:t.self,event:s,reason:r,detail:i,params:void 0,args:[]}}function j(t,e,s){return{kind:"action",exec:e,type:t,action:e,params:s,args:[]}}function R(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 M(t=this.source.system){return function(t){if("string"==typeof t)throw new Error(e(70,t))}(this.event),void 0!==this.delay?t.scheduleTimer(this.source,E(this),this.delay):t.sendEvent(this.source,this.target,this.event)}function z(t,e,s){const r=[t,e,s,{}];return{kind:"builtin",exec:M,type:"@xstate.sendTo",source:t.self,target:e,event:s,id:void 0,delay:void 0,params:void 0,args:r}}function P(t,s){if("done"!==s.status&&"error"!==s.status)throw new Error(e(69,t.self.id,s.status));const r="done"===s.status?{status:"done",output:s.output,error:void 0}:{status:"error",output:void 0,error:s.error},i=[t.self,r];return{kind:"builtin",exec:R,type:n,source:t.self,actor:t.self,id:t.self.id,...r,params:void 0,args:i}}function $(t,e,[s,r]){const i="done"===s.status||"error"===s.status,o="done"===e?.status||"error"===e?.status,c=r.some(t=>"object"==typeof t&&null!==t&&"type"in t&&t.type===n);return!i||o||c?[s,r]:[s,[...r,P(t,s)]]}const L=new WeakMap,N=new WeakMap,K=new Map;function q(t){t._snapshotVersion++}function U(t){return t._snapshotVersion}function D(t){const e=L.get(t);if(e)return e;const s=N.get(t);if(!s)return;const r=s();return L.set(t,r),N.delete(t),r}function C(t,e,s=e.system,r){N.delete(t);const i=U(s),n=r?D(r):void 0,o=n?.actor===e?n:D(t);if(o?.actor===e&&o.systemState.sourceSystem===s&&o.systemState.sourceVersion===i)return void L.set(t,o);const c=function(t){const e=t._getRootActor?.(),s=t._peekChildren?.();if(!e&&!s){if(t._getRootActor&&t._peekChildren)return{};const e=new Map(t.children);return e.size?{children:e}:{}}return s?.size?{children:new Map(t.children)}:e?{root:e}:{}}(s);let a=c.children;const h=function(t){const e=t._peekKeyedActors;return e?e.call(t)??K:t.keyedActors}(s);let u=h.size?new Map(h):K;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===K&&(u=new Map),u.set(t,e))}L.set(t,{actor:e,systemState:{...c,children:a,keyedActors:u,snapshot:{...s._snapshot},sourceSystem:s,sourceVersion:i}})}function J(t){return!!t&&"object"==typeof t&&"machine"in t&&"value"in t}function V(t,e,s){const r="object"==typeof t,i=r?t:void 0;return{next:(r?t.next:t)?.bind(i),error:(r?t.error:e)?.bind(i),complete:(r?t.complete:s)?.bind(i),...r&&t.passive?{passive:!0}:{}}}function W(t){const e=t.nodes.flatMap(e=>[...e.transitions.values()].flatMap(e=>e.map(e=>{const s={type:e.eventType,...e.matches};return!("actorId"in s)||"xstate.done.actor"!==s.type&&"xstate.error.actor"!==s.type&&"xstate.snapshot.actor"!==s.type&&"xstate.timeout.actor"!==s.type||(s.sessionId=t.children[s.actorId]?.sessionId),s})));return e.filter((t,s)=>e.findIndex(e=>{const s=Object.keys(t);return s.length===Object.keys(e).length&&s.every(s=>Object.is(t[s],e[s]))})===s)}function B(t,e){return Object.entries(e).every(([e,s])=>Object.is(t[e],s))}function F(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}let H;Object.freeze({}),Object.freeze([]);let G=0;function X(){return H??=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)}`}(),`${H}:${(G++).toString(36)}`}function Q(t){return t.includes("/")||t.includes("%")?t.replaceAll("%","%25").replaceAll("/","%2F"):t}function Y(t,e){return`${t?t.address:""}|${e}`}function Z(t,e,s){const r=t._snapshot._nextActorIds;(r[e]??0)>=s||(t._snapshot._nextActorIds={...r,[e]:s},q(t))}function tt(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?Z(t,Y(s?.parent,r.prefix),r.index+1):s?.parent||Z(t,Y(void 0,e),1),e}const r=function(t){if("string"==typeof t)return t;const e=t?.id;return"string"==typeof e&&e.length?e:"x"}(s?.src),i=Y(s?.parent,r),n=t._snapshot._nextActorIds[i]??0;return Z(t,i,n+1),s?.parent||"x"===r||0!==n?`${r}:${n}`:r}const et=Object.freeze({});function st(t,e){return O(t,e)}function rt(t,e){return t.getSnapshot()?.timers?.find(t=>function(t,e){if("id"in e)return t.id===e.id;if(void 0!==t.id)return!1;if("seq"in e)return t.seq===e.seq;if(void 0!==t.seq)return!1;const s=t.event,r=e.event;for(const t in r)if(s[t]!==r[t])return!1;return!0}(t,e))}class it{get children(){const t=this._children??=new Map;return this._getRootActor()&&t.set(this._rootActor.sessionId,this._rootActor),t}set children(t){this._children=t}_getRootActor(){return this._rootActor._isRunning()?this._rootActor:void 0}_peekChildren(){return this._children}get keyedActors(){return this._keyedActors??=new Map}set keyedActors(t){this._keyedActors=t}get reverseKeyedActors(){return this._reverseKeyedActors??=new WeakMap}set reverseKeyedActors(t){this._reverseKeyedActors=t}_peekKeyedActors(){return this._keyedActors}constructor(t,e){this._rootActor=t,this._identity={executionId:X(),nextSessionId:0},this._snapshot=void 0,this._snapshotVersion=0,this.scheduler=this,this._clock=void 0,this._logger=void 0,this.createActorRef=void 0,this._clock=e.clock,this._logger=e.logger,this.createActorRef=e.createActorRef;const s=void 0;this._snapshot={_scheduledTimers:et,_nextActorIds:{}}}_recordSent(t,e,s,r,i){if(!this._inspectionObservers?.size||!t)return;const n=t;if(!n._inTransition)return;(n._collectedSent??=[]).push({targetRef:e,targetId:e.id,event:s,delay:r,id:i})}schedule(t,e,s){const r=st(t,e);void 0!==this._timerMap?.[r]&&this.cancel(t,e);const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}const n=this._clock.now?.()??Date.now(),c={source:t,delay:s,key:e,scheduledAt:n,dueAt:n+s};this._snapshot._scheduledTimers===et&&(this._snapshot._scheduledTimers={}),this._snapshot._scheduledTimers[r]=c,q(this);const a=this._clock.setTimeout(()=>{this._timerMap&&delete this._timerMap[r],delete this._snapshot._scheduledTimers[r],q(this),this._deliver(t,t,{type:o,...e})},s);(this._timerMap??={})[r]=a}cancel(t,e){const s=st(t,e),r=this._timerMap?.[s];this._timerMap&&delete this._timerMap[s],this._snapshot._scheduledTimers!==et&&delete this._snapshot._scheduledTimers[s],q(this),void 0!==r&&this._clock.clearTimeout(r)}cancelAll(t){for(const e in this._snapshot._scheduledTimers){const s=this._snapshot._scheduledTimers[e];s.source===t&&this.cancel(t,s.key)}}_deliver(t,e,s){!function(t,e,s){if(u(e)){const r=e,i=t?.system,n=i&&p(i,r);if(!n){const e=l(r);if(!i)throw e;return void i.deadLetter(t,void 0,s,"missingTarget",{targetId:d(r["@actor"]),error:e})}e=n}if(y(t,e,s))return;e._send(s,t)}(t,e,s)}_register(t,e){return e===this._rootActor?this._children?.set(t,e):(this._children??=new Map).set(t,e),q(this),t}_getByAddress(t){const e=this._getRootActor();if(e?.address===t)return e;for(const e of this._children?.values()??[])if(e.address===t&&e._isRunning())return e}_unregister(t){let e;t===this._rootActor?(e=void 0!==this._getRootActor(),e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1)||e):e=void 0!==t.sessionId&&(this._children?.delete(t.sessionId)??!1);const s=this._reverseKeyedActors?.get(t);void 0!==s&&(this._keyedActors?.get(s)===t&&(this._keyedActors.delete(s),e=!0),this._reverseKeyedActors?.delete(t)),e&&q(this)}get(t){return this._keyedActors?.get(t)}getAll(){return Object.fromEntries(this._keyedActors?.entries()??[])}_set(t,s){const r=this._keyedActors?.get(t);if(r&&r!==s)throw new Error(e(45,String(t)));(this._keyedActors??=new Map).set(t,s),(this._reverseKeyedActors??=new WeakMap).set(s,t),r!==s&&q(this)}inspect(t){const e=V(t);return(this._inspectionObservers??=new Set).add(e),{unsubscribe:()=>{this._inspectionObservers?.delete(e)}}}onRejectedEvent(t){const e=e=>t(e);return(this._rejectionListeners??=new Set).add(e),{unsubscribe:()=>{this._rejectionListeners?.delete(e)}}}onEmitted(t){const e=e=>t(e);return(this._emissionListeners??=new Set).add(e),{unsubscribe:()=>{this._emissionListeners?.delete(e)}}}_notifyEmitted(t,e){const s=this._emissionListeners;if(!s?.size)return;const r={actorRef:t,event:e};for(const t of Array.from(s))try{t(r)}catch(t){S(t)}}_hasInspectionObservers(){return!!this._inspectionObservers?.size}_sendInspectionEvent(t){if(!this._inspectionObservers?.size)return;const e={...t,rootId:this._rootActor.sessionId};this._inspectionObservers.forEach(t=>{try{t.next?.(e)}catch(t){S(t)}})}spawnActor(t,e){return this.runtime?.spawnActor?.(t,e)}startActor(t){const e=this.runtime?.startActor;if(e)return e(t);t.start()}stopActor(t){const e=this.runtime?.stopActor;if(e)return e(t);!function(t){t._stop()}(t)}terminateActor(t,e){const s=this.runtime?.terminateActor;if(s)return s(t,e);!function(t,e){t._terminate(e)}(t,e)}sendEvent(t,e,s){if(u(e)){const r=p(this,e);if(r)e=r;else if(this._getByAddress(e["@actor"])||!this.runtime?.sendEvent)return this.deadLetter(t,void 0,s,"missingTarget",{targetId:d(e["@actor"]),error:l(e)})}if(y(t,e,s))return;this._recordSent(t,e,s);const r=this.runtime?.sendEvent;if(r)return r(t,e,s);this._deliver(t,e,s)}emitEvent(t,e){const s=this.runtime?.emitEvent;if(s)return s(t,e);t._emit(e)}deadLetter(t,e,s,r,i){const n=this._rejectionListeners;if(n?.size){const o={event:s,targetRef:e,targetId:e?.id??i?.targetId,sourceRef:t,eventOrigin:t?"actor":"external",reason:r,issues:i?.issues,error:i?.error};for(const t of[...n])try{t(o)}catch(t){S(t)}}const o=this.runtime?.deadLetter;if(o)return o(t,e,s,r,i)}runStep(t,e,s){const r=this.runtime?.runStep;return r?r(t,e,s):v(t,e,s)}runLogic(t,e){const s=this.runtime?.runLogic;return s?s(t,e):e()}scheduleTimer(t,e,s){const r=this.runtime?.scheduleTimer;if(r){const i=rt(t,e);if(i){const e="self"===i.target?t:i.target;this._recordSent(t,e,i.event,s,i.id)}return r(t,e,s)}this.schedule(t,e,s)}cancelTimer(t,e){const s=this.runtime?.cancelTimer;if(s)return s(t,e);this.cancel(t,e)}cancelAllTimers(t){const e=this.runtime?.cancelAllTimers;if(e)return e(t);this.cancelAll(t)}_relay(t,e,s){if(!function(t){let e=!1,s=!1;for(const r of x)r.parent===t&&(r.requiresReevaluation=!0,e=!0,s||="abort"===r.mode);if(s)throw w;return e}(e))return this.sendEvent(t,e,s)}getSnapshot(){return{_scheduledTimers:{...this._snapshot._scheduledTimers}}}start(){const t=this._snapshot._scheduledTimers;let e=!0;for(const s in t){e&&(this._snapshot._scheduledTimers={},e=!1);const{source:r,dueAt:i,key:n}=t[s];this.scheduleTimer(r,n,Math.max(0,i-(this._clock.now?.()??Date.now())))}}}let nt=!1;const ot=Object.freeze([]),ct={"xstate.done.actor":!0,"xstate.error.actor":!0,"xstate.error.execution":!0,"xstate.snapshot.actor":!0,"xstate.done.state":!0,"xstate.after":!0,"xstate.timeout.state":!0,"xstate.timeout.actor":!0,[o]:!0};let at=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const ht=Object.freeze({clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console)});function ut(t,e){try{t?.(e)}catch(t){S(t)}}function dt(t,e){if(t?.length)for(const s of t)e.actionExecutor(s)}function lt(t,e){return new pt(t,e)}class pt{get address(){return this._address??=this._parent?`${this._parent.address}/${Q(this.id)}`:Q(this.id)}get trigger(){return this._trigger??=new Proxy({},{get:(t,e)=>t=>{this.send({...t,type:e})}})}get send(){return this._boundSend??=this._sendPublic.bind(this)}constructor(t,e){this.logic=t,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this._boundProcess=void 0,this.mailbox=void 0,this._mailboxStarted=!1,this.observers=void 0,this._errorObserved=!1,this.eventListeners=void 0,this.logger=void 0,this._processingStatus=at.NotStarted,this._forceDeferredActions=!1,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._lastSourceRef=void 0,this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,this._inTransition=!1,this._initialEffects=void 0,this.registryKey=void 0,this.sessionId=void 0,this._address=void 0,this.system=void 0,this._trigger=void 0,this._boundSend=void 0,this.src=void 0,this._deferred=void 0,this._restored=!1,this._warnedUnhandledTypes=void 0;const s=e?{...ht,...e}:ht,{clock:r,logger:i,parent:n,syncSnapshot:o,id:c,registryKey:a,inspect:h}=s;var u;this.system=n?n.system:s._systemRef?.current??function(t,e){return new it(t,e)}(this,{clock:r,logger:i,createActorRef:lt}),n||!s._systemRef||s._systemRef.current||(s._systemRef.current=this.system,s._systemRef.initialize?.()),h&&!n&&this.system.inspect(V(h)),s.onRejectedEvent&&!n&&this.system.onRejectedEvent(s.onRejectedEvent),this.sessionId=s._sessionId??`${(u=this.system)._identity.executionId}:${u._identity.nextSessionId++}`,this.id=tt(this.system,c,{parent:n,src:s.src??t}),this.logger=e?.logger??this.system._logger,this.clock=e?.clock??this.system._clock,this._parent=n,this._syncSnapshot=o,this.options=s,this.src=s.src??t,this.ref=this,this._actorScope=this,a&&(this.registryKey=a,this.system._set(a,this)),this._collectedMicrosteps=void 0;const d=s._restore;this._restored=void 0!==d;try{if(d)this._setSnapshot(d.restore(this._actorScope));else if(e?._inert);else{this._inTransition=!0;try{const[t,e]=$(this._actorScope,void 0,this.logic.initialTransition(this.options?.input,this._actorScope));this._setSnapshot(t),this._initialEffects=e.length?e:void 0}finally{this._inTransition=!1}}}catch(t){this._setSnapshot(d?.error?.(t)??{status:"error",output:void 0,error:t}),this._deferred&&(this._deferred.length=0)}a&&"active"!==this._snapshot.status&&this.system._unregister(this),(this.system._hasInspectionObservers?.()??1)&&this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this,parentRef:this._parent,id:this.id,src:this.src,snapshot:this._snapshot})}_getLogger(){return this.logger}get self(){return this}get defer(){const t=t=>this._defer(t);return Object.defineProperty(this,"defer",{value:t}),t}get stopChild(){const t=t=>this._stopChild(t);return Object.defineProperty(this,"stopChild",{value:t}),t}get emit(){const t=t=>f(this,t,this.system);return Object.defineProperty(this,"emit",{value:t}),t}get actionExecutor(){const t=t=>this._executeAction(t);return Object.defineProperty(this,"actionExecutor",{value:t}),t}_isRunning(){return this._processingStatus===at.Running}_defer(t){(this._deferred??=[]).push(t)}_stopChild(t){if(t._parent!==this)throw new Error(e(47,t.id,this.id));t._stop()}_executeAction(t){const e=()=>{(this.system._hasInspectionObservers?.()??1)&&(this._collectedActions??=[]).push({type:t.type,params:t.params});const e=nt;try{nt=!0;const e=t.exec();e&&"function"==typeof e.then&&Promise.resolve(e).catch(t=>{this._processingStatus!==at.Stopped&&this._recoverOrError(t)})}finally{nt=e}};this._processingStatus!==at.Running||this._forceDeferredActions?(this._deferred??=[]).push(e):e()}_setSnapshot(t){const e=this._snapshot;this._snapshot=t,C(t,this,this.system,e)}_setErrorSnapshot(t,e=this._snapshot){this._setSnapshot({...e,status:"error",error:t})}_recoverOrError(t,e,s){return!!this._tryHandleExecutionError(t,e)||(this._setErrorSnapshot(t),this._error(t,s),!1)}_tryHandleExecutionError(t,e=this._snapshot){const s=this.logic.getExecutionErrorEvent?.(e,t);if(!s)return!1;const r=this._inTransition;this._inTransition=!0;try{const[t,r]=$(this._actorScope,e,this.logic.transition(e,s,this._actorScope));return this._setSnapshot(t),dt(r,this._actorScope),this.update(t,s),!0}catch{return!1}finally{this._inTransition=r}}_next(t){for(const e of this.observers??ot)ut(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??ot,actions:this._collectedActions??ot,sent:this._collectedSent??ot,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 dt(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=V(t,e,s);if(this._processingStatus!==at.Stopped)(this.observers??=new Set).add(r);else switch(this._snapshot.status){case"done":ut(r.complete);break;case"error":{const t=this._snapshot.error;r.error?(r.passive||(this._errorObserved=!0),ut(r.error,t)):S(t);break}}return{unsubscribe:()=>{this.observers?.delete(r)}}}on(t,e){let s=this.eventListeners?.get(t);return s||(s=new Set,(this.eventListeners??=new Map).set(t,s)),s.add(e),{unsubscribe:()=>{s.delete(e)}}}select(t,e=Object.is){return{subscribe:(s,r,i)=>{const n=V(s,r,i);let o=t(this.getSnapshot());return this.subscribe({next:s=>{const r=t(s);e(o,r)||(o=r,n.next?.(r))},error:n.error,complete:n.complete})},get:()=>t(this.getSnapshot())}}start(){const t=this._inTransition;this._inTransition=!0;try{return this._start()}finally{this._inTransition=t}}_start(){if(this._processingStatus===at.Running)return this;if(this._processingStatus===at.Stopped){const t=this._snapshot.status;if("done"===t||"error"===t)return this;throw new Error(e(48,this.id))}this._syncSnapshot&&this.subscribe({next:t=>{"active"===t.status&&this.system._relay(this,this._parent,{type:"xstate.snapshot.actor",actorId:this.id,sessionId:this.sessionId,snapshot:t})},error:()=>{}}),this.system._register(this.sessionId,this),this.registryKey&&this.system._set(this.registryKey,this),this._processingStatus=at.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,m(this.options.input)),this):this;case"error":return this._error(this._snapshot.error),this;case"stopped":return this._stopProcedure(),this._complete(),this}if(this._parent||this.system.start(),!this._flushInitialEffects())return this;if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope,{restored:this._restored})}catch(t){return this._setErrorSnapshot(t),this._error(t),this}if(this._restored||this._deferred?.length||this.observers?.size||(this.system._hasInspectionObservers?.()??1)?this.update(this._snapshot,m(this.options.input)):(function(t,e,s){const r=L.get(t),i=U(s);return r?.actor===e&&r.systemState.sourceSystem===s&&r.systemState.sourceVersion+1===i&&s._getRootActor?.()===e&&!s._peekChildren?.()&&(r.systemState.root=e,r.systemState.sourceVersion=i,!0)}(this._snapshot,this,this.system)||this._setSnapshot(this._snapshot),this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0),this._restored){const t=this._snapshot.timers??[],e=!this.system._clock.now,s=Date.now();for(const r of t){const t=e&&void 0!==r.scheduledAt?Math.min(r.delay,Math.max(0,r.scheduledAt+r.delay-s)):r.delay;this.system.scheduleTimer(this,E(r),t)}this._restored=!1}return this._mailboxStarted=!0,this.mailbox?.start(),this}_process(t){const e=this._inTransition;this._inTransition=!0;try{this._processEvent(t)}finally{this._inTransition=e}}_processEvent({event:t,sourceRef:e}){this._lastSourceRef=e;const s=this._snapshot;let r,n;try{r=$(this._actorScope,this._snapshot,this.logic.transition(this._snapshot,t,this._actorScope))}catch(t){n={err:t}}if(n)return this._collectedMicrosteps=void 0,this._collectedActions=void 0,this._collectedSent=void 0,void(this._recoverOrError(n.err)||this._inspectTransition(this._snapshot,t));if(!r)return;let o=this._snapshot;try{const[n,c]=r;n!==s||c.length||!("machine"in s)||t.type===i||e&&Object.hasOwn(ct,t.type)||this._reportUnhandledEvent(t),o=n,this._setSnapshot(o),dt(c,this._actorScope),this.update(o,t)}catch(e){return void(this._recoverOrError(e,o,s)||this._inspectTransition(this._snapshot,t))}t.type===i&&(this._stopProcedure(),this._complete())}_reportUnhandledEvent(t){ut(()=>this.options.onUnhandledEvent?.(t,this._snapshot))}_emit(t){for(const e of[this.eventListeners?.get(t.type),this.eventListeners?.get("*")])if(e)for(const s of e)ut(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===at.Stopped?this:(this.mailbox?.clear(),this._processingStatus===at.NotStarted?(this._processingStatus=at.Stopped,this.system._unregister(this),this):(this._send({type:i}),this.system._unregister(this),this))}stop(){if(this._parent)throw new Error(e(49,this.id));return this._stop()}_complete(){for(const t of this.observers??ot)ut(t.complete);this.observers?.clear(),this.eventListeners?.clear()}_reportUnlessObserved(t){setTimeout(()=>{this._errorObserved||S(t)})}_error(t,e){this._stopProcedure();const s=new Set;for(const t of[this._snapshot,e]){const e=t?.children;for(const t of Object.values(e??{}))t?._parent===this&&"function"==typeof t.getSnapshot&&s.add(t)}for(const t of this.system._peekChildren?.()?.values()??[])t._parent===this&&s.add(t);for(const t of s)try{if("active"!==t.getSnapshot().status)continue;const e=this.system.stopActor(t);e&&Promise.resolve(e).catch(S)}catch(i){S(i)}if(this.observers?.size){let e=!1,s=!1;for(const r of this.observers){const i=r.error;r.passive||(e||=!i,s||=!!i),ut(i,t)}e||=!s,this.observers.clear(),e&&this._reportUnlessObserved(t)}else this._parent||this._reportUnlessObserved(t);var r,i,n;this.eventListeners?.clear(),this._parent&&this.system._relay(this,this._parent,(r=this.id,i=t,n=this.sessionId,{type:"xstate.error.actor",error:i,actorId:r,sessionId:n}))}_stopProcedure(){this._processingStatus===at.Running&&(this.system.cancelAllTimers(this),this.mailbox?.clear(),this.mailbox=void 0,this._boundProcess=void 0,this._mailboxStarted=!1,this._processingStatus=at.Stopped,this.system._unregister(this))}_send(t,e){if(this._processingStatus===at.Stopped)return void this.system.deadLetter(e,this,t,"stopped");let s=this.mailbox;s||(this._boundProcess??=this._process.bind(this),s=this.mailbox=new g(this._boundProcess),this._mailboxStarted&&s.start()),s.enqueue({event:t,sourceRef:e})}_sendPublic(t){this.system._relay(void 0,this,t)}toJSON(){return{"@actor":this.address}}getPersistedSnapshot(t){return this.logic.getPersistedSnapshot(this._snapshot,t)}[b](){return this}getSnapshot(){return this._snapshot}}function ft(t,...[r]){return function(t){if(t&&"object"==typeof t)for(const r of Object.keys(t))if(!s.has(r))throw new Error(e(8,r))}(r),new pt(t,r)}function _t(t,e){const s=t.check(e);if(s)throw s}const vt=new WeakMap;function yt(t,e,s){const r=function(t){let e=vt.get(t);return e||(e=new Map,vt.set(t,e)),e}(t);if(void 0!==e&&r.has(e))return;const i=s();r.set(e??Symbol(),{cleanup:"function"==typeof i?i:void 0})}function gt(t){const e=(e,s,n)=>{if("active"!==e.status)return[e,[]];if(s.type===i)return[{...e,status:"stopped",input:void 0},[j("@xstate.cleanup",()=>function(t){const e=vt.get(t);if(!e)return;let s;vt.delete(t);for(const{cleanup:t}of e.values())try{t?.()}catch(t){s??={error:t}}if(s)throw s.error}(n.self))]];if(s.type===h)return[{...e,effects:{...e.effects,[s.key]:{status:"active"}}},[]];if(s.type===c)return[{...e,effects:{...e.effects,[s.key]:{status:"done",output:s.output}}},[]];if(s.type===a)return[{...e,effects:{...e.effects,[s.key]:{status:"error",error:s.error}}},[]];const o=[],u=Object.create(null),d={emit:t=>{o.push(function(t,e){return{kind:"emit",exec:k,type:e.type,source:t.self,event:e,params:void 0,args:[]}}(n,t))},sendBack:t=>{const e=n.self._parent;e&&o.push(z(n,e,t))},raise:t=>{o.push(z(n,n.self,t))},effect:(t,i)=>{if("string"==typeof t)return void((t,i)=>{const c=e.effects&&Object.prototype.hasOwnProperty.call(e.effects,t)?e.effects[t]:void 0;(!c||s.type===r&&"active"===c.status)&&(o.push(j("@xstate.effect",(e=n.self.system)=>yt(n.self,t,()=>i(e)),{key:t})),u[t]={status:"active"})})(t,i);const c=t;o.push(j("@xstate.effect",(t=n.self.system)=>yt(n.self,void 0,()=>c(t))))}},l=t.run({context:e.context,event:s,input:e.input,system:n.system,self:n.self,emit:n.emit},d),p={...e,...l||{}};return("context"in e||void 0!==l?.context)&&(p.context=l?.context??e.context),(l?.effects||Object.keys(u).length)&&(p.effects={...e.effects,...l?.effects,...u}),$(n,e,[p,o])},s=(s,r,i)=>{if(t.validator){const e=i.self._lastSourceRef,o=e?"actor":"external",c=t.validator.check({kind:"event",logic:n,event:r,eventOrigin:o});if(c)return[s,[T(i,e,r,"invalidEvent",{issues:c.issues,error:c})]]}const o=e(s,r,i);return t.validator&&_t(t.validator,{kind:"result",logic:n,snapshot:o[0],effects:o[1]}),o},n={id:t.id,config:t,validator:t.validator,transition:s,start:(t,e,r)=>{if(!r?.restored)return;const[i,n]=s(t,m(t.input),e);Object.assign(t,i);for(const t of n)e.actionExecutor(t)},initialTransition:(e,r)=>{t.validator&&_t(t.validator,{kind:"input",logic:n,input:e});const i=function(t,e){return"function"==typeof t?t({input:e}):t}(t.context,e),o={status:"active",output:void 0,error:void 0,input:e};return void 0!==i&&(o.context=i),s({...o},m(e),r)},getInitialSnapshot:(t,e)=>n.initialTransition(e,t)[0],getPersistedSnapshot:t=>t,restoreSnapshot:t=>t};return n}const mt=gt({context:void 0,run:()=>{}});function St(){const t=ft(mt);return{self:t,logger:console.log,id:"",sessionId:Math.random().toString(32).slice(2),defer:()=>{},system:t.system,stopChild:()=>{},emit:()=>{},actionExecutor:()=>{}}}function bt(t){const{value:e,context:s}=t,r=J(t)?t:void 0,i=r?.getInputs(),n=r?.historyValue;return JSON.stringify({value:e,context:Object.keys(s??{}).length?s:void 0,stateInputs:i&&Object.keys(i).length?i:void 0,historyValue:n&&Object.keys(n).length?Object.fromEntries(Object.entries(n).map(([t,e])=>[t,e.map(t=>t.id)])):void 0})}function xt(t){return JSON.stringify(t)}function wt(t){if(!t||"object"!=typeof t)return!1;const e=t,s=e.root;return!!s&&"object"==typeof s&&"string"==typeof s.id&&"object"==typeof s.states&&"function"==typeof s.transitions?.values&&"function"==typeof e.getStateNodeById&&"function"==typeof e.resolveState&&"function"==typeof e.getTransitionData}function At(t,e,s){const r=s??(wt(t)?(i=t,n=e,{serializeState:bt,serializeEvent:xt,...n,events:t=>W(t),fromState:n?.fromState??i.getInitialSnapshot(St(),n?.input)}):void 0);var i,n;const o=e?.serializeState??r?.serializeState??(t=>JSON.stringify(t)),c=e?.events??r?.events??[];return{serializeState:o,serializeEvent:xt,filterEvents:void 0,limit:1/0,toState:void 0,stopWhen:e?.toState,...r,...e,events:"function"==typeof c||Array.isArray(c)?c:t=>function(t,e,s){const r=[],i=t,n=Object.entries(i).filter(([,t])=>void 0!==t),o=t=>!s||s.some(e=>F(t,e.type));for(const[t,i]of n){if(!o(t))continue;const n="function"==typeof i?i(e):i;if(!Array.isArray(n)||!n.length)throw new Error(`Event cases for "${t}" must be a non-empty array`);for(const e of n){const i={...e,type:t};s&&!s.some(({type:e,...s})=>F(t,e)&&B(i,s))||r.push(i)}}return[...r,...s?.filter(t=>!n.some(([e])=>e===t.type))??[]]}(c,t,J(t)?W(t):void 0),fromState:e?.fromState??r?.fromState}}function Et(t,e,s){return new Error(`Unable to evaluate graph transition from state ${t} with event ${e}. If the transition needs event payloads, provide representative events using the "events" option.`,{cause:s})}function Ot(t){return Array.isArray(t)?t[0]:t}function kt(t,e){const{transition:s}=t,{serializeEvent:r,serializeState:i,events:n,filterEvents:o,limit:c,fromState:a,stopWhen:h}=At(t,e),u=St(),d=a??t.getInitialSnapshot(u,e?.input),l=Object.create(null);let p=0;const f=[{nextState:d,event:void 0,prevState:void 0}];for(let t=0;t<f.length;t++){const{nextState:e,event:a,prevState:d}=f[t];if(t>4096&&2*t>f.length&&(f.splice(0,t+1),t=-1),p++>c)throw new Error("Traversal limit exceeded");const _=i(e,a,d);if(l[_])continue;if(l[_]={state:e,transitions:Object.create(null)},h&&h(e))continue;const v="function"==typeof n?n(e):n;for(const t of v){if(o&&!o(e,t))continue;const i=r(t);let n;try{n=Ot(s(e,t,u))}catch(t){throw Et(_,i,t)}l[_].transitions[i]={event:t,state:n},f.push({nextState:n,event:t,prevState:e})}}return l}function It(t){let e=[];if(t.steps.length){for(let s=0;s<t.steps.length;s++){const i=t.steps[s];e.push({state:i.state,event:0===s?{type:r}:t.steps[s-1].event})}e.push({state:t.state,event:t.steps[t.steps.length-1].event})}else e=[{state:t.state,event:{type:r}}];return{...t,steps:e}}t.adjacencyMapToArray=function(t){const e=[];for(const s of Object.values(t))for(const t of Object.values(s.transitions))e.push({state:s.state,event:t.event,nextState:t.state});return e},t.getAdjacencyMap=kt,t.getAllOwnEvents=W,t.getDescendantStateNodes=function t(e){const{states:s}=e;return Object.keys(s).reduce((e,r)=>{const i=s[r],n=t(i);return e.push(i,...n),e},[])},t.getPathsFromEvents=function(t,e,s){const r=At(t,{events:e,...s}),i=St(),n=r.fromState??t.getInitialSnapshot(i,s?.input),{serializeState:o,serializeEvent:c,filterEvents:a,stopWhen:h,limit:u}=r,d=[];let l=n,p=o(l,void 0,void 0);for(const r of e){if(d.length>=u)throw new Error("Traversal limit exceeded");const e=c(r);let n,f=r;if(void 0!==s?.events){const t="function"==typeof s.events?s.events(l):s.events;f=void 0;for(let s=t.length-1;s>=0;s--){const r=t[s];if((!a||a(l,r))&&c(r)===e){f=r;break}}}else a&&!a(l,r)&&(f=void 0);if(!f||h?.(l))throw new Error(`Invalid transition from ${p} with ${e}`);d.push({state:l,event:r});try{n=t.transition(l,f,i)}catch(t){throw Et(p,e,t)}const _=Array.isArray(n)?n[0]:n;p=o(_,r,l),l=_}return r.toState&&!r.toState(l)?[]:[It({state:l,steps:d,weight:d.length})]},t.getShortestPaths=function(t,e){const s=At(t,e),r=s.serializeState,i=s.fromState??t.getInitialSnapshot(St(),e?.input),n=kt(t,{...s,fromState:i}),o=new Map,c=new Map,a=r(i,void 0,void 0);c.set(a,i),o.set(a,{weight:0,state:void 0,event:void 0});const h=new Set,u=new Set;h.add(a);for(const t of h){const e=c.get(t),{weight:s}=o.get(t);for(const i of Object.keys(n[t].transitions)){const{state:a,event:d}=n[t].transitions[i],l=r(a,d,e);if(c.set(l,a),o.has(l)){const{weight:e}=o.get(l);e>s+1&&o.set(l,{weight:s+1,state:t,event:d})}else o.set(l,{weight:s+1,state:t,event:d});u.has(l)||h.add(l)}u.add(t),h.delete(t)}const d=Object.create(null),l=[];return o.forEach(({weight:t,state:e,event:s},r)=>{const i=c.get(r),n=void 0===e?[]:d[e].paths[0].steps.concat({state:c.get(e),event:s});l.push({state:i,steps:n,weight:t}),d[r]={state:i,paths:[{state:i,steps:n,weight:t}]}}),s.toState?l.filter(t=>s.toState(t.state)).map(It):l.map(It)},t.getSimplePaths=function(t,e){const s=At(t,e),r=St(),i=s.fromState??t.getInitialSnapshot(r,e?.input),n=s.serializeState,o=kt(t,{...s,fromState:i}),c=new Map,a={vertices:new Set,edges:new Set},h=[],u=Object.create(null);function d(t,e){const s=c.get(t);if(a.vertices.add(t),t===e){u[e]||(u[e]={state:c.get(e),paths:[]});const t=u[e],r={state:s,weight:h.length,steps:[...h]};t.paths.push(r)}else{if(!o[t])return;for(const s of Object.keys(o[t].transitions)){const{state:r,event:i}=o[t].transitions[s];if(!(s in o[t].transitions))continue;const u=c.get(t),l=n(r,i,u);c.set(l,r),a.vertices.has(l)||(a.edges.add(s),h.push({state:c.get(t),event:i}),d(l,e))}}h.pop(),a.vertices.delete(t)}const l=n(i,void 0);c.set(l,i);for(const t of Object.keys(o))d(l,t);const p=Object.values(u).flatMap(t=>t.paths);return s.toState?p.filter(t=>s.toState(t.state)).map(It):p.map(It)},t.joinPaths=function(t,e){if(e.steps[0].state!==t.state)throw new Error("Paths cannot be joined");return{state:e.state,steps:t.steps.concat(e.steps.slice(1)),weight:t.weight+e.weight}},t.serializeSnapshot=bt,t.toDirectedGraph=function t(e){const s=wt(e)?e.root:e,r=[],i=[...[...s.transitions.values()].flat(),...s.always??[]].flatMap((t,e)=>{t.to&&r.push({code:"dynamic-target",stateId:s.id,eventType:t.eventType,transitionId:`${s.id}:${e}`,message:"Transition function destinations require execution or source analysis."});return(t.target??(t.to?[]:[s])).map((r,i)=>{const n={id:`${s.id}:${e}:${i}`,source:s,target:r,transition:t,label:{text:t.eventType,toJSON:()=>({text:t.eventType})},toJSON:()=>{const{label:t}=n;return{source:s.id,target:r.id,label:t}}};return n})}),n=function(t){return t.states?Object.keys(t.states).map(e=>t.states[e]):[]}(s).map(t);r.push(...n.flatMap(t=>t.analysis.diagnostics));const o={id:s.id,stateNode:s,children:n,edges:i,analysis:{transitionTargetsComplete:0===r.length,diagnostics:r},toJSON:()=>{const{id:t,children:e,edges:s}=o;return{id:t,children:e,edges:s,analysis:o.analysis}}};return o},Object.defineProperty(t,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=xstate-graph.umd.min.js.map
|