@module-federation/vite 1.11.0 → 1.12.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.
Files changed (47) hide show
  1. package/README.md +4 -1
  2. package/lib/index.cjs +2113 -2109
  3. package/lib/index.d.cts +131 -0
  4. package/lib/index.d.mts +131 -0
  5. package/lib/index.mjs +2239 -0
  6. package/package.json +40 -28
  7. package/lib/index.d.ts +0 -4
  8. package/lib/index.esm.js +0 -2236
  9. package/lib/index.modern.js +0 -2288
  10. package/lib/index.umd.js +0 -2257
  11. package/lib/plugins/__tests__/pluginCheckAliasConflicts.test.d.ts +0 -1
  12. package/lib/plugins/__tests__/pluginDts.test.d.ts +0 -1
  13. package/lib/plugins/pluginAddEntry.d.ts +0 -10
  14. package/lib/plugins/pluginCheckAliasConflicts.d.ts +0 -9
  15. package/lib/plugins/pluginDevProxyModuleTopLevelAwait.d.ts +0 -2
  16. package/lib/plugins/pluginDts.d.ts +0 -3
  17. package/lib/plugins/pluginMFManifest.d.ts +0 -3
  18. package/lib/plugins/pluginModuleParseEnd.d.ts +0 -10
  19. package/lib/plugins/pluginProxyRemoteEntry.d.ts +0 -2
  20. package/lib/plugins/pluginProxyRemotes.d.ts +0 -3
  21. package/lib/plugins/pluginProxySharedModule_preBuild.d.ts +0 -7
  22. package/lib/plugins/pluginVarRemoteEntry.d.ts +0 -3
  23. package/lib/utils/PromiseStore.d.ts +0 -16
  24. package/lib/utils/VirtualModule.d.ts +0 -26
  25. package/lib/utils/__tests__/VirtualModule.test.d.ts +0 -1
  26. package/lib/utils/__tests__/cssModuleHelpers.test.d.ts +0 -1
  27. package/lib/utils/__tests__/helpers.d.ts +0 -2
  28. package/lib/utils/__tests__/normalizeModuleFederationOption.test.d.ts +0 -1
  29. package/lib/utils/__tests__/publicPath.test.d.ts +0 -1
  30. package/lib/utils/__tests__/serializeRuntimeOptions.test.d.ts +0 -1
  31. package/lib/utils/aliasToArrayPlugin.d.ts +0 -10
  32. package/lib/utils/bundleHelpers.d.ts +0 -2
  33. package/lib/utils/cssModuleHelpers.d.ts +0 -75
  34. package/lib/utils/localSharedImportMap_temp.d.ts +0 -2
  35. package/lib/utils/mapCodeToCodeWithSourcemap.d.ts +0 -4
  36. package/lib/utils/normalizeModuleFederationOptions.d.ts +0 -164
  37. package/lib/utils/normalizeOptimizeDeps.d.ts +0 -9
  38. package/lib/utils/packageNameUtils.d.ts +0 -22
  39. package/lib/utils/publicPath.d.ts +0 -9
  40. package/lib/utils/serializeRuntimeOptions.d.ts +0 -10
  41. package/lib/utils/wrapManualChunks.d.ts +0 -1
  42. package/lib/virtualModules/index.d.ts +0 -6
  43. package/lib/virtualModules/virtualExposes.d.ts +0 -2
  44. package/lib/virtualModules/virtualRemoteEntry.d.ts +0 -16
  45. package/lib/virtualModules/virtualRemotes.d.ts +0 -6
  46. package/lib/virtualModules/virtualRuntimeInitStatus.d.ts +0 -3
  47. package/lib/virtualModules/virtualShared_preBuild.d.ts +0 -17
