1 | import { mapValues, isFunction } from './utils.js';
|
2 |
|
3 | function stringifyFunction(fn) {
|
4 | return {
|
5 | $function: fn.toString()
|
6 | };
|
7 | }
|
8 |
|
9 | function getStateNodeId(stateNode) {
|
10 | return "#".concat(stateNode.id);
|
11 | }
|
12 |
|
13 |
|
14 | function machineToJSON(stateNode) {
|
15 | var config = {
|
16 | type: stateNode.type,
|
17 | initial: stateNode.initial === undefined ? undefined : String(stateNode.initial),
|
18 | id: stateNode.id,
|
19 | key: stateNode.key,
|
20 | entry: stateNode.onEntry,
|
21 | exit: stateNode.onExit,
|
22 | on: mapValues(stateNode.on, function (transition) {
|
23 | return transition.map(function (t) {
|
24 | return {
|
25 | target: t.target ? t.target.map(getStateNodeId) : [],
|
26 | source: getStateNodeId(t.source),
|
27 | actions: t.actions,
|
28 | cond: t.cond,
|
29 | eventType: t.eventType
|
30 | };
|
31 | });
|
32 | }),
|
33 | invoke: stateNode.invoke,
|
34 | states: {}
|
35 | };
|
36 | Object.values(stateNode.states).forEach(function (sn) {
|
37 | config.states[sn.key] = machineToJSON(sn);
|
38 | });
|
39 | return config;
|
40 | }
|
41 | function stringify(machine) {
|
42 | return JSON.stringify(machineToJSON(machine), function (_, value) {
|
43 | if (isFunction(value)) {
|
44 | return {
|
45 | $function: value.toString()
|
46 | };
|
47 | }
|
48 |
|
49 | return value;
|
50 | });
|
51 | }
|
52 | function parse(machineString) {
|
53 | var config = JSON.parse(machineString, function (_, value) {
|
54 | if (typeof value === 'object' && '$function' in value) {
|
55 | return new Function(value.value);
|
56 | }
|
57 |
|
58 | return value;
|
59 | });
|
60 | return config;
|
61 | }
|
62 | function jsonify(value) {
|
63 | Object.defineProperty(value, 'toJSON', {
|
64 | value: function () {
|
65 | return mapValues(value, function (subValue) {
|
66 | if (isFunction(subValue)) {
|
67 | return stringifyFunction(subValue);
|
68 | } else if (typeof subValue === 'object' && !Array.isArray(subValue)) {
|
69 |
|
70 | return mapValues(subValue, function (subSubValue) {
|
71 | if (isFunction(subSubValue)) {
|
72 | return stringifyFunction(subSubValue);
|
73 | }
|
74 |
|
75 | return subSubValue;
|
76 | });
|
77 | }
|
78 |
|
79 | return subValue;
|
80 | });
|
81 | }
|
82 | });
|
83 | return value;
|
84 | }
|
85 |
|
86 | export { jsonify, machineToJSON, parse, stringify, stringifyFunction };
|