remote-reload-utils 0.0.8 → 0.0.11

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/main.js CHANGED
@@ -1,4 +1,169 @@
1
1
  import { createInstance } from "@module-federation/enhanced/runtime";
2
+ import react, { Suspense, lazy, useCallback, useEffect, useState } from "react";
3
+ async function loadReactVersion(version) {
4
+ const runtime = await createInstance({
5
+ name: `react_${version}_runtime`,
6
+ remotes: [
7
+ {
8
+ name: `react@${version}`,
9
+ entry: `https://cdn.jsdelivr.net/npm/react@${version}/umd/react.production.min.js`,
10
+ type: 'var',
11
+ entryGlobalName: 'React'
12
+ },
13
+ {
14
+ name: `react-dom@${version}`,
15
+ entry: `https://cdn.jsdelivr.net/npm/react-dom@${version}/umd/react-dom.production.min.js`,
16
+ type: 'var',
17
+ entryGlobalName: 'ReactDOM'
18
+ }
19
+ ]
20
+ });
21
+ const React = await runtime.loadRemote(`react@${version}`);
22
+ const ReactDOM = await runtime.loadRemote(`react-dom@${version}`);
23
+ return {
24
+ React,
25
+ ReactDOM
26
+ };
27
+ }
28
+ function parseVersion(version) {
29
+ const cleaned = version.replace(/^v/i, '');
30
+ const parts = cleaned.split(/[-+]/);
31
+ const [major, minor, patch] = parts[0].split('.').map(Number);
32
+ return {
33
+ major: isNaN(major) ? 0 : major,
34
+ minor: isNaN(minor) ? 0 : minor,
35
+ patch: isNaN(patch) ? 0 : patch,
36
+ prerelease: parts[1],
37
+ build: parts[2],
38
+ raw: cleaned
39
+ };
40
+ }
41
+ function compareVersions(v1, v2) {
42
+ const p1 = parseVersion(v1);
43
+ const p2 = parseVersion(v2);
44
+ if (p1.major !== p2.major) return p1.major - p2.major;
45
+ if (p1.minor !== p2.minor) return p1.minor - p2.minor;
46
+ if (p1.patch !== p2.patch) return p1.patch - p2.patch;
47
+ if (p1.prerelease && !p2.prerelease) return -1;
48
+ if (!p1.prerelease && p2.prerelease) return 1;
49
+ if (p1.prerelease && p2.prerelease) return p1.prerelease.localeCompare(p2.prerelease);
50
+ return 0;
51
+ }
52
+ function satisfiesVersion(current, required) {
53
+ const opMatch = required.match(/^(>=|<=|>|<|=|~|\^)?/);
54
+ const operator = opMatch?.[1] || '=';
55
+ const version = required.replace(/^(>=|<=|>|<|=|~|\^)/, '');
56
+ const cmp = compareVersions(current, version);
57
+ switch(operator){
58
+ case '>':
59
+ return cmp > 0;
60
+ case '>=':
61
+ return cmp >= 0;
62
+ case '<':
63
+ return cmp < 0;
64
+ case '<=':
65
+ return cmp <= 0;
66
+ case '=':
67
+ case '':
68
+ return 0 === cmp;
69
+ case '^':
70
+ return parseVersion(current).major === parseVersion(version).major && (parseVersion(current).major > 0 || parseVersion(current).minor === parseVersion(version).minor);
71
+ case '~':
72
+ return parseVersion(current).major === parseVersion(version).major && parseVersion(current).minor === parseVersion(version).minor;
73
+ default:
74
+ return 0 === cmp;
75
+ }
76
+ }
77
+ function checkVersionCompatibility(currentVersion, requiredVersion, packageName) {
78
+ const isCompatible = satisfiesVersion(currentVersion, requiredVersion);
79
+ const current = parseVersion(currentVersion);
80
+ const required = parseVersion(requiredVersion);
81
+ let message;
82
+ let suggestion;
83
+ let severity;
84
+ if (isCompatible) {
85
+ message = `${packageName}@${currentVersion} 满足要求 ${requiredVersion}`;
86
+ severity = 'info';
87
+ } else {
88
+ const cmp = compareVersions(currentVersion, requiredVersion);
89
+ if (cmp < 0) {
90
+ message = `${packageName}@${currentVersion} 版本过低,需要 ${requiredVersion}`;
91
+ severity = 'error';
92
+ current.patch;
93
+ current.major, current.minor;
94
+ suggestion = `建议升级到 ${current.major}.${current.minor}.x 或更高版本`;
95
+ } else {
96
+ message = `${packageName}@${currentVersion} 版本过高,需要 ${requiredVersion}`;
97
+ severity = 'warning';
98
+ suggestion = `建议降级到 ${required.major}.${required.minor}.x 或匹配主版本的兼容版本`;
99
+ }
100
+ }
101
+ return {
102
+ compatible: isCompatible,
103
+ currentVersion,
104
+ requiredVersion,
105
+ suggestion,
106
+ severity,
107
+ message
108
+ };
109
+ }
110
+ function findCompatibleVersion(availableVersions, range) {
111
+ let candidates = availableVersions;
112
+ if (range.exact) candidates = candidates.filter((v)=>v === range.exact);
113
+ else {
114
+ if (range.min) candidates = candidates.filter((v)=>compareVersions(v, range.min) >= 0);
115
+ if (range.max) candidates = candidates.filter((v)=>compareVersions(v, range.max) <= 0);
116
+ }
117
+ if (0 === candidates.length) return null;
118
+ return candidates.sort((a, b)=>compareVersions(b, a))[0];
119
+ }
120
+ function getCompatibleReactVersions(hostVersion) {
121
+ const host = parseVersion(hostVersion);
122
+ const versions = [];
123
+ for(let i = host.major; i >= 15; i--)for(let j = 0; j <= 5; j++){
124
+ const version = `${i}.${j}.0`;
125
+ if (checkVersionCompatibility(version, `^${host.major}.0.0`, 'react').compatible) versions.push(version);
126
+ }
127
+ const uniqueVersions = [];
128
+ const seen = new Set();
129
+ for (const v of versions)if (!seen.has(v)) {
130
+ seen.add(v);
131
+ uniqueVersions.push(v);
132
+ }
133
+ return uniqueVersions;
134
+ }
135
+ async function fetchAvailableVersions(pkg) {
136
+ try {
137
+ const res = await fetch(`https://registry.npmjs.org/${pkg}`);
138
+ if (!res.ok) return [];
139
+ const data = await res.json();
140
+ return Object.keys(data.versions || {});
141
+ } catch {
142
+ return [];
143
+ }
144
+ }
145
+ function sortVersions(versions, order = 'desc') {
146
+ return [
147
+ ...versions
148
+ ].sort((a, b)=>{
149
+ const cmp = compareVersions(a, b);
150
+ return 'desc' === order ? -cmp : cmp;
151
+ });
152
+ }
153
+ function getLatestVersion(versions) {
154
+ if (0 === versions.length) return null;
155
+ return sortVersions(versions, 'desc')[0];
156
+ }
157
+ function getStableVersions(versions) {
158
+ return versions.filter((v)=>!v.includes('alpha') && !v.includes('beta') && !v.includes('rc'));
159
+ }
160
+ function extractMajorVersion(version) {
161
+ return parseVersion(version).major;
162
+ }
163
+ function isPrerelease(version) {
164
+ const v = parseVersion(version);
165
+ return !!v.prerelease;
166
+ }
2
167
  const fallbackPlugin = ()=>({
3
168
  name: 'fallback-plugin',
4
169
  errorLoadRemote (args) {
@@ -7,29 +172,95 @@ const fallbackPlugin = ()=>({
7
172
  return fallback;
8
173
  }
9
174
  });
175
+ const DEFAULT_CDN_TEMPLATES = [
176
+ 'https://cdn.jsdelivr.net/npm/{pkg}@{version}/dist/remoteEntry.js',
177
+ 'https://unpkg.com/{pkg}@{version}/dist/remoteEntry.js'
178
+ ];
179
+ const DEFAULT_SHARED_CONFIG = {
180
+ react: {
181
+ shareConfig: {
182
+ singleton: true,
183
+ eager: true,
184
+ requiredVersion: false
185
+ }
186
+ },
187
+ 'react-dom': {
188
+ shareConfig: {
189
+ singleton: true,
190
+ eager: true,
191
+ requiredVersion: false
192
+ }
193
+ }
194
+ };
10
195
  async function fetchLatestVersion(pkg) {
11
196
  const res = await fetch(`https://registry.npmjs.org/${pkg}`);
12
- if (!res.ok) throw new Error(`无法获取 ${pkg} 的版本信息`);
197
+ if (!res.ok) throw new Error(`[MF] 无法获取 ${pkg} 的版本信息,状态码:${res.status}`);
13
198
  const data = await res.json();
14
- return data['dist-tags']?.latest;
199
+ const latest = data['dist-tags']?.latest;
200
+ if (!latest) throw new Error(`[MF] 无法从 NPM 获取 ${pkg} 的 latest tag`);
201
+ return latest;
15
202
  }
16
203
  function getVersionCache() {
17
204
  try {
18
- return JSON.parse(localStorage.getItem('mf-multi-version') || '{}');
19
- } catch {
205
+ const cacheStr = localStorage.getItem('mf-multi-version');
206
+ return cacheStr ? JSON.parse(cacheStr) : {};
207
+ } catch (e) {
208
+ console.error('[MF Cache] 读取缓存失败:', e);
20
209
  return {};
21
210
  }
22
211
  }
23
212
  function setVersionCache(pkg, version) {
24
- const cache = getVersionCache();
25
- cache[pkg] = cache[pkg] || {};
26
- cache[pkg][version] = {
27
- timestamp: Date.now()
213
+ try {
214
+ const cache = getVersionCache();
215
+ cache[pkg] = cache[pkg] || {};
216
+ cache[pkg][version] = {
217
+ timestamp: Date.now()
218
+ };
219
+ localStorage.setItem('mf-multi-version', JSON.stringify(cache));
220
+ } catch (e) {
221
+ console.error('[MF Cache] 写入缓存失败:', e);
222
+ }
223
+ }
224
+ function buildCdnUrls(pkg, version) {
225
+ return DEFAULT_CDN_TEMPLATES.map((template)=>template.replace('{pkg}', pkg).replace('{version}', version));
226
+ }
227
+ async function tryLoadRemote(scopeName, url, retries, delay, sharedConfig, plugins) {
228
+ let lastError;
229
+ for(let i = 0; i < retries; i++)try {
230
+ const mf = createInstance({
231
+ name: 'host',
232
+ remotes: [
233
+ {
234
+ name: scopeName,
235
+ entry: url
236
+ }
237
+ ],
238
+ shared: sharedConfig,
239
+ plugins: [
240
+ ...plugins,
241
+ fallbackPlugin()
242
+ ]
243
+ });
244
+ return {
245
+ scopeName,
246
+ mf
247
+ };
248
+ } catch (e) {
249
+ lastError = e;
250
+ console.warn(`[MF] URL ${url} 加载失败,第 ${i + 1} 次重试...`);
251
+ if (i < retries - 1) await new Promise((res)=>setTimeout(res, delay));
252
+ }
253
+ throw new Error(`[MF] URL ${url} 经过 ${retries} 次重试仍加载失败。`, {
254
+ cause: lastError
255
+ });
256
+ }
257
+ function getFinalSharedConfig(customShared) {
258
+ return {
259
+ ...DEFAULT_SHARED_CONFIG,
260
+ ...customShared || {}
28
261
  };
29
- localStorage.setItem('mf-multi-version', JSON.stringify(cache));
30
262
  }
31
- async function loadRemoteMultiVersion(options, plugins) {
32
- const { name, pkg, version = 'latest', retries = 3, delay = 1000, localFallback, cacheTTL = 86400000, revalidate = true } = options;
263
+ async function resolveFinalVersion(pkg, version, cacheTTL, revalidate) {
33
264
  let finalVersion = version;
34
265
  if ('latest' === version) {
35
266
  const cache = getVersionCache();
@@ -38,56 +269,709 @@ async function loadRemoteMultiVersion(options, plugins) {
38
269
  if (latestCached && Date.now() - versions[latestCached].timestamp < cacheTTL) {
39
270
  finalVersion = latestCached;
40
271
  if (revalidate) fetchLatestVersion(pkg).then((latest)=>{
41
- if (latest !== latestCached) setVersionCache(pkg, latest);
42
- }).catch(()=>{});
272
+ if (latest !== latestCached) {
273
+ console.log(`[MF] 发现 ${pkg} 新版本 ${latest},已更新缓存。`);
274
+ setVersionCache(pkg, latest);
275
+ }
276
+ }).catch((e)=>console.error(`[MF] 异步检查最新版本失败:`, e));
43
277
  } else {
44
278
  finalVersion = await fetchLatestVersion(pkg);
45
279
  setVersionCache(pkg, finalVersion);
46
280
  }
47
281
  }
48
- const scopeName = `${name}`;
49
- const urls = [
50
- `https://cdn.jsdelivr.net/npm/${pkg}@${finalVersion}/dist/remoteEntry.js`,
51
- `https://unpkg.com/${pkg}@${finalVersion}/dist/remoteEntry.js`
52
- ];
282
+ return finalVersion;
283
+ }
284
+ function buildFinalUrls(pkg, version, localFallback) {
285
+ const urls = buildCdnUrls(pkg, version);
53
286
  if (localFallback) urls.push(localFallback);
54
- for (const url of urls)for(let i = 0; i < retries; i++)try {
55
- const mf = createInstance({
56
- name: 'host',
57
- remotes: [
58
- {
59
- name: scopeName,
60
- entry: url
61
- }
62
- ],
63
- shared: {
64
- react: {
65
- shareConfig: {
66
- singleton: true,
67
- eager: true,
68
- requiredVersion: false
69
- }
70
- },
71
- 'react-dom': {
72
- shareConfig: {
73
- singleton: true,
74
- eager: true,
75
- requiredVersion: false
76
- }
287
+ return urls;
288
+ }
289
+ async function loadRemoteMultiVersion(options, plugins) {
290
+ const { name, pkg, version = 'latest', retries = 3, delay = 1000, localFallback, cacheTTL = 86400000, revalidate = true, shared: customShared } = options;
291
+ const finalVersion = await resolveFinalVersion(pkg, version, cacheTTL, revalidate);
292
+ const scopeName = `${name}`;
293
+ const urls = buildFinalUrls(pkg, finalVersion, localFallback);
294
+ const finalSharedConfig = getFinalSharedConfig(customShared);
295
+ for (const url of urls)try {
296
+ return await tryLoadRemote(scopeName, url, retries, delay, finalSharedConfig, plugins);
297
+ } catch (e) {
298
+ console.warn(`[MF] 切换 CDN 路径:${url} 失败,尝试下一个...`, e);
299
+ }
300
+ throw new Error(`[MF] 所有加载源 (${urls.length} 个) 均加载失败。`);
301
+ }
302
+ const preloadCache = {};
303
+ const PRELOAD_CACHE_TTL = 300000;
304
+ function getCachedPreload(pkg, version) {
305
+ const cached = preloadCache[pkg];
306
+ if (!cached) return null;
307
+ if (cached.version !== version) return null;
308
+ if (Date.now() - cached.timestamp > PRELOAD_CACHE_TTL) {
309
+ delete preloadCache[pkg];
310
+ return null;
311
+ }
312
+ return {
313
+ scopeName: cached.scopeName,
314
+ mf: cached.mf
315
+ };
316
+ }
317
+ function setCachedPreload(pkg, version, scopeName, mf) {
318
+ preloadCache[pkg] = {
319
+ version,
320
+ scopeName,
321
+ mf,
322
+ timestamp: Date.now()
323
+ };
324
+ }
325
+ function executeWhenIdle(callback) {
326
+ if ('undefined' != typeof requestIdleCallback) requestIdleCallback(()=>callback());
327
+ else setTimeout(callback, 1);
328
+ }
329
+ async function preloadRemote(options) {
330
+ const { pkg, version = 'latest', priority = 'idle', force = false } = options;
331
+ if (!force) {
332
+ const cached = getCachedPreload(pkg, version);
333
+ if (cached) return cached;
334
+ }
335
+ const preloadTask = async ()=>{
336
+ try {
337
+ const { scopeName, mf } = await loadRemoteMultiVersion(options, []);
338
+ setCachedPreload(pkg, version, scopeName, mf);
339
+ return {
340
+ scopeName,
341
+ mf
342
+ };
343
+ } catch (e) {
344
+ console.warn(`[MF Preload] 预加载失败 ${pkg}@${version}:`, e);
345
+ return null;
346
+ }
347
+ };
348
+ if ('high' === priority) return preloadTask();
349
+ return new Promise((resolve)=>{
350
+ executeWhenIdle(async ()=>{
351
+ const result = await preloadTask();
352
+ resolve(result);
353
+ });
354
+ });
355
+ }
356
+ function preloadRemoteList(optionsList, onProgress) {
357
+ let loaded = 0;
358
+ const total = optionsList.length;
359
+ const promises = optionsList.map((options)=>preloadRemote(options).then((result)=>{
360
+ loaded++;
361
+ onProgress?.(loaded, total);
362
+ return result;
363
+ }));
364
+ return Promise.all(promises);
365
+ }
366
+ function cancelPreload(pkg) {
367
+ const cached = preloadCache[pkg];
368
+ if (cached) delete preloadCache[pkg];
369
+ }
370
+ function clearPreloadCache() {
371
+ Object.keys(preloadCache).forEach((pkg)=>delete preloadCache[pkg]);
372
+ }
373
+ function getPreloadStatus(pkg) {
374
+ const cached = preloadCache[pkg];
375
+ if (!cached) return null;
376
+ return {
377
+ loaded: true,
378
+ timestamp: cached.timestamp
379
+ };
380
+ }
381
+ const remoteInstances = new Map();
382
+ function generateInstanceKey(name, pkg, version) {
383
+ return `${name}::${pkg}@${version}`;
384
+ }
385
+ async function unloadRemote(options) {
386
+ const { name, pkg, version = '*', clearCache = false } = options;
387
+ const keysToDelete = [];
388
+ remoteInstances.forEach((instance, key)=>{
389
+ const versionMatch = '*' === version || instance.version === version;
390
+ const pkgMatch = instance.pkg === pkg;
391
+ const nameMatch = instance.name === name;
392
+ if (nameMatch && pkgMatch && versionMatch) keysToDelete.push(key);
393
+ });
394
+ for (const key of keysToDelete){
395
+ const instance = remoteInstances.get(key);
396
+ if (instance) {
397
+ await cleanupInstance(instance);
398
+ remoteInstances.delete(key);
399
+ }
400
+ }
401
+ if (clearCache) clearVersionCache(pkg, version);
402
+ return keysToDelete.length > 0;
403
+ }
404
+ async function cleanupInstance(instance) {
405
+ try {
406
+ instance.loadedModules.clear();
407
+ if (instance.mf && 'function' == typeof instance.mf.cleanup) await instance.mf.cleanup();
408
+ console.log(`[MF Unload] 已卸载 ${instance.pkg}@${instance.version}`);
409
+ } catch (e) {
410
+ console.warn(`[MF Unload] 卸载时出错 ${instance.pkg}:`, e);
411
+ }
412
+ }
413
+ function clearVersionCache(pkg, version) {
414
+ try {
415
+ const cacheKey = 'mf-multi-version';
416
+ const cacheStr = localStorage.getItem(cacheKey);
417
+ if (!cacheStr) return;
418
+ const cache = JSON.parse(cacheStr);
419
+ if (!cache[pkg]) return;
420
+ if ('*' === version) delete cache[pkg];
421
+ else delete cache[pkg][version];
422
+ localStorage.setItem(cacheKey, JSON.stringify(cache));
423
+ console.log(`[MF Unload] 已清除版本缓存 ${pkg}@${version}`);
424
+ } catch (e) {
425
+ console.warn('[MF Unload] 清除缓存失败:', e);
426
+ }
427
+ }
428
+ function registerRemoteInstance(name, scopeName, pkg, version, mf) {
429
+ const key = generateInstanceKey(name, pkg, version);
430
+ const instance = {
431
+ name,
432
+ scopeName,
433
+ pkg,
434
+ version,
435
+ mf,
436
+ loadedModules: new Set(),
437
+ timestamp: Date.now()
438
+ };
439
+ remoteInstances.set(key, instance);
440
+ return key;
441
+ }
442
+ function registerLoadedModule(key, moduleId) {
443
+ const instance = remoteInstances.get(key);
444
+ if (instance) instance.loadedModules.add(moduleId);
445
+ }
446
+ function unloadAll(clearAllCache = false) {
447
+ return new Promise((resolve)=>{
448
+ const keys = Array.from(remoteInstances.keys());
449
+ if (0 === keys.length) return void resolve();
450
+ let completed = 0;
451
+ keys.forEach(async (key)=>{
452
+ const instance = remoteInstances.get(key);
453
+ if (instance) {
454
+ await cleanupInstance(instance);
455
+ remoteInstances.delete(key);
456
+ }
457
+ completed++;
458
+ if (completed >= keys.length) {
459
+ if (clearAllCache) try {
460
+ localStorage.removeItem('mf-multi-version');
461
+ } catch (e) {
462
+ console.warn('[MF Unload] 清除所有缓存失败:', e);
77
463
  }
78
- },
79
- plugins: [
80
- ...plugins,
81
- fallbackPlugin()
82
- ]
464
+ resolve();
465
+ }
466
+ });
467
+ });
468
+ }
469
+ function getLoadedRemotes() {
470
+ const result = [];
471
+ remoteInstances.forEach((instance)=>{
472
+ result.push({
473
+ name: instance.name,
474
+ pkg: instance.pkg,
475
+ version: instance.version,
476
+ loadedModules: instance.loadedModules.size,
477
+ timestamp: instance.timestamp
83
478
  });
479
+ });
480
+ return result;
481
+ }
482
+ function isRemoteLoaded(name, pkg, version) {
483
+ const key = generateInstanceKey(name, pkg, version || '*');
484
+ return remoteInstances.has(key);
485
+ }
486
+ const CDN_URLS = [
487
+ 'https://cdn.jsdelivr.net/npm/{pkg}@{version}/dist/remoteEntry.js',
488
+ 'https://unpkg.com/{pkg}@{version}/dist/remoteEntry.js'
489
+ ];
490
+ async function checkCdnAccess(cdnUrl) {
491
+ const start = performance.now();
492
+ try {
493
+ const controller = new AbortController();
494
+ const timeout = setTimeout(()=>controller.abort(), 5000);
495
+ const res = await fetch(cdnUrl, {
496
+ method: 'HEAD',
497
+ signal: controller.signal
498
+ });
499
+ clearTimeout(timeout);
500
+ const latency = Math.round(performance.now() - start);
84
501
  return {
85
- scopeName,
86
- mf
502
+ reachable: res.ok,
503
+ latency
504
+ };
505
+ } catch (e) {
506
+ const latency = Math.round(performance.now() - start);
507
+ return {
508
+ reachable: false,
509
+ latency
87
510
  };
511
+ }
512
+ }
513
+ async function health_fetchLatestVersion(pkg) {
514
+ try {
515
+ const res = await fetch(`https://registry.npmjs.org/${pkg}`);
516
+ if (!res.ok) return null;
517
+ const data = await res.json();
518
+ return data['dist-tags']?.latest || null;
88
519
  } catch {
89
- await new Promise((res)=>setTimeout(res, delay));
520
+ return null;
521
+ }
522
+ }
523
+ async function checkRemoteHealth(options) {
524
+ const { pkg, version = 'latest' } = options;
525
+ const actualVersion = 'latest' === version ? await health_fetchLatestVersion(pkg) || version : version;
526
+ const results = [];
527
+ for (const template of CDN_URLS){
528
+ const url = template.replace('{pkg}', pkg).replace('{version}', actualVersion);
529
+ const result = await checkCdnAccess(url);
530
+ results.push({
531
+ cdn: url,
532
+ ...result
533
+ });
534
+ }
535
+ const workingCdn = results.find((r)=>r.reachable);
536
+ const bestCdn = results.sort((a, b)=>a.latency - b.latency)[0];
537
+ let status = 'unhealthy';
538
+ if (workingCdn) status = bestCdn.latency < 1000 ? 'healthy' : 'degraded';
539
+ return {
540
+ pkg,
541
+ version: actualVersion,
542
+ status,
543
+ latency: bestCdn?.latency || 0,
544
+ cdn: bestCdn?.cdn || '',
545
+ details: {
546
+ cdnReachable: !!workingCdn,
547
+ remoteEntryValid: false,
548
+ modulesLoadable: false
549
+ }
550
+ };
551
+ }
552
+ async function checkModuleLoadable(scopeName, modulePath, mf) {
553
+ try {
554
+ if (!mf || 'function' != typeof mf.loadRemote) return false;
555
+ const mod = await mf.loadRemote(`${scopeName}/${modulePath}`);
556
+ return null != mod;
557
+ } catch {
558
+ return false;
559
+ }
560
+ }
561
+ async function getRemoteHealthReport(remotes) {
562
+ const results = await Promise.all(remotes.map((r)=>checkRemoteHealth(r)));
563
+ let overall = 'healthy';
564
+ if (results.some((r)=>'unhealthy' === r.status)) overall = 'unhealthy';
565
+ else if (results.some((r)=>'degraded' === r.status)) overall = 'degraded';
566
+ return {
567
+ timestamp: Date.now(),
568
+ overall,
569
+ remotes: results
570
+ };
571
+ }
572
+ function formatHealthStatus(status) {
573
+ const icons = {
574
+ healthy: '🟢',
575
+ degraded: '🟡',
576
+ unhealthy: '🔴'
577
+ };
578
+ return `${icons[status]} ${status}`;
579
+ }
580
+ class EventBusClass {
581
+ listeners = new Map();
582
+ eventHistory = new Map();
583
+ maxHistorySize = 100;
584
+ generateId() {
585
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
586
+ }
587
+ on(event, callback, options) {
588
+ const onceValue = options?.once ?? false;
589
+ if (!this.listeners.has(event)) this.listeners.set(event, new Set());
590
+ const subscription = {
591
+ callback,
592
+ once: onceValue,
593
+ filter: options?.filter
594
+ };
595
+ this.listeners.get(event).add(subscription);
596
+ return ()=>{
597
+ this.off(event, callback);
598
+ };
599
+ }
600
+ once(event, callback) {
601
+ return this.on(event, callback, {
602
+ once: true
603
+ });
604
+ }
605
+ off(event, callback) {
606
+ if (!this.listeners.has(event)) return;
607
+ if (callback) {
608
+ const subscriptions = this.listeners.get(event);
609
+ subscriptions.forEach((sub)=>{
610
+ if (sub.callback === callback) subscriptions.delete(sub);
611
+ });
612
+ } else this.listeners.delete(event);
613
+ }
614
+ emit(event, data, meta) {
615
+ const eventMeta = {
616
+ timestamp: Date.now(),
617
+ source: meta?.source,
618
+ id: meta?.id || this.generateId()
619
+ };
620
+ this.addToHistory(event, data, eventMeta);
621
+ const subscriptions = this.listeners.get(event);
622
+ if (!subscriptions) return;
623
+ const toRemove = [];
624
+ subscriptions.forEach((sub)=>{
625
+ if (sub.filter && !sub.filter(data, eventMeta)) return;
626
+ try {
627
+ sub.callback(data, eventMeta);
628
+ } catch (e) {
629
+ console.error(`[MF EventBus] 事件 ${event} 处理出错:`, e);
630
+ }
631
+ if (sub.once) toRemove.push(sub);
632
+ });
633
+ toRemove.forEach((sub)=>subscriptions.delete(sub));
634
+ }
635
+ addToHistory(event, data, meta) {
636
+ if (!this.eventHistory.has(event)) this.eventHistory.set(event, []);
637
+ const history = this.eventHistory.get(event);
638
+ history.push({
639
+ data,
640
+ meta
641
+ });
642
+ if (history.length > this.maxHistorySize) history.shift();
90
643
  }
91
- throw new Error(`[MF] 所有 CDN 加载失败: ${urls.join(', ')}`);
644
+ getHistory(event) {
645
+ return this.eventHistory.get(event) || [];
646
+ }
647
+ getEvents() {
648
+ return Array.from(this.listeners.keys());
649
+ }
650
+ getListenerCount(event) {
651
+ return this.listeners.get(event)?.size || 0;
652
+ }
653
+ hasListeners(event) {
654
+ return this.listeners.has(event) && this.listeners.get(event).size > 0;
655
+ }
656
+ clear(event) {
657
+ if (event) {
658
+ this.listeners.delete(event);
659
+ this.eventHistory.delete(event);
660
+ } else {
661
+ this.listeners.clear();
662
+ this.eventHistory.clear();
663
+ }
664
+ }
665
+ listenerExists(event, callback) {
666
+ const subscriptions = this.listeners.get(event);
667
+ if (!subscriptions) return false;
668
+ let exists = false;
669
+ subscriptions.forEach((sub)=>{
670
+ if (sub.callback === callback) exists = true;
671
+ });
672
+ return exists;
673
+ }
674
+ emitAsync(event, data, meta) {
675
+ return new Promise((resolve)=>{
676
+ this.emit(event, data, meta);
677
+ resolve();
678
+ });
679
+ }
680
+ static create() {
681
+ return new EventBusClass();
682
+ }
683
+ }
684
+ const eventBus = EventBusClass.create();
685
+ function createEventBus() {
686
+ return EventBusClass.create();
687
+ }
688
+ class ErrorBoundary extends react.Component {
689
+ constructor(props){
690
+ super(props);
691
+ this.state = {
692
+ hasError: false,
693
+ error: null,
694
+ errorInfo: null
695
+ };
696
+ }
697
+ static getDerivedStateFromError(error) {
698
+ return {
699
+ hasError: true,
700
+ error,
701
+ errorInfo: null
702
+ };
703
+ }
704
+ componentDidCatch(error, errorInfo) {
705
+ this.setState({
706
+ errorInfo
707
+ });
708
+ this.props.onError?.(error, errorInfo);
709
+ console.error('[RemoteReloadUtils] ErrorBoundary caught error:', error, errorInfo);
710
+ }
711
+ handleReset = ()=>{
712
+ this.setState({
713
+ hasError: false,
714
+ error: null,
715
+ errorInfo: null
716
+ });
717
+ this.props.onReset?.();
718
+ };
719
+ render() {
720
+ if (this.state.hasError && this.state.error) {
721
+ if ('function' == typeof this.props.fallback) return this.props.fallback(this.state.error, this.handleReset);
722
+ if (void 0 !== this.props.fallback) return this.props.fallback;
723
+ return /*#__PURE__*/ react.createElement("div", {
724
+ role: "alert",
725
+ style: {
726
+ padding: '16px',
727
+ border: '1px solid #ffcccc',
728
+ backgroundColor: '#fff5f5',
729
+ borderRadius: '4px'
730
+ }
731
+ }, /*#__PURE__*/ react.createElement("h3", null, "Something went wrong"), /*#__PURE__*/ react.createElement("p", null, this.state.error.message), /*#__PURE__*/ react.createElement("button", {
732
+ onClick: this.handleReset,
733
+ style: {
734
+ marginTop: '8px',
735
+ padding: '8px 16px',
736
+ cursor: 'pointer'
737
+ }
738
+ }, "Try again"));
739
+ }
740
+ return this.props.children;
741
+ }
742
+ }
743
+ function useRemoteModule({ pkg, version, moduleName, scopeName, onError, onLoad }) {
744
+ const [moduleState, setModuleState] = useState({
745
+ loading: true,
746
+ error: null,
747
+ component: null
748
+ });
749
+ useEffect(()=>{
750
+ let mounted = true;
751
+ async function loadModule() {
752
+ try {
753
+ setModuleState((prev)=>({
754
+ ...prev,
755
+ loading: true,
756
+ error: null
757
+ }));
758
+ const { mf } = await loadRemoteMultiVersion({
759
+ name: scopeName,
760
+ pkg,
761
+ version
762
+ }, []);
763
+ if (!mf || !mounted) return;
764
+ const mod = await mf.loadRemote(`${scopeName}/${moduleName}`);
765
+ if (!mounted) return;
766
+ if (mod && 'object' == typeof mod && 'default' in mod) {
767
+ const Component = mod.default;
768
+ setModuleState({
769
+ loading: false,
770
+ error: null,
771
+ component: Component
772
+ });
773
+ onLoad?.(Component);
774
+ } else throw new Error(`Module "${scopeName}/${moduleName}" does not export a default component`);
775
+ } catch (err) {
776
+ if (mounted) {
777
+ const error = err instanceof Error ? err : new Error(String(err));
778
+ setModuleState({
779
+ loading: false,
780
+ error,
781
+ component: null
782
+ });
783
+ onError?.(error);
784
+ }
785
+ }
786
+ }
787
+ loadModule();
788
+ return ()=>{
789
+ mounted = false;
790
+ };
791
+ }, [
792
+ pkg,
793
+ version,
794
+ moduleName,
795
+ scopeName,
796
+ onError,
797
+ onLoad
798
+ ]);
799
+ return moduleState;
800
+ }
801
+ function RemoteModuleCardContent({ pkg, version, moduleName, scopeName, loadingFallback, errorFallback, componentProps, className, style, onError, onLoad }) {
802
+ const moduleState = useRemoteModule({
803
+ pkg,
804
+ version,
805
+ moduleName,
806
+ scopeName,
807
+ onError,
808
+ onLoad
809
+ });
810
+ const [retryCount, setRetryCount] = useState(0);
811
+ const handleRetry = useCallback(()=>{
812
+ setRetryCount((prev)=>prev + 1);
813
+ }, []);
814
+ useEffect(()=>{}, [
815
+ retryCount
816
+ ]);
817
+ if (moduleState.loading) return /*#__PURE__*/ react.createElement("div", {
818
+ className: className,
819
+ style: style,
820
+ role: "status",
821
+ "aria-live": "polite"
822
+ }, loadingFallback || /*#__PURE__*/ react.createElement("div", {
823
+ className: "module-card module-card--loading"
824
+ }, /*#__PURE__*/ react.createElement("div", {
825
+ className: "loading-spinner",
826
+ "aria-hidden": "true"
827
+ }), /*#__PURE__*/ react.createElement("span", null, "Loading ", moduleName, "...")));
828
+ if (moduleState.error) {
829
+ if ('function' == typeof errorFallback) return /*#__PURE__*/ react.createElement(react.Fragment, null, errorFallback(moduleState.error, handleRetry));
830
+ if (void 0 !== errorFallback) return /*#__PURE__*/ react.createElement(react.Fragment, null, errorFallback);
831
+ return /*#__PURE__*/ react.createElement("div", {
832
+ className: className,
833
+ style: style,
834
+ role: "alert"
835
+ }, /*#__PURE__*/ react.createElement("div", {
836
+ className: "module-card module-card--error"
837
+ }, /*#__PURE__*/ react.createElement("span", {
838
+ className: "error-icon",
839
+ "aria-hidden": "true"
840
+ }, "!"), /*#__PURE__*/ react.createElement("span", null, "Failed to load ", moduleName), /*#__PURE__*/ react.createElement("p", {
841
+ className: "error-message"
842
+ }, moduleState.error.message), /*#__PURE__*/ react.createElement("button", {
843
+ onClick: handleRetry,
844
+ className: "retry-button",
845
+ type: "button"
846
+ }, "Retry")));
847
+ }
848
+ if (!moduleState.component) return null;
849
+ const Component = moduleState.component;
850
+ return /*#__PURE__*/ react.createElement("div", {
851
+ className: className,
852
+ style: style
853
+ }, /*#__PURE__*/ react.createElement(Component, componentProps));
854
+ }
855
+ function RemoteModuleCard(props) {
856
+ const { disableErrorBoundary, errorFallback, loadingFallback, errorBoundaryOptions } = props;
857
+ if (disableErrorBoundary) return /*#__PURE__*/ react.createElement(Suspense, {
858
+ fallback: loadingFallback || /*#__PURE__*/ react.createElement("div", null, "Loading...")
859
+ }, /*#__PURE__*/ react.createElement(RemoteModuleCardContent, props));
860
+ return /*#__PURE__*/ react.createElement(ErrorBoundary, {
861
+ fallback: errorFallback,
862
+ onError: errorBoundaryOptions?.onError,
863
+ onReset: errorBoundaryOptions?.onReset
864
+ }, /*#__PURE__*/ react.createElement(Suspense, {
865
+ fallback: loadingFallback || /*#__PURE__*/ react.createElement("div", null, "Loading...")
866
+ }, /*#__PURE__*/ react.createElement(RemoteModuleCardContent, props)));
867
+ }
868
+ function lazyRemote(options) {
869
+ const { pkg, version = 'latest', moduleName, scopeName, maxRetries = 3, retryDelay = 1000 } = options;
870
+ let retryCount = 0;
871
+ const loadComponent = async ()=>{
872
+ try {
873
+ const { mf } = await loadRemoteMultiVersion({
874
+ name: scopeName,
875
+ pkg,
876
+ version
877
+ }, []);
878
+ if (!mf) throw new Error(`[RemoteReloadUtils] Failed to get Module Federation instance for ${scopeName}`);
879
+ const mod = await mf.loadRemote(`${scopeName}/${moduleName}`);
880
+ if (!mod || 'object' != typeof mod || !('default' in mod)) throw new Error(`[RemoteReloadUtils] Module "${scopeName}/${moduleName}" does not export a default component`);
881
+ return {
882
+ default: mod.default
883
+ };
884
+ } catch (error) {
885
+ if (retryCount < maxRetries) {
886
+ retryCount++;
887
+ await new Promise((resolve)=>setTimeout(resolve, retryDelay * retryCount));
888
+ return loadComponent();
889
+ }
890
+ throw error;
891
+ }
892
+ };
893
+ return /*#__PURE__*/ lazy(loadComponent);
894
+ }
895
+ function SuspenseRemote({ fallback, children }) {
896
+ return /*#__PURE__*/ react.createElement(Suspense, {
897
+ fallback: fallback || /*#__PURE__*/ react.createElement("div", null, "Loading...")
898
+ }, children);
899
+ }
900
+ function SuspenseRemoteLoader({ pkg, version = 'latest', moduleName, scopeName, fallback, errorFallback, componentProps }) {
901
+ const RemoteComponent = lazyRemote({
902
+ pkg,
903
+ version,
904
+ moduleName,
905
+ scopeName
906
+ });
907
+ if (errorFallback) return /*#__PURE__*/ react.createElement(ErrorBoundary, {
908
+ fallback: errorFallback
909
+ }, /*#__PURE__*/ react.createElement(Suspense, {
910
+ fallback: fallback || /*#__PURE__*/ react.createElement("div", null, "Loading...")
911
+ }, /*#__PURE__*/ react.createElement(RemoteComponent, componentProps)));
912
+ return /*#__PURE__*/ react.createElement(Suspense, {
913
+ fallback: fallback || /*#__PURE__*/ react.createElement("div", null, "Loading...")
914
+ }, /*#__PURE__*/ react.createElement(RemoteComponent, componentProps));
915
+ }
916
+ function withRemote(WrappedComponent, options) {
917
+ const RemoteComponent = lazyRemote(options);
918
+ return function(props) {
919
+ return /*#__PURE__*/ react.createElement(Suspense, {
920
+ fallback: /*#__PURE__*/ react.createElement("div", null, "Loading...")
921
+ }, /*#__PURE__*/ react.createElement(RemoteComponent, props));
922
+ };
923
+ }
924
+ function useRemoteModuleHook(options) {
925
+ const { pkg, version = 'latest', moduleName, scopeName } = options;
926
+ const [state, setState] = useState({
927
+ component: null,
928
+ loading: true,
929
+ error: null
930
+ });
931
+ useEffect(()=>{
932
+ let mounted = true;
933
+ async function load() {
934
+ try {
935
+ setState((prev)=>({
936
+ ...prev,
937
+ loading: true,
938
+ error: null
939
+ }));
940
+ const { mf } = await loadRemoteMultiVersion({
941
+ name: scopeName,
942
+ pkg,
943
+ version
944
+ }, []);
945
+ if (!mf) throw new Error(`[RemoteReloadUtils] Failed to get Module Federation instance for ${scopeName}`);
946
+ const mod = await mf.loadRemote(`${scopeName}/${moduleName}`);
947
+ if (mounted) if (mod && 'object' == typeof mod && 'default' in mod) setState({
948
+ component: mod.default,
949
+ loading: false,
950
+ error: null
951
+ });
952
+ else throw new Error(`[RemoteReloadUtils] Module "${scopeName}/${moduleName}" does not export a default component`);
953
+ } catch (err) {
954
+ if (mounted) setState({
955
+ component: null,
956
+ loading: false,
957
+ error: err instanceof Error ? err : new Error(String(err))
958
+ });
959
+ }
960
+ }
961
+ load();
962
+ return ()=>{
963
+ mounted = false;
964
+ };
965
+ }, [
966
+ pkg,
967
+ version,
968
+ moduleName,
969
+ scopeName
970
+ ]);
971
+ return {
972
+ component: state.component,
973
+ loading: state.loading,
974
+ error: state.error
975
+ };
92
976
  }
93
- export { loadRemoteMultiVersion };
977
+ export { ErrorBoundary, RemoteModuleCard, SuspenseRemote, SuspenseRemoteLoader, buildCdnUrls, buildFinalUrls, cancelPreload, checkModuleLoadable, checkRemoteHealth, checkVersionCompatibility, clearPreloadCache, compareVersions, createEventBus, eventBus, extractMajorVersion, fallbackPlugin, fetchAvailableVersions, fetchLatestVersion, findCompatibleVersion, formatHealthStatus, getCompatibleReactVersions, getFinalSharedConfig, getLatestVersion, getLoadedRemotes, getPreloadStatus, getRemoteHealthReport, getStableVersions, getVersionCache, isPrerelease, isRemoteLoaded, lazyRemote, loadReactVersion, loadRemoteMultiVersion, parseVersion, preloadRemote, preloadRemoteList, registerLoadedModule, registerRemoteInstance, resolveFinalVersion, satisfiesVersion, setVersionCache, sortVersions, tryLoadRemote, unloadAll, unloadRemote, useRemoteModuleHook, withRemote };