package/lib/index.umd.js DELETED
@@ -1,2257 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('defu'), require('fs'), require('pathe'), require('magic-string'), require('@rollup/pluginutils'), require('estree-walker'), require('@module-federation/sdk'), require('@module-federation/dts-plugin'), require('@module-federation/dts-plugin/core')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'defu', 'fs', 'pathe', 'magic-string', '@rollup/pluginutils', 'estree-walker', '@module-federation/sdk', '@module-federation/dts-plugin', '@module-federation/dts-plugin/core'], factory) :
4
- (global = global || self, factory(global.vite = {}, global.defu, global.fs, global.pathe, global.magicString, global.pluginutils, global.estreeWalker, global.sdk, global.dtsPlugin, global.core));
5
- })(this, (function (exports, defu, fs, path, MagicString, pluginutils, estreeWalker, sdk, dtsPlugin, core) {
6
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
7
-
8
- function _interopNamespace(e) {
9
- if (e && e.__esModule) return e;
10
- var n = Object.create(null);
11
- if (e) {
12
- Object.keys(e).forEach(function (k) {
13
- if (k !== 'default') {
14
- var d = Object.getOwnPropertyDescriptor(e, k);
15
- Object.defineProperty(n, k, d.get ? d : {
16
- enumerable: true,
17
- get: function () { return e[k]; }
18
- });
19
- }
20
- });
21
- }
22
- n["default"] = e;
23
- return n;
24
- }
25
-
26
- var defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
27
- var fs__namespace = /*#__PURE__*/_interopNamespace(fs);
28
- var path__namespace = /*#__PURE__*/_interopNamespace(path);
29
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
30
- var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
31
-
32
- var mapCodeToCodeWithSourcemap = function mapCodeToCodeWithSourcemap(code) {
33
- return Promise.resolve(code).then(function (resolvedCode) {
34
- if (resolvedCode === undefined) {
35
- return;
36
- }
37
- var s = new MagicString__default["default"](resolvedCode);
38
- return {
39
- code: s.toString(),
40
- map: s.generateMap({
41
- hires: true
42
- })
43
- };
44
- });
45
- };
46
-
47
- function getFirstHtmlEntryFile(entryFiles) {
48
- return entryFiles.find(function (file) {
49
- return file.endsWith('.html');
50
- });
51
- }
52
- var addEntry = function addEntry(_ref) {
53
- var entryName = _ref.entryName,
54
- entryPath = _ref.entryPath,
55
- fileName = _ref.fileName,
56
- _ref$inject = _ref.inject,
57
- inject = _ref$inject === void 0 ? 'entry' : _ref$inject;
58
- var devEntryPath = entryPath.startsWith('virtual:mf') ? '@id/' + entryPath : entryPath;
59
- var entryFiles = [];
60
- var htmlFilePath;
61
- var _command;
62
- var emitFileId;
63
- var viteConfig;
64
- function injectHtml() {
65
- return inject === 'html' && htmlFilePath;
66
- }
67
- function injectEntry() {
68
- return inject === 'entry' || !htmlFilePath;
69
- }
70
- return [{
71
- name: 'add-entry',
72
- apply: 'serve',
73
- config: function config(_config, _ref2) {
74
- var command = _ref2.command;
75
- _command = command;
76
- },
77
- configResolved: function configResolved(config) {
78
- viteConfig = config;
79
- devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, '/').replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/^\//, '');
80
- },
81
- configureServer: function configureServer(server) {
82
- server.middlewares.use(function (req, res, next) {
83
- if (!fileName) {
84
- next();
85
- return;
86
- }
87
- if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, '/'))) {
88
- req.url = devEntryPath;
89
- }
90
- next();
91
- });
92
- },
93
- transformIndexHtml: function transformIndexHtml(c) {
94
- if (!injectHtml()) return;
95
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
96
- },
97
- transform: function transform(code, id) {
98
- if (id.includes('node_modules') || inject !== 'html' || htmlFilePath) {
99
- return;
100
- }
101
- if (id.includes('.svelte-kit') && id.includes('internal.js')) {
102
- var src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/');
103
- return code.replace(/<head>/g, '<head><script type=\\"module\\" src=\\"' + src + '\\"></script>');
104
- }
105
- }
106
- }, {
107
- name: 'add-entry',
108
- enforce: 'post',
109
- configResolved: function configResolved(config) {
110
- viteConfig = config;
111
- var inputOptions = config.build.rollupOptions.input;
112
- if (!inputOptions) {
113
- htmlFilePath = path__namespace.resolve(config.root, 'index.html');
114
- } else if (typeof inputOptions === 'string') {
115
- entryFiles = [inputOptions];
116
- } else if (Array.isArray(inputOptions)) {
117
- entryFiles = inputOptions;
118
- } else if (typeof inputOptions === 'object') {
119
- entryFiles = Object.values(inputOptions);
120
- }
121
- if (entryFiles && entryFiles.length > 0) {
122
- htmlFilePath = getFirstHtmlEntryFile(entryFiles);
123
- }
124
- },
125
- buildStart: function buildStart() {
126
- if (_command === 'serve') return;
127
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
128
- var emitFileOptions = {
129
- name: entryName,
130
- type: 'chunk',
131
- id: entryPath,
132
- preserveSignature: 'strict'
133
- };
134
- if (!hasHash) {
135
- emitFileOptions.fileName = fileName;
136
- }
137
- emitFileId = this.emitFile(emitFileOptions);
138
- if (htmlFilePath && fs__namespace.existsSync(htmlFilePath)) {
139
- var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
140
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
141
- var match;
142
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
143
- entryFiles.push(match[1]);
144
- }
145
- }
146
- },
147
- generateBundle: function generateBundle(options, bundle) {
148
- if (!injectHtml()) return;
149
- var file = this.getFileName(emitFileId);
150
- // Helper to resolve path with proper renderBuiltUrl handling
151
- var resolvePath = function resolvePath(htmlFileName) {
152
- var _viteConfig$experimen;
153
- if (!((_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl)) {
154
- return viteConfig.base + file;
155
- }
156
- var result = viteConfig.experimental.renderBuiltUrl(file, {
157
- hostId: htmlFileName,
158
- hostType: 'html',
159
- type: 'asset',
160
- ssr: false
161
- });
162
- // Handle return types
163
- if (typeof result === 'string') {
164
- return result;
165
- }
166
- if (result && typeof result === 'object') {
167
- if ('runtime' in result) {
168
- // Runtime code cannot be used in <script src="">
169
- 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.');
170
- return viteConfig.base + file;
171
- }
172
- if (result.relative) {
173
- return file;
174
- }
175
- }
176
- // Fallback for undefined or unexpected values
177
- return viteConfig.base + file;
178
- };
179
- // Process each HTML file
180
- for (var _fileName in bundle) {
181
- if (_fileName.endsWith('.html')) {
182
- var htmlAsset = bundle[_fileName];
183
- if (htmlAsset.type === 'chunk') return;
184
- var _path = resolvePath(_fileName);
185
- var scriptContent = "\n <script type=\"module\" src=\"" + _path + "\"></script>\n ";
186
- var htmlContent = htmlAsset.source.toString() || '';
187
- htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
188
- htmlAsset.source = htmlContent;
189
- }
190
- }
191
- },
192
- transform: function transform(code, id) {
193
- if (injectEntry() && entryFiles.some(function (file) {
194
- return id.endsWith(file);
195
- })) {
196
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
197
- return mapCodeToCodeWithSourcemap(injection + code);
198
- }
199
- }
200
- }];
201
- };
202
-
203
- function _arrayLikeToArray(r, a) {
204
- (null == a || a > r.length) && (a = r.length);
205
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
206
- return n;
207
- }
208
- function _createForOfIteratorHelperLoose(r, e) {
209
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
210
- if (t) return (t = t.call(r)).next.bind(t);
211
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
212
- t && (r = t);
213
- var o = 0;
214
- return function () {
215
- return o >= r.length ? {
216
- done: !0
217
- } : {
218
- done: !1,
219
- value: r[o++]
220
- };
221
- };
222
- }
223
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
224
- }
225
- function _extends() {
226
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
227
- for (var e = 1; e < arguments.length; e++) {
228
- var t = arguments[e];
229
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
230
- }
231
- return n;
232
- }, _extends.apply(null, arguments);
233
- }
234
- function _unsupportedIterableToArray(r, a) {
235
- if (r) {
236
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
237
- var t = {}.toString.call(r).slice(8, -1);
238
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
239
- }
240
- }
241
-
242
- /**
243
- * Check if user-defined alias conflicts with shared modules
244
- * This should run after aliasToArrayPlugin to ensure alias is an array
245
- */
246
- function checkAliasConflicts(options) {
247
- var _options$shared = options.shared,
248
- shared = _options$shared === void 0 ? {} : _options$shared;
249
- var sharedKeys = Object.keys(shared);
250
- return {
251
- name: 'check-alias-conflicts',
252
- configResolved: function configResolved(config) {
253
- var _config$resolve;
254
- if (sharedKeys.length === 0) return;
255
- var userAliases = ((_config$resolve = config.resolve) == null ? void 0 : _config$resolve.alias) || [];
256
- var conflicts = [];
257
- for (var _i = 0, _sharedKeys = sharedKeys; _i < _sharedKeys.length; _i++) {
258
- var sharedKey = _sharedKeys[_i];
259
- for (var _iterator = _createForOfIteratorHelperLoose(userAliases), _step; !(_step = _iterator()).done;) {
260
- var aliasEntry = _step.value;
261
- var findPattern = aliasEntry.find;
262
- var replacement = aliasEntry.replacement;
263
- // Skip if replacement is not a string (e.g., customResolver)
264
- if (typeof replacement !== 'string') continue;
265
- // Skip Module Federation internal aliases (used for proxying shared modules)
266
- // These are generated with replacement '$1' and should not trigger warnings
267
- if (replacement === '$1') continue;
268
- // Check if alias pattern matches the shared module
269
- var isMatch = false;
270
- if (typeof findPattern === 'string') {
271
- isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + '/');
272
- } else if (findPattern instanceof RegExp) {
273
- isMatch = findPattern.test(sharedKey);
274
- }
275
- if (isMatch) {
276
- conflicts.push({
277
- sharedModule: sharedKey,
278
- alias: String(findPattern),
279
- target: replacement
280
- });
281
- }
282
- }
283
- }
284
- if (conflicts.length > 0) {
285
- config.logger.warn('\n[Module Federation] Detected alias conflicts with shared modules:');
286
- conflicts.forEach(function (_ref) {
287
- var sharedModule = _ref.sharedModule,
288
- alias = _ref.alias,
289
- target = _ref.target;
290
- config.logger.warn(" - Shared module \"" + sharedModule + "\" is aliased by \"" + alias + "\" to \"" + target + "\"");
291
- });
292
- config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
293
- }
294
- }
295
- };
296
- }
297
-
298
- /**
299
- * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
300
- */
301
- function PluginDevProxyModuleTopLevelAwait() {
302
- var filterFunction = pluginutils.createFilter();
303
- var processedFlag = '/* already-processed-by-dev-proxy-module-top-level-await */';
304
- return {
305
- name: 'dev-proxy-module-top-level-await',
306
- apply: 'serve',
307
- transform: function transform(code, id) {
308
- if (code.includes(processedFlag)) {
309
- return null;
310
- }
311
- if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
312
- return null;
313
- }
314
- if (!filterFunction(id)) return null;
315
- var ast;
316
- try {
317
- ast = this.parse(code, {
318
- allowReturnOutsideFunction: true
319
- });
320
- } catch (e) {
321
- throw new Error(id + ": " + e);
322
- }
323
- var magicString = new MagicString__default["default"](code);
324
- estreeWalker.walk(ast, {
325
- enter: function enter(node) {
326
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
327
- var exportSpecifiers = node.specifiers.map(function (specifier) {
328
- return specifier.exported.name;
329
- });
330
- var proxyStatements = exportSpecifiers.map(function (name) {
331
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
332
- }).join('\n');
333
- var exportStatements = exportSpecifiers.map(function (name) {
334
- return "__mfproxy__" + name + " as " + name;
335
- }).join(', ');
336
- var start = node.start;
337
- var end = node.end;
338
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
339
- magicString.overwrite(start, end, replacement);
340
- }
341
- if (node.type === 'ExportDefaultDeclaration') {
342
- var declaration = node.declaration;
343
- var _start = node.start;
344
- var _end = node.end;
345
- var proxyStatement;
346
- var exportStatement = 'default';
347
- if (declaration.type === 'Identifier') {
348
- // example: export default foo;
349
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
350
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
351
- // example: export default someFunction();
352
- var declarationCode = code.slice(declaration.start, declaration.end);
353
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
354
- } else {
355
- // other
356
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
357
- }
358
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
359
- magicString.overwrite(_start, _end, _replacement);
360
- }
361
- }
362
- });
363
- var transformedCode = magicString.toString();
364
- return {
365
- code: processedFlag + "\n" + transformedCode,
366
- map: magicString.generateMap({
367
- hires: true
368
- })
369
- };
370
- }
371
- };
372
- }
373
-
374
- function _catch(body, recover) {
375
- try {
376
- var result = body();
377
- } catch (e) {
378
- return recover(e);
379
- }
380
- if (result && result.then) {
381
- return result.then(void 0, recover);
382
- }
383
- return result;
384
- }
385
- var DEFAULT_DEV_OPTIONS = {
386
- disableLiveReload: true,
387
- disableHotTypesReload: false,
388
- disableDynamicRemoteTypeHints: false
389
- };
390
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
391
- var getIPv4 = function getIPv4() {
392
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
393
- };
394
- var forkDevWorkerPath = function () {
395
- // eslint-disable-next-line @typescript-eslint/no-var-requires
396
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
397
- }();
398
- var DevWorker = /*#__PURE__*/function () {
399
- function DevWorker(options) {
400
- this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
401
- this.worker.connect(options);
402
- }
403
- var _proto = DevWorker.prototype;
404
- _proto.update = function update() {
405
- var _this$worker$process;
406
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
407
- type: core.rpc.RpcGMCallTypes.CALL,
408
- id: this.worker.id,
409
- args: [undefined, 'update']
410
- });
411
- };
412
- _proto.exit = function exit() {
413
- this.worker.terminate();
414
- };
415
- return DevWorker;
416
- }();
417
- var normalizeDevOptions = function normalizeDevOptions(dev) {
418
- if (dev === false) {
419
- return false;
420
- }
421
- if (dev === true || typeof dev === 'undefined') {
422
- return _extends({}, DEFAULT_DEV_OPTIONS);
423
- }
424
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
425
- };
426
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
427
- var exposes = {};
428
- Object.entries(options.exposes).forEach(function (_ref) {
429
- var key = _ref[0],
430
- value = _ref[1];
431
- if (typeof value === 'string') {
432
- exposes[key] = value;
433
- return;
434
- }
435
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
436
- if (importValue) {
437
- exposes[key] = importValue;
438
- }
439
- });
440
- var remotes = {};
441
- Object.entries(options.remotes).forEach(function (_ref2) {
442
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
443
- var key = _ref2[0],
444
- remote = _ref2[1];
445
- if (typeof remote === 'string') {
446
- remotes[key] = remote;
447
- return;
448
- }
449
- if (!remote.entry) {
450
- return;
451
- }
452
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
453
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
454
- remotes[key] = entryGlobalName + "@" + remote.entry;
455
- });
456
- return _extends({}, options, {
457
- exposes: exposes,
458
- remotes: remotes
459
- });
460
- };
461
- var resolveOutputDir = function resolveOutputDir(config) {
462
- var outDir = config.build.outDir;
463
- if (path__namespace.isAbsolute(outDir)) {
464
- return path__namespace.relative(config.root, outDir);
465
- }
466
- return outDir;
467
- };
468
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
469
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
470
- if (typeof plugin === 'string') {
471
- return plugin === pluginId;
472
- }
473
- return plugin[0] === pluginId;
474
- });
475
- if (!hasPlugin) {
476
- options.runtimePlugins.push(pluginId);
477
- }
478
- };
479
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
480
- var defaultGenerateTypes = {
481
- compileInChildProcess: true
482
- };
483
- var defaultConsumeTypes = {
484
- consumeAPITypes: true
485
- };
486
- return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
487
- generateTypes: defaultGenerateTypes,
488
- consumeTypes: defaultConsumeTypes,
489
- extraOptions: {},
490
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
491
- }, 'mfOptions.dts')(dts);
492
- };
493
- var logDtsError = function logDtsError(error, dtsOptions) {
494
- if (dtsOptions === false) {
495
- return;
496
- }
497
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
498
- return;
499
- }
500
- console.error(error);
501
- };
502
- function pluginDts(options) {
503
- if (options.dts === false) {
504
- return [];
505
- }
506
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
507
- var resolvedConfig;
508
- var devWorker;
509
- var normalizedDevOptions;
510
- var hasGeneratedBundle = false;
511
- var devPlugin = {
512
- name: 'module-federation-dts-dev',
513
- apply: 'serve',
514
- config: function config(_config) {
515
- normalizedDevOptions = normalizeDevOptions(options.dev);
516
- if (!normalizedDevOptions) {
517
- return;
518
- }
519
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
520
- return;
521
- }
522
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
523
- var define = _config.define ? _extends({}, _config.define) : {};
524
- if (!('FEDERATION_IPV4' in define)) {
525
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
526
- }
527
- _config.define = define;
528
- },
529
- configResolved: function configResolved(config) {
530
- resolvedConfig = config;
531
- },
532
- configureServer: function configureServer(server) {
533
- if (!normalizedDevOptions || !resolvedConfig) {
534
- return;
535
- }
536
- var devOptions = normalizedDevOptions;
537
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
538
- return;
539
- }
540
- if (!options.name) {
541
- throw new Error('name is required if you want to enable dev server!');
542
- }
543
- var outputDir = resolveOutputDir(resolvedConfig);
544
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
545
- if (typeof normalizedDtsOptions !== 'object') {
546
- return;
547
- }
548
- var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
549
- compileInChildProcess: true
550
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
551
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
552
- implementation: normalizedDtsOptions.implementation,
553
- context: resolvedConfig.root,
554
- outputDir: outputDir,
555
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
556
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
557
- }, normalizedGenerateTypes, {
558
- typesFolder: '.dev-server'
559
- });
560
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
561
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
562
- }
563
- var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
564
- consumeAPITypes: true
565
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
566
- var host = normalizedConsumeTypes === false ? undefined : _extends({
567
- implementation: normalizedDtsOptions.implementation,
568
- context: resolvedConfig.root,
569
- moduleFederationConfig: dtsModuleFederationConfig,
570
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
571
- abortOnError: false
572
- }, normalizedConsumeTypes);
573
- var extraOptions = normalizedDtsOptions.extraOptions || {};
574
- if (!remote && !host && devOptions.disableLiveReload) {
575
- return;
576
- }
577
- var startDevWorker = function startDevWorker() {
578
- try {
579
- var _temp2 = function _temp2() {
580
- var _server$httpServer;
581
- devWorker = new DevWorker({
582
- name: options.name,
583
- remote: remote,
584
- host: host ? _extends({}, host, {
585
- remoteTypeUrls: remoteTypeUrls
586
- }) : undefined,
587
- extraOptions: extraOptions,
588
- disableLiveReload: devOptions.disableLiveReload,
589
- disableHotTypesReload: devOptions.disableHotTypesReload
590
- });
591
- var update = function update() {
592
- var _devWorker;
593
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
594
- };
595
- server.watcher.on('change', update);
596
- server.watcher.on('add', update);
597
- server.watcher.on('unlink', update);
598
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
599
- var _devWorker2;
600
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
601
- server.watcher.off('change', update);
602
- server.watcher.off('add', update);
603
- server.watcher.off('unlink', update);
604
- });
605
- };
606
- var remoteTypeUrls;
607
- var _temp = function () {
608
- if (host) {
609
- return Promise.resolve(new Promise(function (resolve) {
610
- dtsPlugin.consumeTypesAPI({
611
- host: host,
612
- extraOptions: extraOptions,
613
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
614
- }, resolve);
615
- })).then(function (_Promise) {
616
- remoteTypeUrls = _Promise;
617
- });
618
- }
619
- }();
620
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
621
- } catch (e) {
622
- return Promise.reject(e);
623
- }
624
- };
625
- startDevWorker()["catch"](function (error) {
626
- logDtsError(error, normalizedDtsOptions);
627
- });
628
- }
629
- };
630
- var buildPlugin = {
631
- name: 'module-federation-dts-build',
632
- apply: 'build',
633
- configResolved: function configResolved(config) {
634
- resolvedConfig = config;
635
- },
636
- generateBundle: function generateBundle() {
637
- try {
638
- var _temp6 = function _temp6() {
639
- var generateOptions;
640
- try {
641
- generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
642
- context: context,
643
- outputDir: outputDir,
644
- dtsOptions: normalizedDtsOptions,
645
- pluginOptions: dtsModuleFederationConfig
646
- });
647
- } catch (error) {
648
- logDtsError(error, normalizedDtsOptions);
649
- return;
650
- }
651
- if (!generateOptions) {
652
- return;
653
- }
654
- var _temp4 = _catch(function () {
655
- return Promise.resolve(dtsPlugin.generateTypesAPI({
656
- dtsManagerOptions: generateOptions
657
- })).then(function () {});
658
- }, function (error) {
659
- logDtsError(error, normalizedDtsOptions);
660
- });
661
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
662
- };
663
- if (hasGeneratedBundle) {
664
- return Promise.resolve();
665
- }
666
- hasGeneratedBundle = true;
667
- if (!resolvedConfig) {
668
- return Promise.resolve();
669
- }
670
- var normalizedDtsOptions;
671
- try {
672
- normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
673
- } catch (error) {
674
- logDtsError(error, options.dts);
675
- return Promise.resolve();
676
- }
677
- if (typeof normalizedDtsOptions !== 'object') {
678
- return Promise.resolve();
679
- }
680
- var context = resolvedConfig.root;
681
- var outputDir = resolveOutputDir(resolvedConfig);
682
- var consumeOptions;
683
- try {
684
- consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
685
- context: context,
686
- dtsOptions: normalizedDtsOptions,
687
- pluginOptions: dtsModuleFederationConfig
688
- });
689
- } catch (error) {
690
- logDtsError(error, normalizedDtsOptions);
691
- return Promise.resolve();
692
- }
693
- var _temp5 = function (_consumeOptions) {
694
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
695
- var _temp3 = _catch(function () {
696
- return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
697
- }, function (error) {
698
- logDtsError(error, normalizedDtsOptions);
699
- });
700
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
701
- }
702
- }();
703
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
704
- } catch (e) {
705
- return Promise.reject(e);
706
- }
707
- }
708
- };
709
- return [devPlugin, buildPlugin];
710
- }
711
-
712
- function normalizeExposesItem(key, item) {
713
- var importPath = '';
714
- if (typeof item === 'string') {
715
- importPath = item;
716
- }
717
- if (typeof item === 'object') {
718
- importPath = item["import"];
719
- }
720
- return {
721
- "import": importPath
722
- };
723
- }
724
- function normalizeExposes(exposes) {
725
- if (!exposes) return {};
726
- var res = {};
727
- Object.keys(exposes).forEach(function (key) {
728
- res[key] = normalizeExposesItem(key, exposes[key]);
729
- });
730
- return res;
731
- }
732
- function normalizeRemotes(remotes) {
733
- if (!remotes) return {};
734
- var result = {};
735
- if (typeof remotes === 'object') {
736
- Object.keys(remotes).forEach(function (key) {
737
- result[key] = normalizeRemoteItem(key, remotes[key]);
738
- });
739
- }
740
- return result;
741
- }
742
- function normalizeRemoteItem(key, remote) {
743
- if (typeof remote === 'string') {
744
- var _remote$split = remote.split('@'),
745
- entryGlobalName = _remote$split[0];
746
- var entry = remote.replace(entryGlobalName + '@', '');
747
- return {
748
- type: 'var',
749
- name: key,
750
- entry: entry,
751
- entryGlobalName: entryGlobalName,
752
- shareScope: 'default'
753
- };
754
- }
755
- return Object.assign({
756
- type: 'var',
757
- name: key,
758
- shareScope: 'default',
759
- entryGlobalName: key
760
- }, remote);
761
- }
762
- function removePathFromNpmPackage(packageString) {
763
- // 匹配npm包名的正则表达式,忽略路径部分
764
- var regex = /^(?:@[^/]+\/)?[^/]+/;
765
- // 使用正则表达式匹配并提取包名
766
- var match = packageString.match(regex);
767
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
768
- return match ? match[0] : packageString;
769
- }
770
- /**
771
- * Tries to find the package.json's version of a shared package
772
- * if `package.json` is not declared in `exports`
773
- * @param {string} sharedName
774
- * @returns {string | undefined}
775
- */
776
- function searchPackageVersion(sharedName) {
777
- try {
778
- var sharedPath = require.resolve(sharedName);
779
- var potentialPackageJsonDir = path__namespace.dirname(sharedPath);
780
- var rootDir = path__namespace.parse(potentialPackageJsonDir).root;
781
- while (path__namespace.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
782
- var potentialPackageJsonPath = path__namespace.join(potentialPackageJsonDir, 'package.json');
783
- if (fs__namespace.existsSync(potentialPackageJsonPath)) {
784
- var potentialPackageJson = require(potentialPackageJsonPath);
785
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
786
- return potentialPackageJson.version;
787
- }
788
- }
789
- potentialPackageJsonDir = path__namespace.dirname(potentialPackageJsonDir);
790
- }
791
- } catch (_) {}
792
- return undefined;
793
- }
794
- function normalizeShareItem(key, shareItem) {
795
- var version;
796
- try {
797
- try {
798
- version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
799
- } catch (e1) {
800
- try {
801
- var localPath = path__namespace.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
802
- version = require(localPath).version;
803
- } catch (e2) {
804
- version = searchPackageVersion(key);
805
- if (!version) console.error(e1);
806
- }
807
- }
808
- } catch (e) {
809
- console.error("Unexpected error resolving version for " + key + ":", e);
810
- }
811
- if (typeof shareItem === 'string') {
812
- return {
813
- name: shareItem,
814
- version: version,
815
- scope: 'default',
816
- from: '',
817
- shareConfig: {
818
- "import": undefined,
819
- singleton: false,
820
- requiredVersion: version ? "^" + version : '*'
821
- }
822
- };
823
- }
824
- return {
825
- name: key,
826
- from: '',
827
- version: shareItem.version || version,
828
- scope: shareItem.shareScope || 'default',
829
- shareConfig: {
830
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
831
- singleton: shareItem.singleton || false,
832
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
833
- strictVersion: !!shareItem.strictVersion
834
- }
835
- };
836
- }
837
- function normalizeShared(shared) {
838
- if (!shared) return {};
839
- var result = {};
840
- if (Array.isArray(shared)) {
841
- shared.forEach(function (key) {
842
- result[key] = normalizeShareItem(key, key);
843
- });
844
- return result;
845
- }
846
- if (typeof shared === 'object') {
847
- Object.keys(shared).forEach(function (key) {
848
- result[key] = normalizeShareItem(key, shared[key]);
849
- });
850
- }
851
- return result;
852
- }
853
- function normalizeLibrary(library) {
854
- if (!library) return undefined;
855
- return library;
856
- }
857
- function normalizeManifest(manifest) {
858
- if (manifest === void 0) {
859
- manifest = false;
860
- }
861
- if (typeof manifest === 'boolean') {
862
- return manifest;
863
- }
864
- return Object.assign({
865
- filePath: '',
866
- disableAssetsAnalyze: false,
867
- fileName: 'mf-manifest.json'
868
- }, manifest);
869
- }
870
- var config;
871
- function getNormalizeModuleFederationOptions() {
872
- return config;
873
- }
874
- function getNormalizeShareItem(key) {
875
- var options = getNormalizeModuleFederationOptions();
876
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
877
- return shareItem;
878
- }
879
- function normalizeModuleFederationOptions(options) {
880
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
881
- 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'.");
882
- }
883
- return config = {
884
- exposes: normalizeExposes(options.exposes),
885
- filename: options.filename || 'remoteEntry-[hash]',
886
- library: normalizeLibrary(options.library),
887
- name: options.name,
888
- // remoteType: options.remoteType,
889
- remotes: normalizeRemotes(options.remotes),
890
- runtime: options.runtime,
891
- shareScope: options.shareScope || 'default',
892
- shared: normalizeShared(options.shared),
893
- runtimePlugins: options.runtimePlugins || [],
894
- implementation: options.implementation || require.resolve('@module-federation/runtime'),
895
- manifest: normalizeManifest(options.manifest),
896
- dev: options.dev,
897
- dts: options.dts,
898
- getPublicPath: options.getPublicPath,
899
- publicPath: options.publicPath,
900
- shareStrategy: options.shareStrategy || 'version-first',
901
- ignoreOrigin: options.ignoreOrigin || false,
902
- virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
903
- hostInitInjectLocation: options.hostInitInjectLocation || 'html',
904
- bundleAllCSS: options.bundleAllCSS || false,
905
- moduleParseTimeout: options.moduleParseTimeout || 10,
906
- varFilename: options.varFilename
907
- };
908
- }
909
-
910
- /**
911
- * Escaping rules:
912
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
913
- * @ => 1
914
- * / => 2
915
- * - => 3
916
- * . => 4
917
- */
918
- /**
919
- * Encodes a package name into a valid file name.
920
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
921
- * @returns {string} - The encoded file name.
922
- */
923
- function packageNameEncode(name) {
924
- if (typeof name !== 'string') throw new Error('A string package name is required');
925
- return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
926
- }
927
- /**
928
- * Decodes an encoded file name back to the original package name.
929
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
930
- * @returns {string} - The decoded package name.
931
- */
932
- function packageNameDecode(encoded) {
933
- if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
934
- return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
935
- }
936
-
937
- /**
938
- * https://github.com/module-federation/vite/issues/68
939
- */
940
- function getLocalSharedImportMapPath_temp() {
941
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
942
- name = _getNormalizeModuleFe.name;
943
- return path__default["default"].resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
944
- }
945
- function writeLocalSharedImportMap_temp(content) {
946
- var localSharedImportMapId = getLocalSharedImportMapPath_temp();
947
- createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
948
- }
949
- function createFile(filePath, content) {
950
- var dir = path__default["default"].dirname(filePath);
951
- fs.mkdirSync(dir, {
952
- recursive: true
953
- });
954
- fs.writeFileSync(filePath, content);
955
- }
956
-
957
- /**
958
- * Serializes a JavaScript object into a string of source code that can be evaluated.
959
- * This function is used to create runtime plugin options without relying solely on JSON.stringify,
960
- * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
961
- * It also safely handles circular references.
962
- *
963
- * @param {Record<string, unknown>} options - The options object to serialize.
964
- * @returns {string} The resulting JavaScript source code string.
965
- */
966
- function serializeRuntimeOptions(options) {
967
- // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
968
- var seenObjects = new WeakSet();
969
- /**
970
- * Recursive inner function to serialize any value into a source code string.
971
- */
972
- function valueToCode(val) {
973
- // 1. Handle primitive values
974
- if (val === null) return 'null';
975
- var type = typeof val;
976
- if (type === 'string') return JSON.stringify(val);
977
- if (type === 'number' || type === 'boolean') return String(val);
978
- if (type === 'undefined') return 'undefined';
979
- // Handle Symbol
980
- if (type === 'symbol') {
981
- var _val$description;
982
- var desc = (_val$description = val.description) != null ? _val$description : '';
983
- return "Symbol(" + JSON.stringify(desc) + ")";
984
- }
985
- // Handle Function (returns the function's source code)
986
- if (type === 'function') return val.toString();
987
- // 2. Handle special built-in objects
988
- if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
989
- if (val instanceof RegExp) {
990
- return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
991
- }
992
- // 3. Check for circular references and mark object as seen
993
- // This applies to objects, arrays, maps, and sets.
994
- if (type === 'object') {
995
- if (seenObjects.has(val)) {
996
- // This object has been seen previously in the recursion path
997
- return "\"__circular__\"";
998
- }
999
- seenObjects.add(val);
1000
- }
1001
- // 4. Handle Array, Map, Set
1002
- if (Array.isArray(val)) {
1003
- // Recursively serialize each element
1004
- return "[" + val.map(valueToCode).join(', ') + "]";
1005
- }
1006
- if (val instanceof Map) {
1007
- // Serialize Map entries into an array of [key, value] pairs
1008
- var entries = Array.from(val.entries()).map(function (_ref) {
1009
- var k = _ref[0],
1010
- v = _ref[1];
1011
- return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
1012
- });
1013
- return "new Map([" + entries.join(', ') + "])";
1014
- }
1015
- if (val instanceof Set) {
1016
- // Serialize Set values into an array
1017
- var items = Array.from(val.values()).map(valueToCode);
1018
- return "new Set([" + items.join(', ') + "])";
1019
- }
1020
- // 5. Handle plain objects (the default object type)
1021
- if (type === 'object') {
1022
- var properties = [];
1023
- // Iterate over the object's own enumerable properties
1024
- for (var key in val) {
1025
- if (Object.prototype.hasOwnProperty.call(val, key)) {
1026
- // Wrap the key in JSON.stringify to handle non-identifier keys
1027
- properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
1028
- }
1029
- }
1030
- return "{" + properties.join(', ') + "}";
1031
- }
1032
- // 6. Fallback case (e.g., BigInt, other object types)
1033
- // Coerce to string and then JSON.stringify that string for safety
1034
- return JSON.stringify(String(val));
1035
- }
1036
- // Start serialization for the top-level object
1037
- var topLevelProps = [];
1038
- // Iterate over the properties of the root 'options' object
1039
- for (var key in options) {
1040
- if (Object.prototype.hasOwnProperty.call(options, key)) {
1041
- topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
1042
- }
1043
- }
1044
- return "{" + topLevelProps.join(', ') + "}";
1045
- }
1046
-
1047
- // Cache root path
1048
- var rootDir;
1049
- function findNodeModulesDir(root) {
1050
- if (root === void 0) {
1051
- root = process.cwd();
1052
- }
1053
- var currentDir = root;
1054
- while (currentDir !== path.parse(currentDir).root) {
1055
- var nodeModulesPath = path.join(currentDir, 'node_modules');
1056
- if (fs.existsSync(nodeModulesPath)) {
1057
- return nodeModulesPath;
1058
- }
1059
- currentDir = path.dirname(currentDir);
1060
- }
1061
- return '';
1062
- }
1063
- // Cache nodeModulesDir result to avoid repeated calculations
1064
- var cachedNodeModulesDir;
1065
- function getNodeModulesDir() {
1066
- if (!cachedNodeModulesDir) {
1067
- cachedNodeModulesDir = findNodeModulesDir(rootDir);
1068
- }
1069
- return cachedNodeModulesDir;
1070
- }
1071
- function getSuffix(name) {
1072
- var base = path.basename(name);
1073
- var dotIndex = base.lastIndexOf('.');
1074
- if (dotIndex > 0 && dotIndex < base.length - 1) {
1075
- return base.slice(dotIndex);
1076
- }
1077
- return '.js';
1078
- }
1079
- var patternMap = {};
1080
- var cacheMap = {};
1081
- /**
1082
- * Physically generate files as virtual modules under node_modules/__mf__virtual/*
1083
- */
1084
- function assertModuleFound(tag, str) {
1085
- if (str === void 0) {
1086
- str = '';
1087
- }
1088
- var module = VirtualModule.findModule(tag, str);
1089
- if (!module) {
1090
- throw new Error("Module Federation shared module '" + str + "' not found. Please ensure it's installed as a dependency in your package.json.");
1091
- }
1092
- return module;
1093
- }
1094
- var VirtualModule = /*#__PURE__*/function () {
1095
- function VirtualModule(name, tag, suffix) {
1096
- if (tag === void 0) {
1097
- tag = '__mf_v__';
1098
- }
1099
- if (suffix === void 0) {
1100
- suffix = '';
1101
- }
1102
- this.name = void 0;
1103
- this.tag = void 0;
1104
- this.suffix = void 0;
1105
- this.inited = false;
1106
- this.name = name;
1107
- this.tag = tag;
1108
- this.suffix = suffix || getSuffix(name);
1109
- if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
1110
- cacheMap[this.tag][this.name] = this;
1111
- }
1112
- /**
1113
- * Set the root path for finding node_modules
1114
- * @param root - Root path
1115
- */
1116
- VirtualModule.setRoot = function setRoot(root) {
1117
- rootDir = root;
1118
- // Reset cache to ensure using the new root path
1119
- cachedNodeModulesDir = undefined;
1120
- }
1121
- /**
1122
- * Ensure virtual package directory exists
1123
- */;
1124
- VirtualModule.ensureVirtualPackageExists = function ensureVirtualPackageExists() {
1125
- var nodeModulesDir = getNodeModulesDir();
1126
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
1127
- virtualModuleDir = _getNormalizeModuleFe.virtualModuleDir;
1128
- var virtualPackagePath = path.resolve(nodeModulesDir, virtualModuleDir);
1129
- if (!fs.existsSync(virtualPackagePath)) {
1130
- fs.mkdirSync(virtualPackagePath);
1131
- fs.writeFileSync(path.resolve(virtualPackagePath, 'empty.js'), '');
1132
- fs.writeFileSync(path.resolve(virtualPackagePath, 'package.json'), JSON.stringify({
1133
- name: virtualModuleDir,
1134
- main: 'empty.js'
1135
- }));
1136
- }
1137
- };
1138
- VirtualModule.findModule = function findModule(tag, str) {
1139
- if (str === void 0) {
1140
- str = '';
1141
- }
1142
- if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
1143
- var moduleName = (str.match(patternMap[tag]) || [])[2];
1144
- if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
1145
- return undefined;
1146
- };
1147
- var _proto = VirtualModule.prototype;
1148
- _proto.getPath = function getPath() {
1149
- return path.resolve(getNodeModulesDir(), this.getImportId());
1150
- };
1151
- _proto.getImportId = function getImportId() {
1152
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
1153
- mfName = _getNormalizeModuleFe2.name,
1154
- virtualModuleDir = _getNormalizeModuleFe2.virtualModuleDir;
1155
- return virtualModuleDir + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
1156
- };
1157
- _proto.writeSync = function writeSync(code, force) {
1158
- if (!force && this.inited) return;
1159
- if (!this.inited) {
1160
- this.inited = true;
1161
- }
1162
- fs.writeFileSync(this.getPath(), code);
1163
- };
1164
- _proto.write = function write(code) {
1165
- fs.writeFile(this.getPath(), code, function () {});
1166
- };
1167
- return VirtualModule;
1168
- }();
1169
-
1170
- var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
1171
- function generateExposes() {
1172
- var options = getNormalizeModuleFederationOptions();
1173
- return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
1174
- return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
1175
- }).join(',') + "\n }\n ";
1176
- }
1177
-
1178
- var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
1179
- function writeRuntimeInitStatus() {
1180
- // Use globalThis singleton to ensure only one initPromise exists
1181
- var globalKey = "__mf_init__" + virtualRuntimeInitStatus.getImportId() + "__";
1182
- virtualRuntimeInitStatus.writeSync("\n const globalKey = " + JSON.stringify(globalKey) + "\n if (!globalThis[globalKey]) {\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n globalThis[globalKey] = {\n initPromise,\n initResolve,\n initReject\n }\n }\n module.exports = globalThis[globalKey]\n ");
1183
- }
1184
-
1185
- var cacheRemoteMap = {};
1186
- var LOAD_REMOTE_TAG = '__loadRemote__';
1187
- function getRemoteVirtualModule(remote, command) {
1188
- if (!cacheRemoteMap[remote]) {
1189
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
1190
- cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
1191
- }
1192
- var virtual = cacheRemoteMap[remote];
1193
- return virtual;
1194
- }
1195
- var usedRemotesMap = {
1196
- // remote1: {remote1/App, remote1, remote1/Button}
1197
- };
1198
- function addUsedRemote(remoteKey, remoteModule) {
1199
- if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
1200
- usedRemotesMap[remoteKey].add(remoteModule);
1201
- }
1202
- function getUsedRemotesMap() {
1203
- return usedRemotesMap;
1204
- }
1205
- function generateRemotes(id, command) {
1206
- return "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
1207
- }
1208
-
1209
- /**
1210
- * Even the resolveId hook cannot interfere with vite pre-build,
1211
- * and adding query parameter virtual modules will also fail.
1212
- * You can only proxy to the real file through alias
1213
- */
1214
- // *** __prebuild__
1215
- var preBuildCacheMap = {};
1216
- var PREBUILD_TAG = '__prebuild__';
1217
- function writePreBuildLibPath(pkg) {
1218
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1219
- preBuildCacheMap[pkg].writeSync('');
1220
- }
1221
- function getPreBuildLibImportId(pkg) {
1222
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1223
- var importId = preBuildCacheMap[pkg].getImportId();
1224
- return importId;
1225
- }
1226
- // *** __loadShare__
1227
- var LOAD_SHARE_TAG = '__loadShare__';
1228
- var loadShareCacheMap = {};
1229
- function getLoadShareModulePath(pkg) {
1230
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
1231
- var filepath = loadShareCacheMap[pkg].getPath();
1232
- return filepath;
1233
- }
1234
- function writeLoadShareModule(pkg, shareItem, command) {
1235
- loadShareCacheMap[pkg].writeSync("\n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== 'build' ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}\n }))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "res.then(factory => factory())\n module.exports = exportModule\n ");
1236
- }
1237
-
1238
- var usedShares = new Set();
1239
- function getUsedShares() {
1240
- return usedShares;
1241
- }
1242
- function addUsedShares(pkg) {
1243
- usedShares.add(pkg);
1244
- }
1245
- // *** Expose locally provided shared modules here
1246
- new VirtualModule('localSharedImportMap');
1247
- function getLocalSharedImportMapPath() {
1248
- return getLocalSharedImportMapPath_temp();
1249
- // return localSharedImportMapModule.getPath()
1250
- }
1251
- var prevSharedCount;
1252
- function writeLocalSharedImportMap() {
1253
- var sharedCount = getUsedShares().size;
1254
- if (prevSharedCount !== sharedCount) {
1255
- prevSharedCount = sharedCount;
1256
- writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1257
- // localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true)
1258
- }
1259
- }
1260
- function generateLocalSharedImportMap() {
1261
- var options = getNormalizeModuleFederationOptions();
1262
- return "\n import {loadShare} from \"@module-federation/runtime\";\n const importMap = {\n " + Array.from(getUsedShares()).sort().map(function (pkg) {
1263
- var shareItem = getNormalizeShareItem(pkg);
1264
- return "\n " + JSON.stringify(pkg) + ": async () => {\n " + ((shareItem == null ? void 0 : shareItem.shareConfig["import"]) === false ? "throw new Error(`Shared module '${" + JSON.stringify(pkg) + "}' must be provided by host`);" : "let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\");\n return pkg;") + "\n }\n ";
1265
- }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).sort().map(function (key) {
1266
- var shareItem = getNormalizeShareItem(key);
1267
- if (!shareItem) return null;
1268
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n if (" + (shareItem.shareConfig["import"] === false) + ") {\n throw new Error(`Shared module '${" + JSON.stringify(key) + "}' must be provided by host`);\n }\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap\n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + ",\n " + (shareItem.shareConfig["import"] === false ? 'import: false,' : '') + "\n }\n }\n ";
1269
- }).filter(function (x) {
1270
- return x !== null;
1271
- }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
1272
- var _JSON$stringify;
1273
- var remote = options.remotes[key];
1274
- if (!remote) return null;
1275
- return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n shareScope: " + ((_JSON$stringify = JSON.stringify(remote.shareScope)) != null ? _JSON$stringify : 'default') + ",\n }\n ";
1276
- }).filter(function (x) {
1277
- return x !== null;
1278
- }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
1279
- }
1280
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1281
- function generateRemoteEntry(options) {
1282
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1283
- if (typeof p === 'string') {
1284
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1285
- } else {
1286
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1287
- }
1288
- });
1289
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1290
- return item[1];
1291
- }).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) {
1292
- return item[0] + "(" + item[2] + ")";
1293
- }).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 ";
1294
- }
1295
- /**
1296
- * Inject entry file, automatically init when used as host,
1297
- * and will not inject remoteEntry
1298
- */
1299
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
1300
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1301
- function writeHostAutoInit() {
1302
- 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 ");
1303
- }
1304
- function getHostAutoInitImportId() {
1305
- return hostAutoInitModule.getImportId();
1306
- }
1307
- function getHostAutoInitPath() {
1308
- return hostAutoInitModule.getPath();
1309
- }
1310
-
1311
- function initVirtualModules() {
1312
- writeLocalSharedImportMap();
1313
- writeHostAutoInit();
1314
- writeRuntimeInitStatus();
1315
- }
1316
-
1317
- function findRemoteEntryFile(filename, bundle) {
1318
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1319
- var _Object$entries$_i = _Object$entries[_i],
1320
- fileData = _Object$entries$_i[1];
1321
- if (filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1322
- return fileData.fileName; // We can return early since we only need to find remoteEntry once
1323
- }
1324
- }
1325
- }
1326
-
1327
- var ASSET_TYPES = ['js', 'css'];
1328
- var LOAD_TIMINGS = ['sync', 'async'];
1329
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1330
- /**
1331
- * Creates an empty asset map structure for tracking JS and CSS assets
1332
- * @returns Initialized asset map with sync/async arrays for JS and CSS
1333
- */
1334
- var createEmptyAssetMap = function createEmptyAssetMap() {
1335
- return {
1336
- js: {
1337
- sync: [],
1338
- async: []
1339
- },
1340
- css: {
1341
- sync: [],
1342
- async: []
1343
- }
1344
- };
1345
- };
1346
- /**
1347
- * Tracks an asset in the preload map with deduplication
1348
- * @param map - The preload map to update
1349
- * @param key - The module key to track under
1350
- * @param fileName - The asset filename to track
1351
- * @param isAsync - Whether the asset is loaded async
1352
- * @param type - The asset type ('js' or 'css')
1353
- */
1354
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1355
- if (!map[key]) {
1356
- map[key] = createEmptyAssetMap();
1357
- }
1358
- var target = isAsync ? map[key][type].async : map[key][type].sync;
1359
- if (!target.includes(fileName)) {
1360
- target.push(fileName);
1361
- }
1362
- };
1363
- /**
1364
- * Checks if a file is a CSS file by extension
1365
- * @param fileName - The filename to check
1366
- * @returns True if file has a CSS extension (.css, .scss, .less)
1367
- */
1368
- var isCSSFile = function isCSSFile(fileName) {
1369
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1370
- };
1371
- /**
1372
- * Collects all CSS assets from the bundle
1373
- * @param bundle - The Rollup output bundle
1374
- * @returns Set of CSS asset filenames
1375
- */
1376
- var collectCssAssets = function collectCssAssets(bundle) {
1377
- var cssAssets = new Set();
1378
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1379
- var _Object$entries$_i = _Object$entries[_i],
1380
- fileName = _Object$entries$_i[0],
1381
- fileData = _Object$entries$_i[1];
1382
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
1383
- cssAssets.add(fileName);
1384
- }
1385
- }
1386
- return cssAssets;
1387
- };
1388
- /**
1389
- * Processes module assets and tracks them in the files map
1390
- * @param bundle - The Rollup output bundle
1391
- * @param filesMap - The preload map to populate
1392
- * @param moduleMatcher - Function that matches module paths to keys
1393
- */
1394
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1395
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1396
- var _Object$entries2$_i = _Object$entries2[_i2],
1397
- fileName = _Object$entries2$_i[0],
1398
- fileData = _Object$entries2$_i[1];
1399
- if (fileData.type !== 'chunk') continue;
1400
- if (!fileData.modules) continue;
1401
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1402
- var modulePath = _Object$keys[_i3];
1403
- var matchKey = moduleMatcher(modulePath);
1404
- if (!matchKey) continue;
1405
- // Track main JS chunk
1406
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1407
- // Handle dynamic imports
1408
- if (fileData.dynamicImports) {
1409
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1410
- var dynamicImport = _step.value;
1411
- var importData = bundle[dynamicImport];
1412
- if (!importData) continue;
1413
- var isCss = isCSSFile(dynamicImport);
1414
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1415
- }
1416
- }
1417
- }
1418
- }
1419
- };
1420
- /**
1421
- * Deduplicates assets in the files map
1422
- * @param filesMap - The preload map to deduplicate
1423
- * @returns New deduplicated preload map
1424
- */
1425
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1426
- var result = {};
1427
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1428
- var _Object$entries3$_i = _Object$entries3[_i4],
1429
- key = _Object$entries3$_i[0],
1430
- assetMaps = _Object$entries3$_i[1];
1431
- result[key] = createEmptyAssetMap();
1432
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1433
- var type = _ASSET_TYPES[_i5];
1434
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1435
- var timing = _LOAD_TIMINGS[_i6];
1436
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1437
- }
1438
- }
1439
- }
1440
- return result;
1441
- };
1442
- /**
1443
- * Builds a mapping between module files and their share keys
1444
- * @param shareKeys - Set of share keys to map
1445
- * @param resolveFn - Function to resolve module paths
1446
- * @returns Map of file paths to their corresponding share keys
1447
- */
1448
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1449
- try {
1450
- var fileToShareKey = new Map();
1451
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1452
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1453
- var _resolution$id;
1454
- return {
1455
- shareKey: shareKey,
1456
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1457
- };
1458
- })["catch"](function () {
1459
- return null;
1460
- });
1461
- }))).then(function (resolutions) {
1462
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1463
- var resolution = _step2.value;
1464
- if (resolution != null && resolution.file) {
1465
- fileToShareKey.set(resolution.file, resolution.shareKey);
1466
- }
1467
- }
1468
- return fileToShareKey;
1469
- });
1470
- } catch (e) {
1471
- return Promise.reject(e);
1472
- }
1473
- };
1474
-
1475
- /**
1476
- * Resolves the public path for remote entries
1477
- * @param options - Module Federation options
1478
- * @param viteBase - Vite's base config value
1479
- * @param originalBase - Original base config before any transformations
1480
- * @returns The resolved public path
1481
- */
1482
- function resolvePublicPath(options, viteBase, originalBase) {
1483
- // Use explicitly set publicPath if provided
1484
- if (options.publicPath) {
1485
- return options.publicPath;
1486
- }
1487
- // Handle empty original base case
1488
- if (originalBase === '') {
1489
- return 'auto';
1490
- }
1491
- // Use viteBase if available, ensuring it ends with a slash
1492
- if (viteBase) {
1493
- return viteBase.replace(/\/?$/, '/');
1494
- }
1495
- // Fallback to auto if no base is specified
1496
- return 'auto';
1497
- }
1498
-
1499
- var Manifest = function Manifest() {
1500
- var mfOptions = getNormalizeModuleFederationOptions();
1501
- var name = mfOptions.name,
1502
- filename = mfOptions.filename,
1503
- getPublicPath = mfOptions.getPublicPath,
1504
- manifestOptions = mfOptions.manifest,
1505
- varFilename = mfOptions.varFilename;
1506
- var mfManifestName = '';
1507
- if (manifestOptions === true) {
1508
- mfManifestName = 'mf-manifest.json';
1509
- }
1510
- if (typeof manifestOptions !== 'boolean') {
1511
- mfManifestName = path__namespace.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1512
- }
1513
- var root;
1514
- var remoteEntryFile;
1515
- var publicPath;
1516
- var _command;
1517
- var _originalConfigBase;
1518
- var viteConfig;
1519
- /**
1520
- * Adds global CSS assets to all module exports
1521
- * @param filesMap - The preload map to update
1522
- * @param cssAssets - Set of CSS asset filenames to add
1523
- */
1524
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1525
- Object.keys(filesMap).forEach(function (key) {
1526
- cssAssets.forEach(function (cssAsset) {
1527
- trackAsset(filesMap, key, cssAsset, false, 'css');
1528
- });
1529
- });
1530
- };
1531
- return [{
1532
- name: 'module-federation-manifest',
1533
- apply: 'serve',
1534
- /**
1535
- * Stores resolved Vite config for later use
1536
- */
1537
- /**
1538
- * Finalizes configuration after all plugins are resolved
1539
- * @param config - Fully resolved Vite config
1540
- */
1541
- configResolved: function configResolved(config) {
1542
- viteConfig = config;
1543
- },
1544
- /**
1545
- * Configures dev server middleware to handle manifest requests
1546
- * @param server - Vite dev server instance
1547
- */
1548
- configureServer: function configureServer(server) {
1549
- server.middlewares.use(function (req, res, next) {
1550
- var _req$url;
1551
- if (!mfManifestName) {
1552
- next();
1553
- return;
1554
- }
1555
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1556
- res.setHeader('Content-Type', 'application/json');
1557
- res.setHeader('Access-Control-Allow-Origin', '*');
1558
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1559
- id: name,
1560
- name: name,
1561
- metaData: {
1562
- name: name,
1563
- type: 'app',
1564
- buildInfo: {
1565
- buildVersion: '1.0.0',
1566
- buildName: name
1567
- },
1568
- remoteEntry: {
1569
- name: filename,
1570
- path: '',
1571
- type: 'module'
1572
- },
1573
- ssrRemoteEntry: {
1574
- name: filename,
1575
- path: '',
1576
- type: 'module'
1577
- },
1578
- varRemoteEntry: varFilename ? {
1579
- name: varFilename,
1580
- path: '',
1581
- type: 'var'
1582
- } : undefined,
1583
- types: {
1584
- path: '',
1585
- name: ''
1586
- },
1587
- globalName: name,
1588
- pluginVersion: '0.2.5',
1589
- publicPath: publicPath
1590
- }
1591
- })));
1592
- } else {
1593
- next();
1594
- }
1595
- });
1596
- }
1597
- }, {
1598
- name: 'module-federation-manifest',
1599
- enforce: 'post',
1600
- /**
1601
- * Initial plugin configuration
1602
- * @param config - Vite config object
1603
- * @param command - Current Vite command (serve/build)
1604
- */
1605
- config: function config(_config, _ref) {
1606
- var command = _ref.command;
1607
- if (!_config.build) _config.build = {};
1608
- if (!_config.build.manifest) {
1609
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1610
- }
1611
- _command = command;
1612
- _originalConfigBase = _config.base;
1613
- },
1614
- configResolved: function configResolved(config) {
1615
- root = config.root;
1616
- var base = config.base;
1617
- if (_command === 'serve') {
1618
- base = (config.server.origin || '') + config.base;
1619
- }
1620
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1621
- },
1622
- /**
1623
- * Generates the module federation manifest file
1624
- * @param options - Rollup output options
1625
- * @param bundle - Generated bundle assets
1626
- */
1627
- generateBundle: function generateBundle(options, bundle) {
1628
- try {
1629
- var _this = this;
1630
- if (!mfManifestName) return Promise.resolve();
1631
- var filesMap = {};
1632
- var foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1633
- // First pass: Find remoteEntry file
1634
- if (foundRemoteEntryFile) {
1635
- remoteEntryFile = foundRemoteEntryFile;
1636
- }
1637
- // Second pass: Collect all CSS assets
1638
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1639
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1640
- return mfOptions.exposes[item]["import"];
1641
- });
1642
- // Process exposed modules
1643
- processModuleAssets(bundle, filesMap, function (modulePath) {
1644
- var absoluteModulePath = path__namespace.resolve(root, modulePath);
1645
- return exposesModules.find(function (exposeModule) {
1646
- var exposePath = path__namespace.resolve(root, exposeModule);
1647
- // First try exact path match
1648
- if (absoluteModulePath === exposePath) {
1649
- return true;
1650
- }
1651
- // Then try path match without known extensions
1652
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1653
- var ext = path__namespace.extname(filePath);
1654
- return JS_EXTENSIONS.includes(ext) ? path__namespace.join(path__namespace.dirname(filePath), path__namespace.basename(filePath, ext)) : filePath;
1655
- };
1656
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1657
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1658
- return modulePathNoExt === exposePathNoExt;
1659
- });
1660
- });
1661
- // Process shared modules
1662
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1663
- processModuleAssets(bundle, filesMap, function (modulePath) {
1664
- return fileToShareKey.get(modulePath);
1665
- });
1666
- // Add all CSS assets to every export if bundleAllCSS is enabled
1667
- if (mfOptions.bundleAllCSS) {
1668
- addCssAssetsToAllExports(filesMap, allCssAssets);
1669
- }
1670
- // Final deduplication of all assets
1671
- filesMap = deduplicateAssets(filesMap);
1672
- _this.emitFile({
1673
- type: 'asset',
1674
- fileName: mfManifestName,
1675
- source: JSON.stringify(generateMFManifest(filesMap))
1676
- });
1677
- });
1678
- } catch (e) {
1679
- return Promise.reject(e);
1680
- }
1681
- }
1682
- }];
1683
- /**
1684
- * Generates the final manifest JSON structure
1685
- * @param preloadMap - Map of module assets to include
1686
- * @returns Complete manifest object
1687
- */
1688
- function generateMFManifest(preloadMap) {
1689
- var options = getNormalizeModuleFederationOptions();
1690
- var name = options.name,
1691
- varFilename = options.varFilename;
1692
- var remoteEntry = {
1693
- name: remoteEntryFile,
1694
- path: '',
1695
- type: 'module'
1696
- };
1697
- var varRemoteEntry = varFilename ? {
1698
- name: varFilename,
1699
- path: '',
1700
- type: 'module'
1701
- } : undefined;
1702
- // Process remotes
1703
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1704
- var remoteKey = _ref2[0],
1705
- modules = _ref2[1];
1706
- return Array.from(modules).map(function (moduleKey) {
1707
- return {
1708
- federationContainerName: options.remotes[remoteKey].entry,
1709
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1710
- alias: remoteKey,
1711
- entry: '*'
1712
- };
1713
- });
1714
- });
1715
- // Process shared dependencies
1716
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1717
- var shareItem = getNormalizeShareItem(shareKey);
1718
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1719
- return {
1720
- id: name + ":" + shareKey,
1721
- name: shareKey,
1722
- version: shareItem.version,
1723
- requiredVersion: shareItem.shareConfig.requiredVersion,
1724
- assets: {
1725
- js: {
1726
- async: assets.js.async,
1727
- sync: assets.js.sync
1728
- },
1729
- css: {
1730
- async: assets.css.async,
1731
- sync: assets.css.sync
1732
- }
1733
- }
1734
- };
1735
- }).filter(Boolean);
1736
- // Process exposed modules
1737
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1738
- var key = _ref3[0],
1739
- value = _ref3[1];
1740
- var formatKey = key.replace('./', '');
1741
- var sourceFile = value["import"];
1742
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1743
- return {
1744
- id: name + ":" + formatKey,
1745
- name: formatKey,
1746
- assets: {
1747
- js: {
1748
- async: assets.js.async,
1749
- sync: assets.js.sync
1750
- },
1751
- css: {
1752
- async: assets.css.async,
1753
- sync: assets.css.sync
1754
- }
1755
- },
1756
- path: key
1757
- };
1758
- }).filter(Boolean);
1759
- return {
1760
- id: name,
1761
- name: name,
1762
- metaData: _extends({
1763
- name: name,
1764
- type: 'app',
1765
- buildInfo: {
1766
- buildVersion: '1.0.0',
1767
- buildName: name
1768
- },
1769
- remoteEntry: remoteEntry,
1770
- ssrRemoteEntry: remoteEntry,
1771
- varRemoteEntry: varRemoteEntry,
1772
- types: {
1773
- path: '',
1774
- name: ''
1775
- },
1776
- globalName: name,
1777
- pluginVersion: '0.2.5'
1778
- }, !!getPublicPath ? {
1779
- getPublicPath: getPublicPath
1780
- } : {
1781
- publicPath: publicPath
1782
- }),
1783
- shared: shared,
1784
- remotes: remotes,
1785
- exposes: exposes
1786
- };
1787
- }
1788
- };
1789
-
1790
- var _resolve, _parseTimeout;
1791
- var promise = new Promise(function (resolve, reject) {
1792
- _resolve = function _resolve(v) {
1793
- clearTimeout(_parseTimeout);
1794
- _parseTimeout = null;
1795
- resolve(v);
1796
- };
1797
- });
1798
- function setParseTimeout(timeout) {
1799
- if (!_parseTimeout) {
1800
- _parseTimeout = setTimeout(function () {
1801
- console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1802
- _resolve(1);
1803
- }, timeout * 1000);
1804
- }
1805
- }
1806
- var parsePromise = promise;
1807
- var exposesParseEnd = false;
1808
- var parseStartSet = new Set();
1809
- var parseEndSet = new Set();
1810
- function pluginModuleParseEnd (excludeFn, options) {
1811
- setParseTimeout(options.moduleParseTimeout);
1812
- return [{
1813
- name: '_',
1814
- apply: 'serve',
1815
- config: function config() {
1816
- // No waiting in development mode
1817
- _resolve(1);
1818
- }
1819
- }, {
1820
- enforce: 'pre',
1821
- name: 'parseStart',
1822
- apply: 'build',
1823
- load: function load(id) {
1824
- if (excludeFn(id)) {
1825
- return;
1826
- }
1827
- parseStartSet.add(id);
1828
- }
1829
- }, {
1830
- enforce: 'post',
1831
- name: 'parseEnd',
1832
- apply: 'build',
1833
- moduleParsed: function moduleParsed(module) {
1834
- var id = module.id;
1835
- if (id === VIRTUAL_EXPOSES) {
1836
- // 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.
1837
- exposesParseEnd = true;
1838
- }
1839
- if (excludeFn(id)) {
1840
- return;
1841
- }
1842
- parseEndSet.add(id);
1843
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1844
- _resolve(1);
1845
- }
1846
- }
1847
- }];
1848
- }
1849
-
1850
- var filter = pluginutils.createFilter();
1851
- function pluginProxyRemoteEntry () {
1852
- var viteConfig, _command;
1853
- return {
1854
- name: 'proxyRemoteEntry',
1855
- enforce: 'post',
1856
- configResolved: function configResolved(config) {
1857
- viteConfig = config;
1858
- },
1859
- config: function config(_config, _ref) {
1860
- var command = _ref.command;
1861
- _command = command;
1862
- },
1863
- resolveId: function resolveId(id) {
1864
- if (id === REMOTE_ENTRY_ID) {
1865
- return REMOTE_ENTRY_ID;
1866
- }
1867
- if (id === VIRTUAL_EXPOSES) {
1868
- return VIRTUAL_EXPOSES;
1869
- }
1870
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1871
- return id;
1872
- }
1873
- },
1874
- load: function load(id) {
1875
- if (id === REMOTE_ENTRY_ID) {
1876
- return parsePromise.then(function (_) {
1877
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1878
- });
1879
- }
1880
- if (id === VIRTUAL_EXPOSES) {
1881
- return generateExposes();
1882
- }
1883
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1884
- return id;
1885
- }
1886
- },
1887
- transform: function transform(code, id) {
1888
- var transformedCode = function () {
1889
- if (!filter(id)) return;
1890
- if (id.includes(REMOTE_ENTRY_ID)) {
1891
- return parsePromise.then(function (_) {
1892
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1893
- });
1894
- }
1895
- if (id === VIRTUAL_EXPOSES) {
1896
- return generateExposes();
1897
- }
1898
- if (id.includes(getHostAutoInitPath())) {
1899
- var options = getNormalizeModuleFederationOptions();
1900
- if (_command === 'serve') {
1901
- var _viteConfig$server, _viteConfig$server2;
1902
- 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';
1903
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1904
- 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 ";
1905
- }
1906
- return code;
1907
- }
1908
- }();
1909
- return mapCodeToCodeWithSourcemap(transformedCode);
1910
- }
1911
- };
1912
- }
1913
-
1914
- pluginutils.createFilter();
1915
- function pluginProxyRemotes (options) {
1916
- var remotes = options.remotes;
1917
- return {
1918
- name: 'proxyRemotes',
1919
- config: function config(_config, _ref) {
1920
- var _command = _ref.command;
1921
- Object.keys(remotes).forEach(function (key) {
1922
- var remote = remotes[key];
1923
- _config.resolve.alias.push({
1924
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1925
- replacement: '$1',
1926
- customResolver: function customResolver(source) {
1927
- var remoteModule = getRemoteVirtualModule(source, _command);
1928
- addUsedRemote(remote.name, source);
1929
- return remoteModule.getPath();
1930
- }
1931
- });
1932
- });
1933
- }
1934
- };
1935
- }
1936
-
1937
- /**
1938
- * example:
1939
- * const store = new PromiseStore<number>();
1940
- * store.get("example").then((result) => {
1941
- * console.log("Result from example:", result); // 42
1942
- * });
1943
- * setTimeout(() => {
1944
- * store.set("example", Promise.resolve(42));
1945
- * }, 2000);
1946
- */
1947
- var PromiseStore = /*#__PURE__*/function () {
1948
- function PromiseStore() {
1949
- this.promiseMap = new Map();
1950
- this.resolveMap = new Map();
1951
- }
1952
- var _proto = PromiseStore.prototype;
1953
- _proto.set = function set(id, promise) {
1954
- if (this.resolveMap.has(id)) {
1955
- promise.then(this.resolveMap.get(id));
1956
- this.resolveMap["delete"](id);
1957
- }
1958
- this.promiseMap.set(id, promise);
1959
- };
1960
- _proto.get = function get(id) {
1961
- var _this = this;
1962
- if (this.promiseMap.has(id)) {
1963
- return this.promiseMap.get(id);
1964
- }
1965
- var pendingPromise = new Promise(function (resolve) {
1966
- _this.resolveMap.set(id, resolve);
1967
- });
1968
- this.promiseMap.set(id, pendingPromise);
1969
- return pendingPromise;
1970
- };
1971
- return PromiseStore;
1972
- }();
1973
-
1974
- function proxySharedModule(options) {
1975
- var _options$shared = options.shared,
1976
- shared = _options$shared === void 0 ? {} : _options$shared;
1977
- var _config;
1978
- return [{
1979
- name: 'generateLocalSharedImportMap',
1980
- enforce: 'post',
1981
- load: function load(id) {
1982
- if (id.includes(getLocalSharedImportMapPath())) {
1983
- return parsePromise.then(function (_) {
1984
- return generateLocalSharedImportMap();
1985
- });
1986
- }
1987
- },
1988
- transform: function transform(_, id) {
1989
- if (id.includes(getLocalSharedImportMapPath())) {
1990
- return mapCodeToCodeWithSourcemap(parsePromise.then(function (_) {
1991
- return generateLocalSharedImportMap();
1992
- }));
1993
- }
1994
- }
1995
- }, {
1996
- name: 'proxyPreBuildShared',
1997
- enforce: 'post',
1998
- configResolved: function configResolved(config) {
1999
- _config = config;
2000
- },
2001
- config: function config(_config2, _ref) {
2002
- var _config2$resolve$alia, _config2$resolve$alia2;
2003
- var command = _ref.command;
2004
- (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
2005
- var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
2006
- return {
2007
- // Intercept all shared requests and proxy them to loadShare
2008
- find: new RegExp(pattern),
2009
- replacement: '$1',
2010
- customResolver: function customResolver(source, importer) {
2011
- if (/\.css$/.test(source)) return;
2012
- var loadSharePath = getLoadShareModulePath(source);
2013
- writeLoadShareModule(source, shared[key], command);
2014
- writePreBuildLibPath(source);
2015
- addUsedShares(source);
2016
- writeLocalSharedImportMap();
2017
- return this.resolve(loadSharePath, importer);
2018
- }
2019
- };
2020
- }));
2021
- var savePrebuild = new PromiseStore();
2022
- (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
2023
- return command === 'build' ? {
2024
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
2025
- replacement: function replacement($1) {
2026
- var module = assertModuleFound(PREBUILD_TAG, $1);
2027
- var pkgName = module.name;
2028
- return pkgName;
2029
- }
2030
- } : {
2031
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
2032
- replacement: '$1',
2033
- customResolver: function customResolver(source, importer) {
2034
- try {
2035
- var _this = this;
2036
- var module = assertModuleFound(PREBUILD_TAG, source);
2037
- var pkgName = module.name;
2038
- return Promise.resolve(_this.resolve(pkgName, importer).then(function (item) {
2039
- return item.id;
2040
- })).then(function (result) {
2041
- if (!result.includes(_config.cacheDir)) {
2042
- // save pre-bunding module id
2043
- savePrebuild.set(pkgName, Promise.resolve(result));
2044
- }
2045
- // Fix localSharedImportMap import id
2046
- var _resolve = _this.resolve;
2047
- return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
2048
- return Promise.resolve(_resolve.call(_this, _savePrebuild$get, importer));
2049
- });
2050
- });
2051
- } catch (e) {
2052
- return Promise.reject(e);
2053
- }
2054
- }
2055
- };
2056
- }));
2057
- }
2058
- }];
2059
- }
2060
-
2061
- var VarRemoteEntry = function VarRemoteEntry() {
2062
- var mfOptions = getNormalizeModuleFederationOptions();
2063
- var name = mfOptions.name,
2064
- varFilename = mfOptions.varFilename,
2065
- filename = mfOptions.filename;
2066
- var viteConfig;
2067
- return [{
2068
- name: 'module-federation-var-remote-entry',
2069
- apply: 'serve',
2070
- /**
2071
- * Stores resolved Vite config for later use
2072
- */
2073
- /**
2074
- * Finalizes configuration after all plugins are resolved
2075
- * @param config - Fully resolved Vite config
2076
- */
2077
- configResolved: function configResolved(config) {
2078
- viteConfig = config;
2079
- },
2080
- /**
2081
- * Configures dev server middleware to handle varRemoteEntry requests
2082
- * @param server - Vite dev server instance
2083
- */
2084
- configureServer: function configureServer(server) {
2085
- server.middlewares.use(function (req, res, next) {
2086
- var _req$url;
2087
- if (!varFilename) {
2088
- next();
2089
- return;
2090
- }
2091
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + varFilename).replace(/^\/?/, '/')) {
2092
- res.setHeader('Content-Type', 'text/javascript');
2093
- res.setHeader('Access-Control-Allow-Origin', '*');
2094
- console.log({
2095
- filename: filename
2096
- });
2097
- res.end(generateVarRemoteEntry(filename));
2098
- } else {
2099
- next();
2100
- }
2101
- });
2102
- }
2103
- }, {
2104
- name: 'module-federation-var-remote-entry',
2105
- enforce: 'post',
2106
- /**
2107
- * Initial plugin configuration
2108
- * @param config - Vite config object
2109
- * @param command - Current Vite command (serve/build)
2110
- */
2111
- config: function config(_config, _ref) {
2112
- if (!_config.build) _config.build = {};
2113
- },
2114
- /**
2115
- * Generates the module federation "var" remote entry file
2116
- * @param options - Rollup output options
2117
- * @param bundle - Generated bundle assets
2118
- */
2119
- generateBundle: function generateBundle(options, bundle) {
2120
- try {
2121
- var _this = this;
2122
- if (!varFilename) return Promise.resolve();
2123
- var isValidName = isValidVarName(name);
2124
- if (!isValidName) {
2125
- 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).");
2126
- }
2127
- var remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
2128
- if (!remoteEntryFile) throw new Error("Couldn't find a remoteEntry chunk file for " + mfOptions.filename + ", can't generate varRemoteEntry file");
2129
- _this.emitFile({
2130
- type: 'asset',
2131
- fileName: varFilename,
2132
- source: generateVarRemoteEntry(remoteEntryFile)
2133
- });
2134
- return Promise.resolve();
2135
- } catch (e) {
2136
- return Promise.reject(e);
2137
- }
2138
- }
2139
- }];
2140
- function isValidVarName(name) {
2141
- return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
2142
- }
2143
- /**
2144
- * Generates the final "var" remote entry file
2145
- * @param remoteEntryFile - Path to esm remote entry file
2146
- * @returns Complete "var" remoteEntry.js file source
2147
- */
2148
- function generateVarRemoteEntry(remoteEntryFile) {
2149
- var options = getNormalizeModuleFederationOptions();
2150
- var name = options.name,
2151
- varFilename = options.varFilename;
2152
- var isValidName = isValidVarName(name);
2153
- // todo: implement publicPath/getPublicPath support
2154
- 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 ";
2155
- }
2156
- };
2157
-
2158
- var aliasToArrayPlugin = {
2159
- name: 'alias-transform-plugin',
2160
- config: function config(_config, _ref) {
2161
- if (!_config.resolve) _config.resolve = {};
2162
- if (!_config.resolve.alias) _config.resolve.alias = [];
2163
- var alias = _config.resolve.alias;
2164
- if (typeof alias === 'object' && !Array.isArray(alias)) {
2165
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
2166
- var find = _ref2[0],
2167
- replacement = _ref2[1];
2168
- return {
2169
- find: find,
2170
- replacement: replacement
2171
- };
2172
- });
2173
- }
2174
- }
2175
- };
2176
-
2177
- var normalizeOptimizeDepsPlugin = {
2178
- name: 'normalizeOptimizeDeps',
2179
- config: function config(_config, _ref) {
2180
- var optimizeDeps = _config.optimizeDeps;
2181
- if (!optimizeDeps) {
2182
- _config.optimizeDeps = {};
2183
- optimizeDeps = _config.optimizeDeps;
2184
- }
2185
- // todo: fix this workaround
2186
- optimizeDeps.force = true;
2187
- if (!optimizeDeps.include) optimizeDeps.include = [];
2188
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
2189
- }
2190
- };
2191
-
2192
- function federation(mfUserOptions) {
2193
- var options = normalizeModuleFederationOptions(mfUserOptions);
2194
- var name = options.name,
2195
- shared = options.shared,
2196
- filename = options.filename,
2197
- hostInitInjectLocation = options.hostInitInjectLocation;
2198
- if (!name) throw new Error('name is required');
2199
- return [{
2200
- name: 'vite:module-federation-config',
2201
- enforce: 'pre',
2202
- configResolved: function configResolved(config) {
2203
- // Set root path
2204
- VirtualModule.setRoot(config.root);
2205
- // Ensure virtual package directory exists
2206
- VirtualModule.ensureVirtualPackageExists();
2207
- initVirtualModules();
2208
- }
2209
- }, aliasToArrayPlugin, checkAliasConflicts({
2210
- shared: shared
2211
- }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
2212
- entryName: 'remoteEntry',
2213
- entryPath: REMOTE_ENTRY_ID,
2214
- fileName: filename
2215
- }), addEntry({
2216
- entryName: 'hostInit',
2217
- entryPath: getHostAutoInitPath(),
2218
- inject: hostInitInjectLocation
2219
- }), addEntry({
2220
- entryName: 'virtualExposes',
2221
- entryPath: VIRTUAL_EXPOSES
2222
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2223
- return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2224
- }, {
2225
- moduleParseTimeout: options.moduleParseTimeout
2226
- }), proxySharedModule({
2227
- shared: shared
2228
- }), [PluginDevProxyModuleTopLevelAwait(), {
2229
- name: 'module-federation-vite',
2230
- enforce: 'post',
2231
- // @ts-expect-error
2232
- // used to expose plugin options: https://github.com/rolldown/rolldown/discussions/2577#discussioncomment-11137593
2233
- _options: options,
2234
- config: function config(_config, _ref) {
2235
- var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3, _config$optimizeDeps4;
2236
- // TODO: singleton
2237
- _config.resolve.alias.push({
2238
- find: '@module-federation/runtime',
2239
- replacement: options.implementation
2240
- });
2241
- _config.build = defu__default["default"](_config.build || {}, {
2242
- commonjsOptions: {
2243
- strictRequires: 'auto'
2244
- }
2245
- });
2246
- var virtualDir = options.virtualModuleDir || '__mf__virtual';
2247
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
2248
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(virtualDir);
2249
- (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2250
- (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2251
- }
2252
- }], Manifest(), VarRemoteEntry());
2253
- }
2254
-
2255
- exports.federation = federation;
2256
-
2257
- }));