@module-federation/dts-plugin 2.0.1 → 2.1.0

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