@open-wa/hyperemitter 5.0.0-alpha.2

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.
@@ -0,0 +1,337 @@
1
+ import { EventEmitter as NodeEmitter } from 'node:events';
2
+ import { RadixTree } from '../routing/RadixTree.js';
3
+ import { ListenerOptions, HyperEmitterOptions } from '../types/index.js';
4
+ import {
5
+ ListenerRecord,
6
+ attachAbort,
7
+ cleanupAbort,
8
+ createRecord
9
+ } from '../utils/listener.js';
10
+ import { createLogger, Logger } from '@open-wa/logger';
11
+ import type { LogContext } from '@open-wa/logger';
12
+
13
+ type AnyFn = (...args: any[]) => any;
14
+
15
+ export class HyperEmitter<TMap extends object = Record<string, unknown>> {
16
+ private readonly delimiter: string;
17
+ private readonly captureRejections: boolean;
18
+ private readonly onError?: (err: unknown) => void;
19
+ private readonly finalizer?: FinalizationRegistry<unknown>;
20
+ private readonly logger?: Logger;
21
+ private readonly debugEnabled: boolean;
22
+ private readonly baseLogContext: LogContext;
23
+
24
+ private exactListeners: Map<string, ListenerRecord<AnyFn>[]>;
25
+ private wildcardTree: RadixTree<ListenerRecord<AnyFn>>;
26
+ private wildcardIndex: Map<ListenerRecord<AnyFn>, string>;
27
+ private hasWildcards = false;
28
+ private anyListeners: Set<(event: string, payload: any) => void> = new Set();
29
+
30
+ constructor(options: HyperEmitterOptions = {}) {
31
+ this.delimiter = options.delimiter ?? '.';
32
+ this.captureRejections = options.captureRejections ?? false;
33
+ this.onError = options.onError;
34
+ this.debugEnabled = !!options.debug;
35
+ this.baseLogContext = {
36
+ component: 'hyperemitter',
37
+ ...options.loggerContext
38
+ };
39
+ this.logger =
40
+ options.logger?.withContext?.(this.baseLogContext) ??
41
+ createLogger({ component: 'hyperemitter', ...options.loggerContext });
42
+
43
+ // WeakRef support
44
+ if (typeof FinalizationRegistry !== 'undefined') {
45
+ this.finalizer = new FinalizationRegistry((token: unknown) => {
46
+ if (token && typeof token === 'object') {
47
+ // token is used only for unregister; actual removal is handled during emit via deref
48
+ }
49
+ });
50
+ }
51
+
52
+ this.exactListeners = new Map();
53
+ this.wildcardTree = new RadixTree<ListenerRecord<AnyFn>>(this.delimiter);
54
+ this.wildcardIndex = new Map();
55
+ }
56
+
57
+ on<K extends keyof TMap & string>(
58
+ event: K,
59
+ listener: (payload: TMap[K]) => void | Promise<void>,
60
+ options: ListenerOptions = {}
61
+ ): this {
62
+ const record = createRecord(listener as AnyFn, options, this.finalizer as any);
63
+ this.add(event, record);
64
+ return this;
65
+ }
66
+
67
+ once<K extends keyof TMap & string>(
68
+ event: K,
69
+ listener: (payload: TMap[K]) => void | Promise<void>,
70
+ options: ListenerOptions = {}
71
+ ): this {
72
+ const record = createRecord(listener as AnyFn, options, this.finalizer as any);
73
+ record.once = true;
74
+ this.add(event, record);
75
+ return this;
76
+ }
77
+
78
+ off<K extends keyof TMap & string>(event: K, listener: (payload: TMap[K]) => void | Promise<void>): this {
79
+ const list = this.exactListeners.get(event);
80
+ if (list) {
81
+ const idx = list.findIndex(l => l.fn === listener);
82
+ if (idx !== -1) {
83
+ cleanupAbort(list[idx]);
84
+ list.splice(idx, 1);
85
+ }
86
+ if (list.length === 0) this.exactListeners.delete(event);
87
+ }
88
+ if (this.hasWildcards && (event.includes('+') || event.includes('#'))) {
89
+ this.removeWildcard(event, listener as AnyFn);
90
+ }
91
+ return this;
92
+ }
93
+
94
+ emit<K extends keyof TMap & string>(
95
+ event: K,
96
+ payload: TMap[K]
97
+ ): boolean {
98
+ const exact = this.exactListeners.get(event as string);
99
+ const wildcard = this.hasWildcards
100
+ ? this.wildcardTree.match(event as string)
101
+ : undefined;
102
+
103
+ const called = this.dispatch(exact, [payload]) | this.dispatch(wildcard, [payload]);
104
+
105
+ // Notify catch-all listeners
106
+ for (const listener of this.anyListeners) {
107
+ try {
108
+ listener(event as string, payload);
109
+ } catch { /* swallow */ }
110
+ }
111
+
112
+ return Boolean(called);
113
+ }
114
+
115
+ /**
116
+ * Register a catch-all listener that fires on every emit with (event, payload).
117
+ * Useful for event bridging / debugging.
118
+ */
119
+ onAny(listener: (event: string, payload: any) => void): this {
120
+ this.anyListeners.add(listener);
121
+ return this;
122
+ }
123
+
124
+ /**
125
+ * Remove a catch-all listener registered via onAny.
126
+ */
127
+ offAny(listener: (event: string, payload: any) => void): this {
128
+ this.anyListeners.delete(listener);
129
+ return this;
130
+ }
131
+
132
+ listenerCount(event?: keyof TMap & string): number {
133
+ if (!event) {
134
+ let total = 0;
135
+ for (const arr of this.exactListeners.values()) total += arr.length;
136
+ return total;
137
+ }
138
+ return this.exactListeners.get(event)?.length ?? 0;
139
+ }
140
+
141
+ removeAllListeners(event?: keyof TMap & string): this {
142
+ if (!event) {
143
+ for (const arr of this.exactListeners.values()) {
144
+ arr.forEach(cleanupAbort);
145
+ }
146
+ this.exactListeners.clear();
147
+ this.wildcardTree = new RadixTree<ListenerRecord<AnyFn>>(this.delimiter);
148
+ this.hasWildcards = false;
149
+ this.wildcardIndex.clear();
150
+ return this;
151
+ }
152
+
153
+ const list = this.exactListeners.get(event);
154
+ if (list) {
155
+ list.forEach(cleanupAbort);
156
+ this.exactListeners.delete(event);
157
+ }
158
+ // Wildcards: best effort clear by rebuilding tree
159
+ if (this.hasWildcards && (event.includes('+') || event.includes('#'))) {
160
+ for (const [record, pattern] of this.wildcardIndex.entries()) {
161
+ if (pattern === event) {
162
+ this.wildcardTree.remove(pattern, record);
163
+ this.wildcardIndex.delete(record);
164
+ }
165
+ }
166
+ }
167
+ return this;
168
+ }
169
+
170
+ /**
171
+ * Bridge from a Node EventEmitter: forward Node events into this emitter.
172
+ */
173
+ fromNodeEmitter(emitter: NodeEmitter, event: string): () => void {
174
+ const handler = (...args: any[]) => {
175
+ // @ts-expect-error safe runtime emit
176
+ this.emit(event as any, ...args);
177
+ };
178
+ emitter.on(event, handler);
179
+ return () => emitter.off(event, handler);
180
+ }
181
+
182
+ /**
183
+ * Bridge to a Node EventEmitter: emit HyperEmitter events on a provided Node emitter.
184
+ */
185
+ toNodeEmitter(target: NodeEmitter): () => void {
186
+ const forwarder = (event: string, args: any[]) => target.emit(event, ...args);
187
+ // naive bridge: wrap emit; caller can replace as needed
188
+ const original = (this as any).emit;
189
+ (this as any).emit = (ev: string, ...args: any[]) => {
190
+ forwarder(ev, args);
191
+ return original.call(this, ev, ...args);
192
+ };
193
+ return () => {
194
+ (this as any).emit = original;
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Attach a handler to an EventTarget and re-emit through HyperEmitter.
200
+ */
201
+ onEventTarget(target: EventTarget, type: string, eventName: keyof TMap & string) {
202
+ const handler = (ev: Event) => {
203
+ // @ts-expect-error forwarding payload
204
+ this.emit(eventName, ev);
205
+ };
206
+ target.addEventListener(type, handler);
207
+ return () => target.removeEventListener(type, handler);
208
+ }
209
+
210
+ private add(event: string, record: ListenerRecord<AnyFn>) {
211
+ // Wildcard patterns contain '+' or '#'
212
+ const isWildcard = event.includes('+') || event.includes('#');
213
+ if (isWildcard) {
214
+ this.hasWildcards = true;
215
+ this.wildcardTree.insert(event, record);
216
+ this.wildcardIndex.set(record, event);
217
+ } else {
218
+ const list = this.exactListeners.get(event);
219
+ if (list) {
220
+ list.push(record);
221
+ } else {
222
+ this.exactListeners.set(event, [record]);
223
+ }
224
+ }
225
+
226
+ attachAbort(record, () => this.off(event as any, record.fn as any));
227
+ this.logDebug('listener_registered', {
228
+ event,
229
+ once: record.once,
230
+ wildcard: isWildcard
231
+ });
232
+ }
233
+
234
+ private dispatch(list: ListenerRecord<AnyFn>[] | undefined, args: any[]): number {
235
+ if (!list || list.length === 0) return 0;
236
+ // Copy-on-write to avoid mutation during emit.
237
+ const snapshot = list.slice();
238
+ let called = 0;
239
+ for (const record of snapshot) {
240
+ // WeakRef cleanup: if target gone, remove and skip.
241
+ if (record.weakRef && !record.weakRef.deref()) {
242
+ this.offListener(record);
243
+ continue;
244
+ }
245
+
246
+ called++;
247
+ const result = this.invoke(record, args);
248
+ if (record.once) {
249
+ this.offListener(record);
250
+ }
251
+ if (result && typeof result.then === 'function') {
252
+ result.catch((err: unknown) => this.handleRejection(record, err));
253
+ }
254
+ }
255
+ return called;
256
+ }
257
+
258
+ private invoke(record: ListenerRecord<AnyFn>, args: any[]) {
259
+ switch (args.length) {
260
+ case 0:
261
+ return record.fn();
262
+ case 1:
263
+ return record.fn(args[0]);
264
+ case 2:
265
+ return record.fn(args[0], args[1]);
266
+ case 3:
267
+ return record.fn(args[0], args[1], args[2]);
268
+ default:
269
+ return record.fn(...args);
270
+ }
271
+ }
272
+
273
+ private offListener(record: ListenerRecord<AnyFn>) {
274
+ // Exact listeners
275
+ for (const [event, arr] of this.exactListeners.entries()) {
276
+ const idx = arr.indexOf(record);
277
+ if (idx !== -1) {
278
+ cleanupAbort(arr[idx]);
279
+ arr.splice(idx, 1);
280
+ if (arr.length === 0) this.exactListeners.delete(event);
281
+ return;
282
+ }
283
+ }
284
+ // Wildcard listeners (pattern tracked)
285
+ const pattern = this.wildcardIndex.get(record);
286
+ if (pattern) {
287
+ this.wildcardTree.remove(pattern, record);
288
+ this.wildcardIndex.delete(record);
289
+ }
290
+ }
291
+
292
+ private handleRejection(record: ListenerRecord<AnyFn>, err: unknown) {
293
+ const shouldCapture =
294
+ record.captureRejections !== undefined
295
+ ? record.captureRejections
296
+ : this.captureRejections;
297
+
298
+ if (!shouldCapture) {
299
+ queueMicrotask(() => {
300
+ throw err;
301
+ });
302
+ return;
303
+ }
304
+
305
+ if (this.onError) {
306
+ try {
307
+ this.onError(err);
308
+ } catch {
309
+ // swallow secondary errors
310
+ }
311
+ return;
312
+ }
313
+
314
+ // Fallback logging
315
+ this.logger?.error('listener_rejection', {
316
+ error: err as any,
317
+ ...this.baseLogContext
318
+ });
319
+ }
320
+
321
+ private removeWildcard(event: string, listener: AnyFn) {
322
+ // Slow path: tree removal requires record reference; search recorded patterns.
323
+ for (const [record, pattern] of this.wildcardIndex.entries()) {
324
+ if (pattern === event && record.fn === listener) {
325
+ this.wildcardTree.remove(pattern, record);
326
+ this.wildcardIndex.delete(record);
327
+ cleanupAbort(record);
328
+ break;
329
+ }
330
+ }
331
+ }
332
+
333
+ private logDebug(message: string, meta?: LogContext) {
334
+ if (!this.debugEnabled) return;
335
+ this.logger?.debug(message, { ...this.baseLogContext, ...meta });
336
+ }
337
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { HyperEmitter } from './core/HyperEmitter.js';
2
+ export type {
3
+ EventMap,
4
+ EventListener,
5
+ ListenerOptions,
6
+ HyperEmitterOptions
7
+ } from './types/index.js';
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Monomorphic radix tree node for MQTT-style wildcard routing.
3
+ */
4
+ export class RadixNode<T> {
5
+ segment: string;
6
+ listeners: T[];
7
+ children: Map<string, RadixNode<T>> | null;
8
+ wildcardSingle: RadixNode<T> | null; // '+'
9
+ wildcardMulti: RadixNode<T> | null; // '#'
10
+
11
+ constructor(segment: string) {
12
+ // Preserve property order for hidden-class stability.
13
+ this.segment = segment;
14
+ this.listeners = [];
15
+ this.children = null;
16
+ this.wildcardSingle = null;
17
+ this.wildcardMulti = null;
18
+ }
19
+ }
@@ -0,0 +1,124 @@
1
+ import { RadixNode } from './RadixNode.js';
2
+
3
+ /**
4
+ * Radix tree with MQTT-style wildcards.
5
+ * Complexity: O(K) where K = number of path segments.
6
+ */
7
+ export class RadixTree<T> {
8
+ private readonly delimiter: string;
9
+ private readonly root: RadixNode<T>;
10
+
11
+ constructor(delimiter = '.') {
12
+ this.delimiter = delimiter;
13
+ this.root = new RadixNode<T>('');
14
+ }
15
+
16
+ insert(pattern: string, value: T) {
17
+ const segments = this.tokenize(pattern);
18
+ let node = this.root;
19
+
20
+ for (const segment of segments) {
21
+ if (segment === '+') {
22
+ if (!node.wildcardSingle) node.wildcardSingle = new RadixNode<T>('+');
23
+ node = node.wildcardSingle;
24
+ continue;
25
+ }
26
+ if (segment === '#') {
27
+ if (!node.wildcardMulti) node.wildcardMulti = new RadixNode<T>('#');
28
+ node = node.wildcardMulti;
29
+ break; // '#' consumes the rest
30
+ }
31
+ if (!node.children) node.children = new Map();
32
+ let child = node.children.get(segment);
33
+ if (!child) {
34
+ child = new RadixNode<T>(segment);
35
+ node.children.set(segment, child);
36
+ }
37
+ node = child;
38
+ }
39
+
40
+ node.listeners.push(value);
41
+ }
42
+
43
+ remove(pattern: string, value: T) {
44
+ const path: Array<[RadixNode<T>, string]> = [];
45
+ let node = this.root;
46
+ const segments = this.tokenize(pattern);
47
+
48
+ for (const segment of segments) {
49
+ path.push([node, segment]);
50
+ if (segment === '+') {
51
+ if (!node.wildcardSingle) return;
52
+ node = node.wildcardSingle;
53
+ } else if (segment === '#') {
54
+ if (!node.wildcardMulti) return;
55
+ node = node.wildcardMulti;
56
+ break;
57
+ } else {
58
+ if (!node.children) return;
59
+ const next = node.children.get(segment);
60
+ if (!next) return;
61
+ node = next;
62
+ }
63
+ }
64
+
65
+ const idx = node.listeners.indexOf(value);
66
+ if (idx !== -1) {
67
+ node.listeners.splice(idx, 1);
68
+ }
69
+ }
70
+
71
+ match(event: string): T[] {
72
+ const segments = this.tokenize(event);
73
+ const stack: Array<{ node: RadixNode<T>; index: number }> = [
74
+ { node: this.root, index: 0 }
75
+ ];
76
+ const results: T[] = [];
77
+
78
+ while (stack.length > 0) {
79
+ const { node, index } = stack.pop()!;
80
+
81
+ if (index === segments.length) {
82
+ // Exact depth match
83
+ if (node.listeners.length) results.push(...node.listeners);
84
+ // '#' can also match empty suffix
85
+ if (node.wildcardMulti && node.wildcardMulti.listeners.length) {
86
+ results.push(...node.wildcardMulti.listeners);
87
+ }
88
+ continue;
89
+ }
90
+
91
+ const seg = segments[index];
92
+
93
+ // Exact child
94
+ if (node.children) {
95
+ const child = node.children.get(seg);
96
+ if (child) {
97
+ stack.push({ node: child, index: index + 1 });
98
+ }
99
+ }
100
+
101
+ // Single-level wildcard '+'
102
+ if (node.wildcardSingle) {
103
+ stack.push({ node: node.wildcardSingle, index: index + 1 });
104
+ }
105
+
106
+ // Multi-level wildcard '#'
107
+ if (node.wildcardMulti) {
108
+ // '#' consumes the rest, so we can collect listeners directly
109
+ if (node.wildcardMulti.listeners.length) {
110
+ results.push(...node.wildcardMulti.listeners);
111
+ }
112
+ // But it can also match additional segments
113
+ stack.push({ node: node.wildcardMulti, index: index + 1 });
114
+ }
115
+ }
116
+
117
+ return results;
118
+ }
119
+
120
+ private tokenize(path: string): string[] {
121
+ // Simple tokenizer; allocations are acceptable for initial implementation.
122
+ return path.split(this.delimiter);
123
+ }
124
+ }
@@ -0,0 +1,39 @@
1
+ export type AnyFn = (...args: any[]) => any;
2
+
3
+ export type EventMap = { [key: string]: unknown };
4
+
5
+ export type EventListener<T> = (payload: T) => void | Promise<void>;
6
+
7
+ export interface ListenerOptions {
8
+ /**
9
+ * AbortSignal to auto-remove the listener when aborted.
10
+ */
11
+ signal?: AbortSignal;
12
+ /**
13
+ * Mark the listener as weak; provide a target object to track.
14
+ * When the target is GC'd, the listener is removed.
15
+ */
16
+ weak?: object;
17
+ /**
18
+ * Enable captureRejections for this listener (fallbacks to emitter-level).
19
+ */
20
+ captureRejections?: boolean;
21
+ }
22
+
23
+ export interface HyperEmitterOptions {
24
+ delimiter?: string;
25
+ captureRejections?: boolean;
26
+ onError?: (error: unknown) => void;
27
+ /**
28
+ * Enable debug logging (uses @open-wa/logger).
29
+ */
30
+ debug?: boolean;
31
+ /**
32
+ * Optional logger instance; if omitted, a child logger will be created.
33
+ */
34
+ logger?: import('@open-wa/logger').Logger;
35
+ /**
36
+ * Additional bound context for logger child.
37
+ */
38
+ loggerContext?: import('@open-wa/logger').LogContext;
39
+ }
@@ -0,0 +1,59 @@
1
+ import { ListenerOptions } from '../types/index.js';
2
+
3
+ export type ListenerFn = (...args: any[]) => any;
4
+
5
+ export interface ListenerRecord<T extends ListenerFn> {
6
+ fn: T;
7
+ once: boolean;
8
+ signal?: AbortSignal;
9
+ abortHandler?: () => void;
10
+ weakRef?: WeakRef<object>;
11
+ finalizerToken?: object;
12
+ captureRejections?: boolean;
13
+ }
14
+
15
+ export function createRecord<T extends ListenerFn>(
16
+ fn: T,
17
+ opts: ListenerOptions,
18
+ finalizer?: FinalizationRegistry<unknown>
19
+ ): ListenerRecord<T> {
20
+ const record: ListenerRecord<T> = {
21
+ fn,
22
+ once: false,
23
+ signal: opts.signal,
24
+ captureRejections: opts.captureRejections
25
+ };
26
+
27
+ if (opts.weak && typeof WeakRef !== 'undefined') {
28
+ const weakRef = new WeakRef(opts.weak);
29
+ record.weakRef = weakRef;
30
+ if (finalizer) {
31
+ const token = {};
32
+ record.finalizerToken = token;
33
+ finalizer.register(opts.weak, token, token);
34
+ }
35
+ }
36
+
37
+ return record;
38
+ }
39
+
40
+ export function attachAbort(
41
+ record: ListenerRecord<any>,
42
+ remove: () => void
43
+ ) {
44
+ if (!record.signal) return;
45
+ if (record.signal.aborted) {
46
+ remove();
47
+ return;
48
+ }
49
+ const handler = () => remove();
50
+ record.abortHandler = handler;
51
+ record.signal.addEventListener('abort', handler, { once: true });
52
+ }
53
+
54
+ export function cleanupAbort(record: ListenerRecord<any>) {
55
+ if (record.signal && record.abortHandler) {
56
+ record.signal.removeEventListener('abort', record.abortHandler);
57
+ record.abortHandler = undefined;
58
+ }
59
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "sourceMap": true,
9
+ "module": "ESNext",
10
+ "target": "ES2022",
11
+ "lib": ["ES2022"],
12
+ "moduleResolution": "Bundler",
13
+ "strict": true,
14
+ "noEmit": false,
15
+ "stripInternal": true,
16
+ "composite": true
17
+ },
18
+ "include": [
19
+ "src/**/*"
20
+ ]
21
+ }