@statewalker/fsm 0.9.0 → 0.9.3

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.
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,370 @@
1
+ // @statewalker/fsm v0.9.3 https://github.com/statewalker/statewalker Copyright 2022 Mikhail Kotelnikov
2
+ (function (global, factory) {
3
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.statewalker = global.statewalker || {}, global.statewalker.fsm = global.statewalker.fsm || {})));
6
+ })(this, (function (exports) { 'use strict';
7
+
8
+ const MODE = {
9
+ NONE : 0,
10
+ FIRST: 1, // old=true; new=true => ENTER + ENTER
11
+ NEXT: 2, // old=false; new=true => EXIT + ENTER
12
+ LEAF : 4, // old=true; new=false => ENTER + EXIT
13
+ LAST : 8, // old=false; new=false => EXIT + EXIT
14
+
15
+ ENTER: 1 | 2, // MODE.FIRST | MODE.NEXT
16
+ EXIT : 4 | 8 // MODE.LEAF | MODE.LAST
17
+ };
18
+ var MODE$1 = MODE;
19
+
20
+ function newTreeWalker(
21
+ before, after,
22
+ context = { stack: [], status: MODE$1.NONE }
23
+ ) {
24
+ return (getNode) => {
25
+ let status = context.status;
26
+ const prev = status & MODE$1.EXIT;
27
+ if (prev) after(context);
28
+ if (status & MODE$1.ENTER) context.stack.push(context.current);
29
+ let node = getNode(context);
30
+ if (node) {
31
+ context.current = node;
32
+ status = context.status = prev ? MODE$1.NEXT : MODE$1.FIRST;
33
+ before(context);
34
+ } else {
35
+ node = context.current = context.stack.pop();
36
+ status = context.status = node ? prev ? MODE$1.LAST : MODE$1.LEAF : MODE$1.NONE;
37
+ }
38
+ return status !== MODE$1.NONE;
39
+ }
40
+ }
41
+
42
+ function newAsyncTreeWalker(
43
+ before, after,
44
+ context = { stack: [], status: MODE$1.NONE }
45
+ ) {
46
+ return async (getNode) => {
47
+ let status = context.status;
48
+ const prev = status & MODE$1.EXIT;
49
+ if (prev) await after(context);
50
+ if (status & MODE$1.ENTER) await context.stack.push(context.current);
51
+ let node = await getNode(context);
52
+ if (node) {
53
+ context.current = node;
54
+ status = context.status = prev ? MODE$1.NEXT : MODE$1.FIRST;
55
+ await before(context);
56
+ } else {
57
+ node = context.current = await context.stack.pop();
58
+ status = context.status = node ? prev ? MODE$1.LAST : MODE$1.LEAF : MODE$1.NONE;
59
+ }
60
+ return status !== MODE$1.NONE;
61
+ }
62
+ }
63
+
64
+ function buildStateDescriptor(config = {}) {
65
+ const { key, transitions = [], states = {}, options, ...params } = config;
66
+ const result = {
67
+ key,
68
+ transitions: {},
69
+ states: {},
70
+ options: Object.assign(options || {}, params)
71
+ };
72
+ for (const t of transitions) {
73
+ let stateKey, eventKey, targetStateKey;
74
+ if (Array.isArray(t)) {
75
+ stateKey = t[0];
76
+ eventKey = t[1];
77
+ targetStateKey = t[2];
78
+ } else {
79
+ const { from, event, to } = t;
80
+ stateKey = from;
81
+ eventKey = event;
82
+ targetStateKey = to;
83
+ }
84
+ const index = result.transitions[stateKey] = result.transitions[stateKey] || {};
85
+ index[eventKey] = targetStateKey;
86
+ }
87
+ if (Array.isArray(states)) {
88
+ for (const s of states) {
89
+ result.states[s.key] = buildStateDescriptor(s);
90
+ }
91
+ } else if (states) {
92
+ for (const key of Object.keys(states)) {
93
+ result.states[key] = buildStateDescriptor(states[key]);
94
+ }
95
+ }
96
+ return result;
97
+ }
98
+
99
+ var KEYS = {
100
+ STATE_ANY : "*",
101
+ STATE_INITIAL : "",
102
+ STATE_FINAL : "",
103
+ EVENT_ANY : "*",
104
+ EVENT_EMPTY : "",
105
+ };
106
+
107
+ function checkProcessDescriptor(descriptor) {
108
+ return checkStateDescriptor(descriptor);
109
+
110
+ function checkStateDescriptor(descriptor, report = [], stack = []) {
111
+ stack = [...stack, descriptor.key];
112
+ const result = Object.assign({ key: descriptor.key }, checkStateTransitions(descriptor));
113
+ if (result.deadendStates.length || result.unreachableStates.length) {
114
+ const info = { path: stack };
115
+ report.push(info);
116
+ if (result.deadendStates.length) info.deadendStates = result.deadendStates;
117
+ if (result.unreachableStates.length) info.unreachableStates = result.unreachableStates;
118
+ }
119
+ for (const subDescriptor of Object.values(descriptor.states)) {
120
+ checkStateDescriptor(subDescriptor, report, stack);
121
+ }
122
+ return report;
123
+ }
124
+
125
+ function checkStateTransitions(descriptor) {
126
+ const sourceStates = {};
127
+ const targetStates = {};
128
+ for (const [from, destinations] of Object.entries(descriptor.transitions)) {
129
+ sourceStates[from] = (sourceStates[from] || 0) + 1;
130
+ for (const targetKey of Object.values(destinations)) {
131
+ targetStates[targetKey] = (targetStates[targetKey] || 0) + 1;
132
+ }
133
+ }
134
+ // Unreachable states - no transitions leading to these states
135
+ const unreachableStates = [];
136
+ // Deadend states - no transitions from these states
137
+ const deadendStates = [];
138
+
139
+ // Unreachable states - no transitions leading to these states
140
+ for (const sourceKey of Object.keys(sourceStates)) {
141
+ if (sourceKey !== KEYS.STATE_ANY &&
142
+ sourceKey !== KEYS.STATE_FINAL &&
143
+ sourceKey !== KEYS.STATE_INITIAL &&
144
+ !(sourceKey in targetStates)) {
145
+ unreachableStates.push(sourceKey);
146
+ }
147
+ }
148
+
149
+ // Deadend states - no transitions from these states
150
+ for (const targetKey of Object.keys(targetStates)) {
151
+ if (targetKey !== KEYS.STATE_FINAL && !(targetKey in sourceStates)) {
152
+ deadendStates.push(targetKey);
153
+ }
154
+ }
155
+
156
+ return { unreachableStates, deadendStates }
157
+ }
158
+ }
159
+
160
+ function getStateDescriptor(process, stateKey) {
161
+ let descriptor;
162
+ for (let i = process.stack.length - 1; !descriptor && i >= 0; i--) {
163
+ const states = process.stack[i].descriptor.states || {};
164
+ descriptor = states[stateKey];
165
+ }
166
+ return descriptor || { transitions: {}, states: {} };
167
+ }
168
+
169
+ /**
170
+ * This method returns a list of all states used in
171
+ * the specified state descriptor.
172
+ *
173
+ * @param {object} descriptor compiled state descriptor
174
+ * defining transitions between sub-states and sub-states
175
+ * @returns a sorted list of all states
176
+ */
177
+ function getAllStateKeys(descriptor) {
178
+ const index = {};
179
+ const add = (key) => index[key] = (index[key] || 0) + 1;
180
+ visit(descriptor);
181
+ return Object.keys(index).sort();
182
+ function visit(descriptor) {
183
+ add(descriptor.key);
184
+ for (const [from, destinations] of Object.entries(descriptor.transitions)) {
185
+ add(from);
186
+ for (const targetKey of Object.values(destinations)) {
187
+ add(targetKey);
188
+ }
189
+ }
190
+ for (const [stateKey, stateDescriptor] of Object.entries(descriptor.states)) {
191
+ add(stateKey);
192
+ visit(stateDescriptor);
193
+ }
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Returns all possible transitions from the current state of the process.
199
+ * @param {Object} options - method parameters
200
+ * @param {Process} options.process - the current process for which
201
+ * all transitions should be returned
202
+ * @returns {Array<Object>} - an array of all transitions;
203
+ * each entry in this returned array contains the following keys:
204
+ * 1) parentStateKey - key of the state where the transition can be activated
205
+ * 2) sourceStateKey - the initial transition state
206
+ * 3) eventKey - key of the event activating transition
207
+ * 4) targetStateKey - the resulting state for this transition
208
+ *
209
+ */
210
+ function getAllTransitions(process) {
211
+ const list = [];
212
+ let stateKey = process.current ? process.current.key : KEYS.STATE_INITIAL;
213
+ for (let i = process.stack.length - 1; i >= 0; i--) {
214
+ const parentState = process.stack[i];
215
+ const parentStateKey = parentState.key;
216
+ const descriptor = parentState.descriptor;
217
+ for (const sKey of [stateKey, KEYS.STATE_ANY]) {
218
+ const stateTransitions = descriptor.transitions[sKey];
219
+ if (!stateTransitions) continue;
220
+ for (const[eventKey, targetKey] of Object.entries(stateTransitions)) {
221
+ list.push([parentStateKey, sKey, eventKey, targetKey]);
222
+ }
223
+ }
224
+ stateKey = parentStateKey;
225
+ }
226
+ return list;
227
+ }
228
+
229
+ function getTargetStateKey(descriptor, stateKey, eventKey) {
230
+ const pairs = [
231
+ [stateKey, eventKey],
232
+ [KEYS.STATE_ANY, eventKey],
233
+ [stateKey, KEYS.EVENT_ANY],
234
+ [KEYS.STATE_ANY, KEYS.EVENT_ANY]
235
+ ];
236
+ let targetKey;
237
+ for (let i = 0, len = pairs.length; (targetKey === undefined) && i < len; i++) {
238
+ const [stateKey, eventKey] = pairs[i];
239
+ const stateTransitions = descriptor.transitions[stateKey];
240
+ if (!stateTransitions) continue;
241
+ targetKey = stateTransitions[eventKey];
242
+ if (targetKey === undefined) targetKey = stateTransitions[KEYS.EVENT_ANY];
243
+ }
244
+ return (targetKey !== undefined) ? targetKey : KEYS.STATE_FINAL;
245
+ }
246
+
247
+ function newProcessInstance({
248
+ config,
249
+ descriptor,
250
+ newState = (obj) => obj,
251
+ newProcess = (descriptor) => ({
252
+ descriptor,
253
+ status: 0,
254
+ stack: [],
255
+ event: undefined,
256
+ current: undefined
257
+ })
258
+ }) {
259
+ descriptor = descriptor || buildStateDescriptor(config);
260
+ const process = newProcess(descriptor);
261
+ const loadNextState = () => {
262
+ let key, descriptor;
263
+ if (!process.status) {
264
+ descriptor = process.descriptor;
265
+ key = descriptor.key;
266
+ } else {
267
+ if (!process.stack.length) {
268
+ key = KEYS.STATE_FINAL;
269
+ } else {
270
+ const eventKey = process.event.key || KEYS.EVENT_EMPTY;
271
+ const parentDescriptor = process.stack[process.stack.length - 1].descriptor;
272
+ const stateKey = process.status & MODE$1.ENTER
273
+ ? KEYS.STATE_INITIAL
274
+ : process.current ? process.current.key : KEYS.STATE_FINAL;
275
+ key = getTargetStateKey(parentDescriptor, stateKey, eventKey);
276
+ if (key) {
277
+ descriptor = getStateDescriptor(process, key);
278
+ }
279
+ }
280
+ }
281
+ return key ? newState({ process, key, descriptor }) : null;
282
+ };
283
+ return [process, loadNextState];
284
+ }
285
+
286
+ function newAsyncProcess({
287
+ config,
288
+ descriptor,
289
+ before, after,
290
+ newProcess,
291
+ newState,
292
+ handleError = console.error
293
+ }) {
294
+ const [process, loadNextState] = newProcessInstance({
295
+ config,
296
+ descriptor,
297
+ newProcess,
298
+ newState
299
+ });
300
+ const shift = newAsyncTreeWalker(before, after, process);
301
+ process.finished = false;
302
+ process.next = (event) => {
303
+ process.nextEvent = event;
304
+ return process.running = process.running || Promise
305
+ .resolve()
306
+ .then(async () => {
307
+ try {
308
+ while (!process.finished) {
309
+ if (process.nextEvent) {
310
+ // Consume the next event if it exists.
311
+ process.event = process.nextEvent;
312
+ process.nextEvent = undefined;
313
+ } else if (process.status & MODE$1.LEAF) {
314
+ // Returns control when the process is in a "leaf" state (a state without children)
315
+ break;
316
+ }
317
+ process.finished = !await shift(loadNextState);
318
+ }
319
+ } catch (error) {
320
+ handleError(error);
321
+ }
322
+ })
323
+ .finally(() => process.running = undefined)
324
+ .then(() => !process.finished);
325
+ };
326
+ return process;
327
+ }
328
+
329
+ function newSyncProcess({
330
+ config,
331
+ descriptor,
332
+ before, after,
333
+ newProcess,
334
+ newState,
335
+ }) {
336
+ const [process, loadNextState] = newProcessInstance({
337
+ config,
338
+ descriptor,
339
+ newProcess,
340
+ newState,
341
+ });
342
+ const shift = newTreeWalker(before, after, process);
343
+ process.dispatch = process.next = (event) => {
344
+ if (typeof event === 'string') event = { key : event };
345
+ process.event = event;
346
+ while (process.event) {
347
+ if (!shift(loadNextState)) return false;
348
+ if (process.status & MODE$1.LEAF) return true;
349
+ }
350
+ };
351
+ return process;
352
+ }
353
+
354
+ exports.KEYS = KEYS;
355
+ exports.MODE = MODE$1;
356
+ exports.buildStateDescriptor = buildStateDescriptor;
357
+ exports.checkProcessDescriptor = checkProcessDescriptor;
358
+ exports.getAllStateKeys = getAllStateKeys;
359
+ exports.getAllTransitions = getAllTransitions;
360
+ exports.getStateDescriptor = getStateDescriptor;
361
+ exports.getTargetStateKey = getTargetStateKey;
362
+ exports.newAsyncProcess = newAsyncProcess;
363
+ exports.newAsyncTreeWalker = newAsyncTreeWalker;
364
+ exports.newProcessInstance = newProcessInstance;
365
+ exports.newSyncProcess = newSyncProcess;
366
+ exports.newTreeWalker = newTreeWalker;
367
+
368
+ Object.defineProperty(exports, '__esModule', { value: true });
369
+
370
+ }));
@@ -0,0 +1,2 @@
1
+ // @statewalker/fsm v0.9.3 https://github.com/statewalker/statewalker Copyright 2022 Mikhail Kotelnikov
2
+ !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).statewalker=t.statewalker||{},t.statewalker.fsm=t.statewalker.fsm||{}))}(this,(function(t){"use strict";var e={NONE:0,FIRST:1,NEXT:2,LEAF:4,LAST:8,ENTER:3,EXIT:12};function n(t,n,s={stack:[],status:e.NONE}){return r=>{let o=s.status;const c=o&e.EXIT;c&&n(s),o&e.ENTER&&s.stack.push(s.current);let a=r(s);return a?(s.current=a,o=s.status=c?e.NEXT:e.FIRST,t(s)):(a=s.current=s.stack.pop(),o=s.status=a?c?e.LAST:e.LEAF:e.NONE),o!==e.NONE}}function s(t,n,s={stack:[],status:e.NONE}){return async r=>{let o=s.status;const c=o&e.EXIT;c&&await n(s),o&e.ENTER&&await s.stack.push(s.current);let a=await r(s);return a?(s.current=a,o=s.status=c?e.NEXT:e.FIRST,await t(s)):(a=s.current=await s.stack.pop(),o=s.status=a?c?e.LAST:e.LEAF:e.NONE),o!==e.NONE}}function r(t={}){const{key:e,transitions:n=[],states:s={},options:o,...c}=t,a={key:e,transitions:{},states:{},options:Object.assign(o||{},c)};for(const t of n){let e,n,s;if(Array.isArray(t))e=t[0],n=t[1],s=t[2];else{const{from:r,event:o,to:c}=t;e=r,n=o,s=c}(a.transitions[e]=a.transitions[e]||{})[n]=s}if(Array.isArray(s))for(const t of s)a.states[t.key]=r(t);else if(s)for(const t of Object.keys(s))a.states[t]=r(s[t]);return a}var o={STATE_ANY:"*",STATE_INITIAL:"",STATE_FINAL:"",EVENT_ANY:"*",EVENT_EMPTY:""};function c(t,e){let n;for(let s=t.stack.length-1;!n&&s>=0;s--){n=(t.stack[s].descriptor.states||{})[e]}return n||{transitions:{},states:{}}}function a(t,e,n){const s=[[e,n],[o.STATE_ANY,n],[e,o.EVENT_ANY],[o.STATE_ANY,o.EVENT_ANY]];let r;for(let e=0,n=s.length;void 0===r&&e<n;e++){const[n,c]=s[e],a=t.transitions[n];a&&(r=a[c],void 0===r&&(r=a[o.EVENT_ANY]))}return void 0!==r?r:o.STATE_FINAL}function i({config:t,descriptor:n,newState:s=(t=>t),newProcess:i=(t=>({descriptor:t,status:0,stack:[],event:void 0,current:void 0}))}){const f=i(n=n||r(t));return[f,()=>{let t,n;if(f.status)if(f.stack.length){const s=f.event.key||o.EVENT_EMPTY;t=a(f.stack[f.stack.length-1].descriptor,f.status&e.ENTER?o.STATE_INITIAL:f.current?f.current.key:o.STATE_FINAL,s),t&&(n=c(f,t))}else t=o.STATE_FINAL;else n=f.descriptor,t=n.key;return t?s({process:f,key:t,descriptor:n}):null}]}t.KEYS=o,t.MODE=e,t.buildStateDescriptor=r,t.checkProcessDescriptor=function(t){return function t(e,n=[],s=[]){s=[...s,e.key];const r=Object.assign({key:e.key},function(t){const e={},n={};for(const[s,r]of Object.entries(t.transitions)){e[s]=(e[s]||0)+1;for(const t of Object.values(r))n[t]=(n[t]||0)+1}const s=[],r=[];for(const t of Object.keys(e))t===o.STATE_ANY||t===o.STATE_FINAL||t===o.STATE_INITIAL||t in n||s.push(t);for(const t of Object.keys(n))t===o.STATE_FINAL||t in e||r.push(t);return{unreachableStates:s,deadendStates:r}}(e));if(r.deadendStates.length||r.unreachableStates.length){const t={path:s};n.push(t),r.deadendStates.length&&(t.deadendStates=r.deadendStates),r.unreachableStates.length&&(t.unreachableStates=r.unreachableStates)}for(const r of Object.values(e.states))t(r,n,s);return n}(t)},t.getAllStateKeys=function(t){const e={},n=t=>e[t]=(e[t]||0)+1;return function t(e){n(e.key);for(const[t,s]of Object.entries(e.transitions)){n(t);for(const t of Object.values(s))n(t)}for(const[s,r]of Object.entries(e.states))n(s),t(r)}(t),Object.keys(e).sort()},t.getAllTransitions=function(t){const e=[];let n=t.current?t.current.key:o.STATE_INITIAL;for(let s=t.stack.length-1;s>=0;s--){const r=t.stack[s],c=r.key,a=r.descriptor;for(const t of[n,o.STATE_ANY]){const n=a.transitions[t];if(n)for(const[s,r]of Object.entries(n))e.push([c,t,s,r])}n=c}return e},t.getStateDescriptor=c,t.getTargetStateKey=a,t.newAsyncProcess=function({config:t,descriptor:n,before:r,after:o,newProcess:c,newState:a,handleError:f=console.error}){const[u,T]=i({config:t,descriptor:n,newProcess:c,newState:a}),E=s(r,o,u);return u.finished=!1,u.next=t=>(u.nextEvent=t,u.running=u.running||Promise.resolve().then((async()=>{try{for(;!u.finished;){if(u.nextEvent)u.event=u.nextEvent,u.nextEvent=void 0;else if(u.status&e.LEAF)break;u.finished=!await E(T)}}catch(t){f(t)}})).finally((()=>u.running=void 0)).then((()=>!u.finished))),u},t.newAsyncTreeWalker=s,t.newProcessInstance=i,t.newSyncProcess=function({config:t,descriptor:s,before:r,after:o,newProcess:c,newState:a}){const[f,u]=i({config:t,descriptor:s,newProcess:c,newState:a}),T=n(r,o,f);return f.dispatch=f.next=t=>{for("string"==typeof t&&(t={key:t}),f.event=t;f.event;){if(!T(u))return!1;if(f.status&e.LEAF)return!0}},f},t.newTreeWalker=n,Object.defineProperty(t,"__esModule",{value:!0})}));
@@ -0,0 +1,348 @@
1
+ // @statewalker/fsm v0.9.3 https://github.com/statewalker/statewalker Copyright 2022 Mikhail Kotelnikov
2
+ const MODE = {
3
+ NONE : 0,
4
+ FIRST: 1, // old=true; new=true => ENTER + ENTER
5
+ NEXT: 2, // old=false; new=true => EXIT + ENTER
6
+ LEAF : 4, // old=true; new=false => ENTER + EXIT
7
+ LAST : 8, // old=false; new=false => EXIT + EXIT
8
+
9
+ ENTER: 1 | 2, // MODE.FIRST | MODE.NEXT
10
+ EXIT : 4 | 8 // MODE.LEAF | MODE.LAST
11
+ };
12
+ var MODE$1 = MODE;
13
+
14
+ function newTreeWalker(
15
+ before, after,
16
+ context = { stack: [], status: MODE$1.NONE }
17
+ ) {
18
+ return (getNode) => {
19
+ let status = context.status;
20
+ const prev = status & MODE$1.EXIT;
21
+ if (prev) after(context);
22
+ if (status & MODE$1.ENTER) context.stack.push(context.current);
23
+ let node = getNode(context);
24
+ if (node) {
25
+ context.current = node;
26
+ status = context.status = prev ? MODE$1.NEXT : MODE$1.FIRST;
27
+ before(context);
28
+ } else {
29
+ node = context.current = context.stack.pop();
30
+ status = context.status = node ? prev ? MODE$1.LAST : MODE$1.LEAF : MODE$1.NONE;
31
+ }
32
+ return status !== MODE$1.NONE;
33
+ }
34
+ }
35
+
36
+ function newAsyncTreeWalker(
37
+ before, after,
38
+ context = { stack: [], status: MODE$1.NONE }
39
+ ) {
40
+ return async (getNode) => {
41
+ let status = context.status;
42
+ const prev = status & MODE$1.EXIT;
43
+ if (prev) await after(context);
44
+ if (status & MODE$1.ENTER) await context.stack.push(context.current);
45
+ let node = await getNode(context);
46
+ if (node) {
47
+ context.current = node;
48
+ status = context.status = prev ? MODE$1.NEXT : MODE$1.FIRST;
49
+ await before(context);
50
+ } else {
51
+ node = context.current = await context.stack.pop();
52
+ status = context.status = node ? prev ? MODE$1.LAST : MODE$1.LEAF : MODE$1.NONE;
53
+ }
54
+ return status !== MODE$1.NONE;
55
+ }
56
+ }
57
+
58
+ function buildStateDescriptor(config = {}) {
59
+ const { key, transitions = [], states = {}, options, ...params } = config;
60
+ const result = {
61
+ key,
62
+ transitions: {},
63
+ states: {},
64
+ options: Object.assign(options || {}, params)
65
+ };
66
+ for (const t of transitions) {
67
+ let stateKey, eventKey, targetStateKey;
68
+ if (Array.isArray(t)) {
69
+ stateKey = t[0];
70
+ eventKey = t[1];
71
+ targetStateKey = t[2];
72
+ } else {
73
+ const { from, event, to } = t;
74
+ stateKey = from;
75
+ eventKey = event;
76
+ targetStateKey = to;
77
+ }
78
+ const index = result.transitions[stateKey] = result.transitions[stateKey] || {};
79
+ index[eventKey] = targetStateKey;
80
+ }
81
+ if (Array.isArray(states)) {
82
+ for (const s of states) {
83
+ result.states[s.key] = buildStateDescriptor(s);
84
+ }
85
+ } else if (states) {
86
+ for (const key of Object.keys(states)) {
87
+ result.states[key] = buildStateDescriptor(states[key]);
88
+ }
89
+ }
90
+ return result;
91
+ }
92
+
93
+ var KEYS = {
94
+ STATE_ANY : "*",
95
+ STATE_INITIAL : "",
96
+ STATE_FINAL : "",
97
+ EVENT_ANY : "*",
98
+ EVENT_EMPTY : "",
99
+ };
100
+
101
+ function checkProcessDescriptor(descriptor) {
102
+ return checkStateDescriptor(descriptor);
103
+
104
+ function checkStateDescriptor(descriptor, report = [], stack = []) {
105
+ stack = [...stack, descriptor.key];
106
+ const result = Object.assign({ key: descriptor.key }, checkStateTransitions(descriptor));
107
+ if (result.deadendStates.length || result.unreachableStates.length) {
108
+ const info = { path: stack };
109
+ report.push(info);
110
+ if (result.deadendStates.length) info.deadendStates = result.deadendStates;
111
+ if (result.unreachableStates.length) info.unreachableStates = result.unreachableStates;
112
+ }
113
+ for (const subDescriptor of Object.values(descriptor.states)) {
114
+ checkStateDescriptor(subDescriptor, report, stack);
115
+ }
116
+ return report;
117
+ }
118
+
119
+ function checkStateTransitions(descriptor) {
120
+ const sourceStates = {};
121
+ const targetStates = {};
122
+ for (const [from, destinations] of Object.entries(descriptor.transitions)) {
123
+ sourceStates[from] = (sourceStates[from] || 0) + 1;
124
+ for (const targetKey of Object.values(destinations)) {
125
+ targetStates[targetKey] = (targetStates[targetKey] || 0) + 1;
126
+ }
127
+ }
128
+ // Unreachable states - no transitions leading to these states
129
+ const unreachableStates = [];
130
+ // Deadend states - no transitions from these states
131
+ const deadendStates = [];
132
+
133
+ // Unreachable states - no transitions leading to these states
134
+ for (const sourceKey of Object.keys(sourceStates)) {
135
+ if (sourceKey !== KEYS.STATE_ANY &&
136
+ sourceKey !== KEYS.STATE_FINAL &&
137
+ sourceKey !== KEYS.STATE_INITIAL &&
138
+ !(sourceKey in targetStates)) {
139
+ unreachableStates.push(sourceKey);
140
+ }
141
+ }
142
+
143
+ // Deadend states - no transitions from these states
144
+ for (const targetKey of Object.keys(targetStates)) {
145
+ if (targetKey !== KEYS.STATE_FINAL && !(targetKey in sourceStates)) {
146
+ deadendStates.push(targetKey);
147
+ }
148
+ }
149
+
150
+ return { unreachableStates, deadendStates }
151
+ }
152
+ }
153
+
154
+ function getStateDescriptor(process, stateKey) {
155
+ let descriptor;
156
+ for (let i = process.stack.length - 1; !descriptor && i >= 0; i--) {
157
+ const states = process.stack[i].descriptor.states || {};
158
+ descriptor = states[stateKey];
159
+ }
160
+ return descriptor || { transitions: {}, states: {} };
161
+ }
162
+
163
+ /**
164
+ * This method returns a list of all states used in
165
+ * the specified state descriptor.
166
+ *
167
+ * @param {object} descriptor compiled state descriptor
168
+ * defining transitions between sub-states and sub-states
169
+ * @returns a sorted list of all states
170
+ */
171
+ function getAllStateKeys(descriptor) {
172
+ const index = {};
173
+ const add = (key) => index[key] = (index[key] || 0) + 1;
174
+ visit(descriptor);
175
+ return Object.keys(index).sort();
176
+ function visit(descriptor) {
177
+ add(descriptor.key);
178
+ for (const [from, destinations] of Object.entries(descriptor.transitions)) {
179
+ add(from);
180
+ for (const targetKey of Object.values(destinations)) {
181
+ add(targetKey);
182
+ }
183
+ }
184
+ for (const [stateKey, stateDescriptor] of Object.entries(descriptor.states)) {
185
+ add(stateKey);
186
+ visit(stateDescriptor);
187
+ }
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Returns all possible transitions from the current state of the process.
193
+ * @param {Object} options - method parameters
194
+ * @param {Process} options.process - the current process for which
195
+ * all transitions should be returned
196
+ * @returns {Array<Object>} - an array of all transitions;
197
+ * each entry in this returned array contains the following keys:
198
+ * 1) parentStateKey - key of the state where the transition can be activated
199
+ * 2) sourceStateKey - the initial transition state
200
+ * 3) eventKey - key of the event activating transition
201
+ * 4) targetStateKey - the resulting state for this transition
202
+ *
203
+ */
204
+ function getAllTransitions(process) {
205
+ const list = [];
206
+ let stateKey = process.current ? process.current.key : KEYS.STATE_INITIAL;
207
+ for (let i = process.stack.length - 1; i >= 0; i--) {
208
+ const parentState = process.stack[i];
209
+ const parentStateKey = parentState.key;
210
+ const descriptor = parentState.descriptor;
211
+ for (const sKey of [stateKey, KEYS.STATE_ANY]) {
212
+ const stateTransitions = descriptor.transitions[sKey];
213
+ if (!stateTransitions) continue;
214
+ for (const[eventKey, targetKey] of Object.entries(stateTransitions)) {
215
+ list.push([parentStateKey, sKey, eventKey, targetKey]);
216
+ }
217
+ }
218
+ stateKey = parentStateKey;
219
+ }
220
+ return list;
221
+ }
222
+
223
+ function getTargetStateKey(descriptor, stateKey, eventKey) {
224
+ const pairs = [
225
+ [stateKey, eventKey],
226
+ [KEYS.STATE_ANY, eventKey],
227
+ [stateKey, KEYS.EVENT_ANY],
228
+ [KEYS.STATE_ANY, KEYS.EVENT_ANY]
229
+ ];
230
+ let targetKey;
231
+ for (let i = 0, len = pairs.length; (targetKey === undefined) && i < len; i++) {
232
+ const [stateKey, eventKey] = pairs[i];
233
+ const stateTransitions = descriptor.transitions[stateKey];
234
+ if (!stateTransitions) continue;
235
+ targetKey = stateTransitions[eventKey];
236
+ if (targetKey === undefined) targetKey = stateTransitions[KEYS.EVENT_ANY];
237
+ }
238
+ return (targetKey !== undefined) ? targetKey : KEYS.STATE_FINAL;
239
+ }
240
+
241
+ function newProcessInstance({
242
+ config,
243
+ descriptor,
244
+ newState = (obj) => obj,
245
+ newProcess = (descriptor) => ({
246
+ descriptor,
247
+ status: 0,
248
+ stack: [],
249
+ event: undefined,
250
+ current: undefined
251
+ })
252
+ }) {
253
+ descriptor = descriptor || buildStateDescriptor(config);
254
+ const process = newProcess(descriptor);
255
+ const loadNextState = () => {
256
+ let key, descriptor;
257
+ if (!process.status) {
258
+ descriptor = process.descriptor;
259
+ key = descriptor.key;
260
+ } else {
261
+ if (!process.stack.length) {
262
+ key = KEYS.STATE_FINAL;
263
+ } else {
264
+ const eventKey = process.event.key || KEYS.EVENT_EMPTY;
265
+ const parentDescriptor = process.stack[process.stack.length - 1].descriptor;
266
+ const stateKey = process.status & MODE$1.ENTER
267
+ ? KEYS.STATE_INITIAL
268
+ : process.current ? process.current.key : KEYS.STATE_FINAL;
269
+ key = getTargetStateKey(parentDescriptor, stateKey, eventKey);
270
+ if (key) {
271
+ descriptor = getStateDescriptor(process, key);
272
+ }
273
+ }
274
+ }
275
+ return key ? newState({ process, key, descriptor }) : null;
276
+ };
277
+ return [process, loadNextState];
278
+ }
279
+
280
+ function newAsyncProcess({
281
+ config,
282
+ descriptor,
283
+ before, after,
284
+ newProcess,
285
+ newState,
286
+ handleError = console.error
287
+ }) {
288
+ const [process, loadNextState] = newProcessInstance({
289
+ config,
290
+ descriptor,
291
+ newProcess,
292
+ newState
293
+ });
294
+ const shift = newAsyncTreeWalker(before, after, process);
295
+ process.finished = false;
296
+ process.next = (event) => {
297
+ process.nextEvent = event;
298
+ return process.running = process.running || Promise
299
+ .resolve()
300
+ .then(async () => {
301
+ try {
302
+ while (!process.finished) {
303
+ if (process.nextEvent) {
304
+ // Consume the next event if it exists.
305
+ process.event = process.nextEvent;
306
+ process.nextEvent = undefined;
307
+ } else if (process.status & MODE$1.LEAF) {
308
+ // Returns control when the process is in a "leaf" state (a state without children)
309
+ break;
310
+ }
311
+ process.finished = !await shift(loadNextState);
312
+ }
313
+ } catch (error) {
314
+ handleError(error);
315
+ }
316
+ })
317
+ .finally(() => process.running = undefined)
318
+ .then(() => !process.finished);
319
+ };
320
+ return process;
321
+ }
322
+
323
+ function newSyncProcess({
324
+ config,
325
+ descriptor,
326
+ before, after,
327
+ newProcess,
328
+ newState,
329
+ }) {
330
+ const [process, loadNextState] = newProcessInstance({
331
+ config,
332
+ descriptor,
333
+ newProcess,
334
+ newState,
335
+ });
336
+ const shift = newTreeWalker(before, after, process);
337
+ process.dispatch = process.next = (event) => {
338
+ if (typeof event === 'string') event = { key : event };
339
+ process.event = event;
340
+ while (process.event) {
341
+ if (!shift(loadNextState)) return false;
342
+ if (process.status & MODE$1.LEAF) return true;
343
+ }
344
+ };
345
+ return process;
346
+ }
347
+
348
+ export { KEYS, MODE$1 as MODE, buildStateDescriptor, checkProcessDescriptor, getAllStateKeys, getAllTransitions, getStateDescriptor, getTargetStateKey, newAsyncProcess, newAsyncTreeWalker, newProcessInstance, newSyncProcess, newTreeWalker };
@@ -0,0 +1,2 @@
1
+ // @statewalker/fsm v0.9.3 https://github.com/statewalker/statewalker Copyright 2022 Mikhail Kotelnikov
2
+ var t={NONE:0,FIRST:1,NEXT:2,LEAF:4,LAST:8,ENTER:3,EXIT:12};function e(e,n,s={stack:[],status:t.NONE}){return r=>{let o=s.status;const c=o&t.EXIT;c&&n(s),o&t.ENTER&&s.stack.push(s.current);let a=r(s);return a?(s.current=a,o=s.status=c?t.NEXT:t.FIRST,e(s)):(a=s.current=s.stack.pop(),o=s.status=a?c?t.LAST:t.LEAF:t.NONE),o!==t.NONE}}function n(e,n,s={stack:[],status:t.NONE}){return async r=>{let o=s.status;const c=o&t.EXIT;c&&await n(s),o&t.ENTER&&await s.stack.push(s.current);let a=await r(s);return a?(s.current=a,o=s.status=c?t.NEXT:t.FIRST,await e(s)):(a=s.current=await s.stack.pop(),o=s.status=a?c?t.LAST:t.LEAF:t.NONE),o!==t.NONE}}function s(t={}){const{key:e,transitions:n=[],states:r={},options:o,...c}=t,a={key:e,transitions:{},states:{},options:Object.assign(o||{},c)};for(const t of n){let e,n,s;if(Array.isArray(t))e=t[0],n=t[1],s=t[2];else{const{from:r,event:o,to:c}=t;e=r,n=o,s=c}(a.transitions[e]=a.transitions[e]||{})[n]=s}if(Array.isArray(r))for(const t of r)a.states[t.key]=s(t);else if(r)for(const t of Object.keys(r))a.states[t]=s(r[t]);return a}var r={STATE_ANY:"*",STATE_INITIAL:"",STATE_FINAL:"",EVENT_ANY:"*",EVENT_EMPTY:""};function o(t){return function t(e,n=[],s=[]){s=[...s,e.key];const o=Object.assign({key:e.key},function(t){const e={},n={};for(const[s,r]of Object.entries(t.transitions)){e[s]=(e[s]||0)+1;for(const t of Object.values(r))n[t]=(n[t]||0)+1}const s=[],o=[];for(const t of Object.keys(e))t===r.STATE_ANY||t===r.STATE_FINAL||t===r.STATE_INITIAL||t in n||s.push(t);for(const t of Object.keys(n))t===r.STATE_FINAL||t in e||o.push(t);return{unreachableStates:s,deadendStates:o}}(e));if(o.deadendStates.length||o.unreachableStates.length){const t={path:s};n.push(t),o.deadendStates.length&&(t.deadendStates=o.deadendStates),o.unreachableStates.length&&(t.unreachableStates=o.unreachableStates)}for(const r of Object.values(e.states))t(r,n,s);return n}(t)}function c(t,e){let n;for(let s=t.stack.length-1;!n&&s>=0;s--){n=(t.stack[s].descriptor.states||{})[e]}return n||{transitions:{},states:{}}}function a(t){const e={},n=t=>e[t]=(e[t]||0)+1;return function t(e){n(e.key);for(const[t,s]of Object.entries(e.transitions)){n(t);for(const t of Object.values(s))n(t)}for(const[s,r]of Object.entries(e.states))n(s),t(r)}(t),Object.keys(e).sort()}function i(t){const e=[];let n=t.current?t.current.key:r.STATE_INITIAL;for(let s=t.stack.length-1;s>=0;s--){const o=t.stack[s],c=o.key,a=o.descriptor;for(const t of[n,r.STATE_ANY]){const n=a.transitions[t];if(n)for(const[s,r]of Object.entries(n))e.push([c,t,s,r])}n=c}return e}function u(t,e,n){const s=[[e,n],[r.STATE_ANY,n],[e,r.EVENT_ANY],[r.STATE_ANY,r.EVENT_ANY]];let o;for(let e=0,n=s.length;void 0===o&&e<n;e++){const[n,c]=s[e],a=t.transitions[n];a&&(o=a[c],void 0===o&&(o=a[r.EVENT_ANY]))}return void 0!==o?o:r.STATE_FINAL}function f({config:e,descriptor:n,newState:o=(t=>t),newProcess:a=(t=>({descriptor:t,status:0,stack:[],event:void 0,current:void 0}))}){const i=a(n=n||s(e));return[i,()=>{let e,n;if(i.status)if(i.stack.length){const s=i.event.key||r.EVENT_EMPTY;e=u(i.stack[i.stack.length-1].descriptor,i.status&t.ENTER?r.STATE_INITIAL:i.current?i.current.key:r.STATE_FINAL,s),e&&(n=c(i,e))}else e=r.STATE_FINAL;else n=i.descriptor,e=n.key;return e?o({process:i,key:e,descriptor:n}):null}]}function E({config:e,descriptor:s,before:r,after:o,newProcess:c,newState:a,handleError:i=console.error}){const[u,E]=f({config:e,descriptor:s,newProcess:c,newState:a}),T=n(r,o,u);return u.finished=!1,u.next=e=>(u.nextEvent=e,u.running=u.running||Promise.resolve().then((async()=>{try{for(;!u.finished;){if(u.nextEvent)u.event=u.nextEvent,u.nextEvent=void 0;else if(u.status&t.LEAF)break;u.finished=!await T(E)}}catch(t){i(t)}})).finally((()=>u.running=void 0)).then((()=>!u.finished))),u}function T({config:n,descriptor:s,before:r,after:o,newProcess:c,newState:a}){const[i,u]=f({config:n,descriptor:s,newProcess:c,newState:a}),E=e(r,o,i);return i.dispatch=i.next=e=>{for("string"==typeof e&&(e={key:e}),i.event=e;i.event;){if(!E(u))return!1;if(i.status&t.LEAF)return!0}},i}export{r as KEYS,t as MODE,s as buildStateDescriptor,o as checkProcessDescriptor,a as getAllStateKeys,i as getAllTransitions,c as getStateDescriptor,u as getTargetStateKey,E as newAsyncProcess,n as newAsyncTreeWalker,f as newProcessInstance,T as newSyncProcess,e as newTreeWalker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statewalker/fsm",
3
- "version": "0.9.0",
3
+ "version": "0.9.3",
4
4
  "description": "Utility graph methods (iterators, tree builders etc)",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/statewalker/statewalker",
@@ -31,20 +31,19 @@
31
31
  "url": "https://github.com/statewalker/statewalker.git"
32
32
  },
