@procedures/collections 0.0.0-stage → 0.2.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 (205) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +21 -0
  3. package/README.md +394 -2
  4. package/dist/.tsbuildinfo +1 -0
  5. package/dist/async/async-queue.d.ts +155 -0
  6. package/dist/async/async-queue.d.ts.map +1 -0
  7. package/dist/async/async-queue.js +342 -0
  8. package/dist/async/async-queue.js.map +1 -0
  9. package/dist/async/channels.d.ts +188 -0
  10. package/dist/async/channels.d.ts.map +1 -0
  11. package/dist/async/channels.js +314 -0
  12. package/dist/async/channels.js.map +1 -0
  13. package/dist/behaviors/bounded.d.ts +79 -0
  14. package/dist/behaviors/bounded.d.ts.map +1 -0
  15. package/dist/behaviors/bounded.js +384 -0
  16. package/dist/behaviors/bounded.js.map +1 -0
  17. package/dist/behaviors/composite.d.ts +17 -0
  18. package/dist/behaviors/composite.d.ts.map +1 -0
  19. package/dist/behaviors/composite.js +93 -0
  20. package/dist/behaviors/composite.js.map +1 -0
  21. package/dist/behaviors/evented.d.ts +154 -0
  22. package/dist/behaviors/evented.d.ts.map +1 -0
  23. package/dist/behaviors/evented.js +299 -0
  24. package/dist/behaviors/evented.js.map +1 -0
  25. package/dist/behaviors/lru.d.ts +84 -0
  26. package/dist/behaviors/lru.d.ts.map +1 -0
  27. package/dist/behaviors/lru.js +376 -0
  28. package/dist/behaviors/lru.js.map +1 -0
  29. package/dist/behaviors/readonly.d.ts +73 -0
  30. package/dist/behaviors/readonly.d.ts.map +1 -0
  31. package/dist/behaviors/readonly.js +177 -0
  32. package/dist/behaviors/readonly.js.map +1 -0
  33. package/dist/behaviors/safe.d.ts +163 -0
  34. package/dist/behaviors/safe.d.ts.map +1 -0
  35. package/dist/behaviors/safe.js +176 -0
  36. package/dist/behaviors/safe.js.map +1 -0
  37. package/dist/behaviors/synchronized.d.ts +88 -0
  38. package/dist/behaviors/synchronized.d.ts.map +1 -0
  39. package/dist/behaviors/synchronized.js +285 -0
  40. package/dist/behaviors/synchronized.js.map +1 -0
  41. package/dist/behaviors/ttl.d.ts +118 -0
  42. package/dist/behaviors/ttl.d.ts.map +1 -0
  43. package/dist/behaviors/ttl.js +354 -0
  44. package/dist/behaviors/ttl.js.map +1 -0
  45. package/dist/contracts/model.d.ts +29 -0
  46. package/dist/contracts/model.d.ts.map +1 -0
  47. package/dist/contracts/model.js +26 -0
  48. package/dist/contracts/model.js.map +1 -0
  49. package/dist/core/effects.d.ts +176 -0
  50. package/dist/core/effects.d.ts.map +1 -0
  51. package/dist/core/effects.js +180 -0
  52. package/dist/core/effects.js.map +1 -0
  53. package/dist/core/events.d.ts +192 -0
  54. package/dist/core/events.d.ts.map +1 -0
  55. package/dist/core/events.js +291 -0
  56. package/dist/core/events.js.map +1 -0
  57. package/dist/core/middleware.d.ts +231 -0
  58. package/dist/core/middleware.d.ts.map +1 -0
  59. package/dist/core/middleware.js +161 -0
  60. package/dist/core/middleware.js.map +1 -0
  61. package/dist/core/policies.d.ts +220 -0
  62. package/dist/core/policies.d.ts.map +1 -0
  63. package/dist/core/policies.js +48 -0
  64. package/dist/core/policies.js.map +1 -0
  65. package/dist/core/traits.d.ts +142 -0
  66. package/dist/core/traits.d.ts.map +1 -0
  67. package/dist/core/traits.js +8 -0
  68. package/dist/core/traits.js.map +1 -0
  69. package/dist/fx/collectors.d.ts +193 -0
  70. package/dist/fx/collectors.d.ts.map +1 -0
  71. package/dist/fx/collectors.js +375 -0
  72. package/dist/fx/collectors.js.map +1 -0
  73. package/dist/fx/iter.d.ts +166 -0
  74. package/dist/fx/iter.d.ts.map +1 -0
  75. package/dist/fx/iter.js +421 -0
  76. package/dist/fx/iter.js.map +1 -0
  77. package/dist/impl/array-deque.d.ts +112 -0
  78. package/dist/impl/array-deque.d.ts.map +1 -0
  79. package/dist/impl/array-deque.js +380 -0
  80. package/dist/impl/array-deque.js.map +1 -0
  81. package/dist/impl/array-list.d.ts +101 -0
  82. package/dist/impl/array-list.d.ts.map +1 -0
  83. package/dist/impl/array-list.js +387 -0
  84. package/dist/impl/array-list.js.map +1 -0
  85. package/dist/impl/hash-map.d.ts +149 -0
  86. package/dist/impl/hash-map.d.ts.map +1 -0
  87. package/dist/impl/hash-map.js +473 -0
  88. package/dist/impl/hash-map.js.map +1 -0
  89. package/dist/impl/hash-set.d.ts +125 -0
  90. package/dist/impl/hash-set.d.ts.map +1 -0
  91. package/dist/impl/hash-set.js +264 -0
  92. package/dist/impl/hash-set.js.map +1 -0
  93. package/dist/impl/linked-hash-map.d.ts +141 -0
  94. package/dist/impl/linked-hash-map.d.ts.map +1 -0
  95. package/dist/impl/linked-hash-map.js +442 -0
  96. package/dist/impl/linked-hash-map.js.map +1 -0
  97. package/dist/impl/linked-list.d.ts +109 -0
  98. package/dist/impl/linked-list.d.ts.map +1 -0
  99. package/dist/impl/linked-list.js +494 -0
  100. package/dist/impl/linked-list.js.map +1 -0
  101. package/dist/impl/priority-queue.d.ts +139 -0
  102. package/dist/impl/priority-queue.d.ts.map +1 -0
  103. package/dist/impl/priority-queue.js +343 -0
  104. package/dist/impl/priority-queue.js.map +1 -0
  105. package/dist/impl/tree-map.d.ts +153 -0
  106. package/dist/impl/tree-map.d.ts.map +1 -0
  107. package/dist/impl/tree-map.js +788 -0
  108. package/dist/impl/tree-map.js.map +1 -0
  109. package/dist/impl/tree-set.d.ts +112 -0
  110. package/dist/impl/tree-set.d.ts.map +1 -0
  111. package/dist/impl/tree-set.js +374 -0
  112. package/dist/impl/tree-set.js.map +1 -0
  113. package/dist/index.d.ts +106 -0
  114. package/dist/index.d.ts.map +1 -0
  115. package/dist/index.js +139 -0
  116. package/dist/index.js.map +1 -0
  117. package/dist/interfaces/collection.d.ts +119 -0
  118. package/dist/interfaces/collection.d.ts.map +1 -0
  119. package/dist/interfaces/collection.js +8 -0
  120. package/dist/interfaces/collection.js.map +1 -0
  121. package/dist/interfaces/list.d.ts +247 -0
  122. package/dist/interfaces/list.d.ts.map +1 -0
  123. package/dist/interfaces/list.js +8 -0
  124. package/dist/interfaces/list.js.map +1 -0
  125. package/dist/interfaces/map.d.ts +344 -0
  126. package/dist/interfaces/map.d.ts.map +1 -0
  127. package/dist/interfaces/map.js +8 -0
  128. package/dist/interfaces/map.js.map +1 -0
  129. package/dist/interfaces/queue.d.ts +304 -0
  130. package/dist/interfaces/queue.d.ts.map +1 -0
  131. package/dist/interfaces/queue.js +8 -0
  132. package/dist/interfaces/queue.js.map +1 -0
  133. package/dist/interfaces/set.d.ts +137 -0
  134. package/dist/interfaces/set.d.ts.map +1 -0
  135. package/dist/interfaces/set.js +8 -0
  136. package/dist/interfaces/set.js.map +1 -0
  137. package/dist/register.d.ts +8 -0
  138. package/dist/register.d.ts.map +1 -0
  139. package/dist/register.js +8 -0
  140. package/dist/register.js.map +1 -0
  141. package/dist/storage/index.d.ts +15 -0
  142. package/dist/storage/index.d.ts.map +1 -0
  143. package/dist/storage/index.js +14 -0
  144. package/dist/storage/index.js.map +1 -0
  145. package/dist/storage/interface.d.ts +141 -0
  146. package/dist/storage/interface.d.ts.map +1 -0
  147. package/dist/storage/interface.js +23 -0
  148. package/dist/storage/interface.js.map +1 -0
  149. package/dist/storage/memory.d.ts +68 -0
  150. package/dist/storage/memory.d.ts.map +1 -0
  151. package/dist/storage/memory.js +154 -0
  152. package/dist/storage/memory.js.map +1 -0
  153. package/dist/utils/defaults.d.ts +135 -0
  154. package/dist/utils/defaults.d.ts.map +1 -0
  155. package/dist/utils/defaults.js +322 -0
  156. package/dist/utils/defaults.js.map +1 -0
  157. package/dist/utils/factories.d.ts +144 -0
  158. package/dist/utils/factories.d.ts.map +1 -0
  159. package/dist/utils/factories.js +293 -0
  160. package/dist/utils/factories.js.map +1 -0
  161. package/dist/utils/helpers.d.ts +137 -0
  162. package/dist/utils/helpers.d.ts.map +1 -0
  163. package/dist/utils/helpers.js +221 -0
  164. package/dist/utils/helpers.js.map +1 -0
  165. package/package.json +68 -3
  166. package/src/async/async-queue.ts +417 -0
  167. package/src/async/channels.ts +374 -0
  168. package/src/behaviors/bounded.ts +477 -0
  169. package/src/behaviors/composite.ts +99 -0
  170. package/src/behaviors/evented.ts +464 -0
  171. package/src/behaviors/lru.ts +447 -0
  172. package/src/behaviors/readonly.ts +224 -0
  173. package/src/behaviors/safe.ts +372 -0
  174. package/src/behaviors/synchronized.ts +316 -0
  175. package/src/behaviors/ttl.ts +462 -0
  176. package/src/contracts/model.ts +44 -0
  177. package/src/core/effects.ts +323 -0
  178. package/src/core/events.ts +356 -0
  179. package/src/core/middleware.ts +415 -0
  180. package/src/core/policies.ts +316 -0
  181. package/src/core/traits.ts +164 -0
  182. package/src/fx/collectors.ts +500 -0
  183. package/src/fx/iter.ts +536 -0
  184. package/src/impl/array-deque.ts +463 -0
  185. package/src/impl/array-list.ts +490 -0
  186. package/src/impl/hash-map.ts +623 -0
  187. package/src/impl/hash-set.ts +342 -0
  188. package/src/impl/linked-hash-map.ts +572 -0
  189. package/src/impl/linked-list.ts +606 -0
  190. package/src/impl/priority-queue.ts +448 -0
  191. package/src/impl/tree-map.ts +912 -0
  192. package/src/impl/tree-set.ts +469 -0
  193. package/src/index.ts +277 -0
  194. package/src/interfaces/collection.ts +141 -0
  195. package/src/interfaces/list.ts +281 -0
  196. package/src/interfaces/map.ts +405 -0
  197. package/src/interfaces/queue.ts +353 -0
  198. package/src/interfaces/set.ts +158 -0
  199. package/src/register.ts +8 -0
  200. package/src/storage/index.ts +16 -0
  201. package/src/storage/interface.ts +179 -0
  202. package/src/storage/memory.ts +180 -0
  203. package/src/utils/defaults.ts +345 -0
  204. package/src/utils/factories.ts +357 -0
  205. package/src/utils/helpers.ts +248 -0
