-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathStateNode.ts
More file actions
481 lines (443 loc) · 12.8 KB
/
StateNode.ts
File metadata and controls
481 lines (443 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import { MachineSnapshot } from './State.ts';
import type { StateMachine } from './StateMachine.ts';
import { NULL_EVENT, STATE_DELIMITER } from './constants.ts';
import { evaluateGuard } from './guards.ts';
import { memo } from './memo.ts';
import {
BuiltinAction,
formatInitialTransition,
formatTransition,
formatTransitions,
getCandidates,
getDelayedTransitions
} from './stateUtils.ts';
import type {
DelayedTransitionDefinition,
EventObject,
InitialTransitionDefinition,
InvokeDefinition,
MachineContext,
Mapper,
StateNodeConfig,
StateNodeDefinition,
StateNodesConfig,
StatesDefinition,
TransitionDefinition,
TransitionDefinitionMap,
TODO,
UnknownAction,
ParameterizedObject,
AnyStateMachine,
AnyStateNodeConfig,
ProvidedActor,
NonReducibleUnknown,
EventDescriptor
} from './types.ts';
import {
createInvokeId,
mapValues,
toArray,
toTransitionConfigArray
} from './utils.ts';
const EMPTY_OBJECT = {};
const toSerializableAction = (action: UnknownAction) => {
if (typeof action === 'string') {
return { type: action };
}
if (typeof action === 'function') {
if ('resolve' in action) {
return { type: (action as BuiltinAction).type };
}
return {
type: action.name
};
}
return action;
};
interface StateNodeOptions<
TContext extends MachineContext,
TEvent extends EventObject
> {
_key: string;
_parent?: StateNode<TContext, TEvent>;
_machine: AnyStateMachine;
}
export class StateNode<
TContext extends MachineContext = MachineContext,
TEvent extends EventObject = EventObject
> {
/**
* The relative key of the state node, which represents its location in the
* overall state value.
*/
public key: string;
/** The unique ID of the state node. */
public id: string;
/**
* The type of this state node:
*
* - `'atomic'` - no child state nodes
* - `'compound'` - nested child state nodes (XOR)
* - `'parallel'` - orthogonal nested child state nodes (AND)
* - `'history'` - history state node
* - `'final'` - final state node
*/
public type: 'atomic' | 'compound' | 'parallel' | 'final' | 'history';
/** The string path from the root machine node to this node. */
public path: string[];
/** The child state nodes. */
public states: StateNodesConfig<TContext, TEvent>;
/**
* The type of history on this state node. Can be:
*
* - `'shallow'` - recalls only top-level historical state value
* - `'deep'` - recalls historical state value at all levels
*/
public history: false | 'shallow' | 'deep';
/** The action(s) to be executed upon entering the state node. */
public entry: UnknownAction[];
/** The action(s) to be executed upon exiting the state node. */
public exit: UnknownAction[];
/** The parent state node. */
public parent?: StateNode<TContext, TEvent>;
/** The root machine node. */
public machine: StateMachine<
TContext,
TEvent,
any, // children
any, // actor
any, // action
any, // guard
any, // delay
any, // state value
any, // tag
any, // input
any, // output
any, // emitted
any, // meta
any // state schema
>;
/**
* The meta data associated with this state node, which will be returned in
* State instances.
*/
public meta?: any;
/**
* The output data sent with the "xstate.done.state._id_" event if this is a
* final state node.
*/
public output?:
| Mapper<MachineContext, EventObject, unknown, EventObject>
| NonReducibleUnknown;
/**
* The order this state node appears. Corresponds to the implicit document
* order.
*/
public order: number = -1;
public description?: string;
public tags: string[] = [];
public transitions!: Map<string, TransitionDefinition<TContext, TEvent>[]>;
public always?: Array<TransitionDefinition<TContext, TEvent>>;
constructor(
/** The raw config used to create the machine. */
public config: StateNodeConfig<
TContext,
TEvent,
TODO, // actors
TODO, // actions
TODO, // guards
TODO, // delays
TODO, // tags
TODO, // output
TODO, // emitted
TODO // meta
>,
options: StateNodeOptions<TContext, TEvent>
) {
this.parent = options._parent;
this.key = options._key;
this.machine = options._machine;
this.path = this.parent ? this.parent.path.concat(this.key) : [];
this.id =
this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);
this.type =
this.config.type ||
(this.config.states && Object.keys(this.config.states).length
? 'compound'
: this.config.history
? 'history'
: 'atomic');
this.description = this.config.description;
this.order = this.machine.idMap.size;
this.machine.idMap.set(this.id, this);
this.states = (
this.config.states
? mapValues(
this.config.states,
(stateConfig: AnyStateNodeConfig, key) => {
const stateNode = new StateNode(stateConfig, {
_parent: this,
_key: key,
_machine: this.machine
});
return stateNode;
}
)
: EMPTY_OBJECT
) as StateNodesConfig<TContext, TEvent>;
if (this.type === 'compound' && !this.config.initial) {
throw new Error(
`No initial state specified for compound state node "#${
this.id
}". Try adding { initial: "${
Object.keys(this.states)[0]
}" } to the state config.`
);
}
// History config
this.history =
this.config.history === true ? 'shallow' : this.config.history || false;
this.entry = toArray(this.config.entry).slice();
this.exit = toArray(this.config.exit).slice();
this.meta = this.config.meta;
this.output =
this.type === 'final' || !this.parent ? this.config.output : undefined;
this.tags = toArray(config.tags).slice();
}
/** @internal */
public _initialize() {
this.transitions = formatTransitions(this);
if (this.config.always) {
this.always = toTransitionConfigArray(this.config.always).map((t) =>
formatTransition(this, NULL_EVENT, t)
);
}
Object.keys(this.states).forEach((key) => {
this.states[key]._initialize();
});
}
/** The well-structured state node definition. */
public get definition(): StateNodeDefinition<TContext, TEvent> {
return {
id: this.id,
key: this.key,
version: this.machine.version,
type: this.type,
initial: this.initial
? {
target: this.initial.target,
source: this,
actions: this.initial.actions.map(toSerializableAction),
eventType: null as any,
reenter: false,
toJSON: () => ({
target: this.initial.target.map((t) => `#${t.id}`),
source: `#${this.id}`,
actions: this.initial.actions.map(toSerializableAction),
eventType: null as any
})
}
: undefined,
history: this.history,
states: mapValues(this.states, (state: StateNode<TContext, TEvent>) => {
return state.definition;
}) as StatesDefinition<TContext, TEvent>,
on: this.on,
transitions: [...this.transitions.values()].flat().map((t) => ({
...t,
actions: t.actions.map(toSerializableAction)
})),
entry: this.entry.map(toSerializableAction),
exit: this.exit.map(toSerializableAction),
meta: this.meta,
order: this.order || -1,
output: this.output,
invoke: this.invoke,
description: this.description,
tags: this.tags
};
}
/** @internal */
public toJSON() {
return this.definition;
}
/** The logic invoked as actors by this state node. */
public get invoke(): Array<
InvokeDefinition<
TContext,
TEvent,
ProvidedActor,
ParameterizedObject,
ParameterizedObject,
string,
TODO, // TEmitted
TODO // TMeta
>
> {
return memo(this, 'invoke', () =>
toArray(this.config.invoke).map((invokeConfig, i) => {
const { src, systemId } = invokeConfig;
const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);
const sourceName =
typeof src === 'string'
? src
: `xstate.invoke.${createInvokeId(this.id, i)}`;
return {
...invokeConfig,
src: sourceName,
id: resolvedId,
systemId: systemId,
toJSON() {
const { onDone, onError, ...invokeDefValues } = invokeConfig;
return {
...invokeDefValues,
type: 'xstate.invoke',
src: sourceName,
id: resolvedId
};
}
} as InvokeDefinition<
TContext,
TEvent,
ProvidedActor,
ParameterizedObject,
ParameterizedObject,
string,
TODO, // TEmitted
TODO // TMeta
>;
})
);
}
/** The mapping of events to transitions. */
public get on(): TransitionDefinitionMap<TContext, TEvent> {
return memo(this, 'on', () => {
const transitions = this.transitions;
return [...transitions]
.flatMap(([descriptor, t]) => t.map((t) => [descriptor, t] as const))
.reduce(
(map: any, [descriptor, transition]) => {
map[descriptor] = map[descriptor] || [];
map[descriptor].push(transition);
return map;
},
{} as TransitionDefinitionMap<TContext, TEvent>
);
});
}
public get after(): Array<DelayedTransitionDefinition<TContext, TEvent>> {
return memo(
this,
'delayedTransitions',
() => getDelayedTransitions(this) as any
);
}
public get initial(): InitialTransitionDefinition<TContext, TEvent> {
return memo(this, 'initial', () =>
formatInitialTransition(this, this.config.initial)
);
}
/** @internal */
public next(
snapshot: MachineSnapshot<
TContext,
TEvent,
any,
any,
any,
any,
any, // TMeta
any // TStateSchema
>,
event: TEvent
): TransitionDefinition<TContext, TEvent>[] | undefined {
// Final states are terminal and cannot have outgoing transitions
if (this.type === 'final') {
return undefined;
}
const eventType = event.type;
const actions: UnknownAction[] = [];
let selectedTransition: TransitionDefinition<TContext, TEvent> | undefined;
const candidates: Array<TransitionDefinition<TContext, TEvent>> = memo(
this,
`candidates-${eventType}`,
() => getCandidates(this, eventType)
);
for (const candidate of candidates) {
const { guard } = candidate;
const resolvedContext = snapshot.context;
let guardPassed = false;
try {
guardPassed =
!guard ||
evaluateGuard<TContext, TEvent>(
guard,
resolvedContext,
event,
snapshot
);
} catch (err: any) {
const guardType =
typeof guard === 'string'
? guard
: typeof guard === 'object'
? guard.type
: undefined;
throw new Error(
`Unable to evaluate guard ${
guardType ? `'${guardType}' ` : ''
}in transition for event '${eventType}' in state node '${
this.id
}':\n${err.message}`
);
}
if (guardPassed) {
actions.push(...candidate.actions);
selectedTransition = candidate;
break;
}
}
return selectedTransition ? [selectedTransition] : undefined;
}
/** All the event types accepted by this state node and its descendants. */
public get events(): Array<EventDescriptor<TEvent>> {
return memo(this, 'events', () => {
const { states } = this;
const events = new Set(this.ownEvents);
if (states) {
for (const stateId of Object.keys(states)) {
const state = states[stateId];
if (state.states) {
for (const event of state.events) {
events.add(`${event}`);
}
}
}
}
return Array.from(events);
});
}
/**
* All the events that have transitions directly from this state node.
*
* Excludes any inert events.
*/
public get ownEvents(): Array<EventDescriptor<TEvent>> {
const keys = Object.keys(Object.fromEntries(this.transitions));
const events = new Set(
keys.filter((descriptor) => {
return this.transitions
.get(descriptor)!
.some(
(transition) =>
!(
!transition.target &&
!transition.actions.length &&
!transition.reenter
)
);
})
);
return Array.from(events);
}
}