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