1 | "use strict";
|
2 | var __assign = (this && this.__assign) || function () {
|
3 | __assign = Object.assign || function(t) {
|
4 | for (var s, i = 1, n = arguments.length; i < n; i++) {
|
5 | s = arguments[i];
|
6 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
7 | t[p] = s[p];
|
8 | }
|
9 | return t;
|
10 | };
|
11 | return __assign.apply(this, arguments);
|
12 | };
|
13 | var __read = (this && this.__read) || function (o, n) {
|
14 | var m = typeof Symbol === "function" && o[Symbol.iterator];
|
15 | if (!m) return o;
|
16 | var i = m.call(o), r, ar = [], e;
|
17 | try {
|
18 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
19 | }
|
20 | catch (error) { e = { error: error }; }
|
21 | finally {
|
22 | try {
|
23 | if (r && !r.done && (m = i["return"])) m.call(i);
|
24 | }
|
25 | finally { if (e) throw e.error; }
|
26 | }
|
27 | return ar;
|
28 | };
|
29 | var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
30 | if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
31 | if (ar || !(i in from)) {
|
32 | if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
33 | ar[i] = from[i];
|
34 | }
|
35 | }
|
36 | return to.concat(ar || Array.prototype.slice.call(from));
|
37 | };
|
38 | var __values = (this && this.__values) || function(o) {
|
39 | var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
40 | if (m) return m.call(o);
|
41 | if (o && typeof o.length === "number") return {
|
42 | next: function () {
|
43 | if (o && i >= o.length) o = void 0;
|
44 | return { value: o && o[i++], done: !o };
|
45 | }
|
46 | };
|
47 | throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
48 | };
|
49 | Object.defineProperty(exports, "__esModule", { value: true });
|
50 | exports.toMachine = void 0;
|
51 | var xml_js_1 = require("xml-js");
|
52 | var index_1 = require("./index");
|
53 | var utils_1 = require("./utils");
|
54 | var actions = require("./actions");
|
55 | function getAttribute(element, attribute) {
|
56 | return element.attributes ? element.attributes[attribute] : undefined;
|
57 | }
|
58 | function indexedRecord(items, identifier) {
|
59 | var record = {};
|
60 | var identifierFn = (0, utils_1.isString)(identifier)
|
61 | ? function (item) { return item[identifier]; }
|
62 | : identifier;
|
63 | items.forEach(function (item) {
|
64 | var key = identifierFn(item);
|
65 | record[key] = item;
|
66 | });
|
67 | return record;
|
68 | }
|
69 | function executableContent(elements) {
|
70 | var transition = {
|
71 | actions: mapActions(elements)
|
72 | };
|
73 | return transition;
|
74 | }
|
75 | function getTargets(targetAttr) {
|
76 |
|
77 | return targetAttr
|
78 | ? "".concat(targetAttr).split(/\s+/).map(function (target) { return "#".concat(target); })
|
79 | : undefined;
|
80 | }
|
81 | function delayToMs(delay) {
|
82 | if (!delay) {
|
83 | return undefined;
|
84 | }
|
85 | if (typeof delay === 'number') {
|
86 | return delay;
|
87 | }
|
88 | var millisecondsMatch = delay.match(/(\d+)ms/);
|
89 | if (millisecondsMatch) {
|
90 | return parseInt(millisecondsMatch[1], 10);
|
91 | }
|
92 | var secondsMatch = delay.match(/(\d*)(\.?)(\d+)s/);
|
93 | if (secondsMatch) {
|
94 | var hasDecimal = !!secondsMatch[2];
|
95 | if (!hasDecimal) {
|
96 | return parseInt(secondsMatch[3], 10) * 1000;
|
97 | }
|
98 | var secondsPart = !!secondsMatch[1]
|
99 | ? parseInt(secondsMatch[1], 10) * 1000
|
100 | : 0;
|
101 | var millisecondsPart = parseInt(secondsMatch[3].padEnd(3, '0'), 10);
|
102 | if (millisecondsPart >= 1000) {
|
103 | throw new Error("Can't parse \"".concat(delay, " delay.\""));
|
104 | }
|
105 | return secondsPart + millisecondsPart;
|
106 | }
|
107 | throw new Error("Can't parse \"".concat(delay, " delay.\""));
|
108 | }
|
109 | var evaluateExecutableContent = function (context, _ev, meta, body) {
|
110 | var datamodel = context
|
111 | ? Object.keys(context)
|
112 | .map(function (key) { return "const ".concat(key, " = context['").concat(key, "'];"); })
|
113 | .join('\n')
|
114 | : '';
|
115 | var scope = ['const _sessionid = "NOT_IMPLEMENTED";', datamodel]
|
116 | .filter(Boolean)
|
117 | .join('\n');
|
118 | var args = ['context', '_event'];
|
119 | var fnBody = "\n ".concat(scope, "\n ").concat(body, "\n ");
|
120 | var fn = new (Function.bind.apply(Function, __spreadArray(__spreadArray([void 0], __read(args), false), [fnBody], false)))();
|
121 | return fn(context, meta._event);
|
122 | };
|
123 | function createCond(cond) {
|
124 | return function (context, _event, meta) {
|
125 | return evaluateExecutableContent(context, _event, meta, "return ".concat(cond, ";"));
|
126 | };
|
127 | }
|
128 | function mapAction(element) {
|
129 | var e_1, _a;
|
130 | switch (element.name) {
|
131 | case 'raise': {
|
132 | return actions.raise(element.attributes.event);
|
133 | }
|
134 | case 'assign': {
|
135 | return actions.assign(function (context, e, meta) {
|
136 | var fnBody = "\n return {'".concat(element.attributes.location, "': ").concat(element.attributes.expr, "};\n ");
|
137 | return evaluateExecutableContent(context, e, meta, fnBody);
|
138 | });
|
139 | }
|
140 | case 'send': {
|
141 | var _b = element.attributes, event_1 = _b.event, eventexpr_1 = _b.eventexpr, target = _b.target;
|
142 | var convertedEvent = void 0;
|
143 | var convertedDelay = void 0;
|
144 | var params_1 = element.elements &&
|
145 | element.elements.reduce(function (acc, child) {
|
146 | if (child.name === 'content') {
|
147 | throw new Error('Conversion of <content/> inside <send/> not implemented.');
|
148 | }
|
149 | return "".concat(acc).concat(child.attributes.name, ":").concat(child.attributes.expr, ",\n");
|
150 | }, '');
|
151 | if (event_1 && !params_1) {
|
152 | convertedEvent = event_1;
|
153 | }
|
154 | else {
|
155 | convertedEvent = function (context, _ev, meta) {
|
156 | var fnBody = "\n return { type: ".concat(event_1 ? "\"".concat(event_1, "\"") : eventexpr_1, ", ").concat(params_1 ? params_1 : '', " }\n ");
|
157 | return evaluateExecutableContent(context, _ev, meta, fnBody);
|
158 | };
|
159 | }
|
160 | if ('delay' in element.attributes) {
|
161 | convertedDelay = delayToMs(element.attributes.delay);
|
162 | }
|
163 | else if (element.attributes.delayexpr) {
|
164 | convertedDelay = function (context, _ev, meta) {
|
165 | var fnBody = "\n return (".concat(delayToMs, ")(").concat(element.attributes.delayexpr, ");\n ");
|
166 | return evaluateExecutableContent(context, _ev, meta, fnBody);
|
167 | };
|
168 | }
|
169 | return actions.send(convertedEvent, {
|
170 | delay: convertedDelay,
|
171 | to: target
|
172 | });
|
173 | }
|
174 | case 'log': {
|
175 | var label = element.attributes.label;
|
176 | return actions.log(function (context, e, meta) {
|
177 | var fnBody = "\n return ".concat(element.attributes.expr, ";\n ");
|
178 | return evaluateExecutableContent(context, e, meta, fnBody);
|
179 | }, label !== undefined ? String(label) : undefined);
|
180 | }
|
181 | case 'if': {
|
182 | var conds = [];
|
183 | var current = {
|
184 | cond: createCond(element.attributes.cond),
|
185 | actions: []
|
186 | };
|
187 | try {
|
188 | for (var _c = __values(element.elements), _d = _c.next(); !_d.done; _d = _c.next()) {
|
189 | var el = _d.value;
|
190 | if (el.type === 'comment') {
|
191 | continue;
|
192 | }
|
193 | switch (el.name) {
|
194 | case 'elseif':
|
195 | conds.push(current);
|
196 | current = {
|
197 | cond: createCond(el.attributes.cond),
|
198 | actions: []
|
199 | };
|
200 | break;
|
201 | case 'else':
|
202 | conds.push(current);
|
203 | current = { actions: [] };
|
204 | break;
|
205 | default:
|
206 | current.actions.push(mapAction(el));
|
207 | break;
|
208 | }
|
209 | }
|
210 | }
|
211 | catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
212 | finally {
|
213 | try {
|
214 | if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
|
215 | }
|
216 | finally { if (e_1) throw e_1.error; }
|
217 | }
|
218 | conds.push(current);
|
219 | return actions.choose(conds);
|
220 | }
|
221 | default:
|
222 | throw new Error("Conversion of \"".concat(element.name, "\" elements is not implemented yet."));
|
223 | }
|
224 | }
|
225 | function mapActions(elements) {
|
226 | var e_2, _a;
|
227 | var mapped = [];
|
228 | try {
|
229 | for (var elements_1 = __values(elements), elements_1_1 = elements_1.next(); !elements_1_1.done; elements_1_1 = elements_1.next()) {
|
230 | var element = elements_1_1.value;
|
231 | if (element.type === 'comment') {
|
232 | continue;
|
233 | }
|
234 | mapped.push(mapAction(element));
|
235 | }
|
236 | }
|
237 | catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
238 | finally {
|
239 | try {
|
240 | if (elements_1_1 && !elements_1_1.done && (_a = elements_1.return)) _a.call(elements_1);
|
241 | }
|
242 | finally { if (e_2) throw e_2.error; }
|
243 | }
|
244 | return mapped;
|
245 | }
|
246 | function toConfig(nodeJson, id, options) {
|
247 | var parallel = nodeJson.name === 'parallel';
|
248 | var initial = parallel ? undefined : nodeJson.attributes.initial;
|
249 | var elements = nodeJson.elements;
|
250 | switch (nodeJson.name) {
|
251 | case 'history': {
|
252 | if (!elements) {
|
253 | return {
|
254 | id: id,
|
255 | history: nodeJson.attributes.type || 'shallow'
|
256 | };
|
257 | }
|
258 | var _a = __read(elements.filter(function (element) { return element.name === 'transition'; }), 1), transitionElement = _a[0];
|
259 | var target = getAttribute(transitionElement, 'target');
|
260 | var history_1 = getAttribute(nodeJson, 'type') || 'shallow';
|
261 | return {
|
262 | id: id,
|
263 | history: history_1,
|
264 | target: target ? "#".concat(target) : undefined
|
265 | };
|
266 | }
|
267 | case 'final': {
|
268 | return __assign(__assign({}, nodeJson.attributes), { type: 'final' });
|
269 | }
|
270 | default:
|
271 | break;
|
272 | }
|
273 | if (nodeJson.elements) {
|
274 | var stateElements = nodeJson.elements.filter(function (element) {
|
275 | return element.name === 'state' ||
|
276 | element.name === 'parallel' ||
|
277 | element.name === 'final' ||
|
278 | element.name === 'history';
|
279 | });
|
280 | var transitionElements = nodeJson.elements.filter(function (element) { return element.name === 'transition'; });
|
281 | var invokeElements = nodeJson.elements.filter(function (element) { return element.name === 'invoke'; });
|
282 | var onEntryElement = nodeJson.elements.find(function (element) { return element.name === 'onentry'; });
|
283 | var onExitElement = nodeJson.elements.find(function (element) { return element.name === 'onexit'; });
|
284 | var states = indexedRecord(stateElements, function (item) { return "".concat(item.attributes.id); });
|
285 | var initialElement = !initial
|
286 | ? nodeJson.elements.find(function (element) { return element.name === 'initial'; })
|
287 | : undefined;
|
288 | if (initialElement && initialElement.elements.length) {
|
289 | initial = initialElement.elements.find(function (element) { return element.name === 'transition'; }).attributes.target;
|
290 | }
|
291 | else if (!initialElement && stateElements.length) {
|
292 | initial = stateElements[0].attributes.id;
|
293 | }
|
294 | var on = transitionElements.map(function (value) {
|
295 | var event = getAttribute(value, 'event') || '';
|
296 | var targets = getAttribute(value, 'target');
|
297 | var internal = getAttribute(value, 'type') === 'internal';
|
298 | return __assign(__assign(__assign({ event: event, target: getTargets(targets) }, (value.elements ? executableContent(value.elements) : undefined)), (value.attributes && value.attributes.cond
|
299 | ? {
|
300 | cond: createCond(value.attributes.cond)
|
301 | }
|
302 | : undefined)), { internal: internal });
|
303 | });
|
304 | var onEntry = onEntryElement
|
305 | ? mapActions(onEntryElement.elements)
|
306 | : undefined;
|
307 | var onExit = onExitElement
|
308 | ? mapActions(onExitElement.elements)
|
309 | : undefined;
|
310 | var invoke = invokeElements.map(function (element) {
|
311 | if (!['scxml', 'http://www.w3.org/TR/scxml/'].includes(element.attributes.type)) {
|
312 | throw new Error('Currently only converting invoke elements of type SCXML is supported.');
|
313 | }
|
314 | var content = element.elements.find(function (el) { return el.name === 'content'; });
|
315 | return scxmlToMachine(content, options);
|
316 | });
|
317 | return __assign(__assign(__assign(__assign(__assign(__assign(__assign({ id: id }, (initial ? { initial: initial } : undefined)), (parallel ? { type: 'parallel' } : undefined)), (stateElements.length
|
318 | ? {
|
319 | states: (0, utils_1.mapValues)(states, function (state, key) {
|
320 | return toConfig(state, key, options);
|
321 | })
|
322 | }
|
323 | : undefined)), (transitionElements.length ? { on: on } : undefined)), (onEntry ? { onEntry: onEntry } : undefined)), (onExit ? { onExit: onExit } : undefined)), (invoke.length ? { invoke: invoke } : undefined));
|
324 | }
|
325 | return { id: id };
|
326 | }
|
327 | function scxmlToMachine(scxmlJson, options) {
|
328 | var machineElement = scxmlJson.elements.find(function (element) { return element.name === 'scxml'; });
|
329 | var dataModelEl = machineElement.elements.filter(function (element) { return element.name === 'datamodel'; })[0];
|
330 | var extState = dataModelEl
|
331 | ? dataModelEl
|
332 | .elements.filter(function (element) { return element.name === 'data'; })
|
333 | .reduce(function (acc, element) {
|
334 | if (element.attributes.src) {
|
335 | throw new Error("Conversion of `src` attribute on datamodel's <data> elements is not supported.");
|
336 | }
|
337 | acc[element.attributes.id] = element.attributes.expr
|
338 | ?
|
339 | eval("(".concat(element.attributes.expr, ")"))
|
340 | : undefined;
|
341 | return acc;
|
342 | }, {})
|
343 | : undefined;
|
344 | return (0, index_1.Machine)(__assign(__assign({}, toConfig(machineElement, '(machine)', options)), { context: extState, delimiter: options.delimiter }));
|
345 | }
|
346 | function toMachine(xml, options) {
|
347 | var json = (0, xml_js_1.xml2js)(xml);
|
348 | return scxmlToMachine(json, options);
|
349 | }
|
350 | exports.toMachine = toMachine;
|