@ahoo-wang/fetcher-eventbus 2.8.6 → 2.8.8

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,16 @@
1
+ import { TypedEventBus } from './typedEventBus';
2
+ import { EventHandler, EventType } from './types';
3
+ export declare abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {
4
+ protected eventHandlers: EventHandler<EVENT>[];
5
+ abstract type: EventType;
6
+ /**
7
+ * Gets a copy of all registered event handlers, sorted by order
8
+ */
9
+ get handlers(): EventHandler<EVENT>[];
10
+ destroy(): void;
11
+ protected handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void>;
12
+ abstract emit(event: EVENT): Promise<void>;
13
+ abstract off(name: string): boolean;
14
+ abstract on(handler: EventHandler<EVENT>): boolean;
15
+ }
16
+ //# sourceMappingURL=abstractTypedEventBus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"abstractTypedEventBus.d.ts","sourceRoot":"","sources":["../src/abstractTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAElD,8BAAsB,qBAAqB,CAAC,KAAK,CAAE,YAAW,aAAa,CAAC,KAAK,CAAC;IAChF,SAAS,CAAC,aAAa,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAM;IACpD,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAEzB;;OAEG;IACH,IAAI,QAAQ,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAEpC;IAED,OAAO;cAIS,WAAW,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAQtF,QAAQ,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAE1C,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAEnC,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CACnD"}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  export * from './eventBus';
2
+ export * from './abstractTypedEventBus';
2
3
  export * from './parallelTypedEventBus';
3
4
  export * from './serialTypedEventBus';
4
5
  export * from './typedEventBus';
5
6
  export * from './broadcastTypedEventBus';
6
7
  export * from './types';
