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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/dist/.vite/manifest.json +128 -75
  2. package/dist/AsyncDataAdapter.d.ts +44 -7
  3. package/dist/AutoFetchDataAdapter.d.ts +5 -8
  4. package/dist/Collection/Cursor.d.ts +6 -5
  5. package/dist/Collection/Observer.d.ts +2 -0
  6. package/dist/Collection/index.d.ts +36 -25
  7. package/dist/Collection/types.d.ts +10 -2
  8. package/dist/DataAdapter.d.ts +18 -11
  9. package/dist/DefaultDataAdapter.d.ts +7 -6
  10. package/dist/WorkerDataAdapter.d.ts +7 -6
  11. package/dist/WorkerDataAdapterHost.d.ts +14 -11
  12. package/dist/createIndex.d.ts +2 -2
  13. package/dist/createIndexProvider.d.ts +2 -2
  14. package/dist/createReactivityAdapter.d.ts +2 -2
  15. package/dist/createStorageAdapter.d.ts +1 -1
  16. package/dist/getIndexInfo.d.ts +3 -4
  17. package/dist/index.cjs.js +33 -31
  18. package/dist/index.d.ts +3 -1
  19. package/dist/index.mjs +17 -32
  20. package/dist/index10.cjs.js +23 -0
  21. package/dist/index10.mjs +21 -17
  22. package/dist/index11.cjs.js +45 -0
  23. package/dist/index11.mjs +44 -15
  24. package/dist/index12.cjs.js +22 -0
  25. package/dist/index12.mjs +21 -339
  26. package/dist/index13.cjs.js +45 -0
  27. package/dist/index13.mjs +44 -407
  28. package/dist/index14.cjs.js +86 -0
  29. package/dist/index14.mjs +85 -190
  30. package/dist/index15.cjs.js +15 -0
  31. package/dist/index15.mjs +14 -341
  32. package/dist/index16.cjs.js +136 -0
  33. package/dist/index16.mjs +134 -569
  34. package/dist/index17.cjs.js +47 -0
  35. package/dist/index17.mjs +46 -150
  36. package/dist/index18.cjs.js +15 -0
  37. package/dist/index18.mjs +14 -26
  38. package/dist/index19.cjs.js +23 -0
  39. package/dist/index19.mjs +22 -42
  40. package/dist/index2.cjs.js +33 -0
  41. package/dist/index2.mjs +32 -254
  42. package/dist/index20.cjs.js +37 -0
  43. package/dist/index20.mjs +36 -104
  44. package/dist/index21.cjs.js +35 -0
  45. package/dist/index21.mjs +34 -128
  46. package/dist/index22.cjs.js +25 -0
  47. package/dist/index22.mjs +24 -7
  48. package/dist/index23.cjs.js +19 -0
  49. package/dist/index23.mjs +17 -26
  50. package/dist/index24.cjs.js +342 -0
  51. package/dist/index24.mjs +340 -6
  52. package/dist/index25.cjs.js +542 -0
  53. package/dist/index25.mjs +541 -10
  54. package/dist/index26.cjs.js +11 -0
  55. package/dist/index26.mjs +10 -29
  56. package/dist/index27.cjs.js +11 -0
  57. package/dist/index27.mjs +10 -5
  58. package/dist/index28.cjs.js +90 -0
  59. package/dist/index28.mjs +89 -8
  60. package/dist/index29.cjs.js +424 -0
  61. package/dist/index29.mjs +423 -29
  62. package/dist/index3.cjs.js +19 -0
  63. package/dist/index3.mjs +18 -537
  64. package/dist/index30.cjs.js +72 -0
  65. package/dist/index30.mjs +71 -42
  66. package/dist/index31.cjs.js +191 -0
  67. package/dist/index31.mjs +190 -9
  68. package/dist/index32.cjs.js +21 -0
  69. package/dist/index32.mjs +21 -0
  70. package/dist/index33.cjs.js +336 -0
  71. package/dist/index33.mjs +336 -0
  72. package/dist/index34.cjs.js +539 -0
  73. package/dist/index34.mjs +539 -0
  74. package/dist/index4.cjs.js +150 -0
  75. package/dist/index4.mjs +149 -5
  76. package/dist/index5.cjs.js +254 -0
  77. package/dist/index5.mjs +252 -4
  78. package/dist/index6.cjs.js +125 -0
  79. package/dist/index6.mjs +124 -29
  80. package/dist/index7.cjs.js +33 -0
  81. package/dist/index7.mjs +32 -12
  82. package/dist/index8.cjs.js +12 -0
  83. package/dist/index8.mjs +10 -4
  84. package/dist/index9.cjs.js +11 -0
  85. package/dist/index9.mjs +10 -133
  86. package/dist/types/IndexProvider.d.ts +2 -2
  87. package/dist/types/Modifier.d.ts +1 -1
  88. package/dist/types/ReactivityAdapter.d.ts +1 -1
  89. package/dist/utils/batchOnNextTick.d.ts +16 -0
  90. package/dist/utils/createSignal.d.ts +2 -2
  91. package/dist/utils/deepClone.d.ts +1 -1
  92. package/dist/utils/getMatchingKeys.d.ts +2 -2
  93. package/dist/utils/isFieldExpression.d.ts +1 -1
  94. package/dist/utils/match.d.ts +1 -1
  95. package/dist/utils/modify.d.ts +1 -1
  96. package/dist/utils/queryId.d.ts +2 -2
  97. package/dist/utils/reactiveOrAsync.d.ts +59 -0
  98. package/package.json +3 -3
  99. package/dist/index.cjs10.js +0 -18
  100. package/dist/index.cjs11.js +0 -15
  101. package/dist/index.cjs12.js +0 -339
  102. package/dist/index.cjs13.js +0 -407
  103. package/dist/index.cjs14.js +0 -190
  104. package/dist/index.cjs15.js +0 -341
  105. package/dist/index.cjs16.js +0 -570
  106. package/dist/index.cjs17.js +0 -150
  107. package/dist/index.cjs18.js +0 -26
  108. package/dist/index.cjs19.js +0 -43
  109. package/dist/index.cjs2.js +0 -255
  110. package/dist/index.cjs20.js +0 -104
  111. package/dist/index.cjs21.js +0 -129
  112. package/dist/index.cjs22.js +0 -7
  113. package/dist/index.cjs23.js +0 -27
  114. package/dist/index.cjs24.js +0 -7
  115. package/dist/index.cjs25.js +0 -10
  116. package/dist/index.cjs26.js +0 -29
  117. package/dist/index.cjs27.js +0 -5
  118. package/dist/index.cjs28.js +0 -7
  119. package/dist/index.cjs29.js +0 -29
  120. package/dist/index.cjs3.js +0 -538
  121. package/dist/index.cjs30.js +0 -42
  122. package/dist/index.cjs31.js +0 -9
  123. package/dist/index.cjs4.js +0 -5
  124. package/dist/index.cjs5.js +0 -5
  125. package/dist/index.cjs6.js +0 -29
  126. package/dist/index.cjs7.js +0 -12
  127. package/dist/index.cjs8.js +0 -5
  128. package/dist/index.cjs9.js +0 -133
