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