@signaldb/core 1.7.2 → 1.8.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 (95) hide show
  1. package/dist/.vite/manifest.json +88 -59
  2. package/dist/AutoFetchCollection.d.ts +3 -3
  3. package/dist/Collection/Cursor.d.ts +10 -7
  4. package/dist/Collection/index.d.ts +27 -11
  5. package/dist/Collection/types.d.ts +1 -0
  6. package/dist/ReplicatedCollection.d.ts +4 -4
  7. package/dist/index.cjs.js +26 -27
  8. package/dist/index.d.ts +1 -1
  9. package/dist/index.mjs +14 -28
  10. package/dist/index10.cjs.js +265 -0
  11. package/dist/index10.mjs +263 -28
  12. package/dist/index11.cjs.js +125 -0
  13. package/dist/index11.mjs +124 -12
  14. package/dist/index12.cjs.js +15 -0
  15. package/dist/index12.mjs +14 -5
  16. package/dist/index13.cjs.js +23 -0
  17. package/dist/index13.mjs +22 -133
  18. package/dist/index14.cjs.js +12 -0
  19. package/dist/index14.mjs +11 -73
  20. package/dist/index15.cjs.js +22 -0
  21. package/dist/index15.mjs +21 -10
  22. package/dist/index16.cjs.js +33 -0
  23. package/dist/index16.mjs +32 -27
  24. package/dist/index17.cjs.js +15 -0
  25. package/dist/index17.mjs +14 -142
  26. package/dist/index18.cjs.js +98 -0
  27. package/dist/index18.mjs +97 -7
  28. package/dist/index19.cjs.js +11 -0
  29. package/dist/index19.mjs +10 -41
  30. package/dist/index2.cjs.js +23 -0
  31. package/dist/index2.mjs +22 -260
  32. package/dist/index20.cjs.js +45 -0
  33. package/dist/index20.mjs +44 -15
  34. package/dist/index21.cjs.js +45 -0
  35. package/dist/index21.mjs +44 -26
  36. package/dist/index22.cjs.js +69 -0
  37. package/dist/index22.mjs +66 -77
  38. package/dist/index23.cjs.js +778 -0
  39. package/dist/index23.mjs +775 -81
  40. package/dist/index24.cjs.js +11 -0
  41. package/dist/index24.mjs +10 -18
  42. package/dist/index25.cjs.js +81 -0
  43. package/dist/index25.mjs +80 -29
  44. package/dist/index26.cjs.js +98 -0
  45. package/dist/index26.mjs +96 -8
  46. package/dist/index27.cjs.js +154 -0
  47. package/dist/index27.mjs +153 -7
  48. package/dist/index28.cjs.js +11 -0
  49. package/dist/index28.mjs +10 -29
  50. package/dist/index29.cjs.js +11 -0
  51. package/dist/index29.mjs +10 -42
  52. package/dist/index3.cjs.js +19 -0
  53. package/dist/index3.mjs +18 -788
  54. package/dist/index4.cjs.js +37 -0
  55. package/dist/index4.mjs +36 -167
  56. package/dist/index5.cjs.js +35 -0
  57. package/dist/index5.mjs +34 -67
  58. package/dist/index6.cjs.js +47 -0
  59. package/dist/index6.mjs +46 -5
  60. package/dist/index7.cjs.js +33 -0
  61. package/dist/index7.mjs +32 -5
  62. package/dist/index8.cjs.js +19 -0
  63. package/dist/index8.mjs +18 -5
  64. package/dist/index9.cjs.js +139 -0
  65. package/dist/index9.mjs +138 -5
  66. package/dist/utils/deepClone.d.ts +1 -1
  67. package/package.json +3 -3
  68. package/dist/index.cjs10.js +0 -29
  69. package/dist/index.cjs11.js +0 -12
  70. package/dist/index.cjs12.js +0 -5
  71. package/dist/index.cjs13.js +0 -133
  72. package/dist/index.cjs14.js +0 -74
  73. package/dist/index.cjs15.js +0 -10
  74. package/dist/index.cjs16.js +0 -27
  75. package/dist/index.cjs17.js +0 -142
  76. package/dist/index.cjs18.js +0 -7
  77. package/dist/index.cjs19.js +0 -42
  78. package/dist/index.cjs2.js +0 -261
  79. package/dist/index.cjs20.js +0 -15
  80. package/dist/index.cjs21.js +0 -26
  81. package/dist/index.cjs22.js +0 -79
  82. package/dist/index.cjs23.js +0 -84
  83. package/dist/index.cjs24.js +0 -18
  84. package/dist/index.cjs25.js +0 -29
  85. package/dist/index.cjs26.js +0 -9
  86. package/dist/index.cjs27.js +0 -7
  87. package/dist/index.cjs28.js +0 -29
  88. package/dist/index.cjs29.js +0 -42
  89. package/dist/index.cjs3.js +0 -788
  90. package/dist/index.cjs4.js +0 -167
  91. package/dist/index.cjs5.js +0 -68
  92. package/dist/index.cjs6.js +0 -5
  93. package/dist/index.cjs7.js +0 -5
  94. package/dist/index.cjs8.js +0 -5
  95. package/dist/index.cjs9.js +0 -5
