taladb 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.
@@ -40,7 +40,11 @@ function unsupportedSync(runtime) {
40
40
  }
41
41
  async function readCursor(cursorCol, target) {
42
42
  const doc = await cursorCol.findOne({ target });
43
- return { pushMs: doc?.pushMs ?? 0, pullMs: doc?.pullMs ?? 0 };
43
+ return {
44
+ pushMs: doc?.pushMs ?? 0,
45
+ pullMs: doc?.pullMs ?? 0,
46
+ pullCursor: doc?.pullCursor
47
+ };
44
48
  }
45
49
  async function writeCursor(cursorCol, target, cursor) {
46
50
  const updated = await cursorCol.updateOne({ target }, { $set: { ...cursor } });
@@ -48,13 +52,19 @@ async function writeCursor(cursorCol, target, cursor) {
48
52
  await cursorCol.insert({ target, ...cursor });
49
53
  }
50
54
  }
55
+ function isCursorAdapter(adapter) {
56
+ return typeof adapter.pullWithCursor === "function";
57
+ }
58
+ var MAX_PULL_PAGES = 1e4;
51
59
  async function runSync(handle, adapter, options, syncSchemas = {}) {
52
60
  const direction = options.direction ?? "both";
53
61
  const target = options.target ?? "default";
54
62
  const doPush = direction === "push" || direction === "both";
55
63
  const doPull = direction === "pull" || direction === "both";
56
- if (doPull && !adapter.pull) {
57
- throw new Error(`sync direction '${direction}' requires adapter.pull()`);
64
+ if (doPull && !adapter.pull && !isCursorAdapter(adapter)) {
65
+ throw new Error(
66
+ `sync direction '${direction}' requires adapter.pull() or adapter.pullWithCursor()`
67
+ );
58
68
  }
59
69
  if (doPush && !adapter.push) {
60
70
  throw new Error(`sync direction '${direction}' requires adapter.push()`);
@@ -71,17 +81,35 @@ async function runSync(handle, adapter, options, syncSchemas = {}) {
71
81
  let pulled = 0;
72
82
  let skipped = 0;
73
83
  let quarantined = 0;
84
+ let pullCursor = cursor.pullCursor;
85
+ async function importOne(changeset) {
86
+ if (!changeset || changeset === "[]") return;
87
+ if (useValidated) {
88
+ const report = await handle.importChangesValidated(changeset, JSON.stringify(scopedSchemas));
89
+ pulled += report.applied;
90
+ skipped += report.skipped;
91
+ quarantined += report.quarantined;
92
+ } else {
93
+ pulled += await handle.importChanges(changeset);
94
+ }
95
+ }
74
96
  if (doPull) {
75
- const remote = await adapter.pull(0);
76
- if (remote && remote !== "[]") {
77
- if (useValidated) {
78
- const report = await handle.importChangesValidated(remote, JSON.stringify(scopedSchemas));
79
- pulled = report.applied;
80
- skipped = report.skipped;
81
- quarantined = report.quarantined;
82
- } else {
83
- pulled = await handle.importChanges(remote);
97
+ if (isCursorAdapter(adapter)) {
98
+ let pages = 0;
99
+ for (; ; ) {
100
+ const result = await adapter.pullWithCursor(pullCursor ?? null);
101
+ await importOne(result.changeset);
102
+ pullCursor = result.cursor;
103
+ await writeCursor(cursorCol, target, { ...cursor, pullCursor });
104
+ if (!result.hasMore) break;
105
+ if (++pages >= MAX_PULL_PAGES) {
106
+ throw new Error(
107
+ `sync: origin returned hasMore after ${MAX_PULL_PAGES} pages for target '${target}' \u2014 it is probably not advancing its cursor.`
108
+ );
109
+ }
84
110
  }
111
+ } else {
112
+ await importOne(await adapter.pull(0));
85
113
  }
86
114
  }
87
115
  let pushed = 0;
@@ -91,7 +119,8 @@ async function runSync(handle, adapter, options, syncSchemas = {}) {
91
119
  }
92
120
  await writeCursor(cursorCol, target, {
93
121
  pushMs: cursor.pushMs,
94
- pullMs: cursor.pullMs
122
+ pullMs: cursor.pullMs,
123
+ ...pullCursor !== void 0 ? { pullCursor } : {}
95
124
  });
96
125
  return { pushed, pulled, skipped, quarantined, cursor: 0 };
97
126
  }
@@ -132,6 +161,478 @@ var HttpSyncAdapter = class {
132
161
  }
133
162
  };
134
163
 
164
+ // src/derive-id.ts
165
+ var FNV1A128_OFFSET_BASIS = 0x6c62272e07bb014262b821756295c58dn;
166
+ var FNV1A128_PRIME = 0x0000000001000000000000000000013bn;
167
+ var MASK_128 = (1n << 128n) - 1n;
168
+ var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
169
+ var UTF8 = new TextEncoder();
170
+ function encodeUlid(value) {
171
+ let out = "";
172
+ for (let i = 25; i >= 0; i--) {
173
+ out += CROCKFORD[Number(value >> BigInt(i * 5) & 31n)];
174
+ }
175
+ return out;
176
+ }
177
+ function deriveDocId(collection, key) {
178
+ const bytes = [...UTF8.encode(collection), 0, ...UTF8.encode(key)];
179
+ let hash = FNV1A128_OFFSET_BASIS;
180
+ for (const byte of bytes) {
181
+ hash ^= BigInt(byte);
182
+ hash = hash * FNV1A128_PRIME & MASK_128;
183
+ }
184
+ return encodeUlid(hash);
185
+ }
186
+
187
+ // src/replication/coverage.ts
188
+ var COVERAGE_COLLECTION = "__taladb_replica";
189
+ function coverageKey(key) {
190
+ return [
191
+ key.origin,
192
+ key.collection,
193
+ key.scope,
194
+ `p${key.projectionVersion}`,
195
+ `s${key.schemaVersion}`
196
+ ].map(encodeURIComponent).join("|");
197
+ }
198
+ var CoverageStore = class {
199
+ constructor(db) {
200
+ this.col = db.collection(COVERAGE_COLLECTION);
201
+ }
202
+ async read(key) {
203
+ const doc = await this.col.findOne({ key: coverageKey(key) });
204
+ if (!doc?.state) return { status: "empty" };
205
+ try {
206
+ return JSON.parse(doc.state);
207
+ } catch {
208
+ return { status: "empty" };
209
+ }
210
+ }
211
+ async write(key, state) {
212
+ const k = coverageKey(key);
213
+ const state_json = JSON.stringify(state);
214
+ await this.col.replaceManyWithIds(
215
+ [{ _id: deriveDocId(COVERAGE_COLLECTION, k), key: k, state: state_json }],
216
+ "local"
217
+ );
218
+ }
219
+ /** Drop a scope's coverage, forcing a fresh bootstrap on next use. */
220
+ async clear(key) {
221
+ const k = coverageKey(key);
222
+ await this.col.deleteManyWithIds([deriveDocId(COVERAGE_COLLECTION, k)], "local");
223
+ }
224
+ };
225
+ function isAuthoritative(state) {
226
+ return state.status === "complete";
227
+ }
228
+ function rowsApplied(state) {
229
+ switch (state.status) {
230
+ case "hydrating":
231
+ case "complete":
232
+ case "best-effort":
233
+ return state.rowsApplied;
234
+ default:
235
+ return 0;
236
+ }
237
+ }
238
+ function progress(state) {
239
+ if (state.status === "complete") return 1;
240
+ if (state.status !== "hydrating" || !state.total) return void 0;
241
+ return Math.min(1, state.rowsApplied / state.total);
242
+ }
243
+
244
+ // src/replication/coordinator.ts
245
+ var DEFAULT_PAGE_SIZE = 500;
246
+ var defaultYield = () => new Promise((resolve) => setTimeout(resolve, 0));
247
+ var MAX_BOOTSTRAP_PAGES = 1e5;
248
+ var inflightByDatabase = /* @__PURE__ */ new WeakMap();
249
+ var REPLICA_SCOPE_FIELD = "_replica_scope";
250
+ var REPLICA_REVISION_FIELD = "_remote_rev";
251
+ var ReplicationCoordinator = class {
252
+ constructor(db, source, options = {}) {
253
+ this.db = db;
254
+ this.source = source;
255
+ this.coverage = new CoverageStore(db);
256
+ this.key = {
257
+ origin: source.origin,
258
+ collection: source.collection,
259
+ scope: source.scope,
260
+ projectionVersion: source.projectionVersion,
261
+ schemaVersion: source.schemaVersion
262
+ };
263
+ this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
264
+ this.yieldFn = options.yieldFn ?? defaultYield;
265
+ this.onProgress = options.onProgress;
266
+ this.collectionOptions = options.collectionOptions;
267
+ let shared = inflightByDatabase.get(db);
268
+ if (!shared) {
269
+ shared = /* @__PURE__ */ new Map();
270
+ inflightByDatabase.set(db, shared);
271
+ }
272
+ this.inflight = shared;
273
+ }
274
+ get replicaScope() {
275
+ return coverageKey(this.key);
276
+ }
277
+ get identityNamespace() {
278
+ return `${this.source.origin}\0${this.source.scope}\0${this.source.collection}`;
279
+ }
280
+ getCoverage() {
281
+ return this.coverage.read(this.key);
282
+ }
283
+ /** Whether a purely local read is authorized right now. */
284
+ async isReady() {
285
+ return isAuthoritative(await this.getCoverage());
286
+ }
287
+ /** Dedup by intent: identical concurrent work joins rather than duplicating. */
288
+ dedup(key, run) {
289
+ const existing = this.inflight.get(key);
290
+ if (existing) return existing;
291
+ const pass = run().finally(() => this.inflight.delete(key));
292
+ this.inflight.set(key, pass);
293
+ return pass;
294
+ }
295
+ /**
296
+ * Write a batch of remote rows into the local collection.
297
+ *
298
+ * One commit for the whole batch, ids derived from the origin's primary key, and
299
+ * `origin: 'remote'` so the rows can never replicate back out at the origin they
300
+ * came from. This is the *only* write path in the coordinator — bootstrap, delta
301
+ * and bridge all funnel through it, which is precisely why they converge instead
302
+ * of conflicting.
303
+ */
304
+ async applyRows(rows) {
305
+ if (rows.length === 0) return [];
306
+ const col = this.db.collection(this.source.collection, this.collectionOptions);
307
+ const docs = rows.map(
308
+ (row) => {
309
+ const revision = this.source.revisionOf(row);
310
+ return {
311
+ ...this.source.mapRow(row),
312
+ _id: deriveDocId(this.identityNamespace, String(this.source.keyOf(row))),
313
+ [REPLICA_SCOPE_FIELD]: this.replicaScope,
314
+ [REPLICA_REVISION_FIELD]: revision
315
+ };
316
+ }
317
+ );
318
+ await col.replaceManyWithIds(docs, "remote");
319
+ return docs.map((doc) => doc._id);
320
+ }
321
+ /**
322
+ * Hydrate the scope: walk the origin page by page until the whole collection is
323
+ * local, then mark it complete.
324
+ *
325
+ * Resumable and idempotent. If the walk is interrupted — a reload, a crash, a
326
+ * dead network — the next call picks up from the last committed page, and
327
+ * re-applying a page it already wrote is a no-op because the ids are derived.
328
+ */
329
+ hydrate() {
330
+ return this.dedup(`${this.replicaScope}:hydrate`, () => this.runHydrate());
331
+ }
332
+ async runHydrate() {
333
+ let state = await this.coverage.read(this.key);
334
+ if (state.status === "complete") return state;
335
+ let page = null;
336
+ let snapshot = null;
337
+ let rowsApplied2 = 0;
338
+ let total;
339
+ let deltaCursor;
340
+ if (state.status === "hydrating") {
341
+ page = state.nextPage;
342
+ snapshot = state.snapshot;
343
+ rowsApplied2 = state.rowsApplied;
344
+ total = state.total;
345
+ deltaCursor = state.deltaCursor;
346
+ } else if (state.status === "error" && state.snapshot) {
347
+ page = state.resumeFrom;
348
+ snapshot = state.snapshot;
349
+ rowsApplied2 = state.rowsApplied ?? 0;
350
+ total = state.total;
351
+ deltaCursor = state.deltaCursor;
352
+ }
353
+ let snapshotSupported = true;
354
+ let pages = 0;
355
+ try {
356
+ for (; ; ) {
357
+ const result = await this.source.bootstrap({ page, snapshot, limit: this.pageSize });
358
+ if (snapshot !== null && result.snapshot !== void 0 && result.snapshot !== snapshot) {
359
+ throw new Error(
360
+ `replication: origin '${this.source.origin}' changed snapshot token mid-walk`
361
+ );
362
+ }
363
+ if (snapshot === null && result.snapshot) snapshot = result.snapshot;
364
+ if (result.snapshot === void 0 && page === null) snapshotSupported = false;
365
+ if (result.deltaCursor && !deltaCursor) deltaCursor = result.deltaCursor;
366
+ if (result.total !== void 0) total = result.total;
367
+ rowsApplied2 += (await this.applyRows(result.rows)).length;
368
+ page = result.nextPage;
369
+ if (page !== null) {
370
+ const next = {
371
+ status: "hydrating",
372
+ snapshot: snapshot ?? "",
373
+ nextPage: page,
374
+ rowsApplied: rowsApplied2,
375
+ ...deltaCursor !== void 0 ? { deltaCursor } : {},
376
+ ...total !== void 0 ? { total } : {}
377
+ };
378
+ await this.coverage.write(this.key, next);
379
+ this.onProgress?.(next);
380
+ if (++pages >= MAX_BOOTSTRAP_PAGES) {
381
+ throw new Error(
382
+ `replication: origin '${this.source.origin}' offered more than ${MAX_BOOTSTRAP_PAGES} bootstrap pages for '${this.source.collection}' \u2014 it is probably not advancing nextPage.`
383
+ );
384
+ }
385
+ await this.yieldFn();
386
+ continue;
387
+ }
388
+ if (snapshotSupported && this.source.delta && deltaCursor === void 0) {
389
+ throw new Error(
390
+ `replication: origin '${this.source.origin}' supports delta refresh but did not issue deltaCursor on the first bootstrap page`
391
+ );
392
+ }
393
+ state = snapshotSupported ? {
394
+ status: "complete",
395
+ cursor: deltaCursor ?? "",
396
+ completedAt: Date.now(),
397
+ rowsApplied: rowsApplied2,
398
+ ...total !== void 0 ? { total } : {}
399
+ } : {
400
+ // Every row the origin offered was applied — but without a snapshot
401
+ // we cannot prove we saw a consistent view of it, so we must not
402
+ // claim completeness. Reads keep going to the network.
403
+ status: "best-effort",
404
+ cursor: deltaCursor ?? "",
405
+ reason: "the origin did not return a snapshot token, so a row that moved between pages during the walk may have been missed",
406
+ rowsApplied: rowsApplied2,
407
+ ...total !== void 0 ? { total } : {}
408
+ };
409
+ await this.coverage.write(this.key, state);
410
+ this.onProgress?.(state);
411
+ return state;
412
+ }
413
+ } catch (error) {
414
+ const failed = {
415
+ status: "error",
416
+ resumeFrom: page ?? 0,
417
+ ...snapshot ? { snapshot } : {},
418
+ ...deltaCursor !== void 0 ? { deltaCursor } : {},
419
+ rowsApplied: rowsApplied2,
420
+ ...total !== void 0 ? { total } : {},
421
+ error: error instanceof Error ? error.message : String(error)
422
+ };
423
+ await this.coverage.write(this.key, failed);
424
+ this.onProgress?.(failed);
425
+ throw error;
426
+ }
427
+ }
428
+ /**
429
+ * Apply incremental changes since the stored cursor.
430
+ *
431
+ * Deletions are applied by mapping the origin's primary keys through the same
432
+ * `deriveDocId`, and are written with `origin: 'remote'` so they leave no
433
+ * tombstone — the origin already knows it deleted these, and a tombstone would
434
+ * push its own deletion back at it.
435
+ */
436
+ refresh() {
437
+ return this.dedup(`${this.replicaScope}:refresh`, () => this.runRefresh());
438
+ }
439
+ async runRefresh() {
440
+ const state = await this.coverage.read(this.key);
441
+ if (state.status !== "complete") return state;
442
+ if (!this.source.delta) return state;
443
+ const col = this.db.collection(this.source.collection);
444
+ let cursor = state.cursor;
445
+ let rowsApplied2 = state.rowsApplied;
446
+ for (; ; ) {
447
+ const page = await this.source.delta(cursor);
448
+ rowsApplied2 += (await this.applyRows(page.changed)).length;
449
+ if (page.deleted.length > 0) {
450
+ const ids = page.deleted.map(
451
+ (k) => deriveDocId(this.identityNamespace, String(k))
452
+ );
453
+ await col.deleteManyWithIds(ids, "remote");
454
+ }
455
+ cursor = page.cursor;
456
+ const next = { ...state, cursor, rowsApplied: rowsApplied2 };
457
+ await this.coverage.write(this.key, next);
458
+ if (!page.hasMore) {
459
+ this.onProgress?.(next);
460
+ return next;
461
+ }
462
+ await this.yieldFn();
463
+ }
464
+ }
465
+ /**
466
+ * Cold-start bridge: fetch exactly the rows one query needs, right now.
467
+ *
468
+ * Needed because a SPA or React Native app has no server render to paint behind
469
+ * while the replica fills. The rows land in the same collection under the same
470
+ * derived ids as the walk's, so this is not a cache — it is the replica, arriving
471
+ * early.
472
+ *
473
+ * **Does not advance coverage.** These rows did not come from the bootstrap
474
+ * snapshot and prove nothing about completeness; treating them as progress would
475
+ * let a page-1 fetch masquerade as a hydrated catalog.
476
+ */
477
+ bridge(query) {
478
+ if (!this.source.fetchQuery) return Promise.resolve({ count: 0, ids: [] });
479
+ const key = `bridge:${coverageKey(this.key)}:${JSON.stringify(query)}`;
480
+ return this.dedup(key, async () => {
481
+ const rows = await this.source.fetchQuery(query);
482
+ const ids = await this.applyRows(rows);
483
+ return { count: ids.length, ids };
484
+ });
485
+ }
486
+ /** Drop coverage and force a fresh bootstrap. Local rows are left alone. */
487
+ async reset() {
488
+ await this.coverage.clear(this.key);
489
+ }
490
+ };
491
+
492
+ // src/replication/rest.ts
493
+ function parseRows(body, endpoint) {
494
+ if (Array.isArray(body)) return body;
495
+ if (body && typeof body === "object") {
496
+ const env = body;
497
+ for (const field of ["data", "items", "rows"]) {
498
+ const value = env[field];
499
+ if (Array.isArray(value)) return value;
500
+ }
501
+ throw new Error(
502
+ `taladb: could not find a row array in the response from ${endpoint}. Expected a bare array or a { data | items | rows } envelope, but got an object with keys: ${Object.keys(env).join(", ") || "(none)"}. Pass { parse } to extract them yourself.`
503
+ );
504
+ }
505
+ throw new Error(
506
+ `taladb: expected an array or object from ${endpoint}, got ${typeof body}.`
507
+ );
508
+ }
509
+ function pick(body, names) {
510
+ if (!body || typeof body !== "object") return void 0;
511
+ const rec = body;
512
+ for (const n of names) {
513
+ if (rec[n] !== void 0) return rec[n];
514
+ const meta = rec.meta;
515
+ if (meta && meta[n] !== void 0) return meta[n];
516
+ }
517
+ return void 0;
518
+ }
519
+ function createRestSource(options) {
520
+ const {
521
+ endpoint,
522
+ collection,
523
+ origin = endpoint,
524
+ scope = "global",
525
+ projectionVersion = 1,
526
+ schemaVersion = 1,
527
+ key = "id",
528
+ revision = "rev",
529
+ mapRow,
530
+ getAuth,
531
+ paths,
532
+ toParams,
533
+ parse,
534
+ pagination = "page"
535
+ } = options;
536
+ const doFetch = options.fetch ?? globalThis.fetch;
537
+ async function get(path, params) {
538
+ const url = new URL(path, globalThis.location?.origin ?? "http://localhost");
539
+ for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
540
+ const headers = getAuth ? await getAuth() : void 0;
541
+ const response = await doFetch(url.href, { headers });
542
+ if (!response.ok) {
543
+ throw new Error(
544
+ `taladb: ${path} responded ${response.status} ${response.statusText}`
545
+ );
546
+ }
547
+ return response.json();
548
+ }
549
+ const rowsFrom = (body) => parse ? parse(body) : parseRows(body, endpoint);
550
+ return {
551
+ origin,
552
+ collection,
553
+ scope,
554
+ projectionVersion,
555
+ schemaVersion,
556
+ keyOf: (row) => {
557
+ const value = row[key];
558
+ if (value === void 0 || value === null) {
559
+ throw new Error(
560
+ `taladb: row from ${endpoint} has no '${key}' field to use as its primary key. Pass { key } to name the right one. Without a stable key, repeated fetches of the same row cannot be recognized as the same row.`
561
+ );
562
+ }
563
+ return String(value);
564
+ },
565
+ revisionOf: (row) => {
566
+ const value = typeof revision === "function" ? revision(row) : row[revision];
567
+ if (value === void 0 || value === null) {
568
+ throw new Error(
569
+ `taladb: row from ${endpoint} has no authoritative revision. Pass { revision } to name the monotonic revision field.`
570
+ );
571
+ }
572
+ const n = Number(value);
573
+ if (!Number.isSafeInteger(n)) {
574
+ throw new Error(`taladb: authoritative revision must be a safe integer, got ${String(value)}`);
575
+ }
576
+ return n;
577
+ },
578
+ mapRow: (row) => {
579
+ if (mapRow) return mapRow(row);
580
+ const { _id, ...rest } = row;
581
+ void _id;
582
+ return rest;
583
+ },
584
+ bootstrap: async (request) => {
585
+ const params = { limit: String(request.limit) };
586
+ if (request.page !== null) params.page = String(request.page);
587
+ if (request.snapshot !== null) params.snapshot = request.snapshot;
588
+ const body = await get(endpoint + (paths?.bootstrap ?? ""), params);
589
+ const rows = rowsFrom(body);
590
+ const nextPage = pick(body, ["nextPage", "next_page", "next"]);
591
+ const snapshot = pick(body, ["snapshot"]);
592
+ const deltaCursor = pick(body, ["deltaCursor", "delta_cursor", "cursor"]);
593
+ const total = pick(body, ["total", "totalCount", "count"]);
594
+ return {
595
+ rows,
596
+ // An origin that reports no explicit `nextPage` is treated as exhausted
597
+ // once it returns a short page — the conventional REST behavior.
598
+ nextPage: nextPage !== void 0 ? nextPage : rows.length < request.limit ? null : pagination === "offset" ? Number(request.page ?? 0) + request.limit : Number(request.page ?? 1) + 1,
599
+ ...snapshot !== void 0 ? { snapshot } : {},
600
+ ...deltaCursor !== void 0 ? { deltaCursor } : {},
601
+ ...total !== void 0 ? { total } : {}
602
+ };
603
+ },
604
+ ...options.delta === true || paths?.delta ? { delta: async (cursor) => {
605
+ const body = await get(endpoint + (paths?.delta ?? ""), { since: cursor });
606
+ const changed = rowsFrom(body);
607
+ const deleted = pick(body, ["deleted", "removed"]) ?? [];
608
+ const next = pick(body, ["cursor", "now", "nextCursor"]);
609
+ return {
610
+ changed,
611
+ deleted: deleted.map(String),
612
+ cursor: next ?? cursor,
613
+ hasMore: Boolean(pick(body, ["hasMore", "has_more"]))
614
+ };
615
+ } } : {},
616
+ fetchQuery: async (query) => {
617
+ if (!toParams && Object.values(query.filter ?? {}).some((v) => typeof v === "object" && v !== null)) {
618
+ throw new Error(
619
+ "taladb: bridge filters with operators require RestSourceOptions.toParams; the default translator only supports scalar equality fields."
620
+ );
621
+ }
622
+ const sortEntry = Object.entries(query.sort ?? {})[0];
623
+ const params = toParams ? toParams(query) : {
624
+ ...query.page !== void 0 ? { page: String(query.page) } : {},
625
+ ...query.limit !== void 0 ? { limit: String(query.limit) } : {},
626
+ ...Object.fromEntries(
627
+ Object.entries(query.filter ?? {}).map(([k, v]) => [k, String(v)])
628
+ ),
629
+ ...sortEntry ? { sort: sortEntry[0], order: sortEntry[1] === -1 ? "desc" : "asc" } : {}
630
+ };
631
+ return rowsFrom(await get(endpoint, params));
632
+ }
633
+ };
634
+ }
635
+
135
636
  // src/index.ts
136
637
  var TalaDbValidationError = class extends Error {
137
638
  constructor(cause, context) {
@@ -181,6 +682,10 @@ function applySchema(col, options) {
181
682
  if (!stampVersion || doc._v !== void 0) return doc;
182
683
  return { ...doc, _v: targetVersion };
183
684
  }
685
+ function stampDoc(doc) {
686
+ if (!stampVersion || doc._v !== void 0) return doc;
687
+ return { ...doc, _v: targetVersion };
688
+ }
184
689
  function diffUpdate(original, migrated) {
185
690
  const $set = {};
186
691
  const $unset = {};
@@ -235,6 +740,19 @@ function applySchema(col, options) {
235
740
  if (schema) docs.forEach((doc, i) => parseWrite(doc, `insertMany[${i}]`));
236
741
  return col.insertMany(docs.map(stamp));
237
742
  } : col.insertMany.bind(col),
743
+ // Rows arriving from a remote origin are validated like any other write. This
744
+ // is the "parse, don't assert" boundary: the compile-time generic and the
745
+ // runtime schema check have to be the same seam, or a malformed server
746
+ // response walks straight into a typed collection.
747
+ replaceManyWithIds: wrapWrites ? async (docs, origin) => {
748
+ if (schema) docs.forEach((doc, i) => {
749
+ const { _replica_scope, _remote_rev, ...schemaDoc } = doc;
750
+ void _replica_scope;
751
+ void _remote_rev;
752
+ parseWrite(schemaDoc, `replaceManyWithIds[${i}]`);
753
+ });
754
+ return col.replaceManyWithIds(docs.map((d) => stampDoc(d)), origin);
755
+ } : col.replaceManyWithIds.bind(col),
238
756
  find: wrapReads ? async (filter) => {
239
757
  const docs = await col.find(filter);
240
758
  const migrated = docs.map(migrateRead);
@@ -392,6 +910,19 @@ async function createBrowserDB(dbName, config, passphrase, migrations) {
392
910
  });
393
911
  return JSON.parse(json);
394
912
  },
913
+ replaceManyWithIds: async (docs, origin = "local") => {
914
+ const json = await proxy.send("replaceManyWithIds", {
915
+ collection: name,
916
+ docsJson: s(docs),
917
+ origin
918
+ });
919
+ return JSON.parse(json);
920
+ },
921
+ deleteManyWithIds: (ids, origin = "local") => proxy.send("deleteManyWithIds", {
922
+ collection: name,
923
+ idsJson: s(ids),
924
+ origin
925
+ }),
395
926
  find: async (filter) => {
396
927
  const json = await proxy.send("find", {
397
928
  collection: name,
@@ -463,59 +994,72 @@ async function createBrowserDB(dbName, config, passphrase, migrations) {
463
994
  });
464
995
  return JSON.parse(json);
465
996
  },
466
- subscribe: (filter, callback, onError) => {
467
- let active = true;
468
- let lastJson = "";
469
- let timer = null;
470
- let running = false;
471
- let rerun = false;
472
- const poll = async () => {
473
- if (!active) return;
474
- if (running) {
475
- rerun = true;
476
- return;
477
- }
478
- running = true;
479
- if (timer !== null) {
480
- clearTimeout(timer);
481
- timer = null;
482
- }
483
- try {
484
- const json = await proxy.send("find", {
485
- collection: name,
486
- filterJson: filter ? s(filter) : "null"
487
- });
488
- if (!active) return;
489
- if (json !== lastJson) {
490
- lastJson = json;
491
- callback(JSON.parse(json));
492
- }
493
- } catch (error) {
494
- if (active) onError?.(error);
495
- } finally {
496
- running = false;
497
- }
498
- if (active) {
499
- if (rerun) {
500
- rerun = false;
501
- void poll();
502
- } else timer = setTimeout(poll, 300);
503
- }
504
- };
505
- nudgeCallbacks.add(poll);
506
- poll();
507
- return () => {
508
- active = false;
509
- nudgeCallbacks.delete(poll);
510
- if (timer !== null) {
511
- clearTimeout(timer);
512
- timer = null;
513
- }
514
- };
515
- }
997
+ subscribe: (filter, callback, onError) => nudgedPoller(
998
+ () => proxy.send("find", {
999
+ collection: name,
1000
+ filterJson: filter ? s(filter) : "null"
1001
+ }),
1002
+ callback,
1003
+ onError
1004
+ ),
1005
+ subscribeAggregate: (pipeline, callback, onError) => nudgedPoller(
1006
+ () => proxy.send("aggregate", {
1007
+ collection: name,
1008
+ pipelineJson: s(pipeline)
1009
+ }),
1010
+ callback,
1011
+ onError
1012
+ )
516
1013
  };
517
1014
  return opts ? applySchema(wrapped, opts) : wrapped;
518
1015
  }
1016
+ function nudgedPoller(fetchJson, callback, onError) {
1017
+ let active = true;
1018
+ let lastJson = "";
1019
+ let timer = null;
1020
+ let running = false;
1021
+ let rerun = false;
1022
+ const poll = async () => {
1023
+ if (!active) return;
1024
+ if (running) {
1025
+ rerun = true;
1026
+ return;
1027
+ }
1028
+ running = true;
1029
+ if (timer !== null) {
1030
+ clearTimeout(timer);
1031
+ timer = null;
1032
+ }
1033
+ try {
1034
+ const json = await fetchJson();
1035
+ if (!active) return;
1036
+ if (json !== lastJson) {
1037
+ lastJson = json;
1038
+ callback(JSON.parse(json));
1039
+ }
1040
+ } catch (error) {
1041
+ if (active) onError?.(error);
1042
+ } finally {
1043
+ running = false;
1044
+ }
1045
+ if (active) {
1046
+ if (rerun) {
1047
+ rerun = false;
1048
+ void poll();
1049
+ } else timer = setTimeout(poll, 300);
1050
+ }
1051
+ };
1052
+ nudgeCallbacks.add(poll);
1053
+ poll();
1054
+ return () => {
1055
+ active = false;
1056
+ nudgeCallbacks.delete(poll);
1057
+ if (timer !== null) {
1058
+ clearTimeout(timer);
1059
+ timer = null;
1060
+ }
1061
+ };
1062
+ }
519
1063
  const handle = {
520
1064
  collection: (name, opts) => wrapCollection(name, opts),
521
1065
  compact: () => proxy.send("compact"),
@@ -567,6 +1111,8 @@ async function createNodeDB(dbName, config, passphrase, migrations) {
567
1111
  const wrapped = {
568
1112
  insert: async (doc) => col.insertAsync ? col.insertAsync(doc) : col.insert(doc),
569
1113
  insertMany: async (docs) => col.insertManyAsync ? col.insertManyAsync(docs) : col.insertMany(docs),
1114
+ replaceManyWithIds: async (docs, origin = "local") => col.replaceManyWithIdsAsync ? col.replaceManyWithIdsAsync(docs, origin) : col.replaceManyWithIds(docs, origin),
1115
+ deleteManyWithIds: async (ids, origin = "local") => col.deleteManyWithIdsAsync ? col.deleteManyWithIdsAsync(ids, origin) : col.deleteManyWithIds(ids, origin),
570
1116
  find: async (filter) => col.findAsync ? col.findAsync(filter ?? null) : col.find(filter ?? null),
571
1117
  findOne: async (filter) => col.findOne(filter) ?? null,
572
1118
  updateOne: async (filter, update) => col.updateOneAsync ? col.updateOneAsync(filter, update) : col.updateOne(filter, update),
@@ -592,7 +1138,8 @@ async function createNodeDB(dbName, config, passphrase, migrations) {
592
1138
  const raw = await col.findNearest(field, vector, topK, filter ?? null);
593
1139
  return raw;
594
1140
  },
595
- subscribe: (filter, callback, onError) => makePoller(async () => col.find(filter ?? null), callback, onError)
1141
+ subscribe: (filter, callback, onError) => makePoller(async () => col.find(filter ?? null), callback, onError),
1142
+ subscribeAggregate: (pipeline, callback, onError) => makePoller(async () => wrapped.aggregate(pipeline), callback, onError)
596
1143
  };
597
1144
  return opts ? applySchema(wrapped, opts) : wrapped;
598
1145
  }
@@ -640,6 +1187,8 @@ async function createNativeDB(_dbName, migrations) {
640
1187
  const wrapped = {
641
1188
  insert: async (doc) => native.insert(name, doc),
642
1189
  insertMany: async (docs) => native.insertMany(name, docs),
1190
+ replaceManyWithIds: async (docs, origin = "local") => native.replaceManyWithIds(name, docs, origin),
1191
+ deleteManyWithIds: async (ids, origin = "local") => native.deleteManyWithIds(name, ids, origin),
643
1192
  find: async (filter) => native.find(name, filter ?? {}),
644
1193
  findOne: async (filter) => native.findOne(name, filter ?? {}),
645
1194
  updateOne: async (filter, update) => native.updateOne(name, filter, update),
@@ -671,7 +1220,8 @@ async function createNativeDB(_dbName, migrations) {
671
1220
  const raw = native.findNearest(name, field, vector, topK, filter ?? null);
672
1221
  return raw;
673
1222
  },
674
- subscribe: (filter, callback, onError) => makePoller(async () => native.find(name, filter ?? {}), callback, onError)
1223
+ subscribe: (filter, callback, onError) => makePoller(async () => native.find(name, filter ?? {}), callback, onError),
1224
+ subscribeAggregate: (pipeline, callback, onError) => makePoller(async () => native.aggregate(name, pipeline), callback, onError)
675
1225
  };
676
1226
  return opts ? applySchema(wrapped, opts) : wrapped;
677
1227
  }
@@ -767,9 +1317,20 @@ async function openDB(dbName = "taladb.db", options) {
767
1317
  }
768
1318
  }
769
1319
  export {
1320
+ COVERAGE_COLLECTION,
1321
+ CoverageStore,
770
1322
  HttpSyncAdapter,
1323
+ REPLICA_REVISION_FIELD,
1324
+ REPLICA_SCOPE_FIELD,
1325
+ ReplicationCoordinator,
771
1326
  TalaDbValidationError,
772
1327
  applySchema,
1328
+ coverageKey,
1329
+ createRestSource,
1330
+ deriveDocId,
1331
+ isAuthoritative,
773
1332
  openDB,
1333
+ progress,
1334
+ rowsApplied,
774
1335
  runMigrations
775
1336
  };