asljs-eventful 0.4.2 → 0.4.3

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,10 @@
1
+ import { type EventMap, type Eventful, type EventfulOptions } from './types.js';
2
+ export declare class EventfulBase<E extends EventMap = EventMap> implements Eventful<E> {
3
+ on: Eventful<E>['on'];
4
+ once: Eventful<E>['once'];
5
+ off: Eventful<E>['off'];
6
+ emit: Eventful<E>['emit'];
7
+ emitAsync: Eventful<E>['emitAsync'];
8
+ has: Eventful<E>['has'];
9
+ constructor(options?: EventfulOptions);
10
+ }
@@ -0,0 +1,6 @@
1
+ import { type EventName, type Listener } from './types.js';
2
+ export interface EventfulLike {
3
+ on(event: EventName, listener: Listener): () => boolean;
4
+ }
5
+ export declare function isEventfulLike(value: unknown): value is EventfulLike;
6
+ export declare function asEventfulLike(value: unknown): EventfulLike | undefined;
@@ -0,0 +1,2 @@
1
+ import { type EventfulFn } from './types.js';
2
+ export declare const eventful: EventfulFn;
@@ -0,0 +1,6 @@
1
+ import { type EventName } from './types.js';
2
+ export declare function eventNameTypeGuard(value: unknown): asserts value is EventName;
3
+ export declare function isFunction(value: unknown): value is Function;
4
+ export declare function asFunction(value: unknown): Function | undefined;
5
+ export declare function isObject(value: unknown): value is object;
6
+ export declare function functionTypeGuard(value: unknown): asserts value is Function;
@@ -0,0 +1,98 @@
1
+ export type EventName = string | symbol;
2
+ export type EventMap = Record<EventName, unknown[]>;
3
+ export type Listener<Args extends unknown[] = unknown[]> = (...args: Args) => unknown;
4
+ export interface ListenerErrorArgs {
5
+ error: unknown;
6
+ object: object | Function;
7
+ event: EventName;
8
+ listener: Function;
9
+ }
10
+ export declare class ListenerError extends Error implements ListenerErrorArgs {
11
+ error: unknown;
12
+ object: object | Function;
13
+ event: EventName;
14
+ listener: Function;
15
+ constructor(message: string, error: unknown, object: object | Function, event: EventName, listener: Function);
16
+ }
17
+ type TraceAction = 'new' | 'on' | 'off' | 'emit' | 'emitAsync';
18
+ type TracePayloadByAction = {
19
+ new: {
20
+ object: object | Function;
21
+ };
22
+ on: {
23
+ object: object | Function;
24
+ event: EventName;
25
+ listener: Function;
26
+ };
27
+ off: {
28
+ object: object | Function;
29
+ event: EventName;
30
+ listener: Function;
31
+ };
32
+ emit: {
33
+ object: object | Function;
34
+ listeners: Function[];
35
+ event: EventName;
36
+ args: unknown[];
37
+ };
38
+ emitAsync: {
39
+ object: object | Function;
40
+ listeners: Function[];
41
+ event: EventName;
42
+ args: unknown[];
43
+ };
44
+ };
45
+ export type TraceFn = <A extends TraceAction>(action: A, args: TracePayloadByAction[A]) => void;
46
+ export type ErrorFn = (error: ListenerErrorArgs) => void;
47
+ export type EventfulFn = EventfulFactory & Eventful;
48
+ export interface EventfulFactory {
49
+ <T extends object | Function | undefined, E extends EventMap = EventMap>(object?: T, options?: EventfulOptions): (T extends undefined ? {} : T) & Eventful<E>;
50
+ }
51
+ export interface EventfulOptions {
52
+ /**
53
+ * If true, exceptions from listeners are propagated (fail fast).
54
+ * When false, errors are isolated (ignored) after calling `error` hook.
55
+ */
56
+ strict?: boolean;
57
+ /**
58
+ * Optional tracing hook. Receives action name and a safe payload.
59
+ * Actions include: 'new', 'on', 'off', 'emit', 'emitAsync'.
60
+ * Use to integrate with your logger without exposing internals.
61
+ */
62
+ trace?: TraceFn;
63
+ /**
64
+ * Optional error hook. Receives structured context of listener failures
65
+ * (error, object, event, listener). Called for sync and async errors.
66
+ */
67
+ error?: ErrorFn;
68
+ }
69
+ export interface Eventful<E extends EventMap = EventMap> {
70
+ /**
71
+ * Subscribe to an event. Returns an unsubscribe function.
72
+ */
73
+ on<K extends keyof E & EventName>(event: K, listener: Listener<E[K]>): () => boolean;
74
+ /**
75
+ * Subscribe once to an event. Returns an unsubscribe function
76
+ * (called automatically).
77
+ */
78
+ once<K extends keyof E & EventName>(event: K, listener: Listener<E[K]>): () => boolean;
79
+ /**
80
+ * Unsubscribe a previously registered listener. Returns true if removed.
81
+ */
82
+ off<K extends keyof E & EventName>(event: K, listener: Listener<E[K]>): boolean;
83
+ /**
84
+ * Emit an event synchronously. All listeners run in order.
85
+ * Errors are isolated (ignored) unless `strict` is true.
86
+ */
87
+ emit<K extends keyof E & EventName>(event: K, ...args: E[K]): void;
88
+ /**
89
+ * Emit an event and wait for all listeners (run in parallel).
90
+ * Errors are isolated (ignored) unless `strict` is true.
91
+ */
92
+ emitAsync<K extends keyof E & EventName>(event: K, ...args: E[K]): Promise<void>;
93
+ /**
94
+ * Returns true if there is at least one listener for the event.
95
+ */
96
+ has<K extends keyof E & EventName>(event: K): boolean;
97
+ }
98
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asljs-eventful",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "Lightweight event helper adding on/off/emit to any object.",
5
5
  "files": [
6
6
  "dist/**",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "scripts": {
40
40
  "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
41
- "build": "npx tsc -p tsconfig.json",
41
+ "build": "npx tsc -p tsconfig.build.json",
42
42
  "build:test": "npx tsc -p tsconfig.test.json",
43
43
  "lint": "npx eslint .",
44
44
  "lint:fix": "npx eslint . --fix",
@@ -1,22 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { EventfulBase, } from './eventful-base.js';
4
- test('EventfulBase wires eventful methods in constructor', () => {
5
- class Demo extends EventfulBase {
6
- }
7
- const demo = new Demo();
8
- let seen = null;
9
- demo.on('ping', value => seen = value);
10
- demo.emit('ping', 7);
11
- assert.equal(seen, 7);
12
- });
13
- test('EventfulBase passes options to eventful setup', () => {
14
- class Demo extends EventfulBase {
15
- }
16
- const demo = new Demo({ strict: true,
17
- error: () => { } });
18
- demo.on('boom', () => {
19
- throw new Error('boom');
20
- });
21
- assert.throws(() => demo.emit('boom'), Error);
22
- });
@@ -1,19 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { eventful, } from './eventful.js';
4
- import { asEventfulLike, isEventfulLike } from './eventful-like.js';
5
- test('isEventfulLike returns true for eventful instances', () => {
6
- const value = eventful();
7
- assert.equal(isEventfulLike(value), true);
8
- });
9
- test('asEventfulLike returns value when compatible', () => {
10
- const value = eventful();
11
- const converted = asEventfulLike(value);
12
- assert.equal(converted, value);
13
- const typed = converted;
14
- assert.ok(typed);
15
- });
16
- test('asEventfulLike returns undefined when incompatible', () => {
17
- assert.equal(asEventfulLike({}), undefined);
18
- assert.equal(asEventfulLike(42), undefined);
19
- });
@@ -1,206 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { eventful, } from './eventful.js';
4
- import { EventfulBase, } from './eventful-base.js';
5
- test('eventful extends an object', () => {
6
- const original = {};
7
- const enhanced = eventful(original);
8
- assert.equal(enhanced, original);
9
- assertEventfulMethods(enhanced);
10
- });
11
- test('eventful extends a function', () => {
12
- const original = () => { };
13
- const enhanced = eventful(original);
14
- assert.equal(enhanced, original);
15
- assertEventfulMethods(enhanced);
16
- });
17
- test('eventful can be called without arguments', () => {
18
- const enhanced = eventful();
19
- assert.ok(enhanced !== null);
20
- assertEventfulMethods(enhanced);
21
- });
22
- test('eventful can be extended by inheritance', () => {
23
- class MyClass extends EventfulBase {
24
- constructor(name) {
25
- super();
26
- this.name = name;
27
- }
28
- greet() {
29
- this.emit('greet', `Hello, ${this.name}`);
30
- }
31
- }
32
- const instance = new MyClass('Alice');
33
- let greeting = null;
34
- instance.on('greet', message => greeting = message);
35
- instance.greet();
36
- assert.equal(greeting, 'Hello, Alice');
37
- });
38
- test('eventful can be added during construction', () => {
39
- class MyClass {
40
- constructor(name) {
41
- eventful(this);
42
- this.name = name;
43
- }
44
- greet() {
45
- this.emit('greet', `Hello, ${this.name}`);
46
- }
47
- }
48
- const instance = new MyClass('Alice');
49
- let greeting = null;
50
- instance.on('greet', message => greeting = message);
51
- instance.greet();
52
- assert.equal(greeting, 'Hello, Alice');
53
- });
54
- test('trace is called on creation with action "new"', () => {
55
- const recorder = createRecorder();
56
- const object = eventful({}, { trace: recorder.write });
57
- const creation = recorder.records().find(item => item.action === 'new');
58
- assert.ok(creation);
59
- assert.equal(creation.payload.object, object);
60
- });
61
- test('global trace is called on creation with action "new"', () => {
62
- const recorder = createRecorder();
63
- const off = eventful.on('new', (...args) => recorder.write('new', args[0]));
64
- try {
65
- const object = eventful({}, { trace: recorder.write });
66
- const creation = recorder.records().find(item => item.action === 'new');
67
- assert.ok(creation);
68
- assert.equal(creation.payload.object, object);
69
- }
70
- finally {
71
- off();
72
- }
73
- });
74
- test('eventful throws when an object has one of the event emitter methods', () => {
75
- for (const method of ['on', 'once', 'off', 'emit', 'emitAsync', 'has']) {
76
- assert.throws(() => eventful({
77
- [method]: () => { }
78
- }));
79
- }
80
- });
81
- test('exceptions in listeners are suppressed in async emit by default', async () => {
82
- const obj = eventful();
83
- obj.on('test', () => { throw new Error('test error'); });
84
- await assert.doesNotReject(() => obj.emitAsync('test'));
85
- });
86
- function assertEventfulMethods(object) {
87
- const candidate = object;
88
- assert.equal(typeof candidate.on, 'function');
89
- assert.equal(typeof candidate.off, 'function');
90
- assert.equal(typeof candidate.emit, 'function');
91
- assert.equal(typeof candidate.emitAsync, 'function');
92
- assert.equal(typeof candidate.has, 'function');
93
- }
94
- test('exceptions in listeners are suppressed in async emit by default', async () => {
95
- const obj = eventful();
96
- obj.on('test', () => { throw new Error('test error'); });
97
- await assert.doesNotReject(() => obj.emitAsync('test'));
98
- });
99
- test('exceptions in listeners are suppressed in emit by default', () => {
100
- const obj = eventful();
101
- obj.on('test', () => { throw new Error('test error'); });
102
- assert.doesNotThrow(() => obj.emit('test'));
103
- });
104
- test('strict mode propagates exceptions in listeners in async emit', async () => {
105
- const obj = eventful({}, { error: () => { },
106
- strict: true });
107
- obj.on('test', () => { throw new Error('test error'); });
108
- await assert.rejects(() => obj.emitAsync('test'));
109
- });
110
- test('strict mode propagates exceptions in listeners in emit', () => {
111
- const obj = eventful({}, { error: () => { },
112
- strict: true });
113
- obj.on('test', () => { throw new Error('test error'); });
114
- assert.throws(() => obj.emit('test'), Error);
115
- });
116
- test('non-strict runs other listeners even if one fails', async () => {
117
- const obj = eventful({}, { error: () => { } });
118
- let ran = 0;
119
- obj.on('test', () => ran += 1);
120
- obj.on('test', () => { throw new Error('boom'); });
121
- obj.on('test', () => ran += 1);
122
- await assert.doesNotReject(() => obj.emitAsync('test'));
123
- assert.equal(ran, 2);
124
- });
125
- test('trace receives safe payload and action names', async () => {
126
- const recorder = createRecorder();
127
- const obj = eventful({}, { trace: recorder.write });
128
- const off = obj.on('e', () => { });
129
- obj.emit('e', 1, 2);
130
- await obj.emitAsync('e', 3, 4);
131
- off();
132
- assert.ok(recorder.records().find(item => item.action === 'on'));
133
- assert.ok(recorder.records().find(item => item.action === 'emit'));
134
- assert.ok(recorder.records().find(item => item.action === 'emitAsync'));
135
- const emitTrace = recorder.records().find(item => item.action === 'emit');
136
- assert.ok(emitTrace);
137
- assert.ok(Array.isArray(emitTrace.payload.listeners));
138
- assert.equal(emitTrace.payload.event, 'e');
139
- assert.deepEqual(emitTrace.payload.args, [1, 2]);
140
- const emitAsyncTrace = recorder.records().find(item => item.action === 'emitAsync');
141
- assert.ok(emitAsyncTrace);
142
- assert.ok(Array.isArray(emitAsyncTrace.payload.listeners));
143
- assert.equal(emitAsyncTrace.payload.event, 'e');
144
- assert.deepEqual(emitAsyncTrace.payload.args, [3, 4]);
145
- });
146
- test('error hook runs for async rejection (non-strict)', async () => {
147
- let errors = 0;
148
- const obj = eventful({}, { error: () => errors += 1 });
149
- obj.on('e', async () => { throw new Error('reject'); });
150
- await assert.doesNotReject(() => obj.emitAsync('e'));
151
- assert.equal(errors, 1);
152
- });
153
- test('has reflects subscribe and unsubscribe', () => {
154
- const obj = eventful();
155
- assert.equal(obj.has('x'), false);
156
- const off = obj.on('x', () => { });
157
- assert.equal(obj.has('x'), true);
158
- off();
159
- assert.equal(obj.has('x'), false);
160
- });
161
- test('strict mode propagates async rejections', async () => {
162
- const obj = eventful({}, { error: () => { },
163
- strict: true });
164
- obj.on('e', async () => { throw new Error('nope'); });
165
- await assert.rejects(() => obj.emitAsync('e'));
166
- });
167
- test('emit ignores errors when no error hook (non-strict)', () => {
168
- const obj = eventful();
169
- obj.on('x', () => { throw new Error('boom'); });
170
- assert.doesNotThrow(() => obj.emit('x'));
171
- });
172
- test('throw in global error listener does not loop', () => {
173
- let globalErrorCalls = 0;
174
- const off = eventful.on('error', () => {
175
- globalErrorCalls += 1;
176
- if (globalErrorCalls > 1)
177
- throw new Error('global error listener loop');
178
- throw new Error('boom');
179
- });
180
- try {
181
- const obj = eventful();
182
- obj.on('e', () => { throw new Error('listener failed'); });
183
- assert.throws(() => obj.emit('e'), Error);
184
- assert.equal(globalErrorCalls, 1);
185
- }
186
- finally {
187
- off();
188
- }
189
- });
190
- test('event must be string or symbol', () => {
191
- const obj = eventful();
192
- assert.throws(() => obj.on(123, () => { }), TypeError);
193
- assert.throws(() => obj.emit(123), TypeError);
194
- const s = Symbol('e');
195
- assert.doesNotThrow(() => obj.on(s, () => { }));
196
- assert.doesNotThrow(() => obj.emit(s));
197
- });
198
- export function createRecorder() {
199
- const records = [];
200
- return {
201
- write: (action, payload) => {
202
- records.push({ action, payload });
203
- },
204
- records: () => records
205
- };
206
- }
@@ -1,24 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { eventNameTypeGuard, functionTypeGuard, isFunction, isObject, } from './guards.js';
4
- test('eventNameTypeGuard accepts string and symbol', () => {
5
- assert.doesNotThrow(() => eventNameTypeGuard('event'));
6
- assert.doesNotThrow(() => eventNameTypeGuard(Symbol('event')));
7
- });
8
- test('eventNameTypeGuard throws for invalid values', () => {
9
- assert.throws(() => eventNameTypeGuard(42), TypeError);
10
- assert.throws(() => eventNameTypeGuard(null), TypeError);
11
- });
12
- test('isFunction returns expected result', () => {
13
- assert.equal(isFunction(() => { }), true);
14
- assert.equal(isFunction({}), false);
15
- });
16
- test('isObject returns expected result', () => {
17
- assert.equal(isObject({ key: 'value' }), true);
18
- assert.equal(isObject(null), false);
19
- assert.equal(isObject(() => { }), false);
20
- });
21
- test('functionTypeGuard validates value', () => {
22
- assert.doesNotThrow(() => functionTypeGuard(() => { }));
23
- assert.throws(() => functionTypeGuard('nope'), TypeError);
24
- });
@@ -1,16 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import { ListenerError, } from './types.js';
4
- test('ListenerError extends Error and stores context', () => {
5
- const inner = new Error('inner');
6
- const object = { id: 1 };
7
- const listener = () => { };
8
- const error = new ListenerError('failed', inner, object, 'test', listener);
9
- assert.ok(error instanceof Error);
10
- assert.equal(error.name, 'ListenerError');
11
- assert.equal(error.message, 'failed');
12
- assert.equal(error.error, inner);
13
- assert.equal(error.object, object);
14
- assert.equal(error.event, 'test');
15
- assert.equal(error.listener, listener);
16
- });