@module-federation/dts-plugin 0.0.0-perf-devtools-20260108034446 → 0.0.0-perf-website-code-usage-20260914033703

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