@@ -0,0 +1,11 @@
1
+ //#region src/persistence/createPersistenceAdapter.ts
2
+ /**
3
+ * Creates an PersistenceAdapter based on the given definition.
4
+ * @param definition - The definition of the PersistenceAdapter.
5
+ * @returns The created PersistenceAdapter.
6
+ */
7
+ function createPersistenceAdapter(definition) {
8
+ return definition;
9
+ }
10
+ //#endregion
11
+ exports.default = createPersistenceAdapter;
package/dist/index24.mjs CHANGED
@@ -1,19 +1,11 @@
1
- function get(value, path) {
2
- const normalized = path.replaceAll(/\[(\w+)\]/g, ".$1");
3
- if (normalized.includes("..") || normalized.startsWith(".") || normalized.endsWith(".")) {
4
- return;
5
- }
6
- const segments = normalized.split(".");
7
- let current = value;
8
- for (const key of segments) {
9
- if (current == null)
10
- return;
11
- current = current[key];
12
- }
13
- if (current === void 0)
14
- return;
15
- return current;
1
+ //#region src/persistence/createPersistenceAdapter.ts
2
+ /**
3
+ * Creates an PersistenceAdapter based on the given definition.
4
+ * @param definition - The definition of the PersistenceAdapter.
5
+ * @returns The created PersistenceAdapter.
6
+ */
7
+ function createPersistenceAdapter(definition) {
8
+ return definition;
16
9
  }
17
- export {
18
- get as default
19
- };
10
+ //#endregion
11
+ export { createPersistenceAdapter as default };
@@ -0,0 +1,81 @@
1
+ const require_createPersistenceAdapter = require("./index24.cjs.js");
2
+ //#region src/persistence/combinePersistenceAdapters.ts
3
+ /**
4
+ * Creates a function that executes two asynchronous functions sequentially.
5
+ * The first function is tried first, and if it resolves, its value is used.
6
+ * If the first function fails or a fallback is required, the second function is executed.
7
+ * An optional cache mechanism can store the result temporarily to improve performance.
8
+ * @template Arguments - The argument types for the promise functions.
9
+ * @template ReturnValue - The return value type of the promise functions.
10
+ * @param firstResolvingPromiseFunction - The primary promise-based function to execute.
11
+ * @param secondResolvingPromiseFunction - The secondary fallback promise-based function to execute.
12
+ * @param [options] - Optional configuration.
13
+ * @param [options.onResolve] - Callback executed when a promise resolves.
14
+ * @param [options.cacheTimeout] - Time (in ms) to cache the resolved result.
15
+ * @returns A function that executes the two promises as described.
16
+ */
17
+ function createTemporaryFallbackExecutor(firstResolvingPromiseFunction, secondResolvingPromiseFunction, options) {
18
+ const cacheTimeout = options?.cacheTimeout ?? 0;
19
+ let isResolved = false;
20
+ let resolvedValue = null;
21
+ let timeout = null;
22
+ let secondaryPromise = null;
23
+ return (...args) => {
24
+ if (secondaryPromise == null) {
25
+ if (timeout) {
26
+ clearTimeout(timeout);
27
+ timeout = null;
28
+ }
29
+ secondaryPromise = secondResolvingPromiseFunction(...args).then((result) => {
30
+ if (cacheTimeout > 0) timeout = setTimeout(() => {
31
+ isResolved = false;
32
+ resolvedValue = null;
33
+ secondaryPromise = null;
34
+ }, cacheTimeout);
35
+ isResolved = true;
36
+ resolvedValue = result;
37
+ if (options?.onResolve) options.onResolve(resolvedValue);
38
+ return result;
39
+ });
40
+ } else if (isResolved) return secondaryPromise;
41
+ return firstResolvingPromiseFunction(...args);
42
+ };
43
+ }
44
+ /**
45
+ * Combines two persistence adapters (fast and slow) into a single interface.
46
+ * The fast adapter is used for quick read and write operations, while the slow adapter
47
+ * ensures data persistence and durability. The adapters sync automatically on read and save operations.
48
+ * @template T - The type of the persisted data items.
49
+ * @template I - The type of the identifier for persisted data items.
50
+ * @param slowAdapter - The slow persistence adapter for long-term storage.
51
+ * @param fastAdapter - The fast persistence adapter for quick access.
52
+ * @returns A combined persistence adapter that manages synchronization between the two adapters.
53
+ */
54
+ function combinePersistenceAdapters(slowAdapter, fastAdapter) {
55
+ let handleChange = null;
56
+ const readExecutor = createTemporaryFallbackExecutor(() => fastAdapter.load(), () => slowAdapter.load(), {
57
+ cacheTimeout: 100,
58
+ onResolve: (result) => {
59
+ if (handleChange) handleChange();
60
+ fastAdapter.save(result.items || [], {
61
+ added: result.changes?.added || [],
62
+ modified: result.changes?.modified || [],
63
+ removed: result.changes?.removed || []
64
+ });
65
+ }
66
+ });
67
+ return require_createPersistenceAdapter.default({
68
+ async register(onChange) {
69
+ handleChange = onChange;
70
+ await Promise.all([slowAdapter.register(onChange), fastAdapter.register(onChange)]);
71
+ },
72
+ async load() {
73
+ return readExecutor();
74
+ },
75
+ async save(items, changes) {
76
+ await Promise.all([fastAdapter.save(items, changes), slowAdapter.save(items, changes)]);
77
+ }
78
+ });
79
+ }
80
+ //#endregion
81
+ exports.default = combinePersistenceAdapters;
package/dist/index25.mjs CHANGED
@@ -1,30 +1,81 @@
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
+ import createPersistenceAdapter from "./index24.mjs";
2
+ //#region src/persistence/combinePersistenceAdapters.ts
3
+ /**
4
+ * Creates a function that executes two asynchronous functions sequentially.
5
+ * The first function is tried first, and if it resolves, its value is used.
6
+ * If the first function fails or a fallback is required, the second function is executed.
7
+ * An optional cache mechanism can store the result temporarily to improve performance.
8
+ * @template Arguments - The argument types for the promise functions.
9
+ * @template ReturnValue - The return value type of the promise functions.
10
+ * @param firstResolvingPromiseFunction - The primary promise-based function to execute.
11
+ * @param secondResolvingPromiseFunction - The secondary fallback promise-based function to execute.
12
+ * @param [options] - Optional configuration.
13
+ * @param [options.onResolve] - Callback executed when a promise resolves.
14
+ * @param [options.cacheTimeout] - Time (in ms) to cache the resolved result.
15
+ * @returns A function that executes the two promises as described.
16
+ */
17
+ function createTemporaryFallbackExecutor(firstResolvingPromiseFunction, secondResolvingPromiseFunction, options) {
18
+ const cacheTimeout = options?.cacheTimeout ?? 0;
19
+ let isResolved = false;
20
+ let resolvedValue = null;
21
+ let timeout = null;
22
+ let secondaryPromise = null;
23
+ return (...args) => {
24
+ if (secondaryPromise == null) {
25
+ if (timeout) {
26
+ clearTimeout(timeout);
27
+ timeout = null;
28
+ }
29
+ secondaryPromise = secondResolvingPromiseFunction(...args).then((result) => {
30
+ if (cacheTimeout > 0) timeout = setTimeout(() => {
31
+ isResolved = false;
32
+ resolvedValue = null;
33
+ secondaryPromise = null;
34
+ }, cacheTimeout);
35
+ isResolved = true;
36
+ resolvedValue = result;
37
+ if (options?.onResolve) options.onResolve(resolvedValue);
38
+ return result;
39
+ });
40
+ } else if (isResolved) return secondaryPromise;
41
+ return firstResolvingPromiseFunction(...args);
42
+ };
27
43
  }
28
- export {
29
- set as default
30
- };
44
+ /**
45
+ * Combines two persistence adapters (fast and slow) into a single interface.
46
+ * The fast adapter is used for quick read and write operations, while the slow adapter
47
+ * ensures data persistence and durability. The adapters sync automatically on read and save operations.
48
+ * @template T - The type of the persisted data items.
49
+ * @template I - The type of the identifier for persisted data items.
50
+ * @param slowAdapter - The slow persistence adapter for long-term storage.
51
+ * @param fastAdapter - The fast persistence adapter for quick access.
52
+ * @returns A combined persistence adapter that manages synchronization between the two adapters.
53
+ */
54
+ function combinePersistenceAdapters(slowAdapter, fastAdapter) {
55
+ let handleChange = null;
56
+ const readExecutor = createTemporaryFallbackExecutor(() => fastAdapter.load(), () => slowAdapter.load(), {
57
+ cacheTimeout: 100,
58
+ onResolve: (result) => {
59
+ if (handleChange) handleChange();
60
+ fastAdapter.save(result.items || [], {
61
+ added: result.changes?.added || [],
62
+ modified: result.changes?.modified || [],
63
+ removed: result.changes?.removed || []
64
+ });
65
+ }
66
+ });
67
+ return createPersistenceAdapter({
68
+ async register(onChange) {
69
+ handleChange = onChange;
70
+ await Promise.all([slowAdapter.register(onChange), fastAdapter.register(onChange)]);
71
+ },
72
+ async load() {
73
+ return readExecutor();
74
+ },
75
+ async save(items, changes) {
76
+ await Promise.all([fastAdapter.save(items, changes), slowAdapter.save(items, changes)]);
77
+ }
78
+ });
79
+ }
80
+ //#endregion
81
+ export { combinePersistenceAdapters as default };
@@ -0,0 +1,98 @@
1
+ const require_createSignal = require("./index16.cjs.js");
2
+ const require_index = require("./index23.cjs.js");
3
+ const require_createPersistenceAdapter = require("./index24.cjs.js");
4
+ const require_combinePersistenceAdapters = require("./index25.cjs.js");
5
+ //#region src/ReplicatedCollection.ts
6
+ /**
7
+ * Creates a persistence adapter for replicating a collection, enabling pull and push
8
+ * operations for synchronizing with a remote source. Supports optional remote change registration.
9
+ * @template T - The type of the items being replicated.
10
+ * @template I - The type of the unique identifier for the items.
11
+ * @param options - The options for configuring the replication adapter.
12
+ * @param options.pull - A function to fetch data from the remote source.
13
+ * @param options.push - An optional function to send changes and items to the remote source.
14
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
15
+ * @returns A persistence adapter configured for replication.
16
+ */
17
+ function createReplicationAdapter(options) {
18
+ return require_createPersistenceAdapter.default({
19
+ async register(onChange) {
20
+ if (!options.registerRemoteChange) return;
21
+ await options.registerRemoteChange(onChange);
22
+ },
23
+ load: () => options.pull(),
24
+ save: (items, changes) => {
25
+ if (!options.push) throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
26
+ return options.push(changes, items);
27
+ }
28
+ });
29
+ }
30
+ /**
31
+ * Extends the `Collection` class to support replication with remote sources.
32
+ * Handles pull and push operations, remote change registration, and enhanced loading states.
33
+ * @template T - The type of the items in the collection.
34
+ * @template I - The type of the unique identifier for the items.
35
+ * @template U - The transformed item type after applying transformations (default is T).
36
+ */
37
+ var ReplicatedCollection = class extends require_index.default {
38
+ isPullingRemoteSignal;
39
+ isPushingRemoteSignal;
40
+ /**
41
+ * Creates a new instance of the `ReplicatedCollection` class.
42
+ * Sets up the replication adapter, combining it with an optional persistence adapter, and
43
+ * initializes signals for tracking remote pull and push operations.
44
+ * @param options - The configuration options for the replicated collection.
45
+ * @param options.pull - A function to fetch data from the remote source.
46
+ * @param options.push - An optional function to send changes and items to the remote source.
47
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
48
+ * @param options.persistence - An optional persistence adapter to combine with replication.
49
+ * @param options.reactivity - A reactivity adapter for observing changes in the collection.
50
+ * @param options.transform - A transformation function to apply to items when retrieving them.
51
+ * @param options.indices - An array of index providers for optimized querying.
52
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
53
+ */
54
+ constructor(options) {
55
+ const replicationAdapter = createReplicationAdapter({
56
+ registerRemoteChange: options.registerRemoteChange,
57
+ pull: async () => {
58
+ this.isPullingRemoteSignal.set(true);
59
+ try {
60
+ return await options.pull();
61
+ } finally {
62
+ this.isPullingRemoteSignal.set(false);
63
+ }
64
+ },
65
+ push: options.push ? async (changes, items) => {
66
+ if (!options.push) throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
67
+ this.isPushingRemoteSignal.set(true);
68
+ try {
69
+ await options.push(changes, items);
70
+ } finally {
71
+ this.isPushingRemoteSignal.set(false);
72
+ }
73
+ } : void 0
74
+ });
75
+ const persistenceAdapter = options?.persistence ? require_combinePersistenceAdapters.default(replicationAdapter, options.persistence) : replicationAdapter;
76
+ super({
77
+ ...options,
78
+ persistence: persistenceAdapter
79
+ });
80
+ this.isPullingRemoteSignal = require_createSignal.default(options.reactivity, false);
81
+ this.isPushingRemoteSignal = require_createSignal.default(options.reactivity, false);
82
+ }
83
+ /**
84
+ * Checks whether the collection is currently performing any loading operation,
85
+ * including pulling or pushing data from/to the remote source, or standard
86
+ * persistence adapter operations.
87
+ * ⚡️ this function is reactive!
88
+ * @returns A boolean indicating if the collection is currently loading or synchronizing.
89
+ */
90
+ isLoading() {
91
+ const isPullingRemote = this.isPullingRemoteSignal.get();
92
+ const isPushingRemote = this.isPushingRemoteSignal.get();
93
+ const isLoading = super.isLoading();
94
+ return isPullingRemote || isPushingRemote || isLoading;
95
+ }
96
+ };
97
+ //#endregion
98
+ exports.default = ReplicatedCollection;
package/dist/index26.mjs CHANGED
@@ -1,10 +1,98 @@
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
- });
1
+ import createSignal from "./index16.mjs";
2
+ import Collection from "./index23.mjs";
3
+ import createPersistenceAdapter from "./index24.mjs";
4
+ import combinePersistenceAdapters from "./index25.mjs";
5
+ //#region src/ReplicatedCollection.ts
6
+ /**
7
+ * Creates a persistence adapter for replicating a collection, enabling pull and push
8
+ * operations for synchronizing with a remote source. Supports optional remote change registration.
9
+ * @template T - The type of the items being replicated.
10
+ * @template I - The type of the unique identifier for the items.
11
+ * @param options - The options for configuring the replication adapter.
12
+ * @param options.pull - A function to fetch data from the remote source.
13
+ * @param options.push - An optional function to send changes and items to the remote source.
14
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
15
+ * @returns A persistence adapter configured for replication.
16
+ */
17
+ function createReplicationAdapter(options) {
18
+ return createPersistenceAdapter({
19
+ async register(onChange) {
20
+ if (!options.registerRemoteChange) return;
21
+ await options.registerRemoteChange(onChange);
22
+ },
23
+ load: () => options.pull(),
24
+ save: (items, changes) => {
25
+ if (!options.push) throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
26
+ return options.push(changes, items);
27
+ }
28
+ });
7
29
  }
