@lunora/replica 1.0.0-alpha.4 → 1.0.0-alpha.6

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.
Files changed (31) hide show
  1. package/dist/adapters/better-sqlite3.d.mts +14 -14
  2. package/dist/adapters/better-sqlite3.d.ts +14 -14
  3. package/dist/adapters/sqlite-wasm.d.mts +29 -19
  4. package/dist/adapters/sqlite-wasm.d.ts +29 -19
  5. package/dist/adapters/sqlite-wasm.mjs +12 -24
  6. package/dist/adapters/sqljs.d.mts +10 -10
  7. package/dist/adapters/sqljs.d.ts +10 -10
  8. package/dist/index.d.mts +634 -574
  9. package/dist/index.d.ts +634 -574
  10. package/dist/index.mjs +9 -9
  11. package/dist/packem_shared/EventLog-CnK-3Wge.mjs +264 -0
  12. package/dist/packem_shared/{EventLogDO-CZYUvvSr.mjs → EventLogDO-DqlsVx0H.mjs} +155 -9
  13. package/dist/packem_shared/{EventLogDOClient-DGiEdi96.mjs → EventLogDOClient-F4FO8Si4.mjs} +8 -2
  14. package/dist/packem_shared/{EventSource-DfV4VoRD.mjs → EventSource-D5yO9_aI.mjs} +48 -22
  15. package/dist/packem_shared/{EventsSync-DkVbU0WV.mjs → EventsSync-BP36tC9O.mjs} +49 -17
  16. package/dist/packem_shared/{LocalMirror-GeJ26eNe.mjs → LocalMirror-a-5jEqFN.mjs} +34 -3
  17. package/dist/packem_shared/{MaterializerRuntime-HqNXqJxp.mjs → MaterializerRuntime-BoIrsMYB.mjs} +65 -45
  18. package/dist/packem_shared/applyDiff-98tKzmiW.mjs +67 -0
  19. package/dist/packem_shared/{classifyChanges-aZmkxgVI.mjs → classifyChanges-RcqLBpLs.mjs} +6 -3
  20. package/dist/packem_shared/local-mirror.d-CyGOpUES.d.ts +530 -0
  21. package/dist/packem_shared/local-mirror.d-DTavX_y0.d.mts +530 -0
  22. package/dist/packem_shared/{types.d-BuAWjEY5.d.mts → types.d-CkMkSwLJ.d.mts} +10 -10
  23. package/dist/packem_shared/{types.d-BuAWjEY5.d.ts → types.d-CkMkSwLJ.d.ts} +10 -10
  24. package/dist/react.d.mts +59 -59
  25. package/dist/react.d.ts +59 -59
  26. package/dist/react.mjs +2 -2
  27. package/package.json +1 -1
  28. package/dist/packem_shared/EventLog-zMy7AYP4.mjs +0 -162
  29. package/dist/packem_shared/applyDiff-BtbIl1D3.mjs +0 -40
  30. package/dist/packem_shared/local-mirror.d-BUeOe5KC.d.mts +0 -439
  31. package/dist/packem_shared/local-mirror.d-Cd8tAg-W.d.ts +0 -439
package/dist/index.d.mts CHANGED
@@ -1,130 +1,130 @@
1
1
  export { createBetterSqlite3Adapter } from "./adapters/better-sqlite3.mjs";
2
2
  export { createSqliteWasmAdapter } from "./adapters/sqlite-wasm.mjs";
3
3
  export { createSqlJsAdapter } from "./adapters/sqljs.mjs";
4
- import { S as SqliteAdapter } from "./packem_shared/types.d-BuAWjEY5.mjs";
5
- import { T as TableDiff, I as InputEvent, S as Seq, E as EventLogEntry, a as EventLog, A as AppendOptions, L as LocalMirror } from "./packem_shared/local-mirror.d-BUeOe5KC.mjs";
6
- export { type C as ClientSeq, type b as EventLogSnapshot, type G as GlobalSeq, type c as LocalMirrorOptions, type M as MirrorTableDef, type R as RowChange, d as classifyChanges, e as createTableDiff, f as diffSize, i as isClientSeq, g as isDiffEmpty, h as isGlobalSeq, j as isInputEvent, m as mergeDiffs } from "./packem_shared/local-mirror.d-BUeOe5KC.mjs";
7
- /**
8
- * Apply a single {@link TableDiff} to an in-memory row map and return
9
- * the updated map.
10
- *
11
- * The function creates a **shallow copy** of the input map so the caller's
12
- * reference stays untouched unless they choose to replace it.
13
- * @example
14
- * ```ts
15
- * const rows = new Map<string, Record<string, unknown>>();
16
- * rows.set("id-1", { name: "alice" });
17
- *
18
- * const diff = createTableDiff("users", [
19
- * { type: "insert", data: { id: "id-2", name: "bob" } },
20
- * { type: "update", id: "id-1", data: { name: "alice-updated" } },
21
- * ]);
22
- *
23
- * const updated = applyDiff(rows, diff);
24
- * updated.get("id-1")?.name // "alice-updated"
25
- * updated.get("id-2")?.name // "bob"
26
- * ```
27
- * @experimental
28
- */
4
+ import { S as SqliteAdapter } from "./packem_shared/types.d-CkMkSwLJ.mjs";
5
+ import { T as TableDiff, I as InputEvent, S as Seq, E as EventLogEntry, a as EventLog, A as AppendOptions, L as LocalMirror } from "./packem_shared/local-mirror.d-DTavX_y0.mjs";
6
+ export { type C as ClientSeq, type b as EventLogOptions, type c as EventLogSnapshot, type G as GlobalSeq, type d as LocalMirrorOptions, type M as MirrorTableDef, type R as RowChange, e as classifyChanges, f as createTableDiff, g as diffSize, i as isClientSeq, h as isDiffEmpty, j as isGlobalSeq, k as isInputEvent, m as mergeDiffs } from "./packem_shared/local-mirror.d-DTavX_y0.mjs";
7
+ /**
8
+ * Apply a single {@link TableDiff} to an in-memory row map and return
9
+ * the updated map.
10
+ *
11
+ * The function creates a **shallow copy** of the input map so the caller's
12
+ * reference stays untouched unless they choose to replace it.
13
+ * @example
14
+ * ```ts
15
+ * const rows = new Map<string, Record<string, unknown>>();
16
+ * rows.set("id-1", { name: "alice" });
17
+ *
18
+ * const diff = createTableDiff("users", [
19
+ * { type: "insert", data: { id: "id-2", name: "bob" } },
20
+ * { type: "update", id: "id-1", data: { name: "alice-updated" } },
21
+ * ]);
22
+ *
23
+ * const updated = applyDiff(rows, diff);
24
+ * updated.get("id-1")?.name // "alice-updated"
25
+ * updated.get("id-2")?.name // "bob"
26
+ * ```
27
+ * @experimental
28
+ */
29
29
  declare const applyDiff: (current: ReadonlyMap<string, Record<string, unknown>>, diff: TableDiff) => Map<string, Record<string, unknown>>;
30
30
  /**
31
- * Apply an array of diffs **in order**, returning the final row map.
32
- *
33
- * This is equivalent to calling {@link applyDiff} repeatedly but avoids
34
- * intermediate map copies.
35
- * @experimental
36
- */
31
+ * Apply an array of diffs **in order**, returning the final row map.
32
+ *
33
+ * This is equivalent to calling {@link applyDiff} repeatedly but avoids
34
+ * intermediate map copies.
35
+ * @experimental
36
+ */
37
37
  declare const applyDiffs: (current: ReadonlyMap<string, Record<string, unknown>>, diffs: ReadonlyArray<TableDiff>) => Map<string, Record<string, unknown>>;
38
38
  /**
39
- * Merge the row-level effect of a {@link TableDiff} into plain JSON
40
- * state keyed by table name, returning a new snapshot.
41
- * @param snapshot Current snapshot, e.g. `{ users: Map&lt;id, row>, posts: Map&lt;id, row> }`.
42
- * @param diff Contains the target table name and the row-level changes to merge.
43
- * @returns A shallow copy of `snapshot` with `diff.table`'s map updated.
44
- * @experimental
45
- */
39
+ * Merge the row-level effect of a {@link TableDiff} into plain JSON
40
+ * state keyed by table name, returning a new snapshot.
41
+ * @param snapshot Current snapshot, e.g. `{ users: Map&lt;id, row>, posts: Map&lt;id, row> }`.
42
+ * @param diff Contains the target table name and the row-level changes to merge.
43
+ * @returns A shallow copy of `snapshot` with `diff.table`'s map updated.
44
+ * @experimental
45
+ */
46
46
  declare const applyDiffToSnapshot: (snapshot: ReadonlyMap<string, ReadonlyMap<string, Record<string, unknown>>>, diff: TableDiff) => Map<string, Map<string, Record<string, unknown>>>;
47
47
  /** Map a namespace-and-name pair to a qualified event type string. */
48
48
  type QualifiedType<Ns extends string, Name extends string> = `${Ns}.${Name}`;
