@taladb/react 0.9.2 → 0.9.4

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/dist/index.d.mts CHANGED
@@ -1,10 +1,42 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import { ReactNode } from 'react';
3
- import { TalaDB, OpenDBOptions, Document, Collection, Filter } from 'taladb';
3
+ import { CollectionOptions, Document, TalaDB, OpenDBOptions, Collection, Filter, AggregatePipeline, RestSourceOptions, ReplicationSource, CoverageState } from 'taladb';
4
4
 
5
- type TalaDBProviderProps = {
5
+ /**
6
+ * Per-collection options (`schema`, `syncSchema`, `migrateDocument`, …), keyed by
7
+ * collection name.
8
+ *
9
+ * Register them once on the provider and every hook below it — `useCollection`,
10
+ * and therefore `useFind`, `useQuery` and `useMutation` — resolves a *configured*
11
+ * collection. Without this, those hooks call `db.collection(name)` with no
12
+ * options, so a hook-driven write silently skips the strict `schema` validation
13
+ * and the `_v` stamp that `db.collection(name, { … })` would have applied.
14
+ */
15
+ type CollectionRegistry = Record<string, CollectionOptions<any>>;
16
+ /** Resolves the registered options for a collection. Stable across renders. */
17
+ interface CollectionResolver {
18
+ get<T extends Document>(name: string): CollectionOptions<T> | undefined;
19
+ }
20
+ declare function useCollectionOptions(): CollectionResolver;
21
+ type SharedProps = {
6
22
  children: ReactNode;
7
- } & ({
23
+ /**
24
+ * Per-collection options, keyed by collection name — see {@link CollectionRegistry}.
25
+ *
26
+ * ```tsx
27
+ * <TalaDBProvider
28
+ * name="app.db"
29
+ * collections={{
30
+ * bookings: { schema: BookingSchema, syncSchema: { version: 1 } },
31
+ * }}
32
+ * >
33
+ * ```
34
+ * Treated as static configuration: read when a collection handle is first
35
+ * created, so an inline object here does not thrash live queries.
36
+ */
37
+ collections?: CollectionRegistry;
38
+ };
39
+ type TalaDBProviderProps = SharedProps & ({
8
40
  /** A TalaDB instance you opened yourself with `openDB()`. */
9
41
  db: TalaDB;
10
42
  name?: never;
@@ -57,17 +89,30 @@ declare function useTalaDB(): TalaDB;
57
89
  /**
58
90
  * Returns a stable `Collection<T>` handle from the nearest `<TalaDBProvider>`.
59
91
  *
60
- * The returned collection is memoised the same object reference is returned
61
- * on every render unless the db instance or collection name changes. Pass it
62
- * directly to `useFind` or `useFindOne` without wrapping in `useMemo`.
92
+ * The collection is opened **with its registered options** the `schema`,
93
+ * `syncSchema` and `migrateDocument` declared in the provider's `collections`
94
+ * prop, or the `options` passed here (which win). That is what makes a write
95
+ * through `useMutation` hard-fail on an invalid document and carry its `_v`
96
+ * shape version, exactly as `db.collection(name, { … })` does. Without it the
97
+ * hooks resolve a bare, unconfigured handle and silently skip validation.
98
+ *
99
+ * The returned collection is memoised — the same object reference is returned on
100
+ * every render unless the db instance or collection name changes. Pass it
101
+ * directly to `useFind` or `useFindOne` without wrapping in `useMemo`. Options
102
+ * are read when the handle is first created and treated as static configuration,
103
+ * so an inline `{ schema }` object cannot thrash live-query subscriptions.
63
104
  *
64
- * @param name The collection name (e.g. `'articles'`).
105
+ * @param name The collection name (e.g. `'articles'`).
106
+ * @param options Per-call options; overrides the provider's registry entry.
65
107
  *
66
108
  * @example
109
+ * // Registered once on the provider — every hook below it picks this up:
110
+ * <TalaDBProvider name="app.db" collections={{ articles: { schema: Article } }}>
111
+ *
67
112
  * const articles = useCollection<Article>('articles')
68
113
  * const { data, loading } = useFind(articles, { locale: 'en' })
69
114
  */
70
- declare function useCollection<T extends Document>(name: string): Collection<T>;
115
+ declare function useCollection<T extends Document>(name: string, options?: CollectionOptions<T>): Collection<T>;
71
116
 
72
117
  interface FindResult<T> {
73
118
  /** The current matching documents. Empty array while loading. */
@@ -118,6 +163,40 @@ interface FindOneResult<T> {
118
163
  */
119
164
  declare function useFindOne<T extends Document>(collection: Collection<T>, filter: Filter<T>): FindOneResult<T>;
120
165
 
166
+ interface AggregateResult<R> {
167
+ /** The current pipeline results. Empty while loading. */
168
+ data: R[];
169
+ /** True until the first snapshot has been delivered. */
170
+ loading: boolean;
171
+ /** Most recent subscription error, cleared by the next successful snapshot. */
172
+ error: unknown | null;
173
+ }
174
+ /**
175
+ * Subscribe to a **live aggregation**. Re-renders whenever the results change.
176
+ *
177
+ * This is the paging primitive. `find()` has no sort/skip/limit — only `aggregate`
178
+ * does — but `aggregate` on its own returns a *dead snapshot*: call it in an effect
179
+ * and the page sits frozen while a background hydration fills the collection
180
+ * underneath it. The user watches a spinner finish and the rows never arrive.
181
+ *
182
+ * So anything that pages locally subscribes here rather than calling `aggregate`
183
+ * directly.
184
+ *
185
+ * @param collection A `Collection<T>` (memoize it, or take it from `useCollection`).
186
+ * @param pipeline Inline arrays are safe — the pipeline is serialised for
187
+ * subscription identity, so a fresh array each render does not
188
+ * re-subscribe.
189
+ *
190
+ * @example
191
+ * const page = useAggregate<Product, Product>(products, [
192
+ * { $match: { category: 'kitchen' } },
193
+ * { $sort: { price: 1 } },
194
+ * { $skip: 100 },
195
+ * { $limit: 100 },
196
+ * ])
197
+ */
198
+ declare function useAggregate<T extends Document, R extends Document = T>(collection: Collection<T>, pipeline: AggregatePipeline<T>): AggregateResult<R>;
199
+
121
200
  /** Resolved network configuration for one replicated slice. */
122
201
  interface ResolvedReplicationConfig {
123
202
  /** Base URL; `/push` and `/pull` are appended by {@link HttpSyncAdapter}. */
@@ -138,6 +217,37 @@ interface ResolvedReplicationConfig {
138
217
  };
139
218
  }
140
219
 
220
+ /** When the background hydration walk is allowed to start. */
221
+ type HydrateMode =
222
+ /** Immediately on mount. */
223
+ 'eager'
224
+ /** When the browser is idle (default). Keeps first paint responsive. */
225
+ | 'idle'
226
+ /** Never automatically — the app calls `hydrate()` itself. */
227
+ | 'manual';
228
+ interface ReplicateScope<RemoteRow = any, T extends Document = Document> extends Omit<RestSourceOptions<RemoteRow, T>, 'collection'> {
229
+ /**
230
+ * Provide a fully custom source instead of the REST defaults. When present,
231
+ * every other field here is ignored.
232
+ */
233
+ source?: ReplicationSource<RemoteRow, T>;
234
+ hydrate?: HydrateMode;
235
+ /** Rows per bootstrap page. Default 500. */
236
+ pageSize?: number;
237
+ /** Re-check the origin for changes on this interval. `0` disables. */
238
+ refreshMs?: number;
239
+ /**
240
+ * Fetch the current query directly when coverage isn't ready yet, so a cold
241
+ * start paints immediately. Default `true`.
242
+ *
243
+ * Mandatory in practice for a Vite SPA or React Native, which have no server
244
+ * render to paint behind while the replica fills.
245
+ */
246
+ bridge?: boolean;
247
+ }
248
+ /** One entry per local collection. */
249
+ type ReplicateRegistry = Record<string, ReplicateScope<any, any>>;
250
+
141
251
  /** A slice to warm on first run — a collection, optionally on a specific endpoint. */
142
252
  type PrefetchSlice = {
143
253
  collection: string;
@@ -191,7 +301,15 @@ interface ReplicationConfig {
191
301
  /** Max concurrent prefetch pulls — keeps the active page from starving. Default `2`. */
192
302
  prefetchConcurrency?: number;
193
303
  }
194
- interface ReplicationProviderProps extends ReplicationConfig {
304
+ interface ReplicationProviderProps extends Partial<ReplicationConfig> {
305
+ /**
306
+ * Collections to replicate from a remote origin, keyed by local collection name.
307
+ *
308
+ * This is what makes `useQuery` a local read: once a collection is fully
309
+ * hydrated for its scope, filtering, sorting and paging never touch the network.
310
+ * See {@link ReplicateRegistry}.
311
+ */
312
+ replicate?: ReplicateRegistry;
195
313
  children: ReactNode;
196
314
  }
197
315
  /**
@@ -212,7 +330,7 @@ interface ReplicationProviderProps extends ReplicationConfig {
212
330
  * </TalaDBProvider>
213
331
  * ```
214
332
  */
215
- declare function ReplicationProvider({ children, ...config }: ReplicationProviderProps): react_jsx_runtime.JSX.Element;
333
+ declare function ReplicationProvider({ children, replicate, ...config }: ReplicationProviderProps): react_jsx_runtime.JSX.Element;
216
334
  /**
217
335
  * Read the nearest replication config, merged with per-hook overrides.
218
336
  * Non-throwing: `config` is `null` when no endpoint is resolvable (valid for
@@ -223,73 +341,134 @@ declare function useReplicationConfig(overrides?: Partial<ReplicationConfig>): {
223
341
  pollMs: number;
224
342
  };
225
343
 
344
+ interface Coverage {
345
+ /** The raw state machine value. */
346
+ status: CoverageState['status'];
347
+ /**
348
+ * Whether a purely local read is authorized.
349
+ *
350
+ * True **only** for `complete`. Notably *not* for `best-effort`, which means we
351
+ * applied every row the origin gave us but the origin could not pin a snapshot —
352
+ * so a row that shifted between pages during the walk may never have been seen,
353
+ * and we cannot prove the replica is whole. Serving that as authoritative would
354
+ * silently return incomplete results, which is worse than going to the network.
355
+ */
356
+ ready: boolean;
357
+ /** Rows hydrated so far. */
358
+ rows: number;
359
+ /** Total rows in scope when supplied by the origin. */
360
+ total?: number;
361
+ /** 0–1 when the origin reported a total; otherwise undefined. */
362
+ progress?: number;
363
+ /** Present on `error`, `stale` and `best-effort`. */
364
+ reason?: string;
365
+ }
226
366
  /**
227
- * How a `useQuery` combines the local replica with the remote origin.
228
- * *(`remote-only` is a planned addition; the durable-replica model makes it a
229
- * rare escape hatch.)*
367
+ * How much of a collection is local, and whether it can be trusted for a
368
+ * network-free read.
369
+ *
370
+ * @example
371
+ * const { ready, progress } = useCoverage('products')
372
+ * if (!ready) return <ProgressBar value={progress} />
230
373
  */
374
+ declare function useCoverage(collection: string): Coverage;
375
+ /** Semantic alias for progress-oriented UIs. */
376
+ declare const useHydrationProgress: typeof useCoverage;
377
+
231
378
  type ReadSource = 'local-first' | 'remote-first' | 'local-only';
232
379
  interface UseQueryOptions<T extends Document> extends Partial<Pick<ReplicationConfig, 'endpoint' | 'getAuth' | 'fetch' | 'paths' | 'pollMs'>> {
233
- /** Collection name replicated as a whole; the `filter` narrows locally. */
380
+ /** The local collection to read. */
234
381
  collection: string;
235
- /** Live filter over the local collection. Inline objects are safe. */
382
+ /** Mongo-style filter, applied **locally**. */
236
383
  filter?: Filter<T>;
237
- /**
238
- * - `local-first` *(default)* serve local immediately; refresh in the
239
- * background, and the live query re-renders when the pull lands.
240
- * - `remote-first` — stay `loading` until the first pull completes, then serve.
241
- * - `local-only` never touch the network (no endpoint required).
242
- */
384
+ /** Sort, applied locally. `1` ascending, `-1` descending. */
385
+ sort?: Partial<Record<keyof T & string, 1 | -1>>;
386
+ /** 1-based page number. Requires `limit`. */
387
+ page?: number;
388
+ /** Rows per page. */
389
+ limit?: number;
390
+ /** Skip N rows. Ignored when `page` is set. */
391
+ skip?: number;
392
+ /** Skip the query entirely (e.g. while a route param is undefined). */
393
+ enabled?: boolean;
394
+ /** Legacy sync-contract read policy. Used when no full-replication scope exists. */
243
395
  source?: ReadSource;
244
396
  }
245
397
  interface QueryResult<T> {
246
- /** Current matching documents from the local replica. Reactive. */
398
+ /** The current page. Reactive: re-renders as rows land. */
247
399
  data: T[];
248
- /** First local snapshot pending plus the first pull, for `remote-first`. */
400
+ /** Total rows in the replicated scope when reported by the origin. */
401
+ total?: number;
402
+ /** True until the first local snapshot arrives. */
249
403
  loading: boolean;
250
- /** Most recent local-read error. */
404
+ /** Most recent local read error. */
251
405
  error: unknown | null;
252
- /** A background replication pass is in flight. */
406
+ /** Most recent cold-start bridge error. */
407
+ fetchError: unknown | null;
408
+ /** How much of the collection is local, and whether it is trustworthy. */
409
+ coverage: Coverage;
410
+ /**
411
+ * A cold-start bridge fetch is in flight — we are serving the network because
412
+ * the replica isn't complete yet.
413
+ */
414
+ fetching: boolean;
415
+ /** Legacy sync-contract pull in progress. */
253
416
  syncing: boolean;
254
- /** Most recent replication error (the local data is still served). */
417
+ /** Legacy sync-contract pull error. */
255
418
  syncError: unknown | null;
256
- /** Trigger a pull now. No-op for `local-only`. */
419
+ /** Force a delta refresh from the origin. */
257
420
  refetch: () => Promise<void>;
258
421
  }
259
422
  /**
260
- * Bind a component to a slice of a remote origin, backed by the local replica.
423
+ * Read a page of a collection.
424
+ *
425
+ * ## The point
426
+ *
427
+ * Once the collection is **covered** — fully replicated for this scope — this hook
428
+ * touches the network **zero times**. Filtering, sorting and paging are local
429
+ * queries against the on-device database. Page 1 → page 2 → a new filter → page 47
430
+ * → back to page 1: every one is a local read, instant and offline-capable.
431
+ * Pagination stops being a network concern at all.
432
+ *
433
+ * That is the whole reason to put a real database on the device. A cache of API
434
+ * pages could only ever answer the queries you already asked; a *covered replica*
435
+ * answers queries nobody has asked yet.
436
+ *
437
+ * ## Before coverage lands
261
438
  *
262
- * The read is a live query over the local collection (`useFind`); the network
263
- * pull writes into that same collection, so the live query re-renders on its
264
- * own one-way data flow, no `queryKey`, no `invalidateQueries`. See
265
- * `docs/scoped-replication.md`.
439
+ * On a cold start the replica is empty, and a SPA or React Native app has no server
440
+ * render to paint behind. So the hook **bridges**: it fetches exactly the rows this
441
+ * query needs and writes them into the same collection, under the same derived ids
442
+ * the background walk will use. Those rows are not a cache entry to be reconciled
443
+ * later — they are the replica, arriving early. When the walk reaches them it
444
+ * overwrites them in place.
266
445
  *
267
446
  * @example
268
- * const { data, loading, syncing } = useQuery<Product>({
447
+ * const { data, coverage } = useQuery<Product>({
269
448
  * collection: 'products',
270
- * filter: { category: 'kitchen' },
271
- * pollMs: 30_000,
449
+ * filter: { category: 'kitchen', price: { $lt: 500 } },
450
+ * sort: { price: 1 },
451
+ * page: 2,
452
+ * limit: 100,
272
453
  * })
273
454
  */
274
455
  declare function useQuery<T extends Document>(options: UseQueryOptions<T>): QueryResult<T>;
275
456
 
276
457
  /**
277
- * Run several scoped queries at once one replication + live query per entry,
278
- * in parallel. The result array is index-aligned with `queries`.
458
+ * Several pages at once, from several collections. Index-aligned with `queries`.
279
459
  *
280
- * Each entry is an independent `useQuery`: its own collection, filter, source,
281
- * and (optionally) endpoint. This is the multi-slice page case — e.g. a
282
- * dashboard that needs `orders` and `products` from the same origin. There are
283
- * no cross-collection joins (TalaDB is a document store); compose in the
284
- * component.
460
+ * Hooks can't be called in a variable-length loop, so this manages its own
461
+ * subscriptions rather than calling `useQuery` N times. Behaviour is otherwise
462
+ * identical: once a collection is covered, its read is purely local.
285
463
  *
286
- * v1 note: entries are typed as `Document`. For a strictly-typed single slice
287
- * use `useQuery<T>`; per-entry generics (tuple typing) are a follow-up.
464
+ * TalaDB is a document store with no cross-collection joins, so a page needing
465
+ * several collections composes them in the component (or denormalises at the
466
+ * origin). This is the hook for that.
288
467
  *
289
468
  * @example
290
- * const [orders, products] = useQueries([
291
- * { collection: 'orders', filter: { open: true } },
292
- * { collection: 'products' },
469
+ * const [products, categories] = useQueries([
470
+ * { collection: 'products', filter: { category }, sort: { price: 1 }, page, limit: 50 },
471
+ * { collection: 'categories' },
293
472
  * ])
294
473
  */
295
474
  declare function useQueries(queries: UseQueryOptions<Document>[]): QueryResult<Document>[];
@@ -347,4 +526,4 @@ interface MutationResult<T extends Document> {
347
526
  */
348
527
  declare function useMutation<T extends Document>(options: UseMutationOptions): MutationResult<T>;
349
528
 
350
- export { type FindOneResult, type FindResult, type MutationResult, type PrefetchEntry, type PrefetchMode, type PrefetchSlice, type QueryResult, type ReadSource, type ReplicationConfig, ReplicationProvider, type ReplicationProviderProps, TalaDBProvider, type TalaDBProviderProps, type UseMutationOptions, type UseQueryOptions, type WriteOp, useCollection, useFind, useFindOne, useMutation, useQueries, useQuery, useReplicationConfig, useTalaDB };
529
+ export { type AggregateResult, type CollectionRegistry, type CollectionResolver, type Coverage, type FindOneResult, type FindResult, type HydrateMode, type MutationResult, type PrefetchEntry, type PrefetchMode, type PrefetchSlice, type QueryResult, type ReplicateRegistry, type ReplicateScope, type ReplicationConfig, ReplicationProvider, type ReplicationProviderProps, TalaDBProvider, type TalaDBProviderProps, type UseMutationOptions, type UseQueryOptions, type WriteOp, useAggregate, useCollection, useCollectionOptions, useCoverage, useFind, useFindOne, useHydrationProgress, useMutation, useQueries, useQuery, useReplicationConfig, useTalaDB };