@module-federation/vite 1.11.0 → 1.11.1

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