@module-federation/dts-plugin 0.0.0-chore-bump-node-22-20260710161714

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.
@@ -0,0 +1,1380 @@
1
+ import { a as MF_SERVER_IDENTIFIER, n as ActionKind, o as UpdateMode, r as DEFAULT_TAR_NAME, t as Action } from "./Action-DNNg2YDh.mjs";
2
+ import { a as getIdentifier, c as logger$1, i as getFreePort, l as LogKind, n as UpdateKind, o as getIPV4, r as fib, s as fileLog, t as Broker, u as APIKind } from "./Broker-Cmbh_XVO.mjs";
3
+ import { createRequire } from "node:module";
4
+ import fs, { existsSync, mkdirSync, writeFileSync } from "fs";
5
+ import { fileURLToPath } from "url";
6
+ import path, { dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from "path";
7
+ import { cp, mkdir, readFile, readdir, rm, stat, writeFile } from "fs/promises";
8
+ import { utils } from "@module-federation/managers";
9
+ import typescript from "typescript";
10
+ import { styleText } from "node:util";
11
+ import { ENCODE_NAME_PREFIX, MANIFEST_EXT, TEMP_DIR, decodeName, getProcessEnv, inferAutoPublicPath, parseEntry } from "@module-federation/sdk";
12
+ import { Agent } from "undici";
13
+ import { ThirdPartyExtractor } from "@module-federation/third-party-dts-extractor";
14
+ import AdmZip from "adm-zip";
15
+ import crypto from "crypto";
16
+ import { TYPE_001, typeDescMap } from "@module-federation/error-codes";
17
+ import { logAndReport } from "@module-federation/error-codes/node";
18
+ import { execFile, fork } from "child_process";
19
+ import util from "util";
20
+ import WebSocket from "isomorphic-ws";
21
+ import http from "http";
22
+ import process$1 from "process";
23
+
24
+ //#region \0rolldown/runtime.js
25
+ var __defProp = Object.defineProperty;
26
+ var __exportAll = (all, no_symbols) => {
27
+ let target = {};
28
+ for (var name in all) {
29
+ __defProp(target, name, {
30
+ get: all[name],
31
+ enumerable: true
32
+ });
33
+ }
34
+ if (!no_symbols) {
35
+ __defProp(target, Symbol.toStringTag, { value: "Module" });
36
+ }
37
+ return target;
38
+ };
39
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
40
+
41
+ //#endregion
42
+ //#region src/server/message/Action/AddPublisher.ts
43
+ var AddPublisherAction = class extends Action {
44
+ constructor(payload) {
45
+ super({ payload }, ActionKind.ADD_PUBLISHER);
46
+ }
47
+ };
48
+
49
+ //#endregion
50
+ //#region src/server/message/Action/AddSubscriber.ts
51
+ var AddSubscriberAction = class extends Action {
52
+ constructor(payload) {
53
+ super({ payload }, ActionKind.ADD_SUBSCRIBER);
54
+ }
55
+ };
56
+
57
+ //#endregion
58
+ //#region src/server/message/Action/ExitSubscriber.ts
59
+ var ExitSubscriberAction = class extends Action {
60
+ constructor(payload) {
61
+ super({ payload }, ActionKind.EXIT_SUBSCRIBER);
62
+ }
63
+ };
64
+
65
+ //#endregion
66
+ //#region src/server/message/Action/ExitPublisher.ts
67
+ var ExitPublisherAction = class extends Action {
68
+ constructor(payload) {
69
+ super({ payload }, ActionKind.EXIT_PUBLISHER);
70
+ }
71
+ };
72
+
73
+ //#endregion
74
+ //#region src/server/message/Action/NotifyWebClient.ts
75
+ var NotifyWebClientAction = class extends Action {
76
+ constructor(payload) {
77
+ super({ payload }, ActionKind.NOTIFY_WEB_CLIENT);
78
+ }
79
+ };
80
+
81
+ //#endregion
82
+ //#region src/server/message/Action/UpdatePublisher.ts
83
+ var UpdatePublisherAction = class extends Action {
84
+ constructor(payload) {
85
+ super({ payload }, ActionKind.UPDATE_PUBLISHER);
86
+ }
87
+ };
88
+
89
+ //#endregion
90
+ //#region src/server/broker/createBroker.ts
91
+ const __filename = fileURLToPath(import.meta.url);
92
+ const __dirname = path.dirname(__filename);
93
+ function createBroker() {
94
+ const sub = fork(path.resolve(__dirname, "./start-broker.js"), [], {
95
+ detached: true,
96
+ stdio: "ignore",
97
+ env: process.env
98
+ });
99
+ sub.send("start");
100
+ sub.unref();
101
+ return sub;
102
+ }
103
+
104
+ //#endregion
105
+ //#region src/server/DevServer.ts
106
+ var ModuleFederationDevServer = class {
107
+ constructor(ctx) {
108
+ this._publishWebSocket = null;
109
+ this._subscriberWebsocketMap = {};
110
+ this._reconnect = true;
111
+ this._reconnectTimes = 0;
112
+ this._isConnected = false;
113
+ this._isReconnecting = false;
114
+ this._updateCallback = () => Promise.resolve(void 0);
115
+ const { name, remotes, remoteTypeTarPath, updateCallback } = ctx;
116
+ this._ip = getIPV4();
117
+ this._name = name;
118
+ this._remotes = remotes;
119
+ this._remoteTypeTarPath = remoteTypeTarPath;
120
+ this._updateCallback = updateCallback;
121
+ this._stopWhenSIGTERMOrSIGINT();
122
+ this._handleUnexpectedExit();
123
+ this._connectPublishToServer();
124
+ }
125
+ _connectPublishToServer() {
126
+ if (!this._reconnect) return;
127
+ fileLog(`Publisher:${this._name} Trying to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
128
+ this._publishWebSocket = new WebSocket(`ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
129
+ this._publishWebSocket.on("open", () => {
130
+ fileLog(`Current pid: ${process.pid}, publisher:${this._name} connected to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
131
+ this._isConnected = true;
132
+ const addPublisherAction = new AddPublisherAction({
133
+ name: this._name,
134
+ ip: this._ip,
135
+ remoteTypeTarPath: this._remoteTypeTarPath
136
+ });
137
+ this._publishWebSocket?.send(JSON.stringify(addPublisherAction));
138
+ this._connectSubscribers();
139
+ });
140
+ this._publishWebSocket.on("message", async (message) => {
141
+ try {
142
+ const parsedMessage = JSON.parse(message.toString());
143
+ if (parsedMessage.type === "Log") {
144
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
145
+ fileLog(`Receive broker exit signal, ${this._name} service will exit...`, MF_SERVER_IDENTIFIER, "warn");
146
+ this._exit();
147
+ }
148
+ }
149
+ if (parsedMessage.type === "API") {
150
+ if (parsedMessage.kind === APIKind.FETCH_TYPES) {
151
+ const { payload: { remoteInfo } } = parsedMessage;
152
+ fileLog(`${this._name} Receive broker FETCH_TYPES, payload as follows: ${JSON.stringify(remoteInfo, null, 2)}.`, MF_SERVER_IDENTIFIER, "info");
153
+ await this.fetchDynamicRemoteTypes({ remoteInfo });
154
+ }
155
+ }
156
+ } catch (err) {
157
+ console.error(err);
158
+ const exitPublisher = new ExitPublisherAction({
159
+ name: this._name,
160
+ ip: this._ip
161
+ });
162
+ const exitSubscriber = new ExitSubscriberAction({
163
+ name: this._name,
164
+ ip: this._ip,
165
+ publishers: this._remotes.map((remote) => ({
166
+ name: remote.name,
167
+ ip: remote.ip
168
+ }))
169
+ });
170
+ this._publishWebSocket?.send(JSON.stringify(exitPublisher));
171
+ this._publishWebSocket?.send(JSON.stringify(exitSubscriber));
172
+ fileLog("Parse messages error, ModuleFederationDevServer will exit...", MF_SERVER_IDENTIFIER, "fatal");
173
+ this._exit();
174
+ }
175
+ });
176
+ this._publishWebSocket.on("close", (code) => {
177
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
178
+ this._publishWebSocket && this._publishWebSocket.close();
179
+ this._publishWebSocket = null;
180
+ if (!this._reconnect) return;
181
+ const reconnectTime = fib(++this._reconnectTimes);
182
+ fileLog(`start reconnecting to server after ${reconnectTime}s.`, MF_SERVER_IDENTIFIER, "info");
183
+ setTimeout(() => this._connectPublishToServer(), reconnectTime * 1e3);
184
+ });
185
+ this._publishWebSocket.on("error", this._tryCreateBackgroundBroker.bind(this));
186
+ }
187
+ _connectSubscriberToServer(remote) {
188
+ const { name, ip } = remote;
189
+ fileLog(`remote module:${name} trying to connect to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
190
+ const identifier = getIdentifier({
191
+ name,
192
+ ip
193
+ });
194
+ this._subscriberWebsocketMap[identifier] = new WebSocket(`ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
195
+ this._subscriberWebsocketMap[identifier].on("open", () => {
196
+ fileLog(`Current pid: ${process.pid} remote module: ${name} connected to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
197
+ const addSubscriber = new AddSubscriberAction({
198
+ name: this._name,
199
+ ip: this._ip,
200
+ publishers: [{
201
+ name,
202
+ ip
203
+ }]
204
+ });
205
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(addSubscriber));
206
+ });
207
+ this._subscriberWebsocketMap[identifier].on("message", async (message) => {
208
+ try {
209
+ const parsedMessage = JSON.parse(message.toString());
210
+ if (parsedMessage.type === "Log") {
211
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
212
+ fileLog(`${identifier}'s Server exit, thus ${identifier} will no longer has reload ability.`, MF_SERVER_IDENTIFIER, "warn");
213
+ this._exit();
214
+ }
215
+ }
216
+ if (parsedMessage.type === "API") {
217
+ if (parsedMessage.kind === APIKind.UPDATE_SUBSCRIBER) {
218
+ const { payload: { updateKind, updateSourcePaths, name: subscribeName, remoteTypeTarPath, updateMode } } = parsedMessage;
219
+ await this._updateSubscriber({
220
+ remoteTypeTarPath,
221
+ name: subscribeName,
222
+ updateKind,
223
+ updateMode,
224
+ updateSourcePaths
225
+ });
226
+ }
227
+ }
228
+ } catch (err) {
229
+ console.error(err);
230
+ const exitSubscriber = new ExitSubscriberAction({
231
+ name: this._name,
232
+ ip: this._ip,
233
+ publishers: [{
234
+ name,
235
+ ip
236
+ }]
237
+ });
238
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(exitSubscriber));
239
+ fileLog(`${identifier} exit,
240
+ error: ${err instanceof Error ? err.toString() : JSON.stringify(err)}
241
+ `, MF_SERVER_IDENTIFIER, "warn");
242
+ }
243
+ });
244
+ this._subscriberWebsocketMap[identifier].on("close", (code) => {
245
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
246
+ this._subscriberWebsocketMap[identifier]?.close();
247
+ delete this._subscriberWebsocketMap[identifier];
248
+ });
249
+ this._subscriberWebsocketMap[identifier].on("error", (err) => {
250
+ if ("code" in err && err.code === "ETIMEDOUT") fileLog(`Can not connect ${JSON.stringify(remote)}, please make sure this remote is started locally.`, MF_SERVER_IDENTIFIER, "warn");
251
+ else console.error(err);
252
+ this._subscriberWebsocketMap[identifier]?.close();
253
+ delete this._subscriberWebsocketMap[identifier];
254
+ });
255
+ }
256
+ _connectSubscribers() {
257
+ this._remotes.forEach((remote) => {
258
+ this._connectSubscriberToServer(remote);
259
+ });
260
+ }
261
+ async _updateSubscriber(options) {
262
+ const { updateMode, updateKind, updateSourcePaths, name, remoteTypeTarPath, remoteInfo } = options;
263
+ fileLog(`[_updateSubscriber] run, options: ${JSON.stringify(options, null, 2)}`, MF_SERVER_IDENTIFIER, "warn");
264
+ if (updateMode === UpdateMode.PASSIVE && updateSourcePaths.includes(this._name)) {
265
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} includes ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
266
+ return;
267
+ }
268
+ if (updateSourcePaths.slice(-1)[0] === this._name) {
269
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} ends is ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
270
+ return;
271
+ }
272
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths}, current module:${this._name}, update start...`, MF_SERVER_IDENTIFIER, "info");
273
+ await this._updateCallback({
274
+ name,
275
+ updateMode,
276
+ updateKind,
277
+ updateSourcePaths,
278
+ remoteTypeTarPath,
279
+ remoteInfo
280
+ });
281
+ const newUpdateSourcePaths = updateSourcePaths.concat(this._name);
282
+ const updatePublisher = new UpdatePublisherAction({
283
+ name: this._name,
284
+ ip: this._ip,
285
+ updateMode: UpdateMode.PASSIVE,
286
+ updateKind,
287
+ updateSourcePaths: newUpdateSourcePaths,
288
+ remoteTypeTarPath: this._remoteTypeTarPath
289
+ });
290
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${newUpdateSourcePaths}, update publisher ${this._name} start...`, MF_SERVER_IDENTIFIER, "info");
291
+ this._publishWebSocket?.send(JSON.stringify(updatePublisher));
292
+ }
293
+ _tryCreateBackgroundBroker(err) {
294
+ if (!((err?.code === "ECONNREFUSED" || err?.code === "ETIMEDOUT") && err.port === Broker.DEFAULT_WEB_SOCKET_PORT)) {
295
+ fileLog(`websocket error: ${err.stack}`, MF_SERVER_IDENTIFIER, "fatal");
296
+ return;
297
+ }
298
+ fileLog(`Failed to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "fatal");
299
+ this._isReconnecting = true;
300
+ setTimeout(() => {
301
+ this._isReconnecting = false;
302
+ if (this._reconnect === false) return;
303
+ fileLog("Creating new background broker...", MF_SERVER_IDENTIFIER, "warn");
304
+ createBroker().on("message", (message) => {
305
+ if (message === "ready") {
306
+ fileLog("background broker started.", MF_SERVER_IDENTIFIER, "info");
307
+ this._reconnectTimes = 1;
308
+ if (process.send) process.send("ready");
309
+ }
310
+ });
311
+ }, Math.ceil(100 * Math.random()));
312
+ }
313
+ _stopWhenSIGTERMOrSIGINT() {
314
+ process.on("SIGTERM", () => {
315
+ fileLog(`Process(${process.pid}) SIGTERM, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
316
+ this._exit();
317
+ });
318
+ process.on("SIGINT", () => {
319
+ fileLog(`Process(${process.pid}) SIGINT, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
320
+ this._exit();
321
+ });
322
+ }
323
+ _handleUnexpectedExit() {
324
+ process.on("unhandledRejection", (error) => {
325
+ if (this._isReconnecting) return;
326
+ console.error("Unhandled Rejection Error: ", error);
327
+ fileLog(`Process(${process.pid}) unhandledRejection, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
328
+ this._exit();
329
+ });
330
+ process.on("uncaughtException", (error) => {
331
+ if (this._isReconnecting) return;
332
+ console.error("Unhandled Exception Error: ", error);
333
+ fileLog(`Process(${process.pid}) uncaughtException, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
334
+ this._exit();
335
+ });
336
+ }
337
+ _exit() {
338
+ this._reconnect = false;
339
+ if (this._publishWebSocket) {
340
+ const exitPublisher = new ExitPublisherAction({
341
+ name: this._name,
342
+ ip: this._ip
343
+ });
344
+ this._publishWebSocket.send(JSON.stringify(exitPublisher));
345
+ this._publishWebSocket.on("message", (message) => {
346
+ const parsedMessage = JSON.parse(message.toString());
347
+ fileLog(`[${parsedMessage.kind}]: ${JSON.stringify(parsedMessage)}`, MF_SERVER_IDENTIFIER, "info");
348
+ });
349
+ }
350
+ if (this._publishWebSocket) {
351
+ this._publishWebSocket.close();
352
+ this._publishWebSocket = null;
353
+ }
354
+ process.exit(0);
355
+ }
356
+ exit() {
357
+ this._exit();
358
+ }
359
+ update(options) {
360
+ if (!this._publishWebSocket || !this._isConnected) return;
361
+ const { updateKind, updateMode, updateSourcePaths, clientName } = options;
362
+ fileLog(`update run, ${this._name} module update, updateKind: ${updateKind}, updateMode: ${updateMode}, updateSourcePaths: ${updateSourcePaths}`, MF_SERVER_IDENTIFIER, "info");
363
+ if (updateKind === UpdateKind.RELOAD_PAGE) {
364
+ const notifyWebClient = new NotifyWebClientAction({
365
+ name: clientName || this._name,
366
+ updateMode
367
+ });
368
+ this._publishWebSocket.send(JSON.stringify(notifyWebClient));
369
+ return;
370
+ }
371
+ const updatePublisher = new UpdatePublisherAction({
372
+ name: this._name,
373
+ ip: this._ip,
374
+ updateMode,
375
+ updateKind,
376
+ updateSourcePaths: [this._name],
377
+ remoteTypeTarPath: this._remoteTypeTarPath
378
+ });
379
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
380
+ }
381
+ async fetchDynamicRemoteTypes(options) {
382
+ const { remoteInfo, once } = options;
383
+ const updateMode = UpdateMode.PASSIVE;
384
+ const updateKind = UpdateKind.UPDATE_TYPE;
385
+ fileLog(`fetchDynamicRemoteTypes: remoteInfo: ${JSON.stringify(remoteInfo)}`, MF_SERVER_IDENTIFIER, "info");
386
+ await this._updateCallback({
387
+ name: this._name,
388
+ updateMode,
389
+ updateKind,
390
+ updateSourcePaths: [],
391
+ remoteTypeTarPath: "",
392
+ remoteInfo,
393
+ once
394
+ });
395
+ const updatePublisher = new UpdatePublisherAction({
396
+ name: this._name,
397
+ ip: this._ip,
398
+ updateMode,
399
+ updateKind,
400
+ updateSourcePaths: [this._name],
401
+ remoteTypeTarPath: this._remoteTypeTarPath
402
+ });
403
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
404
+ }
405
+ };
406
+
407
+ //#endregion
408
+ //#region src/server/createHttpServer.ts
409
+ async function createHttpServer(options) {
410
+ const { typeTarPath } = options;
411
+ const freeport = await getFreePort();
412
+ const server = http.createServer((req, res) => {
413
+ if ((req.url?.split("?")[0] ?? "/") === `/${DEFAULT_TAR_NAME}`) {
414
+ res.statusCode = 200;
415
+ res.setHeader("Content-Type", "application/x-gzip");
416
+ if (req.method === "HEAD") {
417
+ res.end();
418
+ return;
419
+ }
420
+ const stream = fs.createReadStream(typeTarPath);
421
+ stream.on("error", () => {
422
+ if (!res.headersSent) res.statusCode = 500;
423
+ res.end();
424
+ });
425
+ res.on("close", () => {
426
+ stream.destroy();
427
+ });
428
+ stream.pipe(res);
429
+ return;
430
+ }
431
+ res.statusCode = 404;
432
+ res.end();
433
+ });
434
+ server.listen(freeport);
435
+ return {
436
+ server,
437
+ serverAddress: `http://${getIPV4()}:${freeport}`
438
+ };
439
+ }
440
+
441
+ //#endregion
442
+ //#region src/core/lib/typeScriptCompiler.ts
443
+ const STARTS_WITH_SLASH = /^\//;
444
+ const DEFINITION_FILE_EXTENSION = ".d.ts";
445
+ const retrieveMfTypesPath = (tsConfig, remoteOptions) => normalize(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, ""));
446
+ const retrieveOriginalOutDir = (tsConfig, remoteOptions) => normalize(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, ""));
447
+ const retrieveMfAPITypesPath = (tsConfig, remoteOptions) => join(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`);
448
+ function writeTempTsConfig(tsConfig, context, name, cwd) {
449
+ const createHash = (contents) => {
450
+ return crypto.createHash("md5").update(contents).digest("hex");
451
+ };
452
+ const hash = createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);
453
+ const tempTsConfigJsonPath = resolve(cwd ?? context, "node_modules", TEMP_DIR, `tsconfig.${hash}.json`);
454
+ mkdirSync(dirname(tempTsConfigJsonPath), { recursive: true });
455
+ writeFileSync(tempTsConfigJsonPath, JSON.stringify(tsConfig, null, 2));
456
+ return tempTsConfigJsonPath;
457
+ }
458
+ const removeExt = (f) => {
459
+ const vueExt = ".vue";
460
+ const ext = extname(f);
461
+ if (ext === vueExt) return f;
462
+ const regexPattern = new RegExp(`\\${ext}$`);
463
+ return f.replace(regexPattern, "");
464
+ };
465
+ function getExposeKey(options) {
466
+ const { filePath, rootDir, outDir, mapExposeToEntry } = options;
467
+ return mapExposeToEntry[relative(outDir, filePath.replace(new RegExp(`\\.d.ts$`), ""))];
468
+ }
469
+ const processTypesFile = async (options) => {
470
+ const { outDir, filePath, rootDir, cb, mapExposeToEntry, mfTypePath } = options;
471
+ if (!existsSync(filePath)) return;
472
+ if ((await stat(filePath)).isDirectory()) {
473
+ const files = await readdir(filePath);
474
+ await Promise.all(files.map((file) => processTypesFile({
475
+ ...options,
476
+ filePath: join(filePath, file)
477
+ })));
478
+ } else if (filePath.endsWith(".d.ts")) {
479
+ const exposeKey = getExposeKey({
480
+ filePath,
481
+ rootDir,
482
+ outDir,
483
+ mapExposeToEntry
484
+ });
485
+ if (exposeKey) {
486
+ const mfeTypeEntry = join(mfTypePath, `${exposeKey === "." ? "index" : exposeKey}${DEFINITION_FILE_EXTENSION}`);
487
+ const mfeTypeEntryDirectory = dirname(mfeTypeEntry);
488
+ const relativePathToOutput = relative(mfeTypeEntryDirectory, filePath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(sep).join("/");
489
+ mkdirSync(mfeTypeEntryDirectory, { recursive: true });
490
+ await writeFile(mfeTypeEntry, `export * from './${relativePathToOutput}';\nexport { default } from './${relativePathToOutput}';`);
491
+ }
492
+ cb(await readFile(filePath, "utf8"));
493
+ }
494
+ };
495
+ const getPMFromUserAgent = () => {
496
+ const userAgent = process.env["npm_config_user_agent"];
497
+ if (userAgent == null) return "null";
498
+ return userAgent.split("/")[0];
499
+ };
500
+ const resolvePackageManagerExecutable = () => {
501
+ switch (getPMFromUserAgent()) {
502
+ case "yarn": return "yarn";
503
+ default: return "npx";
504
+ }
505
+ };
506
+ const splitCommandArgs = (value) => {
507
+ const args = [];
508
+ let current = "";
509
+ let quote = null;
510
+ let escaped = false;
511
+ for (const char of value) {
512
+ if (escaped) {
513
+ current += char;
514
+ escaped = false;
515
+ continue;
516
+ }
517
+ if (char === "\\") {
518
+ escaped = true;
519
+ continue;
520
+ }
521
+ if (quote) {
522
+ if (char === quote) quote = null;
523
+ else current += char;
524
+ continue;
525
+ }
526
+ if (char === "\"" || char === "'") {
527
+ quote = char;
528
+ continue;
529
+ }
530
+ if (char.trim() === "") {
531
+ if (current) {
532
+ args.push(current);
533
+ current = "";
534
+ }
535
+ continue;
536
+ }
537
+ current += char;
538
+ }
539
+ if (current) args.push(current);
540
+ return args;
541
+ };
542
+ const formatCommandForDisplay = (executable, args) => {
543
+ const formatArg = (arg) => {
544
+ if (/[\s'"]/.test(arg)) return JSON.stringify(arg);
545
+ return arg;
546
+ };
547
+ return [executable, ...args].map(formatArg).join(" ");
548
+ };
549
+ const compileTs = async (mapComponentsToExpose, tsConfig, remoteOptions) => {
550
+ if (!Object.keys(mapComponentsToExpose).length) return;
551
+ const { compilerOptions } = tsConfig;
552
+ const tempTsConfigJsonPath = writeTempTsConfig(tsConfig, remoteOptions.context, remoteOptions.moduleFederationConfig.name || "mf", typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? remoteOptions.moduleFederationConfig.dts?.cwd ?? void 0 : void 0);
553
+ logger$1.debug(`tempTsConfigJsonPath: ${tempTsConfigJsonPath}`);
554
+ try {
555
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
556
+ const thirdPartyExtractor = new ThirdPartyExtractor({
557
+ destDir: resolve(mfTypePath, "node_modules"),
558
+ context: remoteOptions.context,
559
+ exclude: typeof remoteOptions.extractThirdParty === "object" ? remoteOptions.extractThirdParty.exclude : void 0
560
+ });
561
+ const execPromise = util.promisify(execFile);
562
+ const pmExecutable = resolvePackageManagerExecutable();
563
+ const compilerArgs = splitCommandArgs(remoteOptions.compilerInstance);
564
+ const cmdArgs = [
565
+ ...compilerArgs.length > 0 ? compilerArgs : [remoteOptions.compilerInstance],
566
+ "--project",
567
+ tempTsConfigJsonPath
568
+ ];
569
+ const cmd = formatCommandForDisplay(pmExecutable, cmdArgs);
570
+ try {
571
+ await execPromise(pmExecutable, cmdArgs, {
572
+ cwd: typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? remoteOptions.moduleFederationConfig.dts?.cwd ?? void 0 : void 0,
573
+ shell: process.platform === "win32"
574
+ });
575
+ } catch (err) {
576
+ if (compilerOptions.tsBuildInfoFile) try {
577
+ await rm(compilerOptions.tsBuildInfoFile);
578
+ } catch (e) {}
579
+ logAndReport(TYPE_001, typeDescMap, { cmd }, (msg) => {
580
+ throw new Error(msg);
581
+ }, void 0);
582
+ }
583
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => {
584
+ const normalizedFileName = normalize(filename);
585
+ let relativeFileName = "";
586
+ if (isAbsolute(normalizedFileName)) relativeFileName = relative(tsConfig.compilerOptions.rootDir, normalizedFileName);
587
+ else relativeFileName = relative(tsConfig.compilerOptions.rootDir, resolve(remoteOptions.context, normalizedFileName));
588
+ return [removeExt(relativeFileName), exposed];
589
+ }));
590
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
591
+ await processTypesFile({
592
+ outDir: compilerOptions.outDir,
593
+ filePath: compilerOptions.outDir,
594
+ rootDir: compilerOptions.rootDir,
595
+ mfTypePath,
596
+ cb,
597
+ mapExposeToEntry
598
+ });
599
+ if (remoteOptions.extractThirdParty) await thirdPartyExtractor.copyDts();
600
+ if (remoteOptions.deleteTsConfig) await rm(tempTsConfigJsonPath);
601
+ } catch (err) {
602
+ throw err;
603
+ }
604
+ };
605
+
606
+ //#endregion
607
+ //#region src/core/lib/archiveHandler.ts
608
+ const retrieveTypesZipPath = (mfTypesPath, remoteOptions) => join(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`);
609
+ const createTypesArchive = async (tsConfig, remoteOptions) => {
610
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
611
+ const zip = new AdmZip();
612
+ zip.addLocalFolder(mfTypesPath);
613
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
614
+ };
615
+ const downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
616
+ throw {
617
+ ...reason,
618
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
619
+ };
620
+ };
621
+ const retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
622
+ return resolve(hostOptions.context, hostOptions.typesFolder, destinationFolder);
623
+ };
624
+ const downloadTypesArchive = (hostOptions) => {
625
+ let retries = 0;
626
+ return async ([destinationFolder, fileToDownload]) => {
627
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
628
+ while (retries++ < hostOptions.maxRetries) try {
629
+ const url = new URL(fileToDownload).href;
630
+ const response = await nativeFetch(url, {
631
+ responseType: "arraybuffer",
632
+ timeout: hostOptions.timeout,
633
+ family: hostOptions.family
634
+ }).catch(downloadErrorLogger(destinationFolder, url));
635
+ if (typeof response.headers?.["content-type"] === "string" && response.headers["content-type"].includes("text/html")) throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);
636
+ try {
637
+ if (hostOptions.deleteTypesFolder) await rm(destinationPath, {
638
+ recursive: true,
639
+ force: true
640
+ });
641
+ } catch (error) {
642
+ fileLog(`Unable to remove types folder, ${error}`, "downloadTypesArchive", "error");
643
+ }
644
+ new AdmZip(Buffer.from(response.data)).extractAllTo(destinationPath, true);
645
+ fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`, "downloadTypesArchive", "info");
646
+ return [destinationFolder, destinationPath];
647
+ } catch (error) {
648
+ fileLog(`Error during types archive download: ${error?.message || "unknown error"}`, "downloadTypesArchive", "error");
649
+ if (retries >= hostOptions.maxRetries) {
650
+ logger$1.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);
651
+ if (hostOptions.abortOnError !== false) throw error;
652
+ return;
653
+ }
654
+ }
655
+ };
656
+ };
657
+
658
+ //#endregion
659
+ //#region src/core/configurations/hostPlugin.ts
660
+ const defaultOptions$1 = {
661
+ typesFolder: "@mf-types",
662
+ remoteTypesFolder: "@mf-types",
663
+ deleteTypesFolder: true,
664
+ maxRetries: 3,
665
+ implementation: "",
666
+ context: process.cwd(),
667
+ abortOnError: true,
668
+ consumeAPITypes: false,
669
+ runtimePkgs: [],
670
+ remoteTypeUrls: {},
671
+ timeout: 6e4,
672
+ typesOnBuild: false,
673
+ family: 0
674
+ };
675
+ const buildZipUrl = (hostOptions, url) => {
676
+ const remoteUrl = new URL(url, "file:");
677
+ remoteUrl.pathname = `${remoteUrl.pathname.split("/").slice(0, -1).join("/")}/${hostOptions.remoteTypesFolder}.zip`;
678
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
679
+ };
680
+ const buildApiTypeUrl = (zipUrl) => {
681
+ if (!zipUrl) return;
682
+ return zipUrl.replace(".zip", ".d.ts");
683
+ };
684
+ const retrieveRemoteInfo = (options) => {
685
+ const { hostOptions, remoteAlias, remote } = options;
686
+ const { remoteTypeUrls } = hostOptions;
687
+ let decodedRemote = remote;
688
+ if (decodedRemote.startsWith(ENCODE_NAME_PREFIX)) decodedRemote = decodeName(decodedRemote, ENCODE_NAME_PREFIX);
689
+ const parsedInfo = parseEntry(decodedRemote, void 0, "@");
690
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
691
+ let zipUrl = "";
692
+ let apiTypeUrl = "";
693
+ const name = parsedInfo.name || remoteAlias;
694
+ const remoteTypeUrl = typeof remoteTypeUrls === "object" && remoteTypeUrls[name];
695
+ if (remoteTypeUrl) {
696
+ zipUrl = remoteTypeUrl.zip;
697
+ apiTypeUrl = remoteTypeUrl.api;
698
+ }
699
+ const shouldResolveTypeUrlsByConvention = Boolean(url && !url.includes(MANIFEST_EXT));
700
+ if (!zipUrl && shouldResolveTypeUrlsByConvention) zipUrl = buildZipUrl(hostOptions, url);
701
+ if (!apiTypeUrl && zipUrl && (remoteTypeUrl || shouldResolveTypeUrlsByConvention)) apiTypeUrl = buildApiTypeUrl(zipUrl);
702
+ return {
703
+ name,
704
+ url,
705
+ zipUrl,
706
+ apiTypeUrl,
707
+ alias: remoteAlias
708
+ };
709
+ };
710
+ const resolveRemotes = (hostOptions) => {
711
+ const parsedOptions = utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
712
+ remote: Array.isArray(item) ? item[0] : item,
713
+ key
714
+ }), (item, key) => ({
715
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
716
+ key
717
+ }));
718
+ const remoteTypeUrls = hostOptions.remoteTypeUrls ?? {};
719
+ if (typeof remoteTypeUrls !== "object") throw new Error("remoteTypeUrls must be consumed before resolveRemotes");
720
+ const remoteInfos = Object.keys(remoteTypeUrls).reduce((sum, remoteName) => {
721
+ const { zip, api, alias } = remoteTypeUrls[remoteName];
722
+ sum[alias] = {
723
+ name: remoteName,
724
+ url: "",
725
+ zipUrl: zip,
726
+ apiTypeUrl: api,
727
+ alias: alias || remoteName
728
+ };
729
+ return sum;
730
+ }, {});
731
+ return parsedOptions.reduce((accumulator, item) => {
732
+ const { key, remote } = item[1];
733
+ const res = retrieveRemoteInfo({
734
+ hostOptions,
735
+ remoteAlias: key,
736
+ remote
737
+ });
738
+ if (accumulator[key]) {
739
+ accumulator[key] = {
740
+ ...accumulator[key],
741
+ url: res.url,
742
+ apiTypeUrl: accumulator[key].apiTypeUrl || res.apiTypeUrl
743
+ };
744
+ return accumulator;
745
+ }
746
+ accumulator[key] = res;
747
+ return accumulator;
748
+ }, remoteInfos);
749
+ };
750
+ const retrieveHostConfig = (options) => {
751
+ validateOptions(options);
752
+ const hostOptions = {
753
+ ...defaultOptions$1,
754
+ ...options
755
+ };
756
+ return {
757
+ hostOptions,
758
+ mapRemotesToDownload: resolveRemotes(hostOptions)
759
+ };
760
+ };
761
+
762
+ //#endregion
763
+ //#region src/core/constant.ts
764
+ const REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
765
+ const REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
766
+ const HOST_API_TYPES_FILE_NAME = "index.d.ts";
767
+
768
+ //#endregion
769
+ //#region src/core/lib/DTSManager.ts
770
+ var DTSManager = class {
771
+ constructor(options) {
772
+ this.options = cloneDeepOptions(options);
773
+ this.runtimePkgs = [
774
+ "@module-federation/runtime",
775
+ "@module-federation/enhanced/runtime",
776
+ "@module-federation/runtime-tools"
777
+ ];
778
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
779
+ this.remoteAliasMap = {};
780
+ this.extraOptions = options?.extraOptions || {};
781
+ this.updatedRemoteInfos = {};
782
+ }
783
+ generateAPITypes(mapComponentsToExpose) {
784
+ const exposePaths = /* @__PURE__ */ new Set();
785
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
786
+ const exposePath = path.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(path.sep).join("/");
787
+ exposePaths.add(`'${exposePath}'`);
788
+ sum = `T extends '${exposePath}' ? typeof import('${exposePath}') :` + sum;
789
+ return sum;
790
+ }, "any;");
791
+ return `
792
+ export type RemoteKeys = ${[...exposePaths].join(" | ")};
793
+ type PackageType<T> = ${packageType}`;
794
+ }
795
+ async extractRemoteTypes(options) {
796
+ const { remoteOptions, tsConfig } = options;
797
+ if (!remoteOptions.extractRemoteTypes) return;
798
+ let hasRemotes = false;
799
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
800
+ if (remotes) {
801
+ if (Array.isArray(remotes)) hasRemotes = Boolean(remotes.length);
802
+ else if (typeof remotes === "object") hasRemotes = Boolean(Object.keys(remotes).length);
803
+ }
804
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
805
+ if (hasRemotes && this.options.host) try {
806
+ const { hostOptions } = retrieveHostConfig(this.options.host);
807
+ const remoteTypesFolder = path.resolve(hostOptions.context, hostOptions.typesFolder);
808
+ const targetDir = path.join(mfTypesPath, "node_modules");
809
+ if (fs.existsSync(remoteTypesFolder)) {
810
+ const targetFolder = path.resolve(remoteOptions.context, targetDir);
811
+ await mkdir(targetFolder, { recursive: true });
812
+ await cp(remoteTypesFolder, targetFolder, {
813
+ recursive: true,
814
+ force: true
815
+ });
816
+ }
817
+ } catch (err) {
818
+ if (this.options.host?.abortOnError === false) fileLog(`Unable to copy remote types, ${err}`, "extractRemoteTypes", "error");
819
+ else throw err;
820
+ }
821
+ }
822
+ async generateTypes() {
823
+ try {
824
+ const { options } = this;
825
+ if (!options.remote) throw new Error("options.remote is required if you want to generateTypes");
826
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
827
+ if (!Object.keys(mapComponentsToExpose).length) return;
828
+ if (!tsConfig.files?.length) {
829
+ logger$1.info("No type files to compile, skip");
830
+ return;
831
+ }
832
+ if (tsConfig.compilerOptions.tsBuildInfoFile) try {
833
+ const tsBuildInfoFile = path.resolve(remoteOptions.context, tsConfig.compilerOptions.tsBuildInfoFile);
834
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
835
+ if (!fs.existsSync(mfTypesPath)) fs.rmSync(tsBuildInfoFile, { force: true });
836
+ } catch (e) {}
837
+ await this.extractRemoteTypes({
838
+ remoteOptions,
839
+ tsConfig,
840
+ mapComponentsToExpose
841
+ });
842
+ await compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
843
+ await createTypesArchive(tsConfig, remoteOptions);
844
+ let apiTypesPath = "";
845
+ if (remoteOptions.generateAPITypes) {
846
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
847
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
848
+ fs.writeFileSync(apiTypesPath, apiTypes);
849
+ }
850
+ try {
851
+ if (remoteOptions.deleteTypesFolder) await rm(retrieveMfTypesPath(tsConfig, remoteOptions), {
852
+ recursive: true,
853
+ force: true
854
+ });
855
+ } catch (err) {
856
+ if (isDebugMode()) console.error(err);
857
+ }
858
+ logger$1.success("Federated types created correctly");
859
+ } catch (error) {
860
+ if (this.options.remote?.abortOnError === false) {
861
+ if (this.options.displayErrorInTerminal) logger$1.error(error);
862
+ } else throw error;
863
+ }
864
+ }
865
+ async requestRemoteManifest(remoteInfo, hostOptions) {
866
+ try {
867
+ if (!remoteInfo.url.includes(MANIFEST_EXT)) return remoteInfo;
868
+ if (remoteInfo.zipUrl) return remoteInfo;
869
+ const url = remoteInfo.url;
870
+ const manifestJson = (await nativeFetch(url, {
871
+ timeout: hostOptions.timeout,
872
+ family: hostOptions.family
873
+ })).data;
874
+ if (!manifestJson.metaData.types.zip) throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
875
+ const addProtocol = (u) => {
876
+ if (u.startsWith("//")) return `https:${u}`;
877
+ return u;
878
+ };
879
+ let publicPath;
880
+ if ("publicPath" in manifestJson.metaData) publicPath = manifestJson.metaData.publicPath;
881
+ else {
882
+ const getPublicPath = new Function(manifestJson.metaData.getPublicPath);
883
+ if (manifestJson.metaData.getPublicPath.startsWith("function")) publicPath = getPublicPath()();
884
+ else publicPath = getPublicPath();
885
+ }
886
+ if (publicPath === "auto") publicPath = inferAutoPublicPath(remoteInfo.url);
887
+ const normalizedPublicPath = addProtocol(publicPath).endsWith("/") ? addProtocol(publicPath) : `${addProtocol(publicPath)}/`;
888
+ remoteInfo.zipUrl = new URL(manifestJson.metaData.types.zip, normalizedPublicPath).href;
889
+ if (!manifestJson.metaData.types.api) {
890
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
891
+ remoteInfo.apiTypeUrl = "";
892
+ return remoteInfo;
893
+ }
894
+ remoteInfo.apiTypeUrl = new URL(manifestJson.metaData.types.api, normalizedPublicPath).href;
895
+ return remoteInfo;
896
+ } catch (_err) {
897
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
898
+ return remoteInfo;
899
+ }
900
+ }
901
+ async consumeTargetRemotes(hostOptions, remoteInfo) {
902
+ if (!remoteInfo.zipUrl) throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
903
+ return downloadTypesArchive(hostOptions)([remoteInfo.alias, remoteInfo.zipUrl]);
904
+ }
905
+ async downloadAPITypes(remoteInfo, destinationPath, hostOptions) {
906
+ const { apiTypeUrl } = remoteInfo;
907
+ if (!apiTypeUrl) return;
908
+ try {
909
+ let apiTypeFile = (await nativeFetch(apiTypeUrl, {
910
+ timeout: hostOptions.timeout,
911
+ family: hostOptions.family
912
+ })).data;
913
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
914
+ const filePath = path.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
915
+ fs.writeFileSync(filePath, apiTypeFile);
916
+ const existed = this.loadedRemoteAPIAlias.has(remoteInfo.alias);
917
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
918
+ fileLog(`success`, "downloadAPITypes", "info");
919
+ return existed;
920
+ } catch (err) {
921
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "downloadAPITypes", "error");
922
+ }
923
+ }
924
+ consumeAPITypes(hostOptions) {
925
+ const apiTypeFileName = path.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
926
+ try {
927
+ const existedFile = fs.readFileSync(apiTypeFileName, "utf-8");
928
+ new ThirdPartyExtractor({ destDir: "" }).collectTypeImports(existedFile).forEach((existedImport) => {
929
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
930
+ this.loadedRemoteAPIAlias.add(alias);
931
+ });
932
+ } catch (err) {}
933
+ if (!this.loadedRemoteAPIAlias.size) return;
934
+ const packageTypes = [];
935
+ const remoteKeys = [];
936
+ const importTypeStr = [...this.loadedRemoteAPIAlias].sort().map((alias, index) => {
937
+ const remoteKey = `RemoteKeys_${index}`;
938
+ const packageType = `PackageType_${index}`;
939
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
940
+ remoteKeys.push(remoteKey);
941
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
942
+ }).join("\n");
943
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
944
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[...packageTypes, "Y"].join(" :\n")} ;`;
945
+ const runtimePkgs = /* @__PURE__ */ new Set();
946
+ [...this.runtimePkgs, ...hostOptions.runtimePkgs].forEach((pkg) => {
947
+ runtimePkgs.add(pkg);
948
+ });
949
+ const fileStr = `${importTypeStr}
950
+ ${[...runtimePkgs].map((pkg) => {
951
+ return `declare module "${pkg}" {
952
+ ${remoteKeysStr}
953
+ ${packageTypesStr}
954
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
955
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
956
+ }`;
957
+ }).join("\n")}
958
+ `;
959
+ fs.writeFileSync(path.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
960
+ }
961
+ async consumeArchiveTypes(options) {
962
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
963
+ const downloadPromises = Object.entries(mapRemotesToDownload).map(async (item) => {
964
+ const remoteInfo = item[1];
965
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
966
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo, hostOptions);
967
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
968
+ }
969
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
970
+ });
971
+ return {
972
+ hostOptions,
973
+ downloadPromisesResult: await Promise.allSettled(downloadPromises)
974
+ };
975
+ }
976
+ async consumeTypes() {
977
+ try {
978
+ const { options } = this;
979
+ if (!options.host) throw new Error("options.host is required if you want to consumeTypes");
980
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
981
+ if (!Object.keys(mapRemotesToDownload).length) return;
982
+ const { downloadPromisesResult, hostOptions } = await this.consumeArchiveTypes(options.host);
983
+ if (hostOptions.consumeAPITypes) {
984
+ await Promise.all(downloadPromisesResult.map(async (item) => {
985
+ if (item.status === "rejected" || !item.value) return;
986
+ const [alias, destinationPath] = item.value;
987
+ const remoteInfo = this.remoteAliasMap[alias];
988
+ if (!remoteInfo) return;
989
+ await this.downloadAPITypes(remoteInfo, destinationPath, hostOptions);
990
+ }));
991
+ this.consumeAPITypes(hostOptions);
992
+ }
993
+ logger$1.success("Federated types extraction completed");
994
+ } catch (err) {
995
+ if (this.options.host?.abortOnError === false) fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
996
+ else throw err;
997
+ }
998
+ }
999
+ async updateTypes(options) {
1000
+ try {
1001
+ const { remoteName, updateMode, remoteTarPath, remoteInfo: updatedRemoteInfo, once } = options;
1002
+ const hostName = this.options?.host?.moduleFederationConfig?.name;
1003
+ fileLog(`options: ${JSON.stringify(options, null, 2)};\nhostName: ${hostName}`, "updateTypes", "info");
1004
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
1005
+ if (!this.options.remote) return;
1006
+ await this.generateTypes();
1007
+ } else {
1008
+ const { remoteAliasMap } = this;
1009
+ if (!this.options.host) return;
1010
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
1011
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
1012
+ const consumeTypes = async (requiredRemoteInfo) => {
1013
+ fileLog(`consumeTypes start`, "updateTypes", "info");
1014
+ if (!requiredRemoteInfo.zipUrl) throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);
1015
+ const [_alias, destinationPath] = await this.consumeTargetRemotes(hostOptions, {
1016
+ ...requiredRemoteInfo,
1017
+ zipUrl: remoteTarPath || requiredRemoteInfo.zipUrl
1018
+ });
1019
+ if (await this.downloadAPITypes(requiredRemoteInfo, destinationPath, hostOptions)) this.consumeAPITypes(hostOptions);
1020
+ fileLog(`consumeTypes end`, "updateTypes", "info");
1021
+ };
1022
+ fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo, null, 2)}`, "updateTypes", "info");
1023
+ if (!loadedRemoteInfo) {
1024
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
1025
+ return item.name === remoteName;
1026
+ });
1027
+ fileLog(`remoteInfo: ${JSON.stringify(remoteInfo, null, 2)}`, "updateTypes", "info");
1028
+ if (remoteInfo) {
1029
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1030
+ const requiredRemoteInfo = await this.requestRemoteManifest(remoteInfo, hostOptions);
1031
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1032
+ }
1033
+ await consumeTypes(this.remoteAliasMap[remoteInfo.alias]);
1034
+ } else if (updatedRemoteInfo) {
1035
+ const consumeDynamicRemoteTypes = async () => {
1036
+ await consumeTypes(this.updatedRemoteInfos[updatedRemoteInfo.name]);
1037
+ };
1038
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1039
+ const parsedRemoteInfo = retrieveRemoteInfo({
1040
+ hostOptions,
1041
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
1042
+ remote: updatedRemoteInfo.url
1043
+ });
1044
+ fileLog(`start request manifest`, "consumeTypes", "info");
1045
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = await this.requestRemoteManifest(parsedRemoteInfo, hostOptions);
1046
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "updateTypes", "info");
1047
+ await consumeDynamicRemoteTypes();
1048
+ }
1049
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) await consumeDynamicRemoteTypes();
1050
+ }
1051
+ } else await consumeTypes(loadedRemoteInfo);
1052
+ }
1053
+ } catch (err) {
1054
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
1055
+ }
1056
+ }
1057
+ };
1058
+
1059
+ //#endregion
1060
+ //#region src/core/lib/utils.ts
1061
+ const dispatcherCache = /* @__PURE__ */ new Map();
1062
+ function getDTSManagerConstructor(implementation) {
1063
+ if (implementation) {
1064
+ const NewConstructor = __require(implementation);
1065
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
1066
+ }
1067
+ return DTSManager;
1068
+ }
1069
+ const validateOptions = (options) => {
1070
+ if (!options.moduleFederationConfig) throw new Error("moduleFederationConfig is required");
1071
+ };
1072
+ function retrieveTypesAssetsInfo(options) {
1073
+ let apiTypesPath = "";
1074
+ let zipTypesPath = "";
1075
+ try {
1076
+ const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
1077
+ if (!Object.keys(mapComponentsToExpose).length || !tsConfig.files.length) return {
1078
+ apiTypesPath,
1079
+ zipTypesPath,
1080
+ zipName: "",
1081
+ apiFileName: ""
1082
+ };
1083
+ zipTypesPath = retrieveTypesZipPath(retrieveMfTypesPath(tsConfig, remoteOptions), remoteOptions);
1084
+ if (remoteOptions.generateAPITypes) apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1085
+ return {
1086
+ apiTypesPath,
1087
+ zipTypesPath,
1088
+ zipName: path.basename(zipTypesPath),
1089
+ apiFileName: path.basename(apiTypesPath)
1090
+ };
1091
+ } catch (err) {
1092
+ console.error(styleText("red", `Unable to compile federated types, ${err}`));
1093
+ return {
1094
+ apiTypesPath: "",
1095
+ zipTypesPath: "",
1096
+ zipName: "",
1097
+ apiFileName: ""
1098
+ };
1099
+ }
1100
+ }
1101
+ function isDebugMode() {
1102
+ return Boolean(process.env["FEDERATION_DEBUG"]) || process.env["NODE_ENV"] === "test";
1103
+ }
1104
+ const isTSProject = (dtsOptions, context = process.cwd()) => {
1105
+ if (dtsOptions === false) return false;
1106
+ try {
1107
+ let filepath = "";
1108
+ if (typeof dtsOptions === "object" && dtsOptions.tsConfigPath) filepath = dtsOptions.tsConfigPath;
1109
+ else filepath = path.resolve(context, "./tsconfig.json");
1110
+ if (!path.isAbsolute(filepath)) filepath = path.resolve(context, filepath);
1111
+ return fs.existsSync(filepath);
1112
+ } catch (err) {
1113
+ return false;
1114
+ }
1115
+ };
1116
+ function cloneDeepOptions(options) {
1117
+ const excludeKeys = new Set(["manifest", "async"]);
1118
+ const cache = /* @__PURE__ */ new WeakMap();
1119
+ function sanitize(val, key) {
1120
+ if (key !== void 0 && excludeKeys.has(key) || typeof val === "function") return false;
1121
+ if (key === "extractThirdParty" && Array.isArray(val)) return val.map(String);
1122
+ if (Array.isArray(val)) {
1123
+ if (cache.has(val)) return cache.get(val);
1124
+ const out = [];
1125
+ cache.set(val, out);
1126
+ val.forEach((v, i) => out.push(sanitize(v, String(i))));
1127
+ return out;
1128
+ }
1129
+ if (val !== null && typeof val === "object" && Object.getPrototypeOf(val) === Object.prototype) {
1130
+ const obj = val;
1131
+ if (cache.has(obj)) return cache.get(obj);
1132
+ const out = {};
1133
+ cache.set(obj, out);
1134
+ for (const [k, v] of Object.entries(obj)) out[k] = sanitize(v, k);
1135
+ return out;
1136
+ }
1137
+ return val;
1138
+ }
1139
+ return structuredClone(sanitize(options));
1140
+ }
1141
+ const getEnvHeaders = () => {
1142
+ const headersStr = getProcessEnv()["MF_ENV_HEADERS"];
1143
+ if (!headersStr || headersStr === "undefined") return {};
1144
+ try {
1145
+ return { ...JSON.parse(headersStr) };
1146
+ } catch {
1147
+ return {};
1148
+ }
1149
+ };
1150
+ const createDispatcherFromFamily = (family) => {
1151
+ if (!family) return void 0;
1152
+ if (dispatcherCache.has(family)) return dispatcherCache.get(family);
1153
+ try {
1154
+ const dispatcher = new Agent({ connect: { family } });
1155
+ dispatcherCache.set(family, dispatcher);
1156
+ return dispatcher;
1157
+ } catch {}
1158
+ };
1159
+ const toHeaderRecord = (headers) => {
1160
+ const out = {};
1161
+ headers.forEach((value, key) => {
1162
+ out[key.toLowerCase()] = value;
1163
+ });
1164
+ return out;
1165
+ };
1166
+ async function nativeFetch(url, config) {
1167
+ const controller = new AbortController();
1168
+ const timeoutMs = config?.timeout ?? 6e4;
1169
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
1170
+ const headers = {
1171
+ ...getEnvHeaders(),
1172
+ ...config?.headers ?? {}
1173
+ };
1174
+ const dispatcher = config?.dispatcher ?? createDispatcherFromFamily(config?.family);
1175
+ try {
1176
+ const resp = await fetch(url, {
1177
+ headers,
1178
+ signal: controller.signal,
1179
+ ...dispatcher ? { dispatcher } : {},
1180
+ ...config?.agent ? { agent: config.agent } : {}
1181
+ });
1182
+ const headerRecord = toHeaderRecord(resp.headers);
1183
+ if (!resp.ok) throw new Error(`Request failed with status ${resp.status}`);
1184
+ if (config?.responseType === "arraybuffer") return {
1185
+ data: await resp.arrayBuffer(),
1186
+ headers: headerRecord,
1187
+ status: resp.status
1188
+ };
1189
+ return {
1190
+ data: (resp.headers.get("content-type") || "").includes("application/json") || url.endsWith(".json") ? await resp.json() : await resp.text(),
1191
+ headers: headerRecord,
1192
+ status: resp.status
1193
+ };
1194
+ } finally {
1195
+ clearTimeout(timeoutId);
1196
+ }
1197
+ }
1198
+
1199
+ //#endregion
1200
+ //#region src/core/configurations/remotePlugin.ts
1201
+ const defaultOptions = {
1202
+ tsConfigPath: "./tsconfig.json",
1203
+ typesFolder: "@mf-types",
1204
+ compiledTypesFolder: "compiled-types",
1205
+ hostRemoteTypesFolder: "@mf-types",
1206
+ deleteTypesFolder: true,
1207
+ additionalFilesToCompile: [],
1208
+ compilerInstance: "tsc",
1209
+ compileInChildProcess: false,
1210
+ implementation: "",
1211
+ generateAPITypes: false,
1212
+ context: process.cwd(),
1213
+ abortOnError: true,
1214
+ extractRemoteTypes: false,
1215
+ extractThirdParty: false,
1216
+ outputDir: "",
1217
+ deleteTsConfig: true
1218
+ };
1219
+ function getEffectiveRootDir(parsedCommandLine) {
1220
+ const compilerOptions = parsedCommandLine.options;
1221
+ if (compilerOptions.rootDir) return compilerOptions.rootDir;
1222
+ const files = parsedCommandLine.fileNames;
1223
+ if (files.length > 0) return files.map((file) => dirname(file)).reduce((commonPath, fileDir) => {
1224
+ while (!fileDir.startsWith(commonPath)) commonPath = dirname(commonPath);
1225
+ return commonPath;
1226
+ }, files[0]);
1227
+ if (parsedCommandLine.projectReferences.length) {
1228
+ const relativeReferences = parsedCommandLine.projectReferences.filter((reference) => !isAbsolute(reference.originalPath ?? reference.path));
1229
+ const referencesForRoot = relativeReferences.length ? relativeReferences : parsedCommandLine.projectReferences;
1230
+ return referencesForRoot.map((reference) => dirname(reference.path)).reduce((commonPath, filePath) => {
1231
+ while (!filePath.startsWith(commonPath)) commonPath = dirname(commonPath);
1232
+ return commonPath;
1233
+ }, dirname(referencesForRoot[0].path));
1234
+ }
1235
+ throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !");
1236
+ }
1237
+ const getDependentFiles = (rootFiles, configContent, rootDir) => {
1238
+ const dependentFiles = typescript.createProgram(rootFiles, configContent.options).getSourceFiles().map((file) => file.fileName).filter((file) => !file.endsWith(".d.ts") && file.startsWith(rootDir + "/"));
1239
+ return dependentFiles.length ? dependentFiles : rootFiles;
1240
+ };
1241
+ const readTsConfig = ({ tsConfigPath, typesFolder, compiledTypesFolder, context, additionalFilesToCompile, outputDir }, mapComponentsToExpose) => {
1242
+ const resolvedTsConfigPath = resolve(context, tsConfigPath);
1243
+ const readResult = typescript.readConfigFile(resolvedTsConfigPath, typescript.sys.readFile);
1244
+ if (readResult.error) throw new Error(readResult.error.messageText.toString());
1245
+ const rawTsConfigJson = readResult.config;
1246
+ const configContent = typescript.parseJsonConfigFileContent(rawTsConfigJson, typescript.sys, dirname(resolvedTsConfigPath));
1247
+ const rootDir = getEffectiveRootDir(configContent);
1248
+ const outDir = resolve(context, outputDir || configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
1249
+ const defaultCompilerOptions = {
1250
+ rootDir,
1251
+ emitDeclarationOnly: true,
1252
+ noEmit: false,
1253
+ declaration: true,
1254
+ outDir
1255
+ };
1256
+ rawTsConfigJson.compilerOptions = rawTsConfigJson.compilerOptions || {};
1257
+ rawTsConfigJson.compilerOptions = {
1258
+ incremental: true,
1259
+ tsBuildInfoFile: resolve(context, "node_modules/.cache/mf-types/.tsbuildinfo"),
1260
+ ...rawTsConfigJson.compilerOptions,
1261
+ ...defaultCompilerOptions
1262
+ };
1263
+ const { paths, baseUrl, ...restCompilerOptions } = rawTsConfigJson.compilerOptions || {};
1264
+ rawTsConfigJson.compilerOptions = restCompilerOptions;
1265
+ const outDirWithoutTypesFolder = resolve(context, outputDir || configContent.options.outDir || "dist");
1266
+ const excludeExtensions = [".mdx", ".md"];
1267
+ const filesToCompile = [...getDependentFiles([...Object.values(mapComponentsToExpose), ...additionalFilesToCompile].filter((filename) => !excludeExtensions.some((ext) => filename.endsWith(ext))), configContent, rootDir), ...configContent.fileNames.filter((filename) => filename.endsWith(".d.ts") && !filename.startsWith(outDirWithoutTypesFolder))];
1268
+ rawTsConfigJson.include = [];
1269
+ rawTsConfigJson.files = [...new Set(filesToCompile)];
1270
+ rawTsConfigJson.exclude = [];
1271
+ "references" in rawTsConfigJson && delete rawTsConfigJson.references;
1272
+ rawTsConfigJson.extends = resolvedTsConfigPath;
1273
+ rawTsConfigJson.compilerOptions.declarationDir = outDir;
1274
+ return rawTsConfigJson;
1275
+ };
1276
+ const TS_EXTENSIONS = [
1277
+ ".ts",
1278
+ ".tsx",
1279
+ ".vue",
1280
+ ".svelte",
1281
+ ".js",
1282
+ ".jsx"
1283
+ ];
1284
+ const resolveWithExtension = (exposedPath, context) => {
1285
+ const explicitExtension = extname(exposedPath);
1286
+ if (TS_EXTENSIONS.includes(explicitExtension)) return resolve(context, exposedPath);
1287
+ for (const extension of TS_EXTENSIONS) {
1288
+ const exposedPathWithExtension = resolve(context, `${exposedPath}${extension}`);
1289
+ if (existsSync(exposedPathWithExtension)) return exposedPathWithExtension;
1290
+ }
1291
+ };
1292
+ const resolveExposes = (remoteOptions) => {
1293
+ return utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
1294
+ exposePath: Array.isArray(item) ? item[0] : item,
1295
+ key
1296
+ }), (item, key) => ({
1297
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
1298
+ key
1299
+ })).reduce((accumulator, item) => {
1300
+ const { exposePath, key } = item[1];
1301
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension(join(exposePath, "index"), remoteOptions.context) || exposePath;
1302
+ return accumulator;
1303
+ }, {});
1304
+ };
1305
+ const retrieveRemoteConfig = (options) => {
1306
+ validateOptions(options);
1307
+ const remoteOptions = {
1308
+ ...defaultOptions,
1309
+ ...options
1310
+ };
1311
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
1312
+ const tsConfig = readTsConfig(remoteOptions, mapComponentsToExpose);
1313
+ if (tsConfig.compilerOptions.incremental && tsConfig.compilerOptions.tsBuildInfoFile && options.deleteTypesFolder !== true) remoteOptions.deleteTypesFolder = false;
1314
+ return {
1315
+ tsConfig,
1316
+ mapComponentsToExpose,
1317
+ remoteOptions
1318
+ };
1319
+ };
1320
+
1321
+ //#endregion
1322
+ //#region src/core/lib/generateTypes.ts
1323
+ async function generateTypes(options) {
1324
+ return new (getDTSManagerConstructor(options.remote?.implementation))(options).generateTypes();
1325
+ }
1326
+
1327
+ //#endregion
1328
+ //#region src/core/rpc/types.ts
1329
+ let RpcGMCallTypes = /* @__PURE__ */ function(RpcGMCallTypes) {
1330
+ RpcGMCallTypes["CALL"] = "mf_call";
1331
+ RpcGMCallTypes["RESOLVE"] = "mf_resolve";
1332
+ RpcGMCallTypes["REJECT"] = "mf_reject";
1333
+ RpcGMCallTypes["EXIT"] = "mf_exit";
1334
+ return RpcGMCallTypes;
1335
+ }({});
1336
+
1337
+ //#endregion
1338
+ //#region src/core/rpc/expose-rpc.ts
1339
+ function exposeRpc(fn) {
1340
+ const sendMessage = (message) => new Promise((resolve, reject) => {
1341
+ if (!process$1.send) reject(/* @__PURE__ */ new Error(`Process ${process$1.pid} doesn't have IPC channels`));
1342
+ else if (!process$1.connected) reject(/* @__PURE__ */ new Error(`Process ${process$1.pid} doesn't have open IPC channels`));
1343
+ else process$1.send(message, void 0, void 0, (error) => {
1344
+ if (error) reject(error);
1345
+ else resolve(void 0);
1346
+ });
1347
+ });
1348
+ const handleMessage = async (message) => {
1349
+ if (message.type === RpcGMCallTypes.CALL) {
1350
+ if (!process$1.send) return;
1351
+ let value, error;
1352
+ try {
1353
+ value = await fn(...message.args);
1354
+ } catch (fnError) {
1355
+ error = fnError;
1356
+ }
1357
+ try {
1358
+ if (error) await sendMessage({
1359
+ type: RpcGMCallTypes.REJECT,
1360
+ id: message.id,
1361
+ error
1362
+ });
1363
+ else await sendMessage({
1364
+ type: RpcGMCallTypes.RESOLVE,
1365
+ id: message.id,
1366
+ value
1367
+ });
1368
+ } catch (sendError) {
1369
+ if (error) {
1370
+ if (error instanceof Error) console.error(error);
1371
+ }
1372
+ console.error(sendError);
1373
+ }
1374
+ }
1375
+ };
1376
+ process$1.on("message", handleMessage);
1377
+ }
1378
+
1379
+ //#endregion
1380
+ export { retrieveMfTypesPath as _, cloneDeepOptions as a, ModuleFederationDevServer as b, isTSProject as c, DTSManager as d, HOST_API_TYPES_FILE_NAME as f, retrieveTypesZipPath as g, retrieveHostConfig as h, retrieveRemoteConfig as i, retrieveTypesAssetsInfo as l, REMOTE_API_TYPES_FILE_NAME as m, RpcGMCallTypes as n, getDTSManagerConstructor as o, REMOTE_ALIAS_IDENTIFIER as p, generateTypes as r, isDebugMode as s, exposeRpc as t, validateOptions as u, retrieveOriginalOutDir as v, __exportAll as x, createHttpServer as y };