@highalch/story 0.0.0-stage → 0.0.1

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.
@@ -0,0 +1,145 @@
1
+ import { W as Source$1, o as Step, s as Steps } from "./steps-CvFOQHum.mjs";
2
+ import { n as Story, o as Invariant } from "./run-C2SdDPWE.mjs";
3
+ import { TaggedFailure } from "@highalch/db";
4
+ import { Answer, Input } from "@highalch/db/internal";
5
+ import { Invocable, Invocable as Invocable$1, Marked, Marked as Marked$1, Runner, commandOf, invoke, mark } from "@highalch/db/xstate";
6
+ import { AnyStateMachine, EventFromLogic, EventObject, MachineContext, StateValue } from "xstate";
7
+ /** Which machine a step addresses: the one of this name, else the one introduced last. */
8
+ type Addressed = {
9
+ readonly machine?: string;
10
+ };
11
+ /** How a machine is named when it enters a story (default: its `id`). */
12
+ type Named = {
13
+ readonly name?: string;
14
+ };
15
+ /** What a snapshot is expected to be: a state value it matches and, optionally, context fields. */
16
+ type Expected = {
17
+ readonly state: StateValue;
18
+ readonly context?: MachineContext;
19
+ };
20
+ /**
21
+ * Reads what a source shows now in the step's client (or the client of `as`), opened and settled
22
+ * first if it was not observed yet: its rows by key, without TanStack DB's virtual fields. It needs
23
+ * a hosted story.
24
+ */
25
+ type Read = <Row extends object>(source: Source$1<Row>, options?: {
26
+ readonly as?: string;
27
+ }) => Promise<ReadonlyArray<Row>>;
28
+ /** A value given as is, or computed from what the story's sources show when the step runs. */
29
+ type FromShown<T> = T | ((read: Read) => T | Promise<T>);
30
+ /** A snapshot a stepped machine starts from: a state value and context, or the machine's input. */
31
+ type Snapshot = {
32
+ readonly state?: StateValue;
33
+ readonly context?: MachineContext;
34
+ readonly input?: Input;
35
+ };
36
+ /**
37
+ * The machine enters the story **stepped purely**: from this snapshot (its initial state and
38
+ * context when omitted, for `input`), every later step is XState's pure `transition`. Nothing
39
+ * runs: `asked` reads the commands a transition would spawn, and `done`/`failed` feed it their
40
+ * results. Works in a hostless story; in a hosted one the snapshot can be computed from what the
41
+ * sources show (`(read) => snapshot`), and the data steps around it run as usual.
42
+ */
43
+ declare const given: (machine: AnyStateMachine, snapshot?: FromShown<Snapshot>, options?: Named) => Step;
44
+ /**
45
+ * The machine enters the story **running**: started with `createEffectActor` against the story's
46
+ * client (of the step's scope, so `as(scope, Machine.start(...))` runs it on that client). The
47
+ * commands it invokes through `invoke(command)` run there and are recorded; their real outcomes
48
+ * arrive by themselves, and `Story.settled`/`Story.rejected` assert them. Stopped when the story
49
+ * ends. Needs a hosted story.
50
+ */
51
+ declare const start: (machine: AnyStateMachine, options?: Named & {
52
+ readonly input?: Input;
53
+ }) => Step;
54
+ /**
55
+ * The machine receives an event (or one computed from what the sources show: `(read) => event`).
56
+ * Stepped: its next snapshot and the commands it would ask for; nothing runs. Running: sent to
57
+ * the actor, which reacts and starts the commands it asks for on the story's client; their replies
58
+ * wait, as after a data `when`, until a settling step.
59
+ */
60
+ declare const when: <E extends EventObject>(event: FromShown<E>, options?: Addressed) => Step;
61
+ /** The machine is in this state (`snapshot.matches(state)`), with these context fields. */
62
+ declare const then: (expected: Expected, options?: Addressed) => Step;
63
+ /**
64
+ * The machine asked for this command (with input fields like these) since its last event.
65
+ * Stepped: the spawn actions of `invoke(command)` logic its last transition returned. Running:
66
+ * the commands the story's `Runner` ran for it.
67
+ */
68
+ declare const asked: <I extends object>(command: Invocable$1<I, unknown, unknown>, input?: Partial<I>, options?: Addressed) => Step;
69
+ /** The machine asked for no command since its last event. */
70
+ declare const askedNothing: (options?: Addressed) => Step;
71
+ /**
72
+ * Stepped only: the command the machine asked for last settled with this output (its `Settled`
73
+ * value); the machine takes `xstate.done.actor.*`.
74
+ */
75
+ declare const done: (command: Marked$1, output?: Answer, options?: Addressed) => Step;
76
+ /**
77
+ * Stepped only: the command the machine asked for last failed with this typed error; the machine
78
+ * takes `xstate.error.actor.*`.
79
+ */
80
+ declare const failed: (command: Marked$1, error: TaggedFailure, options?: Addressed) => Step;
81
+ /**
82
+ * Machine steps, run by the one story runner beside data steps, in any order. A machine enters a
83
+ * story one of two ways, chosen once: `given` (stepped purely, works hostless) or `start` (running
84
+ * against the story's client, needs a host). `when`, `then`, `asked` and `askedNothing` mean the
85
+ * same in both; `done`/`failed` feed results to a stepped machine only. Each takes an optional
86
+ * `{ machine }` naming the machine (default: the one introduced last); `given`/`start` take
87
+ * `{ name }` (default: the machine's `id`).
88
+ */
89
+ export declare const Machine: {
90
+ readonly given: typeof given;
91
+ readonly start: typeof start;
92
+ readonly when: typeof when;
93
+ readonly then: typeof then;
94
+ readonly asked: typeof asked;
95
+ readonly askedNothing: typeof askedNothing;
96
+ readonly done: typeof done;
97
+ readonly failed: typeof failed;
98
+ };
99
+ /** One path through a model: its events, in order. */
100
+ type Path<E> = ReadonlyArray<E>;
101
+ /** What `explore` needs: the model, how each of its events acts on a story, and limits. */
102
+ type Exploration<M extends AnyStateMachine> = {
103
+ /** A small machine that models what can happen (its events) and when (its guards). */
104
+ readonly model: M;
105
+ /** The events to try in every state (XState's graph traversal takes them as given). */
106
+ readonly events: ReadonlyArray<EventFromLogic<M>>;
107
+ /** The story steps of one model event; `index` counts the path's events from 0. */
108
+ readonly steps: (event: EventFromLogic<M>, index: number) => Steps;
109
+ /** Steps before every path (history, opened sources). */
110
+ readonly before?: Steps;
111
+ /** Steps after every path (resume the feed, wait for every command). */
112
+ readonly after?: Steps;
113
+ /** The story runner each path runs on (a fresh world per path). */
114
+ readonly story: Story;
115
+ /** Checked after every step and at the end of each path. */
116
+ readonly invariants: ReadonlyArray<Invariant>;
117
+ /** Paths longer than this many events are not run (default 4). */
118
+ readonly maxLength?: number;
119
+ /** At most this many paths run, in their deterministic order (default 200). */
120
+ readonly maxPaths?: number;
121
+ /** Shrinks a failing path to a shorter one that still fails (default true). */
122
+ readonly shrink?: boolean;
123
+ /** At most this many model states are traversed (default 10 000): the model must be finite. */
124
+ readonly limit?: number;
125
+ };
126
+ /** What an exploration ran. */
127
+ type Explored = {
128
+ readonly paths: number;
129
+ readonly steps: number;
130
+ };
131
+ /**
132
+ * The paths to run: XState's `getShortestPaths` and `getSimplePaths` (`xstate/graph`) over the
133
+ * model (which must be finite: bound it with a counter in its context), without the initial step, deduplicated, without those that a longer path to run
134
+ * contains as a prefix (every step of a path is checked, so its prefixes are), at most
135
+ * `maxLength` events, ordered by length then by their events.
136
+ */
137
+ export declare const pathsOf: <M extends AnyStateMachine>(model: M, events: ReadonlyArray<EventFromLogic<M>>, maxLength: number, limit?: number) => ReadonlyArray<Path<EventFromLogic<M>>>;
138
+ /**
139
+ * Model-based stories: enumerates the model's paths (XState's graph utilities) and runs each as a
140
+ * story (`before`, each event's steps, `after`), checking the invariants after every step. Fails
141
+ * with the shortest failing path it found (shrunk), as a readable event sequence, and the story's
142
+ * own report. Deterministic: the same model and options run the same paths in the same order.
143
+ */
144
+ export declare const explore: <M extends AnyStateMachine>(exploration: Exploration<M>) => Promise<Explored>;
145
+ export { type Addressed, type Expected, type Exploration, type Explored, type FromShown, type Invocable, type Marked, type Named, type Path, type Read, Runner, type Snapshot, commandOf, invoke, mark };
@@ -0,0 +1,405 @@
1
+ import { L as Mismatch, j as json, m as partial, s as flatten, w as staged } from "./steps-DZBFsrQr.mjs";
2
+ import { t as StoryFailure } from "./run-DMO8Dcmq.mjs";
3
+ import { Effect, Exit, Option, Predicate, Scope } from "effect";
4
+ import { Runner, Runner as Runner$1, commandOf, commandOf as commandOf$1, invoke, mark } from "@highalch/db/xstate";
5
+ import { createEffectActor } from "@xstate/effect";
6
+ import { initialTransition, transition } from "xstate";
7
+ import { getShortestPaths, getSimplePaths } from "xstate/graph";
8
+ // src/xstate/machine.ts
9
+ const machinesKey = Symbol("@highalch/story/xstate/machines");
10
+ const machinesOf = (stage) => stage.slot(machinesKey, () => ({
11
+ entered: /* @__PURE__ */ new Map(),
12
+ latest: Option.none()
13
+ }));
14
+ const readerOf = (stage, label) => async (source, options = {}) => {
15
+ const world = stage.hosted(label);
16
+ const { observed, opened } = await world.observe(source, options.as);
17
+ if (opened) await world.settle();
18
+ return observed.sorted().map(([, shown]) => shown.row);
19
+ };
20
+ const resolved = async (value, stage, label) => {
21
+ if (Predicate.isFunction(value)) return value(readerOf(stage, label));
22
+ return value;
23
+ };
24
+ /** The name a machine's `setup({ actors })` registers this command's logic under, if any. */
25
+ const sourceOf = (machine, command) => Option.fromUndefinedOr(Object.entries(machine.sources.actors ?? {}).find(([, logic]) => Option.contains(commandOf$1(logic), command))?.[0]);
26
+ const nameOf = (machine, command) => Option.getOrElse(sourceOf(machine, command), () => "a command");
27
+ const isSpawn = (action) => action.type === "@xstate.spawn" && Predicate.hasProperty(action, "logic") && Predicate.hasProperty(action, "id") && Predicate.isString(action.id);
28
+ const spawnedBy = (actions) => actions.flatMap((action) => {
29
+ if (!isSpawn(action)) return [];
30
+ return Option.match(commandOf$1(action.logic), {
31
+ onNone: () => [],
32
+ onSome: (command) => [{
33
+ command,
34
+ id: action.id,
35
+ input: action.input
36
+ }]
37
+ });
38
+ });
39
+ const stepped = (machine, event) => {
40
+ const [snapshot, actions] = transition(machine.machine, machine.snapshot, event);
41
+ const asked = spawnedBy(actions);
42
+ return {
43
+ ...machine,
44
+ snapshot,
45
+ asked,
46
+ invoked: [...machine.invoked, ...asked]
47
+ };
48
+ };
49
+ const snapshotOf = (machine) => {
50
+ if (machine.mode === "stepped") return machine.snapshot;
51
+ return machine.actor.getSnapshot();
52
+ };
53
+ /** The commands asked for since the last event: spawned (stepped) or run on the client (running). */
54
+ const askedOf = (stage, machine, label) => {
55
+ if (machine.mode === "stepped") return machine.asked;
56
+ return stage.hosted(label).runs.filter((run) => run.by === byOf(machine.name) && run.tick > machine.since).flatMap((run) => Option.match(run.command, {
57
+ onNone: () => [],
58
+ onSome: (command) => [{
59
+ command,
60
+ input: run.input
61
+ }]
62
+ }));
63
+ };
64
+ const where = (machine) => `${machine.name} (${machine.mode})`;
65
+ const describe = (snapshot) => `${json(snapshot.value)} ${json(snapshot.context)}`;
66
+ const listed = (machine, asked) => {
67
+ if (asked.length === 0) return "nothing";
68
+ return asked.map((each) => `${nameOf(machine.machine, each.command)} ${json(each.input)}`).join(", ");
69
+ };
70
+ /** What every machine failure lists: where the machine is and what it asked for. */
71
+ const context = (stage, machine, label) => [`machine ${where(machine)} is ${describe(snapshotOf(machine))}`, `asked since its last event: ${listed(machine, askedOf(stage, machine, label))}`];
72
+ const byOf = (name) => `machine:${name}`;
73
+ /** The machine a step addresses: named, or the one introduced last. */
74
+ const find = (stage, options) => {
75
+ const machines = machinesOf(stage);
76
+ const name = Option.orElse(Option.fromUndefinedOr(options.machine), () => machines.latest);
77
+ if (Option.isNone(name)) throw new Mismatch("no machine in the story yet: bring one in with Machine.given(machine, snapshot) to step it purely, or Machine.start(machine, { input }) to run it");
78
+ const found = machines.entered.get(name.value);
79
+ if (!found) throw new Mismatch(`the story has no machine named "${name.value}"`, [`machines: ${[...machines.entered.keys()].join(", ") || "none"}`]);
80
+ return found;
81
+ };
82
+ const enter = (stage, machine) => {
83
+ const machines = machinesOf(stage);
84
+ if (machines.entered.has(machine.name)) throw new Mismatch(`the story already has a machine named "${machine.name}": name this one ({ name })`);
85
+ machines.entered.set(machine.name, machine);
86
+ machines.latest = Option.some(machine.name);
87
+ };
88
+ /** Replaces a stepped machine's state after a pure step. */
89
+ const store = (stage, machine) => {
90
+ machinesOf(stage).entered.set(machine.name, machine);
91
+ };
92
+ const prefix = (options) => Option.match(Option.fromUndefinedOr(options.machine), {
93
+ onNone: () => "",
94
+ onSome: (name) => `${name}: `
95
+ });
96
+ const isCallable = (command) => Predicate.hasProperty(command, "with") && Predicate.isFunction(command.with);
97
+ /**
98
+ * The story's runner of a running machine's commands: on the client of the machine's scope,
99
+ * recorded as the machine's (`asked` reads them; `settled`/`rejected` assert the last one).
100
+ */
101
+ const runnerOf = (world, machine) => Runner$1.of({ run: (command, input) => Effect.promise(() => {
102
+ const running = machine();
103
+ return world.start(`${running.name}: ${nameOf(running.machine, command)}`, running.scope, byOf(running.name), input, (client, onCommitted) => {
104
+ if (!isCallable(command)) throw new Error("invoke(command) takes a declared HighAlch command");
105
+ return command.with({ client })(input, { onCommitted });
106
+ }, Option.some(command));
107
+ }).pipe(Effect.flatMap((run) => Effect.promise(() => run.done.then(() => run.outcome))), Effect.flatMap((outcome) => {
108
+ if (Predicate.isTagged(outcome, "Rejected") && "error" in outcome) return Effect.fail(outcome.error);
109
+ if (Predicate.isTagged(outcome, "Died") && "cause" in outcome) return Effect.failCause(outcome.cause);
110
+ const value = Option.flatten(Option.liftPredicate(Predicate.hasProperty(outcome, "value") ? outcome.value : Option.none(), Option.isOption));
111
+ return Effect.succeed(Option.getOrUndefined(value));
112
+ })) });
113
+ /**
114
+ * The machine enters the story **stepped purely**: from this snapshot (its initial state and
115
+ * context when omitted, for `input`), every later step is XState's pure `transition`. Nothing
116
+ * runs: `asked` reads the commands a transition would spawn, and `done`/`failed` feed it their
117
+ * results. Works in a hostless story; in a hosted one the snapshot can be computed from what the
118
+ * sources show (`(read) => snapshot`), and the data steps around it run as usual.
119
+ */
120
+ const given = (machine, snapshot = {}, options = {}) => {
121
+ const name = options.name ?? machine.id;
122
+ const label = `given ${name} stepped purely`;
123
+ return staged(label, async (stage) => {
124
+ const from = await resolved(snapshot, stage, label);
125
+ const [initial] = initialTransition(machine, from.input);
126
+ const start = Option.match(Option.fromUndefinedOr(from.state), {
127
+ onNone: () => initial,
128
+ onSome: (value) => machine.resolveState({
129
+ value,
130
+ context: from.context ?? initial.context
131
+ })
132
+ });
133
+ enter(stage, {
134
+ mode: "stepped",
135
+ name,
136
+ machine,
137
+ snapshot: start,
138
+ asked: [],
139
+ invoked: []
140
+ });
141
+ });
142
+ };
143
+ /**
144
+ * The machine enters the story **running**: started with `createEffectActor` against the story's
145
+ * client (of the step's scope, so `as(scope, Machine.start(...))` runs it on that client). The
146
+ * commands it invokes through `invoke(command)` run there and are recorded; their real outcomes
147
+ * arrive by themselves, and `Story.settled`/`Story.rejected` assert them. Stopped when the story
148
+ * ends. Needs a hosted story.
149
+ */
150
+ const start = (machine, options = {}) => {
151
+ const name = options.name ?? machine.id;
152
+ const label = `start ${name} running`;
153
+ return staged(label, async (stage) => {
154
+ const world = stage.hosted(label);
155
+ await world.connect();
156
+ const scope = Effect.runSync(Scope.make());
157
+ let entered = Option.none();
158
+ const current = () => Option.getOrThrowWith(entered, () => /* @__PURE__ */ new Error(`${name} invoked a command while starting`));
159
+ const create = createEffectActor(machine, { input: options.input });
160
+ const actor = Effect.runSync(create.pipe(Effect.provideService(Runner$1, runnerOf(world, current)), Effect.provideService(Scope.Scope, scope)));
161
+ const running = {
162
+ mode: "running",
163
+ name,
164
+ machine,
165
+ actor,
166
+ scope: world.scope,
167
+ since: world.next()
168
+ };
169
+ entered = Option.some(running);
170
+ enter(stage, running);
171
+ world.releases.push(() => {
172
+ actor.stop();
173
+ Effect.runFork(Scope.close(scope, Exit.void));
174
+ });
175
+ await world.settle(false);
176
+ });
177
+ };
178
+ /**
179
+ * The machine receives an event (or one computed from what the sources show: `(read) => event`).
180
+ * Stepped: its next snapshot and the commands it would ask for; nothing runs. Running: sent to
181
+ * the actor, which reacts and starts the commands it asks for on the story's client; their replies
182
+ * wait, as after a data `when`, until a settling step.
183
+ */
184
+ const when = (event, options = {}) => {
185
+ const label = Option.match(Option.liftPredicate(event, (value) => !Predicate.isFunction(value)), {
186
+ onNone: () => `${prefix(options)}send an event from what is shown`,
187
+ onSome: (given) => `${prefix(options)}send ${given.type}`
188
+ });
189
+ return staged(label, async (stage) => {
190
+ const machine = find(stage, options);
191
+ const sent = await resolved(event, stage, label);
192
+ if (machine.mode === "stepped") return store(stage, stepped(machine, sent));
193
+ const world = stage.hosted(label);
194
+ machine.since = world.next();
195
+ machine.actor.send(sent);
196
+ await world.settle(false);
197
+ });
198
+ };
199
+ /** The machine is in this state (`snapshot.matches(state)`), with these context fields. */
200
+ const then = (expected, options = {}) => {
201
+ const label = `${prefix(options)}machine is ${json(expected.state)}`;
202
+ return staged(label, async (stage) => {
203
+ const machine = find(stage, options);
204
+ const snapshot = snapshotOf(machine);
205
+ if (snapshot.matches(expected.state) && partial(expected.context ?? {}, snapshot.context)) return;
206
+ throw new Mismatch(`${where(machine)} is not in the expected state`, [
207
+ `expected ${json(expected.state)} ${json(expected.context ?? {})}`,
208
+ `observed ${describe(snapshot)}`,
209
+ `asked since its last event: ${listed(machine, askedOf(stage, machine, label))}`
210
+ ]);
211
+ });
212
+ };
213
+ /**
214
+ * The machine asked for this command (with input fields like these) since its last event.
215
+ * Stepped: the spawn actions of `invoke(command)` logic its last transition returned. Running:
216
+ * the commands the story's `Runner` ran for it.
217
+ */
218
+ const asked = (command, input, options = {}) => {
219
+ const label = `${prefix(options)}asked ${Option.match(Option.fromUndefinedOr(input), {
220
+ onNone: () => "a command",
221
+ onSome: (fields) => json(fields)
222
+ })}`;
223
+ return staged(label, async (stage) => {
224
+ const machine = find(stage, options);
225
+ const all = askedOf(stage, machine, label);
226
+ if (all.some((each) => each.command === command && (input === void 0 || partial(input, each.input)))) return;
227
+ throw new Mismatch(`${where(machine)} did not ask for ${nameOf(machine.machine, command)}${input ? " with that input" : ""}`, [
228
+ `expected ${nameOf(machine.machine, command)} ${input ? json(input) : "(any input)"}`,
229
+ `observed ${listed(machine, all)}`,
230
+ `machine ${where(machine)} is ${describe(snapshotOf(machine))}`
231
+ ]);
232
+ });
233
+ };
234
+ /** The machine asked for no command since its last event. */
235
+ const askedNothing = (options = {}) => {
236
+ const label = `${prefix(options)}asked nothing`;
237
+ return staged(label, async (stage) => {
238
+ const machine = find(stage, options);
239
+ if (askedOf(stage, machine, label).length === 0) return;
240
+ throw new Mismatch(`${where(machine)} asked for commands`, context(stage, machine, label));
241
+ });
242
+ };
243
+ /** A stepped machine; a running one is a clear error (its commands settle by themselves). */
244
+ const steppedOnly = (machine, step) => {
245
+ if (machine.mode === "stepped") return machine;
246
+ throw new Mismatch(`${step} feeds a result to a machine stepped purely; ${machine.name} is running (Machine.start): its commands settle by themselves, so assert their outcome with Story.settled(...) or Story.rejected(...)`);
247
+ };
248
+ const answer = (machine, command, outcome, value) => {
249
+ const spawned = [...machine.invoked].reverse().find((each) => each.command === command);
250
+ if (!spawned) throw new Mismatch(`${where(machine)} never asked for ${nameOf(machine.machine, command)}`, [`asked so far: ${listed(machine, machine.invoked)}`]);
251
+ const event = Option.match(Option.liftPredicate(outcome, (tag) => tag === "done"), {
252
+ onSome: () => ({
253
+ type: `xstate.done.actor.${spawned.id}`,
254
+ output: value,
255
+ actorId: spawned.id
256
+ }),
257
+ onNone: () => ({
258
+ type: `xstate.error.actor.${spawned.id}`,
259
+ error: value,
260
+ actorId: spawned.id
261
+ })
262
+ });
263
+ return stepped(machine, event);
264
+ };
265
+ /**
266
+ * Stepped only: the command the machine asked for last settled with this output (its `Settled`
267
+ * value); the machine takes `xstate.done.actor.*`.
268
+ */
269
+ const done = (command, output, options = {}) => staged(`${prefix(options)}command done`, async (stage) => {
270
+ const machine = steppedOnly(find(stage, options), "Machine.done");
271
+ store(stage, answer(machine, command, "done", output));
272
+ });
273
+ /**
274
+ * Stepped only: the command the machine asked for last failed with this typed error; the machine
275
+ * takes `xstate.error.actor.*`.
276
+ */
277
+ const failed = (command, error, options = {}) => staged(`${prefix(options)}command failed with ${error._tag}`, async (stage) => {
278
+ const machine = steppedOnly(find(stage, options), "Machine.failed");
279
+ store(stage, answer(machine, command, "error", error));
280
+ });
281
+ /**
282
+ * Machine steps, run by the one story runner beside data steps, in any order. A machine enters a
283
+ * story one of two ways, chosen once: `given` (stepped purely, works hostless) or `start` (running
284
+ * against the story's client, needs a host). `when`, `then`, `asked` and `askedNothing` mean the
285
+ * same in both; `done`/`failed` feed results to a stepped machine only. Each takes an optional
286
+ * `{ machine }` naming the machine (default: the one introduced last); `given`/`start` take
287
+ * `{ name }` (default: the machine's `id`).
288
+ */
289
+ const Machine = {
290
+ given,
291
+ start,
292
+ when,
293
+ then,
294
+ asked,
295
+ askedNothing,
296
+ done,
297
+ failed
298
+ };
299
+ // src/xstate/explore.ts
300
+ const typeOf = (event) => event.type;
301
+ const keyOf = (path) => path.map((event) => JSON.stringify(event)).join(" ");
302
+ /**
303
+ * The paths to run: XState's `getShortestPaths` and `getSimplePaths` (`xstate/graph`) over the
304
+ * model (which must be finite: bound it with a counter in its context), without the initial step, deduplicated, without those that a longer path to run
305
+ * contains as a prefix (every step of a path is checked, so its prefixes are), at most
306
+ * `maxLength` events, ordered by length then by their events.
307
+ */
308
+ const pathsOf = (model, events, maxLength, limit = 1e4) => {
309
+ const options = {
310
+ events: [...events],
311
+ limit
312
+ };
313
+ const found = [...getShortestPaths(model, options), ...getSimplePaths(model, options)].flatMap((path) => {
314
+ const happened = path.steps.flatMap((each) => {
315
+ if (/^@?xstate\./.test(each.event.type)) return [];
316
+ return [each.event];
317
+ });
318
+ if (happened.length === 0 || happened.length > maxLength) return [];
319
+ return [happened];
320
+ });
321
+ const unique = new Map(found.map((path) => [keyOf(path), path]));
322
+ const keys = [...unique.keys()];
323
+ return [...unique.entries()].flatMap(([key, path]) => {
324
+ if (keys.some((other) => other !== key && other.startsWith(`${key} `))) return [];
325
+ return [path];
326
+ }).sort((a, b) => a.length - b.length || keyOf(a).localeCompare(keyOf(b)));
327
+ };
328
+ /** The steps of a path, and which event each step belongs to (`-1` before or after them). */
329
+ const stepsOf = (exploration, path) => {
330
+ const owners = [];
331
+ const list = [];
332
+ const add = (steps, owner) => {
333
+ for (const each of flatten([steps ?? []])) {
334
+ list.push(each);
335
+ owners.push(owner);
336
+ }
337
+ };
338
+ add(exploration.before, -1);
339
+ path.forEach((event, index) => add(exploration.steps(event, index), index));
340
+ add(exploration.after, path.length);
341
+ return {
342
+ list,
343
+ owners
344
+ };
345
+ };
346
+ /** Runs one path; the failure, if any, with the events up to the one whose step failed. */
347
+ const attempt = async (exploration, path) => {
348
+ const { list, owners } = stepsOf(exploration, path);
349
+ try {
350
+ await exploration.story.with({ invariants: exploration.invariants })(list);
351
+ return Option.none();
352
+ } catch (error) {
353
+ if (!(error instanceof StoryFailure)) throw error;
354
+ const owner = owners[error.step - 1] ?? path.length;
355
+ return Option.some({
356
+ failure: error,
357
+ prefix: path.slice(0, Math.min(owner + 1, path.length))
358
+ });
359
+ }
360
+ };
361
+ /** Drops events from a failing path while it still fails; the shortest failing path found. */
362
+ const shrunk = async (exploration, failing) => {
363
+ let best = failing;
364
+ let changed = true;
365
+ while (changed) {
366
+ changed = false;
367
+ for (const index of best.prefix.keys()) {
368
+ const shorter = best.prefix.filter((_, position) => position !== index);
369
+ if (shorter.length === 0) continue;
370
+ const result = await attempt(exploration, shorter);
371
+ if (Option.isSome(result)) {
372
+ best = result.value;
373
+ changed = true;
374
+ break;
375
+ }
376
+ }
377
+ }
378
+ return best;
379
+ };
380
+ /**
381
+ * Model-based stories: enumerates the model's paths (XState's graph utilities) and runs each as a
382
+ * story (`before`, each event's steps, `after`), checking the invariants after every step. Fails
383
+ * with the shortest failing path it found (shrunk), as a readable event sequence, and the story's
384
+ * own report. Deterministic: the same model and options run the same paths in the same order.
385
+ */
386
+ const explore = async (exploration) => {
387
+ const paths = pathsOf(exploration.model, exploration.events, exploration.maxLength ?? 4, exploration.limit).slice(0, exploration.maxPaths ?? 200);
388
+ let steps = 0;
389
+ for (const [index, path] of paths.entries()) {
390
+ const result = await attempt(exploration, path);
391
+ steps += stepsOf(exploration, path).list.length;
392
+ if (Option.isNone(result)) continue;
393
+ const found = exploration.shrink === false ? result.value : await shrunk(exploration, result.value);
394
+ throw new Error([
395
+ `A generated story failed (path ${index + 1} of ${paths.length}): ${found.prefix.map(typeOf).join(" → ")}`,
396
+ ` events: ${found.prefix.map((event) => JSON.stringify(event)).join(", ")}`,
397
+ found.failure.message
398
+ ].join("\n"), { cause: found.failure });
399
+ }
400
+ return {
401
+ paths: paths.length,
402
+ steps
403
+ };
404
+ };
405
+ export { Machine, Runner, commandOf, explore, invoke, mark, pathsOf };
package/package.json CHANGED
@@ -1,6 +1,96 @@
1
1
  {
2
2
  "name": "@highalch/story",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Stories for HighAlch data and the XState machines over it: given, when, then, with screenshots painted without a browser.",
5
+ "keywords": [
6
+ "alchemy",
7
+ "effect",
8
+ "tanstack-db",
9
+ "testing",
10
+ "xstate"
11
+ ],
12
+ "homepage": "https://github.com/maxscn/highalch/tree/main/packages/story#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/maxscn/highalch/issues"
15
+ },
16
+ "license": "MIT",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/maxscn/highalch.git",
20
+ "directory": "packages/story"
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "type": "module",
26
+ "sideEffects": false,
27
+ "types": "./dist/index.d.mts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.mts",
31
+ "default": "./dist/index.mjs"
32
+ },
33
+ "./xstate": {
34
+ "types": "./dist/xstate.d.mts",
35
+ "default": "./dist/xstate.mjs"
36
+ },
37
+ "./screen": {
38
+ "types": "./dist/screen.d.mts",
39
+ "default": "./dist/screen.mjs"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "devDependencies": {
47
+ "@alchemy.run/domain": "2.0.0-beta.87",
48
+ "@highalch/db": "0.0.1",
49
+ "@tanstack/db": "1.0.0-rc.1.5",
50
+ "@tanstack/react-db": "1.0.0-rc.1.5",
51
+ "@types/node": "^24",
52
+ "@types/react": "19.2.17",
53
+ "@types/react-dom": "19.2.3",
54
+ "@xstate/effect": "0.1.0-alpha.2",
55
+ "effect": "4.1.4",
56
+ "happy-dom": "20.11.1",
57
+ "react": "19.2.7",
58
+ "react-dom": "19.2.7",
59
+ "takumi-js": "2.14.0",
60
+ "typescript": "^7.0.2",
61
+ "vite-plus": "1.5.1",
62
+ "xstate": "6.0.0-alpha.60"
63
+ },
64
+ "peerDependencies": {
65
+ "@alchemy.run/domain": "2.0.0-beta.87",
66
+ "@highalch/db": "^0.0.1",
67
+ "@tanstack/db": "1.0.0-rc.1.5",
68
+ "@xstate/effect": "0.1.0-alpha.2",
69
+ "effect": "^4.1.4",
70
+ "happy-dom": "^20.11.1",
71
+ "react": "^19.2.7",
72
+ "react-dom": "^19.2.7",
73
+ "takumi-js": "^2.14.0",
74
+ "xstate": "6.0.0-alpha.60"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@xstate/effect": {
78
+ "optional": true
79
+ },
80
+ "happy-dom": {
81
+ "optional": true
82
+ },
83
+ "react-dom": {
84
+ "optional": true
85
+ },
86
+ "takumi-js": {
87
+ "optional": true
88
+ },
89
+ "xstate": {
90
+ "optional": true
91
+ }
92
+ },
93
+ "scripts": {
94
+ "build": "vp pack"
95
+ }
6
96
  }