@lunora/client 0.0.0 → 1.0.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +105 -0
- package/README.md +113 -9
- package/__assets__/package-og.svg +14 -0
- package/dist/auth/index.d.mts +20 -0
- package/dist/auth/index.d.ts +20 -0
- package/dist/auth/index.mjs +60 -0
- package/dist/index.d.mts +385 -0
- package/dist/index.d.ts +385 -0
- package/dist/index.mjs +15 -0
- package/dist/packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs +4 -0
- package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +107 -0
- package/dist/packem_shared/LunoraClient-CgZ6FhKP.mjs +2721 -0
- package/dist/packem_shared/OfflineQueue-BI0FNNvc.mjs +1 -0
- package/dist/packem_shared/SKIP-vItZChkw.mjs +50 -0
- package/dist/packem_shared/SubscriptionRegistry-Dn-7k7eo.mjs +1 -0
- package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +61 -0
- package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +45 -0
- package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +11 -0
- package/dist/packem_shared/createInMemoryPersistence-CW82inU5.mjs +105 -0
- package/dist/packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs +138 -0
- package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +1 -0
- package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +21 -0
- package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +31 -0
- package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +22 -0
- package/dist/packem_shared/createServerClient-BxkNcRlR.mjs +11 -0
- package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +4 -0
- package/dist/packem_shared/getServerSession-8jXewqxd.mjs +13 -0
- package/dist/packem_shared/local-store-BNgN3Dw3.mjs +111 -0
- package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.mts +2196 -0
- package/dist/packem_shared/lunora-client.d-B5vWSgvD.d.ts +2196 -0
- package/dist/packem_shared/offline-queue-7Wc4onA0.mjs +164 -0
- package/dist/packem_shared/preload.d-3XJD-2hM.d.mts +20 -0
- package/dist/packem_shared/preload.d-CKZR675M.d.ts +20 -0
- package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +13 -0
- package/dist/packem_shared/subscription-C1Jy7HiF.mjs +55 -0
- package/dist/pagination/index.d.mts +82 -0
- package/dist/pagination/index.d.ts +82 -0
- package/dist/pagination/index.mjs +61 -0
- package/dist/query/index.d.mts +62 -0
- package/dist/query/index.d.ts +62 -0
- package/dist/query/index.mjs +1 -0
- package/dist/ssr/index.d.mts +115 -0
- package/dist/ssr/index.d.ts +115 -0
- package/dist/ssr/index.mjs +4 -0
- package/package.json +53 -17
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
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-B5vWSgvD.js";
|
|
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-B5vWSgvD.js";
|
|
3
|
+
export { p as preloadQuery, a as preloadedQueryResult } from "./packem_shared/preload.d-CKZR675M.js";
|
|
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
|
+
*/
|
|
11
|
+
interface AsyncStorageLike {
|
|
12
|
+
getItem: (key: string) => Promise<string | null>;
|
|
13
|
+
removeItem: (key: string) => Promise<void>;
|
|
14
|
+
setItem: (key: string, value: string) => Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
interface AsyncStoragePersistenceOptions {
|
|
17
|
+
/** Storage key the FIFO mutation log is serialized under; defaults to `"lunora:offline-mutations"`. */
|
|
18
|
+
key?: string;
|
|
19
|
+
/** The async key/value store the log is read from and written to (e.g. React Native `AsyncStorage`). */
|
|
20
|
+
storage: AsyncStorageLike;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
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
|
+
*/
|
|
33
|
+
declare const createAsyncStoragePersistence: (options: AsyncStoragePersistenceOptions) => PersistenceAdapter;
|
|
34
|
+
/** Default in-memory bookmark store. Survives the lifetime of the client. */
|
|
35
|
+
declare const createInMemoryBookmarkStorage: () => BookmarkStorage;
|
|
36
|
+
/**
|
|
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
|
+
*/
|
|
63
|
+
interface MutationDelta {
|
|
64
|
+
/** Row id (`_id`) the change applies to. */
|
|
65
|
+
key: string;
|
|
66
|
+
op: "delete" | "insert" | "update";
|
|
67
|
+
row?: Record<string, unknown>;
|
|
68
|
+
table: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
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
|
+
*/
|
|
77
|
+
declare const isMutationDelta: (value: unknown) => value is MutationDelta;
|
|
78
|
+
/**
|
|
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
|
+
}
|
|
113
|
+
/**
|
|
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
|
+
}
|
|
127
|
+
/**
|
|
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
|
+
*/
|
|
146
|
+
interface MutatorTransaction {
|
|
147
|
+
isPersisted: {
|
|
148
|
+
promise: Promise<unknown>;
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
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
|
+
*/
|
|
157
|
+
type MutatorHandle<TArgs> = (args: TArgs) => MutatorTransaction;
|
|
158
|
+
/**
|
|
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
|
+
*/
|
|
163
|
+
interface MutatorRunnerSinks {
|
|
164
|
+
/** Receives the normalized {@link Error} when an invocation rejects, or `undefined` on success / reset. */
|
|
165
|
+
setError: (error: Error | undefined) => void;
|
|
166
|
+
/** Receives `true` while at least one invocation is in flight (ref-counted across overlapping calls), else `false`. */
|
|
167
|
+
setPending: (pending: boolean) => void;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
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
|
+
*/
|
|
188
|
+
declare const createMutatorRunner: <TArgs>(handle: MutatorHandle<TArgs>, sinks: MutatorRunnerSinks) => {
|
|
189
|
+
mutate: (args: TArgs) => Promise<void>;
|
|
190
|
+
reset: () => void;
|
|
191
|
+
};
|
|
192
|
+
interface QueuedMutation<T = unknown> {
|
|
193
|
+
readonly args: Record<string, unknown>;
|
|
194
|
+
readonly functionPath: string;
|
|
195
|
+
/** Stable id used to remove the entry from durable storage once replayed; assigned by the queue when absent. */
|
|
196
|
+
id?: string;
|
|
197
|
+
/**
|
|
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
|
+
*/
|
|
209
|
+
liveAwaiter?: boolean;
|
|
210
|
+
/**
|
|
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
|
+
*/
|
|
215
|
+
readonly onCommit?: (commitCursor: number | undefined) => void;
|
|
216
|
+
/** Rejects if the mutation can no longer be replayed. */
|
|
217
|
+
readonly reject: (error: unknown) => void;
|
|
218
|
+
/** Resolves once the mutation has been replayed against the server. */
|
|
219
|
+
readonly resolve: (value: T) => void;
|
|
220
|
+
readonly shardKey?: string;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
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
|
+
*/
|
|
228
|
+
type EvictHandler = (entry: QueuedMutation, error: Error & {
|
|
229
|
+
code?: string;
|
|
230
|
+
}) => void;
|
|
231
|
+
/** Injected dependencies for {@link OfflineQueue} (kept off the user-facing {@link OfflineQueueOptions}). */
|
|
232
|
+
interface OfflineQueueDeps {
|
|
233
|
+
/** Invoked when an entry is discarded on capacity overflow (carries `OFFLINE_QUEUE_OVERFLOW`). */
|
|
234
|
+
onEvict?: EvictHandler;
|
|
235
|
+
/** Invoked with the new depth after any size change (drives the client's pending-sync count). */
|
|
236
|
+
onSizeChange?: (size: number) => void;
|
|
237
|
+
/** Durable store; when present, writes are mirrored and restored across reloads. */
|
|
238
|
+
persistence?: PersistenceAdapter;
|
|
239
|
+
/** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
|
|
240
|
+
version?: string;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* A process-unique id, used both per-mutation and as the fallback `clientId`. It
|
|
244
|
+
* MUST be globally unique: the server scopes a custom mutator's replay watermark
|
|
245
|
+
* by `(verifiedIdentity, clientId)`, and an anonymous push has no verified
|
|
246
|
+
* identity — so two anonymous clients that collide on `clientId` would share one
|
|
247
|
+
* watermark namespace, letting one stall/suppress the other's ordered mutations.
|
|
248
|
+
* `crypto.randomUUID` covers every modern runtime; the fallback still mixes
|
|
249
|
+
* crypto-quality (or `Math.random`) entropy with the timestamp + counter so it
|
|
250
|
+
* can't collide across two clients started in the same millisecond.
|
|
251
|
+
*/
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Bounded FIFO queue. Mutations issued while the client is offline are
|
|
255
|
+
* enqueued and replayed in the order they were submitted once the WS
|
|
256
|
+
* reconnects and identifies. If the queue exceeds `maxItems` the oldest
|
|
257
|
+
* entry is rejected with `OFFLINE_QUEUE_OVERFLOW`.
|
|
258
|
+
*
|
|
259
|
+
* When a {@link PersistenceAdapter} is supplied, enqueued mutations are mirrored
|
|
260
|
+
* to durable storage so they survive a reload — {@link OfflineQueue.hydrate} restores them on
|
|
261
|
+
* the next startup and the client replays them on reconnect. Durable removal is
|
|
262
|
+
* the caller's responsibility *after* a successful replay (see `LunoraClient`);
|
|
263
|
+
* the queue only persists on enqueue and un-persists on overflow.
|
|
264
|
+
*/
|
|
265
|
+
declare class OfflineQueue {
|
|
266
|
+
/** Opt-in to queueing mutations before the targeted shard's first connect. */
|
|
267
|
+
readonly queueBeforeFirstConnect: boolean;
|
|
268
|
+
private readonly maxItems;
|
|
269
|
+
private readonly onPersistenceError;
|
|
270
|
+
private readonly persistence;
|
|
271
|
+
private readonly onEvict;
|
|
272
|
+
private readonly onSizeChange;
|
|
273
|
+
/** App/schema version stamped on persisted writes; mismatched records are purged on hydrate. */
|
|
274
|
+
private readonly version;
|
|
275
|
+
private readonly items;
|
|
276
|
+
constructor(options?: OfflineQueueOptions, deps?: OfflineQueueDeps);
|
|
277
|
+
get size(): number;
|
|
278
|
+
enqueue<T>(entry: QueuedMutation<T>): void;
|
|
279
|
+
/**
|
|
280
|
+
* Restore mutations persisted in a prior session and re-queue them in FIFO
|
|
281
|
+
* order. Restored entries already live in durable storage, so they are not
|
|
282
|
+
* re-appended; they carry no-op `resolve`/`reject` (the original awaiter is
|
|
283
|
+
* gone after a reload). No-op when no persistence adapter is configured.
|
|
284
|
+
* Returns the distinct shard keys of the restored writes so the caller can
|
|
285
|
+
* open their sockets to trigger a flush.
|
|
286
|
+
*/
|
|
287
|
+
hydrate(): Promise<(string | undefined)[]>;
|
|
288
|
+
/**
|
|
289
|
+
* Remove and return queued mutations. With no `predicate`, drains the whole
|
|
290
|
+
* queue. With one, drains only matching entries (preserving FIFO order) and
|
|
291
|
+
* leaves the rest queued — used to flush a single shard's writes when its
|
|
292
|
+
* socket reconnects while other shards are still down.
|
|
293
|
+
*/
|
|
294
|
+
drain(predicate?: (item: QueuedMutation) => boolean): QueuedMutation[];
|
|
295
|
+
/**
|
|
296
|
+
* Return previously-drained mutations to the front of the queue, preserving
|
|
297
|
+
* their FIFO order, without re-persisting them — they were never unpersisted,
|
|
298
|
+
* so durable storage still holds them. Used when a flush aborts on a transient
|
|
299
|
+
* transport failure: the unreplayed writes stay queued for the next reconnect.
|
|
300
|
+
*/
|
|
301
|
+
requeue(items: QueuedMutation[]): void;
|
|
302
|
+
clear(): void;
|
|
303
|
+
/** Notify the size observer (the client's pending-sync count) after any change. */
|
|
304
|
+
private notifySize;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* In-memory {@link PersistenceAdapter}. Doesn't survive a reload — it exists so
|
|
308
|
+
* the persistence wiring can be exercised without IndexedDB (tests, SSR, or as
|
|
309
|
+
* a deliberate "no durable store" choice that still satisfies the interface).
|
|
310
|
+
* Preserves enqueue order; `clone` keeps callers from mutating stored args.
|
|
311
|
+
*/
|
|
312
|
+
declare const createInMemoryPersistence: () => PersistenceAdapter;
|
|
313
|
+
interface IndexedDbPersistenceOptions {
|
|
314
|
+
/** Database name; defaults to `"lunora"`. */
|
|
315
|
+
databaseName?: string;
|
|
316
|
+
/** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
|
|
317
|
+
indexedDB?: IDBFactory;
|
|
318
|
+
/** Object-store name; defaults to `"offline-mutations"`. */
|
|
319
|
+
storeName?: string;
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* IndexedDB-backed {@link PersistenceAdapter}. Each mutation is stored under an
|
|
323
|
+
* autoincrementing key (so `load()` returns them in enqueue order regardless of
|
|
324
|
+
* the string ids) with a unique secondary index on `id` for `remove()`.
|
|
325
|
+
*
|
|
326
|
+
* The store handle is opened lazily and the open promise is cached, so repeated
|
|
327
|
+
* ops reuse one connection. Throws eagerly if no `IDBFactory` is available —
|
|
328
|
+
* callers in non-browser environments should use {@link createInMemoryPersistence}.
|
|
329
|
+
*/
|
|
330
|
+
declare const createIndexedDbPersistence: (options?: IndexedDbPersistenceOptions) => PersistenceAdapter;
|
|
331
|
+
/**
|
|
332
|
+
* Compose the read-cache key for a subscription. Mirrors how
|
|
333
|
+
* `SubscriptionRegistry` keys live subscriptions so a hydrated value lines up
|
|
334
|
+
* with the subscription that will consume it. `shardKey` defaults to `""` (the
|
|
335
|
+
* root shard) exactly as the registry does.
|
|
336
|
+
*/
|
|
337
|
+
declare const queryCacheKey: (functionPath: string, argsKey: string, shardKey?: string) => string;
|
|
338
|
+
/**
|
|
339
|
+
* In-memory {@link QueryCacheAdapter}. Doesn't survive a reload — it exists so
|
|
340
|
+
* the read-cache wiring can be exercised without IndexedDB (tests, SSR, or as a
|
|
341
|
+
* deliberate "no durable store" choice that still satisfies the interface).
|
|
342
|
+
* Enforces the same LRU row cap as the IndexedDB adapter; `clone` keeps callers
|
|
343
|
+
* from mutating stored values.
|
|
344
|
+
*/
|
|
345
|
+
declare const createInMemoryQueryCache: (options?: {
|
|
346
|
+
maxEntries?: number;
|
|
347
|
+
}) => QueryCacheAdapter;
|
|
348
|
+
interface IndexedDbQueryCacheOptions {
|
|
349
|
+
/** Database name; defaults to `"lunora"` (shared with the offline-mutation store). */
|
|
350
|
+
databaseName?: string;
|
|
351
|
+
/** Injectable `IDBFactory` (e.g. `fake-indexeddb` in tests); defaults to the global `indexedDB`. */
|
|
352
|
+
indexedDB?: IDBFactory;
|
|
353
|
+
/** LRU row cap; defaults to 500. The oldest rows by `ts` are pruned on `put` once exceeded. */
|
|
354
|
+
maxEntries?: number;
|
|
355
|
+
/** Object-store name; defaults to `"query-cache"`. */
|
|
356
|
+
storeName?: string;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* IndexedDB-backed {@link QueryCacheAdapter}. Each query is stored under its
|
|
360
|
+
* composite key (`functionPath::argsKey::shardKey`) with a `ts` index driving
|
|
361
|
+
* LRU eviction. The store handle is opened lazily and cached, so repeated ops
|
|
362
|
+
* reuse one connection.
|
|
363
|
+
*
|
|
364
|
+
* The store lives in the same `lunora` database as the offline-mutation queue
|
|
365
|
+
* (bumped to schema v2). Opening it upgrades a v1 database in place, adding the
|
|
366
|
+
* `query-cache` store without touching `offline-mutations`. Throws eagerly if no
|
|
367
|
+
* `IDBFactory` is available — callers in non-browser environments should use
|
|
368
|
+
* {@link createInMemoryQueryCache}.
|
|
369
|
+
*/
|
|
370
|
+
declare const createIndexedDbQueryCache: (options?: IndexedDbQueryCacheOptions) => QueryCacheAdapter;
|
|
371
|
+
/**
|
|
372
|
+
* Exponential backoff calculator with optional jitter.
|
|
373
|
+
*
|
|
374
|
+
* `next()` doubles the delay each call up to `maxDelayMs`. When `jitter` is
|
|
375
|
+
* enabled the returned value is randomized in `[delay/2, delay]` so a fleet
|
|
376
|
+
* of clients reconnecting at the same time spread out their retries.
|
|
377
|
+
*/
|
|
378
|
+
interface ReconnectCalculator {
|
|
379
|
+
/** Returns the delay to wait before the next reconnect attempt. */
|
|
380
|
+
next: () => number;
|
|
381
|
+
/** Resets the backoff to the initial delay (call on successful reconnect). */
|
|
382
|
+
reset: () => void;
|
|
383
|
+
}
|
|
384
|
+
declare const createReconnect: (options?: ReconnectOptions, random?: () => number) => ReconnectCalculator;
|
|
385
|
+
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 };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export { createAsyncStoragePersistence } from './packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs';
|
|
2
|
+
export { default as createInMemoryBookmarkStorage } from './packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs';
|
|
3
|
+
export { applyDelta, isMutationDelta } from './packem_shared/applyDelta-4jFGTPA3.mjs';
|
|
4
|
+
export { CONFLICT_ERROR_CODE, isConflictError } from './packem_shared/CONFLICT_ERROR_CODE-aUdVbEDw.mjs';
|
|
5
|
+
export { c as createLocalStore } from './packem_shared/local-store-BNgN3Dw3.mjs';
|
|
6
|
+
export { LunoraClient } from './packem_shared/LunoraClient-CgZ6FhKP.mjs';
|
|
7
|
+
export { createMutationRunner } from './packem_shared/createMutationRunner-BqsavzvG.mjs';
|
|
8
|
+
export { createMutatorRunner } from './packem_shared/createMutatorRunner-BETvCd0p.mjs';
|
|
9
|
+
export { O as OfflineQueue } from './packem_shared/offline-queue-7Wc4onA0.mjs';
|
|
10
|
+
export { createInMemoryPersistence, createIndexedDbPersistence } from './packem_shared/createInMemoryPersistence-CW82inU5.mjs';
|
|
11
|
+
export { preloadQuery, preloadedQueryResult } from './packem_shared/preloadQuery-lobFkD2Z.mjs';
|
|
12
|
+
export { createInMemoryQueryCache, createIndexedDbQueryCache, queryCacheKey } from './packem_shared/createInMemoryQueryCache-B1PQ9Twl.mjs';
|
|
13
|
+
export { createReconnect } from './packem_shared/createReconnect-Di_-oHH7.mjs';
|
|
14
|
+
export { DEFAULT_MAX_BUFFER, createStream } from './packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs';
|
|
15
|
+
export { S as SubscriptionRegistry } from './packem_shared/subscription-C1Jy7HiF.mjs';
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
const DEFAULT_MAX_BUFFER = 1024;
|
|
2
|
+
const createStream = (options) => {
|
|
3
|
+
const maxBuffer = options.maxBuffer ?? DEFAULT_MAX_BUFFER;
|
|
4
|
+
const buffer = [];
|
|
5
|
+
const pending = [];
|
|
6
|
+
let done = false;
|
|
7
|
+
let failure;
|
|
8
|
+
let cancelled = false;
|
|
9
|
+
const flushOne = () => {
|
|
10
|
+
const waiter = pending.shift();
|
|
11
|
+
if (!waiter) {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
if (failure) {
|
|
15
|
+
waiter.reject(failure);
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
if (buffer.length > 0) {
|
|
19
|
+
const value = buffer.shift();
|
|
20
|
+
waiter.resolve({ done: false, value });
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
if (done) {
|
|
24
|
+
waiter.resolve({ done: true, value: void 0 });
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
pending.unshift(waiter);
|
|
28
|
+
return false;
|
|
29
|
+
};
|
|
30
|
+
const handle = {
|
|
31
|
+
complete() {
|
|
32
|
+
if (done || failure) {
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
done = true;
|
|
36
|
+
while (flushOne()) {
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
fail(error) {
|
|
40
|
+
if (done || failure) {
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
failure = error;
|
|
44
|
+
buffer.length = 0;
|
|
45
|
+
while (flushOne()) {
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
push(value) {
|
|
49
|
+
if (done || failure || cancelled) {
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (buffer.length >= maxBuffer) {
|
|
53
|
+
handle.fail(
|
|
54
|
+
Object.assign(new Error(`stream buffer overflow (max=${maxBuffer.toString()}); the consumer cannot keep up with the producer`), {
|
|
55
|
+
code: "STREAM_BACKPRESSURE"
|
|
56
|
+
})
|
|
57
|
+
);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
buffer.push(value);
|
|
61
|
+
flushOne();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const cancel = () => {
|
|
65
|
+
if (cancelled) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
cancelled = true;
|
|
69
|
+
done = true;
|
|
70
|
+
buffer.length = 0;
|
|
71
|
+
try {
|
|
72
|
+
options.onCancel();
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
while (flushOne()) {
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const iterable = {
|
|
79
|
+
cancel,
|
|
80
|
+
[Symbol.asyncIterator]() {
|
|
81
|
+
return {
|
|
82
|
+
next() {
|
|
83
|
+
if (failure) {
|
|
84
|
+
return Promise.reject(failure);
|
|
85
|
+
}
|
|
86
|
+
if (buffer.length > 0) {
|
|
87
|
+
const value = buffer.shift();
|
|
88
|
+
return Promise.resolve({ done: false, value });
|
|
89
|
+
}
|
|
90
|
+
if (done) {
|
|
91
|
+
return Promise.resolve({ done: true, value: void 0 });
|
|
92
|
+
}
|
|
93
|
+
return new Promise((resolve, reject) => {
|
|
94
|
+
pending.push({ reject, resolve });
|
|
95
|
+
});
|
|
96
|
+
},
|
|
97
|
+
return() {
|
|
98
|
+
cancel();
|
|
99
|
+
return Promise.resolve({ done: true, value: void 0 });
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
return { handle, iterable };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export { DEFAULT_MAX_BUFFER, createStream };
|