/
StateNode.ts
497 lines (453 loc) · 13.4 KB
/
StateNode.ts
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
import {
getEventType,
mapValues,
flatten,
toArray,
keys,
isString,
toInvokeConfig,
toInvokeSource,
isFunction
} from './utils';
import {
Event,
Transitions,
EventObject,
HistoryStateNodeConfig,
StateNodeDefinition,
TransitionDefinition,
DelayedTransitionDefinition,
StateNodeConfig,
StatesDefinition,
StateNodesConfig,
FinalStateNodeConfig,
InvokeDefinition,
ActionObject,
Mapper,
PropertyMapper,
NullEvent,
SCXML,
TransitionDefinitionMap,
InitialTransitionDefinition,
MachineContext
} from './types';
import { State } from './State';
import * as actionTypes from './actionTypes';
import { toActionObject } from './actions';
import { formatInitialTransition } from './stateUtils';
import {
getDelayedTransitions,
formatTransitions,
getCandidates
} from './stateUtils';
import { evaluateGuard } from './guards';
import { StateMachine } from './StateMachine';
const EMPTY_OBJECT = {};
interface StateNodeOptions<
TContext extends MachineContext,
TEvent extends EventObject
> {
_key: string;
_parent?: StateNode<TContext, TEvent>;
_machine: StateMachine<TContext, TEvent>;
}
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: Array<ActionObject<TContext, TEvent>>;
/**
* The action(s) to be executed upon exiting the state node.
*/
public exit: Array<ActionObject<TContext, TEvent>>;
/**
* The parent state node.
*/
public parent?: StateNode<TContext, TEvent>;
/**
* The root machine node.
*/
public machine: StateMachine<TContext, TEvent>;
/**
* The meta data associated with this state node, which will be returned in State instances.
*/
public meta?: any;
/**
* The data sent with the "done.state._id_" event if this is a final state node.
*/
public doneData?:
| Mapper<TContext, TEvent, any>
| PropertyMapper<TContext, TEvent, any>;
/**
* The order this state node appears. Corresponds to the implicit SCXML document order.
*/
public order: number = -1;
// TODO: make private
public __cache = {
events: undefined as Array<TEvent['type']> | undefined,
initialState: undefined as State<TContext, TEvent> | undefined,
on: undefined as TransitionDefinitionMap<TContext, TEvent> | undefined,
transitions: undefined as
| Array<TransitionDefinition<TContext, TEvent>>
| undefined,
candidates: {} as {
[K in TEvent['type'] | NullEvent['type'] | '*']:
| Array<
TransitionDefinition<
TContext,
K extends TEvent['type']
? Extract<TEvent, { type: K }>
: EventObject
>
>
| undefined;
},
delayedTransitions: undefined as
| Array<DelayedTransitionDefinition<TContext, TEvent>>
| undefined,
invoke: undefined as Array<InvokeDefinition<TContext, TEvent>> | undefined
};
private __initial?: InitialTransitionDefinition<TContext, TEvent>;
public tags: string[] = [];
constructor(
/**
* The raw config used to create the machine.
*/
public config: StateNodeConfig<TContext, TEvent>,
options: StateNodeOptions<TContext, TEvent>
) {
this.parent = options._parent;
this.key = this.config.key || options._key;
this.machine = options._machine;
this.path = this.parent ? this.parent.path.concat(this.key) : [];
this.id =
this.config.id ||
[this.machine.key, ...this.path].join(this.machine.delimiter);
this.type =
this.config.type ||
(this.config.states && keys(this.config.states).length
? 'compound'
: this.config.history
? 'history'
: 'atomic');
this.order = this.machine.idMap.size;
this.machine.idMap.set(this.id, this);
this.states = (this.config.states
? mapValues(
this.config.states,
(stateConfig: StateNodeConfig<TContext, TEvent>, key) => {
const stateNode = new StateNode(stateConfig, {
_parent: this,
_key: key as string,
_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).map((action) =>
toActionObject(action)
);
this.exit = toArray(this.config.exit).map((action) =>
toActionObject(action)
);
this.meta = this.config.meta;
this.doneData =
this.type === 'final'
? (this.config as FinalStateNodeConfig<TContext, TEvent>).data
: undefined;
this.tags = toArray(config.tags);
}
/**
* The well-structured state node definition.
*/
public get definition(): StateNodeDefinition<TContext, TEvent> {
return {
id: this.id,
key: this.key,
version: this.machine.version,
context: this.machine.context!,
type: this.type,
initial: this.initial
? {
target: this.initial.target,
source: this,
actions: this.initial.actions,
eventType: null as any,
toJSON: () => ({
target: this.initial!.target!.map((t) => `#${t.id}`),
source: `#${this.id}`,
actions: this.initial!.actions,
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,
entry: this.entry,
exit: this.exit,
meta: this.meta,
order: this.order || -1,
data: this.doneData,
invoke: this.invoke
};
}
public toJSON() {
return this.definition;
}
/**
* The behaviors invoked as actors by this state node.
*/
public get invoke(): Array<InvokeDefinition<TContext, TEvent>> {
return (
this.__cache.invoke ||
(this.__cache.invoke = toArray(this.config.invoke).map((invocable, i) => {
const id = `${this.id}:invocation[${i}]`;
const invokeConfig = toInvokeConfig(invocable, id);
const resolvedId = invokeConfig.id || id;
const resolvedSrc = toInvokeSource(
isString(invokeConfig.src)
? invokeConfig.src
: typeof invokeConfig.src === 'object' && invokeConfig.src !== null
? invokeConfig.src
: resolvedId
);
if (
!this.machine.options.actors[resolvedSrc.type] &&
isFunction(invokeConfig.src)
) {
this.machine.options.actors = {
...this.machine.options.actors,
[resolvedSrc.type]: invokeConfig.src
};
}
return {
type: actionTypes.invoke,
...invokeConfig,
src: resolvedSrc,
id: resolvedId,
toJSON() {
const { onDone, onError, ...invokeDefValues } = invokeConfig;
return {
...invokeDefValues,
type: actionTypes.invoke,
src: resolvedSrc,
id: resolvedId
};
}
} as InvokeDefinition<TContext, TEvent>;
}))
);
}
/**
* The mapping of events to transitions.
*/
public get on(): TransitionDefinitionMap<TContext, TEvent> {
if (this.__cache.on) {
return this.__cache.on;
}
const transitions = this.transitions;
return (this.__cache.on = transitions.reduce((map, transition) => {
map[transition.eventType] = map[transition.eventType] || [];
map[transition.eventType].push(transition as any);
return map;
}, {} as TransitionDefinitionMap<TContext, TEvent>));
}
public get after(): Array<DelayedTransitionDefinition<TContext, TEvent>> {
return (
this.__cache.delayedTransitions ||
((this.__cache.delayedTransitions = getDelayedTransitions(this)),
this.__cache.delayedTransitions)
);
}
/**
* All the transitions that can be taken from this state node.
*/
public get transitions(): Array<TransitionDefinition<TContext, TEvent>> {
return (
this.__cache.transitions ||
((this.__cache.transitions = formatTransitions(this)),
this.__cache.transitions)
);
}
public get initial(): InitialTransitionDefinition<TContext, TEvent> {
return (
this.__initial ||
((this.__initial = formatInitialTransition(
this,
this.config.initial || []
)),
this.__initial)
);
}
/**
* Returns `true` if this state node explicitly handles the given event.
*
* @param event The event in question
*/
public handles(event: Event<TEvent>): boolean {
const eventType = getEventType<TEvent>(event);
return this.events.includes(eventType);
}
public next(
state: State<TContext, TEvent>,
_event: SCXML.Event<TEvent>
): Transitions<TContext, TEvent> | undefined {
const eventName = _event.name;
const actions: Array<ActionObject<TContext, TEvent>> = [];
let selectedTransition: TransitionDefinition<TContext, TEvent> | undefined;
const candidates: Array<TransitionDefinition<TContext, TEvent>> =
this.__cache.candidates[eventName] ||
(this.__cache.candidates[eventName] = getCandidates(
this,
eventName,
this.machine.config.scxml // Whether token matching should be used
));
for (const candidate of candidates) {
const { guard } = candidate;
const resolvedContext = state.context;
let guardPassed = false;
try {
guardPassed =
!guard ||
evaluateGuard<TContext, TEvent>(
guard,
resolvedContext,
_event,
state
);
} catch (err) {
throw new Error(
`Unable to evaluate guard '${
guard!.type
}' in transition for event '${eventName}' in state node '${
this.id
}':\n${err.message}`
);
}
if (guardPassed) {
actions.push(...candidate.actions);
selectedTransition = candidate;
break;
}
}
return selectedTransition ? [selectedTransition] : undefined;
}
/**
* The target state value of the history state node, if it exists. This represents the
* default state value to transition to if no history value exists yet.
*/
public get target(): string | undefined {
if (this.type === 'history') {
const historyConfig = this.config as HistoryStateNodeConfig<
TContext,
TEvent
>;
return historyConfig.target;
}
return undefined;
}
/**
* All the state node IDs of this state node and its descendant state nodes.
*/
public get stateIds(): string[] {
const childStateIds = flatten(
keys(this.states).map((stateKey) => {
return this.states[stateKey].stateIds;
})
);
return [this.id].concat(childStateIds);
}
/**
* All the event types accepted by this state node and its descendants.
*/
public get events(): Array<TEvent['type']> {
if (this.__cache.events) {
return this.__cache.events;
}
const { states } = this;
const events = new Set(this.ownEvents);
if (states) {
for (const stateId of keys(states)) {
const state = states[stateId];
if (state.states) {
for (const event of state.events) {
events.add(`${event}`);
}
}
}
}
return (this.__cache.events = Array.from(events));
}
/**
* All the events that have transitions directly from this state node.
*
* Excludes any inert events.
*/
public get ownEvents(): Array<TEvent['type']> {
const events = new Set(
this.transitions
.filter((transition) => {
return !(
!transition.target &&
!transition.actions.length &&
transition.internal
);
})
.map((transition) => transition.eventType)
);
return Array.from(events);
}
}