@highalch/story 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maximilian Schön
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,343 @@
1
+ # @highalch/story
2
+
3
+ Stories for data synced with [`@highalch/db`](../db/README.md) and the XState machines over it:
4
+ given server history, when a client, another client or the world acts, then what each source
5
+ shows, its read state and how each command settled. Optional screen steps paint a filmstrip of a
6
+ mounted React component without a browser.
7
+
8
+ | Entry point | What |
9
+ | ------------------------ | ---------------------------------------------------------------------------------------- |
10
+ | `@highalch/story` | The story runner, data steps, invariants, view helpers; never imports XState |
11
+ | `@highalch/story/xstate` | Machine steps and generated stories (`explore`) for the same runner; needs `xstate` |
12
+ | `@highalch/story/screen` | Screen steps: a mounted component's frames vs reviewed baselines; needs takumi/happy-dom |
13
+
14
+ Peer dependencies: `@highalch/db` and its peers; optional `xstate` and `@xstate/effect` (for
15
+ `/xstate`), `react-dom`, `happy-dom` and `takumi-js` 2.14.0 (for `/screen`).
16
+
17
+ A story tells a frontend's behaviour like Foldkit's: given a state, when something happens, then
18
+ the next state and what was asked for. There is **one runner** and one vocabulary: data steps (a
19
+ client, another client or the world acts; what each source shows; how each command settled) and
20
+ machine steps (an XState machine receives events; where it is; which commands it asked for)
21
+ compose freely in one story, in any order. Stories depend on no test runner: steps are plain
22
+ values and a story is a promise you await inside your own `it(...)`. A failed expectation throws a
23
+ `StoryFailure` whose message names the step, what it expected and what it observed (every state
24
+ each row key showed, in order; for a machine step the machine's name and mode, its state and the
25
+ commands it asked for), and lists the steps (✓ passed, ✗ failed, blank not run).
26
+
27
+ ```ts
28
+ import * as Story from "@highalch/story"; // the runner and the data steps; never imports XState
29
+ import { explore, Machine } from "@highalch/story/xstate"; // machine steps and generated stories
30
+ import { invoke } from "@highalch/db/xstate"; // production: how a machine invokes a command
31
+ ```
32
+
33
+ `@highalch/db` never imports the story kit. Only `@highalch/db/xstate` and
34
+ `@highalch/story/xstate` import `xstate` and `@xstate/effect`, optional peer dependencies;
35
+ the repository's `vp run check:patterns` enforces both.
36
+
37
+ ## Making a story
38
+
39
+ ```ts
40
+ // Hosted: the consumer's Domain in memory, real HighAlch clients (one per scope) behind a wire the
41
+ // story controls, on a clock it controls. Data steps and machine steps.
42
+ const story = Story.make(
43
+ Story.memory({ api: NotesApi, layer: handlers, services: stores, session: readerOf }),
44
+ { scope: "acc-1" }, // and any client settings: settleTimeout, reloadDelay, retry, clock
45
+ );
46
+
47
+ // Hostless: no Domain, no client, nothing started. Machines stepped purely.
48
+ const pure = Story.make();
49
+
50
+ it("renames optimistically, then settles through the feed", () =>
51
+ story.with({ invariants: Story.invariants })(
52
+ Story.given(Note.ref(id), new NoteCreated({ note: ada })),
53
+ Story.shows(notes.list({ account: "acc-1" }), [{ title: "Ada" }]),
54
+ Story.when(notes.rename, { NoteId: "n1", title: "Ada 2" }),
55
+ Story.shows(notes.list({ account: "acc-1" }), [{ title: "Ada 2", $hasPendingWrites: true }]),
56
+ Story.settled("Committed"),
57
+ Story.shows(notes.list({ account: "acc-1" }), [{ title: "Ada 2", $hasPendingWrites: false }]),
58
+ ));
59
+ ```
60
+
61
+ Each call of a hosted runner builds a fresh host and fresh clients and disposes them; nothing is
62
+ global. `Story.memory` hosts the Api's model on alchemy's in-memory platform: `layer` (a function,
63
+ so each story gets fresh state) is what the model's `layer` takes, `services` the stores those
64
+ handlers share with `check` steps (`world.host.service(Tag)`), and `session(scope)` the reader's
65
+ middleware when the Api's reads are guarded. Any other host is a `Hosting`: a function returning
66
+ `{ api, client(scope), dispose }` (plus optional `idle`, `seed`, `send`, `service`), for example
67
+ a deployed model's records over HTTP.
68
+
69
+ A hostless story runs any step that needs no Domain: machines stepped purely, and your own steps
70
+ built with `staged`. A data step or a running machine in it fails at once, naming itself:
71
+ `Step 2 (shows …) failed: "shows …" needs a host, and this story has none`. `pure.with(...)` is
72
+ refused (it has no clients, clock or invariants).
73
+
74
+ ## The steps
75
+
76
+ Data steps (`Story.*`; they need a host):
77
+
78
+ | Step | What it does |
79
+ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
80
+ | `given(ref, ...events)` | history: events committed on an aggregate (seeded as alchemy's `Story.given` seeds them; projections see them) |
81
+ | `remote(ref, command)` / `remote(label, (api) => eff)` | another client writes: a command to an aggregate, or any call of the scope's Api client; it must be accepted |
82
+ | `alchemy(Story.given(...))` / `alchemy(Story.when(...))` | alchemy's own `Given`/`When` step values, run on the story's host |
83
+ | `open(source, { as?, settle? })` | materialises a source in a client and keeps it observed, as a mounted `useLiveQuery` would |
84
+ | `shows(source, rows \| predicate, { as? })` | what the source shows now, by key order, each row compared partially; `$hasPendingWrites` names a pending row |
85
+ | `state(source, tag \| error, fields?, { single? })` | the read state, by the same conversion `match` uses: `Loading`, `Retrying`, `Ready`, `Missing`, or the typed error |
86
+ | `when(command, input)` | the client calls a declared command with its input (`command.with({ client })(input)`) |
87
+ | `when(label, ({ client, activate }) => transaction)` | anything that returns a transaction: `createOptimisticAction(command.options)`, `createPacedMutations(command.paced)` |
88
+ | `settled("Committed" \| "Unconfirmed"?)` | the last command (a `when`'s or a running machine's) settled so |
89
+ | `rejected(error)` | the last command was rejected with this typed error (same class, same fields) |
90
+ | `drop(error?)` / `resume()` | the feed fails (reconnecting fails too) / connects again: its retries run now |
91
+ | `mute(on?)` | the feed stays connected and delivers nothing (what it drops is lost to that connection) |
92
+ | `fail(name, error, times?)` / `recover(name)` | a query or command fails with a typed error / answers again |
93
+ | `reload(source)` / `reload(Rows)` | what a `match` handler's `retry` does (`collection.reload()`) / `HighAlch.reload(db, Rows)`, its debounce passed |
94
+ | `hold()` / `release()` | queries answer with what they saw when asked, but only at `release` (a write racing a load) |
95
+ | `advance(ms)` | time passes on the story's clock: retries, reload debounces and settle timeouts due within `ms` fire, in order |
96
+ | `settle()` / `idle()` | wait until nothing more happens by itself / until every command ended |
97
+ | `check(label, (world) => ...)` | anything else: the host's services, a client's wire (`sent`, `asked`), the runs, the feed's entries |
98
+ | `as(scope, ...steps)` | the steps act as the client of another scope (two accounts in one story; a machine started inside runs there) |
99
+
100
+ Machine steps (`Machine.*`). Each addressing step takes a last `{ machine?: name }` (default: the
101
+ machine introduced last), as data steps take `{ as?: scope }`:
102
+
103
+ | Step | Stepped purely (`given`) | Running (`start`) |
104
+ | ----------------------------------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------- |
105
+ | `given(machine, snapshot \| (read) => snapshot, { name? })` | enters from `{ state?, context?, input? }`; works hostless | — |
106
+ | `start(machine, { input?, name? })` | — | enters as an actor (`createEffectActor`) on the step's client; needs a host |
107
+ | `when(event \| (read) => event, { machine? })` | XState's pure `transition`; nothing runs | sent to the actor; the commands it starts wait for a settling step |
108
+ | `then({ state, context? }, { machine? })` | `snapshot.matches(state)`, context compared partially | the same, on the actor's snapshot |
109
+ | `asked(command, input?, { machine? })` | the last transition's spawn actions of `invoke(command)` logic | the commands the story's `Runner` ran for it since its last event |
110
+ | `askedNothing({ machine? })` | the last transition spawned none | it ran none since its last event |
111
+ | `done(command, output?, { machine? })` | feeds `xstate.done.actor.*` for the command it asked for last | an error: its commands settle by themselves (`Story.settled`) |
112
+ | `failed(command, error, { machine? })` | feeds `xstate.error.actor.*` with the typed error | an error: assert the real rejection with `Story.rejected` |
113
+
114
+ `(read) => …` computes a snapshot or an event from what the story's sources show when the step runs
115
+ (`read(source, { as? })` returns its rows, opening it first), so a stepped machine can be asked
116
+ what it _would_ do with the rows a collection shows now. It needs a host.
117
+
118
+ ## Pure or running: one explicit choice
119
+
120
+ A machine enters a story once, and how it enters decides what every later step means for it;
121
+ nothing switches modes silently.
122
+
123
+ - **`Machine.given` — stepped purely.** No actor, no client: each step is XState's
124
+ `transition(machine, snapshot, event)`. `asked` reads the commands the transition _would_ spawn;
125
+ `done`/`failed` feed it their results. It proves the machine's decisions exactly, without
126
+ timing. In a hosted story it sits beside the data: the rows it reads are real, and the commands
127
+ it asks for are never sent.
128
+ - **`Machine.start` — running.** An actor on the story's client (of the step's scope). The
129
+ commands it invokes run there and are recorded as its runs; their real outcomes arrive by
130
+ themselves and `Story.settled`/`Story.rejected` assert them. It proves the machine and the data
131
+ together: what is shown while a command is in flight, how it reacts to typed rejections, that
132
+ rows roll back. Needs a host.
133
+
134
+ ```ts
135
+ story(
136
+ Story.given(n1, new NoteCreated({ note: ada })),
137
+ Story.open(one),
138
+ Story.remote(n1, new RenameNote({ NoteId: "n1", title: "Ada (theirs)" })),
139
+ // A draft editor, stepped purely, beside the data: what would it save?
140
+ Machine.given(editor, { input: { NoteId: "n1" } }, { name: "draft" }),
141
+ Machine.when(async (read) => ({ type: "Edit", title: `${(await read(one))[0]?.title}, edited` })),
142
+ Machine.when({ type: "Save" }),
143
+ Machine.asked(notes.rename, { title: "Ada (theirs), edited" }),
144
+ Story.shows(one, [{ title: "Ada (theirs)", $hasPendingWrites: false }]), // nothing was sent
145
+ // A running editor: its rename really runs, is rejected and rolls back.
146
+ Machine.start(editor, { input: { NoteId: "n1" }, name: "live" }),
147
+ Machine.when({ type: "Edit", title: "locked" }, { machine: "live" }),
148
+ Machine.when({ type: "Save" }, { machine: "live" }),
149
+ Story.shows(one, [{ title: "locked", $hasPendingWrites: true }]),
150
+ Story.rejected(new NoteLocked({ title: "locked" })),
151
+ Machine.then({ state: "Failed" }, { machine: "live" }),
152
+ );
153
+ ```
154
+
155
+ **Several machines.** `given`/`start` name a machine (`{ name }`, default its `id`; a second
156
+ machine of the same name is an error); every other machine step addresses one by
157
+ `{ machine: name }`, else the one introduced last. A failure names the machine and its mode:
158
+ `draft (stepped) is not in the expected state … expected "Saved" … observed "Saving" … asked since
159
+ its last event: rename {"NoteId":"n1","title":"Ada 2"}`.
160
+
161
+ **Invoking a command.** A machine invokes a command through `invoke(command)` from
162
+ `@highalch/db/xstate` (production code imports it there, never from a testing entry;
163
+ `story/xstate` re-exports it), registered as an actor and run with `@xstate/effect`'s
164
+ `createEffectActor`:
165
+
166
+ ```ts
167
+ const editor = setupEffect({ actors: { rename: invoke(notes.rename) }, schemas }).createMachine({
168
+ states: {
169
+ Saving: {
170
+ invoke: {
171
+ src: "rename",
172
+ input: ({ context }) => ({ NoteId: context.NoteId, title: context.draft }),
173
+ onDone: () => ({ target: "Saved" }),
174
+ onError: ({ event }) => ({
175
+ target: isTagged(event.error, "NoteMissing") ? "Stale" : "Failed",
176
+ }),
177
+ },
178
+ },
179
+ },
180
+ });
181
+ ```
182
+
183
+ It is `fromEffect` over `command.effect(input)`: the invoked actor's output is the `Settled` value
184
+ and its error the typed rejection (the original instance). The logic is marked with its command,
185
+ which is what makes "the command it asked for" observable: XState 6's pure `transition` returns,
186
+ for each invoked actor, an `@xstate.spawn` executable action holding the actor `logic`, its `id`
187
+ and resolved `input`; the story reads the mark from `logic`, and names the command by the key it
188
+ is registered under in `setup({ actors })`. Plain XState logic works the same once marked:
189
+ `mark(createAsyncLogic({ run: ({ input }) => command.result(input) }), command)`. In production
190
+ the invoked command runs on the client the `Provider` registered; for a running machine in a story
191
+ the `Runner` service the story provides runs it on the story's client.
192
+
193
+ ## Generated stories
194
+
195
+ `explore` runs a model: a small XState machine models what can happen to an entity (its events,
196
+ guarded by what it tracks); `steps(event, index)` maps each event to story steps, data steps or
197
+ machine steps alike (an `EDIT` can be a running editor's `Machine.when(Edit)` and
198
+ `Machine.when(Save)`); `explore` enumerates paths with XState's own graph utilities
199
+ (`xstate/graph`'s `getShortestPaths` and `getSimplePaths`), keeps the longest of each prefix
200
+ (every step is checked, so prefixes are), at most `maxLength` events and `maxPaths` paths, in a
201
+ deterministic order, and runs each as a fresh story on the given runner (`before`, the events,
202
+ `after`) with the invariants checked after every step. A failure is shrunk to a shorter failing
203
+ path and reported as its event sequence (`A generated story failed (path 3 of 64): EDIT → DROP →
204
+ REMOTE`) with the story's report. The model must be finite (bound it with a counter) and must
205
+ record what distinguishes interleavings, since paths are simple paths through its states.
206
+
207
+ ## How time and the network behave
208
+
209
+ Steps that let the world move (`given`, `remote`, `open`, `settled`, `rejected`, `advance`,
210
+ `drop`, `resume`, `release`, `reload`, `settle`, `idle`) end when it is quiet: the server is idle,
211
+ no request is in flight, and every live feed delivered the server's latest entry. A command's
212
+ reply reaches the client only while the world moves, so the steps after a `when` (or a running
213
+ machine's `when`) see the optimistic rows whatever the server already did, and `rejected` sees the
214
+ rollback. The clients wait on the story's clock (`clock: "manual"`, the default): a retry, a
215
+ reload debounce or a settle timeout fires only when `advance` (or `resume`, for retries) lets it,
216
+ so stories never sleep and never race the timer. `clock: "real"` uses `setTimeout`, still tracked.
217
+ A source records what a mounted live query renders: one state per key per change batch (a reload's
218
+ delete and insert of a row in one batch is one change). When a story ends, or fails, with a command
219
+ in flight, closing its clients (`HighAlch.close` waits for sent commands) lets the replies through
220
+ and runs the clock's waits, so a failure is reported instead of hanging.
221
+
222
+ **Invariants.** `story.with({ invariants })` checks invariants after every step and at the end.
223
+ `Story.invariants` are a collection's defaults:
224
+
225
+ - `noFlickerBack`: a source never shows a row of the feed older than one it already showed for that
226
+ key, and once a command's optimistic row showed, never one older than the command's own change
227
+ (no new → old → new when it settles).
228
+ - `nothingPending`: at rest (settled, every command ended, every feed live) no row is pending.
229
+ - `subsetsAgree`: at rest, every ready subset of an entity in one client agrees on a shared row.
230
+ - `rejectedRestores`: right after a rejection, each source shows the row it showed before the
231
+ command (or a newer row of the feed), not pending.
232
+
233
+ They judge rows against the feed's own entries (read from the Domain, not through the wire).
234
+
235
+ ## Screens: a filmstrip of a story
236
+
237
+ `@highalch/story/screen` adds steps that mount a real React component against the story's
238
+ own client and capture a frame after every later step, painted by takumi's WASM renderer without
239
+ a browser and compared with reviewed baselines. A story then yields a filmstrip: loading, ready,
240
+ pending, settled or rolled back, retrying.
241
+
242
+ ```tsx
243
+ import * as Screen from "@highalch/story/screen";
244
+
245
+ const screen = Screen.make({
246
+ css, // the compiled stylesheet(s) the markup is painted with
247
+ width: 360,
248
+ height: 200,
249
+ fonts, // optional: local font bytes; takumi's built-in font otherwise
250
+ baselines: new URL("./baselines/", import.meta.url), // committed, reviewed PNGs
251
+ output: new URL("../artifacts/stories/", import.meta.url), // the run's report (ignored)
252
+ update: process.env.UPDATE_SCREENS === "1", // write baselines; never implicitly
253
+ });
254
+
255
+ await story.with({ name: "rename is rejected" })(
256
+ Story.given(n1, new NoteCreated({ note: ada })),
257
+ screen.render(<NoteList account="acc-1" />), // mounted; frame 2
258
+ Story.when(notes.rename, { NoteId: "n1", title: "locked" }), // frame 3: pending
259
+ Story.rejected(new NoteLocked({ title: "locked" })), // frame 4: rolled back
260
+ );
261
+ ```
262
+
263
+ - `render(element, { every? })` mounts the element with `react-dom/client` under the package's
264
+ `Provider` with the story's client (of the step's scope), so stock `useLiveQuery` reads story
265
+ data; React is flushed with `act`. After this step and every later one, once the world is quiet
266
+ (command replies still held, so a pending row stays pending) and React has flushed, the DOM is
267
+ serialised and painted. `every: false` captures only at `shot(label?)` steps. One screen per
268
+ story; it is unmounted when the story ends, passed or failed.
269
+ - A frame is named by the story's name and the step: `<story>/<step>-<label>.png`. A screen story
270
+ needs `story.with({ name })`; without one, and in a hostless story, `render` fails naming
271
+ itself. Screen steps compose with machine steps (a running editor's frames) like any other.
272
+ - Frames compare decoded pixels exactly, not PNG bytes. A missing or different baseline fails the
273
+ step that captured it and writes the actual frame, the expected one and a diff (differing
274
+ pixels red over the faded frame) to `output`. `update` writes baselines instead; review them
275
+ before committing.
276
+ - `output` holds, per story, every frame (PNG and the HTML painted), `manifest.json` and a
277
+ filmstrip page `index.html`, and an `index.html` of all stories. A story's folder starts afresh
278
+ on each run.
279
+ - The happy-dom window is installed as the global DOM when `render` runs and removed exactly when
280
+ the story ends, so other tests keep their environment. Only this entry imports `takumi-js`,
281
+ `happy-dom` and `react-dom` (optional peer dependencies), checked by `vp run check:patterns`.
282
+
283
+ **What the painter does and does not do.** Takumi paints HTML and CSS (flexbox, borders, radii,
284
+ colours, text) and runs no script. Form controls are not painted, so `input`, `textarea` and
285
+ `select` are serialised as `span`s with their attributes, `data-control` naming the control, and
286
+ their current value as text (passwords masked, checkboxes ☑/☐); style them by class, not by tag.
287
+ No browser layout, focus rings, canvas, images from the network or fonts it is not given; the
288
+ renderer is the pinned WASM build on every platform, so a takumi upgrade means reviewing the
289
+ baselines. A read state that never shows (a query failing on its first load is `Loading` while it
290
+ retries; `Retrying` is a ready source whose feed retries) has no frame to capture.
291
+
292
+ ## Your own steps
293
+
294
+ Every step carries its own interpretation: `{ label, run(stage) }`, where the `Stage` is one story
295
+ run: `stage.world` (the hosted world, `None` hostless), `stage.hosted(label)` (the world, or the
296
+ "needs a host" failure naming the step) and `stage.slot(key, make)` (state your kind of step keeps
297
+ for the run, under a private symbol), `stage.after(run)` (runs after every later step, as a screen
298
+ captures its frames) and `stage.end(run)` (runs when the story ends, before its clients close).
299
+ `Story.step(label, (world) => …)` builds a data step;
300
+ `Story.staged(label, (stage) => …)` any other kind. The machine steps are built exactly so; the
301
+ runner knows nothing about XState. Throw a `Story.Mismatch(reason, detail)` for a readable failure.
302
+
303
+ ## Built on alchemy's `Story`?
304
+
305
+ Not on its runner: alchemy's steps are a closed union interpreted by a private `switch` inside
306
+ `Story.make`, which creates its own platform per run with manual scheduling (deliveries run only on
307
+ its `drain`) and replays the whole story once per order of concurrent work; there is no custom
308
+ step, no access to its host or Api client, and a client that runs concurrently cannot follow a
309
+ replayed scheduler. The kit reuses what it can: the vocabulary (`given`, `when`, `rejected`),
310
+ alchemy's in-memory platform and its `idle`, the same seeding seam for `given` (the model's
311
+ aggregate store `seed`), and alchemy's `Given`/`When` values through `alchemy(...)`. Server-side
312
+ decisions stay alchemy's stories; these stories are about what a client shows.
313
+
314
+ ## What stories prove, and what not
315
+
316
+ They prove what a consumer's sources show and how its commands settle against the real model, the
317
+ real client and TanStack DB, through the same states `match` renders, including failures and
318
+ timing the story controls; a stepped machine's decisions and the commands it asks for, exactly;
319
+ and a running machine together with the data. Generated stories prove the invariants over every
320
+ modelled interleaving up to the bound; nothing outside the model or beyond the bound. They do not
321
+ test React rendering (use the view helpers), the websocket protocol (the wire is the Api client in
322
+ process, or whatever transport your `Hosting` uses), or orders the story does not try.
323
+
324
+ ## View helpers
325
+
326
+ A presentational component takes plain props; its composition component renders
327
+ `match(useLiveQuery(...)).on(...)`. To render each branch without a server:
328
+
329
+ - `Story.Live` constructs every state `match` gives a live query (`Loading()`, `Retrying({ error,
330
+ attempt, data })`, `Ready({ data, feed, retry })`, `Missing()`, `Disabled()`), and
331
+ `Story.Settled` a command's settled value (`Committed(...)`, `Unconfirmed(...)`).
332
+ - `Story.view(source, state)` is a value shaped like a stock `useLiveQuery` result over `source` in
333
+ that state (a `Live` state or one of the source's typed errors), which `match` accepts without
334
+ casts and reads exactly as the real one, with the source's errors; `retried()` counts `retry`
335
+ calls. It is for view tests only: it holds no collection.
336
+
337
+ ## Seams in the core
338
+
339
+ The kit needs two small, behaviour-preserving seams in the core, published as the unstable
340
+ `@highalch/db/internal` entry: `make({ timers })` (`Timers`:
341
+ where retries, reload debounces and settle timeouts wait; the default is `setTimeout`), and a
342
+ feed subscription's read-only `current` (caught up and not failed), which the kit reads to know a
343
+ feed is live. The constructors of `match`'s live states and of `Settled` are shared with it.
@@ -0,0 +1,42 @@
1
+ import { $ as Hosting, A as staged, B as Options, C as release, D as settle, E as resume, F as Stage, G as World, H as Run, I as Client, J as retryTransport, K as json, L as Entry, M as step, N as when, O as settled, P as Mismatch, Q as Host, R as Observation, S as rejected, T as remote, U as Shown, V as Outcome, W as Source, X as transport, Y as Wire, Z as ClientOf, _ as hold, a as ShownRow, b as open, c as advance, d as check, et as Memory, f as drop, g as historyOf, h as given, i as ReadState, j as state, k as shows, l as alchemy, m as flatten, n as Callable, nt as memory, o as Step, p as fail, q as plain, r as Expected, s as Steps, t as Acting, tt as SessionOf, u as as, v as idle, w as reload, x as recover, y as mute, z as Observed } from "./steps-CvFOQHum.mjs";
2
+ import { a as make, c as invariants, d as rejectedRestores, f as subsetsAgree, i as StoryOptions, l as noFlickerBack, n as Story, o as Invariant, r as StoryFailure, s as Moment, t as StepReport, u as nothingPending } from "./run-C2SdDPWE.mjs";
3
+ import { Data } from "effect";
4
+ import { ErrorsOf, Live as Live$1, Source as Source$1, TaggedFailure } from "@highalch/db";
5
+ import { CollectionStatus, HealthNode } from "@tanstack/db";
6
+ /**
7
+ * The constructors of every state `match` gives a live query result: `Loading()`,
8
+ * `Retrying({ error, attempt, data })`, `Ready({ data, feed, retry })`, `Missing()`,
9
+ * `Disabled()`. A presentational component that takes a state renders each branch from them.
10
+ */
11
+ export declare const Live: Data.TaggedEnum.GenericConstructor<import("@highalch/db/internal").LiveDefinition>;
12
+ /** The constructors of a command's settled value: `Committed({ reply, stream, version })`, `Unconfirmed(...)`. */
13
+ export declare const Settled: Data.TaggedEnum.GenericConstructor<import("@highalch/db/internal").SettledDefinition>;
14
+ type States<Row, E> = Live$1<ReadonlyArray<Row>, E>;
15
+ /**
16
+ * The states a view result can be built for: `Live.Loading()`, `Live.Retrying(...)`,
17
+ * `Live.Ready(...)`, or one of the source's typed errors.
18
+ */
19
+ type ViewState<Row, E> = Data.TaggedEnum.Value<States<Row, E>, "Loading" | "Retrying" | "Ready"> | E;
20
+ /**
21
+ * A value shaped like a stock `useLiveQuery` result over a source, in a given state. `match`
22
+ * accepts it as it accepts the real one (no casts) and reads the same state from it, with the
23
+ * source's errors. For view tests: render a composition component's `match` branches without a
24
+ * server. `retry` is recorded in `retried`.
25
+ */
26
+ type ViewResult<Row> = {
27
+ readonly data: Array<Row>;
28
+ readonly status: CollectionStatus;
29
+ readonly isEnabled: true;
30
+ readonly isReady: boolean;
31
+ readonly isLoadingError: boolean;
32
+ readonly isCrashed: false;
33
+ readonly health: HealthNode;
34
+ readonly collection: {
35
+ readonly reload: () => Promise<void>;
36
+ };
37
+ /** How many times a handler's `retry` reloaded it. */
38
+ readonly retried: () => number;
39
+ };
40
+ /** `view(customers.list(input), state)`: a live query result over that source in `state`. */
41
+ export declare const view: <Row extends object>(source: Source$1<Row>, state: ViewState<NoInfer<Row>, Extract<ErrorsOf<Array<NoInfer<Row>>>, TaggedFailure>>) => ViewResult<Row>;
42
+ export { type Acting, type Callable, type Client, type ClientOf, type Entry, type Expected, type Host, type Hosting, type Invariant, type Memory, Mismatch, type Moment, type Observation, Observed, type Options, type Outcome, type ReadState, type Run, type Story as Runner, type SessionOf, type Shown, type ShownRow, type Source, type Stage, type Step, type StepReport, type Steps, StoryFailure, type StoryOptions, type ViewResult, type ViewState, 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, when };