@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.
- package/LICENSE +21 -0
- package/README.md +342 -2
- package/dist/index.d.mts +42 -0
- package/dist/index.mjs +321 -0
- package/dist/run-C2SdDPWE.d.mts +75 -0
- package/dist/run-DMO8Dcmq.mjs +131 -0
- package/dist/screen.d.mts +71 -0
- package/dist/screen.mjs +505 -0
- package/dist/steps-CvFOQHum.d.mts +599 -0
- package/dist/steps-DZBFsrQr.mjs +950 -0
- package/dist/xstate.d.mts +145 -0
- package/dist/xstate.mjs +405 -0
- package/package.json +93 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { n as make, t as StoryFailure } from "./run-DMO8Dcmq.mjs";
|
|
2
|
+
import { C as shows, D as when, E as step, F as Wire, I as transport, L as Mismatch, N as plain, O as Observed, P as retryTransport, S as settled, T as state, _ as release, a as drop, b as resume, c as given, d as idle, f as mute, g as rejected, h as recover, i as check, j as json, k as World, l as historyOf, n as alchemy, o as fail, p as open, r as as, s as flatten, t as advance, u as hold, v as reload, w as staged, x as settle, y as remote } from "./steps-DZBFsrQr.mjs";
|
|
3
|
+
import * as InMemory from "@alchemy.run/domain/InMemory";
|
|
4
|
+
import * as Model from "@alchemy.run/domain/Model";
|
|
5
|
+
import { Cause, Context, Effect, Exit, Layer, ManagedRuntime, Option, Predicate } from "effect";
|
|
6
|
+
import { Live as Live$1, Settled as Settled$1 } from "@highalch/db/internal";
|
|
7
|
+
// src/host.ts
|
|
8
|
+
const isHostable = (model) => Predicate.hasProperty(model, "layer") && Predicate.isFunction(model.layer);
|
|
9
|
+
const servesInProcess = (api) => Predicate.hasProperty(api, "layerClientInProcess");
|
|
10
|
+
/**
|
|
11
|
+
* Hosts an Api's model on alchemy's in-memory platform, as the story runs it: projections and
|
|
12
|
+
* policies run in the background (not alchemy's manual scheduling, since the client runs
|
|
13
|
+
* concurrently), `given` seeds history through the model's stores exactly as alchemy's own `Story`
|
|
14
|
+
* does, and `idle` is the platform's own quiescence.
|
|
15
|
+
*/
|
|
16
|
+
const memory = (options) => async () => {
|
|
17
|
+
const platform = InMemory.make();
|
|
18
|
+
const services = options.services?.() ?? Layer.empty;
|
|
19
|
+
const api = options.api;
|
|
20
|
+
if (!isHostable(api.model) || !servesInProcess(api)) throw new Error(`${api.apiName} cannot be hosted in memory`);
|
|
21
|
+
const handlers = options.layer();
|
|
22
|
+
const provided = services;
|
|
23
|
+
const model = api.model.layer(handlers).pipe(Layer.provide(platform.layer), Layer.provideMerge(provided));
|
|
24
|
+
const hosted = ManagedRuntime.make(model);
|
|
25
|
+
const context = await hosted.runPromise(Effect.context());
|
|
26
|
+
const internals = Context.get(context, Model.Internals);
|
|
27
|
+
const runtimes = [];
|
|
28
|
+
const shared = /* @__PURE__ */ new Map();
|
|
29
|
+
const client = (scope) => {
|
|
30
|
+
const id = options.session ? scope : "";
|
|
31
|
+
const known = shared.get(id);
|
|
32
|
+
if (known) return known;
|
|
33
|
+
const made = connect(scope);
|
|
34
|
+
shared.set(id, made);
|
|
35
|
+
return made;
|
|
36
|
+
};
|
|
37
|
+
const connect = async (scope) => {
|
|
38
|
+
const session = options.session?.(scope) ?? Layer.empty;
|
|
39
|
+
const layer = api.layerClientInProcess.pipe(Layer.provide(session), Layer.provide(Layer.succeedContext(context)));
|
|
40
|
+
const runtime = ManagedRuntime.make(layer);
|
|
41
|
+
runtimes.push(runtime);
|
|
42
|
+
const client = Effect.service(api.Client);
|
|
43
|
+
return runtime.runPromise(client);
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
api,
|
|
47
|
+
client,
|
|
48
|
+
idle: () => Effect.runPromise(platform.control.idle),
|
|
49
|
+
seed: async (ref, events) => {
|
|
50
|
+
const store = internals.aggregates.get(ref.aggregate);
|
|
51
|
+
if (!store?.seed) throw new Error(`The platform cannot seed ${ref.aggregate}`);
|
|
52
|
+
const seed = store.seed;
|
|
53
|
+
await hosted.runPromise(Effect.gen(function* () {
|
|
54
|
+
const encoded = yield* Effect.forEach(events, internals.kernel.encodeEvent);
|
|
55
|
+
yield* seed(String(ref.id), encoded);
|
|
56
|
+
}));
|
|
57
|
+
},
|
|
58
|
+
send: async (ref, command, commandId) => {
|
|
59
|
+
const aggregate = internals.commands.get(command._tag);
|
|
60
|
+
if (!aggregate) throw new Error(`No aggregate handles ${command._tag}`);
|
|
61
|
+
const exit = await hosted.runPromiseExit(aggregate.send(ref, command, { commandId }));
|
|
62
|
+
return Exit.match(exit, {
|
|
63
|
+
onSuccess: () => Option.none(),
|
|
64
|
+
onFailure: (cause) => Option.some(Cause.pretty(cause))
|
|
65
|
+
});
|
|
66
|
+
},
|
|
67
|
+
service: (key) => hosted.runPromise(Effect.service(key)),
|
|
68
|
+
dispose: async () => {
|
|
69
|
+
for (const runtime of runtimes) await runtime.dispose();
|
|
70
|
+
await hosted.dispose();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
// src/invariants.ts
|
|
75
|
+
/** The `seq`s of the feed entries that carried exactly this row of this entity's key. */
|
|
76
|
+
const seqsOf = (entries, entity, key, shown) => entries.flatMap((entry) => {
|
|
77
|
+
const same = Option.match(entry.row, {
|
|
78
|
+
onNone: () => false,
|
|
79
|
+
onSome: (row) => json(row) === json(shown.row)
|
|
80
|
+
});
|
|
81
|
+
if (entry.entity !== entity || entry.key !== key || !same) return [];
|
|
82
|
+
return [entry.seq];
|
|
83
|
+
});
|
|
84
|
+
/** The observed sources of an entity, with their entity's name. */
|
|
85
|
+
const subsets = (world) => world.observed().flatMap((observed) => Option.match(observed.entity(), {
|
|
86
|
+
onNone: () => [],
|
|
87
|
+
onSome: (entity) => [{
|
|
88
|
+
observed,
|
|
89
|
+
entity: entity.entityName
|
|
90
|
+
}]
|
|
91
|
+
}));
|
|
92
|
+
/** The feed entries of a scope, read once per check. */
|
|
93
|
+
const entriesOf = async (world, scope, cache) => {
|
|
94
|
+
const known = cache.get(scope);
|
|
95
|
+
if (known) return known;
|
|
96
|
+
const read = await world.entries(scope);
|
|
97
|
+
cache.set(scope, read);
|
|
98
|
+
return read;
|
|
99
|
+
};
|
|
100
|
+
const brief = (shown) => `${json(shown.row)}${shown.pending ? " (pending)" : ""}`;
|
|
101
|
+
/** Whether the world is at rest now: settled since the last change, every run ended, feeds live. */
|
|
102
|
+
const atRest = (world) => world.settled === world.tick && world.runs.every((run) => !Predicate.isTagged(run.outcome, "Pending")) && world.all().every((client) => !client.wire.dropped);
|
|
103
|
+
/**
|
|
104
|
+
* No flicker back: once a source showed a row of the feed at `seq`, it never shows an older one
|
|
105
|
+
* for that key (rows the feed never carried, such as pending ones, are not judged). And once a
|
|
106
|
+
* command's optimistic row showed, the source never shows a row older than the command's own
|
|
107
|
+
* change after it (no "new → old → new" when the command settles).
|
|
108
|
+
*/
|
|
109
|
+
const noFlickerBack = {
|
|
110
|
+
name: "no flicker back",
|
|
111
|
+
check: async (world) => {
|
|
112
|
+
const cache = /* @__PURE__ */ new Map();
|
|
113
|
+
const violations = [];
|
|
114
|
+
for (const { observed, entity } of subsets(world)) {
|
|
115
|
+
const entries = await entriesOf(world, observed.scope, cache);
|
|
116
|
+
const keys = new Set(observed.history.map((each) => each.key));
|
|
117
|
+
for (const key of keys) {
|
|
118
|
+
let last = 0;
|
|
119
|
+
for (const each of observed.history) {
|
|
120
|
+
if (each.key !== key || Option.isNone(each.shown) || each.shown.value.pending) continue;
|
|
121
|
+
const seqs = seqsOf(entries, entity, key, each.shown.value);
|
|
122
|
+
if (seqs.length === 0) continue;
|
|
123
|
+
const next = seqs.find((seq) => seq >= last);
|
|
124
|
+
if (next === void 0) {
|
|
125
|
+
violations.push(`${observed.label} showed ${key} as ${brief(each.shown.value)} (seq ${Math.max(...seqs)}) after a newer row (seq ${last}), in step ${each.step}`);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
last = next;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
for (const run of world.runs) {
|
|
132
|
+
const committed = Predicate.isTagged(run.outcome, "Committed");
|
|
133
|
+
if (run.scope !== observed.scope || !committed || run.key === "") continue;
|
|
134
|
+
const caused = entries.flatMap((entry) => {
|
|
135
|
+
const own = entry.commandId === run.transaction.id || entry.commandId.startsWith(`${run.transaction.id}:`);
|
|
136
|
+
if (entry.key !== run.key || entry.entity !== entity || !own) return [];
|
|
137
|
+
return [entry.seq];
|
|
138
|
+
});
|
|
139
|
+
if (caused.length === 0) continue;
|
|
140
|
+
const own = Math.max(...caused);
|
|
141
|
+
const anchor = observed.history.findIndex((each) => each.tick > run.tick && each.key === run.key && Option.isSome(each.shown) && each.shown.value.pending);
|
|
142
|
+
if (anchor < 0) continue;
|
|
143
|
+
for (const each of observed.history.slice(anchor)) {
|
|
144
|
+
if (each.key !== run.key || Option.isNone(each.shown) || each.shown.value.pending) continue;
|
|
145
|
+
const seqs = seqsOf(entries, entity, run.key, each.shown.value);
|
|
146
|
+
if (seqs.some((seq) => seq >= own)) continue;
|
|
147
|
+
violations.push(`${observed.label} showed ${run.key} as ${brief(each.shown.value)} (${seqs.length > 0 ? `seq ${Math.max(...seqs)}` : "a row the feed never carried"}) after ${run.label} showed its change, which the feed carried at seq ${own} (step ${each.step})`);
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return violations;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
/** Nothing pending at rest: every command ended and every feed is live, so no row is pending. */
|
|
156
|
+
const nothingPending = {
|
|
157
|
+
name: "nothing pending at rest",
|
|
158
|
+
check: async (world, moment) => {
|
|
159
|
+
if (!atRest(world) && !moment.final) return [];
|
|
160
|
+
return world.observed().flatMap((observed) => [...observed.rows].flatMap(([key, shown]) => {
|
|
161
|
+
if (!shown.pending) return [];
|
|
162
|
+
return [`${observed.label} still shows ${key} pending: ${brief(shown)}`];
|
|
163
|
+
}));
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
/** At rest, every ready subset of an entity in one client that shows a row shows the same row. */
|
|
167
|
+
const subsetsAgree = {
|
|
168
|
+
name: "subsets agree",
|
|
169
|
+
check: async (world, moment) => {
|
|
170
|
+
if (!atRest(world) && !moment.final) return [];
|
|
171
|
+
const groups = /* @__PURE__ */ new Map();
|
|
172
|
+
for (const { observed, entity } of subsets(world)) {
|
|
173
|
+
if (!Predicate.isTagged(observed.state(), "Ready")) continue;
|
|
174
|
+
const group = `${observed.scope}/${entity}`;
|
|
175
|
+
const members = groups.get(group) ?? [];
|
|
176
|
+
members.push(observed);
|
|
177
|
+
groups.set(group, members);
|
|
178
|
+
}
|
|
179
|
+
const violations = [];
|
|
180
|
+
for (const members of groups.values()) for (const [index, first] of members.entries()) for (const second of members.slice(index + 1)) for (const [key, shown] of first.rows) {
|
|
181
|
+
const other = second.rows.get(key);
|
|
182
|
+
if (other && json(other.row) !== json(shown.row)) violations.push(`${first.label} shows ${key} as ${brief(shown)}, ${second.label} as ${brief(other)}`);
|
|
183
|
+
}
|
|
184
|
+
return violations;
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
const judged = /* @__PURE__ */ new WeakMap();
|
|
188
|
+
/**
|
|
189
|
+
* A rejected command leaves the value it found: right after its rejection, each source that showed
|
|
190
|
+
* its row shows what it showed before the command (or a newer row of the feed), not pending.
|
|
191
|
+
*/
|
|
192
|
+
const rejectedRestores = {
|
|
193
|
+
name: "a rejection restores the row",
|
|
194
|
+
check: async (world) => {
|
|
195
|
+
const done = judged.get(world) ?? /* @__PURE__ */ new Set();
|
|
196
|
+
const cache = /* @__PURE__ */ new Map();
|
|
197
|
+
const violations = [];
|
|
198
|
+
judged.set(world, done);
|
|
199
|
+
for (const run of world.runs) {
|
|
200
|
+
if (!Predicate.isTagged(run.outcome, "Rejected") || done.has(run) || run.key === "") continue;
|
|
201
|
+
done.add(run);
|
|
202
|
+
if (world.runs.some((other) => other !== run && other.key === run.key && other.scope === run.scope && Predicate.isTagged(other.outcome, "Pending"))) continue;
|
|
203
|
+
for (const { observed, entity } of subsets(world)) {
|
|
204
|
+
if (observed.scope !== run.scope) continue;
|
|
205
|
+
const before = Option.fromUndefinedOr(run.before.get(observed.id)?.get(run.key));
|
|
206
|
+
const now = Option.fromUndefinedOr(observed.rows.get(run.key));
|
|
207
|
+
if (Option.isNone(before) && Option.isNone(now)) continue;
|
|
208
|
+
if (Option.isSome(now) && now.value.pending) {
|
|
209
|
+
violations.push(`${observed.label} still shows ${run.key} pending after ${run.label} was rejected`);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (Option.isSome(before) && Option.isSome(now)) {
|
|
213
|
+
if (json(before.value.row) === json(now.value.row)) continue;
|
|
214
|
+
const entries = await entriesOf(world, observed.scope, cache);
|
|
215
|
+
const was = Math.max(0, ...seqsOf(entries, entity, run.key, before.value));
|
|
216
|
+
if (seqsOf(entries, entity, run.key, now.value).some((seq) => seq >= was)) continue;
|
|
217
|
+
}
|
|
218
|
+
violations.push(`after ${run.label} was rejected, ${observed.label} shows ${run.key} as ${Option.match(now, {
|
|
219
|
+
onNone: () => "nothing",
|
|
220
|
+
onSome: brief
|
|
221
|
+
})}; before it, ${Option.match(before, {
|
|
222
|
+
onNone: () => "nothing",
|
|
223
|
+
onSome: brief
|
|
224
|
+
})}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return violations;
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
/** The default invariants of a collection. */
|
|
231
|
+
const invariants = [
|
|
232
|
+
noFlickerBack,
|
|
233
|
+
nothingPending,
|
|
234
|
+
subsetsAgree,
|
|
235
|
+
rejectedRestores
|
|
236
|
+
];
|
|
237
|
+
// src/view.ts
|
|
238
|
+
/**
|
|
239
|
+
* The constructors of every state `match` gives a live query result: `Loading()`,
|
|
240
|
+
* `Retrying({ error, attempt, data })`, `Ready({ data, feed, retry })`, `Missing()`,
|
|
241
|
+
* `Disabled()`. A presentational component that takes a state renders each branch from them.
|
|
242
|
+
*/
|
|
243
|
+
const Live = Live$1;
|
|
244
|
+
/** The constructors of a command's settled value: `Committed({ reply, stream, version })`, `Unconfirmed(...)`. */
|
|
245
|
+
const Settled = Settled$1;
|
|
246
|
+
/** Whether a view state is one of `match`'s own states (an error is never tagged like one). */
|
|
247
|
+
const is = (tag) => (state) => Predicate.isTagged(state, tag);
|
|
248
|
+
const problem = (cause, attempts) => {
|
|
249
|
+
const info = {
|
|
250
|
+
name: cause._tag,
|
|
251
|
+
message: cause._tag,
|
|
252
|
+
at: 0,
|
|
253
|
+
cause
|
|
254
|
+
};
|
|
255
|
+
return {
|
|
256
|
+
...info,
|
|
257
|
+
errors: Array.from({ length: attempts }, () => info)
|
|
258
|
+
};
|
|
259
|
+
};
|
|
260
|
+
const nodeOf = (id, status, failureReason, error) => ({
|
|
261
|
+
alias: "root",
|
|
262
|
+
collectionId: id,
|
|
263
|
+
kind: "source",
|
|
264
|
+
status,
|
|
265
|
+
hasErrors: failureReason !== null || error !== null,
|
|
266
|
+
failureReason,
|
|
267
|
+
error,
|
|
268
|
+
reloading: false,
|
|
269
|
+
sources: []
|
|
270
|
+
});
|
|
271
|
+
/** `view(customers.list(input), state)`: a live query result over that source in `state`. */
|
|
272
|
+
const view = (source, state) => {
|
|
273
|
+
let retried = 0;
|
|
274
|
+
const collection = { reload: async () => {
|
|
275
|
+
retried += 1;
|
|
276
|
+
} };
|
|
277
|
+
const id = source.id ?? "view";
|
|
278
|
+
const base = {
|
|
279
|
+
isEnabled: true,
|
|
280
|
+
isCrashed: false,
|
|
281
|
+
collection,
|
|
282
|
+
retried: () => retried
|
|
283
|
+
};
|
|
284
|
+
if (is("Loading")(state)) return {
|
|
285
|
+
...base,
|
|
286
|
+
data: [],
|
|
287
|
+
status: "loading",
|
|
288
|
+
isReady: false,
|
|
289
|
+
isLoadingError: false,
|
|
290
|
+
health: nodeOf(id, "loading", null, null)
|
|
291
|
+
};
|
|
292
|
+
if (is("Retrying")(state)) return {
|
|
293
|
+
...base,
|
|
294
|
+
data: [...state.data],
|
|
295
|
+
status: "ready",
|
|
296
|
+
isReady: true,
|
|
297
|
+
isLoadingError: false,
|
|
298
|
+
health: nodeOf(id, "ready", problem(state.error, state.attempt - 1), null)
|
|
299
|
+
};
|
|
300
|
+
if (is("Ready")(state)) {
|
|
301
|
+
const feed = Option.map(state.feed, (error) => problem(error, 1));
|
|
302
|
+
return {
|
|
303
|
+
...base,
|
|
304
|
+
data: [...state.data],
|
|
305
|
+
status: "ready",
|
|
306
|
+
isReady: true,
|
|
307
|
+
isLoadingError: false,
|
|
308
|
+
health: nodeOf(id, "ready", null, Option.getOrNull(feed))
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const error = state;
|
|
312
|
+
return {
|
|
313
|
+
...base,
|
|
314
|
+
data: [],
|
|
315
|
+
status: "error",
|
|
316
|
+
isReady: false,
|
|
317
|
+
isLoadingError: true,
|
|
318
|
+
health: nodeOf(id, "error", null, problem(error, 1))
|
|
319
|
+
};
|
|
320
|
+
};
|
|
321
|
+
export { Live, Mismatch, Observed, Settled, StoryFailure, Wire, World, advance, alchemy, as, check, drop, fail, flatten, given, historyOf, hold, idle, invariants, json, make, memory, mute, noFlickerBack, nothingPending, open, plain, recover, rejected, rejectedRestores, release, reload, remote, resume, retryTransport, settle, settled, shows, staged, state, step, subsetsAgree, transport, view, when };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { $ as Hosting, B as Options, G as World, s as Steps } from "./steps-CvFOQHum.mjs";
|
|
2
|
+
import { Option } from "effect";
|
|
3
|
+
import * as Domain from "@alchemy.run/domain";
|
|
4
|
+
/** When an invariant is checked: after a step, or at the end of the story (`final`). */
|
|
5
|
+
type Moment = {
|
|
6
|
+
readonly final: boolean;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* A property every state of a story must have. `check` answers the violations it found (empty
|
|
10
|
+
* when it holds); stories run with invariants check them after every step and at the end.
|
|
11
|
+
*/
|
|
12
|
+
type Invariant = {
|
|
13
|
+
readonly name: string;
|
|
14
|
+
readonly check: (world: World, moment: Moment) => Promise<ReadonlyArray<string>>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* No flicker back: once a source showed a row of the feed at `seq`, it never shows an older one
|
|
18
|
+
* for that key (rows the feed never carried, such as pending ones, are not judged). And once a
|
|
19
|
+
* command's optimistic row showed, the source never shows a row older than the command's own
|
|
20
|
+
* change after it (no "new → old → new" when the command settles).
|
|
21
|
+
*/
|
|
22
|
+
declare const noFlickerBack: Invariant;
|
|
23
|
+
/** Nothing pending at rest: every command ended and every feed is live, so no row is pending. */
|
|
24
|
+
declare const nothingPending: Invariant;
|
|
25
|
+
/** At rest, every ready subset of an entity in one client that shows a row shows the same row. */
|
|
26
|
+
declare const subsetsAgree: Invariant;
|
|
27
|
+
/**
|
|
28
|
+
* A rejected command leaves the value it found: right after its rejection, each source that showed
|
|
29
|
+
* its row shows what it showed before the command (or a newer row of the feed), not pending.
|
|
30
|
+
*/
|
|
31
|
+
declare const rejectedRestores: Invariant;
|
|
32
|
+
/** The default invariants of a collection. */
|
|
33
|
+
declare const invariants: ReadonlyArray<Invariant>;
|
|
34
|
+
/** How far a story got with one step. */
|
|
35
|
+
type StepReport = {
|
|
36
|
+
readonly step: number;
|
|
37
|
+
readonly label: string;
|
|
38
|
+
readonly status: "passed" | "failed" | "not-run";
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* A failed story. `message` names the failed step and why (expected vs observed, the row
|
|
42
|
+
* histories), then lists every step: ✓ passed, ✗ failed, blank not run.
|
|
43
|
+
*/
|
|
44
|
+
declare class StoryFailure extends Error {
|
|
45
|
+
readonly step: number;
|
|
46
|
+
readonly reason: string;
|
|
47
|
+
readonly detail: ReadonlyArray<string>;
|
|
48
|
+
readonly steps: ReadonlyArray<StepReport>;
|
|
49
|
+
readonly name = "StoryFailure";
|
|
50
|
+
constructor(step: number, reason: string, detail: ReadonlyArray<string>, steps: ReadonlyArray<StepReport>);
|
|
51
|
+
}
|
|
52
|
+
/** The options of a story: its clients' settings, its first scope, and invariants to keep. */
|
|
53
|
+
type StoryOptions = Options & {
|
|
54
|
+
/** The scope of the story's first client; `as(scope, ...)` steps open others. */
|
|
55
|
+
readonly scope: string;
|
|
56
|
+
/** Checked after every step and at the end. */
|
|
57
|
+
readonly invariants?: ReadonlyArray<Invariant>;
|
|
58
|
+
/** The story's name: what kinds of steps that write files per story (a screen) name them by. */
|
|
59
|
+
readonly name?: string;
|
|
60
|
+
};
|
|
61
|
+
/** A story runner: call it with steps inside your test runner's test; it returns a promise. */
|
|
62
|
+
type Story = ((...steps: ReadonlyArray<Steps>) => Promise<void>) & {
|
|
63
|
+
/** The same runner with other options (invariants, clock, settings); a hosted story's only. */
|
|
64
|
+
readonly with: (options: Partial<StoryOptions>) => Story;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* The story runner. Hosted, `make(memory({ api, layer }), { scope: "acc-1" })`: each call hosts a
|
|
68
|
+
* fresh Domain and fresh clients and disposes them when it ends; data steps and machine steps
|
|
69
|
+
* (`@highalch/story/xstate`) run on it in any order. Hostless, `make()`: no Domain, no
|
|
70
|
+
* client, nothing started, for machines stepped purely; a data step fails at once, naming itself.
|
|
71
|
+
* Call it inside a test: `await story(given(...), shows(...), when(...), settled("Committed"))`.
|
|
72
|
+
*/
|
|
73
|
+
declare function make(): Story;
|
|
74
|
+
declare function make<A extends Domain.Api.Any>(hosting: Hosting<A>, options: StoryOptions): Story;
|
|
75
|
+
export { make as a, invariants as c, rejectedRestores as d, subsetsAgree as f, StoryOptions as i, noFlickerBack as l, Story as n, Invariant as o, StoryFailure as r, Moment as s, StepReport as t, nothingPending as u };
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { A as describeDefect, L as Mismatch, R as Stage, k as World, s as flatten } from "./steps-DZBFsrQr.mjs";
|
|
2
|
+
import { Option } from "effect";
|
|
3
|
+
// src/run.ts
|
|
4
|
+
/**
|
|
5
|
+
* A failed story. `message` names the failed step and why (expected vs observed, the row
|
|
6
|
+
* histories), then lists every step: ✓ passed, ✗ failed, blank not run.
|
|
7
|
+
*/
|
|
8
|
+
var StoryFailure = class extends Error {
|
|
9
|
+
step;
|
|
10
|
+
reason;
|
|
11
|
+
detail;
|
|
12
|
+
steps;
|
|
13
|
+
name = "StoryFailure";
|
|
14
|
+
constructor(step, reason, detail, steps) {
|
|
15
|
+
super([
|
|
16
|
+
reason,
|
|
17
|
+
...detail.map((line) => ` ${line}`),
|
|
18
|
+
" steps:",
|
|
19
|
+
...steps.map((each) => ` ${{
|
|
20
|
+
passed: "✓",
|
|
21
|
+
failed: "✗",
|
|
22
|
+
"not-run": " "
|
|
23
|
+
}[each.status]} ${each.step}. ${each.label}`)
|
|
24
|
+
].join("\n"));
|
|
25
|
+
this.step = step;
|
|
26
|
+
this.reason = reason;
|
|
27
|
+
this.detail = detail;
|
|
28
|
+
this.steps = steps;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
const reportOf = (steps, failed) => steps.map((each, index) => {
|
|
32
|
+
const number = index + 1;
|
|
33
|
+
let status = "not-run";
|
|
34
|
+
if (number < failed) status = "passed";
|
|
35
|
+
else if (number === failed) status = "failed";
|
|
36
|
+
return {
|
|
37
|
+
step: number,
|
|
38
|
+
label: each.label,
|
|
39
|
+
status
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
const why = (error) => {
|
|
43
|
+
if (error instanceof Mismatch) return {
|
|
44
|
+
reason: error.reason,
|
|
45
|
+
detail: error.detail
|
|
46
|
+
};
|
|
47
|
+
if (error instanceof Error) return {
|
|
48
|
+
reason: error.message,
|
|
49
|
+
detail: []
|
|
50
|
+
};
|
|
51
|
+
return {
|
|
52
|
+
reason: describeDefect(error),
|
|
53
|
+
detail: []
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
/** Checks every invariant; the violations as a failure of `number`. */
|
|
57
|
+
const keep = async (world, invariants, steps, number, final) => {
|
|
58
|
+
for (const invariant of invariants) {
|
|
59
|
+
const violations = await invariant.check(world, { final });
|
|
60
|
+
if (violations.length > 0) throw new StoryFailure(number, `${final ? "At the end of the story" : `After step ${number} (${steps[number - 1]?.label})`}, "${invariant.name}" does not hold`, violations, reportOf(steps, final ? steps.length + 1 : number));
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Runs steps on a fresh stage (with a fresh host and world when the story has a host); throws a
|
|
65
|
+
* `StoryFailure`; always disposes.
|
|
66
|
+
*/
|
|
67
|
+
const play = async (setup, steps) => {
|
|
68
|
+
const world = await Option.match(setup, {
|
|
69
|
+
onNone: async () => Option.none(),
|
|
70
|
+
onSome: async ({ hosting, options }) => Option.some(new World(await hosting(), options.scope, options))
|
|
71
|
+
});
|
|
72
|
+
const stage = new Stage(world, Option.flatMap(setup, ({ options }) => Option.fromUndefinedOr(options.name)));
|
|
73
|
+
const invariants = Option.match(setup, {
|
|
74
|
+
onNone: () => [],
|
|
75
|
+
onSome: ({ options }) => options.invariants ?? []
|
|
76
|
+
});
|
|
77
|
+
const kept = async (number, final) => {
|
|
78
|
+
if (Option.isSome(world)) await keep(world.value, invariants, steps, number, final);
|
|
79
|
+
};
|
|
80
|
+
try {
|
|
81
|
+
for (const [index, each] of steps.entries()) {
|
|
82
|
+
const number = index + 1;
|
|
83
|
+
stage.step = number;
|
|
84
|
+
if (Option.isSome(world)) world.value.step = number;
|
|
85
|
+
try {
|
|
86
|
+
await each.run(stage);
|
|
87
|
+
await stage.passed({
|
|
88
|
+
step: number,
|
|
89
|
+
label: each.label
|
|
90
|
+
});
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error instanceof StoryFailure) throw error;
|
|
93
|
+
const { reason, detail } = why(error);
|
|
94
|
+
throw new StoryFailure(number, `Step ${number} (${each.label}) failed: ${reason}`, detail, reportOf(steps, number));
|
|
95
|
+
}
|
|
96
|
+
await kept(number, false);
|
|
97
|
+
}
|
|
98
|
+
await kept(steps.length, true);
|
|
99
|
+
const ended = await stage.close();
|
|
100
|
+
if (Option.isSome(ended)) throw ended.value;
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await stage.close();
|
|
103
|
+
throw error;
|
|
104
|
+
} finally {
|
|
105
|
+
if (Option.isSome(world)) await world.value.dispose();
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const runner = (setup) => {
|
|
109
|
+
const story = (...steps) => play(setup, flatten(steps));
|
|
110
|
+
const more = (options) => Option.match(setup, {
|
|
111
|
+
onNone: () => {
|
|
112
|
+
throw new Error("A hostless story has no clients, clock or invariants to set: Story.make(hosting, options) makes a hosted one");
|
|
113
|
+
},
|
|
114
|
+
onSome: (hosted) => runner(Option.some({
|
|
115
|
+
...hosted,
|
|
116
|
+
options: {
|
|
117
|
+
...hosted.options,
|
|
118
|
+
...options
|
|
119
|
+
}
|
|
120
|
+
}))
|
|
121
|
+
});
|
|
122
|
+
return Object.assign(story, { with: more });
|
|
123
|
+
};
|
|
124
|
+
function make(hosting, options) {
|
|
125
|
+
if (hosting === void 0 || options === void 0) return runner(Option.none());
|
|
126
|
+
return runner(Option.some({
|
|
127
|
+
hosting,
|
|
128
|
+
options
|
|
129
|
+
}));
|
|
130
|
+
}
|
|
131
|
+
export { make as n, StoryFailure as t };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { o as Step } from "./steps-CvFOQHum.mjs";
|
|
2
|
+
import { ReactElement } from "react";
|
|
3
|
+
import { Font } from "takumi-js";
|
|
4
|
+
/** Where a screen's files go: a path, or a `file:` URL (`new URL("./baselines/", import.meta.url)`). */
|
|
5
|
+
type Place = string | URL;
|
|
6
|
+
/** How a story's screens are rendered, compared and reported. */
|
|
7
|
+
type Options = {
|
|
8
|
+
/** The stylesheets the component's markup is painted with (compiled CSS text). */
|
|
9
|
+
readonly css?: string | ReadonlyArray<string>;
|
|
10
|
+
/** The viewport, in CSS pixels; every frame is this size. */
|
|
11
|
+
readonly width: number;
|
|
12
|
+
readonly height: number;
|
|
13
|
+
/** Fonts to paint with (local bytes); takumi's built-in font otherwise. */
|
|
14
|
+
readonly fonts?: ReadonlyArray<Font>;
|
|
15
|
+
/** Reviewed frames: `<baselines>/<story>/<step>-<label>.png`, committed. */
|
|
16
|
+
readonly baselines: Place;
|
|
17
|
+
/** The run's report: frames, diffs, a filmstrip page per story and a manifest (gitignored). */
|
|
18
|
+
readonly output: Place;
|
|
19
|
+
/** Writes (creates or replaces) baselines instead of comparing. Never implicitly. */
|
|
20
|
+
readonly update?: boolean;
|
|
21
|
+
};
|
|
22
|
+
/** How one frame compared with its baseline. */
|
|
23
|
+
type Status = "matched" | "created" | "updated" | "missing" | "mismatch";
|
|
24
|
+
/** One captured frame, as the manifest lists it. */
|
|
25
|
+
type Frame = {
|
|
26
|
+
readonly step: number;
|
|
27
|
+
readonly label: string;
|
|
28
|
+
readonly file: string;
|
|
29
|
+
readonly status: Status;
|
|
30
|
+
/** Pixels that differ from the baseline (a mismatch). */
|
|
31
|
+
readonly differing?: number;
|
|
32
|
+
};
|
|
33
|
+
/**
|
|
34
|
+
* Screens for stories: `make(options)` gives `render(element)`, a step that mounts a React
|
|
35
|
+
* element under the package's `Provider` with the story's client (stock `useLiveQuery` reads the
|
|
36
|
+
* story's data) in a happy-dom document, and captures a frame after it and after every later
|
|
37
|
+
* step: once the world is quiet (command replies still held) and React has flushed, the DOM is
|
|
38
|
+
* serialised (current control values) and painted by takumi's WASM renderer with `css`, then
|
|
39
|
+
* compared pixel by pixel with its baseline. `shot(label?)` captures a frame on demand (with
|
|
40
|
+
* `render(element, { every: false })`, only there).
|
|
41
|
+
*/
|
|
42
|
+
export declare const make: (options: Options) => {
|
|
43
|
+
render: (element: ReactElement, settings?: {
|
|
44
|
+
readonly every?: boolean;
|
|
45
|
+
}) => Step;
|
|
46
|
+
shot: (label?: string) => Step;
|
|
47
|
+
};
|
|
48
|
+
/** An image as 8-bit RGBA pixels, row by row. */
|
|
49
|
+
type Pixels = {
|
|
50
|
+
readonly width: number;
|
|
51
|
+
readonly height: number;
|
|
52
|
+
readonly data: Uint8Array;
|
|
53
|
+
};
|
|
54
|
+
/** Encodes RGBA pixels as a PNG (8-bit RGBA, no filter): what baselines and frames are stored as. */
|
|
55
|
+
export declare const encode: (pixels: Pixels) => Uint8Array;
|
|
56
|
+
/**
|
|
57
|
+
* Decodes a PNG to RGBA pixels: 8-bit RGB or RGBA, not interlaced, any filter (what `encode`
|
|
58
|
+
* writes, and what common tools re-save it as). Anything else is an error.
|
|
59
|
+
*/
|
|
60
|
+
export declare const decode: (png: Uint8Array) => Pixels;
|
|
61
|
+
/** How two images differ: the pixels that differ, and an image marking them in red. */
|
|
62
|
+
type Difference = {
|
|
63
|
+
readonly pixels: number;
|
|
64
|
+
readonly image: Pixels;
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Compares decoded pixels exactly (not PNG bytes). Images of different sizes differ everywhere;
|
|
68
|
+
* the difference image then has the actual image's size.
|
|
69
|
+
*/
|
|
70
|
+
export declare const compare: (actual: Pixels, expected: Pixels) => Difference;
|
|
71
|
+
export type { Difference, Frame, Options, Pixels, Place, Status };
|