@module-federation/dts-plugin 0.1.19 → 0.1.21

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 (35) hide show
  1. package/dist/CHANGELOG.md +27 -0
  2. package/dist/{DtsWorker-d731dc2b.d.ts → DtsWorker-7113d2b0.d.ts} +6 -3
  3. package/dist/core.d.mts +85 -0
  4. package/dist/core.d.ts +5 -5
  5. package/dist/core.js +1105 -1008
  6. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  7. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  8. package/dist/dynamic-remote-type-hints-plugin.js +198 -0
  9. package/dist/esm/chunk-55BKSNZ4.js +2372 -0
  10. package/dist/esm/chunk-G7ONFBMA.js +24 -0
  11. package/dist/esm/chunk-MQRIERJP.js +236 -0
  12. package/dist/esm/core.js +44 -0
  13. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  14. package/dist/esm/fork-dev-worker.js +141 -0
  15. package/dist/esm/fork-generate-dts.js +26 -0
  16. package/dist/esm/index.js +406 -0
  17. package/dist/esm/start-broker.js +36 -0
  18. package/dist/fork-dev-worker.d.ts +15 -0
  19. package/dist/fork-dev-worker.js +2543 -0
  20. package/dist/{forkGenerateDts.d.ts → fork-generate-dts.d.mts} +1 -1
  21. package/dist/fork-generate-dts.d.ts +9 -0
  22. package/dist/fork-generate-dts.js +1902 -0
  23. package/dist/iife/launch-web-client.js +91 -42
  24. package/dist/index.d.mts +10 -0
  25. package/dist/index.js +1287 -1181
  26. package/dist/package.json +11 -2
  27. package/dist/{startBroker.d.ts → start-broker.d.mts} +2 -0
  28. package/dist/start-broker.d.ts +42 -0
  29. package/dist/start-broker.js +1273 -0
  30. package/package.json +14 -5
  31. package/dist/forkDevWorker.js +0 -2523
  32. package/dist/forkGenerateDts.js +0 -1618
  33. package/dist/launch-web-client.d.ts +0 -2
  34. package/dist/startBroker.js +0 -902
  35. /package/dist/{forkDevWorker.d.ts → fork-dev-worker.d.mts} +0 -0
