@signaldb/core 2.0.0-beta.17 → 2.0.0-beta.19

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.
@@ -0,0 +1,513 @@
1
+ import isEqual from "./index2.mjs";
2
+ import getIndexInfo from "./index17.mjs";
3
+ import deepClone from "./index18.mjs";
4
+ import match from "./index19.mjs";
5
+ import modify from "./index20.mjs";
6
+ import project from "./index22.mjs";
7
+ import sortItems from "./index24.mjs";
8
+ import queryId from "./index26.mjs";
9
+ import idIndexQuery from "./index27.mjs";
10
+ import storageIndexQuery from "./index33.mjs";
11
+ //#region src/AutoFetchDataAdapter.ts
12
+ /**
13
+ * Default merge strategy: shallow spread (right wins)
14
+ * @param a first item
15
+ * @param b second item
16
+ * @returns merged item
17
+ */
18
+ function defaultMergeItems(a, b) {
19
+ return {
20
+ ...a,
21
+ ...b
22
+ };
23
+ }
24
+ /**
25
+ * Generates a stable key for a selector
26
+ * @param selector - the selector
27
+ * @returns the key
28
+ */
29
+ function selectorId(selector) {
30
+ return JSON.stringify(selector ?? {});
31
+ }
32
+ /**
33
+ * AutoFetchDataAdapter
34
+ *
35
+ * A DataAdapter that:
36
+ * - Mirrors the CollectionBackend surface (CRUD + query registry + lifecycle)
37
+ * - Executes queries against a provided StorageAdapter (local cache)
38
+ * - On first registration of a selector, auto-fetches from a remote source and
39
+ * ingests the result into storage (upsert), then pushes query result updates
40
+ * - Optionally purges auto-fetched items for a selector once no observers remain
41
+ * - Can subscribe to remote change notifications to re-fetch active selectors
42
+ *
43
+ * IMPORTANT: Purging only ever deletes items that were introduced via the
44
+ * auto-fetch path and are no longer referenced by any active selector. Items
45
+ * inserted through CRUD calls are never purged.
46
+ */
47
+ var AutoFetchDataAdapter = class {
48
+ options;
49
+ id;
50
+ onError;
51
+ fetchQueryItems;
52
+ mergeItems;
53
+ purgeDelay;
54
+ storageAdapters = /* @__PURE__ */ new Map();
55
+ storageAdapterReady = /* @__PURE__ */ new Map();
56
+ collectionIndices = /* @__PURE__ */ new Map();
57
+ queries = /* @__PURE__ */ new Map();
58
+ activeObservers = /* @__PURE__ */ new Map();
59
+ observerTimeouts = /* @__PURE__ */ new Map();
60
+ selectorIds = /* @__PURE__ */ new Map();
61
+ idRefCounts = /* @__PURE__ */ new Map();
62
+ autoloadIds = /* @__PURE__ */ new Map();
63
+ constructor(options) {
64
+ this.options = options;
65
+ this.id = options.id || "autofetch-data-adapter";
66
+ this.onError = options.onError ?? ((error) => {
67
+ console.error(error);
68
+ });
69
+ this.fetchQueryItems = options.fetchQueryItems;
70
+ this.mergeItems = options.mergeItems ?? defaultMergeItems;
71
+ this.purgeDelay = options.purgeDelay ?? 1e4;
72
+ if (options.registerRemoteChange) options.registerRemoteChange(async () => {
73
+ await this.forceRefetchAll();
74
+ });
75
+ }
76
+ createCollectionBackend(collection, indices) {
77
+ this.collectionIndices.set(collection.name, indices);
78
+ this.queries.set(collection.name, /* @__PURE__ */ new Map());
79
+ this.ensureStorageAdapter(collection.name);
80
+ this.activeObservers.set(collection.name, /* @__PURE__ */ new Map());
81
+ this.observerTimeouts.set(collection.name, /* @__PURE__ */ new Map());
82
+ this.selectorIds.set(collection.name, /* @__PURE__ */ new Map());
83
+ this.idRefCounts.set(collection.name, /* @__PURE__ */ new Map());
84
+ this.autoloadIds.set(collection.name, /* @__PURE__ */ new Set());
85
+ const ready = this.setupStorage(collection.name, indices);
86
+ this.storageAdapterReady.set(collection.name, ready);
87
+ const registerQuery = (selector, options) => {
88
+ const qid = queryId(selector, options);
89
+ const registry = this.queries.get(collection.name);
90
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
91
+ registry.set(qid, {
92
+ selector,
93
+ options,
94
+ items: [],
95
+ listeners: /* @__PURE__ */ new Set(),
96
+ ...registry.get(qid),
97
+ state: "active",
98
+ error: null
99
+ });
100
+ const key = selectorId(selector);
101
+ const perColObservers = this.activeObservers.get(collection.name);
102
+ const current = perColObservers?.get(key)?.count ?? 0;
103
+ perColObservers?.set(key, {
104
+ selector,
105
+ count: current + 1
106
+ });
107
+ const t = this.observerTimeouts.get(collection.name)?.get(key);
108
+ if (t) clearTimeout(t);
109
+ if (current === 0) this.fetchAndIngest(collection.name, selector).catch(this.onError);
110
+ this.fulfillQuery(collection.name, selector, options).catch(this.onError);
111
+ };
112
+ const unregisterQuery = (selector, options) => {
113
+ const qid = queryId(selector, options);
114
+ this.queries.get(collection.name)?.delete(qid);
115
+ const key = selectorId(selector);
116
+ const perColObservers = this.activeObservers.get(collection.name);
117
+ const current = perColObservers?.get(key)?.count ?? 0;
118
+ const remaining = Math.max(0, current - 1);
119
+ if (remaining > 0) {
120
+ perColObservers?.set(key, {
121
+ selector,
122
+ count: remaining
123
+ });
124
+ return;
125
+ }
126
+ const doPurge = () => {
127
+ perColObservers?.delete(key);
128
+ this.purgeSelector(collection.name, selector).catch(this.onError);
129
+ };
130
+ if (this.purgeDelay === 0) doPurge();
131
+ else {
132
+ const timeouts = this.observerTimeouts.get(collection.name);
133
+ const t = timeouts?.get(key);
134
+ if (t) clearTimeout(t);
135
+ timeouts?.set(key, setTimeout(doPurge, this.purgeDelay));
136
+ }
137
+ };
138
+ const getQueryState = (selector, options) => {
139
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.state ?? "active";
140
+ };
141
+ const getQueryError = (selector, options) => {
142
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.error ?? null;
143
+ };
144
+ const getQueryResult = (selector, options) => {
145
+ return (this.queries.get(collection.name)?.get(queryId(selector, options)))?.items ?? [];
146
+ };
147
+ const onQueryStateChange = (selector, options, callback) => {
148
+ const qid = queryId(selector, options);
149
+ const registry = this.queries.get(collection.name);
150
+ if (!registry) throw new Error(`Collection ${collection.name} not initialized!`);
151
+ if (!registry.has(qid)) registry.set(qid, {
152
+ selector,
153
+ options,
154
+ state: "active",
155
+ error: null,
156
+ items: [],
157
+ listeners: /* @__PURE__ */ new Set()
158
+ });
159
+ registry.get(qid)?.listeners.add(callback);
160
+ return () => {
161
+ registry.get(qid)?.listeners.delete(callback);
162
+ };
163
+ };
164
+ return {
165
+ insert: async (item) => {
166
+ await ready;
167
+ return await this.insert(collection.name, item);
168
+ },
169
+ updateOne: async (selector, modifier) => {
170
+ await ready;
171
+ return this.updateOne(collection.name, selector, modifier);
172
+ },
173
+ updateMany: async (selector, modifier) => {
174
+ await ready;
175
+ return this.updateMany(collection.name, selector, modifier);
176
+ },
177
+ replaceOne: async (selector, replacement) => {
178
+ await ready;
179
+ return this.replaceOne(collection.name, selector, replacement);
180
+ },
181
+ removeOne: async (selector) => {
182
+ await ready;
183
+ return this.removeOne(collection.name, selector);
184
+ },
185
+ removeMany: async (selector) => {
186
+ await ready;
187
+ return this.removeMany(collection.name, selector);
188
+ },
189
+ registerQuery,
190
+ unregisterQuery,
191
+ getQueryState,
192
+ getQueryError,
193
+ getQueryResult,
194
+ onQueryStateChange,
195
+ executeQuery: async (selector, options) => {
196
+ await ready;
197
+ registerQuery(selector, options);
198
+ await new Promise((resolve) => {
199
+ let stop = () => {};
200
+ stop = onQueryStateChange(selector, options, (state) => {
201
+ if (state === "active") return;
202
+ resolve();
203
+ stop();
204
+ });
205
+ });
206
+ const result = getQueryResult(selector, options);
207
+ unregisterQuery(selector, options);
208
+ return result;
209
+ },
210
+ dispose: async () => {
211
+ this.storageAdapters.delete(collection.name);
212
+ this.queries.delete(collection.name);
213
+ this.collectionIndices.delete(collection.name);
214
+ this.storageAdapterReady.delete(collection.name);
215
+ this.activeObservers.delete(collection.name);
216
+ this.observerTimeouts.delete(collection.name);
217
+ this.selectorIds.delete(collection.name);
218
+ this.idRefCounts.delete(collection.name);
219
+ this.autoloadIds.delete(collection.name);
220
+ },
221
+ isReady: async () => {
222
+ await ready;
223
+ }
224
+ };
225
+ }
226
+ async forceRefetchAll() {
227
+ const tasks = [];
228
+ for (const [collectionName, observers] of this.activeObservers.entries()) for (const { selector, count } of observers.values()) if (count > 0) tasks.push(this.fetchAndIngest(collectionName, selector));
229
+ await Promise.all(tasks);
230
+ }
231
+ async fetchAndIngest(collectionName, selector) {
232
+ this.publishForSelector(collectionName, selector, "active", null);
233
+ try {
234
+ const items = await this.fetchQueryItems(collectionName, selector);
235
+ if (!items || !Array.isArray(items)) throw new Error("AutoFetchDataAdapter: fetchQueryItems must resolve to { items: T[] }");
236
+ const ids = items.map((i) => i.id);
237
+ const selectorKey = selectorId(selector);
238
+ const selMap = this.selectorIds.get(collectionName);
239
+ const previous = selMap?.get(selectorKey) ?? /* @__PURE__ */ new Set();
240
+ ids.forEach((id) => previous.add(id));
241
+ selMap?.set(selectorKey, previous);
242
+ await this.upsertMerged(collectionName, items);
243
+ await this.checkQueryUpdates(collectionName, items);
244
+ } catch (error) {
245
+ this.publishForSelector(collectionName, selector, "error", error);
246
+ this.onError(error);
247
+ }
248
+ }
249
+ async purgeSelector(collectionName, selector) {
250
+ const selectorKey = selectorId(selector);
251
+ const selMap = this.selectorIds.get(collectionName);
252
+ const ids = selMap?.get(selectorKey);
253
+ selMap?.delete(selectorKey);
254
+ if (!ids || ids.size === 0) return;
255
+ const referenceMap = this.idRefCounts.get(collectionName);
256
+ const autoload = this.autoloadIds.get(collectionName);
257
+ const toRemove = [];
258
+ for (const id of ids) {
259
+ const current = referenceMap?.get(id) ?? 0;
260
+ const next = Math.max(0, current - 1);
261
+ if (next === 0) {
262
+ referenceMap?.delete(id);
263
+ if (autoload?.has(id)) toRemove.push(id);
264
+ } else referenceMap?.set(id, next);
265
+ }
266
+ if (toRemove.length === 0) return;
267
+ const storage = this.storageAdapters.get(collectionName);
268
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
269
+ const items = await storage.readIds(toRemove);
270
+ if (items.length > 0) {
271
+ await storage.remove(items);
272
+ await this.checkQueryUpdates(collectionName, items);
273
+ }
274
+ toRemove.forEach((id) => autoload?.delete(id));
275
+ }
276
+ async setupStorage(collectionName, indices) {
277
+ const storage = this.storageAdapters.get(collectionName);
278
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
279
+ await storage.setup();
280
+ await Promise.all(indices.map((field) => storage.createIndex(field)));
281
+ }
282
+ ensureStorageAdapter(name) {
283
+ if (this.storageAdapters.has(name)) return;
284
+ const adapter = this.options.storage && this.options.storage(name);
285
+ if (!adapter) return;
286
+ this.storageAdapters.set(name, adapter);
287
+ }
288
+ publishForSelector(collectionName, selector, state, error) {
289
+ const registry = this.queries.get(collectionName);
290
+ if (!registry) return;
291
+ for (const query of registry.values()) {
292
+ if (!isEqual(query.selector, selector)) continue;
293
+ this.publishState(collectionName, queryId(query.selector, query.options), state, error);
294
+ }
295
+ }
296
+ publishState(collectionName, qid, state, error) {
297
+ const query = this.queries.get(collectionName)?.get(qid);
298
+ if (!query) return;
299
+ query.state = state;
300
+ query.error = error;
301
+ for (const callback of query.listeners) try {
302
+ callback(state);
303
+ } catch (error_) {
304
+ this.onError(error_);
305
+ }
306
+ }
307
+ publishResult(collectionName, qid, items) {
308
+ const query = this.queries.get(collectionName)?.get(qid);
309
+ if (!query) return;
310
+ query.items = items;
311
+ this.queries.get(collectionName)?.set(qid, query);
312
+ }
313
+ async fulfillQuery(collectionName, selector, options) {
314
+ const qid = queryId(selector, options);
315
+ const registry = this.queries.get(collectionName);
316
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
317
+ if (!registry.get(qid)) return;
318
+ this.publishState(collectionName, qid, "active", null);
319
+ try {
320
+ const items = await this.executeQuery(collectionName, selector, options);
321
+ this.publishResult(collectionName, qid, items);
322
+ this.publishState(collectionName, qid, "complete", null);
323
+ } catch (error) {
324
+ this.publishState(collectionName, qid, "error", error);
325
+ }
326
+ }
327
+ async getIndexInfo(collectionName, selector) {
328
+ const storage = this.storageAdapters.get(collectionName);
329
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
330
+ if (selector != null && Object.keys(selector).length === 1 && "id" in selector) {
331
+ const idResult = idIndexQuery(selector);
332
+ if (idResult.matched) return {
333
+ matched: true,
334
+ ids: idResult.ids,
335
+ optimizedSelector: {}
336
+ };
337
+ }
338
+ if (selector == null) return {
339
+ matched: false,
340
+ ids: [],
341
+ optimizedSelector: {}
342
+ };
343
+ return getIndexInfo((this.collectionIndices.get(collectionName) ?? []).map((field) => storageIndexQuery(storage, field)), selector);
344
+ }
345
+ async queryItems(collectionName, selector) {
346
+ const storage = this.storageAdapters.get(collectionName);
347
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
348
+ const index = await this.getIndexInfo(collectionName, selector);
349
+ const matchItems = (item) => {
350
+ if (index.optimizedSelector == null) return true;
351
+ if (Object.keys(index.optimizedSelector).length <= 0) return true;
352
+ return match(item, index.optimizedSelector);
353
+ };
354
+ if (index.matched) {
355
+ const items = await storage.readIds(index.ids);
356
+ if (isEqual(index.optimizedSelector, {})) return items;
357
+ return items.filter(matchItems);
358
+ } else {
359
+ const allItems = await storage.readAll();
360
+ if (isEqual(selector, {})) return allItems;
361
+ return allItems.filter(matchItems);
362
+ }
363
+ }
364
+ async executeQuery(collectionName, selector, options) {
365
+ const items = await this.queryItems(collectionName, selector || {});
366
+ const { sort, skip, limit, fields } = options || {};
367
+ const sorted = sort ? sortItems(items, sort) : items;
368
+ const skipped = skip ? sorted.slice(skip) : sorted;
369
+ const limited = limit ? skipped.slice(0, limit) : skipped;
370
+ const idExcluded = fields && fields.id === 0;
371
+ return limited.map((item) => {
372
+ if (!fields) return item;
373
+ return {
374
+ ...idExcluded ? {} : { id: item.id },
375
+ ...project(item, fields)
376
+ };
377
+ });
378
+ }
379
+ async checkQueryUpdates(collectionName, changedItems) {
380
+ const registry = this.queries.get(collectionName);
381
+ if (!registry) throw new Error(`Collection ${collectionName} not initialized!`);
382
+ if (registry.size === 0) return;
383
+ const affected = [...registry.values()].filter(({ selector }) => changedItems.some((item) => match(item, selector)));
384
+ if (affected.length === 0) return;
385
+ for (const { selector, options } of affected) {
386
+ const qid = queryId(selector, options);
387
+ this.publishState(collectionName, qid, "active", null);
388
+ }
389
+ await Promise.all(affected.map(async ({ selector, options }) => {
390
+ const qid = queryId(selector, options);
391
+ try {
392
+ const items = await this.executeQuery(collectionName, selector, options);
393
+ this.publishResult(collectionName, qid, items);
394
+ this.publishState(collectionName, qid, "complete", null);
395
+ } catch (error) {
396
+ this.publishState(collectionName, qid, "error", error);
397
+ }
398
+ }));
399
+ }
400
+ async insert(collectionName, newItem) {
401
+ const storage = this.storageAdapters.get(collectionName);
402
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
403
+ if ((await this.executeQuery(collectionName, { id: newItem.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(newItem.id)} already exists`);
404
+ await storage.insert([newItem]);
405
+ await this.checkQueryUpdates(collectionName, [newItem]);
406
+ return newItem;
407
+ }
408
+ async updateOne(collectionName, selector, modifier) {
409
+ const storage = this.storageAdapters.get(collectionName);
410
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
411
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
412
+ const { $setOnInsert, ...rest } = modifier;
413
+ if (item == null) return [];
414
+ const modified = modify(deepClone(item), rest);
415
+ if (item.id !== modified.id) {
416
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
417
+ }
418
+ await storage.replace([modified]);
419
+ await this.checkQueryUpdates(collectionName, [item, modified]);
420
+ return [modified];
421
+ }
422
+ async updateMany(collectionName, selector, modifier) {
423
+ const storage = this.storageAdapters.get(collectionName);
424
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
425
+ const items = await this.executeQuery(collectionName, selector);
426
+ if (items.length === 0) return [];
427
+ const { $setOnInsert, ...rest } = modifier;
428
+ const changed = await Promise.all(items.map(async (item) => {
429
+ const modified = modify(deepClone(item), rest);
430
+ if (item.id !== modified.id) {
431
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
432
+ }
433
+ return modified;
434
+ }));
435
+ await storage.replace(changed);
436
+ await this.checkQueryUpdates(collectionName, [...items, ...changed]);
437
+ return changed;
438
+ }
439
+ async replaceOne(collectionName, selector, replacement) {
440
+ const storage = this.storageAdapters.get(collectionName);
441
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
442
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
443
+ if (item == null) return [];
444
+ const modified = {
445
+ ...replacement,
446
+ id: replacement.id ?? item.id
447
+ };
448
+ if (item.id !== modified.id) {
449
+ if ((await this.executeQuery(collectionName, { id: modified.id }, { limit: 1 })).length > 0) throw new Error(`Item with id ${String(modified.id)} already exists`);
450
+ }
451
+ await storage.replace([modified]);
452
+ await this.checkQueryUpdates(collectionName, [item, modified]);
453
+ return [modified];
454
+ }
455
+ async removeOne(collectionName, selector) {
456
+ const storage = this.storageAdapters.get(collectionName);
457
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
458
+ const [item] = await this.executeQuery(collectionName, selector, { limit: 1 });
459
+ if (item == null) return [];
460
+ await storage.remove([item]);
461
+ await this.checkQueryUpdates(collectionName, [item]);
462
+ return [item];
463
+ }
464
+ async removeMany(collectionName, selector) {
465
+ const storage = this.storageAdapters.get(collectionName);
466
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
467
+ const items = await this.executeQuery(collectionName, selector);
468
+ if (items.length === 0) return [];
469
+ await storage.remove(items);
470
+ await this.checkQueryUpdates(collectionName, items);
471
+ return items;
472
+ }
473
+ async upsertMerged(collectionName, incoming) {
474
+ if (incoming.length === 0) return;
475
+ const storage = this.storageAdapters.get(collectionName);
476
+ if (!storage) throw new Error(`No persistence adapter for collection ${collectionName}`);
477
+ const ids = incoming.map((i) => i.id);
478
+ const existing = await storage.readIds(ids);
479
+ const existingById = new Map(existing.map((it) => [it.id, it]));
480
+ const toInsert = [];
481
+ const toReplace = [];
482
+ const referenceMap = this.idRefCounts.get(collectionName);
483
+ const autoload = this.autoloadIds.get(collectionName);
484
+ for (const item of incoming) {
485
+ const previous = existingById.get(item.id);
486
+ if (previous) toReplace.push(this.mergeItems(previous, item));
487
+ else toInsert.push(item);
488
+ autoload?.add(item.id);
489
+ referenceMap?.set(item.id, (referenceMap?.get(item.id) ?? 0) + 1);
490
+ }
491
+ if (toInsert.length > 0) await storage.insert(toInsert);
492
+ if (toReplace.length > 0) await storage.replace(toReplace);
493
+ }
494
+ };
495
+ /**
496
+ * Usage (example):
497
+ *
498
+ * const adapter = new AutoFetchDataAdapter({
499
+ * storage: (name) => new IndexedDBStorage(name),
500
+ * fetchQueryItems: async (collectionName, selector) => {
501
+ * const res = await fetch(`/api/${collectionName}?q=${encodeURIComponent(JSON.stringify(selector||{}))}`)
502
+ * const items = await res.json()
503
+ * return { items }
504
+ * },
505
+ * registerRemoteChange: (onChange) => subscribeToWS(onChange),
506
+ * mergeItems: (a, b) => ({ ...a, ...b }),
507
+ * purgeDelay: 10_000,
508
+ * })
509
+ *
510
+ * const backend = adapter.createCollectionBackend(myCollection, ['status', 'projectId'])
511
+ */
512
+ //#endregion
513
+ export { AutoFetchDataAdapter as default };
@@ -12,7 +12,15 @@ export default interface StorageAdapter<T extends {
12
12
  readIds(positions: I[]): Promise<T[]>;
13
13
  createIndex(field: string): Promise<void>;
14
14
  dropIndex(field: string): Promise<void>;
15
- readIndex(field: string): Promise<Map<any, Set<I>>>;
15
+ /**
16
+ * The index, keyed by `serializeValue(value)` — not by the raw field value.
17
+ *
18
+ * SignalDB looks an index up with the serialized form, because that is what
19
+ * makes `3`, `'3'` and `new Date(...)` comparable as map keys at all. An
20
+ * adapter that stores its backend's own keys instead answers nothing for
21
+ * every non-string field, and everything for a `$ne` on one.
22
+ */
23
+ readIndex(field: string): Promise<Map<string | null, Set<I>>>;
16
24
  insert(items: T[]): Promise<void>;
17
25
  replace(items: T[]): Promise<void>;
18
26
  remove(items: T[]): Promise<void>;
@@ -0,0 +1,20 @@
1
+ import { BaseItem } from '../Collection/types';
2
+ import { IndexResult } from '../types/IndexProvider';
3
+ import { FlatSelector } from '../types/Selector';
4
+ /**
5
+ * Resolves a selector on `id` into the ids it names, without consulting an index.
6
+ *
7
+ * `id` is the one field every storage adapter can look up directly — that is what
8
+ * `readIds` is — so a query on it never needs an index to be declared and never
9
+ * needs the whole collection to be read. This behaves like an index provider that
10
+ * happens to need no stored index, because the ids are already in the selector.
11
+ *
12
+ * Only inclusive forms can be answered this way. `$ne`/`$nin` describe everything
13
+ * except* something, which cannot be enumerated without knowing every id, so they
14
+ * report no match and take the ordinary path.
15
+ * @template T - The type of the items in the collection.
16
+ * @template I - The type of the unique identifier for the items.
17
+ * @param selector - The flat selector to resolve.
18
+ * @returns An index result naming the matched ids, or `{ matched: false }`.
19
+ */
20
+ export default function idIndexQuery<T extends BaseItem<I> = BaseItem, I = any>(selector: FlatSelector<T>): IndexResult<I>;
@@ -0,0 +1,20 @@
1
+ import { BaseItem } from '../Collection/types';
2
+ import { default as StorageAdapter } from '../types/StorageAdapter';
3
+ import { AsynchronousQueryFunction } from '../types/IndexProvider';
4
+ /**
5
+ * Builds the index provider a data adapter uses to narrow a selector down through
6
+ * a storage adapter's index.
7
+ *
8
+ * Every adapter that keeps its data in a `StorageAdapter` needs exactly this, and
9
+ * each of them used to carry its own copy — three transcriptions of one set of
10
+ * rules about null, `$exists`, inclusion and exclusion, which is how they drift
11
+ * apart without anyone noticing. The index is keyed by `serializeValue(value)`,
12
+ * which is what `getMatchingKeys` produces, so the two only agree while they stay
13
+ * in one place.
14
+ * @template T - The type of the items in the collection.
15
+ * @template I - The type of the unique identifier for the items.
16
+ * @param storage - The storage adapter holding the index.
17
+ * @param field - The indexed field this provider answers for.
18
+ * @returns A query function for `getIndexInfo`.
19
+ */
20
+ export default function storageIndexQuery<T extends BaseItem<I>, I = any>(storage: Pick<StorageAdapter<T, I>, 'readIndex'>, field: string): AsynchronousQueryFunction<T, I>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signaldb/core",
3
- "version": "2.0.0-beta.17",
3
+ "version": "2.0.0-beta.19",
4
4
  "description": "SignalDB is a client-side database that provides a simple MongoDB-like interface to the data with first-class typescript support to achieve an optimistic UI. Data persistence can be achieved by using storage providers that store the data through a JSON interface to places such as localStorage.",
5
5
  "scripts": {
6
6
  "build": "rimraf dist && vite build",