package/dist/index2.mjs CHANGED
@@ -1,255 +1,33 @@
1
- import Observer from "./index17.mjs";
2
- function isInReactiveScope(reactivity) {
3
- if (!reactivity)
4
- return false;
5
- if (!reactivity.isInScope)
6
- return true;
7
- return reactivity.isInScope();
1
+ //#region src/utils/isEqual.ts
2
+ /**
3
+ * Compares two values for deep equality.
4
+ * @param a - The first value to compare.
5
+ * @param b - The second value to compare.
6
+ * @returns - Returns `true` if the two values are deeply equal, otherwise `false`.
7
+ * @example
8
+ * isEqual({ a: 1 }, { a: 1 }); // true
9
+ * isEqual([1, 2], [1, 2]); // true
10
+ * isEqual(new Date(0), new Date(0)); // true
11
+ * isEqual(/abc/, /abc/); // true
12
+ * isEqual({ a: 1 }, { a: 2 }); // false
13
+ * isEqual(null, null); // true
14
+ */
15
+ function isEqual(a, b) {
16
+ if (Object.is(a, b)) return true;
17
+ if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
18
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
19
+ if (typeof a !== "object") return false;
20
+ if (typeof b !== "object") return false;
21
+ if (a === null) return false;
22
+ if (b === null) return false;
23
+ const aKeys = Object.keys(a);
24
+ const bKeys = Object.keys(b);
25
+ if (aKeys.length !== bKeys.length) return false;
26
+ for (const key of aKeys) {
27
+ if (!bKeys.includes(key)) return false;
28
+ if (!isEqual(a[key], b[key])) return false;
29
+ }
30
+ return true;
8
31
  }
9
- class Cursor {
10
- observer;
11
- getItems;
12
- options;
13
- onCleanupCallbacks = [];
14
- /**
15
- * Creates a new instance of the `Cursor` class.
16
- * Provides utilities for querying, observing, and transforming items from a collection.
17
- * @template T - The type of the items in the collection.
18
- * @template U - The transformed item type after applying transformations (default is T).
19
- * @param getItems - A function that retrieves the filtered list of items.
20
- * @param options - Optional configuration for the cursor.
21
- * @param options.transform - A transformation function to apply to each item when retrieving them.
22
- * @param options.bindEvents - A function to bind reactivity events for the cursor, which should return a cleanup function.
23
- * @param options.fields - A projection object defining which fields of the item should be included or excluded.
24
- * @param options.sort - A sort specifier to determine the order of the items.
25
- * @param options.skip - The number of items to skip from the beginning of the result set.
26
- * @param options.limit - The maximum number of items to return in the result set.
27
- * @param options.reactive - A reactivity adapter to enable observing changes in the cursor's result set.
28
- * @param options.fieldTracking - A boolean to enable fine-grained field tracking for reactivity.
29
- */
30
- constructor(getItems, options) {
31
- this.getItems = getItems;
32
- this.options = options || {};
33
- }
34
- addGetters(item) {
35
- if (!isInReactiveScope(this.options.reactive))
36
- return item;
37
- const depend = this.depend.bind(this);
38
- return Object.entries(item).reduce((memo, [key, value]) => {
39
- Object.defineProperty(memo, key, {
40
- get() {
41
- depend({
42
- changedField: (notify) => (changedItem, changedFieldName) => {
43
- if (changedFieldName !== key || changedItem.id !== item.id)
44
- return;
45
- notify();
46
- }
47
- });
48
- return value;
49
- },
50
- enumerable: true,
51
- configurable: true
52
- });
53
- return memo;
54
- }, {});
55
- }
56
- transform(rawItem) {
57
- const item = this.options.fieldTracking ? this.addGetters(rawItem) : rawItem;
58
- if (!this.options.transform)
59
- return item;
60
- return this.options.transform(item);
61
- }
62
- depend(changeEvents) {
63
- if (!this.options.reactive)
64
- return;
65
- if (!isInReactiveScope(this.options.reactive))
66
- return;
67
- const signal = this.options.reactive.create();
68
- signal.depend();
69
- const notify = () => signal.notify();
70
- function buildNotifier(event) {
71
- const eventHandler = changeEvents[event];
72
- return (...args) => {
73
- if (eventHandler === true) {
74
- notify();
75
- return;
76
- }
77
- if (typeof eventHandler !== "function")
78
- return;
79
- eventHandler(notify)(...args);
80
- };
81
- }
82
- const stop = this.observeRawChanges({
83
- added: buildNotifier("added"),
84
- addedBefore: buildNotifier("addedBefore"),
85
- changed: buildNotifier("changed"),
86
- changedField: buildNotifier("changedField"),
87
- movedBefore: buildNotifier("movedBefore"),
88
- removed: buildNotifier("removed")
89
- }, true);
90
- if (this.options.reactive.onDispose) {
91
- this.options.reactive.onDispose(() => stop(), signal);
92
- }
93
- this.onCleanup(stop);
94
- }
95
- ensureObserver() {
96
- if (!this.observer) {
97
- const observer = new Observer(() => {
98
- const requery = () => {
99
- observer.runChecks(this.getItems);
100
- };
101
- const cleanup = this.options.bindEvents && this.options.bindEvents(requery);
102
- return () => {
103
- if (cleanup)
104
- cleanup();
105
- };
106
- });
107
- this.onCleanup(() => observer.stop());
108
- this.observer = observer;
109
- }
110
- return this.observer;
111
- }
112
- observeRawChanges(callbacks, skipInitial = false) {
113
- const observer = this.ensureObserver();
114
- observer.addCallbacks(callbacks, skipInitial);
115
- observer.runChecks(this.getItems);
116
- return () => {
117
- observer.removeCallbacks(callbacks);
118
- if (!observer.isEmpty())
119
- return;
120
- observer.stop();
121
- this.observer = void 0;
122
- };
123
- }
124
- /**
125
- * Cleans up all resources associated with the cursor, such as reactive bindings
126
- * and event listeners. This method should be called when the cursor is no longer needed
127
- * to prevent memory leaks.
128
- */
129
- cleanup() {
130
- this.onCleanupCallbacks.forEach((callback) => {
131
- callback();
132
- });
133
- this.onCleanupCallbacks = [];
134
- }
135
- /**
136
- * Registers a cleanup callback to be executed when the `cleanup` method is called.
137
- * Useful for managing resources and ensuring proper cleanup of bindings or listeners.
138
- * @param callback - A function to be executed during cleanup.
139
- */
140
- onCleanup(callback) {
141
- this.onCleanupCallbacks.push(callback);
142
- }
143
- /**
144
- * Iterates over each item in the cursor's result set, applying the provided callback
145
- * function to each transformed item.
146
- * ⚡️ this function is reactive!
147
- * @param callback - A function to execute for each item in the result set.
148
- * @param callback.item - The transformed item.
149
- * @returns A promise that resolves when all items have been processed, or void if not in async mode.
150
- */
151
- forEach(callback) {
152
- this.depend({
153
- addedBefore: true,
154
- removed: true,
155
- movedBefore: true,
156
- ...this.options.fieldTracking ? {} : { changed: true }
157
- });
158
- const executeForEach = (items) => {
159
- items.forEach((item) => {
160
- callback(this.transform(item));
161
- });
162
- };
163
- const result = this.getItems();
164
- if (result instanceof Promise) {
165
- return result.then(executeForEach);
166
- } else {
167
- executeForEach(result);
168
- return void 0;
169
- }
170
- }
171
- /**
172
- * Creates a new array populated with the results of applying the provided callback
173
- * function to each transformed item in the cursor's result set.
174
- * ⚡️ this function is reactive!
175
- * @template V - The type of the items in the resulting array.
176
- * @param callback - A function to execute for each item in the result set.
177
- * @param callback.item - The transformed item.
178
- * @returns An array of results after applying the callback to each item.
179
- */
180
- map(callback) {
181
- const results = [];
182
- const maybePromise = this.forEach((item) => {
183
- results.push(callback(item));
184
- });
185
- if (maybePromise instanceof Promise) {
186
- return maybePromise.then(() => results);
187
- }
188
- return results;
189
- }
190
- /**
191
- * Fetches all transformed items from the cursor's result set as an array.
192
- * Automatically applies filtering, sorting, and limiting as per the cursor's options.
193
- * ⚡️ this function is reactive!
194
- * @returns An array of transformed items in the result set.
195
- */
196
- fetch() {
197
- return this.map((item) => item);
198
- }
199
- /**
200
- * Counts the total number of items in the cursor's result set after applying
201
- * filtering and other criteria.
202
- * ⚡️ this function is reactive!
203
- * @returns The total number of items in the result set.
204
- */
205
- count() {
206
- this.depend({
207
- added: true,
208
- removed: true
209
- });
210
- const maybePromise = this.getItems();
211
- return maybePromise instanceof Promise ? maybePromise.then((items) => items.length) : maybePromise.length;
212
- }
213
- /**
214
- * Observes changes to the cursor's result set and triggers the specified callbacks
215
- * when items are added, removed, or updated. Supports reactivity and transformation.
216
- * @param callbacks - An object containing the callback functions to handle different change events.
217
- * @param callbacks.added - Triggered when an item is added to the result set.
218
- * @param callbacks.removed - Triggered when an item is removed from the result set.
219
- * @param callbacks.changed - Triggered when an item in the result set is modified.
220
- * @param callbacks.addedBefore - Triggered when an item is added before another item in the result set.
221
- * @param callbacks.movedBefore - Triggered when an item is moved before another item in the result set.
222
- * @param callbacks.changedField - Triggered when a specific field of an item changes.
223
- * @param skipInitial - A boolean indicating whether to skip the initial notification of the current result set.
224
- * @returns A function to stop observing changes.
225
- */
226
- observeChanges(callbacks, skipInitial = false) {
227
- return this.observeRawChanges(Object.entries(callbacks).reduce((memo, [callbackName, callback]) => {
228
- if (!callback)
229
- return memo;
230
- return {
231
- ...memo,
232
- [callbackName]: (item, before) => {
233
- const transformedValue = this.transform(item);
234
- const hasBeforeParameter = before !== void 0;
235
- const transformedBeforeValue = hasBeforeParameter && before ? this.transform(before) : null;
236
- return callback(transformedValue, ...hasBeforeParameter ? [transformedBeforeValue] : []);
237
- }
238
- };
239
- }, {}), skipInitial);
240
- }
241
- /**
242
- * Forces the cursor to re-evaluate its result set by re-fetching items
243
- * from the collection. This is useful when the underlying data or query
244
- * criteria have changed, and you want to ensure the cursor reflects the latest state.
245
- */
246
- requery() {
247
- if (!this.observer)
248
- return;
249
- this.observer.runChecks(this.getItems);
250
- }
251
- }
252
- export {
253
- Cursor as default,
254
- isInReactiveScope
255
- };
32
+ //#endregion
33
+ export { isEqual as default };
@@ -0,0 +1,37 @@
1
+ //#region src/utils/set.ts
2
+ /**
3
+ * Sets a value at a specified path within an object. Creates nested structures
4
+ * (arrays or objects) as needed to set the value at the correct location. Supports
5
+ * deleting the key if the value is `undefined` and the `deleteIfUndefined` flag is set to `true`.
6
+ * @template T - The type of the object to modify.
7
+ * @template K - The type of the value to set.
8
+ * @param object - The object to modify. The object is mutated directly.
9
+ * @param path - The path (dot or bracket notation) where the value should be set.
10
+ * @param value - The value to set at the specified path.
11
+ * @param deleteIfUndefined - A boolean indicating whether to delete the key if the value is `undefined` (default: `false`).
12
+ * @returns The modified object.
13
+ */
14
+ function set(object, path, value, deleteIfUndefined = false) {
15
+ if (object == null) return object;
16
+ const segments = path.split(/[.[\]]/g);
17
+ if (segments[0] === "") segments.shift();
18
+ if (segments.at(-1) === "") segments.pop();
19
+ const apply = (node) => {
20
+ if (segments.length > 1) {
21
+ const key = segments.shift();
22
+ const nextIsNumber = !Number.isNaN(Number.parseInt(segments[0], 10));
23
+ if (node[key] === void 0) node[key] = nextIsNumber ? [] : {};
24
+ apply(node[key]);
25
+ } else {
26
+ if (deleteIfUndefined && value === void 0) {
27
+ delete node[segments[0]];
28
+ return;
29
+ }
30
+ node[segments[0]] = value;
31
+ }
32
+ };
33
+ apply(object);
34
+ return object;
35
+ }
36
+ //#endregion
37
+ exports.default = set;
package/dist/index20.mjs CHANGED
@@ -1,105 +1,37 @@
1
- import createIndexProvider from "./index27.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);
12
- }
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
- }
31
- }
32
- } else {
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
- }
41
- }
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
- }
51
- }
52
- includedIds = includedIds.filter((pos) => !excludeIds.has(pos));
53
- }
54
- return {
55
- matched: true,
56
- ids: includedIds,
57
- fields: [field],
58
- keepSelector: filteresForNull
59
- };
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);
97
- }
98
- ensureSet(newValue).add(newItem.id);
99
- }
100
- }
101
- });
1
+ //#region src/utils/set.ts
2
+ /**
3
+ * Sets a value at a specified path within an object. Creates nested structures
4
+ * (arrays or objects) as needed to set the value at the correct location. Supports
5
+ * deleting the key if the value is `undefined` and the `deleteIfUndefined` flag is set to `true`.
6
+ * @template T - The type of the object to modify.
7
+ * @template K - The type of the value to set.
8
+ * @param object - The object to modify. The object is mutated directly.
9
+ * @param path - The path (dot or bracket notation) where the value should be set.
10
+ * @param value - The value to set at the specified path.
11
+ * @param deleteIfUndefined - A boolean indicating whether to delete the key if the value is `undefined` (default: `false`).
12
+ * @returns The modified object.
13
+ */
14
+ function set(object, path, value, deleteIfUndefined = false) {
15
+ if (object == null) return object;
16
+ const segments = path.split(/[.[\]]/g);
17
+ if (segments[0] === "") segments.shift();
18
+ if (segments.at(-1) === "") segments.pop();
19
+ const apply = (node) => {
20
+ if (segments.length > 1) {
21
+ const key = segments.shift();
22
+ const nextIsNumber = !Number.isNaN(Number.parseInt(segments[0], 10));
23
+ if (node[key] === void 0) node[key] = nextIsNumber ? [] : {};
24
+ apply(node[key]);
25
+ } else {
26
+ if (deleteIfUndefined && value === void 0) {
27
+ delete node[segments[0]];
28
+ return;
29
+ }
30
+ node[segments[0]] = value;
31
+ }
32
+ };
33
+ apply(object);
34
+ return object;
102
35
  }
