@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
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
package/README.md
CHANGED
|
@@ -1,3 +1,267 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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), and [snapshots and traces](#snapshots-and-trace-margoenginefsmtrace).
|
|
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
|
+
## Live inspection (`margoengine/fsm/inspect`)
|
|
231
|
+
|
|
232
|
+
`MachineView` shows hierarchy, outgoing triggers, remembered history and recent transitions.
|
|
233
|
+
Expanded state disclosures stay expanded through live refresh and filtering, independently
|
|
234
|
+
for each parallel machine. `FinalMachine.transitionDefinitions` exposes the authored
|
|
235
|
+
transitions in definition order, including `always`, `after` and event names; inspection
|
|
236
|
+
does not evaluate guards. `InvokeMachine` inherits these descriptions.
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import {FinalMachine} from 'margoengine/fsm/final';
|
|
240
|
+
import {MachineView} from 'margoengine/fsm/inspect';
|
|
241
|
+
|
|
242
|
+
const machine = new FinalMachine({idle: {}, waiting: {}, finished: {final: true}}, 'idle', {}, [
|
|
243
|
+
{from: 'idle', to: 'waiting', event: 'begin'},
|
|
244
|
+
{from: 'waiting', to: 'finished', after: 0.5}
|
|
245
|
+
]);
|
|
246
|
+
using view = new MachineView(machine, {parent: document.body, live: false});
|
|
247
|
+
machine.send('begin');
|
|
248
|
+
machine.update(0.5);
|
|
249
|
+
view.refresh();
|
|
250
|
+
console.log(machine.transitionDefinitions[1].after); // 0.5
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
Mounting defaults to `document.body`; `parent` takes precedence over `inspector: {element}`.
|
|
254
|
+
An inspector's open shadow root is used when available. `live` defaults to true and
|
|
255
|
+
refreshes on animation frames; false requires `refresh(filter?)`, where the default
|
|
256
|
+
filter is empty and matches state names without case sensitivity. `capacity` defaults
|
|
257
|
+
to 32 (1 to 10,000) recent trace entries. Supply `trace` to borrow an existing trace;
|
|
258
|
+
otherwise the view owns a new `MachineTrace`, which needs the machine's free listener.
|
|
259
|
+
`signal` defaults to none and abort disposes the view. `dispose()` and `using` remove
|
|
260
|
+
the overlay and stop its frame callbacks, disposing only an owned trace. Trigger
|
|
261
|
+
descriptions are available only when the optional final or invoke runtime is used;
|
|
262
|
+
ordinary machines retain their event and delay labels.
|
|
263
|
+
|
|
264
|
+
Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
|
|
265
|
+
|
|
266
|
+
Build and unit tests: npm test --workspace @margoengine/fsm
|
|
267
|
+
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { StateMachine } from './index.js';
|
|
2
|
+
/** A transition as data. As {@link Transition}, with `guard` naming a function of {@link MachineBindings}. */
|
|
3
|
+
export interface TransitionDocument {
|
|
4
|
+
/** Source state. */
|
|
5
|
+
from: string;
|
|
6
|
+
/** Target state. */
|
|
7
|
+
to: string;
|
|
8
|
+
/** Event name. Give this or `after`. */
|
|
9
|
+
event?: string;
|
|
10
|
+
/** Delay in seconds, above 0. Give this or `event`. */
|
|
11
|
+
after?: number;
|
|
12
|
+
/** Cross-fade time in seconds. Default 0. */
|
|
13
|
+
duration?: number;
|
|
14
|
+
/** Name in `bindings.guards`. Default none. */
|
|
15
|
+
guard?: string;
|
|
16
|
+
}
|
|
17
|
+
/** A state as data. Hooks are names in `bindings.hooks`, as functions do not fit in JSON. */
|
|
18
|
+
export interface StateDocument {
|
|
19
|
+
/** Name of the parent state. */
|
|
20
|
+
parent?: string;
|
|
21
|
+
/** Descendant to go on to. */
|
|
22
|
+
initial?: string;
|
|
23
|
+
/** What the state remembers. */
|
|
24
|
+
history?: 'shallow' | 'deep';
|
|
25
|
+
/** Hook name, called on entry. */
|
|
26
|
+
enter?: string;
|
|
27
|
+
/** Hook name, called on exit. */
|
|
28
|
+
exit?: string;
|
|
29
|
+
/** Hook name, called with the context and delta on update. */
|
|
30
|
+
update?: string;
|
|
31
|
+
/** Parallel regions by name, run while this state is active. A state with regions takes no hooks. */
|
|
32
|
+
regions?: Record<string, RegionDocument>;
|
|
33
|
+
/** With `regions`: each region resumes where it stopped. Default false. */
|
|
34
|
+
regionHistory?: boolean;
|
|
35
|
+
}
|
|
36
|
+
/** A region as data: states, a starting state and transitions. */
|
|
37
|
+
export interface RegionDocument {
|
|
38
|
+
/** States by name. */
|
|
39
|
+
states: Record<string, StateDocument>;
|
|
40
|
+
/** The starting state. */
|
|
41
|
+
initial: string;
|
|
42
|
+
/** Transitions. Default none. */
|
|
43
|
+
transitions?: TransitionDocument[];
|
|
44
|
+
}
|
|
45
|
+
/** A whole machine as plain data, so it saves and loads as JSON. */
|
|
46
|
+
export interface MachineDocument extends RegionDocument {
|
|
47
|
+
/** Format version; 1. */
|
|
48
|
+
version: 1;
|
|
49
|
+
}
|
|
50
|
+
/** The functions a document names. */
|
|
51
|
+
export interface MachineBindings<C> {
|
|
52
|
+
/** Hooks by name; `enter` and `exit` hooks get the context, `update` hooks the context and delta. */
|
|
53
|
+
hooks?: Readonly<Record<string, (context: C, delta: number) => void>>;
|
|
54
|
+
/** Guards by name. */
|
|
55
|
+
guards?: Readonly<Record<string, (context: C) => boolean>>;
|
|
56
|
+
}
|
|
57
|
+
/** One thing wrong with a document. */
|
|
58
|
+
export interface MachineIssue {
|
|
59
|
+
/** Where, such as `states.run.parent` or `transitions[2].to`. */
|
|
60
|
+
path: string;
|
|
61
|
+
/** What is wrong and how to fix it. */
|
|
62
|
+
message: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Every problem in a document, or an empty list. With `bindings`, each hook and guard must also name a function there.
|
|
66
|
+
* Takes any value, so it can check what `JSON.parse` returned.
|
|
67
|
+
*/
|
|
68
|
+
export declare function validateMachine<C>(value: unknown, bindings?: MachineBindings<C>): MachineIssue[];
|
|
69
|
+
/**
|
|
70
|
+
* Build a machine from a document. Its `enter` hooks run, as for `new StateMachine`.
|
|
71
|
+
* @throws TypeError listing every issue of {@link validateMachine}.
|
|
72
|
+
*/
|
|
73
|
+
export declare function loadMachine<C>(document: MachineDocument, context: C, bindings?: MachineBindings<C>): StateMachine<C>;
|
|
74
|
+
/**
|
|
75
|
+
* The document of a machine, for `JSON.stringify`: its definition, not where it is now; for that see `fsm/trace`.
|
|
76
|
+
* @throws TypeError for a hook or guard that is not in `bindings`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function saveMachine<C>(machine: StateMachine<C>, bindings?: MachineBindings<C>): MachineDocument;
|