8
- export {
9
- uniqueBy as default
30
+ /**
31
+ * Extends the `Collection` class to support replication with remote sources.
32
+ * Handles pull and push operations, remote change registration, and enhanced loading states.
33
+ * @template T - The type of the items in the collection.
34
+ * @template I - The type of the unique identifier for the items.
35
+ * @template U - The transformed item type after applying transformations (default is T).
36
+ */
37
+ var ReplicatedCollection = class extends Collection {
38
+ isPullingRemoteSignal;
39
+ isPushingRemoteSignal;
40
+ /**
41
+ * Creates a new instance of the `ReplicatedCollection` class.
42
+ * Sets up the replication adapter, combining it with an optional persistence adapter, and
43
+ * initializes signals for tracking remote pull and push operations.
44
+ * @param options - The configuration options for the replicated collection.
45
+ * @param options.pull - A function to fetch data from the remote source.
46
+ * @param options.push - An optional function to send changes and items to the remote source.
47
+ * @param options.registerRemoteChange - An optional function to register a listener for remote changes.
48
+ * @param options.persistence - An optional persistence adapter to combine with replication.
49
+ * @param options.reactivity - A reactivity adapter for observing changes in the collection.
50
+ * @param options.transform - A transformation function to apply to items when retrieving them.
51
+ * @param options.indices - An array of index providers for optimized querying.
52
+ * @param options.enableDebugMode - A boolean to enable or disable debug mode.
53
+ */
54
+ constructor(options) {
55
+ const replicationAdapter = createReplicationAdapter({
56
+ registerRemoteChange: options.registerRemoteChange,
57
+ pull: async () => {
58
+ this.isPullingRemoteSignal.set(true);
59
+ try {
60
+ return await options.pull();
61
+ } finally {
62
+ this.isPullingRemoteSignal.set(false);
63
+ }
64
+ },
65
+ push: options.push ? async (changes, items) => {
66
+ if (!options.push) throw new Error("Pushing is not configured for this collection. Try to pass a `push` function to the collection options.");
67
+ this.isPushingRemoteSignal.set(true);
68
+ try {
69
+ await options.push(changes, items);
70
+ } finally {
71
+ this.isPushingRemoteSignal.set(false);
72
+ }
73
+ } : void 0
74
+ });
75
+ const persistenceAdapter = options?.persistence ? combinePersistenceAdapters(replicationAdapter, options.persistence) : replicationAdapter;
76
+ super({
77
+ ...options,
78
+ persistence: persistenceAdapter
79
+ });
80
+ this.isPullingRemoteSignal = createSignal(options.reactivity, false);
81
+ this.isPushingRemoteSignal = createSignal(options.reactivity, false);
82
+ }
83
+ /**
84
+ * Checks whether the collection is currently performing any loading operation,
85
+ * including pulling or pushing data from/to the remote source, or standard
86
+ * persistence adapter operations.
87
+ * ⚡️ this function is reactive!
88
+ * @returns A boolean indicating if the collection is currently loading or synchronizing.
89
+ */
90
+ isLoading() {
91
+ const isPullingRemote = this.isPullingRemoteSignal.get();
92
+ const isPushingRemote = this.isPushingRemoteSignal.get();
93
+ const isLoading = super.isLoading();
94
+ return isPullingRemote || isPushingRemote || isLoading;
95
+ }
10
96
  };
97
+ //#endregion
98
+ export { ReplicatedCollection as default };
@@ -0,0 +1,154 @@
1
+ const require_createSignal = require("./index16.cjs.js");
2
+ const require_ReplicatedCollection = require("./index26.cjs.js");
3
+ //#region src/AutoFetchCollection.ts
4
+ /**
5
+ * A special collection that automatically fetches items when they are needed.
6
+ */
7
+ var AutoFetchCollection = class extends require_ReplicatedCollection.default {
8
+ activeObservers = /* @__PURE__ */ new Map();
9
+ observerTimeouts = /* @__PURE__ */ new Map();
10
+ purgeDelay;
11
+ idQueryCache = /* @__PURE__ */ new Map();
12
+ itemsCache = /* @__PURE__ */ new Map();
13
+ fetchQueryItems;
14
+ triggerReload = null;
15
+ reactivityAdapter = null;
16
+ loadingSignals = /* @__PURE__ */ new Map();
17
+ isFetchingSignal;
18
+ mergeItems;
19
+ /**
20
+ * @param options {Object} - Options for the collection.
21
+ * @param options.fetchQueryItems {Function} - A function that fetches items from the server. It takes the selector as an argument and returns a promise that resolves to an object with an `items` property.
22
+ * @param options.purgeDelay {Number} - The delay in milliseconds before purging an item from the cache.
23
+ */
24
+ constructor(options) {
25
+ let triggerRemoteChange;
26
+ super({
27
+ ...options,
28
+ pull: () => Promise.resolve({ items: [...this.itemsCache.values()].reduce((memo, items) => {
29
+ const newItems = [...memo];
30
+ items.forEach((item) => {
31
+ const index = newItems.findIndex((i) => i.id === item.id);
32
+ if (index === -1) {
33
+ newItems.push(item);
34
+ return;
35
+ }
36
+ newItems[index] = this.mergeItems(newItems[index], item);
37
+ });
38
+ return newItems;
39
+ }, []) }),
40
+ registerRemoteChange: async (onChange) => {
41
+ triggerRemoteChange = onChange;
42
+ }
43
+ });
44
+ this.mergeItems = options.mergeItems ?? ((itemA, itemB) => ({
45
+ ...itemA,
46
+ ...itemB
47
+ }));
48
+ this.purgeDelay = options.purgeDelay ?? 1e4;
49
+ this.isFetchingSignal = require_createSignal.default(options.reactivity, false);
50
+ if (!triggerRemoteChange) throw new Error("No triggerRemoteChange method found. Looks like your persistence adapter was not registered");
51
+ this.triggerReload = triggerRemoteChange;
52
+ this.reactivityAdapter = options.reactivity ?? null;
53
+ this.fetchQueryItems = options.fetchQueryItems;
54
+ this.on("observer.created", (selector) => this.handleObserverCreation(selector ?? {}));
55
+ this.on("observer.disposed", (selector) => setTimeout(() => this.handleObserverDisposal(selector ?? {}), 100));
56
+ if (options.registerRemoteChange) options.registerRemoteChange(() => this.forceRefetch());
57
+ }
58
+ /**
59
+ * Registers a query manually that items should be fetched for it
60
+ * @param selector {Object} Selector of the query
61
+ */
62
+ registerQuery(selector) {
63
+ this.handleObserverCreation(selector);
64
+ }
65
+ /**
66
+ * Unregisters a query manually that items are not fetched anymore for it
67
+ * @param selector {Object} Selector of the query
68
+ */
69
+ unregisterQuery(selector) {
70
+ this.handleObserverDisposal(selector);
71
+ }
72
+ getKeyForSelector(selector) {
73
+ return JSON.stringify(selector);
74
+ }
75
+ async forceRefetch() {
76
+ return Promise.all([...this.activeObservers.values()].map(({ selector }) => this.fetchSelector(selector))).then(() => {});
77
+ }
78
+ fetchSelector(selector) {
79
+ this.isFetchingSignal.set(true);
80
+ return this.fetchQueryItems(selector).then((response) => {
81
+ if (!response.items) throw new Error("AutoFetchCollection currently only works with a full item response");
82
+ this.itemsCache.set(this.getKeyForSelector(selector), response.items);
83
+ response.items.forEach((item) => {
84
+ const queries = this.idQueryCache.get(item.id) ?? [];
85
+ queries.push(selector);
86
+ this.idQueryCache.set(item.id, queries);
87
+ });
88
+ this.setLoading(selector, true);
89
+ this.once("persistence.received", () => {
90
+ this.setLoading(selector, false);
91
+ });
92
+ if (!this.triggerReload) throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
93
+ this.triggerReload();
94
+ }).catch((error) => {
95
+ this.emit("persistence.error", error);
96
+ }).finally(() => {
97
+ this.isFetchingSignal.set(false);
98
+ });
99
+ }
100
+ handleObserverCreation(selector) {
101
+ const activeObservers = this.activeObservers.get(this.getKeyForSelector(selector))?.count ?? 0;
102
+ this.activeObservers.set(this.getKeyForSelector(selector), {
103
+ selector,
104
+ count: activeObservers + 1
105
+ });
106
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
107
+ if (timeout) clearTimeout(timeout);
108
+ if (activeObservers === 0) this.fetchSelector(selector);
109
+ }
110
+ handleObserverDisposal(selector) {
111
+ const activeObservers = (this.activeObservers.get(this.getKeyForSelector(selector))?.count ?? 0) - 1;
112
+ if (activeObservers > 0) {
113
+ this.activeObservers.set(this.getKeyForSelector(selector), {
114
+ selector,
115
+ count: activeObservers
116
+ });
117
+ return;
118
+ }
119
+ const timeout = this.observerTimeouts.get(this.getKeyForSelector(selector));
120
+ if (timeout) clearTimeout(timeout);
121
+ const removeObserver = () => {
122
+ this.activeObservers.delete(this.getKeyForSelector(selector));
123
+ this.itemsCache.delete(this.getKeyForSelector(selector));
124
+ if (!this.triggerReload) throw new Error("No triggerReload method found. Looks like your persistence adapter was not registered");
125
+ this.triggerReload();
126
+ };
127
+ if (this.purgeDelay === 0) {
128
+ removeObserver();
129
+ return;
130
+ }
131
+ this.observerTimeouts.set(this.getKeyForSelector(selector), setTimeout(removeObserver, this.purgeDelay));
132
+ }
133
+ ensureSignal(selector) {
134
+ if (!this.reactivityAdapter) throw new Error("No reactivity adapter found");
135
+ if (!this.loadingSignals.has(this.getKeyForSelector(selector))) this.loadingSignals.set(this.getKeyForSelector(selector), require_createSignal.default(this.reactivityAdapter, false));
136
+ return this.loadingSignals.get(this.getKeyForSelector(selector));
137
+ }
138
+ setLoading(selector, value) {
139
+ this.ensureSignal(selector).set(value);
140
+ }
141
+ /**
142
+ * Indicates wether a query is currently been loaded
143
+ * ⚡️ this function is reactive!
144
+ * @param selector {Object} Selector of the query
145
+ * @returns The loading state
146
+ */
147
+ isLoading(selector) {
148
+ const isPushing = this.isPushing();
149
+ if (!selector) return this.isFetchingSignal.get() || isPushing;
150
+ return this.ensureSignal(selector).get() || isPushing;
151
+ }
152
+ };
153
+ //#endregion
154
+ exports.default = AutoFetchCollection;