@module-federation/dts-plugin 0.1.3 → 0.1.5

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