@module-federation/vite 1.9.8 → 1.11.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.
package/lib/index.esm.js CHANGED
@@ -126,15 +126,44 @@ var addEntry = function addEntry(_ref) {
126
126
  }
127
127
  },
128
128
  generateBundle: function generateBundle(options, bundle) {
129
- var _viteConfig$experimen, _viteConfig$experimen2;
130
129
  if (!injectHtml()) return;
131
130
  var file = this.getFileName(emitFileId);
132
- var path = (_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl ? (_viteConfig$experimen2 = viteConfig.experimental) == null ? void 0 : _viteConfig$experimen2.renderBuiltUrl(file) : viteConfig.base + file;
133
- var scriptContent = "\n <script type=\"module\" src=\"" + path + "\"></script>\n ";
131
+ // Helper to resolve path with proper renderBuiltUrl handling
132
+ var resolvePath = function resolvePath(htmlFileName) {
133
+ var _viteConfig$experimen;
134
+ if (!((_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl)) {
135
+ return viteConfig.base + file;
136
+ }
137
+ var result = viteConfig.experimental.renderBuiltUrl(file, {
138
+ hostId: htmlFileName,
139
+ hostType: 'html',
140
+ type: 'asset',
141
+ ssr: false
142
+ });
143
+ // Handle return types
144
+ if (typeof result === 'string') {
145
+ return result;
146
+ }
147
+ if (result && typeof result === 'object') {
148
+ if ('runtime' in result) {
149
+ // Runtime code cannot be used in <script src="">
150
+ console.warn('[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. ' + 'Runtime code cannot be used in <script src="">. Falling back to base path.');
151
+ return viteConfig.base + file;
152
+ }
153
+ if (result.relative) {
154
+ return file;
155
+ }
156
+ }
157
+ // Fallback for undefined or unexpected values
158
+ return viteConfig.base + file;
159
+ };
160
+ // Process each HTML file
134
161
  for (var _fileName in bundle) {
135
162
  if (_fileName.endsWith('.html')) {
136
163
  var htmlAsset = bundle[_fileName];
137
164
  if (htmlAsset.type === 'chunk') return;
165
+ var _path = resolvePath(_fileName);
166
+ var scriptContent = "\n <script type=\"module\" src=\"" + _path + "\"></script>\n ";
138
167
  var htmlContent = htmlAsset.source.toString() || '';
139
168
  htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
140
169
  htmlAsset.source = htmlContent;
@@ -323,181 +352,519 @@ function PluginDevProxyModuleTopLevelAwait() {
323
352
  };
324
353
  }
325
354
 
326
- function normalizeExposesItem(key, item) {
327
- var importPath = '';
328
- if (typeof item === 'string') {
329
- importPath = item;
355
+ function _catch(body, recover) {
356
+ try {
357
+ var result = body();
358
+ } catch (e) {
359
+ return recover(e);
330
360
  }
331
- if (typeof item === 'object') {
332
- importPath = item["import"];
361
+ if (result && result.then) {
362
+ return result.then(void 0, recover);
333
363
  }
334
- return {
335
- "import": importPath
336
- };
337
- }
338
- function normalizeExposes(exposes) {
339
- if (!exposes) return {};
340
- var res = {};
341
- Object.keys(exposes).forEach(function (key) {
342
- res[key] = normalizeExposesItem(key, exposes[key]);
343
- });
344
- return res;
364
+ return result;
345
365
  }
346
- function normalizeRemotes(remotes) {
347
- if (!remotes) return {};
348
- var result = {};
349
- if (typeof remotes === 'object') {
350
- Object.keys(remotes).forEach(function (key) {
351
- result[key] = normalizeRemoteItem(key, remotes[key]);
366
+ var DEFAULT_DEV_OPTIONS = {
367
+ disableLiveReload: true,
368
+ disableHotTypesReload: false,
369
+ disableDynamicRemoteTypeHints: false
370
+ };
371
+ var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
372
+ var getIPv4 = function getIPv4() {
373
+ return process.env['FEDERATION_IPV4'] || '127.0.0.1';
374
+ };
375
+ var forkDevWorkerPath = function () {
376
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
377
+ return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
378
+ }();
379
+ var DevWorker = /*#__PURE__*/function () {
380
+ function DevWorker(options) {
381
+ this.worker = rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
382
+ this.worker.connect(options);
383
+ }
384
+ var _proto = DevWorker.prototype;
385
+ _proto.update = function update() {
386
+ var _this$worker$process;
387
+ (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
388
+ type: rpc.RpcGMCallTypes.CALL,
389
+ id: this.worker.id,
390
+ args: [undefined, 'update']
352
391
  });
392
+ };
393
+ _proto.exit = function exit() {
394
+ this.worker.terminate();
395
+ };
396
+ return DevWorker;
397
+ }();
398
+ var normalizeDevOptions = function normalizeDevOptions(dev) {
399
+ if (dev === false) {
400
+ return false;
353
401
  }
354
- return result;
355
- }
356
- function normalizeRemoteItem(key, remote) {
357
- if (typeof remote === 'string') {
358
- var _remote$split = remote.split('@'),
359
- entryGlobalName = _remote$split[0];
360
- var entry = remote.replace(entryGlobalName + '@', '');
361
- return {
362
- type: 'var',
363
- name: key,
364
- entry: entry,
365
- entryGlobalName: entryGlobalName,
366
- shareScope: 'default'
367
- };
402
+ if (dev === true || typeof dev === 'undefined') {
403
+ return _extends({}, DEFAULT_DEV_OPTIONS);
368
404
  }
369
- return Object.assign({
370
- type: 'var',
371
- name: key,
372
- shareScope: 'default',
373
- entryGlobalName: key
374
- }, remote);
375
- }
376
- function removePathFromNpmPackage(packageString) {
377
- // 匹配npm包名的正则表达式,忽略路径部分
378
- var regex = /^(?:@[^/]+\/)?[^/]+/;
379
- // 使用正则表达式匹配并提取包名
380
- var match = packageString.match(regex);
381
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
382
- return match ? match[0] : packageString;
383
- }
384
- /**
385
- * Tries to find the package.json's version of a shared package
386
- * if `package.json` is not declared in `exports`
387
- * @param {string} sharedName
388
- * @returns {string | undefined}
389
- */
390
- function searchPackageVersion(sharedName) {
391
- try {
392
- var sharedPath = require.resolve(sharedName);
393
- var potentialPackageJsonDir = path.dirname(sharedPath);
394
- var rootDir = path.parse(potentialPackageJsonDir).root;
395
- while (path.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
396
- var potentialPackageJsonPath = path.join(potentialPackageJsonDir, 'package.json');
397
- if (fs.existsSync(potentialPackageJsonPath)) {
398
- var potentialPackageJson = require(potentialPackageJsonPath);
399
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
400
- return potentialPackageJson.version;
401
- }
402
- }
403
- potentialPackageJsonDir = path.dirname(potentialPackageJsonDir);
405
+ return _extends({}, DEFAULT_DEV_OPTIONS, dev);
406
+ };
407
+ var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
408
+ var exposes = {};
409
+ Object.entries(options.exposes).forEach(function (_ref) {
410
+ var key = _ref[0],
411
+ value = _ref[1];
412
+ if (typeof value === 'string') {
413
+ exposes[key] = value;
414
+ return;
404
415
  }
405
- } catch (_) {}
406
- return undefined;
407
- }
408
- function normalizeShareItem(key, shareItem) {
409
- var version;
410
- try {
411
- try {
412
- version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
413
- } catch (e1) {
414
- try {
415
- var localPath = path.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
416
- version = require(localPath).version;
417
- } catch (e2) {
418
- version = searchPackageVersion(key);
419
- if (!version) console.error(e1);
420
- }
416
+ var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
417
+ if (importValue) {
418
+ exposes[key] = importValue;
421
419
  }
422
- } catch (e) {
423
- console.error("Unexpected error resolving version for " + key + ":", e);
424
- }
425
- if (typeof shareItem === 'string') {
426
- return {
427
- name: shareItem,
428
- version: version,
429
- scope: 'default',
430
- from: '',
431
- shareConfig: {
432
- "import": undefined,
433
- singleton: false,
434
- requiredVersion: version ? "^" + version : '*'
435
- }
436
- };
420
+ });
421
+ var remotes = {};
422
+ Object.entries(options.remotes).forEach(function (_ref2) {
423
+ var _remote$entryGlobalNa, _remote$entryGlobalNa2;
424
+ var key = _ref2[0],
425
+ remote = _ref2[1];
426
+ if (typeof remote === 'string') {
427
+ remotes[key] = remote;
428
+ return;
429
+ }
430
+ if (!remote.entry) {
431
+ return;
432
+ }
433
+ var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
434
+ var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
435
+ remotes[key] = entryGlobalName + "@" + remote.entry;
436
+ });
437
+ return _extends({}, options, {
438
+ exposes: exposes,
439
+ remotes: remotes
440
+ });
441
+ };
442
+ var resolveOutputDir = function resolveOutputDir(config) {
443
+ var outDir = config.build.outDir;
444
+ if (path.isAbsolute(outDir)) {
445
+ return path.relative(config.root, outDir);
437
446
  }
438
- return {
439
- name: key,
440
- from: '',
441
- version: shareItem.version || version,
442
- scope: shareItem.shareScope || 'default',
443
- shareConfig: {
444
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
445
- singleton: shareItem.singleton || false,
446
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
447
- strictVersion: !!shareItem.strictVersion
447
+ return outDir;
448
+ };
449
+ var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
450
+ var hasPlugin = options.runtimePlugins.some(function (plugin) {
451
+ if (typeof plugin === 'string') {
452
+ return plugin === pluginId;
448
453
  }
449
- };
450
- }
451
- function normalizeShared(shared) {
452
- if (!shared) return {};
453
- var result = {};
454
- if (Array.isArray(shared)) {
455
- shared.forEach(function (key) {
456
- result[key] = normalizeShareItem(key, key);
457
- });
458
- return result;
454
+ return plugin[0] === pluginId;
455
+ });
456
+ if (!hasPlugin) {
457
+ options.runtimePlugins.push(pluginId);
459
458
  }
460
- if (typeof shared === 'object') {
461
- Object.keys(shared).forEach(function (key) {
462
- result[key] = normalizeShareItem(key, shared[key]);
463
- });
459
+ };
460
+ var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
461
+ var defaultGenerateTypes = {
462
+ compileInChildProcess: true
463
+ };
464
+ var defaultConsumeTypes = {
465
+ consumeAPITypes: true
466
+ };
467
+ return normalizeOptions(isTSProject(dts, context), {
468
+ generateTypes: defaultGenerateTypes,
469
+ consumeTypes: defaultConsumeTypes,
470
+ extraOptions: {},
471
+ displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
472
+ }, 'mfOptions.dts')(dts);
473
+ };
474
+ var logDtsError = function logDtsError(error, dtsOptions) {
475
+ if (dtsOptions === false) {
476
+ return;
464
477
  }
465
- return result;
466
- }
467
- function normalizeLibrary(library) {
468
- if (!library) return undefined;
469
- return library;
470
- }
471
- function normalizeManifest(manifest) {
472
- if (manifest === void 0) {
473
- manifest = false;
478
+ if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
479
+ return;
474
480
  }
475
- if (typeof manifest === 'boolean') {
476
- return manifest;
481
+ console.error(error);
482
+ };
483
+ function pluginDts(options) {
484
+ if (options.dts === false) {
485
+ return [];
477
486
  }
478
- return Object.assign({
479
- filePath: '',
480
- disableAssetsAnalyze: false,
481
- fileName: 'mf-manifest.json'
482
- }, manifest);
487
+ var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
488
+ var resolvedConfig;
489
+ var devWorker;
490
+ var normalizedDevOptions;
491
+ var hasGeneratedBundle = false;
492
+ var devPlugin = {
493
+ name: 'module-federation-dts-dev',
494
+ apply: 'serve',
495
+ config: function config(_config) {
496
+ normalizedDevOptions = normalizeDevOptions(options.dev);
497
+ if (!normalizedDevOptions) {
498
+ return;
499
+ }
500
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
501
+ return;
502
+ }
503
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
504
+ var define = _config.define ? _extends({}, _config.define) : {};
505
+ if (!('FEDERATION_IPV4' in define)) {
506
+ define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
507
+ }
508
+ _config.define = define;
509
+ },
510
+ configResolved: function configResolved(config) {
511
+ resolvedConfig = config;
512
+ },
513
+ configureServer: function configureServer(server) {
514
+ if (!normalizedDevOptions || !resolvedConfig) {
515
+ return;
516
+ }
517
+ var devOptions = normalizedDevOptions;
518
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
519
+ return;
520
+ }
521
+ if (!options.name) {
522
+ throw new Error('name is required if you want to enable dev server!');
523
+ }
524
+ var outputDir = resolveOutputDir(resolvedConfig);
525
+ var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
526
+ if (typeof normalizedDtsOptions !== 'object') {
527
+ return;
528
+ }
529
+ var normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
530
+ compileInChildProcess: true
531
+ }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
532
+ var remote = normalizedGenerateTypes === false ? undefined : _extends({
533
+ implementation: normalizedDtsOptions.implementation,
534
+ context: resolvedConfig.root,
535
+ outputDir: outputDir,
536
+ moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
537
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
538
+ }, normalizedGenerateTypes, {
539
+ typesFolder: '.dev-server'
540
+ });
541
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
542
+ remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
543
+ }
544
+ var normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
545
+ consumeAPITypes: true
546
+ }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
547
+ var host = normalizedConsumeTypes === false ? undefined : _extends({
548
+ implementation: normalizedDtsOptions.implementation,
549
+ context: resolvedConfig.root,
550
+ moduleFederationConfig: dtsModuleFederationConfig,
551
+ typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
552
+ abortOnError: false
553
+ }, normalizedConsumeTypes);
554
+ var extraOptions = normalizedDtsOptions.extraOptions || {};
555
+ if (!remote && !host && devOptions.disableLiveReload) {
556
+ return;
557
+ }
558
+ var startDevWorker = function startDevWorker() {
559
+ try {
560
+ var _temp2 = function _temp2() {
561
+ var _server$httpServer;
562
+ devWorker = new DevWorker({
563
+ name: options.name,
564
+ remote: remote,
565
+ host: host ? _extends({}, host, {
566
+ remoteTypeUrls: remoteTypeUrls
567
+ }) : undefined,
568
+ extraOptions: extraOptions,
569
+ disableLiveReload: devOptions.disableLiveReload,
570
+ disableHotTypesReload: devOptions.disableHotTypesReload
571
+ });
572
+ var update = function update() {
573
+ var _devWorker;
574
+ return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
575
+ };
576
+ server.watcher.on('change', update);
577
+ server.watcher.on('add', update);
578
+ server.watcher.on('unlink', update);
579
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
580
+ var _devWorker2;
581
+ (_devWorker2 = devWorker) == null || _devWorker2.exit();
582
+ server.watcher.off('change', update);
583
+ server.watcher.off('add', update);
584
+ server.watcher.off('unlink', update);
585
+ });
586
+ };
587
+ var remoteTypeUrls;
588
+ var _temp = function () {
589
+ if (host) {
590
+ return Promise.resolve(new Promise(function (resolve) {
591
+ consumeTypesAPI({
592
+ host: host,
593
+ extraOptions: extraOptions,
594
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
595
+ }, resolve);
596
+ })).then(function (_Promise) {
597
+ remoteTypeUrls = _Promise;
598
+ });
599
+ }
600
+ }();
601
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
602
+ } catch (e) {
603
+ return Promise.reject(e);
604
+ }
605
+ };
606
+ startDevWorker()["catch"](function (error) {
607
+ logDtsError(error, normalizedDtsOptions);
608
+ });
609
+ }
610
+ };
611
+ var buildPlugin = {
612
+ name: 'module-federation-dts-build',
613
+ apply: 'build',
614
+ configResolved: function configResolved(config) {
615
+ resolvedConfig = config;
616
+ },
617
+ generateBundle: function generateBundle() {
618
+ try {
619
+ var _temp6 = function _temp6() {
620
+ var generateOptions;
621
+ try {
622
+ generateOptions = normalizeGenerateTypesOptions({
623
+ context: context,
624
+ outputDir: outputDir,
625
+ dtsOptions: normalizedDtsOptions,
626
+ pluginOptions: dtsModuleFederationConfig
627
+ });
628
+ } catch (error) {
629
+ logDtsError(error, normalizedDtsOptions);
630
+ return;
631
+ }
632
+ if (!generateOptions) {
633
+ return;
634
+ }
635
+ var _temp4 = _catch(function () {
636
+ return Promise.resolve(generateTypesAPI({
637
+ dtsManagerOptions: generateOptions
638
+ })).then(function () {});
639
+ }, function (error) {
640
+ logDtsError(error, normalizedDtsOptions);
641
+ });
642
+ if (_temp4 && _temp4.then) return _temp4.then(function () {});
643
+ };
644
+ if (hasGeneratedBundle) {
645
+ return Promise.resolve();
646
+ }
647
+ hasGeneratedBundle = true;
648
+ if (!resolvedConfig) {
649
+ return Promise.resolve();
650
+ }
651
+ var normalizedDtsOptions;
652
+ try {
653
+ normalizedDtsOptions = normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
654
+ } catch (error) {
655
+ logDtsError(error, options.dts);
656
+ return Promise.resolve();
657
+ }
658
+ if (typeof normalizedDtsOptions !== 'object') {
659
+ return Promise.resolve();
660
+ }
661
+ var context = resolvedConfig.root;
662
+ var outputDir = resolveOutputDir(resolvedConfig);
663
+ var consumeOptions;
664
+ try {
665
+ consumeOptions = normalizeConsumeTypesOptions({
666
+ context: context,
667
+ dtsOptions: normalizedDtsOptions,
668
+ pluginOptions: dtsModuleFederationConfig
669
+ });
670
+ } catch (error) {
671
+ logDtsError(error, normalizedDtsOptions);
672
+ return Promise.resolve();
673
+ }
674
+ var _temp5 = function (_consumeOptions) {
675
+ if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
676
+ var _temp3 = _catch(function () {
677
+ return Promise.resolve(consumeTypesAPI(consumeOptions)).then(function () {});
678
+ }, function (error) {
679
+ logDtsError(error, normalizedDtsOptions);
680
+ });
681
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
682
+ }
683
+ }();
684
+ return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
685
+ } catch (e) {
686
+ return Promise.reject(e);
687
+ }
688
+ }
689
+ };
690
+ return [devPlugin, buildPlugin];
483
691
  }
484
- var config;
485
- function getNormalizeModuleFederationOptions() {
486
- return config;
692
+
693
+ function normalizeExposesItem(key, item) {
694
+ var importPath = '';
695
+ if (typeof item === 'string') {
696
+ importPath = item;
697
+ }
698
+ if (typeof item === 'object') {
699
+ importPath = item["import"];
700
+ }
701
+ return {
702
+ "import": importPath
703
+ };
487
704
  }
488
- function getNormalizeShareItem(key) {
489
- var options = getNormalizeModuleFederationOptions();
490
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
491
- return shareItem;
705
+ function normalizeExposes(exposes) {
706
+ if (!exposes) return {};
707
+ var res = {};
708
+ Object.keys(exposes).forEach(function (key) {
709
+ res[key] = normalizeExposesItem(key, exposes[key]);
710
+ });
711
+ return res;
492
712
  }
493
- function normalizeModuleFederationOptions(options) {
494
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
495
- throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
713
+ function normalizeRemotes(remotes) {
714
+ if (!remotes) return {};
715
+ var result = {};
716
+ if (typeof remotes === 'object') {
717
+ Object.keys(remotes).forEach(function (key) {
718
+ result[key] = normalizeRemoteItem(key, remotes[key]);
719
+ });
496
720
  }
497
- return config = {
498
- exposes: normalizeExposes(options.exposes),
499
- filename: options.filename || 'remoteEntry-[hash]',
500
- library: normalizeLibrary(options.library),
721
+ return result;
722
+ }
723
+ function normalizeRemoteItem(key, remote) {
724
+ if (typeof remote === 'string') {
725
+ var _remote$split = remote.split('@'),
726
+ entryGlobalName = _remote$split[0];
727
+ var entry = remote.replace(entryGlobalName + '@', '');
728
+ return {
729
+ type: 'var',
730
+ name: key,
731
+ entry: entry,
732
+ entryGlobalName: entryGlobalName,
733
+ shareScope: 'default'
734
+ };
735
+ }
736
+ return Object.assign({
737
+ type: 'var',
738
+ name: key,
739
+ shareScope: 'default',
740
+ entryGlobalName: key
741
+ }, remote);
742
+ }
743
+ function removePathFromNpmPackage(packageString) {
744
+ // 匹配npm包名的正则表达式,忽略路径部分
745
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
746
+ // 使用正则表达式匹配并提取包名
747
+ var match = packageString.match(regex);
748
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
749
+ return match ? match[0] : packageString;
750
+ }
751
+ /**
752
+ * Tries to find the package.json's version of a shared package
753
+ * if `package.json` is not declared in `exports`
754
+ * @param {string} sharedName
755
+ * @returns {string | undefined}
756
+ */
757
+ function searchPackageVersion(sharedName) {
758
+ try {
759
+ var sharedPath = require.resolve(sharedName);
760
+ var potentialPackageJsonDir = path.dirname(sharedPath);
761
+ var rootDir = path.parse(potentialPackageJsonDir).root;
762
+ while (path.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
763
+ var potentialPackageJsonPath = path.join(potentialPackageJsonDir, 'package.json');
764
+ if (fs.existsSync(potentialPackageJsonPath)) {
765
+ var potentialPackageJson = require(potentialPackageJsonPath);
766
+ if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
767
+ return potentialPackageJson.version;
768
+ }
769
+ }
770
+ potentialPackageJsonDir = path.dirname(potentialPackageJsonDir);
771
+ }
772
+ } catch (_) {}
773
+ return undefined;
774
+ }
775
+ function normalizeShareItem(key, shareItem) {
776
+ var version;
777
+ try {
778
+ try {
779
+ version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
780
+ } catch (e1) {
781
+ try {
782
+ var localPath = path.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
783
+ version = require(localPath).version;
784
+ } catch (e2) {
785
+ version = searchPackageVersion(key);
786
+ if (!version) console.error(e1);
787
+ }
788
+ }
789
+ } catch (e) {
790
+ console.error("Unexpected error resolving version for " + key + ":", e);
791
+ }
792
+ if (typeof shareItem === 'string') {
793
+ return {
794
+ name: shareItem,
795
+ version: version,
796
+ scope: 'default',
797
+ from: '',
798
+ shareConfig: {
799
+ "import": undefined,
800
+ singleton: false,
801
+ requiredVersion: version ? "^" + version : '*'
802
+ }
803
+ };
804
+ }
805
+ return {
806
+ name: key,
807
+ from: '',
808
+ version: shareItem.version || version,
809
+ scope: shareItem.shareScope || 'default',
810
+ shareConfig: {
811
+ "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
812
+ singleton: shareItem.singleton || false,
813
+ requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
814
+ strictVersion: !!shareItem.strictVersion
815
+ }
816
+ };
817
+ }
818
+ function normalizeShared(shared) {
819
+ if (!shared) return {};
820
+ var result = {};
821
+ if (Array.isArray(shared)) {
822
+ shared.forEach(function (key) {
823
+ result[key] = normalizeShareItem(key, key);
824
+ });
825
+ return result;
826
+ }
827
+ if (typeof shared === 'object') {
828
+ Object.keys(shared).forEach(function (key) {
829
+ result[key] = normalizeShareItem(key, shared[key]);
830
+ });
831
+ }
832
+ return result;
833
+ }
834
+ function normalizeLibrary(library) {
835
+ if (!library) return undefined;
836
+ return library;
837
+ }
838
+ function normalizeManifest(manifest) {
839
+ if (manifest === void 0) {
840
+ manifest = false;
841
+ }
842
+ if (typeof manifest === 'boolean') {
843
+ return manifest;
844
+ }
845
+ return Object.assign({
846
+ filePath: '',
847
+ disableAssetsAnalyze: false,
848
+ fileName: 'mf-manifest.json'
849
+ }, manifest);
850
+ }
851
+ var config;
852
+ function getNormalizeModuleFederationOptions() {
853
+ return config;
854
+ }
855
+ function getNormalizeShareItem(key) {
856
+ var options = getNormalizeModuleFederationOptions();
857
+ var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
858
+ return shareItem;
859
+ }
860
+ function normalizeModuleFederationOptions(options) {
861
+ if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
862
+ throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
863
+ }
864
+ return config = {
865
+ exposes: normalizeExposes(options.exposes),
866
+ filename: options.filename || 'remoteEntry-[hash]',
867
+ library: normalizeLibrary(options.library),
501
868
  name: options.name,
502
869
  // remoteType: options.remoteType,
503
870
  remotes: normalizeRemotes(options.remotes),
@@ -515,7 +882,9 @@ function normalizeModuleFederationOptions(options) {
515
882
  ignoreOrigin: options.ignoreOrigin || false,
516
883
  virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
517
884
  hostInitInjectLocation: options.hostInitInjectLocation || 'html',
518
- bundleAllCSS: options.bundleAllCSS || false
885
+ bundleAllCSS: options.bundleAllCSS || false,
886
+ moduleParseTimeout: options.moduleParseTimeout || 10,
887
+ varFilename: options.varFilename
519
888
  };
520
889
  }
521
890
 
@@ -888,969 +1257,662 @@ function generateLocalSharedImportMap() {
888
1257
  }).filter(function (x) {
889
1258
  return x !== null;
890
1259
  }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
891
- }
892
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
893
- function generateRemoteEntry(options) {
894
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
895
- if (typeof p === 'string') {
896
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
897
- } else {
898
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
899
- }
900
- });
901
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
902
- return item[1];
903
- }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
904
- return item[0] + "(" + item[2] + ")";
905
- }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
906
- }
907
- /**
908
- * Inject entry file, automatically init when used as host,
909
- * and will not inject remoteEntry
910
- */
911
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
912
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
913
- function writeHostAutoInit() {
914
- hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
915
- }
916
- function getHostAutoInitImportId() {
917
- return hostAutoInitModule.getImportId();
918
- }
919
- function getHostAutoInitPath() {
920
- return hostAutoInitModule.getPath();
921
- }
922
-
923
- function initVirtualModules() {
924
- writeLocalSharedImportMap();
925
- writeHostAutoInit();
926
- writeRuntimeInitStatus();
927
- }
928
-
929
- var ASSET_TYPES = ['js', 'css'];
930
- var LOAD_TIMINGS = ['sync', 'async'];
931
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
932
- /**
933
- * Creates an empty asset map structure for tracking JS and CSS assets
934
- * @returns Initialized asset map with sync/async arrays for JS and CSS
935
- */
936
- var createEmptyAssetMap = function createEmptyAssetMap() {
937
- return {
938
- js: {
939
- sync: [],
940
- async: []
941
- },
942
- css: {
943
- sync: [],
944
- async: []
945
- }
946
- };
947
- };
948
- /**
949
- * Tracks an asset in the preload map with deduplication
950
- * @param map - The preload map to update
951
- * @param key - The module key to track under
952
- * @param fileName - The asset filename to track
953
- * @param isAsync - Whether the asset is loaded async
954
- * @param type - The asset type ('js' or 'css')
955
- */
956
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
957
- if (!map[key]) {
958
- map[key] = createEmptyAssetMap();
959
- }
960
- var target = isAsync ? map[key][type].async : map[key][type].sync;
961
- if (!target.includes(fileName)) {
962
- target.push(fileName);
963
- }
964
- };
965
- /**
966
- * Checks if a file is a CSS file by extension
967
- * @param fileName - The filename to check
968
- * @returns True if file has a CSS extension (.css, .scss, .less)
969
- */
970
- var isCSSFile = function isCSSFile(fileName) {
971
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
972
- };
973
- /**
974
- * Collects all CSS assets from the bundle
975
- * @param bundle - The Rollup output bundle
976
- * @returns Set of CSS asset filenames
977
- */
978
- var collectCssAssets = function collectCssAssets(bundle) {
979
- var cssAssets = new Set();
980
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
981
- var _Object$entries$_i = _Object$entries[_i],
982
- fileName = _Object$entries$_i[0],
983
- fileData = _Object$entries$_i[1];
984
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
985
- cssAssets.add(fileName);
986
- }
987
- }
988
- return cssAssets;
989
- };
990
- /**
991
- * Processes module assets and tracks them in the files map
992
- * @param bundle - The Rollup output bundle
993
- * @param filesMap - The preload map to populate
994
- * @param moduleMatcher - Function that matches module paths to keys
995
- */
996
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
997
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
998
- var _Object$entries2$_i = _Object$entries2[_i2],
999
- fileName = _Object$entries2$_i[0],
1000
- fileData = _Object$entries2$_i[1];
1001
- if (fileData.type !== 'chunk') continue;
1002
- if (!fileData.modules) continue;
1003
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1004
- var modulePath = _Object$keys[_i3];
1005
- var matchKey = moduleMatcher(modulePath);
1006
- if (!matchKey) continue;
1007
- // Track main JS chunk
1008
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1009
- // Handle dynamic imports
1010
- if (fileData.dynamicImports) {
1011
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1012
- var dynamicImport = _step.value;
1013
- var importData = bundle[dynamicImport];
1014
- if (!importData) continue;
1015
- var isCss = isCSSFile(dynamicImport);
1016
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1017
- }
1018
- }
1019
- }
1020
- }
1021
- };
1022
- /**
1023
- * Deduplicates assets in the files map
1024
- * @param filesMap - The preload map to deduplicate
1025
- * @returns New deduplicated preload map
1026
- */
1027
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1028
- var result = {};
1029
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1030
- var _Object$entries3$_i = _Object$entries3[_i4],
1031
- key = _Object$entries3$_i[0],
1032
- assetMaps = _Object$entries3$_i[1];
1033
- result[key] = createEmptyAssetMap();
1034
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1035
- var type = _ASSET_TYPES[_i5];
1036
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1037
- var timing = _LOAD_TIMINGS[_i6];
1038
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1039
- }
1040
- }
1041
- }
1042
- return result;
1043
- };
1044
- /**
1045
- * Builds a mapping between module files and their share keys
1046
- * @param shareKeys - Set of share keys to map
1047
- * @param resolveFn - Function to resolve module paths
1048
- * @returns Map of file paths to their corresponding share keys
1049
- */
1050
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1051
- try {
1052
- var fileToShareKey = new Map();
1053
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1054
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1055
- var _resolution$id;
1056
- return {
1057
- shareKey: shareKey,
1058
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1059
- };
1060
- })["catch"](function () {
1061
- return null;
1062
- });
1063
- }))).then(function (resolutions) {
1064
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1065
- var resolution = _step2.value;
1066
- if (resolution != null && resolution.file) {
1067
- fileToShareKey.set(resolution.file, resolution.shareKey);
1068
- }
1069
- }
1070
- return fileToShareKey;
1071
- });
1072
- } catch (e) {
1073
- return Promise.reject(e);
1074
- }
1075
- };
1076
-
1077
- /**
1078
- * Resolves the public path for remote entries
1079
- * @param options - Module Federation options
1080
- * @param viteBase - Vite's base config value
1081
- * @param originalBase - Original base config before any transformations
1082
- * @returns The resolved public path
1083
- */
1084
- function resolvePublicPath(options, viteBase, originalBase) {
1085
- // Use explicitly set publicPath if provided
1086
- if (options.publicPath) {
1087
- return options.publicPath;
1088
- }
1089
- // Handle empty original base case
1090
- if (originalBase === '') {
1091
- return 'auto';
1092
- }
1093
- // Use viteBase if available, ensuring it ends with a slash
1094
- if (viteBase) {
1095
- return viteBase.replace(/\/?$/, '/');
1096
- }
1097
- // Fallback to auto if no base is specified
1098
- return 'auto';
1099
- }
1100
-
1101
- var Manifest = function Manifest() {
1102
- var mfOptions = getNormalizeModuleFederationOptions();
1103
- var name = mfOptions.name,
1104
- filename = mfOptions.filename,
1105
- getPublicPath = mfOptions.getPublicPath,
1106
- manifestOptions = mfOptions.manifest;
1107
- var mfManifestName = '';
1108
- if (manifestOptions === true) {
1109
- mfManifestName = 'mf-manifest.json';
1110
- }
1111
- if (typeof manifestOptions !== 'boolean') {
1112
- mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1113
- }
1114
- var root;
1115
- var remoteEntryFile;
1116
- var publicPath;
1117
- var _command;
1118
- var _originalConfigBase;
1119
- var viteConfig;
1120
- /**
1121
- * Adds global CSS assets to all module exports
1122
- * @param filesMap - The preload map to update
1123
- * @param cssAssets - Set of CSS asset filenames to add
1124
- */
1125
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1126
- Object.keys(filesMap).forEach(function (key) {
1127
- cssAssets.forEach(function (cssAsset) {
1128
- trackAsset(filesMap, key, cssAsset, false, 'css');
1129
- });
1130
- });
1131
- };
1132
- return [{
1133
- name: 'module-federation-manifest',
1134
- apply: 'serve',
1135
- /**
1136
- * Stores resolved Vite config for later use
1137
- */
1138
- /**
1139
- * Finalizes configuration after all plugins are resolved
1140
- * @param config - Fully resolved Vite config
1141
- */
1142
- configResolved: function configResolved(config) {
1143
- viteConfig = config;
1144
- },
1145
- /**
1146
- * Configures dev server middleware to handle manifest requests
1147
- * @param server - Vite dev server instance
1148
- */
1149
- configureServer: function configureServer(server) {
1150
- server.middlewares.use(function (req, res, next) {
1151
- var _req$url;
1152
- if (!mfManifestName) {
1153
- next();
1154
- return;
1155
- }
1156
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1157
- res.setHeader('Content-Type', 'application/json');
1158
- res.setHeader('Access-Control-Allow-Origin', '*');
1159
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1160
- id: name,
1161
- name: name,
1162
- metaData: {
1163
- name: name,
1164
- type: 'app',
1165
- buildInfo: {
1166
- buildVersion: '1.0.0',
1167
- buildName: name
1168
- },
1169
- remoteEntry: {
1170
- name: filename,
1171
- path: '',
1172
- type: 'module'
1173
- },
1174
- ssrRemoteEntry: {
1175
- name: filename,
1176
- path: '',
1177
- type: 'module'
1178
- },
1179
- types: {
1180
- path: '',
1181
- name: ''
1182
- },
1183
- globalName: name,
1184
- pluginVersion: '0.2.5',
1185
- publicPath: publicPath
1186
- }
1187
- })));
1188
- } else {
1189
- next();
1190
- }
1191
- });
1192
- }
1193
- }, {
1194
- name: 'module-federation-manifest',
1195
- enforce: 'post',
1196
- /**
1197
- * Initial plugin configuration
1198
- * @param config - Vite config object
1199
- * @param command - Current Vite command (serve/build)
1200
- */
1201
- config: function config(_config, _ref) {
1202
- var command = _ref.command;
1203
- if (!_config.build) _config.build = {};
1204
- if (!_config.build.manifest) {
1205
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1206
- }
1207
- _command = command;
1208
- _originalConfigBase = _config.base;
1209
- },
1210
- configResolved: function configResolved(config) {
1211
- root = config.root;
1212
- var base = config.base;
1213
- if (_command === 'serve') {
1214
- base = (config.server.origin || '') + config.base;
1215
- }
1216
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1217
- },
1218
- /**
1219
- * Generates the module federation manifest file
1220
- * @param options - Rollup output options
1221
- * @param bundle - Generated bundle assets
1222
- */
1223
- generateBundle: function generateBundle(options, bundle) {
1224
- try {
1225
- var _this = this;
1226
- if (!mfManifestName) return Promise.resolve();
1227
- var filesMap = {};
1228
- // First pass: Find remoteEntry file
1229
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1230
- var _Object$entries$_i = _Object$entries[_i],
1231
- _ = _Object$entries$_i[0],
1232
- fileData = _Object$entries$_i[1];
1233
- if (mfOptions.filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1234
- remoteEntryFile = fileData.fileName;
1235
- break; // We can break early since we only need to find remoteEntry once
1236
- }
1237
- }
1238
- // Second pass: Collect all CSS assets
1239
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1240
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1241
- return mfOptions.exposes[item]["import"];
1242
- });
1243
- // Process exposed modules
1244
- processModuleAssets(bundle, filesMap, function (modulePath) {
1245
- var absoluteModulePath = path.resolve(root, modulePath);
1246
- return exposesModules.find(function (exposeModule) {
1247
- var exposePath = path.resolve(root, exposeModule);
1248
- // First try exact path match
1249
- if (absoluteModulePath === exposePath) {
1250
- return true;
1251
- }
1252
- // Then try path match without known extensions
1253
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1254
- var ext = path.extname(filePath);
1255
- return JS_EXTENSIONS.includes(ext) ? path.join(path.dirname(filePath), path.basename(filePath, ext)) : filePath;
1256
- };
1257
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1258
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1259
- return modulePathNoExt === exposePathNoExt;
1260
- });
1261
- });
1262
- // Process shared modules
1263
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1264
- processModuleAssets(bundle, filesMap, function (modulePath) {
1265
- return fileToShareKey.get(modulePath);
1266
- });
1267
- // Add all CSS assets to every export if bundleAllCSS is enabled
1268
- if (mfOptions.bundleAllCSS) {
1269
- addCssAssetsToAllExports(filesMap, allCssAssets);
1270
- }
1271
- // Final deduplication of all assets
1272
- filesMap = deduplicateAssets(filesMap);
1273
- _this.emitFile({
1274
- type: 'asset',
1275
- fileName: mfManifestName,
1276
- source: JSON.stringify(generateMFManifest(filesMap))
1277
- });
1278
- });
1279
- } catch (e) {
1280
- return Promise.reject(e);
1281
- }
1282
- }
1283
- }];
1284
- /**
1285
- * Generates the final manifest JSON structure
1286
- * @param preloadMap - Map of module assets to include
1287
- * @returns Complete manifest object
1288
- */
1289
- function generateMFManifest(preloadMap) {
1290
- var options = getNormalizeModuleFederationOptions();
1291
- var name = options.name;
1292
- var remoteEntry = {
1293
- name: remoteEntryFile,
1294
- path: '',
1295
- type: 'module'
1296
- };
1297
- // Process remotes
1298
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1299
- var remoteKey = _ref2[0],
1300
- modules = _ref2[1];
1301
- return Array.from(modules).map(function (moduleKey) {
1302
- return {
1303
- federationContainerName: options.remotes[remoteKey].entry,
1304
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1305
- alias: remoteKey,
1306
- entry: '*'
1307
- };
1308
- });
1309
- });
1310
- // Process shared dependencies
1311
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1312
- var shareItem = getNormalizeShareItem(shareKey);
1313
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1314
- return {
1315
- id: name + ":" + shareKey,
1316
- name: shareKey,
1317
- version: shareItem.version,
1318
- requiredVersion: shareItem.shareConfig.requiredVersion,
1319
- assets: {
1320
- js: {
1321
- async: assets.js.async,
1322
- sync: assets.js.sync
1323
- },
1324
- css: {
1325
- async: assets.css.async,
1326
- sync: assets.css.sync
1327
- }
1328
- }
1329
- };
1330
- }).filter(Boolean);
1331
- // Process exposed modules
1332
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1333
- var key = _ref3[0],
1334
- value = _ref3[1];
1335
- var formatKey = key.replace('./', '');
1336
- var sourceFile = value["import"];
1337
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1338
- return {
1339
- id: name + ":" + formatKey,
1340
- name: formatKey,
1341
- assets: {
1342
- js: {
1343
- async: assets.js.async,
1344
- sync: assets.js.sync
1345
- },
1346
- css: {
1347
- async: assets.css.async,
1348
- sync: assets.css.sync
1349
- }
1350
- },
1351
- path: key
1352
- };
1353
- }).filter(Boolean);
1354
- return {
1355
- id: name,
1356
- name: name,
1357
- metaData: _extends({
1358
- name: name,
1359
- type: 'app',
1360
- buildInfo: {
1361
- buildVersion: '1.0.0',
1362
- buildName: name
1363
- },
1364
- remoteEntry: remoteEntry,
1365
- ssrRemoteEntry: remoteEntry,
1366
- types: {
1367
- path: '',
1368
- name: ''
1369
- },
1370
- globalName: name,
1371
- pluginVersion: '0.2.5'
1372
- }, !!getPublicPath ? {
1373
- getPublicPath: getPublicPath
1374
- } : {
1375
- publicPath: publicPath
1376
- }),
1377
- shared: shared,
1378
- remotes: remotes,
1379
- exposes: exposes
1380
- };
1381
- }
1382
- };
1383
-
1384
- var _resolve,
1385
- promise = new Promise(function (resolve, reject) {
1386
- _resolve = resolve;
1387
- });
1388
- var parsePromise = promise;
1389
- var exposesParseEnd = false;
1390
- var parseStartSet = new Set();
1391
- var parseEndSet = new Set();
1392
- function pluginModuleParseEnd (excludeFn) {
1393
- return [{
1394
- name: '_',
1395
- apply: 'serve',
1396
- config: function config() {
1397
- // No waiting in development mode
1398
- _resolve(1);
1399
- }
1400
- }, {
1401
- enforce: 'pre',
1402
- name: 'parseStart',
1403
- apply: 'build',
1404
- load: function load(id) {
1405
- if (excludeFn(id)) {
1406
- return;
1407
- }
1408
- parseStartSet.add(id);
1409
- }
1410
- }, {
1411
- enforce: 'post',
1412
- name: 'parseEnd',
1413
- apply: 'build',
1414
- moduleParsed: function moduleParsed(module) {
1415
- var id = module.id;
1416
- if (id === VIRTUAL_EXPOSES) {
1417
- // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1418
- exposesParseEnd = true;
1419
- }
1420
- if (excludeFn(id)) {
1421
- return;
1422
- }
1423
- parseEndSet.add(id);
1424
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1425
- _resolve(1);
1426
- }
1260
+ }
1261
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1262
+ function generateRemoteEntry(options) {
1263
+ var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1264
+ if (typeof p === 'string') {
1265
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1266
+ } else {
1267
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1427
1268
  }
1428
- }];
1269
+ });
1270
+ return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1271
+ return item[1];
1272
+ }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
1273
+ return item[0] + "(" + item[2] + ")";
1274
+ }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
1275
+ }
1276
+ /**
1277
+ * Inject entry file, automatically init when used as host,
1278
+ * and will not inject remoteEntry
1279
+ */
1280
+ var HOST_AUTO_INIT_TAG = '__H_A_I__';
1281
+ var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1282
+ function writeHostAutoInit() {
1283
+ hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1284
+ }
1285
+ function getHostAutoInitImportId() {
1286
+ return hostAutoInitModule.getImportId();
1287
+ }
1288
+ function getHostAutoInitPath() {
1289
+ return hostAutoInitModule.getPath();
1429
1290
  }
