@lunora/client 1.0.0-alpha.6 → 1.0.0-alpha.60

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