@signaldb/core 2.0.0-beta.0 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/.vite/manifest.json +25 -12
  2. package/dist/AutoFetchDataAdapter.d.ts +0 -1
  3. package/dist/Collection/index.d.ts +2 -0
  4. package/dist/DataAdapter.d.ts +7 -6
  5. package/dist/DefaultDataAdapter.d.ts +1 -0
  6. package/dist/WorkerDataAdapter.d.ts +4 -1
  7. package/dist/WorkerDataAdapterHost.d.ts +9 -6
  8. package/dist/index.cjs12.js +32 -21
  9. package/dist/index.cjs13.js +25 -13
  10. package/dist/index.cjs14.js +31 -37
  11. package/dist/index.cjs15.js +120 -75
  12. package/dist/index.cjs16.js +45 -36
  13. package/dist/index.cjs17.js +1 -1
  14. package/dist/index.cjs2.js +5 -2
  15. package/dist/index.cjs20.js +5 -102
  16. package/dist/index.cjs21.js +93 -118
  17. package/dist/index.cjs22.js +127 -5
  18. package/dist/index.cjs23.js +5 -25
  19. package/dist/index.cjs24.js +25 -5
  20. package/dist/index.cjs26.js +1 -1
  21. package/dist/index.cjs27.js +44 -3
  22. package/dist/index.cjs28.js +6 -5
  23. package/dist/index.cjs29.js +7 -27
  24. package/dist/index.cjs3.js +25 -21
  25. package/dist/index.cjs30.js +3 -40
  26. package/dist/index.cjs31.js +5 -7
  27. package/dist/index.cjs32.js +29 -0
  28. package/dist/index.cjs33.js +42 -0
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index12.mjs +32 -21
  31. package/dist/index13.mjs +25 -13
  32. package/dist/index14.mjs +31 -37
  33. package/dist/index15.mjs +120 -75
  34. package/dist/index16.mjs +45 -36
  35. package/dist/index17.mjs +1 -1
  36. package/dist/index2.mjs +5 -2
  37. package/dist/index20.mjs +5 -102
  38. package/dist/index21.mjs +93 -117
  39. package/dist/index22.mjs +126 -5
  40. package/dist/index23.mjs +5 -25
  41. package/dist/index24.mjs +25 -5
  42. package/dist/index26.mjs +1 -1
  43. package/dist/index27.mjs +44 -3
  44. package/dist/index28.mjs +6 -5
  45. package/dist/index29.mjs +7 -27
  46. package/dist/index3.mjs +25 -21
  47. package/dist/index30.mjs +3 -40
  48. package/dist/index31.mjs +5 -7
  49. package/dist/index32.mjs +30 -0
  50. package/dist/index33.mjs +43 -0
  51. package/dist/utils/batchOnNextTick.d.ts +16 -0
  52. package/package.json +1 -1