33
33
  "devDependencies": {
34
- "@statewalker/tree": "^0.9.0"
34
+ "@statewalker/tree": "^0.9.1"
35
35
  },
36
36
  "scripts": {
37
37
  "eslint": "../../node_modules/eslint/bin/eslint.js src",
38
38
  "rollup": "../../node_modules/rollup/dist/bin/rollup -c",
39
39
  "test": "../../node_modules/mocha/bin/mocha -R spec ./test/index.js && yarn eslint",
40
40
  "prepare": "yarn rollup",
41
- "prepublishOnly": "rm -rf dist && yarn test",
41
+ "prepublishOnly": "rm -rf dist && yarn test && yarn rollup",
42
42
  "postpublish": "zip -j dist/statewalker-fsm.zip -- ../../LICENSE README.md dist/*.js"
43
43
  },
44
44
  "license": "MIT",
45
45
  "sideEffects": false,
46
46
  "publishConfig": {
47
47
  "access": "public"
48
- },
49
- "gitHead": "af84ae369e62a81037e0a89740883bc06ba8f559"
48
+ }
50
49
  }
@@ -7,24 +7,39 @@ export default function newAsyncProcess({
7
7
  before, after,
8
8
  newProcess,
9
9
  newState,
10
+ handleError = console.error
10
11
  }) {
11
12
  const [process, loadNextState] = newProcessInstance({
12
13
  config,
13
14
  descriptor,
14
15
  newProcess,
15
- newState,
16
+ newState
16
17
  });
17
18
  const shift = newAsyncTreeWalker(before, after, process);
18
- process.running = Promise.resolve();
19
- process.next = async (event) => {
20
- await process.running;
21
- return await (process.running = (async() => {
22
- process.event = event;
23
- while (process.event) {
24
- if (!await shift(loadNextState)) return false;
25
- if (process.status & MODE.LEAF) return true;
26
- }
27
- })())
19
+ process.finished = false;
20
+ process.next = (event) => {
21
+ process.nextEvent = event;
22
+ return process.running = process.running || Promise
23
+ .resolve()
24
+ .then(async () => {
25
+ try {
26
+ while (!process.finished) {
27
+ if (process.nextEvent) {
28
+ // Consume the next event if it exists.
29
+ process.event = process.nextEvent;
30
+ process.nextEvent = undefined;
31
+ } else if (process.status & MODE.LEAF) {
32
+ // Returns control when the process is in a "leaf" state (a state without children)
33
+ break;
34
+ }
35
+ process.finished = !await shift(loadNextState);
36
+ }
37
+ } catch (error) {
38
+ handleError(error);
39
+ }
40
+ })
41
+ .finally(() => process.running = undefined)
42
+ .then(() => !process.finished);
28
43
  }
29
44
  return process;
30
45
  }
@@ -1,7 +1,7 @@
1
1
  import { MODE, newTreeWalker } from "@statewalker/tree";
2
2
  import newProcessInstance from "./newProcessInstance.js";
3
3
 
4
- export default function newSyncProcess({
4
+ export default function newSyncProcess({
5
5
  config,
6
6
  descriptor,
7
7
  before, after,
@@ -15,7 +15,8 @@ export default function newSyncProcess({
15
15
  newState,
16
16
  });
17
17
  const shift = newTreeWalker(before, after, process);
18
- process.next = (event) => {
18
+ process.dispatch = process.next = (event) => {
19
+ if (typeof event === 'string') event = { key : event };
19
20
  process.event = event;
20
21
  while (process.event) {
21
22
  if (!shift(loadNextState)) return false;
package/LICENSE DELETED
@@ -1,27 +0,0 @@
1
- Copyright 2010-2020 Mikhail Kotelnikov
2
- All rights reserved.
3
-
4
- Redistribution and use in source and binary forms, with or without modification,
5
- are permitted provided that the following conditions are met:
6
-
7
- * Redistributions of source code must retain the above copyright notice, this
8
- list of conditions and the following disclaimer.
9
-
10
- * Redistributions in binary form must reproduce the above copyright notice,
11
- this list of conditions and the following disclaimer in the documentation
12
- and/or other materials provided with the distribution.
13
-
14
- * Neither the name of the author nor the names of contributors may be used to
15
- endorse or promote products derived from this software without specific prior
16
- written permission.
17
-
18
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.