@tinyactors/scxmljs 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +174 -0
- package/THIRD_PARTY_NOTICES +63 -0
- package/dist/bridge.d.ts +44 -0
- package/dist/bridge.js +254 -0
- package/dist/bridge.js.map +1 -0
- package/dist/clock.d.ts +113 -0
- package/dist/clock.js +310 -0
- package/dist/clock.js.map +1 -0
- package/dist/common.d.ts +15 -0
- package/dist/common.js +14 -0
- package/dist/common.js.map +1 -0
- package/dist/datamodel-base.d.ts +122 -0
- package/dist/datamodel-base.js +268 -0
- package/dist/datamodel-base.js.map +1 -0
- package/dist/datamodel-quickjs.d.ts +21 -0
- package/dist/datamodel-quickjs.js +286 -0
- package/dist/datamodel-quickjs.js.map +1 -0
- package/dist/datamodel-trusted.d.ts +1 -0
- package/dist/datamodel-trusted.js +149 -0
- package/dist/datamodel-trusted.js.map +1 -0
- package/dist/diagnostics.d.ts +39 -0
- package/dist/diagnostics.js +154 -0
- package/dist/diagnostics.js.map +1 -0
- package/dist/element-events.d.ts +85 -0
- package/dist/element-events.js +129 -0
- package/dist/element-events.js.map +1 -0
- package/dist/events.d.ts +31 -0
- package/dist/events.js +33 -0
- package/dist/events.js.map +1 -0
- package/dist/explorer/element.d.ts +150 -0
- package/dist/explorer/element.js +1791 -0
- package/dist/explorer/element.js.map +1 -0
- package/dist/explorer/layout.d.ts +43 -0
- package/dist/explorer/layout.js +50 -0
- package/dist/explorer/layout.js.map +1 -0
- package/dist/explorer/strings.d.ts +275 -0
- package/dist/explorer/strings.js +135 -0
- package/dist/explorer/strings.js.map +1 -0
- package/dist/explorer/styles.d.ts +10 -0
- package/dist/explorer/styles.js +265 -0
- package/dist/explorer/styles.js.map +1 -0
- package/dist/explorer/viewmodel.d.ts +284 -0
- package/dist/explorer/viewmodel.js +481 -0
- package/dist/explorer/viewmodel.js.map +1 -0
- package/dist/explorer.d.ts +21 -0
- package/dist/explorer.js +22 -0
- package/dist/explorer.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/dist/model.d.ts +157 -0
- package/dist/model.js +485 -0
- package/dist/model.js.map +1 -0
- package/dist/session-events.d.ts +136 -0
- package/dist/session-events.js +114 -0
- package/dist/session-events.js.map +1 -0
- package/dist/session.d.ts +412 -0
- package/dist/session.js +1399 -0
- package/dist/session.js.map +1 -0
- package/dist/themes/tinyactors.css +44 -0
- package/dist/trusted.d.ts +15 -0
- package/dist/trusted.js +30 -0
- package/dist/trusted.js.map +1 -0
- package/dist/ui/announcer.d.ts +22 -0
- package/dist/ui/announcer.js +31 -0
- package/dist/ui/announcer.js.map +1 -0
- package/dist/ui/svg.d.ts +8 -0
- package/dist/ui/svg.js +29 -0
- package/dist/ui/svg.js.map +1 -0
- package/dist/ui/theme.d.ts +34 -0
- package/dist/ui/theme.js +151 -0
- package/dist/ui/theme.js.map +1 -0
- package/dist/view/element.d.ts +172 -0
- package/dist/view/element.js +1045 -0
- package/dist/view/element.js.map +1 -0
- package/dist/view/layout.d.ts +154 -0
- package/dist/view/layout.js +1122 -0
- package/dist/view/layout.js.map +1 -0
- package/dist/view/strings.d.ts +72 -0
- package/dist/view/strings.js +48 -0
- package/dist/view/strings.js.map +1 -0
- package/dist/view/styles.d.ts +1 -0
- package/dist/view/styles.js +115 -0
- package/dist/view/styles.js.map +1 -0
- package/dist/view.d.ts +20 -0
- package/dist/view.js +21 -0
- package/dist/view.js.map +1 -0
- package/package.json +87 -0
package/dist/session.js
ADDED
|
@@ -0,0 +1,1399 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An SCXML session: a faithful implementation of the algorithm in
|
|
3
|
+
* W3C SCXML 1.0, Appendix D, plus executable content (§4), the data model
|
|
4
|
+
* rules (§5), `<send>` / `<invoke>` (§6) and the SCXML Event I/O Processor
|
|
5
|
+
* (Appendix C.1).
|
|
6
|
+
*
|
|
7
|
+
* Procedure names follow the spec so the two can be read side by side.
|
|
8
|
+
* Performance is a non-goal: sets are rebuilt freely, nothing is cached.
|
|
9
|
+
*
|
|
10
|
+
* Scheduling: the internal queue is drained synchronously (a macrostep).
|
|
11
|
+
* External events are processed one at a time on `clock.defer`, so the
|
|
12
|
+
* session is always idle between external events and never re-entered.
|
|
13
|
+
*/
|
|
14
|
+
import { bind as bindDeclarative, connect as connectEvents, } from "./bridge.js";
|
|
15
|
+
import { realClock } from "./clock.js";
|
|
16
|
+
import { ElementBridge } from "./element-events.js";
|
|
17
|
+
import { nameMatch, parseDelay, SCXML_INVOKE_TYPES, SCXML_IOPROCESSOR } from "./events.js";
|
|
18
|
+
import { compile, documentOrder, exitOrder, isAtomic, isCompound, isCompoundOrRoot, isDescendant, properAncestors, SCXMLParseError, scxmlChildren, } from "./model.js";
|
|
19
|
+
import { ChildSessionEvent, DoneEvent, InvokeEvent, LogEvent, MacrostepEvent, MicrostepEvent, SCXMLErrorEvent, SendEvent, } from "./session-events.js";
|
|
20
|
+
// ──────────────────────────────── registry ────────────────────────────────
|
|
21
|
+
/** Sessions by id, for `#_scxml_<sessionid>` targets. */
|
|
22
|
+
const sessions = new Map();
|
|
23
|
+
let sessionCounter = 0;
|
|
24
|
+
/** Marks events that came from an invoked child (for finalize and cancellation filtering). */
|
|
25
|
+
const FROM_CHILD = Symbol("fromChild");
|
|
26
|
+
/**
|
|
27
|
+
* SCXML text, an `<scxml>` element or a compiled model → a compiled model.
|
|
28
|
+
* @internal used by the entry points' `createSession`
|
|
29
|
+
*/
|
|
30
|
+
export function resolveModel(source, opts = {}) {
|
|
31
|
+
if (typeof source === "string")
|
|
32
|
+
return compile(parseSCXML(source, opts.domParser), { loader: opts.loader });
|
|
33
|
+
if ("root" in source && "states" in source)
|
|
34
|
+
return source;
|
|
35
|
+
return compile(source, { loader: opts.loader });
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Parse SCXML text into its `<scxml>` element.
|
|
39
|
+
*
|
|
40
|
+
* Browsers have a `DOMParser`; Node, Bun and Deno don't, so pass one there
|
|
41
|
+
* (any standards-compliant implementation, e.g. happy-dom's or linkedom's).
|
|
42
|
+
*
|
|
43
|
+
* @throws {SCXMLParseError} `code: "SCXML_NO_DOMPARSER"` when no parser is
|
|
44
|
+
* available, `code: "SCXML_PARSE"` when the text isn't well-formed XML.
|
|
45
|
+
*/
|
|
46
|
+
export function parseSCXML(source, domParser) {
|
|
47
|
+
const parser = domParser ?? (typeof DOMParser !== "undefined" ? new DOMParser() : undefined);
|
|
48
|
+
if (!parser)
|
|
49
|
+
throw new SCXMLParseError("SCXML_NO_DOMPARSER", [
|
|
50
|
+
"No DOMParser is available to parse SCXML text in this environment.",
|
|
51
|
+
"Browsers provide one; Node, Bun and Deno don't. Either:",
|
|
52
|
+
" • pass one in the options, e.g. with happy-dom:",
|
|
53
|
+
' import { Window } from "happy-dom";',
|
|
54
|
+
" const { DOMParser } = new Window();",
|
|
55
|
+
" await createSession(source, { domParser: new DOMParser() });",
|
|
56
|
+
" • or pass an already-parsed <scxml> Element (or a compiled model) instead of text.",
|
|
57
|
+
].join("\n"));
|
|
58
|
+
const doc = parser.parseFromString(source, "application/xml");
|
|
59
|
+
const err = doc.getElementsByTagName("parsererror")[0];
|
|
60
|
+
if (err)
|
|
61
|
+
throw new SCXMLParseError("SCXML_PARSE", `SCXML is not well-formed XML: ${err.textContent?.trim()}`);
|
|
62
|
+
return doc.documentElement;
|
|
63
|
+
}
|
|
64
|
+
// ──────────────────────────────── session ─────────────────────────────────
|
|
65
|
+
/**
|
|
66
|
+
* A running (or not yet started) SCXML session.
|
|
67
|
+
*
|
|
68
|
+
* This is the type every session has, whichever data model runs it — use it
|
|
69
|
+
* to type code that works with any session (renderers, tests, invoked
|
|
70
|
+
* children). To create sessions, use `createSession` or `Session` from
|
|
71
|
+
* `@tinyactors/scxmljs` (sandboxed) or `@tinyactors/scxmljs/trusted`.
|
|
72
|
+
*
|
|
73
|
+
* Lifetime: `start()` runs the chart; it ends by reaching a top-level final
|
|
74
|
+
* state or by `cancel()`. Every session holds resources until `dispose()` —
|
|
75
|
+
* a data model context (a QuickJS context, or an iframe / vm realm), timers,
|
|
76
|
+
* listeners it installed with `connect()` / `bind()`, and an entry in a
|
|
77
|
+
* page-wide registry used to route `<send target="#_scxml_<sessionid>">`
|
|
78
|
+
* between sessions. Call `dispose()` when you are done with a session, even
|
|
79
|
+
* a finished one.
|
|
80
|
+
*/
|
|
81
|
+
export class SCXMLSession extends EventTarget {
|
|
82
|
+
/** The compiled chart the session runs. */
|
|
83
|
+
model;
|
|
84
|
+
/** The session's id: `_sessionid`, and the address `#_scxml_<sessionId>`. */
|
|
85
|
+
sessionId;
|
|
86
|
+
/** The session's data model (advanced: evaluate expressions against the running chart, for example in tools). */
|
|
87
|
+
datamodel;
|
|
88
|
+
opts;
|
|
89
|
+
/** The clock this session schedules on (delayed sends, deferred event processing). */
|
|
90
|
+
clock;
|
|
91
|
+
configurationSet = new Set();
|
|
92
|
+
statesToInvoke = new Set();
|
|
93
|
+
internalQueue = [];
|
|
94
|
+
externalQueue = [];
|
|
95
|
+
historyValue = new Map();
|
|
96
|
+
lateBound = new Set();
|
|
97
|
+
invoked = new Map();
|
|
98
|
+
invokeIds = new Map();
|
|
99
|
+
delayed = new Map(); // send key → timer
|
|
100
|
+
delayedBySendid = new Map();
|
|
101
|
+
processors = new Map();
|
|
102
|
+
ioSessions = new Map();
|
|
103
|
+
parent;
|
|
104
|
+
bridge;
|
|
105
|
+
running = false;
|
|
106
|
+
started = false;
|
|
107
|
+
exited = false;
|
|
108
|
+
busy = false;
|
|
109
|
+
scheduled = false;
|
|
110
|
+
sendCounter = 0;
|
|
111
|
+
settleWaiters = [];
|
|
112
|
+
resolveDone;
|
|
113
|
+
/**
|
|
114
|
+
* Resolves when the session terminates, with the top-level final state's
|
|
115
|
+
* `<donedata>` (or `undefined`). It never rejects: a session that is
|
|
116
|
+
* cancelled or disposed first resolves with `undefined` — check
|
|
117
|
+
* `session.cancelled` to tell the two apart.
|
|
118
|
+
*/
|
|
119
|
+
done = new Promise((resolve) => (this.resolveDone = resolve));
|
|
120
|
+
constructor(model, opts = {}) {
|
|
121
|
+
super();
|
|
122
|
+
this.model = model;
|
|
123
|
+
this.opts = opts;
|
|
124
|
+
this.clock = opts.clock ?? realClock;
|
|
125
|
+
if (opts.elementEvents || opts.reflect)
|
|
126
|
+
this.bridge = new ElementBridge(this, model, this.clock, !!opts.elementEvents, opts.reflect === true ? {} : opts.reflect || false);
|
|
127
|
+
this.sessionId = opts.sessionId ?? `session${++sessionCounter}.${Math.random().toString(36).slice(2, 8)}`;
|
|
128
|
+
const ioprocessors = {
|
|
129
|
+
[SCXML_IOPROCESSOR]: { location: `#_scxml_${this.sessionId}` },
|
|
130
|
+
scxml: { location: `#_scxml_${this.sessionId}` },
|
|
131
|
+
};
|
|
132
|
+
for (const p of opts.ioprocessors ?? []) {
|
|
133
|
+
const io = {
|
|
134
|
+
sessionId: this.sessionId,
|
|
135
|
+
deliver: (name, data, origin) => this.enqueueExternal({ name, type: "external", data, origin, origintype: p.type }),
|
|
136
|
+
};
|
|
137
|
+
this.ioSessions.set(p, io);
|
|
138
|
+
for (const key of [p.type, ...(p.aliases ?? [])]) {
|
|
139
|
+
this.processors.set(key, p);
|
|
140
|
+
ioprocessors[key] = { location: p.location(io) };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (!opts.datamodel)
|
|
144
|
+
throw new Error("no data model: use SCXMLSession/createSession from '@tinyactors/scxmljs' or '@tinyactors/scxmljs/trusted'");
|
|
145
|
+
this.datamodel = opts.datamodel({
|
|
146
|
+
sessionId: this.sessionId,
|
|
147
|
+
name: model.name,
|
|
148
|
+
ioprocessors,
|
|
149
|
+
In: (id) => {
|
|
150
|
+
const s = this.model.byId.get(id);
|
|
151
|
+
return !!s && this.configurationSet.has(s);
|
|
152
|
+
},
|
|
153
|
+
timeoutMs: opts.scriptTimeoutMs,
|
|
154
|
+
memoryLimitBytes: opts.memoryLimitBytes,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
// ───────────────────────────── typed listeners ─────────────────────────────
|
|
158
|
+
/**
|
|
159
|
+
* Listeners are wrapped so an exception in host code is reported and
|
|
160
|
+
* swallowed: it can never abort a step (in Bun an uncaught listener error
|
|
161
|
+
* would otherwise terminate the process).
|
|
162
|
+
*/
|
|
163
|
+
wrapped = new WeakMap();
|
|
164
|
+
addEventListener(type, listener, options) {
|
|
165
|
+
if (!listener)
|
|
166
|
+
return;
|
|
167
|
+
const key = `${type}\0${capture(options)}`;
|
|
168
|
+
let byKey = this.wrapped.get(listener);
|
|
169
|
+
if (!byKey) {
|
|
170
|
+
byKey = new Map();
|
|
171
|
+
this.wrapped.set(listener, byKey);
|
|
172
|
+
}
|
|
173
|
+
let safe = byKey.get(key);
|
|
174
|
+
if (!safe) {
|
|
175
|
+
safe = (ev) => {
|
|
176
|
+
try {
|
|
177
|
+
if (typeof listener === "function")
|
|
178
|
+
listener.call(this, ev);
|
|
179
|
+
else
|
|
180
|
+
listener.handleEvent(ev);
|
|
181
|
+
}
|
|
182
|
+
catch (e) {
|
|
183
|
+
console.error(`scxml: a "${type}" listener threw`, e);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
byKey.set(key, safe);
|
|
187
|
+
}
|
|
188
|
+
super.addEventListener(type, safe, options);
|
|
189
|
+
}
|
|
190
|
+
removeEventListener(type, listener, options) {
|
|
191
|
+
if (!listener)
|
|
192
|
+
return;
|
|
193
|
+
const safe = this.wrapped.get(listener)?.get(`${type}\0${capture(options)}`);
|
|
194
|
+
if (safe)
|
|
195
|
+
super.removeEventListener(type, safe, options);
|
|
196
|
+
}
|
|
197
|
+
// ─────────────────────────────── public API ───────────────────────────────
|
|
198
|
+
/** Active states, document order. */
|
|
199
|
+
get configuration() {
|
|
200
|
+
return [...this.configurationSet].sort(documentOrder);
|
|
201
|
+
}
|
|
202
|
+
/** The ids of the active states, document order. */
|
|
203
|
+
activeStateIds() {
|
|
204
|
+
return this.configuration.map((s) => s.id);
|
|
205
|
+
}
|
|
206
|
+
/** Whether the state with this id is active. */
|
|
207
|
+
isActive(id) {
|
|
208
|
+
const s = this.model.byId.get(id);
|
|
209
|
+
return !!s && this.configurationSet.has(s);
|
|
210
|
+
}
|
|
211
|
+
/** Whether this state node is active. */
|
|
212
|
+
isActiveNode(s) {
|
|
213
|
+
return this.configurationSet.has(s);
|
|
214
|
+
}
|
|
215
|
+
/** Active invocations: what `<invoke>` started and is still running, with the child session for SCXML invokes. */
|
|
216
|
+
get invocations() {
|
|
217
|
+
return [...this.invoked.values()].map((a) => ({ invokeid: a.id, type: a.type, state: a.node.state, node: a.node, session: a.child }));
|
|
218
|
+
}
|
|
219
|
+
/** The invoking session and invokeid, when this session was started by `<invoke>`. */
|
|
220
|
+
get parentSession() {
|
|
221
|
+
return this.parent;
|
|
222
|
+
}
|
|
223
|
+
/** `"idle"` before `start()`, `"running"`, or `"done"` once the session has terminated (see `cancelled` for how). */
|
|
224
|
+
get status() {
|
|
225
|
+
return this.exited ? "done" : this.started ? "running" : "idle";
|
|
226
|
+
}
|
|
227
|
+
/** The handle an I/O processor uses for this session. */
|
|
228
|
+
ioSession(p) {
|
|
229
|
+
return this.ioSessions.get(p);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* A plain-data copy of every variable declared with `<data>`, keyed by id.
|
|
233
|
+
*
|
|
234
|
+
* Values are copied out of the data model the way JSON would copy them:
|
|
235
|
+
* objects and arrays are copied, functions are dropped, dates become ISO
|
|
236
|
+
* strings, and properties whose value is `undefined` may be omitted. XML
|
|
237
|
+
* values are serialised strings with the sandboxed data model and DOM nodes
|
|
238
|
+
* with the trusted one. Variables created by `<script>` without `<data>`
|
|
239
|
+
* are not included. After `dispose()` it returns `{}`.
|
|
240
|
+
*/
|
|
241
|
+
snapshot() {
|
|
242
|
+
if (this.exited && !this.running && this.disposedDm)
|
|
243
|
+
return {};
|
|
244
|
+
return this.datamodel.snapshot(this.model.allData.map((d) => d.getAttribute("id")));
|
|
245
|
+
}
|
|
246
|
+
/** Enqueue an external event. */
|
|
247
|
+
send(name, data) {
|
|
248
|
+
this.enqueueExternal({ name, type: "external", data });
|
|
249
|
+
}
|
|
250
|
+
/** `interpret()` — spec Appendix D. */
|
|
251
|
+
start() {
|
|
252
|
+
if (this.started)
|
|
253
|
+
return this;
|
|
254
|
+
this.started = true;
|
|
255
|
+
this.running = true;
|
|
256
|
+
sessions.set(this.sessionId, this);
|
|
257
|
+
for (const [p, io] of this.ioSessions)
|
|
258
|
+
p.attach?.(io);
|
|
259
|
+
this.busy = true;
|
|
260
|
+
try {
|
|
261
|
+
this.initializeDatamodel();
|
|
262
|
+
for (const s of this.model.scripts)
|
|
263
|
+
this.executeContent([s]);
|
|
264
|
+
this.bridge?.start();
|
|
265
|
+
const entered = this.enterStates([this.model.root.initial]);
|
|
266
|
+
this.afterMicrostep([this.model.root.initial], [], entered, undefined);
|
|
267
|
+
this.mainEventLoop();
|
|
268
|
+
}
|
|
269
|
+
finally {
|
|
270
|
+
this.busy = false;
|
|
271
|
+
}
|
|
272
|
+
this.emit(new MacrostepEvent(this, { configuration: this.configuration }));
|
|
273
|
+
this.schedule();
|
|
274
|
+
this.checkSettled();
|
|
275
|
+
return this;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Cancel the session from outside (like a parent cancelling an invoke):
|
|
279
|
+
* it exits all states, running `onexit` handlers, without a done event.
|
|
280
|
+
*/
|
|
281
|
+
cancel() {
|
|
282
|
+
if (!this.started || this.exited)
|
|
283
|
+
return;
|
|
284
|
+
this.running = false;
|
|
285
|
+
this.wasCancelled = true;
|
|
286
|
+
if (!this.busy)
|
|
287
|
+
this.exitInterpreter();
|
|
288
|
+
this.bridge?.cleanup();
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Release everything the session holds: cancels it if it is still running
|
|
292
|
+
* (running `onexit` handlers, no done event), stops its timers, removes
|
|
293
|
+
* listeners installed by `connect()` / `bind()` and attributes set by
|
|
294
|
+
* `reflect`, frees the data model context and leaves the session registry.
|
|
295
|
+
* `done` resolves (with `undefined` if it hadn't finished). Safe to call
|
|
296
|
+
* more than once; the session can't be used afterwards.
|
|
297
|
+
*/
|
|
298
|
+
dispose() {
|
|
299
|
+
this.cancel();
|
|
300
|
+
this.bridge?.cleanup();
|
|
301
|
+
this.lifetime.abort();
|
|
302
|
+
this.disposedDm = true;
|
|
303
|
+
this.datamodel.dispose();
|
|
304
|
+
// a session disposed before it ever started never ran exitInterpreter
|
|
305
|
+
this.resolveDone(undefined);
|
|
306
|
+
this.checkSettled();
|
|
307
|
+
}
|
|
308
|
+
/** True when the session was ended by `cancel()` / `dispose()` rather than by reaching a final state. */
|
|
309
|
+
get cancelled() {
|
|
310
|
+
return this.wasCancelled;
|
|
311
|
+
}
|
|
312
|
+
wasCancelled = false;
|
|
313
|
+
disposedDm = false;
|
|
314
|
+
lifetime = new AbortController();
|
|
315
|
+
/**
|
|
316
|
+
* Aborts when the session terminates (final state, cancel) or is disposed.
|
|
317
|
+
* Pass it to `addEventListener(…, { signal })` to tie host listeners to the session.
|
|
318
|
+
*/
|
|
319
|
+
get signal() {
|
|
320
|
+
return this.lifetime.signal;
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Send `scxmlEvent` whenever `target` fires `domType` (space-separated types or an array).
|
|
324
|
+
* `scxmlEvent` may be a function of the DOM event (null/undefined: don't send);
|
|
325
|
+
* `data` computes the event data. Returns a disposer; also disconnects on
|
|
326
|
+
* `options.signal` abort and when the session terminates.
|
|
327
|
+
*/
|
|
328
|
+
connect(target, domType, scxmlEvent, data, options) {
|
|
329
|
+
return connectEvents(this, target, domType, scxmlEvent, data, options);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Declarative sends by event delegation on `root`: elements with
|
|
333
|
+
* `data-scxml-send` (see `bind` in bridge.ts for the attribute rules).
|
|
334
|
+
* Returns a disposer; also disconnects on `options.signal` abort and when
|
|
335
|
+
* the session terminates.
|
|
336
|
+
*/
|
|
337
|
+
bind(root, options) {
|
|
338
|
+
return bindDeclarative(this, root, options);
|
|
339
|
+
}
|
|
340
|
+
// ───────────────────────────── promise helpers ─────────────────────────────
|
|
341
|
+
/**
|
|
342
|
+
* Resolves once the session is idle: both queues are empty and no
|
|
343
|
+
* processing is scheduled (or the session has terminated / not started).
|
|
344
|
+
* Pending delayed `<send>`s and replies still owed by I/O processors or
|
|
345
|
+
* invoked services do not count — the session is idle while it waits for them.
|
|
346
|
+
*
|
|
347
|
+
* It is driven by the session's own scheduler, never by polling: with a
|
|
348
|
+
* `VirtualClock`, nothing happens until the host calls `clock.run()`, and
|
|
349
|
+
* the promise resolves during that call.
|
|
350
|
+
*/
|
|
351
|
+
settled() {
|
|
352
|
+
if (this.isIdle())
|
|
353
|
+
return Promise.resolve();
|
|
354
|
+
return new Promise((resolve) => this.settleWaiters.push(resolve));
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Resolves with the configuration at the first moment `what` holds:
|
|
358
|
+
* immediately, after a macrostep, or on entering a top-level final state
|
|
359
|
+
* (the configuration is cleared right after that, per the spec).
|
|
360
|
+
*
|
|
361
|
+
* `what`: a state id (active), several ids (all active) or a predicate.
|
|
362
|
+
* Rejects with `options.signal.reason` on abort, a `TimeoutError`
|
|
363
|
+
* DOMException after `timeoutMs` (measured on the session's clock), or an
|
|
364
|
+
* Error when the session terminates first.
|
|
365
|
+
*/
|
|
366
|
+
waitFor(what, options = {}) {
|
|
367
|
+
const test = typeof what === "function" ? what : (s) => (typeof what === "string" ? [what] : what).every((id) => s.isActive(id));
|
|
368
|
+
const describe = typeof what === "function" ? "the condition" : `[${typeof what === "string" ? what : what.join(", ")}]`;
|
|
369
|
+
const { signal, timeoutMs } = options;
|
|
370
|
+
return new Promise((resolve, reject) => {
|
|
371
|
+
if (signal?.aborted)
|
|
372
|
+
return reject(signal.reason);
|
|
373
|
+
let timer;
|
|
374
|
+
const cleanup = () => {
|
|
375
|
+
this.removeEventListener("macrostep", onMacrostep);
|
|
376
|
+
this.removeEventListener("microstep", onMicrostep);
|
|
377
|
+
this.signal.removeEventListener("abort", onTerminated);
|
|
378
|
+
signal?.removeEventListener("abort", onAbort);
|
|
379
|
+
if (timer !== undefined)
|
|
380
|
+
this.clock.clearTimeout(timer);
|
|
381
|
+
};
|
|
382
|
+
const check = () => {
|
|
383
|
+
let ok;
|
|
384
|
+
try {
|
|
385
|
+
ok = test(this);
|
|
386
|
+
}
|
|
387
|
+
catch (e) {
|
|
388
|
+
cleanup();
|
|
389
|
+
reject(e);
|
|
390
|
+
return true;
|
|
391
|
+
}
|
|
392
|
+
if (ok) {
|
|
393
|
+
cleanup();
|
|
394
|
+
resolve(this.configuration);
|
|
395
|
+
}
|
|
396
|
+
return ok;
|
|
397
|
+
};
|
|
398
|
+
const onMacrostep = () => void check();
|
|
399
|
+
// the only moment a top-level final state is observable
|
|
400
|
+
const onMicrostep = (e) => {
|
|
401
|
+
if (e.entered.some((s) => s.kind === "final" && s.parent === this.model.root))
|
|
402
|
+
check();
|
|
403
|
+
};
|
|
404
|
+
const onTerminated = () => {
|
|
405
|
+
cleanup();
|
|
406
|
+
reject(new Error(`session ${this.sessionId} terminated before ${describe} held`));
|
|
407
|
+
};
|
|
408
|
+
const onAbort = () => {
|
|
409
|
+
cleanup();
|
|
410
|
+
reject(signal.reason);
|
|
411
|
+
};
|
|
412
|
+
if (check())
|
|
413
|
+
return;
|
|
414
|
+
if (this.signal.aborted)
|
|
415
|
+
return onTerminated();
|
|
416
|
+
this.addEventListener("macrostep", onMacrostep);
|
|
417
|
+
this.addEventListener("microstep", onMicrostep);
|
|
418
|
+
this.signal.addEventListener("abort", onTerminated, { once: true });
|
|
419
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
420
|
+
if (timeoutMs != null)
|
|
421
|
+
timer = this.clock.setTimeout(() => {
|
|
422
|
+
timer = undefined;
|
|
423
|
+
cleanup();
|
|
424
|
+
reject(new DOMException(`timed out after ${timeoutMs}ms waiting for ${describe}`, "TimeoutError"));
|
|
425
|
+
}, timeoutMs);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* An async iterator over macrosteps, ending when the session terminates
|
|
430
|
+
* (or `options.signal` aborts). Macrosteps are buffered, so none are lost
|
|
431
|
+
* while the consumer is busy.
|
|
432
|
+
*
|
|
433
|
+
* for await (const step of session.steps()) render(step.configuration);
|
|
434
|
+
*/
|
|
435
|
+
steps(options = {}) {
|
|
436
|
+
const buffer = [];
|
|
437
|
+
let wake;
|
|
438
|
+
let ended = false;
|
|
439
|
+
const onMacrostep = (e) => {
|
|
440
|
+
buffer.push(e);
|
|
441
|
+
wake?.();
|
|
442
|
+
};
|
|
443
|
+
const end = () => {
|
|
444
|
+
if (ended)
|
|
445
|
+
return;
|
|
446
|
+
ended = true;
|
|
447
|
+
this.removeEventListener("macrostep", onMacrostep);
|
|
448
|
+
this.signal.removeEventListener("abort", end);
|
|
449
|
+
options.signal?.removeEventListener("abort", end);
|
|
450
|
+
wake?.();
|
|
451
|
+
};
|
|
452
|
+
this.addEventListener("macrostep", onMacrostep);
|
|
453
|
+
this.signal.addEventListener("abort", end, { once: true });
|
|
454
|
+
options.signal?.addEventListener("abort", end, { once: true });
|
|
455
|
+
if (this.signal.aborted || options.signal?.aborted)
|
|
456
|
+
end();
|
|
457
|
+
const iterator = {
|
|
458
|
+
[Symbol.asyncIterator]: () => iterator,
|
|
459
|
+
next: async () => {
|
|
460
|
+
while (!buffer.length && !ended)
|
|
461
|
+
await new Promise((r) => (wake = r));
|
|
462
|
+
wake = undefined;
|
|
463
|
+
const value = buffer.shift();
|
|
464
|
+
return value ? { value, done: false } : { value: undefined, done: true };
|
|
465
|
+
},
|
|
466
|
+
return: async () => {
|
|
467
|
+
end();
|
|
468
|
+
buffer.length = 0;
|
|
469
|
+
return { value: undefined, done: true };
|
|
470
|
+
},
|
|
471
|
+
};
|
|
472
|
+
return iterator;
|
|
473
|
+
}
|
|
474
|
+
isIdle() {
|
|
475
|
+
return this.exited || this.disposedDm || (!this.busy && !this.scheduled && !this.externalQueue.length && !this.internalQueue.length);
|
|
476
|
+
}
|
|
477
|
+
checkSettled() {
|
|
478
|
+
if (this.settleWaiters.length && this.isIdle())
|
|
479
|
+
for (const resolve of this.settleWaiters.splice(0))
|
|
480
|
+
resolve();
|
|
481
|
+
}
|
|
482
|
+
// ──────────────────────────── event loop (App. D) ─────────────────────────
|
|
483
|
+
/**
|
|
484
|
+
* The part of `mainEventLoop` that runs until the session has to wait for
|
|
485
|
+
* an external event: macrosteps, then invokes, repeated while invoking
|
|
486
|
+
* produced internal events.
|
|
487
|
+
*/
|
|
488
|
+
mainEventLoop() {
|
|
489
|
+
const limit = this.opts.maxMicrosteps ?? 100_000;
|
|
490
|
+
let steps = 0;
|
|
491
|
+
while (this.running) {
|
|
492
|
+
let macrostepDone = false;
|
|
493
|
+
while (this.running && !macrostepDone) {
|
|
494
|
+
let trigger;
|
|
495
|
+
let enabled = this.selectEventlessTransitions();
|
|
496
|
+
if (enabled.length === 0) {
|
|
497
|
+
trigger = this.internalQueue.shift();
|
|
498
|
+
if (!trigger)
|
|
499
|
+
macrostepDone = true;
|
|
500
|
+
else {
|
|
501
|
+
this.datamodel.setEvent(trigger);
|
|
502
|
+
enabled = this.selectTransitions(trigger);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if (enabled.length) {
|
|
506
|
+
this.microstep(enabled, trigger);
|
|
507
|
+
if (++steps > limit) {
|
|
508
|
+
this.emitError("error.platform", `more than ${limit} microsteps in one macrostep: stopping`);
|
|
509
|
+
this.running = false;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if (!this.running)
|
|
514
|
+
break;
|
|
515
|
+
for (const state of [...this.statesToInvoke].sort(documentOrder))
|
|
516
|
+
for (const inv of [...state.invokes].sort(documentOrder))
|
|
517
|
+
this.invoke(inv);
|
|
518
|
+
this.statesToInvoke.clear();
|
|
519
|
+
if (this.internalQueue.length)
|
|
520
|
+
continue;
|
|
521
|
+
break;
|
|
522
|
+
}
|
|
523
|
+
if (!this.running)
|
|
524
|
+
this.exitInterpreter();
|
|
525
|
+
}
|
|
526
|
+
/** Process one external event: the second half of `mainEventLoop`. */
|
|
527
|
+
processExternalEvent() {
|
|
528
|
+
const ev = this.externalQueue.shift();
|
|
529
|
+
if (!ev)
|
|
530
|
+
return;
|
|
531
|
+
this.datamodel.setEvent(ev);
|
|
532
|
+
for (const state of this.configuration) {
|
|
533
|
+
for (const inv of state.invokes) {
|
|
534
|
+
const active = this.invoked.get(this.invokeIds.get(inv) ?? "");
|
|
535
|
+
if (!active)
|
|
536
|
+
continue;
|
|
537
|
+
if (ev[FROM_CHILD] && ev.invokeid === active.id)
|
|
538
|
+
this.applyFinalize(inv);
|
|
539
|
+
if (inv.autoforward)
|
|
540
|
+
this.deliverToInvoke(active, stripMarks(ev)); // every external event (§6.4.1)
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
const enabled = this.selectTransitions(ev);
|
|
544
|
+
if (enabled.length)
|
|
545
|
+
this.microstep(enabled, ev);
|
|
546
|
+
this.mainEventLoop();
|
|
547
|
+
this.emit(new MacrostepEvent(this, { event: stripMarks(ev), configuration: this.configuration }));
|
|
548
|
+
}
|
|
549
|
+
schedule() {
|
|
550
|
+
if (this.scheduled || this.exited)
|
|
551
|
+
return;
|
|
552
|
+
if (!this.externalQueue.length && !this.internalQueue.length)
|
|
553
|
+
return;
|
|
554
|
+
this.scheduled = true;
|
|
555
|
+
this.clock.defer(() => this.pump());
|
|
556
|
+
}
|
|
557
|
+
pump() {
|
|
558
|
+
this.scheduled = false;
|
|
559
|
+
if (!this.running || this.busy)
|
|
560
|
+
return;
|
|
561
|
+
this.busy = true;
|
|
562
|
+
try {
|
|
563
|
+
if (this.internalQueue.length) {
|
|
564
|
+
// internal events that arrived asynchronously (delayed #_internal sends, late errors)
|
|
565
|
+
this.mainEventLoop();
|
|
566
|
+
this.emit(new MacrostepEvent(this, { configuration: this.configuration }));
|
|
567
|
+
}
|
|
568
|
+
else
|
|
569
|
+
this.processExternalEvent();
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
this.busy = false;
|
|
573
|
+
}
|
|
574
|
+
if (!this.running && !this.exited)
|
|
575
|
+
this.exitInterpreter();
|
|
576
|
+
this.schedule();
|
|
577
|
+
this.checkSettled();
|
|
578
|
+
}
|
|
579
|
+
enqueueExternal(ev) {
|
|
580
|
+
if (!this.running)
|
|
581
|
+
return;
|
|
582
|
+
this.externalQueue.push(ev);
|
|
583
|
+
this.schedule();
|
|
584
|
+
}
|
|
585
|
+
enqueueInternal(ev) {
|
|
586
|
+
this.internalQueue.push(ev);
|
|
587
|
+
if (!this.busy)
|
|
588
|
+
this.schedule();
|
|
589
|
+
}
|
|
590
|
+
/** `exitInterpreter()` */
|
|
591
|
+
exitInterpreter() {
|
|
592
|
+
if (this.exited)
|
|
593
|
+
return;
|
|
594
|
+
this.exited = true;
|
|
595
|
+
this.running = false;
|
|
596
|
+
let doneData;
|
|
597
|
+
let reachedFinal = false;
|
|
598
|
+
for (const s of [...this.configurationSet].sort(exitOrder)) {
|
|
599
|
+
for (const block of s.onexit)
|
|
600
|
+
this.executeContent(scxmlChildren(block, this.model.ns));
|
|
601
|
+
for (const inv of s.invokes)
|
|
602
|
+
this.cancelInvoke(inv);
|
|
603
|
+
this.configurationSet.delete(s);
|
|
604
|
+
if (s.kind === "final" && s.parent === this.model.root) {
|
|
605
|
+
reachedFinal = true;
|
|
606
|
+
doneData = this.evaluateDoneData(s);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
for (const t of this.delayed.values())
|
|
610
|
+
this.clock.clearTimeout(t);
|
|
611
|
+
this.delayed.clear();
|
|
612
|
+
for (const [p, io] of this.ioSessions)
|
|
613
|
+
p.detach?.(io);
|
|
614
|
+
sessions.delete(this.sessionId);
|
|
615
|
+
if (reachedFinal && !this.wasCancelled)
|
|
616
|
+
this.returnDoneEvent(doneData);
|
|
617
|
+
this.emit(new DoneEvent(this, { data: doneData }));
|
|
618
|
+
this.bridge?.done(doneData);
|
|
619
|
+
this.lifetime.abort();
|
|
620
|
+
this.resolveDone(doneData);
|
|
621
|
+
this.checkSettled();
|
|
622
|
+
}
|
|
623
|
+
returnDoneEvent(data) {
|
|
624
|
+
const p = this.parent;
|
|
625
|
+
if (p)
|
|
626
|
+
p.session.receiveFromChild(p.invokeid, { name: `done.invoke.${p.invokeid}`, type: "external", data });
|
|
627
|
+
}
|
|
628
|
+
// ──────────────────────────── selection (App. D) ──────────────────────────
|
|
629
|
+
selectEventlessTransitions() {
|
|
630
|
+
return this.select(null);
|
|
631
|
+
}
|
|
632
|
+
selectTransitions(ev) {
|
|
633
|
+
return this.select(ev);
|
|
634
|
+
}
|
|
635
|
+
select(ev) {
|
|
636
|
+
const enabled = [];
|
|
637
|
+
const atomic = [...this.configurationSet].filter(isAtomic).sort(documentOrder);
|
|
638
|
+
for (const state of atomic) {
|
|
639
|
+
loop: for (const s of [state, ...properAncestors(state, null)]) {
|
|
640
|
+
for (const t of [...s.transitions].sort(documentOrder)) {
|
|
641
|
+
const eventOk = ev ? t.events.length > 0 && nameMatch(t.events, ev.name) : t.events.length === 0;
|
|
642
|
+
if (eventOk && this.conditionMatch(t)) {
|
|
643
|
+
if (!enabled.includes(t))
|
|
644
|
+
enabled.push(t);
|
|
645
|
+
break loop;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return this.removeConflictingTransitions(enabled);
|
|
651
|
+
}
|
|
652
|
+
conditionMatch(t) {
|
|
653
|
+
return t.cond == null ? true : this.evaluateCondition(t.cond, t.element);
|
|
654
|
+
}
|
|
655
|
+
removeConflictingTransitions(enabled) {
|
|
656
|
+
let filtered = [];
|
|
657
|
+
for (const t1 of enabled) {
|
|
658
|
+
let t1Preempted = false;
|
|
659
|
+
const toRemove = new Set();
|
|
660
|
+
const exit1 = this.computeExitSet([t1]);
|
|
661
|
+
for (const t2 of filtered) {
|
|
662
|
+
const exit2 = this.computeExitSet([t2]);
|
|
663
|
+
if ([...exit1].some((s) => exit2.has(s))) {
|
|
664
|
+
if (isDescendant(t1.source, t2.source))
|
|
665
|
+
toRemove.add(t2);
|
|
666
|
+
else {
|
|
667
|
+
t1Preempted = true;
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (!t1Preempted) {
|
|
673
|
+
filtered = filtered.filter((t) => !toRemove.has(t));
|
|
674
|
+
filtered.push(t1);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
return filtered;
|
|
678
|
+
}
|
|
679
|
+
// ───────────────────────────── microstep (App. D) ─────────────────────────
|
|
680
|
+
microstep(enabled, event) {
|
|
681
|
+
const exited = this.exitStates(enabled);
|
|
682
|
+
this.executeTransitionContent(enabled);
|
|
683
|
+
const entered = this.enterStates(enabled);
|
|
684
|
+
this.afterMicrostep(enabled, exited, entered, event && stripMarks(event));
|
|
685
|
+
}
|
|
686
|
+
/** The configuration is consistent again: tell the host (session event, then element events / attributes). */
|
|
687
|
+
afterMicrostep(transitions, exited, entered, event) {
|
|
688
|
+
this.emit(new MicrostepEvent(this, { event, transitions, exited, entered }));
|
|
689
|
+
this.bridge?.microstep(transitions, exited, entered, event);
|
|
690
|
+
}
|
|
691
|
+
exitStates(enabled) {
|
|
692
|
+
const statesToExit = [...this.computeExitSet(enabled)];
|
|
693
|
+
for (const s of statesToExit)
|
|
694
|
+
this.statesToInvoke.delete(s);
|
|
695
|
+
statesToExit.sort(exitOrder);
|
|
696
|
+
for (const s of statesToExit)
|
|
697
|
+
for (const h of s.history)
|
|
698
|
+
this.historyValue.set(h, [...this.configurationSet].filter((s0) => (h.historyType === "deep" ? isAtomic(s0) && isDescendant(s0, s) : s0.parent === s)));
|
|
699
|
+
for (const s of statesToExit) {
|
|
700
|
+
for (const block of [...s.onexit])
|
|
701
|
+
this.executeContent(scxmlChildren(block, this.model.ns));
|
|
702
|
+
for (const inv of s.invokes)
|
|
703
|
+
this.cancelInvoke(inv);
|
|
704
|
+
this.configurationSet.delete(s);
|
|
705
|
+
}
|
|
706
|
+
return statesToExit;
|
|
707
|
+
}
|
|
708
|
+
computeExitSet(transitions) {
|
|
709
|
+
const statesToExit = new Set();
|
|
710
|
+
for (const t of transitions) {
|
|
711
|
+
if (!t.targets.length)
|
|
712
|
+
continue;
|
|
713
|
+
const domain = this.getTransitionDomain(t);
|
|
714
|
+
if (!domain)
|
|
715
|
+
continue;
|
|
716
|
+
for (const s of this.configurationSet)
|
|
717
|
+
if (isDescendant(s, domain))
|
|
718
|
+
statesToExit.add(s);
|
|
719
|
+
}
|
|
720
|
+
return statesToExit;
|
|
721
|
+
}
|
|
722
|
+
executeTransitionContent(enabled) {
|
|
723
|
+
for (const t of enabled)
|
|
724
|
+
if (t.element)
|
|
725
|
+
this.executeContent(scxmlChildren(t.element, this.model.ns));
|
|
726
|
+
}
|
|
727
|
+
enterStates(enabled) {
|
|
728
|
+
const statesToEnter = new Set();
|
|
729
|
+
const statesForDefaultEntry = new Set();
|
|
730
|
+
const defaultHistoryContent = new Map();
|
|
731
|
+
this.computeEntrySet(enabled, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
732
|
+
const entered = [...statesToEnter].sort(documentOrder);
|
|
733
|
+
for (const s of entered) {
|
|
734
|
+
this.configurationSet.add(s);
|
|
735
|
+
this.statesToInvoke.add(s);
|
|
736
|
+
if (this.model.binding === "late" && !this.lateBound.has(s)) {
|
|
737
|
+
this.lateBound.add(s);
|
|
738
|
+
this.bindData(s.data);
|
|
739
|
+
}
|
|
740
|
+
for (const block of s.onentry)
|
|
741
|
+
this.executeContent(scxmlChildren(block, this.model.ns));
|
|
742
|
+
if (statesForDefaultEntry.has(s) && s.initial?.element)
|
|
743
|
+
this.executeContent(scxmlChildren(s.initial.element, this.model.ns));
|
|
744
|
+
const hc = defaultHistoryContent.get(s);
|
|
745
|
+
if (hc)
|
|
746
|
+
this.executeContent(scxmlChildren(hc, this.model.ns));
|
|
747
|
+
if (s.kind === "final") {
|
|
748
|
+
const parent = s.parent;
|
|
749
|
+
if (parent === this.model.root)
|
|
750
|
+
this.running = false;
|
|
751
|
+
else {
|
|
752
|
+
this.internalQueue.push({ name: `done.state.${parent.id}`, type: "platform", data: this.evaluateDoneData(s) });
|
|
753
|
+
const grandparent = parent.parent;
|
|
754
|
+
if (grandparent?.kind === "parallel" && grandparent.children.every((c) => this.isInFinalState(c)))
|
|
755
|
+
this.internalQueue.push({ name: `done.state.${grandparent.id}`, type: "platform" });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
return entered;
|
|
760
|
+
}
|
|
761
|
+
computeEntrySet(transitions, statesToEnter, statesForDefaultEntry, defaultHistoryContent) {
|
|
762
|
+
for (const t of transitions) {
|
|
763
|
+
for (const s of t.targets)
|
|
764
|
+
this.addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
765
|
+
const ancestor = this.getTransitionDomain(t);
|
|
766
|
+
for (const s of this.getEffectiveTargetStates(t))
|
|
767
|
+
this.addAncestorStatesToEnter(s, ancestor, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
addDescendantStatesToEnter(state, statesToEnter, statesForDefaultEntry, defaultHistoryContent) {
|
|
771
|
+
if (state.kind === "history") {
|
|
772
|
+
const hv = this.historyValue.get(state);
|
|
773
|
+
let targets;
|
|
774
|
+
if (hv)
|
|
775
|
+
targets = hv;
|
|
776
|
+
else {
|
|
777
|
+
const t = state.transitions[0];
|
|
778
|
+
if (t.element)
|
|
779
|
+
defaultHistoryContent.set(state.parent, t.element);
|
|
780
|
+
targets = t.targets;
|
|
781
|
+
}
|
|
782
|
+
for (const s of targets)
|
|
783
|
+
this.addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
784
|
+
for (const s of targets)
|
|
785
|
+
this.addAncestorStatesToEnter(s, state.parent, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
statesToEnter.add(state);
|
|
789
|
+
if (isCompound(state)) {
|
|
790
|
+
statesForDefaultEntry.add(state);
|
|
791
|
+
for (const s of state.initial.targets)
|
|
792
|
+
this.addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
793
|
+
for (const s of state.initial.targets)
|
|
794
|
+
this.addAncestorStatesToEnter(s, state, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
795
|
+
}
|
|
796
|
+
else if (state.kind === "parallel") {
|
|
797
|
+
for (const child of state.children)
|
|
798
|
+
if (![...statesToEnter].some((s) => isDescendant(s, child)))
|
|
799
|
+
this.addDescendantStatesToEnter(child, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
addAncestorStatesToEnter(state, ancestor, statesToEnter, statesForDefaultEntry, defaultHistoryContent) {
|
|
803
|
+
for (const anc of properAncestors(state, ancestor)) {
|
|
804
|
+
if (anc.kind === "scxml")
|
|
805
|
+
continue;
|
|
806
|
+
statesToEnter.add(anc);
|
|
807
|
+
if (anc.kind === "parallel")
|
|
808
|
+
for (const child of anc.children)
|
|
809
|
+
if (![...statesToEnter].some((s) => isDescendant(s, child)))
|
|
810
|
+
this.addDescendantStatesToEnter(child, statesToEnter, statesForDefaultEntry, defaultHistoryContent);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
isInFinalState(s) {
|
|
814
|
+
if (isCompound(s))
|
|
815
|
+
return s.children.some((c) => c.kind === "final" && this.configurationSet.has(c));
|
|
816
|
+
if (s.kind === "parallel")
|
|
817
|
+
return s.children.every((c) => this.isInFinalState(c));
|
|
818
|
+
return false;
|
|
819
|
+
}
|
|
820
|
+
getTransitionDomain(t) {
|
|
821
|
+
const tstates = this.getEffectiveTargetStates(t);
|
|
822
|
+
if (!tstates.length)
|
|
823
|
+
return null;
|
|
824
|
+
if (t.type === "internal" && isCompound(t.source) && tstates.every((s) => isDescendant(s, t.source)))
|
|
825
|
+
return t.source;
|
|
826
|
+
return this.findLCCA([t.source, ...tstates]);
|
|
827
|
+
}
|
|
828
|
+
findLCCA(stateList) {
|
|
829
|
+
const [head, ...tail] = stateList;
|
|
830
|
+
for (const anc of properAncestors(head, null).filter(isCompoundOrRoot))
|
|
831
|
+
if (tail.every((s) => isDescendant(s, anc)))
|
|
832
|
+
return anc;
|
|
833
|
+
return this.model.root;
|
|
834
|
+
}
|
|
835
|
+
getEffectiveTargetStates(t) {
|
|
836
|
+
const targets = new Set();
|
|
837
|
+
for (const s of t.targets) {
|
|
838
|
+
if (s.kind === "history") {
|
|
839
|
+
const hv = this.historyValue.get(s);
|
|
840
|
+
for (const x of hv ?? this.getEffectiveTargetStates(s.transitions[0]))
|
|
841
|
+
targets.add(x);
|
|
842
|
+
}
|
|
843
|
+
else
|
|
844
|
+
targets.add(s);
|
|
845
|
+
}
|
|
846
|
+
return [...targets];
|
|
847
|
+
}
|
|
848
|
+
// ───────────────────────────── data model (§5) ────────────────────────────
|
|
849
|
+
initializeDatamodel() {
|
|
850
|
+
if (this.model.binding === "early")
|
|
851
|
+
this.bindData(this.model.allData);
|
|
852
|
+
else {
|
|
853
|
+
// late: every variable exists from the start, values are assigned on first entry
|
|
854
|
+
for (const d of this.model.allData)
|
|
855
|
+
this.declare(d.getAttribute("id"), undefined);
|
|
856
|
+
this.lateBound.add(this.model.root);
|
|
857
|
+
this.bindData(this.model.root.data);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
bindData(data) {
|
|
861
|
+
for (const d of data) {
|
|
862
|
+
const id = d.getAttribute("id");
|
|
863
|
+
if (this.opts.data && id in this.opts.data) {
|
|
864
|
+
this.declare(id, this.opts.data[id]);
|
|
865
|
+
continue;
|
|
866
|
+
}
|
|
867
|
+
try {
|
|
868
|
+
const expr = d.getAttribute("expr");
|
|
869
|
+
if (expr != null)
|
|
870
|
+
this.datamodel.declareExpr(id, expr);
|
|
871
|
+
else if (d.hasAttribute("src")) {
|
|
872
|
+
const text = this.model.resources.get(d);
|
|
873
|
+
if (text == null || text instanceof Error)
|
|
874
|
+
throw new Error(`could not load <data src="${d.getAttribute("src")}">: ${text?.message ?? "no loader"}`);
|
|
875
|
+
this.datamodel.declareValue(id, this.parseTextValue(text));
|
|
876
|
+
}
|
|
877
|
+
else
|
|
878
|
+
this.datamodel.declareValue(id, this.inlineValue(d));
|
|
879
|
+
}
|
|
880
|
+
catch (e) {
|
|
881
|
+
this.declare(id, undefined);
|
|
882
|
+
this.raiseExecutionError(e, d);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
declare(id, value) {
|
|
887
|
+
try {
|
|
888
|
+
this.datamodel.declareValue(id, value);
|
|
889
|
+
}
|
|
890
|
+
catch (e) {
|
|
891
|
+
this.raiseExecutionError(e, null);
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
/** Inline content of `<data>`, `<content>`, `<assign>` (spec §5.3, B.2): JSON, else a space-normalised string. */
|
|
895
|
+
inlineValue(el) {
|
|
896
|
+
const elements = scxmlChildrenAny(el);
|
|
897
|
+
if (elements.length)
|
|
898
|
+
return elements.length === 1 ? elements[0] : elements;
|
|
899
|
+
const text = el.textContent ?? "";
|
|
900
|
+
if (!text.trim())
|
|
901
|
+
return undefined;
|
|
902
|
+
return this.parseTextValue(text);
|
|
903
|
+
}
|
|
904
|
+
/** Text content: JSON if it parses, XML if it is a document, else a whitespace-normalised string (spec B.2). */
|
|
905
|
+
parseTextValue(text) {
|
|
906
|
+
const t = text.trim();
|
|
907
|
+
try {
|
|
908
|
+
return JSON.parse(t);
|
|
909
|
+
}
|
|
910
|
+
catch {
|
|
911
|
+
/* not JSON */
|
|
912
|
+
}
|
|
913
|
+
if (t.startsWith("<")) {
|
|
914
|
+
try {
|
|
915
|
+
return parseSCXMLLike(t, this.opts.domParser);
|
|
916
|
+
}
|
|
917
|
+
catch {
|
|
918
|
+
/* not XML either */
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return t.replace(/\s+/g, " ");
|
|
922
|
+
}
|
|
923
|
+
evaluateCondition(cond, element) {
|
|
924
|
+
try {
|
|
925
|
+
return this.datamodel.condition(cond);
|
|
926
|
+
}
|
|
927
|
+
catch (e) {
|
|
928
|
+
this.raiseExecutionError(e, element);
|
|
929
|
+
return false;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
evaluateDoneData(finalState) {
|
|
933
|
+
const dd = finalState.donedata;
|
|
934
|
+
if (!dd)
|
|
935
|
+
return undefined;
|
|
936
|
+
try {
|
|
937
|
+
return this.evaluatePayload(dd);
|
|
938
|
+
}
|
|
939
|
+
catch (e) {
|
|
940
|
+
this.raiseExecutionError(e, dd);
|
|
941
|
+
return undefined;
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
/** namelist / `<param>` / `<content>` → event data. */
|
|
945
|
+
evaluatePayload(el) {
|
|
946
|
+
const kids = scxmlChildren(el, this.model.ns);
|
|
947
|
+
const content = kids.find((c) => c.localName === "content");
|
|
948
|
+
if (content) {
|
|
949
|
+
const expr = content.getAttribute("expr");
|
|
950
|
+
return expr != null ? this.datamodel.evaluate(expr) : this.inlineValue(content);
|
|
951
|
+
}
|
|
952
|
+
const params = kids.filter((c) => c.localName === "param");
|
|
953
|
+
const namelist = (el.getAttribute("namelist") ?? "").split(/\s+/).filter(Boolean);
|
|
954
|
+
if (!params.length && !namelist.length)
|
|
955
|
+
return undefined;
|
|
956
|
+
// every key/value pair is kept, even duplicates (spec §5.7): a repeated name collects its values in an array
|
|
957
|
+
const out = {};
|
|
958
|
+
const repeated = new Set();
|
|
959
|
+
const add = (name, value) => {
|
|
960
|
+
if (!Object.hasOwn(out, name))
|
|
961
|
+
out[name] = value;
|
|
962
|
+
else if (repeated.has(name))
|
|
963
|
+
out[name].push(value);
|
|
964
|
+
else {
|
|
965
|
+
out[name] = [out[name], value];
|
|
966
|
+
repeated.add(name);
|
|
967
|
+
}
|
|
968
|
+
};
|
|
969
|
+
for (const name of namelist) {
|
|
970
|
+
if (!this.datamodel.isValidLocation(name))
|
|
971
|
+
throw new Error(`namelist: "${name}" is not a valid location`);
|
|
972
|
+
add(name, this.datamodel.evaluate(name));
|
|
973
|
+
}
|
|
974
|
+
for (const p of params) {
|
|
975
|
+
const name = p.getAttribute("name");
|
|
976
|
+
const expr = p.getAttribute("expr");
|
|
977
|
+
const location = p.getAttribute("location");
|
|
978
|
+
if (location != null && !this.datamodel.isValidLocation(location))
|
|
979
|
+
throw new Error(`<param name="${name}">: "${location}" is not a valid location`);
|
|
980
|
+
add(name, this.datamodel.evaluate(expr ?? location ?? "undefined"));
|
|
981
|
+
}
|
|
982
|
+
return out;
|
|
983
|
+
}
|
|
984
|
+
// ────────────────────────── executable content (§4) ───────────────────────
|
|
985
|
+
/** Execute a block. An error raises `error.execution` and ends the block (spec §4.9). */
|
|
986
|
+
executeContent(actions) {
|
|
987
|
+
try {
|
|
988
|
+
for (const a of actions)
|
|
989
|
+
this.execute(a);
|
|
990
|
+
}
|
|
991
|
+
catch (e) {
|
|
992
|
+
this.raiseExecutionError(e, e instanceof ActionError ? e.element : null, e instanceof ActionError ? e.sendid : undefined);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
execute(a) {
|
|
996
|
+
const attr = (n) => a.getAttribute(n);
|
|
997
|
+
const fail = (e) => {
|
|
998
|
+
throw e instanceof ActionError ? e : new ActionError(message(e), a);
|
|
999
|
+
};
|
|
1000
|
+
try {
|
|
1001
|
+
switch (a.localName) {
|
|
1002
|
+
case "raise":
|
|
1003
|
+
this.internalQueue.push({ name: attr("event"), type: "internal" });
|
|
1004
|
+
break;
|
|
1005
|
+
case "log":
|
|
1006
|
+
this.emit(new LogEvent(this, {
|
|
1007
|
+
label: attr("label") ?? "",
|
|
1008
|
+
// an empty expr (`<log label="…" expr=""/>`, as W3C test 307 writes) logs no value
|
|
1009
|
+
value: (attr("expr") ?? "").trim() ? this.datamodel.evaluate(attr("expr")) : undefined,
|
|
1010
|
+
}));
|
|
1011
|
+
break;
|
|
1012
|
+
case "assign": {
|
|
1013
|
+
const location = attr("location");
|
|
1014
|
+
const expr = attr("expr");
|
|
1015
|
+
if (expr != null)
|
|
1016
|
+
this.datamodel.assignExpr(location, expr);
|
|
1017
|
+
else
|
|
1018
|
+
this.datamodel.assignValue(location, this.inlineValue(a));
|
|
1019
|
+
break;
|
|
1020
|
+
}
|
|
1021
|
+
case "script": {
|
|
1022
|
+
const src = attr("src");
|
|
1023
|
+
const code = src != null ? this.model.resources.get(a) : (a.textContent ?? "");
|
|
1024
|
+
if (code instanceof Error || code == null)
|
|
1025
|
+
throw new Error(`script src "${src}" is unavailable`);
|
|
1026
|
+
this.datamodel.script(code);
|
|
1027
|
+
break;
|
|
1028
|
+
}
|
|
1029
|
+
case "if": {
|
|
1030
|
+
// conditions that fail to evaluate count as false (§5.9.1) — the block goes on
|
|
1031
|
+
let branchTaken = this.evaluateCondition(attr("cond"), a);
|
|
1032
|
+
let executing = branchTaken;
|
|
1033
|
+
for (const c of scxmlChildren(a, this.model.ns)) {
|
|
1034
|
+
if (c.localName === "elseif") {
|
|
1035
|
+
executing = !branchTaken && this.evaluateCondition(c.getAttribute("cond"), c);
|
|
1036
|
+
branchTaken ||= executing;
|
|
1037
|
+
}
|
|
1038
|
+
else if (c.localName === "else") {
|
|
1039
|
+
executing = !branchTaken;
|
|
1040
|
+
branchTaken = true;
|
|
1041
|
+
}
|
|
1042
|
+
else if (executing)
|
|
1043
|
+
this.execute(c);
|
|
1044
|
+
}
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1047
|
+
case "foreach":
|
|
1048
|
+
this.datamodel.foreach(attr("array"), attr("item"), attr("index"), () => {
|
|
1049
|
+
for (const c of scxmlChildren(a, this.model.ns))
|
|
1050
|
+
this.execute(c);
|
|
1051
|
+
});
|
|
1052
|
+
break;
|
|
1053
|
+
case "send":
|
|
1054
|
+
this.executeSend(a);
|
|
1055
|
+
break;
|
|
1056
|
+
case "cancel": {
|
|
1057
|
+
const sendid = attr("sendid") ?? String(this.datamodel.evaluate(attr("sendidexpr")));
|
|
1058
|
+
for (const key of this.delayedBySendid.get(sendid) ?? []) {
|
|
1059
|
+
this.clock.clearTimeout(this.delayed.get(key));
|
|
1060
|
+
this.delayed.delete(key);
|
|
1061
|
+
}
|
|
1062
|
+
this.delayedBySendid.delete(sendid);
|
|
1063
|
+
break;
|
|
1064
|
+
}
|
|
1065
|
+
default:
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
catch (e) {
|
|
1070
|
+
fail(e);
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
// ───────────────────────────── <send> (§6.2) ─────────────────────────────
|
|
1074
|
+
executeSend(a) {
|
|
1075
|
+
const attr = (n) => a.getAttribute(n);
|
|
1076
|
+
const evalAttr = (name, exprName) => {
|
|
1077
|
+
if (a.hasAttribute(name))
|
|
1078
|
+
return attr(name);
|
|
1079
|
+
if (a.hasAttribute(exprName))
|
|
1080
|
+
return String(this.datamodel.evaluate(attr(exprName)));
|
|
1081
|
+
return undefined;
|
|
1082
|
+
};
|
|
1083
|
+
// all arguments are evaluated when <send> executes (§6.2.3)
|
|
1084
|
+
const event = evalAttr("event", "eventexpr");
|
|
1085
|
+
const target = evalAttr("target", "targetexpr") ?? "";
|
|
1086
|
+
const type = evalAttr("type", "typeexpr") ?? SCXML_IOPROCESSOR;
|
|
1087
|
+
let sendid = attr("id") ?? undefined;
|
|
1088
|
+
if (a.hasAttribute("idlocation")) {
|
|
1089
|
+
sendid = `${this.sessionId}.send${++this.sendCounter}`;
|
|
1090
|
+
this.datamodel.assignValue(attr("idlocation"), sendid);
|
|
1091
|
+
}
|
|
1092
|
+
try {
|
|
1093
|
+
this.prepareAndSend(a, event, target, type, sendid);
|
|
1094
|
+
}
|
|
1095
|
+
catch (e) {
|
|
1096
|
+
throw new ActionError(message(e), a, sendid);
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
prepareAndSend(a, event, target, type, sendid) {
|
|
1100
|
+
const attr = (n) => a.getAttribute(n);
|
|
1101
|
+
const evalAttr = (name, exprName) => {
|
|
1102
|
+
if (a.hasAttribute(name))
|
|
1103
|
+
return attr(name);
|
|
1104
|
+
if (a.hasAttribute(exprName))
|
|
1105
|
+
return String(this.datamodel.evaluate(attr(exprName)));
|
|
1106
|
+
return undefined;
|
|
1107
|
+
};
|
|
1108
|
+
const delayValue = evalAttr("delay", "delayexpr");
|
|
1109
|
+
const delay = delayValue == null ? 0 : parseDelay(delayValue);
|
|
1110
|
+
if (Number.isNaN(delay))
|
|
1111
|
+
throw new Error(`<send>: invalid delay "${delayValue}"`);
|
|
1112
|
+
const data = this.evaluatePayload(a);
|
|
1113
|
+
const scxmlType = type === SCXML_IOPROCESSOR || type === "scxml";
|
|
1114
|
+
const processor = scxmlType ? undefined : this.processors.get(type);
|
|
1115
|
+
if (!scxmlType && !processor)
|
|
1116
|
+
throw new Error(`<send>: unsupported type "${type}"`);
|
|
1117
|
+
if (scxmlType && event == null)
|
|
1118
|
+
throw new Error(`<send>: the SCXML processor needs an event name`);
|
|
1119
|
+
if (scxmlType && !isValidScxmlTarget(target))
|
|
1120
|
+
throw new Error(`<send>: invalid target "${target}"`);
|
|
1121
|
+
if (delay > 0 && target === "#_internal")
|
|
1122
|
+
throw new Error(`<send>: cannot delay an event to #_internal`);
|
|
1123
|
+
const dispatch = () => {
|
|
1124
|
+
this.emit(new SendEvent(this, { message: { event: event ?? "", target, type: processor?.type ?? SCXML_IOPROCESSOR, data, sendid } }));
|
|
1125
|
+
if (processor) {
|
|
1126
|
+
try {
|
|
1127
|
+
processor.send({ event: event ?? "", target, type: processor.type, data, sendid }, this.ioSessions.get(processor));
|
|
1128
|
+
}
|
|
1129
|
+
catch (e) {
|
|
1130
|
+
this.communicationError(sendid, e);
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
else
|
|
1134
|
+
this.dispatchScxml(event, target, data, sendid);
|
|
1135
|
+
};
|
|
1136
|
+
if (delay > 0) {
|
|
1137
|
+
const key = sendid ?? `${this.sessionId}.anon${++this.sendCounter}`;
|
|
1138
|
+
const timer = this.clock.setTimeout(() => {
|
|
1139
|
+
this.delayed.delete(key);
|
|
1140
|
+
this.delayedBySendid.get(key)?.delete(key);
|
|
1141
|
+
if (this.running)
|
|
1142
|
+
dispatch();
|
|
1143
|
+
}, delay);
|
|
1144
|
+
this.delayed.set(key, timer);
|
|
1145
|
+
if (sendid) {
|
|
1146
|
+
const keys = this.delayedBySendid.get(sendid) ?? new Set();
|
|
1147
|
+
keys.add(key);
|
|
1148
|
+
this.delayedBySendid.set(sendid, keys);
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
else
|
|
1152
|
+
dispatch();
|
|
1153
|
+
}
|
|
1154
|
+
/** The SCXML Event I/O Processor (Appendix C.1). */
|
|
1155
|
+
dispatchScxml(name, target, data, sendid) {
|
|
1156
|
+
const ev = {
|
|
1157
|
+
name,
|
|
1158
|
+
type: "external",
|
|
1159
|
+
sendid,
|
|
1160
|
+
origin: `#_scxml_${this.sessionId}`,
|
|
1161
|
+
origintype: SCXML_IOPROCESSOR,
|
|
1162
|
+
data,
|
|
1163
|
+
};
|
|
1164
|
+
if (target === "")
|
|
1165
|
+
return this.enqueueExternal(ev);
|
|
1166
|
+
if (target === "#_internal")
|
|
1167
|
+
return this.enqueueInternal({ ...ev, type: "internal" });
|
|
1168
|
+
if (target === "#_parent") {
|
|
1169
|
+
if (!this.parent)
|
|
1170
|
+
return this.communicationError(sendid, "no parent session");
|
|
1171
|
+
return this.parent.session.receiveFromChild(this.parent.invokeid, ev);
|
|
1172
|
+
}
|
|
1173
|
+
if (target.startsWith("#_scxml_")) {
|
|
1174
|
+
const other = sessions.get(target.slice("#_scxml_".length));
|
|
1175
|
+
if (!other || other.status === "done")
|
|
1176
|
+
return this.communicationError(sendid, `no session "${target}"`);
|
|
1177
|
+
return other.enqueueExternal(ev);
|
|
1178
|
+
}
|
|
1179
|
+
const active = this.invoked.get(target.slice(2));
|
|
1180
|
+
if (!active)
|
|
1181
|
+
return this.communicationError(sendid, `no invoked session "${target}"`);
|
|
1182
|
+
this.deliverToInvoke(active, ev);
|
|
1183
|
+
}
|
|
1184
|
+
communicationError(sendid, e) {
|
|
1185
|
+
this.emitError("error.communication", message(e));
|
|
1186
|
+
this.enqueueInternal({ name: "error.communication", type: "platform", sendid });
|
|
1187
|
+
}
|
|
1188
|
+
// ───────────────────────────── <invoke> (§6.4) ────────────────────────────
|
|
1189
|
+
invoke(inv) {
|
|
1190
|
+
const el = inv.element;
|
|
1191
|
+
const attr = (n) => el.getAttribute(n);
|
|
1192
|
+
let id;
|
|
1193
|
+
let ctx;
|
|
1194
|
+
try {
|
|
1195
|
+
const type = attr("type") ?? (el.hasAttribute("typeexpr") ? String(this.datamodel.evaluate(attr("typeexpr"))) : "scxml");
|
|
1196
|
+
const src = attr("src") ?? (el.hasAttribute("srcexpr") ? String(this.datamodel.evaluate(attr("srcexpr"))) : undefined);
|
|
1197
|
+
if (el.hasAttribute("id"))
|
|
1198
|
+
id = attr("id");
|
|
1199
|
+
else {
|
|
1200
|
+
id = `${inv.state.id}.${this.sessionId}.${++this.sendCounter}`;
|
|
1201
|
+
if (el.hasAttribute("idlocation"))
|
|
1202
|
+
this.datamodel.assignValue(attr("idlocation"), id);
|
|
1203
|
+
}
|
|
1204
|
+
const params = (this.evaluatePayload(withoutContent(el, this.model.ns)) ?? {});
|
|
1205
|
+
const contentEl = scxmlChildren(el, this.model.ns).find((c) => c.localName === "content");
|
|
1206
|
+
let content;
|
|
1207
|
+
if (contentEl) {
|
|
1208
|
+
const expr = contentEl.getAttribute("expr");
|
|
1209
|
+
content = expr != null ? this.datamodel.evaluate(expr) : this.inlineValue(contentEl);
|
|
1210
|
+
}
|
|
1211
|
+
ctx = { invokeid: id, type, src, content, params };
|
|
1212
|
+
}
|
|
1213
|
+
catch (e) {
|
|
1214
|
+
this.raiseExecutionError(e, el);
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
const active = { id, node: inv, type: ctx.type, pending: [] };
|
|
1218
|
+
this.invoked.set(id, active);
|
|
1219
|
+
this.invokeIds.set(inv, id);
|
|
1220
|
+
this.emit(new InvokeEvent(this, { invokeid: id, invokeType: ctx.type, state: inv.state }));
|
|
1221
|
+
const full = {
|
|
1222
|
+
...ctx,
|
|
1223
|
+
sendToParent: (name, data) => this.receiveFromChild(id, { name, type: "external", data }),
|
|
1224
|
+
done: (data) => this.receiveFromChild(id, { name: `done.invoke.${id}`, type: "external", data }),
|
|
1225
|
+
};
|
|
1226
|
+
const started = (service) => {
|
|
1227
|
+
if (this.invoked.get(id) !== active)
|
|
1228
|
+
return service.cancel(); // cancelled while starting
|
|
1229
|
+
active.service = service;
|
|
1230
|
+
// The invoked session starts now — at the end of the macrostep, as the spec's main loop does —
|
|
1231
|
+
// so it is already running (and has entered its states) when the next event could cancel it.
|
|
1232
|
+
service.start?.();
|
|
1233
|
+
// then the events sent to it while its source was still loading (a session that
|
|
1234
|
+
// hasn't started yet drops incoming events, so this must come after start)
|
|
1235
|
+
for (const ev of active.pending.splice(0))
|
|
1236
|
+
service.send(ev);
|
|
1237
|
+
};
|
|
1238
|
+
const failed = (e) => {
|
|
1239
|
+
if (this.invoked.get(id) !== active)
|
|
1240
|
+
return;
|
|
1241
|
+
this.invoked.delete(id);
|
|
1242
|
+
this.raiseExecutionError(e, el);
|
|
1243
|
+
};
|
|
1244
|
+
try {
|
|
1245
|
+
const r = SCXML_INVOKE_TYPES.has(ctx.type) ? this.invokeScxml(full) : this.customInvoke(full);
|
|
1246
|
+
if (r instanceof Promise)
|
|
1247
|
+
r.then(started, failed);
|
|
1248
|
+
else
|
|
1249
|
+
started(r);
|
|
1250
|
+
}
|
|
1251
|
+
catch (e) {
|
|
1252
|
+
failed(e);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
customInvoke(ctx) {
|
|
1256
|
+
const invoker = this.opts.invokers?.[ctx.type];
|
|
1257
|
+
if (!invoker)
|
|
1258
|
+
throw new Error(`<invoke>: unsupported type "${ctx.type}"`);
|
|
1259
|
+
return invoker(ctx);
|
|
1260
|
+
}
|
|
1261
|
+
/** SCXML child sessions. Synchronous unless the loader is asynchronous. */
|
|
1262
|
+
invokeScxml(ctx) {
|
|
1263
|
+
const make = (root) => {
|
|
1264
|
+
const m = compile(root, { loader: this.opts.loader });
|
|
1265
|
+
const spawn = (model) => {
|
|
1266
|
+
// children don't inherit elementEvents/reflect: their elements live inside the parent's <content>
|
|
1267
|
+
const child = new SCXMLSession(model, {
|
|
1268
|
+
...this.opts,
|
|
1269
|
+
sessionId: undefined,
|
|
1270
|
+
data: ctx.params,
|
|
1271
|
+
elementEvents: false,
|
|
1272
|
+
reflect: false,
|
|
1273
|
+
});
|
|
1274
|
+
child.parent = { session: this, invokeid: ctx.invokeid };
|
|
1275
|
+
const active = this.invoked.get(ctx.invokeid);
|
|
1276
|
+
if (active)
|
|
1277
|
+
active.child = child;
|
|
1278
|
+
this.emit(new ChildSessionEvent(this, { invokeid: ctx.invokeid, child }));
|
|
1279
|
+
const service = {
|
|
1280
|
+
send: (ev) => child.enqueueExternal({ ...ev }),
|
|
1281
|
+
cancel: () => child.cancel(),
|
|
1282
|
+
// started by the parent once the invocation is registered, so early replies find it
|
|
1283
|
+
// (also when the child's source arrived asynchronously)
|
|
1284
|
+
start: () => child.start(),
|
|
1285
|
+
};
|
|
1286
|
+
return service;
|
|
1287
|
+
};
|
|
1288
|
+
return m instanceof Promise ? m.then(spawn) : spawn(m);
|
|
1289
|
+
};
|
|
1290
|
+
if (ctx.content instanceof Object && isElement(ctx.content)) {
|
|
1291
|
+
const root = ctx.content.localName === "scxml" ? ctx.content : null;
|
|
1292
|
+
if (!root)
|
|
1293
|
+
throw new Error("<invoke>: inline <content> must contain an <scxml> document");
|
|
1294
|
+
return make(root);
|
|
1295
|
+
}
|
|
1296
|
+
if (typeof ctx.content === "string")
|
|
1297
|
+
return make(parseSCXML(ctx.content, this.opts.domParser));
|
|
1298
|
+
if (ctx.src != null) {
|
|
1299
|
+
if (!this.opts.loader)
|
|
1300
|
+
throw new Error(`<invoke>: no loader for src "${ctx.src}"`);
|
|
1301
|
+
const text = this.opts.loader(ctx.src);
|
|
1302
|
+
return typeof text === "string"
|
|
1303
|
+
? make(parseSCXML(text, this.opts.domParser))
|
|
1304
|
+
: text.then((t) => make(parseSCXML(t, this.opts.domParser)));
|
|
1305
|
+
}
|
|
1306
|
+
throw new Error("<invoke>: needs src, srcexpr or <content>");
|
|
1307
|
+
}
|
|
1308
|
+
cancelInvoke(inv) {
|
|
1309
|
+
const id = this.invokeIds.get(inv);
|
|
1310
|
+
if (!id)
|
|
1311
|
+
return;
|
|
1312
|
+
this.invokeIds.delete(inv);
|
|
1313
|
+
const active = this.invoked.get(id);
|
|
1314
|
+
if (!active)
|
|
1315
|
+
return;
|
|
1316
|
+
this.invoked.delete(id);
|
|
1317
|
+
active.service?.cancel();
|
|
1318
|
+
}
|
|
1319
|
+
applyFinalize(inv) {
|
|
1320
|
+
if (inv.finalize)
|
|
1321
|
+
this.executeContent(scxmlChildren(inv.finalize, this.model.ns));
|
|
1322
|
+
}
|
|
1323
|
+
deliverToInvoke(active, ev) {
|
|
1324
|
+
if (active.service)
|
|
1325
|
+
active.service.send(ev);
|
|
1326
|
+
else
|
|
1327
|
+
active.pending.push(ev);
|
|
1328
|
+
}
|
|
1329
|
+
/** An event from an invoked child (or done.invoke): stamped with its invokeid. */
|
|
1330
|
+
receiveFromChild(invokeid, ev) {
|
|
1331
|
+
if (!this.invoked.has(invokeid))
|
|
1332
|
+
return; // cancelled
|
|
1333
|
+
this.enqueueExternal({ ...ev, invokeid, [FROM_CHILD]: true });
|
|
1334
|
+
}
|
|
1335
|
+
// ─────────────────────────────── errors ───────────────────────────────
|
|
1336
|
+
raiseExecutionError(e, element, sendid) {
|
|
1337
|
+
this.emitError("error.execution", message(e), element);
|
|
1338
|
+
this.internalQueue.push({ name: "error.execution", type: "platform", sendid, data: { message: message(e) } });
|
|
1339
|
+
if (!this.busy)
|
|
1340
|
+
this.schedule();
|
|
1341
|
+
}
|
|
1342
|
+
emitError(kind, msg, element = null) {
|
|
1343
|
+
this.emit(new SCXMLErrorEvent(this, { kind, message: msg, element }));
|
|
1344
|
+
}
|
|
1345
|
+
emit(event) {
|
|
1346
|
+
this.dispatchEvent(event);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
// ─────────────────────────────── helpers ───────────────────────────────
|
|
1350
|
+
class ActionError extends Error {
|
|
1351
|
+
element;
|
|
1352
|
+
sendid;
|
|
1353
|
+
constructor(msg, element,
|
|
1354
|
+
/** set for errors raised by <send>, so the error event carries it (spec §5.10.1) */
|
|
1355
|
+
sendid) {
|
|
1356
|
+
super(msg);
|
|
1357
|
+
this.element = element;
|
|
1358
|
+
this.sendid = sendid;
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
function capture(options) {
|
|
1362
|
+
return typeof options === "boolean" ? options : !!options?.capture;
|
|
1363
|
+
}
|
|
1364
|
+
function message(e) {
|
|
1365
|
+
return e instanceof Error ? e.message : String(e);
|
|
1366
|
+
}
|
|
1367
|
+
function stripMarks(ev) {
|
|
1368
|
+
const { [FROM_CHILD]: _, ...rest } = ev;
|
|
1369
|
+
return rest;
|
|
1370
|
+
}
|
|
1371
|
+
function isValidScxmlTarget(target) {
|
|
1372
|
+
return target === "" || target === "#_internal" || target === "#_parent" || /^#_scxml_.+/.test(target) || /^#_[^#].*/.test(target);
|
|
1373
|
+
}
|
|
1374
|
+
function isElement(v) {
|
|
1375
|
+
return typeof v === "object" && v !== null && v.nodeType === 1;
|
|
1376
|
+
}
|
|
1377
|
+
/** Element children of any namespace (inline XML content). */
|
|
1378
|
+
function scxmlChildrenAny(el) {
|
|
1379
|
+
return Array.from(el.children);
|
|
1380
|
+
}
|
|
1381
|
+
/** Parse arbitrary XML text into a document element (throws when it isn't XML). */
|
|
1382
|
+
function parseSCXMLLike(text, domParser) {
|
|
1383
|
+
const parser = domParser ?? (typeof DOMParser !== "undefined" ? new DOMParser() : undefined);
|
|
1384
|
+
if (!parser)
|
|
1385
|
+
throw new Error("no DOMParser");
|
|
1386
|
+
const doc = parser.parseFromString(text, "application/xml");
|
|
1387
|
+
if (doc.getElementsByTagName("parsererror").length)
|
|
1388
|
+
throw new Error("not XML");
|
|
1389
|
+
return doc.documentElement;
|
|
1390
|
+
}
|
|
1391
|
+
/** A shallow view of `<invoke>` without `<content>`, for namelist/param evaluation. */
|
|
1392
|
+
function withoutContent(el, ns) {
|
|
1393
|
+
const clone = el.cloneNode(false);
|
|
1394
|
+
for (const c of scxmlChildren(el, ns))
|
|
1395
|
+
if (c.localName === "param")
|
|
1396
|
+
clone.appendChild(c.cloneNode(true));
|
|
1397
|
+
return clone;
|
|
1398
|
+
}
|
|
1399
|
+
//# sourceMappingURL=session.js.map
|