1430
1291
 
1431
- var filter = createFilter();
1432
- function pluginProxyRemoteEntry () {
1433
- var viteConfig, _command;
1434
- return {
1435
- name: 'proxyRemoteEntry',
1436
- enforce: 'post',
1437
- configResolved: function configResolved(config) {
1438
- viteConfig = config;
1439
- },
1440
- config: function config(_config, _ref) {
1441
- var command = _ref.command;
1442
- _command = command;
1443
- },
1444
- resolveId: function resolveId(id) {
1445
- if (id === REMOTE_ENTRY_ID) {
1446
- return REMOTE_ENTRY_ID;
1447
- }
1448
- if (id === VIRTUAL_EXPOSES) {
1449
- return VIRTUAL_EXPOSES;
1450
- }
1451
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1452
- return id;
1453
- }
1454
- },
1455
- load: function load(id) {
1456
- if (id === REMOTE_ENTRY_ID) {
1457
- return parsePromise.then(function (_) {
1458
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1459
- });
1460
- }
1461
- if (id === VIRTUAL_EXPOSES) {
1462
- return generateExposes();
1463
- }
1464
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1465
- return id;
1466
- }
1467
- },
1468
- transform: function transform(code, id) {
1469
- var transformedCode = function () {
1470
- if (!filter(id)) return;
1471
- if (id.includes(REMOTE_ENTRY_ID)) {
1472
- return parsePromise.then(function (_) {
1473
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1474
- });
1475
- }
1476
- if (id === VIRTUAL_EXPOSES) {
1477
- return generateExposes();
1478
- }
1479
- if (id.includes(getHostAutoInitPath())) {
1480
- var options = getNormalizeModuleFederationOptions();
1481
- if (_command === 'serve') {
1482
- var _viteConfig$server, _viteConfig$server2;
1483
- var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1484
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1485
- return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1486
- }
1487
- return code;
1488
- }
1489
- }();
1490
- return mapCodeToCodeWithSourcemap(transformedCode);
1292
+ function initVirtualModules() {
1293
+ writeLocalSharedImportMap();
1294
+ writeHostAutoInit();
1295
+ writeRuntimeInitStatus();
1296
+ }
1297
+
1298
+ function findRemoteEntryFile(filename, bundle) {
1299
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1300
+ var _Object$entries$_i = _Object$entries[_i],
1301
+ fileData = _Object$entries$_i[1];
1302
+ if (filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1303
+ return fileData.fileName; // We can return early since we only need to find remoteEntry once
1491
1304
  }
1492
- };
1305
+ }
1493
1306
  }
