@evolu/common 6.0.1-preview.9 → 7.0.0

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 (184) hide show
  1. package/README.md +2 -2
  2. package/dist/src/Array.d.ts +256 -12
  3. package/dist/src/Array.d.ts.map +1 -1
  4. package/dist/src/Array.js +215 -9
  5. package/dist/src/Assert.d.ts +0 -13
  6. package/dist/src/Assert.d.ts.map +1 -1
  7. package/dist/src/Assert.js +0 -15
  8. package/dist/src/Brand.d.ts +75 -0
  9. package/dist/src/Brand.d.ts.map +1 -0
  10. package/dist/src/Brand.js +1 -0
  11. package/dist/src/Buffer.d.ts +1 -1
  12. package/dist/src/Buffer.d.ts.map +1 -1
  13. package/dist/src/Buffer.js +8 -7
  14. package/dist/src/Cache.d.ts +44 -0
  15. package/dist/src/Cache.d.ts.map +1 -0
  16. package/dist/src/Cache.js +52 -0
  17. package/dist/src/Callbacks.d.ts +45 -12
  18. package/dist/src/Callbacks.d.ts.map +1 -1
  19. package/dist/src/Callbacks.js +14 -7
  20. package/dist/src/Console.d.ts +31 -6
  21. package/dist/src/Console.d.ts.map +1 -1
  22. package/dist/src/Console.js +72 -9
  23. package/dist/src/Crypto.d.ts +56 -42
  24. package/dist/src/Crypto.d.ts.map +1 -1
  25. package/dist/src/Crypto.js +40 -53
  26. package/dist/src/Evolu/Db.d.ts +162 -74
  27. package/dist/src/Evolu/Db.d.ts.map +1 -1
  28. package/dist/src/Evolu/Db.js +284 -702
  29. package/dist/src/Evolu/Diff.d.ts +3 -3
  30. package/dist/src/Evolu/Diff.d.ts.map +1 -1
  31. package/dist/src/Evolu/Diff.js +7 -5
  32. package/dist/src/Evolu/Evolu.d.ts +213 -133
  33. package/dist/src/Evolu/Evolu.d.ts.map +1 -1
  34. package/dist/src/Evolu/Evolu.js +189 -180
  35. package/dist/src/Evolu/Internal.d.ts +0 -2
  36. package/dist/src/Evolu/Internal.d.ts.map +1 -1
  37. package/dist/src/Evolu/Internal.js +0 -2
  38. package/dist/src/Evolu/LocalAuth.d.ts +150 -0
  39. package/dist/src/Evolu/LocalAuth.d.ts.map +1 -0
  40. package/dist/src/Evolu/LocalAuth.js +174 -0
  41. package/dist/src/Evolu/Owner.d.ts +273 -120
  42. package/dist/src/Evolu/Owner.d.ts.map +1 -1
  43. package/dist/src/Evolu/Owner.js +130 -104
  44. package/dist/src/Evolu/Platform.d.ts +9 -7
  45. package/dist/src/Evolu/Platform.d.ts.map +1 -1
  46. package/dist/src/Evolu/Protocol.d.ts +268 -240
  47. package/dist/src/Evolu/Protocol.d.ts.map +1 -1
  48. package/dist/src/Evolu/Protocol.js +595 -447
  49. package/dist/src/Evolu/Public.d.ts +6 -8
  50. package/dist/src/Evolu/Public.d.ts.map +1 -1
  51. package/dist/src/Evolu/Public.js +2 -3
  52. package/dist/src/Evolu/PublicKysely.d.ts.map +1 -1
  53. package/dist/src/Evolu/PublicKysely.js +3 -4
  54. package/dist/src/Evolu/Query.d.ts +2 -1
  55. package/dist/src/Evolu/Query.d.ts.map +1 -1
  56. package/dist/src/Evolu/Query.js +1 -1
  57. package/dist/src/Evolu/Relay.d.ts +91 -8
  58. package/dist/src/Evolu/Relay.d.ts.map +1 -1
  59. package/dist/src/Evolu/Relay.js +214 -88
  60. package/dist/src/Evolu/Schema.d.ts +125 -47
  61. package/dist/src/Evolu/Schema.d.ts.map +1 -1
  62. package/dist/src/Evolu/Schema.js +175 -31
  63. package/dist/src/Evolu/Storage.d.ts +249 -27
  64. package/dist/src/Evolu/Storage.d.ts.map +1 -1
  65. package/dist/src/Evolu/Storage.js +198 -92
  66. package/dist/src/Evolu/Sync.d.ts +68 -13
  67. package/dist/src/Evolu/Sync.d.ts.map +1 -1
  68. package/dist/src/Evolu/Sync.js +469 -20
  69. package/dist/src/Evolu/Timestamp.d.ts +83 -30
  70. package/dist/src/Evolu/Timestamp.d.ts.map +1 -1
  71. package/dist/src/Evolu/Timestamp.js +79 -34
  72. package/dist/src/Identicon.d.ts +35 -0
  73. package/dist/src/Identicon.d.ts.map +1 -0
  74. package/dist/src/Identicon.js +143 -0
  75. package/dist/src/Instances.d.ts +34 -0
  76. package/dist/src/Instances.d.ts.map +1 -0
  77. package/dist/src/Instances.js +44 -0
  78. package/dist/src/Number.d.ts +4 -3
  79. package/dist/src/Number.d.ts.map +1 -1
  80. package/dist/src/Number.js +5 -4
  81. package/dist/src/Object.d.ts +10 -4
  82. package/dist/src/Object.d.ts.map +1 -1
  83. package/dist/src/Object.js +9 -3
  84. package/dist/src/Platform.d.ts +20 -0
  85. package/dist/src/Platform.d.ts.map +1 -0
  86. package/dist/src/Platform.js +22 -0
  87. package/dist/src/Random.d.ts +3 -2
  88. package/dist/src/Random.d.ts.map +1 -1
  89. package/dist/src/Relation.d.ts +79 -0
  90. package/dist/src/Relation.d.ts.map +1 -0
  91. package/dist/src/Relation.js +127 -0
  92. package/dist/src/Resources.d.ts +118 -0
  93. package/dist/src/Resources.d.ts.map +1 -0
  94. package/dist/src/Resources.js +197 -0
  95. package/dist/src/Result.d.ts +184 -52
  96. package/dist/src/Result.d.ts.map +1 -1
  97. package/dist/src/Result.js +30 -241
  98. package/dist/src/Skiplist.js +2 -1
  99. package/dist/src/Sqlite.d.ts +89 -5
  100. package/dist/src/Sqlite.d.ts.map +1 -1
  101. package/dist/src/Sqlite.js +136 -9
  102. package/dist/src/Task.d.ts +586 -0
  103. package/dist/src/Task.d.ts.map +1 -0
  104. package/dist/src/Task.js +469 -0
  105. package/dist/src/Time.d.ts +66 -1
  106. package/dist/src/Time.d.ts.map +1 -1
  107. package/dist/src/Time.js +99 -5
  108. package/dist/src/Type.d.ts +676 -343
  109. package/dist/src/Type.d.ts.map +1 -1
  110. package/dist/src/Type.js +718 -467
  111. package/dist/src/Types.d.ts +1 -75
  112. package/dist/src/Types.d.ts.map +1 -1
  113. package/dist/src/WebSocket.d.ts +5 -2
  114. package/dist/src/WebSocket.d.ts.map +1 -1
  115. package/dist/src/WebSocket.js +12 -18
  116. package/dist/src/Worker.d.ts +39 -11
  117. package/dist/src/Worker.d.ts.map +1 -1
  118. package/dist/src/Worker.js +22 -4
  119. package/dist/src/index.d.ts +8 -3
  120. package/dist/src/index.d.ts.map +1 -1
  121. package/dist/src/index.js +8 -3
  122. package/package.json +14 -13
  123. package/src/Array.ts +301 -19
  124. package/src/Assert.ts +0 -21
  125. package/src/Brand.ts +75 -0
  126. package/src/Buffer.ts +7 -7
  127. package/src/Cache.ts +85 -0
  128. package/src/Callbacks.ts +62 -22
  129. package/src/Console.ts +91 -11
  130. package/src/Crypto.ts +94 -90
  131. package/src/Evolu/Db.ts +519 -1026
  132. package/src/Evolu/Diff.ts +7 -5
  133. package/src/Evolu/Evolu.ts +476 -360
  134. package/src/Evolu/Internal.ts +0 -2
  135. package/src/Evolu/LocalAuth.ts +463 -0
  136. package/src/Evolu/Owner.ts +355 -228
  137. package/src/Evolu/Platform.ts +9 -9
  138. package/src/Evolu/Protocol.ts +846 -742
  139. package/src/Evolu/Public.ts +7 -14
  140. package/src/Evolu/PublicKysely.ts +4 -5
  141. package/src/Evolu/Query.ts +3 -2
  142. package/src/Evolu/Relay.ts +406 -103
  143. package/src/Evolu/Schema.ts +323 -91
  144. package/src/Evolu/Storage.ts +559 -137
  145. package/src/Evolu/Sync.ts +819 -36
  146. package/src/Evolu/Timestamp.ts +90 -58
  147. package/src/Identicon.ts +197 -0
  148. package/src/Instances.ts +90 -0
  149. package/src/Number.ts +6 -10
  150. package/src/Object.ts +13 -5
  151. package/src/Platform.ts +26 -0
  152. package/src/Random.ts +3 -2
  153. package/src/Relation.ts +234 -0
  154. package/src/Resources.ts +367 -0
  155. package/src/Result.ts +191 -54
  156. package/src/Skiplist.ts +1 -1
  157. package/src/Sqlite.ts +152 -17
  158. package/src/Task.ts +901 -0
  159. package/src/Time.ts +180 -5
  160. package/src/Type.ts +1135 -730
  161. package/src/Types.ts +1 -77
  162. package/src/WebSocket.ts +27 -25
  163. package/src/Worker.ts +72 -23
  164. package/src/index.ts +8 -3
  165. package/dist/src/Evolu/Config.d.ts +0 -69
  166. package/dist/src/Evolu/Config.d.ts.map +0 -1
  167. package/dist/src/Evolu/Config.js +0 -9
  168. package/dist/src/Evolu/Kysely.d.ts +0 -6
  169. package/dist/src/Evolu/Kysely.d.ts.map +0 -1
  170. package/dist/src/Evolu/Kysely.js +0 -21
  171. package/dist/src/ManyToManyMap.d.ts +0 -26
  172. package/dist/src/ManyToManyMap.d.ts.map +0 -1
  173. package/dist/src/ManyToManyMap.js +0 -92
  174. package/dist/src/NanoId.d.ts +0 -27
  175. package/dist/src/NanoId.d.ts.map +0 -1
  176. package/dist/src/NanoId.js +0 -6
  177. package/dist/src/Promise.d.ts +0 -180
  178. package/dist/src/Promise.d.ts.map +0 -1
  179. package/dist/src/Promise.js +0 -176
  180. package/src/Evolu/Config.ts +0 -83
  181. package/src/Evolu/Kysely.ts +0 -38
  182. package/src/ManyToManyMap.ts +0 -140
  183. package/src/NanoId.ts +0 -39
  184. package/src/Promise.ts +0 -295
