@vnb/mfe-events 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,790 @@
1
+ /**
2
+ * @vnb/mfe-events v1.0.0
3
+ * Micro frontend event plugin for cross-app communication with type safety
4
+ * License: MIT
5
+ */
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
8
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.MfeEvents = {}));
10
+ })(this, (function (exports) { 'use strict';
11
+
12
+ /**
13
+ * @vnb/mfe-events — Transport Layer
14
+ *
15
+ * Provides abstraction for event transmission across different environments:
16
+ * - MemoryTransport: Shell internal (no window)
17
+ * - WindowTransport: MF/NF Remote Apps (CustomEvent)
18
+ * - PostMessageTransport: iframe Remote Apps (postMessage)
19
+ * - IframeProxyTransport: Shell → iframe proxy (postMessage)
20
+ */
21
+ /**
22
+ * MemoryTransport — Shell internal event bus
23
+ * Uses in-memory EventTarget, does not touch window
24
+ */
25
+ class MemoryTransport {
26
+ constructor() {
27
+ this.target = new EventTarget();
28
+ }
29
+ emit(event, data) {
30
+ this.target.dispatchEvent(new CustomEvent(event, { detail: data }));
31
+ }
32
+ on(event, handler) {
33
+ const wrapper = (e) => handler(e.detail);
34
+ this.target.addEventListener(event, wrapper);
35
+ return () => this.target.removeEventListener(event, wrapper);
36
+ }
37
+ }
38
+ /**
39
+ * WindowTransport — MF/NF Remote Apps communication
40
+ * Uses window.CustomEvent for same-tab communication
41
+ */
42
+ class WindowTransport {
43
+ emit(event, data) {
44
+ window.dispatchEvent(new CustomEvent(event, { detail: data }));
45
+ }
46
+ on(event, handler) {
47
+ const wrapper = (e) => handler(e.detail);
48
+ window.addEventListener(event, wrapper);
49
+ return () => window.removeEventListener(event, wrapper);
50
+ }
51
+ }
52
+ /**
53
+ * PostMessageTransport — iframe Remote Apps communication
54
+ * Uses window.postMessage for cross-origin communication
55
+ */
56
+ class PostMessageTransport {
57
+ constructor(options = {}) {
58
+ this.targetWindow = options.targetWindow || window.parent;
59
+ this.targetOrigin = options.targetOrigin || '*';
60
+ }
61
+ emit(event, data) {
62
+ this.targetWindow.postMessage({ scope: 'mfe', event, data, ts: Date.now() }, this.targetOrigin);
63
+ }
64
+ on(event, handler) {
65
+ const wrapper = (e) => {
66
+ if (e.data?.scope === 'mfe' && e.data?.event === event) {
67
+ handler(e.data.data);
68
+ }
69
+ };
70
+ window.addEventListener('message', wrapper);
71
+ return () => window.removeEventListener('message', wrapper);
72
+ }
73
+ }
74
+ /**
75
+ * IframeProxyTransport — Shell side proxy for iframe communication
76
+ * Sends postMessage to specific iframe and receives messages from it
77
+ */
78
+ class IframeProxyTransport {
79
+ constructor(iframe, targetOrigin = '*') {
80
+ this.iframe = iframe;
81
+ this.targetOrigin = targetOrigin;
82
+ }
83
+ emit(event, data) {
84
+ this.iframe.contentWindow?.postMessage({ scope: 'mfe', event, data, ts: Date.now() }, this.targetOrigin);
85
+ }
86
+ on(event, handler) {
87
+ const wrapper = (e) => {
88
+ // Only receive messages from this specific iframe
89
+ if (e.source === this.iframe.contentWindow &&
90
+ e.data?.scope === 'mfe' &&
91
+ e.data?.event === event) {
92
+ handler(e.data.data);
93
+ }
94
+ };
95
+ window.addEventListener('message', wrapper);
96
+ return () => window.removeEventListener('message', wrapper);
97
+ }
98
+ }
99
+
100
+ var transport = /*#__PURE__*/Object.freeze({
101
+ __proto__: null,
102
+ IframeProxyTransport: IframeProxyTransport,
103
+ MemoryTransport: MemoryTransport,
104
+ PostMessageTransport: PostMessageTransport,
105
+ WindowTransport: WindowTransport
106
+ });
107
+
108
+ /**
109
+ * @vnb/mfe-events — Type-safe Event Bus
110
+ *
111
+ * Provides compile-time type checking for event names and payloads.
112
+ * Wraps Transport with generic type constraints.
113
+ */
114
+ class Bus {
115
+ constructor(transport) {
116
+ this.transport = transport;
117
+ }
118
+ /**
119
+ * Emit an event with type-safe payload
120
+ */
121
+ emit(event, data) {
122
+ this.transport.emit(event, data);
123
+ }
124
+ /**
125
+ * Subscribe to an event with type-safe handler
126
+ * Returns unsubscribe function
127
+ */
128
+ on(event, handler, options) {
129
+ if (options?.once) {
130
+ return this.once(event, handler);
131
+ }
132
+ return this.transport.on(event, handler);
133
+ }
134
+ /**
135
+ * Subscribe to an event once
136
+ * Returns unsubscribe function
137
+ */
138
+ once(event, handler) {
139
+ const off = this.on(event, (data) => {
140
+ off();
141
+ handler(data);
142
+ });
143
+ return off;
144
+ }
145
+ }
146
+
147
+ /**
148
+ * @vnb/mfe-events — Event Constants
149
+ *
150
+ * Three scopes:
151
+ * - EvtShl: Shell internal (no window, memory only)
152
+ * - EvtMfe: Cross-app (Shell + Remote Apps)
153
+ * - EvtApp: Remote App internal (framework-specific)
154
+ *
155
+ * Naming convention: {scope}:{domain}-{action}
156
+ * - State/notification events: must have -{action} suffix
157
+ * - Event markers (error, shell-ready, raw): no suffix
158
+ */
159
+ // ─────────────────────────────────────────────
160
+ // Shell Internal — no window, memory only
161
+ // ─────────────────────────────────────────────
162
+ const EvtShl = {
163
+ TabOverflow: 'shl:tab-overflow',
164
+ TabClose: 'shl:tab-close',
165
+ RouteReuse: 'shl:route-reuse',
166
+ AuthSync: 'shl:auth-sync',
167
+ StateSync: 'shl:state-sync',
168
+ AppMounted: 'shl:app-mounted',
169
+ AppUnmounted: 'shl:app-unmounted',
170
+ };
171
+ // ─────────────────────────────────────────────
172
+ // Cross-App — Shell and Remote Apps shared protocol
173
+ // ─────────────────────────────────────────────
174
+ const EvtMfe = {
175
+ // Global state domain
176
+ ThemeUpdate: 'mfe:theme-update',
177
+ LocaleUpdate: 'mfe:locale-update',
178
+ BreakpointUpdate: 'mfe:breakpoint-update',
179
+ StateUpdate: 'mfe:state-update',
180
+ ShellReady: 'mfe:shell-ready',
181
+ Error: 'mfe:error',
182
+ Raw: 'mfe:raw',
183
+ // Auth domain
184
+ AuthLogin: 'mfe:auth-login',
185
+ AuthLogout: 'mfe:auth-logout',
186
+ AuthTokenUpdate: 'mfe:auth-token-update',
187
+ AuthTokenClear: 'mfe:auth-token-clear',
188
+ AuthPermissionUpdate: 'mfe:auth-permission-update',
189
+ AuthExpired: 'mfe:auth-expired',
190
+ // Route domain
191
+ RouteNavigate: 'mfe:route-navigate',
192
+ RouteRefresh: 'mfe:route-refresh',
193
+ RouteChange: 'mfe:route-change',
194
+ // Lifecycle domain
195
+ LifecycleAppClose: 'mfe:lifecycle-app-close',
196
+ LifecycleAppReady: 'mfe:lifecycle-app-ready',
197
+ LifecycleAppUnmount: 'mfe:lifecycle-app-unmount',
198
+ // Notification domain
199
+ NotifyShow: 'mfe:notify-show',
200
+ NotifyClose: 'mfe:notify-close',
201
+ NotifyCloseAll: 'mfe:notify-close-all',
202
+ };
203
+ // ─────────────────────────────────────────────
204
+ // Remote App Internal — defined by each app
205
+ // ─────────────────────────────────────────────
206
+ function EvtApp(appId, name) {
207
+ return `app:${appId}-${name}`;
208
+ }
209
+
210
+ /**
211
+ * @vnb/mfe-events — Plugin Core
212
+ *
213
+ * MfeEventPlugin manages Remote App registration and provides:
214
+ * - register/unregister for Remote Apps
215
+ * - emitTo for targeted communication
216
+ * - emit for broadcast communication
217
+ * - Notification API (success/info/warning/danger)
218
+ * - Automatic iframe message proxying
219
+ */
220
+ class MfeEventPlugin {
221
+ constructor() {
222
+ this.registry = new Map();
223
+ this._notifyId = 0;
224
+ this._shellReady = false;
225
+ this._notifyContainer = null;
226
+ this._notifyItems = new Map();
227
+ this._pendingClosers = new Map();
228
+ this._customRenderer = null;
229
+ this._customCloser = null;
230
+ this._customClear = null;
231
+ if (typeof window === 'undefined')
232
+ return;
233
+ // Shell side: globally listen for iframe messages and forward as CustomEvent
234
+ if (window.self === window.top) {
235
+ window.addEventListener('message', (e) => {
236
+ if (e.data?.scope === 'mfe' && e.data?.event) {
237
+ window.dispatchEvent(new CustomEvent(e.data.event, { detail: e.data.data }));
238
+ }
239
+ });
240
+ }
241
+ // Always init DOM fallback for notifications
242
+ this._initDOMFallback();
243
+ }
244
+ // ─────────────────────────────────────────
245
+ // Custom Renderer (for Shell integration)
246
+ // ─────────────────────────────────────────
247
+ /**
248
+ * Register custom notification renderer (Shell use)
249
+ * When registered, DOM fallback is disabled
250
+ */
251
+ useRenderer(render, close, clear) {
252
+ this._customRenderer = render;
253
+ this._customCloser = close || null;
254
+ this._customClear = clear || null;
255
+ }
256
+ // ─────────────────────────────────────────
257
+ // DOM Fallback Renderer
258
+ // ─────────────────────────────────────────
259
+ _initDOMFallback() {
260
+ // Inject styles
261
+ const styleId = 'mfe-notify-styles';
262
+ if (!document.getElementById(styleId)) {
263
+ const style = document.createElement('style');
264
+ style.id = styleId;
265
+ style.textContent = `
266
+ .mfe-notify-host {
267
+ position: fixed;
268
+ top: 16px;
269
+ left: 50%;
270
+ transform: translateX(-50%);
271
+ z-index: 99999;
272
+ display: flex;
273
+ flex-direction: column;
274
+ gap: 8px;
275
+ max-width: 480px;
276
+ width: calc(100% - 32px);
277
+ pointer-events: none;
278
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
279
+ }
280
+ .mfe-notify-item {
281
+ display: flex;
282
+ align-items: flex-start;
283
+ gap: 10px;
284
+ padding: 12px 14px;
285
+ background: #ffffff;
286
+ border: 1px solid rgba(0, 0, 0, 0.08);
287
+ border-left: 4px solid var(--mfe-notify-color, #6b7280);
288
+ border-radius: 8px;
289
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
290
+ pointer-events: auto;
291
+ animation: mfe-notify-slide-in 180ms ease-out;
292
+ }
293
+ .mfe-notify-item[data-type="success"] { --mfe-notify-color: #16a34a; }
294
+ .mfe-notify-item[data-type="info"] { --mfe-notify-color: #3b82f6; }
295
+ .mfe-notify-item[data-type="warning"] { --mfe-notify-color: #d97706; }
296
+ .mfe-notify-item[data-type="danger"] { --mfe-notify-color: #dc2626; }
297
+ .mfe-notify-icon {
298
+ flex: 0 0 24px;
299
+ width: 24px;
300
+ height: 24px;
301
+ border-radius: 50%;
302
+ display: flex;
303
+ align-items: center;
304
+ justify-content: center;
305
+ font-size: 14px;
306
+ font-weight: 700;
307
+ color: #fff;
308
+ background: var(--mfe-notify-color, #6b7280);
309
+ }
310
+ .mfe-notify-body { flex: 1; min-width: 0; }
311
+ .mfe-notify-title {
312
+ font-size: 13px;
313
+ font-weight: 600;
314
+ color: #1f2937;
315
+ margin-bottom: 2px;
316
+ }
317
+ .mfe-notify-message {
318
+ font-size: 13px;
319
+ line-height: 1.4;
320
+ color: #374151;
321
+ word-break: break-word;
322
+ }
323
+ .mfe-notify-close {
324
+ flex: 0 0 24px;
325
+ width: 24px;
326
+ height: 24px;
327
+ border: none;
328
+ background: none;
329
+ color: #6b7280;
330
+ cursor: pointer;
331
+ font-size: 18px;
332
+ line-height: 1;
333
+ border-radius: 4px;
334
+ }
335
+ .mfe-notify-close:hover { background: rgba(0, 0, 0, 0.06); color: #111827; }
336
+ .mfe-notify-actions {
337
+ display: flex;
338
+ gap: 8px;
339
+ margin-top: 8px;
340
+ }
341
+ .mfe-notify-btn {
342
+ padding: 4px 12px;
343
+ font-size: 12px;
344
+ font-weight: 500;
345
+ border: 1px solid rgba(0, 0, 0, 0.15);
346
+ border-radius: 4px;
347
+ background: #fff;
348
+ color: #374151;
349
+ cursor: pointer;
350
+ transition: background 0.15s, border-color 0.15s;
351
+ }
352
+ .mfe-notify-btn:hover {
353
+ background: #f3f4f6;
354
+ border-color: rgba(0, 0, 0, 0.25);
355
+ }
356
+ .mfe-notify-btn:active {
357
+ background: #e5e7eb;
358
+ }
359
+ @keyframes mfe-notify-slide-in {
360
+ from { transform: translateY(-12px); opacity: 0; }
361
+ to { transform: translateY(0); opacity: 1; }
362
+ }
363
+ `;
364
+ document.head.appendChild(style);
365
+ }
366
+ // Create container
367
+ this._notifyContainer = document.createElement('div');
368
+ this._notifyContainer.className = 'mfe-notify-host';
369
+ this._notifyContainer.setAttribute('aria-live', 'polite');
370
+ document.body.appendChild(this._notifyContainer);
371
+ }
372
+ _renderToast(config) {
373
+ if (!this._notifyContainer)
374
+ return;
375
+ const { id, type = 'info', message = '', title, duration = 3000, buttons = [] } = config;
376
+ const icons = {
377
+ success: '✓',
378
+ info: 'i',
379
+ warning: '!',
380
+ danger: '✕',
381
+ };
382
+ // Escape HTML to prevent XSS
383
+ const escapeHtml = (str) => {
384
+ const div = document.createElement('div');
385
+ div.textContent = str;
386
+ return div.innerHTML;
387
+ };
388
+ const item = document.createElement('div');
389
+ item.className = 'mfe-notify-item';
390
+ item.setAttribute('data-type', type);
391
+ item.setAttribute('data-notify-id', id);
392
+ // Build buttons HTML
393
+ let buttonsHtml = '';
394
+ if (buttons.length > 0) {
395
+ buttonsHtml = `<div class="mfe-notify-actions">${buttons.map((btn, idx) => `<button class="mfe-notify-btn" data-btn-idx="${idx}">${escapeHtml(btn.text)}</button>`).join('')}</div>`;
396
+ }
397
+ item.innerHTML = `
398
+ <div class="mfe-notify-icon">${icons[type] || 'i'}</div>
399
+ <div class="mfe-notify-body">
400
+ ${title ? `<div class="mfe-notify-title">${escapeHtml(title)}</div>` : ''}
401
+ <div class="mfe-notify-message">${escapeHtml(message)}</div>
402
+ ${buttonsHtml}
403
+ </div>
404
+ <button class="mfe-notify-close" type="button" aria-label="Dismiss">×</button>
405
+ `;
406
+ // Bind button handlers
407
+ buttons.forEach((btn, idx) => {
408
+ const btnEl = item.querySelector(`[data-btn-idx="${idx}"]`);
409
+ if (btnEl && btn.handler) {
410
+ btnEl.addEventListener('click', () => {
411
+ btn.handler();
412
+ if (btn.role !== 'sticky') {
413
+ this._removeToast(id);
414
+ }
415
+ });
416
+ }
417
+ });
418
+ const closeBtn = item.querySelector('.mfe-notify-close');
419
+ closeBtn.addEventListener('click', () => this._removeToast(id));
420
+ this._notifyContainer.appendChild(item);
421
+ this._notifyItems.set(id, item);
422
+ if (duration > 0) {
423
+ setTimeout(() => this._removeToast(id), duration);
424
+ }
425
+ }
426
+ _removeToast(id) {
427
+ const item = this._notifyItems.get(id);
428
+ if (item) {
429
+ item.remove();
430
+ this._notifyItems.delete(id);
431
+ }
432
+ this._pendingClosers.delete(id);
433
+ }
434
+ _removeAllToasts() {
435
+ this._notifyItems.forEach((item) => item.remove());
436
+ this._notifyItems.clear();
437
+ this._pendingClosers.clear();
438
+ }
439
+ // ─────────────────────────────────────────
440
+ // Remote App Registration
441
+ // ─────────────────────────────────────────
442
+ /**
443
+ * Register a Remote App with event handlers
444
+ */
445
+ register(options) {
446
+ if (this.registry.has(options.appId)) {
447
+ this.unregister(options.appId);
448
+ }
449
+ const meta = {
450
+ appId: options.appId,
451
+ type: options.type || 'mf',
452
+ };
453
+ const cleanups = [];
454
+ // Auto-subscribe handlers
455
+ Object.entries(options.handlers).forEach(([event, handler]) => {
456
+ if (!handler)
457
+ return;
458
+ if (options.type === 'iframe') {
459
+ // iframe: listen via postMessage
460
+ const wrapper = (e) => {
461
+ if (e.data?.scope === 'mfe' && e.data?.event === event) {
462
+ handler(e.data.data);
463
+ }
464
+ };
465
+ window.addEventListener('message', wrapper);
466
+ cleanups.push(() => window.removeEventListener('message', wrapper));
467
+ }
468
+ else {
469
+ // MF/NF: listen via window.CustomEvent
470
+ const wrapper = (e) => handler(e.detail);
471
+ window.addEventListener(event, wrapper);
472
+ cleanups.push(() => window.removeEventListener(event, wrapper));
473
+ }
474
+ });
475
+ this.registry.set(options.appId, { meta, options, cleanups });
476
+ // fallback 存入 registry,不覆盖全局 _customRenderer
477
+ // 全局渲染器仅由 Shell 的 useRenderer() 设置
478
+ }
479
+ /**
480
+ * Register an iframe Remote App (Shell side)
481
+ */
482
+ registerIframe(appId, iframe, targetOrigin) {
483
+ // Lazy import to avoid bundling issues
484
+ Promise.resolve().then(function () { return transport; }).then(({ IframeProxyTransport }) => {
485
+ const transport = new IframeProxyTransport(iframe, targetOrigin);
486
+ this.registry.set(appId, {
487
+ meta: { appId, type: 'iframe', transport },
488
+ options: { appId, type: 'iframe', handlers: {} },
489
+ cleanups: [],
490
+ });
491
+ });
492
+ }
493
+ /**
494
+ * Unregister a Remote App
495
+ */
496
+ unregister(appId) {
497
+ const entry = this.registry.get(appId);
498
+ if (entry) {
499
+ entry.cleanups.forEach((fn) => fn());
500
+ }
501
+ this.registry.delete(appId);
502
+ }
503
+ // ─────────────────────────────────────────
504
+ // Shell Targeted Communication
505
+ // ─────────────────────────────────────────
506
+ /**
507
+ * Send event to a specific Remote App
508
+ */
509
+ emitTo(appId, event, data) {
510
+ const app = this.registry.get(appId);
511
+ if (!app)
512
+ return;
513
+ if (app.meta.type === 'iframe' && app.meta.transport) {
514
+ // iframe: send via postMessage
515
+ app.meta.transport.emit(event, data);
516
+ }
517
+ else {
518
+ // MF: call handler directly or dispatch CustomEvent
519
+ const handler = app.options.handlers[event];
520
+ if (handler) {
521
+ handler(data);
522
+ }
523
+ }
524
+ }
525
+ // ─────────────────────────────────────────
526
+ // Shell Broadcast Communication
527
+ // ─────────────────────────────────────────
528
+ /**
529
+ * Broadcast event to all Remote Apps (MF + iframe)
530
+ */
531
+ emit(event, data) {
532
+ // Broadcast to all MF Remote Apps
533
+ window.dispatchEvent(new CustomEvent(event, { detail: data }));
534
+ // Broadcast to all iframe Remote Apps
535
+ this.registry.forEach(({ meta }) => {
536
+ if (meta.type === 'iframe' && meta.transport) {
537
+ meta.transport.emit(event, data);
538
+ }
539
+ });
540
+ }
541
+ // ─────────────────────────────────────────
542
+ // Notification API
543
+ // ─────────────────────────────────────────
544
+ /**
545
+ * Build notification config from flexible arguments
546
+ * Supports: success("msg"), success({message:"msg",duration:5000}), success("msg","title",{duration:5000})
547
+ */
548
+ _buildConfig(type, message, args) {
549
+ const config = { type };
550
+ if (typeof message === 'string') {
551
+ config.message = message;
552
+ }
553
+ else if (message && typeof message === 'object') {
554
+ Object.assign(config, message);
555
+ }
556
+ args.forEach((arg) => {
557
+ if (typeof arg === 'string') {
558
+ config.title = arg;
559
+ }
560
+ else if (arg && typeof arg === 'object') {
561
+ Object.assign(config, arg);
562
+ }
563
+ });
564
+ return config;
565
+ }
566
+ /**
567
+ * Show a notification
568
+ */
569
+ notify(config) {
570
+ if (typeof window === 'undefined')
571
+ return { close: () => { } };
572
+ const id = `mfe-${++this._notifyId}`;
573
+ const finalConfig = {
574
+ duration: 3000,
575
+ ...config,
576
+ id,
577
+ };
578
+ // 1. Always dispatch CustomEvent (for Shell listeners)
579
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyShow, {
580
+ detail: finalConfig,
581
+ bubbles: true,
582
+ cancelable: true,
583
+ }));
584
+ // 2. Render DOM fallback (or use custom renderer)
585
+ if (this._customRenderer) {
586
+ this._customRenderer(finalConfig);
587
+ }
588
+ else {
589
+ this._renderToast(finalConfig);
590
+ }
591
+ // 3. Track closer for closeAll()
592
+ const closeFn = () => {
593
+ // Dispatch close event
594
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyClose, {
595
+ detail: { id },
596
+ bubbles: true,
597
+ }));
598
+ // Remove DOM toast
599
+ if (this._customCloser) {
600
+ this._customCloser(id);
601
+ }
602
+ else {
603
+ this._removeToast(id);
604
+ }
605
+ };
606
+ this._pendingClosers.set(id, closeFn);
607
+ return {
608
+ close: () => {
609
+ const closer = this._pendingClosers.get(id);
610
+ if (closer) {
611
+ closer();
612
+ this._pendingClosers.delete(id);
613
+ }
614
+ },
615
+ };
616
+ }
617
+ /**
618
+ * Show success notification
619
+ */
620
+ success(message, ...args) {
621
+ return this.notify(this._buildConfig('success', message, args));
622
+ }
623
+ /**
624
+ * Show info notification
625
+ */
626
+ info(message, ...args) {
627
+ return this.notify(this._buildConfig('info', message, args));
628
+ }
629
+ /**
630
+ * Show warning notification
631
+ */
632
+ warning(message, ...args) {
633
+ return this.notify(this._buildConfig('warning', message, args));
634
+ }
635
+ /**
636
+ * Show danger notification
637
+ */
638
+ danger(message, ...args) {
639
+ return this.notify(this._buildConfig('danger', message, args));
640
+ }
641
+ /**
642
+ * Close all notifications
643
+ */
644
+ closeAll() {
645
+ // Call all pending closers
646
+ this._pendingClosers.forEach((closer) => closer());
647
+ this._pendingClosers.clear();
648
+ // Dispatch close-all event
649
+ window.dispatchEvent(new CustomEvent(EvtMfe.NotifyCloseAll, {
650
+ detail: {},
651
+ bubbles: true,
652
+ }));
653
+ // Clear DOM toasts
654
+ if (this._customClear) {
655
+ this._customClear();
656
+ }
657
+ else {
658
+ this._removeAllToasts();
659
+ }
660
+ }
661
+ // ─────────────────────────────────────────
662
+ // Lifecycle Helpers
663
+ // ─────────────────────────────────────────
664
+ /**
665
+ * Mark Shell as ready
666
+ */
667
+ shellReady() {
668
+ setTimeout(() => {
669
+ window.dispatchEvent(new CustomEvent(EvtMfe.ShellReady, {
670
+ detail: {},
671
+ bubbles: true,
672
+ cancelable: true,
673
+ }));
674
+ this._shellReady = true;
675
+ }, 100);
676
+ }
677
+ /**
678
+ * Check if Shell is ready
679
+ */
680
+ isShellReady() {
681
+ return !!this._shellReady;
682
+ }
683
+ // ─────────────────────────────────────────
684
+ // Auth Helpers (convenience methods)
685
+ // ─────────────────────────────────────────
686
+ /**
687
+ * Broadcast auth login event
688
+ */
689
+ authLogin(user) {
690
+ this.emit(EvtMfe.AuthLogin, { user, token: '' });
691
+ }
692
+ /**
693
+ * Broadcast auth logout event
694
+ */
695
+ authLogout(reason) {
696
+ this.emit(EvtMfe.AuthLogout, { reason: reason || 'user' });
697
+ }
698
+ /**
699
+ * Broadcast token update event
700
+ */
701
+ tokenUpdate(data) {
702
+ this.emit(EvtMfe.AuthTokenUpdate, data);
703
+ }
704
+ /**
705
+ * Broadcast auth expired event
706
+ */
707
+ authExpired() {
708
+ this.emit(EvtMfe.AuthExpired, {});
709
+ }
710
+ /**
711
+ * Broadcast locale update event
712
+ */
713
+ locale(locale) {
714
+ this.emit(EvtMfe.LocaleUpdate, { locale });
715
+ }
716
+ }
717
+ // Singleton export
718
+ const mfeEventPlugin = new MfeEventPlugin();
719
+
720
+ /**
721
+ * @vnb/mfe-events — Micro Frontend Event Plugin
722
+ *
723
+ * Unified event communication for Module Federation / Native Federation / iframe architectures.
724
+ *
725
+ * Features:
726
+ * - Three scopes: EvtShl (Shell internal), EvtMfe (cross-app), EvtApp (Remote App internal)
727
+ * - Type-safe event bus with compile-time checking
728
+ * - Automatic Transport adaptation (CustomEvent for MF, postMessage for iframe)
729
+ * - Plugin API for Remote App registration and communication
730
+ * - Notification API with fallback support
731
+ *
732
+ * Usage:
733
+ * ```typescript
734
+ * import mfeEventPlugin, { mfeBus, shlBus } from '@vnb/mfe-events'
735
+ * import { EvtMfe, EvtShl, EvtApp } from '@vnb/mfe-events'
736
+ * ```
737
+ */
738
+ // Transport layer
739
+ /**
740
+ * Shell internal bus — isolated, does not touch window
741
+ * Use for Shell-internal state synchronization
742
+ */
743
+ const shlBus = new Bus(new MemoryTransport());
744
+ /**
745
+ * Cross-app bus — auto-detects environment and selects Transport
746
+ * - Shell/MF/NF: WindowTransport (CustomEvent)
747
+ * - iframe: PostMessageTransport (postMessage)
748
+ */
749
+ function createMfeBus() {
750
+ if (typeof window === 'undefined') {
751
+ // SSR fallback — use MemoryTransport
752
+ return new Bus(new MemoryTransport());
753
+ }
754
+ if (window.self !== window.top) {
755
+ // iframe environment → send to parent via postMessage
756
+ return new Bus(new PostMessageTransport());
757
+ }
758
+ // Shell/MF/NF environment → use window.CustomEvent
759
+ // Federation modules may not share the same instance,
760
+ // so window is used as the shared channel fallback
761
+ return new Bus(new WindowTransport());
762
+ }
763
+ const mfeBus = createMfeBus();
764
+ // ─────────────────────────────────────────────
765
+ // Global variable for backward compatibility
766
+ // ─────────────────────────────────────────────
767
+ if (typeof window !== 'undefined') {
768
+ const win = window;
769
+ if (!win.__MFE_EVENT_PLUGIN__) {
770
+ win.__MFE_EVENT_PLUGIN__ = mfeEventPlugin;
771
+ }
772
+ }
773
+
774
+ exports.Bus = Bus;
775
+ exports.EvtApp = EvtApp;
776
+ exports.EvtMfe = EvtMfe;
777
+ exports.EvtShl = EvtShl;
778
+ exports.IframeProxyTransport = IframeProxyTransport;
779
+ exports.MemoryTransport = MemoryTransport;
780
+ exports.PostMessageTransport = PostMessageTransport;
781
+ exports.WindowTransport = WindowTransport;
782
+ exports.default = mfeEventPlugin;
783
+ exports.mfeBus = mfeBus;
784
+ exports.mfeEventPlugin = mfeEventPlugin;
785
+ exports.shlBus = shlBus;
786
+
787
+ Object.defineProperty(exports, '__esModule', { value: true });
788
+
789
+ }));
790
+ //# sourceMappingURL=index.umd.js.map