1494
1307
 
1495
- createFilter();
1496
- function pluginProxyRemotes (options) {
1497
- var remotes = options.remotes;
1308
+ var ASSET_TYPES = ['js', 'css'];
1309
+ var LOAD_TIMINGS = ['sync', 'async'];
1310
+ var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1311
+ /**
1312
+ * Creates an empty asset map structure for tracking JS and CSS assets
1313
+ * @returns Initialized asset map with sync/async arrays for JS and CSS
1314
+ */
1315
+ var createEmptyAssetMap = function createEmptyAssetMap() {
1498
1316
  return {
1499
- name: 'proxyRemotes',
1500
- config: function config(_config, _ref) {
1501
- var _command = _ref.command;
1502
- Object.keys(remotes).forEach(function (key) {
1503
- var remote = remotes[key];
1504
- _config.resolve.alias.push({
1505
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1506
- replacement: '$1',
1507
- customResolver: function customResolver(source) {
1508
- var remoteModule = getRemoteVirtualModule(source, _command);
1509
- addUsedRemote(remote.name, source);
1510
- return remoteModule.getPath();
1511
- }
1512
- });
1513
- });
1317
+ js: {
1318
+ sync: [],
1319
+ async: []
1320
+ },
1321
+ css: {
1322
+ sync: [],
1323
+ async: []
1514
1324
  }
1515
1325
  };
1516
- }
1517
-
1518
- function _catch(body, recover) {
1519
- try {
1520
- var result = body();
1521
- } catch (e) {
1522
- return recover(e);
1326
+ };
1327
+ /**
1328
+ * Tracks an asset in the preload map with deduplication
1329
+ * @param map - The preload map to update
1330
+ * @param key - The module key to track under
1331
+ * @param fileName - The asset filename to track
1332
+ * @param isAsync - Whether the asset is loaded async
1333
+ * @param type - The asset type ('js' or 'css')
1334
+ */
1335
+ var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1336
+ if (!map[key]) {
1337
+ map[key] = createEmptyAssetMap();
1523
1338
  }
1524
- if (result && result.then) {
1525
- return result.then(void 0, recover);
1339
+ var target = isAsync ? map[key][type].async : map[key][type].sync;
1340
+ if (!target.includes(fileName)) {
1341
+ target.push(fileName);
1526
1342
  }
1527
- return result;
1528
- }
1529
- var DEFAULT_DEV_OPTIONS = {
1530
- disableLiveReload: true,
1531
- disableHotTypesReload: false,
1532
- disableDynamicRemoteTypeHints: false
1533
1343
  };
1534
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
1535
- var getIPv4 = function getIPv4() {
1536
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
1344
+ /**
1345
+ * Checks if a file is a CSS file by extension
1346
+ * @param fileName - The filename to check
1347
+ * @returns True if file has a CSS extension (.css, .scss, .less)
1348
+ */
1349
+ var isCSSFile = function isCSSFile(fileName) {
1350
+ return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1537
1351
  };
1538
- var forkDevWorkerPath = function () {
1539
- // eslint-disable-next-line @typescript-eslint/no-var-requires
1540
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
1541
- }();
1542
- var DevWorker = /*#__PURE__*/function () {
1543
- function DevWorker(options) {
1544
- this.worker = rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
1545
- this.worker.connect(options);
1546
- }
1547
- var _proto = DevWorker.prototype;
1548
- _proto.update = function update() {
1549
- var _this$worker$process;
1550
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
1551
- type: rpc.RpcGMCallTypes.CALL,
1552
- id: this.worker.id,
1553
- args: [undefined, 'update']
1554
- });
1555
- };
1556
- _proto.exit = function exit() {
1557
- this.worker.terminate();
1558
- };
1559
- return DevWorker;
1560
- }();
1561
- var normalizeDevOptions = function normalizeDevOptions(dev) {
1562
- if (dev === false) {
1563
- return false;
1564
- }
1565
- if (dev === true || typeof dev === 'undefined') {
1566
- return _extends({}, DEFAULT_DEV_OPTIONS);
1352
+ /**
1353
+ * Collects all CSS assets from the bundle
1354
+ * @param bundle - The Rollup output bundle
1355
+ * @returns Set of CSS asset filenames
1356
+ */
1357
+ var collectCssAssets = function collectCssAssets(bundle) {
1358
+ var cssAssets = new Set();
1359
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1360
+ var _Object$entries$_i = _Object$entries[_i],
1361
+ fileName = _Object$entries$_i[0],
1362
+ fileData = _Object$entries$_i[1];
1363
+ if (fileData.type === 'asset' && isCSSFile(fileName)) {
1364
+ cssAssets.add(fileName);
1365
+ }
1567
1366
  }
1568
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
1367
+ return cssAssets;
1569
1368
  };
1570
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
1571
- var exposes = {};
1572
- Object.entries(options.exposes).forEach(function (_ref) {
1573
- var key = _ref[0],
1574
- value = _ref[1];
1575
- if (typeof value === 'string') {
1576
- exposes[key] = value;
1577
- return;
1578
- }
1579
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
1580
- if (importValue) {
1581
- exposes[key] = importValue;
1582
- }
1583
- });
1584
- var remotes = {};
1585
- Object.entries(options.remotes).forEach(function (_ref2) {
1586
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
1587
- var key = _ref2[0],
1588
- remote = _ref2[1];
1589
- if (typeof remote === 'string') {
1590
- remotes[key] = remote;
1591
- return;
1592
- }
1593
- if (!remote.entry) {
1594
- return;
1369
+ /**
1370
+ * Processes module assets and tracks them in the files map
1371
+ * @param bundle - The Rollup output bundle
1372
+ * @param filesMap - The preload map to populate
1373
+ * @param moduleMatcher - Function that matches module paths to keys
1374
+ */
1375
+ var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1376
+ for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1377
+ var _Object$entries2$_i = _Object$entries2[_i2],
1378
+ fileName = _Object$entries2$_i[0],
1379
+ fileData = _Object$entries2$_i[1];
1380
+ if (fileData.type !== 'chunk') continue;
1381
+ if (!fileData.modules) continue;
1382
+ for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1383
+ var modulePath = _Object$keys[_i3];
1384
+ var matchKey = moduleMatcher(modulePath);
1385
+ if (!matchKey) continue;
1386
+ // Track main JS chunk
1387
+ trackAsset(filesMap, matchKey, fileName, false, 'js');
1388
+ // Handle dynamic imports
1389
+ if (fileData.dynamicImports) {
1390
+ for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1391
+ var dynamicImport = _step.value;
1392
+ var importData = bundle[dynamicImport];
1393
+ if (!importData) continue;
1394
+ var isCss = isCSSFile(dynamicImport);
1395
+ trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1396
+ }
1397
+ }
1595
1398
  }
1596
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
1597
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
1598
- remotes[key] = entryGlobalName + "@" + remote.entry;
1599
- });
1600
- return _extends({}, options, {
1601
- exposes: exposes,
1602
- remotes: remotes
1603
- });
1604
- };
1605
- var resolveOutputDir = function resolveOutputDir(config) {
1606
- var outDir = config.build.outDir;
1607
- if (path.isAbsolute(outDir)) {
1608
- return path.relative(config.root, outDir);
1609
1399
  }
1610
- return outDir;
1611
1400
  };
1612
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
1613
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
1614
- if (typeof plugin === 'string') {
1615
- return plugin === pluginId;
1401
+ /**
1402
+ * Deduplicates assets in the files map
1403
+ * @param filesMap - The preload map to deduplicate
1404
+ * @returns New deduplicated preload map
1405
+ */
1406
+ var deduplicateAssets = function deduplicateAssets(filesMap) {
1407
+ var result = {};
1408
+ for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1409
+ var _Object$entries3$_i = _Object$entries3[_i4],
1410
+ key = _Object$entries3$_i[0],
1411
+ assetMaps = _Object$entries3$_i[1];
1412
+ result[key] = createEmptyAssetMap();
1413
+ for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1414
+ var type = _ASSET_TYPES[_i5];
1415
+ for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1416
+ var timing = _LOAD_TIMINGS[_i6];
1417
+ result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1418
+ }
1616
1419
  }
1617
- return plugin[0] === pluginId;
1618
- });
1619
- if (!hasPlugin) {
1620
- options.runtimePlugins.push(pluginId);
1621
1420
  }
