@margoengine/fsm 0.0.0-stage → 1.0.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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Scott Campbell
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Margo Engine
2
+ Copyright 2026 Scott Campbell
3
+
4
+ This product includes Margo Engine (https://margoengine.com) by Scott Campbell.
package/README.md CHANGED
@@ -1,3 +1,390 @@
1
- # Temporary Holding Version
1
+ # @margoengine/fsm
2
+
3
+ Import `margoengine/fsm` from the `margoengine` package, or `@margoengine/fsm` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Hierarchical states preserve common ancestors during transitions, bubble events from leaf to root, and expose previous/state/blend for cross-fades. On top of that: [history states](#history-states), [delayed transitions](#delayed-transitions), [parallel regions](#parallel-regions-margoenginefsmparallel), [machines as data](#machines-as-data-margoenginefsmdocument), [snapshots and traces](#snapshots-and-trace-margoenginefsmtrace), [event payloads](#event-payloads-margoenginefsmevents), [final states](#final-states-and-eventless-transitions-margoenginefsmfinal) and [invoked tasks](#invoked-tasks-margoenginefsminvoke).
6
+
7
+ ```ts
8
+ import {StateMachine} from 'margoengine/fsm';
9
+ const machine = new StateMachine({game: {}, idle: {parent: 'game'}, run: {parent: 'game'}}, 'idle', {}, [
10
+ {from: 'idle', to: 'run', event: 'move', duration: 0.2}
11
+ ]);
12
+ machine.send('move');
13
+ machine.update(1 / 60);
14
+ ```
15
+
16
+ State hooks receive context; update hooks also receive delta seconds. Guards can decline an event transition. Hierarchy cycles and unknown states are rejected. goto changes state directly. Recursive transitions from enter/exit hooks are rejected. Cross-fade progress is a timer for the caller's animation mixer; this package does not own animations.
17
+
18
+ ## History states
19
+
20
+ Give a parent `history` and it returns to where it was when you come back, for pause menus and interrupts. Give it `initial` for the child to start in before that, and for any parent that should never rest on itself.
21
+
22
+ ```ts
23
+ import {StateMachine} from 'margoengine/fsm';
24
+
25
+ const machine = new StateMachine({
26
+ play: {history: 'deep', initial: 'explore'},
27
+ explore: {parent: 'play'},
28
+ combat: {parent: 'play', initial: 'melee'},
29
+ melee: {parent: 'combat'},
30
+ ranged: {parent: 'combat'},
31
+ pause: {}
32
+ }, 'play', {}, [
33
+ {from: 'explore', to: 'combat', event: 'enemy'},
34
+ {from: 'melee', to: 'ranged', event: 'switch'},
35
+ {from: 'play', to: 'pause', event: 'pause'},
36
+ {from: 'pause', to: 'play', event: 'resume'}
37
+ ]);
38
+ machine.send('enemy');
39
+ machine.send('switch');
40
+ machine.send('pause');
41
+ machine.send('resume');
42
+ console.log(machine.state); // 'ranged'; with history: 'shallow', 'melee', as combat restarts at its initial
43
+ ```
44
+
45
+ - A transition to `play` uses the memory; a transition straight to a child of `play` does not, and an exit records it again as usual.
46
+ - The memory counts when the state is entered. A transition to a parent the machine is still inside goes to the parent's `initial`, or stops on the parent if it has none.
47
+ - `machine.memory` maps each state to what it remembers: `machine.memory.delete('play')` forgets one, `machine.memory.clear()` forgets all.
48
+ - Each state with `history` keeps its own memory, and a state remembered by a parent uses its own on the way in.
49
+ - Parallel regions inside remembered states start again at their `initial`, unless the regions have `{history: true}`.
50
+
51
+ ## Delayed transitions
52
+
53
+ Give a transition `after` in place of `event` and `update` takes it by itself once the machine has spent that many seconds in `from`. No timers to write, and none to cancel.
54
+
55
+ ```ts
56
+ import {StateMachine} from 'margoengine/fsm';
57
+
58
+ const machine = new StateMachine({
59
+ attack: {},
60
+ windup: {parent: 'attack'},
61
+ swing: {parent: 'attack'},
62
+ recover: {},
63
+ ready: {}
64
+ }, 'windup', {}, [
65
+ {from: 'windup', to: 'swing', after: 0.2},
66
+ {from: 'attack', to: 'recover', after: 0.5, duration: 0.1},
67
+ {from: 'recover', to: 'ready', after: 0.3}
68
+ ]);
69
+ machine.update(0.6);
70
+ console.log(machine.state); // 'recover'
71
+ ```
72
+
73
+ - The time counts from entering `from`. A parent keeps counting while the machine moves between its children, as `attack` does above; leaving `from` cancels the wait, and coming back starts it again.
74
+ - A delay that ends inside a long `delta` splits it, so the machine does not depend on the frame rate: `update(0.6)` ends where 36 updates of 1/60 do, and the next state's delay counts from the moment the last one ended. Update hooks get the pieces of `delta`, which add up to the whole.
75
+ - A guard that declines is asked again on every update until it passes, or the machine leaves `from`.
76
+ - Inner states go first when delays end together.
77
+ - A delayed transition that leaves its `from` active, such as one from a parent to its child, waits again from that moment. So `{from: 'patrol', to: 'look', after: 5}` runs every five seconds while inside `patrol`. Only that transition's wait starts again: the other delays of `patrol` keep counting from entry (before 2026-11-10 a re-armed delay restarted them all, so a longer one never came).
78
+ - `machine.clock` is the machine's running time and `machine.entered` holds when each active state began.
79
+
80
+ ## Parallel regions (`margoengine/fsm/parallel`)
81
+
82
+ Run independent states at once, such as what a character's legs do and what its weapon does. Each region is an ordinary machine with one active state of its own; they share a context and hear the same events. Two machines side by side would do until a guard in one reads the other, or a hook in one tells the other: `ParallelRegions` settles those.
83
+
84
+ ```ts
85
+ import {ParallelRegions} from 'margoengine/fsm/parallel';
86
+
87
+ const regions: ParallelRegions<object> = new ParallelRegions({
88
+ movement: {
89
+ states: {idle: {}, run: {}},
90
+ initial: 'idle',
91
+ transitions: [{from: 'idle', to: 'run', event: 'move'}, {from: 'run', to: 'idle', event: 'halt'}]
92
+ },
93
+ weapon: {
94
+ states: {ready: {}, firing: {}},
95
+ initial: 'ready',
96
+ transitions: [{
97
+ from: 'ready', to: 'firing', event: 'fire',
98
+ guard: () => !regions.matches('movement', 'run')
99
+ }]
100
+ }
101
+ }, {});
102
+
103
+ regions.start();
104
+ regions.send('fire');
105
+ regions.update(1 / 60);
106
+ console.log(regions.active); // {movement: 'idle', weapon: 'firing'}
107
+ ```
108
+
109
+ - `send(event)` reaches every region and returns true when one took it. All regions choose first and then all move, so a guard sees the same states whichever region it sits in, and the order of the regions changes nothing but the order hooks run in.
110
+ - `raise(event)` is for hooks: the event waits until the running delivery ends, then goes to every region, in the order raised. `send` from a hook throws. `forward: (event) => machine.send(event)` gets a raised event no region took.
111
+ - `active` gives each region's state, `matches(region, state)` tests one, parents included, and `machines` holds each region's `StateMachine`, for `blend` and the like.
112
+ - Regions enter in the order written and leave in reverse. `stop()` leaves them, and `start()` begins at each `initial` again, or where each stopped with `{history: true}`.
113
+
114
+ Put regions in a state of another machine with `asState()`. Entering that state starts them, leaving stops them, and an event reaches them first: the outer machine's transitions on the same event only run when no region took it. Regions nest the same way.
115
+
116
+ ```ts
117
+ import {StateMachine} from 'margoengine/fsm';
118
+ import {ParallelRegions} from 'margoengine/fsm/parallel';
119
+
120
+ const regions: ParallelRegions<object> = new ParallelRegions({
121
+ legs: {states: {stand: {}, walk: {}}, initial: 'stand', transitions: [{from: 'stand', to: 'walk', event: 'move'}]},
122
+ arms: {states: {rest: {}, wave: {}}, initial: 'rest', transitions: [{from: 'rest', to: 'wave', event: 'greet'}]}
123
+ }, {});
124
+ const machine = new StateMachine({game: {}, alive: {...regions.asState(), parent: 'game'}, dead: {parent: 'game'}}, 'alive', {}, [
125
+ {from: 'alive', to: 'dead', event: 'die'}
126
+ ]);
127
+ machine.send('move'); // the legs walk
128
+ machine.send('die'); // the regions stop
129
+ ```
130
+
131
+ A transition cannot cross from one region to another or into a region from outside: a region starts at its `initial`, and a transition out of the regions belongs to the state that holds them. `machine.plan(event)` is the choosing half of `send`, which a nested machine uses through the `plan` hook of `State`; `machine.matches(state)` tests the active path.
132
+
133
+ ## Machines as data (`margoengine/fsm/document`)
134
+
135
+ Keep a machine in a JSON file, as the animator keeps its graph, so a tool can write it and a designer can change it. Everything a machine has fits: hierarchy, `initial`, `history`, `after`, cross-fades and parallel regions. Functions do not fit in JSON, so hooks and guards are names, and you hand over the functions when loading. Guards get the context.
136
+
137
+ ```ts
138
+ import {loadMachine, saveMachine, validateMachine, type MachineDocument} from 'margoengine/fsm/document';
139
+
140
+ const document: MachineDocument = {
141
+ version: 1,
142
+ initial: 'patrol',
143
+ states: {
144
+ patrol: {enter: 'shout'},
145
+ chase: {update: 'run'},
146
+ both: {regions: {
147
+ legs: {states: {up: {}, down: {}}, initial: 'up', transitions: [{from: 'up', to: 'down', event: 'duck'}]}
148
+ }}
149
+ },
150
+ transitions: [
151
+ {from: 'patrol', to: 'chase', event: 'see', guard: 'awake', duration: 0.2},
152
+ {from: 'chase', to: 'patrol', after: 5}
153
+ ]
154
+ };
155
+ const guard = {awake: true};
156
+ const bindings = {
157
+ hooks: {shout: () => console.log('who goes there'), run: (_context: typeof guard, delta: number) => console.log(delta)},
158
+ guards: {awake: (context: typeof guard) => context.awake}
159
+ };
160
+
161
+ console.log(validateMachine(document, bindings)); // []
162
+ const machine = loadMachine(document, guard, bindings);
163
+ machine.send('see');
164
+ const text = JSON.stringify(saveMachine(machine, bindings));
165
+ const again = loadMachine(JSON.parse(text), guard, bindings);
166
+ ```
167
+
168
+ - `validateMachine(value, bindings?)` takes anything, such as what `JSON.parse` gave, and lists every problem with its place, `[{path: 'transitions[2].to', message: '...'}]`, or nothing. Unknown keys are problems, so a typing slip does not pass quietly. Each problem is listed once, where it is: a parent that does not exist on the state naming it, a hierarchy cycle on the states in the cycle, a value that is not an object at `document`. With `bindings` each name must also have its function.
169
+ - `loadMachine(document, context, bindings?)` builds the machine, or throws a `TypeError` listing every problem. A raised event no region takes goes to the machine holding the regions.
170
+ - `saveMachine(machine, bindings?)` gives the document of any machine, also one built by hand: it finds each function's name in `bindings`, and throws a `TypeError` for one that has none. It saves the definition, not where the machine is now: for that see below.
171
+ - A state with regions takes no hooks in a document; put them on its parent.
172
+
173
+ Guards in `StateMachine` get the context too: `guard: (context) => context.awake`.
174
+
175
+ ## SCXML (`margoengine/fsm/scxml`)
176
+
177
+ Read and write the W3C SCXML subset that maps onto machine documents: `state`, `parallel`, `initial`, `history`, `transition` with `event`/`cond`/`target`, and `onentry`/`onexit` hooks written as a name call such as `leave()`. Hooks and guards stay names, as in a document; nothing in the file runs. Margo reads the XML itself, the same way in browsers, workers and Node, so no DOM parser is needed and file text is never parsed as HTML.
178
+
179
+ ```ts
180
+ import {loadMachine} from 'margoengine/fsm/document';
181
+ import {exportSCXML, importSCXML} from 'margoengine/fsm/scxml';
182
+
183
+ const document = importSCXML(`<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0" initial="idle">
184
+ <state id="idle"><transition event="go" target="run" cond="ready()"/></state>
185
+ <state id="run"><onentry><script>shout()</script></onentry></state>
186
+ </scxml>`);
187
+ const machine = loadMachine(document, {}, {hooks: {shout: () => console.log('off we go')}, guards: {ready: () => true}});
188
+ machine.send('go');
189
+ console.log(machine.state); // 'run'
190
+ console.log(exportSCXML(document, {extensions: false}).startsWith('<?xml')); // true
191
+ ```
192
+
193
+ - `importSCXML(text)` throws a `TypeError` naming the problem for malformed XML, a DTD or entity declaration, processing instructions, script code that is not a single name call, unknown elements or attributes, or input over 1 MiB, 10,000 elements or 128 levels deep.
194
+ - `exportSCXML(document, {extensions})` writes the document back. With the default `extensions: true`, fields SCXML cannot hold (`after`, `duration`, `update`, region history, names that are not XML ids) keep their values in the `urn:margoengine:fsm:1` namespace; with `extensions: false` such a document is refused instead of losing them.
195
+ - Margo never leaves a state that stays on the path between source and target, which is SCXML's `type="internal"`. SCXML itself (W3C 2015, section 3.13 and `getTransitionDomain` in Appendix D) exits and re-enters the source of a transition to itself or to an ancestor, and the source of an external transition (the default type) to a descendant. Since 2026-11-10 `importSCXML` refuses those three cases with a `TypeError` rather than running other hooks than the file means: write `type="internal"` for a descendant target. `exportSCXML` marks Margo's own self and ancestor transitions `m:stay="true"`, so they come back, and refuses them with `extensions: false`. A standard SCXML tool ignores the mark and exits and re-enters there.
196
+ - Accepted difference: an SCXML event descriptor `a` also matches the event `a.b` (section 3.12.1). Margo matches the whole event name, so `send('a.b')` does not take a transition on `a`.
197
+ - The old `parser` option is ignored and deprecated.
198
+
199
+ ## Snapshots and trace (`margoengine/fsm/trace`)
200
+
201
+ `snapshotMachine` gives where a machine is now as plain data: the state, cross-fade, every delay's progress (`waits` holds the delays that started waiting again; a snapshot without it restores with none), what states remember and all parallel regions. Put it in a save file or send it over the network, and `restoreMachine` puts a machine with the same definition back there. The machine then goes on exactly as the first would have, so rollback netcode can go back and replay.
202
+
203
+ ```ts
204
+ import {StateMachine} from 'margoengine/fsm';
205
+ import {MachineTrace, restoreMachine, snapshotMachine} from 'margoengine/fsm/trace';
206
+
207
+ const make = () => new StateMachine({idle: {}, windup: {}, swing: {}}, 'idle', {}, [
208
+ {from: 'idle', to: 'windup', event: 'attack'},
209
+ {from: 'windup', to: 'swing', after: 0.5}
210
+ ]);
211
+
212
+ const machine = make();
213
+ using trace = new MachineTrace(machine, {capacity: 64});
214
+ machine.send('attack');
215
+ machine.update(0.25);
216
+
217
+ const save = JSON.stringify(snapshotMachine(machine));
218
+ const loaded = make();
219
+ restoreMachine(loaded, JSON.parse(save));
220
+ loaded.update(0.25);
221
+ console.log(loaded.state); // 'swing'
222
+ console.log(trace.records); // [{machine: '', clock: 0, from: 'idle', to: 'windup', event: 'attack', after: null}]
223
+ ```
224
+
225
+ - `restoreMachine` runs no hooks. It restores the machine, and what your hooks did to your context is yours to save beside it.
226
+ - A snapshot that does not fit the machine throws a `TypeError` and leaves the machine untouched. Both functions throw a `MargoError` with code `state` from a hook in the middle of a change.
227
+ - `MachineTrace` keeps the newest `capacity` changes, default 256, oldest first in `records`, for every machine down through parallel regions. `machine` says which, such as `alive/weapon`; `event` and `after` say what caused the change, both null for `goto`. `from` is null when regions start and `to` when they stop. `dispose()`, or `using`, stops it.
228
+ - A machine has one `listener`, the hook a trace uses; set it yourself for your own debug overlay. A second trace on the same machine throws a `MargoError` with code `attached`.
229
+
230
+ ## Event payloads (`margoengine/fsm/events`)
231
+
232
+ `EventMachine` is a `StateMachine` whose `send(event, data)` and `plan(event, data)` carry a payload to the guards and
233
+ hooks of that one delivery: a transition's `guard(context, data)`, and the `exit(context, data)` and
234
+ `enter(context, data)` of the states it leaves and enters. A nested machine's `plan(event, data)` hook sees it too.
235
+
236
+ ```ts
237
+ import {EventMachine, EventTrace} from 'margoengine/fsm/events';
238
+
239
+ type Hit = {damage: number};
240
+ const context = {health: 30, log: [] as string[]};
241
+ const machine = new EventMachine<typeof context, Hit>({
242
+ alive: {exit: (c, hit) => c.log.push(`last hit ${hit?.damage}`)},
243
+ dead: {enter: (c, hit) => c.log.push(`killed by ${hit?.damage}`)}
244
+ }, 'alive', context, [
245
+ {from: 'alive', to: 'dead', event: 'hit', guard: (c, hit) => (c.health -= hit!.damage) <= 0}
246
+ ]);
247
+ using trace = new EventTrace(machine, {capacity: 16});
248
+ const big = {damage: 25};
249
+ console.log(machine.send('hit', {damage: 10})); // false: the guard declined, health is 20
250
+ console.log(machine.send('hit', big)); // true
251
+ console.log(machine.state, context.log); // 'dead', ['last hit 25', 'killed by 25']
252
+ console.log(trace.records[0].data === big); // true: the payload itself, not a copy
253
+ ```
254
+
255
+ - Payloads are passed by reference, never cloned or merged into the context; keep or copy what you need.
256
+ - `machine.data` is the payload of the delivery running now and undefined outside one. Initial entry, `goto` and timed
257
+ (`after`) transitions deliver undefined.
258
+ - `plan(event, data)` keeps its payload in the action it returns, even when other events are sent before it runs.
259
+ - `EventTrace` is a `MachineTrace` (the same `capacity`, default 256, and `dispose()` or `using`) whose records also
260
+ hold each accepted transition's `data`.
261
+
262
+ ## Final states and eventless transitions (`margoengine/fsm/final`)
263
+
264
+ `FinalMachine` adds the run-to-completion steps of SCXML (W3C, State Chart XML, 2015) to `EventMachine`: final states,
265
+ `done.state.<parent>` completion events and `always` transitions that fire without an event while their guard holds.
266
+
267
+ ```ts
268
+ import {FinalMachine} from 'margoengine/fsm/final';
269
+
270
+ const context = {coins: 0};
271
+ const level = new FinalMachine({
272
+ playing: {initial: 'collect'},
273
+ collect: {parent: 'playing'},
274
+ cleared: {parent: 'playing', final: true},
275
+ results: {},
276
+ over: {final: true}
277
+ }, 'playing', context, [
278
+ {from: 'collect', to: 'cleared', always: true, guard: (c) => c.coins >= 3},
279
+ {from: 'playing', to: 'results', event: 'done.state.playing'},
280
+ {from: 'results', to: 'over', event: 'continue'}
281
+ ]);
282
+ for (let i = 0; i < 3; i++) {
283
+ context.coins++;
284
+ level.send('coin'); // no transition takes 'coin', but send asks the always guards again
285
+ }
286
+ // The third coin: collect -> cleared (always), then done.state.playing -> results, in one macrostep.
287
+ console.log(level.state, level.done); // 'results', false
288
+ level.send('continue');
289
+ console.log(level.done, level.send('continue')); // true, false: a stopped machine accepts nothing
290
+ level.goto('playing'); // restarts it
291
+ console.log(level.done, level.state); // false, 'results': coins is still 3, so the level clears at once
292
+ ```
293
+
294
+ - A final state is a leaf with no outgoing transitions or regions (anything else throws a `TypeError`). Entering one
295
+ queues `done.state.<parent>`; entering a top-level final sets `done` and the machine takes no more events or updates
296
+ until `goto` restarts it.
297
+ - Each transition gives exactly one trigger: `event`, a positive `after`, or `always: true`. Event names starting with
298
+ NUL are reserved.
299
+ - One `send`, `update` or `goto` settles a whole macrostep: `always` transitions and completion events run until none is
300
+ enabled. `send` asks the `always` guards again even when no transition accepted the event. A chain that does not
301
+ settle in 10,000 microsteps throws a `MargoError` with code `state`.
302
+ - `transitionDefinitions` lists the authored transitions in order, with their `event`, `after` and `always` triggers.
303
+
304
+ ## Invoked tasks (`margoengine/fsm/invoke`)
305
+
306
+ `InvokeMachine` is a `FinalMachine` whose states own asynchronous tasks: a state's `invoke` (one task or a list) starts
307
+ when the machine settles in it and is cancelled when the machine leaves it. A task's result comes back as the event
308
+ `done.invoke.<id>` with `{output}`, a rejection as `error.invoke.<id>` with `{error}`.
309
+
310
+ ```ts
311
+ import {InvokeMachine} from 'margoengine/fsm/invoke';
312
+
313
+ const context = {level: ''};
314
+ const stop = new AbortController();
315
+ using loader = new InvokeMachine({
316
+ loading: {
317
+ invoke: {
318
+ id: 'level',
319
+ run: async (_c, signal, data) => {
320
+ await new Promise((resolve) => setTimeout(resolve, 10));
321
+ signal.throwIfAborted();
322
+ return `level ${(data as {n: number} | undefined)?.n ?? 1}`;
323
+ }
324
+ }
325
+ },
326
+ ready: {enter: (c, data) => (c.level = (data as {output: string}).output)},
327
+ failed: {}
328
+ }, 'loading', context, [
329
+ {from: 'loading', to: 'ready', event: 'done.invoke.level'},
330
+ {from: 'loading', to: 'failed', event: 'error.invoke.level'},
331
+ {from: 'ready', to: 'loading', event: 'next'}
332
+ ], {signal: stop.signal});
333
+
334
+ await loader.invocations.get('level')!.settled;
335
+ console.log(loader.state, context.level); // 'ready', 'level 1'
336
+ loader.send('next', {n: 2}); // run receives the entering payload
337
+ const second = loader.invocations.get('level')!;
338
+ await second.settled;
339
+ console.log(second.status, second.output, context.level); // 'done', 'level 2', 'level 2'
340
+ stop.abort(); // or loader.dispose(): cancels every running task
341
+ ```
342
+
343
+ - `run(context, signal, data)` receives the payload of the event that entered the state (undefined on the first
344
+ entry) and an `AbortSignal` aborted when the state exits, a top-level final is reached or the machine is disposed;
345
+ pass it to `fetch` and other cancellable calls. A cancelled task's result is dropped.
346
+ - Task ids are unique and non-empty, and final states own no tasks (a `TypeError` otherwise). A task on a parent keeps
347
+ running while the machine moves between its children.
348
+ - `invocations` maps each id to its latest record: `state`, `signal`, `status` (`running`, `done`, `error` or
349
+ `cancelled`), `output` or `error`, and `settled`, a promise that resolves once the done or error event is delivered
350
+ or the task is cancelled (and rejects if a hook handling the event throws). A re-entry makes a fresh record.
351
+ - `options.signal` aborts the whole runtime; `dispose()`, or `using`, does the same. A disposed machine accepts no events.
352
+
353
+ ## Live inspection (`margoengine/fsm/inspect`)
354
+
355
+ `MachineView` shows hierarchy, outgoing triggers, remembered history and recent transitions.
356
+ Expanded state disclosures stay expanded through live refresh and filtering, independently
357
+ for each parallel machine. `FinalMachine.transitionDefinitions` exposes the authored
358
+ transitions in definition order, including `always`, `after` and event names; inspection
359
+ does not evaluate guards. `InvokeMachine` inherits these descriptions.
360
+
361
+ ```ts
362
+ import {FinalMachine} from 'margoengine/fsm/final';
363
+ import {MachineView} from 'margoengine/fsm/inspect';
364
+
365
+ const machine = new FinalMachine({idle: {}, waiting: {}, finished: {final: true}}, 'idle', {}, [
366
+ {from: 'idle', to: 'waiting', event: 'begin'},
367
+ {from: 'waiting', to: 'finished', after: 0.5}
368
+ ]);
369
+ using view = new MachineView(machine, {parent: document.body, live: false});
370
+ machine.send('begin');
371
+ machine.update(0.5);
372
+ view.refresh();
373
+ console.log(machine.transitionDefinitions[1].after); // 0.5
374
+ ```
375
+
376
+ Mounting defaults to `document.body`; `parent` takes precedence over `inspector: {element}`.
377
+ An inspector's open shadow root is used when available. `live` defaults to true and
378
+ refreshes on animation frames; false requires `refresh(filter?)`, where the default
379
+ filter is empty and matches state names without case sensitivity. `capacity` defaults
380
+ to 32 (1 to 10,000) recent trace entries. Supply `trace` to borrow an existing trace;
381
+ otherwise the view owns a new `MachineTrace`, which needs the machine's free listener.
382
+ `signal` defaults to none and abort disposes the view. `dispose()` and `using` remove
383
+ the overlay and stop its frame callbacks, disposing only an owned trace. Trigger
384
+ descriptions are available only when the optional final or invoke runtime is used;
385
+ ordinary machines retain their event and delay labels.
386
+
387
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
388
+
389
+ Build and unit tests: npm test --workspace @margoengine/fsm
2
390
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.