@lunora/replica 1.0.0-alpha.2 → 1.0.0-alpha.21
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.md +214 -0
- package/README.md +2 -0
- package/dist/adapters/better-sqlite3.d.mts +14 -13
- package/dist/adapters/better-sqlite3.d.ts +14 -13
- package/dist/adapters/better-sqlite3.mjs +1 -29
- package/dist/adapters/sqlite-wasm.d.mts +29 -18
- package/dist/adapters/sqlite-wasm.d.ts +29 -18
- package/dist/adapters/sqlite-wasm.mjs +1 -56
- package/dist/adapters/sqljs.d.mts +10 -9
- package/dist/adapters/sqljs.d.ts +10 -9
- package/dist/adapters/sqljs.mjs +1 -55
- package/dist/index.d.mts +646 -531
- package/dist/index.d.ts +646 -531
- package/dist/index.mjs +1 -20
- package/dist/packem_shared/EventEmitter-ovTsLeAj.mjs +1 -0
- package/dist/packem_shared/EventLog-DmlRY_4Z.mjs +1 -0
- package/dist/packem_shared/EventLogDO-Cb-7iN9w.mjs +1 -0
- package/dist/packem_shared/EventLogDOClient-C6gA3b3u.mjs +1 -0
- package/dist/packem_shared/EventSource-B5UTlkl9.mjs +1 -0
- package/dist/packem_shared/EventsSync-DWyGGZQZ.mjs +1 -0
- package/dist/packem_shared/InMemorySnapshotStore-C4taIG5K.mjs +1 -0
- package/dist/packem_shared/LocalMirror-Q7cPH_rX.mjs +4 -0
- package/dist/packem_shared/MaterializerRuntime-CqGGjSxl.mjs +1 -0
- package/dist/packem_shared/SubscriptionManager-CbSjG_GA.mjs +1 -0
- package/dist/packem_shared/applyDiff-BUzddc6r.mjs +1 -0
- package/dist/packem_shared/applyDiffToDb-1M2I3BHi.mjs +1 -0
- package/dist/packem_shared/classifyChanges-IoOGDVVx.mjs +1 -0
- package/dist/packem_shared/defineEvents-CJZV8Bgi.mjs +1 -0
- package/dist/packem_shared/eventsContext-Dxow9Y7S.mjs +1 -0
- package/dist/packem_shared/isClientSeq-DSXBJskD.mjs +1 -0
- package/dist/packem_shared/local-mirror.d-CyGOpUES.d.ts +530 -0
- package/dist/packem_shared/local-mirror.d-DTavX_y0.d.mts +530 -0
- package/dist/packem_shared/subscribeToMirror-Dru_AYBu.mjs +1 -0
- package/dist/packem_shared/{types.d-VfJ76cK4.d.mts → types.d-CkMkSwLJ.d.mts} +10 -9
- package/dist/packem_shared/{types.d-VfJ76cK4.d.ts → types.d-CkMkSwLJ.d.ts} +10 -9
- package/dist/react.d.mts +59 -57
- package/dist/react.d.ts +59 -57
- package/dist/react.mjs +1 -15
- package/package.json +2 -2
- package/dist/packem_shared/EventEmitter-CMZfct03.mjs +0 -92
- package/dist/packem_shared/EventLog-zMy7AYP4.mjs +0 -162
- package/dist/packem_shared/EventLogDO-CZYUvvSr.mjs +0 -235
- package/dist/packem_shared/EventLogDOClient-DGiEdi96.mjs +0 -86
- package/dist/packem_shared/EventSource-DfV4VoRD.mjs +0 -195
- package/dist/packem_shared/EventsSync-DkVbU0WV.mjs +0 -91
- package/dist/packem_shared/InMemorySnapshotStore-BHVAD-Bp.mjs +0 -24
- package/dist/packem_shared/LocalMirror-GeJ26eNe.mjs +0 -188
- package/dist/packem_shared/MaterializerRuntime-HqNXqJxp.mjs +0 -204
- package/dist/packem_shared/SubscriptionManager-C5xbw0pg.mjs +0 -75
- package/dist/packem_shared/applyDiff-BtbIl1D3.mjs +0 -40
- package/dist/packem_shared/applyDiffToDb-DQ1xZp5J.mjs +0 -58
- package/dist/packem_shared/classifyChanges-aZmkxgVI.mjs +0 -38
- package/dist/packem_shared/defineEvents-DiBkPTh_.mjs +0 -28
- package/dist/packem_shared/eventsContext-Bk_p48hj.mjs +0 -6
- package/dist/packem_shared/isClientSeq-C46BkzqJ.mjs +0 -5
- package/dist/packem_shared/local-mirror.d-Bp19ueGy.d.mts +0 -412
- package/dist/packem_shared/local-mirror.d-GhuZAKgm.d.ts +0 -412
- package/dist/packem_shared/subscribeToMirror-CiaM-nQ7.mjs +0 -45
|
@@ -0,0 +1,530 @@
|
|
|
1
|
+
import { S as SqliteAdapter } from "./types.d-CkMkSwLJ.mjs";
|
|
2
|
+
/**
|
|
3
|
+
* Row-level change kind within a TableDiff.
|
|
4
|
+
*
|
|
5
|
+
* Each change represents one row that was inserted, updated, or deleted on
|
|
6
|
+
* the server since the last sync tick.
|
|
7
|
+
* @experimental
|
|
8
|
+
*/
|
|
9
|
+
type RowChange = {
|
|
10
|
+
data: Record<string, unknown>;
|
|
11
|
+
type: "insert";
|
|
12
|
+
} | {
|
|
13
|
+
data: Record<string, unknown>;
|
|
14
|
+
id: string;
|
|
15
|
+
type: "update";
|
|
16
|
+
} | {
|
|
17
|
+
id: string;
|
|
18
|
+
type: "delete";
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A scoped, ordered set of row changes for a single table.
|
|
22
|
+
*
|
|
23
|
+
* `TableDiff` is the unit of replication between the server and the local
|
|
24
|
+
* SQLite mirror. The server pushes diffs over the poke protocol; the
|
|
25
|
+
* client applies them via `applyDiff`.
|
|
26
|
+
* @experimental
|
|
27
|
+
*/
|
|
28
|
+
interface TableDiff {
|
|
29
|
+
/** Ordered row changes — insert/update/delete, earliest first. */
|
|
30
|
+
readonly changes: ReadonlyArray<RowChange>;
|
|
31
|
+
/**
|
|
32
|
+
* Optional stable identity for this diff, distinct from `timestamp`
|
|
33
|
+
* (multiple diffs can legitimately share a millisecond, so `timestamp`
|
|
34
|
+
* alone is not a unique diff identity). Used by `deriveInsertId` in
|
|
35
|
+
* `apply-diff.ts` to derive deterministic row ids for id-less inserts:
|
|
36
|
+
* replaying the SAME diff (same `id`) must always mint the SAME id,
|
|
37
|
+
* while two DIFFERENT diffs emitted in the same millisecond must not
|
|
38
|
+
* alias onto the same one. `createTableDiff` auto-generates one when
|
|
39
|
+
* omitted; diffs built as plain object literals (bypassing the helper)
|
|
40
|
+
* simply fall back to `timestamp` for that derivation.
|
|
41
|
+
*/
|
|
42
|
+
readonly id?: string;
|
|
43
|
+
/** Logical table name (matches the schema table name). */
|
|
44
|
+
readonly table: string;
|
|
45
|
+
/** Monotonic server timestamp (ms since epoch) when this diff was emitted. */
|
|
46
|
+
readonly timestamp: number;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Create a {@link TableDiff} with a snapshot of the current time and a
|
|
50
|
+
* fresh stable `id` (unless one is explicitly provided).
|
|
51
|
+
* @experimental
|
|
52
|
+
*/
|
|
53
|
+
declare const createTableDiff: (table: string, changes: ReadonlyArray<RowChange>, timestamp?: number, id?: string) => TableDiff;
|
|
54
|
+
/**
|
|
55
|
+
* Return `true` when the diff contains no row changes.
|
|
56
|
+
* @experimental
|
|
57
|
+
*/
|
|
58
|
+
declare const isDiffEmpty: (diff: TableDiff) => boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Return the number of rows touched by the diff (inserts + updates + deletes).
|
|
61
|
+
* @experimental
|
|
62
|
+
*/
|
|
63
|
+
declare const diffSize: (diff: TableDiff) => number;
|
|
64
|
+
/**
|
|
65
|
+
* Partition a {@link TableDiff} into three categories for batch processing.
|
|
66
|
+
* @experimental
|
|
67
|
+
*/
|
|
68
|
+
declare const classifyChanges: (diff: TableDiff) => {
|
|
69
|
+
deletes: RowChange[];
|
|
70
|
+
inserts: RowChange[];
|
|
71
|
+
updates: RowChange[];
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* Merge several diffs for the same table into one (ordering preserved).
|
|
75
|
+
*
|
|
76
|
+
* Returns `null` when the input list is empty.
|
|
77
|
+
* @experimental
|
|
78
|
+
*/
|
|
79
|
+
declare const mergeDiffs: (diffs: ReadonlyArray<TableDiff>) => TableDiff | null;
|
|
80
|
+
/**
|
|
81
|
+
* Sequence-number types for the event log.
|
|
82
|
+
*
|
|
83
|
+
* Three namespaces match the vocabulary established by event-sourcing:
|
|
84
|
+
*
|
|
85
|
+
* | Namespace | Shape | Producer | Consumer |
|
|
86
|
+
* |-----------|--------------------|---------------------------|------------------------------|
|
|
87
|
+
* | `Global` | `number` | `EventLog` / `EventLogDO` | Materializers, subscribers |
|
|
88
|
+
* | `Input` | No seq (optimistic) | `defineEvents` factories | `EventLog.append` / DO client|
|
|
89
|
+
* | `Client` | `{generation,seq}` | _(future: rebase engine)_ | _(future: rebase-aware code)_|
|
|
90
|
+
* @module
|
|
91
|
+
*/
|
|
92
|
+
/**
|
|
93
|
+
* A server-authoritative (global) sequence number.
|
|
94
|
+
*
|
|
95
|
+
* Monotonically increasing, assigned by `EventLog` (in-memory) or
|
|
96
|
+
* `EventLogDO` (Durable Object). All confirmed log entries carry a
|
|
97
|
+
* `GlobalSeq`.
|
|
98
|
+
* @experimental
|
|
99
|
+
*/
|
|
100
|
+
type GlobalSeq = number;
|
|
101
|
+
/**
|
|
102
|
+
* A client-originated composite sequence number designed to survive rebase.
|
|
103
|
+
*
|
|
104
|
+
* Carries the last-confirmed `global` seq, a monotonically increasing
|
|
105
|
+
* `client` counter, and a `rebaseGeneration` that increments whenever the
|
|
106
|
+
* client's local events are rebased onto a new upstream baseline.
|
|
107
|
+
* @experimental
|
|
108
|
+
*/
|
|
109
|
+
interface ClientSeq {
|
|
110
|
+
/** Client-local monotonically increasing counter. */
|
|
111
|
+
readonly client: number;
|
|
112
|
+
/** The last-confirmed global sequence number. 0 for unconfirmed events. */
|
|
113
|
+
readonly global: number;
|
|
114
|
+
/** Incremented on every rebase. */
|
|
115
|
+
readonly rebaseGeneration: number;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Discriminated union of all sequence-number types.
|
|
119
|
+
* @experimental
|
|
120
|
+
*/
|
|
121
|
+
type Seq = GlobalSeq | ClientSeq;
|
|
122
|
+
/**
|
|
123
|
+
* Narrow `Seq` to `GlobalSeq`.
|
|
124
|
+
* @experimental
|
|
125
|
+
*/
|
|
126
|
+
declare const isGlobalSeq: (seq: Seq) => seq is GlobalSeq;
|
|
127
|
+
/**
|
|
128
|
+
* Narrow `Seq` to `ClientSeq`.
|
|
129
|
+
* @experimental
|
|
130
|
+
*/
|
|
131
|
+
declare const isClientSeq: (seq: Seq) => seq is ClientSeq;
|
|
132
|
+
/**
|
|
133
|
+
* An event that has **not** yet been assigned a sequence number.
|
|
134
|
+
*
|
|
135
|
+
* Input events represent optimistic / command payloads before the server
|
|
136
|
+
* confirms them. They carry `type`, `payload`, and `timestamp` but no
|
|
137
|
+
* `seq` — the log assigns one on append.
|
|
138
|
+
*
|
|
139
|
+
* Create input events via `defineEvents` factories:
|
|
140
|
+
*
|
|
141
|
+
* ```ts
|
|
142
|
+
* const event = events.chat.messageSent({ channelId: "c1", text: "hello" });
|
|
143
|
+
* // event: InputEvent<"chat.messageSent", { channelId: string; text: string }>
|
|
144
|
+
* ```
|
|
145
|
+
* @experimental
|
|
146
|
+
*/
|
|
147
|
+
interface InputEvent<Type extends string = string, Payload = unknown> {
|
|
148
|
+
/** Arbitrary JSON-serialisable payload. */
|
|
149
|
+
readonly payload: Payload;
|
|
150
|
+
/** Millisecond timestamp (epoch) when the event was created. */
|
|
151
|
+
readonly timestamp: number;
|
|
152
|
+
/** Event type discriminator (e.g. `"chat.messageSent"`). */
|
|
153
|
+
readonly type: Type;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Type guard: check whether `value` is an {@link InputEvent}.
|
|
157
|
+
* @experimental
|
|
158
|
+
*/
|
|
159
|
+
declare const isInputEvent: (value: unknown) => value is InputEvent;
|
|
160
|
+
/**
|
|
161
|
+
* A single entry in the append-only {@link EventLog}.
|
|
162
|
+
*
|
|
163
|
+
* Entries are immutable once appended; the `seq` field is assigned
|
|
164
|
+
* monotonically by the log and doubles as a watermark for catch-up
|
|
165
|
+
* replication between tabs or service-worker instances.
|
|
166
|
+
* @experimental
|
|
167
|
+
*/
|
|
168
|
+
interface EventLogEntry {
|
|
169
|
+
/**
|
|
170
|
+
* Globally-unique client identifier that originated this event.
|
|
171
|
+
* Set by clients that support offline / optimistic writes.
|
|
172
|
+
* `undefined` when the event was created server-side.
|
|
173
|
+
*/
|
|
174
|
+
readonly clientId?: string;
|
|
175
|
+
/**
|
|
176
|
+
* The sequence number of the causal parent event.
|
|
177
|
+
*
|
|
178
|
+
* A {@link GlobalSeq} for events confirmed by the server (pointing
|
|
179
|
+
* to the previous confirmed event), or a {@link ClientSeq} for
|
|
180
|
+
* optimistic / offline events pointing to the local predecessor.
|
|
181
|
+
* `undefined` for the first event in a log.
|
|
182
|
+
*/
|
|
183
|
+
readonly parentSeqNum?: Seq;
|
|
184
|
+
/** Arbitrary JSON-serialisable payload. */
|
|
185
|
+
readonly payload: unknown;
|
|
186
|
+
/** Monotonically increasing sequence number (0-based). A {@link GlobalSeq}. */
|
|
187
|
+
readonly seq: GlobalSeq;
|
|
188
|
+
/**
|
|
189
|
+
* Session identifier from the originating client.
|
|
190
|
+
* Paired with `clientId` to disambiguate concurrent sessions.
|
|
191
|
+
*/
|
|
192
|
+
readonly sessionId?: string;
|
|
193
|
+
/**
|
|
194
|
+
* Optional table diffs that this event produced.
|
|
195
|
+
* When present, a consumer can re-play the event by applying the diffs
|
|
196
|
+
* to its local mirror without re-executing the originating mutation.
|
|
197
|
+
*/
|
|
198
|
+
readonly tableDiffs?: ReadonlyArray<TableDiff>;
|
|
199
|
+
/** Millisecond timestamp (epoch) when the entry was appended. */
|
|
200
|
+
readonly timestamp: number;
|
|
201
|
+
/** Event type discriminator (e.g. "row-insert", "mutation-apply"). */
|
|
202
|
+
readonly type: string;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Serialised snapshot of the log — used for persistence and transfer.
|
|
206
|
+
* @experimental
|
|
207
|
+
*/
|
|
208
|
+
interface EventLogSnapshot {
|
|
209
|
+
readonly entries: ReadonlyArray<EventLogEntry>;
|
|
210
|
+
/** The sequence number of the last entry (head), or `null` for an empty log. */
|
|
211
|
+
readonly headSeq: GlobalSeq | null;
|
|
212
|
+
readonly nextSeq: number;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Optional metadata that can accompany an appended event.
|
|
216
|
+
* @experimental
|
|
217
|
+
*/
|
|
218
|
+
interface AppendOptions {
|
|
219
|
+
/** Globally-unique client identifier. */
|
|
220
|
+
readonly clientId?: string;
|
|
221
|
+
/**
|
|
222
|
+
* Causal parent sequence number.
|
|
223
|
+
* Automatically set to the previous entry's seq when omitted.
|
|
224
|
+
*/
|
|
225
|
+
readonly parentSeqNum?: Seq;
|
|
226
|
+
/** Session identifier within the client. */
|
|
227
|
+
readonly sessionId?: string;
|
|
228
|
+
/**
|
|
229
|
+
* Override the entry's `timestamp` instead of stamping `Date.now()` at
|
|
230
|
+
* append time.
|
|
231
|
+
*
|
|
232
|
+
* Used by callers (e.g. {@link import("./event-source").EventSource | EventSource})
|
|
233
|
+
* that must commit the EXACT entry a reducer already observed — a
|
|
234
|
+
* second, independently-drawn `Date.now()` at append time could produce
|
|
235
|
+
* a persisted entry a timestamp-dependent reducer cannot reproduce on
|
|
236
|
+
* replay.
|
|
237
|
+
*/
|
|
238
|
+
readonly timestamp?: number;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Options for constructing an {@link EventLog}.
|
|
242
|
+
* @experimental
|
|
243
|
+
*/
|
|
244
|
+
interface EventLogOptions {
|
|
245
|
+
/**
|
|
246
|
+
* Cap the number of entries retained in memory (REPLICA-06). When an
|
|
247
|
+
* append would exceed the cap, the OLDEST entries are evicted (ring
|
|
248
|
+
* buffer) — a `getSince`/`getFrom` call for a watermark below the oldest
|
|
249
|
+
* retained `seq` then returns only what's left, silently missing
|
|
250
|
+
* anything evicted.
|
|
251
|
+
*
|
|
252
|
+
* `undefined` (the default) preserves the original unbounded behavior.
|
|
253
|
+
* Set this only when you have another durable source of truth for
|
|
254
|
+
* anything older than the cap (a snapshot, a server-side `EventLogDO`) —
|
|
255
|
+
* see {@link EventLog#truncateBelow} for the caller-driven equivalent
|
|
256
|
+
* tied to snapshot persistence.
|
|
257
|
+
*/
|
|
258
|
+
readonly maxEntries?: number;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* An append-only, in-memory event log for local event sourcing.
|
|
262
|
+
*
|
|
263
|
+
* The log is the single source of truth for "what happened" and drives
|
|
264
|
+
* catch-up replication: a new tab or service worker asks for entries
|
|
265
|
+
* since its known `seq` watermark and re-applies them.
|
|
266
|
+
* @remarks This class is intentionally **not** a full SQLite-backed log.
|
|
267
|
+
* Persistence is the caller's responsibility (write the snapshot
|
|
268
|
+
* to IndexedDB / OPFS via {@link EventLog#snapshot}).
|
|
269
|
+
* @experimental
|
|
270
|
+
*/
|
|
271
|
+
declare class EventLog {
|
|
272
|
+
#private;
|
|
273
|
+
constructor(options?: EventLogOptions);
|
|
274
|
+
/**
|
|
275
|
+
* Append a new entry to the log.
|
|
276
|
+
*
|
|
277
|
+
* Accepts either an {@link InputEvent} (e.g. from a `defineEvents` factory)
|
|
278
|
+
* or the traditional `(type, payload, tableDiffs?)` triple.
|
|
279
|
+
* @returns The newly created entry (already written to the log).
|
|
280
|
+
*/
|
|
281
|
+
append(event: InputEvent, options?: AppendOptions): EventLogEntry;
|
|
282
|
+
append(type: string, payload: unknown, tableDiffs?: ReadonlyArray<TableDiff>, options?: AppendOptions): EventLogEntry;
|
|
283
|
+
/**
|
|
284
|
+
* Atomically append multiple events to the log.
|
|
285
|
+
*
|
|
286
|
+
* All events are assigned sequential global sequence numbers and
|
|
287
|
+
* automatically wired as a causal chain (each event's `parentSeqNum`
|
|
288
|
+
* points to the previous event in the batch, or to the log head for
|
|
289
|
+
* the first event).
|
|
290
|
+
* @param events An array of events to commit atomically.
|
|
291
|
+
* @returns The newly created entries in order.
|
|
292
|
+
*/
|
|
293
|
+
commitAll(events: ReadonlyArray<InputEvent | {
|
|
294
|
+
payload: unknown;
|
|
295
|
+
type: string;
|
|
296
|
+
}>): EventLogEntry[];
|
|
297
|
+
/**
|
|
298
|
+
* Replace the log contents with a previously captured snapshot.
|
|
299
|
+
* This is the restore counterpart of {@link EventLog#snapshot}.
|
|
300
|
+
* Restores `headSeq` from the snapshot so auto-parenting continues
|
|
301
|
+
* after restore.
|
|
302
|
+
*
|
|
303
|
+
* Runs `#enforceCap()` after restoring so a snapshot captured under a
|
|
304
|
+
* different (or no) `maxEntries` can never leave this log over its
|
|
305
|
+
* configured capacity.
|
|
306
|
+
*/
|
|
307
|
+
load(snapshot: EventLogSnapshot): void;
|
|
308
|
+
/**
|
|
309
|
+
* Return **all** entries whose `seq >= sinceSeq`.
|
|
310
|
+
* Useful for catch-up: "give me everything since my last watermark".
|
|
311
|
+
*/
|
|
312
|
+
getSince(sinceSeq: number): ReadonlyArray<EventLogEntry>;
|
|
313
|
+
/**
|
|
314
|
+
* Paginated read starting at `fromSeq`.
|
|
315
|
+
* @returns `{ entries, hasMore }` where `hasMore` is `true` when more
|
|
316
|
+
* entries exist beyond the requested page.
|
|
317
|
+
*/
|
|
318
|
+
getFrom(fromSeq: number, limit?: number): {
|
|
319
|
+
entries: ReadonlyArray<EventLogEntry>;
|
|
320
|
+
hasMore: boolean;
|
|
321
|
+
};
|
|
322
|
+
/**
|
|
323
|
+
* Return all entries as a snapshot suitable for serialisation.
|
|
324
|
+
*/
|
|
325
|
+
snapshot(): EventLogSnapshot;
|
|
326
|
+
/** Number of entries currently in the log. */
|
|
327
|
+
get size(): number;
|
|
328
|
+
/** The next sequence number that will be assigned. */
|
|
329
|
+
get nextSeq(): number;
|
|
330
|
+
/** Return `true` when there are no entries. */
|
|
331
|
+
get isEmpty(): boolean;
|
|
332
|
+
/**
|
|
333
|
+
* The sequence number of the last (most recent) entry, or `null`
|
|
334
|
+
* when the log is empty. Used internally for auto-parenting and
|
|
335
|
+
* exposed for consumers that need the causal head.
|
|
336
|
+
*/
|
|
337
|
+
get headSeq(): GlobalSeq | null;
|
|
338
|
+
/** Remove all entries (primarily for testing). */
|
|
339
|
+
clear(): void;
|
|
340
|
+
/**
|
|
341
|
+
* Discard all entries with `seq < floorSeq` (REPLICA-06).
|
|
342
|
+
*
|
|
343
|
+
* `headSeq`/`nextSeq` are untouched (they're independent counters), so
|
|
344
|
+
* appends after a truncation continue the same sequence uninterrupted.
|
|
345
|
+
*
|
|
346
|
+
* **Caller-driven, not automatic**: only call this after the truncated
|
|
347
|
+
* range has already been durably captured elsewhere (a snapshot, a
|
|
348
|
+
* server-side `EventLogDO`) — truncating without such a floor makes any
|
|
349
|
+
* future `getSince`/`getFrom`/`EventSource.replayFromLog` call for a
|
|
350
|
+
* watermark below `floorSeq` silently miss the discarded entries. This is
|
|
351
|
+
* the hook the caller ties to snapshot persistence; the log itself has no
|
|
352
|
+
* concept of "already durably persisted".
|
|
353
|
+
*
|
|
354
|
+
* `floorSeq` must be a non-negative safe integer — `NaN` would make
|
|
355
|
+
* every comparison false and silently clear the entire log.
|
|
356
|
+
*/
|
|
357
|
+
truncateBelow(floorSeq: number): void;
|
|
358
|
+
/**
|
|
359
|
+
* Return an async generator that yields every entry starting from
|
|
360
|
+
* `fromSeq` (default `0` = all entries).
|
|
361
|
+
*
|
|
362
|
+
* Because `EventLog` is purely in-memory, the generator yields all
|
|
363
|
+
* matching entries synchronously on first iteration and then completes.
|
|
364
|
+
* For a streaming / push-based variant see {@link EventSource.events}.
|
|
365
|
+
*/
|
|
366
|
+
events(fromSeq?: number): AsyncGenerator<EventLogEntry>;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* `MirrorTableDef` is part of the experimental `@lunora/replica` API and may change without a major version bump.
|
|
370
|
+
* @experimental
|
|
371
|
+
*/
|
|
372
|
+
interface MirrorTableDef {
|
|
373
|
+
/** Primary key column name (defaults to `"id"`). */
|
|
374
|
+
readonly primaryKey?: string;
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Options for constructing a {@link LocalMirror}.
|
|
378
|
+
* @experimental
|
|
379
|
+
*/
|
|
380
|
+
interface LocalMirrorOptions {
|
|
381
|
+
/** Platform-specific SQLite adapter. */
|
|
382
|
+
readonly db: SqliteAdapter;
|
|
383
|
+
/**
|
|
384
|
+
* Cap the mirror's internal {@link EventLog} to this many entries
|
|
385
|
+
* (REPLICA-06). Every applied diff is recorded in the log — with no cap,
|
|
386
|
+
* a long-running client accumulates one entry per diff forever.
|
|
387
|
+
*
|
|
388
|
+
* `undefined` (the default) preserves unbounded retention. Set this when
|
|
389
|
+
* catch-up replication only ever needs a bounded recent window; older
|
|
390
|
+
* entries are silently evicted (oldest-first) once the cap is exceeded.
|
|
391
|
+
* See {@link EventLog#truncateBelow} for caller-driven truncation tied to
|
|
392
|
+
* a snapshot instead.
|
|
393
|
+
*/
|
|
394
|
+
readonly maxEventLogEntries?: number;
|
|
395
|
+
/**
|
|
396
|
+
* Table schemas the mirror should manage.
|
|
397
|
+
*
|
|
398
|
+
* On first use the mirror creates any missing tables automatically
|
|
399
|
+
* based on the columns observed in the first diff/row applied.
|
|
400
|
+
* If you want a fixed schema, pass it here with explicit column
|
|
401
|
+
* definitions in `columns`.
|
|
402
|
+
*/
|
|
403
|
+
readonly tables?: Record<string, MirrorTableDef>;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Local SQLite mirror that maintains a client-side replica of server
|
|
407
|
+
* tables by applying {@link TableDiff} deltas.
|
|
408
|
+
*
|
|
409
|
+
* Usage:
|
|
410
|
+
* ```ts
|
|
411
|
+
* import { createSqlJsAdapter } from "@lunora/replica/adapters/sqljs";
|
|
412
|
+
* import initSqlJs from "sql.js";
|
|
413
|
+
*
|
|
414
|
+
* const SQL = await initSqlJs();
|
|
415
|
+
* const db = createSqlJsAdapter(new SQL.Database());
|
|
416
|
+
*
|
|
417
|
+
* const mirror = new LocalMirror({ db });
|
|
418
|
+
*
|
|
419
|
+
* // Apply a server diff:
|
|
420
|
+
* mirror.applyDiff(someDiff);
|
|
421
|
+
*
|
|
422
|
+
* // Query locally:
|
|
423
|
+
* const rows = mirror.query<{ id: string; name: string }>(
|
|
424
|
+
* "SELECT id, name FROM users WHERE name LIKE ?",
|
|
425
|
+
* ["alice%"],
|
|
426
|
+
* );
|
|
427
|
+
* ```
|
|
428
|
+
*/
|
|
429
|
+
type ChangeSubscriber = () => void;
|
|
430
|
+
/**
|
|
431
|
+
* `LocalMirror` is part of the experimental `@lunora/replica` API and may change without a major version bump.
|
|
432
|
+
* @experimental
|
|
433
|
+
*/
|
|
434
|
+
declare class LocalMirror {
|
|
435
|
+
#private;
|
|
436
|
+
/**
|
|
437
|
+
* Convenience factory that creates a {@link LocalMirror} backed by a
|
|
438
|
+
* {@link createSqlJsAdapter sql.js adapter} without needing to import
|
|
439
|
+
* and wire sql.js manually.
|
|
440
|
+
*
|
|
441
|
+
* The caller provides an initialised sql.js database — this method wraps
|
|
442
|
+
* it in an adapter and constructs the mirror.
|
|
443
|
+
* @example
|
|
444
|
+
* ```ts
|
|
445
|
+
* import initSqlJs from "sql.js";
|
|
446
|
+
*
|
|
447
|
+
* const SQL = await initSqlJs();
|
|
448
|
+
* const mirror = LocalMirror.create(new SQL.Database(), {
|
|
449
|
+
* tables: { todos: { primaryKey: "id" } },
|
|
450
|
+
* });
|
|
451
|
+
* ```
|
|
452
|
+
*/
|
|
453
|
+
static create(sqlJsDatabase: {
|
|
454
|
+
close: () => void;
|
|
455
|
+
exec: (sql: string) => {
|
|
456
|
+
columns: string[];
|
|
457
|
+
values: unknown[][];
|
|
458
|
+
}[];
|
|
459
|
+
run: (sql: string, params?: unknown[]) => void;
|
|
460
|
+
}, options?: {
|
|
461
|
+
tables?: Record<string, MirrorTableDef>;
|
|
462
|
+
}): LocalMirror;
|
|
463
|
+
constructor(options: LocalMirrorOptions);
|
|
464
|
+
/**
|
|
465
|
+
* Subscribe to data-change notifications. Fires after every {@link applyDiff}.
|
|
466
|
+
* Returns an unsubscribe function.
|
|
467
|
+
*/
|
|
468
|
+
onChange(callback: ChangeSubscriber): () => void;
|
|
469
|
+
/**
|
|
470
|
+
* The in-memory event log tracking every diff applied to this mirror.
|
|
471
|
+
* Use {@link EventLog.getSince} for catch-up replication across tabs
|
|
472
|
+
* or service-worker instances.
|
|
473
|
+
*/
|
|
474
|
+
get eventLog(): EventLog;
|
|
475
|
+
/**
|
|
476
|
+
* The raw SQLite adapter. Advanced consumers (e.g. the React hook)
|
|
477
|
+
* can use it for ad-hoc queries or bulk operations.
|
|
478
|
+
*/
|
|
479
|
+
get db(): SqliteAdapter;
|
|
480
|
+
/**
|
|
481
|
+
* Monotonically increasing version counter, bumped on every operation
|
|
482
|
+
* that changes mirrored data (`applyDiff`, `clearData`). Use this — not
|
|
483
|
+
* `eventLog.size` — as a `useSyncExternalStore` snapshot so operations
|
|
484
|
+
* that don't append to the log still trigger a re-render.
|
|
485
|
+
*/
|
|
486
|
+
get version(): number;
|
|
487
|
+
/**
|
|
488
|
+
* Apply a server-side diff to the local SQLite mirror.
|
|
489
|
+
*
|
|
490
|
+
* The diff is applied in a transaction and recorded in the event log
|
|
491
|
+
* so other tabs or the SW can catch up.
|
|
492
|
+
*/
|
|
493
|
+
applyDiff(diff: TableDiff): void;
|
|
494
|
+
/**
|
|
495
|
+
* Run an arbitrary SQL query against the local mirror and return
|
|
496
|
+
* typed results.
|
|
497
|
+
* @example
|
|
498
|
+
* ```ts
|
|
499
|
+
* const users = mirror.query<{ id: string; name: string }>(
|
|
500
|
+
* "SELECT id, name FROM users WHERE active = ?",
|
|
501
|
+
* [true],
|
|
502
|
+
* );
|
|
503
|
+
* ```
|
|
504
|
+
*/
|
|
505
|
+
query<T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>): T[];
|
|
506
|
+
/**
|
|
507
|
+
* Delete every row from all known tables (preserves the event log
|
|
508
|
+
* and schema). Useful when re-syncing from scratch.
|
|
509
|
+
*
|
|
510
|
+
* Notifies `onChange` subscribers and bumps {@link LocalMirror.version}
|
|
511
|
+
* (REPLICA-09) even though nothing is appended to the event log — a
|
|
512
|
+
* consumer keyed only on `eventLog.size` would otherwise never learn the
|
|
513
|
+
* mirror was cleared and keep rendering deleted rows.
|
|
514
|
+
*/
|
|
515
|
+
clearData(): void;
|
|
516
|
+
/**
|
|
517
|
+
* Dispose the mirror and close the database connection.
|
|
518
|
+
*/
|
|
519
|
+
close(): void;
|
|
520
|
+
/**
|
|
521
|
+
* Register a table schema so the mirror can create the table on
|
|
522
|
+
* first use.
|
|
523
|
+
*/
|
|
524
|
+
registerTable(name: string, definition: MirrorTableDef): void;
|
|
525
|
+
/**
|
|
526
|
+
* Return the list of mirrored table names.
|
|
527
|
+
*/
|
|
528
|
+
get mirroredTables(): ReadonlyArray<string>;
|
|
529
|
+
}
|
|
530
|
+
export { AppendOptions as A, ClientSeq as C, EventLogEntry as E, GlobalSeq as G, InputEvent as I, LocalMirror as L, MirrorTableDef as M, RowChange as R, Seq as S, TableDiff as T, EventLog as a, EventLogOptions as b, EventLogSnapshot as c, LocalMirrorOptions as d, classifyChanges as e, createTableDiff as f, diffSize as g, isDiffEmpty as h, isClientSeq as i, isGlobalSeq as j, isInputEvent as k, mergeDiffs as m };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const d=e=>`fn_${e.replaceAll(/[/:.]/g,"_")}`,u=e=>Array.isArray(e)?e:e!==null&&typeof e=="object"?[e]:[],g=(e,a,n,f,i)=>{const l=d(n.__lunoraRef);a.registerTable(l,{});let p=new Set;return e.subscribe(n,f,b=>{const y=u(b),o=new Set,t=[];for(const r of y){const c=r,s=c.id;(typeof s=="string"||typeof s=="number")&&o.add(String(s)),t.push({type:"insert",data:c})}for(const r of p)o.has(r)||t.push({type:"delete",id:r});p=o,t.length!==0&&a.applyDiff({table:l,changes:t,timestamp:Date.now()})},{shardKey:i})};export{g as subscribeToMirror};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Abstract SQLite driver interface used by the local mirror.
|
|
3
|
-
*
|
|
4
|
-
* Each runtime (browser via sql.js, React Native via expo-sqlite,
|
|
5
|
-
* Node via better-sqlite3) provides its own adapter implementing this
|
|
6
|
-
* interface so the rest of `@lunora/replica` stays platform-agnostic.
|
|
7
|
-
|
|
2
|
+
* Abstract SQLite driver interface used by the local mirror.
|
|
3
|
+
*
|
|
4
|
+
* Each runtime (browser via sql.js, React Native via expo-sqlite,
|
|
5
|
+
* Node via better-sqlite3) provides its own adapter implementing this
|
|
6
|
+
* interface so the rest of `@lunora/replica` stays platform-agnostic.
|
|
7
|
+
* @experimental
|
|
8
|
+
*/
|
|
8
9
|
interface SqliteAdapter {
|
|
9
10
|
/** Close the database connection. */
|
|
10
11
|
close: () => void;
|
|
@@ -13,9 +14,9 @@ interface SqliteAdapter {
|
|
|
13
14
|
/** Return the id of the last inserted row. */
|
|
14
15
|
lastInsertRowId: () => number;
|
|
15
16
|
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
* Execute a SQL statement and return the result rows.
|
|
18
|
+
* Columns can be accessed by index or by name.
|
|
19
|
+
*/
|
|
19
20
|
query: <T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>) => T[];
|
|
20
21
|
/** Run all statements in a transaction. */
|
|
21
22
|
transaction: (function_: () => void) => void;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Abstract SQLite driver interface used by the local mirror.
|
|
3
|
-
*
|
|
4
|
-
* Each runtime (browser via sql.js, React Native via expo-sqlite,
|
|
5
|
-
* Node via better-sqlite3) provides its own adapter implementing this
|
|
6
|
-
* interface so the rest of `@lunora/replica` stays platform-agnostic.
|
|
7
|
-
|
|
2
|
+
* Abstract SQLite driver interface used by the local mirror.
|
|
3
|
+
*
|
|
4
|
+
* Each runtime (browser via sql.js, React Native via expo-sqlite,
|
|
5
|
+
* Node via better-sqlite3) provides its own adapter implementing this
|
|
6
|
+
* interface so the rest of `@lunora/replica` stays platform-agnostic.
|
|
7
|
+
* @experimental
|
|
8
|
+
*/
|
|
8
9
|
interface SqliteAdapter {
|
|
9
10
|
/** Close the database connection. */
|
|
10
11
|
close: () => void;
|
|
@@ -13,9 +14,9 @@ interface SqliteAdapter {
|
|
|
13
14
|
/** Return the id of the last inserted row. */
|
|
14
15
|
lastInsertRowId: () => number;
|
|
15
16
|
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
* Execute a SQL statement and return the result rows.
|
|
18
|
+
* Columns can be accessed by index or by name.
|
|
19
|
+
*/
|
|
19
20
|
query: <T = Record<string, unknown>>(sql: string, params?: ReadonlyArray<unknown>) => T[];
|
|
20
21
|
/** Run all statements in a transaction. */
|
|
21
22
|
transaction: (function_: () => void) => void;
|