@@ -0,0 +1,2372 @@
1
+ import {
2
+ ActionKind,
3
+ AddPublisherAction,
4
+ AddSubscriberAction,
5
+ DEFAULT_TAR_NAME,
6
+ DEFAULT_WEB_SOCKET_PORT,
7
+ ExitPublisherAction,
8
+ ExitSubscriberAction,
9
+ HOST_API_TYPES_FILE_NAME,
10
+ MF_SERVER_IDENTIFIER,
11
+ Message,
12
+ NotifyWebClientAction,
13
+ REMOTE_ALIAS_IDENTIFIER,
14
+ REMOTE_API_TYPES_FILE_NAME,
15
+ UpdateKind,
16
+ UpdateMode,
17
+ UpdatePublisherAction,
18
+ WEB_SOCKET_CONNECT_MAGIC_ID,
19
+ __async,
20
+ __export,
21
+ __name,
22
+ __publicField,
23
+ __require,
24
+ __spreadProps,
25
+ __spreadValues
26
+ } from "./chunk-MQRIERJP.js";
27
+
28
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
29
+ import { existsSync } from "fs";
30
+ import { dirname as dirname2, join as join3, resolve as resolve3, extname } from "path";
31
+ import { utils as utils2 } from "@module-federation/managers";
32
+ import typescript2 from "typescript";
33
+
34
+ // packages/dts-plugin/src/core/lib/utils.ts
35
+ import fs3 from "fs";
36
+ import path3 from "path";
37
+ import axios from "axios";
38
+ import http from "http";
39
+ import https from "https";
40
+ import ansiColors3 from "ansi-colors";
41
+
42
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
43
+ import ansiColors2 from "ansi-colors";
44
+ import path2 from "path";
45
+ import { rm as rm2 } from "fs/promises";
46
+ import fs2 from "fs";
47
+ import { MANIFEST_EXT, inferAutoPublicPath } from "@module-federation/sdk";
48
+ import cloneDeepWith from "lodash.clonedeepwith";
49
+ import { ThirdPartyExtractor as ThirdPartyExtractor2 } from "@module-federation/third-party-dts-extractor";
50
+
51
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
52
+ import AdmZip from "adm-zip";
53
+ import { resolve as resolve2, join as join2 } from "path";
54
+ import { rm } from "fs/promises";
55
+
56
+ // packages/dts-plugin/src/core/lib/typeScriptCompiler.ts
57
+ import ansiColors from "ansi-colors";
58
+ import { dirname, join, normalize, relative, resolve, sep } from "path";
59
+ import typescript from "typescript";
60
+ import { ThirdPartyExtractor } from "@module-federation/third-party-dts-extractor";
61
+ var STARTS_WITH_SLASH = /^\//;
62
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
63
+ var reportCompileDiagnostic = /* @__PURE__ */ __name((diagnostic) => {
64
+ const { line } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
65
+ console.error(ansiColors.red(`TS Error ${diagnostic.code}':' ${typescript.flattenDiagnosticMessageText(diagnostic.messageText, typescript.sys.newLine)}`));
66
+ console.error(ansiColors.red(` at ${diagnostic.file.fileName}:${line + 1} typescript.sys.newLine`));
67
+ }, "reportCompileDiagnostic");
68
+ var retrieveMfTypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => normalize(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "")), "retrieveMfTypesPath");
69
+ var retrieveOriginalOutDir = /* @__PURE__ */ __name((tsConfig, remoteOptions) => normalize(tsConfig.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")), "retrieveOriginalOutDir");
70
+ var retrieveMfAPITypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => join(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`), "retrieveMfAPITypesPath");
71
+ var createHost = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions, cb) => {
72
+ const host = typescript.createCompilerHost(tsConfig);
73
+ const originalWriteFile = host.writeFile;
74
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => [
75
+ normalize(filename),
76
+ exposed
77
+ ]));
78
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
79
+ host.writeFile = (filepath, text, writeOrderByteMark, onError, sourceFiles, data) => {
80
+ originalWriteFile(filepath, text, writeOrderByteMark, onError, sourceFiles, data);
81
+ for (const sourceFile of sourceFiles || []) {
82
+ let sourceEntry = mapExposeToEntry[normalize(sourceFile.fileName)];
83
+ if (sourceEntry === ".") {
84
+ sourceEntry = "index";
85
+ }
86
+ if (sourceEntry) {
87
+ const mfeTypeEntry = join(mfTypePath, `${sourceEntry}${DEFINITION_FILE_EXTENSION}`);
88
+ const mfeTypeEntryDirectory = dirname(mfeTypeEntry);
89
+ const relativePathToOutput = relative(mfeTypeEntryDirectory, filepath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(sep).join("/");
90
+ originalWriteFile(mfeTypeEntry, `export * from './${relativePathToOutput}';
91
+ export { default } from './${relativePathToOutput}';`, writeOrderByteMark);
92
+ }
93
+ }
94
+ cb(text);
95
+ };
96
+ return host;
97
+ }, "createHost");
98
+ var createVueTscProgram = /* @__PURE__ */ __name((programOptions) => {
99
+ const vueTypescript = __require("vue-tsc");
100
+ return vueTypescript.createProgram(programOptions);
101
+ }, "createVueTscProgram");
102
+ var createProgram = /* @__PURE__ */ __name((remoteOptions, programOptions) => {
103
+ switch (remoteOptions.compilerInstance) {
104
+ case "vue-tsc":
105
+ return createVueTscProgram(programOptions);
106
+ case "tsc":
107
+ default:
108
+ return typescript.createProgram(programOptions);
109
+ }
110
+ }, "createProgram");
111
+ var compileTs = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions) => {
112
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
113
+ const thirdPartyExtractor = new ThirdPartyExtractor(resolve(mfTypePath, "node_modules"), remoteOptions.context);
114
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
115
+ const tsHost = createHost(mapComponentsToExpose, tsConfig, remoteOptions, cb);
116
+ const filesToCompile = [
117
+ ...Object.values(mapComponentsToExpose),
118
+ ...remoteOptions.additionalFilesToCompile
119
+ ];
120
+ const programOptions = {
121
+ rootNames: filesToCompile,
122
+ host: tsHost,
123
+ options: tsConfig
124
+ };
125
+ const tsProgram = createProgram(remoteOptions, programOptions);
126
+ const { diagnostics = [] } = tsProgram.emit();
127
+ diagnostics.forEach(reportCompileDiagnostic);
128
+ if (remoteOptions.extractThirdParty) {
129
+ thirdPartyExtractor.copyDts();
130
+ }
131
+ }, "compileTs");
132
+
133
+ // packages/dts-plugin/src/server/message/API/API.ts
134
+ var APIKind;
135
+ (function(APIKind2) {
136
+ APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
137
+ APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
138
+ APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
139
+ })(APIKind || (APIKind = {}));
140
+ var _API = class _API extends Message {
141
+ constructor(content, kind) {
142
+ super("API", kind);
143
+ __publicField(this, "code");
144
+ __publicField(this, "payload");
145
+ const { code, payload } = content;
146
+ this.code = code;
147
+ this.payload = payload;
148
+ }
149
+ };
150
+ __name(_API, "API");
151
+ var API = _API;
152
+
153
+ // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
154
+ var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
155
+ constructor(payload) {
156
+ super({
157
+ code: 0,
158
+ payload
159
+ }, APIKind.UPDATE_SUBSCRIBER);
160
+ }
161
+ };
162
+ __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
163
+ var UpdateSubscriberAPI = _UpdateSubscriberAPI;
164
+
165
+ // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
166
+ var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
167
+ constructor(payload) {
168
+ super({
169
+ code: 0,
170
+ payload
171
+ }, APIKind.RELOAD_WEB_CLIENT);
172
+ }
173
+ };
174
+ __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
175
+ var ReloadWebClientAPI = _ReloadWebClientAPI;
176
+
177
+ // packages/dts-plugin/src/server/message/API/FetchTypes.ts
178
+ var _FetchTypesAPI = class _FetchTypesAPI extends API {
179
+ constructor(payload) {
180
+ super({
181
+ code: 0,
182
+ payload
183
+ }, APIKind.FETCH_TYPES);
184
+ }
185
+ };
186
+ __name(_FetchTypesAPI, "FetchTypesAPI");
187
+ var FetchTypesAPI = _FetchTypesAPI;
188
+
189
+ // packages/dts-plugin/src/server/utils/index.ts
190
+ import net from "net";
191
+ import { SEPARATOR } from "@module-federation/sdk";
192
+
193
+ // packages/dts-plugin/src/server/utils/logTransform.ts
194
+ import chalk from "chalk";
195
+
196
+ // packages/dts-plugin/src/server/message/Log/Log.ts
197
+ var LogLevel;
198
+ (function(LogLevel2) {
199
+ LogLevel2["LOG"] = "LOG";
200
+ LogLevel2["WARN"] = "WARN";
201
+ LogLevel2["ERROR"] = "ERROR";
202
+ })(LogLevel || (LogLevel = {}));
203
+ var LogKind;
204
+ (function(LogKind2) {
205
+ LogKind2["BrokerExitLog"] = "BrokerExitLog";
206
+ LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
207
+ })(LogKind || (LogKind = {}));
208
+ var _Log = class _Log extends Message {
209
+ constructor(level, kind, ignoreVerbose = false) {
210
+ super("Log", kind);
211
+ __publicField(this, "level");
212
+ __publicField(this, "ignoreVerbose", false);
213
+ this.level = level;
214
+ this.ignoreVerbose = ignoreVerbose;
215
+ }
216
+ };
217
+ __name(_Log, "Log");
218
+ var Log = _Log;
219
+
220
+ // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
221
+ var _BrokerExitLog = class _BrokerExitLog extends Log {
222
+ constructor() {
223
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
224
+ }
225
+ };
226
+ __name(_BrokerExitLog, "BrokerExitLog");
227
+ var BrokerExitLog = _BrokerExitLog;
228
+
229
+ // packages/dts-plugin/src/server/utils/log.ts
230
+ import { logger } from "@module-federation/sdk";
231
+ import * as log4js from "log4js";
232
+ import chalk2 from "chalk";
233
+ function fileLog(msg, module, level) {
234
+ var _a3, _b;
235
+ if (!((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3["FEDERATION_DEBUG"])) {
236
+ return;
237
+ }
238
+ log4js.configure({
239
+ appenders: {
240
+ [module]: {
241
+ type: "file",
242
+ filename: ".mf/typesGenerate.log"
243
+ },
244
+ default: {
245
+ type: "file",
246
+ filename: ".mf/typesGenerate.log"
247
+ }
248
+ },
249
+ categories: {
250
+ [module]: {
251
+ appenders: [
252
+ module
253
+ ],
254
+ level: "error"
255
+ },
256
+ default: {
257
+ appenders: [
258
+ "default"
259
+ ],
260
+ level: "trace"
261
+ }
262
+ }
263
+ });
264
+ const logger4 = log4js.getLogger(module);
265
+ logger4.level = "debug";
266
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
267
+ }
268
+ __name(fileLog, "fileLog");
269
+ function error(error2, action, from) {
270
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
271
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
272
+ return err.toString();
273
+ }
274
+ __name(error, "error");
275
+
276
+ // packages/dts-plugin/src/server/utils/getIPV4.ts
277
+ import os from "os";
278
+ var localIpv4 = "127.0.0.1";
279
+ var getIpv4Interfaces = /* @__PURE__ */ __name(() => {
280
+ try {
281
+ const interfaces = os.networkInterfaces();
282
+ const ipv4Interfaces = [];
283
+ Object.values(interfaces).forEach((detail) => {
284
+ detail == null ? void 0 : detail.forEach((detail2) => {
285
+ const familyV4Value = typeof detail2.family === "string" ? "IPv4" : 4;
286
+ if (detail2.family === familyV4Value && detail2.address !== localIpv4) {
287
+ ipv4Interfaces.push(detail2);
288
+ }
289
+ });
290
+ });
291
+ return ipv4Interfaces;
292
+ } catch (_err) {
293
+ return [];
294
+ }
295
+ }, "getIpv4Interfaces");
296
+ var getIPV4 = /* @__PURE__ */ __name(() => {
297
+ const ipv4Interfaces = getIpv4Interfaces();
298
+ const ipv4Interface = ipv4Interfaces[0] || {
299
+ address: localIpv4
300
+ };
301
+ return ipv4Interface.address;
302
+ }, "getIPV4");
303
+
304
+ // packages/dts-plugin/src/server/utils/index.ts
305
+ function getIdentifier(options) {
306
+ const { ip, name } = options;
307
+ return `mf ${SEPARATOR}${name}${ip ? `${SEPARATOR}${ip}` : ""}`;
308
+ }
309
+ __name(getIdentifier, "getIdentifier");
310
+ function fib(n) {
311
+ let i = 2;
312
+ const res = [
313
+ 0,
314
+ 1,
315
+ 1
316
+ ];
317
+ while (i <= n) {
318
+ res[i] = res[i - 1] + res[i - 2];
319
+ i++;
320
+ }
321
+ return res[n];
322
+ }
323
+ __name(fib, "fib");
324
+ function getFreePort() {
325
+ return new Promise((resolve4, reject) => {
326
+ const server = net.createServer();
327
+ server.unref();
328
+ server.on("error", reject);
329
+ server.listen(0, () => {
330
+ const { port } = server.address();
331
+ server.close(() => {
332
+ resolve4(port);
333
+ });
334
+ });
335
+ });
336
+ }
337
+ __name(getFreePort, "getFreePort");
338
+
339
+ // packages/dts-plugin/src/server/Publisher.ts
340
+ var _Publisher = class _Publisher {
341
+ constructor(ctx) {
342
+ __publicField(this, "_ip");
343
+ __publicField(this, "_name");
344
+ __publicField(this, "_remoteTypeTarPath");
345
+ __publicField(this, "_subscribers");
346
+ __publicField(this, "_ws");
347
+ __publicField(this, "dynamicRemoteMap");
348
+ this._name = ctx.name;
349
+ this._ip = ctx.ip;
350
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
351
+ this._subscribers = /* @__PURE__ */ new Map();
352
+ this._ws = ctx.ws;
353
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
354
+ }
355
+ get identifier() {
356
+ return getIdentifier({
357
+ name: this._name,
358
+ ip: this._ip
359
+ });
360
+ }
361
+ get name() {
362
+ return this._name;
363
+ }
364
+ get ip() {
365
+ return this._ip;
366
+ }
367
+ get remoteTypeTarPath() {
368
+ return this._remoteTypeTarPath;
369
+ }
370
+ get hasSubscribes() {
371
+ return Boolean(this._subscribers.size);
372
+ }
373
+ get subscribers() {
374
+ return this._subscribers;
375
+ }
376
+ addSubscriber(identifier, subscriber) {
377
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
378
+ this._subscribers.set(identifier, subscriber);
379
+ }
380
+ removeSubscriber(identifier) {
381
+ if (this._subscribers.has(identifier)) {
382
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
383
+ this._subscribers.delete(identifier);
384
+ }
385
+ }
386
+ notifySubscriber(subscriberIdentifier, options) {
387
+ const subscriber = this._subscribers.get(subscriberIdentifier);
388
+ if (!subscriber) {
389
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
390
+ return;
391
+ }
392
+ const api = new UpdateSubscriberAPI(options);
393
+ subscriber.send(JSON.stringify(api));
394
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
395
+ }
396
+ fetchRemoteTypes(options) {
397
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
398
+ if (!this._ws) {
399
+ return;
400
+ }
401
+ const api = new FetchTypesAPI(options);
402
+ this._ws.send(JSON.stringify(api));
403
+ }
404
+ notifySubscribers(options) {
405
+ const api = new UpdateSubscriberAPI(options);
406
+ this.broadcast(api);
407
+ }
408
+ broadcast(message) {
409
+ if (this.hasSubscribes) {
410
+ this._subscribers.forEach((subscriber, key) => {
411
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
412
+ subscriber.send(JSON.stringify(message));
413
+ });
414
+ } else {
415
+ fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
416
+ }
417
+ }
418
+ close() {
419
+ this._ws = void 0;
420
+ this._subscribers.forEach((_subscriber, identifier) => {
421
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
422
+ this.removeSubscriber(identifier);
423
+ });
424
+ }
425
+ };
426
+ __name(_Publisher, "Publisher");
427
+ var Publisher = _Publisher;
428
+
429
+ // packages/dts-plugin/src/server/DevServer.ts
430
+ import WebSocket2 from "isomorphic-ws";
431
+
432
+ // packages/dts-plugin/src/server/broker/Broker.ts
433
+ import { createServer } from "http";
434
+ import WebSocket from "isomorphic-ws";
435
+ import schedule from "node-schedule";
436
+ import { parse } from "url";
437
+ var _Broker = class _Broker {
438
+ constructor() {
439
+ __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
440
+ __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
441
+ __publicField(this, "_webSocketServer");
442
+ __publicField(this, "_secureWebSocketServer");
443
+ __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
444
+ __publicField(this, "_scheduleJob", null);
445
+ this._setSchedule();
446
+ this._startWsServer();
447
+ this._stopWhenSIGTERMOrSIGINT();
448
+ this._handleUnexpectedExit();
449
+ }
450
+ get hasPublishers() {
451
+ return Boolean(this._publisherMap.size);
452
+ }
453
+ _startWsServer() {
454
+ return __async(this, null, function* () {
455
+ const wsHandler = /* @__PURE__ */ __name((ws, req) => {
456
+ const { url: reqUrl = "" } = req;
457
+ const { query } = parse(reqUrl, true);
458
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
459
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
460
+ ws.on("message", (message) => {
461
+ try {
462
+ const text = message.toString();
463
+ const action = JSON.parse(text);
464
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
465
+ this._takeAction(action, ws);
466
+ } catch (error2) {
467
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
468
+ }
469
+ });
470
+ ws.on("error", (e) => {
471
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
472
+ });
473
+ } else {
474
+ ws.send("Invalid CONNECT ID.");
475
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
476
+ ws.close();
477
+ }
478
+ }, "wsHandler");
479
+ const server = createServer();
480
+ this._webSocketServer = new WebSocket.Server({
481
+ noServer: true
482
+ });
483
+ this._webSocketServer.on("error", (err) => {
484
+ fileLog(`ws error:
485
+ ${err.message}
486
+ ${err.stack}`, "Broker", "error");
487
+ });
488
+ this._webSocketServer.on("listening", () => {
489
+ fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
490
+ });
491
+ this._webSocketServer.on("connection", wsHandler);
492
+ this._webSocketServer.on("close", (code) => {
493
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
494
+ this._webSocketServer && this._webSocketServer.close();
495
+ this._webSocketServer = void 0;
496
+ });
497
+ server.on("upgrade", (req, socket, head) => {
498
+ var _a3;
499
+ if (req.url) {
500
+ const { pathname } = parse(req.url);
501
+ if (pathname === "/") {
502
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.handleUpgrade(req, socket, head, (ws) => {
503
+ var _a4;
504
+ (_a4 = this._webSocketServer) == null ? void 0 : _a4.emit("connection", ws, req);
505
+ });
506
+ }
507
+ }
508
+ });
509
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
510
+ });
511
+ }
512
+ _takeAction(action, client) {
513
+ return __async(this, null, function* () {
514
+ const { kind, payload } = action;
515
+ if (kind === ActionKind.ADD_PUBLISHER) {
516
+ yield this._addPublisher(payload, client);
517
+ }
518
+ if (kind === ActionKind.UPDATE_PUBLISHER) {
519
+ yield this._updatePublisher(payload, client);
520
+ }
521
+ if (kind === ActionKind.ADD_SUBSCRIBER) {
522
+ yield this._addSubscriber(payload, client);
523
+ }
524
+ if (kind === ActionKind.EXIT_SUBSCRIBER) {
525
+ yield this._removeSubscriber(payload, client);
526
+ }
527
+ if (kind === ActionKind.EXIT_PUBLISHER) {
528
+ yield this._removePublisher(payload, client);
529
+ }
530
+ if (kind === ActionKind.ADD_WEB_CLIENT) {
531
+ yield this._addWebClient(payload, client);
532
+ }
533
+ if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
534
+ yield this._notifyWebClient(payload, client);
535
+ }
536
+ if (kind === ActionKind.FETCH_TYPES) {
537
+ yield this._fetchTypes(payload, client);
538
+ }
539
+ if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
540
+ this._addDynamicRemote(payload);
541
+ }
542
+ });
543
+ }
544
+ _addPublisher(context, client) {
545
+ return __async(this, null, function* () {
546
+ const { name, ip, remoteTypeTarPath } = context != null ? context : {};
547
+ const identifier = getIdentifier({
548
+ name,
549
+ ip
550
+ });
551
+ if (this._publisherMap.has(identifier)) {
552
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
553
+ return;
554
+ }
555
+ try {
556
+ const publisher = new Publisher({
557
+ name,
558
+ ip,
559
+ remoteTypeTarPath,
560
+ ws: client
561
+ });
562
+ this._publisherMap.set(identifier, publisher);
563
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
564
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
565
+ if (tmpSubScribers) {
566
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
567
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
568
+ this._clearTmpSubScriberRelation(identifier);
569
+ }
570
+ } catch (err) {
571
+ const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
572
+ client.send(msg);
573
+ client.close();
574
+ }
575
+ });
576
+ }
577
+ _updatePublisher(context, client) {
578
+ return __async(this, null, function* () {
579
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
580
+ const identifier = getIdentifier({
581
+ name,
582
+ ip
583
+ });
584
+ if (!this._publisherMap.has(identifier)) {
585
+ fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
586
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
587
+ `, "Broker", "warn");
588
+ return;
589
+ }
590
+ try {
591
+ const publisher = this._publisherMap.get(identifier);
592
+ fileLog(
593
+ // eslint-disable-next-line max-len
594
+ `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
595
+ "Broker",
596
+ "info"
597
+ );
598
+ if (publisher) {
599
+ publisher.notifySubscribers({
600
+ remoteTypeTarPath,
601
+ name,
602
+ updateMode,
603
+ updateKind,
604
+ updateSourcePaths: updateSourcePaths || []
605
+ });
606
+ this._publisherMap.forEach((p) => {
607
+ if (p.name === publisher.name) {
608
+ return;
609
+ }
610
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
611
+ if (dynamicRemoteInfo) {
612
+ fileLog(
613
+ // eslint-disable-next-line max-len
614
+ `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
615
+ "Broker",
616
+ "info"
617
+ );
618
+ p.fetchRemoteTypes({
619
+ remoteInfo: dynamicRemoteInfo,
620
+ once: false
621
+ });
622
+ }
623
+ });
624
+ }
625
+ } catch (err) {
626
+ const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
627
+ client.send(msg);
628
+ client.close();
629
+ }
630
+ });
631
+ }
632
+ _fetchTypes(context, _client) {
633
+ return __async(this, null, function* () {
634
+ const { name, ip, remoteInfo } = context != null ? context : {};
635
+ const identifier = getIdentifier({
636
+ name,
637
+ ip
638
+ });
639
+ try {
640
+ const publisher = this._publisherMap.get(identifier);
641
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
642
+ if (publisher) {
643
+ publisher.fetchRemoteTypes({
644
+ remoteInfo,
645
+ once: true
646
+ });
647
+ }
648
+ } catch (err) {
649
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
650
+ }
651
+ });
652
+ }
653
+ _addDynamicRemote(context) {
654
+ const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
655
+ const identifier = getIdentifier({
656
+ name,
657
+ ip
658
+ });
659
+ const publisher = this._publisherMap.get(identifier);
660
+ const remoteId = getIdentifier({
661
+ name: remoteInfo.name,
662
+ ip: remoteIp
663
+ });
664
+ fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
665
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
666
+ return;
667
+ }
668
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
669
+ }
670
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
671
+ // provider1 is app1's remote
672
+ _addSubscriber(context, client) {
673
+ return __async(this, null, function* () {
674
+ const { publishers, name: subscriberName } = context != null ? context : {};
675
+ publishers.forEach((publisher) => {
676
+ const { name, ip } = publisher;
677
+ const identifier = getIdentifier({
678
+ name,
679
+ ip
680
+ });
681
+ if (!this._publisherMap.has(identifier)) {
682
+ fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
683
+ this._addTmpSubScriberRelation({
684
+ name: getIdentifier({
685
+ name: context.name,
686
+ ip: context.ip
687
+ }),
688
+ client
689
+ }, publisher);
690
+ return;
691
+ }
692
+ try {
693
+ const registeredPublisher = this._publisherMap.get(identifier);
694
+ if (registeredPublisher) {
695
+ registeredPublisher.addSubscriber(getIdentifier({
696
+ name: subscriberName,
697
+ ip: context.ip
698
+ }), client);
699
+ fileLog(
700
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
701
+ `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
702
+ "Broker",
703
+ "info"
704
+ );
705
+ registeredPublisher.notifySubscriber(getIdentifier({
706
+ name: subscriberName,
707
+ ip: context.ip
708
+ }), {
709
+ updateKind: UpdateKind.UPDATE_TYPE,
710
+ updateMode: UpdateMode.PASSIVE,
711
+ updateSourcePaths: [
712
+ registeredPublisher.name
713
+ ],
714
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
715
+ name: registeredPublisher.name
716
+ });
717
+ fileLog(
718
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
719
+ `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
720
+ "Broker",
721
+ "info"
722
+ );
723
+ }
724
+ } catch (err) {
725
+ const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
726
+ client.send(msg);
727
+ client.close();
728
+ }
729
+ });
730
+ });
731
+ }
732
+ // Trigger while consumer exit
733
+ _removeSubscriber(context, client) {
734
+ return __async(this, null, function* () {
735
+ const { publishers } = context != null ? context : {};
736
+ const subscriberIdentifier = getIdentifier({
737
+ name: context == null ? void 0 : context.name,
738
+ ip: context == null ? void 0 : context.ip
739
+ });
740
+ publishers.forEach((publisher) => {
741
+ const { name, ip } = publisher;
742
+ const identifier = getIdentifier({
743
+ name,
744
+ ip
745
+ });
746
+ const registeredPublisher = this._publisherMap.get(identifier);
747
+ if (!registeredPublisher) {
748
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
749
+ return;
750
+ }
751
+ try {
752
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
753
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
754
+ this._clearTmpSubScriberRelation(identifier);
755
+ if (!registeredPublisher.hasSubscribes) {
756
+ this._publisherMap.delete(identifier);
757
+ }
758
+ if (!this.hasPublishers) {
759
+ this.exit();
760
+ }
761
+ } catch (err) {
762
+ const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
763
+ client.send(msg);
764
+ client.close();
765
+ }
766
+ });
767
+ });
768
+ }
769
+ _removePublisher(context, client) {
770
+ return __async(this, null, function* () {
771
+ const { name, ip } = context != null ? context : {};
772
+ const identifier = getIdentifier({
773
+ name,
774
+ ip
775
+ });
776
+ const publisher = this._publisherMap.get(identifier);
777
+ if (!publisher) {
778
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
779
+ return;
780
+ }
781
+ try {
782
+ const { subscribers } = publisher;
783
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
784
+ this._addTmpSubScriberRelation({
785
+ name: subscriberIdentifier,
786
+ client: subscriber
787
+ }, {
788
+ name: publisher.name,
789
+ ip: publisher.ip
790
+ });
791
+ fileLog(
792
+ // eslint-disable-next-line max-len
793
+ `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
794
+ "Broker",
795
+ "info"
796
+ );
797
+ });
798
+ this._publisherMap.delete(identifier);
799
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
800
+ if (!this.hasPublishers) {
801
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
802
+ this.exit();
803
+ }
804
+ } catch (err) {
805
+ const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
806
+ client.send(msg);
807
+ client.close();
808
+ }
809
+ });
810
+ }
811
+ _addWebClient(context, client) {
812
+ return __async(this, null, function* () {
813
+ const { name } = context != null ? context : {};
814
+ const identifier = getIdentifier({
815
+ name
816
+ });
817
+ if (this._webClientMap.has(identifier)) {
818
+ fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
819
+ }
820
+ try {
821
+ this._webClientMap.set(identifier, client);
822
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
823
+ } catch (err) {
824
+ const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
825
+ client.send(msg);
826
+ client.close();
827
+ }
828
+ });
829
+ }
830
+ _notifyWebClient(context, client) {
831
+ return __async(this, null, function* () {
832
+ const { name, updateMode } = context != null ? context : {};
833
+ const identifier = getIdentifier({
834
+ name
835
+ });
836
+ const webClient = this._webClientMap.get(identifier);
837
+ if (!webClient) {
838
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
839
+ return;
840
+ }
841
+ try {
842
+ const api = new ReloadWebClientAPI({
843
+ name,
844
+ updateMode
845
+ });
846
+ webClient.send(JSON.stringify(api));
847
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
848
+ } catch (err) {
849
+ const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
850
+ client.send(msg);
851
+ client.close();
852
+ }
853
+ });
854
+ }
855
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
856
+ _addTmpSubScriberRelation(subscriber, publisher) {
857
+ const publisherIdentifier = getIdentifier({
858
+ name: publisher.name,
859
+ ip: publisher.ip
860
+ });
861
+ const subscriberIdentifier = subscriber.name;
862
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
863
+ if (!shelter) {
864
+ const map = /* @__PURE__ */ new Map();
865
+ map.set(subscriberIdentifier, subscriber);
866
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
867
+ subscribers: map,
868
+ timestamp: Date.now()
869
+ });
870
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
871
+ return;
872
+ }
873
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
874
+ if (tmpSubScriberShelterSubscriber) {
875
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
876
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
877
+ shelter.timestamp = Date.now();
878
+ } else {
879
+ fileLog(
880
+ // eslint-disable-next-line max-len
881
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
882
+ "Broker",
883
+ "warn"
884
+ );
885
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
886
+ }
887
+ }
888
+ _getTmpSubScribers(publisherIdentifier) {
889
+ var _a3;
890
+ return (_a3 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a3.subscribers;
891
+ }
892
+ // after adding publisher, it will change the temp subscriber to regular subscriber
893
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
894
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
895
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
896
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
897
+ publisher.notifySubscriber(identifier, {
898
+ updateKind: UpdateKind.UPDATE_TYPE,
899
+ updateMode: UpdateMode.PASSIVE,
900
+ updateSourcePaths: [
901
+ publisher.name
902
+ ],
903
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
904
+ name: publisher.name
905
+ });
906
+ });
907
+ }
908
+ _clearTmpSubScriberRelation(identifier) {
909
+ this._tmpSubscriberShelter.delete(identifier);
910
+ }
911
+ _clearTmpSubScriberRelations() {
912
+ this._tmpSubscriberShelter.clear();
913
+ }
914
+ _disconnect() {
915
+ this._publisherMap.forEach((publisher) => {
916
+ publisher.close();
917
+ });
918
+ }
919
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
920
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
921
+ _setSchedule() {
922
+ const rule = new schedule.RecurrenceRule();
923
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
924
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
925
+ const second = [];
926
+ for (let i = 0; i < 60; i = i + interval) {
927
+ second.push(i);
928
+ }
929
+ rule.second = second;
930
+ } else {
931
+ rule.second = 0;
932
+ rule.hour = [
933
+ 0,
934
+ 3,
935
+ 6,
936
+ 9,
937
+ 12,
938
+ 15,
939
+ 18
940
+ ];
941
+ rule.minute = 0;
942
+ }
943
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
944
+ this._scheduleJob = schedule.scheduleJob(rule, () => {
945
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
946
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
947
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
948
+ this._clearTmpSubScriberRelation(identifier);
949
+ }
950
+ });
951
+ });
952
+ }
953
+ _clearSchedule() {
954
+ if (!this._scheduleJob) {
955
+ return;
956
+ }
957
+ this._scheduleJob.cancel();
958
+ this._scheduleJob = null;
959
+ }
960
+ _stopWhenSIGTERMOrSIGINT() {
961
+ process.on("SIGTERM", () => {
962
+ this.exit();
963
+ });
964
+ process.on("SIGINT", () => {
965
+ this.exit();
966
+ });
967
+ }
968
+ _handleUnexpectedExit() {
969
+ process.on("unhandledRejection", (error2) => {
970
+ console.error("Unhandled Rejection Error: ", error2);
971
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
972
+ process.exit(1);
973
+ });
974
+ process.on("uncaughtException", (error2) => {
975
+ console.error("Unhandled Exception Error: ", error2);
976
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
977
+ process.exit(1);
978
+ });
979
+ }
980
+ start() {
981
+ return __async(this, null, function* () {
982
+ });
983
+ }
984
+ exit() {
985
+ const brokerExitLog = new BrokerExitLog();
986
+ this.broadcast(JSON.stringify(brokerExitLog));
987
+ this._disconnect();
988
+ this._clearSchedule();
989
+ this._clearTmpSubScriberRelations();
990
+ this._webSocketServer && this._webSocketServer.close();
991
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
992
+ process.exit(0);
993
+ }
994
+ broadcast(message) {
995
+ var _a3, _b;
996
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
997
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.clients.forEach((client) => {
998
+ client.send(JSON.stringify(message));
999
+ });
1000
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1001
+ client.send(JSON.stringify(message));
1002
+ });
1003
+ }
1004
+ };
1005
+ __name(_Broker, "Broker");
1006
+ __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1007
+ __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1008
+ __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1009
+ __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1010
+ var Broker = _Broker;
1011
+
1012
+ // packages/dts-plugin/src/server/broker/createBroker.ts
1013
+ import { fork } from "child_process";
1014
+ import path from "path";
1015
+ function createBroker() {
1016
+ const startBrokerPath = path.resolve(__dirname, "./start-broker.js");
1017
+ const sub = fork(startBrokerPath, [], {
1018
+ detached: true,
1019
+ stdio: "ignore",
1020
+ env: process.env
1021
+ });
1022
+ sub.send("start");
1023
+ sub.unref();
1024
+ return sub;
1025
+ }
1026
+ __name(createBroker, "createBroker");
1027
+
1028
+ // packages/dts-plugin/src/server/DevServer.ts
1029
+ var _ModuleFederationDevServer = class _ModuleFederationDevServer {
1030
+ constructor(ctx) {
1031
+ __publicField(this, "_remotes");
1032
+ __publicField(this, "_ip");
1033
+ __publicField(this, "_name");
1034
+ __publicField(this, "_remoteTypeTarPath");
1035
+ __publicField(this, "_publishWebSocket", null);
1036
+ __publicField(this, "_subscriberWebsocketMap", {});
1037
+ __publicField(this, "_reconnect", true);
1038
+ __publicField(this, "_reconnectTimes", 0);
1039
+ __publicField(this, "_isConnected", false);
1040
+ __publicField(this, "_isReconnecting", false);
1041
+ __publicField(this, "_updateCallback", /* @__PURE__ */ __name(() => Promise.resolve(void 0), "_updateCallback"));
1042
+ const { name, remotes, remoteTypeTarPath, updateCallback } = ctx;
1043
+ this._ip = getIPV4();
1044
+ this._name = name;
1045
+ this._remotes = remotes;
1046
+ this._remoteTypeTarPath = remoteTypeTarPath;
1047
+ this._updateCallback = updateCallback;
1048
+ this._stopWhenSIGTERMOrSIGINT();
1049
+ this._handleUnexpectedExit();
1050
+ this._connectPublishToServer();
1051
+ }
1052
+ _connectPublishToServer() {
1053
+ if (!this._reconnect) {
1054
+ return;
1055
+ }
1056
+ fileLog(`Publisher:${this._name} Trying to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1057
+ this._publishWebSocket = new WebSocket2(`ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1058
+ this._publishWebSocket.on("open", () => {
1059
+ var _a3;
1060
+ fileLog(`Current pid: ${process.pid}, publisher:${this._name} connected to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1061
+ this._isConnected = true;
1062
+ const startGarfishModule = new AddPublisherAction({
1063
+ name: this._name,
1064
+ ip: this._ip,
1065
+ remoteTypeTarPath: this._remoteTypeTarPath
1066
+ });
1067
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(startGarfishModule));
1068
+ this._connectSubscribers();
1069
+ });
1070
+ this._publishWebSocket.on("message", (message) => __async(this, null, function* () {
1071
+ var _a3, _b;
1072
+ try {
1073
+ const parsedMessage = JSON.parse(message.toString());
1074
+ if (parsedMessage.type === "Log") {
1075
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1076
+ fileLog(`Receive broker exit signal, ${this._name} service will exit...`, MF_SERVER_IDENTIFIER, "warn");
1077
+ this._exit();
1078
+ }
1079
+ }
1080
+ if (parsedMessage.type === "API") {
1081
+ if (parsedMessage.kind === APIKind.FETCH_TYPES) {
1082
+ const { payload: { remoteInfo } } = parsedMessage;
1083
+ fileLog(`${this._name} Receive broker FETCH_TYPES, payload as follows: ${JSON.stringify(remoteInfo, null, 2)}.`, MF_SERVER_IDENTIFIER, "info");
1084
+ yield this.fetchDynamicRemoteTypes({
1085
+ remoteInfo
1086
+ });
1087
+ }
1088
+ }
1089
+ } catch (err) {
1090
+ console.error(err);
1091
+ const exitPublisher = new ExitPublisherAction({
1092
+ name: this._name,
1093
+ ip: this._ip
1094
+ });
1095
+ const exitSubscriber = new ExitSubscriberAction({
1096
+ name: this._name,
1097
+ ip: this._ip,
1098
+ publishers: this._remotes.map((remote) => ({
1099
+ name: remote.name,
1100
+ ip: remote.ip
1101
+ }))
1102
+ });
1103
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(exitPublisher));
1104
+ (_b = this._publishWebSocket) == null ? void 0 : _b.send(JSON.stringify(exitSubscriber));
1105
+ fileLog("Parse messages error, ModuleFederationDevServer will exit...", MF_SERVER_IDENTIFIER, "fatal");
1106
+ this._exit();
1107
+ }
1108
+ }));
1109
+ this._publishWebSocket.on("close", (code) => {
1110
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1111
+ this._publishWebSocket && this._publishWebSocket.close();
1112
+ this._publishWebSocket = null;
1113
+ if (!this._reconnect) {
1114
+ return;
1115
+ }
1116
+ const reconnectTime = fib(++this._reconnectTimes);
1117
+ fileLog(`start reconnecting to server after ${reconnectTime}s.`, MF_SERVER_IDENTIFIER, "info");
1118
+ setTimeout(() => this._connectPublishToServer(), reconnectTime * 1e3);
1119
+ });
1120
+ this._publishWebSocket.on("error", this._tryCreateBackgroundBroker.bind(this));
1121
+ }
1122
+ // Associate the remotes(Subscriber) to the Broker
1123
+ _connectSubscriberToServer(remote) {
1124
+ const { name, ip } = remote;
1125
+ fileLog(`remote module:${name} trying to connect to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1126
+ const identifier = getIdentifier({
1127
+ name,
1128
+ ip
1129
+ });
1130
+ this._subscriberWebsocketMap[identifier] = new WebSocket2(`ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1131
+ this._subscriberWebsocketMap[identifier].on("open", () => {
1132
+ fileLog(`Current pid: ${process.pid} remote module: ${name} connected to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1133
+ const addSubscriber = new AddSubscriberAction({
1134
+ name: this._name,
1135
+ ip: this._ip,
1136
+ publishers: [
1137
+ {
1138
+ name,
1139
+ ip
1140
+ }
1141
+ ]
1142
+ });
1143
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(addSubscriber));
1144
+ });
1145
+ this._subscriberWebsocketMap[identifier].on("message", (message) => __async(this, null, function* () {
1146
+ try {
1147
+ const parsedMessage = JSON.parse(message.toString());
1148
+ if (parsedMessage.type === "Log") {
1149
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1150
+ fileLog(`${identifier}'s Server exit, thus ${identifier} will no longer has reload ability.`, MF_SERVER_IDENTIFIER, "warn");
1151
+ this._exit();
1152
+ }
1153
+ }
1154
+ if (parsedMessage.type === "API") {
1155
+ if (parsedMessage.kind === APIKind.UPDATE_SUBSCRIBER) {
1156
+ const { payload: { updateKind, updateSourcePaths, name: subscribeName, remoteTypeTarPath, updateMode } } = parsedMessage;
1157
+ yield this._updateSubscriber({
1158
+ remoteTypeTarPath,
1159
+ name: subscribeName,
1160
+ updateKind,
1161
+ updateMode,
1162
+ updateSourcePaths
1163
+ });
1164
+ }
1165
+ }
1166
+ } catch (err) {
1167
+ console.error(err);
1168
+ const exitSubscriber = new ExitSubscriberAction({
1169
+ name: this._name,
1170
+ ip: this._ip,
1171
+ publishers: [
1172
+ {
1173
+ name,
1174
+ ip
1175
+ }
1176
+ ]
1177
+ });
1178
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(exitSubscriber));
1179
+ fileLog(`${identifier} exit,
1180
+ error: ${err instanceof Error ? err.toString() : JSON.stringify(err)}
1181
+ `, MF_SERVER_IDENTIFIER, "warn");
1182
+ }
1183
+ }));
1184
+ this._subscriberWebsocketMap[identifier].on("close", (code) => {
1185
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1186
+ this._subscriberWebsocketMap[identifier] && this._subscriberWebsocketMap[identifier].close();
1187
+ delete this._subscriberWebsocketMap[identifier];
1188
+ });
1189
+ }
1190
+ _connectSubscribers() {
1191
+ this._remotes.forEach((remote) => {
1192
+ this._connectSubscriberToServer(remote);
1193
+ });
1194
+ }
1195
+ // app1 consumes provider1. And the function will be triggered when provider1 code change.
1196
+ _updateSubscriber(options) {
1197
+ return __async(this, null, function* () {
1198
+ var _a3;
1199
+ const { updateMode, updateKind, updateSourcePaths, name, remoteTypeTarPath, remoteInfo } = options;
1200
+ fileLog(
1201
+ // eslint-disable-next-line max-len
1202
+ `[_updateSubscriber] run, options: ${JSON.stringify(options, null, 2)}`,
1203
+ MF_SERVER_IDENTIFIER,
1204
+ "warn"
1205
+ );
1206
+ if (updateMode === UpdateMode.PASSIVE && updateSourcePaths.includes(this._name)) {
1207
+ fileLog(
1208
+ // eslint-disable-next-line max-len
1209
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} includes ${this._name}, update ignore!`,
1210
+ MF_SERVER_IDENTIFIER,
1211
+ "warn"
1212
+ );
1213
+ return;
1214
+ }
1215
+ if (updateSourcePaths.slice(-1)[0] === this._name) {
1216
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} ends is ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
1217
+ return;
1218
+ }
1219
+ fileLog(
1220
+ // eslint-disable-next-line max-len
1221
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths}, current module:${this._name}, update start...`,
1222
+ MF_SERVER_IDENTIFIER,
1223
+ "info"
1224
+ );
1225
+ yield this._updateCallback({
1226
+ name,
1227
+ updateMode,
1228
+ updateKind,
1229
+ updateSourcePaths,
1230
+ remoteTypeTarPath,
1231
+ remoteInfo
1232
+ });
1233
+ const newUpdateSourcePaths = updateSourcePaths.concat(this._name);
1234
+ const updatePublisher = new UpdatePublisherAction({
1235
+ name: this._name,
1236
+ ip: this._ip,
1237
+ updateMode: UpdateMode.PASSIVE,
1238
+ updateKind,
1239
+ updateSourcePaths: newUpdateSourcePaths,
1240
+ remoteTypeTarPath: this._remoteTypeTarPath
1241
+ });
1242
+ fileLog(
1243
+ // eslint-disable-next-line max-len
1244
+ `[_updateSubscriber] run, updateSourcePaths:${newUpdateSourcePaths}, update publisher ${this._name} start...`,
1245
+ MF_SERVER_IDENTIFIER,
1246
+ "info"
1247
+ );
1248
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(updatePublisher));
1249
+ });
1250
+ }
1251
+ _tryCreateBackgroundBroker(err) {
1252
+ if (!((err == null ? void 0 : err.code) === "ECONNREFUSED" && err.port === Broker.DEFAULT_WEB_SOCKET_PORT)) {
1253
+ fileLog(`websocket error: ${err.stack}`, MF_SERVER_IDENTIFIER, "fatal");
1254
+ return;
1255
+ }
1256
+ fileLog(`Failed to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "fatal");
1257
+ this._isReconnecting = true;
1258
+ setTimeout(() => {
1259
+ this._isReconnecting = false;
1260
+ if (this._reconnect === false) {
1261
+ return;
1262
+ }
1263
+ fileLog("Creating new background broker...", MF_SERVER_IDENTIFIER, "warn");
1264
+ const broker = createBroker();
1265
+ broker.on("message", (message) => {
1266
+ if (message === "ready") {
1267
+ fileLog("background broker started.", MF_SERVER_IDENTIFIER, "info");
1268
+ this._reconnectTimes = 1;
1269
+ if (process.send) {
1270
+ process.send("ready");
1271
+ }
1272
+ }
1273
+ });
1274
+ }, Math.ceil(100 * Math.random()));
1275
+ }
1276
+ _stopWhenSIGTERMOrSIGINT() {
1277
+ process.on("SIGTERM", () => {
1278
+ fileLog(`Process(${process.pid}) SIGTERM, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1279
+ this._exit();
1280
+ });
1281
+ process.on("SIGINT", () => {
1282
+ fileLog(`Process(${process.pid}) SIGINT, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1283
+ this._exit();
1284
+ });
1285
+ }
1286
+ _handleUnexpectedExit() {
1287
+ process.on("unhandledRejection", (error2) => {
1288
+ if (this._isReconnecting) {
1289
+ return;
1290
+ }
1291
+ console.error("Unhandled Rejection Error: ", error2);
1292
+ fileLog(`Process(${process.pid}) unhandledRejection, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1293
+ this._exit();
1294
+ });
1295
+ process.on("uncaughtException", (error2) => {
1296
+ if (this._isReconnecting) {
1297
+ return;
1298
+ }
1299
+ console.error("Unhandled Exception Error: ", error2);
1300
+ fileLog(`Process(${process.pid}) uncaughtException, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1301
+ this._exit();
1302
+ });
1303
+ }
1304
+ _exit() {
1305
+ this._reconnect = false;
1306
+ if (this._publishWebSocket) {
1307
+ const exitPublisher = new ExitPublisherAction({
1308
+ name: this._name,
1309
+ ip: this._ip
1310
+ });
1311
+ this._publishWebSocket.send(JSON.stringify(exitPublisher));
1312
+ this._publishWebSocket.on("message", (message) => {
1313
+ const parsedMessage = JSON.parse(message.toString());
1314
+ fileLog(`[${parsedMessage.kind}]: ${JSON.stringify(parsedMessage)}`, MF_SERVER_IDENTIFIER, "info");
1315
+ });
1316
+ }
1317
+ if (this._publishWebSocket) {
1318
+ this._publishWebSocket.close();
1319
+ this._publishWebSocket = null;
1320
+ }
1321
+ process.exit(0);
1322
+ }
1323
+ exit() {
1324
+ this._exit();
1325
+ }
1326
+ update(options) {
1327
+ if (!this._publishWebSocket || !this._isConnected) {
1328
+ return;
1329
+ }
1330
+ const { updateKind, updateMode, updateSourcePaths } = options;
1331
+ fileLog(`update run, ${this._name} module update, updateKind: ${updateKind}, updateMode: ${updateMode}, updateSourcePaths: ${updateSourcePaths}`, MF_SERVER_IDENTIFIER, "info");
1332
+ if (updateKind === UpdateKind.RELOAD_PAGE) {
1333
+ const notifyWebClient = new NotifyWebClientAction({
1334
+ name: this._name,
1335
+ updateMode
1336
+ });
1337
+ this._publishWebSocket.send(JSON.stringify(notifyWebClient));
1338
+ return;
1339
+ }
1340
+ const updatePublisher = new UpdatePublisherAction({
1341
+ name: this._name,
1342
+ ip: this._ip,
1343
+ updateMode,
1344
+ updateKind,
1345
+ updateSourcePaths: [
1346
+ this._name
1347
+ ],
1348
+ remoteTypeTarPath: this._remoteTypeTarPath
1349
+ });
1350
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1351
+ }
1352
+ fetchDynamicRemoteTypes(options) {
1353
+ return __async(this, null, function* () {
1354
+ const { remoteInfo, once } = options;
1355
+ const updateMode = UpdateMode.PASSIVE;
1356
+ const updateKind = UpdateKind.UPDATE_TYPE;
1357
+ fileLog(`fetchDynamicRemoteTypes: remoteInfo: ${JSON.stringify(remoteInfo)}`, MF_SERVER_IDENTIFIER, "info");
1358
+ yield this._updateCallback({
1359
+ name: this._name,
1360
+ updateMode,
1361
+ updateKind,
1362
+ updateSourcePaths: [],
1363
+ remoteTypeTarPath: "",
1364
+ remoteInfo,
1365
+ once
1366
+ });
1367
+ const updatePublisher = new UpdatePublisherAction({
1368
+ name: this._name,
1369
+ ip: this._ip,
1370
+ updateMode,
1371
+ updateKind,
1372
+ updateSourcePaths: [
1373
+ this._name
1374
+ ],
1375
+ remoteTypeTarPath: this._remoteTypeTarPath
1376
+ });
1377
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1378
+ });
1379
+ }
1380
+ };
1381
+ __name(_ModuleFederationDevServer, "ModuleFederationDevServer");
1382
+ var ModuleFederationDevServer = _ModuleFederationDevServer;
1383
+
1384
+ // packages/dts-plugin/src/server/createKoaServer.ts
1385
+ import fs from "fs-extra";
1386
+ import Koa from "koa";
1387
+ function createKoaServer(options) {
1388
+ return __async(this, null, function* () {
1389
+ const { typeTarPath } = options;
1390
+ const freeport = yield getFreePort();
1391
+ const app = new Koa();
1392
+ app.use((ctx, next) => __async(this, null, function* () {
1393
+ if (ctx.path === `/${DEFAULT_TAR_NAME}`) {
1394
+ ctx.status = 200;
1395
+ ctx.body = fs.createReadStream(typeTarPath);
1396
+ ctx.response.type = "application/x-gzip";
1397
+ } else {
1398
+ yield next();
1399
+ }
1400
+ }));
1401
+ app.listen(freeport);
1402
+ return {
1403
+ server: app,
1404
+ serverAddress: `http://${getIPV4()}:${freeport}`
1405
+ };
1406
+ });
1407
+ }
1408
+ __name(createKoaServer, "createKoaServer");
1409
+
1410
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
1411
+ var retrieveTypesZipPath = /* @__PURE__ */ __name((mfTypesPath, remoteOptions) => join2(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`), "retrieveTypesZipPath");
1412
+ var createTypesArchive = /* @__PURE__ */ __name((tsConfig, remoteOptions) => __async(void 0, null, function* () {
1413
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1414
+ const zip = new AdmZip();
1415
+ zip.addLocalFolder(mfTypesPath);
1416
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1417
+ }), "createTypesArchive");
1418
+ var downloadErrorLogger = /* @__PURE__ */ __name((destinationFolder, fileToDownload) => (reason) => {
1419
+ throw __spreadProps(__spreadValues({}, reason), {
1420
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1421
+ });
1422
+ }, "downloadErrorLogger");
1423
+ var retrieveTypesArchiveDestinationPath = /* @__PURE__ */ __name((hostOptions, destinationFolder) => {
1424
+ return resolve2(hostOptions.context, hostOptions.typesFolder, destinationFolder);
1425
+ }, "retrieveTypesArchiveDestinationPath");
1426
+ var downloadTypesArchive = /* @__PURE__ */ __name((hostOptions) => {
1427
+ let retries = 0;
1428
+ return (_0) => __async(void 0, [_0], function* ([destinationFolder, fileToDownload]) {
1429
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
1430
+ while (retries++ < hostOptions.maxRetries) {
1431
+ try {
1432
+ const url = fileToDownload;
1433
+ const response = yield axiosGet(url, {
1434
+ responseType: "arraybuffer"
1435
+ }).catch(downloadErrorLogger(destinationFolder, url));
1436
+ try {
1437
+ if (hostOptions.deleteTypesFolder) {
1438
+ yield rm(destinationPath, {
1439
+ recursive: true,
1440
+ force: true
1441
+ });
1442
+ }
1443
+ } catch (error2) {
1444
+ fileLog(`Unable to remove types folder, ${error2}`, "downloadTypesArchive", "error");
1445
+ }
1446
+ const zip = new AdmZip(Buffer.from(response.data));
1447
+ zip.extractAllTo(destinationPath, true);
1448
+ return [
1449
+ destinationFolder,
1450
+ destinationPath
1451
+ ];
1452
+ } catch (error2) {
1453
+ fileLog(`Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`, "downloadTypesArchive", "error");
1454
+ if (retries >= hostOptions.maxRetries) {
1455
+ if (hostOptions.abortOnError !== false) {
1456
+ throw error2;
1457
+ }
1458
+ return void 0;
1459
+ }
1460
+ }
1461
+ }
1462
+ });
1463
+ }, "downloadTypesArchive");
1464
+
1465
+ // packages/dts-plugin/src/core/configurations/hostPlugin.ts
1466
+ import { parseEntry, ENCODE_NAME_PREFIX, decodeName } from "@module-federation/sdk";
1467
+ import { utils } from "@module-federation/managers";
1468
+ var defaultOptions = {
1469
+ typesFolder: "@mf-types",
1470
+ remoteTypesFolder: "@mf-types",
1471
+ deleteTypesFolder: true,
1472
+ maxRetries: 3,
1473
+ implementation: "",
1474
+ context: process.cwd(),
1475
+ abortOnError: true,
1476
+ consumeAPITypes: false
1477
+ };
1478
+ var buildZipUrl = /* @__PURE__ */ __name((hostOptions, url) => {
1479
+ const remoteUrl = new URL(url, "file:");
1480
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
1481
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
1482
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
1483
+ }, "buildZipUrl");
1484
+ var buildApiTypeUrl = /* @__PURE__ */ __name((zipUrl) => {
1485
+ if (!zipUrl) {
1486
+ return void 0;
1487
+ }
1488
+ return zipUrl.replace(".zip", ".d.ts");
1489
+ }, "buildApiTypeUrl");
1490
+ var retrieveRemoteInfo = /* @__PURE__ */ __name((options) => {
1491
+ const { hostOptions, remoteAlias, remote } = options;
1492
+ let decodedRemote = remote;
1493
+ if (decodedRemote.startsWith(ENCODE_NAME_PREFIX)) {
1494
+ decodedRemote = decodeName(decodedRemote, ENCODE_NAME_PREFIX);
1495
+ }
1496
+ const parsedInfo = parseEntry(decodedRemote, void 0, "@");
1497
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
1498
+ const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
1499
+ return {
1500
+ name: parsedInfo.name || remoteAlias,
1501
+ url,
1502
+ zipUrl,
1503
+ apiTypeUrl: buildApiTypeUrl(zipUrl),
1504
+ alias: remoteAlias
1505
+ };
1506
+ }, "retrieveRemoteInfo");
1507
+ var resolveRemotes = /* @__PURE__ */ __name((hostOptions) => {
1508
+ const parsedOptions = utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
1509
+ remote: Array.isArray(item) ? item[0] : item,
1510
+ key
1511
+ }), (item, key) => ({
1512
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
1513
+ key
1514
+ }));
1515
+ return parsedOptions.reduce((accumulator, item) => {
1516
+ const { key, remote } = item[1];
1517
+ accumulator[key] = retrieveRemoteInfo({
1518
+ hostOptions,
1519
+ remoteAlias: key,
1520
+ remote
1521
+ });
1522
+ return accumulator;
1523
+ }, {});
1524
+ }, "resolveRemotes");
1525
+ var retrieveHostConfig = /* @__PURE__ */ __name((options) => {
1526
+ validateOptions(options);
1527
+ const hostOptions = __spreadValues(__spreadValues({}, defaultOptions), options);
1528
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
1529
+ return {
1530
+ hostOptions,
1531
+ mapRemotesToDownload
1532
+ };
1533
+ }, "retrieveHostConfig");
1534
+
1535
+ // packages/dts-plugin/src/core/lib/DTSManager.ts
1536
+ var _a;
1537
+ var DTSManager = (_a = class {
1538
+ constructor(options) {
1539
+ __publicField(this, "options");
1540
+ __publicField(this, "runtimePkgs");
1541
+ __publicField(this, "remoteAliasMap");
1542
+ __publicField(this, "loadedRemoteAPIAlias");
1543
+ __publicField(this, "extraOptions");
1544
+ __publicField(this, "updatedRemoteInfos");
1545
+ this.options = cloneDeepWith(options, (_value, key) => {
1546
+ if (key === "manifest") {
1547
+ return false;
1548
+ }
1549
+ });
1550
+ this.runtimePkgs = [
1551
+ "@module-federation/runtime",
1552
+ "@module-federation/enhanced/runtime",
1553
+ "@module-federation/runtime-tools"
1554
+ ];
1555
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
1556
+ this.remoteAliasMap = {};
1557
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
1558
+ this.updatedRemoteInfos = {};
1559
+ }
1560
+ generateAPITypes(mapComponentsToExpose) {
1561
+ const exposePaths = /* @__PURE__ */ new Set();
1562
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
1563
+ const exposePath = path2.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(path2.sep).join("/");
1564
+ exposePaths.add(`'${exposePath}'`);
1565
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
1566
+ sum = curType + sum;
1567
+ return sum;
1568
+ }, "any;");
1569
+ const exposePathKeys = [
1570
+ ...exposePaths
1571
+ ].join(" | ");
1572
+ return `
1573
+ export type RemoteKeys = ${exposePathKeys};
1574
+ type PackageType<T> = ${packageType}`;
1575
+ }
1576
+ extractRemoteTypes(options) {
1577
+ return __async(this, null, function* () {
1578
+ const { remoteOptions, tsConfig } = options;
1579
+ if (!remoteOptions.extractRemoteTypes) {
1580
+ return;
1581
+ }
1582
+ let hasRemotes = false;
1583
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
1584
+ if (remotes) {
1585
+ if (Array.isArray(remotes)) {
1586
+ hasRemotes = Boolean(remotes.length);
1587
+ } else if (typeof remotes === "object") {
1588
+ hasRemotes = Boolean(Object.keys(remotes).length);
1589
+ }
1590
+ }
1591
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1592
+ if (hasRemotes) {
1593
+ const tempHostOptions = {
1594
+ moduleFederationConfig: remoteOptions.moduleFederationConfig,
1595
+ typesFolder: path2.join(mfTypesPath, "node_modules"),
1596
+ remoteTypesFolder: (remoteOptions == null ? void 0 : remoteOptions.hostRemoteTypesFolder) || remoteOptions.typesFolder,
1597
+ deleteTypesFolder: true,
1598
+ context: remoteOptions.context,
1599
+ implementation: remoteOptions.implementation,
1600
+ abortOnError: false
1601
+ };
1602
+ yield this.consumeArchiveTypes(tempHostOptions);
1603
+ }
1604
+ });
1605
+ }
1606
+ generateTypes() {
1607
+ return __async(this, null, function* () {
1608
+ var _a3;
1609
+ try {
1610
+ const { options } = this;
1611
+ if (!options.remote) {
1612
+ throw new Error("options.remote is required if you want to generateTypes");
1613
+ }
1614
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
1615
+ if (!Object.keys(mapComponentsToExpose).length) {
1616
+ return;
1617
+ }
1618
+ this.extractRemoteTypes({
1619
+ remoteOptions,
1620
+ tsConfig,
1621
+ mapComponentsToExpose
1622
+ });
1623
+ compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
1624
+ yield createTypesArchive(tsConfig, remoteOptions);
1625
+ let apiTypesPath = "";
1626
+ if (remoteOptions.generateAPITypes) {
1627
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
1628
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1629
+ fs2.writeFileSync(apiTypesPath, apiTypes);
1630
+ }
1631
+ try {
1632
+ if (remoteOptions.deleteTypesFolder) {
1633
+ yield rm2(retrieveMfTypesPath(tsConfig, remoteOptions), {
1634
+ recursive: true,
1635
+ force: true
1636
+ });
1637
+ }
1638
+ } catch (err) {
1639
+ if (isDebugMode()) {
1640
+ console.error(err);
1641
+ }
1642
+ }
1643
+ console.log(ansiColors2.green("Federated types created correctly"));
1644
+ } catch (error2) {
1645
+ if (((_a3 = this.options.remote) == null ? void 0 : _a3.abortOnError) === false) {
1646
+ console.error(ansiColors2.red(`Unable to compile federated types, ${error2}`));
1647
+ } else {
1648
+ throw error2;
1649
+ }
1650
+ }
1651
+ });
1652
+ }
1653
+ requestRemoteManifest(remoteInfo) {
1654
+ return __async(this, null, function* () {
1655
+ try {
1656
+ if (!remoteInfo.url.includes(MANIFEST_EXT)) {
1657
+ return remoteInfo;
1658
+ }
1659
+ const url = remoteInfo.url;
1660
+ const res = yield axiosGet(url);
1661
+ const manifestJson = res.data;
1662
+ if (!manifestJson.metaData.types.zip) {
1663
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1664
+ }
1665
+ const addProtocol = /* @__PURE__ */ __name((u) => {
1666
+ if (u.startsWith("//")) {
1667
+ return `https:${u}`;
1668
+ }
1669
+ return u;
1670
+ }, "addProtocol");
1671
+ let publicPath = "publicPath" in manifestJson.metaData ? manifestJson.metaData.publicPath : new Function(manifestJson.metaData.getPublicPath)();
1672
+ if (publicPath === "auto") {
1673
+ publicPath = inferAutoPublicPath(remoteInfo.url);
1674
+ }
1675
+ remoteInfo.zipUrl = new URL(path2.join(addProtocol(publicPath), manifestJson.metaData.types.zip)).href;
1676
+ if (!manifestJson.metaData.types.api) {
1677
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
1678
+ remoteInfo.apiTypeUrl = "";
1679
+ return remoteInfo;
1680
+ }
1681
+ remoteInfo.apiTypeUrl = new URL(path2.join(addProtocol(publicPath), manifestJson.metaData.types.api)).href;
1682
+ return remoteInfo;
1683
+ } catch (_err) {
1684
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
1685
+ return remoteInfo;
1686
+ }
1687
+ });
1688
+ }
1689
+ consumeTargetRemotes(hostOptions, remoteInfo) {
1690
+ return __async(this, null, function* () {
1691
+ if (!remoteInfo.zipUrl) {
1692
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
1693
+ }
1694
+ const typesDownloader = downloadTypesArchive(hostOptions);
1695
+ return typesDownloader([
1696
+ remoteInfo.alias,
1697
+ remoteInfo.zipUrl
1698
+ ]);
1699
+ });
1700
+ }
1701
+ downloadAPITypes(remoteInfo, destinationPath) {
1702
+ return __async(this, null, function* () {
1703
+ const { apiTypeUrl } = remoteInfo;
1704
+ if (!apiTypeUrl) {
1705
+ return;
1706
+ }
1707
+ try {
1708
+ const url = apiTypeUrl;
1709
+ const res = yield axiosGet(url);
1710
+ let apiTypeFile = res.data;
1711
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
1712
+ const filePath = path2.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
1713
+ fs2.writeFileSync(filePath, apiTypeFile);
1714
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
1715
+ } catch (err) {
1716
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "consumeTargetRemotes", "error");
1717
+ }
1718
+ });
1719
+ }
1720
+ consumeAPITypes(hostOptions) {
1721
+ const apiTypeFileName = path2.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
1722
+ try {
1723
+ const existedFile = fs2.readFileSync(apiTypeFileName, "utf-8");
1724
+ const existedImports = new ThirdPartyExtractor2("").collectTypeImports(existedFile);
1725
+ existedImports.forEach((existedImport) => {
1726
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
1727
+ this.loadedRemoteAPIAlias.add(alias);
1728
+ });
1729
+ } catch (err) {
1730
+ }
1731
+ if (!this.loadedRemoteAPIAlias.size) {
1732
+ return;
1733
+ }
1734
+ const packageTypes = [];
1735
+ const remoteKeys = [];
1736
+ const importTypeStr = [
1737
+ ...this.loadedRemoteAPIAlias
1738
+ ].sort().map((alias, index) => {
1739
+ const remoteKey = `RemoteKeys_${index}`;
1740
+ const packageType = `PackageType_${index}`;
1741
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
1742
+ remoteKeys.push(remoteKey);
1743
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
1744
+ }).join("\n");
1745
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
1746
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
1747
+ ...packageTypes,
1748
+ "Y"
1749
+ ].join(" :\n")} ;`;
1750
+ const pkgsDeclareStr = this.runtimePkgs.map((pkg) => {
1751
+ return `declare module "${pkg}" {
1752
+ ${remoteKeysStr}
1753
+ ${packageTypesStr}
1754
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
1755
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
1756
+ }`;
1757
+ }).join("\n");
1758
+ const fileStr = `${importTypeStr}
1759
+ ${pkgsDeclareStr}
1760
+ `;
1761
+ fs2.writeFileSync(path2.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
1762
+ }
1763
+ consumeArchiveTypes(options) {
1764
+ return __async(this, null, function* () {
1765
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
1766
+ const downloadPromises = Object.entries(mapRemotesToDownload).map((item) => __async(this, null, function* () {
1767
+ const remoteInfo = item[1];
1768
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1769
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo);
1770
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1771
+ }
1772
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1773
+ }));
1774
+ const downloadPromisesResult = yield Promise.allSettled(downloadPromises);
1775
+ return {
1776
+ hostOptions,
1777
+ downloadPromisesResult
1778
+ };
1779
+ });
1780
+ }
1781
+ consumeTypes() {
1782
+ return __async(this, null, function* () {
1783
+ var _a3;
1784
+ try {
1785
+ const { options } = this;
1786
+ if (!options.host) {
1787
+ throw new Error("options.host is required if you want to consumeTypes");
1788
+ }
1789
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
1790
+ if (!Object.keys(mapRemotesToDownload).length) {
1791
+ return;
1792
+ }
1793
+ const { downloadPromisesResult, hostOptions } = yield this.consumeArchiveTypes(options.host);
1794
+ if (hostOptions.consumeAPITypes) {
1795
+ yield Promise.all(downloadPromisesResult.map((item) => __async(this, null, function* () {
1796
+ if (item.status === "rejected" || !item.value) {
1797
+ return;
1798
+ }
1799
+ const [alias, destinationPath] = item.value;
1800
+ const remoteInfo = this.remoteAliasMap[alias];
1801
+ if (!remoteInfo) {
1802
+ return;
1803
+ }
1804
+ yield this.downloadAPITypes(remoteInfo, destinationPath);
1805
+ })));
1806
+ this.consumeAPITypes(hostOptions);
1807
+ }
1808
+ console.log(ansiColors2.green("Federated types extraction completed"));
1809
+ } catch (err) {
1810
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1811
+ fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
1812
+ } else {
1813
+ throw err;
1814
+ }
1815
+ }
1816
+ });
1817
+ }
1818
+ updateTypes(options) {
1819
+ return __async(this, null, function* () {
1820
+ var _a3, _b, _c;
1821
+ try {
1822
+ const { remoteName, updateMode, remoteInfo: updatedRemoteInfo, once } = options;
1823
+ const hostName = (_c = (_b = (_a3 = this.options) == null ? void 0 : _a3.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
1824
+ fileLog(`updateTypes options:, ${JSON.stringify(options, null, 2)}`, "consumeTypes", "info");
1825
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
1826
+ if (!this.options.remote) {
1827
+ return;
1828
+ }
1829
+ this.generateTypes();
1830
+ } else {
1831
+ const { remoteAliasMap } = this;
1832
+ if (!this.options.host) {
1833
+ return;
1834
+ }
1835
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
1836
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
1837
+ if (!loadedRemoteInfo) {
1838
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
1839
+ return item.name === remoteName;
1840
+ });
1841
+ if (remoteInfo) {
1842
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
1843
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo);
1844
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
1845
+ }
1846
+ yield this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
1847
+ } else if (updatedRemoteInfo) {
1848
+ const consumeDynamicRemoteTypes = /* @__PURE__ */ __name(() => __async(this, null, function* () {
1849
+ const [_destinationFolder, destinationPath] = yield this.consumeTargetRemotes(hostOptions, this.updatedRemoteInfos[updatedRemoteInfo.name]);
1850
+ yield this.downloadAPITypes(this.updatedRemoteInfos[updatedRemoteInfo.name], destinationPath);
1851
+ this.consumeAPITypes(hostOptions);
1852
+ }), "consumeDynamicRemoteTypes");
1853
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1854
+ const parsedRemoteInfo = retrieveRemoteInfo({
1855
+ hostOptions,
1856
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
1857
+ remote: updatedRemoteInfo.url
1858
+ });
1859
+ fileLog(`start request manifest`, "consumeTypes", "info");
1860
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = yield this.requestRemoteManifest(parsedRemoteInfo);
1861
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "consumeTypes", "info");
1862
+ yield consumeDynamicRemoteTypes();
1863
+ }
1864
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) {
1865
+ yield consumeDynamicRemoteTypes();
1866
+ }
1867
+ }
1868
+ } else {
1869
+ yield this.consumeTargetRemotes(hostOptions, loadedRemoteInfo);
1870
+ }
1871
+ }
1872
+ } catch (err) {
1873
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
1874
+ }
1875
+ });
1876
+ }
1877
+ }, __name(_a, "DTSManager"), _a);
1878
+
1879
+ // packages/dts-plugin/src/core/lib/utils.ts
1880
+ function getDTSManagerConstructor(implementation) {
1881
+ if (implementation) {
1882
+ const NewConstructor = __require(implementation);
1883
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
1884
+ }
1885
+ return DTSManager;
1886
+ }
1887
+ __name(getDTSManagerConstructor, "getDTSManagerConstructor");
1888
+ var validateOptions = /* @__PURE__ */ __name((options) => {
1889
+ if (!options.moduleFederationConfig) {
1890
+ throw new Error("moduleFederationConfig is required");
1891
+ }
1892
+ }, "validateOptions");
1893
+ function retrieveTypesAssetsInfo(options) {
1894
+ let apiTypesPath = "";
1895
+ let zipTypesPath = "";
1896
+ try {
1897
+ const { tsConfig, remoteOptions, mapComponentsToExpose } = retrieveRemoteConfig(options);
1898
+ if (!Object.keys(mapComponentsToExpose).length) {
1899
+ return {
1900
+ apiTypesPath,
1901
+ zipTypesPath,
1902
+ zipName: "",
1903
+ apiFileName: ""
1904
+ };
1905
+ }
1906
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1907
+ zipTypesPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
1908
+ if (remoteOptions.generateAPITypes) {
1909
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1910
+ }
1911
+ return {
1912
+ apiTypesPath,
1913
+ zipTypesPath,
1914
+ zipName: path3.basename(zipTypesPath),
1915
+ apiFileName: path3.basename(apiTypesPath)
1916
+ };
1917
+ } catch (err) {
1918
+ console.error(ansiColors3.red(`Unable to compile federated types, ${err}`));
1919
+ return {
1920
+ apiTypesPath: "",
1921
+ zipTypesPath: "",
1922
+ zipName: "",
1923
+ apiFileName: ""
1924
+ };
1925
+ }
1926
+ }
1927
+ __name(retrieveTypesAssetsInfo, "retrieveTypesAssetsInfo");
1928
+ function isDebugMode() {
1929
+ return Boolean(process.env["FEDERATION_DEBUG"]);
1930
+ }
1931
+ __name(isDebugMode, "isDebugMode");
1932
+ var isTSProject = /* @__PURE__ */ __name((dtsOptions, context = process.cwd()) => {
1933
+ if (dtsOptions === false) {
1934
+ return false;
1935
+ }
1936
+ try {
1937
+ let filepath = "";
1938
+ if (typeof dtsOptions === "object" && dtsOptions.tsConfigPath) {
1939
+ filepath = dtsOptions.tsConfigPath;
1940
+ } else {
1941
+ filepath = path3.resolve(context, "./tsconfig.json");
1942
+ }
1943
+ if (!path3.isAbsolute(filepath)) {
1944
+ filepath = path3.resolve(context, filepath);
1945
+ }
1946
+ return fs3.existsSync(filepath);
1947
+ } catch (err) {
1948
+ return false;
1949
+ }
1950
+ }, "isTSProject");
1951
+ function axiosGet(url, config) {
1952
+ return __async(this, null, function* () {
1953
+ const httpAgent = new http.Agent({
1954
+ family: 4
1955
+ });
1956
+ const httpsAgent = new https.Agent({
1957
+ family: 4
1958
+ });
1959
+ return axios.get(url, __spreadValues({
1960
+ httpAgent,
1961
+ httpsAgent
1962
+ }, config));
1963
+ });
1964
+ }
1965
+ __name(axiosGet, "axiosGet");
1966
+
1967
+ // packages/dts-plugin/src/core/configurations/remotePlugin.ts
1968
+ var defaultOptions2 = {
1969
+ tsConfigPath: "./tsconfig.json",
1970
+ typesFolder: "@mf-types",
1971
+ compiledTypesFolder: "compiled-types",
1972
+ hostRemoteTypesFolder: "@mf-types",
1973
+ deleteTypesFolder: true,
1974
+ additionalFilesToCompile: [],
1975
+ compilerInstance: "tsc",
1976
+ compileInChildProcess: false,
1977
+ implementation: "",
1978
+ generateAPITypes: false,
1979
+ context: process.cwd(),
1980
+ abortOnError: true,
1981
+ extractRemoteTypes: false,
1982
+ extractThirdParty: false
1983
+ };
1984
+ var readTsConfig = /* @__PURE__ */ __name(({ tsConfigPath, typesFolder, compiledTypesFolder, context }) => {
1985
+ const resolvedTsConfigPath = resolve3(context, tsConfigPath);
1986
+ const readResult = typescript2.readConfigFile(resolvedTsConfigPath, typescript2.sys.readFile);
1987
+ if (readResult.error) {
1988
+ throw new Error(readResult.error.messageText.toString());
1989
+ }
1990
+ const configContent = typescript2.parseJsonConfigFileContent(readResult.config, typescript2.sys, dirname2(resolvedTsConfigPath));
1991
+ const outDir = resolve3(context, configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
1992
+ return __spreadProps(__spreadValues({}, configContent.options), {
1993
+ emitDeclarationOnly: true,
1994
+ noEmit: false,
1995
+ declaration: true,
1996
+ outDir
1997
+ });
1998
+ }, "readTsConfig");
1999
+ var TS_EXTENSIONS = [
2000
+ "ts",
2001
+ "tsx",
2002
+ "vue",
2003
+ "svelte"
2004
+ ];
2005
+ var resolveWithExtension = /* @__PURE__ */ __name((exposedPath, context) => {
2006
+ if (extname(exposedPath)) {
2007
+ return resolve3(context, exposedPath);
2008
+ }
2009
+ for (const extension of TS_EXTENSIONS) {
2010
+ const exposedPathWithExtension = resolve3(context, `${exposedPath}.${extension}`);
2011
+ if (existsSync(exposedPathWithExtension)) {
2012
+ return exposedPathWithExtension;
2013
+ }
2014
+ }
2015
+ return void 0;
2016
+ }, "resolveWithExtension");
2017
+ var resolveExposes = /* @__PURE__ */ __name((remoteOptions) => {
2018
+ const parsedOptions = utils2.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
2019
+ exposePath: Array.isArray(item) ? item[0] : item,
2020
+ key
2021
+ }), (item, key) => ({
2022
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
2023
+ key
2024
+ }));
2025
+ return parsedOptions.reduce((accumulator, item) => {
2026
+ const { exposePath, key } = item[1];
2027
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension(join3(exposePath, "index"), remoteOptions.context) || exposePath;
2028
+ return accumulator;
2029
+ }, {});
2030
+ }, "resolveExposes");
2031
+ var retrieveRemoteConfig = /* @__PURE__ */ __name((options) => {
2032
+ validateOptions(options);
2033
+ const remoteOptions = __spreadValues(__spreadValues({}, defaultOptions2), options);
2034
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
2035
+ const tsConfig = readTsConfig(remoteOptions);
2036
+ return {
2037
+ tsConfig,
2038
+ mapComponentsToExpose,
2039
+ remoteOptions
2040
+ };
2041
+ }, "retrieveRemoteConfig");
2042
+
2043
+ // packages/dts-plugin/src/core/lib/generateTypes.ts
2044
+ function generateTypes(options) {
2045
+ return __async(this, null, function* () {
2046
+ var _a3;
2047
+ const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.remote) == null ? void 0 : _a3.implementation);
2048
+ const dtsManager = new DTSManagerConstructor(options);
2049
+ return dtsManager.generateTypes();
2050
+ });
2051
+ }
2052
+ __name(generateTypes, "generateTypes");
2053
+
2054
+ // packages/dts-plugin/src/core/lib/DtsWorker.ts
2055
+ import path4 from "path";
2056
+ import cloneDeepWith2 from "lodash.clonedeepwith";
2057
+
2058
+ // packages/dts-plugin/src/core/rpc/index.ts
2059
+ var rpc_exports = {};
2060
+ __export(rpc_exports, {
2061
+ RpcExitError: () => RpcExitError,
2062
+ RpcGMCallTypes: () => RpcGMCallTypes,
2063
+ createRpcWorker: () => createRpcWorker,
2064
+ exposeRpc: () => exposeRpc,
2065
+ getRpcWorkerData: () => getRpcWorkerData,
2066
+ wrapRpc: () => wrapRpc
2067
+ });
2068
+
2069
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
2070
+ import process2 from "process";
2071
+
2072
+ // packages/dts-plugin/src/core/rpc/types.ts
2073
+ var RpcGMCallTypes;
2074
+ (function(RpcGMCallTypes2) {
2075
+ RpcGMCallTypes2["CALL"] = "mf_call";
2076
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
2077
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
2078
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
2079
+ })(RpcGMCallTypes || (RpcGMCallTypes = {}));
2080
+
2081
+ // packages/dts-plugin/src/core/rpc/expose-rpc.ts
2082
+ function exposeRpc(fn) {
2083
+ const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve4, reject) => {
2084
+ if (!process2.send) {
2085
+ reject(new Error(`Process ${process2.pid} doesn't have IPC channels`));
2086
+ } else if (!process2.connected) {
2087
+ reject(new Error(`Process ${process2.pid} doesn't have open IPC channels`));
2088
+ } else {
2089
+ process2.send(message, void 0, void 0, (error2) => {
2090
+ if (error2) {
2091
+ reject(error2);
2092
+ } else {
2093
+ resolve4(void 0);
2094
+ }
2095
+ });
2096
+ }
2097
+ }), "sendMessage");
2098
+ const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
2099
+ if (message.type === RpcGMCallTypes.CALL) {
2100
+ if (!process2.send) {
2101
+ return;
2102
+ }
2103
+ let value, error2;
2104
+ try {
2105
+ value = yield fn(...message.args);
2106
+ } catch (fnError) {
2107
+ error2 = fnError;
2108
+ }
2109
+ try {
2110
+ if (error2) {
2111
+ yield sendMessage({
2112
+ type: RpcGMCallTypes.REJECT,
2113
+ id: message.id,
2114
+ error: error2
2115
+ });
2116
+ } else {
2117
+ yield sendMessage({
2118
+ type: RpcGMCallTypes.RESOLVE,
2119
+ id: message.id,
2120
+ value
2121
+ });
2122
+ }
2123
+ } catch (sendError) {
2124
+ if (error2) {
2125
+ if (error2 instanceof Error) {
2126
+ console.error(error2);
2127
+ }
2128
+ }
2129
+ console.error(sendError);
2130
+ }
2131
+ }
2132
+ }), "handleMessage");
2133
+ process2.on("message", handleMessage);
2134
+ }
2135
+ __name(exposeRpc, "exposeRpc");
2136
+
2137
+ // packages/dts-plugin/src/core/rpc/rpc-error.ts
2138
+ var _a2;
2139
+ var RpcExitError = (_a2 = class extends Error {
2140
+ constructor(message, code, signal) {
2141
+ super(message);
2142
+ __publicField(this, "code");
2143
+ __publicField(this, "signal");
2144
+ this.code = code;
2145
+ this.signal = signal;
2146
+ this.name = "RpcExitError";
2147
+ }
2148
+ }, __name(_a2, "RpcExitError"), _a2);
2149
+
2150
+ // packages/dts-plugin/src/core/rpc/wrap-rpc.ts
2151
+ function createControlledPromise() {
2152
+ let resolve4 = /* @__PURE__ */ __name(() => void 0, "resolve");
2153
+ let reject = /* @__PURE__ */ __name(() => void 0, "reject");
2154
+ const promise = new Promise((aResolve, aReject) => {
2155
+ resolve4 = aResolve;
2156
+ reject = aReject;
2157
+ });
2158
+ return {
2159
+ promise,
2160
+ resolve: resolve4,
2161
+ reject
2162
+ };
2163
+ }
2164
+ __name(createControlledPromise, "createControlledPromise");
2165
+ function wrapRpc(childProcess, options) {
2166
+ return (...args) => __async(this, null, function* () {
2167
+ if (!childProcess.send) {
2168
+ throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
2169
+ } else if (!childProcess.connected) {
2170
+ throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
2171
+ }
2172
+ const { id, once } = options;
2173
+ const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
2174
+ const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
2175
+ const handleMessage = /* @__PURE__ */ __name((message) => {
2176
+ if ((message == null ? void 0 : message.id) === id) {
2177
+ if (message.type === RpcGMCallTypes.RESOLVE) {
2178
+ resolveResult(message.value);
2179
+ } else if (message.type === RpcGMCallTypes.REJECT) {
2180
+ rejectResult(message.error);
2181
+ }
2182
+ }
2183
+ if (once && (childProcess == null ? void 0 : childProcess.kill)) {
2184
+ childProcess.kill("SIGTERM");
2185
+ }
2186
+ }, "handleMessage");
2187
+ const handleClose = /* @__PURE__ */ __name((code, signal) => {
2188
+ rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
2189
+ removeHandlers();
2190
+ }, "handleClose");
2191
+ const removeHandlers = /* @__PURE__ */ __name(() => {
2192
+ childProcess.off("message", handleMessage);
2193
+ childProcess.off("close", handleClose);
2194
+ }, "removeHandlers");
2195
+ if (once) {
2196
+ childProcess.once("message", handleMessage);
2197
+ } else {
2198
+ childProcess.on("message", handleMessage);
2199
+ }
2200
+ childProcess.on("close", handleClose);
2201
+ childProcess.send({
2202
+ type: RpcGMCallTypes.CALL,
2203
+ id,
2204
+ args
2205
+ }, (error2) => {
2206
+ if (error2) {
2207
+ rejectSend(error2);
2208
+ removeHandlers();
2209
+ } else {
2210
+ resolveSend(void 0);
2211
+ }
2212
+ });
2213
+ return sendPromise.then(() => resultPromise);
2214
+ });
2215
+ }
2216
+ __name(wrapRpc, "wrapRpc");
2217
+
2218
+ // packages/dts-plugin/src/core/rpc/rpc-worker.ts
2219
+ import * as child_process from "child_process";
2220
+ import * as process3 from "process";
2221
+ import { randomUUID } from "crypto";
2222
+ var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
2223
+ function createRpcWorker(modulePath, data, memoryLimit, once) {
2224
+ const options = {
2225
+ env: __spreadProps(__spreadValues({}, process3.env), {
2226
+ [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
2227
+ }),
2228
+ stdio: [
2229
+ "inherit",
2230
+ "inherit",
2231
+ "inherit",
2232
+ "ipc"
2233
+ ],
2234
+ serialization: "advanced"
2235
+ };
2236
+ if (memoryLimit) {
2237
+ options.execArgv = [
2238
+ `--max-old-space-size=${memoryLimit}`
2239
+ ];
2240
+ }
2241
+ let childProcess, remoteMethod;
2242
+ const id = randomUUID();
2243
+ const worker = {
2244
+ connect(...args) {
2245
+ if (childProcess && !childProcess.connected) {
2246
+ childProcess.send({
2247
+ type: RpcGMCallTypes.EXIT,
2248
+ id
2249
+ });
2250
+ childProcess = void 0;
2251
+ remoteMethod = void 0;
2252
+ }
2253
+ if (!(childProcess == null ? void 0 : childProcess.connected)) {
2254
+ childProcess = child_process.fork(modulePath, options);
2255
+ remoteMethod = wrapRpc(childProcess, {
2256
+ id,
2257
+ once
2258
+ });
2259
+ }
2260
+ if (!remoteMethod) {
2261
+ return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
2262
+ }
2263
+ return remoteMethod(...args);
2264
+ },
2265
+ terminate() {
2266
+ var _a3;
2267
+ (_a3 = childProcess == null ? void 0 : childProcess.send) == null ? void 0 : _a3.call(childProcess, {
2268
+ type: RpcGMCallTypes.EXIT,
2269
+ id
2270
+ });
2271
+ childProcess = void 0;
2272
+ remoteMethod = void 0;
2273
+ },
2274
+ get connected() {
2275
+ return Boolean(childProcess == null ? void 0 : childProcess.connected);
2276
+ },
2277
+ get process() {
2278
+ return childProcess;
2279
+ },
2280
+ get id() {
2281
+ return id;
2282
+ }
2283
+ };
2284
+ return worker;
2285
+ }
2286
+ __name(createRpcWorker, "createRpcWorker");
2287
+ function getRpcWorkerData() {
2288
+ return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
2289
+ }
2290
+ __name(getRpcWorkerData, "getRpcWorkerData");
2291
+
2292
+ // packages/dts-plugin/src/core/lib/DtsWorker.ts
2293
+ var _DtsWorker = class _DtsWorker {
2294
+ constructor(options) {
2295
+ __publicField(this, "rpcWorker");
2296
+ __publicField(this, "_options");
2297
+ __publicField(this, "_res");
2298
+ this._options = cloneDeepWith2(options, (_value, key) => {
2299
+ if (key === "manifest") {
2300
+ return false;
2301
+ }
2302
+ });
2303
+ this.removeUnSerializationOptions();
2304
+ this.rpcWorker = createRpcWorker(path4.resolve(__dirname, "./fork-generate-dts.js"), {}, void 0, true);
2305
+ this._res = this.rpcWorker.connect(this._options);
2306
+ }
2307
+ removeUnSerializationOptions() {
2308
+ var _a3, _b, _c, _d, _e, _f, _g, _h;
2309
+ if ((_b = (_a3 = this._options.remote) == null ? void 0 : _a3.moduleFederationConfig) == null ? void 0 : _b.manifest) {
2310
+ (_d = (_c = this._options.remote) == null ? void 0 : _c.moduleFederationConfig) == null ? true : delete _d.manifest;
2311
+ }
2312
+ if ((_f = (_e = this._options.host) == null ? void 0 : _e.moduleFederationConfig) == null ? void 0 : _f.manifest) {
2313
+ (_h = (_g = this._options.host) == null ? void 0 : _g.moduleFederationConfig) == null ? true : delete _h.manifest;
2314
+ }
2315
+ }
2316
+ get controlledPromise() {
2317
+ return Promise.resolve(this._res).then(() => {
2318
+ this.exit();
2319
+ });
2320
+ }
2321
+ exit() {
2322
+ var _a3;
2323
+ (_a3 = this.rpcWorker) == null ? void 0 : _a3.terminate();
2324
+ }
2325
+ };
2326
+ __name(_DtsWorker, "DtsWorker");
2327
+ var DtsWorker = _DtsWorker;
2328
+
2329
+ // packages/dts-plugin/src/core/lib/generateTypesInChildProcess.ts
2330
+ function generateTypesInChildProcess(options) {
2331
+ return __async(this, null, function* () {
2332
+ const dtsWorker = new DtsWorker(options);
2333
+ return dtsWorker.controlledPromise;
2334
+ });
2335
+ }
2336
+ __name(generateTypesInChildProcess, "generateTypesInChildProcess");
2337
+
2338
+ // packages/dts-plugin/src/core/lib/consumeTypes.ts
2339
+ function consumeTypes(options) {
2340
+ return __async(this, null, function* () {
2341
+ var _a3;
2342
+ const DTSManagerConstructor = getDTSManagerConstructor((_a3 = options.host) == null ? void 0 : _a3.implementation);
2343
+ const dtsManager = new DTSManagerConstructor(options);
2344
+ yield dtsManager.consumeTypes();
2345
+ });
2346
+ }
2347
+ __name(consumeTypes, "consumeTypes");
2348
+
2349
+ export {
2350
+ retrieveMfTypesPath,
2351
+ retrieveOriginalOutDir,
2352
+ fileLog,
2353
+ getIPV4,
2354
+ Broker,
2355
+ ModuleFederationDevServer,
2356
+ createKoaServer,
2357
+ retrieveTypesZipPath,
2358
+ retrieveHostConfig,
2359
+ DTSManager,
2360
+ getDTSManagerConstructor,
2361
+ validateOptions,
2362
+ retrieveTypesAssetsInfo,
2363
+ isTSProject,
2364
+ retrieveRemoteConfig,
2365
+ generateTypes,
2366
+ RpcGMCallTypes,
2367
+ exposeRpc,
2368
+ rpc_exports,
2369
+ DtsWorker,
2370
+ generateTypesInChildProcess,
2371
+ consumeTypes
2372
+ };