@@ -0,0 +1,323 @@
1
+ /**
2
+ * Functional effect types for error handling and optional values.
3
+ *
4
+ * Provides Option<T> and Result<T,E> types for explicit, type-safe
5
+ * error handling without exceptions. Includes async variants.
6
+ */
7
+
8
+ // ============================================================================
9
+ // Option<T> - represents optional values
10
+ // ============================================================================
11
+
12
+ /**
13
+ * Represents the absence of a value.
14
+ */
15
+ export interface None {
16
+ readonly _tag: "None";
17
+ }
18
+
19
+ /**
20
+ * Represents the presence of a value.
21
+ */
22
+ export interface Some<T> {
23
+ readonly _tag: "Some";
24
+ readonly value: T;
25
+ }
26
+
27
+ /**
28
+ * Option<T> represents a value that may or may not be present.
29
+ * This is a type-safe alternative to null/undefined.
30
+ *
31
+ * @example
32
+ * function findUser(id: string): Option<User> {
33
+ * const user = db.get(id);
34
+ * return user ? Some(user) : None;
35
+ * }
36
+ */
37
+ export type Option<T> = None | Some<T>;
38
+
39
+ /**
40
+ * The singleton None value.
41
+ */
42
+ export const None: None = Object.freeze({ _tag: "None" });
43
+
44
+ /**
45
+ * Constructs a Some value containing the given value.
46
+ */
47
+ export const Some = <T>(value: T): Some<T> =>
48
+ Object.freeze({ _tag: "Some", value });
49
+
50
+ /**
51
+ * Type guard to check if an Option is None.
52
+ */
53
+ export const isNone = <T>(opt: Option<T>): opt is None => opt._tag === "None";
54
+
55
+ /**
56
+ * Type guard to check if an Option is Some.
57
+ */
58
+ export const isSome = <T>(opt: Option<T>): opt is Some<T> =>
59
+ opt._tag === "Some";
60
+
61
+ /**
62
+ * Extracts the value from a Some, or returns the default value if None.
63
+ */
64
+ export const getOrElse = <T>(opt: Option<T>, defaultValue: T): T =>
65
+ isSome(opt) ? opt.value : defaultValue;
66
+
67
+ /**
68
+ * Extracts the value from a Some, or throws an error if None.
69
+ */
70
+ export const unwrap = <T>(opt: Option<T>): T => {
71
+ if (isSome(opt)) return opt.value;
72
+ throw new Error("Called unwrap on None");
73
+ };
74
+
75
+ /**
76
+ * Maps a function over the value in a Some, or returns None.
77
+ */
78
+ export const mapOption = <T, U>(
79
+ opt: Option<T>,
80
+ f: (value: T) => U
81
+ ): Option<U> => (isSome(opt) ? Some(f(opt.value)) : None);
82
+
83
+ /**
84
+ * Chains Option-returning operations.
85
+ */
86
+ export const flatMapOption = <T, U>(
87
+ opt: Option<T>,
88
+ f: (value: T) => Option<U>
89
+ ): Option<U> => (isSome(opt) ? f(opt.value) : None);
90
+
91
+ /**
92
+ * Converts a nullable value to an Option.
93
+ */
94
+ export const fromNullable = <T>(value: T | null | undefined): Option<T> =>
95
+ value == null ? None : Some(value);
96
+
97
+ /**
98
+ * Converts an Option to a nullable value.
99
+ */
100
+ export const toNullable = <T>(opt: Option<T>): T | undefined =>
101
+ isSome(opt) ? opt.value : undefined;
102
+
103
+ // ============================================================================
104
+ // Result<T, E> - represents success or failure
105
+ // ============================================================================
106
+
107
+ /**
108
+ * Represents a successful result containing a value.
109
+ */
110
+ export interface Ok<T> {
111
+ readonly _tag: "Ok";
112
+ readonly value: T;
113
+ }
114
+
115
+ /**
116
+ * Represents a failed result containing an error.
117
+ */
118
+ export interface Err<E> {
119
+ readonly _tag: "Err";
120
+ readonly error: E;
121
+ }
122
+
123
+ /**
124
+ * Result<T, E> represents the result of an operation that may fail.
125
+ * It contains either a success value (Ok) or an error value (Err).
126
+ *
127
+ * @example
128
+ * function divide(a: number, b: number): Result<number, string> {
129
+ * if (b === 0) return Err("Division by zero");
130
+ * return Ok(a / b);
131
+ * }
132
+ */
133
+ export type Result<T, E> = Ok<T> | Err<E>;
134
+
135
+ /**
136
+ * Constructs an Ok result containing the given value.
137
+ */
138
+ export const Ok = <T>(value: T): Ok<T> =>
139
+ Object.freeze({
140
+ _tag: "Ok",
141
+ value,
142
+ match: <U>(f: { Ok: (value: T) => U; Err: (error: unknown) => U }) =>
143
+ f.Ok(value),
144
+ });
145
+
146
+ /**
147
+ * Constructs an Err result containing the given error.
148
+ */
149
+ export const Err = <E>(error: E): Err<E> =>
150
+ Object.freeze({
151
+ _tag: "Err",
152
+ error,
153
+ match: <U>(f: { Ok: (value: unknown) => U; Err: (error: E) => U }) =>
154
+ f.Err(error),
155
+ });
156
+
157
+ /**
158
+ * Type guard to check if a Result is Ok.
159
+ */
160
+ export const isOk = <T, E>(result: Result<T, E>): result is Ok<T> =>
161
+ result._tag === "Ok";
162
+
163
+ /**
164
+ * Type guard to check if a Result is Err.
165
+ */
166
+ export const isErr = <T, E>(result: Result<T, E>): result is Err<E> =>
167
+ result._tag === "Err";
168
+
169
+ /**
170
+ * Extracts the value from an Ok, or returns the default value if Err.
171
+ */
172
+ export const getOrElseResult = <T, E>(
173
+ result: Result<T, E>,
174
+ defaultValue: T
175
+ ): T => (isOk(result) ? result.value : defaultValue);
176
+
177
+ /**
178
+ * Extracts the value from an Ok, or throws the error if Err.
179
+ */
180
+ export const unwrapResult = <T, E>(result: Result<T, E>): T => {
181
+ if (isOk(result)) return result.value;
182
+ throw result.error;
183
+ };
184
+
185
+ /**
186
+ * Maps a function over the value in an Ok, or returns the Err unchanged.
187
+ */
188
+ export const mapResult = <T, U, E>(
189
+ result: Result<T, E>,
190
+ f: (value: T) => U
191
+ ): Result<U, E> => (isOk(result) ? Ok(f(result.value)) : result);
192
+
193
+ /**
194
+ * Maps a function over the error in an Err, or returns the Ok unchanged.
195
+ */
196
+ export const mapError = <T, E, F>(
197
+ result: Result<T, E>,
198
+ f: (error: E) => F
199
+ ): Result<T, F> => (isErr(result) ? Err(f(result.error)) : result);
200
+
201
+ /**
202
+ * Chains Result-returning operations.
203
+ */
204
+ export const flatMapResult = <T, U, E>(
205
+ result: Result<T, E>,
206
+ f: (value: T) => Result<U, E>
207
+ ): Result<U, E> => (isOk(result) ? f(result.value) : result);
208
+
209
+ /**
210
+ * Converts a throwing function into a Result-returning function.
211
+ */
212
+ export const tryCatch = <T, E = unknown>(
213
+ fn: () => T,
214
+ onError?: (error: unknown) => E
215
+ ): Result<T, E> => {
216
+ try {
217
+ return Ok(fn());
218
+ } catch (error) {
219
+ return Err((onError ? onError(error) : error) as E);
220
+ }
221
+ };
222
+
223
+ /**
224
+ * Converts an async throwing function into a Result-returning async function.
225
+ */
226
+ export const tryCatchAsync = async <T, E = unknown>(
227
+ fn: () => Promise<T>,
228
+ onError?: (error: unknown) => E
229
+ ): Promise<Result<T, E>> => {
230
+ try {
231
+ return Ok(await fn());
232
+ } catch (error) {
233
+ return Err((onError ? onError(error) : error) as E);
234
+ }
235
+ };
236
+
237
+ // ============================================================================
238
+ // Async variants
239
+ // ============================================================================
240
+
241
+ /**
242
+ * Async variant of Option<T>.
243
+ */
244
+ export type AsyncOption<T> = Promise<Option<T>>;
245
+
246
+ /**
247
+ * Async variant of Result<T, E>.
248
+ */
249
+ export type AsyncResult<T, E> = Promise<Result<T, E>>;
250
+
251
+ /**
252
+ * Maps a function over an async Option.
253
+ */
254
+ export const mapAsyncOption = async <T, U>(
255
+ opt: AsyncOption<T>,
256
+ f: (value: T) => U | Promise<U>
257
+ ): AsyncOption<U> => {
258
+ const resolved = await opt;
259
+ if (isSome(resolved)) {
260
+ return Some(await f(resolved.value));
261
+ }
262
+ return None;
263
+ };
264
+
265
+ /**
266
+ * Maps a function over an async Result.
267
+ */
268
+ export const mapAsyncResult = async <T, U, E>(
269
+ result: AsyncResult<T, E>,
270
+ f: (value: T) => U | Promise<U>
271
+ ): AsyncResult<U, E> => {
272
+ const resolved = await result;
273
+ if (isOk(resolved)) {
274
+ return Ok(await f(resolved.value));
275
+ }
276
+ return resolved;
277
+ };
278
+
279
+ // ============================================================================
280
+ // Conversion utilities
281
+ // ============================================================================
282
+
283
+ /**
284
+ * Converts an Option to a Result.
285
+ * None becomes Err with the provided error.
286
+ */
287
+ export const optionToResult = <T, E>(opt: Option<T>, error: E): Result<T, E> =>
288
+ isSome(opt) ? Ok(opt.value) : Err(error);
289
+
290
+ /**
291
+ * Converts a Result to an Option.
292
+ * Err becomes None, discarding the error.
293
+ */
294
+ export const resultToOption = <T, E>(result: Result<T, E>): Option<T> =>
295
+ isOk(result) ? Some(result.value) : None;
296
+
297
+ /**
298
+ * Combines multiple Options into an Option of an array.
299
+ * Returns None if any input is None.
300
+ */
301
+ export const sequence = <T>(opts: Option<T>[]): Option<T[]> => {
302
+ const values: T[] = [];
303
+ for (const opt of opts) {
304
+ if (isNone(opt)) return None;
305
+ values.push(opt.value);
306
+ }
307
+ return Some(values);
308
+ };
309
+
310
+ /**
311
+ * Combines multiple Results into a Result of an array.
312
+ * Returns the first Err encountered, or Ok with all values.
313
+ */
314
+ export const sequenceResults = <T, E>(
315
+ results: Result<T, E>[]
316
+ ): Result<T[], E> => {
317
+ const values: T[] = [];
318
+ for (const result of results) {
319
+ if (isErr(result)) return result;
320
+ values.push(result.value);
321
+ }
322
+ return Ok(values);
323
+ };
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Typed event emitter system for collections.
3
+ *
4
+ * Provides a lightweight, type-safe event system for mutation events
5
+ * and other observable behavior. Events are strongly typed using
6
+ * TypeScript's mapped types.
7
+ */
8
+
9
+ /**
10
+ * A listener function that receives an event payload.
11
+ */
12
+ export type Listener<P> = (payload: P) => void;
13
+
14
+ /**
15
+ * A function to unsubscribe from an event.
16
+ */
17
+ export type Unsubscribe = () => void;
18
+
19
+ /**
20
+ * Event map defining event names and their payload types.
21
+ *
22
+ * @example
23
+ * interface MyEvents {
24
+ * add: { value: number; index: number }
25
+ * remove: { value: number }
26
+ * clear: {}
27
+ * }
28
+ */
29
+ export type EventMap = Record<string, any>;
30
+
31
+ /**
32
+ * Type-safe event emitter.
33
+ *
34
+ * Supports subscribing to events, emitting events, and managing listeners.
35
+ * All event names and payloads are type-checked at compile time.
36
+ *
37
+ * @example
38
+ * interface ListEvents<T> {
39
+ * add: { value: T; index: number }
40
+ * remove: { value: T; index: number }
41
+ * clear: {}
42
+ * }
43
+ *
44
+ * const emitter = new Emitter<ListEvents<number>>()
45
+ *
46
+ * const unsub = emitter.on('add', ({ value, index }) => {
47
+ * console.log(`Added ${value} at ${index}`)
48
+ * })
49
+ *
50
+ * emitter.emit('add', { value: 42, index: 0 })
51
+ * unsub() // Unsubscribe
52
+ */
53
+ export class Emitter<E extends EventMap> {
54
+ private listeners = new Map<keyof E, Set<Listener<any>>>();
55
+
56
+ /**
57
+ * Subscribe to an event.
58
+ *
59
+ * @param event The event name
60
+ * @param listener The callback to invoke when event is emitted
61
+ * @returns A function to unsubscribe
62
+ */
63
+ on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {
64
+ let listeners = this.listeners.get(event);
65
+ if (!listeners) {
66
+ listeners = new Set();
67
+ this.listeners.set(event, listeners);
68
+ }
69
+ listeners.add(listener);
70
+
71
+ // Return unsubscribe function
72
+ return () => {
73
+ listeners!.delete(listener);
74
+ // Clean up empty sets
75
+ if (listeners!.size === 0) {
76
+ this.listeners.delete(event);
77
+ }
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Subscribe to an event, but automatically unsubscribe after first emission.
83
+ *
84
+ * @param event The event name
85
+ * @param listener The callback to invoke once
86
+ * @returns A function to unsubscribe (in case you want to cancel before emission)
87
+ */
88
+ once<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {
89
+ const wrappedListener: Listener<E[K]> = (payload) => {
90
+ unsubscribe();
91
+ listener(payload);
92
+ };
93
+
94
+ const unsubscribe = this.on(event, wrappedListener);
95
+ return unsubscribe;
96
+ }
97
+
98
+ /**
99
+ * Emit an event to all registered listeners.
100
+ *
101
+ * @param event The event name
102
+ * @param payload The event payload
103
+ */
104
+ emit<K extends keyof E>(event: K, payload: E[K]): void {
105
+ const listeners = this.listeners.get(event);
106
+ if (listeners) {
107
+ // Create a snapshot to avoid issues if listeners modify the set
108
+ const snapshot = Array.from(listeners);
109
+ for (const listener of snapshot) {
110
+ try {
111
+ listener(payload);
112
+ } catch (error) {
113
+ // Log error but don't stop other listeners
114
+ console.error(
115
+ `Error in event listener for '${String(event)}':`,
116
+ error
117
+ );
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Remove all listeners for a specific event, or all events if no event specified.
125
+ *
126
+ * @param event Optional event name to clear listeners for
127
+ */
128
+ off<K extends keyof E>(event?: K): void {
129
+ if (event !== undefined) {
130
+ this.listeners.delete(event);
131
+ } else {
132
+ this.listeners.clear();
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Get the number of listeners for a specific event.
138
+ *
139
+ * @param event The event name
140
+ * @returns Number of registered listeners
141
+ */
142
+ listenerCount<K extends keyof E>(event: K): number {
143
+ return this.listeners.get(event)?.size ?? 0;
144
+ }
145
+
146
+ /**
147
+ * Get all event names that have at least one listener.
148
+ */
149
+ eventNames(): (keyof E)[] {
150
+ return Array.from(this.listeners.keys());
151
+ }
152
+
153
+ /**
154
+ * Check if there are any listeners for a specific event.
155
+ */
156
+ hasListeners<K extends keyof E>(event: K): boolean {
157
+ return this.listenerCount(event) > 0;
158
+ }
159
+
160
+ /**
161
+ * Remove all listeners and clean up resources.
162
+ */
163
+ dispose(): void {
164
+ this.listeners.clear();
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Create an event emitter for a specific event map.
170
+ *
171
+ * This is a convenience factory function.
172
+ *
173
+ * @example
174
+ * const events = createEmitter<ListEvents<number>>()
175
+ */
176
+ export const createEmitter = <E extends EventMap>(): Emitter<E> => {
177
+ return new Emitter<E>();
178
+ };
179
+
180
+ /**
181
+ * Event batching utility for reducing event noise.
182
+ * Collects events and emits them in batches.
183
+ *
184
+ * @example
185
+ * const batcher = new EventBatcher(emitter, 'add', 100)
186
+ * batcher.queue({ value: 1, index: 0 })
187
+ * batcher.queue({ value: 2, index: 1 })
188
+ * // After 100ms or flush(), emits single 'batch-add' event with both items
189
+ */
190
+ export class EventBatcher<E extends EventMap, K extends keyof E> {
191
+ private batch: E[K][] = [];
192
+ private timer: ReturnType<typeof setTimeout> | null = null;
193
+
194
+ constructor(
195
+ private emitter: Emitter<E & { [P in `batch-${K & string}`]: E[K][] }>,
196
+ private event: K,
197
+ private delayMs: number
198
+ ) {}
199
+
200
+ /**
201
+ * Add an event to the current batch.
202
+ */
203
+ queue(payload: E[K]): void {
204
+ this.batch.push(payload);
205
+
206
+ if (this.timer === null) {
207
+ this.timer = setTimeout(() => this.flush(), this.delayMs);
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Immediately emit all batched events.
213
+ */
214
+ flush(): void {
215
+ if (this.timer !== null) {
216
+ clearTimeout(this.timer);
217
+ this.timer = null;
218
+ }
219
+
220
+ if (this.batch.length > 0) {
221
+ const batchEvent = `batch-${String(this.event)}` as keyof (E & { [P in `batch-${K & string}`]: E[K][] });
222
+ this.emitter.emit(batchEvent, this.batch as any);
223
+ this.batch = [];
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Clean up resources.
229
+ */
230
+ dispose(): void {
231
+ this.flush();
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Async event emitter that returns promises.
237
+ * Waits for all async listeners to complete.
238
+ *
239
+ * @example
240
+ * const emitter = new AsyncEmitter<{ save: { data: string } }>()
241
+ *
242
+ * emitter.on('save', async ({ data }) => {
243
+ * await database.save(data)
244
+ * })
245
+ *
246
+ * await emitter.emit('save', { data: 'test' }) // Waits for save
247
+ */
248
+ export class AsyncEmitter<E extends EventMap> {
249
+ private listeners = new Map<keyof E, Set<Listener<any>>>();
250
+
251
+ on<K extends keyof E>(event: K, listener: Listener<E[K]>): Unsubscribe {
252
+ let listeners = this.listeners.get(event);
253
+ if (!listeners) {
254
+ listeners = new Set();
255
+ this.listeners.set(event, listeners);
256
+ }
257
+ listeners.add(listener);
258
+
259
+ return () => {
260
+ listeners!.delete(listener);
261
+ if (listeners!.size === 0) {
262
+ this.listeners.delete(event);
263
+ }
264
+ };
265
+ }
266
+
267
+ /**
268
+ * Emit an event and wait for all async listeners to complete.
269
+ *
270
+ * @param event The event name
271
+ * @param payload The event payload
272
+ * @returns Promise that resolves when all listeners complete
273
+ */
274
+ async emit<K extends keyof E>(event: K, payload: E[K]): Promise<void> {
275
+ const listeners = this.listeners.get(event);
276
+ if (listeners) {
277
+ const promises = Array.from(listeners).map((listener) =>
278
+ Promise.resolve().then(() => listener(payload))
279
+ );
280
+ await Promise.all(promises);
281
+ }
282
+ }
283
+
284
+ off<K extends keyof E>(event?: K): void {
285
+ if (event !== undefined) {
286
+ this.listeners.delete(event);
287
+ } else {
288
+ this.listeners.clear();
289
+ }
290
+ }
291
+
292
+ listenerCount<K extends keyof E>(event: K): number {
293
+ return this.listeners.get(event)?.size ?? 0;
294
+ }
295
+
296
+ eventNames(): (keyof E)[] {
297
+ return Array.from(this.listeners.keys());
298
+ }
299
+
300
+ dispose(): void {
301
+ this.listeners.clear();
302
+ }
303
+ }
304
+
305
+ /**
306
+ * Utility to forward events from one emitter to another.
307
+ * Useful for composing event sources.
308
+ *
309
+ * @example
310
+ * const child = new Emitter<ChildEvents>()
311
+ * const parent = new Emitter<ParentEvents>()
312
+ *
313
+ * forwardEvent(child, parent, 'childEvent', 'parentEvent')
314
+ */
315
+ export const forwardEvent = <
316
+ E1 extends EventMap,
317
+ E2 extends EventMap,
318
+ K1 extends keyof E1,
319
+ K2 extends keyof E2
320
+ >(
321
+ source: Emitter<E1>,
322
+ target: Emitter<E2>,
323
+ sourceEvent: K1,
324
+ targetEvent: K2,
325
+ transform?: (payload: E1[K1]) => E2[K2]
326
+ ): Unsubscribe => {
327
+ return source.on(sourceEvent, (payload) => {
328
+ const transformedPayload = transform
329
+ ? transform(payload)
330
+ : (payload as any);
331
+ target.emit(targetEvent, transformedPayload);
332
+ });
333
+ };
334
+
335
+ /**
336
+ * Create a filtered event subscription that only fires when predicate is true.
337
+ *
338
+ * @example
339
+ * const emitter = new Emitter<{ change: { value: number } }>()
340
+ *
341
+ * onWhen(emitter, 'change', ({ value }) => value > 10, ({ value }) => {
342
+ * console.log('Value exceeded 10:', value)
343
+ * })
344
+ */
345
+ export const onWhen = <E extends EventMap, K extends keyof E>(
346
+ emitter: Emitter<E>,
347
+ event: K,
348
+ predicate: (payload: E[K]) => boolean,
349
+ listener: Listener<E[K]>
350
+ ): Unsubscribe => {
351
+ return emitter.on(event, (payload) => {
352
+ if (predicate(payload)) {
353
+ listener(payload);
354
+ }
355
+ });
356
+ };