@@ -0,0 +1,234 @@
1
+ import { assert } from "./Assert.js";
2
+
3
+ /**
4
+ * Bidirectional relation between two types.
5
+ *
6
+ * Why useful:
7
+ *
8
+ * - Provides O(1) (amortized) lookup in both directions (A → B and B → A) without
9
+ * maintaining two maps manually and risking them diverging.
10
+ * - Natural fit for symmetric associations such as ownerId ↔ WebSocket, tag ↔
11
+ * item, user ↔ role, entity ↔ subscription where both directions are
12
+ * frequently queried.
13
+ * - Supports fast membership tests via `has`, `hasA`, and `hasB`.
14
+ * - Iteration helpers (`forEach`, iterator) allow treating the structure as a set
15
+ * of pairs when needed.
16
+ *
17
+ * Complexity:
18
+ *
19
+ * - `add` / `remove` / `has*` / `get*` each perform a constant number of Map/Set
20
+ * operations (O(1) expected).
21
+ * - `deleteA` and `deleteB` are O(d) where d is the number of associated elements
22
+ * (the degree). This is optimal because every associated pair must be touched
23
+ * once.
24
+ *
25
+ * Object identity:
26
+ *
27
+ * - Elements are compared by reference (standard Map / Set semantics). Structural
28
+ * hashing of objects in JavaScript is non-trivial, can be expensive, and
29
+ * collision-prone if done naively. Prefer using stable primitive identifiers
30
+ * (ids, strings) instead of attempting to hash full object structures.
31
+ * - If structural equivalence is truly required, wrap objects in an adapter that
32
+ * supplies a canonical hash/id and stores/retrieves the original objects
33
+ * separately. This is a rare need; avoid unless you have clear requirements.
34
+ */
35
+ export interface Relation<A, B> {
36
+ /**
37
+ * Adds a pair to the relation. Returns true if the pair was newly added,
38
+ * false if it already existed.
39
+ */
40
+ readonly add: (a: A, b: B) => boolean;
41
+
42
+ /**
43
+ * Removes a specific pair from the relation. Returns true if the pair existed
44
+ * and was removed, false if it was not present.
45
+ */
46
+ readonly remove: (a: A, b: B) => boolean;
47
+
48
+ /** Gets all B elements related to an A element. */
49
+ readonly getB: (a: A) => ReadonlySet<B> | undefined;
50
+
51
+ /** Gets all A elements related to a B element. */
52
+ readonly getA: (b: B) => ReadonlySet<A> | undefined;
53
+
54
+ /**
55
+ * Iterates over each pair in the relation (in insertion order of A elements,
56
+ * then B elements per A).
57
+ */
58
+ readonly forEach: (callback: (a: A, b: B) => void) => void;
59
+
60
+ /**
61
+ * Iterator over all pairs enabling for..of and spread. Yields readonly [a, b]
62
+ * tuples.
63
+ */
64
+ readonly [Symbol.iterator]: () => IterableIterator<readonly [A, B]>;
65
+
66
+ /** Checks if a specific pair exists in the relation. */
67
+ readonly has: (a: A, b: B) => boolean;
68
+
69
+ /** Checks if an A element exists in the relation. */
70
+ readonly hasA: (a: A) => boolean;
71
+
72
+ /** Checks if a B element exists in the relation. */
73
+ readonly hasB: (b: B) => boolean;
74
+
75
+ /** Deletes all pairs containing the given A element. */
76
+ readonly deleteA: (a: A) => boolean;
77
+
78
+ /** Deletes all pairs containing the given B element. */
79
+ readonly deleteB: (b: B) => boolean;
80
+
81
+ /** Clears all pairs from the relation. */
82
+ readonly clear: () => void;
83
+
84
+ /** Number of distinct A elements currently present. */
85
+ readonly aCount: () => number;
86
+
87
+ /** Number of distinct B elements currently present. */
88
+ readonly bCount: () => number;
89
+
90
+ /** Number of pairs currently stored in the relation. */
91
+ readonly size: () => number;
92
+ }
93
+
94
+ /** Creates a {@link Relation}. */
95
+ export const createRelation = <A, B>(): Relation<A, B> => {
96
+ const aToB = new Map<A, Set<B>>();
97
+ const bToA = new Map<B, Set<A>>();
98
+ let sizeInternal = 0;
99
+
100
+ const relation: Relation<A, B> = {
101
+ add(a: A, b: B) {
102
+ let bSet = aToB.get(a);
103
+ if (bSet?.has(b)) return false;
104
+ if (!bSet) {
105
+ bSet = new Set<B>();
106
+ aToB.set(a, bSet);
107
+ }
108
+ bSet.add(b);
109
+
110
+ let aSet = bToA.get(b);
111
+ if (!aSet) {
112
+ aSet = new Set<A>();
113
+ bToA.set(b, aSet);
114
+ }
115
+ aSet.add(a);
116
+ sizeInternal++;
117
+ return true;
118
+ },
119
+
120
+ remove(a: A, b: B) {
121
+ const bSet = aToB.get(a);
122
+ if (!bSet?.has(b)) return false;
123
+
124
+ bSet.delete(b);
125
+ if (bSet.size === 0) {
126
+ aToB.delete(a);
127
+ }
128
+
129
+ const aSet = bToA.get(b);
130
+ assert(aSet, "Relation mapping inconsistency");
131
+
132
+ aSet.delete(a);
133
+ if (aSet.size === 0) {
134
+ bToA.delete(b);
135
+ }
136
+ sizeInternal--;
137
+ return true;
138
+ },
139
+
140
+ getB(a: A): ReadonlySet<B> | undefined {
141
+ return aToB.get(a);
142
+ },
143
+
144
+ getA(b: B): ReadonlySet<A> | undefined {
145
+ return bToA.get(b);
146
+ },
147
+
148
+ forEach(callback: (a: A, b: B) => void) {
149
+ for (const [a, bSet] of aToB) {
150
+ for (const b of bSet) callback(a, b);
151
+ }
152
+ },
153
+
154
+ [Symbol.iterator](): IterableIterator<readonly [A, B]> {
155
+ const iterator = function* () {
156
+ for (const [a, bSet] of aToB) {
157
+ for (const b of bSet) {
158
+ yield [a, b] as const;
159
+ }
160
+ }
161
+ };
162
+ return iterator();
163
+ },
164
+
165
+ has(a: A, b: B) {
166
+ const bSet = aToB.get(a);
167
+ return bSet?.has(b) ?? false;
168
+ },
169
+
170
+ hasA(a: A) {
171
+ return aToB.has(a);
172
+ },
173
+
174
+ hasB(b: B) {
175
+ return bToA.has(b);
176
+ },
177
+
178
+ deleteA(a: A) {
179
+ const bSet = aToB.get(a);
180
+ if (!bSet) return false;
181
+ const removed = bSet.size;
182
+ for (const b of bSet) {
183
+ const aSet = bToA.get(b);
184
+ if (aSet) {
185
+ aSet.delete(a);
186
+ if (aSet.size === 0) {
187
+ bToA.delete(b);
188
+ }
189
+ }
190
+ }
191
+ aToB.delete(a);
192
+ sizeInternal -= removed;
193
+ return true;
194
+ },
195
+
196
+ deleteB(b: B) {
197
+ const aSet = bToA.get(b);
198
+ if (!aSet) return false;
199
+ const removed = aSet.size;
200
+ for (const a of aSet) {
201
+ const bSet = aToB.get(a);
202
+ if (bSet) {
203
+ bSet.delete(b);
204
+ if (bSet.size === 0) {
205
+ aToB.delete(a);
206
+ }
207
+ }
208
+ }
209
+ bToA.delete(b);
210
+ sizeInternal -= removed;
211
+ return true;
212
+ },
213
+
214
+ clear() {
215
+ aToB.clear();
216
+ bToA.clear();
217
+ sizeInternal = 0;
218
+ },
219
+
220
+ aCount() {
221
+ return aToB.size;
222
+ },
223
+
224
+ bCount() {
225
+ return bToA.size;
226
+ },
227
+
228
+ size() {
229
+ return sizeInternal;
230
+ },
231
+ };
232
+
233
+ return relation;
234
+ };
@@ -0,0 +1,367 @@
1
+ import { err, ok, Result } from "./Result.js";
2
+ import { PositiveInt } from "./Type.js";
3
+
4
+ /**
5
+ * A generic resource manager that handles reference counting and delayed
6
+ * disposal of shared resources. Useful for managing expensive resources like
7
+ * WebSocket connections that need to be shared among multiple consumers.
8
+ */
9
+ export interface Resources<
10
+ TResource extends Disposable,
11
+ TResourceKey extends string,
12
+ TResourceConfig,
13
+ TConsumer,
14
+ TConsumerId extends string,
15
+ > extends Disposable {
16
+ /**
17
+ * Adds a consumer to resources, creating them if necessary. Increments
18
+ * reference counts for existing consumer-resource pairs.
19
+ */
20
+ readonly addConsumer: (
21
+ consumer: TConsumer,
22
+ resourceConfigs: ReadonlyArray<TResourceConfig>,
23
+ ) => void;
24
+
25
+ /**
26
+ * Removes a consumer from resources. Decrements reference counts and
27
+ * schedules disposal when no consumers remain.
28
+ *
29
+ * Returns an error if the resource doesn't exist or if the consumer wasn't
30
+ * added to the resource.
31
+ */
32
+ readonly removeConsumer: (
33
+ consumer: TConsumer,
34
+ resourceConfigs: ReadonlyArray<TResourceConfig>,
35
+ ) => Result<
36
+ void,
37
+ | ResourceNotFoundError<TResourceKey>
38
+ | ConsumerNotFoundError<TConsumerId, TResourceKey>
39
+ >;
40
+
41
+ /** Gets the resource for the specified key, or null if it doesn't exist. */
42
+ readonly getResource: (key: TResourceKey) => TResource | null;
43
+
44
+ /** Gets all consumer IDs currently using the specified resource key. */
45
+ readonly getConsumersForResource: (
46
+ key: TResourceKey,
47
+ ) => ReadonlyArray<TConsumerId>;
48
+
49
+ /** Checks if a consumer is currently using any resources. */
50
+ readonly hasConsumerAnyResource: (consumer: TConsumer) => boolean;
51
+
52
+ /**
53
+ * Gets the consumer for the specified consumer ID, or null if not found or
54
+ * not using any resources.
55
+ */
56
+ readonly getConsumer: (consumerId: TConsumerId) => TConsumer | null;
57
+ }
58
+
59
+ /** Error when trying to remove a consumer from a resource that doesn't exist. */
60
+ export interface ResourceNotFoundError<TResourceKey extends string = string> {
61
+ readonly type: "ResourceNotFoundError";
62
+ readonly resourceKey: TResourceKey;
63
+ }
64
+
65
+ /** Error when trying to remove a consumer that wasn't added to a resource. */
66
+ export interface ConsumerNotFoundError<
67
+ TConsumerId extends string = string,
68
+ TResourceKey extends string = string,
69
+ > {
70
+ readonly type: "ConsumerNotFoundError";
71
+ readonly consumerId: TConsumerId;
72
+ readonly resourceKey: TResourceKey;
73
+ }
74
+
75
+ export interface ResourcesConfig<
76
+ TResource extends Disposable,
77
+ TResourceKey extends string,
78
+ TResourceConfig,
79
+ TConsumer,
80
+ TConsumerId extends string,
81
+ > {
82
+ /** Creates a new resource for the given config. */
83
+ readonly createResource: (config: TResourceConfig) => TResource;
84
+
85
+ /** Extracts a unique key from a resource config for deduplication. */
86
+ readonly getResourceKey: (config: TResourceConfig) => TResourceKey;
87
+
88
+ /** Extracts a unique identifier from a consumer for reference counting. */
89
+ readonly getConsumerId: (consumer: TConsumer) => TConsumerId;
90
+
91
+ /**
92
+ * Delay in milliseconds before disposing unused resources. Helps avoid
93
+ * resource churn during rapid add/remove cycles. Defaults to 100ms.
94
+ */
95
+ readonly disposalDelay?: number;
96
+
97
+ /**
98
+ * Called when a consumer is added to a resource for the first time. This
99
+ * happens when the consumer's reference count goes from 0 to 1 for this
100
+ * resource.
101
+ */
102
+ readonly onConsumerAdded?: (
103
+ consumer: TConsumer,
104
+ resource: TResource,
105
+ resourceKey: TResourceKey,
106
+ ) => void;
107
+
108
+ /**
109
+ * Called when a consumer is completely removed from a resource. This happens
110
+ * when the consumer's reference count goes from 1 to 0 for this resource.
111
+ */
112
+ readonly onConsumerRemoved?: (
113
+ consumer: TConsumer,
114
+ resource: TResource,
115
+ resourceKey: TResourceKey,
116
+ ) => void;
117
+ }
118
+
119
+ /**
120
+ * Creates {@link Resources}.
121
+ *
122
+ * This tracks which consumers are using which resources and maintains reference
123
+ * counts to know when it's safe to dispose resources. Resources are created
124
+ * on-demand and disposed with a configurable delay to avoid churn.
125
+ *
126
+ * ### Example Usage
127
+ *
128
+ * ```ts
129
+ * // WebSocket connections
130
+ * interface WebSocketConfig {
131
+ * readonly url: WebSocketUrl;
132
+ * }
133
+ *
134
+ * type WebSocketUrl = string & Brand<"WebSocketUrl">;
135
+ * type UserId = string & Brand<"UserId">;
136
+ *
137
+ * const webSockets = createResources<
138
+ * WebSocket,
139
+ * WebSocketUrl,
140
+ * WebSocketConfig,
141
+ * User,
142
+ * UserId
143
+ * >({
144
+ * createResource: (config) => new WebSocket(config.url),
145
+ * getResourceKey: (config) => config.url,
146
+ * getConsumerId: (user) => user.id,
147
+ * disposalDelay: 1000,
148
+ * });
149
+ *
150
+ * // Add users to WebSocket connections
151
+ * webSockets.addConsumer(user1, [
152
+ * { url: "ws://server1.com" as WebSocketUrl },
153
+ * { url: "ws://server2.com" as WebSocketUrl },
154
+ * ]);
155
+ * webSockets.addConsumer(user2, [
156
+ * { url: "ws://server1.com" as WebSocketUrl },
157
+ * ]);
158
+ *
159
+ * // Remove users - server1 stays alive (user2 still using it)
160
+ * webSockets.removeConsumer(user1, [
161
+ * { url: "ws://server1.com" as WebSocketUrl },
162
+ * { url: "ws://server2.com" as WebSocketUrl },
163
+ * ]);
164
+ *
165
+ * // server2 gets disposed after delay, server1 stays alive
166
+ * ```
167
+ */
168
+ export const createResources = <
169
+ TResource extends Disposable,
170
+ TResourceKey extends string,
171
+ TResourceConfig,
172
+ TConsumer,
173
+ TConsumerId extends string,
174
+ >(
175
+ config: ResourcesConfig<
176
+ TResource,
177
+ TResourceKey,
178
+ TResourceConfig,
179
+ TConsumer,
180
+ TConsumerId
181
+ >,
182
+ ): Resources<
183
+ TResource,
184
+ TResourceKey,
185
+ TResourceConfig,
186
+ TConsumer,
187
+ TConsumerId
188
+ > => {
189
+ let isDisposed = false;
190
+
191
+ const resourcesMap = new Map<TResourceKey, TResource>();
192
+ const consumerCounts = new Map<TResourceKey, Map<TConsumerId, PositiveInt>>();
193
+ const consumers = new Map<TConsumerId, TConsumer>();
194
+ const disposalTimeouts = new Map<
195
+ TResourceKey,
196
+ ReturnType<typeof setTimeout>
197
+ >();
198
+
199
+ const disposalDelay = config.disposalDelay ?? 100;
200
+
201
+ const ensureResource = (resourceConfig: TResourceConfig) => {
202
+ const key = config.getResourceKey(resourceConfig);
203
+ const timeout = disposalTimeouts.get(key);
204
+ if (timeout) {
205
+ clearTimeout(timeout);
206
+ disposalTimeouts.delete(key);
207
+ }
208
+
209
+ if (!resourcesMap.has(key)) {
210
+ const resource = config.createResource(resourceConfig);
211
+ resourcesMap.set(key, resource);
212
+ }
213
+ };
214
+
215
+ const scheduleDisposal = (key: TResourceKey): void => {
216
+ const timeout = setTimeout(() => {
217
+ const resource = resourcesMap.get(key);
218
+ if (resource) {
219
+ resource[Symbol.dispose]();
220
+ resourcesMap.delete(key);
221
+ }
222
+ disposalTimeouts.delete(key);
223
+ }, disposalDelay);
224
+
225
+ disposalTimeouts.set(key, timeout);
226
+ };
227
+
228
+ const resources: Resources<
229
+ TResource,
230
+ TResourceKey,
231
+ TResourceConfig,
232
+ TConsumer,
233
+ TConsumerId
234
+ > = {
235
+ addConsumer: (consumer, resourceConfigs) => {
236
+ if (isDisposed) return;
237
+
238
+ const consumerId = config.getConsumerId(consumer);
239
+
240
+ // Store consumer (last added consumer for this ID)
241
+ consumers.set(consumerId, consumer);
242
+
243
+ for (const resourceConfig of resourceConfigs) {
244
+ ensureResource(resourceConfig);
245
+ const resourceKey = config.getResourceKey(resourceConfig);
246
+
247
+ let counts = consumerCounts.get(resourceKey);
248
+ if (!counts) {
249
+ counts = new Map<TConsumerId, PositiveInt>();
250
+ consumerCounts.set(resourceKey, counts);
251
+ }
252
+
253
+ const currentCount = counts.get(consumerId) ?? 0;
254
+ const newCount = currentCount + 1;
255
+ counts.set(consumerId, PositiveInt.orThrow(newCount));
256
+
257
+ // Call onConsumerAdded callback only when consumer is added for the first time (0 -> 1)
258
+ if (currentCount === 0 && config.onConsumerAdded) {
259
+ const resource = resourcesMap.get(resourceKey);
260
+ if (resource) {
261
+ config.onConsumerAdded(consumer, resource, resourceKey);
262
+ }
263
+ }
264
+ }
265
+ },
266
+
267
+ removeConsumer: (consumer, resourceConfigs) => {
268
+ if (isDisposed) return ok();
269
+
270
+ const consumerId = config.getConsumerId(consumer);
271
+
272
+ for (const resourceConfig of resourceConfigs) {
273
+ const key = config.getResourceKey(resourceConfig);
274
+ const counts = consumerCounts.get(key);
275
+ if (!counts) {
276
+ return err({ type: "ResourceNotFoundError", resourceKey: key });
277
+ }
278
+
279
+ const currentCount = counts.get(consumerId);
280
+ if (currentCount == null) {
281
+ return err({
282
+ type: "ConsumerNotFoundError",
283
+ consumerId: consumerId,
284
+ resourceKey: key,
285
+ });
286
+ }
287
+
288
+ if (currentCount === 1) {
289
+ counts.delete(consumerId);
290
+
291
+ // Call onConsumerRemoved callback only when consumer is completely removed (1 -> 0)
292
+ if (config.onConsumerRemoved) {
293
+ const resource = resourcesMap.get(key);
294
+ if (resource) {
295
+ config.onConsumerRemoved(consumer, resource, key);
296
+ }
297
+ }
298
+
299
+ if (counts.size === 0) {
300
+ consumerCounts.delete(key);
301
+ scheduleDisposal(key);
302
+ }
303
+ } else {
304
+ counts.set(consumerId, PositiveInt.orThrow(currentCount - 1));
305
+ }
306
+ }
307
+
308
+ if (!resources.hasConsumerAnyResource(consumer)) {
309
+ consumers.delete(consumerId);
310
+ }
311
+
312
+ return ok();
313
+ },
314
+
315
+ getResource: (key) => {
316
+ if (isDisposed) return null;
317
+ return resourcesMap.get(key) ?? null;
318
+ },
319
+
320
+ getConsumersForResource: (key) => {
321
+ if (isDisposed) return [];
322
+ const counts = consumerCounts.get(key);
323
+ return counts ? Array.from(counts.keys()) : [];
324
+ },
325
+
326
+ hasConsumerAnyResource: (consumer) => {
327
+ if (isDisposed) return false;
328
+ const consumerId = config.getConsumerId(consumer);
329
+ // If slow, can be optimized with reverse index
330
+ return Array.from(consumerCounts.values()).some((counts) =>
331
+ counts.has(consumerId),
332
+ );
333
+ },
334
+
335
+ getConsumer: (consumerId) => {
336
+ if (isDisposed) return null;
337
+ const consumer = consumers.get(consumerId);
338
+ if (!consumer) return null;
339
+
340
+ // Only return consumer if it's currently using any resources
341
+ if (!resources.hasConsumerAnyResource(consumer)) {
342
+ return null;
343
+ }
344
+
345
+ return consumer;
346
+ },
347
+
348
+ [Symbol.dispose]: () => {
349
+ if (isDisposed) return;
350
+ isDisposed = true;
351
+
352
+ for (const timeout of disposalTimeouts.values()) {
353
+ clearTimeout(timeout);
354
+ }
355
+ disposalTimeouts.clear();
356
+
357
+ for (const resource of resourcesMap.values()) {
358
+ resource[Symbol.dispose]();
359
+ }
360
+ resourcesMap.clear();
361
+ consumerCounts.clear();
362
+ consumers.clear();
363
+ },
364
+ };
365
+
366
+ return resources;
367
+ };