@lunora/db 1.0.0-alpha.8 → 1.0.0-alpha.80

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 (33) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +7 -1
  3. package/dist/collections/index.d.mts +2 -2
  4. package/dist/collections/index.d.ts +2 -2
  5. package/dist/collections/index.mjs +1 -2
  6. package/dist/index.d.mts +144 -5
  7. package/dist/index.d.ts +144 -5
  8. package/dist/index.mjs +1 -8
  9. package/dist/mutators/index.d.mts +2 -2
  10. package/dist/mutators/index.d.ts +2 -2
  11. package/dist/mutators/index.mjs +1 -1
  12. package/dist/packem_shared/CHECKPOINT_FALLBACK_MS-DAWfz0yD.mjs +1 -0
  13. package/dist/packem_shared/DIRECT_TRANSACTION_METADATA_KEY-C-CHKj3n.mjs +1 -0
  14. package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-BfFCughR.mjs +1 -0
  15. package/dist/packem_shared/applyPlanToCollections-C_eyqNF9.mjs +1 -0
  16. package/dist/packem_shared/collection-options.d-BA8jp3ji.d.mts +357 -0
  17. package/dist/packem_shared/collection-options.d-BA8jp3ji.d.ts +357 -0
  18. package/dist/packem_shared/defineCollections-Czhhf-A8.mjs +1 -0
  19. package/dist/packem_shared/index.d-BCKTZhCD.d.mts +235 -0
  20. package/dist/packem_shared/index.d-BZ00iQoq.d.ts +235 -0
  21. package/dist/packem_shared/index.d-C3aBVnK7.d.ts +174 -0
  22. package/dist/packem_shared/index.d-Depww9_D.d.mts +174 -0
  23. package/package.json +3 -2
  24. package/dist/packem_shared/OUTBOX_MUTATION_FN_NAME-DZrP1gna.mjs +0 -100
  25. package/dist/packem_shared/bindMutators-Bh6giR9x.mjs +0 -66
  26. package/dist/packem_shared/collection-options.d-CbS3J_Fm.d.mts +0 -207
  27. package/dist/packem_shared/collection-options.d-CbS3J_Fm.d.ts +0 -207
  28. package/dist/packem_shared/createCheckpointRegistry-C1kzNWCs.mjs +0 -124
  29. package/dist/packem_shared/define-collections.d-DTS0ANuU.d.mts +0 -85
  30. package/dist/packem_shared/define-collections.d-Po97lX6i.d.ts +0 -85
  31. package/dist/packem_shared/define-mutators.d-C3DO284A.d.ts +0 -80
  32. package/dist/packem_shared/define-mutators.d-DNVJIpW8.d.mts +0 -80
  33. package/dist/packem_shared/defineCollections-DR6fcIkQ.mjs +0 -74
