@ahoo-wang/fetcher-eventbus 3.13.15 → 3.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +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,CAC/C,YAAW,aAAa,CAAC,KAAK,CAAC;IAE/B,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,CACzB,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,EAC5B,KAAK,EAAE,KAAK,GACX,OAAO,CAAC,IAAI,CAAC;IAQhB,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"}
1
+ {"version":3,"file":"abstractTypedEventBus.d.ts","sourceRoot":"","sources":["../src/abstractTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEvD,8BAAsB,qBAAqB,CAAC,KAAK,CAC/C,YAAW,aAAa,CAAC,KAAK,CAAC;IAE/B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as r } from "@ahoo-wang/fetcher";
2
- class y {
3
- /**
4
- * Creates a generic event bus
5
- *
6
- * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types
7
- */
8
- constructor(e) {
9
- this.typeEventBusSupplier = e, this.buses = /* @__PURE__ */ new Map();
10
- }
11
- /**
12
- * Adds an event handler for a specific event type
13
- *
14
- * @template Key - The event type
15
- * @param type - The event type to listen for
16
- * @param handler - The event handler to add
17
- * @returns true if the handler was added, false if a handler with the same name already exists
18
- */
19
- on(e, t) {
20
- let s = this.buses.get(e);
21
- return s || (s = this.typeEventBusSupplier(e), this.buses.set(e, s)), s?.on(t) ?? !1;
22
- }
23
- /**
24
- * Removes an event handler for a specific event type
25
- *
26
- * @template Key - The event type
27
- * @param type - The event type
28
- * @param name - The name of the event handler to remove
29
- * @returns true if a handler was removed, false otherwise
30
- */
31
- off(e, t) {
32
- return this.buses.get(e)?.off(t) ?? !1;
33
- }
34
- /**
35
- * Emits an event for a specific event type
36
- *
37
- * @template Key - The event type
38
- * @param type - The event type to emit
39
- * @param event - The event data
40
- * @returns Promise if the underlying bus is async, void otherwise
41
- */
42
- emit(e, t) {
43
- return this.buses.get(e)?.emit(t);
44
- }
45
- /**
46
- * Cleans up all managed event buses
47
- */
48
- destroy() {
49
- for (const e of this.buses.values())
50
- e.destroy();
51
- this.buses.clear();
52
- }
53
- }
54
- class i {
55
- constructor() {
56
- this.eventHandlers = [];
57
- }
58
- /**
59
- * Gets a copy of all registered event handlers, sorted by order
60
- */
61
- get handlers() {
62
- return [...this.eventHandlers];
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 w 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
- }
84
- /**
85
- * Emits an event to all registered handlers in parallel
86
- *
87
- * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.
88
- * Errors in individual handlers are logged but do not affect other handlers.
89
- *
90
- * @param event - The event to emit
91
- */
92
- async emit(e) {
93
- const t = [], s = this.eventHandlers.map(async (a) => {
94
- await this.handleEvent(a, e), a.once && t.push(a);
95
- });
96
- await Promise.all(s), t.length > 0 && (this.eventHandlers = this.eventHandlers.filter(
97
- (a) => !t.includes(a)
98
- ));
99
- }
100
- /**
101
- * Removes an event handler by name
102
- *
103
- * @param name - The name of the handler to remove
104
- * @returns true if a handler was removed, false otherwise
105
- */
106
- off(e) {
107
- const t = this.eventHandlers;
108
- return t.some((s) => s.name === e) ? (this.eventHandlers = t.filter((s) => s.name !== e), !0) : !1;
109
- }
110
- /**
111
- * Adds an event handler if not already present
112
- *
113
- * Handlers are sorted by their order property after addition.
114
- *
115
- * @param handler - The event handler to add
116
- * @returns true if the handler was added, false if a handler with the same name already exists
117
- */
118
- on(e) {
119
- const t = this.eventHandlers;
120
- return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = [...t, e], !0);
121
- }
122
- }
123
- class E extends i {
124
- /**
125
- * Creates an in-memory typed event bus
126
- *
127
- * @param type - The event type identifier for this bus
128
- */
129
- constructor(e) {
130
- super(), this.type = e;
131
- }
132
- /**
133
- * Emits an event to all registered handlers serially
134
- *
135
- * Handlers are executed in order of their priority. Once-only handlers are removed after execution.
136
- * Errors in individual handlers are logged but do not stop other handlers.
137
- *
138
- * @param event - The event to emit
139
- */
140
- async emit(e) {
141
- const t = [];
142
- for (const s of this.eventHandlers)
143
- await this.handleEvent(s, e), s.once && t.push(s);
144
- t.length > 0 && (this.eventHandlers = r(
145
- this.eventHandlers.filter((s) => !t.includes(s))
146
- ));
147
- }
148
- /**
149
- * Removes an event handler by name
150
- *
151
- * @param name - The name of the handler to remove
152
- * @returns true if a handler was removed, false otherwise
153
- */
154
- off(e) {
155
- const t = this.eventHandlers;
156
- return t.some((s) => s.name === e) ? (this.eventHandlers = r(t, (s) => s.name !== e), !0) : !1;
157
- }
158
- /**
159
- * Adds an event handler if not already present
160
- *
161
- * Handlers are sorted by their order property after addition.
162
- *
163
- * @param handler - The event handler to add
164
- * @returns true if the handler was added, false if a handler with the same name already exists
165
- */
166
- on(e) {
167
- const t = this.eventHandlers;
168
- return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = r([...t, e]), !0);
169
- }
170
- }
171
- class h {
172
- constructor(e) {
173
- this.broadcastChannel = new BroadcastChannel(e);
174
- }
175
- postMessage(e) {
176
- this.broadcastChannel.postMessage(e);
177
- }
178
- /**
179
- * Set the message handler for incoming messages
180
- *
181
- * @param handler - Function to handle incoming messages, or undefined to remove handler
182
- */
183
- set onmessage(e) {
184
- this.broadcastChannel.onmessage = (t) => {
185
- e(t.data);
186
- };
187
- }
188
- /**
189
- * Close the messenger and clean up resources
190
- *
191
- * After calling close(), the messenger cannot be used again.
192
- */
193
- close() {
194
- this.broadcastChannel.close();
195
- }
196
- }
197
- const c = 1e3, u = 6e4;
198
- class d {
199
- constructor(e) {
200
- this.storageEventHandler = (t) => {
201
- if (!(t.storageArea !== this.storage || !t.key?.startsWith(this.messageKeyPrefix) || !t.newValue))
202
- try {
203
- const s = JSON.parse(t.newValue);
204
- this.messageHandler?.(s.data);
205
- } catch (s) {
206
- console.warn("Failed to parse storage message:", s);
207
- }
208
- }, this.channelName = e.channelName, this.storage = e.storage ?? localStorage, this.messageKeyPrefix = `_storage_msg_${this.channelName}`, this.ttl = e.ttl ?? c, this.cleanupInterval = e.cleanupInterval ?? u, this.cleanupTimer = window.setInterval(
209
- () => this.cleanup(),
210
- this.cleanupInterval
211
- ), window.addEventListener("storage", this.storageEventHandler);
212
- }
213
- generateMessageKey() {
214
- return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
215
- }
216
- /**
217
- * Send a message to other tabs/windows via localStorage
218
- */
219
- postMessage(e) {
220
- const t = this.generateMessageKey(), s = {
221
- data: e,
222
- timestamp: Date.now()
223
- };
224
- this.storage.setItem(t, JSON.stringify(s)), setTimeout(() => this.storage.removeItem(t), this.ttl);
225
- }
226
- /**
227
- * Set the message handler for incoming messages
228
- */
229
- set onmessage(e) {
230
- this.messageHandler = e;
231
- }
232
- /**
233
- * Clean up expired messages from storage
234
- */
235
- cleanup() {
236
- const e = Date.now(), t = [];
237
- for (let s = 0; s < this.storage.length; s++) {
238
- const a = this.storage.key(s);
239
- if (a?.startsWith(this.messageKeyPrefix))
240
- try {
241
- const o = this.storage.getItem(a);
242
- if (o) {
243
- const l = JSON.parse(o);
244
- e > l.timestamp + this.ttl && t.push(a);
245
- }
246
- } catch {
247
- t.push(a);
248
- }
249
- }
250
- t.forEach((s) => this.storage.removeItem(s));
251
- }
252
- /**
253
- * Close the messenger and clean up resources
254
- */
255
- close() {
256
- this.cleanupTimer && clearInterval(this.cleanupTimer), window.removeEventListener("storage", this.storageEventHandler);
257
- }
258
- }
259
- function g() {
260
- return typeof BroadcastChannel < "u" && typeof BroadcastChannel.prototype?.postMessage == "function";
261
- }
262
- function f() {
263
- return typeof StorageEvent < "u" && typeof window < "u" && typeof window.addEventListener == "function" && (typeof localStorage < "u" || typeof sessionStorage < "u");
264
- }
265
- function m(n) {
266
- if (g())
267
- return new h(n);
268
- if (f())
269
- return new d({ channelName: n });
1
+ import { toSorted as e } from "@ahoo-wang/fetcher";
2
+ //#region src/eventBus.ts
3
+ var t = class {
4
+ constructor(e) {
5
+ this.typeEventBusSupplier = e, this.buses = /* @__PURE__ */ new Map();
6
+ }
7
+ on(e, t) {
8
+ let n = this.buses.get(e);
9
+ return n || (n = this.typeEventBusSupplier(e), this.buses.set(e, n)), n?.on(t) ?? !1;
10
+ }
11
+ off(e, t) {
12
+ return this.buses.get(e)?.off(t) ?? !1;
13
+ }
14
+ emit(e, t) {
15
+ return this.buses.get(e)?.emit(t);
16
+ }
17
+ destroy() {
18
+ for (let e of this.buses.values()) e.destroy();
19
+ this.buses.clear();
20
+ }
21
+ }, n = class {
22
+ constructor() {
23
+ this.eventHandlers = [];
24
+ }
25
+ get handlers() {
26
+ return [...this.eventHandlers];
27
+ }
28
+ destroy() {
29
+ this.eventHandlers = [];
30
+ }
31
+ async handleEvent(e, t) {
32
+ try {
33
+ e.handle(t);
34
+ } catch (t) {
35
+ console.warn(`Event handler error for ${e.name}:`, t);
36
+ }
37
+ }
38
+ }, r = class extends n {
39
+ constructor(e) {
40
+ super(), this.type = e;
41
+ }
42
+ async emit(e) {
43
+ let t = [], n = this.eventHandlers.map(async (n) => {
44
+ await this.handleEvent(n, e), n.once && t.push(n);
45
+ });
46
+ await Promise.all(n), t.length > 0 && (this.eventHandlers = this.eventHandlers.filter((e) => !t.includes(e)));
47
+ }
48
+ off(e) {
49
+ let t = this.eventHandlers;
50
+ return t.some((t) => t.name === e) ? (this.eventHandlers = t.filter((t) => t.name !== e), !0) : !1;
51
+ }
52
+ on(e) {
53
+ let t = this.eventHandlers;
54
+ return t.some((t) => t.name === e.name) ? !1 : (this.eventHandlers = [...t, e], !0);
55
+ }
56
+ }, i = class extends n {
57
+ constructor(e) {
58
+ super(), this.type = e;
59
+ }
60
+ async emit(t) {
61
+ let n = [];
62
+ for (let e of this.eventHandlers) await this.handleEvent(e, t), e.once && n.push(e);
63
+ n.length > 0 && (this.eventHandlers = e(this.eventHandlers.filter((e) => !n.includes(e))));
64
+ }
65
+ off(t) {
66
+ let n = this.eventHandlers;
67
+ return n.some((e) => e.name === t) ? (this.eventHandlers = e(n, (e) => e.name !== t), !0) : !1;
68
+ }
69
+ on(t) {
70
+ let n = this.eventHandlers;
71
+ return n.some((e) => e.name === t.name) ? !1 : (this.eventHandlers = e([...n, t]), !0);
72
+ }
73
+ }, a = class {
74
+ constructor(e) {
75
+ this.broadcastChannel = new BroadcastChannel(e);
76
+ }
77
+ postMessage(e) {
78
+ this.broadcastChannel.postMessage(e);
79
+ }
80
+ set onmessage(e) {
81
+ this.broadcastChannel.onmessage = (t) => {
82
+ e(t.data);
83
+ };
84
+ }
85
+ close() {
86
+ this.broadcastChannel.close();
87
+ }
88
+ }, o = 1e3, s = 6e4, c = class {
89
+ constructor(e) {
90
+ this.storageEventHandler = (e) => {
91
+ if (!(e.storageArea !== this.storage || !e.key?.startsWith(this.messageKeyPrefix) || !e.newValue)) try {
92
+ let t = JSON.parse(e.newValue);
93
+ this.messageHandler?.(t.data);
94
+ } catch (e) {
95
+ console.warn("Failed to parse storage message:", e);
96
+ }
97
+ }, this.channelName = e.channelName, this.storage = e.storage ?? localStorage, this.messageKeyPrefix = `_storage_msg_${this.channelName}`, this.ttl = e.ttl ?? o, this.cleanupInterval = e.cleanupInterval ?? s, this.cleanupTimer = window.setInterval(() => this.cleanup(), this.cleanupInterval), window.addEventListener("storage", this.storageEventHandler);
98
+ }
99
+ generateMessageKey() {
100
+ return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
101
+ }
102
+ postMessage(e) {
103
+ let t = this.generateMessageKey(), n = {
104
+ data: e,
105
+ timestamp: Date.now()
106
+ };
107
+ this.storage.setItem(t, JSON.stringify(n)), setTimeout(() => this.storage.removeItem(t), this.ttl);
108
+ }
109
+ set onmessage(e) {
110
+ this.messageHandler = e;
111
+ }
112
+ cleanup() {
113
+ let e = Date.now(), t = [];
114
+ for (let n = 0; n < this.storage.length; n++) {
115
+ let r = this.storage.key(n);
116
+ if (r?.startsWith(this.messageKeyPrefix)) try {
117
+ let n = this.storage.getItem(r);
118
+ n && e > JSON.parse(n).timestamp + this.ttl && t.push(r);
119
+ } catch {
120
+ t.push(r);
121
+ }
122
+ }
123
+ t.forEach((e) => this.storage.removeItem(e));
124
+ }
125
+ close() {
126
+ this.cleanupTimer && clearInterval(this.cleanupTimer), window.removeEventListener("storage", this.storageEventHandler);
127
+ }
128
+ };
129
+ //#endregion
130
+ //#region src/messengers/crossTabMessenger.ts
131
+ function l() {
132
+ return typeof BroadcastChannel < "u" && typeof BroadcastChannel.prototype?.postMessage == "function";
270
133
  }
271
- class H {
272
- /**
273
- * Creates a new broadcast event bus with cross-context communication
274
- *
275
- * @param options - Configuration object containing delegate bus and optional messenger
276
- * @throws {Error} If messenger creation fails when no messenger is provided
277
- */
278
- constructor(e) {
279
- this.delegate = e.delegate, this.type = this.delegate.type;
280
- const t = e.messenger ?? m(`_broadcast_:${this.type}`);
281
- if (!t)
282
- throw new Error("Messenger setup failed");
283
- this.messenger = t, this.messenger.onmessage = async (s) => {
284
- await this.delegate.emit(s);
285
- };
286
- }
287
- /**
288
- * Returns a copy of all currently registered event handlers
289
- *
290
- * This getter delegates to the underlying event bus and returns the current
291
- * list of handlers that will process incoming events.
292
- *
293
- * @returns Array of event handlers registered with this bus
294
- */
295
- get handlers() {
296
- return this.delegate.handlers;
297
- }
298
- /**
299
- * Emits an event locally and broadcasts it to other browser contexts
300
- *
301
- * This method first processes the event through the local delegate bus,
302
- * allowing all registered local handlers to process it. Then, if successful,
303
- * the event is broadcasted to other tabs/windows through the messenger.
304
- *
305
- * Note: If broadcasting fails (e.g., due to messenger errors), the local
306
- * emission is still completed and a warning is logged to console.
307
- *
308
- * @param event - The event data to emit and broadcast
309
- * @returns Promise that resolves when local processing is complete
310
- * @throws Propagates any errors from local event processing
311
- */
312
- async emit(e) {
313
- await this.delegate.emit(e), this.messenger.postMessage(e);
314
- }
315
- /**
316
- * Removes an event handler by its registered name
317
- *
318
- * This method delegates to the underlying event bus to remove the specified
319
- * handler. The handler will no longer receive events emitted to this bus.
320
- *
321
- * @param name - The unique name of the handler to remove
322
- * @returns true if a handler with the given name was found and removed, false otherwise
323
- */
324
- off(e) {
325
- return this.delegate.off(e);
326
- }
327
- /**
328
- * Registers a new event handler with this bus
329
- *
330
- * The handler will receive all events emitted to this bus, both locally
331
- * generated and received from other browser contexts via broadcasting.
332
- *
333
- * @param handler - The event handler configuration to register
334
- * @returns true if the handler was successfully added, false if a handler with the same name already exists
335
- */
336
- on(e) {
337
- return this.delegate.on(e);
338
- }
339
- /**
340
- * Cleans up resources and stops cross-context communication
341
- *
342
- * This method closes the messenger connection, preventing further
343
- * cross-tab communication. Local event handling continues to work
344
- * through the delegate bus. After calling destroy(), the bus should
345
- * not be used for broadcasting operations.
346
- *
347
- * Note: This does not remove event handlers or affect local event processing.
348
- */
349
- destroy() {
350
- this.messenger.close();
351
- }
134
+ function u() {
135
+ return typeof StorageEvent < "u" && typeof window < "u" && typeof window.addEventListener == "function" && (typeof localStorage < "u" || typeof sessionStorage < "u");
352
136
  }
353
- class p {
354
- constructor() {
355
- this.namingCounter = 0;
356
- }
357
- /**
358
- * Generates a unique name by appending an incrementing counter to the prefix
359
- * @param prefix - The prefix for the generated name
360
- * @returns The generated unique name
361
- */
362
- generate(e) {
363
- return this.namingCounter++, `${e}_${this.namingCounter}`;
364
- }
137
+ function d(e) {
138
+ if (l()) return new a(e);
139
+ if (u()) return new c({ channelName: e });
365
140
  }
366
- const b = new p();
367
- export {
368
- i as AbstractTypedEventBus,
369
- h as BroadcastChannelMessenger,
370
- H as BroadcastTypedEventBus,
371
- p as DefaultNameGenerator,
372
- y as EventBus,
373
- w as ParallelTypedEventBus,
374
- E as SerialTypedEventBus,
375
- d as StorageMessenger,
376
- m as createCrossTabMessenger,
377
- g as isBroadcastChannelSupported,
378
- f as isStorageEventSupported,
379
- b as nameGenerator
380
- };
381
- //# sourceMappingURL=index.es.js.map
141
+ //#endregion
142
+ //#region src/broadcastTypedEventBus.ts
143
+ var f = class {
144
+ constructor(e) {
145
+ this.delegate = e.delegate, this.type = this.delegate.type;
146
+ let t = e.messenger ?? d(`_broadcast_:${this.type}`);
147
+ if (!t) throw Error("Messenger setup failed");
148
+ this.messenger = t, this.messenger.onmessage = async (e) => {
149
+ await this.delegate.emit(e);
150
+ };
151
+ }
152
+ get handlers() {
153
+ return this.delegate.handlers;
154
+ }
155
+ async emit(e) {
156
+ await this.delegate.emit(e), this.messenger.postMessage(e);
157
+ }
158
+ off(e) {
159
+ return this.delegate.off(e);
160
+ }
161
+ on(e) {
162
+ return this.delegate.on(e);
163
+ }
164
+ destroy() {
165
+ this.messenger.close();
166
+ }
167
+ }, p = class {
168
+ constructor() {
169
+ this.namingCounter = 0;
170
+ }
171
+ generate(e) {
172
+ return this.namingCounter++, `${e}_${this.namingCounter}`;
173
+ }
174
+ }, m = new p();
175
+ //#endregion
176
+ export { n as AbstractTypedEventBus, a as BroadcastChannelMessenger, f as BroadcastTypedEventBus, p as DefaultNameGenerator, t as EventBus, r as ParallelTypedEventBus, i as SerialTypedEventBus, c as StorageMessenger, d as createCrossTabMessenger, l as isBroadcastChannelSupported, u as isStorageEventSupported, m as nameGenerator };
177
+
178
+ //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.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 * 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>(type: Key, name: string): 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>\n implements TypedEventBus<EVENT>\n{\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(\n handler: EventHandler<EVENT>,\n event: EVENT,\n ): 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","/*\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 * 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 * 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 { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\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\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\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 { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\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 { createCrossTabMessenger, CrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully 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 and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.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","BroadcastChannelMessenger","channelName","message","DEFAULT_TTL","DEFAULT_CLEANUP_INTERVAL","StorageMessenger","options","storageMessage","error","key","now","keysToRemove","i","value","isBroadcastChannelSupported","isStorageEventSupported","createCrossTabMessenger","BroadcastTypedEventBus","messenger","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,EAOK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAU1E,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,GAA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AAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBA,MAAM,KAAKA,GAA6B;AACtC,UAAM,KAAK,SAAS,KAAKA,CAAK,GAC9B,KAAK,UAAU,YAAYA,CAAK;AAAA,EAClC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,IAAID,GAAuB;AACzB,WAAO,KAAK,SAAS,IAAIA,CAAI;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,GAAGF,GAAuC;AACxC,WAAO,KAAK,SAAS,GAAGA,CAAO;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,UAAgB;AACd,SAAK,UAAU,MAAA;AAAA,EACjB;AACF;ACrLO,MAAMgC,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;"}
1
+ {"version":3,"file":"index.es.js","names":[],"sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.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 type { EventHandler, EventType } from './types';\nimport type { 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 * 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>(type: Key, name: string): 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 type { TypedEventBus } from './typedEventBus';\nimport type { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT>\n implements TypedEventBus<EVENT>\n{\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(\n handler: EventHandler<EVENT>,\n event: EVENT,\n ): 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","/*\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 type { 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 * 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 type { 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 * 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 type { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\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\nimport type { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\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 { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\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 type { TypedEventBus } from './typedEventBus';\nimport type { EventHandler, EventType } from './types';\nimport type { CrossTabMessenger } from './messengers';\nimport { createCrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully 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 and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.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"],"mappings":";;AAkCA,IAAa,IAAb,MAAiE;CAQ/D,YAAY,GAA6D;EAA5C,KAAA,uBAAA,gCAPoC,IAAI,KAAK;;CAiB1E,GACE,GACA,GACS;EACT,IAAI,IAAM,KAAK,MAAM,IAAI,EAAK;AAK9B,SAJK,MACH,IAAM,KAAK,qBAAqB,EAAK,EACrC,KAAK,MAAM,IAAI,GAAM,EAAI,GAEpB,GAAK,GAAG,EAAQ,IA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1
- (function(n,o){typeof exports=="object"&&typeof module<"u"?o(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],o):(n=typeof globalThis<"u"?globalThis:n||self,o(n.FetcherEventBus={},n.Fetcher))})(this,(function(n,o){"use strict";class m{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 i{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 p extends i{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 v extends i{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=o.toSorted(this.eventHandlers.filter(s=>!t.includes(s))))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=o.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=o.toSorted([...t,e]),!0)}}class l{constructor(e){this.broadcastChannel=new BroadcastChannel(e)}postMessage(e){this.broadcastChannel.postMessage(e)}set onmessage(e){this.broadcastChannel.onmessage=t=>{e(t.data)}}close(){this.broadcastChannel.close()}}const y=1e3,w=6e4;class h{constructor(e){this.storageEventHandler=t=>{if(!(t.storageArea!==this.storage||!t.key?.startsWith(this.messageKeyPrefix)||!t.newValue))try{const s=JSON.parse(t.newValue);this.messageHandler?.(s.data)}catch(s){console.warn("Failed to parse storage message:",s)}},this.channelName=e.channelName,this.storage=e.storage??localStorage,this.messageKeyPrefix=`_storage_msg_${this.channelName}`,this.ttl=e.ttl??y,this.cleanupInterval=e.cleanupInterval??w,this.cleanupTimer=window.setInterval(()=>this.cleanup(),this.cleanupInterval),window.addEventListener("storage",this.storageEventHandler)}generateMessageKey(){return`${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}postMessage(e){const t=this.generateMessageKey(),s={data:e,timestamp:Date.now()};this.storage.setItem(t,JSON.stringify(s)),setTimeout(()=>this.storage.removeItem(t),this.ttl)}set onmessage(e){this.messageHandler=e}cleanup(){const e=Date.now(),t=[];for(let s=0;s<this.storage.length;s++){const r=this.storage.key(s);if(r?.startsWith(this.messageKeyPrefix))try{const f=this.storage.getItem(r);if(f){const H=JSON.parse(f);e>H.timestamp+this.ttl&&t.push(r)}}catch{t.push(r)}}t.forEach(s=>this.storage.removeItem(s))}close(){this.cleanupTimer&&clearInterval(this.cleanupTimer),window.removeEventListener("storage",this.storageEventHandler)}}function c(){return typeof BroadcastChannel<"u"&&typeof BroadcastChannel.prototype?.postMessage=="function"}function d(){return typeof StorageEvent<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(typeof localStorage<"u"||typeof sessionStorage<"u")}function u(a){if(c())return new l(a);if(d())return new h({channelName:a})}class E{constructor(e){this.delegate=e.delegate,this.type=this.delegate.type;const t=e.messenger??u(`_broadcast_:${this.type}`);if(!t)throw new Error("Messenger setup failed");this.messenger=t,this.messenger.onmessage=async s=>{await this.delegate.emit(s)}}get handlers(){return this.delegate.handlers}async emit(e){await this.delegate.emit(e),this.messenger.postMessage(e)}off(e){return this.delegate.off(e)}on(e){return this.delegate.on(e)}destroy(){this.messenger.close()}}class g{constructor(){this.namingCounter=0}generate(e){return this.namingCounter++,`${e}_${this.namingCounter}`}}const S=new g;n.AbstractTypedEventBus=i,n.BroadcastChannelMessenger=l,n.BroadcastTypedEventBus=E,n.DefaultNameGenerator=g,n.EventBus=m,n.ParallelTypedEventBus=p,n.SerialTypedEventBus=v,n.StorageMessenger=h,n.createCrossTabMessenger=u,n.isBroadcastChannelSupported=c,n.isStorageEventSupported=d,n.nameGenerator=S,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
2
- //# sourceMappingURL=index.umd.js.map
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`@ahoo-wang/fetcher`)):typeof define==`function`&&define.amd?define([`exports`,`@ahoo-wang/fetcher`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.FetcherEventBus={},e.Fetcher))})(this,function(e,t){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var n=class{constructor(e){this.typeEventBusSupplier=e,this.buses=new Map}on(e,t){let n=this.buses.get(e);return n||(n=this.typeEventBusSupplier(e),this.buses.set(e,n)),n?.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(let e of this.buses.values())e.destroy();this.buses.clear()}},r=class{constructor(){this.eventHandlers=[]}get handlers(){return[...this.eventHandlers]}destroy(){this.eventHandlers=[]}async handleEvent(e,t){try{e.handle(t)}catch(t){console.warn(`Event handler error for ${e.name}:`,t)}}},i=class extends r{constructor(e){super(),this.type=e}async emit(e){let t=[],n=this.eventHandlers.map(async n=>{await this.handleEvent(n,e),n.once&&t.push(n)});await Promise.all(n),t.length>0&&(this.eventHandlers=this.eventHandlers.filter(e=>!t.includes(e)))}off(e){let t=this.eventHandlers;return t.some(t=>t.name===e)?(this.eventHandlers=t.filter(t=>t.name!==e),!0):!1}on(e){let t=this.eventHandlers;return t.some(t=>t.name===e.name)?!1:(this.eventHandlers=[...t,e],!0)}},a=class extends r{constructor(e){super(),this.type=e}async emit(e){let n=[];for(let t of this.eventHandlers)await this.handleEvent(t,e),t.once&&n.push(t);n.length>0&&(this.eventHandlers=(0,t.toSorted)(this.eventHandlers.filter(e=>!n.includes(e))))}off(e){let n=this.eventHandlers;return n.some(t=>t.name===e)?(this.eventHandlers=(0,t.toSorted)(n,t=>t.name!==e),!0):!1}on(e){let n=this.eventHandlers;return n.some(t=>t.name===e.name)?!1:(this.eventHandlers=(0,t.toSorted)([...n,e]),!0)}},o=class{constructor(e){this.broadcastChannel=new BroadcastChannel(e)}postMessage(e){this.broadcastChannel.postMessage(e)}set onmessage(e){this.broadcastChannel.onmessage=t=>{e(t.data)}}close(){this.broadcastChannel.close()}},s=1e3,c=6e4,l=class{constructor(e){this.storageEventHandler=e=>{if(!(e.storageArea!==this.storage||!e.key?.startsWith(this.messageKeyPrefix)||!e.newValue))try{let t=JSON.parse(e.newValue);this.messageHandler?.(t.data)}catch(e){console.warn(`Failed to parse storage message:`,e)}},this.channelName=e.channelName,this.storage=e.storage??localStorage,this.messageKeyPrefix=`_storage_msg_${this.channelName}`,this.ttl=e.ttl??s,this.cleanupInterval=e.cleanupInterval??c,this.cleanupTimer=window.setInterval(()=>this.cleanup(),this.cleanupInterval),window.addEventListener(`storage`,this.storageEventHandler)}generateMessageKey(){return`${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}postMessage(e){let t=this.generateMessageKey(),n={data:e,timestamp:Date.now()};this.storage.setItem(t,JSON.stringify(n)),setTimeout(()=>this.storage.removeItem(t),this.ttl)}set onmessage(e){this.messageHandler=e}cleanup(){let e=Date.now(),t=[];for(let n=0;n<this.storage.length;n++){let r=this.storage.key(n);if(r?.startsWith(this.messageKeyPrefix))try{let n=this.storage.getItem(r);n&&e>JSON.parse(n).timestamp+this.ttl&&t.push(r)}catch{t.push(r)}}t.forEach(e=>this.storage.removeItem(e))}close(){this.cleanupTimer&&clearInterval(this.cleanupTimer),window.removeEventListener(`storage`,this.storageEventHandler)}};function u(){return typeof BroadcastChannel<`u`&&typeof BroadcastChannel.prototype?.postMessage==`function`}function d(){return typeof StorageEvent<`u`&&typeof window<`u`&&typeof window.addEventListener==`function`&&(typeof localStorage<`u`||typeof sessionStorage<`u`)}function f(e){if(u())return new o(e);if(d())return new l({channelName:e})}var p=class{constructor(e){this.delegate=e.delegate,this.type=this.delegate.type;let t=e.messenger??f(`_broadcast_:${this.type}`);if(!t)throw Error(`Messenger setup failed`);this.messenger=t,this.messenger.onmessage=async e=>{await this.delegate.emit(e)}}get handlers(){return this.delegate.handlers}async emit(e){await this.delegate.emit(e),this.messenger.postMessage(e)}off(e){return this.delegate.off(e)}on(e){return this.delegate.on(e)}destroy(){this.messenger.close()}},m=class{constructor(){this.namingCounter=0}generate(e){return this.namingCounter++,`${e}_${this.namingCounter}`}},h=new m;e.AbstractTypedEventBus=r,e.BroadcastChannelMessenger=o,e.BroadcastTypedEventBus=p,e.DefaultNameGenerator=m,e.EventBus=n,e.ParallelTypedEventBus=i,e.SerialTypedEventBus=a,e.StorageMessenger=l,e.createCrossTabMessenger=f,e.isBroadcastChannelSupported=u,e.isStorageEventSupported=d,e.nameGenerator=h});
2
+ //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.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 * 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>(type: Key, name: string): 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>\n implements TypedEventBus<EVENT>\n{\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(\n handler: EventHandler<EVENT>,\n event: EVENT,\n ): 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","/*\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 * 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 * 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 { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\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\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\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 { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\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 { createCrossTabMessenger, CrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully 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 and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.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","BroadcastChannelMessenger","channelName","message","DEFAULT_TTL","DEFAULT_CLEANUP_INTERVAL","StorageMessenger","options","storageMessage","error","key","now","keysToRemove","i","value","isBroadcastChannelSupported","isStorageEventSupported","createCrossTabMessenger","BroadcastTypedEventBus","messenger","DefaultNameGenerator","prefix","nameGenerator"],"mappings":"uSAkC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KAAK,IAAI,EAAE,EACzE,GAAI,CAACE,EACH,MAAM,IAAI,MAAM,wBAAwB,EAE1C,KAAK,UAAYA,EACjB,KAAK,UAAU,UAAY,MAAO5B,GAAiB,CACjD,MAAM,KAAK,SAAS,KAAKA,CAAK,CAChC,CACF,CAUA,IAAI,UAAkC,CACpC,OAAO,KAAK,SAAS,QACvB,CAgBA,MAAM,KAAKA,EAA6B,CACtC,MAAM,KAAK,SAAS,KAAKA,CAAK,EAC9B,KAAK,UAAU,YAAYA,CAAK,CAClC,CAWA,IAAID,EAAuB,CACzB,OAAO,KAAK,SAAS,IAAIA,CAAI,CAC/B,CAWA,GAAGF,EAAuC,CACxC,OAAO,KAAK,SAAS,GAAGA,CAAO,CACjC,CAYA,SAAgB,CACd,KAAK,UAAU,MAAA,CACjB,CACF,CCrLO,MAAMgC,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"}
1
+ {"version":3,"file":"index.umd.js","names":[],"sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.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 type { EventHandler, EventType } from './types';\nimport type { 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 * 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>(type: Key, name: string): 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 type { TypedEventBus } from './typedEventBus';\nimport type { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT>\n implements TypedEventBus<EVENT>\n{\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(\n handler: EventHandler<EVENT>,\n event: EVENT,\n ): 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","/*\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 type { 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 * 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 type { 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 * 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 type { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\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\nimport type { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\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 { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\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 type { TypedEventBus } from './typedEventBus';\nimport type { EventHandler, EventType } from './types';\nimport type { CrossTabMessenger } from './messengers';\nimport { createCrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully 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 and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.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"],"mappings":"sVAkCA,IAAa,EAAb,KAAiE,CAQ/D,YAAY,EAA6D,CAA5C,KAAA,qBAAA,aAPoC,IAAI,IAiBrE,GACE,EACA,EACS,CACT,IAAI,EAAM,KAAK,MAAM,IAAI,EAAK,CAK9B,OAJK,IACH,EAAM,KAAK,qBAAqB,EAAK,CACrC,KAAK,MAAM,IAAI,EAAM,EAAI,EAEpB,GAAK,GAAG,EAAQ,EAAI,GAW7B,IAA2B,EAAW,EAAuB,CAC3D,OAAO,KAAK,MAAM,IAAI,EAAK,EAAE,IAAI,EAAK,EAAI,GAW5C,KACE,EACA,EACsB,CACtB,OAAO,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AC,OAAO,EAAE,GAAG,GAAG,IAAI;IAI/B;;;;OAIG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAI5C;IAED;;;;OAIG;IACH,KAAK,IAAI,IAAI;CAGd"}
1
+ {"version":3,"file":"broadcastChannelMessenger.d.ts","sourceRoot":"","sources":["../../src/messengers/broadcastChannelMessenger.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAErF,qBAAa,yBAA0B,YAAW,iBAAiB;IACjE,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAmB;gBAExC,WAAW,EAAE,MAAM;IAI/B,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAI/B;;;;OAIG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAI5C;IAED;;;;OAIG;IACH,KAAK,IAAI,IAAI;CAGd"}
@@ -1 +1 @@
1
- {"version":3,"file":"storageMessenger.d.ts","sourceRoot":"","sources":["../../src/messengers/storageMessenger.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,MAAM,WAAW,uBAAuB;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,wDAAwD;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,GAAG,CAAC;IACV,SAAS,EAAE,MAAM,CAAC;CACnB;AAKD,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAU;IAClC,OAAO,CAAC,cAAc,CAAC,CAAyB;IAChD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;I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mB,CAclC;gBAEU,OAAO,EAAE,uBAAuB;IAa5C,OAAO,CAAC,kBAAkB;IAI1B;;OAEG;IACH,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAW/B;;OAEG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAE5C;IAED;;OAEG;IACH,OAAO,CAAC,OAAO;IAuBf;;OAEG;IACH,KAAK,IAAI,IAAI;CAMd"}
@@ -1 +1 @@
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;aAMhD,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
+ {"version":3,"file":"parallelTypedEventBus.d.ts","sourceRoot":"","sources":["../src/parallelTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,qBAAqB,CAAC,KAAK,CAAE,SAAQ,qBAAqB,CAAC,KAAK,CAAC;aAMhD,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 +1 @@
1
- {"version":3,"file":"serialTypedEventBus.d.ts","sourceRoot":"","sources":["../src/serialTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAElD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,mBAAmB,CAAC,KAAK,CAAE,SAAQ,qBAAqB,CAAC,KAAK,CAAC;aAM9C,IAAI,EAAE,SAAS;IAL3C;;;;OAIG;gBACyB,IAAI,EAAE,SAAS;IAI3C;;;;;;;OAOG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAevC;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAS1B;;;;;;;OAOG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CAQ1C"}
1
+ {"version":3,"file":"serialTypedEventBus.d.ts","sourceRoot":"","sources":["../src/serialTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,mBAAmB,CAAC,KAAK,CAAE,SAAQ,qBAAqB,CAAC,KAAK,CAAC;aAM9C,IAAI,EAAE,SAAS;IAL3C;;;;OAIG;gBACyB,IAAI,EAAE,SAAS;IAI3C;;;;;;;OAOG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAevC;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAS1B;;;;;;;OAOG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;CAQ1C"}
@@ -1 +1 @@
1
- {"version":3,"file":"typedEventBus.d.ts","sourceRoot":"","sources":["../src/typedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAElD;;;;GAIG;AACH,MAAM,WAAW,aAAa,CAAC,KAAK;IAClC;;OAEG;IACH,IAAI,EAAE,SAAS,CAAC;IAEhB;;OAEG;IACH,QAAQ,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;IAEhC;;;;;OAKG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC;IAE1C;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAE3B;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAElC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;CACjB"}
1
+ {"version":3,"file":"typedEventBus.d.ts","sourceRoot":"","sources":["../src/typedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAEvD;;;;GAIG;AACH,MAAM,WAAW,aAAa,CAAC,KAAK;IAClC;;OAEG;IACH,IAAI,EAAE,SAAS,CAAC;IAEhB;;OAEG;IACH,QAAQ,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;IAEhC;;;;;OAKG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO,CAAC;IAE1C;;;;;OAKG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAE3B;;;;OAIG;IACH,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAElC;;OAEG;IACH,OAAO,IAAI,IAAI,CAAC;CACjB"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { NamedCapable, OrderedCapable } from '@ahoo-wang/fetcher';
1
+ import { OrderedCapable, NamedCapable } from '@ahoo-wang/fetcher';
2
2
  export type EventType = string;
3
3
  export interface EventHandler<EVENT> extends NamedCapable, OrderedCapable {
4
4
  once?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,KAAK,YAAY,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEvE,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAE/B,MAAM,WAAW,YAAY,CAAC,KAAK,CAAE,SAAQ,YAAY,EAAE,cAAc;IACvE,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC;AAE/B,MAAM,WAAW,YAAY,CAAC,KAAK,CAAE,SAAQ,YAAY,EAAE,cAAc;IACvE,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-eventbus",
3
- "version": "3.13.15",
3
+ "version": "3.15.1",
4
4
  "description": "A TypeScript event bus library with serial, parallel, and broadcast implementations",
5
5
  "keywords": [
6
6
  "eventbus",
@@ -41,17 +41,17 @@
41
41
  },
42
42
  "devDependencies": {
43
43
  "@eslint/js": "^9.39.4",
44
- "@vitest/coverage-v8": "^4.0.0",
45
- "@vitest/ui": "^4.0.0",
44
+ "@vitest/coverage-v8": "^4.1.4",
45
+ "@vitest/ui": "^4.1.4",
46
46
  "eslint": "^9.39.4",
47
47
  "globals": "^17.4.0",
48
48
  "prettier": "^3.8.1",
49
- "typescript": "^5.9.3",
50
- "typescript-eslint": "^8.58.0",
49
+ "typescript": "^6.0.2",
50
+ "typescript-eslint": "^8.58.1",
51
51
  "unplugin-dts": "1.0.0-beta.6",
52
- "vite": "^7.3.1",
53
- "vite-bundle-analyzer": "^1.3.6",
54
- "vitest": "^4.1.2"
52
+ "vite": "^8.0.8",
53
+ "vite-bundle-analyzer": "^1.3.7",
54
+ "vitest": "^4.1.4"
55
55
  },
56
56
  "scripts": {
57
57
  "build": "vite build",