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