@lunora/client 1.0.0-alpha.9 → 1.0.0-alpha.91

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 (90) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/auth/index.d.mts +12 -10
  4. package/dist/auth/index.d.ts +12 -10
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +893 -247
  7. package/dist/index.d.ts +893 -247
  8. package/dist/index.mjs +1 -15
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-BOeeP_Wl.mjs +1 -0
  10. package/dist/packem_shared/ClientServiceWorker-DXnBXeWK.mjs +1 -0
  11. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  12. package/dist/packem_shared/LunoraClient-DArMFG67.mjs +1 -0
  13. package/dist/packem_shared/OfflineQueue-ZapYrAVi.mjs +1 -0
  14. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  15. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  16. package/dist/packem_shared/SubscriptionRegistry-CS-AFUI9.mjs +1 -0
  17. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  18. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  19. package/dist/packem_shared/applyDelta-DwcQmRsV.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs +1 -0
  21. package/dist/packem_shared/createAsyncStorageQueryCache-BfZkthAE.mjs +1 -0
  22. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  23. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  26. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  27. package/dist/packem_shared/createLocalStore-nwwRbT0L.mjs +1 -0
  28. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  29. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  30. package/dist/packem_shared/createReply-CwFABEJs.mjs +1 -0
  31. package/dist/packem_shared/createServerClient-BrNyme3I.mjs +1 -0
  32. package/dist/packem_shared/createSnapshotPrecondition-GRVKxPsh.mjs +1 -0
  33. package/dist/packem_shared/delta-merge-vxvH3PvF.mjs +1 -0
  34. package/dist/packem_shared/deserializePreloaded-C6NTQdFa.mjs +1 -0
  35. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  36. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  37. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  38. package/dist/packem_shared/httpStream-CPdblK2G.mjs +11 -0
  39. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  40. package/dist/packem_shared/local-store-CVfQDdXy.mjs +1 -0
  41. package/dist/packem_shared/lunora-client.d-C5tvkz8x.d.mts +3891 -0
  42. package/dist/packem_shared/lunora-client.d-CK3FxGNH.d.ts +3891 -0
  43. package/dist/packem_shared/offline-queue-xntsWiKt.mjs +1 -0
  44. package/dist/packem_shared/preload.d-CAXl1Y8Y.d.mts +21 -0
  45. package/dist/packem_shared/preload.d-Csjxr5HM.d.ts +21 -0
  46. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  47. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  48. package/dist/packem_shared/wire-codec-Sw1rAu-Z.mjs +1 -0
  49. package/dist/packem_shared/wire-key-HsUDTlQ7.mjs +1 -0
  50. package/dist/pagination/index.d.mts +42 -42
  51. package/dist/pagination/index.d.ts +42 -42
  52. package/dist/pagination/index.mjs +1 -61
  53. package/dist/query/index.d.mts +111 -43
  54. package/dist/query/index.d.ts +111 -43
  55. package/dist/query/index.mjs +1 -1
  56. package/dist/service.d.mts +49 -0
  57. package/dist/service.d.ts +49 -0
  58. package/dist/service.mjs +1 -0
  59. package/dist/ssr/index.d.mts +109 -79
  60. package/dist/ssr/index.d.ts +109 -79
  61. package/dist/ssr/index.mjs +1 -4
  62. package/dist/upload.d.mts +35 -0
  63. package/dist/upload.d.ts +35 -0
  64. package/dist/upload.mjs +1 -0
  65. package/package.json +16 -1
  66. package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +0 -4
  67. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  68. package/dist/packem_shared/LunoraClient-C4eFp92b.mjs +0 -2598
  69. package/dist/packem_shared/OfflineQueue-eJBiWPfg.mjs +0 -134
  70. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  71. package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +0 -1
  72. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  73. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  74. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  75. package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +0 -105
  76. package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +0 -138
  77. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +0 -1
  78. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  79. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  80. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  81. package/dist/packem_shared/createServerClient-PHoMdNGJ.mjs +0 -11
  82. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  83. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  84. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +0 -111
  85. package/dist/packem_shared/lunora-client.d-CfwxuJo8.d.mts +0 -2106
  86. package/dist/packem_shared/lunora-client.d-CfwxuJo8.d.ts +0 -2106
  87. package/dist/packem_shared/preload.d-Bbn8plix.d.mts +0 -20
  88. package/dist/packem_shared/preload.d-DuMetDdU.d.ts +0 -20
  89. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  90. package/dist/packem_shared/subscription-C1Jy7HiF.mjs +0 -55
