@earnestjs/xstate 0.0.0-stage → 0.2.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.LESSER ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md CHANGED
@@ -1,3 +1,445 @@
1
- # Temporary Holding Version
1
+ # @earnestjs/xstate
2
2
 
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.
3
+ Earnest's state search for XState v5 machines, in two parts, both built on `search` from
4
+ [`@earnestjs/model`](../model/README.md#searching-states-that-are-not-a-model):
5
+
6
+ - `earnestPaths`, a path generator for XState's model-based tests. `createTestModel` from
7
+ `@xstate/graph` stays as it is: a test calls `model.getPaths(earnestPaths)` where it would call
8
+ `model.getShortestPaths()`, and gets one shortest path to every reachable state.
9
+ - `checkMachine`, which checks rules and stuck states on a machine, as `earnest verify` does on a
10
+ model, and gives the shortest path of events to each problem.
11
+ - `modelFileOf`, which writes a machine out as a `.model.ts` file, so `earnest verify` and TLC
12
+ can redo that check without running JavaScript.
13
+
14
+ The [integration page](https://earnest.cpeaustriajc.dev/integrations/xstate/) on the docs site
15
+ walks through both examples, the schema and the limits.
16
+
17
+ ## Installing
18
+
19
+ ```sh
20
+ npm install --save-dev @earnestjs/xstate xstate @xstate/graph
21
+ ```
22
+
23
+ `xstate` (5.19.4 or newer) and `@xstate/graph` (3.0.4 or newer) are peer dependencies, so the
24
+ test uses the copies the project already has. A test that declares the context or the payloads
25
+ with `m` imports it from `@earnestjs/model`: install the version `@earnestjs/xstate` depends on.
26
+
27
+ ## Getting the paths
28
+
29
+ `test/machines/turnstile.ts` in this package is a turnstile with a guard and an `assign`: a
30
+ visitor pays, pushes and enters, and the gate is full after two visitors. Its 7 states are
31
+ `locked`, `paid` and `open` with 0 and with 1 visitor, and `full`. `test/turnstile.test.ts`
32
+ checks `Gate`, a class in `test/gate.ts` that claims to work as the machine says:
33
+
34
+ ```ts title="test/turnstile.test.ts"
35
+ import { createTestModel } from "@xstate/graph";
36
+ import { earnestPaths } from "@earnestjs/xstate";
37
+ import { expect, test } from "vitest";
38
+ import { turnstile } from "./machines/turnstile.ts";
39
+ import { Gate } from "./gate.ts";
40
+
41
+ const model = createTestModel(turnstile);
42
+
43
+ for (const path of model.getPaths(earnestPaths)) {
44
+ test(path.description, async () => {
45
+ const gate = new Gate();
46
+ await path.test({
47
+ events: { PAY: () => gate.pay(), PUSH: () => gate.push(), ENTER: () => gate.enter() },
48
+ states: {
49
+ locked: () => expect(gate.state).toBe("locked"),
50
+ paid: () => expect(gate.state).toBe("paid"),
51
+ open: () => expect(gate.state).toBe("open"),
52
+ full: () => expect(gate.state).toBe("full"),
53
+ },
54
+ });
55
+ });
56
+ }
57
+ ```
58
+
59
+ `getPaths` drops a path that a longer one contains, as it does for `getShortestPaths`. Every
60
+ state of the turnstile lies on the path to `full`, so the loop runs 1 test, of 6 events. Pass
61
+ `{ allowDuplicatePaths: true }` to get all 7 paths.
62
+
63
+ - Each path has the shape of XState's own shortest paths: a first step with the start snapshot
64
+ and the event `xstate.init`, one step per event with the snapshot after it, `state` (the
65
+ last snapshot) and `weight` (the number of events).
66
+ - The options of `getPaths` work as they do for `getShortestPaths`. States are told apart by
67
+ `serializeState`, which `createTestModel` makes from the snapshot and the event that led to
68
+ it. The search starts at `fromState`, or at the initial snapshot made with `input`. It sends
69
+ the events `events` lists, does not go on from a state for which `stopWhen` is true (by
70
+ default `toState`), and gives only the paths that end in a state for which `toState` is true.
71
+ - A finite `limit` is the most distinct states the search may hold; without one it is the
72
+ default of `search`, 5,000,000. When the states do not fit, `getPaths` throws an error that
73
+ names the limit and the count, such as `earnestPaths stopped at the state limit of 3 after 3
74
+ states`, and gives no paths.
75
+
76
+ ## Checking rules and stuck states
77
+
78
+ `test/machines/open-turnstile.ts` is the turnstile of Earnest's conformance models as a machine:
79
+ the gate is `locked` or `open`, and `paid` is in the context. `PUSH` opens a locked gate without
80
+ asking for payment:
81
+
82
+ ```ts title="test/machines/open-turnstile.ts"
83
+ import { assign, setup } from "xstate";
84
+
85
+ export const openTurnstile = setup({
86
+ types: {
87
+ context: {} as { paid: boolean },
88
+ events: {} as { type: "PAY" } | { type: "PUSH" } | { type: "ENTER" },
89
+ },
90
+ }).createMachine({
91
+ id: "openTurnstile",
92
+ initial: "locked",
93
+ context: { paid: false },
94
+ states: {
95
+ locked: {
96
+ on: {
97
+ PAY: { guard: ({ context }) => !context.paid, actions: assign({ paid: true }) },
98
+ PUSH: { target: "open" },
99
+ },
100
+ },
101
+ open: {
102
+ on: {
103
+ ENTER: { target: "locked", actions: assign({ paid: false }) },
104
+ },
105
+ },
106
+ },
107
+ });
108
+ ```
109
+
110
+ `test/open-turnstile.test.ts` checks it with one rule. `checkMachine` takes the events to try in
111
+ every state and the rules by id, each a sentence `says` and a predicate `holds` on the snapshot:
112
+
113
+ ```ts title="test/open-turnstile.test.ts"
114
+ import { checkMachine } from "@earnestjs/xstate";
115
+ import { expect, test } from "vitest";
116
+ import { openTurnstile } from "./machines/open-turnstile.ts";
117
+
118
+ test("the gate opens unpaid after one push", () => {
119
+ const found = checkMachine(openTurnstile, {
120
+ events: [{ type: "PAY" }, { type: "PUSH" }, { type: "ENTER" }],
121
+ rules: {
122
+ locked: {
123
+ says: "The gate is never open unpaid",
124
+ holds: (snapshot) => snapshot.matches("locked") || snapshot.context.paid,
125
+ },
126
+ },
127
+ });
128
+ expect(found.status).toBe("fail");
129
+ expect(found.states).toBe(4);
130
+ expect(found.rules[0]?.verdict).toBe("broken");
131
+ expect(found.rules[0]?.path?.events).toStrictEqual([{ type: "PUSH" }]);
132
+ });
133
+ ```
134
+
135
+ The machine has 4 states, `locked` and `open`, each paid and unpaid, the count `earnest verify`
136
+ gives for `turnstile.model.ts`. The rule is broken after the one event `PUSH`.
137
+
138
+ - The result has the fields of `explore` from `@earnestjs/model`: `status` (`pass`, `fail` or
139
+ `unfinished`), `states`, `rules` (`id`, `says`, `verdict` and `path`), `findings` and `reason`.
140
+ `reached()` gives the shortest path to every state, in the order the search reached them.
141
+ - A path has the initial snapshot `start`, one step `{ event, snapshot }` per event, `events`
142
+ (the events alone, ready to `send` to an actor of the machine) and `end`, the last snapshot.
143
+ - Two snapshots are one state when their state value, context and status are equal, whatever
144
+ event led there. The context must be plain data: plain objects with string keys, arrays,
145
+ strings, numbers, booleans, `null`, `undefined`, and values with a `toJSON`, such as a
146
+ `Date`, read through it. A `Map`, a class instance or a function in it is an error.
147
+ A field set to `undefined` is the same as no field.
148
+ - `events` is a list or a function of the snapshot, as in `@xstate/graph`. An event is tried
149
+ only where `snapshot.can(event)` is true, so a failed guard, or a transition with no target
150
+ and no action, is not taken.
151
+ - A snapshot whose status is `done` (a top-level final state) is an end. Any other snapshot
152
+ where no listed event can happen is a stuck state, reported in `findings` with its path.
153
+ - `input` is the machine's input. `maxStates` is the most distinct states the check may hold,
154
+ 5,000,000 by default. Past it, `reason` says so, as in `state limit of 3`, no rule that was
155
+ not seen broken `holds`, and the check is `unfinished` unless it already found a problem.
156
+ - Events go through the machine's `transition`. No action of your own runs, except one made with
157
+ `assign`, and no child actor starts, but the code that computes the next snapshot does, often more than once:
158
+ guards, `assign`, `enqueueActions` callbacks, invoke `input` and the context of a child
159
+ machine. Keep that code free of side effects, with the same result for the same snapshot and
160
+ event.
161
+
162
+ ## Bounding the context and declaring payloads
163
+
164
+ A context is any JavaScript, so a count that grows forever gives a new state on every event, and
165
+ only `maxStates` stops the search. `checkMachine` takes declarations written with `m` from
166
+ [`@earnestjs/model`](../model/README.md#the-builders) that bound it.
167
+ `test/machines/visitor-count.ts` counts visitors who enter in groups and never stops:
168
+
169
+ ```ts title="test/machines/visitor-count.ts"
170
+ import { assign, setup } from "xstate";
171
+
172
+ export const visitorCount = setup({
173
+ types: {
174
+ context: {} as { visitors: number },
175
+ events: {} as { type: "ENTER"; group: number },
176
+ },
177
+ }).createMachine({
178
+ id: "visitorCount",
179
+ context: { visitors: 0 },
180
+ on: {
181
+ ENTER: {
182
+ actions: assign({ visitors: ({ context, event }) => context.visitors + event.group }),
183
+ },
184
+ },
185
+ });
186
+ ```
187
+
188
+ `test/visitor-count.test.ts` declares the group size of `ENTER` and the range of `visitors`:
189
+
190
+ ```ts title="test/visitor-count.test.ts"
191
+ import { m } from "@earnestjs/model";
192
+ import { checkMachine } from "@earnestjs/xstate";
193
+ import { expect, test } from "vitest";
194
+ import { visitorCount } from "./machines/visitor-count.ts";
195
+
196
+ test("the count leaves its range after two groups of two", () => {
197
+ const found = checkMachine(visitorCount, {
198
+ events: { ENTER: { group: m.int(1, 2) } },
199
+ context: { visitors: m.int(0, 3) },
200
+ rules: {
201
+ counted: {
202
+ says: "The count is never below zero",
203
+ holds: (snapshot) => snapshot.context.visitors >= 0,
204
+ },
205
+ },
206
+ });
207
+ expect(found.status).toBe("fail");
208
+ expect(found.states).toBe(6);
209
+ expect(found.rules[0]?.verdict).toBe("unknown");
210
+ expect(found.findings[0]?.message).toBe(
211
+ "the context field `visitors` leaves the values it declares",
212
+ );
213
+ expect(found.findings[0]?.path.events).toStrictEqual([
214
+ { type: "ENTER", group: 2 },
215
+ { type: "ENTER", group: 2 },
216
+ ]);
217
+ });
218
+ ```
219
+
220
+ The counts 0 to 3 are in range. Groups of 1 and 2 reach 4 and 5 from them, and those two states
221
+ are out of range, 6 in all. The first state out of range is 4, after two groups of 2, and
222
+ nothing is searched from 4 or 5.
223
+
224
+ - `context` declares some fields of the context. A snapshot where one of them holds a value its
225
+ declaration does not have is out of range, as a model's state is in `explore`. It is counted,
226
+ no rule is judged in it, and nothing is searched from it. `findings` gives the first one, as
227
+ `out-of-range` with its shortest path and the message ``the context field `visitors` leaves the
228
+ values it declares``. The check fails, and a rule not seen broken is `unknown`.
229
+ - A field the schema names but the context lacks, or holds `undefined`, is out of range, unless
230
+ its declaration is `.optional()`: an optional field is in range when it is missing,
231
+ `undefined` or `null`. For the context `{ mode: "on"; level: number } | { mode: "off" }`,
232
+ declare `context: { level: m.int(0, 3).optional() }`; without `.optional()`, every snapshot of
233
+ the member that lacks `level` is out of range. An optional declaration so no longer tells a
234
+ stray `undefined` from `null`.
235
+ The same holds inside a record, at any depth: an optional field there is in range when it is
236
+ missing, `undefined` or `null`, and any other missing field is out of range. A field set to
237
+ `undefined` is the same as no field, as it is in the state, so a record may hold it where its
238
+ declaration lacks the field. A field the schema does not name is not checked.
239
+ - A value a record declaration checks must be plain data at every level. An object that is not
240
+ a plain object, such as a `Date` where `m.record({})` is declared, is out of range.
241
+ - `events` can be a record of event types, each with a declaration for each payload field, such
242
+ as `{ PAY: { coins: m.int(1, 2) }, PUSH: {} }`. Each type is tried with every combination of
243
+ its fields' values, the first field varying fastest, as `explore` tries an action's inputs
244
+ (`combinationsOf` from `@earnestjs/model` lists them). The event sent, and shown in a path, is
245
+ `{ type, ...payload }`. Types are tried in the record's key order, where JavaScript puts
246
+ integer-like keys first. A type with more than 1,000,000 payloads is a `RangeError`. A record
247
+ payload arrives frozen and is shared by every snapshot it is sent from: copy it, never change
248
+ it in place.
249
+ - The keys of `context`, the event types and their fields are checked against the machine's
250
+ types, so a misspelt one does not compile. `context` may name a field of any member of a union
251
+ context.
252
+ - The declarations must hold plain JavaScript values: `m.boolean()`, `m.int`, `m.enum`,
253
+ `m.oneOf`, `.optional()` of those, and `m.record` of all of these. A set, map, sequence,
254
+ queue, lock, timer, request or retry, also inside an optional or a record, holds objects of
255
+ `@earnestjs/model` that a context or an event does not, and `checkMachine` throws a
256
+ `TypeError` that names the field before it searches, as in `checkMachine can't take
257
+ context.tags, a set declaration`.
258
+ - An entry that is not a declaration, which plain JavaScript or a cast lets through, is a
259
+ `TypeError` before the search too. It names the entry and says what it found: `checkMachine
260
+ can't take context.visitors: it is the number 1, not a declaration; write one with m from
261
+ @earnestjs/model, such as m.int(0, 3), or m.record({ ... }) for an object`. An event type's entry must be a record of payload
262
+ fields, `{}` for none; anything else, a whole `m.record(...)` included, is refused the same
263
+ way.
264
+
265
+ ## Writing a machine out as a model file
266
+
267
+ `checkMachine` searches in the test's own process. `modelFileOf` writes the machine out as a
268
+ model file, so the `earnest` binary and TLC can confirm that search on their own.
269
+ `test/open-turnstile-model.test.ts` writes the open turnstile with the options its check used,
270
+ and the context declared:
271
+
272
+ ```ts title="test/open-turnstile-model.test.ts"
273
+ import { readFileSync } from "node:fs";
274
+ import { m } from "@earnestjs/model";
275
+ import { modelFileOf } from "@earnestjs/xstate";
276
+ import { expect, test } from "vitest";
277
+ import { openTurnstile } from "./machines/open-turnstile.ts";
278
+
279
+ test("the open turnstile is written out as a model file", () => {
280
+ const { text, threw } = modelFileOf(openTurnstile, {
281
+ name: "OpenTurnstile",
282
+ events: [{ type: "PAY" }, { type: "PUSH" }, { type: "ENTER" }],
283
+ context: { paid: m.boolean() },
284
+ rules: {
285
+ locked: {
286
+ says: "The gate is never open unpaid",
287
+ holds: (snapshot) => snapshot.matches("locked") || snapshot.context.paid,
288
+ },
289
+ },
290
+ });
291
+ expect(threw).toStrictEqual([]);
292
+ const committed = new URL("models/open-turnstile.model.ts", import.meta.url);
293
+ expect(text).toBe(readFileSync(committed, "utf8"));
294
+ });
295
+ ```
296
+
297
+ `text` is the committed file `test/models/open-turnstile.model.ts`:
298
+
299
+ ```ts title="test/models/open-turnstile.model.ts"
300
+ import { m } from "@earnestjs/model";
301
+
302
+ export const OpenTurnstile = m.model("OpenTurnstile", {
303
+ state: m.enum(["locked", "open"]).initial("locked"),
304
+ paid: m.boolean().initial(false),
305
+ });
306
+
307
+ export const PAY = m.action(OpenTurnstile, "PAY", {
308
+ when: (s) => s.state === "locked" && !s.paid,
309
+ changes: () => ({ paid: true }),
310
+ });
311
+
312
+ export const PUSH = m.action(OpenTurnstile, "PUSH", {
313
+ when: (s) => s.state === "locked",
314
+ changes: () => ({ state: "open" }),
315
+ });
316
+
317
+ export const ENTER = m.action(OpenTurnstile, "ENTER", {
318
+ when: (s) => s.state === "open",
319
+ changes: () => ({ state: "locked", paid: false }),
320
+ });
321
+
322
+ export const locked = m.rule(
323
+ OpenTurnstile,
324
+ "The gate is never open unpaid",
325
+ (s) => !(s.state === "open" && !s.paid),
326
+ );
327
+
328
+ export type State = m.Infer<typeof OpenTurnstile>;
329
+ ```
330
+
331
+ `earnest verify test/models/open-turnstile.model.ts` gives what `checkMachine` gave: `fail`, 4
332
+ states, and `locked` broken after the one action `PUSH`. `earnest confirm --tlc
333
+ tla2tools.jar test/models/open-turnstile.model.ts` prints `same OpenTurnstile 4 states
334
+ fail`: TLC finds the same.
335
+
336
+ - No guard or `assign` is read as source. `modelFileOf` runs the machine's own `transition`
337
+ with every listed event and declared payload, on every state value the machine can take, with
338
+ every combination of declared context values, and writes the results as tables. A guard may
339
+ call a helper, read a constant or look up a `Map`. The combinations include contexts
340
+ `checkMachine` never reaches, so `earnest verify` searches the whole table from the start.
341
+ - The model has the field `state`, a label for the state value, such as `locked` or
342
+ `on.lid.shut, on.water.cold`, and one field per declared context field, with the declaration
343
+ given. Where two states differ only in what a history state remembers, the label says it, as
344
+ in `off (on.last: on.high)`. Each field starts where the initial snapshot, made with `input`,
345
+ starts.
346
+ - Each event type is an action whose sentence is the event type, with the payload fields as its
347
+ `input`. Each rule keeps its id and sentence. A top-level final state is an `m.end`. An id
348
+ that is not a name, such as `user.click`, becomes one, such as `user_click`. `actions` and
349
+ `rules` in the result map each exported id back to the event type or rule id.
350
+ - A transition that leaves a declaration, such as `visitors` going to 4 past `m.int(0, 3)`, is
351
+ written as it is, so `earnest verify` reports the state out of range, as `checkMachine` does.
352
+ - A guard, `assign` or rule that throws at a point of the table is listed in `threw`. The file
353
+ makes reaching that point visible: the event sets the extra field `threw` to 1, outside
354
+ `m.int(0, 0)`, so the state is out of range, and the rule is broken there. Expect `threw` to
355
+ be empty, as the test above does.
356
+ - Where `checkMachine` reaches a state, the machine is given the context `checkMachine` reaches
357
+ there, so an optional field stays missing, `undefined` or `null` as the machine left it, at
358
+ any depth. Elsewhere an optional context field's `null` is given as a missing field when the
359
+ initial context lacks the field, and as `null` otherwise; inside a record it is given as
360
+ `null`. A missing field and `undefined` read back as `null`.
361
+ - Each event and each rule gets a snapshot rebuilt from the state value, the context and what
362
+ history remembers, so an `assign` that changes the context in place changes nothing else. The
363
+ snapshot has no `output` and no child actors: a rule must not read them.
364
+ - The file typechecks as long as every value it writes is of its field's type. A transition that
365
+ writes text outside an `m.enum`, or a number outside an `m.oneOf`, gives a file `earnest
366
+ verify` reads but `tsc` refuses.
367
+ - The same machine and options give the same text. `maxStates` is not written: pass
368
+ `--max-states` to `earnest verify`.
369
+
370
+ `modelFileOf` refuses, with an error that names the field or the event:
371
+
372
+ - a context field without a declaration in `context`, before any event is tried:
373
+ ``modelFileOf can't write the context field `paid` of the initial snapshot: it has no
374
+ declaration in context``;
375
+ - `events` given as a function, and a listed event with a payload, such as
376
+ `{ type: "ENTER", group: 1 }`: write those as a record of event types;
377
+ - a table of more than `MOST_TABLE_ROWS` (100,000) rows. A row is one state value with one
378
+ combination of context values and one event with one payload, or one rule. The count for one
379
+ state value is checked from the declarations before any event is tried, and the count for the
380
+ state values found as they are found;
381
+ - a next context that the declaration's type can't hold, such as text in a field declared
382
+ `m.boolean()`, or a field with no declaration, naming the event that wrote it;
383
+ - an optional field, at any depth, that the machine leaves missing or `undefined` in one state
384
+ and sets to `null` in another that is otherwise the same. `checkMachine` counts two states
385
+ there and the file has one `null` for both, so the error names the event and the field:
386
+ ``modelFileOf can't write the context field `spot.dim` after the event {"type":"DROP"}: it is
387
+ missing or undefined here and null in a state reached before that is otherwise the same``;
388
+ - an initial context outside its declarations, a model name or field name that is not an
389
+ identifier, and the declarations `checkMachine` refuses.
390
+
391
+ The confirmation shows that the search over the machine's own transitions, on the declared
392
+ values, gives the same states and verdicts in `earnest verify` and TLC. It does not check the
393
+ machine against the app: test the app against the machine with `earnestPaths`.
394
+
395
+ ## Limits
396
+
397
+ - The paths come in the order the search reached their states: breadth first, events in the
398
+ order `events` lists them. When two paths to a state are equally short, the one found first is
399
+ kept. XState's order and choice can differ, so a test must not rely on either.
400
+ - `getSimplePaths` stays with XState.
401
+ - `checkMachine` tries only the events `events` gives, with the payloads written or declared
402
+ there. No timer fires and no invoked actor finishes, so a state left only by `after` or by `onDone` is
403
+ reported stuck.
404
+ - A state is its value, its context, its status and the states its history states remember. A
405
+ machine with a history state counts a state again once a history state remembers something.
406
+ A final state's output and the child actors are not part of a state, so two snapshots that
407
+ differ only there count as one. An actor
408
+ spawned into the context without an `id` gets a new one on each event, so give it an `id`.
409
+ - Every state found is held in memory with its whole snapshot, a few hundred bytes for a small
410
+ context. A machine with millions of states can run out of memory before the default
411
+ `maxStates`; give a lower one.
412
+ - Child actors are made but never run, and the machine has no parent. An error in a child,
413
+ its `onDone` and `onError`, and events sent with `sendTo` to `self` are not followed, and
414
+ `sendParent` throws. List an event sent to `self` in `events` to have it tried.
415
+ - All events are sent in one actor system, so a child actor with a `systemId` that starts a
416
+ second time, as when its state is entered again, makes `checkMachine` throw that the id
417
+ already exists.
418
+ - `checkMachine` runs in the test's process, on the machine's `transition`, not in the `earnest`
419
+ binary. `modelFileOf` writes a file the binary can check.
420
+ - `modelFileOf` takes the same limits: no timer, child actor or `onDone`.
421
+
422
+ ## Development
423
+
424
+ From this folder, after `bun install --frozen-lockfile` at the repository root:
425
+
426
+ ```sh
427
+ bun run typecheck # tsrs --noEmit, over src/, scripts/ and test/
428
+ bun run format # oxfmt --check
429
+ bun run test # vitest run
430
+ ```
431
+
432
+ - The tests compare `getPaths(earnestPaths)` with `getShortestPaths()` on the turnstile and on
433
+ each traversal option, and run every path's `test` against a working gate.
434
+ - The tests of `checkMachine` compare the open turnstile with the same model checked by
435
+ `explore`, and check the working turnstile, a stuck state, a final state and the state limit.
436
+ - The tests of the schema compare a counter out of range with the same model checked by
437
+ `explore`, try each kind of declaration as a context field and as a payload, and check the
438
+ refusal of each kind that is not plain.
439
+ - The tests of `modelFileOf` compare each file in `test/models/` with what it writes, byte for
440
+ byte, and compare `earnest verify --json` on it with `checkMachine` on the machine. They build
441
+ the `earnest` binary with `cargo build --release`, as the tests of `@earnestjs/cli` do, and are
442
+ skipped when `cargo` is not on the `PATH`.
443
+ - `tsconfig.json` sets `skipLibCheck`: the declarations `xstate` ships do not compile under
444
+ `exactOptionalPropertyTypes`, which this package keeps on for its own code.
445
+ - `bun run build` and `prepack` work as in `@earnestjs/model`.