1421
+ return result;
1622
1422
  };
1623
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
1624
- var defaultGenerateTypes = {
1625
- compileInChildProcess: true
1626
- };
1627
- var defaultConsumeTypes = {
1628
- consumeAPITypes: true
1629
- };
1630
- return normalizeOptions(isTSProject(dts, context), {
1631
- generateTypes: defaultGenerateTypes,
1632
- consumeTypes: defaultConsumeTypes,
1633
- extraOptions: {},
1634
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
1635
- }, 'mfOptions.dts')(dts);
1423
+ /**
1424
+ * Builds a mapping between module files and their share keys
1425
+ * @param shareKeys - Set of share keys to map
1426
+ * @param resolveFn - Function to resolve module paths
1427
+ * @returns Map of file paths to their corresponding share keys
1428
+ */
1429
+ var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1430
+ try {
1431
+ var fileToShareKey = new Map();
1432
+ return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1433
+ return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1434
+ var _resolution$id;
1435
+ return {
1436
+ shareKey: shareKey,
1437
+ file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1438
+ };
1439
+ })["catch"](function () {
1440
+ return null;
1441
+ });
1442
+ }))).then(function (resolutions) {
1443
+ for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1444
+ var resolution = _step2.value;
1445
+ if (resolution != null && resolution.file) {
1446
+ fileToShareKey.set(resolution.file, resolution.shareKey);
1447
+ }
1448
+ }
1449
+ return fileToShareKey;
1450
+ });
1451
+ } catch (e) {
1452
+ return Promise.reject(e);
1453
+ }
1636
1454
  };
