-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiled-fsm.js
239 lines (204 loc) · 7.74 KB
/
compiled-fsm.js
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
import { destructureEvent, INIT_EVENT, NO_OUTPUT } from "kingly"
import { eventMonikers, stateMonikers, runOperation, renderSucceeded, renderError, renderFallback, startTimer } from "./properties"
const [INIT, SUSPENSE, PENDING, SPINNING, ERROR, DONE] = stateMonikers;
const [START, TIMER_EXPIRED, SUCCEEDED, FAILED] = eventMonikers;
// State update
// Basically {a, b: {c, d}}, [{b:{e}]} -> {a, b:{e}}
// All Object.assign caveats apply
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
function updateState(extendedState, extendedStateUpdates) {
const extendedStateCopy = Object.assign({}, extendedState);
return extendedStateUpdates.reduce((acc, x) => Object.assign(acc, x), extendedStateCopy);
}
// TODO: add in contracts that no event can be called INIT_EVENT or undefined!!
// TODO: add in contracts that no state can be called INIT_STATE
const _EVENTLESS_ = "undefined";
const initialControlState = INIT;
const initialExtendedState = {};
// This is to prevent infinite loops (possible due to eventless self-transitions)
const maxLoopCount = 1000;
const compoundStates = { [SUSPENSE]: true };
// TODO: what about INIT_STATE nok initial transition??
const eventlessStates = {};
function isCompoundState(controlState) {
return compoundStates[controlState]
}
function isEventlessState(controlState) {
return eventlessStates[controlState]
}
function hasAutomaticEvents(controlState) {
return isCompoundState(controlState) || isEventlessState(controlState)
}
function getAutomaticEvent(controlState, eventData) {
if (isCompoundState(controlState)) {
return { eventName: INIT_EVENT, eventData }
}
else if (isEventlessState(controlState)) {
return { eventName: _EVENTLESS_, eventData }
}
else {
throw `getAutomaticEvent: should be called only for control state which admit automatic events...!`
}
}
const eventHandlers = {
[INIT]: {
[START]: handleStartInInitState
},
[SUSPENSE]: {
[INIT_EVENT]: handleInitInSuspenseState,
[SUCCEEDED]: handleSucceededInSuspenseState,
[FAILED]: handleFailedInSuspenseState
},
[PENDING]: {
[TIMER_EXPIRED]: handleTimerExpiredInPendingState,
},
[SPINNING]: {},
[ERROR]: {},
[DONE]: {}
};
export function compiledFactory(settings) {
let controlState = initialControlState;
let extendedState = initialExtendedState;
let historyState = null;
// TODO: haven't dealt with history states yet!! That should be done in the event handler?
return function suspenseFsm(event) {
const { eventName, eventData } = destructureEvent(event);
let currEventHandler;
// Deal with events on compound states
if ([PENDING, SPINNING].includes(controlState) && [SUCCEEDED, FAILED].includes(eventName)) {
currEventHandler = eventHandlers[SUSPENSE][eventName]
}
else {
currEventHandler = eventHandlers[controlState][eventName];
}
if (!currEventHandler) { return NO_OUTPUT }
else {
let loopCount = 0;
let shouldProcessAnotherEvent = false;
let currMachineState = { controlState, extendedState, historyState };
let currEventData = eventData;
let currOutputs = [];
do {
const { updatedMachineState, outputs } = currEventHandler(currMachineState, currEventData, settings);
currOutputs = aggregateOutputs(currOutputs, outputs);
// Update machine state
controlState = updatedMachineState.updatedControlState;
extendedState = updatedMachineState.updatedExtendedState;
historyState = updatedMachineState.updatedHistoryState;
if (!hasAutomaticEvents(controlState)) {
shouldProcessAnotherEvent = false;
}
else {
shouldProcessAnotherEvent = true;
const automaticEvent = getAutomaticEvent(controlState, eventData);
currEventHandler = eventHandlers[controlState][automaticEvent.eventName];
currEventData = automaticEvent.eventData;
currMachineState = { controlState, extendedState, historyState };
}
}
while ( shouldProcessAnotherEvent && ++loopCount < maxLoopCount )
if (loopCount === maxLoopCount) {
throw `Stopping a possible infinite loop after ${maxLoopCount} loops! Unless you have a very deeply nested machine(!), there may be a bug in the machine compiler implementation.`
}
return currOutputs
}
}
}
/**
* Aggregates two machine outputs into a single array of machine outputs
* @param {Array} o1
* @param {Array} o2
* @returns {Array}
*/
function aggregateOutputs(o1, o2) {
return o1.concat(o2)
}
function handleStartInInitState(machineState, eventData, settings) {
const { controlState, extendedState, historyState } = machineState;
const { updates, outputs } = runOperation(extendedState, eventData, settings);
// TODO: in the compiler distinguish case when no history state update and when there is
const updatedHistoryState = historyState;
const updatedMachineState = {
updatedControlState: SUSPENSE,
updatedExtendedState: updateState(extendedState, updates),
updatedHistoryState
}
return {
updatedMachineState,
outputs
}
}
function handleInitInSuspenseState(machineState, eventData, settings) {
const { controlState, extendedState, historyState } = machineState;
const { updates, outputs } = startTimer(extendedState, eventData, settings);
const updatedHistoryState = historyState;
const updatedMachineState = {
updatedControlState: PENDING,
updatedExtendedState: updateState(extendedState, updates),
updatedHistoryState
}
return {
updatedMachineState,
outputs
}
}
function handleTimerExpiredInPendingState(machineState, eventData, settings) {
const { controlState, extendedState, historyState } = machineState;
const { updates, outputs } = renderFallback(extendedState, eventData, settings);
const updatedHistoryState = historyState;
const updatedMachineState = {
updatedControlState: SPINNING,
updatedExtendedState: updateState(extendedState, updates),
updatedHistoryState
}
return {
updatedMachineState,
outputs
}
}
function handleSucceededInSuspenseState(machineState, eventData, settings) {
const { controlState, extendedState, historyState } = machineState;
const { updates, outputs } = renderSucceeded(extendedState, eventData, settings);
// TODO : I should update the history state her but won't cause no history states defined for this compound state!
const updatedHistoryState = historyState;
const updatedMachineState = {
updatedControlState: DONE,
updatedExtendedState: updateState(extendedState, updates),
updatedHistoryState
}
return {
updatedMachineState,
outputs
}
}
function handleFailedInSuspenseState(machineState, eventData, settings) {
const { controlState, extendedState, historyState } = machineState;
const { updates, outputs } = renderError(extendedState, eventData, settings);
// TODO : I should update the history state her but won't cause no history states defined for this compound state!
const updatedHistoryState = historyState;
const updatedMachineState = {
updatedControlState: ERROR,
updatedExtendedState: updateState(extendedState, updates),
updatedHistoryState
}
return {
updatedMachineState,
outputs
}
}
// const transitions = [
// { from: INIT, event: START, to: SUSPENSE, action: runOperation },
// { from: SUSPENSE, event: INIT_EVENT, to: PENDING, action: startTimer },
// { from: PENDING, event: TIMER_EXPIRED, to: SPINNING, action: renderFallback },
// { from: SUSPENSE, event: SUCCEEDED, to: DONE, action: renderSucceeded },
// { from: SUSPENSE, event: FAILED, to: ERROR, action: renderError },
// ];
// const states = {
// [INIT]: "",
// [SUSPENSE]: {
// [PENDING]: "",
// [SPINNING]: "",
// },
// [ERROR]: "",
// [DONE]: "",
// };