-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.ts
350 lines (313 loc) · 9.62 KB
/
index.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
import {
ContextFrom,
EventFrom,
EventObject,
InitEvent,
InterpreterStatus,
MachineImplementationsFrom,
ServiceFrom,
StateFrom,
StateMachine,
Typestate
} from './types';
export {
StateMachine,
EventObject,
InterpreterStatus,
Typestate,
MachineImplementationsFrom,
StateFrom,
EventFrom,
ContextFrom,
ServiceFrom
};
const INIT_EVENT: InitEvent = { type: 'xstate.init' };
const ASSIGN_ACTION: StateMachine.AssignAction = 'xstate.assign';
const WILDCARD = '*';
function toArray<T>(item: T | T[] | undefined): T[] {
return item === undefined ? [] : ([] as T[]).concat(item);
}
export function assign<TC extends object, TE extends EventObject = EventObject>(
assignment:
| StateMachine.Assigner<TC, TE>
| StateMachine.PropertyAssigner<TC, TE>
): StateMachine.AssignActionObject<TC, TE> {
return {
type: ASSIGN_ACTION,
assignment
};
}
function toActionObject<TContext extends object, TEvent extends EventObject>(
// tslint:disable-next-line:ban-types
action:
| string
| StateMachine.ActionFunction<TContext, TEvent>
| StateMachine.ActionObject<TContext, TEvent>,
actionMap: StateMachine.ActionMap<TContext, TEvent> | undefined
) {
action =
typeof action === 'string' && actionMap && actionMap[action]
? actionMap[action]
: action;
return typeof action === 'string'
? {
type: action
}
: typeof action === 'function'
? {
type: action.name,
exec: action
}
: action;
}
const IS_PRODUCTION = process.env.NODE_ENV === 'production';
function createMatcher(value: string) {
return (stateValue) => value === stateValue;
}
function toEventObject<TEvent extends EventObject>(
event: TEvent['type'] | TEvent
): TEvent {
return (typeof event === 'string' ? { type: event } : event) as TEvent;
}
function createUnchangedState<
TC extends object,
TE extends EventObject,
TS extends Typestate<TC>
>(value: string, context: TC): StateMachine.State<TC, TE, TS> {
return {
value,
context,
actions: [],
changed: false,
matches: createMatcher(value)
};
}
function handleActions<
TContext extends object,
TEvent extends EventObject = EventObject
>(
actions: Array<StateMachine.ActionObject<TContext, TEvent>>,
context: TContext,
eventObject: TEvent
): [Array<StateMachine.ActionObject<TContext, TEvent>>, TContext, boolean] {
let nextContext = context;
let assigned = false;
const nonAssignActions = actions.filter((action) => {
if (action.type === ASSIGN_ACTION) {
assigned = true;
let tmpContext = Object.assign({}, nextContext);
if (typeof action.assignment === 'function') {
tmpContext = action.assignment(nextContext, eventObject);
} else {
Object.keys(action.assignment).forEach((key) => {
tmpContext[key] =
typeof action.assignment[key] === 'function'
? action.assignment[key](nextContext, eventObject)
: action.assignment[key];
});
}
nextContext = tmpContext;
return false;
}
return true;
});
return [nonAssignActions, nextContext, assigned];
}
export function createMachine<
TContext extends object,
TEvent extends EventObject = EventObject,
TState extends Typestate<TContext> = Typestate<TContext>
>(
fsmConfig: StateMachine.Config<TContext, TEvent, TState>,
implementations: {
actions?: StateMachine.ActionMap<TContext, TEvent>;
} = {}
): StateMachine.Machine<TContext, TEvent, TState> {
if (!IS_PRODUCTION) {
Object.keys(fsmConfig.states).forEach((state) => {
if (fsmConfig.states[state].states) {
throw new Error(`Nested finite states not supported.
Please check the configuration for the "${state}" state.`);
}
});
}
const [initialActions, initialContext] = handleActions(
toArray(fsmConfig.states[fsmConfig.initial].entry).map((action) =>
toActionObject(action, implementations.actions)
),
fsmConfig.context!,
INIT_EVENT as TEvent
);
const machine = {
config: fsmConfig,
_options: implementations,
initialState: {
value: fsmConfig.initial,
actions: initialActions,
context: initialContext,
matches: createMatcher(fsmConfig.initial)
},
transition: (
state: string | StateMachine.State<TContext, TEvent, TState>,
event: TEvent | TEvent['type']
): StateMachine.State<TContext, TEvent, TState> => {
const { value, context } =
typeof state === 'string'
? { value: state, context: fsmConfig.context! }
: state;
const eventObject = toEventObject<TEvent>(event);
const stateConfig = fsmConfig.states[value];
if (!IS_PRODUCTION && !stateConfig) {
throw new Error(
`State '${value}' not found on machine ${fsmConfig.id ?? ''}`
);
}
if (!IS_PRODUCTION && eventObject.type === WILDCARD) {
throw new Error(
`An event cannot have the wildcard type ('${WILDCARD}')`
);
}
if (stateConfig.on) {
const transitions: Array<
StateMachine.Transition<TContext, TEvent, TState['value']>
> = toArray(stateConfig.on[eventObject.type]);
if (WILDCARD in stateConfig.on) {
transitions.push(...toArray(stateConfig.on[WILDCARD]));
}
for (const transition of transitions) {
if (transition === undefined) {
return createUnchangedState(value, context);
}
const {
target,
actions = [],
cond = () => true
} = typeof transition === 'string'
? { target: transition }
: transition;
const isTargetless = target === undefined;
const nextStateValue = target ?? value;
const nextStateConfig = fsmConfig.states[nextStateValue];
if (!IS_PRODUCTION && !nextStateConfig) {
throw new Error(
`State '${nextStateValue}' not found on machine ${
fsmConfig.id ?? ''
}`
);
}
if (cond(context, eventObject)) {
const allActions = (
isTargetless
? toArray(actions)
: ([] as any[])
.concat(stateConfig.exit, actions, nextStateConfig.entry)
.filter((a) => a)
).map<StateMachine.ActionObject<TContext, TEvent>>((action) =>
toActionObject(action, (machine as any)._options.actions)
);
const [nonAssignActions, nextContext, assigned] = handleActions(
allActions,
context,
eventObject
);
const resolvedTarget = target ?? value;
return {
value: resolvedTarget,
context: nextContext,
actions: nonAssignActions,
changed:
target !== value || nonAssignActions.length > 0 || assigned,
matches: createMatcher(resolvedTarget)
};
}
}
}
// No transitions match
return createUnchangedState(value, context);
}
};
return machine;
}
const executeStateActions = <
TContext extends object,
TEvent extends EventObject = any,
TState extends Typestate<TContext> = { value: any; context: TContext }
>(
state: StateMachine.State<TContext, TEvent, TState>,
event: TEvent | InitEvent
) => state.actions.forEach(({ exec }) => exec && exec(state.context, event));
export function interpret<
TContext extends object,
TEvent extends EventObject = EventObject,
TState extends Typestate<TContext> = { value: any; context: TContext }
>(
machine: StateMachine.Machine<TContext, TEvent, TState>
): StateMachine.Service<TContext, TEvent, TState> {
let state = machine.initialState;
let status = InterpreterStatus.NotStarted;
const listeners = new Set<StateMachine.StateListener<typeof state>>();
const service = {
_machine: machine,
send: (event: TEvent | TEvent['type']): void => {
if (status !== InterpreterStatus.Running) {
return;
}
state = machine.transition(state, event);
executeStateActions(state, toEventObject(event));
listeners.forEach((listener) => listener(state));
},
subscribe: (listener: StateMachine.StateListener<typeof state>) => {
listeners.add(listener);
listener(state);
return {
unsubscribe: () => listeners.delete(listener)
};
},
start: (
initialState?:
| TState['value']
| { context: TContext; value: TState['value'] }
) => {
if (initialState) {
const resolved =
typeof initialState === 'object'
? initialState
: { context: machine.config.context!, value: initialState };
state = {
value: resolved.value,
actions: [],
context: resolved.context,
matches: createMatcher(resolved.value)
};
if (!IS_PRODUCTION) {
if (!(state.value in machine.config.states)) {
throw new Error(
`Cannot start service in state '${
state.value
}'. The state is not found on machine${
machine.config.id ? ` '${machine.config.id}'` : ''
}.`
);
}
}
} else {
state = machine.initialState;
}
status = InterpreterStatus.Running;
executeStateActions(state, INIT_EVENT);
return service;
},
stop: () => {
status = InterpreterStatus.Stopped;
listeners.clear();
return service;
},
get state() {
return state;
},
get status() {
return status;
}
};
return service;
}