1637
- var logDtsError = function logDtsError(error, dtsOptions) {
1638
- if (dtsOptions === false) {
1639
- return;
1455
+
1456
+ /**
1457
+ * Resolves the public path for remote entries
1458
+ * @param options - Module Federation options
1459
+ * @param viteBase - Vite's base config value
1460
+ * @param originalBase - Original base config before any transformations
1461
+ * @returns The resolved public path
1462
+ */
1463
+ function resolvePublicPath(options, viteBase, originalBase) {
1464
+ // Use explicitly set publicPath if provided
1465
+ if (options.publicPath) {
1466
+ return options.publicPath;
1640
1467
  }
1641
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
1642
- return;
1468
+ // Handle empty original base case
1469
+ if (originalBase === '') {
1470
+ return 'auto';
1643
1471
  }
1644
- console.error(error);
1645
- };
1646
- function pluginDts(options) {
1647
- if (options.dts === false) {
1648
- return [];
1472
+ // Use viteBase if available, ensuring it ends with a slash
1473
+ if (viteBase) {
1474
+ return viteBase.replace(/\/?$/, '/');
1649
1475
  }
1650
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
1651
- var resolvedConfig;
1652
- var devWorker;
1653
- var normalizedDevOptions;
1654
- var hasGeneratedBundle = false;
1655
- var devPlugin = {
1656
- name: 'module-federation-dts-dev',
1476
+ // Fallback to auto if no base is specified
1477
+ return 'auto';
1478
+ }
1479
+
1480
+ var Manifest = function Manifest() {
1481
+ var mfOptions = getNormalizeModuleFederationOptions();
1482
+ var name = mfOptions.name,
1483
+ filename = mfOptions.filename,
1484
+ getPublicPath = mfOptions.getPublicPath,
1485
+ manifestOptions = mfOptions.manifest,
1486
+ varFilename = mfOptions.varFilename;
1487
+ var mfManifestName = '';
1488
+ if (manifestOptions === true) {
1489
+ mfManifestName = 'mf-manifest.json';
1490
+ }
1491
+ if (typeof manifestOptions !== 'boolean') {
1492
+ mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1493
+ }
1494
+ var root;
1495
+ var remoteEntryFile;
1496
+ var publicPath;
1497
+ var _command;
1498
+ var _originalConfigBase;
1499
+ var viteConfig;
1500
+ /**
1501
+ * Adds global CSS assets to all module exports
1502
+ * @param filesMap - The preload map to update
1503
+ * @param cssAssets - Set of CSS asset filenames to add
1504
+ */
1505
+ var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1506
+ Object.keys(filesMap).forEach(function (key) {
1507
+ cssAssets.forEach(function (cssAsset) {
1508
+ trackAsset(filesMap, key, cssAsset, false, 'css');
1509
+ });
1510
+ });
1511
+ };
1512
+ return [{
1513
+ name: 'module-federation-manifest',
1657
1514
  apply: 'serve',
1658
- config: function config(_config) {
1659
- normalizedDevOptions = normalizeDevOptions(options.dev);
1660
- if (!normalizedDevOptions) {
1661
- return;
1662
- }
1663
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
1664
- return;
1665
- }
1666
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
1667
- var define = _config.define ? _extends({}, _config.define) : {};
1668
- if (!('FEDERATION_IPV4' in define)) {
1669
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
1515
+ /**
1516
+ * Stores resolved Vite config for later use
1517
+ */
1518
+ /**
1519
+ * Finalizes configuration after all plugins are resolved
1520
+ * @param config - Fully resolved Vite config
1521
+ */
1522
+ configResolved: function configResolved(config) {
1523
+ viteConfig = config;
1524
+ },
1525
+ /**
1526
+ * Configures dev server middleware to handle manifest requests
1527
+ * @param server - Vite dev server instance
1528
+ */
1529
+ configureServer: function configureServer(server) {
1530
+ server.middlewares.use(function (req, res, next) {
1531
+ var _req$url;
1532
+ if (!mfManifestName) {
1533
+ next();
1534
+ return;
1535
+ }
1536
+ if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1537
+ res.setHeader('Content-Type', 'application/json');
1538
+ res.setHeader('Access-Control-Allow-Origin', '*');
1539
+ res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1540
+ id: name,
1541
+ name: name,
1542
+ metaData: {
1543
+ name: name,
1544
+ type: 'app',
1545
+ buildInfo: {
1546
+ buildVersion: '1.0.0',
1547
+ buildName: name
1548
+ },
1549
+ remoteEntry: {
1550
+ name: filename,
1551
+ path: '',
1552
+ type: 'module'
1553
+ },
1554
+ ssrRemoteEntry: {
1555
+ name: filename,
1556
+ path: '',
1557
+ type: 'module'
1558
+ },
1559
+ varRemoteEntry: varFilename ? {
1560
+ name: varFilename,
1561
+ path: '',
1562
+ type: 'var'
1563
+ } : undefined,
1564
+ types: {
1565
+ path: '',
1566
+ name: ''
1567
+ },
1568
+ globalName: name,
1569
+ pluginVersion: '0.2.5',
1570
+ publicPath: publicPath
1571
+ }
1572
+ })));
1573
+ } else {
1574
+ next();
1575
+ }
1576
+ });
1577
+ }
1578
+ }, {
1579
+ name: 'module-federation-manifest',
1580
+ enforce: 'post',
1581
+ /**
1582
+ * Initial plugin configuration
1583
+ * @param config - Vite config object
1584
+ * @param command - Current Vite command (serve/build)
1585
+ */
1586
+ config: function config(_config, _ref) {
1587
+ var command = _ref.command;
1588
+ if (!_config.build) _config.build = {};
1589
+ if (!_config.build.manifest) {
1590
+ _config.build.manifest = _config.build.manifest || !!manifestOptions;
1670
1591
  }
1671
- _config.define = define;
1592
+ _command = command;
1593
+ _originalConfigBase = _config.base;
1672
1594
  },
1673
1595
  configResolved: function configResolved(config) {
1674
- resolvedConfig = config;
1675
- },
1676
- configureServer: function configureServer(server) {
1677
- if (!normalizedDevOptions || !resolvedConfig) {
1678
- return;
1679
- }
1680
- var devOptions = normalizedDevOptions;
1681
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
1682
- return;
1683
- }
1684
- if (!options.name) {
1685
- throw new Error('name is required if you want to enable dev server!');
1596
+ root = config.root;
1597
+ var base = config.base;
1598
+ if (_command === 'serve') {
1599
+ base = (config.server.origin || '') + config.base;
1686
1600
  }
1687
- var outputDir = resolveOutputDir(resolvedConfig);
1688
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
1689
- if (typeof normalizedDtsOptions !== 'object') {
1690
- return;
1601
+ publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1602
+ },
1603
+ /**
1604
+ * Generates the module federation manifest file
1605
+ * @param options - Rollup output options
1606
+ * @param bundle - Generated bundle assets
1607
+ */
1608
+ generateBundle: function generateBundle(options, bundle) {
1609
+ try {
1610
+ var _this = this;
1611
+ if (!mfManifestName) return Promise.resolve();
1612
+ var filesMap = {};
1613
+ var foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1614
+ // First pass: Find remoteEntry file
1615
+ if (foundRemoteEntryFile) {
1616
+ remoteEntryFile = foundRemoteEntryFile;
1617
+ }
1618
+ // Second pass: Collect all CSS assets
1619
+ var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1620
+ var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1621
+ return mfOptions.exposes[item]["import"];
1622
+ });
1623
+ // Process exposed modules
1624
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1625
+ var absoluteModulePath = path.resolve(root, modulePath);
1626
+ return exposesModules.find(function (exposeModule) {
1627
+ var exposePath = path.resolve(root, exposeModule);
1628
+ // First try exact path match
1629
+ if (absoluteModulePath === exposePath) {
1630
+ return true;
1631
+ }
1632
+ // Then try path match without known extensions
1633
+ var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1634
+ var ext = path.extname(filePath);
1635
+ return JS_EXTENSIONS.includes(ext) ? path.join(path.dirname(filePath), path.basename(filePath, ext)) : filePath;
1636
+ };
1637
+ var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1638
+ var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1639
+ return modulePathNoExt === exposePathNoExt;
1640
+ });
1641
+ });
1642
+ // Process shared modules
1643
+ return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1644
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1645
+ return fileToShareKey.get(modulePath);
1646
+ });
1647
+ // Add all CSS assets to every export if bundleAllCSS is enabled
1648
+ if (mfOptions.bundleAllCSS) {
1649
+ addCssAssetsToAllExports(filesMap, allCssAssets);
1650
+ }
1651
+ // Final deduplication of all assets
1652
+ filesMap = deduplicateAssets(filesMap);
1653
+ _this.emitFile({
1654
+ type: 'asset',
1655
+ fileName: mfManifestName,
1656
+ source: JSON.stringify(generateMFManifest(filesMap))
1657
+ });
1658
+ });
1659
+ } catch (e) {
1660
+ return Promise.reject(e);
1691
1661
  }