49
49
  /**
50
- * Extract the payload type from an event schema.
51
- *
52
- * A `@lunora/values` validator (e.g. `v.object(...)`) carries its output type on
53
- * the phantom `__type` field (the same hook `Infer` reads), so match that FIRST
54
- * — otherwise a validator, being object-shaped, would fall through to the
55
- * `Record` branch and resolve to the validator instance itself rather than its
56
- * validated `{ … }` output. A bare factory function or plain descriptor object
57
- * is still supported as a fallback.
58
- */
50
+ * Extract the payload type from an event schema.
51
+ *
52
+ * A `@lunora/values` validator (e.g. `v.object(...)`) carries its output type on
53
+ * the phantom `__type` field (the same hook `Infer` reads), so match that FIRST
54
+ * — otherwise a validator, being object-shaped, would fall through to the
55
+ * `Record` branch and resolve to the validator instance itself rather than its
56
+ * validated `{ … }` output. A bare factory function or plain descriptor object
57
+ * is still supported as a fallback.
58
+ */
59
59
  type PayloadOf<T> = T extends {
60
60
  readonly __type: infer P;
61
61
  } ? P : T extends ((payload: infer P) => unknown) ? P : T extends Record<string, unknown> ? T : never;
62
62
  type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
63
63
  /**
64
- * Produce `{ "ns.name": Payload }` for every event, merged.
65
- */
66
- type EventTypeMap<TDefinition extends Record<string, Record<string, unknown>>> = UnionToIntersection<{ [Ns in keyof TDefinition & string]: { [Name in keyof TDefinition[Ns] & string]: { [K in QualifiedType<Ns, Name>]: PayloadOf<TDefinition[Ns][Name]> } }[keyof TDefinition[Ns] & string] }[keyof TDefinition & string]>;
64
+ * Produce `{ "ns.name": Payload }` for every event, merged.
65
+ */
66
+ type EventTypeMap<TDefinition extends Record<string, Record<string, unknown>>> = UnionToIntersection<{ [Ns in keyof TDefinition & string]: { [Name in keyof TDefinition[Ns] & string]: { [K in QualifiedType<Ns, Name>]: PayloadOf<TDefinition[Ns][Name]>; }; }[keyof TDefinition[Ns] & string]; }[keyof TDefinition & string]>;
67
67
  /**
68
- * A factory function that creates an {@link InputEvent} for a specific event type.
69
- *
70
- * The returned event has no `seq` — it is an optimistic / command payload
71
- * that the event log will assign a sequence number to on append.
72
- * @experimental
73
- */
68
+ * A factory function that creates an {@link InputEvent} for a specific event type.
69
+ *
70
+ * The returned event has no `seq` — it is an optimistic / command payload
71
+ * that the event log will assign a sequence number to on append.
72
+ * @experimental
73
+ */
74
74
  interface EventFactory<Type extends string, Payload> {
75
75
  (payload: Payload): InputEvent<Type, Payload>;
76
76
  /** The fully qualified event type string (e.g. `"chat.messageSent"`). */
77
77
  readonly type: Type;
78
78
  }
