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