@module-federation/dts-plugin 0.0.0-feat-support-bridge-react-router-v7-20251015102312

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 (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/dist/CHANGELOG.md +1065 -0
  4. package/dist/DTSManager-b15Gfat3.d.ts +53 -0
  5. package/dist/DTSManagerOptions-QVchWb0x.d.ts +32 -0
  6. package/dist/DtsWorker-BrHsGz8C.d.ts +56 -0
  7. package/dist/README.md +1 -0
  8. package/dist/core.d.mts +68 -0
  9. package/dist/core.d.ts +68 -0
  10. package/dist/core.js +2365 -0
  11. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  12. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  13. package/dist/dynamic-remote-type-hints-plugin.js +196 -0
  14. package/dist/esm/chunk-2GDMDG2O.js +282 -0
  15. package/dist/esm/chunk-647HGGGS.js +241 -0
  16. package/dist/esm/chunk-ETMHGGQH.js +1564 -0
  17. package/dist/esm/chunk-G65LOFTY.js +24 -0
  18. package/dist/esm/chunk-WWV5RWOP.js +902 -0
  19. package/dist/esm/core.js +44 -0
  20. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  21. package/dist/esm/fork-dev-worker.js +145 -0
  22. package/dist/esm/fork-generate-dts.js +27 -0
  23. package/dist/esm/index.js +655 -0
  24. package/dist/esm/start-broker.js +36 -0
  25. package/dist/fork-dev-worker.d.mts +15 -0
  26. package/dist/fork-dev-worker.d.ts +15 -0
  27. package/dist/fork-dev-worker.js +2844 -0
  28. package/dist/fork-generate-dts.d.mts +10 -0
  29. package/dist/fork-generate-dts.d.ts +10 -0
  30. package/dist/fork-generate-dts.js +2015 -0
  31. package/dist/iife/launch-web-client.js +152 -0
  32. package/dist/index.d.mts +56 -0
  33. package/dist/index.d.ts +56 -0
  34. package/dist/index.js +2996 -0
  35. package/dist/package.json +87 -0
  36. package/dist/start-broker.d.mts +42 -0
  37. package/dist/start-broker.d.ts +42 -0
  38. package/dist/start-broker.js +958 -0
  39. package/dist/utils-BjKKtOcx.d.ts +16 -0
  40. package/package.json +87 -0
@@ -0,0 +1,2844 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
40
+ };
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
48
+ };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __publicField = (obj, key, value) => {
59
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
60
+ return value;
61
+ };
62
+ var __async = (__this, __arguments, generator) => {
63
+ return new Promise((resolve4, reject) => {
64
+ var fulfilled = (value) => {
65
+ try {
66
+ step(generator.next(value));
67
+ } catch (e) {
68
+ reject(e);
69
+ }
70
+ };
71
+ var rejected = (value) => {
72
+ try {
73
+ step(generator.throw(value));
74
+ } catch (e) {
75
+ reject(e);
76
+ }
77
+ };
78
+ var step = (x) => x.done ? resolve4(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
79
+ step((generator = generator.apply(__this, __arguments)).next());
80
+ });
81
+ };
82
+
83
+ // src/dev-worker/forkDevWorker.ts
84
+ var forkDevWorker_exports = {};
85
+ __export(forkDevWorker_exports, {
86
+ forkDevWorker: () => forkDevWorker
87
+ });
88
+ module.exports = __toCommonJS(forkDevWorker_exports);
89
+
90
+ // src/core/configurations/remotePlugin.ts
91
+ var import_fs2 = require("fs");
92
+ var import_path5 = require("path");
93
+ var import_managers2 = require("@module-federation/managers");
94
+ var import_typescript = __toESM(require("typescript"));
95
+
96
+ // src/core/lib/utils.ts
97
+ var import_axios = __toESM(require("axios"));
98
+ var import_http2 = __toESM(require("http"));
99
+ var import_https = __toESM(require("https"));
100
+ var import_sdk6 = require("@module-federation/sdk");
101
+ var import_ansi_colors = __toESM(require("ansi-colors"));
102
+
103
+ // src/core/lib/DTSManager.ts
104
+ var import_path4 = __toESM(require("path"));
105
+ var import_promises3 = require("fs/promises");
106
+ var import_fs = __toESM(require("fs"));
107
+ var import_fs_extra3 = __toESM(require("fs-extra"));
108
+ var import_sdk5 = require("@module-federation/sdk");
109
+ var import_third_party_dts_extractor2 = require("@module-federation/third-party-dts-extractor");
110
+
111
+ // src/core/lib/archiveHandler.ts
112
+ var import_adm_zip = __toESM(require("adm-zip"));
113
+ var import_path3 = require("path");
114
+ var import_promises2 = require("fs/promises");
115
+
116
+ // src/core/lib/typeScriptCompiler.ts
117
+ var import_fs_extra = require("fs-extra");
118
+ var import_crypto = __toESM(require("crypto"));
119
+ var import_promises = require("fs/promises");
120
+ var import_path = require("path");
121
+ var import_error_codes = require("@module-federation/error-codes");
122
+ var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
123
+ var import_child_process = require("child_process");
124
+ var import_util = __toESM(require("util"));
125
+ var import_sdk = require("@module-federation/sdk");
126
+ var STARTS_WITH_SLASH = /^\//;
127
+ var DEFINITION_FILE_EXTENSION = ".d.ts";
128
+ var retrieveMfTypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "")), "retrieveMfTypesPath");
129
+ var retrieveOriginalOutDir = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.normalize)(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder, "").replace(remoteOptions.typesFolder, "")), "retrieveOriginalOutDir");
130
+ var retrieveMfAPITypesPath = /* @__PURE__ */ __name((tsConfig, remoteOptions) => (0, import_path.join)(retrieveOriginalOutDir(tsConfig, remoteOptions), `${remoteOptions.typesFolder}.d.ts`), "retrieveMfAPITypesPath");
131
+ function writeTempTsConfig(tsConfig, context, name, cwd) {
132
+ const createHash = /* @__PURE__ */ __name((contents) => {
133
+ return import_crypto.default.createHash("md5").update(contents).digest("hex");
134
+ }, "createHash");
135
+ const hash = createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);
136
+ const tempTsConfigJsonPath = (0, import_path.resolve)(cwd != null ? cwd : context, "node_modules", import_sdk.TEMP_DIR, `tsconfig.${hash}.json`);
137
+ (0, import_fs_extra.ensureDirSync)((0, import_path.dirname)(tempTsConfigJsonPath));
138
+ (0, import_fs_extra.writeFileSync)(tempTsConfigJsonPath, JSON.stringify(tsConfig, null, 2));
139
+ return tempTsConfigJsonPath;
140
+ }
141
+ __name(writeTempTsConfig, "writeTempTsConfig");
142
+ var removeExt = /* @__PURE__ */ __name((f) => {
143
+ const vueExt = ".vue";
144
+ const ext = (0, import_path.extname)(f);
145
+ if (ext === vueExt) {
146
+ return f;
147
+ }
148
+ const regexPattern = new RegExp(`\\${ext}$`);
149
+ return f.replace(regexPattern, "");
150
+ }, "removeExt");
151
+ function getExposeKey(options) {
152
+ const { filePath, rootDir, outDir, mapExposeToEntry } = options;
153
+ const relativeFilePath = (0, import_path.relative)(outDir, filePath.replace(new RegExp(`\\.d.ts$`), ""));
154
+ return mapExposeToEntry[relativeFilePath];
155
+ }
156
+ __name(getExposeKey, "getExposeKey");
157
+ var processTypesFile = /* @__PURE__ */ __name((options) => __async(void 0, null, function* () {
158
+ const { outDir, filePath, rootDir, cb, mapExposeToEntry, mfTypePath } = options;
159
+ if (!(0, import_fs_extra.existsSync)(filePath)) {
160
+ return;
161
+ }
162
+ const stats = yield (0, import_promises.stat)(filePath);
163
+ if (stats.isDirectory()) {
164
+ const files = yield (0, import_promises.readdir)(filePath);
165
+ yield Promise.all(files.map((file) => processTypesFile(__spreadProps(__spreadValues({}, options), {
166
+ filePath: (0, import_path.join)(filePath, file)
167
+ }))));
168
+ } else if (filePath.endsWith(".d.ts")) {
169
+ const exposeKey = getExposeKey({
170
+ filePath,
171
+ rootDir,
172
+ outDir,
173
+ mapExposeToEntry
174
+ });
175
+ if (exposeKey) {
176
+ const sourceEntry = exposeKey === "." ? "index" : exposeKey;
177
+ const mfeTypeEntry = (0, import_path.join)(mfTypePath, `${sourceEntry}${DEFINITION_FILE_EXTENSION}`);
178
+ const mfeTypeEntryDirectory = (0, import_path.dirname)(mfeTypeEntry);
179
+ const relativePathToOutput = (0, import_path.relative)(mfeTypeEntryDirectory, filePath).replace(DEFINITION_FILE_EXTENSION, "").replace(STARTS_WITH_SLASH, "").split(import_path.sep).join("/");
180
+ (0, import_fs_extra.ensureDirSync)(mfeTypeEntryDirectory);
181
+ yield (0, import_promises.writeFile)(mfeTypeEntry, `export * from './${relativePathToOutput}';
182
+ export { default } from './${relativePathToOutput}';`);
183
+ }
184
+ const content = yield (0, import_promises.readFile)(filePath, "utf8");
185
+ cb(content);
186
+ }
187
+ }), "processTypesFile");
188
+ var compileTs = /* @__PURE__ */ __name((mapComponentsToExpose, tsConfig, remoteOptions) => __async(void 0, null, function* () {
189
+ var _a3, _b, _c, _d;
190
+ if (!Object.keys(mapComponentsToExpose).length) {
191
+ return;
192
+ }
193
+ const { compilerOptions } = tsConfig;
194
+ const tempTsConfigJsonPath = writeTempTsConfig(tsConfig, remoteOptions.context, remoteOptions.moduleFederationConfig.name || "mf", typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? (_b = (_a3 = remoteOptions.moduleFederationConfig.dts) == null ? void 0 : _a3.cwd) != null ? _b : void 0 : void 0);
195
+ try {
196
+ const mfTypePath = retrieveMfTypesPath(tsConfig, remoteOptions);
197
+ const thirdPartyExtractor = new import_third_party_dts_extractor.ThirdPartyExtractor({
198
+ destDir: (0, import_path.resolve)(mfTypePath, "node_modules"),
199
+ context: remoteOptions.context,
200
+ exclude: typeof remoteOptions.extractThirdParty === "object" ? remoteOptions.extractThirdParty.exclude : void 0
201
+ });
202
+ const execPromise = import_util.default.promisify(import_child_process.exec);
203
+ const cmd = `npx ${remoteOptions.compilerInstance} --project '${tempTsConfigJsonPath}'`;
204
+ try {
205
+ yield execPromise(cmd, {
206
+ cwd: typeof remoteOptions.moduleFederationConfig.dts !== "boolean" ? (_d = (_c = remoteOptions.moduleFederationConfig.dts) == null ? void 0 : _c.cwd) != null ? _d : void 0 : void 0
207
+ });
208
+ } catch (err) {
209
+ if (compilerOptions.tsBuildInfoFile) {
210
+ try {
211
+ yield (0, import_promises.rm)(compilerOptions.tsBuildInfoFile);
212
+ } catch (e) {
213
+ }
214
+ }
215
+ throw new Error((0, import_error_codes.getShortErrorMsg)(import_error_codes.TYPE_001, import_error_codes.typeDescMap, {
216
+ cmd
217
+ }));
218
+ }
219
+ const mapExposeToEntry = Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed, filename]) => {
220
+ const normalizedFileName = (0, import_path.normalize)(filename);
221
+ let relativeFileName = "";
222
+ if ((0, import_path.isAbsolute)(normalizedFileName)) {
223
+ relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, normalizedFileName);
224
+ } else {
225
+ relativeFileName = (0, import_path.relative)(tsConfig.compilerOptions.rootDir, (0, import_path.resolve)(remoteOptions.context, normalizedFileName));
226
+ }
227
+ return [
228
+ removeExt(relativeFileName),
229
+ exposed
230
+ ];
231
+ }));
232
+ const cb = remoteOptions.extractThirdParty ? thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor) : () => void 0;
233
+ yield processTypesFile({
234
+ outDir: compilerOptions.outDir,
235
+ filePath: compilerOptions.outDir,
236
+ rootDir: compilerOptions.rootDir,
237
+ mfTypePath,
238
+ cb,
239
+ mapExposeToEntry
240
+ });
241
+ if (remoteOptions.extractThirdParty) {
242
+ yield thirdPartyExtractor.copyDts();
243
+ }
244
+ yield (0, import_promises.rm)(tempTsConfigJsonPath);
245
+ } catch (err) {
246
+ throw err;
247
+ }
248
+ }), "compileTs");
249
+
250
+ // src/server/message/Message.ts
251
+ var _Message = class _Message {
252
+ constructor(type, kind) {
253
+ __publicField(this, "type");
254
+ __publicField(this, "kind");
255
+ __publicField(this, "time");
256
+ this.type = type;
257
+ this.kind = kind;
258
+ this.time = Date.now();
259
+ }
260
+ };
261
+ __name(_Message, "Message");
262
+ var Message = _Message;
263
+
264
+ // src/server/message/API/API.ts
265
+ var APIKind;
266
+ (function(APIKind2) {
267
+ APIKind2["UPDATE_SUBSCRIBER"] = "UPDATE_SUBSCRIBER";
268
+ APIKind2["RELOAD_WEB_CLIENT"] = "RELOAD_WEB_CLIENT";
269
+ APIKind2["FETCH_TYPES"] = "FETCH_TYPES";
270
+ })(APIKind || (APIKind = {}));
271
+ var _API = class _API extends Message {
272
+ constructor(content, kind) {
273
+ super("API", kind);
274
+ __publicField(this, "code");
275
+ __publicField(this, "payload");
276
+ const { code, payload } = content;
277
+ this.code = code;
278
+ this.payload = payload;
279
+ }
280
+ };
281
+ __name(_API, "API");
282
+ var API = _API;
283
+
284
+ // src/server/message/API/UpdateSubscriber.ts
285
+ var _UpdateSubscriberAPI = class _UpdateSubscriberAPI extends API {
286
+ constructor(payload) {
287
+ super({
288
+ code: 0,
289
+ payload
290
+ }, APIKind.UPDATE_SUBSCRIBER);
291
+ }
292
+ };
293
+ __name(_UpdateSubscriberAPI, "UpdateSubscriberAPI");
294
+ var UpdateSubscriberAPI = _UpdateSubscriberAPI;
295
+
296
+ // src/server/message/API/ReloadWebClient.ts
297
+ var _ReloadWebClientAPI = class _ReloadWebClientAPI extends API {
298
+ constructor(payload) {
299
+ super({
300
+ code: 0,
301
+ payload
302
+ }, APIKind.RELOAD_WEB_CLIENT);
303
+ }
304
+ };
305
+ __name(_ReloadWebClientAPI, "ReloadWebClientAPI");
306
+ var ReloadWebClientAPI = _ReloadWebClientAPI;
307
+
308
+ // src/server/message/API/FetchTypes.ts
309
+ var _FetchTypesAPI = class _FetchTypesAPI extends API {
310
+ constructor(payload) {
311
+ super({
312
+ code: 0,
313
+ payload
314
+ }, APIKind.FETCH_TYPES);
315
+ }
316
+ };
317
+ __name(_FetchTypesAPI, "FetchTypesAPI");
318
+ var FetchTypesAPI = _FetchTypesAPI;
319
+
320
+ // src/server/utils/index.ts
321
+ var import_net = __toESM(require("net"));
322
+ var import_sdk3 = require("@module-federation/sdk");
323
+
324
+ // src/server/utils/logTransform.ts
325
+ var import_chalk = __toESM(require("chalk"));
326
+
327
+ // src/server/message/Log/Log.ts
328
+ var LogLevel;
329
+ (function(LogLevel2) {
330
+ LogLevel2["LOG"] = "LOG";
331
+ LogLevel2["WARN"] = "WARN";
332
+ LogLevel2["ERROR"] = "ERROR";
333
+ })(LogLevel || (LogLevel = {}));
334
+ var LogKind;
335
+ (function(LogKind2) {
336
+ LogKind2["BrokerExitLog"] = "BrokerExitLog";
337
+ LogKind2["PublisherRegisteredLog"] = "PublisherRegisteredLog";
338
+ })(LogKind || (LogKind = {}));
339
+ var _Log = class _Log extends Message {
340
+ constructor(level, kind, ignoreVerbose = false) {
341
+ super("Log", kind);
342
+ __publicField(this, "level");
343
+ __publicField(this, "ignoreVerbose", false);
344
+ this.level = level;
345
+ this.ignoreVerbose = ignoreVerbose;
346
+ }
347
+ };
348
+ __name(_Log, "Log");
349
+ var Log = _Log;
350
+
351
+ // src/server/message/Log/BrokerExitLog.ts
352
+ var _BrokerExitLog = class _BrokerExitLog extends Log {
353
+ constructor() {
354
+ super(LogLevel.LOG, LogKind.BrokerExitLog);
355
+ }
356
+ };
357
+ __name(_BrokerExitLog, "BrokerExitLog");
358
+ var BrokerExitLog = _BrokerExitLog;
359
+
360
+ // src/server/utils/log.ts
361
+ var import_sdk2 = require("@module-federation/sdk");
362
+ var log4js = __toESM(require("log4js"));
363
+
364
+ // src/server/constant.ts
365
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
366
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
367
+ var MF_SERVER_IDENTIFIER = "Module Federation DTS";
368
+ var DEFAULT_TAR_NAME = "@mf-types.zip";
369
+ var UpdateMode;
370
+ (function(UpdateMode2) {
371
+ UpdateMode2["POSITIVE"] = "POSITIVE";
372
+ UpdateMode2["PASSIVE"] = "PASSIVE";
373
+ })(UpdateMode || (UpdateMode = {}));
374
+
375
+ // src/server/utils/log.ts
376
+ var logger = (0, import_sdk2.createLogger)(`[ ${MF_SERVER_IDENTIFIER} ]`);
377
+ function fileLog(msg, module2, level) {
378
+ var _a3, _b;
379
+ if (!((_a3 = process == null ? void 0 : process.env) == null ? void 0 : _a3["FEDERATION_DEBUG"])) {
380
+ return;
381
+ }
382
+ log4js.configure({
383
+ appenders: {
384
+ [module2]: {
385
+ type: "file",
386
+ filename: ".mf/typesGenerate.log"
387
+ },
388
+ default: {
389
+ type: "file",
390
+ filename: ".mf/typesGenerate.log"
391
+ }
392
+ },
393
+ categories: {
394
+ [module2]: {
395
+ appenders: [
396
+ module2
397
+ ],
398
+ level: "error"
399
+ },
400
+ default: {
401
+ appenders: [
402
+ "default"
403
+ ],
404
+ level: "trace"
405
+ }
406
+ }
407
+ });
408
+ const logger4 = log4js.getLogger(module2);
409
+ logger4.level = "debug";
410
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
411
+ }
412
+ __name(fileLog, "fileLog");
413
+ function error(error2, action, from) {
414
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
415
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
416
+ return err.toString();
417
+ }
418
+ __name(error, "error");
419
+
420
+ // src/server/utils/getIPV4.ts
421
+ var import_os = __toESM(require("os"));
422
+ var localIpv4 = "127.0.0.1";
423
+ var getIpv4Interfaces = /* @__PURE__ */ __name(() => {
424
+ try {
425
+ const interfaces = import_os.default.networkInterfaces();
426
+ const ipv4Interfaces = [];
427
+ Object.values(interfaces).forEach((detail) => {
428
+ detail == null ? void 0 : detail.forEach((detail2) => {
429
+ const familyV4Value = typeof detail2.family === "string" ? "IPv4" : 4;
430
+ if (detail2.family === familyV4Value && detail2.address !== localIpv4) {
431
+ ipv4Interfaces.push(detail2);
432
+ }
433
+ });
434
+ });
435
+ return ipv4Interfaces;
436
+ } catch (_err) {
437
+ return [];
438
+ }
439
+ }, "getIpv4Interfaces");
440
+ var getIPV4 = /* @__PURE__ */ __name(() => {
441
+ const ipv4Interfaces = getIpv4Interfaces();
442
+ const ipv4Interface = ipv4Interfaces[0] || {
443
+ address: localIpv4
444
+ };
445
+ return ipv4Interface.address;
446
+ }, "getIPV4");
447
+
448
+ // src/server/utils/index.ts
449
+ function getIdentifier(options) {
450
+ const { ip, name } = options;
451
+ return `mf ${import_sdk3.SEPARATOR}${name}${ip ? `${import_sdk3.SEPARATOR}${ip}` : ""}`;
452
+ }
453
+ __name(getIdentifier, "getIdentifier");
454
+ function fib(n) {
455
+ let i = 2;
456
+ const res = [
457
+ 0,
458
+ 1,
459
+ 1
460
+ ];
461
+ while (i <= n) {
462
+ res[i] = res[i - 1] + res[i - 2];
463
+ i++;
464
+ }
465
+ return res[n];
466
+ }
467
+ __name(fib, "fib");
468
+ function getFreePort() {
469
+ return new Promise((resolve4, reject) => {
470
+ const server = import_net.default.createServer();
471
+ server.unref();
472
+ server.on("error", reject);
473
+ server.listen(0, () => {
474
+ const { port } = server.address();
475
+ server.close(() => {
476
+ resolve4(port);
477
+ });
478
+ });
479
+ });
480
+ }
481
+ __name(getFreePort, "getFreePort");
482
+
483
+ // src/server/Publisher.ts
484
+ var _Publisher = class _Publisher {
485
+ constructor(ctx) {
486
+ __publicField(this, "_ip");
487
+ __publicField(this, "_name");
488
+ __publicField(this, "_remoteTypeTarPath");
489
+ __publicField(this, "_subscribers");
490
+ __publicField(this, "_ws");
491
+ __publicField(this, "dynamicRemoteMap");
492
+ this._name = ctx.name;
493
+ this._ip = ctx.ip;
494
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
495
+ this._subscribers = /* @__PURE__ */ new Map();
496
+ this._ws = ctx.ws;
497
+ this.dynamicRemoteMap = /* @__PURE__ */ new Map();
498
+ }
499
+ get identifier() {
500
+ return getIdentifier({
501
+ name: this._name,
502
+ ip: this._ip
503
+ });
504
+ }
505
+ get name() {
506
+ return this._name;
507
+ }
508
+ get ip() {
509
+ return this._ip;
510
+ }
511
+ get remoteTypeTarPath() {
512
+ return this._remoteTypeTarPath;
513
+ }
514
+ get hasSubscribes() {
515
+ return Boolean(this._subscribers.size);
516
+ }
517
+ get subscribers() {
518
+ return this._subscribers;
519
+ }
520
+ addSubscriber(identifier, subscriber) {
521
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
522
+ this._subscribers.set(identifier, subscriber);
523
+ }
524
+ removeSubscriber(identifier) {
525
+ if (this._subscribers.has(identifier)) {
526
+ fileLog(`${this.name} removeSubscriber: ${identifier}`, "Publisher", "warn");
527
+ this._subscribers.delete(identifier);
528
+ }
529
+ }
530
+ notifySubscriber(subscriberIdentifier, options) {
531
+ const subscriber = this._subscribers.get(subscriberIdentifier);
532
+ if (!subscriber) {
533
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`, "Publisher", "error");
534
+ return;
535
+ }
536
+ const api = new UpdateSubscriberAPI(options);
537
+ subscriber.send(JSON.stringify(api));
538
+ fileLog(`[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(subscriberIdentifier)}, message: ${JSON.stringify(api)}`, "Publisher", "info");
539
+ }
540
+ fetchRemoteTypes(options) {
541
+ fileLog(`[fetchRemoteTypes] ${this.name} fetchRemoteTypes, options: ${JSON.stringify(options)}, ws: ${Boolean(this._ws)}`, "Publisher", "info");
542
+ if (!this._ws) {
543
+ return;
544
+ }
545
+ const api = new FetchTypesAPI(options);
546
+ this._ws.send(JSON.stringify(api));
547
+ }
548
+ notifySubscribers(options) {
549
+ const api = new UpdateSubscriberAPI(options);
550
+ this.broadcast(api);
551
+ }
552
+ broadcast(message) {
553
+ if (this.hasSubscribes) {
554
+ this._subscribers.forEach((subscriber, key) => {
555
+ fileLog(`[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`, "Publisher", "info");
556
+ subscriber.send(JSON.stringify(message));
557
+ });
558
+ } else {
559
+ fileLog(`[BroadCast] ${this.name}'s subscribe is empty`, "Publisher", "warn");
560
+ }
561
+ }
562
+ close() {
563
+ this._ws = void 0;
564
+ this._subscribers.forEach((_subscriber, identifier) => {
565
+ fileLog(`[BroadCast] close ${this.name} remove: ${identifier}`, "Publisher", "warn");
566
+ this.removeSubscriber(identifier);
567
+ });
568
+ }
569
+ };
570
+ __name(_Publisher, "Publisher");
571
+ var Publisher = _Publisher;
572
+
573
+ // src/server/DevServer.ts
574
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
575
+
576
+ // src/server/broker/Broker.ts
577
+ var import_http = require("http");
578
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
579
+ var import_node_schedule = __toESM(require("node-schedule"));
580
+ var import_url = require("url");
581
+
582
+ // src/server/message/Action/Action.ts
583
+ var ActionKind;
584
+ (function(ActionKind2) {
585
+ ActionKind2["ADD_SUBSCRIBER"] = "ADD_SUBSCRIBER";
586
+ ActionKind2["EXIT_SUBSCRIBER"] = "EXIT_SUBSCRIBER";
587
+ ActionKind2["ADD_PUBLISHER"] = "ADD_PUBLISHER";
588
+ ActionKind2["UPDATE_PUBLISHER"] = "UPDATE_PUBLISHER";
589
+ ActionKind2["NOTIFY_SUBSCRIBER"] = "NOTIFY_SUBSCRIBER";
590
+ ActionKind2["EXIT_PUBLISHER"] = "EXIT_PUBLISHER";
591
+ ActionKind2["ADD_WEB_CLIENT"] = "ADD_WEB_CLIENT";
592
+ ActionKind2["NOTIFY_WEB_CLIENT"] = "NOTIFY_WEB_CLIENT";
593
+ ActionKind2["FETCH_TYPES"] = "FETCH_TYPES";
594
+ ActionKind2["ADD_DYNAMIC_REMOTE"] = "ADD_DYNAMIC_REMOTE";
595
+ })(ActionKind || (ActionKind = {}));
596
+ var _Action = class _Action extends Message {
597
+ constructor(content, kind) {
598
+ super("Action", kind);
599
+ __publicField(this, "payload");
600
+ const { payload } = content;
601
+ this.payload = payload;
602
+ }
603
+ };
604
+ __name(_Action, "Action");
605
+ var Action = _Action;
606
+
607
+ // src/server/message/Action/Update.ts
608
+ var UpdateKind;
609
+ (function(UpdateKind2) {
610
+ UpdateKind2["UPDATE_TYPE"] = "UPDATE_TYPE";
611
+ UpdateKind2["RELOAD_PAGE"] = "RELOAD_PAGE";
612
+ })(UpdateKind || (UpdateKind = {}));
613
+
614
+ // src/server/message/Action/AddPublisher.ts
615
+ var _AddPublisherAction = class _AddPublisherAction extends Action {
616
+ constructor(payload) {
617
+ super({
618
+ payload
619
+ }, ActionKind.ADD_PUBLISHER);
620
+ }
621
+ };
622
+ __name(_AddPublisherAction, "AddPublisherAction");
623
+ var AddPublisherAction = _AddPublisherAction;
624
+
625
+ // src/server/message/Action/AddSubscriber.ts
626
+ var _AddSubscriberAction = class _AddSubscriberAction extends Action {
627
+ constructor(payload) {
628
+ super({
629
+ payload
630
+ }, ActionKind.ADD_SUBSCRIBER);
631
+ }
632
+ };
633
+ __name(_AddSubscriberAction, "AddSubscriberAction");
634
+ var AddSubscriberAction = _AddSubscriberAction;
635
+
636
+ // src/server/message/Action/ExitSubscriber.ts
637
+ var _ExitSubscriberAction = class _ExitSubscriberAction extends Action {
638
+ constructor(payload) {
639
+ super({
640
+ payload
641
+ }, ActionKind.EXIT_SUBSCRIBER);
642
+ }
643
+ };
644
+ __name(_ExitSubscriberAction, "ExitSubscriberAction");
645
+ var ExitSubscriberAction = _ExitSubscriberAction;
646
+
647
+ // src/server/message/Action/ExitPublisher.ts
648
+ var _ExitPublisherAction = class _ExitPublisherAction extends Action {
649
+ constructor(payload) {
650
+ super({
651
+ payload
652
+ }, ActionKind.EXIT_PUBLISHER);
653
+ }
654
+ };
655
+ __name(_ExitPublisherAction, "ExitPublisherAction");
656
+ var ExitPublisherAction = _ExitPublisherAction;
657
+
658
+ // src/server/message/Action/NotifyWebClient.ts
659
+ var _NotifyWebClientAction = class _NotifyWebClientAction extends Action {
660
+ constructor(payload) {
661
+ super({
662
+ payload
663
+ }, ActionKind.NOTIFY_WEB_CLIENT);
664
+ }
665
+ };
666
+ __name(_NotifyWebClientAction, "NotifyWebClientAction");
667
+ var NotifyWebClientAction = _NotifyWebClientAction;
668
+
669
+ // src/server/message/Action/UpdatePublisher.ts
670
+ var _UpdatePublisherAction = class _UpdatePublisherAction extends Action {
671
+ constructor(payload) {
672
+ super({
673
+ payload
674
+ }, ActionKind.UPDATE_PUBLISHER);
675
+ }
676
+ };
677
+ __name(_UpdatePublisherAction, "UpdatePublisherAction");
678
+ var UpdatePublisherAction = _UpdatePublisherAction;
679
+
680
+ // src/server/broker/Broker.ts
681
+ var _Broker = class _Broker {
682
+ constructor() {
683
+ __publicField(this, "_publisherMap", /* @__PURE__ */ new Map());
684
+ __publicField(this, "_webClientMap", /* @__PURE__ */ new Map());
685
+ __publicField(this, "_webSocketServer");
686
+ __publicField(this, "_secureWebSocketServer");
687
+ __publicField(this, "_tmpSubscriberShelter", /* @__PURE__ */ new Map());
688
+ __publicField(this, "_scheduleJob", null);
689
+ this._setSchedule();
690
+ this._startWsServer();
691
+ this._stopWhenSIGTERMOrSIGINT();
692
+ this._handleUnexpectedExit();
693
+ }
694
+ get hasPublishers() {
695
+ return Boolean(this._publisherMap.size);
696
+ }
697
+ _startWsServer() {
698
+ return __async(this, null, function* () {
699
+ const wsHandler = /* @__PURE__ */ __name((ws, req) => {
700
+ const { url: reqUrl = "" } = req;
701
+ const { query } = (0, import_url.parse)(reqUrl, true);
702
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
703
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
704
+ ws.on("message", (message) => {
705
+ try {
706
+ const text = message.toString();
707
+ const action = JSON.parse(text);
708
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
709
+ this._takeAction(action, ws);
710
+ } catch (error2) {
711
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
712
+ }
713
+ });
714
+ ws.on("error", (e) => {
715
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
716
+ });
717
+ } else {
718
+ ws.send("Invalid CONNECT ID.");
719
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
720
+ ws.close();
721
+ }
722
+ }, "wsHandler");
723
+ const server = (0, import_http.createServer)();
724
+ this._webSocketServer = new import_isomorphic_ws.default.Server({
725
+ noServer: true
726
+ });
727
+ this._webSocketServer.on("error", (err) => {
728
+ fileLog(`ws error:
729
+ ${err.message}
730
+ ${err.stack}`, "Broker", "error");
731
+ });
732
+ this._webSocketServer.on("listening", () => {
733
+ fileLog(`WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`, "Broker", "info");
734
+ });
735
+ this._webSocketServer.on("connection", wsHandler);
736
+ this._webSocketServer.on("close", (code) => {
737
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
738
+ this._webSocketServer && this._webSocketServer.close();
739
+ this._webSocketServer = void 0;
740
+ });
741
+ server.on("upgrade", (req, socket, head) => {
742
+ var _a3;
743
+ if (req.url) {
744
+ const { pathname } = (0, import_url.parse)(req.url);
745
+ if (pathname === "/") {
746
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.handleUpgrade(req, socket, head, (ws) => {
747
+ var _a4;
748
+ (_a4 = this._webSocketServer) == null ? void 0 : _a4.emit("connection", ws, req);
749
+ });
750
+ }
751
+ }
752
+ });
753
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
754
+ });
755
+ }
756
+ _takeAction(action, client) {
757
+ return __async(this, null, function* () {
758
+ const { kind, payload } = action;
759
+ if (kind === ActionKind.ADD_PUBLISHER) {
760
+ yield this._addPublisher(payload, client);
761
+ }
762
+ if (kind === ActionKind.UPDATE_PUBLISHER) {
763
+ yield this._updatePublisher(payload, client);
764
+ }
765
+ if (kind === ActionKind.ADD_SUBSCRIBER) {
766
+ yield this._addSubscriber(payload, client);
767
+ }
768
+ if (kind === ActionKind.EXIT_SUBSCRIBER) {
769
+ yield this._removeSubscriber(payload, client);
770
+ }
771
+ if (kind === ActionKind.EXIT_PUBLISHER) {
772
+ yield this._removePublisher(payload, client);
773
+ }
774
+ if (kind === ActionKind.ADD_WEB_CLIENT) {
775
+ yield this._addWebClient(payload, client);
776
+ }
777
+ if (kind === ActionKind.NOTIFY_WEB_CLIENT) {
778
+ yield this._notifyWebClient(payload, client);
779
+ }
780
+ if (kind === ActionKind.FETCH_TYPES) {
781
+ yield this._fetchTypes(payload, client);
782
+ }
783
+ if (kind === ActionKind.ADD_DYNAMIC_REMOTE) {
784
+ this._addDynamicRemote(payload);
785
+ }
786
+ });
787
+ }
788
+ _addPublisher(context, client) {
789
+ return __async(this, null, function* () {
790
+ const { name, ip, remoteTypeTarPath } = context != null ? context : {};
791
+ const identifier = getIdentifier({
792
+ name,
793
+ ip
794
+ });
795
+ if (this._publisherMap.has(identifier)) {
796
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`, "Broker", "warn");
797
+ return;
798
+ }
799
+ try {
800
+ const publisher = new Publisher({
801
+ name,
802
+ ip,
803
+ remoteTypeTarPath,
804
+ ws: client
805
+ });
806
+ this._publisherMap.set(identifier, publisher);
807
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`, "Broker", "info");
808
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
809
+ if (tmpSubScribers) {
810
+ fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `, "Broker", "info");
811
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
812
+ this._clearTmpSubScriberRelation(identifier);
813
+ }
814
+ } catch (err) {
815
+ const msg = error(err, ActionKind.ADD_PUBLISHER, "Broker");
816
+ client.send(msg);
817
+ client.close();
818
+ }
819
+ });
820
+ }
821
+ _updatePublisher(context, client) {
822
+ return __async(this, null, function* () {
823
+ const { name, updateMode, updateKind, updateSourcePaths, remoteTypeTarPath, ip } = context != null ? context : {};
824
+ const identifier = getIdentifier({
825
+ name,
826
+ ip
827
+ });
828
+ if (!this._publisherMap.has(identifier)) {
829
+ fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
830
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
831
+ `, "Broker", "warn");
832
+ return;
833
+ }
834
+ try {
835
+ const publisher = this._publisherMap.get(identifier);
836
+ fileLog(
837
+ // eslint-disable-next-line max-len
838
+ `[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,
839
+ "Broker",
840
+ "info"
841
+ );
842
+ if (publisher) {
843
+ publisher.notifySubscribers({
844
+ remoteTypeTarPath,
845
+ name,
846
+ updateMode,
847
+ updateKind,
848
+ updateSourcePaths: updateSourcePaths || []
849
+ });
850
+ this._publisherMap.forEach((p) => {
851
+ if (p.name === publisher.name) {
852
+ return;
853
+ }
854
+ const dynamicRemoteInfo = p.dynamicRemoteMap.get(identifier);
855
+ if (dynamicRemoteInfo) {
856
+ fileLog(
857
+ // eslint-disable-next-line max-len
858
+ `dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,
859
+ "Broker",
860
+ "info"
861
+ );
862
+ p.fetchRemoteTypes({
863
+ remoteInfo: dynamicRemoteInfo,
864
+ once: false
865
+ });
866
+ }
867
+ });
868
+ }
869
+ } catch (err) {
870
+ const msg = error(err, ActionKind.UPDATE_PUBLISHER, "Broker");
871
+ client.send(msg);
872
+ client.close();
873
+ }
874
+ });
875
+ }
876
+ _fetchTypes(context, _client) {
877
+ return __async(this, null, function* () {
878
+ const { name, ip, remoteInfo } = context != null ? context : {};
879
+ const identifier = getIdentifier({
880
+ name,
881
+ ip
882
+ });
883
+ try {
884
+ const publisher = this._publisherMap.get(identifier);
885
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`, "Broker", "info");
886
+ if (publisher) {
887
+ publisher.fetchRemoteTypes({
888
+ remoteInfo,
889
+ once: true
890
+ });
891
+ }
892
+ } catch (err) {
893
+ fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`, "Broker", "error");
894
+ }
895
+ });
896
+ }
897
+ _addDynamicRemote(context) {
898
+ const { name, ip, remoteInfo, remoteIp } = context != null ? context : {};
899
+ const identifier = getIdentifier({
900
+ name,
901
+ ip
902
+ });
903
+ const publisher = this._publisherMap.get(identifier);
904
+ const remoteId = getIdentifier({
905
+ name: remoteInfo.name,
906
+ ip: remoteIp
907
+ });
908
+ fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`, "Broker", "error");
909
+ if (!publisher || publisher.dynamicRemoteMap.has(remoteId)) {
910
+ return;
911
+ }
912
+ publisher.dynamicRemoteMap.set(remoteId, remoteInfo);
913
+ }
914
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
915
+ // provider1 is app1's remote
916
+ _addSubscriber(context, client) {
917
+ return __async(this, null, function* () {
918
+ const { publishers, name: subscriberName } = context != null ? context : {};
919
+ publishers.forEach((publisher) => {
920
+ const { name, ip } = publisher;
921
+ const identifier = getIdentifier({
922
+ name,
923
+ ip
924
+ });
925
+ if (!this._publisherMap.has(identifier)) {
926
+ fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`, "Broker", "warn");
927
+ this._addTmpSubScriberRelation({
928
+ name: getIdentifier({
929
+ name: context.name,
930
+ ip: context.ip
931
+ }),
932
+ client
933
+ }, publisher);
934
+ return;
935
+ }
936
+ try {
937
+ const registeredPublisher = this._publisherMap.get(identifier);
938
+ if (registeredPublisher) {
939
+ registeredPublisher.addSubscriber(getIdentifier({
940
+ name: subscriberName,
941
+ ip: context.ip
942
+ }), client);
943
+ fileLog(
944
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
945
+ `[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,
946
+ "Broker",
947
+ "info"
948
+ );
949
+ registeredPublisher.notifySubscriber(getIdentifier({
950
+ name: subscriberName,
951
+ ip: context.ip
952
+ }), {
953
+ updateKind: UpdateKind.UPDATE_TYPE,
954
+ updateMode: UpdateMode.PASSIVE,
955
+ updateSourcePaths: [
956
+ registeredPublisher.name
957
+ ],
958
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
959
+ name: registeredPublisher.name
960
+ });
961
+ fileLog(
962
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
963
+ `[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
964
+ "Broker",
965
+ "info"
966
+ );
967
+ }
968
+ } catch (err) {
969
+ const msg = error(err, ActionKind.ADD_SUBSCRIBER, "Broker");
970
+ client.send(msg);
971
+ client.close();
972
+ }
973
+ });
974
+ });
975
+ }
976
+ // Trigger while consumer exit
977
+ _removeSubscriber(context, client) {
978
+ return __async(this, null, function* () {
979
+ const { publishers } = context != null ? context : {};
980
+ const subscriberIdentifier = getIdentifier({
981
+ name: context == null ? void 0 : context.name,
982
+ ip: context == null ? void 0 : context.ip
983
+ });
984
+ publishers.forEach((publisher) => {
985
+ const { name, ip } = publisher;
986
+ const identifier = getIdentifier({
987
+ name,
988
+ ip
989
+ });
990
+ const registeredPublisher = this._publisherMap.get(identifier);
991
+ if (!registeredPublisher) {
992
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `, "Broker", "warn");
993
+ return;
994
+ }
995
+ try {
996
+ fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `, "Broker", "INFO");
997
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
998
+ this._clearTmpSubScriberRelation(identifier);
999
+ if (!registeredPublisher.hasSubscribes) {
1000
+ this._publisherMap.delete(identifier);
1001
+ }
1002
+ if (!this.hasPublishers) {
1003
+ this.exit();
1004
+ }
1005
+ } catch (err) {
1006
+ const msg = error(err, ActionKind.EXIT_SUBSCRIBER, "Broker");
1007
+ client.send(msg);
1008
+ client.close();
1009
+ }
1010
+ });
1011
+ });
1012
+ }
1013
+ _removePublisher(context, client) {
1014
+ return __async(this, null, function* () {
1015
+ const { name, ip } = context != null ? context : {};
1016
+ const identifier = getIdentifier({
1017
+ name,
1018
+ ip
1019
+ });
1020
+ const publisher = this._publisherMap.get(identifier);
1021
+ if (!publisher) {
1022
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`, "Broker", "warn");
1023
+ return;
1024
+ }
1025
+ try {
1026
+ const { subscribers } = publisher;
1027
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
1028
+ this._addTmpSubScriberRelation({
1029
+ name: subscriberIdentifier,
1030
+ client: subscriber
1031
+ }, {
1032
+ name: publisher.name,
1033
+ ip: publisher.ip
1034
+ });
1035
+ fileLog(
1036
+ // eslint-disable-next-line max-len
1037
+ `[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
1038
+ "Broker",
1039
+ "info"
1040
+ );
1041
+ });
1042
+ this._publisherMap.delete(identifier);
1043
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `, "Broker", "info");
1044
+ if (!this.hasPublishers) {
1045
+ fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `, "Broker", "warn");
1046
+ this.exit();
1047
+ }
1048
+ } catch (err) {
1049
+ const msg = error(err, ActionKind.EXIT_PUBLISHER, "Broker");
1050
+ client.send(msg);
1051
+ client.close();
1052
+ }
1053
+ });
1054
+ }
1055
+ _addWebClient(context, client) {
1056
+ return __async(this, null, function* () {
1057
+ const { name } = context != null ? context : {};
1058
+ const identifier = getIdentifier({
1059
+ name
1060
+ });
1061
+ if (this._webClientMap.has(identifier)) {
1062
+ fileLog(`${identifier}} has been added, this action will override prev WebClient`, "Broker", "warn");
1063
+ }
1064
+ try {
1065
+ this._webClientMap.set(identifier, client);
1066
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
1067
+ } catch (err) {
1068
+ const msg = error(err, ActionKind.ADD_WEB_CLIENT, "Broker");
1069
+ client.send(msg);
1070
+ client.close();
1071
+ }
1072
+ });
1073
+ }
1074
+ _notifyWebClient(context, client) {
1075
+ return __async(this, null, function* () {
1076
+ const { name, updateMode } = context != null ? context : {};
1077
+ const identifier = getIdentifier({
1078
+ name
1079
+ });
1080
+ const webClient = this._webClientMap.get(identifier);
1081
+ if (!webClient) {
1082
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`, "Broker", "warn");
1083
+ return;
1084
+ }
1085
+ try {
1086
+ const api = new ReloadWebClientAPI({
1087
+ name,
1088
+ updateMode
1089
+ });
1090
+ webClient.send(JSON.stringify(api));
1091
+ fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`, "Broker", "info");
1092
+ } catch (err) {
1093
+ const msg = error(err, ActionKind.NOTIFY_WEB_CLIENT, "Broker");
1094
+ client.send(msg);
1095
+ client.close();
1096
+ }
1097
+ });
1098
+ }
1099
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
1100
+ _addTmpSubScriberRelation(subscriber, publisher) {
1101
+ const publisherIdentifier = getIdentifier({
1102
+ name: publisher.name,
1103
+ ip: publisher.ip
1104
+ });
1105
+ const subscriberIdentifier = subscriber.name;
1106
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
1107
+ if (!shelter) {
1108
+ const map = /* @__PURE__ */ new Map();
1109
+ map.set(subscriberIdentifier, subscriber);
1110
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
1111
+ subscribers: map,
1112
+ timestamp: Date.now()
1113
+ });
1114
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `, "Broker", "info");
1115
+ return;
1116
+ }
1117
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
1118
+ if (tmpSubScriberShelterSubscriber) {
1119
+ fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`, "Broker", "warn");
1120
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1121
+ shelter.timestamp = Date.now();
1122
+ } else {
1123
+ fileLog(
1124
+ // eslint-disable-next-line max-len
1125
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
1126
+ "Broker",
1127
+ "warn"
1128
+ );
1129
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1130
+ }
1131
+ }
1132
+ _getTmpSubScribers(publisherIdentifier) {
1133
+ var _a3;
1134
+ return (_a3 = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a3.subscribers;
1135
+ }
1136
+ // after adding publisher, it will change the temp subscriber to regular subscriber
1137
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
1138
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
1139
+ fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `, "Broker", "warn");
1140
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
1141
+ publisher.notifySubscriber(identifier, {
1142
+ updateKind: UpdateKind.UPDATE_TYPE,
1143
+ updateMode: UpdateMode.PASSIVE,
1144
+ updateSourcePaths: [
1145
+ publisher.name
1146
+ ],
1147
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
1148
+ name: publisher.name
1149
+ });
1150
+ });
1151
+ }
1152
+ _clearTmpSubScriberRelation(identifier) {
1153
+ this._tmpSubscriberShelter.delete(identifier);
1154
+ }
1155
+ _clearTmpSubScriberRelations() {
1156
+ this._tmpSubscriberShelter.clear();
1157
+ }
1158
+ _disconnect() {
1159
+ this._publisherMap.forEach((publisher) => {
1160
+ publisher.close();
1161
+ });
1162
+ }
1163
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
1164
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
1165
+ _setSchedule() {
1166
+ const rule = new import_node_schedule.default.RecurrenceRule();
1167
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
1168
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
1169
+ const second = [];
1170
+ for (let i = 0; i < 60; i = i + interval) {
1171
+ second.push(i);
1172
+ }
1173
+ rule.second = second;
1174
+ } else {
1175
+ rule.second = 0;
1176
+ rule.hour = [
1177
+ 0,
1178
+ 3,
1179
+ 6,
1180
+ 9,
1181
+ 12,
1182
+ 15,
1183
+ 18
1184
+ ];
1185
+ rule.minute = 0;
1186
+ }
1187
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
1188
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
1189
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
1190
+ fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`, "Broker", "info");
1191
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
1192
+ this._clearTmpSubScriberRelation(identifier);
1193
+ }
1194
+ });
1195
+ });
1196
+ }
1197
+ _clearSchedule() {
1198
+ if (!this._scheduleJob) {
1199
+ return;
1200
+ }
1201
+ this._scheduleJob.cancel();
1202
+ this._scheduleJob = null;
1203
+ }
1204
+ _stopWhenSIGTERMOrSIGINT() {
1205
+ process.on("SIGTERM", () => {
1206
+ this.exit();
1207
+ });
1208
+ process.on("SIGINT", () => {
1209
+ this.exit();
1210
+ });
1211
+ }
1212
+ _handleUnexpectedExit() {
1213
+ process.on("unhandledRejection", (error2) => {
1214
+ console.error("Unhandled Rejection Error: ", error2);
1215
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1216
+ process.exit(1);
1217
+ });
1218
+ process.on("uncaughtException", (error2) => {
1219
+ console.error("Unhandled Exception Error: ", error2);
1220
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1221
+ process.exit(1);
1222
+ });
1223
+ }
1224
+ start() {
1225
+ return __async(this, null, function* () {
1226
+ });
1227
+ }
1228
+ exit() {
1229
+ const brokerExitLog = new BrokerExitLog();
1230
+ this.broadcast(JSON.stringify(brokerExitLog));
1231
+ this._disconnect();
1232
+ this._clearSchedule();
1233
+ this._clearTmpSubScriberRelations();
1234
+ this._webSocketServer && this._webSocketServer.close();
1235
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
1236
+ process.exit(0);
1237
+ }
1238
+ broadcast(message) {
1239
+ var _a3, _b;
1240
+ fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`, "Broker", "warn");
1241
+ (_a3 = this._webSocketServer) == null ? void 0 : _a3.clients.forEach((client) => {
1242
+ client.send(JSON.stringify(message));
1243
+ });
1244
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1245
+ client.send(JSON.stringify(message));
1246
+ });
1247
+ }
1248
+ };
1249
+ __name(_Broker, "Broker");
1250
+ __publicField(_Broker, "WEB_SOCKET_CONNECT_MAGIC_ID", WEB_SOCKET_CONNECT_MAGIC_ID);
1251
+ __publicField(_Broker, "DEFAULT_WEB_SOCKET_PORT", DEFAULT_WEB_SOCKET_PORT);
1252
+ __publicField(_Broker, "DEFAULT_SECURE_WEB_SOCKET_PORT", 16324);
1253
+ __publicField(_Broker, "DEFAULT_WAITING_TIME", 1.5 * 60 * 60 * 1e3);
1254
+ var Broker = _Broker;
1255
+
1256
+ // src/server/broker/createBroker.ts
1257
+ var import_child_process2 = require("child_process");
1258
+ var import_path2 = __toESM(require("path"));
1259
+ function createBroker() {
1260
+ const startBrokerPath = import_path2.default.resolve(__dirname, "./start-broker.js");
1261
+ const sub = (0, import_child_process2.fork)(startBrokerPath, [], {
1262
+ detached: true,
1263
+ stdio: "ignore",
1264
+ env: process.env
1265
+ });
1266
+ sub.send("start");
1267
+ sub.unref();
1268
+ return sub;
1269
+ }
1270
+ __name(createBroker, "createBroker");
1271
+
1272
+ // src/server/DevServer.ts
1273
+ var _ModuleFederationDevServer = class _ModuleFederationDevServer {
1274
+ constructor(ctx) {
1275
+ __publicField(this, "_remotes");
1276
+ __publicField(this, "_ip");
1277
+ __publicField(this, "_name");
1278
+ __publicField(this, "_remoteTypeTarPath");
1279
+ __publicField(this, "_publishWebSocket", null);
1280
+ __publicField(this, "_subscriberWebsocketMap", {});
1281
+ __publicField(this, "_reconnect", true);
1282
+ __publicField(this, "_reconnectTimes", 0);
1283
+ __publicField(this, "_isConnected", false);
1284
+ __publicField(this, "_isReconnecting", false);
1285
+ __publicField(this, "_updateCallback", /* @__PURE__ */ __name(() => Promise.resolve(void 0), "_updateCallback"));
1286
+ const { name, remotes, remoteTypeTarPath, updateCallback: updateCallback2 } = ctx;
1287
+ this._ip = getIPV4();
1288
+ this._name = name;
1289
+ this._remotes = remotes;
1290
+ this._remoteTypeTarPath = remoteTypeTarPath;
1291
+ this._updateCallback = updateCallback2;
1292
+ this._stopWhenSIGTERMOrSIGINT();
1293
+ this._handleUnexpectedExit();
1294
+ this._connectPublishToServer();
1295
+ }
1296
+ _connectPublishToServer() {
1297
+ if (!this._reconnect) {
1298
+ return;
1299
+ }
1300
+ fileLog(`Publisher:${this._name} Trying to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1301
+ this._publishWebSocket = new import_isomorphic_ws2.default(`ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1302
+ this._publishWebSocket.on("open", () => {
1303
+ var _a3;
1304
+ fileLog(`Current pid: ${process.pid}, publisher:${this._name} connected to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1305
+ this._isConnected = true;
1306
+ const addPublisherAction = new AddPublisherAction({
1307
+ name: this._name,
1308
+ ip: this._ip,
1309
+ remoteTypeTarPath: this._remoteTypeTarPath
1310
+ });
1311
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(addPublisherAction));
1312
+ this._connectSubscribers();
1313
+ });
1314
+ this._publishWebSocket.on("message", (message) => __async(this, null, function* () {
1315
+ var _a3, _b;
1316
+ try {
1317
+ const parsedMessage = JSON.parse(message.toString());
1318
+ if (parsedMessage.type === "Log") {
1319
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1320
+ fileLog(`Receive broker exit signal, ${this._name} service will exit...`, MF_SERVER_IDENTIFIER, "warn");
1321
+ this._exit();
1322
+ }
1323
+ }
1324
+ if (parsedMessage.type === "API") {
1325
+ if (parsedMessage.kind === APIKind.FETCH_TYPES) {
1326
+ const { payload: { remoteInfo } } = parsedMessage;
1327
+ fileLog(`${this._name} Receive broker FETCH_TYPES, payload as follows: ${JSON.stringify(remoteInfo, null, 2)}.`, MF_SERVER_IDENTIFIER, "info");
1328
+ yield this.fetchDynamicRemoteTypes({
1329
+ remoteInfo
1330
+ });
1331
+ }
1332
+ }
1333
+ } catch (err) {
1334
+ console.error(err);
1335
+ const exitPublisher = new ExitPublisherAction({
1336
+ name: this._name,
1337
+ ip: this._ip
1338
+ });
1339
+ const exitSubscriber = new ExitSubscriberAction({
1340
+ name: this._name,
1341
+ ip: this._ip,
1342
+ publishers: this._remotes.map((remote) => ({
1343
+ name: remote.name,
1344
+ ip: remote.ip
1345
+ }))
1346
+ });
1347
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(exitPublisher));
1348
+ (_b = this._publishWebSocket) == null ? void 0 : _b.send(JSON.stringify(exitSubscriber));
1349
+ fileLog("Parse messages error, ModuleFederationDevServer will exit...", MF_SERVER_IDENTIFIER, "fatal");
1350
+ this._exit();
1351
+ }
1352
+ }));
1353
+ this._publishWebSocket.on("close", (code) => {
1354
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1355
+ this._publishWebSocket && this._publishWebSocket.close();
1356
+ this._publishWebSocket = null;
1357
+ if (!this._reconnect) {
1358
+ return;
1359
+ }
1360
+ const reconnectTime = fib(++this._reconnectTimes);
1361
+ fileLog(`start reconnecting to server after ${reconnectTime}s.`, MF_SERVER_IDENTIFIER, "info");
1362
+ setTimeout(() => this._connectPublishToServer(), reconnectTime * 1e3);
1363
+ });
1364
+ this._publishWebSocket.on("error", this._tryCreateBackgroundBroker.bind(this));
1365
+ }
1366
+ // Associate the remotes(Subscriber) to the Broker
1367
+ _connectSubscriberToServer(remote) {
1368
+ const { name, ip } = remote;
1369
+ fileLog(`remote module:${name} trying to connect to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "info");
1370
+ const identifier = getIdentifier({
1371
+ name,
1372
+ ip
1373
+ });
1374
+ this._subscriberWebsocketMap[identifier] = new import_isomorphic_ws2.default(`ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}?WEB_SOCKET_CONNECT_MAGIC_ID=${Broker.WEB_SOCKET_CONNECT_MAGIC_ID}`);
1375
+ this._subscriberWebsocketMap[identifier].on("open", () => {
1376
+ fileLog(`Current pid: ${process.pid} remote module: ${name} connected to ws://${ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}, starting service...`, MF_SERVER_IDENTIFIER, "info");
1377
+ const addSubscriber = new AddSubscriberAction({
1378
+ name: this._name,
1379
+ ip: this._ip,
1380
+ publishers: [
1381
+ {
1382
+ name,
1383
+ ip
1384
+ }
1385
+ ]
1386
+ });
1387
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(addSubscriber));
1388
+ });
1389
+ this._subscriberWebsocketMap[identifier].on("message", (message) => __async(this, null, function* () {
1390
+ try {
1391
+ const parsedMessage = JSON.parse(message.toString());
1392
+ if (parsedMessage.type === "Log") {
1393
+ if (parsedMessage.kind === LogKind.BrokerExitLog) {
1394
+ fileLog(`${identifier}'s Server exit, thus ${identifier} will no longer has reload ability.`, MF_SERVER_IDENTIFIER, "warn");
1395
+ this._exit();
1396
+ }
1397
+ }
1398
+ if (parsedMessage.type === "API") {
1399
+ if (parsedMessage.kind === APIKind.UPDATE_SUBSCRIBER) {
1400
+ const { payload: { updateKind, updateSourcePaths, name: subscribeName, remoteTypeTarPath, updateMode } } = parsedMessage;
1401
+ yield this._updateSubscriber({
1402
+ remoteTypeTarPath,
1403
+ name: subscribeName,
1404
+ updateKind,
1405
+ updateMode,
1406
+ updateSourcePaths
1407
+ });
1408
+ }
1409
+ }
1410
+ } catch (err) {
1411
+ console.error(err);
1412
+ const exitSubscriber = new ExitSubscriberAction({
1413
+ name: this._name,
1414
+ ip: this._ip,
1415
+ publishers: [
1416
+ {
1417
+ name,
1418
+ ip
1419
+ }
1420
+ ]
1421
+ });
1422
+ this._subscriberWebsocketMap[identifier].send(JSON.stringify(exitSubscriber));
1423
+ fileLog(`${identifier} exit,
1424
+ error: ${err instanceof Error ? err.toString() : JSON.stringify(err)}
1425
+ `, MF_SERVER_IDENTIFIER, "warn");
1426
+ }
1427
+ }));
1428
+ this._subscriberWebsocketMap[identifier].on("close", (code) => {
1429
+ var _a3;
1430
+ fileLog(`Connection closed with code ${code}.`, MF_SERVER_IDENTIFIER, "warn");
1431
+ (_a3 = this._subscriberWebsocketMap[identifier]) == null ? void 0 : _a3.close();
1432
+ delete this._subscriberWebsocketMap[identifier];
1433
+ });
1434
+ this._subscriberWebsocketMap[identifier].on("error", (err) => {
1435
+ var _a3;
1436
+ if ("code" in err && err.code === "ETIMEDOUT") {
1437
+ fileLog(`Can not connect ${JSON.stringify(remote)}, please make sure this remote is started locally.`, MF_SERVER_IDENTIFIER, "warn");
1438
+ } else {
1439
+ console.error(err);
1440
+ }
1441
+ (_a3 = this._subscriberWebsocketMap[identifier]) == null ? void 0 : _a3.close();
1442
+ delete this._subscriberWebsocketMap[identifier];
1443
+ });
1444
+ }
1445
+ _connectSubscribers() {
1446
+ this._remotes.forEach((remote) => {
1447
+ this._connectSubscriberToServer(remote);
1448
+ });
1449
+ }
1450
+ // app1 consumes provider1. And the function will be triggered when provider1 code change.
1451
+ _updateSubscriber(options) {
1452
+ return __async(this, null, function* () {
1453
+ var _a3;
1454
+ const { updateMode, updateKind, updateSourcePaths, name, remoteTypeTarPath, remoteInfo } = options;
1455
+ fileLog(
1456
+ // eslint-disable-next-line max-len
1457
+ `[_updateSubscriber] run, options: ${JSON.stringify(options, null, 2)}`,
1458
+ MF_SERVER_IDENTIFIER,
1459
+ "warn"
1460
+ );
1461
+ if (updateMode === UpdateMode.PASSIVE && updateSourcePaths.includes(this._name)) {
1462
+ fileLog(
1463
+ // eslint-disable-next-line max-len
1464
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} includes ${this._name}, update ignore!`,
1465
+ MF_SERVER_IDENTIFIER,
1466
+ "warn"
1467
+ );
1468
+ return;
1469
+ }
1470
+ if (updateSourcePaths.slice(-1)[0] === this._name) {
1471
+ fileLog(`[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths} ends is ${this._name}, update ignore!`, MF_SERVER_IDENTIFIER, "warn");
1472
+ return;
1473
+ }
1474
+ fileLog(
1475
+ // eslint-disable-next-line max-len
1476
+ `[_updateSubscriber] run, updateSourcePaths:${updateSourcePaths}, current module:${this._name}, update start...`,
1477
+ MF_SERVER_IDENTIFIER,
1478
+ "info"
1479
+ );
1480
+ yield this._updateCallback({
1481
+ name,
1482
+ updateMode,
1483
+ updateKind,
1484
+ updateSourcePaths,
1485
+ remoteTypeTarPath,
1486
+ remoteInfo
1487
+ });
1488
+ const newUpdateSourcePaths = updateSourcePaths.concat(this._name);
1489
+ const updatePublisher = new UpdatePublisherAction({
1490
+ name: this._name,
1491
+ ip: this._ip,
1492
+ updateMode: UpdateMode.PASSIVE,
1493
+ updateKind,
1494
+ updateSourcePaths: newUpdateSourcePaths,
1495
+ remoteTypeTarPath: this._remoteTypeTarPath
1496
+ });
1497
+ fileLog(
1498
+ // eslint-disable-next-line max-len
1499
+ `[_updateSubscriber] run, updateSourcePaths:${newUpdateSourcePaths}, update publisher ${this._name} start...`,
1500
+ MF_SERVER_IDENTIFIER,
1501
+ "info"
1502
+ );
1503
+ (_a3 = this._publishWebSocket) == null ? void 0 : _a3.send(JSON.stringify(updatePublisher));
1504
+ });
1505
+ }
1506
+ _tryCreateBackgroundBroker(err) {
1507
+ if (!(((err == null ? void 0 : err.code) === "ECONNREFUSED" || (err == null ? void 0 : err.code) === "ETIMEDOUT") && err.port === Broker.DEFAULT_WEB_SOCKET_PORT)) {
1508
+ fileLog(`websocket error: ${err.stack}`, MF_SERVER_IDENTIFIER, "fatal");
1509
+ return;
1510
+ }
1511
+ fileLog(`Failed to connect to ws://${this._ip}:${Broker.DEFAULT_WEB_SOCKET_PORT}...`, MF_SERVER_IDENTIFIER, "fatal");
1512
+ this._isReconnecting = true;
1513
+ setTimeout(() => {
1514
+ this._isReconnecting = false;
1515
+ if (this._reconnect === false) {
1516
+ return;
1517
+ }
1518
+ fileLog("Creating new background broker...", MF_SERVER_IDENTIFIER, "warn");
1519
+ const broker = createBroker();
1520
+ broker.on("message", (message) => {
1521
+ if (message === "ready") {
1522
+ fileLog("background broker started.", MF_SERVER_IDENTIFIER, "info");
1523
+ this._reconnectTimes = 1;
1524
+ if (process.send) {
1525
+ process.send("ready");
1526
+ }
1527
+ }
1528
+ });
1529
+ }, Math.ceil(100 * Math.random()));
1530
+ }
1531
+ _stopWhenSIGTERMOrSIGINT() {
1532
+ process.on("SIGTERM", () => {
1533
+ fileLog(`Process(${process.pid}) SIGTERM, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1534
+ this._exit();
1535
+ });
1536
+ process.on("SIGINT", () => {
1537
+ fileLog(`Process(${process.pid}) SIGINT, ModuleFederationDevServer will exit...`, MF_SERVER_IDENTIFIER, "warn");
1538
+ this._exit();
1539
+ });
1540
+ }
1541
+ _handleUnexpectedExit() {
1542
+ process.on("unhandledRejection", (error2) => {
1543
+ if (this._isReconnecting) {
1544
+ return;
1545
+ }
1546
+ console.error("Unhandled Rejection Error: ", error2);
1547
+ fileLog(`Process(${process.pid}) unhandledRejection, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1548
+ this._exit();
1549
+ });
1550
+ process.on("uncaughtException", (error2) => {
1551
+ if (this._isReconnecting) {
1552
+ return;
1553
+ }
1554
+ console.error("Unhandled Exception Error: ", error2);
1555
+ fileLog(`Process(${process.pid}) uncaughtException, garfishModuleServer will exit...`, MF_SERVER_IDENTIFIER, "error");
1556
+ this._exit();
1557
+ });
1558
+ }
1559
+ _exit() {
1560
+ this._reconnect = false;
1561
+ if (this._publishWebSocket) {
1562
+ const exitPublisher = new ExitPublisherAction({
1563
+ name: this._name,
1564
+ ip: this._ip
1565
+ });
1566
+ this._publishWebSocket.send(JSON.stringify(exitPublisher));
1567
+ this._publishWebSocket.on("message", (message) => {
1568
+ const parsedMessage = JSON.parse(message.toString());
1569
+ fileLog(`[${parsedMessage.kind}]: ${JSON.stringify(parsedMessage)}`, MF_SERVER_IDENTIFIER, "info");
1570
+ });
1571
+ }
1572
+ if (this._publishWebSocket) {
1573
+ this._publishWebSocket.close();
1574
+ this._publishWebSocket = null;
1575
+ }
1576
+ process.exit(0);
1577
+ }
1578
+ exit() {
1579
+ this._exit();
1580
+ }
1581
+ update(options) {
1582
+ if (!this._publishWebSocket || !this._isConnected) {
1583
+ return;
1584
+ }
1585
+ const { updateKind, updateMode, updateSourcePaths, clientName } = options;
1586
+ fileLog(`update run, ${this._name} module update, updateKind: ${updateKind}, updateMode: ${updateMode}, updateSourcePaths: ${updateSourcePaths}`, MF_SERVER_IDENTIFIER, "info");
1587
+ if (updateKind === UpdateKind.RELOAD_PAGE) {
1588
+ const notifyWebClient = new NotifyWebClientAction({
1589
+ name: clientName || this._name,
1590
+ updateMode
1591
+ });
1592
+ this._publishWebSocket.send(JSON.stringify(notifyWebClient));
1593
+ return;
1594
+ }
1595
+ const updatePublisher = new UpdatePublisherAction({
1596
+ name: this._name,
1597
+ ip: this._ip,
1598
+ updateMode,
1599
+ updateKind,
1600
+ updateSourcePaths: [
1601
+ this._name
1602
+ ],
1603
+ remoteTypeTarPath: this._remoteTypeTarPath
1604
+ });
1605
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1606
+ }
1607
+ fetchDynamicRemoteTypes(options) {
1608
+ return __async(this, null, function* () {
1609
+ const { remoteInfo, once } = options;
1610
+ const updateMode = UpdateMode.PASSIVE;
1611
+ const updateKind = UpdateKind.UPDATE_TYPE;
1612
+ fileLog(`fetchDynamicRemoteTypes: remoteInfo: ${JSON.stringify(remoteInfo)}`, MF_SERVER_IDENTIFIER, "info");
1613
+ yield this._updateCallback({
1614
+ name: this._name,
1615
+ updateMode,
1616
+ updateKind,
1617
+ updateSourcePaths: [],
1618
+ remoteTypeTarPath: "",
1619
+ remoteInfo,
1620
+ once
1621
+ });
1622
+ const updatePublisher = new UpdatePublisherAction({
1623
+ name: this._name,
1624
+ ip: this._ip,
1625
+ updateMode,
1626
+ updateKind,
1627
+ updateSourcePaths: [
1628
+ this._name
1629
+ ],
1630
+ remoteTypeTarPath: this._remoteTypeTarPath
1631
+ });
1632
+ this._publishWebSocket.send(JSON.stringify(updatePublisher));
1633
+ });
1634
+ }
1635
+ };
1636
+ __name(_ModuleFederationDevServer, "ModuleFederationDevServer");
1637
+ var ModuleFederationDevServer = _ModuleFederationDevServer;
1638
+
1639
+ // src/server/createKoaServer.ts
1640
+ var import_fs_extra2 = __toESM(require("fs-extra"));
1641
+ var import_koa = __toESM(require("koa"));
1642
+ function createKoaServer(options) {
1643
+ return __async(this, null, function* () {
1644
+ const { typeTarPath } = options;
1645
+ const freeport = yield getFreePort();
1646
+ const app = new import_koa.default();
1647
+ app.use((ctx, next) => __async(this, null, function* () {
1648
+ if (ctx.path === `/${DEFAULT_TAR_NAME}`) {
1649
+ ctx.status = 200;
1650
+ ctx.body = import_fs_extra2.default.createReadStream(typeTarPath);
1651
+ ctx.response.type = "application/x-gzip";
1652
+ } else {
1653
+ yield next();
1654
+ }
1655
+ }));
1656
+ app.listen(freeport);
1657
+ return {
1658
+ server: app,
1659
+ serverAddress: `http://${getIPV4()}:${freeport}`
1660
+ };
1661
+ });
1662
+ }
1663
+ __name(createKoaServer, "createKoaServer");
1664
+
1665
+ // src/core/lib/archiveHandler.ts
1666
+ var retrieveTypesZipPath = /* @__PURE__ */ __name((mfTypesPath, remoteOptions) => (0, import_path3.join)(mfTypesPath.replace(remoteOptions.typesFolder, ""), `${remoteOptions.typesFolder}.zip`), "retrieveTypesZipPath");
1667
+ var createTypesArchive = /* @__PURE__ */ __name((tsConfig, remoteOptions) => __async(void 0, null, function* () {
1668
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1669
+ const zip = new import_adm_zip.default();
1670
+ zip.addLocalFolder(mfTypesPath);
1671
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1672
+ }), "createTypesArchive");
1673
+ var downloadErrorLogger = /* @__PURE__ */ __name((destinationFolder, fileToDownload) => (reason) => {
1674
+ throw __spreadProps(__spreadValues({}, reason), {
1675
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1676
+ });
1677
+ }, "downloadErrorLogger");
1678
+ var retrieveTypesArchiveDestinationPath = /* @__PURE__ */ __name((hostOptions, destinationFolder) => {
1679
+ return (0, import_path3.resolve)(hostOptions.context, hostOptions.typesFolder, destinationFolder);
1680
+ }, "retrieveTypesArchiveDestinationPath");
1681
+ var downloadTypesArchive = /* @__PURE__ */ __name((hostOptions) => {
1682
+ let retries = 0;
1683
+ return (_0) => __async(void 0, [_0], function* ([destinationFolder, fileToDownload]) {
1684
+ var _a3;
1685
+ const destinationPath = retrieveTypesArchiveDestinationPath(hostOptions, destinationFolder);
1686
+ while (retries++ < hostOptions.maxRetries) {
1687
+ try {
1688
+ const url = new URL(fileToDownload).href;
1689
+ const response = yield axiosGet(url, {
1690
+ responseType: "arraybuffer",
1691
+ timeout: hostOptions.timeout,
1692
+ family: hostOptions.family
1693
+ }).catch(downloadErrorLogger(destinationFolder, url));
1694
+ if (typeof ((_a3 = response.headers) == null ? void 0 : _a3["content-type"]) === "string" && response.headers["content-type"].includes("text/html")) {
1695
+ throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);
1696
+ }
1697
+ try {
1698
+ if (hostOptions.deleteTypesFolder) {
1699
+ yield (0, import_promises2.rm)(destinationPath, {
1700
+ recursive: true,
1701
+ force: true
1702
+ });
1703
+ }
1704
+ } catch (error2) {
1705
+ fileLog(`Unable to remove types folder, ${error2}`, "downloadTypesArchive", "error");
1706
+ }
1707
+ const zip = new import_adm_zip.default(Buffer.from(response.data));
1708
+ zip.extractAllTo(destinationPath, true);
1709
+ fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`, "downloadTypesArchive", "info");
1710
+ return [
1711
+ destinationFolder,
1712
+ destinationPath
1713
+ ];
1714
+ } catch (error2) {
1715
+ fileLog(`Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`, "downloadTypesArchive", "error");
1716
+ if (retries >= hostOptions.maxRetries) {
1717
+ logger.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);
1718
+ if (hostOptions.abortOnError !== false) {
1719
+ throw error2;
1720
+ }
1721
+ return void 0;
1722
+ }
1723
+ }
1724
+ }
1725
+ });
1726
+ }, "downloadTypesArchive");
1727
+
1728
+ // src/core/configurations/hostPlugin.ts
1729
+ var import_sdk4 = require("@module-federation/sdk");
1730
+ var import_managers = require("@module-federation/managers");
1731
+ var defaultOptions = {
1732
+ typesFolder: "@mf-types",
1733
+ remoteTypesFolder: "@mf-types",
1734
+ deleteTypesFolder: true,
1735
+ maxRetries: 3,
1736
+ implementation: "",
1737
+ context: process.cwd(),
1738
+ abortOnError: true,
1739
+ consumeAPITypes: false,
1740
+ runtimePkgs: [],
1741
+ remoteTypeUrls: {},
1742
+ timeout: 6e4,
1743
+ typesOnBuild: false,
1744
+ family: 4
1745
+ };
1746
+ var buildZipUrl = /* @__PURE__ */ __name((hostOptions, url) => {
1747
+ const remoteUrl = new URL(url, "file:");
1748
+ const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
1749
+ remoteUrl.pathname = `${pathnameWithoutEntry}/${hostOptions.remoteTypesFolder}.zip`;
1750
+ return remoteUrl.protocol === "file:" ? remoteUrl.pathname : remoteUrl.href;
1751
+ }, "buildZipUrl");
1752
+ var buildApiTypeUrl = /* @__PURE__ */ __name((zipUrl) => {
1753
+ if (!zipUrl) {
1754
+ return void 0;
1755
+ }
1756
+ return zipUrl.replace(".zip", ".d.ts");
1757
+ }, "buildApiTypeUrl");
1758
+ var retrieveRemoteInfo = /* @__PURE__ */ __name((options) => {
1759
+ const { hostOptions, remoteAlias, remote } = options;
1760
+ const { remoteTypeUrls } = hostOptions;
1761
+ let decodedRemote = remote;
1762
+ if (decodedRemote.startsWith(import_sdk4.ENCODE_NAME_PREFIX)) {
1763
+ decodedRemote = (0, import_sdk4.decodeName)(decodedRemote, import_sdk4.ENCODE_NAME_PREFIX);
1764
+ }
1765
+ const parsedInfo = (0, import_sdk4.parseEntry)(decodedRemote, void 0, "@");
1766
+ const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === decodedRemote ? decodedRemote : "";
1767
+ let zipUrl = "";
1768
+ let apiTypeUrl = "";
1769
+ const name = parsedInfo.name || remoteAlias;
1770
+ if (typeof remoteTypeUrls === "object" && remoteTypeUrls[name]) {
1771
+ zipUrl = remoteTypeUrls[name].zip;
1772
+ apiTypeUrl = remoteTypeUrls[name].api;
1773
+ }
1774
+ if (!zipUrl && url) {
1775
+ zipUrl = buildZipUrl(hostOptions, url);
1776
+ }
1777
+ if (!apiTypeUrl && zipUrl) {
1778
+ apiTypeUrl = buildApiTypeUrl(zipUrl);
1779
+ }
1780
+ return {
1781
+ name,
1782
+ url,
1783
+ zipUrl,
1784
+ apiTypeUrl,
1785
+ alias: remoteAlias
1786
+ };
1787
+ }, "retrieveRemoteInfo");
1788
+ var resolveRemotes = /* @__PURE__ */ __name((hostOptions) => {
1789
+ var _a3;
1790
+ const parsedOptions = import_managers.utils.parseOptions(hostOptions.moduleFederationConfig.remotes || {}, (item, key) => ({
1791
+ remote: Array.isArray(item) ? item[0] : item,
1792
+ key
1793
+ }), (item, key) => ({
1794
+ remote: Array.isArray(item.external) ? item.external[0] : item.external,
1795
+ key
1796
+ }));
1797
+ const remoteTypeUrls = (_a3 = hostOptions.remoteTypeUrls) != null ? _a3 : {};
1798
+ if (typeof remoteTypeUrls !== "object") {
1799
+ throw new Error("remoteTypeUrls must be consumed before resolveRemotes");
1800
+ }
1801
+ const remoteInfos = Object.keys(remoteTypeUrls).reduce((sum, remoteName) => {
1802
+ const { zip, api, alias } = remoteTypeUrls[remoteName];
1803
+ sum[alias] = {
1804
+ name: remoteName,
1805
+ url: "",
1806
+ zipUrl: zip,
1807
+ apiTypeUrl: api,
1808
+ alias: alias || remoteName
1809
+ };
1810
+ return sum;
1811
+ }, {});
1812
+ return parsedOptions.reduce((accumulator, item) => {
1813
+ const { key, remote } = item[1];
1814
+ const res = retrieveRemoteInfo({
1815
+ hostOptions,
1816
+ remoteAlias: key,
1817
+ remote
1818
+ });
1819
+ if (accumulator[key]) {
1820
+ accumulator[key] = __spreadProps(__spreadValues({}, accumulator[key]), {
1821
+ url: res.url,
1822
+ apiTypeUrl: accumulator[key].apiTypeUrl || res.apiTypeUrl
1823
+ });
1824
+ return accumulator;
1825
+ }
1826
+ accumulator[key] = res;
1827
+ return accumulator;
1828
+ }, remoteInfos);
1829
+ }, "resolveRemotes");
1830
+ var retrieveHostConfig = /* @__PURE__ */ __name((options) => {
1831
+ validateOptions(options);
1832
+ const hostOptions = __spreadValues(__spreadValues({}, defaultOptions), options);
1833
+ const mapRemotesToDownload = resolveRemotes(hostOptions);
1834
+ return {
1835
+ hostOptions,
1836
+ mapRemotesToDownload
1837
+ };
1838
+ }, "retrieveHostConfig");
1839
+
1840
+ // src/core/constant.ts
1841
+ var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
1842
+ var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
1843
+ var HOST_API_TYPES_FILE_NAME = "index.d.ts";
1844
+
1845
+ // src/core/lib/DTSManager.ts
1846
+ var _a;
1847
+ var DTSManager = (_a = class {
1848
+ constructor(options) {
1849
+ __publicField(this, "options");
1850
+ __publicField(this, "runtimePkgs");
1851
+ __publicField(this, "remoteAliasMap");
1852
+ __publicField(this, "loadedRemoteAPIAlias");
1853
+ __publicField(this, "extraOptions");
1854
+ __publicField(this, "updatedRemoteInfos");
1855
+ this.options = cloneDeepOptions(options);
1856
+ this.runtimePkgs = [
1857
+ "@module-federation/runtime",
1858
+ "@module-federation/enhanced/runtime",
1859
+ "@module-federation/runtime-tools"
1860
+ ];
1861
+ this.loadedRemoteAPIAlias = /* @__PURE__ */ new Set();
1862
+ this.remoteAliasMap = {};
1863
+ this.extraOptions = (options == null ? void 0 : options.extraOptions) || {};
1864
+ this.updatedRemoteInfos = {};
1865
+ }
1866
+ generateAPITypes(mapComponentsToExpose) {
1867
+ const exposePaths = /* @__PURE__ */ new Set();
1868
+ const packageType = Object.keys(mapComponentsToExpose).reduce((sum, exposeKey) => {
1869
+ const exposePath = import_path4.default.join(REMOTE_ALIAS_IDENTIFIER, exposeKey).split(import_path4.default.sep).join("/");
1870
+ exposePaths.add(`'${exposePath}'`);
1871
+ const curType = `T extends '${exposePath}' ? typeof import('${exposePath}') :`;
1872
+ sum = curType + sum;
1873
+ return sum;
1874
+ }, "any;");
1875
+ const exposePathKeys = [
1876
+ ...exposePaths
1877
+ ].join(" | ");
1878
+ return `
1879
+ export type RemoteKeys = ${exposePathKeys};
1880
+ type PackageType<T> = ${packageType}`;
1881
+ }
1882
+ extractRemoteTypes(options) {
1883
+ return __async(this, null, function* () {
1884
+ var _a3;
1885
+ const { remoteOptions, tsConfig } = options;
1886
+ if (!remoteOptions.extractRemoteTypes) {
1887
+ return;
1888
+ }
1889
+ let hasRemotes = false;
1890
+ const remotes = remoteOptions.moduleFederationConfig.remotes;
1891
+ if (remotes) {
1892
+ if (Array.isArray(remotes)) {
1893
+ hasRemotes = Boolean(remotes.length);
1894
+ } else if (typeof remotes === "object") {
1895
+ hasRemotes = Boolean(Object.keys(remotes).length);
1896
+ }
1897
+ }
1898
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1899
+ if (hasRemotes && this.options.host) {
1900
+ try {
1901
+ const { hostOptions } = retrieveHostConfig(this.options.host);
1902
+ const remoteTypesFolder = import_path4.default.resolve(hostOptions.context, hostOptions.typesFolder);
1903
+ const targetDir = import_path4.default.join(mfTypesPath, "node_modules");
1904
+ if (import_fs.default.existsSync(remoteTypesFolder)) {
1905
+ const targetFolder = import_path4.default.resolve(remoteOptions.context, targetDir);
1906
+ yield import_fs_extra3.default.ensureDir(targetFolder);
1907
+ yield import_fs_extra3.default.copy(remoteTypesFolder, targetFolder, {
1908
+ overwrite: true
1909
+ });
1910
+ }
1911
+ } catch (err) {
1912
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
1913
+ fileLog(`Unable to copy remote types, ${err}`, "extractRemoteTypes", "error");
1914
+ } else {
1915
+ throw err;
1916
+ }
1917
+ }
1918
+ }
1919
+ });
1920
+ }
1921
+ // it must execute after consumeTypes
1922
+ generateTypes() {
1923
+ return __async(this, null, function* () {
1924
+ var _a3, _b;
1925
+ try {
1926
+ const { options } = this;
1927
+ if (!options.remote) {
1928
+ throw new Error("options.remote is required if you want to generateTypes");
1929
+ }
1930
+ const { remoteOptions, tsConfig, mapComponentsToExpose } = retrieveRemoteConfig(options.remote);
1931
+ if (!Object.keys(mapComponentsToExpose).length) {
1932
+ return;
1933
+ }
1934
+ if (!((_a3 = tsConfig.files) == null ? void 0 : _a3.length)) {
1935
+ logger.info("No type files to compile, skip");
1936
+ return;
1937
+ }
1938
+ if (tsConfig.compilerOptions.tsBuildInfoFile) {
1939
+ try {
1940
+ const tsBuildInfoFile = import_path4.default.resolve(remoteOptions.context, tsConfig.compilerOptions.tsBuildInfoFile);
1941
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1942
+ if (!import_fs.default.existsSync(mfTypesPath)) {
1943
+ import_fs.default.rmSync(tsBuildInfoFile, {
1944
+ force: true
1945
+ });
1946
+ }
1947
+ } catch (e) {
1948
+ }
1949
+ }
1950
+ yield this.extractRemoteTypes({
1951
+ remoteOptions,
1952
+ tsConfig,
1953
+ mapComponentsToExpose
1954
+ });
1955
+ yield compileTs(mapComponentsToExpose, tsConfig, remoteOptions);
1956
+ yield createTypesArchive(tsConfig, remoteOptions);
1957
+ let apiTypesPath = "";
1958
+ if (remoteOptions.generateAPITypes) {
1959
+ const apiTypes = this.generateAPITypes(mapComponentsToExpose);
1960
+ apiTypesPath = retrieveMfAPITypesPath(tsConfig, remoteOptions);
1961
+ import_fs.default.writeFileSync(apiTypesPath, apiTypes);
1962
+ }
1963
+ try {
1964
+ if (remoteOptions.deleteTypesFolder) {
1965
+ yield (0, import_promises3.rm)(retrieveMfTypesPath(tsConfig, remoteOptions), {
1966
+ recursive: true,
1967
+ force: true
1968
+ });
1969
+ }
1970
+ } catch (err) {
1971
+ if (isDebugMode()) {
1972
+ console.error(err);
1973
+ }
1974
+ }
1975
+ logger.success("Federated types created correctly");
1976
+ } catch (error2) {
1977
+ if (((_b = this.options.remote) == null ? void 0 : _b.abortOnError) === false) {
1978
+ if (this.options.displayErrorInTerminal) {
1979
+ logger.error(error2);
1980
+ }
1981
+ } else {
1982
+ throw error2;
1983
+ }
1984
+ }
1985
+ });
1986
+ }
1987
+ requestRemoteManifest(remoteInfo, hostOptions) {
1988
+ return __async(this, null, function* () {
1989
+ try {
1990
+ if (!remoteInfo.url.includes(import_sdk5.MANIFEST_EXT)) {
1991
+ return remoteInfo;
1992
+ }
1993
+ if (remoteInfo.zipUrl) {
1994
+ return remoteInfo;
1995
+ }
1996
+ const url = remoteInfo.url;
1997
+ const res = yield axiosGet(url, {
1998
+ timeout: hostOptions.timeout,
1999
+ family: hostOptions.family
2000
+ });
2001
+ const manifestJson = res.data;
2002
+ if (!manifestJson.metaData.types.zip) {
2003
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
2004
+ }
2005
+ const addProtocol = /* @__PURE__ */ __name((u) => {
2006
+ if (u.startsWith("//")) {
2007
+ return `https:${u}`;
2008
+ }
2009
+ return u;
2010
+ }, "addProtocol");
2011
+ let publicPath;
2012
+ if ("publicPath" in manifestJson.metaData) {
2013
+ publicPath = manifestJson.metaData.publicPath;
2014
+ } else {
2015
+ const getPublicPath = new Function(manifestJson.metaData.getPublicPath);
2016
+ if (manifestJson.metaData.getPublicPath.startsWith("function")) {
2017
+ publicPath = getPublicPath()();
2018
+ } else {
2019
+ publicPath = getPublicPath();
2020
+ }
2021
+ }
2022
+ if (publicPath === "auto") {
2023
+ publicPath = (0, import_sdk5.inferAutoPublicPath)(remoteInfo.url);
2024
+ }
2025
+ remoteInfo.zipUrl = new URL(import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.zip)).href;
2026
+ if (!manifestJson.metaData.types.api) {
2027
+ console.warn(`Can not get ${remoteInfo.name}'s api types url!`);
2028
+ remoteInfo.apiTypeUrl = "";
2029
+ return remoteInfo;
2030
+ }
2031
+ remoteInfo.apiTypeUrl = new URL(import_path4.default.join(addProtocol(publicPath), manifestJson.metaData.types.api)).href;
2032
+ return remoteInfo;
2033
+ } catch (_err) {
2034
+ fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`, "requestRemoteManifest", "error");
2035
+ return remoteInfo;
2036
+ }
2037
+ });
2038
+ }
2039
+ consumeTargetRemotes(hostOptions, remoteInfo) {
2040
+ return __async(this, null, function* () {
2041
+ if (!remoteInfo.zipUrl) {
2042
+ throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);
2043
+ }
2044
+ const typesDownloader = downloadTypesArchive(hostOptions);
2045
+ return typesDownloader([
2046
+ remoteInfo.alias,
2047
+ remoteInfo.zipUrl
2048
+ ]);
2049
+ });
2050
+ }
2051
+ downloadAPITypes(remoteInfo, destinationPath, hostOptions) {
2052
+ return __async(this, null, function* () {
2053
+ const { apiTypeUrl } = remoteInfo;
2054
+ if (!apiTypeUrl) {
2055
+ return;
2056
+ }
2057
+ try {
2058
+ const url = apiTypeUrl;
2059
+ const res = yield axiosGet(url, {
2060
+ timeout: hostOptions.timeout,
2061
+ family: hostOptions.family
2062
+ });
2063
+ let apiTypeFile = res.data;
2064
+ apiTypeFile = apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER, remoteInfo.alias);
2065
+ const filePath = import_path4.default.join(destinationPath, REMOTE_API_TYPES_FILE_NAME);
2066
+ import_fs.default.writeFileSync(filePath, apiTypeFile);
2067
+ const existed = this.loadedRemoteAPIAlias.has(remoteInfo.alias);
2068
+ this.loadedRemoteAPIAlias.add(remoteInfo.alias);
2069
+ fileLog(`success`, "downloadAPITypes", "info");
2070
+ return existed;
2071
+ } catch (err) {
2072
+ fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`, "downloadAPITypes", "error");
2073
+ }
2074
+ });
2075
+ }
2076
+ consumeAPITypes(hostOptions) {
2077
+ const apiTypeFileName = import_path4.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME);
2078
+ try {
2079
+ const existedFile = import_fs.default.readFileSync(apiTypeFileName, "utf-8");
2080
+ const existedImports = new import_third_party_dts_extractor2.ThirdPartyExtractor({
2081
+ destDir: ""
2082
+ }).collectTypeImports(existedFile);
2083
+ existedImports.forEach((existedImport) => {
2084
+ const alias = existedImport.split("./").slice(1).join("./").replace("/apis.d.ts", "");
2085
+ this.loadedRemoteAPIAlias.add(alias);
2086
+ });
2087
+ } catch (err) {
2088
+ }
2089
+ if (!this.loadedRemoteAPIAlias.size) {
2090
+ return;
2091
+ }
2092
+ const packageTypes = [];
2093
+ const remoteKeys = [];
2094
+ const importTypeStr = [
2095
+ ...this.loadedRemoteAPIAlias
2096
+ ].sort().map((alias, index) => {
2097
+ const remoteKey = `RemoteKeys_${index}`;
2098
+ const packageType = `PackageType_${index}`;
2099
+ packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);
2100
+ remoteKeys.push(remoteKey);
2101
+ return `import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`;
2102
+ }).join("\n");
2103
+ const remoteKeysStr = `type RemoteKeys = ${remoteKeys.join(" | ")};`;
2104
+ const packageTypesStr = `type PackageType<T, Y=any> = ${[
2105
+ ...packageTypes,
2106
+ "Y"
2107
+ ].join(" :\n")} ;`;
2108
+ const runtimePkgs = /* @__PURE__ */ new Set();
2109
+ [
2110
+ ...this.runtimePkgs,
2111
+ ...hostOptions.runtimePkgs
2112
+ ].forEach((pkg) => {
2113
+ runtimePkgs.add(pkg);
2114
+ });
2115
+ const pkgsDeclareStr = [
2116
+ ...runtimePkgs
2117
+ ].map((pkg) => {
2118
+ return `declare module "${pkg}" {
2119
+ ${remoteKeysStr}
2120
+ ${packageTypesStr}
2121
+ export function loadRemote<T extends RemoteKeys,Y>(packageName: T): Promise<PackageType<T, Y>>;
2122
+ export function loadRemote<T extends string,Y>(packageName: T): Promise<PackageType<T, Y>>;
2123
+ }`;
2124
+ }).join("\n");
2125
+ const fileStr = `${importTypeStr}
2126
+ ${pkgsDeclareStr}
2127
+ `;
2128
+ import_fs.default.writeFileSync(import_path4.default.join(hostOptions.context, hostOptions.typesFolder, HOST_API_TYPES_FILE_NAME), fileStr);
2129
+ }
2130
+ consumeArchiveTypes(options) {
2131
+ return __async(this, null, function* () {
2132
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(options);
2133
+ const downloadPromises = Object.entries(mapRemotesToDownload).map((item) => __async(this, null, function* () {
2134
+ const remoteInfo = item[1];
2135
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
2136
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
2137
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
2138
+ }
2139
+ return this.consumeTargetRemotes(hostOptions, this.remoteAliasMap[remoteInfo.alias]);
2140
+ }));
2141
+ const downloadPromisesResult = yield Promise.allSettled(downloadPromises);
2142
+ return {
2143
+ hostOptions,
2144
+ downloadPromisesResult
2145
+ };
2146
+ });
2147
+ }
2148
+ consumeTypes() {
2149
+ return __async(this, null, function* () {
2150
+ var _a3;
2151
+ try {
2152
+ const { options } = this;
2153
+ if (!options.host) {
2154
+ throw new Error("options.host is required if you want to consumeTypes");
2155
+ }
2156
+ const { mapRemotesToDownload } = retrieveHostConfig(options.host);
2157
+ if (!Object.keys(mapRemotesToDownload).length) {
2158
+ return;
2159
+ }
2160
+ const { downloadPromisesResult, hostOptions } = yield this.consumeArchiveTypes(options.host);
2161
+ if (hostOptions.consumeAPITypes) {
2162
+ yield Promise.all(downloadPromisesResult.map((item) => __async(this, null, function* () {
2163
+ if (item.status === "rejected" || !item.value) {
2164
+ return;
2165
+ }
2166
+ const [alias, destinationPath] = item.value;
2167
+ const remoteInfo = this.remoteAliasMap[alias];
2168
+ if (!remoteInfo) {
2169
+ return;
2170
+ }
2171
+ yield this.downloadAPITypes(remoteInfo, destinationPath, hostOptions);
2172
+ })));
2173
+ this.consumeAPITypes(hostOptions);
2174
+ }
2175
+ logger.success("Federated types extraction completed");
2176
+ } catch (err) {
2177
+ if (((_a3 = this.options.host) == null ? void 0 : _a3.abortOnError) === false) {
2178
+ fileLog(`Unable to consume federated types, ${err}`, "consumeTypes", "error");
2179
+ } else {
2180
+ throw err;
2181
+ }
2182
+ }
2183
+ });
2184
+ }
2185
+ updateTypes(options) {
2186
+ return __async(this, null, function* () {
2187
+ var _a3, _b, _c;
2188
+ try {
2189
+ const { remoteName, updateMode, remoteTarPath, remoteInfo: updatedRemoteInfo, once } = options;
2190
+ const hostName = (_c = (_b = (_a3 = this.options) == null ? void 0 : _a3.host) == null ? void 0 : _b.moduleFederationConfig) == null ? void 0 : _c.name;
2191
+ fileLog(`options: ${JSON.stringify(options, null, 2)};
2192
+ hostName: ${hostName}`, "updateTypes", "info");
2193
+ if (updateMode === UpdateMode.POSITIVE && remoteName === hostName) {
2194
+ if (!this.options.remote) {
2195
+ return;
2196
+ }
2197
+ yield this.generateTypes();
2198
+ } else {
2199
+ const { remoteAliasMap } = this;
2200
+ if (!this.options.host) {
2201
+ return;
2202
+ }
2203
+ const { hostOptions, mapRemotesToDownload } = retrieveHostConfig(this.options.host);
2204
+ const loadedRemoteInfo = Object.values(remoteAliasMap).find((i) => i.name === remoteName);
2205
+ const consumeTypes2 = /* @__PURE__ */ __name((requiredRemoteInfo) => __async(this, null, function* () {
2206
+ fileLog(`consumeTypes start`, "updateTypes", "info");
2207
+ if (!requiredRemoteInfo.zipUrl) {
2208
+ throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);
2209
+ }
2210
+ const [_alias, destinationPath] = yield this.consumeTargetRemotes(hostOptions, __spreadProps(__spreadValues({}, requiredRemoteInfo), {
2211
+ // use remoteTarPath first
2212
+ zipUrl: remoteTarPath || requiredRemoteInfo.zipUrl
2213
+ }));
2214
+ const addNew = yield this.downloadAPITypes(requiredRemoteInfo, destinationPath, hostOptions);
2215
+ if (addNew) {
2216
+ this.consumeAPITypes(hostOptions);
2217
+ }
2218
+ fileLog(`consumeTypes end`, "updateTypes", "info");
2219
+ }), "consumeTypes");
2220
+ fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo, null, 2)}`, "updateTypes", "info");
2221
+ if (!loadedRemoteInfo) {
2222
+ const remoteInfo = Object.values(mapRemotesToDownload).find((item) => {
2223
+ return item.name === remoteName;
2224
+ });
2225
+ fileLog(`remoteInfo: ${JSON.stringify(remoteInfo, null, 2)}`, "updateTypes", "info");
2226
+ if (remoteInfo) {
2227
+ if (!this.remoteAliasMap[remoteInfo.alias]) {
2228
+ const requiredRemoteInfo = yield this.requestRemoteManifest(remoteInfo, hostOptions);
2229
+ this.remoteAliasMap[remoteInfo.alias] = requiredRemoteInfo;
2230
+ }
2231
+ yield consumeTypes2(this.remoteAliasMap[remoteInfo.alias]);
2232
+ } else if (updatedRemoteInfo) {
2233
+ const consumeDynamicRemoteTypes = /* @__PURE__ */ __name(() => __async(this, null, function* () {
2234
+ yield consumeTypes2(this.updatedRemoteInfos[updatedRemoteInfo.name]);
2235
+ }), "consumeDynamicRemoteTypes");
2236
+ if (!this.updatedRemoteInfos[updatedRemoteInfo.name]) {
2237
+ const parsedRemoteInfo = retrieveRemoteInfo({
2238
+ hostOptions,
2239
+ remoteAlias: updatedRemoteInfo.alias || updatedRemoteInfo.name,
2240
+ remote: updatedRemoteInfo.url
2241
+ });
2242
+ fileLog(`start request manifest`, "consumeTypes", "info");
2243
+ this.updatedRemoteInfos[updatedRemoteInfo.name] = yield this.requestRemoteManifest(parsedRemoteInfo, hostOptions);
2244
+ fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name], null, 2)}`, "updateTypes", "info");
2245
+ yield consumeDynamicRemoteTypes();
2246
+ }
2247
+ if (!once && this.updatedRemoteInfos[updatedRemoteInfo.name]) {
2248
+ yield consumeDynamicRemoteTypes();
2249
+ }
2250
+ }
2251
+ } else {
2252
+ yield consumeTypes2(loadedRemoteInfo);
2253
+ }
2254
+ }
2255
+ } catch (err) {
2256
+ fileLog(`updateTypes fail, ${err}`, "updateTypes", "error");
2257
+ }
2258
+ });
2259
+ }
2260
+ }, __name(_a, "DTSManager"), _a);
2261
+
2262
+ // src/core/lib/utils.ts
2263
+ var import_lodash = __toESM(require("lodash.clonedeepwith"));
2264
+ function getDTSManagerConstructor(implementation) {
2265
+ if (implementation) {
2266
+ const NewConstructor = require(implementation);
2267
+ return NewConstructor.default ? NewConstructor.default : NewConstructor;
2268
+ }
2269
+ return DTSManager;
2270
+ }
2271
+ __name(getDTSManagerConstructor, "getDTSManagerConstructor");
2272
+ var validateOptions = /* @__PURE__ */ __name((options) => {
2273
+ if (!options.moduleFederationConfig) {
2274
+ throw new Error("moduleFederationConfig is required");
2275
+ }
2276
+ }, "validateOptions");
2277
+ function isDebugMode() {
2278
+ return Boolean(process.env["FEDERATION_DEBUG"]) || process.env["NODE_ENV"] === "test";
2279
+ }
2280
+ __name(isDebugMode, "isDebugMode");
2281
+ function cloneDeepOptions(options) {
2282
+ const excludeKeys = [
2283
+ "manifest",
2284
+ "async"
2285
+ ];
2286
+ return (0, import_lodash.default)(options, (value, key) => {
2287
+ if (typeof key === "string" && excludeKeys.includes(key)) {
2288
+ return false;
2289
+ }
2290
+ if (typeof value === "function") {
2291
+ return false;
2292
+ }
2293
+ if (key === "extractThirdParty" && Array.isArray(value)) {
2294
+ return value.map((item) => {
2295
+ return item.toString();
2296
+ });
2297
+ }
2298
+ });
2299
+ }
2300
+ __name(cloneDeepOptions, "cloneDeepOptions");
2301
+ var getEnvHeaders = /* @__PURE__ */ __name(() => {
2302
+ const headersStr = (0, import_sdk6.getProcessEnv)()["MF_ENV_HEADERS"] || "{}";
2303
+ return __spreadValues({}, JSON.parse(headersStr));
2304
+ }, "getEnvHeaders");
2305
+ function axiosGet(url, config) {
2306
+ return __async(this, null, function* () {
2307
+ var _a3, _b;
2308
+ const httpAgent = new import_http2.default.Agent({
2309
+ family: (_a3 = config == null ? void 0 : config.family) != null ? _a3 : 4
2310
+ });
2311
+ const httpsAgent = new import_https.default.Agent({
2312
+ family: (_b = config == null ? void 0 : config.family) != null ? _b : 4
2313
+ });
2314
+ return import_axios.default.get(url, __spreadProps(__spreadValues(__spreadValues({
2315
+ httpAgent,
2316
+ httpsAgent
2317
+ }, {
2318
+ headers: getEnvHeaders()
2319
+ }), config), {
2320
+ timeout: (config == null ? void 0 : config.timeout) || 6e4
2321
+ }));
2322
+ });
2323
+ }
2324
+ __name(axiosGet, "axiosGet");
2325
+
2326
+ // src/core/configurations/remotePlugin.ts
2327
+ var defaultOptions2 = {
2328
+ tsConfigPath: "./tsconfig.json",
2329
+ typesFolder: "@mf-types",
2330
+ compiledTypesFolder: "compiled-types",
2331
+ hostRemoteTypesFolder: "@mf-types",
2332
+ deleteTypesFolder: true,
2333
+ additionalFilesToCompile: [],
2334
+ compilerInstance: "tsc",
2335
+ compileInChildProcess: false,
2336
+ implementation: "",
2337
+ generateAPITypes: false,
2338
+ context: process.cwd(),
2339
+ abortOnError: true,
2340
+ extractRemoteTypes: false,
2341
+ extractThirdParty: false,
2342
+ outputDir: ""
2343
+ };
2344
+ function getEffectiveRootDir(parsedCommandLine) {
2345
+ const compilerOptions = parsedCommandLine.options;
2346
+ if (compilerOptions.rootDir) {
2347
+ return compilerOptions.rootDir;
2348
+ }
2349
+ const files = parsedCommandLine.fileNames;
2350
+ if (files.length > 0) {
2351
+ const commonRoot = files.map((file) => (0, import_path5.dirname)(file)).reduce((commonPath, fileDir) => {
2352
+ while (!fileDir.startsWith(commonPath)) {
2353
+ commonPath = (0, import_path5.dirname)(commonPath);
2354
+ }
2355
+ return commonPath;
2356
+ }, files[0]);
2357
+ return commonRoot;
2358
+ }
2359
+ throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !");
2360
+ }
2361
+ __name(getEffectiveRootDir, "getEffectiveRootDir");
2362
+ var getDependentFiles = /* @__PURE__ */ __name((rootFiles, configContent, rootDir) => {
2363
+ const program = import_typescript.default.createProgram(rootFiles, configContent.options);
2364
+ const sourceFiles = program.getSourceFiles();
2365
+ const dependentFiles = sourceFiles.map((file) => file.fileName).filter((file) => !file.endsWith(".d.ts") && file.startsWith(rootDir));
2366
+ return dependentFiles.length ? dependentFiles : rootFiles;
2367
+ }, "getDependentFiles");
2368
+ var readTsConfig = /* @__PURE__ */ __name(({ tsConfigPath, typesFolder, compiledTypesFolder, context, additionalFilesToCompile, outputDir }, mapComponentsToExpose) => {
2369
+ const resolvedTsConfigPath = (0, import_path5.resolve)(context, tsConfigPath);
2370
+ const readResult = import_typescript.default.readConfigFile(resolvedTsConfigPath, import_typescript.default.sys.readFile);
2371
+ if (readResult.error) {
2372
+ throw new Error(readResult.error.messageText.toString());
2373
+ }
2374
+ const rawTsConfigJson = readResult.config;
2375
+ const configContent = import_typescript.default.parseJsonConfigFileContent(rawTsConfigJson, import_typescript.default.sys, (0, import_path5.dirname)(resolvedTsConfigPath));
2376
+ const rootDir = getEffectiveRootDir(configContent);
2377
+ const outDir = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist", typesFolder, compiledTypesFolder);
2378
+ const defaultCompilerOptions = {
2379
+ rootDir,
2380
+ emitDeclarationOnly: true,
2381
+ noEmit: false,
2382
+ declaration: true,
2383
+ outDir
2384
+ };
2385
+ rawTsConfigJson.compilerOptions = rawTsConfigJson.compilerOptions || {};
2386
+ rawTsConfigJson.compilerOptions = __spreadValues(__spreadValues({
2387
+ incremental: true,
2388
+ tsBuildInfoFile: (0, import_path5.resolve)(context, "node_modules/.cache/mf-types/.tsbuildinfo")
2389
+ }, rawTsConfigJson.compilerOptions), defaultCompilerOptions);
2390
+ const _a3 = rawTsConfigJson.compilerOptions || {}, { paths, baseUrl } = _a3, restCompilerOptions = __objRest(_a3, ["paths", "baseUrl"]);
2391
+ rawTsConfigJson.compilerOptions = restCompilerOptions;
2392
+ const outDirWithoutTypesFolder = (0, import_path5.resolve)(context, outputDir || configContent.options.outDir || "dist");
2393
+ const excludeExtensions = [
2394
+ ".mdx",
2395
+ ".md"
2396
+ ];
2397
+ const rootFiles = [
2398
+ ...Object.values(mapComponentsToExpose),
2399
+ ...additionalFilesToCompile
2400
+ ].filter((filename) => !excludeExtensions.some((ext) => filename.endsWith(ext)));
2401
+ const filesToCompile = [
2402
+ ...getDependentFiles(rootFiles, configContent, rootDir),
2403
+ ...configContent.fileNames.filter((filename) => filename.endsWith(".d.ts") && !filename.startsWith(outDirWithoutTypesFolder))
2404
+ ];
2405
+ rawTsConfigJson.include = [];
2406
+ rawTsConfigJson.files = [
2407
+ ...new Set(filesToCompile)
2408
+ ];
2409
+ rawTsConfigJson.exclude = [];
2410
+ "references" in rawTsConfigJson && delete rawTsConfigJson.references;
2411
+ rawTsConfigJson.extends = resolvedTsConfigPath;
2412
+ return rawTsConfigJson;
2413
+ }, "readTsConfig");
2414
+ var TS_EXTENSIONS = [
2415
+ "ts",
2416
+ "tsx",
2417
+ "vue",
2418
+ "svelte"
2419
+ ];
2420
+ var resolveWithExtension = /* @__PURE__ */ __name((exposedPath, context) => {
2421
+ if ((0, import_path5.extname)(exposedPath)) {
2422
+ return (0, import_path5.resolve)(context, exposedPath);
2423
+ }
2424
+ for (const extension of TS_EXTENSIONS) {
2425
+ const exposedPathWithExtension = (0, import_path5.resolve)(context, `${exposedPath}.${extension}`);
2426
+ if ((0, import_fs2.existsSync)(exposedPathWithExtension)) {
2427
+ return exposedPathWithExtension;
2428
+ }
2429
+ }
2430
+ return void 0;
2431
+ }, "resolveWithExtension");
2432
+ var resolveExposes = /* @__PURE__ */ __name((remoteOptions) => {
2433
+ const parsedOptions = import_managers2.utils.parseOptions(remoteOptions.moduleFederationConfig.exposes || {}, (item, key) => ({
2434
+ exposePath: Array.isArray(item) ? item[0] : item,
2435
+ key
2436
+ }), (item, key) => ({
2437
+ exposePath: Array.isArray(item.import) ? item.import[0] : item.import[0],
2438
+ key
2439
+ }));
2440
+ return parsedOptions.reduce((accumulator, item) => {
2441
+ const { exposePath, key } = item[1];
2442
+ accumulator[key] = resolveWithExtension(exposePath, remoteOptions.context) || resolveWithExtension((0, import_path5.join)(exposePath, "index"), remoteOptions.context) || exposePath;
2443
+ return accumulator;
2444
+ }, {});
2445
+ }, "resolveExposes");
2446
+ var retrieveRemoteConfig = /* @__PURE__ */ __name((options) => {
2447
+ validateOptions(options);
2448
+ const remoteOptions = __spreadValues(__spreadValues({}, defaultOptions2), options);
2449
+ const mapComponentsToExpose = resolveExposes(remoteOptions);
2450
+ const tsConfig = readTsConfig(remoteOptions, mapComponentsToExpose);
2451
+ if (tsConfig.compilerOptions.incremental && tsConfig.compilerOptions.tsBuildInfoFile && options.deleteTypesFolder !== true) {
2452
+ remoteOptions.deleteTypesFolder = false;
2453
+ }
2454
+ return {
2455
+ tsConfig,
2456
+ mapComponentsToExpose,
2457
+ remoteOptions
2458
+ };
2459
+ }, "retrieveRemoteConfig");
2460
+
2461
+ // src/core/rpc/index.ts
2462
+ var rpc_exports = {};
2463
+ __export(rpc_exports, {
2464
+ RpcExitError: () => RpcExitError,
2465
+ RpcGMCallTypes: () => RpcGMCallTypes,
2466
+ createRpcWorker: () => createRpcWorker,
2467
+ exposeRpc: () => exposeRpc,
2468
+ getRpcWorkerData: () => getRpcWorkerData,
2469
+ wrapRpc: () => wrapRpc
2470
+ });
2471
+
2472
+ // src/core/rpc/expose-rpc.ts
2473
+ var import_process = __toESM(require("process"));
2474
+
2475
+ // src/core/rpc/types.ts
2476
+ var RpcGMCallTypes;
2477
+ (function(RpcGMCallTypes2) {
2478
+ RpcGMCallTypes2["CALL"] = "mf_call";
2479
+ RpcGMCallTypes2["RESOLVE"] = "mf_resolve";
2480
+ RpcGMCallTypes2["REJECT"] = "mf_reject";
2481
+ RpcGMCallTypes2["EXIT"] = "mf_exit";
2482
+ })(RpcGMCallTypes || (RpcGMCallTypes = {}));
2483
+
2484
+ // src/core/rpc/expose-rpc.ts
2485
+ function exposeRpc(fn) {
2486
+ const sendMessage = /* @__PURE__ */ __name((message) => new Promise((resolve4, reject) => {
2487
+ if (!import_process.default.send) {
2488
+ reject(new Error(`Process ${import_process.default.pid} doesn't have IPC channels`));
2489
+ } else if (!import_process.default.connected) {
2490
+ reject(new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`));
2491
+ } else {
2492
+ import_process.default.send(message, void 0, void 0, (error2) => {
2493
+ if (error2) {
2494
+ reject(error2);
2495
+ } else {
2496
+ resolve4(void 0);
2497
+ }
2498
+ });
2499
+ }
2500
+ }), "sendMessage");
2501
+ const handleMessage = /* @__PURE__ */ __name((message) => __async(this, null, function* () {
2502
+ if (message.type === RpcGMCallTypes.CALL) {
2503
+ if (!import_process.default.send) {
2504
+ return;
2505
+ }
2506
+ let value, error2;
2507
+ try {
2508
+ value = yield fn(...message.args);
2509
+ } catch (fnError) {
2510
+ error2 = fnError;
2511
+ }
2512
+ try {
2513
+ if (error2) {
2514
+ yield sendMessage({
2515
+ type: RpcGMCallTypes.REJECT,
2516
+ id: message.id,
2517
+ error: error2
2518
+ });
2519
+ } else {
2520
+ yield sendMessage({
2521
+ type: RpcGMCallTypes.RESOLVE,
2522
+ id: message.id,
2523
+ value
2524
+ });
2525
+ }
2526
+ } catch (sendError) {
2527
+ if (error2) {
2528
+ if (error2 instanceof Error) {
2529
+ console.error(error2);
2530
+ }
2531
+ }
2532
+ console.error(sendError);
2533
+ }
2534
+ }
2535
+ }), "handleMessage");
2536
+ import_process.default.on("message", handleMessage);
2537
+ }
2538
+ __name(exposeRpc, "exposeRpc");
2539
+
2540
+ // src/core/rpc/rpc-error.ts
2541
+ var _a2;
2542
+ var RpcExitError = (_a2 = class extends Error {
2543
+ constructor(message, code, signal) {
2544
+ super(message);
2545
+ __publicField(this, "code");
2546
+ __publicField(this, "signal");
2547
+ this.code = code, this.signal = signal;
2548
+ this.name = "RpcExitError";
2549
+ }
2550
+ }, __name(_a2, "RpcExitError"), _a2);
2551
+
2552
+ // src/core/rpc/wrap-rpc.ts
2553
+ function createControlledPromise() {
2554
+ let resolve4 = /* @__PURE__ */ __name(() => void 0, "resolve");
2555
+ let reject = /* @__PURE__ */ __name(() => void 0, "reject");
2556
+ const promise = new Promise((aResolve, aReject) => {
2557
+ resolve4 = aResolve;
2558
+ reject = aReject;
2559
+ });
2560
+ return {
2561
+ promise,
2562
+ resolve: resolve4,
2563
+ reject
2564
+ };
2565
+ }
2566
+ __name(createControlledPromise, "createControlledPromise");
2567
+ function wrapRpc(childProcess, options) {
2568
+ return (...args) => __async(this, null, function* () {
2569
+ if (!childProcess.send) {
2570
+ throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);
2571
+ } else if (!childProcess.connected) {
2572
+ throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);
2573
+ }
2574
+ const { id, once } = options;
2575
+ const { promise: resultPromise, resolve: resolveResult, reject: rejectResult } = createControlledPromise();
2576
+ const { promise: sendPromise, resolve: resolveSend, reject: rejectSend } = createControlledPromise();
2577
+ const handleMessage = /* @__PURE__ */ __name((message) => {
2578
+ if ((message == null ? void 0 : message.id) === id) {
2579
+ if (message.type === RpcGMCallTypes.RESOLVE) {
2580
+ resolveResult(message.value);
2581
+ } else if (message.type === RpcGMCallTypes.REJECT) {
2582
+ rejectResult(message.error);
2583
+ }
2584
+ }
2585
+ if (once && (childProcess == null ? void 0 : childProcess.kill)) {
2586
+ childProcess.kill("SIGTERM");
2587
+ }
2588
+ }, "handleMessage");
2589
+ const handleClose = /* @__PURE__ */ __name((code, signal) => {
2590
+ rejectResult(new RpcExitError(code ? `Process ${childProcess.pid} exited with code ${code}${signal ? ` [${signal}]` : ""}` : `Process ${childProcess.pid} exited${signal ? ` [${signal}]` : ""}`, code, signal));
2591
+ removeHandlers();
2592
+ }, "handleClose");
2593
+ const removeHandlers = /* @__PURE__ */ __name(() => {
2594
+ childProcess.off("message", handleMessage);
2595
+ childProcess.off("close", handleClose);
2596
+ }, "removeHandlers");
2597
+ if (once) {
2598
+ childProcess.once("message", handleMessage);
2599
+ } else {
2600
+ childProcess.on("message", handleMessage);
2601
+ }
2602
+ childProcess.on("close", handleClose);
2603
+ childProcess.send({
2604
+ type: RpcGMCallTypes.CALL,
2605
+ id,
2606
+ args
2607
+ }, (error2) => {
2608
+ if (error2) {
2609
+ rejectSend(error2);
2610
+ removeHandlers();
2611
+ } else {
2612
+ resolveSend(void 0);
2613
+ }
2614
+ });
2615
+ return sendPromise.then(() => resultPromise);
2616
+ });
2617
+ }
2618
+ __name(wrapRpc, "wrapRpc");
2619
+
2620
+ // src/core/rpc/rpc-worker.ts
2621
+ var child_process = __toESM(require("child_process"));
2622
+ var process3 = __toESM(require("process"));
2623
+ var import_crypto2 = require("crypto");
2624
+ var FEDERATION_WORKER_DATA_ENV_KEY = "VMOK_WORKER_DATA_ENV";
2625
+ function createRpcWorker(modulePath, data, memoryLimit, once) {
2626
+ const options = {
2627
+ env: __spreadProps(__spreadValues({}, process3.env), {
2628
+ [FEDERATION_WORKER_DATA_ENV_KEY]: JSON.stringify(data || {})
2629
+ }),
2630
+ stdio: [
2631
+ "inherit",
2632
+ "inherit",
2633
+ "inherit",
2634
+ "ipc"
2635
+ ],
2636
+ serialization: "advanced"
2637
+ };
2638
+ if (memoryLimit) {
2639
+ options.execArgv = [
2640
+ `--max-old-space-size=${memoryLimit}`
2641
+ ];
2642
+ }
2643
+ let childProcess, remoteMethod;
2644
+ const id = (0, import_crypto2.randomUUID)();
2645
+ const worker = {
2646
+ connect(...args) {
2647
+ if (childProcess && !childProcess.connected) {
2648
+ childProcess.send({
2649
+ type: RpcGMCallTypes.EXIT,
2650
+ id
2651
+ });
2652
+ childProcess = void 0;
2653
+ remoteMethod = void 0;
2654
+ }
2655
+ if (!(childProcess == null ? void 0 : childProcess.connected)) {
2656
+ childProcess = child_process.fork(modulePath, options);
2657
+ remoteMethod = wrapRpc(childProcess, {
2658
+ id,
2659
+ once
2660
+ });
2661
+ }
2662
+ if (!remoteMethod) {
2663
+ return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));
2664
+ }
2665
+ return remoteMethod(...args);
2666
+ },
2667
+ terminate() {
2668
+ try {
2669
+ if (childProcess.connected) {
2670
+ childProcess.send({
2671
+ type: RpcGMCallTypes.EXIT,
2672
+ id
2673
+ }, (err) => {
2674
+ if (err) {
2675
+ console.error("Error sending message:", err);
2676
+ }
2677
+ });
2678
+ }
2679
+ } catch (error2) {
2680
+ if (error2.code === "EPIPE") {
2681
+ console.error("Pipe closed before message could be sent:", error2);
2682
+ } else {
2683
+ console.error("Unexpected error:", error2);
2684
+ }
2685
+ }
2686
+ childProcess = void 0;
2687
+ remoteMethod = void 0;
2688
+ },
2689
+ get connected() {
2690
+ return Boolean(childProcess == null ? void 0 : childProcess.connected);
2691
+ },
2692
+ get process() {
2693
+ return childProcess;
2694
+ },
2695
+ get id() {
2696
+ return id;
2697
+ }
2698
+ };
2699
+ return worker;
2700
+ }
2701
+ __name(createRpcWorker, "createRpcWorker");
2702
+ function getRpcWorkerData() {
2703
+ return JSON.parse(process3.env[FEDERATION_WORKER_DATA_ENV_KEY] || "{}");
2704
+ }
2705
+ __name(getRpcWorkerData, "getRpcWorkerData");
2706
+
2707
+ // src/dev-worker/forkDevWorker.ts
2708
+ var import_sdk7 = require("@module-federation/sdk");
2709
+
2710
+ // src/dev-worker/utils.ts
2711
+ var DEFAULT_LOCAL_IPS = [
2712
+ "localhost",
2713
+ "127.0.0.1"
2714
+ ];
2715
+ function getIpFromEntry(entry, ipv4) {
2716
+ let ip;
2717
+ entry.replace(/https?:\/\/([0-9|.]+|localhost):/, (str, matched) => {
2718
+ ip = matched;
2719
+ return str;
2720
+ });
2721
+ if (ip) {
2722
+ return DEFAULT_LOCAL_IPS.includes(ip) ? ipv4 : ip;
2723
+ }
2724
+ }
2725
+ __name(getIpFromEntry, "getIpFromEntry");
2726
+
2727
+ // src/dev-worker/forkDevWorker.ts
2728
+ var typesManager;
2729
+ var serverAddress;
2730
+ var moduleServer;
2731
+ var cacheOptions;
2732
+ function getLocalRemoteNames(options, encodeNameIdentifier) {
2733
+ if (!options) {
2734
+ return [];
2735
+ }
2736
+ const { mapRemotesToDownload } = retrieveHostConfig(options);
2737
+ return Object.keys(mapRemotesToDownload).reduce((sum, remoteModuleName) => {
2738
+ const remoteInfo = mapRemotesToDownload[remoteModuleName];
2739
+ const name = encodeNameIdentifier ? (0, import_sdk7.decodeName)(remoteInfo.name, encodeNameIdentifier) : remoteInfo.name;
2740
+ const ip = getIpFromEntry(remoteInfo.url, getIPV4());
2741
+ if (!ip) {
2742
+ return sum;
2743
+ }
2744
+ sum.push({
2745
+ name,
2746
+ entry: remoteInfo.url,
2747
+ ip
2748
+ });
2749
+ return sum;
2750
+ }, []);
2751
+ }
2752
+ __name(getLocalRemoteNames, "getLocalRemoteNames");
2753
+ function updateCallback(_0) {
2754
+ return __async(this, arguments, function* ({ updateMode, name, remoteTypeTarPath, remoteInfo, once }) {
2755
+ const { disableHotTypesReload, disableLiveReload } = cacheOptions || {};
2756
+ fileLog(`sync remote module ${name}, types to ${cacheOptions == null ? void 0 : cacheOptions.name},typesManager.updateTypes run`, "forkDevWorker", "info");
2757
+ if (!disableLiveReload && moduleServer) {
2758
+ moduleServer.update({
2759
+ updateKind: UpdateKind.RELOAD_PAGE,
2760
+ updateMode: UpdateMode.PASSIVE
2761
+ });
2762
+ }
2763
+ if (!disableHotTypesReload && typesManager) {
2764
+ yield typesManager.updateTypes({
2765
+ updateMode,
2766
+ remoteName: name,
2767
+ remoteTarPath: remoteTypeTarPath,
2768
+ remoteInfo,
2769
+ once
2770
+ });
2771
+ }
2772
+ });
2773
+ }
2774
+ __name(updateCallback, "updateCallback");
2775
+ function forkDevWorker(options, action) {
2776
+ return __async(this, null, function* () {
2777
+ if (!typesManager) {
2778
+ const { name, remote, host, extraOptions } = options;
2779
+ const DTSManagerConstructor = getDTSManagerConstructor(remote == null ? void 0 : remote.implementation);
2780
+ typesManager = new DTSManagerConstructor({
2781
+ remote,
2782
+ host,
2783
+ extraOptions
2784
+ });
2785
+ if (!options.disableHotTypesReload && remote) {
2786
+ const { remoteOptions, tsConfig } = retrieveRemoteConfig(remote);
2787
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
2788
+ const mfTypesZipPath = retrieveTypesZipPath(mfTypesPath, remoteOptions);
2789
+ yield Promise.all([
2790
+ createKoaServer({
2791
+ typeTarPath: mfTypesZipPath
2792
+ }).then((res) => {
2793
+ serverAddress = res.serverAddress;
2794
+ }),
2795
+ typesManager.generateTypes()
2796
+ ]).catch((err) => {
2797
+ fileLog(`${name} module generateTypes done, localServerAddress: ${JSON.stringify(err)}`, "forkDevWorker", "error");
2798
+ });
2799
+ fileLog(`${name} module generateTypes done, localServerAddress: ${serverAddress}`, "forkDevWorker", "info");
2800
+ }
2801
+ moduleServer = new ModuleFederationDevServer({
2802
+ name,
2803
+ remotes: getLocalRemoteNames(host, extraOptions == null ? void 0 : extraOptions["encodeNameIdentifier"]),
2804
+ updateCallback,
2805
+ remoteTypeTarPath: `${serverAddress}/${DEFAULT_TAR_NAME}`
2806
+ });
2807
+ cacheOptions = options;
2808
+ }
2809
+ if (action === "update" && cacheOptions) {
2810
+ fileLog(`remoteModule ${cacheOptions.name} receive devWorker update, start typesManager.updateTypes `, "forkDevWorker", "info");
2811
+ if (!cacheOptions.disableLiveReload) {
2812
+ moduleServer == null ? void 0 : moduleServer.update({
2813
+ updateKind: UpdateKind.RELOAD_PAGE,
2814
+ updateMode: UpdateMode.POSITIVE
2815
+ });
2816
+ }
2817
+ if (!cacheOptions.disableHotTypesReload) {
2818
+ typesManager == null ? void 0 : typesManager.updateTypes({
2819
+ updateMode: UpdateMode.POSITIVE,
2820
+ remoteName: cacheOptions.name
2821
+ }).then(() => {
2822
+ moduleServer == null ? void 0 : moduleServer.update({
2823
+ updateKind: UpdateKind.UPDATE_TYPE,
2824
+ updateMode: UpdateMode.POSITIVE
2825
+ });
2826
+ });
2827
+ }
2828
+ }
2829
+ });
2830
+ }
2831
+ __name(forkDevWorker, "forkDevWorker");
2832
+ process.on("message", (message) => {
2833
+ fileLog(`ChildProcess(${process.pid}), message: ${JSON.stringify(message)} `, "forkDevWorker", "info");
2834
+ if (message.type === rpc_exports.RpcGMCallTypes.EXIT) {
2835
+ fileLog(`ChildProcess(${process.pid}) SIGTERM, Federation DevServer will exit...`, "forkDevWorker", "error");
2836
+ moduleServer.exit();
2837
+ process.exit(0);
2838
+ }
2839
+ });
2840
+ rpc_exports.exposeRpc(forkDevWorker);
2841
+ // Annotate the CommonJS export names for ESM import in node:
2842
+ 0 && (module.exports = {
2843
+ forkDevWorker
2844
+ });