79
79
  /**
80
- * The namespace object returned for each group of events.
81
- * @experimental
82
- */
83
- type EventNamespace<Ns extends string, TDefinition extends Record<string, unknown>> = { [Name in keyof TDefinition & string]: EventFactory<QualifiedType<Ns, Name>, PayloadOf<TDefinition[Name]>> };
80
+ * The namespace object returned for each group of events.
81
+ * @experimental
82
+ */
83
+ type EventNamespace<Ns extends string, TDefinition extends Record<string, unknown>> = { [Name in keyof TDefinition & string]: EventFactory<QualifiedType<Ns, Name>, PayloadOf<TDefinition[Name]>>; };
84
84
  /**
85
- * The full result of {@link defineEvents}.
86
- * @experimental
87
- */
88
- type EventsDefinition<TDefinition extends Record<string, Record<string, unknown>>> = { [Ns in keyof TDefinition & string]: EventNamespace<Ns, TDefinition[Ns]> } & {
85
+ * The full result of {@link defineEvents}.
86
+ * @experimental
87
+ */
88
+ type EventsDefinition<TDefinition extends Record<string, Record<string, unknown>>> = { [Ns in keyof TDefinition & string]: EventNamespace<Ns, TDefinition[Ns]>; } & {
89
89
  /** Type-level map of event type → payload shape. Useful for generic code. */
90
90
  readonly _types: EventTypeMap<TDefinition>;
91
91
  };
92
92
  /**
93
- * Declare typed event types for event sourcing.
94
- *
95
- * Each key under a namespace becomes a factory function that produces
96
- * an {@link InputEvent} — an optimistic / command event that the event
97
- * log will assign a sequence number to on append.
98
- * @param definition A nested object where the outer keys are namespaces
99
- * and the inner keys are event names mapped to their
100
- * payload schemas (or simple type-descriptor objects).
101
- * @returns An object with the same nesting structure, where each leaf is
102
- * a factory function plus a `.type` property.
103
- */
93
+ * Declare typed event types for event sourcing.
94
+ *
95
+ * Each key under a namespace becomes a factory function that produces
96
+ * an {@link InputEvent} — an optimistic / command event that the event
97
+ * log will assign a sequence number to on append.
98
+ * @param definition A nested object where the outer keys are namespaces
99
+ * and the inner keys are event names mapped to their
100
+ * payload schemas (or simple type-descriptor objects).
101
+ * @returns An object with the same nesting structure, where each leaf is
102
+ * a factory function plus a `.type` property.
103
+ */
104
104
  interface DefineEventsOptions {
105
105
  /**
106
- * Optional version prefix for all event types.
107
- *
108
- * When set, every qualified event type is prefixed with `"v&lt;N>."`, enabling
109
- * versioned event naming like `"v1.chat.messageSent"` or `"v2.chat.messageSent"`.
110
- * This allows materializers to evolve their handling logic based on the event
111
- * version without breaking backward compatibility.
112
- * @example "v1" → event type becomes "v1.chat.messageSent"
113
- */
106
+ * Optional version prefix for all event types.
107
+ *
108
+ * When set, every qualified event type is prefixed with `"v&lt;N>."`, enabling
109
+ * versioned event naming like `"v1.chat.messageSent"` or `"v2.chat.messageSent"`.
110
+ * This allows materializers to evolve their handling logic based on the event
111
+ * version without breaking backward compatibility.
112
+ * @example "v1" → event type becomes "v1.chat.messageSent"
113
+ */
114
114
  readonly version?: string;
115
115
  }
116
116
  /**
117
- * `defineEvents` is part of the experimental `@lunora/replica` API and may change without a major version bump.
118
- * @experimental
119
- */
117
+ * `defineEvents` is part of the experimental `@lunora/replica` API and may change without a major version bump.
118
+ * @experimental
119
+ */
120
120
  declare const defineEvents: <TDefinition extends Record<string, Record<string, unknown>>>(definition: TDefinition, options?: DefineEventsOptions) => EventsDefinition<TDefinition>;
121
121
  /**
122
- * Shape of the `events[]` items sent in a POST `/append` body.
123
- *
124
- * Like {@link InputEvent} but with `timestamp` optional — omit it to
125
- * let the server assign the timestamp.
126
- * @experimental
127
- */
122
+ * Shape of the `events[]` items sent in a POST `/append` body.
123
+ *
124
+ * Like {@link InputEvent} but with `timestamp` optional — omit it to
125
+ * let the server assign the timestamp.
126
+ * @experimental
127
+ */
128
128
  interface AppendEventInput {
129
129
  /** Globally-unique client identifier (for offline/optimistic support). */
130
130
  readonly clientId?: string;
@@ -140,133 +140,141 @@ interface AppendEventInput {
140
140
  readonly type: string;
141
141
  }
142
142
  /**
143
- * Options for constructing an {@link EventLogDOClient}.
144
- * @experimental
145
- */
143
+ * Options for constructing an {@link EventLogDOClient}.
144
+ * @experimental
145
+ */
146
146
  interface EventLogDOClientOptions {
147
147
  /**
148
- * A function that dispatches an HTTP request to the target EventLogDO
149
- * instance. In a Cloudflare Worker this is:
150
- *
151
- * ```ts
152
- * (req) => env.MY_DO_NAMESPACE.get(id).fetch(req)
153
- * ```
154
- */
148
+ * A function that dispatches an HTTP request to the target EventLogDO
149
+ * instance. In a Cloudflare Worker this is:
150
+ *
151
+ * ```ts
152
+ * (req) => env.MY_DO_NAMESPACE.get(id).fetch(req)
153
+ * ```
154
+ */
155
155
  fetch: (request: Request) => Promise<Response>;
156
156
  }
157
157
  /**
158
- * Lightweight HTTP client for EventLogDO's RPC surface.
159
- *
160
- * Each method maps to one of the DO's endpoints, throws on non-OK status,
161
- * and returns the parsed response body.
162
- * @experimental
163
- */
158
+ * Lightweight HTTP client for EventLogDO's RPC surface.
159
+ *
160
+ * Each method maps to one of the DO's endpoints, throws on non-OK status,
161
+ * and returns the parsed response body.
162
+ * @experimental
163
+ */
164
164
  declare class EventLogDOClient {
165
165
  #private;
166
166
  constructor(options: EventLogDOClientOptions);
167
167
  /**
168
- * Append one or more events to the log.
169
- * @returns The persisted entries with their assigned `seq` numbers.
170
- */
171
- append(events: AppendEventInput[]): Promise<EventLogEntry[]>;
172
- /**
173
- * Fetch all entries with `seq >= sinceSeq`.
174
- *
175
- * Pass `sinceSeq = 0` to fetch the entire log.
176
- */
168
+ * Append one or more events to the log.
169
+ * @param events The events to append.
170
+ * @param options Idempotency controls for the batch.
171
+ * @param options.batchId Optional idempotency key for the whole batch — a
172
+ * retried `append` call with the same `batchId` (e.g. after a network
173
+ * timeout that hid a successful response) returns the originally-persisted
174
+ * entries instead of inserting duplicates.
175
+ * @returns The persisted entries with their assigned `seq` numbers.
176
+ */
177
+ append(events: AppendEventInput[], options?: {
178
+ batchId?: string;
179
+ }): Promise<EventLogEntry[]>;
180
+ /**
181
+ * Fetch all entries with `seq >= sinceSeq`.
182
+ *
183
+ * Pass `sinceSeq = 0` to fetch the entire log.
184
+ */
177
185
  getSince(sinceSeq: number): Promise<EventLogEntry[]>;
178
186
  /**
179
- * Fetch a paginated range of entries.
180
- * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
181
- * page exists (i.e. the DO returned `limit + 1` rows).
182
- */
187
+ * Fetch a paginated range of entries.
188
+ * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
189
+ * page exists (i.e. the DO returned `limit + 1` rows).
190
+ */
183
191
  getRange(fromSeq: number, limit?: number): Promise<{
184
192
  entries: EventLogEntry[];
185
193
  hasMore: boolean;
186
194
  }>;
187
195
  /**
188
- * Return the total number of entries currently in the log.
189
- */
196
+ * Return the total number of entries currently in the log.
197
+ */
190
198
  getSize(): Promise<number>;
191
199
  /**
192
- * Return the full log state — all entries plus the next seq number.
193
- */
200
+ * Return the full log state — all entries plus the next seq number.
201
+ */
194
202
  getState(): Promise<{
195
203
  entries: EventLogEntry[];
196
204
  nextSeq: number;
197
205
  }>;
198
206
  }
199
207
  /**
200
- * Type-safe event emitter that powers the event-sourcing runtime.
201
- * @example
202
- * ```ts
203
- * type MyEvents = { userCreated: { id: string; name: string }; error: { message: string } };
204
- *
205
- * const emitter = new EventEmitter<MyEvents>();
206
- * emitter.on("userCreated", (payload) => console.log(payload.name));
207
- * emitter.emit("userCreated", { id: "1", name: "alice" });
208
- * ```
209
- * @experimental
210
- */
208
+ * Type-safe event emitter that powers the event-sourcing runtime.
209
+ * @example
210
+ * ```ts
211
+ * type MyEvents = { userCreated: { id: string; name: string }; error: { message: string } };
212
+ *
213
+ * const emitter = new EventEmitter<MyEvents>();
214
+ * emitter.on("userCreated", (payload) => console.log(payload.name));
215
+ * emitter.emit("userCreated", { id: "1", name: "alice" });
216
+ * ```
217
+ * @experimental
218
+ */
211
219
  declare class EventEmitter<EventMap extends Record<string, unknown>> {
212
220
  #private;
213
221
  /**
214
- * Register a handler for a specific event type.
215
- * @returns An unsubscribe function (equivalent to calling {@link off}).
216
- */
222
+ * Register a handler for a specific event type.
223
+ * @returns An unsubscribe function (equivalent to calling {@link off}).
224
+ */
217
225
  on<K extends keyof EventMap>(event: K, handler: (payload: EventMap[K]) => void): () => void;
218
226
  /**
219
- * Remove a previously registered handler.
220
- */
227
+ * Remove a previously registered handler.
228
+ */
221
229
  off<K extends keyof EventMap>(event: K, handler: (payload: EventMap[K]) => void): void;
222
230
  /**
223
- * Register a wildcard handler that fires for **every** event type.
224
- * @returns An unsubscribe function.
225
- */
231
+ * Register a wildcard handler that fires for **every** event type.
232
+ * @returns An unsubscribe function.
233
+ */
226
234
  onAny(handler: (event: keyof EventMap, payload: unknown) => void): () => void;
227
235
  /**
228
- * Remove a wildcard handler.
229
- */
236
+ * Remove a wildcard handler.
237
+ */
230
238
  offAny(handler: (event: keyof EventMap, payload: unknown) => void): void;
231
239
  /**
232
- * Emit an event. All registered handlers (typed + wildcard) are invoked
233
- * synchronously. Exceptions from handlers are caught and silently
234
- * swallowed — they **must not** break the emitter loop.
235
- * @returns `true` if at least one handler was called.
236
- */
240
+ * Emit an event. All registered handlers (typed + wildcard) are invoked
241
+ * synchronously. Exceptions from handlers are caught and silently
242
+ * swallowed — they **must not** break the emitter loop.
243
+ * @returns `true` if at least one handler was called.
244
+ */
237
245
  emit<K extends keyof EventMap>(event: K, payload: EventMap[K]): boolean;
238
246
  /**
239
- * Return `true` when at least one listener is registered for `event`.
240
- */
247
+ * Return `true` when at least one listener is registered for `event`.
248
+ */
241
249
  hasListeners(event: keyof EventMap): boolean;
242
250
  /**
243
- * Return the number of typed listeners for a specific event.
244
- */
251
+ * Return the number of typed listeners for a specific event.
252
+ */
245
253
  listenerCount(event: keyof EventMap): number;
246
254
  /**
247
- * Remove all listeners.
248
- */
255
+ * Remove all listeners.
256
+ */
249
257
  clear(): void;
250
258
  }
251
259
  /**
252
- * Strategy for handling events whose `type` the reducer does not recognise.
253
- *
254
- * - `"warn"` _(default)_ — log a warning and skip the event (state unchanged).
255
- * - `"ignore"` — skip silently (no warning, no error).
256
- * - `"fail"` — throw an error, halting the apply / replay cycle.
257
- * - A **callback** — invoked with the entry; return truthy to mark it as
258
- * handled (no warning), falsy to fall through to the configured fallback.
259
- * @experimental
260
- */
260
+ * Strategy for handling events whose `type` the reducer does not recognise.
261
+ *
262
+ * - `"warn"` _(default)_ — log a warning and skip the event (state unchanged).
263
+ * - `"ignore"` — skip silently (no warning, no error).
264
+ * - `"fail"` — throw an error, halting the apply / replay cycle.
265
+ * - A **callback** — invoked with the entry; return truthy to mark it as
266
+ * handled (no warning), falsy to fall through to the configured fallback.
267
+ * @experimental
268
+ */
261
269
  type UnknownEventHandling = "warn" | "ignore" | "fail" | ((entry: EventLogEntry) => boolean);
262
270
  /**
263
- * Events emitted by the {@link EventSource} runtime.
264
- *
265
- * A `type` (not `interface`) so it satisfies `EventEmitter`'s
266
- * `Record&lt;string, unknown>` constraint — interfaces have no implicit index
267
- * signature and aren't assignable to `Record&lt;string, unknown>`.
268
- * @experimental
269
- */
271
+ * Events emitted by the {@link EventSource} runtime.
272
+ *
273
+ * A `type` (not `interface`) so it satisfies `EventEmitter`'s
274
+ * `Record&lt;string, unknown>` constraint — interfaces have no implicit index
275
+ * signature and aren't assignable to `Record&lt;string, unknown>`.
276
+ * @experimental
277
+ */
270
278
  type EventSourceEvents = {
271
279
  /** Fired (once) after the initial replay completes. */
272
280
  ready: {
@@ -284,111 +292,143 @@ type EventSourceEvents = {
284
292
  };
285
293
  };
286
294
  /**
287
- * A function that reduces an event into a state mutation.
288
- *
289
- * Pure functions are strongly encouraged: given the same event payload
290
- * and state, they must produce the same next state.
291
- * @experimental
292
- */
293
- type EventReducer<S> = (state: S, entry: EventLogEntry) => S;
294
- /**
295
- * Options for constructing an {@link EventSource}.
296
- * @experimental
297
- */
295
+ * Sentinel a reducer can return to EXPLICITLY signal it does not handle a
296
+ * given event's `type` — as opposed to returning the current `state`
297
+ * reference unchanged to represent a legitimate, idempotent no-op for a type
298
+ * it DOES recognise.
299
+ *
300
+ * Reference equality alone can't tell these two cases apart (REPLICA-07): a
301
+ * reducer that intentionally returns `state` for a type it fully understands
302
+ * (e.g. "already applied this event, nothing to do") would otherwise be
303
+ * misclassified as "unhandled" and trigger {@link UnknownEventHandling} — a
304
+ * spurious warning, or worse, a thrown error under `"fail"`. Return `UNHANDLED`
305
+ * only for a `type` your reducer truly does not recognise; every other return
306
+ * (including a `state` returned by reference) is treated as handled.
307
+ *
308
+ * Reducers that always recognise every event they're given (a single
309
+ * always-matching type, or a catch-all) can ignore this entirely.
310
+ * @experimental
311
+ */
312
+ declare const UNHANDLED: unique symbol;
313
+ /**
314
+ * A function that reduces an event into a state mutation.
315
+ *
316
+ * Pure functions are strongly encouraged: given the same event payload
317
+ * and state, they must produce the same next state. Return {@link UNHANDLED}
318
+ * to explicitly mark an event `type` this reducer does not process — see
319
+ * {@link UNHANDLED} for why reference equality against the input `state`
320
+ * cannot be used for this instead.
321
+ * @experimental
322
+ */
323
+ type EventReducer<S> = (state: S, entry: EventLogEntry) => S | typeof UNHANDLED;
324
+ /**
325
+ * Options for constructing an {@link EventSource}.
326
+ * @experimental
327
+ */
298
328
  interface EventSourceOptions {
299
329
  /**
300
- * How to handle events whose `type` is not recognised by the reducer.
301
- * @default "warn"
302
- */
330
+ * Cap this runtime's internal `log` to this many entries (REPLICA-06).
331
+ * `replayFromLog` copies every entry it replays from the source log into
332
+ * `this.log` too — a second, uncapped copy of the same history — so a
333
+ * long-lived `EventSource` fed by repeated replay accumulates entries in
334
+ * both places forever without a cap.
335
+ *
336
+ * `undefined` (the default) preserves unbounded retention.
337
+ */
338
+ maxLogEntries?: number;
339
+ /**
340
+ * How to handle events whose `type` is not recognised by the reducer.
341
+ * @default "warn"
342
+ */
303
343
  unknownEventHandling?: UnknownEventHandling;
304
344
  }
305
345
  /**
306
- * Event-sourcing runtime that maintains a derived state by replaying an
307
- * append-only {@link EventLog}.
308
- *
309
- * Usage:
310
- * ```ts
311
- * const source = new EventSource(initialState, myReducer);
312
- * await source.replayFromLog(existingLog);
313
- *
314
- * // Later, when a new event arrives:
315
- * const entry = source.applyEvent("user-created", { id: "1", name: "alice" });
316
- * console.log(source.state); // updated state
317
- * ```
318
- * @experimental
319
- */
346
+ * Event-sourcing runtime that maintains a derived state by replaying an
347
+ * append-only {@link EventLog}.
348
+ *
349
+ * Usage:
350
+ * ```ts
351
+ * const source = new EventSource(initialState, myReducer);
352
+ * await source.replayFromLog(existingLog);
353
+ *
354
+ * // Later, when a new event arrives:
355
+ * const entry = source.applyEvent("user-created", { id: "1", name: "alice" });
356
+ * console.log(source.state); // updated state
357
+ * ```
358
+ * @experimental
359
+ */
320
360
  declare class EventSource<S extends Record<string, unknown> = Record<string, unknown>> {
321
361
  #private;
322
362
  readonly emitter: EventEmitter<EventSourceEvents>;
323
363
  readonly log: EventLog;
324
364
  constructor(initialState: S, reducer: EventReducer<S>, options?: EventSourceOptions);
325
365
  /**
326
- * The current derived state. Read-only snapshot; mutate through events.
327
- */
366
+ * The current derived state. Read-only snapshot; mutate through events.
367
+ */
328
368
  get state(): Readonly<S>;
329
369
  /**
330
- * Whether the initial replay from an existing log has completed.
331
- */
370
+ * Whether the initial replay from an existing log has completed.
371
+ */
332
372
  get replayed(): boolean;
333
373
  /**
334
- * Append a new event to the log and apply it to the current state.
335
- *
336
- * Accepts either an {@link InputEvent} (e.g. from a `defineEvents` factory)
337
- * or the traditional `(type, payload)` pair.
338
- * @returns The newly created log entry (with its assigned `seq`).
339
- */
374
+ * Append a new event to the log and apply it to the current state.
375
+ *
376
+ * Accepts either an {@link InputEvent} (e.g. from a `defineEvents` factory)
377
+ * or the traditional `(type, payload)` pair.
378
+ * @returns The newly created log entry (with its assigned `seq`).
379
+ */
340
380
  applyEvent(event: InputEvent, options?: AppendOptions): EventLogEntry;
341
381
  applyEvent(type: string, payload: unknown, options?: AppendOptions): EventLogEntry;
342
382
  /**
343
- * Replay all entries from an existing {@link EventLog} to bootstrap
344
- * the current state.
345
- *
346
- * Idempotent across calls: only source entries past the `#lastAppliedSeq`
347
- * watermark are applied, so re-invoking picks up just the new entries.
348
- * @param log The external log to replay from.
349
- */
383
+ * Replay all entries from an existing {@link EventLog} to bootstrap
384
+ * the current state.
385
+ *
386
+ * Idempotent across calls: only source entries past the `#lastAppliedSeq`
387
+ * watermark are applied, so re-invoking picks up just the new entries.
388
+ * @param log The external log to replay from.
389
+ */
350
390
  replayFromLog(log: EventLog): void;
351
391
  /**
352
- * Reset the runtime to a base state, optionally resuming from a watermark.
353
- *
354
- * Useful after loading a snapshot from the DO: pass the snapshot's state as
355
- * `initialState` and its highest applied source `seq` as `resumeFromSeq`, so
356
- * the next {@link replayFromLog} applies ONLY the events after the snapshot
357
- * (`getSince(resumeFromSeq + 1)`) rather than replaying the whole log on top
358
- * of the snapshot — which would double-apply non-idempotent reducers.
359
- *
360
- * Omit `resumeFromSeq` (default `-1`) for a full reset that replays from the
361
- * beginning.
362
- * @param initialState The base state to reset to (e.g. a loaded snapshot).
363
- * @param resumeFromSeq Highest source `seq` already baked into `initialState`, or `-1` to replay all.
364
- */
392
+ * Reset the runtime to a base state, optionally resuming from a watermark.
393
+ *
394
+ * Useful after loading a snapshot from the DO: pass the snapshot's state as
395
+ * `initialState` and its highest applied source `seq` as `resumeFromSeq`, so
396
+ * the next {@link replayFromLog} applies ONLY the events after the snapshot
397
+ * (`getSince(resumeFromSeq + 1)`) rather than replaying the whole log on top
398
+ * of the snapshot — which would double-apply non-idempotent reducers.
399
+ *
400
+ * Omit `resumeFromSeq` (default `-1`) for a full reset that replays from the
401
+ * beginning.
402
+ * @param initialState The base state to reset to (e.g. a loaded snapshot).
403
+ * @param resumeFromSeq Highest source `seq` already baked into `initialState`, or `-1` to replay all.
404
+ */
365
405
  reset(initialState: S, resumeFromSeq?: number): void;
366
406
  /**
367
- * Return an async generator that yields every event as it is applied,
368
- * starting from the events currently in the log and continuing with
369
- * every future `applyEvent` / `replayFromLog` call.
370
- *
371
- * The generator runs indefinitely — it never returns. Callers should
372
- * break out of the `for await` loop or use an `AbortSignal` to stop.
373
- * @example
374
- * ```ts
375
- * for await (const entry of source.events()) {
376
- * console.log("event applied:", entry);
377
- * }
378
- * ```
379
- */
407
+ * Return an async generator that yields every event as it is applied,
408
+ * starting from the events currently in the log and continuing with
409
+ * every future `applyEvent` / `replayFromLog` call.
410
+ *
411
+ * The generator runs indefinitely — it never returns. Callers should
412
+ * break out of the `for await` loop or use an `AbortSignal` to stop.
413
+ * @example
414
+ * ```ts
415
+ * for await (const entry of source.events()) {
416
+ * console.log("event applied:", entry);
417
+ * }
418
+ * ```
419
+ */
380
420
  events(signal?: AbortSignal): AsyncGenerator<EventLogEntry>;
381
421
  }
382
422
  /**
383
- * Interface for persisting event-sourced state snapshots.
384
- *
385
- * In a Lunora app the primary implementation is backed by the
386
- * SnapshotDO (a Durable Object) on the server side. On the client
387
- * the {@link InMemorySnapshotStore} is used for the offline-first
388
- * local mirror, while a production client would implement this
389
- * over IndexedDB or OPFS.
390
- * @experimental
391
- */
423
+ * Interface for persisting event-sourced state snapshots.
424
+ *
425
+ * In a Lunora app the primary implementation is backed by the
426
+ * SnapshotDO (a Durable Object) on the server side. On the client
427
+ * the {@link InMemorySnapshotStore} is used for the offline-first
428
+ * local mirror, while a production client would implement this
429
+ * over IndexedDB or OPFS.
430
+ * @experimental
431
+ */
392
432
  interface SnapshotStore {
393
433
  /** Delete all snapshots. */
394
434
  clear: () => Promise<void>;
@@ -402,11 +442,11 @@ interface SnapshotStore {
402
442
  save: (key: string, snapshot: unknown) => Promise<void>;
403
443
  }
404
444
  /**
405
- * In-memory snapshot store. Useful for testing and for the local
406
- * offline-first mirror where persistence is handled at a higher
407
- * layer (IndexedDB adapter).
408
- * @experimental
409
- */
445
+ * In-memory snapshot store. Useful for testing and for the local
446
+ * offline-first mirror where persistence is handled at a higher
447
+ * layer (IndexedDB adapter).
448
+ * @experimental
449
+ */
410
450
  declare class InMemorySnapshotStore implements SnapshotStore {
411
451
  #private;
412
452
  save(key: string, snapshot: unknown): Promise<void>;
@@ -416,23 +456,23 @@ declare class InMemorySnapshotStore implements SnapshotStore {
416
456
  clear(): Promise<void>;
417
457
  }
418
458
  /**
419
- * A function that reduces an event entry into a state mutation.
420
- *
421
- * Pure functions are strongly encouraged: given the same event and state,
422
- * they must produce the same next state for deterministic replay.
423
- * @experimental
424
- */
459
+ * A function that reduces an event entry into a state mutation.
460
+ *
461
+ * Pure functions are strongly encouraged: given the same event and state,
462
+ * they must produce the same next state for deterministic replay.
463
+ * @experimental
464
+ */
425
465
  type MaterializerReducer<S> = (state: S, entry: EventLogEntry) => S;
426
466
  /**
427
- * Options for defining a single materializer.
428
- * @experimental
429
- */
467
+ * Options for defining a single materializer.
468
+ * @experimental
469
+ */
430
470
  interface MaterializerDef<S> {
431
471
  /**
432
- * Reducer invoked for every event in the log.
433
- *
434
- * Return the current state unchanged to skip the event.
435
- */
472
+ * Reducer invoked for every event in the log.
473
+ *
474
+ * Return the current state unchanged to skip the event.
475
+ */
436
476
  handle: MaterializerReducer<S>;
437
477
  /** Factory for the initial (empty) state. */
438
478
  initial: () => S;
@@ -440,9 +480,9 @@ interface MaterializerDef<S> {
440
480
  readonly name: string;
441
481
  }
442
482
  /**
443
- * A constructed materializer ready to be used with a {@link MaterializerRuntime}.
444
- * @experimental
445
- */
483
+ * A constructed materializer ready to be used with a {@link MaterializerRuntime}.
484
+ * @experimental
485
+ */
446
486
  interface Materializer<S> {
447
487
  /** Apply a single event entry through the reducer. */
448
488
  apply: (entry: EventLogEntry) => void;
@@ -455,141 +495,162 @@ interface Materializer<S> {
455
495
  readonly state: Readonly<S>;
456
496
  }
457
497
  /**
458
- * Declare a materializer — a named reducer that derives state from events.
459
- *
460
- * The returned {@link Materializer} object can be used standalone or passed
461
- * to a {@link MaterializerRuntime} for automatic log subscription.
462
- * @experimental
463
- */
498
+ * Declare a materializer — a named reducer that derives state from events.
499
+ *
500
+ * The returned {@link Materializer} object can be used standalone or passed
501
+ * to a {@link MaterializerRuntime} for automatic log subscription.
502
+ * @experimental
503
+ */
464
504
  declare const defineMaterializer: <S>(definition: MaterializerDef<S>) => Materializer<S>;
465
505
  /**
466
- * A materializer of any state shape. The {@link MaterializerRuntime} holds a
467
- * heterogeneous collection and only ever calls `apply(entry)` / `setState(...)`
468
- * (with cast values) / reads `def.name` — it never needs the concrete state
469
- * type. `Materializer&lt;unknown>` won't do: `setState(state: S)` makes
470
- * `Materializer&lt;S>` invariant in `S`, so `Materializer&lt;number>` isn't assignable
471
- * to `Materializer&lt;unknown>`. Erasing the type param is the idiomatic fix.
472
- */
506
+ * A materializer of any state shape. The {@link MaterializerRuntime} holds a
507
+ * heterogeneous collection and only ever calls `apply(entry)` / `setState(...)`
508
+ * (with cast values) / reads `def.name` — it never needs the concrete state
509
+ * type. `Materializer&lt;unknown>` won't do: `setState(state: S)` makes
510
+ * `Materializer&lt;S>` invariant in `S`, so `Materializer&lt;number>` isn't assignable
511
+ * to `Materializer&lt;unknown>`. Erasing the type param is the idiomatic fix.
512
+ */
473
513
  type AnyMaterializer = Materializer<any>;
474
514
  /**
475
- * Options for constructing a {@link MaterializerRuntime}.
476
- * @experimental
477
- */
515
+ * Options for constructing a {@link MaterializerRuntime}.
516
+ * @experimental
517
+ */
478
518
  interface MaterializerRuntimeOptions {
479
519
  /**
480
- * Optional EventLogDO client for persistent event log integration.
481
- *
482
- * When provided, the runtime can bootstrap from the DO on startup
483
- * (recover from snapshots → catch up via `getSince`) and append
484
- * new events through the DO automatically.
485
- */
520
+ * Optional EventLogDO client for persistent event log integration.
521
+ *
522
+ * When provided, the runtime can bootstrap from the DO on startup
523
+ * (recover from snapshots → catch up via `getSince`) and append
524
+ * new events through the DO automatically.
525
+ */
486
526
  doClient?: EventLogDOClient;
487
527
  /** Optional snapshot store for persisting/recovering materialized state. */
488
528
  snapshotStore?: SnapshotStore;
489
529
  /**
490
- * How to handle events whose type no materializer handles.
491
- * @default "warn"
492
- */
530
+ * How to handle events whose type no materializer handles.
531
+ * @default "warn"
532
+ */
493
533
  unknownEventHandling?: UnknownEventHandling;
494
534
  }
495
535
  /**
496
- * Runtime that drives one or more materializers from an event log.
497
- *
498
- * Handles:
499
- * - Replaying the full log on startup
500
- * - Applying new events as they arrive
501
- * - Periodic snapshot persistence
502
- * - Recovery from snapshots (replay only what's missing)
503
- * @experimental
504
- */
536
+ * Runtime that drives one or more materializers from an event log.
537
+ *
538
+ * Handles:
539
+ * - Replaying the full log on startup
540
+ * - Applying new events as they arrive
541
+ * - Periodic snapshot persistence
542
+ * - Recovery from snapshots (replay only what's missing)
543
+ * @experimental
544
+ */
505
545
  declare class MaterializerRuntime {
506
546
  #private;
507
547
  constructor(materializers: AnyMaterializer[], options?: MaterializerRuntimeOptions);
508
548
  /**
509
- * The sequence number of the last event applied to all materializers.
510
- */
549
+ * The lowest per-materializer watermark — the seq of the next event that
550
+ * at least one materializer has not yet applied. `0` when there are no
551
+ * materializers.
552
+ */
511
553
  get appliedSeq(): number;
512
554
  /**
513
- * Replay a batch of entries through all materializers.
514
- *
515
- * Entries with `seq < this.appliedSeq` are silently skipped (idempotent).
516
- * @returns The number of entries actually applied.
517
- */
555
+ * Replay a batch of entries, applying each entry only to the
556
+ * materializers whose own watermark is behind it — a materializer at or
557
+ * past an entry's seq (e.g. recovered from a snapshot, or already caught
558
+ * up) skips it, so no materializer ever double-applies an event.
559
+ * @returns The number of entries applied to at least one materializer.
560
+ */
518
561
  applyEntries(entries: ReadonlyArray<EventLogEntry>): number;
519
562
  /**
520
- * Attempt to recover materialized state from a snapshot store.
521
- *
522
- * When a snapshot is found for a materializer, its state is restored
523
- * and the snapshot's watermark (`appliedSeq`) is returned so the caller
524
- * can skip replaying entries up to that point.
525
- * @returns The highest `appliedSeq` across all recovered snapshots, or `0`.
526
- */
563
+ * Attempt to recover materialized state from a snapshot store.
564
+ *
565
+ * When a snapshot is found for a materializer, its state AND its own
566
+ * watermark are restored from that snapshot. A materializer with no
567
+ * snapshot keeps its current watermark (`0` for a fresh runtime) — it
568
+ * does NOT inherit another materializer's watermark, so it still catches
569
+ * up from the very beginning (REPLICA-04: previously a shared watermark
570
+ * was bumped to the MAX across snapshots, permanently skipping events 0..N
571
+ * for any un-snapshotted or lagging materializer).
572
+ * @returns The highest snapshot `appliedSeq` across all materializers, or
573
+ * `0` — kept for backward compatibility; callers that need the fetch
574
+ * watermark for catch-up should use the per-materializer minimum instead
575
+ * (see `initialize`).
576
+ */
527
577
  recoverFromSnapshots(): Promise<number>;
528
578
  /**
529
- * Persist the current state of all materializers as snapshots.
530
- */
579
+ * Persist the current state of all materializers as snapshots, each
580
+ * tagged with ITS OWN watermark (not a shared one).
581
+ */
531
582
  persistSnapshots(): Promise<void>;
532
583
  /**
533
- * Bootstrap the runtime from the EventLogDO.
534
- *
535
- * 1. Recover materialized state from snapshots (if a snapshotStore is
536
- * configured).
537
- * 2. Fetch all entries since the recovered watermark from the DO.
538
- * 3. Apply them through the materializers.
539
- *
540
- * Call this once on startup / after the DO binding is available.
541
- * @returns The number of entries applied during catch-up.
542
- */
584
+ * Bootstrap the runtime from the EventLogDO.
585
+ *
586
+ * 1. Recover materialized state from snapshots (if a snapshotStore is
587
+ * configured).
588
+ * 2. Fetch all entries since the MINIMUM per-materializer watermark from
589
+ * the DO — not the maximum — so a materializer with no snapshot (or a
590
+ * lower one) still receives every event it hasn't seen (REPLICA-04).
591
+ * 3. Apply them through the materializers; `applyEntries` skips each
592
+ * entry for any materializer already past it, so nothing is double-applied.
593
+ *
594
+ * Call this once on startup / after the DO binding is available.
595
+ * @returns The number of entries applied during catch-up.
596
+ */
543
597
  initialize(): Promise<number>;
544
598
  /**
545
- * Append an event to the EventLogDO and apply it through all
546
- * materializers.
547
- *
548
- * This is a convenience over calling `doClient.append(...)` +
549
- * `runtime.applyEntries(...)` yourself — it persists the event
550
- * **then** applies the returned entry (with its assigned seq).
551
- * @returns The persisted entry with its DO-assigned `seq`.
552
- */
599
+ * Append an event to the EventLogDO and apply it through all
600
+ * materializers.
601
+ *
602
+ * This is a convenience over calling `doClient.append(...)` +
603
+ * `runtime.applyEntries(...)` yourself — it persists the event
604
+ * **then** applies the returned entry (with its assigned seq).
605
+ * @returns The persisted entry with its DO-assigned `seq`.
606
+ */
553
607
  appendEvent(input: AppendEventInput): Promise<EventLogEntry>;
554
608
  /**
555
- * Reset all materializers to their initial state and clear snapshots.
556
- */
609
+ * Reset all materializers to their initial state and clear snapshots.
610
+ */
557
611
  reset(): void;
558
612
  /**
559
- * The list of registered materializers.
560
- */
613
+ * The list of registered materializers.
614
+ */
561
615
  get materializers(): ReadonlyArray<Materializer<unknown>>;
562
616
  }
563
617
  /**
564
- * Apply a {@link TableDiff} to the given SQLite database by translating
565
- * each row change into an INSERT, UPDATE, or DELETE statement.
566
- *
567
- * All statements are wrapped in a single transaction.
568
- * @param database SQLite adapter the statements run against.
569
- * @param diff The table diff to apply.
570
- * @param pkColumn Primary key column for DELETE/UPDATE (default `"id"`).
571
- * @experimental
572
- */
618
+ * Apply a {@link TableDiff} to the given SQLite database by translating
619
+ * each row change into an INSERT, UPDATE, or DELETE statement.
620
+ *
621
+ * All statements are wrapped in a single transaction.
622
+ * @param database SQLite adapter the statements run against.
623
+ * @param diff The table diff to apply.
624
+ * @param pkColumn Primary key column for DELETE/UPDATE (default `"id"`).
625
+ * @experimental
626
+ */
573
627
  declare const applyDiffToDatabase: (database: SqliteAdapter, diff: TableDiff, pkColumn?: string) => void;
574
628
  /**
575
- * Apply multiple diffs **in order** within a single transaction.
576
- *
577
- * Each diff uses `"id"` as the primary key column. For tables with a custom
578
- * PK, use {@link applyDiffToDatabase} per-diff and pass the PK explicitly.
579
- * @experimental
580
- */
629
+ * Apply multiple diffs **in order** within a single transaction.
630
+ *
631
+ * Each diff uses `"id"` as the primary key column. For tables with a custom
632
+ * PK, use {@link applyDiffToDatabase} per-diff and pass the PK explicitly.
633
+ * @experimental
634
+ */
581
635
  declare const applyDiffsToDatabase: (database: SqliteAdapter, diffs: ReadonlyArray<TableDiff>) => void;
582
636
  interface EventLogDOState {
583
637
  storage: {
584
638
  sql: {
585
639
  exec: (query: string, ...params: unknown[]) => unknown;
586
640
  };
641
+ /**
642
+ * The DO platform's native atomic-transaction primitive (async;
643
+ * commits on resolve, rolls back on throw/reject). Test doubles that
644
+ * omit it fall back to a bare (non-transactional) call — see
645
+ * `#handleAppend`.
646
+ */
647
+ transaction?: <T>(closure: () => Promise<T> | T) => Promise<T>;
587
648
  };
588
649
  }
589
650
  /**
590
- * `EventLogDO` is part of the experimental `@lunora/replica` API and may change without a major version bump.
591
- * @experimental
592
- */
651
+ * `EventLogDO` is part of the experimental `@lunora/replica` API and may change without a major version bump.
652
+ * @experimental
653
+ */
593
654
  declare class EventLogDO {
594
655
  #private;
595
656
  protected state: EventLogDOState;
@@ -598,10 +659,10 @@ declare class EventLogDO {
598
659
  fetch(request: Request): Promise<Response>;
599
660
  }
600
661
  /**
601
- * `next()` advances the middleware chain. Called with no argument it forwards
602
- * the current context unchanged; called with `{ ctx }` it shallow-merges the
603
- * extension, and the result type reflects the widened context.
604
- */
662
+ * `next()` advances the middleware chain. Called with no argument it forwards
663
+ * the current context unchanged; called with `{ ctx }` it shallow-merges the
664
+ * extension, and the result type reflects the widened context.
665
+ */
605
666
  interface MiddlewareNext<ContextIn> {
606
667
  (): Promise<ContextIn>;
607
668
  <Extension extends Record<string, unknown>>(options: {
@@ -609,46 +670,45 @@ interface MiddlewareNext<ContextIn> {
609
670
  }): Promise<ContextIn & Extension>;
610
671
  }
611
672
  /**
612
- * A middleware receives the current context and a `next` continuation. Its
613
- * return type becomes the builder's new context, so `return next({ ctx })`
614
- * propagates the extension into every downstream `.use()` and the handler.
615
- */
673
+ * A middleware receives the current context and a `next` continuation. Its
674
+ * return type becomes the builder's new context, so `return next({ ctx })`
675
+ * propagates the extension into every downstream `.use()` and the handler.
676
+ */
616
677
  type Middleware<ContextIn, ContextOut> = (options: {
617
678
  ctx: ContextIn;
618
679
  next: MiddlewareNext<ContextIn>;
619
680
  }) => ContextOut | Promise<ContextOut>;
620
- /** Options accepted by `initLunora.dataModel&lt;DM>().create(...)`. Reserved for transformer/error-formatter wiring. */
621
- /**
622
- * The per-request `ctx.events` facade that {@link eventsContext} attaches.
623
- *
624
- * Each method delegates to the corresponding {@link EventLogDOClient} method,
625
- * so handlers never need to import or reference the DO client directly.
626
- * @experimental
627
- */
681
+ /**
682
+ * The per-request `ctx.events` facade that {@link eventsContext} attaches.
683
+ *
684
+ * Each method delegates to the corresponding {@link EventLogDOClient} method,
685
+ * so handlers never need to import or reference the DO client directly.
686
+ * @experimental
687
+ */
628
688
  interface EventsFacade {
629
689
  /**
630
- * Append one or more events to the log.
631
- * @returns The persisted entries with their assigned `seq` numbers.
632
- */
690
+ * Append one or more events to the log.
691
+ * @returns The persisted entries with their assigned `seq` numbers.
692
+ */
633
693
  append: (events: {
634
694
  payload: unknown;
635
695
  timestamp?: number;
636
696
  type: string;
637
697
  }[]) => Promise<EventLogEntry[]>;
638
698
  /**
639
- * Fetch a paginated range of entries.
640
- * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
641
- * page exists.
642
- */
699
+ * Fetch a paginated range of entries.
700
+ * @returns `{ entries, hasMore }` — `hasMore` is `true` when another
701
+ * page exists.
702
+ */
643
703
  getRange: (fromSeq: number, limit?: number) => Promise<{
644
704
  entries: EventLogEntry[];
645
705
  hasMore: boolean;
646
706
  }>;
647
707
  /**
648
- * Fetch all entries with `seq >= sinceSeq`.
649
- *
650
- * Pass `sinceSeq = 0` to fetch the entire log.
651
- */
708
+ * Fetch all entries with `seq >= sinceSeq`.
709
+ *
710
+ * Pass `sinceSeq = 0` to fetch the entire log.
711
+ */
652
712
  getSince: (sinceSeq: number) => Promise<EventLogEntry[]>;
653
713
  /** Return the total number of entries currently in the log. */
654
714
  getSize: () => Promise<number>;
@@ -659,47 +719,47 @@ interface EventsFacade {
659
719
  }>;
660
720
  }
661
721
  /**
662
- * The context shape produced by {@link eventsContext}.
663
- * @experimental
664
- */
722
+ * The context shape produced by {@link eventsContext}.
723
+ * @experimental
724
+ */
665
725
  interface EventsContextOutput {
666
726
  /** Typed event log facade backed by an {@link EventLogDOClient}. */
667
727
  readonly events: EventsFacade;
668
728
  }
669
729
  /**
670
- * Create a middleware that attaches a typed `ctx.events` facade backed by
671
- * the given {@link EventLogDOClient}.
672
- *
673
- * The facade surfaces `append`, `getSince`, `getRange`, `getSize`, and
674
- * `getState` — every method the DO client exposes — so handlers can read
675
- * and write the event log without reaching for the DO stub directly.
676
- *
677
- * The middleware is unopinionated about which context it extends — it works
678
- * with `MutationCtx`, `ActionCtx`, or `QueryCtx` equally.
679
- * @param client A configured {@link EventLogDOClient} instance.
680
- * @returns A Lunora middleware that injects `ctx.events`.
681
- *
682
- * ```ts
683
- * const client = new EventLogDOClient({
684
- * fetch: (req) => env.EVENTS.get(id).fetch(req),
685
- * });
686
- *
687
- * export const logEvent = mutation
688
- * .use(eventsContext(client))
689
- * .mutation(async ({ ctx, args }) => {
690
- * const [entry] = await ctx.events.append([{ type: "order.placed", payload: args }]);
691
- * return entry;
692
- * });
693
- * ```
694
- * @experimental
695
- */
730
+ * Create a middleware that attaches a typed `ctx.events` facade backed by
731
+ * the given {@link EventLogDOClient}.
732
+ *
733
+ * The facade surfaces `append`, `getSince`, `getRange`, `getSize`, and
734
+ * `getState` — every method the DO client exposes — so handlers can read
735
+ * and write the event log without reaching for the DO stub directly.
736
+ *
737
+ * The middleware is unopinionated about which context it extends — it works
738
+ * with `MutationCtx`, `ActionCtx`, or `QueryCtx` equally.
739
+ * @param client A configured {@link EventLogDOClient} instance.
740
+ * @returns A Lunora middleware that injects `ctx.events`.
741
+ *
742
+ * ```ts
743
+ * const client = new EventLogDOClient({
744
+ * fetch: (req) => env.EVENTS.get(id).fetch(req),
745
+ * });
746
+ *
747
+ * export const logEvent = mutation
748
+ * .use(eventsContext(client))
749
+ * .mutation(async ({ ctx, args }) => {
750
+ * const [entry] = await ctx.events.append([{ type: "order.placed", payload: args }]);
751
+ * return entry;
752
+ * });
753
+ * ```
754
+ * @experimental
755
+ */
696
756
  declare const eventsContext: <Context>(client: EventLogDOClient) => Middleware<Context, Context & EventsContextOutput>;
697
757
  /**
698
- * A dependency-light subscription sink interface that mirrors what
699
- * `LunoraClient.subscribe` expects, so the mirror helper doesn't
700
- * need to import `@lunora/client`.
701
- * @experimental
702
- */
758
+ * A dependency-light subscription sink interface that mirrors what
759
+ * `LunoraClient.subscribe` expects, so the mirror helper doesn't
760
+ * need to import `@lunora/client`.
761
+ * @experimental
762
+ */
703
763
  interface SubscriptionClient {
704
764
  subscribe: (functionRef: {
705
765
  __lunoraRef: string;
@@ -708,203 +768,203 @@ interface SubscriptionClient {
708
768
  }) => () => void;
709
769
  }
710
770
  /**
711
- * Subscribe a Lunora-query to the local mirror so every server push
712
- * is applied to the local SQLite store.
713
- *
714
- * Each frame from a Lunora live query is the FULL current result set, so the
715
- * callback treats it as a snapshot: it upserts every row present and emits a
716
- * `delete` for any id that was mirrored on a previous frame but is absent now —
717
- * otherwise rows that drop out of the server result would linger stale in the
718
- * local mirror. Rows are keyed by their `id` field (the mirror's default primary
719
- * key); a row without an `id` can't be reconciled on removal, and — because the
720
- * mirror table's `id` column is `NOT NULL` — will fail the insert.
721
- *
722
- * The mirror table name is derived from the function ref alone (not `args`), so
723
- * do NOT mirror two subscriptions to the same function with different `args`
724
- * into the same mirror: they'd share one table and the snapshot-delete pass of
725
- * one could remove rows still live in the other.
726
- *
727
- * Call the returned unsubscribe function to tear down both the client
728
- * subscription and future mirror writes.
729
- * @example
730
- * ```ts
731
- * const unsub = subscribeToMirror(client, mirror, api.todos.list, { userId });
732
- * // Later:
733
- * unsub();
734
- * ```
735
- * @experimental
736
- */
771
+ * Subscribe a Lunora-query to the local mirror so every server push
772
+ * is applied to the local SQLite store.
773
+ *
774
+ * Each frame from a Lunora live query is the FULL current result set, so the
775
+ * callback treats it as a snapshot: it upserts every row present and emits a
776
+ * `delete` for any id that was mirrored on a previous frame but is absent now —
777
+ * otherwise rows that drop out of the server result would linger stale in the
778
+ * local mirror. Rows are keyed by their `id` field (the mirror's default primary
779
+ * key); a row without an `id` can't be reconciled on removal, and — because the
780
+ * mirror table's `id` column is `NOT NULL` — will fail the insert.
781
+ *
782
+ * The mirror table name is derived from the function ref alone (not `args`), so
783
+ * do NOT mirror two subscriptions to the same function with different `args`
784
+ * into the same mirror: they'd share one table and the snapshot-delete pass of
785
+ * one could remove rows still live in the other.
786
+ *
787
+ * Call the returned unsubscribe function to tear down both the client
788
+ * subscription and future mirror writes.
789
+ * @example
790
+ * ```ts
791
+ * const unsub = subscribeToMirror(client, mirror, api.todos.list, { userId });
792
+ * // Later:
793
+ * unsub();
794
+ * ```
795
+ * @experimental
796
+ */
737
797
  declare const subscribeToMirror: (client: SubscriptionClient, mirror: LocalMirror, functionRef: {
738
798
  __lunoraRef: string;
739
799
  }, args: Record<string, unknown>, shardKey?: string) => (() => void);
740
800
  /**
741
- * Callback signature for state-change subscriptions.
742
- * @experimental
743
- */
801
+ * Callback signature for state-change subscriptions.
802
+ * @experimental
803
+ */
744
804
  type StateChangeCallback = (state: Readonly<Record<string, unknown>>) => void;
745
805
  /**
746
- * Callback signature for event-type subscriptions.
747
- * @experimental
748
- */
806
+ * Callback signature for event-type subscriptions.
807
+ * @experimental
808
+ */
749
809
  type EventCallback = (entry: EventLogEntry) => void;
750
810
  /**
751
- * Manages subscriptions to state changes and individual event types
752
- * for the event-sourcing runtime.
753
- *
754
- * Each subscription returns an unsubscribe function — the caller is
755
- * expected to call it during cleanup (e.g. in a React `useEffect`
756
- * return or a Svelte `onDestroy`).
757
- * @example
758
- * ```ts
759
- * const subs = new SubscriptionManager();
760
- *
761
- * // Subscribe to every state change
762
- * const unsub1 = subs.onStateChange((state) => console.log("new state", state));
763
- *
764
- * // Subscribe to a specific event type
765
- * const unsub2 = subs.onEvent("user-created", (entry) => console.log("user created", entry.payload));
766
- *
767
- * // Later, when state or events arrive:
768
- * subs.notifyState({ users: [] });
769
- * subs.notifyEvent({ seq: 1, type: "user-created", payload: { id: "1" }, timestamp: 100 });
770
- *
771
- * // Cleanup
772
- * unsub1();
773
- * unsub2();
774
- * ```
775
- * @experimental
776
- */
811
+ * Manages subscriptions to state changes and individual event types
812
+ * for the event-sourcing runtime.
813
+ *
814
+ * Each subscription returns an unsubscribe function — the caller is
815
+ * expected to call it during cleanup (e.g. in a React `useEffect`
816
+ * return or a Svelte `onDestroy`).
817
+ * @example
818
+ * ```ts
819
+ * const subs = new SubscriptionManager();
820
+ *
821
+ * // Subscribe to every state change
822
+ * const unsub1 = subs.onStateChange((state) => console.log("new state", state));
823
+ *
824
+ * // Subscribe to a specific event type
825
+ * const unsub2 = subs.onEvent("user-created", (entry) => console.log("user created", entry.payload));
826
+ *
827
+ * // Later, when state or events arrive:
828
+ * subs.notifyState({ users: [] });
829
+ * subs.notifyEvent({ seq: 1, type: "user-created", payload: { id: "1" }, timestamp: 100 });
830
+ *
831
+ * // Cleanup
832
+ * unsub1();
833
+ * unsub2();
834
+ * ```
835
+ * @experimental
836
+ */
777
837
  declare class SubscriptionManager {
778
838
  #private;
779
839
  /**
780
- * Subscribe to every state change emitted by the event source.
781
- * @returns Unsubscribe function.
782
- */
840
+ * Subscribe to every state change emitted by the event source.
841
+ * @returns Unsubscribe function.
842
+ */
783
843
  onStateChange(callback: StateChangeCallback): () => void;
784
844
  /**
785
- * Subscribe to a specific event type.
786
- * @param eventType The event type to listen for (matches `entry.type`).
787
- * @param callback Invoked with each matching entry.
788
- * @returns Unsubscribe function.
789
- */
845
+ * Subscribe to a specific event type.
846
+ * @param eventType The event type to listen for (matches `entry.type`).
847
+ * @param callback Invoked with each matching entry.
848
+ * @returns Unsubscribe function.
849
+ */
790
850
  onEvent(eventType: string, callback: EventCallback): () => void;
791
851
  /**
792
- * Notify all state-change subscribers with the current state.
793
- */
852
+ * Notify all state-change subscribers with the current state.
853
+ */
794
854
  notifyState(state: Readonly<Record<string, unknown>>): void;
795
855
  /**
796
- * Notify event-type subscribers whose `eventType` matches.
797
- */
856
+ * Notify event-type subscribers whose `eventType` matches.
857
+ */
798
858
  notifyEvent(entry: EventLogEntry): void;
799
859
  /**
800
- * Return the total number of active subscriptions.
801
- */
860
+ * Return the total number of active subscriptions.
861
+ */
802
862
  get size(): number;
803
863
  /**
804
- * Remove all subscriptions.
805
- */
864
+ * Remove all subscriptions.
865
+ */
806
866
  clear(): void;
807
867
  }
808
868
  /**
809
- * Options for constructing an {@link EventsSync}.
810
- * @experimental
811
- */
869
+ * Options for constructing an {@link EventsSync}.
870
+ * @experimental
871
+ */
812
872
  interface EventsSyncOptions {
813
873
  /**
814
- * Replay a batch of events through the derived-state machine.
815
- *
816
- * Called with every batch of new events fetched from the log. The
817
- * consumer should feed these events into their state machine
818
- * (e.g. an {@link import("@lunora/replica").EventSource | EventSource})
819
- * so that the machine's state reflects the latest log position.
820
- */
874
+ * Replay a batch of events through the derived-state machine.
875
+ *
876
+ * Called with every batch of new events fetched from the log. The
877
+ * consumer should feed these events into their state machine
878
+ * (e.g. an {@link import("@lunora/replica").EventSource | EventSource})
879
+ * so that the machine's state reflects the latest log position.
880
+ */
821
881
  applyEvents: (events: ReadonlyArray<EventLogEntry>) => void;
822
882
  /**
823
- * Fetch all events whose `seq >= sinceSeq`.
824
- *
825
- * In a server-side context, this typically wraps
826
- * {@link import("@lunora/replica").EventLogDOClient.getSince |
827
- * EventLogDOClient.getSince()}.
828
- * In a client context it could call a Lunora action that proxies to the
829
- * event log, or read from an IndexedDB cache.
830
- *
831
- * Return an empty array when there are no new events.
832
- */
883
+ * Fetch all events whose `seq >= sinceSeq`.
884
+ *
885
+ * In a server-side context, this typically wraps
886
+ * {@link import("@lunora/replica").EventLogDOClient.getSince |
887
+ * EventLogDOClient.getSince()}.
888
+ * In a client context it could call a Lunora action that proxies to the
889
+ * event log, or read from an IndexedDB cache.
890
+ *
891
+ * Return an empty array when there are no new events.
892
+ */
833
893
  fetchEventsSince: (sinceSeq: number) => Promise<ReadonlyArray<EventLogEntry>>;
834
894
  /**
835
- * Produce {@link TableDiff | TableDiffs} from the current derived state.
836
- *
837
- * Called after every batch of events has been applied. The consumer
838
- * compares the state _before_ and _after_ the batch and returns the
839
- * diffs needed to bring the LocalMirror up to date.
840
- *
841
- * Return an empty array when there are no changes to push to the mirror.
842
- */
895
+ * Produce {@link TableDiff | TableDiffs} from the current derived state.
896
+ *
897
+ * Called after every batch of events has been applied. The consumer
898
+ * compares the state _before_ and _after_ the batch and returns the
899
+ * diffs needed to bring the LocalMirror up to date.
900
+ *
901
+ * Return an empty array when there are no changes to push to the mirror.
902
+ */
843
903
  getTableDiffs: () => TableDiff[];
844
904
  /**
845
- * The local SQLite mirror to apply diffs to.
846
- */
905
+ * The local SQLite mirror to apply diffs to.
906
+ */
847
907
  mirror: LocalMirror;
848
908
  /**
849
- * Called when an error occurs during a poll cycle.
850
- *
851
- * Defaults to `console.error`. Set to a no-op to suppress error logging.
852
- */
909
+ * Called when an error occurs during a poll cycle.
910
+ *
911
+ * Defaults to `console.error`. Set to a no-op to suppress error logging.
912
+ */
853
913
  onError?: (error: unknown) => void;
854
914
  /**
855
- * How often to poll for new events (in milliseconds).
856
- * @default 5000
857
- */
915
+ * How often to poll for new events (in milliseconds).
916
+ * @default 5000
917
+ */
858
918
  pollInterval?: number;
859
919
  }
860
920
  /**
861
- * Periodically polls an event log, replays events through a state machine,
862
- * converts the resulting state into {@link TableDiff | TableDiffs}, and
863
- * applies them to a {@link LocalMirror}.
864
- *
865
- * The class is **transport-agnostic** — it accepts a generic
866
- * `fetchEventsSince` function rather than coupling to a specific source
867
- * (EventLogDO, WebSocket push, IndexedDB, etc.).
868
- *
869
- * ## Lifecycle
870
- *
871
- * 1. Call `start()` to begin periodic polling.
872
- * 2. Call `sync()` to perform an immediate one-shot sync.
873
- * 3. Call `stop()` to halt polling.
874
- *
875
- * The current watermark is exposed via `watermark` and advances
876
- * monotonically as events are applied.
877
- * @experimental
878
- */
921
+ * Periodically polls an event log, replays events through a state machine,
922
+ * converts the resulting state into {@link TableDiff | TableDiffs}, and
923
+ * applies them to a {@link LocalMirror}.
924
+ *
925
+ * The class is **transport-agnostic** — it accepts a generic
926
+ * `fetchEventsSince` function rather than coupling to a specific source
927
+ * (EventLogDO, WebSocket push, IndexedDB, etc.).
928
+ *
929
+ * ## Lifecycle
930
+ *
931
+ * 1. Call `start()` to begin periodic polling.
932
+ * 2. Call `sync()` to perform an immediate one-shot sync.
933
+ * 3. Call `stop()` to halt polling.
934
+ *
935
+ * The current watermark is exposed via `watermark` and advances
936
+ * monotonically as events are applied.
937
+ * @experimental
938
+ */
879
939
  declare class EventsSync {
880
940
  #private;
881
941
  constructor(options: EventsSyncOptions);
882
942
  /**
883
- * The current watermark — the next `seq` the sync will fetch from.
884
- *
885
- * Starts at `0` (fetch everything). Advances to `max(seq) + 1` after
886
- * each successful poll cycle.
887
- */
943
+ * The current watermark — the next `seq` the sync will fetch from.
944
+ *
945
+ * Starts at `0` (fetch everything). Advances to `max(seq) + 1` after
946
+ * each successful poll cycle.
947
+ */
888
948
  get watermark(): number;
889
949
  /**
890
- * Start polling for new events on the configured interval.
891
- *
892
- * Does nothing if polling is already active.
893
- * Does **not** perform an initial sync — call {@link sync} once if you
894
- * need to catch up immediately.
895
- */
950
+ * Start polling for new events on the configured interval.
951
+ *
952
+ * Does nothing if polling is already active.
953
+ * Does **not** perform an initial sync — call {@link sync} once if you
954
+ * need to catch up immediately.
955
+ */
896
956
  start(): void;
897
957
  /**
898
- * Stop polling for new events.
899
- *
900
- * Safe to call when not started.
901
- */
958
+ * Stop polling for new events.
959
+ *
960
+ * Safe to call when not started.
961
+ */
902
962
  stop(): void;
903
963
  /**
904
- * Perform a one-shot sync: fetch events since the current watermark,
905
- * apply them through the state machine, and push diffs to the mirror.
906
- * @returns The number of events that were fetched and applied.
907
- */
964
+ * Perform a one-shot sync: fetch events since the current watermark,
965
+ * apply them through the state machine, and push diffs to the mirror.
966
+ * @returns The number of events that were fetched and applied.
967
+ */
908
968
  sync(): Promise<number>;
909
969
  }
910
- export { type AppendEventInput, type AppendOptions, type EventCallback, EventEmitter, type EventFactory, EventLog, EventLogDO, EventLogDOClient, type EventLogDOClientOptions, type EventLogEntry, type EventNamespace, type EventReducer, EventSource, type EventSourceEvents, type EventSourceOptions, type EventsContextOutput, type EventsDefinition, type EventsFacade, EventsSync, type EventsSyncOptions, InMemorySnapshotStore, type InputEvent, LocalMirror, type Materializer, type MaterializerDef, type MaterializerReducer, MaterializerRuntime, type MaterializerRuntimeOptions, type Seq, type SnapshotStore, type SqliteAdapter, type StateChangeCallback, type SubscriptionClient, SubscriptionManager, type TableDiff, type UnknownEventHandling, applyDiff, applyDiffToDatabase as applyDiffToDb, applyDiffToSnapshot, applyDiffs, applyDiffsToDatabase as applyDiffsToDb, defineEvents, defineMaterializer, eventsContext, subscribeToMirror };
970
+ export { type AppendEventInput, type AppendOptions, type EventCallback, EventEmitter, type EventFactory, EventLog, EventLogDO, EventLogDOClient, type EventLogDOClientOptions, type EventLogEntry, type EventNamespace, type EventReducer, EventSource, type EventSourceEvents, type EventSourceOptions, type EventsContextOutput, type EventsDefinition, type EventsFacade, EventsSync, type EventsSyncOptions, InMemorySnapshotStore, type InputEvent, LocalMirror, type Materializer, type MaterializerDef, type MaterializerReducer, MaterializerRuntime, type MaterializerRuntimeOptions, type Seq, type SnapshotStore, type SqliteAdapter, type StateChangeCallback, type SubscriptionClient, SubscriptionManager, type TableDiff, UNHANDLED, type UnknownEventHandling, applyDiff, applyDiffToDatabase as applyDiffToDb, applyDiffToSnapshot, applyDiffs, applyDiffsToDatabase as applyDiffsToDb, defineEvents, defineMaterializer, eventsContext, subscribeToMirror };