@margoengine/fsm 0.0.0-stage → 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 +201 -0
- package/NOTICE +4 -0
- package/README.md +267 -3
- package/dist/document.d.ts +78 -0
- package/dist/document.js +149 -0
- package/dist/events.d.ts +41 -0
- package/dist/events.js +50 -0
- package/dist/final.d.ts +39 -0
- package/dist/final.js +116 -0
- package/dist/index.d.ts +124 -0
- package/dist/index.js +129 -0
- package/dist/inspect.d.ts +43 -0
- package/dist/inspect.js +111 -0
- package/dist/invoke.d.ts +55 -0
- package/dist/invoke.js +79 -0
- package/dist/parallel.d.ts +96 -0
- package/dist/parallel.js +99 -0
- package/dist/scxml.d.ts +22 -0
- package/dist/scxml.js +423 -0
- package/dist/trace.d.ts +92 -0
- package/dist/trace.js +118 -0
- package/package.json +86 -6
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { StateMachine } from './index.js';
|
|
2
|
+
import { MachineTrace } from './trace.js';
|
|
3
|
+
/** Where the live machine overlay is mounted and how it obtains trace records. */
|
|
4
|
+
export interface MachineViewOptions<C> {
|
|
5
|
+
/** Inspector host. Its open shadow root is used when present. Default none. */
|
|
6
|
+
inspector?: {
|
|
7
|
+
element: HTMLElement;
|
|
8
|
+
};
|
|
9
|
+
/** Explicit mount point, taking precedence over inspector. Default document.body. */
|
|
10
|
+
parent?: HTMLElement;
|
|
11
|
+
/** Existing trace to read without taking ownership. Default a new MachineTrace. */
|
|
12
|
+
trace?: Pick<MachineTrace<C>, 'records'>;
|
|
13
|
+
/** Most recent trace entries shown, whole number 1 to 10,000. Default 32. */
|
|
14
|
+
capacity?: number;
|
|
15
|
+
/** Refresh on animation frames. Default true; false requires refresh(). */
|
|
16
|
+
live?: boolean;
|
|
17
|
+
/** Dispose when aborted. Default none. */
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
}
|
|
20
|
+
/** Live, accessible hierarchy and transition view, embeddable in the inspector without a renderer dependency. */
|
|
21
|
+
export declare class MachineView<C> {
|
|
22
|
+
/** Overlay host, removed on disposal. */
|
|
23
|
+
readonly element: HTMLDivElement;
|
|
24
|
+
private readonly machine;
|
|
25
|
+
private readonly trace;
|
|
26
|
+
private readonly owned;
|
|
27
|
+
private readonly capacity;
|
|
28
|
+
private readonly content;
|
|
29
|
+
private readonly window;
|
|
30
|
+
private readonly detach;
|
|
31
|
+
private readonly unlisten;
|
|
32
|
+
private frame;
|
|
33
|
+
private disposed;
|
|
34
|
+
private signature;
|
|
35
|
+
private readonly disclosures;
|
|
36
|
+
/** Mount a view. If the machine is already traced, supply that trace to avoid taking its listener. */
|
|
37
|
+
constructor(machine: StateMachine<C>, options?: MachineViewOptions<C>);
|
|
38
|
+
/** Refresh active paths, remembered history and recent transitions, including nested parallel machines. */
|
|
39
|
+
refresh(filter?: string): void;
|
|
40
|
+
/** Remove the overlay, stop frame callbacks and dispose only the trace created by this view. */
|
|
41
|
+
dispose(): void;
|
|
42
|
+
[Symbol.dispose]: () => void;
|
|
43
|
+
}
|
package/dist/inspect.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { MachineTrace as e } from "./trace.js";
|
|
2
|
+
//#region src/inspect.ts
|
|
3
|
+
var t = class {
|
|
4
|
+
constructor(t, n = {}) {
|
|
5
|
+
this.disposed = !1, this.signature = "", this.disclosures = /* @__PURE__ */ new Map();
|
|
6
|
+
let { capacity: r = 32 } = n;
|
|
7
|
+
if (!Number.isInteger(r) || r < 1 || r > 1e4) throw RangeError("Invalid view capacity; use an integer from 1 to 10000");
|
|
8
|
+
let i = n.parent ?? n.inspector?.element ?? globalThis.document?.body;
|
|
9
|
+
if (!i) throw TypeError("Missing DOM mount point; pass parent or inspector from a browser document");
|
|
10
|
+
let a = i.ownerDocument;
|
|
11
|
+
this.window = a.defaultView, this.machine = t, this.capacity = r, this.element = a.createElement("div"), this.element.dataset.margoMachineView = "", n.parent || (this.element.style.cssText = "position:fixed;left:12px;bottom:12px;width:min(480px,calc(100vw - 24px));z-index:10002"), this.element.setAttribute("role", "region"), this.element.setAttribute("aria-label", "State machine");
|
|
12
|
+
let o = this.element.attachShadow({ mode: "open" }), s = a.createElement("style");
|
|
13
|
+
s.textContent = ":host{display:block;box-sizing:border-box;background:#151b24;color:#e7edf5;font:12px/1.5 ui-monospace,monospace;max-width:520px;max-height:70vh;overflow:auto;border:1px solid #405064;border-radius:6px;padding:14px}h2{font:600 15px system-ui;margin:0 0 10px}h3{font:600 12px system-ui;color:#a5b8cd;margin:16px 0 6px}ol{padding-left:22px;margin:0}li{padding:2px 0;overflow-wrap:anywhere}button,input{font:inherit;color:inherit;background:#222e3e;border:1px solid #53677e;border-radius:3px;padding:4px 7px}input{width:140px;margin-left:8px}[aria-current=true]{color:#85edc8;font-weight:bold}pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:0}.state{border-left:2px solid #405064;padding-left:10px;margin:4px 0}.active{border-color:#85edc8}.muted{color:#9aacbf}summary{cursor:pointer}";
|
|
14
|
+
let c = a.createElement("h2");
|
|
15
|
+
c.textContent = "State machine";
|
|
16
|
+
let l = a.createElement("div"), u = a.createElement("button");
|
|
17
|
+
u.type = "button", u.textContent = "Refresh";
|
|
18
|
+
let d = () => this.refresh(f.value);
|
|
19
|
+
u.addEventListener("click", d);
|
|
20
|
+
let f = a.createElement("input");
|
|
21
|
+
f.type = "search", f.placeholder = "Filter states", f.setAttribute("aria-label", "Filter states");
|
|
22
|
+
let p = () => {
|
|
23
|
+
this.signature = "", this.refresh(f.value);
|
|
24
|
+
};
|
|
25
|
+
f.addEventListener("input", p), this.unlisten = () => {
|
|
26
|
+
u.removeEventListener("click", d), f.removeEventListener("input", p);
|
|
27
|
+
}, l.append(u, f), this.content = a.createElement("div"), o.append(s, c, l, this.content), this.owned = n.trace ? void 0 : new e(t, { capacity: r }), this.trace = n.trace ?? this.owned;
|
|
28
|
+
let m = () => this.dispose();
|
|
29
|
+
if (this.detach = () => n.signal?.removeEventListener("abort", m), n.signal?.aborted) this.dispose();
|
|
30
|
+
else if (n.signal?.addEventListener("abort", m, { once: !0 }), (!n.parent && n.inspector ? i.shadowRoot ?? i : i).append(this.element), this.refresh(), n.live !== !1 && this.window?.requestAnimationFrame) {
|
|
31
|
+
let e = () => {
|
|
32
|
+
this.refresh(f.value), this.disposed || (this.frame = this.window.requestAnimationFrame(e));
|
|
33
|
+
};
|
|
34
|
+
this.frame = this.window.requestAnimationFrame(e);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
refresh(e = "") {
|
|
38
|
+
if (this.disposed) return;
|
|
39
|
+
let t = this.trace.records.slice(-this.capacity), n = [], r = (e, t) => {
|
|
40
|
+
let i = [];
|
|
41
|
+
for (let t = e.state; t !== void 0; t = e.states[t]?.parent) i.unshift(t);
|
|
42
|
+
n.push({
|
|
43
|
+
name: t,
|
|
44
|
+
machine: e,
|
|
45
|
+
path: i
|
|
46
|
+
});
|
|
47
|
+
for (let [n, i] of Object.entries(e.states)) if (i.regions) for (let [e, a] of Object.entries(i.regions.machines)) r(a, `${t}/${n}/${e}`);
|
|
48
|
+
};
|
|
49
|
+
r(this.machine, "root");
|
|
50
|
+
let i = JSON.stringify([
|
|
51
|
+
e,
|
|
52
|
+
n.map((e) => [
|
|
53
|
+
e.name,
|
|
54
|
+
e.path,
|
|
55
|
+
[...e.machine.memory]
|
|
56
|
+
]),
|
|
57
|
+
t.map(({ machine: e, clock: t, from: n, to: r, event: i, after: a }) => [
|
|
58
|
+
e,
|
|
59
|
+
t,
|
|
60
|
+
n,
|
|
61
|
+
r,
|
|
62
|
+
i,
|
|
63
|
+
a
|
|
64
|
+
])
|
|
65
|
+
]);
|
|
66
|
+
if (i === this.signature) return;
|
|
67
|
+
this.signature = i;
|
|
68
|
+
let a = this.element.ownerDocument, o = [], s = new Set(n.map((e) => e.machine));
|
|
69
|
+
for (let e of this.disclosures.keys()) s.has(e) || this.disclosures.delete(e);
|
|
70
|
+
let c = (e) => {
|
|
71
|
+
let t = a.createElement("h3");
|
|
72
|
+
t.textContent = e, o.push(t);
|
|
73
|
+
};
|
|
74
|
+
for (let { name: t, machine: r, path: i } of n) {
|
|
75
|
+
c(`${t}: ${i.join(" > ")}`);
|
|
76
|
+
let n = a.createElement("div");
|
|
77
|
+
n.dataset.machine = t;
|
|
78
|
+
let s = this.disclosures.get(r);
|
|
79
|
+
s || this.disclosures.set(r, s = /* @__PURE__ */ new Map());
|
|
80
|
+
for (let e of s.keys()) Object.hasOwn(r.states, e) || s.delete(e);
|
|
81
|
+
let l = r.transitionDefinitions ?? r.transitions;
|
|
82
|
+
for (let [t, o] of Object.entries(r.states)) {
|
|
83
|
+
if (e && !t.toLowerCase().includes(e.toLowerCase())) continue;
|
|
84
|
+
let c = s.get(t);
|
|
85
|
+
c || (c = a.createElement("details"), c.append(a.createElement("summary"), a.createElement("pre")), s.set(t, c)), c.className = `state${i.includes(t) ? " active" : ""}`, c.dataset.state = t, i.includes(t) ? c.setAttribute("aria-current", "true") : c.removeAttribute("aria-current");
|
|
86
|
+
let u = 0;
|
|
87
|
+
for (let e = o.parent; e !== void 0; e = r.states[e]?.parent) u++;
|
|
88
|
+
c.style.marginLeft = `${u * 16}px`, c.children[0].textContent = t, c.children[1].textContent = l.filter((e) => e.from === t).map((e) => `${"always" in e && e.always ? "always" : e.event?.startsWith("\0") ? "internal" : e.event ?? `after ${e.after}s`} -> ${e.to}`).join("\n") || "No outgoing transitions", n.append(c);
|
|
89
|
+
}
|
|
90
|
+
o.push(n);
|
|
91
|
+
let u = a.createElement("pre");
|
|
92
|
+
u.dataset.history = t, u.textContent = [...r.memory].map(([e, t]) => `${e}: ${t}`).join("\n") || "No remembered history", c(`${t} history`), o.push(u);
|
|
93
|
+
}
|
|
94
|
+
c("Recent transitions");
|
|
95
|
+
let l = a.createElement("ol");
|
|
96
|
+
l.dataset.trace = "";
|
|
97
|
+
for (let e of t) {
|
|
98
|
+
let t = a.createElement("li");
|
|
99
|
+
t.textContent = `${e.clock}s ${e.machine || "root"}: ${e.from ?? "(start)"} -> ${e.to ?? "(stop)"} [${e.event ?? (e.after === null ? "goto / always" : `after ${e.after}s`)}]`, l.append(t);
|
|
100
|
+
}
|
|
101
|
+
o.push(l), this.content.replaceChildren(...o);
|
|
102
|
+
}
|
|
103
|
+
dispose() {
|
|
104
|
+
this.disposed || (this.disposed = !0, this.frame !== void 0 && this.window?.cancelAnimationFrame(this.frame), this.detach(), this.unlisten(), this.owned?.dispose(), this.element.remove(), this.disclosures.clear());
|
|
105
|
+
}
|
|
106
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
107
|
+
this.dispose();
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
//#endregion
|
|
111
|
+
export { t as MachineView };
|
package/dist/invoke.d.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { FinalMachine, type FinalState, type FinalTransition } from './final.js';
|
|
2
|
+
/** An asynchronous service owned by one state's lifetime. */
|
|
3
|
+
export interface InvokedTask<C> {
|
|
4
|
+
/** Unique non-empty id, used in done.invoke.id and error.invoke.id events. */
|
|
5
|
+
id: string;
|
|
6
|
+
/** Start work. Pass signal into fetch or other cancellable APIs; data is the entering event payload. */
|
|
7
|
+
run: (context: C, signal: AbortSignal, data: unknown) => unknown | PromiseLike<unknown>;
|
|
8
|
+
}
|
|
9
|
+
/** State with one or several independently cancellable tasks. */
|
|
10
|
+
export interface InvokeState<C> extends FinalState<C> {
|
|
11
|
+
/** Services started after the state reaches a stable configuration. Default none. */
|
|
12
|
+
invoke?: InvokedTask<C> | readonly InvokedTask<C>[];
|
|
13
|
+
}
|
|
14
|
+
/** Inspectable lifecycle of one task instance. A re-entry creates a fresh record and signal. */
|
|
15
|
+
export interface Invocation {
|
|
16
|
+
/** Owning state name. */
|
|
17
|
+
state: string;
|
|
18
|
+
/** Service id. */
|
|
19
|
+
id: string;
|
|
20
|
+
/** Signal aborted on state exit, top-level completion or disposal. */
|
|
21
|
+
signal: AbortSignal;
|
|
22
|
+
/** Current task state. */
|
|
23
|
+
status: 'running' | 'done' | 'error' | 'cancelled';
|
|
24
|
+
/** Resolved service value, if done. */
|
|
25
|
+
output?: unknown;
|
|
26
|
+
/** Rejected service value, if error. */
|
|
27
|
+
error?: unknown;
|
|
28
|
+
/** Resolves after delivery of done/error, or cancellation; rejects if an event handler throws. */
|
|
29
|
+
settled: Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
/** Options for the invoked-task runtime. */
|
|
32
|
+
export interface InvokeOptions {
|
|
33
|
+
/** Abort the entire runtime and all its tasks. Default none. */
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
}
|
|
36
|
+
/** FinalMachine with state-scoped promise tasks, cancellation and completion/error events. */
|
|
37
|
+
export declare class InvokeMachine<C> extends FinalMachine<C> {
|
|
38
|
+
private readonly services;
|
|
39
|
+
private readonly live;
|
|
40
|
+
private readonly detach;
|
|
41
|
+
private closed;
|
|
42
|
+
/** Latest invocation for each id, including finished and cancelled records. */
|
|
43
|
+
readonly invocations: Map<string, Invocation>;
|
|
44
|
+
/** Build, settle initial transitions, then start services belonging to active nonfinal states. */
|
|
45
|
+
constructor(states: Readonly<Record<string, InvokeState<C>>>, initial: string, context: C, transitions?: readonly FinalTransition<C>[], options?: InvokeOptions);
|
|
46
|
+
/** Dispose all services. The underlying state definition remains available for inspection. */
|
|
47
|
+
dispose(): void;
|
|
48
|
+
[Symbol.dispose]: () => void;
|
|
49
|
+
/** Closed runtimes no longer accept events. */
|
|
50
|
+
plan(event: string, data?: unknown): (() => void) | null;
|
|
51
|
+
/** Synchronize services with the stable active path, retaining services on common ancestors. */
|
|
52
|
+
protected onStable(data?: unknown): void;
|
|
53
|
+
private cancel;
|
|
54
|
+
private start;
|
|
55
|
+
}
|
package/dist/invoke.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { FinalMachine as e } from "./final.js";
|
|
2
|
+
//#region src/invoke.ts
|
|
3
|
+
var t = class extends e {
|
|
4
|
+
constructor(e, t, n, r = [], i = {}) {
|
|
5
|
+
let a = /* @__PURE__ */ new Set();
|
|
6
|
+
for (let t of Object.values(e)) {
|
|
7
|
+
let e = t.invoke === void 0 ? [] : Array.isArray(t.invoke) ? t.invoke : [t.invoke];
|
|
8
|
+
for (let n of e) {
|
|
9
|
+
if (!n || typeof n.id != "string" || !n.id.length || a.has(n.id) || typeof n.run != "function" || t.final) throw TypeError("Invalid invoked task; give each service a unique non-empty id and run function on a nonfinal state");
|
|
10
|
+
a.add(n.id);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
let o = () => {}, s = Object.fromEntries(Object.entries(e).map(([e, t]) => [e, {
|
|
14
|
+
...t,
|
|
15
|
+
exit: (n, r) => {
|
|
16
|
+
t.exit?.(n, r), o(e);
|
|
17
|
+
}
|
|
18
|
+
}]));
|
|
19
|
+
super(s, t, n, r), this.live = /* @__PURE__ */ new Map(), this.closed = !1, this.invocations = /* @__PURE__ */ new Map(), this.services = e, o = (e) => {
|
|
20
|
+
for (let [t, { record: n }] of this.live) n.state === e && this.cancel(t);
|
|
21
|
+
};
|
|
22
|
+
let c = () => this.dispose();
|
|
23
|
+
this.detach = () => i.signal?.removeEventListener("abort", c), i.signal?.aborted ? this.dispose() : (i.signal?.addEventListener("abort", c, { once: !0 }), this.onStable());
|
|
24
|
+
}
|
|
25
|
+
dispose() {
|
|
26
|
+
if (!this.closed) {
|
|
27
|
+
this.closed = !0, this.detach();
|
|
28
|
+
for (let e of [...this.live.keys()]) this.cancel(e);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
[Symbol.dispose ?? Symbol()]() {
|
|
32
|
+
this.dispose();
|
|
33
|
+
}
|
|
34
|
+
plan(e, t) {
|
|
35
|
+
return this.closed ? null : super.plan(e, t);
|
|
36
|
+
}
|
|
37
|
+
onStable(e) {
|
|
38
|
+
if (this.closed) return;
|
|
39
|
+
for (let [e, { record: t }] of this.live) (this.done || !this.matches(t.state)) && this.cancel(e);
|
|
40
|
+
if (this.done) return;
|
|
41
|
+
let t = [];
|
|
42
|
+
for (let e = this.state; e !== void 0; e = this.states[e].parent) t.unshift(e);
|
|
43
|
+
for (let n of t) {
|
|
44
|
+
let t = this.services[n].invoke, r = t === void 0 ? [] : Array.isArray(t) ? t : [t];
|
|
45
|
+
for (let t of r) !this.live.has(t.id) && this.matches(n) && !this.closed && this.start(n, t, e);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
cancel(e) {
|
|
49
|
+
let t = this.live.get(e);
|
|
50
|
+
this.live.delete(e), t.record.status === "running" && (t.record.status = "cancelled"), t.abort.abort();
|
|
51
|
+
}
|
|
52
|
+
start(e, t, n) {
|
|
53
|
+
let r = new AbortController(), i = {
|
|
54
|
+
state: e,
|
|
55
|
+
id: t.id,
|
|
56
|
+
signal: r.signal,
|
|
57
|
+
status: "running",
|
|
58
|
+
settled: Promise.resolve()
|
|
59
|
+
}, a = {
|
|
60
|
+
record: i,
|
|
61
|
+
abort: r
|
|
62
|
+
};
|
|
63
|
+
this.live.set(t.id, a), this.invocations.set(t.id, i);
|
|
64
|
+
let o, s = new Promise((e) => {
|
|
65
|
+
o = e;
|
|
66
|
+
}), c = () => {
|
|
67
|
+
i.status === "cancelled" && o();
|
|
68
|
+
};
|
|
69
|
+
r.signal.addEventListener("abort", c, { once: !0 });
|
|
70
|
+
let l = new Promise((e) => e(t.run(this.context, r.signal, n))).then((e) => {
|
|
71
|
+
this.live.get(t.id) !== a || r.signal.aborted || (i.status = "done", i.output = e, this.send(`done.invoke.${t.id}`, { output: e }));
|
|
72
|
+
}, (e) => {
|
|
73
|
+
this.live.get(t.id) !== a || r.signal.aborted || (i.status = "error", i.error = e, this.send(`error.invoke.${t.id}`, { error: e }));
|
|
74
|
+
});
|
|
75
|
+
i.settled = Promise.race([l, s]).finally(() => r.signal.removeEventListener("abort", c));
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
export { t as InvokeMachine };
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type State, StateMachine, type Transition } from './index.js';
|
|
2
|
+
/** One region of {@link ParallelRegions}: an ordinary machine's states, starting state and transitions. */
|
|
3
|
+
export interface Region<C> {
|
|
4
|
+
/** The region's states, as for `StateMachine`. */
|
|
5
|
+
states: Readonly<Record<string, State<C>>>;
|
|
6
|
+
/** State the region starts in. */
|
|
7
|
+
initial: string;
|
|
8
|
+
/** The region's transitions. Default none. */
|
|
9
|
+
transitions?: readonly Transition<C>[];
|
|
10
|
+
}
|
|
11
|
+
/** Options of {@link ParallelRegions}. */
|
|
12
|
+
export interface ParallelOptions {
|
|
13
|
+
/** Each region resumes where it stopped instead of at its `initial` state. Default false. */
|
|
14
|
+
history?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Where an event from {@link ParallelRegions.raise} goes when no region takes it, usually the machine holding the
|
|
17
|
+
* regions: `(event) => machine.send(event)`. Default none: the event is dropped.
|
|
18
|
+
*/
|
|
19
|
+
forward?: (event: string) => void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Several state machines active at once, such as movement and weapon, sharing one context. Each region has one active
|
|
23
|
+
* state of its own. An event reaches every region, and all regions choose before any of them moves, so the result does
|
|
24
|
+
* not depend on the order of the regions. Regions are stopped until `start()`, or until the state from `asState()`
|
|
25
|
+
* is entered.
|
|
26
|
+
*/
|
|
27
|
+
export declare class ParallelRegions<C> {
|
|
28
|
+
readonly definition: Readonly<Record<string, Region<C>>>;
|
|
29
|
+
readonly context: C;
|
|
30
|
+
readonly options: ParallelOptions;
|
|
31
|
+
/** The machine of each region, by name; use it for `blend`, `goto` and the like. */
|
|
32
|
+
readonly machines: Readonly<Record<string, StateMachine<C>>>;
|
|
33
|
+
/** True between `start()` and `stop()`. */
|
|
34
|
+
running: boolean;
|
|
35
|
+
private readonly list;
|
|
36
|
+
/** Where each region starts next, in region order. */
|
|
37
|
+
readonly starts: string[];
|
|
38
|
+
private readonly queue;
|
|
39
|
+
private readonly forward;
|
|
40
|
+
private readonly history;
|
|
41
|
+
/** True during a delivery: while regions start, take an event or update. */
|
|
42
|
+
busy: boolean;
|
|
43
|
+
private draining;
|
|
44
|
+
/**
|
|
45
|
+
* @param regions The regions by name, in the order they enter and take updates.
|
|
46
|
+
* @throws TypeError without a region, for an unknown `initial`, or for what `StateMachine` refuses.
|
|
47
|
+
*/
|
|
48
|
+
constructor(definition: Readonly<Record<string, Region<C>>>, context: C, options?: ParallelOptions);
|
|
49
|
+
/** The current state of each region, by name; null for all while stopped. */
|
|
50
|
+
get active(): Record<string, string | null>;
|
|
51
|
+
/**
|
|
52
|
+
* True while `region` is in `state` or a child of it. For a guard in another region, as in Harel's `in(S)`.
|
|
53
|
+
* @throws RangeError for an unknown region.
|
|
54
|
+
*/
|
|
55
|
+
matches(region: string, state: string): boolean;
|
|
56
|
+
/**
|
|
57
|
+
* Enter every region in order, each at its `initial` state, or where it stopped with `history`.
|
|
58
|
+
* @throws MargoError `'state'` when already running.
|
|
59
|
+
*/
|
|
60
|
+
start(): void;
|
|
61
|
+
/**
|
|
62
|
+
* Leave every region, last region first. Events still waiting from `raise` are dropped.
|
|
63
|
+
* @throws MargoError `'state'` when stopped, or when called from a region's hook during a delivery.
|
|
64
|
+
*/
|
|
65
|
+
stop(): void;
|
|
66
|
+
/**
|
|
67
|
+
* Choose what every region would do with `event`, with no region moved yet: guards see the same states in all of
|
|
68
|
+
* them. Returns the action that moves them, or null when no region takes the event.
|
|
69
|
+
* @throws MargoError `'state'` when stopped.
|
|
70
|
+
*/
|
|
71
|
+
plan(event: string): (() => void) | null;
|
|
72
|
+
/**
|
|
73
|
+
* Deliver `event` to every region. Returns true when at least one took it.
|
|
74
|
+
* @throws MargoError `'state'` when stopped, or when called from a region's hook; use `raise` there.
|
|
75
|
+
*/
|
|
76
|
+
send(event: string): boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Deliver `event` once what is running now has finished, after any events raised before it; at once if nothing is.
|
|
79
|
+
* For a hook of one region to tell the others. An event no region takes goes to `forward`.
|
|
80
|
+
* @throws MargoError `'state'` when stopped, or when hooks raise events for ever.
|
|
81
|
+
*/
|
|
82
|
+
raise(event: string): void;
|
|
83
|
+
/**
|
|
84
|
+
* Update every region in order, as `StateMachine.update` does. An update is a delivery: a hook uses `raise`.
|
|
85
|
+
* @throws MargoError `'state'` when stopped. @throws RangeError when `delta` is negative or not finite.
|
|
86
|
+
*/
|
|
87
|
+
update(delta: number): void;
|
|
88
|
+
/**
|
|
89
|
+
* The state that runs these regions inside another machine: entering it starts them, leaving it stops them, and an
|
|
90
|
+
* event reaches them before that state's own transitions. Spread it to add a `parent`: `{...regions.asState(), parent}`.
|
|
91
|
+
*/
|
|
92
|
+
asState(): State<C>;
|
|
93
|
+
private assertRunning;
|
|
94
|
+
private deliver;
|
|
95
|
+
private drain;
|
|
96
|
+
}
|
package/dist/parallel.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { StateMachine as e } from "./index.js";
|
|
2
|
+
import { MargoError as t } from "@margoengine/math/errors";
|
|
3
|
+
//#region src/parallel.ts
|
|
4
|
+
var n = "\0stopped", r = 1e4, i = class {
|
|
5
|
+
constructor(t, r, i = {}) {
|
|
6
|
+
this.definition = t, this.context = r, this.options = i, this.running = !1, this.queue = [], this.busy = !1, this.draining = !1;
|
|
7
|
+
let a = Object.keys(t);
|
|
8
|
+
if (!a.length) throw TypeError("ParallelRegions has no regions; name at least one region");
|
|
9
|
+
this.list = a.map((i) => {
|
|
10
|
+
let { states: a, initial: o, transitions: s } = t[i];
|
|
11
|
+
if (!Object.hasOwn(a, o)) throw TypeError(`Unknown initial state of region ${i}; name one of the region's states`);
|
|
12
|
+
return new e({
|
|
13
|
+
...a,
|
|
14
|
+
[n]: {}
|
|
15
|
+
}, n, r, s);
|
|
16
|
+
}), this.machines = Object.fromEntries(a.map((e, t) => [e, this.list[t]])), this.starts = a.map((e) => t[e].initial), this.forward = i.forward, this.history = i.history ?? !1;
|
|
17
|
+
}
|
|
18
|
+
get active() {
|
|
19
|
+
return Object.fromEntries(Object.entries(this.machines).map(([e, { state: t }]) => [e, t === n ? null : t]));
|
|
20
|
+
}
|
|
21
|
+
matches(e, t) {
|
|
22
|
+
if (!Object.hasOwn(this.machines, e)) throw RangeError("Unknown region; name a region of these regions");
|
|
23
|
+
return this.machines[e].matches(t);
|
|
24
|
+
}
|
|
25
|
+
start() {
|
|
26
|
+
if (this.running) throw new t("state", "Regions already running; call stop() first");
|
|
27
|
+
this.running = !0, this.deliver(() => {
|
|
28
|
+
for (let e = 0; e < this.list.length; e++) this.list[e].goto(this.starts[e]);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
stop() {
|
|
32
|
+
if (this.assertRunning(), this.busy) throw new t("state", "Regions stopped from their own hook; use raise() and forward");
|
|
33
|
+
this.queue.length = 0, this.running = !1;
|
|
34
|
+
for (let e = this.list.length - 1; e >= 0; e--) this.history && (this.starts[e] = this.list[e].state), this.list[e].goto(n);
|
|
35
|
+
}
|
|
36
|
+
plan(e) {
|
|
37
|
+
this.assertRunning();
|
|
38
|
+
let t = [];
|
|
39
|
+
for (let n of this.list) {
|
|
40
|
+
let r = n.plan(e);
|
|
41
|
+
r && t.push(r);
|
|
42
|
+
}
|
|
43
|
+
return t.length ? () => this.deliver(() => {
|
|
44
|
+
for (let e of t) e();
|
|
45
|
+
}) : null;
|
|
46
|
+
}
|
|
47
|
+
send(e) {
|
|
48
|
+
if (this.busy) throw new t("state", "Event sent from a hook of these regions; use raise() there");
|
|
49
|
+
let n = this.plan(e);
|
|
50
|
+
return n?.(), n !== null;
|
|
51
|
+
}
|
|
52
|
+
raise(e) {
|
|
53
|
+
this.assertRunning(), this.queue.push(e), this.drain();
|
|
54
|
+
}
|
|
55
|
+
update(e) {
|
|
56
|
+
this.assertRunning(), this.deliver(() => {
|
|
57
|
+
for (let t of this.list) t.update(e);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
asState() {
|
|
61
|
+
return {
|
|
62
|
+
enter: () => this.start(),
|
|
63
|
+
exit: () => this.stop(),
|
|
64
|
+
update: (e, t) => this.update(t),
|
|
65
|
+
plan: (e) => this.plan(e),
|
|
66
|
+
regions: this
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
assertRunning() {
|
|
70
|
+
if (!this.running) throw new t("state", "Regions are stopped; call start() first");
|
|
71
|
+
}
|
|
72
|
+
deliver(e) {
|
|
73
|
+
let t = !1;
|
|
74
|
+
this.busy = !0;
|
|
75
|
+
try {
|
|
76
|
+
e(), t = !0;
|
|
77
|
+
} finally {
|
|
78
|
+
this.busy = !1, t || (this.queue.length = 0);
|
|
79
|
+
}
|
|
80
|
+
this.drain();
|
|
81
|
+
}
|
|
82
|
+
drain() {
|
|
83
|
+
if (this.busy || this.draining) return;
|
|
84
|
+
let e = !1;
|
|
85
|
+
this.draining = !0;
|
|
86
|
+
try {
|
|
87
|
+
for (let e = 0; this.queue.length; e++) {
|
|
88
|
+
if (e === r) throw new t("state", "Hooks of these regions raise events for ever; end the chain of raise() calls");
|
|
89
|
+
let n = this.queue.shift(), i = this.plan(n);
|
|
90
|
+
i ? i() : this.forward?.(n);
|
|
91
|
+
}
|
|
92
|
+
e = !0;
|
|
93
|
+
} finally {
|
|
94
|
+
this.draining = !1, e || (this.queue.length = 0);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
export { i as ParallelRegions };
|
package/dist/scxml.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type MachineDocument } from './document.js';
|
|
2
|
+
/** SCXML import options. */
|
|
3
|
+
export interface SCXMLImportOptions {
|
|
4
|
+
/**
|
|
5
|
+
* @deprecated Ignored. SCXML is read by Margo's own strict XML reader in browsers, workers and Node alike, so no DOM
|
|
6
|
+
* parser is needed and file text is never parsed as HTML.
|
|
7
|
+
*/
|
|
8
|
+
parser?: unknown;
|
|
9
|
+
}
|
|
10
|
+
/** SCXML output options. */
|
|
11
|
+
export interface SCXMLExportOptions {
|
|
12
|
+
/** Preserve native delay, duration, update, region history and arbitrary names with namespaced extensions. Default true. */
|
|
13
|
+
extensions?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Convert the SCXML document subset into a validated native machine document, without running scripts or guards.
|
|
17
|
+
* Supports hierarchy, initial states, parallel regions, history targets, named hooks/guards and event transitions.
|
|
18
|
+
* Native extensions round-trip fields that SCXML cannot express directly. Rejects DTDs and unsupported content.
|
|
19
|
+
*/
|
|
20
|
+
export declare function importSCXML(text: string, options?: SCXMLImportOptions): MachineDocument;
|
|
21
|
+
/** Export a validated machine document; optional namespaced extensions preserve native-only fields without executing code. */
|
|
22
|
+
export declare function exportSCXML(document: MachineDocument, options?: SCXMLExportOptions): string;
|