@@ -0,0 +1,357 @@
1
+ import { OutboxSink, LunoraClient, FunctionReference, SubscriptionError } from '@lunora/client';
2
+ import { CollectionConfig } from '@tanstack/db';
3
+ import { OnlineDetector } from '@tanstack/offline-transactions';
4
+ /**
5
+ * Reserved `mutationFns` key the unified outbox routes raw `client.mutation`
6
+ * offline writes through. `defineCollections` registers a handler under this
7
+ * name that reads `transaction.metadata` (functionPath + args) and replays the
8
+ * write, so a db app's direct mutations ride the same durable executor as its
9
+ * collection inserts instead of the standalone {@link OutboxSink} fallback.
10
+ */
11
+ declare const OUTBOX_MUTATION_FN_NAME = "__lunora_outbox__";
12
+ /**
13
+ * Provenance stamped on a durable write at enqueue time: the two questions a
14
+ * replay cannot answer from the persisted row once the write outlives the
15
+ * session that made it — WHO queued it, and WHICH shard it belongs to.
16
+ *
17
+ * Shared so both replay paths (`db.actions.*` and the reserved
18
+ * `__lunora_outbox__` handler) check the same fields; they drifted apart once
19
+ * already, and only one of them had the identity guard.
20
+ */
21
+ interface WriteProvenance extends Record<string, unknown> {
22
+ /** Issuing identity fingerprint; a replay drops the write when it no longer matches. */
23
+ identity: string | null;
24
+ /** Captured, not re-read at replay: a queued write follows the shard it was made against even if the app reboots pointed at another. */
25
+ shardKey?: string;
26
+ }
27
+ /** The metadata an outbox-routed transaction carries so its replay can call `client.mutation`. */
28
+ interface OutboxMutationMetadata extends WriteProvenance {
29
+ args: Record<string, unknown>;
30
+ clientId: string;
31
+ functionPath: string;
32
+ /** Stable `${clientId}:${mutationId}` replay key; passed back as the mutation id so a committed-but-unacked replay is server-idempotent. */
33
+ idempotencyKey: string;
34
+ mutationId: number;
35
+ }
36
+ /** A committable outbox transaction handle (the `OfflineTransaction` the executor mints). */
37
+ interface OutboxTransaction {
38
+ commit?: () => Promise<unknown>;
39
+ mutate: (callback: () => void) => unknown;
40
+ }
41
+ /**
42
+ * The slice of the TanStack `OfflineExecutor` the {@link createExecutorOutboxSink}
43
+ * drives. Declared structurally so `@lunora/db`'s outbox glue doesn't widen its
44
+ * coupling to the executor's full surface (and stays unit-testable with a fake).
45
+ */
46
+ interface OutboxExecutor {
47
+ createOfflineTransaction: (options: {
48
+ autoCommit?: boolean;
49
+ idempotencyKey?: string;
50
+ metadata?: Record<string, unknown>;
51
+ mutationFnName: string;
52
+ }) => OutboxTransaction;
53
+ getPendingCount: () => number;
54
+ }
55
+ /** Tuning for {@link createExecutorOutboxSink}. */
56
+ interface ExecutorOutboxSinkOptions {
57
+ /** Max persisted-but-unconfirmed writes before `enqueue` rejects with `OFFLINE_QUEUE_OVERFLOW` (default 1000, matching `OfflineQueue`). */
58
+ maxItems?: number;
59
+ /** `mutationFns` key the replay handler is registered under (default {@link OUTBOX_MUTATION_FN_NAME}). */
60
+ mutationFnName?: string;
61
+ }
62
+ /**
63
+ * The blessed {@link OutboxSink} over the TanStack `OfflineExecutor` — the single
64
+ * durable write path for a `@lunora/db` app. It persists each offline write as an
65
+ * executor transaction carrying the `client.mutation` target in `metadata`, then
66
+ * ports the two semantics the executor lacks vs the built-in `OfflineQueue`.
67
+ *
68
+ * First: a `maxItems` cap that **rejects** a new write at capacity with an
69
+ * `OFFLINE_QUEUE_OVERFLOW`-coded error — the {@link OutboxSink} contract, matching
70
+ * `OfflineQueue`. Rejecting (rather than evicting the oldest) preserves the
71
+ * at-least-once promise: an already-persisted write is never silently dropped, and
72
+ * the caller surfaces back-pressure to the issuing mutation (which rolls its
73
+ * optimistic write back).
74
+ * Second: the identity guard lives in the replay handler (`defineCollections`), which drops a write whose captured `identity` no longer matches — see {@link OutboxMutationMetadata}.
75
+ */
76
+ declare const createExecutorOutboxSink: (executor: OutboxExecutor, options?: ExecutorOutboxSinkOptions) => OutboxSink;
77
+ /** A row carrying the Lunora document id. */
78
+ type Row = Record<string, unknown> & {
79
+ _id: string;
80
+ };
81
+ /** The subset of a TanStack DB sync write channel that {@link makeDiffEmit} drives. */
82
+ interface SyncWriter<T extends object> {
83
+ begin: () => void;
84
+ commit: () => void;
85
+ write: (message: {
86
+ type: "insert" | "update";
87
+ value: T;
88
+ } | {
89
+ key: string;
90
+ type: "delete";
91
+ }) => void;
92
+ }
93
+ /** Index a row list into a keyed map. */
94
+ declare const toMap: <T extends object>(rows: ReadonlyArray<T>, getKey: (row: T) => string) => Map<string, T>;
95
+ /**
96
+ * Build an `emit(next)` that diffs a desired keyed snapshot into a collection's
97
+ * sync channel — only changed rows are written, so a reconnect snapshot or a
98
+ * scope change never churns the synced view out from under a pending optimistic
99
+ * row. The last-synced base is tracked in `syncedJson`.
100
+ *
101
+ * Change detection compares rows by `JSON.stringify`, which is key-order
102
+ * sensitive — safe here because server snapshots have stable column order
103
+ * across reconnects (same query projection). A sync source with unstable key
104
+ * ordering would need a structural compare instead.
105
+ *
106
+ * `syncedJson` holds the JSON-serialized form of each last-synced row, keyed
107
+ * by row id. It is the **sole** synced-state map — no parallel row-object map
108
+ * is kept. Each incoming value is serialized exactly once per tick (for both
109
+ * comparison and cache update), so the previous value is never re-serialized.
110
+ *
111
+ * Lifecycle: `syncedJson` must be owned by the caller at the same scope as any
112
+ * other per-collection state (e.g. outside the `sync.sync` callback), so the
113
+ * cache persists correctly across sync restarts. A new `makeDiffEmit` closure
114
+ * created on restart receives the same map reference and starts from the
115
+ * committed synced state — no spurious diffs on reconnect.
116
+ */
117
+ declare const makeDiffEmit: <T extends object>(syncedJson: Map<string, string>, writer: SyncWriter<T>) => (next: Map<string, T>) => void;
118
+ /**
119
+ * Run a Lunora mutation under the outbox's retry policy.
120
+ *
121
+ * The retryable/permanent split keys on whether the failure carries a server
122
+ * application error `code` (set by `@lunora/client`'s rpc when the server returns
123
+ * a `{ error: { code, … } }` envelope — validation, conflict, etc.). A coded
124
+ * error is a definite verdict: surface it as a `NonRetriableError` so the executor
125
+ * stops and TanStack DB rolls the optimistic insert back. Everything without a
126
+ * code is transient — a `fetch` network failure (`TypeError`) or an HTTP/infra
127
+ * blip the rpc surfaces as a code-less `Error` (a 5xx gateway page, a non-JSON
128
+ * body) — so it's rethrown as-is and the durable outbox replays it. Keying on
129
+ * `error instanceof TypeError` alone would wrongly drop the latter.
130
+ */
131
+ declare const runOutboxMutation: (mutate: () => Promise<unknown>) => Promise<void>;
132
+ /**
133
+ * An "always attempt" online detector. We deliberately don't trust
134
+ * `navigator.onLine`: some environments (and Playwright's `setOffline` under
135
+ * Firefox) leave it stuck, which would freeze the outbox. Instead the executor
136
+ * always tries the send and {@link runOutboxMutation}'s transient-error retry
137
+ * handles real offline; the periodic tick nudges the executor to drain the outbox
138
+ * so a queued write replays promptly once connectivity returns.
139
+ *
140
+ * `isOnline` is therefore intentionally always `true` — it gates the executor's
141
+ * attempts, not a UI signal. A consumer that wants to show real connectivity
142
+ * should read `navigator.onLine` itself, separately from this detector.
143
+ */
144
+ declare const createOptimisticOnlineDetector: () => OnlineDetector;
145
+ /** A watermark pair — the two monotonic lines a checkpoint registry gates on. */
146
+ interface CheckpointWatermark {
147
+ /** Op-log cursor the server has durably applied. */
148
+ checkpoint?: number;
149
+ /** Highest `clientSeq` the server has echoed back for this client. */
150
+ mutationId?: number;
151
+ }
152
+ /** Reported when the fallback releases an overlay the sync stream never confirmed. */
153
+ interface CheckpointFallbackEvent {
154
+ /** Which gate released. */
155
+ kind: "checkpoint" | "mutationId";
156
+ /** How long the release waited past the server acknowledgement, in ms. */
157
+ waitedMs: number;
158
+ /** The watermark that was acknowledged but never confirmed by a sync frame. */
159
+ watermark: number;
160
+ }
161
+ /** Counters for {@link CheckpointRegistry.stats} — feeds a debug/diagnostics surface. */
162
+ interface CheckpointRegistryStats {
163
+ /** How many times the fallback timer released an overlay (a non-zero value means sync frames are being lost). */
164
+ fallbacks: number;
165
+ /** Overlays currently waiting on a checkpoint cursor. */
166
+ pendingCheckpointWaiters: number;
167
+ /** Overlays currently waiting on a mutation id. */
168
+ pendingMutationWaiters: number;
169
+ }
170
+ /** Tuning for {@link createCheckpointRegistry}. */
171
+ interface CheckpointRegistryOptions {
172
+ /**
173
+ * How long an {@link CheckpointRegistry.acknowledge}d watermark waits for the
174
+ * authoritative sync frame before the overlay is released anyway. Default 3000.
175
+ * `0` disables the fallback (an overlay then waits forever for the frame — the
176
+ * pre-fallback behavior, which hangs on a dropped poke).
177
+ */
178
+ fallbackMs?: number;
179
+ /**
180
+ * Notified each time the fallback fires. A fallback is never *correct* — it
181
+ * means a poke or `settled` frame that should have confirmed the write never
182
+ * arrived — so this is the hook for a warning or a metric. Defaults to a
183
+ * one-shot `console.warn`.
184
+ */
185
+ onFallback?: (event: CheckpointFallbackEvent) => void;
186
+ }
187
+ /**
188
+ * Resolves the TanStack optimistic-overlay drop against the server's confirmed
189
+ * watermarks. A mutator's optimistic transaction returns `awaitMutationId(id)`
190
+ * (or `awaitCheckpoint(cursor)`); TanStack keeps the overlay until that promise
191
+ * settles, so the row de-duplicates exactly as the synced server value lands — no
192
+ * flash of the optimistic row disappearing then reappearing.
193
+ *
194
+ * Two inputs, deliberately distinct:
195
+ *
196
+ * - {@link CheckpointRegistry.resolve} is the **authoritative** advance, called by whoever owns
197
+ * the watermark stream — a `data`/`delta` frame's `lastMutationId`, or a shape poke's
198
+ * `checkpoint`. The synced rows have landed, so gates open immediately.
199
+ * - {@link CheckpointRegistry.acknowledge} is the **provisional** advance, called when the server
200
+ * has accepted the write (the mutator RPC ack) but the matching rows have not
201
+ * necessarily been delivered yet. Releasing here would drop the overlay before
202
+ * the synced row exists — a visible flicker — so instead it arms a bounded
203
+ * fallback. If the authoritative frame lands first the fallback is cancelled;
204
+ * if it never lands, the overlay is released after `fallbackMs` and the event is
205
+ * reported rather than hanging forever.
206
+ *
207
+ * That pairing is why a lost poke degrades to a late overlay drop instead of a
208
+ * permanently stuck `isPersisted` promise.
209
+ */
210
+ interface CheckpointRegistry {
211
+ /**
212
+ * Record a server-accepted watermark whose rows may not have synced yet: arms
213
+ * the bounded fallback described on {@link CheckpointRegistry}. Safe to call
214
+ * repeatedly; a watermark already passed is a no-op.
215
+ */
216
+ acknowledge: (watermark: CheckpointWatermark) => void;
217
+ /** Resolve once the server has acknowledged the op-log `cursor`. */
218
+ awaitCheckpoint: (cursor: number) => Promise<void>;
219
+ /** Resolve once the server has echoed a `lastMutationId >= id` for this client. */
220
+ awaitMutationId: (id: number) => Promise<void>;
221
+ /**
222
+ * Tear the registry down: `clearTimeout` every armed fallback timer and empty
223
+ * the armed set. Idempotent. A discarded registry (Vite HMR dispose, sign-out)
224
+ * can otherwise hold up to `fallbackMs` of pending `setTimeout`s alive through
225
+ * their closures — keeping a Node/SSR event loop from draining. Distinct from
226
+ * {@link CheckpointRegistry.resolve}: `resolve` settles parked *waiters* (and disarms the timers it
227
+ * subsumes as a side effect); `dispose` guarantees no armed timer survives,
228
+ * independent of any watermark.
229
+ */
230
+ dispose: () => void;
231
+ /** Advance the gates from a sync frame's watermark; later callers past the mark settle immediately. */
232
+ resolve: (watermark: CheckpointWatermark) => void;
233
+ /** Diagnostics counters — notably how often the fallback had to fire. */
234
+ stats: () => CheckpointRegistryStats;
235
+ }
236
+ /** Default fallback window: long enough that a slow-but-arriving poke wins, short enough that a UI isn't visibly stuck. */
237
+ declare const CHECKPOINT_FALLBACK_MS = 3e3;
238
+ /**
239
+ * A standalone checkpoint/mutation-id registry. Prefer {@link getShardCheckpoints}
240
+ * unless you are wiring a bespoke watermark stream — a registry must be shared by
241
+ * every collection on a shard (see that function for why).
242
+ */
243
+ declare const createCheckpointRegistry: (options?: CheckpointRegistryOptions) => CheckpointRegistry;
244
+ /**
245
+ * Release every pending overlay gate for `client` and drop its shard registries.
246
+ *
247
+ * The hot-reload / teardown escape hatch. When a module that owns collections and
248
+ * mutators is replaced — a Vite HMR update, a sign-out that rebuilds the data layer
249
+ * — the *old* bindings may still have transactions parked in `awaitMutationId`. The
250
+ * subscriptions that would have resolved them are gone with the old module, so
251
+ * without this those promises never settle and every one of their
252
+ * `transaction.isPersisted` waiters hangs forever.
253
+ *
254
+ * Resolving to `Infinity` settles the parked waiters (the writes were already sent;
255
+ * the server is authoritative regardless), and dropping the registries means the
256
+ * replacement module's bindings start from a clean per-shard gate.
257
+ *
258
+ * ```ts
259
+ * // In the module that owns the data layer:
260
+ * import.meta.hot?.dispose(() => releaseShardCheckpoints(client));
261
+ * ```
262
+ */
263
+ declare const releaseShardCheckpoints: (client: LunoraClient) => void;
264
+ /**
265
+ * The shared checkpoint registry for `client` + `shardKey` — created on first use.
266
+ * This is the registry {@link lunoraCollectionOptions} and
267
+ * {@link import("./define-mutators").bindMutators} default to, which is what makes
268
+ * a multi-collection shard work without the caller relaying pokes between
269
+ * registries by hand.
270
+ *
271
+ * `options` applies **only when the registry is created**. Because the point is that
272
+ * every collection and mutator on a shard shares one gate, a later call cannot
273
+ * retune an existing registry — it returns the existing one and `options` is ignored.
274
+ * To control `fallbackMs` / `onFallback`, build the registry yourself with
275
+ * {@link createCheckpointRegistry} and pass it explicitly to every
276
+ * `lunoraCollectionOptions` and `bindMutators` call for that shard.
277
+ */
278
+ declare const getShardCheckpoints: (client: LunoraClient, shardKey?: string, options?: CheckpointRegistryOptions) => CheckpointRegistry;
279
+ /**
280
+ * A replication-shape sync source (the local-first partial-replication path).
281
+ * Mutually exclusive with {@link LunoraCollectionConfig.list}: the collection
282
+ * live-syncs the named shape's rowset via the client's poke protocol
283
+ * (`subscribeShape`) instead of a full-table `list` query subscription.
284
+ */
285
+ interface ShapeSource {
286
+ /** Validated shape parameters (the partition selector — e.g. `{ channelId }`). */
287
+ args?: Record<string, unknown>;
288
+ /** The `defineShape` export name registered in `LUNORA_SHAPES`. */
289
+ name: string;
290
+ /** Routes the subscription to a specific shard's DO when the table is sharded. */
291
+ shardKey?: string;
292
+ }
293
+ /** Declarative inputs for {@link lunoraCollectionOptions}. */
294
+ interface LunoraCollectionConfig<TRow extends Row> {
295
+ /**
296
+ * The registry optimistic overlays are gated on. Defaults to the shared
297
+ * per-shard registry ({@link getShardCheckpoints}), which is what a
298
+ * multi-collection shard needs — pass one explicitly only to isolate a
299
+ * collection's gate (tests) or to supply custom {@link CheckpointRegistryOptions}.
300
+ */
301
+ checkpoints?: CheckpointRegistry;
302
+ /** The Lunora client to subscribe through. */
303
+ client: LunoraClient;
304
+ /** Row key extractor — defaults to `row._id`. */
305
+ getKey?: (row: TRow) => string;
306
+ /** Collection id (TanStack identity) — defaults to the `list` function path (or `shape:` + the shape name). */
307
+ id?: string;
308
+ /** The Lunora query that lists the rows (the full-table sync source). Mutually exclusive with {@link LunoraCollectionConfig.shape}. */
309
+ list?: FunctionReference;
310
+ /**
311
+ * When the collection starts syncing. `"lazy"` (default) starts on the first
312
+ * `useLiveQuery` subscriber; `"eager"` starts at creation (TanStack's
313
+ * `startSync`) — for small "instant" reference data you want warm at boot.
314
+ * No effect on a `scopeBy` collection, which has nothing to sync until scoped.
315
+ * (Even eager, TanStack pauses sync while there are no subscribers, per its
316
+ * `gcTime` lifecycle — "warm while referenced", not pinned forever.)
317
+ */
318
+ load?: "eager" | "lazy";
319
+ /** Notified when the underlying subscription errors; the collection always leaves `loading` regardless. */
320
+ onError?: (error: SubscriptionError) => void;
321
+ /** When set, the collection stays empty until {@link LunoraCollectionOptions.scope} points it at args (sharded). */
322
+ scopeBy?: string;
323
+ /** A replication shape as the sync source (partial replication). Mutually exclusive with {@link LunoraCollectionConfig.list}. */
324
+ shape?: ShapeSource;
325
+ /**
326
+ * Routes the `list` subscription — and the confirmed-mutation watermark its
327
+ * data/`settled` frames advance the checkpoint gate from — to a specific
328
+ * shard's DO. Applies to the `list` source; a `shape` carries its own
329
+ * {@link ShapeSource.shardKey}. Without it the list path falls back to the
330
+ * default ("") watermark bucket, which must not be compared against a
331
+ * per-shard mutator's sequence line (it would drop a sharded overlay early or
332
+ * hang it forever).
333
+ */
334
+ shardKey?: string;
335
+ }
336
+ /** The result of {@link lunoraCollectionOptions}: a TanStack collection config plus its sync controls. */
337
+ interface LunoraCollectionOptions<TRow extends Row> {
338
+ /** Resolves optimistic-overlay drops against the server's confirmed watermarks. */
339
+ checkpoints: CheckpointRegistry;
340
+ /** Pass to TanStack's `createCollection`. */
341
+ config: CollectionConfig<TRow, string>;
342
+ /** Re-point a `scopeBy` collection's subscription (omit `args` to detach). No-op for unscoped collections. */
343
+ scope: (args?: Record<string, unknown>) => void;
344
+ }
345
+ /**
346
+ * Build a TanStack DB collection config (+ sync controls) that live-syncs a
347
+ * Lunora `list` query through the client. This is the reusable core lifted out of
348
+ * {@link import("./define-collections").defineCollections}: the same `makeDiffEmit`
349
+ * diff-into-channel, `autoIndex:"eager"` + B-tree indexes, scoped-resubscribe, and
350
+ * fail-safe `markReady`-on-error behavior, exposed as a standalone
351
+ * collection-options creator so apps (and codegen) can compose it directly.
352
+ *
353
+ * The returned `checkpoints` registry lets a mutator runtime resolve optimistic
354
+ * overlays against confirmed server watermarks (see {@link CheckpointRegistry}).
355
+ */
356
+ declare const lunoraCollectionOptions: <TRow extends Row>(options: LunoraCollectionConfig<TRow>) => LunoraCollectionOptions<TRow>;
357
+ export { CHECKPOINT_FALLBACK_MS as C, ExecutorOutboxSinkOptions as E, LunoraCollectionConfig as L, OUTBOX_MUTATION_FN_NAME as O, Row as R, SyncWriter as S, CheckpointFallbackEvent as a, CheckpointRegistry as b, CheckpointRegistryOptions as c, CheckpointRegistryStats as d, CheckpointWatermark as e, LunoraCollectionOptions as f, OutboxExecutor as g, OutboxMutationMetadata as h, createCheckpointRegistry as i, createExecutorOutboxSink as j, createOptimisticOnlineDetector as k, getShardCheckpoints as l, lunoraCollectionOptions as m, makeDiffEmit as n, runOutboxMutation as o, releaseShardCheckpoints as r, toMap as t };
@@ -0,0 +1 @@
1
+ import{lunoraCollectionOptions as T}from"./CHECKPOINT_FALLBACK_MS-DAWfz0yD.mjs";import{createCollection as M,safeRandomUUID as U}from"@tanstack/db";import{startOfflineExecutor as _,NonRetriableError as g}from"@tanstack/offline-transactions";import{createOutboxCarrier as B,createOptimisticOnlineDetector as R,OUTBOX_MUTATION_FN_NAME as K,registerOutboxCarrier as A,runOutboxMutation as I}from"./OUTBOX_MUTATION_FN_NAME-BfFCughR.mjs";const N=new WeakMap,D=(n,r)=>{let e=N.get(n);e===void 0&&(e=new Map,N.set(n,e));const a=e.get(r)??0;e.set(r,a+1),a===1&&console.warn(`[@lunora/db] table "${r}" is bound by more than one defineCollections call on this client. Each call creates its own live collection and outbox for the table, so the two can drift and derived indexes built from one can silently read stale rows. Bind every table in a single defineCollections call (see the "One source of truth per table" docs section).`)},p=(n,r)=>{try{n.onWriteRejected?.(r)}catch{}},v=(n,r)=>{const e=n.replayIdentityVerdict(r?.identity);if(e==="mismatch")throw new g("outbox write dropped: identity changed since it was queued");if(e==="unknown")throw new Error("outbox write deferred: no identity established yet")},k=(n,r,e={})=>{const a={},w={},m={},b=Object.entries(r);for(const[o,t]of b){const i=t.insert;D(n,o);const{config:d,scope:h}=T({client:n,getKey:t.getKey,id:o,list:t.list,...t.load===void 0?{}:{load:t.load},onError:t.onError,scopeBy:t.scopeBy,shardKey:t.shardKey});a[o]=M(d),t.scopeBy!==void 0&&(w[o]=h),i&&(m[o]=async({idempotencyKey:l,transaction:u})=>{const c=u.metadata;for(const[y,F]of u.mutations.entries()){const x=F.modified,E=`${l}:${String(y)}`;try{v(n,c),await I(()=>n.mutation(i.mutation,i.toArgs(x),{mutationId:E,shardKey:c.shardKey}))}catch(f){throw f instanceof g&&p(e,{code:f.code,collection:o,error:f,row:x}),f}}})}m[K]=async({transaction:o})=>{const t=o.metadata;if(t)try{v(n,t),await I(()=>n.mutation({__lunoraRef:t.functionPath},t.args,{mutationId:t.idempotencyKey,shardKey:t.shardKey}))}catch(i){throw i instanceof g&&p(e,{code:i.code,collection:t.functionPath,error:i}),i}};const O=B(),s=_({collections:{...a,[K]:O},mutationFns:m,onlineDetector:R(),...e.onLeadershipChange?{onLeadershipChange:e.onLeadershipChange}:{},...e.onStorageFailure?{onStorageFailure:e.onStorageFailure}:{},onUnknownMutationFn:(o,t)=>{p(e,{code:"UNKNOWN_MUTATION_FN",collection:o,error:new Error(`offline write dropped: mutation "${o}" no longer exists (removed or renamed in a deploy?)`),row:t.mutations[0]?.modified})}});A(s,O);const C={};for(const[o,t]of b){const i=t.insert,d=a[o];!i||!d||(C[o]=h=>{const l=U(),u={identity:n.currentIdentity(),shardKey:t.shardKey},c=s.createOfflineTransaction({autoCommit:!1,metadata:u,mutationFnName:o}),y=c.mutate(()=>{d.insert(i.optimistic(h,l))});return c.commit().catch(()=>{}),{id:l,transaction:y}})}return{actions:C,collections:a,executor:s,pendingCount:()=>s.getPendingCount(),scope:w}};export{k as defineCollections};
@@ -0,0 +1,235 @@
1
+ import { LunoraClient } from '@lunora/client';
2
+ import { Collection, Transaction } from '@tanstack/db';
3
+ import { b as CheckpointRegistry } from "./collection-options.d-BA8jp3ji.mjs";
4
+ /**
5
+ * TanStack DB's "direct transaction" marker.
6
+ *
7
+ * A completed transaction's optimistic rows are discarded as **stale** unless
8
+ * either a synced transaction for the same key is already queued, or the
9
+ * transaction carried this flag (`CollectionStateManager.recomputeOptimisticState`
10
+ * → `pendingOptimisticDirectUpserts`). Marked rows instead survive until a sync
11
+ * operation for that key actually lands, which is precisely the semantics a Lunora
12
+ * custom mutator needs: the server is the linearization point, so the prediction
13
+ * must stay visible until the authoritative row arrives. Without it, a text edit
14
+ * visibly reverts to the last synced value the moment the push is acked.
15
+ *
16
+ * The literal is pinned here because `@tanstack/db` does not re-export the constant
17
+ * from its package root (it lives in the unexported
18
+ * `collection/transaction-metadata` module). `__tests__/define-mutators.test.ts`
19
+ * reads that module off disk and fails if the upstream value ever changes.
20
+ */
21
+ declare const DIRECT_TRANSACTION_METADATA_KEY = "__tanstack_db_direct";
22
+ /**
23
+ * A map of wired collections, keyed by the name the optimistic bodies address them
24
+ * by.
25
+ *
26
+ * The row type is `any` on purpose. `Collection<T, string>` is **invariant** in
27
+ * `T` (its methods both consume and produce rows), so a concrete
28
+ * `Collection<Doc<"nodes"> & Row>` is NOT assignable to `Collection<Row>` — which
29
+ * is why the previous `Record<string, Collection<Row, string>>` forced an
30
+ * `as never` cast on every entry, and left `context.collections.<name>` too
31
+ * untyped to be worth using. Projects recover the concrete types by binding them
32
+ * once through {@link initMutators}.
33
+ */
34
+ type CollectionMap = Record<string, Collection<any, string>>;
35
+ /** The local store a client mutator's optimistic body writes against. */
36
+ interface ClientMutatorContext<TCollections extends CollectionMap = CollectionMap> {
37
+ /** The wired collections, keyed by name — apply optimistic inserts/updates/deletes here. */
38
+ collections: TCollections;
39
+ }
40
+ /**
41
+ * A generated mutator reference (`api.mutators.sendMessage`), accepted by
42
+ * {@link defineMutator} in place of a hand-written path string.
43
+ *
44
+ * Declared structurally rather than imported from `@lunora/client` so this module
45
+ * keeps its narrow dependency surface; the shape matches `FunctionReference`, and
46
+ * the phantom marker carries the server mutator's arg type so the client body's
47
+ * args are **inferred** instead of restated.
48
+ */
49
+ interface MutatorReference<TArgs = unknown> {
50
+ readonly __lunoraPhantom?: {
51
+ args: TArgs;
52
+ kind: unknown;
53
+ returns: unknown;
54
+ };
55
+ readonly __lunoraRef: string;
56
+ }
57
+ /** A client-side custom mutator: an optimistic body plus the path of its authoritative server impl. */
58
+ interface ClientMutatorDef<TArgs, TCollections extends CollectionMap = CollectionMap> {
59
+ /** Brand so codegen / `bindMutators` can recognize a mutator definition. */
60
+ __lunoraClientMutator: true;
61
+ /** The optimistic update applied to the local collections before the server confirms. */
62
+ apply: (context: ClientMutatorContext<TCollections>, args: TArgs) => void;
63
+ /** The Lunora function path of the server-authoritative mutator (`defineMutator` on the server). */
64
+ serverRef: string;
65
+ }
66
+ /**
67
+ * Declare a client-side custom mutator. `apply` runs optimistically against the
68
+ * local TanStack collections; `serverRef` names the authoritative server mutator
69
+ * the write is pushed to over the watermark protocol. The server impl is the
70
+ * linearization point — this body is a prediction the server can override.
71
+ *
72
+ * **Pass a generated reference, not a string.** `serverRef: api.mutators.sendMessage`
73
+ * both binds the path at compile time — a rename, a typo, or a moved file becomes a
74
+ * type error instead of a mutation that silently fails at runtime — and **infers
75
+ * `TArgs` from the server mutator's own validators**, so the arg type is declared
76
+ * once on the server rather than restated in every client body:
77
+ *
78
+ * ```ts
79
+ * // Typed + checked: args inferred from the server mutator.
80
+ * defineMutator({
81
+ * apply: ({ collections }, args) => { … }, // args: { channelId: Id<"channels">; text: string }
82
+ * serverRef: api.mutators.sendMessage,
83
+ * });
84
+ *
85
+ * // Escape hatch: a path string still works, but nothing checks it and you must
86
+ * // restate the args yourself.
87
+ * defineMutator<{ text: string }>({ apply, serverRef: "mutators:sendMessage" });
88
+ * ```
89
+ *
90
+ * `context.collections` is typed by whatever map it is bound to — which for this
91
+ * standalone form is the widest one. Bind the concrete collections once with
92
+ * {@link initMutators} to get `collections.<name>` typed inside `apply`.
93
+ */
94
+ declare const defineMutator: {
95
+ <TArgs = Record<string, unknown>>(definition: {
96
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
97
+ serverRef: string;
98
+ }): ClientMutatorDef<TArgs>;
99
+ <TArgs>(definition: {
100
+ apply: (context: ClientMutatorContext, args: TArgs) => void;
101
+ serverRef: MutatorReference<TArgs>;
102
+ }): ClientMutatorDef<TArgs>;
103
+ };
104
+ /**
105
+ * A mutator map whose defs are bound to `TCollections`, arg types erased — the
106
+ * `TCollections`-pinned counterpart of {@link AnyMutatorMap}, and `any` for the
107
+ * same variance reason.
108
+ */
109
+ type MutatorMapFor<TCollections extends CollectionMap> = Record<string, ClientMutatorDef<any, TCollections>>;
110
+ type AnyMutatorMap = Record<string, ClientMutatorDef<any, any>>;
111
+ /** Args type of a mutator definition, whatever collections map it was bound to. */
112
+ type ArgsOf<M> = M extends ClientMutatorDef<infer A, infer _C> ? A : never;
113
+ /** A mutator write that was permanently rejected, passed to {@link BindMutatorsContext.onWriteRejected}. */
114
+ interface MutatorRejectedEvent {
115
+ /** The args the rejected call was made with. */
116
+ args: unknown;
117
+ /**
118
+ * The machine-readable reason when the server supplied one (e.g. `CONFLICT`,
119
+ * `FORBIDDEN`). Mirrors {@link import("./define-collections").WriteRejectedEvent.code}.
120
+ */
121
+ code?: string;
122
+ /** The error that rejected the write. */
123
+ error: Error;
124
+ /** The bound mutator's key in the map passed to `bindMutators`. */
125
+ mutator: string;
126
+ /** The `namespace:fn` path the push targeted. */
127
+ serverRef: string;
128
+ }
129
+ interface BindMutatorsContext<TCollections extends CollectionMap = CollectionMap> {
130
+ /**
131
+ * Resolves the optimistic-overlay drop against confirmed server watermarks: a
132
+ * mutation's overlay is held until the sync stream echoes
133
+ * `lastMutationId >= clientSeq` (via {@link CheckpointRegistry.resolve}), so the
134
+ * row never flashes out and back.
135
+ *
136
+ * Defaults to the shared per-shard registry for `client` + {@link BindMutatorsContext.shardKey}
137
+ * ({@link getShardCheckpoints}) — the same one
138
+ * {@link import("./collection-options").lunoraCollectionOptions} defaults to, so
139
+ * a shard's collections and its mutators gate on one watermark line without the
140
+ * caller wiring them together. Pass `false` to drop the overlay as soon as the
141
+ * server accepts the write (the by-value sync diff then converges the synced row
142
+ * in place).
143
+ */
144
+ checkpoints?: CheckpointRegistry | false;
145
+ /** The wired collections the optimistic bodies write against. */
146
+ collections: TCollections;
147
+ /**
148
+ * Called when a mutator's server push is permanently rejected — the aggregate
149
+ * failure channel for writes, symmetric with
150
+ * {@link import("./define-collections").DefineCollectionsOptions.onWriteRejected}
151
+ * on the outbox path.
152
+ *
153
+ * Supplying it also makes a **fire-and-forget** call safe: a bound handle
154
+ * returns a `Transaction` whose `isPersisted` promise rejects on failure, so a
155
+ * caller that neither awaits it nor attaches a `.catch` leaves an unhandled
156
+ * rejection. With this hook set, `bindMutators` consumes that rejection itself
157
+ * after reporting it — a caller that DOES await still sees the rejection, so
158
+ * per-call handling is unaffected.
159
+ *
160
+ * A throwing listener is swallowed: reporting a failure must not manufacture a
161
+ * second one.
162
+ */
163
+ onWriteRejected?: (event: MutatorRejectedEvent) => void;
164
+ /** Optional shard key the mutator's server push is routed to. */
165
+ shardKey?: string;
166
+ }
167
+ /** Calling a bound mutator runs the optimistic body + pushes the server write; returns the TanStack transaction. */
168
+ type BoundMutators<M extends AnyMutatorMap> = { [K in keyof M]: (args: ArgsOf<M[K]>) => Transaction; };
169
+ /**
170
+ * Bind a set of client mutators to a client + local store. Each returned handle,
171
+ * when called, opens a TanStack optimistic transaction: the mutator's `apply`
172
+ * body writes the predicted rows into the collections, and the transaction's
173
+ * `mutationFn` pushes the authoritative write through
174
+ * {@link LunoraClient.callMutator} under a monotonic per-client `clientSeq`.
175
+ *
176
+ * Rebase-on-poke is free — TanStack DB re-derives every pending optimistic overlay
177
+ * over the latest synced base on each sync tick. The overlay is dropped when the
178
+ * server confirms the write (and, if `checkpoints` is supplied, once it echoes the
179
+ * matching watermark so the synced row has landed).
180
+ *
181
+ * The `clientSeq` generator is seeded from the server's echoed watermark
182
+ * ({@link LunoraClient.confirmedMutationWatermark}) on every issue, so a reload —
183
+ * which resets this in-memory counter while the server keeps a durable per-client
184
+ * watermark — never reissues a sequence the DO has already applied. As a backstop
185
+ * for the very first push of a fresh session (before any ack has taught the client
186
+ * the watermark), a push the DO swallows as a replay (`applied === false`) is
187
+ * reissued above the now-known watermark instead of being mistaken for a confirmed
188
+ * write — closing the silent-drop window without risking a double-apply (a fresh
189
+ * session's first stale push provably cannot be an honest replay).
190
+ *
191
+ * Pushes are **serialized per binding** (a FIFO chain): the DO rejects any push
192
+ * with `clientSeq > watermark + 1` as `OUT_OF_ORDER` and drops the write, so two
193
+ * mutators fired concurrently must not race the network into a gap. Each push
194
+ * waits for the previous one's ack and assigns its `clientSeq` *inside* the
195
+ * critical section — from the live watermark — so the sequence is always exactly
196
+ * `watermark + 1`. Because a failed mutation never advances the server watermark,
197
+ * a permanently-rejected predecessor can't wedge the chain: the next push simply
198
+ * reclaims the same `watermark + 1` instead of leaving a hole the DO waits on.
199
+ */
200
+ declare const bindMutators: <M extends AnyMutatorMap, TCollections extends CollectionMap = CollectionMap>(client: LunoraClient, context: BindMutatorsContext<TCollections>, mutators: M) => BoundMutators<M>;
201
+ /** `defineMutator` + `bindMutators`, both bound to one project's collections map. */
202
+ interface BoundMutatorApi<TCollections extends CollectionMap> {
203
+ /** {@link bindMutators}, with `collections` pinned to `TCollections`. */
204
+ bindMutators: <M extends MutatorMapFor<TCollections>>(client: LunoraClient, context: BindMutatorsContext<TCollections>, mutators: M) => BoundMutators<M>;
205
+ /** {@link defineMutator}, with `context.collections` typed as `TCollections`. */
206
+ defineMutator: {
207
+ <TArgs = Record<string, unknown>>(definition: {
208
+ apply: (context: ClientMutatorContext<TCollections>, args: TArgs) => void;
209
+ serverRef: string;
210
+ }): ClientMutatorDef<TArgs, TCollections>;
211
+ <TArgs>(definition: {
212
+ apply: (context: ClientMutatorContext<TCollections>, args: TArgs) => void;
213
+ serverRef: MutatorReference<TArgs>;
214
+ }): ClientMutatorDef<TArgs, TCollections>;
215
+ };
216
+ }
217
+ /**
218
+ * Bind the mutator surface to **this project's** collections map, once.
219
+ *
220
+ * `Collection` is invariant in its row type, so a shared
221
+ * `Record<string, Collection<Row, string>>` could neither accept a generated
222
+ * collection without an `as never` cast nor hand a usable type back to `apply` —
223
+ * which is why optimistic bodies tended to ignore `context.collections` and close
224
+ * over module-scope collection variables instead. Declaring the map once here
225
+ * fixes both ends: `bindMutators` takes the concrete collections cast-free, and
226
+ * `apply` reads `collections.<name>` at its real row type.
227
+ *
228
+ * Runtime-identical to the standalone {@link defineMutator} / {@link bindMutators}
229
+ * (this returns those very functions); only the types narrow.
230
+ * @example
231
+ * const { bindMutators, defineMutator } = initMutators<{ nodes: typeof wholeOutlineCollection }>();
232
+ * const setText = defineMutator({ apply: ({ collections }, args) => collections.nodes.update(args.id, setter), serverRef: api.mutators.setText });
233
+ */
234
+ declare const initMutators: <TCollections extends CollectionMap>() => BoundMutatorApi<TCollections>;
235
+ export { BindMutatorsContext as B, ClientMutatorContext as C, DIRECT_TRANSACTION_METADATA_KEY as D, MutatorReference as M, BoundMutatorApi as a, BoundMutators as b, ClientMutatorDef as c, CollectionMap as d, MutatorRejectedEvent as e, bindMutators as f, defineMutator as g, initMutators as i };