@module-federation/vite 1.20.0 → 1.20.2

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.
@@ -1,845 +0,0 @@
1
- import "node:module";
2
- import fs, { existsSync, readFileSync, readdirSync } from "fs";
3
- import { createRequire as createRequire$1 } from "module";
4
- import * as path$1 from "node:path";
5
- import { fileURLToPath, pathToFileURL } from "url";
6
- import { normalizeOptions } from "@module-federation/sdk";
7
- import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
8
- import { rpc } from "@module-federation/dts-plugin/core";
9
- //#region \0rolldown/runtime.js
10
- var __defProp = Object.defineProperty;
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
13
- for (var name in all) __defProp(target, name, {
14
- get: all[name],
15
- enumerable: true
16
- });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
19
- };
20
- //#endregion
21
- //#region src/utils/buildPaths.ts
22
- /**
23
- * Rebase an import path for a bootstrap file that moved from root into `dir`.
24
- *
25
- * When entryFileNames places entries in a subdirectory (e.g. `static/js/`),
26
- * the bootstrap file moves there too. Paths that resolved from the HTML root
27
- * must resolve from the new directory instead.
28
- *
29
- * Cases: `/static/js/hostInit.js` → `./hostInit.js` (strip dir prefix)
30
- * `./src/main.tsx` → `../../src/main.tsx` (climb back up for each dir level)
31
- * `https://cdn.example.com` → unchanged (absolute URL)
32
- */
33
- function rebaseImport(importSrc, dir) {
34
- if (!dir) return importSrc;
35
- if (isAbsoluteUrl(importSrc)) return importSrc;
36
- const normalizedDir = dir.replace(/^\/+|\/+$/g, "");
37
- if (!normalizedDir) return importSrc;
38
- const stripDirPrefix = (src, prefix) => {
39
- if (src === prefix) return "";
40
- if (src.startsWith(prefix + "/")) return src.slice(prefix.length);
41
- };
42
- const absoluteRemainder = stripDirPrefix(importSrc, "/" + normalizedDir);
43
- if (absoluteRemainder !== void 0) {
44
- const remainder = absoluteRemainder.replace(/^\/+/, "");
45
- return remainder ? "./" + remainder : "./";
46
- }
47
- const relativeRemainder = stripDirPrefix(importSrc, normalizedDir);
48
- if (relativeRemainder !== void 0) {
49
- const remainder = relativeRemainder.replace(/^\/+/, "");
50
- return remainder ? "./" + remainder : "./";
51
- }
52
- const upLevels = normalizedDir.split("/").filter(Boolean).length;
53
- const prefix = upLevels > 0 ? "../".repeat(upLevels) : "./";
54
- if (importSrc.startsWith("./")) return prefix + importSrc.slice(2);
55
- if (importSrc.startsWith("/")) return prefix + importSrc.slice(1);
56
- return prefix + importSrc;
57
- }
58
- function normalizePathForImport(path) {
59
- return path.replace(/\\/g, "/");
60
- }
61
- const EXTERNAL_URL_RE = /^(?:[a-z]+:|\/\/)/i;
62
- function isAbsoluteUrl(src) {
63
- if (/^[a-z]:[\\/]/i.test(src)) return false;
64
- return EXTERNAL_URL_RE.test(src);
65
- }
66
- //#endregion
67
- //#region src/utils/logger.ts
68
- const MODULE_FEDERATION_LOG_PREFIX = "[Module Federation]";
69
- function formatModuleFederationMessage(message) {
70
- return `${MODULE_FEDERATION_LOG_PREFIX} ${message}`;
71
- }
72
- function createModuleFederationError(message) {
73
- return new Error(formatModuleFederationMessage(message));
74
- }
75
- function toConsoleArgs(message, rest = []) {
76
- if (typeof message === "string") return [formatModuleFederationMessage(message), ...rest];
77
- if (message === void 0) return [MODULE_FEDERATION_LOG_PREFIX, ...rest];
78
- return [
79
- MODULE_FEDERATION_LOG_PREFIX,
80
- message,
81
- ...rest
82
- ];
83
- }
84
- const moduleFederationConsole = {
85
- log(message, ...rest) {
86
- console.log(...toConsoleArgs(message, rest));
87
- },
88
- warn(message, ...rest) {
89
- console.warn(...toConsoleArgs(message, rest));
90
- },
91
- error(message, ...rest) {
92
- console.error(...toConsoleArgs(message, rest));
93
- }
94
- };
95
- moduleFederationConsole.log;
96
- const mfWarn = moduleFederationConsole.warn;
97
- const mfError = moduleFederationConsole.error;
98
- //#endregion
99
- //#region src/utils/packageUtils.ts
100
- const dependencyPresenceCache = /* @__PURE__ */ new Map();
101
- let packageDetectionCwd;
102
- function getDependencyCacheKey(cwd, dependencyName) {
103
- return `${cwd}:${dependencyName}`;
104
- }
105
- const installedPackageJsonCache = /* @__PURE__ */ new Map();
106
- function setPackageDetectionCwd(cwd) {
107
- packageDetectionCwd = cwd;
108
- }
109
- function getPackageDetectionCwd() {
110
- return packageDetectionCwd || process.cwd();
111
- }
112
- function resolveImportPath(specifier) {
113
- const resolved = import.meta.resolve(specifier);
114
- if (!resolved.startsWith("file:")) return resolved;
115
- const filePath = fileURLToPath(resolved);
116
- if (!existsSync(filePath)) {
117
- const error = /* @__PURE__ */ new Error(`Cannot find module '${specifier}'`);
118
- error.code = "MODULE_NOT_FOUND";
119
- throw error;
120
- }
121
- return filePath;
122
- }
123
- const DEFAULT_EXPORT_CONDITIONS = [
124
- "browser",
125
- "import",
126
- "module",
127
- "default"
128
- ];
129
- function resolveExportsEntry(exportsField, conditions = DEFAULT_EXPORT_CONDITIONS) {
130
- return resolveExportsEntryWithConditions(exportsField, new Set(conditions));
131
- }
132
- function resolveExportsEntryWithConditions(exportsField, conditions) {
133
- if (typeof exportsField === "string") return exportsField;
134
- if (!exportsField || typeof exportsField !== "object") return void 0;
135
- if (Array.isArray(exportsField)) {
136
- for (const target of exportsField) {
137
- const resolved = resolveExportsEntryWithConditions(target, conditions);
138
- if (resolved) return resolved;
139
- }
140
- return;
141
- }
142
- const record = exportsField;
143
- const rootExport = record["."];
144
- if (rootExport) return resolveExportsEntryWithConditions(rootExport, conditions);
145
- for (const [condition, value] of Object.entries(record)) {
146
- if (condition !== "default" && !conditions.has(condition)) continue;
147
- const target = resolveExportsEntryWithConditions(value, conditions);
148
- if (target) return target;
149
- }
150
- }
151
- function substituteExportsWildcard(target, patternMatch) {
152
- if (typeof target === "string") return target.split("*").join(patternMatch);
153
- if (Array.isArray(target)) return target.map((entry) => substituteExportsWildcard(entry, patternMatch));
154
- if (target && typeof target === "object") {
155
- const source = target;
156
- const out = {};
157
- for (const key of Object.keys(source)) out[key] = substituteExportsWildcard(source[key], patternMatch);
158
- return out;
159
- }
160
- return target;
161
- }
162
- function matchExportsSubpath(record, subpath) {
163
- if (subpath in record) return record[subpath];
164
- let bestKey;
165
- let bestBaseLength = -1;
166
- let bestKeyLength = -1;
167
- for (const key of Object.keys(record)) {
168
- const wildcardIndex = key.indexOf("*");
169
- if (wildcardIndex === -1) continue;
170
- const patternBase = key.slice(0, wildcardIndex);
171
- const patternTrailer = key.slice(wildcardIndex + 1);
172
- if (patternTrailer.includes("*")) continue;
173
- if (!subpath.startsWith(patternBase) || !subpath.endsWith(patternTrailer)) continue;
174
- if (subpath.length <= patternBase.length + patternTrailer.length) continue;
175
- if (patternBase.length > bestBaseLength || patternBase.length === bestBaseLength && key.length > bestKeyLength) {
176
- bestKey = key;
177
- bestBaseLength = patternBase.length;
178
- bestKeyLength = key.length;
179
- }
180
- }
181
- if (bestKey === void 0) return void 0;
182
- const patternTrailer = bestKey.slice(bestKey.indexOf("*") + 1);
183
- const patternMatch = subpath.slice(bestBaseLength, subpath.length - patternTrailer.length);
184
- return substituteExportsWildcard(record[bestKey], patternMatch);
185
- }
186
- function getPackageExportsTarget(pkg, packageName, exportsField) {
187
- if (typeof exportsField === "string") return pkg === packageName ? exportsField : void 0;
188
- if (!exportsField || typeof exportsField !== "object") return void 0;
189
- const record = exportsField;
190
- const subpath = pkg === packageName ? "." : `.${pkg.slice(packageName.length)}`;
191
- if (subpath !== ".") return matchExportsSubpath(record, subpath);
192
- return record["."] ?? (!Object.keys(record).some((key) => key.startsWith(".")) ? record : void 0);
193
- }
194
- /**
195
- * Escaping rules:
196
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
197
- * @ => 1
198
- * / => 2
199
- * - => 3
200
- * . => 4
201
- */
202
- /**
203
- * Encodes a package name into a valid file name.
204
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
205
- * @returns {string} - The encoded file name.
206
- */
207
- function packageNameEncode(name) {
208
- if (typeof name !== "string") throw createModuleFederationError("A string package name is required");
209
- return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
210
- }
211
- /**
212
- * Decodes an encoded file name back to the original package name.
213
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
214
- * @returns {string} - The decoded package name.
215
- */
216
- function packageNameDecode(encoded) {
217
- if (typeof encoded !== "string") throw createModuleFederationError("A string encoded file name is required");
218
- return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
219
- }
220
- /**
221
- * Removes any subpath from an npm package specifier and returns the package name only.
222
- * @param {string} packageString - The package specifier, e.g., "@scope/pkg/runtime" or "react/jsx-runtime".
223
- * @returns {string} - The base npm package name.
224
- */
225
- function getPackageName(packageString) {
226
- const match = packageString.match(/^(?:@[^/]+\/)?[^/]+/);
227
- return match ? match[0] : packageString;
228
- }
229
- function getPackageNameFromNodeModulePath(source) {
230
- const normalized = source.replace(/\\/g, "/");
231
- const nodeModulesIndex = normalized.lastIndexOf("/node_modules/");
232
- if (nodeModulesIndex < 0) return;
233
- const parts = normalized.slice(nodeModulesIndex + 14).split("/");
234
- if (!parts[0]) return;
235
- if (parts[0].startsWith("@")) return parts[1] ? `${parts[0]}/${parts[1]}` : void 0;
236
- return parts[0];
237
- }
238
- function getSharedCacheKeyParts(input) {
239
- const scope = (Array.isArray(input.scope) ? input.scope[0] : input.scope) || "default";
240
- const id = input.singleton || !input.version ? input.pkg : `${input.pkg}@${input.version}`;
241
- return {
242
- scope,
243
- id,
244
- key: `${scope}:${id}`
245
- };
246
- }
247
- function getSharedCacheDescriptor(pkg, shareItem) {
248
- const parts = getSharedCacheKeyParts({
249
- pkg,
250
- singleton: shareItem.shareConfig.singleton,
251
- version: shareItem.version,
252
- scope: shareItem.scope
253
- });
254
- return {
255
- canonical: parts.key,
256
- ...parts.scope === "default" ? { aliases: [parts.id] } : {}
257
- };
258
- }
259
- const sharedCacheHelperCode = `const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
260
- const normalizedScope = Array.isArray(scope) ? scope[0] : scope;
261
- const scopeName = normalizedScope || "default";
262
- const id = singleton || !version ? pkg : pkg + "@" + version;
263
- const descriptor = { canonical: scopeName + ":" + id };
264
- if (scopeName === "default") descriptor.aliases = [id];
265
- return descriptor;
266
- };
267
- const __mfReadSharedCache = (cache, descriptor) => {
268
- const value = cache[descriptor.canonical];
269
- if (value !== undefined) return value;
270
- const aliases = descriptor.aliases || [];
271
- for (const alias of aliases) {
272
- if (!Object.prototype.hasOwnProperty.call(cache, alias)) continue;
273
- const aliasValue = cache[alias];
274
- if (aliasValue !== undefined) {
275
- cache[descriptor.canonical] = aliasValue;
276
- return aliasValue;
277
- }
278
- }
279
- return undefined;
280
- };
281
- const __mfSharedCacheListenersKey = Symbol.for("module-federation.shared-cache-listeners");
282
- const __mfGetSharedCacheListeners = (cache) => {
283
- let listeners = cache[__mfSharedCacheListenersKey];
284
- if (listeners === undefined) {
285
- listeners = Object.create(null);
286
- Object.defineProperty(cache, __mfSharedCacheListenersKey, {
287
- value: listeners,
288
- enumerable: false,
289
- configurable: false,
290
- writable: false
291
- });
292
- }
293
- return listeners;
294
- };
295
- const __mfSubscribeSharedCache = (cache, descriptor, listener) => {
296
- const listeners = __mfGetSharedCacheListeners(cache);
297
- (listeners[descriptor.canonical] ||= new Set()).add(listener);
298
- };
299
- const __mfSharedCacheOwnersKey = Symbol.for("module-federation.shared-cache-owners");
300
- const __mfGetSharedCacheOwners = (cache) => {
301
- let owners = cache[__mfSharedCacheOwnersKey];
302
- if (owners === undefined) {
303
- owners = Object.create(null);
304
- Object.defineProperty(cache, __mfSharedCacheOwnersKey, {
305
- value: owners,
306
- enumerable: false,
307
- configurable: false,
308
- writable: false
309
- });
310
- }
311
- return owners;
312
- };
313
- const __mfReadSharedCacheOwner = (cache, descriptor) =>
314
- cache[__mfSharedCacheOwnersKey]?.[descriptor.canonical];
315
- const __mfWriteSharedCache = (cache, descriptor, value, owner) => {
316
- cache[descriptor.canonical] = value;
317
- const aliases = descriptor.aliases || [];
318
- for (const alias of aliases) {
319
- Object.defineProperty(cache, alias, {
320
- value,
321
- enumerable: true,
322
- configurable: true,
323
- writable: true
324
- });
325
- }
326
- const owners = cache[__mfSharedCacheOwnersKey];
327
- if (owner === undefined) {
328
- if (owners) delete owners[descriptor.canonical];
329
- } else {
330
- __mfGetSharedCacheOwners(cache)[descriptor.canonical] = owner;
331
- }
332
- const listeners = cache[__mfSharedCacheListenersKey]?.[descriptor.canonical];
333
- if (listeners) {
334
- for (const listener of listeners) listener(value);
335
- }
336
- return value;
337
- };
338
- const __mfTreeShakingSharedCacheKey = Symbol.for("module-federation.tree-shaking-shared-cache");
339
- const __mfGetTreeShakingSharedCache = (cache) => {
340
- let metadata = cache[__mfTreeShakingSharedCacheKey];
341
- if (metadata === undefined) {
342
- metadata = Object.create(null);
343
- Object.defineProperty(cache, __mfTreeShakingSharedCacheKey, {
344
- value: metadata,
345
- enumerable: false,
346
- configurable: false,
347
- writable: false
348
- });
349
- }
350
- return metadata;
351
- };
352
- const __mfReadTreeShakingSharedCache = (cache, descriptor, requiredExports) => {
353
- const fullModule = __mfReadSharedCache(cache, descriptor);
354
- if (fullModule !== undefined) return fullModule;
355
- if (!Array.isArray(requiredExports)) return undefined;
356
- const metadata = cache[__mfTreeShakingSharedCacheKey];
357
- const entries = metadata?.[descriptor.canonical] || [];
358
- let compatibleEntry;
359
- for (const entry of entries) {
360
- if (!requiredExports.every((name) => entry.providedExports.includes(name))) continue;
361
- if (!compatibleEntry || entry.providedExports.length < compatibleEntry.providedExports.length) {
362
- compatibleEntry = entry;
363
- }
364
- }
365
- return compatibleEntry?.value;
366
- };
367
- const __mfWriteTreeShakingSharedCache = (cache, descriptor, providedExports, value) => {
368
- if (!Array.isArray(providedExports)) return value;
369
- const normalizedExports = [...new Set(providedExports)].sort();
370
- const metadata = __mfGetTreeShakingSharedCache(cache);
371
- const entries = (metadata[descriptor.canonical] ||= []);
372
- const existing = entries.find((entry) =>
373
- entry.providedExports.length === normalizedExports.length &&
374
- entry.providedExports.every((name, index) => name === normalizedExports[index])
375
- );
376
- if (existing) existing.value = value;
377
- else entries.push({ providedExports: normalizedExports, value });
378
- return value;
379
- };
380
- const __mfTreeShakingSelectionCacheKey = Symbol.for("module-federation.tree-shaking-shared-selection-cache");
381
- const __mfGetTreeShakingSelectionCache = (cache) => {
382
- let selections = cache[__mfTreeShakingSelectionCacheKey];
383
- if (selections === undefined) {
384
- selections = Object.create(null);
385
- Object.defineProperty(cache, __mfTreeShakingSelectionCacheKey, {
386
- value: selections,
387
- enumerable: false,
388
- configurable: false,
389
- writable: false
390
- });
391
- }
392
- return selections;
393
- };
394
- const __mfReadTreeShakingSharedSelection = (cache, descriptor, consumer) => {
395
- const fullModule = __mfReadSharedCache(cache, descriptor);
396
- if (fullModule !== undefined) return fullModule;
397
- return cache[__mfTreeShakingSelectionCacheKey]?.[descriptor.canonical]?.[consumer];
398
- };
399
- const __mfWriteTreeShakingSharedSelection = (cache, descriptor, consumer, value) => {
400
- const selections = __mfGetTreeShakingSelectionCache(cache);
401
- const byConsumer = (selections[descriptor.canonical] ||= Object.create(null));
402
- byConsumer[consumer] = value;
403
- return value;
404
- };`;
405
- function getInstalledPackageJson(pkg, opts) {
406
- const cwd = opts?.cwd || getPackageDetectionCwd();
407
- const packageName = opts?.packageName || getPackageName(pkg);
408
- const cacheKey = `${cwd}\0${pkg}\0${packageName}\0${opts?.fromResolvedEntry ?? ""}`;
409
- if (installedPackageJsonCache.has(cacheKey)) return installedPackageJsonCache.get(cacheKey);
410
- const result = resolveInstalledPackageJson(pkg, cwd, packageName, opts);
411
- installedPackageJsonCache.set(cacheKey, result);
412
- return result;
413
- }
414
- function resolveInstalledPackageJson(pkg, cwd, packageName, opts) {
415
- const tryReadPackageJson = (packageJsonPath) => {
416
- if (!existsSync(packageJsonPath)) return void 0;
417
- try {
418
- return {
419
- path: packageJsonPath,
420
- dir: path$1.dirname(packageJsonPath),
421
- packageJson: JSON.parse(readFileSync(packageJsonPath, "utf-8"))
422
- };
423
- } catch {
424
- return;
425
- }
426
- };
427
- const findPackageInPnpmStore = (startDir) => {
428
- let currentDir = startDir;
429
- const rootDir = path$1.parse(currentDir).root;
430
- while (true) {
431
- const pnpmStoreDir = path$1.join(currentDir, "node_modules", ".pnpm");
432
- if (existsSync(pnpmStoreDir)) try {
433
- for (const entry of readdirSync(pnpmStoreDir, { withFileTypes: true })) {
434
- if (!entry.isDirectory()) continue;
435
- const candidate = tryReadPackageJson(path$1.join(pnpmStoreDir, entry.name, "node_modules", packageName, "package.json"));
436
- if (candidate?.packageJson.name === packageName) return candidate;
437
- }
438
- } catch {}
439
- if (currentDir === rootDir) break;
440
- currentDir = path$1.dirname(currentDir);
441
- }
442
- };
443
- try {
444
- const projectRequire = createRequire$1(pathToFileURL(path$1.join(cwd, "package.json")));
445
- let resolvedPath;
446
- if (opts?.fromResolvedEntry) resolvedPath = opts.fromResolvedEntry;
447
- else try {
448
- resolvedPath = projectRequire.resolve(pkg);
449
- } catch {
450
- resolvedPath = projectRequire.resolve(packageName);
451
- }
452
- let currentDir = path$1.dirname(resolvedPath);
453
- const rootDir = path$1.parse(currentDir).root;
454
- while (true) {
455
- const packageJsonPath = path$1.join(currentDir, "package.json");
456
- if (existsSync(packageJsonPath)) {
457
- const packageJsonContent = readFileSync(packageJsonPath, "utf-8");
458
- try {
459
- const packageJson = JSON.parse(packageJsonContent);
460
- if (packageJson.name === packageName) return {
461
- path: packageJsonPath,
462
- dir: currentDir,
463
- packageJson
464
- };
465
- } catch (error) {
466
- if (!(error instanceof SyntaxError)) throw error;
467
- }
468
- }
469
- if (currentDir === rootDir) break;
470
- currentDir = path$1.dirname(currentDir);
471
- }
472
- } catch {
473
- let currentDir = cwd;
474
- const rootDir = path$1.parse(currentDir).root;
475
- while (true) {
476
- const directCandidate = tryReadPackageJson(path$1.join(currentDir, "node_modules", packageName, "package.json"));
477
- if (directCandidate?.packageJson.name === packageName) return directCandidate;
478
- if (currentDir === rootDir) break;
479
- currentDir = path$1.dirname(currentDir);
480
- }
481
- return findPackageInPnpmStore(cwd);
482
- }
483
- }
484
- function getInstalledPackageEntry(pkg, opts) {
485
- const installed = getInstalledPackageJson(pkg, opts);
486
- if (!installed) return void 0;
487
- const cwd = opts?.cwd || getPackageDetectionCwd();
488
- const packageName = opts?.packageName || getPackageName(pkg);
489
- const packageJson = installed.packageJson;
490
- if (pkg !== packageName && (opts?.resolveSubpathWithRequire !== false || packageJson.exports === void 0)) try {
491
- return createRequire$1(pathToFileURL(path$1.join(cwd, "package.json"))).resolve(pkg);
492
- } catch {}
493
- const explicitEntry = resolveExportsEntry(getPackageExportsTarget(pkg, packageName, packageJson.exports), opts?.conditions) || (typeof packageJson.module === "string" ? packageJson.module : void 0) || (typeof packageJson.main === "string" ? packageJson.main : void 0) || "index.js";
494
- return path$1.join(installed.dir, explicitEntry);
495
- }
496
- /**
497
- * Detect whether the current runtime is Vite 8+ by checking for a Vite version flag
498
- * on the plugin hook context, with Rolldown metadata kept as a compatibility fallback.
499
- */
500
- function getIsRolldown(ctx) {
501
- const viteVersion = ctx?.meta?.viteVersion;
502
- const viteMajor = Number(String(viteVersion ?? "").split(".")[0]);
503
- return Number.isFinite(viteMajor) && viteMajor >= 8 || !!ctx?.meta?.rolldownVersion;
504
- }
505
- /** Walk up from Vite `config.root` (Nuxt may point at `.nuxt` cache dirs). */
506
- function isNuxtProjectRoot(root) {
507
- let dir = root;
508
- for (let i = 0; i < 8; i++) {
509
- if (hasPackageDependency("nuxt", dir) || hasPackageDependency("nuxt-nightly", dir)) return true;
510
- const parent = path$1.dirname(dir);
511
- if (parent === dir) break;
512
- dir = parent;
513
- }
514
- return false;
515
- }
516
- function hasPackageDependency(dependencyName, cwd = packageDetectionCwd || process.cwd()) {
517
- const cacheKey = getDependencyCacheKey(cwd, dependencyName);
518
- const cached = dependencyPresenceCache.get(cacheKey);
519
- if (cached !== void 0) return cached;
520
- try {
521
- const packageJson = JSON.parse(readFileSync(path$1.join(cwd, "package.json"), "utf8"));
522
- const hasDependency = [
523
- packageJson.dependencies,
524
- packageJson.devDependencies,
525
- packageJson.peerDependencies,
526
- packageJson.optionalDependencies
527
- ].some((deps) => !!deps?.[dependencyName]);
528
- dependencyPresenceCache.set(cacheKey, hasDependency);
529
- return hasDependency;
530
- } catch {
531
- dependencyPresenceCache.set(cacheKey, false);
532
- return false;
533
- }
534
- }
535
- //#endregion
536
- //#region src/plugins/pluginDts.ts
537
- var pluginDts_exports = /* @__PURE__ */ __exportAll({
538
- DEFAULT_PUBLIC_TYPES_FOLDER: () => DEFAULT_PUBLIC_TYPES_FOLDER,
539
- createDevDtsAssetMiddleware: () => createDevDtsAssetMiddleware,
540
- default: () => pluginDts,
541
- getDevDtsAssetPaths: () => getDevDtsAssetPaths,
542
- resolveDtsPluginOptions: () => resolveDtsPluginOptions
543
- });
544
- const DEFAULT_DEV_OPTIONS = {
545
- disableLiveReload: true,
546
- disableHotTypesReload: false,
547
- disableDynamicRemoteTypeHints: false
548
- };
549
- const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
550
- const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
551
- const DEV_TYPES_FOLDER = ".dev-server";
552
- const DEFAULT_PUBLIC_TYPES_FOLDER = "@mf-types";
553
- const forkDevWorkerPath = resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
554
- var DevWorker = class {
555
- worker = rpc.createRpcWorker(forkDevWorkerPath, {}, void 0, false);
556
- constructor(options) {
557
- this.worker.connect(options);
558
- }
559
- update() {
560
- this.worker.process?.send?.({
561
- type: rpc.RpcGMCallTypes.CALL,
562
- id: this.worker.id,
563
- args: [void 0, "update"]
564
- });
565
- }
566
- exit() {
567
- this.worker.terminate();
568
- }
569
- };
570
- const normalizeDevOptions = (dev) => {
571
- if (dev === false) return false;
572
- if (dev === true || typeof dev === "undefined") return { ...DEFAULT_DEV_OPTIONS };
573
- return {
574
- ...DEFAULT_DEV_OPTIONS,
575
- ...dev
576
- };
577
- };
578
- const buildDtsModuleFederationConfig = (options) => {
579
- const exposes = {};
580
- Object.entries(options.exposes).forEach(([key, value]) => {
581
- if (value.import) exposes[key] = value.import;
582
- });
583
- const remotes = {};
584
- Object.entries(options.remotes).forEach(([key, remote]) => {
585
- if (!remote.entry) return;
586
- remotes[key] = `${remote.entryGlobalName?.startsWith("http") || remote.entryGlobalName?.includes(".json") ? remote.name || key : remote.entryGlobalName || remote.name || key}@${remote.entry}`;
587
- });
588
- return {
589
- ...options,
590
- exposes,
591
- remotes
592
- };
593
- };
594
- const resolveOutputDir = (config) => {
595
- const { outDir } = config.build;
596
- if (path$1.isAbsolute(outDir)) return normalizePathForImport(path$1.relative(config.root, outDir));
597
- return outDir;
598
- };
599
- const ensureRuntimePlugin = (options, pluginId) => {
600
- if (!options.runtimePlugins.some((plugin) => {
601
- if (typeof plugin === "string") return plugin === pluginId;
602
- return plugin[0] === pluginId;
603
- })) options.runtimePlugins.push(pluginId);
604
- };
605
- const getExposeImportPaths = (options) => {
606
- return Object.values(options.exposes).map((value) => {
607
- return value.import;
608
- }).filter((value) => Boolean(value));
609
- };
610
- const usesVueSfcExposes = (options) => {
611
- return getExposeImportPaths(options).some((value) => value.endsWith(".vue"));
612
- };
613
- const resolveDtsPluginOptions = (dts, options, context) => {
614
- if (dts === false) return false;
615
- const inferredGenerateTypesDefaults = { generateAPITypes: true };
616
- if (usesVueSfcExposes(options) && hasPackageDependency("vue-tsc", context)) inferredGenerateTypesDefaults.compilerInstance = "vue-tsc";
617
- if (dts === true || typeof dts === "undefined") return { generateTypes: inferredGenerateTypesDefaults };
618
- const generateTypes = dts.generateTypes;
619
- return {
620
- ...dts,
621
- generateTypes: generateTypes === false ? false : {
622
- ...inferredGenerateTypesDefaults,
623
- ...generateTypes === true || typeof generateTypes === "undefined" ? {} : generateTypes
624
- }
625
- };
626
- };
627
- const getBasePath = (base) => {
628
- if (base.startsWith("http://") || base.startsWith("https://")) return new URL(base).pathname.replace(/\/$/, "") || "/";
629
- return base.replace(/\/$/, "") || "/";
630
- };
631
- const joinBaseAndAsset = (base, assetFileName) => {
632
- const basePath = getBasePath(base);
633
- return `${basePath === "/" ? "" : basePath}/${assetFileName}`.replace(/\/{2,}/g, "/");
634
- };
635
- const getDevDtsAssetPaths = (options) => {
636
- const { outputDir, publicTypesFolder, root, base } = options;
637
- return {
638
- apiFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.d.ts`),
639
- apiRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.d.ts`),
640
- zipFilePath: path$1.resolve(root, outputDir, `${DEV_TYPES_FOLDER}.zip`),
641
- zipRequestPath: joinBaseAndAsset(base, `${publicTypesFolder}.zip`)
642
- };
643
- };
644
- const createDevDtsAssetMiddleware = (assetPaths) => {
645
- return (req, res, next) => {
646
- const requestPath = req.url?.split("?")[0];
647
- const isZipRequest = requestPath === assetPaths.zipRequestPath;
648
- const isApiRequest = requestPath === assetPaths.apiRequestPath;
649
- if (!isZipRequest && !isApiRequest) {
650
- next();
651
- return;
652
- }
653
- const filePath = isZipRequest ? assetPaths.zipFilePath : assetPaths.apiFilePath;
654
- if (!fs.existsSync(filePath)) {
655
- res.statusCode = 404;
656
- res.end();
657
- return;
658
- }
659
- res.statusCode = 200;
660
- res.setHeader("Content-Type", isZipRequest ? "application/x-gzip" : "application/typescript");
661
- if (req.method === "HEAD") {
662
- res.end();
663
- return;
664
- }
665
- const stream = fs.createReadStream(filePath);
666
- stream.on("error", () => {
667
- if (!res.headersSent) res.statusCode = 500;
668
- res.end();
669
- });
670
- res.on("close", () => {
671
- stream.destroy();
672
- });
673
- stream.pipe(res);
674
- };
675
- };
676
- const normalizeDevDtsOptions = (dts, context) => {
677
- return normalizeOptions(isTSProject(dts, context), {
678
- generateTypes: { compileInChildProcess: true },
679
- consumeTypes: { consumeAPITypes: true },
680
- extraOptions: {},
681
- displayErrorInTerminal: typeof dts === "object" && dts ? dts.displayErrorInTerminal : void 0
682
- }, "mfOptions.dts")(dts);
683
- };
684
- const logDtsError = (error, dtsOptions) => {
685
- if (dtsOptions === false) return;
686
- if (typeof dtsOptions === "object" && dtsOptions && dtsOptions.displayErrorInTerminal === false) return;
687
- mfError(error);
688
- };
689
- function pluginDts(options) {
690
- if (options.dts === false) return [];
691
- const baseDtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
692
- const getDtsModuleFederationConfig = (context) => ({
693
- ...baseDtsModuleFederationConfig,
694
- dts: resolveDtsPluginOptions(options.dts, options, context)
695
- });
696
- let resolvedConfig;
697
- let devWorker;
698
- let normalizedDevOptions;
699
- let hasGeneratedBundle = false;
700
- return [{
701
- name: "module-federation-dts-dev",
702
- apply: "serve",
703
- config(config) {
704
- normalizedDevOptions = normalizeDevOptions(options.dev);
705
- if (!normalizedDevOptions) return;
706
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) return;
707
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
708
- const define = config.define ? { ...config.define } : {};
709
- if (!("FEDERATION_IPV4" in define)) define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
710
- config.define = define;
711
- },
712
- configResolved(config) {
713
- resolvedConfig = config;
714
- },
715
- configureServer(server) {
716
- if (!normalizedDevOptions || !resolvedConfig) return;
717
- const devOptions = normalizedDevOptions;
718
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) return;
719
- if (!options.name) throw createModuleFederationError("name is required if you want to enable dev server!");
720
- const outputDir = resolveOutputDir(resolvedConfig);
721
- const dtsModuleFederationConfig = getDtsModuleFederationConfig(resolvedConfig.root);
722
- const normalizedDtsOptions = normalizeDevDtsOptions(dtsModuleFederationConfig.dts, resolvedConfig.root);
723
- if (typeof normalizedDtsOptions !== "object") return;
724
- const normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), { compileInChildProcess: true }, "mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);
725
- const remote = normalizedGenerateTypes === false ? void 0 : {
726
- implementation: normalizedDtsOptions.implementation,
727
- context: resolvedConfig.root,
728
- outputDir,
729
- moduleFederationConfig: { ...dtsModuleFederationConfig },
730
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || "@mf-types",
731
- ...normalizedGenerateTypes,
732
- typesFolder: DEV_TYPES_FOLDER
733
- };
734
- if (remote) server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({
735
- outputDir,
736
- publicTypesFolder: remote.hostRemoteTypesFolder || "@mf-types",
737
- root: resolvedConfig.root,
738
- base: resolvedConfig.base
739
- })));
740
- if (remote && !remote.tsConfigPath && normalizedDtsOptions.tsConfigPath) remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
741
- const normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), { consumeAPITypes: true }, "mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);
742
- const host = normalizedConsumeTypes === false ? void 0 : {
743
- implementation: normalizedDtsOptions.implementation,
744
- context: resolvedConfig.root,
745
- moduleFederationConfig: dtsModuleFederationConfig,
746
- typesFolder: normalizedConsumeTypes.typesFolder || "@mf-types",
747
- abortOnError: false,
748
- ...normalizedConsumeTypes
749
- };
750
- const extraOptions = normalizedDtsOptions.extraOptions || {};
751
- if (!remote && !host && devOptions.disableLiveReload) return;
752
- const startDevWorker = async () => {
753
- let remoteTypeUrls;
754
- if (host) remoteTypeUrls = await new Promise((resolve) => {
755
- consumeTypesAPI({
756
- host,
757
- extraOptions,
758
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
759
- }, resolve);
760
- });
761
- devWorker = new DevWorker({
762
- name: options.name,
763
- remote,
764
- host: host ? {
765
- ...host,
766
- remoteTypeUrls
767
- } : void 0,
768
- extraOptions,
769
- disableLiveReload: devOptions.disableLiveReload,
770
- disableHotTypesReload: devOptions.disableHotTypesReload
771
- });
772
- const update = () => devWorker?.update();
773
- server.watcher.on("change", update);
774
- server.watcher.on("add", update);
775
- server.watcher.on("unlink", update);
776
- server.httpServer?.once("close", () => {
777
- devWorker?.exit();
778
- server.watcher.off("change", update);
779
- server.watcher.off("add", update);
780
- server.watcher.off("unlink", update);
781
- });
782
- };
783
- startDevWorker().catch((error) => {
784
- logDtsError(error, normalizedDtsOptions);
785
- });
786
- }
787
- }, {
788
- name: "module-federation-dts-build",
789
- apply: "build",
790
- configResolved(config) {
791
- resolvedConfig = config;
792
- },
793
- async generateBundle() {
794
- if (hasGeneratedBundle) return;
795
- hasGeneratedBundle = true;
796
- if (!resolvedConfig) return;
797
- let normalizedDtsOptions;
798
- try {
799
- normalizedDtsOptions = normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root), resolvedConfig.root);
800
- } catch (error) {
801
- logDtsError(error, options.dts);
802
- return;
803
- }
804
- if (typeof normalizedDtsOptions !== "object") return;
805
- const context = resolvedConfig.root;
806
- const outputDir = resolveOutputDir(resolvedConfig);
807
- let consumeOptions;
808
- try {
809
- consumeOptions = normalizeConsumeTypesOptions({
810
- context,
811
- dtsOptions: normalizedDtsOptions,
812
- pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
813
- });
814
- } catch (error) {
815
- logDtsError(error, normalizedDtsOptions);
816
- return;
817
- }
818
- if (consumeOptions?.host?.typesOnBuild) try {
819
- await consumeTypesAPI(consumeOptions);
820
- } catch (error) {
821
- logDtsError(error, normalizedDtsOptions);
822
- }
823
- let generateOptions;
824
- try {
825
- generateOptions = normalizeGenerateTypesOptions({
826
- context,
827
- outputDir,
828
- dtsOptions: normalizedDtsOptions,
829
- pluginOptions: getDtsModuleFederationConfig(resolvedConfig.root)
830
- });
831
- } catch (error) {
832
- logDtsError(error, normalizedDtsOptions);
833
- return;
834
- }
835
- if (!generateOptions) return;
836
- try {
837
- await generateTypesAPI({ dtsManagerOptions: generateOptions });
838
- } catch (error) {
839
- logDtsError(error, normalizedDtsOptions);
840
- }
841
- }
842
- }];
843
- }
844
- //#endregion
845
- export { createModuleFederationError as _, getIsRolldown as a, rebaseImport as b, getPackageNameFromNodeModulePath as c, isNuxtProjectRoot as d, packageNameDecode as f, sharedCacheHelperCode as g, setPackageDetectionCwd as h, getInstalledPackageJson as i, getSharedCacheDescriptor as l, resolveImportPath as m, pluginDts_exports as n, getPackageDetectionCwd as o, packageNameEncode as p, getInstalledPackageEntry as r, getPackageName as s, DEFAULT_PUBLIC_TYPES_FOLDER as t, hasPackageDependency as u, mfWarn as v, normalizePathForImport as y };