1692
- var normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
1693
- compileInChildProcess: true
1694
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
1695
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
1696
- implementation: normalizedDtsOptions.implementation,
1697
- context: resolvedConfig.root,
1698
- outputDir: outputDir,
1699
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
1700
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
1701
- }, normalizedGenerateTypes, {
1702
- typesFolder: '.dev-server'
1662
+ }
1663
+ }];
1664
+ /**
1665
+ * Generates the final manifest JSON structure
1666
+ * @param preloadMap - Map of module assets to include
1667
+ * @returns Complete manifest object
1668
+ */
1669
+ function generateMFManifest(preloadMap) {
1670
+ var options = getNormalizeModuleFederationOptions();
1671
+ var name = options.name,
1672
+ varFilename = options.varFilename;
1673
+ var remoteEntry = {
1674
+ name: remoteEntryFile,
1675
+ path: '',
1676
+ type: 'module'
1677
+ };
1678
+ var varRemoteEntry = varFilename ? {
1679
+ name: varFilename,
1680
+ path: '',
1681
+ type: 'module'
1682
+ } : undefined;
1683
+ // Process remotes
1684
+ var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1685
+ var remoteKey = _ref2[0],
1686
+ modules = _ref2[1];
1687
+ return Array.from(modules).map(function (moduleKey) {
1688
+ return {
1689
+ federationContainerName: options.remotes[remoteKey].entry,
1690
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1691
+ alias: remoteKey,
1692
+ entry: '*'
1693
+ };
1703
1694
  });
1704
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
1705
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
1706
- }
1707
- var normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
1708
- consumeAPITypes: true
1709
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
1710
- var host = normalizedConsumeTypes === false ? undefined : _extends({
1711
- implementation: normalizedDtsOptions.implementation,
1712
- context: resolvedConfig.root,
1713
- moduleFederationConfig: dtsModuleFederationConfig,
1714
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
1715
- abortOnError: false
1716
- }, normalizedConsumeTypes);
1717
- var extraOptions = normalizedDtsOptions.extraOptions || {};
1718
- if (!remote && !host && devOptions.disableLiveReload) {
1719
- return;
1720
- }
1721
- var startDevWorker = function startDevWorker() {
1722
- try {
1723
- var _temp2 = function _temp2() {
1724
- var _server$httpServer;
1725
- devWorker = new DevWorker({
1726
- name: options.name,
1727
- remote: remote,
1728
- host: host ? _extends({}, host, {
1729
- remoteTypeUrls: remoteTypeUrls
1730
- }) : undefined,
1731
- extraOptions: extraOptions,
1732
- disableLiveReload: devOptions.disableLiveReload,
1733
- disableHotTypesReload: devOptions.disableHotTypesReload
1734
- });
1735
- var update = function update() {
1736
- var _devWorker;
1737
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
1738
- };
1739
- server.watcher.on('change', update);
1740
- server.watcher.on('add', update);
1741
- server.watcher.on('unlink', update);
1742
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
1743
- var _devWorker2;
1744
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
1745
- server.watcher.off('change', update);
1746
- server.watcher.off('add', update);
1747
- server.watcher.off('unlink', update);
1748
- });
1749
- };
1750
- var remoteTypeUrls;
1751
- var _temp = function () {
1752
- if (host) {
1753
- return Promise.resolve(new Promise(function (resolve) {
1754
- consumeTypesAPI({
1755
- host: host,
1756
- extraOptions: extraOptions,
1757
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
1758
- }, resolve);
1759
- })).then(function (_Promise) {
1760
- remoteTypeUrls = _Promise;
1761
- });
1762
- }
1763
- }();
1764
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
1765
- } catch (e) {
1766
- return Promise.reject(e);
1695
+ });
1696
+ // Process shared dependencies
1697
+ var shared = Array.from(getUsedShares()).map(function (shareKey) {
1698
+ var shareItem = getNormalizeShareItem(shareKey);
1699
+ var assets = preloadMap[shareKey] || createEmptyAssetMap();
1700
+ return {
1701
+ id: name + ":" + shareKey,
1702
+ name: shareKey,
1703
+ version: shareItem.version,
1704
+ requiredVersion: shareItem.shareConfig.requiredVersion,
1705
+ assets: {
1706
+ js: {
1707
+ async: assets.js.async,
1708
+ sync: assets.js.sync
1709
+ },
1710
+ css: {
1711
+ async: assets.css.async,
1712
+ sync: assets.css.sync
1713
+ }
1767
1714
  }
1768
1715
  };
1769
- startDevWorker()["catch"](function (error) {
1770
- logDtsError(error, normalizedDtsOptions);
1771
- });
1772
- }
1716
+ }).filter(Boolean);
1717
+ // Process exposed modules
1718
+ var exposes = Object.entries(options.exposes).map(function (_ref3) {
1719
+ var key = _ref3[0],
1720
+ value = _ref3[1];
1721
+ var formatKey = key.replace('./', '');
1722
+ var sourceFile = value["import"];
1723
+ var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1724
+ return {
1725
+ id: name + ":" + formatKey,
1726
+ name: formatKey,
1727
+ assets: {
1728
+ js: {
1729
+ async: assets.js.async,
1730
+ sync: assets.js.sync
1731
+ },
1732
+ css: {
1733
+ async: assets.css.async,
1734
+ sync: assets.css.sync
1735
+ }
1736
+ },
1737
+ path: key
1738
+ };
1739
+ }).filter(Boolean);
1740
+ return {
1741
+ id: name,
1742
+ name: name,
1743
+ metaData: _extends({
1744
+ name: name,
1745
+ type: 'app',
1746
+ buildInfo: {
1747
+ buildVersion: '1.0.0',
1748
+ buildName: name
1749
+ },
1750
+ remoteEntry: remoteEntry,
1751
+ ssrRemoteEntry: remoteEntry,
1752
+ varRemoteEntry: varRemoteEntry,
1753
+ types: {
1754
+ path: '',
1755
+ name: ''
1756
+ },
1757
+ globalName: name,
1758
+ pluginVersion: '0.2.5'
1759
+ }, !!getPublicPath ? {
1760
+ getPublicPath: getPublicPath
1761
+ } : {
1762
+ publicPath: publicPath
1763
+ }),
1764
+ shared: shared,
1765
+ remotes: remotes,
1766
+ exposes: exposes
1767
+ };
1768
+ }
1769
+ };
1770
+
1771
+ var _resolve, _parseTimeout;
1772
+ var promise = new Promise(function (resolve, reject) {
1773
+ _resolve = function _resolve(v) {
1774
+ clearTimeout(_parseTimeout);
1775
+ _parseTimeout = null;
1776
+ resolve(v);
1773
1777
  };
1774
- var buildPlugin = {
1775
- name: 'module-federation-dts-build',
1778
+ });
1779
+ function setParseTimeout(timeout) {
1780
+ if (!_parseTimeout) {
1781
+ _parseTimeout = setTimeout(function () {
1782
+ console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1783
+ _resolve(1);
1784
+ }, timeout * 1000);
1785
+ }
1786
+ }
1787
+ var parsePromise = promise;
1788
+ var exposesParseEnd = false;
1789
+ var parseStartSet = new Set();
1790
+ var parseEndSet = new Set();
1791
+ function pluginModuleParseEnd (excludeFn, options) {
1792
+ setParseTimeout(options.moduleParseTimeout);
1793
+ return [{
1794
+ name: '_',
1795
+ apply: 'serve',
1796
+ config: function config() {
1797
+ // No waiting in development mode
1798
+ _resolve(1);
1799
+ }
1800
+ }, {
1801
+ enforce: 'pre',
1802
+ name: 'parseStart',
1803
+ apply: 'build',
1804
+ load: function load(id) {
1805
+ if (excludeFn(id)) {
1806
+ return;
1807
+ }
1808
+ parseStartSet.add(id);
1809
+ }
1810
+ }, {
1811
+ enforce: 'post',
1812
+ name: 'parseEnd',
1776
1813
  apply: 'build',
1814
+ moduleParsed: function moduleParsed(module) {
1815
+ var id = module.id;
1816
+ if (id === VIRTUAL_EXPOSES) {
1817
+ // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1818
+ exposesParseEnd = true;
1819
+ }
1820
+ if (excludeFn(id)) {
1821
+ return;
1822
+ }
1823
+ parseEndSet.add(id);
1824
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1825
+ _resolve(1);
1826
+ }
1827
+ }
1828
+ }];
1829
+ }
1830
+
1831
+ var filter = createFilter();
1832
+ function pluginProxyRemoteEntry () {
1833
+ var viteConfig, _command;
1834
+ return {
1835
+ name: 'proxyRemoteEntry',
1836
+ enforce: 'post',
1777
1837
  configResolved: function configResolved(config) {
1778
- resolvedConfig = config;
1838
+ viteConfig = config;
1779
1839
  },
1780
- generateBundle: function generateBundle() {
1781
- try {
1782
- var _temp6 = function _temp6() {
1783
- var generateOptions;
1784
- try {
1785
- generateOptions = normalizeGenerateTypesOptions({
1786
- context: context,
1787
- outputDir: outputDir,
1788
- dtsOptions: normalizedDtsOptions,
1789
- pluginOptions: dtsModuleFederationConfig
1790
- });
1791
- } catch (error) {
1792
- logDtsError(error, normalizedDtsOptions);
1793
- return;
1794
- }
1795
- if (!generateOptions) {
1796
- return;
1797
- }
1798
- var _temp4 = _catch(function () {
1799
- return Promise.resolve(generateTypesAPI({
1800
- dtsManagerOptions: generateOptions
1801
- })).then(function () {});
1802
- }, function (error) {
1803
- logDtsError(error, normalizedDtsOptions);
1840
+ config: function config(_config, _ref) {
1841
+ var command = _ref.command;
1842
+ _command = command;
1843
+ },
1844
+ resolveId: function resolveId(id) {
1845
+ if (id === REMOTE_ENTRY_ID) {
1846
+ return REMOTE_ENTRY_ID;
1847
+ }
1848
+ if (id === VIRTUAL_EXPOSES) {
1849
+ return VIRTUAL_EXPOSES;
1850
+ }
1851
+ if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1852
+ return id;
1853
+ }
1854
+ },
1855
+ load: function load(id) {
1856
+ if (id === REMOTE_ENTRY_ID) {
1857
+ return parsePromise.then(function (_) {
1858
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1859
+ });
1860
+ }
1861
+ if (id === VIRTUAL_EXPOSES) {
1862
+ return generateExposes();
1863
+ }
1864
+ if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1865
+ return id;
1866
+ }
1867
+ },
1868
+ transform: function transform(code, id) {
1869
+ var transformedCode = function () {
1870
+ if (!filter(id)) return;
1871
+ if (id.includes(REMOTE_ENTRY_ID)) {
1872
+ return parsePromise.then(function (_) {
1873
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1804
1874
  });
1805
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
1806
- };
1807
- if (hasGeneratedBundle) {
1808
- return Promise.resolve();
1809
- }
1810
- hasGeneratedBundle = true;
1811
- if (!resolvedConfig) {
1812
- return Promise.resolve();
1813
- }
1814
- var normalizedDtsOptions;
1815
- try {
1816
- normalizedDtsOptions = normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
1817
- } catch (error) {
1818
- logDtsError(error, options.dts);
1819
- return Promise.resolve();
1820
1875
  }
1821
- if (typeof normalizedDtsOptions !== 'object') {
1822
- return Promise.resolve();
1876
+ if (id === VIRTUAL_EXPOSES) {
1877
+ return generateExposes();
1823
1878
  }
1824
- var context = resolvedConfig.root;
1825
- var outputDir = resolveOutputDir(resolvedConfig);
1826
- var consumeOptions;
1827
- try {
1828
- consumeOptions = normalizeConsumeTypesOptions({
1829
- context: context,
1830
- dtsOptions: normalizedDtsOptions,
1831
- pluginOptions: dtsModuleFederationConfig
1832
- });
1833
- } catch (error) {
1834
- logDtsError(error, normalizedDtsOptions);
1835
- return Promise.resolve();
1879
+ if (id.includes(getHostAutoInitPath())) {
1880
+ var options = getNormalizeModuleFederationOptions();
1881
+ if (_command === 'serve') {
1882
+ var _viteConfig$server, _viteConfig$server2;
1883
+ var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1884
+ var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1885
+ return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1886
+ }
1887
+ return code;
1836
1888
  }
1837
- var _temp5 = function (_consumeOptions) {
1838
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
1839
- var _temp3 = _catch(function () {
1840
- return Promise.resolve(consumeTypesAPI(consumeOptions)).then(function () {});
1841
- }, function (error) {
1842
- logDtsError(error, normalizedDtsOptions);
1843
- });
1844
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
1889
+ }();
1890
+ return mapCodeToCodeWithSourcemap(transformedCode);
1891
+ }
1892
+ };
1893
+ }
1894
+
1895
+ createFilter();
1896
+ function pluginProxyRemotes (options) {
1897
+ var remotes = options.remotes;
1898
+ return {
1899
+ name: 'proxyRemotes',
1900
+ config: function config(_config, _ref) {
1901
+ var _command = _ref.command;
1902
+ Object.keys(remotes).forEach(function (key) {
1903
+ var remote = remotes[key];
1904
+ _config.resolve.alias.push({
1905
+ find: new RegExp("^(" + remote.name + "(/.*|$))"),
1906
+ replacement: '$1',
1907
+ customResolver: function customResolver(source) {
1908
+ var remoteModule = getRemoteVirtualModule(source, _command);
1909
+ addUsedRemote(remote.name, source);
1910
+ return remoteModule.getPath();
1845
1911
  }
1846
- }();
1847
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
1848
- } catch (e) {
1849
- return Promise.reject(e);
1850
- }
1912
+ });
1913
+ });
1851
1914
  }
1852
1915
  };
1853
- return [devPlugin, buildPlugin];
1854
1916
  }
1855
1917
 
1856
1918
  /**
@@ -1977,6 +2039,103 @@ function proxySharedModule(options) {
1977
2039
  }];
1978
2040
  }
1979
2041
 
2042
+ var VarRemoteEntry = function VarRemoteEntry() {
2043
+ var mfOptions = getNormalizeModuleFederationOptions();
2044
+ var name = mfOptions.name,
2045
+ varFilename = mfOptions.varFilename,
2046
+ filename = mfOptions.filename;
2047
+ var viteConfig;
2048
+ return [{
2049
+ name: 'module-federation-var-remote-entry',
2050
+ apply: 'serve',
2051
+ /**
2052
+ * Stores resolved Vite config for later use
2053
+ */
2054
+ /**
2055
+ * Finalizes configuration after all plugins are resolved
2056
+ * @param config - Fully resolved Vite config
2057
+ */
2058
+ configResolved: function configResolved(config) {
2059
+ viteConfig = config;
2060
+ },
2061
+ /**
2062
+ * Configures dev server middleware to handle varRemoteEntry requests
2063
+ * @param server - Vite dev server instance
2064
+ */
2065
+ configureServer: function configureServer(server) {
2066
+ server.middlewares.use(function (req, res, next) {
2067
+ var _req$url;
2068
+ if (!varFilename) {
2069
+ next();
2070
+ return;
2071
+ }
2072
+ if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + varFilename).replace(/^\/?/, '/')) {
2073
+ res.setHeader('Content-Type', 'text/javascript');
2074
+ res.setHeader('Access-Control-Allow-Origin', '*');
2075
+ console.log({
2076
+ filename: filename
2077
+ });
2078
+ res.end(generateVarRemoteEntry(filename));
2079
+ } else {
2080
+ next();
2081
+ }
2082
+ });
2083
+ }
2084
+ }, {
2085
+ name: 'module-federation-var-remote-entry',
2086
+ enforce: 'post',
2087
+ /**
2088
+ * Initial plugin configuration
2089
+ * @param config - Vite config object
2090
+ * @param command - Current Vite command (serve/build)
2091
+ */
2092
+ config: function config(_config, _ref) {
2093
+ if (!_config.build) _config.build = {};
2094
+ },
2095
+ /**
2096
+ * Generates the module federation "var" remote entry file
2097
+ * @param options - Rollup output options
2098
+ * @param bundle - Generated bundle assets
2099
+ */
2100
+ generateBundle: function generateBundle(options, bundle) {
2101
+ try {
2102
+ var _this = this;
2103
+ if (!varFilename) return Promise.resolve();
2104
+ var isValidName = isValidVarName(name);
2105
+ if (!isValidName) {
2106
+ viteConfig.logger.warn("Provided remote name \"" + name + "\" is not valid for \"var\" remoteEntry type, thus it's placed in globalThis['" + name + "'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).");
2107
+ }
2108
+ var remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
2109
+ if (!remoteEntryFile) throw new Error("Couldn't find a remoteEntry chunk file for " + mfOptions.filename + ", can't generate varRemoteEntry file");
2110
+ _this.emitFile({
2111
+ type: 'asset',
2112
+ fileName: varFilename,
2113
+ source: generateVarRemoteEntry(remoteEntryFile)
2114
+ });
2115
+ return Promise.resolve();
2116
+ } catch (e) {
2117
+ return Promise.reject(e);
2118
+ }
2119
+ }
2120
+ }];
2121
+ function isValidVarName(name) {
2122
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
2123
+ }
2124
+ /**
2125
+ * Generates the final "var" remote entry file
2126
+ * @param remoteEntryFile - Path to esm remote entry file
2127
+ * @returns Complete "var" remoteEntry.js file source
2128
+ */
2129
+ function generateVarRemoteEntry(remoteEntryFile) {
2130
+ var options = getNormalizeModuleFederationOptions();
2131
+ var name = options.name,
2132
+ varFilename = options.varFilename;
2133
+ var isValidName = isValidVarName(name);
2134
+ // todo: implement publicPath/getPublicPath support
2135
+ return "\n " + (isValidName ? "var " + name + ";" : '') + "\n " + (isValidName ? name : "globalThis['" + name + "']") + " = (function () {\n function getScriptUrl() {\n const currentScript = document.currentScript;\n if (!currentScript) {\n console.error(\"[VarRemoteEntry] " + varFilename + " script should be called from sync <script> tag (document.currentScript is undefined)\")\n return '/';\n }\n return document.currentScript.src.replace(/\\/[^/]*$/, '/');\n }\n\n const entry = getScriptUrl() + '" + remoteEntryFile + "';\n\n return {\n get: (...args) => import(entry).then(m => m.get(...args)),\n init: (...args) => import(entry).then(m => m.init(...args)),\n };\n })();\n ";
2136
+ }
2137
+ };
2138
+
1980
2139
  var aliasToArrayPlugin = {
1981
2140
  name: 'alias-transform-plugin',
1982
2141
  config: function config(_config, _ref) {
@@ -2043,6 +2202,8 @@ function federation(mfUserOptions) {
2043
2202
  entryPath: VIRTUAL_EXPOSES
2044
2203
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2045
2204
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2205
+ }, {
2206
+ moduleParseTimeout: options.moduleParseTimeout
2046
2207
  }), proxySharedModule({
2047
2208
  shared: shared
2048
2209
  }), [PluginDevProxyModuleTopLevelAwait(), {
@@ -2069,7 +2230,7 @@ function federation(mfUserOptions) {
2069
2230
  (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2070
2231
  (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2071
2232
  }
2072
- }], Manifest());
2233
+ }], Manifest(), VarRemoteEntry());
2073
2234
  }
2074
2235
 
2075
2236
  export { federation };