8
+ export * from './nameGenerator';
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC"}
package/dist/index.es.js CHANGED
@@ -1,5 +1,5 @@
1
- import { toSorted as o } from "@ahoo-wang/fetcher";
2
- class l {
1
+ import { toSorted as a } from "@ahoo-wang/fetcher";
2
+ class c {
3
3
  /**
4
4
  * Creates a generic event bus
5
5
  *
@@ -51,14 +51,9 @@ class l {
51
51
  this.buses.clear();
52
52
  }
53
53
  }
54
- class d {
55
- /**
56
- * Creates a parallel typed event bus
57
- *
58
- * @param type - The event type identifier for this bus
59
- */
60
- constructor(e) {
61
- this.type = e, this.eventHandlers = [];
54
+ class i {
55
+ constructor() {
56
+ this.eventHandlers = [];
62
57
  }
63
58
  /**
64
59
  * Gets a copy of all registered event handlers, sorted by order
@@ -66,6 +61,26 @@ class d {
66
61
  get handlers() {
67
62
  return [...this.eventHandlers];
68
63
  }
64
+ destroy() {
65
+ this.eventHandlers = [];
66
+ }
67
+ async handleEvent(e, t) {
68
+ try {
69
+ e.handle(t);
70
+ } catch (s) {
71
+ console.warn(`Event handler error for ${e.name}:`, s);
72
+ }
73
+ }
74
+ }
75
+ class u extends i {
76
+ /**
77
+ * Creates a parallel typed event bus
78
+ *
79
+ * @param type - The event type identifier for this bus
80
+ */
81
+ constructor(e) {
82
+ super(), this.type = e;
83
+ }
69
84
  /**
70
85
  * Emits an event to all registered handlers in parallel
71
86
  *
@@ -75,17 +90,11 @@ class d {
75
90
  * @param event - The event to emit
76
91
  */
77
92
  async emit(e) {
78
- const t = [], s = this.eventHandlers.map(async (r) => {
79
- try {
80
- await r.handle(e);
81
- } catch (a) {
82
- console.warn(`Event handler error for ${r.name}:`, a);
83
- } finally {
84
- r.once && t.push(r);
85
- }
93
+ const t = [], s = this.eventHandlers.map(async (n) => {
94
+ await this.handleEvent(n, e), n.once && t.push(n);
86
95
  });
87
96
  await Promise.all(s), t.length > 0 && (this.eventHandlers = this.eventHandlers.filter(
88
- (r) => !t.includes(r)
97
+ (n) => !t.includes(n)
89
98
  ));
90
99
  }
91
100
  /**
@@ -110,24 +119,15 @@ class d {
110
119
  const t = this.eventHandlers;
111
120
  return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = [...t, e], !0);
112
121
  }
113
- destroy() {
114
- this.eventHandlers = [];
115
- }
116
122
  }
117
- class h {
123
+ class d extends i {
118
124
  /**
119
125
  * Creates an in-memory typed event bus
120
126
  *
121
127
  * @param type - The event type identifier for this bus
122
128
  */
123
129
  constructor(e) {
124
- this.type = e, this.sortedHandlers = [];
125
- }
126
- /**
127
- * Gets a copy of all registered event handlers, sorted by order
128
- */
129
- get handlers() {
130
- return [...this.sortedHandlers];
130
+ super(), this.type = e;
131
131
  }
132
132
  /**
133
133
  * Emits an event to all registered handlers serially
@@ -139,16 +139,10 @@ class h {
139
139
  */
140
140
  async emit(e) {
141
141
  const t = [];
142
- for (const s of this.sortedHandlers)
143
- try {
144
- await s.handle(e);
145
- } catch (r) {
146
- console.warn(`Event handler error for ${s.name}:`, r);
147
- } finally {
148
- s.once && t.push(s);
149
- }
150
- t.length > 0 && (this.sortedHandlers = o(
151
- this.sortedHandlers.filter((s) => !t.includes(s))
142
+ for (const s of this.eventHandlers)
143
+ await this.handleEvent(s, e), s.once && t.push(s);
144
+ t.length > 0 && (this.eventHandlers = a(
145
+ this.eventHandlers.filter((s) => !t.includes(s))
152
146
  ));
153
147
  }
154
148
  /**
@@ -158,8 +152,8 @@ class h {
158
152
  * @returns true if a handler was removed, false otherwise
159
153
  */
160
154
  off(e) {
161
- const t = this.sortedHandlers;
162
- return t.some((s) => s.name === e) ? (this.sortedHandlers = o(t, (s) => s.name !== e), !0) : !1;
155
+ const t = this.eventHandlers;
156
+ return t.some((s) => s.name === e) ? (this.eventHandlers = a(t, (s) => s.name !== e), !0) : !1;
163
157
  }
164
158
  /**
165
159
  * Adds an event handler if not already present
@@ -170,14 +164,11 @@ class h {
170
164
  * @returns true if the handler was added, false if a handler with the same name already exists
171
165
  */
172
166
  on(e) {
173
- const t = this.sortedHandlers;
174
- return t.some((s) => s.name === e.name) ? !1 : (this.sortedHandlers = o([...t, e]), !0);
175
- }
176
- destroy() {
177
- this.sortedHandlers = [];
167
+ const t = this.eventHandlers;
168
+ return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = a([...t, e]), !0);
178
169
  }
179
170
  }
180
- class c {
171
+ class f {
181
172
  /**
182
173
  * Creates a broadcast typed event bus
183
174
  *
@@ -187,11 +178,11 @@ class c {
187
178
  constructor(e, t) {
188
179
  this.delegate = e, this.type = e.type;
189
180
  const s = t ?? `_broadcast_:${this.type}`;
190
- this.broadcastChannel = new BroadcastChannel(s), this.broadcastChannel.onmessage = async (r) => {
181
+ this.broadcastChannel = new BroadcastChannel(s), this.broadcastChannel.onmessage = async (n) => {
191
182
  try {
192
- await this.delegate.emit(r.data);
193
- } catch (a) {
194
- console.warn(`Broadcast event handler error for ${this.type}:`, a);
183
+ await this.delegate.emit(n.data);
184
+ } catch (o) {
185
+ console.warn(`Broadcast event handler error for ${this.type}:`, o);
195
186
  }
196
187
  };
197
188
  }
@@ -234,10 +225,27 @@ class c {
234
225
  this.broadcastChannel.close();
235
226
  }
236
227
  }
228
+ class l {
229
+ constructor() {
230
+ this.namingCounter = 0;
231
+ }
232
+ /**
233
+ * Generates a unique name by appending an incrementing counter to the prefix
234
+ * @param prefix - The prefix for the generated name
235
+ * @returns The generated unique name
236
+ */
237
+ generate(e) {
238
+ return this.namingCounter++, `${e}_${this.namingCounter}`;
239
+ }
240
+ }
241
+ const m = new l();
237
242
  export {
238
- c as BroadcastTypedEventBus,
239
- l as EventBus,
240
- d as ParallelTypedEventBus,
241
- h as SerialTypedEventBus
243
+ i as AbstractTypedEventBus,
244
+ f as BroadcastTypedEventBus,
245
+ l as DefaultNameGenerator,
246
+ c as EventBus,
247
+ u as ParallelTypedEventBus,
248
+ d as SerialTypedEventBus,
249
+ m as nameGenerator
242
250
  };
243
251
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/eventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n private eventHandlers: EventHandler<EVENT>[] = [];\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n }\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n try {\n await handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n } finally {\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n private sortedHandlers: EventHandler<EVENT>[] = [];\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n }\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.sortedHandlers];\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.sortedHandlers) {\n try {\n await handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n } finally {\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n }\n if (onceHandlers.length > 0) {\n this.sortedHandlers = toSorted(\n this.sortedHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.sortedHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.sortedHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.sortedHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.sortedHandlers = toSorted([...original, handler]);\n return true;\n }\n\n destroy() {\n this.sortedHandlers = [];\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","ParallelTypedEventBus","onceHandlers","promises","e","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName"],"mappings":";AAkCO,MAAMA,EAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/D,YAA6BC,GAA4C;AAA5C,SAAA,uBAAAA,GAP7B,KAAiB,4BAAoD,IAAA;AAAA,EAQrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,GACEC,GACAC,GACS;AACT,QAAIC,IAAM,KAAK,MAAM,IAAIF,CAAI;AAC7B,WAAKE,MACHA,IAAM,KAAK,qBAAqBF,CAAI,GACpC,KAAK,MAAM,IAAIA,GAAME,CAAG,IAEnBA,GAAK,GAAGD,CAAO,KAAK;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,IACED,GACAG,GACS;AACT,WAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,KAAK;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,KACEH,G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BAAiB,MAAA;AAAA,EACxB;AACF;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName","DefaultNameGenerator","prefix","nameGenerator"],"mappings":";AAkCO,MAAMA,EAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/D,YAA6BC,GAA4C;AAA5C,SAAA,uBAAAA,GAP7B,KAAiB,4BAAoD,IAAA;AAAA,EAQrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,GACEC,GACAC,GACS;AACT,QAAIC,IAAM,KAAK,MAAM,IAAIF,CAAI;AAC7B,WAAKE,MACHA,IAA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AK,SAAS,IAAIA,CAAI;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,GAAGF,GAAuC;AACxC,WAAO,KAAK,SAAS,GAAGA,CAAO;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU;AACR,SAAK,iBAAiB,MAAA;AAAA,EACxB;AACF;ACtFO,MAAMiB,EAA8C;AAAA,EAApD,cAAA;AACL,SAAQ,gBAAwB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,SAASC,GAAwB;AAC/B,gBAAK,iBACE,GAAGA,CAAM,IAAI,KAAK,aAAa;AAAA,EACxC;AACF;AAKO,MAAMC,IAAgB,IAAIF,EAAA;"}
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(n,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],a):(n=typeof globalThis<"u"?globalThis:n||self,a(n.FetcherEventBus={},n.Fetcher))})(this,(function(n,a){"use strict";class l{constructor(e){this.typeEventBusSupplier=e,this.buses=new Map}on(e,t){let s=this.buses.get(e);return s||(s=this.typeEventBusSupplier(e),this.buses.set(e,s)),s?.on(t)??!1}off(e,t){return this.buses.get(e)?.off(t)??!1}emit(e,t){return this.buses.get(e)?.emit(t)}destroy(){for(const e of this.buses.values())e.destroy();this.buses.clear()}}class d{constructor(e){this.type=e,this.eventHandlers=[]}get handlers(){return[...this.eventHandlers]}async emit(e){const t=[],s=this.eventHandlers.map(async r=>{try{await r.handle(e)}catch(i){console.warn(`Event handler error for ${r.name}:`,i)}finally{r.once&&t.push(r)}});await Promise.all(s),t.length>0&&(this.eventHandlers=this.eventHandlers.filter(r=>!t.includes(r)))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=t.filter(s=>s.name!==e),!0):!1}on(e){const t=this.eventHandlers;return t.some(s=>s.name===e.name)?!1:(this.eventHandlers=[...t,e],!0)}destroy(){this.eventHandlers=[]}}class h{constructor(e){this.type=e,this.sortedHandlers=[]}get handlers(){return[...this.sortedHandlers]}async emit(e){const t=[];for(const s of this.sortedHandlers)try{await s.handle(e)}catch(r){console.warn(`Event handler error for ${s.name}:`,r)}finally{s.once&&t.push(s)}t.length>0&&(this.sortedHandlers=a.toSorted(this.sortedHandlers.filter(s=>!t.includes(s))))}off(e){const t=this.sortedHandlers;return t.some(s=>s.name===e)?(this.sortedHandlers=a.toSorted(t,s=>s.name!==e),!0):!1}on(e){const t=this.sortedHandlers;return t.some(s=>s.name===e.name)?!1:(this.sortedHandlers=a.toSorted([...t,e]),!0)}destroy(){this.sortedHandlers=[]}}class u{constructor(e,t){this.delegate=e,this.type=e.type;const s=t??`_broadcast_:${this.type}`;this.broadcastChannel=new BroadcastChannel(s),this.broadcastChannel.onmessage=async r=>{try{await this.delegate.emit(r.data)}catch(i){console.warn(`Broadcast event handler error for ${this.type}:`,i)}}}get handlers(){return this.delegate.handlers}async emit(e){await this.delegate.emit(e),this.broadcastChannel.postMessage(e)}off(e){return this.delegate.off(e)}on(e){return this.delegate.on(e)}destroy(){this.broadcastChannel.close()}}n.BroadcastTypedEventBus=u,n.EventBus=l,n.ParallelTypedEventBus=d,n.SerialTypedEventBus=h,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(n,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],a):(n=typeof globalThis<"u"?globalThis:n||self,a(n.FetcherEventBus={},n.Fetcher))})(this,(function(n,a){"use strict";class u{constructor(e){this.typeEventBusSupplier=e,this.buses=new Map}on(e,t){let s=this.buses.get(e);return s||(s=this.typeEventBusSupplier(e),this.buses.set(e,s)),s?.on(t)??!1}off(e,t){return this.buses.get(e)?.off(t)??!1}emit(e,t){return this.buses.get(e)?.emit(t)}destroy(){for(const e of this.buses.values())e.destroy();this.buses.clear()}}class o{constructor(){this.eventHandlers=[]}get handlers(){return[...this.eventHandlers]}destroy(){this.eventHandlers=[]}async handleEvent(e,t){try{e.handle(t)}catch(s){console.warn(`Event handler error for ${e.name}:`,s)}}}class h extends o{constructor(e){super(),this.type=e}async emit(e){const t=[],s=this.eventHandlers.map(async r=>{await this.handleEvent(r,e),r.once&&t.push(r)});await Promise.all(s),t.length>0&&(this.eventHandlers=this.eventHandlers.filter(r=>!t.includes(r)))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=t.filter(s=>s.name!==e),!0):!1}on(e){const t=this.eventHandlers;return t.some(s=>s.name===e.name)?!1:(this.eventHandlers=[...t,e],!0)}}class d extends o{constructor(e){super(),this.type=e}async emit(e){const t=[];for(const s of this.eventHandlers)await this.handleEvent(s,e),s.once&&t.push(s);t.length>0&&(this.eventHandlers=a.toSorted(this.eventHandlers.filter(s=>!t.includes(s))))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=a.toSorted(t,s=>s.name!==e),!0):!1}on(e){const t=this.eventHandlers;return t.some(s=>s.name===e.name)?!1:(this.eventHandlers=a.toSorted([...t,e]),!0)}}class c{constructor(e,t){this.delegate=e,this.type=e.type;const s=t??`_broadcast_:${this.type}`;this.broadcastChannel=new BroadcastChannel(s),this.broadcastChannel.onmessage=async r=>{try{await this.delegate.emit(r.data)}catch(v){console.warn(`Broadcast event handler error for ${this.type}:`,v)}}}get handlers(){return this.delegate.handlers}async emit(e){await this.delegate.emit(e),this.broadcastChannel.postMessage(e)}off(e){return this.delegate.off(e)}on(e){return this.delegate.on(e)}destroy(){this.broadcastChannel.close()}}class l{constructor(){this.namingCounter=0}generate(e){return this.namingCounter++,`${e}_${this.namingCounter}`}}const f=new l;n.AbstractTypedEventBus=o,n.BroadcastTypedEventBus=c,n.DefaultNameGenerator=l,n.EventBus=u,n.ParallelTypedEventBus=h,n.SerialTypedEventBus=d,n.nameGenerator=f,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/eventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n private eventHandlers: EventHandler<EVENT>[] = [];\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n }\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n try {\n await handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n } finally {\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n private sortedHandlers: EventHandler<EVENT>[] = [];\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n }\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.sortedHandlers];\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.sortedHandlers) {\n try {\n await handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n } finally {\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n }\n if (onceHandlers.length > 0) {\n this.sortedHandlers = toSorted(\n this.sortedHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.sortedHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.sortedHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.sortedHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.sortedHandlers = toSorted([...original, handler]);\n return true;\n }\n\n destroy() {\n this.sortedHandlers = [];\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","ParallelTypedEventBus","onceHandlers","promises","e","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName"],"mappings":"uSAkCO,MAAMA,CAAoD,CAQ/D,YAA6BC,EAA4C,CAA5C,KAAA,qBAAAA,EAP7B,KAAiB,UAAoD,GAQrE,CAUA,GACEC,EACAC,EACS,CACT,IAAIC,EAAM,KAAK,MAAM,IAAIF,CAAI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GACvD,KAAK,iBAAmB,IAAI,iBAAiBC,CAAW,EACxD,KAAK,iBAAiB,UAAY,MAAMZ,GAAS,CAC/C,GAAI,CACF,MAAM,KAAK,SAAS,KAAKA,EAAM,IAAI,CACrC,OAASI,EAAG,CACV,QAAQ,KAAK,qCAAqC,KAAK,IAAI,IAAKA,CAAC,CACnE,CACF,CACF,CAKA,IAAI,UAAkC,CACpC,OAAO,KAAK,SAAS,QACvB,CAOA,MAAM,KAAKJ,EAA6B,CACtC,MAAM,KAAK,SAAS,KAAKA,CAAK,EAC9B,KAAK,iBAAiB,YAAYA,CAAK,CACzC,CAQA,IAAID,EAAuB,CACzB,OAAO,KAAK,SAAS,IAAIA,CAAI,CAC/B,CAQA,GAAGF,EAAuC,CACxC,OAAO,KAAK,SAAS,GAAGA,CAAO,CACjC,CAKA,SAAU,CACR,KAAK,iBAAiB,MAAA,CACxB,CACF"}
1
+ {"version":3,"file":"index.umd.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName","DefaultNameGenerator","prefix","nameGenerator"],"mappings":"uSAkCO,MAAMA,CAAoD,CAQ/D,YAA6BC,EAA4C,CAA5C,KAAA,qBAAAA,EAP7B,KAAiB,UAAoD,GAQrE,CAUA,GACEC,EACAC,EACS,CACT,IAAIC,EAAM,KAAK,MAAM,IAAIF,CAAI,EAC7B,OAAKE,IACHA,EAAM,KAAK,qBAAqBF,CAAI,EACpC,KAAK,MAAM,IAAIA,EAAME,CAAG,GAEnBA,GAAK,GAAGD,CAAO,GAAK,EAC7B,CAUA,IACED,EACAG,EACS,CACT,OAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,GAAK,EAC5C,CAUA,KACEH,EACAI,EACsB,CACtB,OAAO,KAAK,MAAM,IAAIJ,CAAI,GAAG,KAAKI,CAAK,CACzC,CAKA,SAAgB,CACd,UAAWF,KAAO,KAAK,MAAM,OAAA,EAC3BA,EAAI,QAAA,EAEN,KAAK,MAAM,MAAA,CACb,CACF,CCxFO,MAAeG,CAA6D,CAA5E,aAAA,CACL,KAAU,cAAuC,CAAA,CAAC,CAMlD,IAAI,UAAkC,CACpC,MAAO,CAAC,GAAG,KAAK,aAAa,CAC/B,CAEA,SAAU,CACR,KAAK,cAAgB,CAAA,CACvB,CAEA,MAAgB,YAAYJ,EAA8BG,EAA6B,CACrF,GAAI,CACFH,EAAQ,OAAOG,CAAK,CACtB,OAASE,EAAG,CACV,QAAQ,KAAK,2BAA2BL,EAAQ,IAAI,IAAKK,CAAC,CAC5D,CACF,CAOF,CCZO,MAAMC,UAAqCF,CAA6B,CAO7E,YAA4BL,EAAiB,CAC3C,MAAA,EAD0B,KAAA,KAAAA,CAE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GF,EAAuC,CACxC,MAAMU,EAAW,KAAK,cACtB,OAAIA,EAAS,KAAKD,GAAQA,EAAK,OAAST,EAAQ,IAAI,EAC3C,IAET,KAAK,cAAgBY,EAAAA,SAAS,CAAC,GAAGF,EAAUV,CAAO,CAAC,EAC7C,GACT,CACF,CC1DO,MAAMa,CAA8D,CAUzE,YACmBC,EACjBC,EACA,CAFiB,KAAA,SAAAD,EAGjB,KAAK,KAAOA,EAAS,KACrB,MAAME,EAAcD,GAAW,eAAe,KAAK,IAAI,GACvD,KAAK,iBAAmB,IAAI,iBAAiBC,CAAW,EACxD,KAAK,iBAAiB,UAAY,MAAMb,GAAS,CAC/C,GAAI,CACF,MAAM,KAAK,SAAS,KAAKA,EAAM,IAAI,CACrC,OAASE,EAAG,CACV,QAAQ,KAAK,qCAAqC,KAAK,IAAI,IAAKA,CAAC,CACnE,CACF,CACF,CAKA,IAAI,UAAkC,CACpC,OAAO,KAAK,SAAS,QACvB,CAOA,MAAM,KAAKF,EAA6B,CACtC,MAAM,KAAK,SAAS,KAAKA,CAAK,EAC9B,KAAK,iBAAiB,YAAYA,CAAK,CACzC,CAQA,IAAID,EAAuB,CACzB,OAAO,KAAK,SAAS,IAAIA,CAAI,CAC/B,CAQA,GAAGF,EAAuC,CACxC,OAAO,KAAK,SAAS,GAAGA,CAAO,CACjC,CAKA,SAAU,CACR,KAAK,iBAAiB,MAAA,CACxB,CACF,CCtFO,MAAMiB,CAA8C,CAApD,aAAA,CACL,KAAQ,cAAwB,CAAA,CAOhC,SAASC,EAAwB,CAC/B,YAAK,gBACE,GAAGA,CAAM,IAAI,KAAK,aAAa,EACxC,CACF,CAKO,MAAMC,EAAgB,IAAIF"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Interface for generating unique names with a prefix
3
+ */
4
+ export interface NameGenerator {
5
+ generate(prefix: string): string;
6
+ }
7
+ /**
8
+ * Default implementation of NameGenerator that generates names with incrementing counters
9
+ */
10
+ export declare class DefaultNameGenerator implements NameGenerator {
11
+ private namingCounter;
12
+ /**
13
+ * Generates a unique name by appending an incrementing counter to the prefix
14
+ * @param prefix - The prefix for the generated name
15
+ * @returns The generated unique name
16
+ */
17
+ generate(prefix: string): string;
18
+ }
19
+ /**
20
+ * Default instance of NameGenerator
21
+ */
22
+ export declare const nameGenerator: DefaultNameGenerator;
23
+ //# sourceMappingURL=nameGenerator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nameGenerator.d.ts","sourceRoot":"","sources":["../src/nameGenerator.ts"],"names":[],"mappings":"AAaA;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;CAClC;AAED;;GAEG;AACH,qBAAa,oBAAqB,YAAW,aAAa;IACxD,OAAO,CAAC,aAAa,CAAa;IAElC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;CAIjC;AAED;;GAEG;AACH,eAAO,MAAM,aAAa,sBAA6B,CAAC"}
@@ -1,5 +1,5 @@
1
- import { TypedEventBus } from './typedEventBus';
2
1
  import { EventHandler, EventType } from './types';
2
+ import { AbstractTypedEventBus } from './abstractTypedEventBus';
3
3
  /**
4
4
  * Parallel implementation of TypedEventBus
5
5
  *
@@ -16,19 +16,14 @@ import { EventHandler, EventType } from './types';
16
16
  * await bus.emit('hello'); // Both handlers execute in parallel
17
17
  * ```
18
18
  */
19
- export declare class ParallelTypedEventBus<EVENT> implements TypedEventBus<EVENT> {
19
+ export declare class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {
20
20
  readonly type: EventType;
21
- private eventHandlers;
22
21
  /**
23
22
  * Creates a parallel typed event bus
24
23
  *
25
24
  * @param type - The event type identifier for this bus
26
25
  */
27
26
  constructor(type: EventType);
28
- /**
29
- * Gets a copy of all registered event handlers, sorted by order
30
- */
31
- get handlers(): EventHandler<EVENT>[];
32
27
  /**
33
28
  * Emits an event to all registered handlers in parallel
34
29
  *
@@ -54,6 +49,5 @@ export declare class ParallelTypedEventBus<EVENT> implements TypedEventBus<EVENT
54
49
  * @returns true if the handler was added, false if a handler with the same name already exists
55
50
  */
56
51
  on(handler: EventHandler<EVENT>): boolean;
57
- destroy(): void;
58
52
  }
59
53
  //# sourceMappingURL=parallelTypedEventBus.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"parallelTypedEventBus.d.ts","sourceRoot":"","sources":["../src/parallelTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAElD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,qBAAqB,CAAC,KAAK,CAAE,YAAW,aAAa,CAAC,KAAK,CAAC;aAQ3C,IAAI,EAAE,SAAS;IAP3C,OAAO,CAAC,aAAa,CAA6B;IAElD;;;;OAIG;gBACyB,IAAI,EAAE,SAAS;IAG3C;;OAEG;IACH,IAAI,QAAQ,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAEpC;IAED;;;;;;;OAOG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBvC;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAS1B;;;;;;;OAOG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;IASzC,OAAO;CAGR"}
1
+ {"version":3,"file":"parallelTypedEventBus.d.ts","sourceRoot":"","sources":["../src/parallelTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,qBAAqB,CAAC,KAAK,CAAE,SAAQ,qBAAqB,CAAC,KAAK,CAAC;aAOhD,IAAI,EAAE,SAAS;IAL3C;;;;OAIG;gBACyB,IAAI,EAAE,SAAS;IAI3C;;;;;;;OAOG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAgBvC;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAS1B;;;;;;;OAOG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CAQ1C"}
@@ -1,5 +1,5 @@
1
- import { TypedEventBus } from './typedEventBus';
2
1
  import { EventHandler, EventType } from './types';
2
+ import { AbstractTypedEventBus } from './abstractTypedEventBus';
3
3
  /**
4
4
  * Serial implementation of TypedEventBus
5
5
  *
@@ -16,19 +16,14 @@ import { EventHandler, EventType } from './types';
16
16
  * await bus.emit('hello'); // handler1 executes first, then handler2
17
17
  * ```
18
18
  */
19
- export declare class SerialTypedEventBus<EVENT> implements TypedEventBus<EVENT> {
19
+ export declare class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {
20
20
  readonly type: EventType;
21
- private sortedHandlers;
22
21
  /**
23
22
  * Creates an in-memory typed event bus
24
23
  *
25
24
  * @param type - The event type identifier for this bus
26
25
  */
27
26
  constructor(type: EventType);
28
- /**
29
- * Gets a copy of all registered event handlers, sorted by order
30
- */
31
- get handlers(): EventHandler<EVENT>[];
32
27
  /**
33
28
  * Emits an event to all registered handlers serially
34
29
  *
@@ -54,6 +49,5 @@ export declare class SerialTypedEventBus<EVENT> implements TypedEventBus<EVENT>
54
49
  * @returns true if the handler was added, false if a handler with the same name already exists
55
50
  */
56
51
  on(handler: EventHandler<EVENT>): boolean;
57
- destroy(): void;
58
52
  }
59
53
  //# sourceMappingURL=serialTypedEventBus.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serialTypedEventBus.d.ts","sourceRoot":"","sources":["../src/serialTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EA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1C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-eventbus",
3
- "version": "2.8.6",
3
+ "version": "2.8.8",
4
4
  "description": "A TypeScript event bus library with serial, parallel, and broadcast implementations",
5
5
  "keywords": [
6
6
  "eventbus",