@bernierllc/event-emitter 1.0.9 → 1.3.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.
@@ -1,132 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- import { EventEmitter } from '../src';
10
-
11
- describe('EventEmitter - Logger Integration', () => {
12
- describe('with logger enabled', () => {
13
- it('should log events when logEvents is true', async () => {
14
- const emitter = new EventEmitter({ logEvents: true });
15
-
16
- const handler = jest.fn();
17
- emitter.on('test', handler);
18
-
19
- await emitter.emit('test', { data: 'test' });
20
-
21
- expect(handler).toHaveBeenCalledWith({ data: 'test' });
22
- });
23
-
24
- it('should log listener additions', () => {
25
- const emitter = new EventEmitter({ logEvents: true });
26
-
27
- const handler = jest.fn();
28
- const subscription = emitter.on('user.created', handler);
29
-
30
- expect(subscription).toBeDefined();
31
- expect(subscription.eventType).toBe('user.created');
32
- });
33
-
34
- it('should log listener removals', () => {
35
- const emitter = new EventEmitter({ logEvents: true });
36
-
37
- const handler = jest.fn();
38
- const subscription = emitter.on('test', handler);
39
-
40
- emitter.off(subscription);
41
- expect(emitter.listenerCount('test')).toBe(0);
42
- });
43
-
44
- it('should log removeAllListeners operations', () => {
45
- const emitter = new EventEmitter({ logEvents: true });
46
-
47
- emitter.on('test1', jest.fn());
48
- emitter.on('test2', jest.fn());
49
-
50
- emitter.removeAllListeners('test1');
51
- expect(emitter.listenerCount('test1')).toBe(0);
52
- expect(emitter.listenerCount('test2')).toBe(1);
53
- });
54
-
55
- it('should log removeAllListeners for all events', () => {
56
- const emitter = new EventEmitter({ logEvents: true });
57
-
58
- emitter.on('test1', jest.fn());
59
- emitter.on('test2', jest.fn());
60
-
61
- emitter.removeAllListeners();
62
- expect(emitter.listenerCount('test1')).toBe(0);
63
- expect(emitter.listenerCount('test2')).toBe(0);
64
- });
65
-
66
- it('should log handler errors when captureErrors is true', async () => {
67
- const emitter = new EventEmitter({ logEvents: true, captureErrors: true });
68
-
69
- const errorHandler = jest.fn(() => {
70
- throw new Error('Test error');
71
- });
72
-
73
- emitter.on('test', errorHandler);
74
- await emitter.emit('test', {});
75
-
76
- expect(errorHandler).toHaveBeenCalled();
77
- });
78
- });
79
-
80
- describe('without logger', () => {
81
- it('should work without logger when logEvents is false', async () => {
82
- const emitter = new EventEmitter({ logEvents: false });
83
-
84
- const handler = jest.fn();
85
- emitter.on('test', handler);
86
-
87
- await emitter.emit('test', { data: 'test' });
88
-
89
- expect(handler).toHaveBeenCalledWith({ data: 'test' });
90
- });
91
-
92
- it('should not attempt logging when logger unavailable', async () => {
93
- // Logger is optional, so this should work fine
94
- const emitter = new EventEmitter({ logEvents: true });
95
-
96
- const handler = jest.fn();
97
- emitter.on('test', handler);
98
-
99
- await expect(emitter.emit('test', {})).resolves.toBeUndefined();
100
- expect(handler).toHaveBeenCalled();
101
- });
102
- });
103
-
104
- describe('error logging', () => {
105
- it('should handle errors without logger when captureErrors is true', async () => {
106
- const emitter = new EventEmitter({ captureErrors: true, logEvents: false });
107
-
108
- const handler = jest.fn(() => {
109
- throw new Error('Handler error');
110
- });
111
-
112
- emitter.on('test', handler);
113
-
114
- // Should not throw despite error in handler
115
- await expect(emitter.emit('test', {})).resolves.toBeUndefined();
116
- });
117
-
118
- it('should log errors with subscription ID when available', async () => {
119
- const emitter = new EventEmitter({ logEvents: true, captureErrors: true });
120
-
121
- const handler = jest.fn(() => {
122
- throw new Error('Handler error with ID');
123
- });
124
-
125
- const subscription = emitter.on('test', handler);
126
-
127
- await emitter.emit('test', {});
128
-
129
- expect(subscription.id).toBeDefined();
130
- });
131
- });
132
- });
@@ -1,151 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- import { EventEmitter } from '../src';
10
-
11
- describe('EventEmitter - Wildcard Listeners', () => {
12
- let emitter: EventEmitter;
13
-
14
- beforeEach(() => {
15
- emitter = new EventEmitter();
16
- });
17
-
18
- describe('wildcard subscription', () => {
19
- it('should add wildcard listener', () => {
20
- const handler = jest.fn();
21
- const subscription = emitter.on('*', handler);
22
-
23
- expect(subscription.eventType).toBe('*');
24
- expect(emitter.listenerCount('*')).toBe(1);
25
- });
26
-
27
- it('should call wildcard listener for any event', async () => {
28
- const wildcardHandler = jest.fn();
29
- emitter.on('*', wildcardHandler);
30
-
31
- await emitter.emit('event1', { data: 'test1' });
32
- await emitter.emit('event2', { data: 'test2' });
33
- await emitter.emit('event3', { data: 'test3' });
34
-
35
- expect(wildcardHandler).toHaveBeenCalledTimes(3);
36
- expect(wildcardHandler).toHaveBeenCalledWith({ data: 'test1' });
37
- expect(wildcardHandler).toHaveBeenCalledWith({ data: 'test2' });
38
- expect(wildcardHandler).toHaveBeenCalledWith({ data: 'test3' });
39
- });
40
-
41
- it('should call both wildcard and specific listeners', async () => {
42
- const wildcardHandler = jest.fn();
43
- const specificHandler = jest.fn();
44
-
45
- emitter.on('*', wildcardHandler);
46
- emitter.on('test', specificHandler);
47
-
48
- await emitter.emit('test', { data: 'test' });
49
-
50
- expect(wildcardHandler).toHaveBeenCalledTimes(1);
51
- expect(specificHandler).toHaveBeenCalledTimes(1);
52
- });
53
-
54
- it('should handle multiple wildcard listeners', async () => {
55
- const handler1 = jest.fn();
56
- const handler2 = jest.fn();
57
- const handler3 = jest.fn();
58
-
59
- emitter.on('*', handler1);
60
- emitter.on('*', handler2);
61
- emitter.on('*', handler3);
62
-
63
- await emitter.emit('test', { data: 'test' });
64
-
65
- expect(handler1).toHaveBeenCalledTimes(1);
66
- expect(handler2).toHaveBeenCalledTimes(1);
67
- expect(handler3).toHaveBeenCalledTimes(1);
68
- });
69
-
70
- it('should remove wildcard listener', () => {
71
- const handler = jest.fn();
72
- const subscription = emitter.on('*', handler);
73
-
74
- expect(emitter.listenerCount('*')).toBe(1);
75
-
76
- emitter.off(subscription);
77
- expect(emitter.listenerCount('*')).toBe(0);
78
- });
79
-
80
- it('should support wildcard once listeners', async () => {
81
- const handler = jest.fn();
82
- emitter.once('*', handler);
83
-
84
- await emitter.emit('event1', { data: 'test1' });
85
- await emitter.emit('event2', { data: 'test2' });
86
-
87
- expect(handler).toHaveBeenCalledTimes(1);
88
- expect(handler).toHaveBeenCalledWith({ data: 'test1' });
89
- });
90
-
91
- it('should remove all wildcard listeners', () => {
92
- emitter.on('*', jest.fn());
93
- emitter.on('*', jest.fn());
94
-
95
- expect(emitter.listenerCount('*')).toBe(2);
96
-
97
- emitter.removeAllListeners('*');
98
- expect(emitter.listenerCount('*')).toBe(0);
99
- });
100
-
101
- it('should remove wildcard listeners when removing all', () => {
102
- emitter.on('*', jest.fn());
103
- emitter.on('test', jest.fn());
104
-
105
- emitter.removeAllListeners();
106
-
107
- expect(emitter.listenerCount('*')).toBe(0);
108
- expect(emitter.listenerCount('test')).toBe(0);
109
- });
110
- });
111
-
112
- describe('wildcard listener edge cases', () => {
113
- it('should handle wildcard with no other listeners', async () => {
114
- const handler = jest.fn();
115
- emitter.on('*', handler);
116
-
117
- await emitter.emit('test', { data: 'test' });
118
-
119
- expect(handler).toHaveBeenCalledTimes(1);
120
- });
121
-
122
- it('should not affect specific listeners when removing wildcard', async () => {
123
- const wildcardHandler = jest.fn();
124
- const specificHandler = jest.fn();
125
-
126
- const wildcardSub = emitter.on('*', wildcardHandler);
127
- emitter.on('test', specificHandler);
128
-
129
- emitter.off(wildcardSub);
130
-
131
- await emitter.emit('test', { data: 'test' });
132
-
133
- expect(wildcardHandler).not.toHaveBeenCalled();
134
- expect(specificHandler).toHaveBeenCalledTimes(1);
135
- });
136
-
137
- it('should handle mixed wildcard and specific once listeners', async () => {
138
- const wildcardHandler = jest.fn();
139
- const specificHandler = jest.fn();
140
-
141
- emitter.once('*', wildcardHandler);
142
- emitter.once('test', specificHandler);
143
-
144
- await emitter.emit('test', { data: 'test' });
145
- await emitter.emit('test', { data: 'test2' });
146
-
147
- expect(wildcardHandler).toHaveBeenCalledTimes(1);
148
- expect(specificHandler).toHaveBeenCalledTimes(1);
149
- });
150
- });
151
- });
package/jest.config.cjs DELETED
@@ -1,30 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- module.exports = {
10
- preset: 'ts-jest',
11
- // Use fixed environment to handle Node.js v25+ localStorage issue
12
- testEnvironment: '<rootDir>/../../../jest-environment-node-fixed.cjs',
13
- roots: ['<rootDir>/__tests__'],
14
- testMatch: ['**/*.test.ts'],
15
- collectCoverageFrom: [
16
- 'src/**/*.ts',
17
- '!src/**/*.d.ts',
18
- '!src/index.ts'
19
- ],
20
- coverageThreshold: {
21
- global: {
22
- branches: 90,
23
- functions: 90,
24
- lines: 90,
25
- statements: 90
26
- }
27
- },
28
- coverageDirectory: 'coverage',
29
- verbose: true
30
- };
@@ -1,190 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- import { EventHandler, EventSubscription, EventEmitterOptions } from './types';
10
-
11
- /**
12
- * Event bus for inter-package communication
13
- */
14
- export class EventEmitter {
15
- private listeners: Map<string, Set<EventSubscription>>;
16
- private wildcardListeners: Set<EventSubscription>;
17
- private options: Required<EventEmitterOptions>;
18
- private logger?: any;
19
-
20
- constructor(options: EventEmitterOptions = {}) {
21
- this.listeners = new Map();
22
- this.wildcardListeners = new Set();
23
- this.options = {
24
- maxListeners: options.maxListeners || 0,
25
- logEvents: options.logEvents || false,
26
- captureErrors: options.captureErrors !== false // Default to true
27
- };
28
-
29
- // Try to load logger if available
30
- try {
31
- // eslint-disable-next-line @typescript-eslint/no-var-requires
32
- const { createLogger } = require('@bernierllc/logger');
33
- this.logger = createLogger({ level: 'debug' });
34
- } catch {
35
- // Logger not available, continue without it
36
- }
37
- }
38
-
39
- /**
40
- * Subscribe to event
41
- */
42
- on<T = any>(eventType: string, handler: EventHandler<T>): EventSubscription {
43
- // Check max listeners
44
- if (this.options.maxListeners > 0) {
45
- const currentCount = this.listenerCount(eventType);
46
- if (currentCount >= this.options.maxListeners) {
47
- throw new Error(`Max listeners (${this.options.maxListeners}) exceeded for event type: ${eventType}`);
48
- }
49
- }
50
-
51
- const subscription: EventSubscription = {
52
- id: `${eventType}-${Date.now()}-${Math.random()}`,
53
- eventType,
54
- handler,
55
- once: false,
56
- unsubscribe: () => this.off(subscription)
57
- };
58
-
59
- if (eventType === '*') {
60
- this.wildcardListeners.add(subscription);
61
- } else {
62
- if (!this.listeners.has(eventType)) {
63
- this.listeners.set(eventType, new Set());
64
- }
65
- this.listeners.get(eventType)!.add(subscription);
66
- }
67
-
68
- if (this.options.logEvents && this.logger) {
69
- this.logger.debug('Event listener added', { eventType, subscriptionId: subscription.id });
70
- }
71
-
72
- return subscription;
73
- }
74
-
75
- /**
76
- * Subscribe to event once
77
- */
78
- once<T = any>(eventType: string, handler: EventHandler<T>): EventSubscription {
79
- const subscription = this.on(eventType, handler);
80
- subscription.once = true;
81
- return subscription;
82
- }
83
-
84
- /**
85
- * Unsubscribe from event
86
- */
87
- off(subscription: EventSubscription): void {
88
- if (subscription.eventType === '*') {
89
- this.wildcardListeners.delete(subscription);
90
- } else {
91
- const listeners = this.listeners.get(subscription.eventType);
92
- if (listeners) {
93
- listeners.delete(subscription);
94
- // Clean up empty sets
95
- if (listeners.size === 0) {
96
- this.listeners.delete(subscription.eventType);
97
- }
98
- }
99
- }
100
-
101
- if (this.options.logEvents && this.logger) {
102
- this.logger.debug('Event listener removed', {
103
- eventType: subscription.eventType,
104
- subscriptionId: subscription.id
105
- });
106
- }
107
- }
108
-
109
- /**
110
- * Publish event
111
- */
112
- async emit<T = any>(eventType: string, data: T): Promise<void> {
113
- if (this.options.logEvents && this.logger) {
114
- this.logger.debug('Event emitted', { eventType, data });
115
- }
116
-
117
- // Get specific listeners
118
- const specificListeners = this.listeners.get(eventType) || new Set();
119
-
120
- // Combine with wildcard listeners
121
- const allListeners = [...specificListeners, ...this.wildcardListeners];
122
-
123
- // Execute handlers
124
- const promises = allListeners.map(async (subscription) => {
125
- try {
126
- await subscription.handler(data);
127
- } catch (error) {
128
- if (this.options.captureErrors) {
129
- if (this.logger) {
130
- this.logger.error('Event handler error', {
131
- eventType,
132
- subscriptionId: subscription.id,
133
- error: error instanceof Error ? error.message : String(error)
134
- });
135
- }
136
- } else {
137
- throw error;
138
- }
139
- } finally {
140
- // Remove if once subscription (always happens, even if error occurred)
141
- if (subscription.once) {
142
- this.off(subscription);
143
- }
144
- }
145
- });
146
-
147
- await Promise.all(promises);
148
- }
149
-
150
- /**
151
- * Remove all listeners for event type
152
- */
153
- removeAllListeners(eventType?: string): void {
154
- if (eventType) {
155
- if (eventType === '*') {
156
- this.wildcardListeners.clear();
157
- } else {
158
- this.listeners.delete(eventType);
159
- }
160
- } else {
161
- this.listeners.clear();
162
- this.wildcardListeners.clear();
163
- }
164
-
165
- if (this.options.logEvents && this.logger) {
166
- this.logger.debug('Listeners removed', { eventType: eventType || 'all' });
167
- }
168
- }
169
-
170
- /**
171
- * Get listener count for event type
172
- */
173
- listenerCount(eventType: string): number {
174
- if (eventType === '*') {
175
- return this.wildcardListeners.size;
176
- }
177
- return this.listeners.get(eventType)?.size || 0;
178
- }
179
-
180
- /**
181
- * Get all event types with listeners
182
- */
183
- eventNames(): string[] {
184
- const names = Array.from(this.listeners.keys());
185
- if (this.wildcardListeners.size > 0) {
186
- names.push('*');
187
- }
188
- return names;
189
- }
190
- }
package/src/factory.ts DELETED
@@ -1,17 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- import { EventEmitter } from './event-emitter';
10
- import { EventEmitterOptions } from './types';
11
-
12
- /**
13
- * Factory function for creating event emitters
14
- */
15
- export function createEventEmitter(options?: EventEmitterOptions): EventEmitter {
16
- return new EventEmitter(options);
17
- }
package/src/index.ts DELETED
@@ -1,11 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- export { EventEmitter } from './event-emitter';
10
- export { createEventEmitter } from './factory';
11
- export type { EventHandler, EventSubscription, EventEmitterOptions } from './types';
package/src/types.ts DELETED
@@ -1,46 +0,0 @@
1
- /*
2
- Copyright (c) 2025 Bernier LLC
3
-
4
- This file is licensed to the client under a limited-use license.
5
- The client may use and modify this code *only within the scope of the project it was delivered for*.
6
- Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
- */
8
-
9
- /**
10
- * Event handler function
11
- */
12
- export type EventHandler<T = any> = (data: T) => void | Promise<void>;
13
-
14
- /**
15
- * Event subscription
16
- */
17
- export interface EventSubscription {
18
- /** Unique subscription ID */
19
- id: string;
20
-
21
- /** Event type */
22
- eventType: string;
23
-
24
- /** Handler function */
25
- handler: EventHandler;
26
-
27
- /** Whether this is a one-time subscription */
28
- once: boolean;
29
-
30
- /** Unsubscribe function */
31
- unsubscribe: () => void;
32
- }
33
-
34
- /**
35
- * Event emitter options
36
- */
37
- export interface EventEmitterOptions {
38
- /** Maximum listeners per event (0 = unlimited) */
39
- maxListeners?: number;
40
-
41
- /** Whether to log events */
42
- logEvents?: boolean;
43
-
44
- /** Whether to capture errors */
45
- captureErrors?: boolean;
46
- }
package/tsconfig.json DELETED
@@ -1,22 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2020",
4
- "module": "commonjs",
5
- "lib": ["ES2020"],
6
- "declaration": true,
7
- "outDir": "./dist",
8
- "rootDir": "./src",
9
- "strict": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "forceConsistentCasingInFileNames": true,
13
- "moduleResolution": "node",
14
- "resolveJsonModule": true,
15
- "noUnusedLocals": true,
16
- "noUnusedParameters": true,
17
- "noImplicitReturns": true,
18
- "noFallthroughCasesInSwitch": true
19
- },
20
- "include": ["src/**/*"],
21
- "exclude": ["node_modules", "dist", "__tests__"]
22
- }