103
- export {
104
- createIndex as default
105
- };
36
+ //#endregion
37
+ export { set as default };
@@ -0,0 +1,35 @@
1
+ const require_get = require("./index10.cjs.js");
2
+ const require_set = require("./index20.cjs.js");
3
+ //#region src/utils/project.ts
4
+ /**
5
+ * Projects the fields of an object based on a specified fields configuration.
6
+ * Supports inclusion (`1`) and exclusion (`0`) of specific fields. Creates a new object
7
+ * with the desired fields included or excluded, based on the configuration.
8
+ * @template T - The type of the object being projected.
9
+ * @param item - The original object to project fields from.
10
+ * @param fields - An object defining the fields to include (`1`) or exclude (`0`).
11
+ * - Keys are the field names, and values are either `1` (include) or `0` (exclude).
12
+ * @returns A new object with the specified fields included or excluded.
13
+ * - If all fields are set to `0`, the excluded fields are removed from the result.
14
+ * - If fields are set to `1`, only the included fields are retained.
15
+ */
16
+ function project(item, fields) {
17
+ if (Object.values(fields).every((value) => value === 0)) {
18
+ const result = { ...item };
19
+ Object.keys(fields).forEach((key) => {
20
+ if (require_get.default(item, key) === void 0) return;
21
+ require_set.default(result, key, void 0, true);
22
+ });
23
+ return result;
24
+ }
25
+ const result = {};
26
+ Object.entries(fields).forEach(([key, value]) => {
27
+ const fieldValue = require_get.default(item, key);
28
+ if (fieldValue === void 0) return;
29
+ if (fieldValue == null && value !== 1) return;
30
+ require_set.default(result, key, value === 1 ? fieldValue : void 0);
31
+ });
32
+ return result;
33
+ }
34
+ //#endregion
35
+ exports.default = project;
package/dist/index21.mjs CHANGED
@@ -1,129 +1,35 @@
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
- });
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
- });
1
+ import get from "./index10.mjs";
2
+ import set from "./index20.mjs";
3
+ //#region src/utils/project.ts
4
+ /**
5
+ * Projects the fields of an object based on a specified fields configuration.
6
+ * Supports inclusion (`1`) and exclusion (`0`) of specific fields. Creates a new object
7
+ * with the desired fields included or excluded, based on the configuration.
8
+ * @template T - The type of the object being projected.
9
+ * @param item - The original object to project fields from.
10
+ * @param fields - An object defining the fields to include (`1`) or exclude (`0`).
11
+ * - Keys are the field names, and values are either `1` (include) or `0` (exclude).
12
+ * @returns A new object with the specified fields included or excluded.
13
+ * - If all fields are set to `0`, the excluded fields are removed from the result.
14
+ * - If fields are set to `1`, only the included fields are retained.
15
+ */
16
+ function project(item, fields) {
17
+ if (Object.values(fields).every((value) => value === 0)) {
18
+ const result = { ...item };
19
+ Object.keys(fields).forEach((key) => {
20
+ if (get(item, key) === void 0) return;
21
+ set(result, key, void 0, true);
22
+ });
23
+ return result;
24
+ }
25
+ const result = {};
26
+ Object.entries(fields).forEach(([key, value]) => {
27
+ const fieldValue = get(item, key);
28
+ if (fieldValue === void 0) return;
29
+ if (fieldValue == null && value !== 1) return;
30
+ set(result, key, value === 1 ? fieldValue : void 0);
31
+ });
32
+ return result;
30
33
  }
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);
125
- }
126
- export {
127
- getIndexInfo as default,
128
- getMergedIndexInfo
129
- };
34
+ //#endregion
35
+ export { project as default };