package/dist/index.d.mts CHANGED
@@ -1,13 +1,180 @@
1
- import { c as PersistenceAdapter, B as BookmarkStorage, F as FunctionReference, A as ArgsOf, M as MutationCallOptions, R as ReturnOf, O as OfflineQueueOptions, Q as QueryCacheAdapter, d as ReconnectOptions } from "./packem_shared/lunora-client.d-CfwxuJo8.mjs";
2
- export { type C as CachedQuery, type e as ClientMessage, type f as ClientShapeSubscribeMessage, type g as ClientShapeUnsubscribeMessage, type h as ConnectionStatus, D as DEFAULT_MAX_BUFFER, type i as FunctionArgumentDescriptor, type j as FunctionDescriptor, type G as GlobalFacetResult, type k as GlobalFacetValue, type l as GlobalFilterClause, type m as GlobalTableInfo, type n as GlobalTablePage, L as LunoraClient, type o as LunoraClientOptions, type p as MutationSettledEvent, type q as OptimisticLocalStore, type r as OptimisticUpdate, type s as OutboxMutation, type t as OutboxSink, type u as PersistedMutation, type P as Preloaded, type v as RowOp, type w as RpcEnvelope, type x as RpcResponseBody, type y as ScheduleRecord, type z as SchedulerPoolStatus, type E as SchedulerStatus, type H as ServerMessage, type I as ServerPokeEndMessage, type J as ServerPokePartMessage, type K as ServerPokeStartMessage, type N as ShardTrafficEntry, type T as ShardTrafficResult, type V as StorageListPage, type W as StorageObject, type X as StreamHandle, type Y as StreamIterable, type Z as SubscriptionCallback, type S as SubscriptionError, type b as SubscriptionErrorCallback, _ as SubscriptionRegistry, type $ as SubscriptionState, type a0 as SyncWatermark, type a as Unsubscribe, type U as User, type a1 as WorkflowInstanceAction, type a2 as WorkflowInstanceDetail, type a3 as WorkflowInstancePage, type a4 as WorkflowInstanceStatus, type a5 as WorkflowInstanceSummary, type a6 as WorkflowStepDetail, a7 as createLocalStore, a8 as createStream } from "./packem_shared/lunora-client.d-CfwxuJo8.mjs";
3
- export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-Bbn8plix.mjs";
4
- export type { AuthCapabilities, AuthImpersonation, AuthPage, AuthSession, AuthUser, CronJobInfo, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
5
- /**
6
- * The slice of React Native's `AsyncStorage` (or any async key/value store —
7
- * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
8
- * adapter needs. Matches `@react-native-async-storage/async-storage`'s core
9
- * surface, so you can pass the module straight in.
10
- */
1
+ import { c as PersistenceAdapter, Q as QueryCacheAdapter, B as BookmarkStorage, C as ConnectionStatus, S as SubscriptionError, H as HttpStreamRef, d as HttpStreamArgsOf, e as HttpStreamChunkOf, f as StreamIterable, O as OfflineQueueOptions, R as ReconnectOptions, L as LunoraClient } from "./packem_shared/lunora-client.d-C5tvkz8x.mjs";
2
+ export { type A as ActionCallOptions, type g as BatchSlot, type h as CachedQuery, type i as ClientDebugShard, type j as ClientDebugSnapshot, type k as ClientDebugSubscription, type l as ClientMessage, type m as ClientQueryRef, type n as ClientShapeSubscribeMessage, type o as ClientShapeUnsubscribeMessage, D as DEFAULT_MAX_BUFFER, type F as FunctionArgumentDescriptor, type p as FunctionDescriptor, type G as GlobalFacetResult, type q as GlobalFacetValue, type r as GlobalFilterClause, type s as GlobalTableInfo, type t as GlobalTablePage, type u as HttpStreamCallArgs, type v as LunoraClientError, type w as LunoraClientOptions, type M as MutationCallOptions, type x as MutationSettledEvent, type y as OptimisticLocalStore, type z as OptimisticUpdate, type E as OutboxMutation, type I as OutboxSink, type J as PersistedMutation, type P as Preloaded, type K as RowOp, type N as RpcEnvelope, type T as RpcResponseBody, type V as ScheduleRecord, type W as ScheduleRetryPolicy, type X as SchedulerPoolStatus, type Y as SchedulerStatus, type Z as ServerMessage, type _ as ServerPokeEndMessage, type $ as ServerPokePartMessage, type a0 as ServerPokeStartMessage, type a1 as ShardTrafficEntry, type a2 as ShardTrafficResult, type a3 as StorageListPage, type a4 as StorageObject, type a5 as StoredQuery, type a6 as StreamHandle, type a7 as SubscriptionCallback, type b as SubscriptionErrorCallback, a8 as SubscriptionRegistry, type a9 as SubscriptionState, type aa as SyncWatermark, type a as Unsubscribe, type U as User, type ab as WorkflowInstanceAction, type ac as WorkflowInstanceDetail, type ad as WorkflowInstancePage, type ae as WorkflowInstanceStatus, type af as WorkflowInstanceSummary, type ag as WorkflowStepDetail, type ah as WsTokenProvider, ai as createClientQuery, aj as createLocalStore, ak as createStream } from "./packem_shared/lunora-client.d-C5tvkz8x.mjs";
3
+ import { LunoraError, LunoraErrorCode } from '@lunora/errors';
4
+ export type { LunoraErrorCode } from '@lunora/errors';
5
+ export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CAXl1Y8Y.mjs";
6
+ import { F as FunctionReference } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
7
+ export type { A as ArgsOf, R as ReturnOf } from "./packem_shared/function-reference.d-Br_hsKje.mjs";
8
+ export type { AuthCapabilities, AuthConfigInfo, AuthImpersonation, AuthPage, AuthSession, AuthUser, AuthUserFieldSpec, CronJobInfo, KvKeyEntry, KvKeyListResult, KvNamespaceSummary, KvValueResult, PipelineLogColumnMap, PipelineLogCursor, PipelineLogField, PipelineLogPage, PipelineLogQuery, PipelineLogRow, VectorIndexSummary, VectorQueryMatch } from '@lunora/runtime';
9
+ /**
10
+ * A failure the SERVER reached no verdict on: the response carried no
11
+ * `{ error }` envelope at all — no `fetch` implementation, a non-JSON body from
12
+ * a proxy, a bare 5xx gateway page.
13
+ *
14
+ * The distinction matters because a durable write must be re-queued rather than
15
+ * dropped, and `code` cannot carry it: these arrive as `INTERNAL`, which is also
16
+ * what a server that DID reach a verdict sends. It used to be a `Symbol` stamped
17
+ * on with `Object.assign` and read back through a `Record<symbol, unknown>`
18
+ * cast, so the one classifier that knew the convention was the only reader that
19
+ * could ever see it. As a kind, every reader can: `error instanceof
20
+ * TransportError`.
21
+ *
22
+ * Still `INTERNAL` on the wire, so nothing that switches on `code` changes.
23
+ *
24
+ * `data` carries the structured payload such an error can still have — the
25
+ * `{ retryAfterMs }` a `Retry-After` on the unreadable response named, which
26
+ * {@link getRetryAfterMs} reads back and the outbox paces its retry on.
27
+ */
28
+ declare class TransportError extends LunoraError {
29
+ constructor(message: string, data?: unknown);
30
+ }
31
+ /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
32
+ declare const CONFLICT_ERROR_CODE = "CONFLICT";
33
+ /**
34
+ * Whether an unknown rejection is an optimistic-concurrency conflict — the
35
+ * server lost a write race and the caller should refetch and retry (or surface
36
+ * the conflict). Structural check on the `code` property the client attaches
37
+ * when decoding the worker's `{ error: { code, message } }` envelope.
38
+ */
39
+ declare const isConflictError: (error: unknown) => error is Error & {
40
+ code: "CONFLICT";
41
+ };
42
+ /**
43
+ * Whether a rejection is an RLS/policy denial (`FORBIDDEN`, HTTP 403) — the
44
+ * caller is authenticated but not permitted to read/write the row. The most
45
+ * common per-call error a UI must handle in an RLS-first app.
46
+ */
47
+ declare const isForbiddenError: (error: unknown) => error is Error & {
48
+ code: "FORBIDDEN";
49
+ };
50
+ /** Whether a rejection is an authentication failure (`UNAUTHORIZED`, HTTP 401) — no/invalid identity. */
51
+ declare const isUnauthorizedError: (error: unknown) => error is Error & {
52
+ code: "UNAUTHORIZED";
53
+ };
54
+ /**
55
+ * Whether a rejection is a rate-limit denial (`TOO_MANY_REQUESTS`, HTTP 429).
56
+ * The retry hint (if the server sent one) is read with {@link getRetryAfterMs}.
57
+ */
58
+ declare const isRateLimitedError: (error: unknown) => error is Error & {
59
+ code: "TOO_MANY_REQUESTS";
60
+ };
61
+ /**
62
+ * Read the server's machine-readable `code` off a rejection, narrowed to the
63
+ * known {@link LunoraErrorCode} union. Returns `undefined` for a non-`Error`, a
64
+ * missing code, or a code string absent from the catalog (an app-minted code
65
+ * passed to `LunoraError` reads as `undefined` here rather than being falsely
66
+ * narrowed).
67
+ */
68
+ declare const getErrorCode: (error: unknown) => LunoraErrorCode | undefined;
69
+ /**
70
+ * Read the rate-limit retry hint (`data.retryAfterMs`) off a
71
+ * `TOO_MANY_REQUESTS` rejection without hand-casting the `unknown` `data`
72
+ * payload. Returns the finite millisecond value the server sent, or `undefined`
73
+ * when absent/non-numeric. Pair with {@link isRateLimitedError}.
74
+ */
75
+ declare const getRetryAfterMs: (error: unknown) => number | undefined;
76
+ declare const anyApi: Record<string, Record<string, unknown>>;
77
+ /**
78
+ * Optimistic-reconcile logic shared by every `@lunora/*` framework adapter's
79
+ * agent-chat surface (`@lunora/react` `useAgentChat`, plus the `@lunora/vue`,
80
+ * `@lunora/solid`, `@lunora/svelte`, and `@lunora/angular` counterparts). The
81
+ * adapters keep only their framework-specific state plumbing
82
+ * (`useState` / `.value` / `.set()` / a store) and delegate the pure merge decision
83
+ * here, so the heuristic lives — and is tested — in exactly one place.
84
+ */
85
+ /**
86
+ * The durable-message shape the reconcile reads: a structural subset of each
87
+ * adapter's `AgentChatMessage` (itself a client-safe mirror of `@lunora/agent`'s
88
+ * `AgentMessageRow`). Only `content`, `role`, and the per-thread-monotonic `seq` are
89
+ * consulted; adapters pass their fuller row type, which is assignable to this.
90
+ */
91
+ interface ReconcileDurableMessage {
92
+ content: string;
93
+ role: "assistant" | "system" | "tool" | "user";
94
+ seq: number;
95
+ }
96
+ /**
97
+ * A local optimistic user turn awaiting server acknowledgement. `id` is a
98
+ * client-generated handle the adapter uses to roll the row back on a failed send;
99
+ * the reconcile itself reads only `content` and `maxDurableSeqAtSend`.
100
+ */
101
+ interface OptimisticMessage {
102
+ content: string;
103
+ id: number;
104
+ /**
105
+ * The highest durable `seq` present when this row was sent. The reconcile
106
+ * retires the row when a durable `user` row with matching `content` lands at a
107
+ * STRICTLY GREATER `seq` (i.e. after the send) — window-independent because
108
+ * `seq` is monotonic, not a positional count. Also the age baseline for the
109
+ * {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} fallback.
110
+ *
111
+ * `seq` is monotonic PER THREAD, not globally (`@lunora/agent` assigns it from
112
+ * the thread's own message count), so a baseline captured in one thread is
113
+ * meaningless in another: an optimistic row carried across a thread switch can
114
+ * never be retired by the new thread's history until its `seq` happens to pass
115
+ * the old thread's. Adapters therefore drop their optimistic rows whenever the
116
+ * resolved thread key changes.
117
+ */
118
+ maxDurableSeqAtSend: number;
119
+ }
120
+ /**
121
+ * The highest `seq` across `messages`, or `-1` when empty. Used both to capture an
122
+ * optimistic row's `maxDurableSeqAtSend` at send time and to base the synthetic
123
+ * seqs of rendered optimistic rows above the highest real durable seq (not just
124
+ * `messages.length`, which under-counts when durable rows have gaps), so a
125
+ * placeholder seq never collides with a real one.
126
+ */
127
+ declare const maxSeq: (messages: ReadonlyArray<{
128
+ seq: number;
129
+ }>) => number;
130
+ /**
131
+ * Secondary, windowed fallback: retire a pending optimistic row once the durable
132
+ * history's highest `seq` has advanced at least this far past the value seen at
133
+ * send, even though no matching-content user row is currently visible to claim it.
134
+ * This covers the pathological "identical content already present at send time"
135
+ * case, where no user row with a STRICTLY GREATER `seq` than the send-time max will
136
+ * ever appear for the primary content match to consume (e.g. the acknowledging row
137
+ * was evicted by a bounded `limit` before reconcile could see it). `seq` is monotonic
138
+ * within the thread, so it keeps climbing even when the visible user-row COUNT does not.
139
+ *
140
+ * The `2` is a heuristic threshold, NOT an invariant about turn shape. It is
141
+ * tempting to read it as "one turn == a user row and an assistant row (+2)", but
142
+ * `@lunora/agent`'s tool-loop turns can persist MANY rows, and an ERRORED turn
143
+ * persists only the user row (+1). Those non-(+2) turns are retired by the PRIMARY
144
+ * seq-based content match below (which sees the user row land at a greater `seq`),
145
+ * never by this count-based fallback. The fully robust fix is a server-echoed
146
+ * correlation id on each persisted user row (deferred — see plan 188).
147
+ *
148
+ * KNOWN LIMITATION (inherent to a client-only heuristic): on an ownerless /
149
+ * `instanceId`-less thread a FOREIGN writer that advances `seq` by >= 2 between this
150
+ * row's send and its own acknowledgement can trip this fallback and retire the row a
151
+ * beat early. The correlation id closes that gap; until then it is the accepted
152
+ * residual edge.
153
+ */
154
+ declare const RETIRE_AFTER_DURABLE_SEQ_ADVANCE = 2;
155
+ /**
156
+ * Drop the optimistic user turns the durable history has now caught up on. Pure —
157
+ * it reads only the two arrays plus values captured on each pending row at send
158
+ * time (no clock, no state mutation), so it is safe to run in render.
159
+ *
160
+ * The primary retire condition: a durable `user` row with the same `content` exists
161
+ * whose `seq` is STRICTLY GREATER than the row's `maxDurableSeqAtSend` — i.e. a user
162
+ * row that landed AFTER the send. This is window-independent (it matches on monotonic
163
+ * `seq`, not a positional count), so it retires the normal turn AND an errored
164
+ * single-row (+1) turn even under a saturated, sliding `limit`. Each durable row is
165
+ * consumed at most once (the `consumed` set), so repeated identical prompts sent
166
+ * back-to-back each wait for their OWN durable row instead of collapsing onto one.
167
+ *
168
+ * Failing that, the {@link RETIRE_AFTER_DURABLE_SEQ_ADVANCE} windowed fallback fires
169
+ * (see its doc) for the "identical content already present" pathological case.
170
+ */
171
+ declare const reconcileOptimistic: (optimistic: ReadonlyArray<OptimisticMessage>, durable: ReadonlyArray<ReconcileDurableMessage>) => OptimisticMessage[];
172
+ /**
173
+ * The slice of React Native's `AsyncStorage` (or any async key/value store —
174
+ * Expo `SecureStore`, a wrapped `localForage`, an in-memory map in tests) this
175
+ * adapter needs. Matches `@react-native-async-storage/async-storage`'s core
176
+ * surface, so you can pass the module straight in.
177
+ */
11
178
  interface AsyncStorageLike {
12
179
  getItem: (key: string) => Promise<string | null>;
13
180
  removeItem: (key: string) => Promise<void>;
@@ -20,46 +187,325 @@ interface AsyncStoragePersistenceOptions {
20
187
  storage: AsyncStorageLike;
21
188
  }
22
189
  /**
23
- * Builds a {@link PersistenceAdapter} over an async key/value store — the React
24
- * Native / Expo counterpart to the IndexedDB adapter (`createIndexedDbPersistence`).
25
- * The whole FIFO mutation log is serialized to JSON under a single key (`key`),
26
- * so enqueue order is preserved and `load()` returns freshly-parsed records that
27
- * callers can't alias.
28
- *
29
- * AsyncStorage has no transactions, so every read-modify-write is funnelled
30
- * through a single promise chain — concurrent `append`/`remove` calls run one at
31
- * a time and can't clobber each other's writes.
32
- */
190
+ * Builds a {@link PersistenceAdapter} over an async key/value store — the React
191
+ * Native / Expo counterpart to the IndexedDB adapter (`createIndexedDbPersistence`).
192
+ * The whole FIFO mutation log is serialized to JSON under a single key (`key`),
193
+ * so enqueue order is preserved and `load()` returns freshly-parsed records that
194
+ * callers can't alias.
195
+ *
196
+ * AsyncStorage has no transactions, so every read-modify-write runs through
197
+ * {@link singleBlobStore}'s serialized chain — concurrent `append`/`remove`
198
+ * calls run one at a time and can't clobber each other's writes.
199
+ */
33
200
  declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => PersistenceAdapter;
201
+ interface AsyncStorageQueryCacheOptions {
202
+ /** Storage key the cache is serialized under; defaults to `"lunora:query-cache"`. */
203
+ key?: string;
204
+ /** LRU row cap; defaults to 50 (see {@link DEFAULT_MAX_ENTRIES}). Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
205
+ maxEntries?: number;
206
+ /** The async key/value store the cache is read from and written to (e.g. React Native `AsyncStorage`). */
207
+ storage: AsyncStorageLike;
208
+ }
209
+ /**
210
+ * Builds a {@link QueryCacheAdapter} over an async key/value store — the React
211
+ * Native / Expo counterpart to `createIndexedDbQueryCache`. The whole cache is
212
+ * serialized under a single key (`key`).
213
+ *
214
+ * Values pass through the transport's {@link encodeWire}/{@link decodeWire}
215
+ * codec, NOT raw `JSON.stringify`. What this cache holds is a decoded SERVER
216
+ * value — whatever the query returned, including the `bigint`, `Date`, `Map`,
217
+ * `Set`, `ArrayBuffer`/typed-array, and `NaN`/`Infinity` leaves `decodeWire`
218
+ * just reconstructed on the way in. Raw JSON would mangle every one of them
219
+ * (`Date` to a string, bytes to `{}`, `NaN` to `null`) or throw outright on a
220
+ * `bigint`, and nothing would ever repair it: a `resume` frame keeps the
221
+ * hydrated value as-is, so the damage would survive every reconnect and every
222
+ * delta merged onto it. The IndexedDB sibling gets this for free via structured
223
+ * clone; here it is explicit. (This is what separates the read cache from the
224
+ * outbox, which stores JSON-safe args the caller chose.)
225
+ *
226
+ * AsyncStorage has no transactions, so every read-modify-write runs through
227
+ * {@link singleBlobStore}'s serialized chain — concurrent `put`/`remove` calls
228
+ * run one at a time and can't clobber each other's writes.
229
+ *
230
+ * Single-blob storage rewrites the whole cache per `put` (bounded by
231
+ * `maxEntries` — see the cap's note on Android's row and shared-budget limits);
232
+ * if that ever shows up in profiles, per-key storage entries are the upgrade
233
+ * path.
234
+ */
235
+ declare const createAsyncStorageQueryCache: (options: AsyncStorageQueryCacheOptions) => QueryCacheAdapter;
34
236
  /** Default in-memory bookmark store. Survives the lifetime of the client. */
35
237
  declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
36
238
  /**
37
- * Client-side incremental merging of structured mutation deltas.
38
- *
39
- * Lunora's live-query fan-out has two server paths:
40
- *
41
- * 1. Server re-execution (subscriptions carrying a `functionPath`) pushes a
42
- * full `data` snapshot whenever a write touches a table the query reads. These
43
- * already carry the authoritative result and are applied wholesale.
44
- * 2. Legacy delta fan-out (`broadcastDelta`) pushes a structured `MutationDelta`
45
- * as a `delta` frame to subscribers matched by table + args. The delta describes
46
- * a single row change (`insert` / `update` / `delete`) keyed by row id, so the
47
- * client can splice it into the cached list result without a full re-send.
48
- *
49
- * Historically the client treated the `delta` field as an opaque blob and
50
- * replaced the whole cached value with it on every message — which only made
51
- * sense for the rare delta payloads that already carried the full result. This
52
- * module lets the client recognise a structured delta and merge it into the
53
- * existing array (preserving order, no dup/loss), falling back to full
54
- * replacement when the payload isn't a recognisable row delta or can't be
55
- * applied cleanly against the current cached shape.
56
- */
57
- /**
58
- * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
59
- * `MutationDelta` in `@lunora/do` structurally so the client carries no
60
- * dependency on it. `row` is absent on `delete` events (and may be absent on
61
- * older servers for any op).
62
- */
239
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
240
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
241
+ * them; how they store the value is the adapter's concern (e.g. Solid and React
242
+ * wrap function-valued results in a thunk so the setter stores them rather than
243
+ * invoking them).
244
+ */
245
+ interface CallRunnerSinks<R> {
246
+ /** Receives the normalized {@link Error} when the latest invocation rejects. */
247
+ setError: (error: Error) => void;
248
+ /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
249
+ setPending: (pending: boolean) => void;
250
+ /** Receives the resolved value when the latest invocation succeeds. */
251
+ setResult: (result: R) => void;
252
+ }
253
+ /**
254
+ * Build the framework-neutral half of an adapter's write primitive the `mutate`
255
+ * of `useMutation`/`createMutation`/`mutation`, and the `call` of
256
+ * `useAction`/`createAction`/`action`.
257
+ *
258
+ * It owns the orchestration every adapter otherwise copy-pastes: ref-counting
259
+ * overlapping invocations into `setPending` (so the flag clears only once the
260
+ * last settles), normalizing a thrown non-`Error`, and routing success/failure to
261
+ * `setResult`/`setError` before re-throwing the SAME instance (so a typed error's
262
+ * `.code`/`.data` survive for both the `catch` and the template).
263
+ *
264
+ * `invoke` is a pre-bound thunk — `(args, options) => client.mutation(fn, args, options)`
265
+ * or `(args, options) => client.action(fn, args, options)`. Binding at the call
266
+ * site is what keeps this one function: the runner never inspects `options`, it
267
+ * only forwards them, so the option type is inferred from the closure rather
268
+ * than hard-coded per procedure kind. What actually keeps `optimisticUpdate` off
269
+ * an action is the adapter's exported handle type, not this file.
270
+ *
271
+ * `data`/`error` track the LATEST invocation, not the last to settle: overlapping
272
+ * calls can resolve out of order, so an earlier call that finishes later must not
273
+ * clobber a newer call's outcome. Each invocation takes a monotonic token and
274
+ * writes the value sinks only while it is still the most recent one — otherwise a
275
+ * double-click could leave the UI showing the first click's result, or an error
276
+ * for a call that succeeded.
277
+ */
278
+ declare const createCallRunner: <A, O, R>(invoke: (args: A, options?: O) => Promise<R>, sinks: CallRunnerSinks<R>) => ((args: A, options?: O) => Promise<R>);
279
+ interface TabCoordinatorOptions {
280
+ /**
281
+ * BroadcastChannel name. Defaults to `"lunora-bridge"`.
282
+ */
283
+ channelName?: string;
284
+ /**
285
+ * Interval (ms) between leader heartbeats. Defaults to 1000.
286
+ */
287
+ heartbeatInterval?: number;
288
+ /**
289
+ * Milliseconds without a heartbeat to consider the leader dead. Must be
290
+ * larger than `heartbeatInterval`. Defaults to 3000.
291
+ */
292
+ leaderTimeout?: number;
293
+ /**
294
+ * Called when this tab becomes the leader (should open WS connections).
295
+ */
296
+ onBecomeLeader?: () => void;
297
+ /**
298
+ * Called when the leader broadcasts its aggregate `ConnectionStatus`
299
+ * (see `LunoraClient.emitConnectionStatus`) — a follower owns no socket
300
+ * of its own, so this is its only truthful signal for a status indicator
301
+ * or the offline-queue gate. Sent on every leader-side status change and
302
+ * once more right after a new leader takes over, so a follower already
303
+ * mid-mirroring isn't stuck on a stale value from the PREVIOUS leader.
304
+ *
305
+ * `identity` is the leader's own `identityFingerprint()` (`null` = signed
306
+ * out) — the channel-name scoping (see `LunoraClient.createTabCoordinator`)
307
+ * is the primary defence against a stale frame from a since-changed
308
+ * identity, but `setAuthToken` in one tab can move it to a new channel
309
+ * while this frame is already queued in another tab's message task queue.
310
+ * A follower drops the frame when `identity` is present and doesn't match
311
+ * its own; an **absent** `identity` (mixed-version leader) is accepted —
312
+ * today's behavior, and the channel split already separates version groups.
313
+ */
314
+ onConnectionStatus?: (status: ConnectionStatus, identity?: string | null) => void;
315
+ /**
316
+ * Called when the leader broadcasts a subscription error.
317
+ */
318
+ /** Fired on the LEADER when it answers another tab's leadership claim — the moment a new follower is known to be listening. */
319
+ onLeaderClaimAnswered?: () => void;
320
+ /**
321
+ * Called when this tab loses leadership (should close WS connections).
322
+ */
323
+ onStopBeingLeader?: () => void;
324
+ /**
325
+ * Called when the leader broadcasts subscription data. `cursor`/`epoch`
326
+ * ride along when the leader is CLIENT-01-aware, so the follower can drop
327
+ * its own confirmed optimistic layers instead of just displaying the raw
328
+ * value; both are absent on a mixed-version leader that hasn't shipped the
329
+ * cursor yet (the follower falls back to its historical behavior — see
330
+ * `lunora-client.ts`'s `onSubscriptionData` wiring).
331
+ *
332
+ * `identity` is the leader's `identityFingerprint()` (see
333
+ * `onConnectionStatus`'s docblock for the full rationale and the
334
+ * absent-field mixed-version rule — identical here).
335
+ */
336
+ onSubscriptionData?: (key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null) => void;
337
+ onSubscriptionError?: (key: string, error: SubscriptionError, identity?: string | null) => void;
338
+ /**
339
+ * Called when the leader broadcasts a `settled` frame's checkpoint advance
340
+ * (no value change, but the resume cursor moved). A follower needs this
341
+ * too — otherwise a `setQuery`/per-call optimistic overlay that a
342
+ * byte-identical write just confirmed stays masked on follower tabs until
343
+ * the next VISIBLE data frame arrives, even though the leader already
344
+ * dropped it.
345
+ *
346
+ * `lastMutationId` is the LEADER's own per-client `__client_watermark` —
347
+ * scoped server-side to the socket's announced `clientId` — so it only
348
+ * means anything to a follower whose `clientId` matches the leader's
349
+ * (`clientId` rides along for exactly that comparison; see
350
+ * `LunoraClient`'s wiring). An **absent** `clientId` (a mixed-version
351
+ * leader that hasn't shipped this field yet) also skips the
352
+ * `mutationId` half — safe, because the follower's own gates still
353
+ * resolve via its own RPC-ack watermark path and the `CheckpointRegistry`
354
+ * bounded fallback. The checkpoint (cursor) half of this callback fires
355
+ * unconditionally regardless of `clientId` — only the `mutationId` half
356
+ * is scoped.
357
+ *
358
+ * `identity` is the leader's `identityFingerprint()` — see
359
+ * `onConnectionStatus`'s docblock for the drop rule (identical here).
360
+ */
361
+ onSubscriptionSettled?: (key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null) => void;
362
+ }
363
+ declare class TabCoordinator {
364
+ private readonly bc;
365
+ private readonly tabId;
366
+ private readonly heartbeatInterval;
367
+ private readonly leaderTimeout;
368
+ /** The tab id of the current known leader, or `undefined` if no leader. */
369
+ private knownLeader;
370
+ /** `true` when this tab believes it is the leader. */
371
+ private leader;
372
+ /** `true` once `start()` has been called. */
373
+ private running;
374
+ /**
375
+ * `true` while a `claimAndPromote()` claim window is open. Guards the yield
376
+ * handler and `checkLeaderHealth`'s belt-and-braces else-branch so the two
377
+ * promotion paths can't both arm a `becomeLeader` timeout for the same gap.
378
+ */
379
+ private promotionPending;
380
+ /** Timestamp of the most recent leader heartbeat. */
381
+ private lastHeartbeat;
382
+ private heartbeatTimer;
383
+ private leaderCheckTimer;
384
+ /** Callbacks set via constructor options. */
385
+ private readonly onBecomeLeader;
386
+ private readonly onStopBeingLeader;
387
+ private readonly onConnectionStatus;
388
+ private readonly onSubscriptionData;
389
+ private readonly onLeaderClaimAnswered;
390
+ private readonly onSubscriptionError;
391
+ private readonly onSubscriptionSettled;
392
+ constructor(options?: TabCoordinatorOptions);
393
+ /**
394
+ * Start the coordinator: attempt to claim leadership and begin the
395
+ * heartbeat/leader-check cycle. Safe to call multiple times.
396
+ */
397
+ start(): void;
398
+ /**
399
+ * Stop the coordinator: yield leadership (if held), close the channel, and
400
+ * clear all timers. Safe to call multiple times.
401
+ */
402
+ stop(): void;
403
+ /** `true` when this tab is the current WebSocket leader. */
404
+ isLeader(): boolean;
405
+ /**
406
+ * Force this (freshly `start()`-ed) tab to become leader immediately,
407
+ * skipping the normal claim-then-`leaderTimeout` dance. Safe to call
408
+ * right after `start()` when the caller already knows this tab was the
409
+ * SOLE leader of the group it's replacing (e.g. `LunoraClient`'s
410
+ * identity-change coordinator restart — waiting out the full
411
+ * `leaderTimeout` there would freeze every live query for no reason,
412
+ * since this tab is overwhelmingly likely to be alone on the freshly
413
+ * derived channel). A sibling tab going through the normal `start()`
414
+ * dance for the SAME transition observes this tab's `becomeLeader`
415
+ * heartbeat and defers before its own claim-timeout fires; if another
416
+ * tab ALSO force-promotes at the same moment (e.g. two tabs both
417
+ * transitioning to the same new identity), the existing
418
+ * `resolveLeaderVsLeaderTieBreak` resolves the rare double-promotion
419
+ * the same way it resolves any other split-brain.
420
+ */
421
+ promoteImmediately(): void;
422
+ /** The tab id of the current leader, or `undefined` if unknown / no leader. */
423
+ get leaderTabId(): string | undefined;
424
+ /** The id of this tab. */
425
+ get id(): string;
426
+ /** `true` when the coordinator has been started and is not yet stopped. */
427
+ get isRunning(): boolean;
428
+ /**
429
+ * Broadcast subscription data to all follower tabs. Only the leader should
430
+ * call this. `cursor`/`epoch` are omitted from the wire frame when
431
+ * `undefined` (e.g. a CDC-off shard) — a follower on ANY version treats a
432
+ * missing `cursor` as "no confirmed-layer drop this frame", so omitting it
433
+ * here is equivalent to sending it as `undefined`. `identity` is this
434
+ * (leader) tab's own `identityFingerprint()` (`null` = signed out) —
435
+ * stamped so a follower can drop a frame from a since-changed identity
436
+ * (see the `onSubscriptionData` docblock); spread-included whenever
437
+ * supplied, since a fixed leader always knows its own identity (never
438
+ * omits it) and `null` must round-trip distinctly from "field absent".
439
+ */
440
+ broadcastSubscriptionData(key: string, data: unknown, cursor?: number, epoch?: string, identity?: string | null): void;
441
+ /**
442
+ * Broadcast a subscription error to all follower tabs. Only the leader
443
+ * should call this.
444
+ *
445
+ * `identity` is this tab's own `identityFingerprint()`, stamped so a
446
+ * follower can drop a frame minted under a different credential — the same
447
+ * guard `broadcastSubscriptionData` and `broadcastSubscriptionSettled`
448
+ * carry. This one lacked it, which was harmless only because nothing called
449
+ * it; once the leader started fanning errors, an unstamped frame could
450
+ * deliver one caller's rejection to a tab that had since signed in as
451
+ * someone else.
452
+ */
453
+ broadcastSubscriptionError(key: string, error: SubscriptionError, identity?: string | null): void;
454
+ /**
455
+ * Broadcast a `settled` frame's checkpoint advance to all follower tabs
456
+ * (no value change, but the resume cursor/epoch moved — see
457
+ * `LunoraClient.handleSettledMessage`). `clientId` is this (leader) tab's
458
+ * own client id, stamped so a follower can tell whether the echoed
459
+ * `lastMutationId` watermark is genuinely its own (see the
460
+ * `onSubscriptionSettled` docblock). `identity` is this tab's own
461
+ * `identityFingerprint()` — see `broadcastSubscriptionData`'s docblock for
462
+ * the same round-tripping rule. Only the leader should call this.
463
+ */
464
+ broadcastSubscriptionSettled(key: string, cursor?: number, epoch?: string, lastMutationId?: number, clientId?: string, identity?: string | null): void;
465
+ /**
466
+ * Broadcast this tab's aggregate `ConnectionStatus` to follower tabs, so
467
+ * they can mirror a truthful status without a socket of their own (see
468
+ * `LunoraClient.computeStatus`/`emitConnectionStatus`). `identity` is this
469
+ * tab's own `identityFingerprint()` — see `broadcastSubscriptionData`'s
470
+ * docblock for the same round-tripping rule. Only the leader should call
471
+ * this.
472
+ */
473
+ broadcastConnectionStatus(status: ConnectionStatus, identity?: string | null): void;
474
+ private broadcast;
475
+ private handleMessage;
476
+ private handleClaimLeadership;
477
+ private handleHeartbeat;
478
+ /**
479
+ * Resolve two leaders existing at once — e.g. this tab was backgrounded
480
+ * and its heartbeat/health timers were throttled while a foreground
481
+ * follower's were not, so the follower's `checkLeaderHealth` timed out
482
+ * the (still-alive) leader and self-promoted. `BroadcastChannel` message
483
+ * delivery isn't subject to the same timer-throttling clamp, so even a
484
+ * backgrounded leader eventually observes the pretender's heartbeat here
485
+ * — resolve the split-brain deterministically with the same
486
+ * lexicographically-smaller-tabId rule used at claim-adoption. If the
487
+ * other tab wins, step down; if we win, reassert immediately so the
488
+ * pretender demotes itself the moment it processes our heartbeat.
489
+ */
490
+ private resolveLeaderVsLeaderTieBreak;
491
+ private becomeLeader;
492
+ private sendHeartbeat;
493
+ private checkLeaderHealth;
494
+ /**
495
+ * Broadcast a leadership claim and arm a `becomeLeader` fallback: if no
496
+ * other tab has asserted itself as leader by the time the window elapses,
497
+ * self-promote. Shared by `checkLeaderHealth`'s stale-leader path and the
498
+ * `yield-leadership` handler so both promotion triggers use one claim
499
+ * window instead of each arming its own timeout.
500
+ */
501
+ private claimAndPromote;
502
+ }
503
+ /**
504
+ * One row change as emitted by `@lunora/do`'s `broadcastDelta`. Mirrors
505
+ * `MutationDelta` in `@lunora/do` structurally so the client carries no
506
+ * dependency on it. `row` is absent on `delete` events (and may be absent on
507
+ * older servers for any op).
508
+ */
63
509
  interface MutationDelta {
64
510
  /** Row id (`_id`) the change applies to. */
65
511
  key: string;
@@ -68,98 +514,88 @@ interface MutationDelta {
68
514
  table: string;
69
515
  }
70
516
  /**
71
- * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
72
- * We require `op`, `table`, and a string `key` so opaque payloads that merely
73
- * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
74
- * verbatim) are never mistaken for a row delta and keep replacing the cached
75
- * value wholesale.
76
- */
517
+ * Structural guard: is `value` a `MutationDelta` the client knows how to merge?
518
+ * We require `op`, `table`, and a string `key` so opaque payloads that merely
519
+ * happen to be objects (e.g. an aggregate `{ count: 1 }` a query returns
520
+ * verbatim) are never mistaken for a row delta and keep replacing the cached
521
+ * value wholesale.
522
+ */
77
523
  declare const isMutationDelta: (value: unknown) => value is MutationDelta;
78
524
  /**
79
- * Apply a structured `MutationDelta` to a cached array result, returning a new
80
- * array (never mutating the input). Returns `undefined` when the delta can't be
81
- * applied cleanly — the caller should then fall back to the existing
82
- * full-replacement behaviour (or trust the next snapshot to reconcile).
83
- *
84
- * Mergeable shape: a plain array of id-bearing row objects, e.g. the result of
85
- * `db.query().collect()`.
86
- *
87
- * Insert / update / delete are matched by row `_id`:
88
- * - `insert`: appended (or placed by `_creationTime` order) if absent; treated
89
- * as an update if a row with the same id already exists (idempotent — guards
90
- * against a delta replayed after a snapshot already included it).
91
- * - `update`: replaces the matching row in place, preserving its position.
92
- * - `delete`: removes the matching row.
93
- *
94
- * Returns `undefined` when `current` isn't an array of id-keyable objects, or
95
- * when an `insert`/`update` delta carries no `row` to splice in.
96
- */
97
- declare const applyDelta: (current: unknown, delta: MutationDelta) => undefined | unknown[];
98
- /** Error code the server uses for optimistic-concurrency conflicts (HTTP 409). */
99
- declare const CONFLICT_ERROR_CODE = "CONFLICT";
525
+ * Apply a structured `MutationDelta` to a cached list result, returning a new
526
+ * value (never mutating the input). Returns `undefined` when the delta can't be
527
+ * applied cleanly — the caller should then fall back to the existing
528
+ * full-replacement behaviour (or trust the next snapshot to reconcile).
529
+ *
530
+ * Mergeable shapes: an array of id-bearing row objects, or a `.paginate()`
531
+ * result wrapping one in `page` (see `rowListOf`). A paginated value keeps its
532
+ * other fields and comes back as a new object with a new `page` — the server
533
+ * only sends row deltas for that shape when everything outside the page is
534
+ * unchanged, so the merged value matches the snapshot it chose not to send.
535
+ * @returns the merged value, or `undefined` when the delta cannot be applied
536
+ */
537
+ declare const applyDelta: (current: unknown, delta: MutationDelta) => Record<string, unknown> | undefined | unknown[];
100
538
  /**
101
- * Whether an unknown rejection is an optimistic-concurrency conflict — the
102
- * server lost a write race and the caller should refetch and retry (or surface
103
- * the conflict). Structural check on the `code` property the client attaches
104
- * when decoding the worker's `{ error: { code, message } }` envelope.
105
- */
106
- declare const isConflictError: (error: unknown) => error is Error & {
107
- code: "CONFLICT";
108
- };
109
- /** The single transport method a mutation runner needs — narrowed so adapters can test against a stub. */
110
- interface MutationCapableClient<F extends FunctionReference> {
111
- mutation: (function_: F, args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>;
539
+ * Options accepted by {@link httpStream}.
540
+ * @experimental Part of the HTTP-SSE stream surface.
541
+ */
542
+ interface HttpStreamOptions {
543
+ /**
544
+ * Origin (or origin + prefix) the route path is appended to, e.g.
545
+ * `https://my-app.example.com`. Defaults to `""` — a relative URL, which
546
+ * resolves against the page origin in a browser.
547
+ */
548
+ baseUrl?: string;
549
+ /** `fetch` implementation override; defaults to the global `fetch`. */
550
+ fetch?: typeof fetch;
551
+ /** Extra request headers (e.g. `authorization`). `accept: text/event-stream` is always sent. */
552
+ headers?: Record<string, string>;
553
+ /** Caps the in-flight chunk buffer (see `createStream`); exceeding it fails the stream. */
554
+ maxBuffer?: number;
555
+ /** External abort signal — aborting it cancels the fetch (→ the server handler's `signal`). */
556
+ signal?: AbortSignal;
112
557
  }
113
558
  /**
114
- * Reactive sinks an adapter binds to its own primitive's setters (a Solid
115
- * signal, a Vue ref, a Svelte store). The runner pushes into them; how they
116
- * store the value is the adapter's concern (e.g. Solid wraps function-valued
117
- * results in a thunk).
118
- */
119
- interface MutationRunnerSinks<R> {
120
- /** Receives the normalized {@link Error} when an invocation rejects. */
121
- setError: (error: Error) => void;
122
- /** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
123
- setPending: (pending: boolean) => void;
124
- /** Receives the resolved value when an invocation succeeds. */
125
- setResult: (result: R) => void;
126
- }
559
+ * Open a typed HTTP-SSE stream route and iterate its chunks:
560
+ *
561
+ * ```ts
562
+ * const stream = httpStream(httpStreams.http.tokens, { searchParams: { prompt } }, { baseUrl });
563
+ * for await (const token of stream) {
564
+ * render(token); // typed as the route handler's yielded chunk
565
+ * }
566
+ * ```
567
+ *
568
+ * The returned iterable terminates when the server writes `event: complete`;
569
+ * an `event: error` frame (or a transport failure) surfaces as a coded
570
+ * rejection on the next `next()`. `.cancel()` or aborting `options.signal` —
571
+ * aborts the underlying fetch, which the server observes via `request.signal`.
572
+ * @experimental Reconnect/POST-body/wire-fidelity design questions are still open, so the shape may change.
573
+ */
574
+ declare const httpStream: <Ref extends HttpStreamRef>(route: Ref, args?: HttpStreamArgsOf<Ref>, options?: HttpStreamOptions) => StreamIterable<HttpStreamChunkOf<Ref>>;
127
575
  /**
128
- * Build the framework-neutral `mutate` half of an adapter's mutation hook.
129
- *
130
- * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
131
- * overlapping invocations into `setPending` (so it only clears once the last
132
- * settles), normalizes a thrown non-`Error`, and routes success/failure to
133
- * `setResult`/`setError` before re-throwing. Each adapter (`@lunora/react`,
134
- * `/solid`, `/svelte`, `/vue`) binds the three sinks to its own reactive
135
- * setters, so this logic lives in exactly one place. Optimistic-update options
136
- * pass straight through to `client.mutation`.
137
- */
138
- declare const createMutationRunner: <F extends FunctionReference>(client: MutationCapableClient<F>, function_: F, sinks: MutationRunnerSinks<ReturnOf<F>>) => ((args: ArgsOf<F>, options?: MutationCallOptions<unknown, unknown, ArgsOf<F>>) => Promise<ReturnOf<F>>);
139
- /**
140
- * The structural surface of a TanStack `Transaction` a bound custom mutator
141
- * returns — its `isPersisted.promise` resolves once the write is persisted and
142
- * rejects on failure. Typed structurally so the framework adapters need not
143
- * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
144
- * `bindMutators`).
145
- */
576
+ * The structural surface of a TanStack `Transaction` a bound custom mutator
577
+ * returns — its `isPersisted.promise` resolves once the write is persisted and
578
+ * rejects on failure. Typed structurally so the framework adapters need not
579
+ * depend on `@tanstack/db` or `@lunora/db` (the handle is created app-side by
580
+ * `bindMutators`).
581
+ */
146
582
  interface MutatorTransaction {
147
583
  isPersisted: {
148
584
  promise: Promise<unknown>;
149
585
  };
150
586
  }
151
587
  /**
152
- * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
153
- * in `@lunora/db`. Calling it applies the optimistic overlay to the local
154
- * collections and pushes the authoritative server write; it returns the TanStack
155
- * transaction whose `isPersisted` promise tracks completion.
156
- */
588
+ * A bound custom-mutator handle produced by `bindMutators(client, ctx, mutators)`
589
+ * in `@lunora/db`. Calling it applies the optimistic overlay to the local
590
+ * collections and pushes the authoritative server write; it returns the TanStack
591
+ * transaction whose `isPersisted` promise tracks completion.
592
+ */
157
593
  type MutatorHandle<TArgs> = (args: TArgs) => MutatorTransaction;
158
594
  /**
159
- * Reactive sinks an adapter binds to its own primitive's setters (a React
160
- * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
161
- * them; how they store the value is the adapter's concern.
162
- */
595
+ * Reactive sinks an adapter binds to its own primitive's setters (a React
596
+ * `useState`, a Solid signal, a Vue ref, a Svelte store). The runner pushes into
597
+ * them; how they store the value is the adapter's concern.
598
+ */
163
599
  interface MutatorRunnerSinks {
164
600
  /** Receives the normalized {@link Error} when an invocation rejects, or `undefined` on success / reset. */
165
601
  setError: (error: Error | undefined) => void;
@@ -167,52 +603,72 @@ interface MutatorRunnerSinks {
167
603
  setPending: (pending: boolean) => void;
168
604
  }
169
605
  /**
170
- * Build the framework-neutral `mutate` / `reset` pair of an adapter's
171
- * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
172
- *
173
- * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
174
- * overlapping invocations into `setPending` (so it only clears once the last
175
- * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
176
- * non-`Error`, and routes failure to `setError` (clearing it on success) before
177
- * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
178
- * the two sinks to its own reactive setters, so this logic lives in exactly one
179
- * place. The optimistic overlay + server push are owned by the bound handle.
180
- *
181
- * `error` tracks the LATEST invocation, not the last to settle: overlapping
182
- * calls can resolve out of order, so an earlier call that finishes later must
183
- * not clobber a newer call's outcome. Each invocation takes a monotonic token
184
- * and only writes `setError` while it is still the most recent one — otherwise
185
- * `error`/`isError` could surface a stale success or failure (the documented
186
- * "latest invocation's error" contract every adapter advertises).
187
- */
606
+ * Build the framework-neutral `mutate` / `reset` pair of an adapter's
607
+ * custom-mutator hook (`useMutator` / `createMutator` / `mutator`).
608
+ *
609
+ * Owns the orchestration every adapter otherwise copy-pastes: ref-counts
610
+ * overlapping invocations into `setPending` (so it only clears once the last
611
+ * settles), awaits the bound handle's `isPersisted` promise, normalizes a thrown
612
+ * non-`Error`, and routes failure to `setError` (clearing it on success) before
613
+ * re-throwing. Each adapter (`@lunora/react`, `/solid`, `/svelte`, `/vue`) binds
614
+ * the two sinks to its own reactive setters, so this logic lives in exactly one
615
+ * place. The optimistic overlay + server push are owned by the bound handle.
616
+ *
617
+ * `error` tracks the LATEST invocation, not the last to settle: overlapping
618
+ * calls can resolve out of order, so an earlier call that finishes later must
619
+ * not clobber a newer call's outcome. Each invocation takes a monotonic token
620
+ * and only writes `setError` while it is still the most recent one — otherwise
621
+ * `error`/`isError` could surface a stale success or failure (the documented
622
+ * "latest invocation's error" contract every adapter advertises).
623
+ */
188
624
  declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks: MutatorRunnerSinks) => {
189
625
  mutate: (args: TArgs) => Promise<void>;
190
626
  reset: () => void;
191
627
  };
192
628
  interface QueuedMutation<T = unknown> {
193
629
  readonly args: Record<string, unknown>;
630
+ /**
631
+ * The client id that queued this write (see {@link PersistedMutation.clientId}).
632
+ * Persisted and restored, so a replay namespaces by the id that issued the
633
+ * write rather than whatever the current session minted.
634
+ */
635
+ clientId?: string;
194
636
  readonly functionPath: string;
195
637
  /** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
196
638
  id?: string;
197
639
  /**
198
- * Issuing identity fingerprint carried through to durable storage (`null` =
199
- * signed out). Absent on hydrated legacy records, which replay ambiently.
200
- */
201
- readonly identity?: string | null;
202
- /**
203
- * `true` when a live caller is still awaiting this write's `mutation()`
204
- * Promise; `false`/absent for a write restored from durable storage after a
205
- * reload (its original awaiter is gone). Carried so terminal-verdict
206
- * observers can distinguish "the caller already saw this" from "nothing else
207
- * will report this". Maps to the public `MutationSettledEvent.hadAwaiter`.
208
- */
640
+ * Issuing identity fingerprint carried through to durable storage (`null` =
641
+ * signed out). Absent on hydrated legacy records, which replay ambiently.
642
+ *
643
+ * Mutable so {@link OfflineQueue.restampIdentity} can relabel a still-queued
644
+ * write when the identity's LABEL changes but the credential does not (the
645
+ * `setAuthToken(token, userId)` case where the subject resolves a tick after
646
+ * the token). The value is re-persisted alongside, so the new label survives
647
+ * a reload and a requeue.
648
+ */
649
+ identity?: string | null;
650
+ /**
651
+ * `true` when a live caller is still awaiting this write's `mutation()`
652
+ * Promise; `false`/absent for a write restored from durable storage after a
653
+ * reload (its original awaiter is gone). Carried so terminal-verdict
654
+ * observers can distinguish "the caller already saw this" from "nothing else
655
+ * will report this". Maps to the public `MutationSettledEvent.hadAwaiter`.
656
+ */
209
657
  liveAwaiter?: boolean;
210
658
  /**
211
- * Invoked on a successful replay with the server's echoed commit CDC cursor,
212
- * so a live per-call optimistic layer drops gaplessly once a frame reaches it.
213
- * Absent on hydrated records (the optimistic write lived in a prior session).
214
- */
659
+ * Invoked on a successful replay with the server's echoed commit CDC cursor,
660
+ * so a live per-call optimistic layer drops gaplessly once a frame reaches it.
661
+ * Absent on hydrated records (the optimistic write lived in a prior session).
662
+ */
215
663
  readonly onCommit?: (commitCursor: number | undefined) => void;
664
+ /**
665
+ * Optional sync predicate evaluated just before replay. When it returns
666
+ * `false` the write is dropped instead of replaying, handling the case
667
+ * where the mutation's preconditions are no longer valid (e.g. the
668
+ * document it referred to was deleted while offline). Absent or `true`
669
+ * means "ok to replay".
670
+ */
671
+ readonly precondition?: () => boolean;
216
672
  /** Rejects if the mutation can no longer be replayed. */
217
673
  readonly reject: (error: unknown) => void;
218
674
  /** Resolves once the mutation has been replayed against the server. */
@@ -220,37 +676,45 @@ interface QueuedMutation<T = unknown> {
220
676
  readonly shardKey?: string;
221
677
  }
222
678
  /**
223
- * Invoked when the queue itself discards an entry on overflow (capacity
224
- * eviction), so the client can surface the dropped write on its
225
- * terminal-verdict observer even when the entry has no live awaiter (a hydrated
226
- * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
227
- */
679
+ * Invoked when the queue itself discards an entry on overflow (capacity
680
+ * eviction), so the client can surface the dropped write on its
681
+ * terminal-verdict observer even when the entry has no live awaiter (a hydrated
682
+ * record). The `error` carries the `OFFLINE_QUEUE_OVERFLOW` code.
683
+ *
684
+ * The `sdks/*` ports deliberately do NOT mirror this shape — they return the
685
+ * discarded entry from `enqueue`/`hydrate`/`drainConflict`/`clear` instead,
686
+ * because they call the queue with a real lock held and settling a write needs
687
+ * that same lock, which self-deadlocks a non-reentrant one. Keep the callback
688
+ * here: this client is single-threaded, so the hazard does not exist, and an
689
+ * observer the queue fires itself is what covers the case a return value's
690
+ * consumer can quietly miss — a hydrated entry whose `reject` is a no-op.
691
+ */
228
692
  type EvictHandler = (entry: QueuedMutation, error: Error & {
229
693
  code?: string;
230
694
  }) => void;
695
+ /** Injected dependencies for {@link OfflineQueue} (kept off the user-facing {@link OfflineQueueOptions}). */
696
+ interface OfflineQueueDeps {
697
+ /** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
698
+ onEvict?: EvictHandler;
699
+ /** Invoked with the new depth after any size change (drives the client's pending-sync count). */
700
+ onSizeChange?: (size: number) => void;
701
+ /** Durable store; when present, writes are mirrored and restored across reloads. */
702
+ persistence?: PersistenceAdapter;
703
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
704
+ version?: string;
705
+ }
231
706
  /**
232
- * A process-unique id, used both per-mutation and as the fallback `clientId`. It
233
- * MUST be globally unique: the server scopes a custom mutator's replay watermark
234
- * by `(verifiedIdentity, clientId)`, and an anonymous push has no verified
235
- * identity so two anonymous clients that collide on `clientId` would share one
236
- * watermark namespace, letting one stall/suppress the other's ordered mutations.
237
- * `crypto.randomUUID` covers every modern runtime; the fallback still mixes
238
- * crypto-quality (or `Math.random`) entropy with the timestamp + counter so it
239
- * can't collide across two clients started in the same millisecond.
240
- */
241
-
242
- /**
243
- * Bounded FIFO queue. Mutations issued while the client is offline are
244
- * enqueued and replayed in the order they were submitted once the WS
245
- * reconnects and identifies. If the queue exceeds `maxItems` the oldest
246
- * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
247
- *
248
- * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
249
- * to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
250
- * the next startup and the client replays them on reconnect. Durable removal is
251
- * the caller's responsibility *after* a successful replay (see `LunoraClient`);
252
- * the queue only persists on enqueue and un-persists on overflow.
253
- */
707
+ * Bounded FIFO queue. Mutations issued while the client is offline are
708
+ * enqueued and replayed in the order they were submitted once the WS
709
+ * reconnects and identifies. If the queue exceeds `maxItems` the oldest
710
+ * entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
711
+ *
712
+ * When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
713
+ * to durable storage so they survive a reload {@link OfflineQueue.hydrate} restores them on
714
+ * the next startup and the client replays them on reconnect. Durable removal is
715
+ * the caller's responsibility *after* a successful replay (see `LunoraClient`);
716
+ * the queue only persists on enqueue and un-persists on overflow.
717
+ */
254
718
  declare class OfflineQueue {
255
719
  /** Opt-in to queueing mutations before the targeted shard's first connect. */
256
720
  readonly queueBeforeFirstConnect: boolean;
@@ -258,44 +722,118 @@ declare class OfflineQueue {
258
722
  private readonly onPersistenceError;
259
723
  private readonly persistence;
260
724
  private readonly onEvict;
725
+ private readonly onSizeChange;
726
+ /** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
727
+ private readonly version;
261
728
  private readonly items;
262
- constructor(options?: OfflineQueueOptions, persistence?: PersistenceAdapter, onEvict?: EvictHandler);
729
+ constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
263
730
  get size(): number;
264
731
  enqueue<T>(entry: QueuedMutation<T>): void;
265
732
  /**
266
- * Restore mutations persisted in a prior session and re-queue them in FIFO
267
- * order. Restored entries already live in durable storage, so they are not
268
- * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
269
- * gone after a reload). No-op when no persistence adapter is configured.
270
- * Returns the distinct shard keys of the restored writes so the caller can
271
- * open their sockets to trigger a flush.
272
- */
733
+ * Restore mutations persisted in a prior session and re-queue them in FIFO
734
+ * order. Restored entries already live in durable storage, so they are not
735
+ * re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
736
+ * gone after a reload). No-op when no persistence adapter is configured.
737
+ * Returns the distinct shard keys of the restored writes so the caller can
738
+ * open their sockets to trigger a flush.
739
+ *
740
+ * `hydrate()` runs post-construction (the caller awaits an async durable-store
741
+ * load), so a mutation issued while offline during that boot window is
742
+ * enqueued into `items` *before* this method's `await` resolves. Restored
743
+ * records are therefore `unshift`-ed ahead of whatever is already queued
744
+ * rather than `push`-ed to the end: the durable store's persist order is
745
+ * authoritative (a prior-session write is always older than anything from
746
+ * this session), so replaying a same-session boot-time write before an
747
+ * older restored write on the same document would let last-writer-wins
748
+ * silently clobber the newer data with the stale one.
749
+ */
273
750
  hydrate(): Promise<(string | undefined)[]>;
274
751
  /**
275
- * Remove and return queued mutations. With no `predicate`, drains the whole
276
- * queue. With one, drains only matching entries (preserving FIFO order) and
277
- * leaves the rest queued — used to flush a single shard's writes when its
278
- * socket reconnects while other shards are still down.
279
- */
752
+ * Relabel every queued write stamped `from` to `to`, in memory AND in durable
753
+ * storage.
754
+ *
755
+ * Used when the auth identity's LABEL changes while the credential does not
756
+ * `setAuthToken(token, userId)` where the user id resolves a tick after the
757
+ * token was set. `setAuthToken` documents that this re-stamps in-flight
758
+ * queued writes rather than dropping them, and that promise only held for the
759
+ * caller's live in-memory stamp map, which is consumed and deleted on the
760
+ * first flush attempt. Everything durable still carried the old token hash,
761
+ * so a reload — or a transient-failure requeue after the token had since been
762
+ * refreshed — fell back to it, failed the replay identity gate, and rejected
763
+ * the SAME user's offline write with `OFFLINE_IDENTITY_CHANGED`.
764
+ *
765
+ * The durable rewrite goes through `PersistenceAdapter.replace`, the one
766
+ * operation on the contract that is required to be atomic — see
767
+ * {@link OfflineQueue.rewriteStamp}.
768
+ */
769
+ restampIdentity(from: string | null, to: string | null): void;
770
+ /**
771
+ * Remove and return queued mutations. With no `predicate`, drains the whole
772
+ * queue. With one, drains only matching entries (preserving FIFO order) and
773
+ * leaves the rest queued — used to flush a single shard's writes when its
774
+ * socket reconnects while other shards are still down.
775
+ */
280
776
  drain(predicate?: (item: QueuedMutation) => boolean): QueuedMutation[];
281
777
  /**
282
- * Return previously-drained mutations to the front of the queue, preserving
283
- * their FIFO order, without re-persisting them — they were never unpersisted,
284
- * so durable storage still holds them. Used when a flush aborts on a transient
285
- * transport failure: the unreplayed writes stay queued for the next reconnect.
286
- */
778
+ * Return previously-drained mutations to the front of the queue, preserving
779
+ * their FIFO order, without re-persisting them — they were never unpersisted,
780
+ * so durable storage still holds them. Used when a flush aborts on a transient
781
+ * transport failure: the unreplayed writes stay queued for the next reconnect.
782
+ */
287
783
  requeue(items: QueuedMutation[]): void;
784
+ /**
785
+ * Remove mutations whose precondition evaluates to `false` (stale/dirty
786
+ * writes that should not replay) and reject each with an
787
+ * `OFFLINE_PRECONDITION_FAILED` error. The valid (admitted) mutations stay
788
+ * queued in FIFO order. Returns the drained stale entries.
789
+ *
790
+ * Called during reconnect before the flush cycle to weed out writes whose
791
+ * assumptions no longer hold (e.g. a document was deleted by another client).
792
+ */
793
+ drainConflict(): QueuedMutation[];
288
794
  clear(): void;
795
+ /**
796
+ * The durable half of {@link OfflineQueue.restampIdentity}: rewrite the
797
+ * persisted record under the new identity stamp.
798
+ *
799
+ * This used to be `remove` then `append` (because `append` is an insert, not
800
+ * an upsert) with a compensating re-append on failure, and no arrangement of
801
+ * those two calls is safe. A process stop between a committed `remove` and
802
+ * the `append` leaves the mutation in NO durable store while the in-memory
803
+ * entry has already advanced, so a reload loses the write outright — and
804
+ * compensation cannot cover a crash, only a rejection. The re-append also
805
+ * moved the record to the tail, replaying it out of issue order.
806
+ *
807
+ * `PersistenceAdapter.replace` is the single atomic operation that removes
808
+ * both: the swap lands whole or not at all, and the record keeps its place
809
+ * in FIFO order. A rejection means nothing changed durably — the record
810
+ * stands under its OLD stamp, which is the documented outcome (a replay
811
+ * under a stale stamp is refused with `OFFLINE_IDENTITY_CHANGED`, visible
812
+ * and recoverable, unlike a silent loss) — so there is nothing to
813
+ * compensate, only to report.
814
+ */
815
+ private rewriteStamp;
816
+ /**
817
+ * Evict entries from the FRONT of `items` (the oldest — FIFO order) until
818
+ * the queue is at or under `maxItems`, rejecting each with
819
+ * `OFFLINE_QUEUE_OVERFLOW`, un-persisting it, and firing `onEvict`. Shared
820
+ * by `enqueue` (a live write pushes past capacity) and `hydrate` (a durable
821
+ * store restored more than `maxItems` records — CLIENT-03) so an overflow
822
+ * always drops the same way regardless of which caller triggered it.
823
+ */
824
+ private evictOverflow;
825
+ /** Notify the size observer (the client's pending-sync count) after any change. */
826
+ private notifySize;
289
827
  }
290
828
  /**
291
- * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
292
- * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
293
- * a deliberate "no durable store" choice that still satisfies the interface).
294
- * Preserves enqueue order; `clone` keeps callers from mutating stored args.
295
- */
829
+ * In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
830
+ * the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
831
+ * a deliberate "no durable store" choice that still satisfies the interface).
832
+ * Preserves enqueue order; `clone` keeps callers from mutating stored args.
833
+ */
296
834
  declare const createInMemoryPersistence: () => PersistenceAdapter;
297
835
  interface IndexedDbPersistenceOptions {
298
- /** Database name; defaults to `"lunora"`. */
836
+ /** Database name; defaults to `"lunora-outbox"` (its own DB, separate from the read cache). */
299
837
  databaseName?: string;
300
838
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
301
839
  indexedDB?: IDBFactory;
@@ -303,62 +841,62 @@ interface IndexedDbPersistenceOptions {
303
841
  storeName?: string;
304
842
  }
305
843
  /**
306
- * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
307
- * autoincrementing key (so `load()` returns them in enqueue order regardless of
308
- * the string ids) with a unique secondary index on `id` for `remove()`.
309
- *
310
- * The store handle is opened lazily and the open promise is cached, so repeated
311
- * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
312
- * callers in non-browser environments should use {@link createInMemoryPersistence}.
313
- */
844
+ * IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
845
+ * autoincrementing key (so `load()` returns them in enqueue order regardless of
846
+ * the string ids) with a unique secondary index on `id` for `remove()`.
847
+ *
848
+ * The store handle is opened lazily and the open promise is cached, so repeated
849
+ * ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
850
+ * callers in non-browser environments should use {@link createInMemoryPersistence}.
851
+ */
314
852
  declare const createIndexedDbPersistence: (options?: IndexedDbPersistenceOptions) => PersistenceAdapter;
315
853
  /**
316
- * Compose the read-cache key for a subscription. Mirrors how
317
- * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
318
- * with the subscription that will consume it. `shardKey` defaults to `""` (the
319
- * root shard) exactly as the registry does.
320
- */
854
+ * Compose the read-cache key for a subscription. Mirrors how
855
+ * `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
856
+ * with the subscription that will consume it. `shardKey` defaults to `""` (the
857
+ * root shard) exactly as the registry does.
858
+ */
321
859
  declare const queryCacheKey: (functionPath: string, argsKey: string, shardKey?: string) => string;
322
860
  /**
323
- * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
324
- * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
325
- * deliberate "no durable store" choice that still satisfies the interface).
326
- * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
327
- * from mutating stored values.
328
- */
861
+ * In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
862
+ * the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
863
+ * deliberate "no durable store" choice that still satisfies the interface).
864
+ * Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
865
+ * from mutating stored values.
866
+ */
329
867
  declare const createInMemoryQueryCache: (options?: {
330
868
  maxEntries?: number;
331
869
  }) => QueryCacheAdapter;
332
870
  interface IndexedDbQueryCacheOptions {
333
- /** Database name; defaults to `"lunora"` (shared with the offline-mutation store). */
871
+ /** Database name; defaults to `"lunora-query-cache"` (its own DB, separate from the offline outbox). */
334
872
  databaseName?: string;
335
873
  /** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
336
874
  indexedDB?: IDBFactory;
337
- /** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
875
+ /** LRU row cap; defaults to 500. Must be a positive integer. The oldest rows by `ts` are pruned on `put` once exceeded. */
338
876
  maxEntries?: number;
339
877
  /** Object-store name; defaults to `"query-cache"`. */
340
878
  storeName?: string;
341
879
  }
342
880
  /**
343
- * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
344
- * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
345
- * LRU eviction. The store handle is opened lazily and cached, so repeated ops
346
- * reuse one connection.
347
- *
348
- * The store lives in the same `lunora` database as the offline-mutation queue
349
- * (bumped to schema v2). Opening it upgrades a v1 database in place, adding the
350
- * `query-cache` store without touching `offline-mutations`. Throws eagerly if no
351
- * `IDBFactory` is available — callers in non-browser environments should use
352
- * {@link createInMemoryQueryCache}.
353
- */
881
+ * IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
882
+ * composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
883
+ * LRU eviction. The store handle is opened lazily and cached, so repeated ops
884
+ * reuse one connection.
885
+ *
886
+ * The store lives in its own `lunora-query-cache` database deliberately
887
+ * separate from the offline-mutation outbox's `lunora-outbox` database so the two
888
+ * independently-toggleable adapters never share (and drift on) a schema version.
889
+ * Throws eagerly if no `IDBFactory` is available — callers in non-browser
890
+ * environments should use {@link createInMemoryQueryCache}.
891
+ */
354
892
  declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
355
893
  /**
356
- * Exponential backoff calculator with optional jitter.
357
- *
358
- * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
359
- * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
360
- * of clients reconnecting at the same time spread out their retries.
361
- */
894
+ * Exponential backoff calculator with optional jitter.
895
+ *
896
+ * `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
897
+ * enabled the returned value is randomized in `[delay/2, delay]` so a fleet
898
+ * of clients reconnecting at the same time spread out their retries.
899
+ */
362
900
  interface ReconnectCalculator {
363
901
  /** Returns the delay to wait before the next reconnect attempt. */
364
902
  next: () => number;
@@ -366,4 +904,112 @@ interface ReconnectCalculator {
366
904
  reset: () => void;
367
905
  }
368
906
  declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
369
- export { type ArgsOf, type AsyncStorageLike, type AsyncStoragePersistenceOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, type FunctionReference, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, type MutationCallOptions, type MutationDelta, type MutationRunnerSinks, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, type ReconnectCalculator, type ReconnectOptions, type ReturnOf, applyDelta, createAsyncStoragePersistence, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutationRunner, createMutatorRunner, createReconnect, isConflictError, isMutationDelta, queryCacheKey };
907
+ /**
908
+ * Capture a snapshot of the current live query value at call time and produce a
909
+ * `() => boolean` precondition that compares it against the value at replay time.
910
+ *
911
+ * When the precondition is checked (on queue drain / reconnect) it re-reads the
912
+ * query's current state via {@link LunoraClient.peekActiveQuerySnapshot}. The
913
+ * comparison only runs when a live subscription backed **both** reads; if either
914
+ * read found no active subscription (e.g. the originating component unmounted
915
+ * before replay), the precondition returns `true` (not stale) because absence of
916
+ * a subscription is not evidence the value changed — the read simply cannot see
917
+ * it. When both reads did have a live subscription and the value differs, the
918
+ * precondition returns `false` and the offline mutation is dropped as stale.
919
+ * @example
920
+ * ```ts
921
+ * client.mutation(api.todos.update, { id, text }, {
922
+ * precondition: createSnapshotPrecondition(client, api.todos.list, { userId }),
923
+ * });
924
+ * ```
925
+ */
926
+ declare const createSnapshotPrecondition: (client: LunoraClient, functionRef: FunctionReference, args: Record<string, unknown>, shardKey?: string) => (() => boolean);
927
+ /**
928
+ * Client-side service-worker registration and lifecycle management.
929
+ *
930
+ * Usage:
931
+ * ```ts
932
+ * const sw = new ClientServiceWorker({ swUrl: "/sw.js" });
933
+ * await sw.register();
934
+ *
935
+ * if (sw.active) {
936
+ * sw.postMessage({ type: "sync" });
937
+ * }
938
+ * ```
939
+ */
940
+ type ServiceWorkerStatus = "unsupported" | "unregistered" | "registering" | "active" | "error";
941
+ interface ClientSwOptions {
942
+ /** Called when the status changes. */
943
+ onStatusChange?: (status: ServiceWorkerStatus) => void;
944
+ /** Optional registration scope. Defaults to `/`. */
945
+ scope?: string;
946
+ /** URL of the service worker script (relative to origin). */
947
+ swUrl: string;
948
+ }
949
+ /**
950
+ * Manages service-worker registration and provides a simple API for
951
+ * sending messages and listening for responses.
952
+ */
953
+ declare class ClientServiceWorker {
954
+ #private;
955
+ readonly swUrl: string;
956
+ readonly scope: string;
957
+ constructor(options: ClientSwOptions);
958
+ /** Current registration status. */
959
+ get status(): ServiceWorkerStatus;
960
+ /** The underlying `ServiceWorkerRegistration`, if registered. */
961
+ get registration(): ServiceWorkerRegistration | undefined;
962
+ /** Whether the SW is currently controlling this page. */
963
+ get active(): boolean;
964
+ /**
965
+ * Register the service worker.
966
+ *
967
+ * Returns `false` when the browser does not support service workers.
968
+ */
969
+ register(): Promise<boolean>;
970
+ /**
971
+ * Remove the active service worker registration and clear listeners.
972
+ *
973
+ * Returns `false` when no registration is currently held.
974
+ */
975
+ unregister(): Promise<boolean>;
976
+ /**
977
+ * Send a message to the active service worker.
978
+ */
979
+ postMessage(message: unknown): void;
980
+ /**
981
+ * Register a handler for messages **from** the service worker.
982
+ * @returns Unsubscribe function.
983
+ */
984
+ onMessage(handler: (event: MessageEvent) => void): () => void;
985
+ }
986
+ /**
987
+ * Outbound message from the client to the SW.
988
+ */
989
+ interface ClientToSwMessage {
990
+ /** Opaque correlation ID for request/response patterns. */
991
+ correlationId?: string;
992
+ payload?: unknown;
993
+ type: string;
994
+ }
995
+ /**
996
+ * Inbound message from the SW to the client.
997
+ */
998
+ interface SwToClientMessage {
999
+ /** Echoes the correlation ID from the client request, if any. */
1000
+ correlationId?: string;
1001
+ payload?: unknown;
1002
+ type: string;
1003
+ }
1004
+ /**
1005
+ * Send a typed message to the service worker and optionally await a
1006
+ * matching response.
1007
+ * @returns A promise that resolves when the SW sends a reply with the
1008
+ * same `correlationId` (if `expectResponse` is true).
1009
+ */
1010
+ declare const sendToSw: (sw: ServiceWorker | null, message: ClientToSwMessage, expectResponse?: boolean) => Promise<unknown>;
1011
+ /**
1012
+ * Create a reply for a client message (call from inside the SW).
1013
+ */
1014
+ declare const createReply: (original: ClientToSwMessage, payload?: unknown) => SwToClientMessage;
1015
+ export { type AsyncStorageLike, type AsyncStoragePersistenceOptions, type AsyncStorageQueryCacheOptions, type BookmarkStorage, CONFLICT_ERROR_CODE, ClientServiceWorker, type ClientSwOptions, type ClientToSwMessage, type ConnectionStatus, type FunctionReference, type HttpStreamArgsOf, type HttpStreamChunkOf, type HttpStreamOptions, type HttpStreamRef, type IndexedDbPersistenceOptions, type IndexedDbQueryCacheOptions, LunoraClient, type MutationDelta, type MutatorHandle, type MutatorRunnerSinks, type MutatorTransaction, OfflineQueue, type OfflineQueueOptions, type OptimisticMessage, type PersistenceAdapter, type QueryCacheAdapter, type QueuedMutation, RETIRE_AFTER_DURABLE_SEQ_ADVANCE, type ReconcileDurableMessage, type ReconnectCalculator, type ReconnectOptions, type ServiceWorkerStatus, type StreamIterable, type SubscriptionError, type SwToClientMessage, TabCoordinator, TransportError, anyApi, applyDelta, createAsyncStoragePersistence, createAsyncStorageQueryCache, createCallRunner, createInMemoryBookmarkStorage, createInMemoryPersistence, createInMemoryQueryCache, createIndexedDbPersistence, createIndexedDbQueryCache, createMutatorRunner, createReconnect, createReply, createSnapshotPrecondition, getErrorCode, getRetryAfterMs, httpStream, isConflictError, isForbiddenError, isMutationDelta, isRateLimitedError, isUnauthorizedError, maxSeq, queryCacheKey, reconcileOptimistic, sendToSw };