package/dist/index21.mjs CHANGED
@@ -1,129 +1,105 @@
1
- import intersection from "./index28.mjs";
2
- function getMergedIndexInfo(queryFunctions, selector) {
3
- return queryFunctions.reduce((memoOrPromise, queryFunction) => {
4
- const resultOrPromise = queryFunction(selector);
5
- const processResult = (memo2, result) => {
6
- if (!result.matched)
7
- return memo2;
8
- const optimizedSelector = result.keepSelector ? memo2.optimizedSelector : Object.fromEntries(Object.entries(memo2.optimizedSelector).filter(([key]) => !result.fields.includes(key)));
9
- return {
10
- matched: true,
11
- ids: [...new Set(memo2.matched ? intersection(memo2.ids, result.ids) : result.ids)],
12
- optimizedSelector
13
- };
14
- };
15
- if (resultOrPromise instanceof Promise) {
16
- return resultOrPromise.then(async (result) => {
17
- const memo2 = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
18
- return processResult(memo2, result);
19
- });
1
+ import createIndexProvider from "./index30.mjs";
2
+ import get from "./index10.mjs";
3
+ import getMatchingKeys from "./index26.mjs";
4
+ import serializeValue from "./index11.mjs";
5
+ function createIndex(field) {
6
+ const index = /* @__PURE__ */ new Map();
7
+ const ensureSet = (key) => {
8
+ let set = index.get(key);
9
+ if (!set) {
10
+ set = /* @__PURE__ */ new Set();
11
+ index.set(key, set);
20
12
  }
21
- const memo = memoOrPromise;
22
- if (memo instanceof Promise)
23
- throw new Error("Mixing async and sync index providers is not supported");
24
- return processResult(memo, resultOrPromise);
25
- }, {
26
- matched: false,
27
- ids: [],
28
- optimizedSelector: { ...selector }
29
- });
30
- }
31
- function optimizeLogicGate(queryFunctions, logicGate, idsCallback) {
32
- return logicGate.reduce((memoOrPromise, sel) => {
33
- const getSelector = (indexInfo) => {
34
- const { matched: selMatched, ids: selIds, optimizedSelector: optimizedSelector2 } = indexInfo;
35
- if (selMatched) {
36
- idsCallback(true, selIds);
37
- if (Object.keys(optimizedSelector2).length > 0) {
38
- return optimizedSelector2;
13
+ return set;
14
+ };
15
+ return createIndexProvider({
16
+ query(selector) {
17
+ if (!Object.hasOwnProperty.call(selector, field)) {
18
+ return { matched: false };
19
+ }
20
+ const fieldSelector = selector[field];
21
+ const filteresForNull = fieldSelector == null || fieldSelector.$exists === false;
22
+ const keys = filteresForNull ? { include: null, exclude: [...index.keys()].filter((key) => key != null) } : getMatchingKeys(field, selector);
23
+ if (keys.include == null && keys.exclude == null)
24
+ return { matched: false };
25
+ let includedIds = [];
26
+ if (keys.include == null) {
27
+ for (const set of index.values()) {
28
+ for (const pos of set) {
29
+ includedIds.push(pos);
30
+ }
39
31
  }
40
32
  } else {
41
- idsCallback(false, []);
42
- return sel;
33
+ for (const key of keys.include) {
34
+ const posSet = index.get(key);
35
+ if (posSet) {
36
+ for (const pos of posSet) {
37
+ includedIds.push(pos);
38
+ }
39
+ }
40
+ }
43
41
  }
44
- };
45
- const indexInfoOrPromise = getIndexInfo(queryFunctions, sel);
46
- if (indexInfoOrPromise instanceof Promise) {
47
- return indexInfoOrPromise.then(async (indexInfo) => {
48
- const memo2 = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
49
- const optimizedSelector2 = getSelector(indexInfo);
50
- if (optimizedSelector2)
51
- memo2.push(optimizedSelector2);
52
- return memo2;
53
- });
54
- }
55
- const memo = memoOrPromise;
56
- if (memo instanceof Promise)
57
- throw new Error("Mixing async and sync index providers is not supported");
58
- const optimizedSelector = getSelector(indexInfoOrPromise);
59
- if (optimizedSelector)
60
- memo.push(optimizedSelector);
61
- return memo;
62
- }, []);
63
- }
64
- function getIndexInfo(queryFunctions, selector) {
65
- if (selector == null || Object.keys(selector).length <= 0) {
66
- return {
67
- matched: false,
68
- ids: [],
69
- optimizedSelector: selector
70
- };
71
- }
72
- const { $and, $or, ...rest } = selector;
73
- const flatInfoOrPromise = getMergedIndexInfo(queryFunctions, rest);
74
- const processFlatInfo = (flatInfo) => {
75
- let { matched, ids } = flatInfo;
76
- const newSelector = flatInfo.optimizedSelector;
77
- const $andNewOrPromise = Array.isArray($and) ? optimizeLogicGate(queryFunctions, $and, (match, selIds) => {
78
- if (!match)
79
- return;
80
- ids = matched ? intersection(ids, selIds) : selIds;
81
- matched = true;
82
- }) : void 0;
83
- const process$and = ($andNew) => {
84
- if ($andNew && $andNew.length > 0)
85
- newSelector.$and = $andNew;
86
- let hasNonIndexField = false;
87
- const matchedBefore = matched;
88
- const idsBefore = ids;
89
- const process$or = ($orNew) => {
90
- if ($orNew && $orNew.length > 0)
91
- newSelector.$or = $orNew;
92
- if (hasNonIndexField) {
93
- newSelector.$or = $or;
94
- matched = matchedBefore;
95
- ids = idsBefore;
42
+ if (keys.exclude != null) {
43
+ const excludeIds = /* @__PURE__ */ new Set();
44
+ for (const key of keys.exclude) {
45
+ const posSet = index.get(key);
46
+ if (posSet) {
47
+ for (const pos of posSet) {
48
+ excludeIds.add(pos);
49
+ }
50
+ }
96
51
  }
97
- return {
98
- matched,
99
- ids: ids || [],
100
- optimizedSelector: newSelector
101
- };
52
+ includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
53
+ }
54
+ return {
55
+ matched: true,
56
+ ids: includedIds,
57
+ fields: [field],
58
+ keepSelector: filteresForNull
102
59
  };
103
- const $orNewOrPromise = Array.isArray($or) ? optimizeLogicGate(queryFunctions, $or, (match, selIds) => {
104
- if (match) {
105
- ids = [.../* @__PURE__ */ new Set([...ids, ...selIds])];
106
- matched = true;
107
- } else {
108
- hasNonIndexField = true;
60
+ },
61
+ rebuild(items) {
62
+ index.clear();
63
+ items.forEach((item) => {
64
+ const value = serializeValue(get(item, field));
65
+ ensureSet(value).add(item.id);
66
+ });
67
+ },
68
+ // NEW: delta methods
69
+ insert(items) {
70
+ for (const item of items) {
71
+ const value = serializeValue(get(item, field));
72
+ ensureSet(value).add(item.id);
73
+ }
74
+ },
75
+ remove(items) {
76
+ for (const item of items) {
77
+ const value = serializeValue(get(item, field));
78
+ const set = index.get(value);
79
+ if (!set)
80
+ continue;
81
+ set.delete(item.id);
82
+ if (set.size === 0)
83
+ index.delete(value);
84
+ }
85
+ },
86
+ update(pairs) {
87
+ for (const { oldItem, newItem } of pairs) {
88
+ const oldValue = serializeValue(get(oldItem, field));
89
+ const newValue = serializeValue(get(newItem, field));
90
+ if (oldValue === newValue)
91
+ continue;
92
+ const oldSet = index.get(oldValue);
93
+ if (oldSet) {
94
+ oldSet.delete(oldItem.id);
95
+ if (oldSet.size === 0)
96
+ index.delete(oldValue);
109
97
  }
110
- }) : void 0;
111
- if ($orNewOrPromise instanceof Promise) {
112
- return $orNewOrPromise.then(($orNew) => process$or($orNew));
98
+ ensureSet(newValue).add(newItem.id);
113
99
  }
114
- return process$or($orNewOrPromise);
115
- };
116
- if ($andNewOrPromise instanceof Promise) {
117
- return $andNewOrPromise.then(($andNew) => process$and($andNew));
118
100
  }
119
- return process$and($andNewOrPromise);
120
- };
121
- if (flatInfoOrPromise instanceof Promise) {
122
- return flatInfoOrPromise.then(processFlatInfo);
123
- }
124
- return processFlatInfo(flatInfoOrPromise);
101
+ });
125
102
  }
126
103
  export {
127
- getIndexInfo as default,
128
- getMergedIndexInfo
104
+ createIndex as default
129
105
  };
package/dist/index22.mjs CHANGED
@@ -1,8 +1,129 @@
1
- import { Query } from "mingo";
2
- function match(item, selector) {
3
- const query = new Query(selector);
4
- return query.test(item);
1
+ import intersection from "./index31.mjs";
2
+ function getMergedIndexInfo(queryFunctions, selector) {
3
+ return queryFunctions.reduce((memoOrPromise, queryFunction) => {
4
+ const resultOrPromise = queryFunction(selector);
5
+ const processResult = (memo2, result) => {
6
+ if (!result.matched)
7
+ return memo2;
8
+ const optimizedSelector = result.keepSelector ? memo2.optimizedSelector : Object.fromEntries(Object.entries(memo2.optimizedSelector).filter(([key]) => !result.fields.includes(key)));
9
+ return {
10
+ matched: true,
11
+ ids: [...new Set(memo2.matched ? intersection(memo2.ids, result.ids) : result.ids)],
12
+ optimizedSelector
13
+ };
14
+ };
15
+ if (resultOrPromise instanceof Promise) {
16
+ return resultOrPromise.then(async (result) => {
17
+ const memo2 = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
18
+ return processResult(memo2, result);
19
+ });
20
+ }
21
+ const memo = memoOrPromise;
22
+ if (memo instanceof Promise)
23
+ throw new Error("Mixing async and sync index providers is not supported");
24
+ return processResult(memo, resultOrPromise);
25
+ }, {
26
+ matched: false,
27
+ ids: [],
28
+ optimizedSelector: { ...selector }
29
+ });
30
+ }
31
+ function optimizeLogicGate(queryFunctions, logicGate, idsCallback) {
32
+ return logicGate.reduce((memoOrPromise, sel) => {
33
+ const getSelector = (indexInfo) => {
34
+ const { matched: selMatched, ids: selIds, optimizedSelector: optimizedSelector2 } = indexInfo;
35
+ if (selMatched) {
36
+ idsCallback(true, selIds);
37
+ if (Object.keys(optimizedSelector2).length > 0) {
38
+ return optimizedSelector2;
39
+ }
40
+ } else {
41
+ idsCallback(false, []);
42
+ return sel;
43
+ }
44
+ };
45
+ const indexInfoOrPromise = getIndexInfo(queryFunctions, sel);
46
+ if (indexInfoOrPromise instanceof Promise) {
47
+ return indexInfoOrPromise.then(async (indexInfo) => {
48
+ const memo2 = memoOrPromise instanceof Promise ? await memoOrPromise : memoOrPromise;
49
+ const optimizedSelector2 = getSelector(indexInfo);
50
+ if (optimizedSelector2)
51
+ memo2.push(optimizedSelector2);
52
+ return memo2;
53
+ });
54
+ }
55
+ const memo = memoOrPromise;
56
+ if (memo instanceof Promise)
57
+ throw new Error("Mixing async and sync index providers is not supported");
58
+ const optimizedSelector = getSelector(indexInfoOrPromise);
59
+ if (optimizedSelector)
60
+ memo.push(optimizedSelector);
61
+ return memo;
62
+ }, []);
63
+ }
64
+ function getIndexInfo(queryFunctions, selector) {
65
+ if (selector == null || Object.keys(selector).length <= 0) {
66
+ return {
67
+ matched: false,
68
+ ids: [],
69
+ optimizedSelector: selector
70
+ };
71
+ }
72
+ const { $and, $or, ...rest } = selector;
73
+ const flatInfoOrPromise = getMergedIndexInfo(queryFunctions, rest);
74
+ const processFlatInfo = (flatInfo) => {
75
+ let { matched, ids } = flatInfo;
76
+ const newSelector = flatInfo.optimizedSelector;
77
+ const $andNewOrPromise = Array.isArray($and) ? optimizeLogicGate(queryFunctions, $and, (match, selIds) => {
78
+ if (!match)
79
+ return;
80
+ ids = matched ? intersection(ids, selIds) : selIds;
81
+ matched = true;
82
+ }) : void 0;
83
+ const process$and = ($andNew) => {
84
+ if ($andNew && $andNew.length > 0)
85
+ newSelector.$and = $andNew;
86
+ let hasNonIndexField = false;
87
+ const matchedBefore = matched;
88
+ const idsBefore = ids;
89
+ const process$or = ($orNew) => {
90
+ if ($orNew && $orNew.length > 0)
91
+ newSelector.$or = $orNew;
92
+ if (hasNonIndexField) {
93
+ newSelector.$or = $or;
94
+ matched = matchedBefore;
95
+ ids = idsBefore;
96
+ }
97
+ return {
98
+ matched,
99
+ ids: ids || [],
100
+ optimizedSelector: newSelector
101
+ };
102
+ };
103
+ const $orNewOrPromise = Array.isArray($or) ? optimizeLogicGate(queryFunctions, $or, (match, selIds) => {
104
+ if (match) {
105
+ ids = [.../* @__PURE__ */ new Set([...ids, ...selIds])];
106
+ matched = true;
107
+ } else {
108
+ hasNonIndexField = true;
109
+ }
110
+ }) : void 0;
111
+ if ($orNewOrPromise instanceof Promise) {
112
+ return $orNewOrPromise.then(($orNew) => process$or($orNew));
113
+ }
114
+ return process$or($orNewOrPromise);
115
+ };
116
+ if ($andNewOrPromise instanceof Promise) {
117
+ return $andNewOrPromise.then(($andNew) => process$and($andNew));
118
+ }
119
+ return process$and($andNewOrPromise);
120
+ };
121
+ if (flatInfoOrPromise instanceof Promise) {
122
+ return flatInfoOrPromise.then(processFlatInfo);
123
+ }
124
+ return processFlatInfo(flatInfoOrPromise);
5
125
  }
6
126
  export {
7
- match as default
127
+ getIndexInfo as default,
128
+ getMergedIndexInfo
8
129
  };
package/dist/index23.mjs CHANGED
@@ -1,28 +1,8 @@
1
- import get from "./index10.mjs";
2
- import set from "./index29.mjs";
3
- function project(item, fields) {
4
- const allFieldsDeactivated = Object.values(fields).every((value) => value === 0);
5
- if (allFieldsDeactivated) {
6
- const result2 = { ...item };
7
- Object.keys(fields).forEach((key) => {
8
- const fieldValue = get(item, key);
9
- if (fieldValue === void 0)
10
- return;
11
- set(result2, key, void 0, true);
12
- });
13
- return result2;
14
- }
15
- const result = {};
16
- Object.entries(fields).forEach(([key, value]) => {
17
- const fieldValue = get(item, key);
18
- if (fieldValue === void 0)
19
- return;
20
- if (fieldValue == null && value !== 1)
21
- return;
22
- set(result, key, value === 1 ? fieldValue : void 0);
23
- });
24
- return result;
1
+ import { Query } from "mingo";
2
+ function match(item, selector) {
3
+ const query = new Query(selector);
4
+ return query.test(item);
25
5
  }
26
6
  export {
27
- project as default
7
+ match as default
28
8
  };
package/dist/index24.mjs CHANGED
@@ -1,8 +1,28 @@
1
- function queryId(selector, options) {
2
- const selectorId = JSON.stringify(selector);
3
- const optionsId = options == null ? -1 : JSON.stringify(options);
4
- return `${selectorId}:${optionsId}`;
1
+ import get from "./index10.mjs";
2
+ import set from "./index32.mjs";
3
+ function project(item, fields) {
4
+ const allFieldsDeactivated = Object.values(fields).every((value) => value === 0);
5
+ if (allFieldsDeactivated) {
6
+ const result2 = { ...item };
7
+ Object.keys(fields).forEach((key) => {
8
+ const fieldValue = get(item, key);
9
+ if (fieldValue === void 0)
10
+ return;
11
+ set(result2, key, void 0, true);
12
+ });
13
+ return result2;
14
+ }
15
+ const result = {};
16
+ Object.entries(fields).forEach(([key, value]) => {
17
+ const fieldValue = get(item, key);
18
+ if (fieldValue === void 0)
19
+ return;
20
+ if (fieldValue == null && value !== 1)
21
+ return;
22
+ set(result, key, value === 1 ? fieldValue : void 0);
23
+ });
24
+ return result;
5
25
  }
6
26
  export {
7
- queryId as default
27
+ project as default
8
28
  };
package/dist/index26.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import isFieldExpression from "./index30.mjs";
1
+ import isFieldExpression from "./index33.mjs";
2
2
  import serializeValue from "./index11.mjs";
3
3
  function getMatchingKeys(field, selector) {
4
4
  const result = { include: null, exclude: null };
package/dist/index27.mjs CHANGED
@@ -1,6 +1,47 @@
1
- function createIndexProvider(definition) {
2
- return definition;
1
+ function batchOnNextTick(onFlush) {
2
+ const queues = /* @__PURE__ */ new Map();
3
+ function enqueue(key, args) {
4
+ return new Promise((resolve, reject) => {
5
+ let q = queues.get(key);
6
+ if (!q) {
7
+ q = {
8
+ timer: null,
9
+ items: [],
10
+ flush: () => flush(key)
11
+ };
12
+ queues.set(key, q);
13
+ }
14
+ q.items.push({ args, resolve, reject });
15
+ if (q.timer == null) {
16
+ q.timer = setTimeout(() => {
17
+ q.timer = null;
18
+ void q.flush();
19
+ }, 0);
20
+ }
21
+ });
22
+ }
23
+ async function flush(key) {
24
+ const q = queues.get(key);
25
+ if (!q || q.items.length === 0)
26
+ return;
27
+ if (q.timer != null) {
28
+ clearTimeout(q.timer);
29
+ q.timer = null;
30
+ }
31
+ const items = q.items.splice(0);
32
+ onFlush(key, items.map((i) => i.args)).then((results) => {
33
+ for (const [index, result] of results.entries()) {
34
+ const { resolve } = items[index];
35
+ resolve(result);
36
+ }
37
+ }).catch((error) => {
38
+ for (const { reject } of items) {
39
+ reject(error);
40
+ }
41
+ });
42
+ }
43
+ return { enqueue, flush };
3
44
  }
4
45
  export {
5
- createIndexProvider as default
46
+ batchOnNextTick as default
6
47
  };
package/dist/index28.mjs CHANGED
@@ -1,8 +1,9 @@
1
- function intersection(...arrays) {
2
- if (arrays.length === 0)
3
- return [];
4
- return [...new Set(arrays.reduce((a, b) => a.filter((c) => b.includes(c))))];
1
+ function truthy(value) {
2
+ return !!value;
3
+ }
4
+ function compact(array) {
5
+ return array.filter(truthy);
5
6
  }
6
7
  export {
7
- intersection as default
8
+ compact as default
8
9
  };
package/dist/index29.mjs CHANGED
@@ -1,30 +1,10 @@
1
- function set(object, path, value, deleteIfUndefined = false) {
2
- if (object == null)
3
- return object;
4
- const segments = path.split(/[.[\]]/g);
5
- if (segments[0] === "")
6
- segments.shift();
7
- if (segments.at(-1) === "")
8
- segments.pop();
9
- const apply = (node) => {
10
- if (segments.length > 1) {
11
- const key = segments.shift();
12
- const nextIsNumber = !Number.isNaN(Number.parseInt(segments[0], 10));
13
- if (node[key] === void 0) {
14
- node[key] = nextIsNumber ? [] : {};
15
- }
16
- apply(node[key]);
17
- } else {
18
- if (deleteIfUndefined && value === void 0) {
19
- delete node[segments[0]];
20
- return;
21
- }
22
- node[segments[0]] = value;
23
- }
24
- };
25
- apply(object);
26
- return object;
1
+ function uniqueBy(array, fn) {
2
+ const set = /* @__PURE__ */ new Set();
3
+ return array.filter((element) => {
4
+ const value = typeof fn === "function" ? fn(element) : element[fn];
5
+ return !set.has(value) && set.add(value);
6
+ });
27
7
  }
28
8
  export {
29
- set as default
9
+ uniqueBy as default
30
10
  };
package/dist/index3.mjs CHANGED
@@ -4,6 +4,7 @@ import randomId from "./index8.mjs";
4
4
  import DefaultDataAdapter from "./index12.mjs";
5
5
  import modify from "./index7.mjs";
6
6
  import deepClone from "./index19.mjs";
7
+ import queryId from "./index20.mjs";
7
8
  import Cursor from "./index2.mjs";
8
9
  class Collection extends EventEmitter {
9
10
  static collections = [];
@@ -66,6 +67,7 @@ class Collection extends EventEmitter {
66
67
  isDisposed = false;
67
68
  postBatchCallbacks = /* @__PURE__ */ new Set();
68
69
  fieldTracking = false;
70
+ queryListenersMap = /* @__PURE__ */ new Map();
69
71
  constructor(nameOrOptions, maybeDataAdapter, maybeOptions) {
70
72
  super();
71
73
  const name = typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions?.name || `${this.constructor.name}-${randomId()}`;
@@ -204,21 +206,9 @@ class Collection extends EventEmitter {
204
206
  return this.profile(() => {
205
207
  if (!options?.async)
206
208
  return this.backend.getQueryResult(selector, options);
207
- return new Promise((resolve, reject) => {
208
- this.isPullingSignal.set(true);
209
- const cleanup = this.backend.onQueryStateChange(selector, options, (state) => {
210
- if (state === "error") {
211
- cleanup();
212
- reject(this.backend.getQueryError(selector, options) || new Error("Unknown error"));
213
- } else if (state === "complete") {
214
- cleanup();
215
- resolve(this.backend.getQueryResult(selector, options) || []);
216
- }
217
- });
218
- this.backend.registerQuery(selector, options);
219
- }).finally(() => {
209
+ this.isPullingSignal.set(true);
210
+ return this.backend.executeQuery(selector, options).finally(() => {
220
211
  this.isPullingSignal.set(false);
221
- this.backend.unregisterQuery(selector, options);
222
212
  });
223
213
  }, (measuredTime) => this.executeInDebugMode((callstack) => this.emit("_debug.getItems", callstack, selector, measuredTime)));
224
214
  }
@@ -230,6 +220,13 @@ class Collection extends EventEmitter {
230
220
  this.isPushingSignal.set(false);
231
221
  }
232
222
  }
223
+ queryListeners(query, listeners) {
224
+ const id = queryId(query.selector, query.options);
225
+ if (listeners != null) {
226
+ return this.queryListenersMap.set(id, listeners);
227
+ }
228
+ return this.queryListenersMap.get(id) ?? 0;
229
+ }
233
230
  /**
234
231
  * Disposes the collection, unregisters persistence adapters, clears memory, and
235
232
  * cleans up all resources used by the collection.
@@ -268,17 +265,25 @@ class Collection extends EventEmitter {
268
265
  }
269
266
  requery();
270
267
  };
271
- this.backend.registerQuery(selector, options);
272
- const queryStateChangeCleanup = this.backend.onQueryStateChange(selector, options, (state) => {
268
+ const listeners = this.queryListeners({ selector, options });
269
+ if (listeners === 0)
270
+ this.backend.registerQuery(selector, options || {});
271
+ this.queryListeners({ selector, options }, listeners + 1);
272
+ const queryStateChangeCleanup = this.backend.onQueryStateChange(selector, options || {}, (state) => {
273
273
  if (state !== "complete")
274
274
  return;
275
275
  handleRequery();
276
276
  });
277
277
  this.emit("observer.created", selector, options);
278
278
  return () => {
279
- this.backend.unregisterQuery(selector, options);
280
- queryStateChangeCleanup();
281
- this.emit("observer.disposed", selector, options);
279
+ setTimeout(() => {
280
+ const newListeners = Math.max(0, this.queryListeners({ selector, options }) - 1);
281
+ if (newListeners === 0)
282
+ this.backend.unregisterQuery(selector, options || {});
283
+ this.queryListeners({ selector, options }, newListeners);
284
+ queryStateChangeCleanup();
285
+ this.emit("observer.disposed", selector, options);
286
+ }, 0);
282
287
  };
283
288
  }
284
289
  });
@@ -371,9 +376,8 @@ class Collection extends EventEmitter {
371
376
  throw new Error("Collection is disposed");
372
377
  if (!items)
373
378
  throw new Error("Invalid items");
374
- if (items.length === 0) {
379
+ if (items.length === 0)
375
380
  return [];
376
- }
377
381
  const ids = [];
378
382
  await this.batch(async () => {
379
383
  await Promise.all(items.map(async (item) => {