@module-federation/dts-plugin 0.1.4 → 0.1.6

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.
@@ -45,9 +45,9 @@ function exposeRpc(fn) {
45
45
  new Error(`Process ${import_process.default.pid} doesn't have open IPC channels`)
46
46
  );
47
47
  } else {
48
- import_process.default.send(message, void 0, void 0, (error) => {
49
- if (error) {
50
- reject(error);
48
+ import_process.default.send(message, void 0, void 0, (error2) => {
49
+ if (error2) {
50
+ reject(error2);
51
51
  } else {
52
52
  resolve4(void 0);
53
53
  }
@@ -59,18 +59,18 @@ function exposeRpc(fn) {
59
59
  if (!import_process.default.send) {
60
60
  return;
61
61
  }
62
- let value, error;
62
+ let value, error2;
63
63
  try {
64
64
  value = await fn(...message.args);
65
65
  } catch (fnError) {
66
- error = fnError;
66
+ error2 = fnError;
67
67
  }
68
68
  try {
69
- if (error) {
69
+ if (error2) {
70
70
  await sendMessage({
71
71
  type: "mf_reject" /* REJECT */,
72
72
  id: message.id,
73
- error
73
+ error: error2
74
74
  });
75
75
  } else {
76
76
  await sendMessage({
@@ -80,9 +80,9 @@ function exposeRpc(fn) {
80
80
  });
81
81
  }
82
82
  } catch (sendError) {
83
- if (error) {
84
- if (error instanceof Error) {
85
- console.error(error);
83
+ if (error2) {
84
+ if (error2 instanceof Error) {
85
+ console.error(error2);
86
86
  }
87
87
  }
88
88
  console.error(sendError);
@@ -202,16 +202,15 @@ var retrieveRemoteConfig = (options) => {
202
202
  };
203
203
 
204
204
  // packages/dts-plugin/src/core/lib/DTSManager.ts
205
- var import_ansi_colors3 = __toESM(require("ansi-colors"));
205
+ var import_ansi_colors2 = __toESM(require("ansi-colors"));
206
206
  var import_path4 = __toESM(require("path"));
207
207
  var import_promises = require("fs/promises");
208
208
  var import_fs2 = __toESM(require("fs"));
209
- var import_sdk2 = require("@module-federation/sdk");
210
- var import_lodash = __toESM(require("lodash.clonedeepwith"));
209
+ var import_sdk4 = require("@module-federation/sdk");
210
+ var import_lodash2 = __toESM(require("lodash.clonedeepwith"));
211
211
 
212
212
  // packages/dts-plugin/src/core/lib/archiveHandler.ts
213
213
  var import_adm_zip = __toESM(require("adm-zip"));
214
- var import_ansi_colors2 = __toESM(require("ansi-colors"));
215
214
  var import_axios = __toESM(require("axios"));
216
215
  var import_path3 = require("path");
217
216
 
@@ -323,65 +322,217 @@ var compileTs = (mapComponentsToExpose, tsConfig, remoteOptions) => {
323
322
  }
324
323
  };
325
324
 
326
- // packages/dts-plugin/src/core/lib/archiveHandler.ts
327
- var retrieveTypesZipPath = (mfTypesPath, remoteOptions) => (0, import_path3.join)(
328
- mfTypesPath.replace(remoteOptions.typesFolder, ""),
329
- `${remoteOptions.typesFolder}.zip`
330
- );
331
- var createTypesArchive = async (tsConfig, remoteOptions) => {
332
- const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
333
- const zip = new import_adm_zip.default();
334
- zip.addLocalFolder(mfTypesPath);
335
- return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
325
+ // packages/dts-plugin/src/server/message/Message.ts
326
+ var Message = class {
327
+ constructor(type, kind) {
328
+ this.type = type;
329
+ this.kind = kind;
330
+ this.time = Date.now();
331
+ }
336
332
  };
337
- var downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
338
- throw {
339
- ...reason,
340
- message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
341
- };
333
+
334
+ // packages/dts-plugin/src/server/message/API/API.ts
335
+ var API = class extends Message {
336
+ constructor(content, kind) {
337
+ super("API", kind);
338
+ const { code, payload } = content;
339
+ this.code = code;
340
+ this.payload = payload;
341
+ }
342
342
  };
343
- var retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
344
- return (0, import_path3.resolve)(
345
- hostOptions.context,
346
- hostOptions.typesFolder,
347
- destinationFolder
348
- );
343
+
344
+ // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
345
+ var UpdateSubscriberAPI = class extends API {
346
+ constructor(payload) {
347
+ super(
348
+ {
349
+ code: 0,
350
+ payload
351
+ },
352
+ "UPDATE_SUBSCRIBER" /* UPDATE_SUBSCRIBER */
353
+ );
354
+ }
349
355
  };
350
- var downloadTypesArchive = (hostOptions) => {
351
- let retries = 0;
352
- return async ([destinationFolder, fileToDownload]) => {
353
- const destinationPath = retrieveTypesArchiveDestinationPath(
354
- hostOptions,
355
- destinationFolder
356
+
357
+ // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
358
+ var ReloadWebClientAPI = class extends API {
359
+ constructor(payload) {
360
+ super(
361
+ {
362
+ code: 0,
363
+ payload
364
+ },
365
+ "RELOAD_WEB_CLIENT" /* RELOAD_WEB_CLIENT */
356
366
  );
357
- while (retries++ < hostOptions.maxRetries) {
358
- try {
359
- const url = replaceLocalhost(fileToDownload);
360
- const response = await import_axios.default.get(url, { responseType: "arraybuffer" }).catch(downloadErrorLogger(destinationFolder, url));
361
- const zip = new import_adm_zip.default(Buffer.from(response.data));
362
- zip.extractAllTo(destinationPath, true);
363
- return [destinationFolder, destinationPath];
364
- } catch (error) {
365
- if (isDebugMode()) {
366
- console.error(
367
- import_ansi_colors2.default.red(
368
- `Error during types archive download: ${(error == null ? void 0 : error.message) || "unknown error"}`
369
- )
370
- );
371
- }
372
- if (retries >= hostOptions.maxRetries) {
373
- if (hostOptions.abortOnError !== false) {
374
- throw error;
375
- }
376
- return void 0;
377
- }
378
- }
367
+ }
368
+ };
369
+
370
+ // packages/dts-plugin/src/server/utils/index.ts
371
+ var import_sdk2 = require("@module-federation/sdk");
372
+
373
+ // packages/dts-plugin/src/server/utils/logTransform.ts
374
+ var import_chalk = __toESM(require("chalk"));
375
+
376
+ // packages/dts-plugin/src/server/message/Log/Log.ts
377
+ var Log = class extends Message {
378
+ constructor(level, kind, ignoreVerbose = false) {
379
+ super("Log", kind);
380
+ this.ignoreVerbose = false;
381
+ this.level = level;
382
+ this.ignoreVerbose = ignoreVerbose;
383
+ }
384
+ };
385
+
386
+ // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
387
+ var BrokerExitLog = class extends Log {
388
+ constructor() {
389
+ super("LOG" /* LOG */, "BrokerExitLog" /* BrokerExitLog */);
390
+ }
391
+ };
392
+
393
+ // packages/dts-plugin/src/server/utils/log.ts
394
+ var import_sdk = require("@module-federation/sdk");
395
+ var log4js = __toESM(require("log4js"));
396
+ var import_chalk2 = __toESM(require("chalk"));
397
+
398
+ // packages/dts-plugin/src/server/constant.ts
399
+ var DEFAULT_WEB_SOCKET_PORT = 16322;
400
+ var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
401
+
402
+ // packages/dts-plugin/src/server/utils/log.ts
403
+ function fileLog(msg, module2, level) {
404
+ var _a, _b;
405
+ if (!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a["FEDERATION_DEBUG"])) {
406
+ return;
407
+ }
408
+ log4js.configure({
409
+ appenders: {
410
+ [module2]: { type: "file", filename: ".mf/typesGenerate.log" },
411
+ default: { type: "file", filename: ".mf/typesGenerate.log" }
412
+ },
413
+ categories: {
414
+ [module2]: { appenders: [module2], level: "error" },
415
+ default: { appenders: ["default"], level: "trace" }
379
416
  }
380
- };
417
+ });
418
+ const logger4 = log4js.getLogger(module2);
419
+ logger4.level = "debug";
420
+ (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
421
+ }
422
+ function error(error2, action, from) {
423
+ const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
424
+ fileLog(`[${action}] error: ${err}`, from, "fatal");
425
+ return err.toString();
426
+ }
427
+
428
+ // packages/dts-plugin/src/server/utils/index.ts
429
+ function getIdentifier(options) {
430
+ const { ip, name } = options;
431
+ return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
432
+ }
433
+
434
+ // packages/dts-plugin/src/server/Publisher.ts
435
+ var Publisher = class {
436
+ constructor(ctx) {
437
+ this._name = ctx.name;
438
+ this._ip = ctx.ip;
439
+ this._remoteTypeTarPath = ctx.remoteTypeTarPath;
440
+ this._subscribers = /* @__PURE__ */ new Map();
441
+ }
442
+ get identifier() {
443
+ return getIdentifier({
444
+ name: this._name,
445
+ ip: this._ip
446
+ });
447
+ }
448
+ get name() {
449
+ return this._name;
450
+ }
451
+ get ip() {
452
+ return this._ip;
453
+ }
454
+ get remoteTypeTarPath() {
455
+ return this._remoteTypeTarPath;
456
+ }
457
+ get hasSubscribes() {
458
+ return Boolean(this._subscribers.size);
459
+ }
460
+ get subscribers() {
461
+ return this._subscribers;
462
+ }
463
+ addSubscriber(identifier, subscriber) {
464
+ fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
465
+ this._subscribers.set(identifier, subscriber);
466
+ }
467
+ removeSubscriber(identifier) {
468
+ if (this._subscribers.has(identifier)) {
469
+ fileLog(
470
+ `${this.name} removeSubscriber: ${identifier}`,
471
+ "Publisher",
472
+ "warn"
473
+ );
474
+ this._subscribers.delete(identifier);
475
+ }
476
+ }
477
+ notifySubscriber(subscriberIdentifier, options) {
478
+ const subscriber = this._subscribers.get(subscriberIdentifier);
479
+ if (!subscriber) {
480
+ fileLog(
481
+ `[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`,
482
+ "Publisher",
483
+ "error"
484
+ );
485
+ return;
486
+ }
487
+ const api = new UpdateSubscriberAPI(options);
488
+ subscriber.send(JSON.stringify(api));
489
+ fileLog(
490
+ `[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(
491
+ subscriberIdentifier
492
+ )}, message: ${JSON.stringify(api)}`,
493
+ "Publisher",
494
+ "info"
495
+ );
496
+ }
497
+ notifySubscribers(options) {
498
+ const api = new UpdateSubscriberAPI(options);
499
+ this.broadcast(api);
500
+ }
501
+ broadcast(message) {
502
+ if (this.hasSubscribes) {
503
+ this._subscribers.forEach((subscriber, key) => {
504
+ fileLog(
505
+ `[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`,
506
+ "Publisher",
507
+ "info"
508
+ );
509
+ subscriber.send(JSON.stringify(message));
510
+ });
511
+ } else {
512
+ fileLog(
513
+ `[BroadCast] ${this.name}'s subscribe is empty`,
514
+ "Publisher",
515
+ "warn"
516
+ );
517
+ }
518
+ }
519
+ close() {
520
+ this._subscribers.forEach((_subscriber, identifier) => {
521
+ fileLog(
522
+ `[BroadCast] close ${this.name} remove: ${identifier}`,
523
+ "Publisher",
524
+ "warn"
525
+ );
526
+ this.removeSubscriber(identifier);
527
+ });
528
+ }
381
529
  };
382
530
 
531
+ // packages/dts-plugin/src/server/DevServer.ts
532
+ var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
533
+
383
534
  // packages/dts-plugin/src/core/configurations/hostPlugin.ts
384
- var import_sdk = require("@module-federation/sdk");
535
+ var import_sdk3 = require("@module-federation/sdk");
385
536
  var import_managers2 = require("@module-federation/managers");
386
537
  var defaultOptions2 = {
387
538
  typesFolder: "@mf-types",
@@ -395,7 +546,7 @@ var defaultOptions2 = {
395
546
  };
396
547
  var buildZipUrl = (hostOptions, url) => {
397
548
  const remoteUrl = new URL(url);
398
- if (remoteUrl.href.includes(import_sdk.MANIFEST_EXT)) {
549
+ if (remoteUrl.href.includes(import_sdk3.MANIFEST_EXT)) {
399
550
  return void 0;
400
551
  }
401
552
  const pathnameWithoutEntry = remoteUrl.pathname.split("/").slice(0, -1).join("/");
@@ -410,7 +561,7 @@ var buildApiTypeUrl = (zipUrl) => {
410
561
  };
411
562
  var retrieveRemoteInfo = (options) => {
412
563
  const { hostOptions, remoteAlias, remote } = options;
413
- const parsedInfo = (0, import_sdk.parseEntry)(remote, void 0, "@");
564
+ const parsedInfo = (0, import_sdk3.parseEntry)(remote, void 0, "@");
414
565
  const url = "entry" in parsedInfo ? parsedInfo.entry : parsedInfo.name === remote ? remote : "";
415
566
  const zipUrl = url ? buildZipUrl(hostOptions, url) : "";
416
567
  return {
@@ -456,22 +607,653 @@ var retrieveHostConfig = (options) => {
456
607
  };
457
608
  };
458
609
 
610
+ // packages/dts-plugin/src/core/lib/DtsWorker.ts
611
+ var import_lodash = __toESM(require("lodash.clonedeepwith"));
612
+
459
613
  // packages/dts-plugin/src/core/constant.ts
460
614
  var REMOTE_ALIAS_IDENTIFIER = "REMOTE_ALIAS_IDENTIFIER";
461
615
  var REMOTE_API_TYPES_FILE_NAME = "apis.d.ts";
462
616
  var HOST_API_TYPES_FILE_NAME = "index.d.ts";
463
617
 
618
+ // packages/dts-plugin/src/server/broker/Broker.ts
619
+ var import_http = require("http");
620
+ var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
621
+ var import_node_schedule = __toESM(require("node-schedule"));
622
+ var import_url = require("url");
623
+ var _Broker = class _Broker {
624
+ constructor() {
625
+ // 1.5h
626
+ this._publisherMap = /* @__PURE__ */ new Map();
627
+ this._webClientMap = /* @__PURE__ */ new Map();
628
+ this._tmpSubscriberShelter = /* @__PURE__ */ new Map();
629
+ this._scheduleJob = null;
630
+ this._setSchedule();
631
+ this._startWsServer();
632
+ this._stopWhenSIGTERMOrSIGINT();
633
+ this._handleUnexpectedExit();
634
+ }
635
+ get hasPublishers() {
636
+ return Boolean(this._publisherMap.size);
637
+ }
638
+ async _startWsServer() {
639
+ const wsHandler = (ws, req) => {
640
+ const { url: reqUrl = "" } = req;
641
+ const { query } = (0, import_url.parse)(reqUrl, true);
642
+ const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
643
+ if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
644
+ ws.on("message", (message) => {
645
+ try {
646
+ const text = message.toString();
647
+ const action = JSON.parse(text);
648
+ fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
649
+ this._takeAction(action, ws);
650
+ } catch (error2) {
651
+ fileLog(`parse action message error: ${error2}`, "Broker", "error");
652
+ }
653
+ });
654
+ ws.on("error", (e) => {
655
+ fileLog(`parse action message error: ${e}`, "Broker", "error");
656
+ });
657
+ } else {
658
+ ws.send("Invalid CONNECT ID.");
659
+ fileLog("Invalid CONNECT ID.", "Broker", "warn");
660
+ ws.close();
661
+ }
662
+ };
663
+ const server = (0, import_http.createServer)();
664
+ this._webSocketServer = new import_isomorphic_ws.default.Server({ noServer: true });
665
+ this._webSocketServer.on("error", (err) => {
666
+ fileLog(`ws error:
667
+ ${err.message}
668
+ ${err.stack}`, "Broker", "error");
669
+ });
670
+ this._webSocketServer.on("listening", () => {
671
+ fileLog(
672
+ `WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`,
673
+ "Broker",
674
+ "info"
675
+ );
676
+ });
677
+ this._webSocketServer.on("connection", wsHandler);
678
+ this._webSocketServer.on("close", (code) => {
679
+ fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
680
+ this._webSocketServer && this._webSocketServer.close();
681
+ this._webSocketServer = void 0;
682
+ });
683
+ server.on("upgrade", (req, socket, head) => {
684
+ var _a;
685
+ if (req.url) {
686
+ const { pathname } = (0, import_url.parse)(req.url);
687
+ if (pathname === "/") {
688
+ (_a = this._webSocketServer) == null ? void 0 : _a.handleUpgrade(req, socket, head, (ws) => {
689
+ var _a2;
690
+ (_a2 = this._webSocketServer) == null ? void 0 : _a2.emit("connection", ws, req);
691
+ });
692
+ }
693
+ }
694
+ });
695
+ server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
696
+ }
697
+ async _takeAction(action, client) {
698
+ const { kind, payload } = action;
699
+ if (kind === "ADD_PUBLISHER" /* ADD_PUBLISHER */) {
700
+ await this._addPublisher(payload, client);
701
+ }
702
+ if (kind === "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */) {
703
+ await this._updatePublisher(
704
+ payload,
705
+ client
706
+ );
707
+ }
708
+ if (kind === "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */) {
709
+ await this._addSubscriber(payload, client);
710
+ }
711
+ if (kind === "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */) {
712
+ await this._removeSubscriber(
713
+ payload,
714
+ client
715
+ );
716
+ }
717
+ if (kind === "EXIT_PUBLISHER" /* EXIT_PUBLISHER */) {
718
+ await this._removePublisher(payload, client);
719
+ }
720
+ if (kind === "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */) {
721
+ await this._addWebClient(payload, client);
722
+ }
723
+ if (kind === "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */) {
724
+ await this._notifyWebClient(
725
+ payload,
726
+ client
727
+ );
728
+ }
729
+ }
730
+ async _addPublisher(context, client) {
731
+ const { name, ip, remoteTypeTarPath } = context ?? {};
732
+ const identifier = getIdentifier({ name, ip });
733
+ if (this._publisherMap.has(identifier)) {
734
+ fileLog(
735
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} has been added, this action will be ignored`,
736
+ "Broker",
737
+ "warn"
738
+ );
739
+ return;
740
+ }
741
+ try {
742
+ const publisher = new Publisher({ name, ip, remoteTypeTarPath });
743
+ this._publisherMap.set(identifier, publisher);
744
+ fileLog(
745
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} Adding Publisher Succeed`,
746
+ "Broker",
747
+ "info"
748
+ );
749
+ const tmpSubScribers = this._getTmpSubScribers(identifier);
750
+ if (tmpSubScribers) {
751
+ fileLog(
752
+ `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `,
753
+ "Broker",
754
+ "info"
755
+ );
756
+ this._consumeTmpSubScribers(publisher, tmpSubScribers);
757
+ this._clearTmpSubScriberRelation(identifier);
758
+ }
759
+ } catch (err) {
760
+ const msg = error(err, "ADD_PUBLISHER" /* ADD_PUBLISHER */, "Broker");
761
+ client.send(msg);
762
+ client.close();
763
+ }
764
+ }
765
+ async _updatePublisher(context, client) {
766
+ const {
767
+ name,
768
+ updateMode,
769
+ updateKind,
770
+ updateSourcePaths,
771
+ remoteTypeTarPath,
772
+ ip
773
+ } = context ?? {};
774
+ const identifier = getIdentifier({ name, ip });
775
+ if (!this._publisherMap.has(identifier)) {
776
+ fileLog(
777
+ `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} has not been started, this action will be ignored
778
+ this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
779
+ `,
780
+ "Broker",
781
+ "warn"
782
+ );
783
+ return;
784
+ }
785
+ try {
786
+ const publisher = this._publisherMap.get(identifier);
787
+ fileLog(
788
+ // eslint-disable-next-line max-len
789
+ `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} update, and notify subscribers to update`,
790
+ "Broker",
791
+ "info"
792
+ );
793
+ if (publisher) {
794
+ publisher.notifySubscribers({
795
+ remoteTypeTarPath,
796
+ name,
797
+ updateMode,
798
+ updateKind,
799
+ updateSourcePaths: updateSourcePaths || []
800
+ });
801
+ }
802
+ } catch (err) {
803
+ const msg = error(err, "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */, "Broker");
804
+ client.send(msg);
805
+ client.close();
806
+ }
807
+ }
808
+ // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
809
+ // provider1 is app1's remote
810
+ async _addSubscriber(context, client) {
811
+ const { publishers, name: subscriberName } = context ?? {};
812
+ publishers.forEach((publisher) => {
813
+ const { name, ip } = publisher;
814
+ const identifier = getIdentifier({ name, ip });
815
+ if (!this._publisherMap.has(identifier)) {
816
+ fileLog(
817
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`,
818
+ "Broker",
819
+ "warn"
820
+ );
821
+ this._addTmpSubScriberRelation(
822
+ {
823
+ name: getIdentifier({
824
+ name: context.name,
825
+ ip: context.ip
826
+ }),
827
+ client
828
+ },
829
+ publisher
830
+ );
831
+ return;
832
+ }
833
+ try {
834
+ const registeredPublisher = this._publisherMap.get(identifier);
835
+ if (registeredPublisher) {
836
+ registeredPublisher.addSubscriber(
837
+ getIdentifier({
838
+ name: subscriberName,
839
+ ip: context.ip
840
+ }),
841
+ client
842
+ );
843
+ fileLog(
844
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
845
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(
846
+ Array.from(this._publisherMap.entries())
847
+ )}`,
848
+ "Broker",
849
+ "info"
850
+ );
851
+ registeredPublisher.notifySubscriber(
852
+ getIdentifier({
853
+ name: subscriberName,
854
+ ip: context.ip
855
+ }),
856
+ {
857
+ updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
858
+ updateMode: "PASSIVE" /* PASSIVE */,
859
+ updateSourcePaths: [registeredPublisher.name],
860
+ remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
861
+ name: registeredPublisher.name
862
+ }
863
+ );
864
+ fileLog(
865
+ // eslint-disable-next-line @ies/eden/max-calls-in-template
866
+ `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
867
+ "Broker",
868
+ "info"
869
+ );
870
+ }
871
+ } catch (err) {
872
+ const msg = error(err, "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */, "Broker");
873
+ client.send(msg);
874
+ client.close();
875
+ }
876
+ });
877
+ }
878
+ // Trigger while consumer exit
879
+ async _removeSubscriber(context, client) {
880
+ const { publishers } = context ?? {};
881
+ const subscriberIdentifier = getIdentifier({
882
+ name: context == null ? void 0 : context.name,
883
+ ip: context == null ? void 0 : context.ip
884
+ });
885
+ publishers.forEach((publisher) => {
886
+ const { name, ip } = publisher;
887
+ const identifier = getIdentifier({
888
+ name,
889
+ ip
890
+ });
891
+ const registeredPublisher = this._publisherMap.get(identifier);
892
+ if (!registeredPublisher) {
893
+ fileLog(
894
+ `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} does not exit `,
895
+ "Broker",
896
+ "warn"
897
+ );
898
+ return;
899
+ }
900
+ try {
901
+ fileLog(
902
+ `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} will exit `,
903
+ "Broker",
904
+ "INFO"
905
+ );
906
+ registeredPublisher.removeSubscriber(subscriberIdentifier);
907
+ this._clearTmpSubScriberRelation(identifier);
908
+ if (!registeredPublisher.hasSubscribes) {
909
+ this._publisherMap.delete(identifier);
910
+ }
911
+ if (!this.hasPublishers) {
912
+ this.exit();
913
+ }
914
+ } catch (err) {
915
+ const msg = error(err, "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */, "Broker");
916
+ client.send(msg);
917
+ client.close();
918
+ }
919
+ });
920
+ }
921
+ async _removePublisher(context, client) {
922
+ const { name, ip } = context ?? {};
923
+ const identifier = getIdentifier({
924
+ name,
925
+ ip
926
+ });
927
+ const publisher = this._publisherMap.get(identifier);
928
+ if (!publisher) {
929
+ fileLog(
930
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier}} has not been added, this action will be ingored`,
931
+ "Broker",
932
+ "warn"
933
+ );
934
+ return;
935
+ }
936
+ try {
937
+ const { subscribers } = publisher;
938
+ subscribers.forEach((subscriber, subscriberIdentifier) => {
939
+ this._addTmpSubScriberRelation(
940
+ {
941
+ name: subscriberIdentifier,
942
+ client: subscriber
943
+ },
944
+ { name: publisher.name, ip: publisher.ip }
945
+ );
946
+ fileLog(
947
+ // eslint-disable-next-line max-len
948
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
949
+ "Broker",
950
+ "info"
951
+ );
952
+ });
953
+ this._publisherMap.delete(identifier);
954
+ fileLog(
955
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removed `,
956
+ "Broker",
957
+ "info"
958
+ );
959
+ if (!this.hasPublishers) {
960
+ fileLog(
961
+ `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: _publisherMap is empty, all server will exit `,
962
+ "Broker",
963
+ "warn"
964
+ );
965
+ this.exit();
966
+ }
967
+ } catch (err) {
968
+ const msg = error(err, "EXIT_PUBLISHER" /* EXIT_PUBLISHER */, "Broker");
969
+ client.send(msg);
970
+ client.close();
971
+ }
972
+ }
973
+ async _addWebClient(context, client) {
974
+ const { name } = context ?? {};
975
+ const identifier = getIdentifier({
976
+ name
977
+ });
978
+ if (this._webClientMap.has(identifier)) {
979
+ fileLog(
980
+ `${identifier}} has been added, this action will override prev WebClient`,
981
+ "Broker",
982
+ "warn"
983
+ );
984
+ }
985
+ try {
986
+ this._webClientMap.set(identifier, client);
987
+ fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
988
+ } catch (err) {
989
+ const msg = error(err, "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */, "Broker");
990
+ client.send(msg);
991
+ client.close();
992
+ }
993
+ }
994
+ async _notifyWebClient(context, client) {
995
+ const { name, updateMode } = context ?? {};
996
+ const identifier = getIdentifier({
997
+ name
998
+ });
999
+ const webClient = this._webClientMap.get(identifier);
1000
+ if (!webClient) {
1001
+ fileLog(
1002
+ `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] ${identifier} has not been added, this action will be ignored`,
1003
+ "Broker",
1004
+ "warn"
1005
+ );
1006
+ return;
1007
+ }
1008
+ try {
1009
+ const api = new ReloadWebClientAPI({ name, updateMode });
1010
+ webClient.send(JSON.stringify(api));
1011
+ fileLog(
1012
+ `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] Notify ${name} WebClient Succeed`,
1013
+ "Broker",
1014
+ "info"
1015
+ );
1016
+ } catch (err) {
1017
+ const msg = error(err, "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */, "Broker");
1018
+ client.send(msg);
1019
+ client.close();
1020
+ }
1021
+ }
1022
+ // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
1023
+ _addTmpSubScriberRelation(subscriber, publisher) {
1024
+ const publisherIdentifier = getIdentifier({
1025
+ name: publisher.name,
1026
+ ip: publisher.ip
1027
+ });
1028
+ const subscriberIdentifier = subscriber.name;
1029
+ const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
1030
+ if (!shelter) {
1031
+ const map = /* @__PURE__ */ new Map();
1032
+ map.set(subscriberIdentifier, subscriber);
1033
+ this._tmpSubscriberShelter.set(publisherIdentifier, {
1034
+ subscribers: map,
1035
+ timestamp: Date.now()
1036
+ });
1037
+ fileLog(
1038
+ `[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `,
1039
+ "Broker",
1040
+ "info"
1041
+ );
1042
+ return;
1043
+ }
1044
+ const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
1045
+ if (tmpSubScriberShelterSubscriber) {
1046
+ fileLog(
1047
+ `[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`,
1048
+ "Broker",
1049
+ "warn"
1050
+ );
1051
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1052
+ shelter.timestamp = Date.now();
1053
+ } else {
1054
+ fileLog(
1055
+ // eslint-disable-next-line max-len
1056
+ `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
1057
+ "Broker",
1058
+ "warn"
1059
+ );
1060
+ shelter.subscribers.set(subscriberIdentifier, subscriber);
1061
+ }
1062
+ }
1063
+ _getTmpSubScribers(publisherIdentifier) {
1064
+ var _a;
1065
+ return (_a = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a.subscribers;
1066
+ }
1067
+ // after adding publisher, it will change the temp subscriber to regular subscriber
1068
+ _consumeTmpSubScribers(publisher, tmpSubScribers) {
1069
+ tmpSubScribers.forEach((tmpSubScriber, identifier) => {
1070
+ fileLog(
1071
+ `notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `,
1072
+ "Broker",
1073
+ "warn"
1074
+ );
1075
+ publisher.addSubscriber(identifier, tmpSubScriber.client);
1076
+ publisher.notifySubscriber(identifier, {
1077
+ updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
1078
+ updateMode: "PASSIVE" /* PASSIVE */,
1079
+ updateSourcePaths: [publisher.name],
1080
+ remoteTypeTarPath: publisher.remoteTypeTarPath,
1081
+ name: publisher.name
1082
+ });
1083
+ });
1084
+ }
1085
+ _clearTmpSubScriberRelation(identifier) {
1086
+ this._tmpSubscriberShelter.delete(identifier);
1087
+ }
1088
+ _clearTmpSubScriberRelations() {
1089
+ this._tmpSubscriberShelter.clear();
1090
+ }
1091
+ _disconnect() {
1092
+ this._publisherMap.forEach((publisher) => {
1093
+ publisher.close();
1094
+ });
1095
+ }
1096
+ // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
1097
+ // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
1098
+ _setSchedule() {
1099
+ const rule = new import_node_schedule.default.RecurrenceRule();
1100
+ if (Number(process.env["FEDERATION_SERVER_TEST"])) {
1101
+ const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
1102
+ const second = [];
1103
+ for (let i = 0; i < 60; i = i + interval) {
1104
+ second.push(i);
1105
+ }
1106
+ rule.second = second;
1107
+ } else {
1108
+ rule.second = 0;
1109
+ rule.hour = [0, 3, 6, 9, 12, 15, 18];
1110
+ rule.minute = 0;
1111
+ }
1112
+ const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
1113
+ this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
1114
+ this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
1115
+ fileLog(
1116
+ ` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`,
1117
+ "Broker",
1118
+ "info"
1119
+ );
1120
+ if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
1121
+ this._clearTmpSubScriberRelation(identifier);
1122
+ }
1123
+ });
1124
+ });
1125
+ }
1126
+ _clearSchedule() {
1127
+ if (!this._scheduleJob) {
1128
+ return;
1129
+ }
1130
+ this._scheduleJob.cancel();
1131
+ this._scheduleJob = null;
1132
+ }
1133
+ _stopWhenSIGTERMOrSIGINT() {
1134
+ process.on("SIGTERM", () => {
1135
+ this.exit();
1136
+ });
1137
+ process.on("SIGINT", () => {
1138
+ this.exit();
1139
+ });
1140
+ }
1141
+ _handleUnexpectedExit() {
1142
+ process.on("unhandledRejection", (error2) => {
1143
+ console.error("Unhandled Rejection Error: ", error2);
1144
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1145
+ process.exit(1);
1146
+ });
1147
+ process.on("uncaughtException", (error2) => {
1148
+ console.error("Unhandled Exception Error: ", error2);
1149
+ fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
1150
+ process.exit(1);
1151
+ });
1152
+ }
1153
+ async start() {
1154
+ }
1155
+ exit() {
1156
+ const brokerExitLog = new BrokerExitLog();
1157
+ this.broadcast(JSON.stringify(brokerExitLog));
1158
+ this._disconnect();
1159
+ this._clearSchedule();
1160
+ this._clearTmpSubScriberRelations();
1161
+ this._webSocketServer && this._webSocketServer.close();
1162
+ this._secureWebSocketServer && this._secureWebSocketServer.close();
1163
+ process.exit(0);
1164
+ }
1165
+ broadcast(message) {
1166
+ var _a, _b;
1167
+ fileLog(
1168
+ `[broadcast] exit info : ${JSON.stringify(message)}`,
1169
+ "Broker",
1170
+ "warn"
1171
+ );
1172
+ (_a = this._webSocketServer) == null ? void 0 : _a.clients.forEach((client) => {
1173
+ client.send(JSON.stringify(message));
1174
+ });
1175
+ (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
1176
+ client.send(JSON.stringify(message));
1177
+ });
1178
+ }
1179
+ };
1180
+ _Broker.WEB_SOCKET_CONNECT_MAGIC_ID = WEB_SOCKET_CONNECT_MAGIC_ID;
1181
+ _Broker.DEFAULT_WEB_SOCKET_PORT = DEFAULT_WEB_SOCKET_PORT;
1182
+ _Broker.DEFAULT_SECURE_WEB_SOCKET_PORT = 16324;
1183
+ _Broker.DEFAULT_WAITING_TIME = 1.5 * 60 * 60 * 1e3;
1184
+ var Broker = _Broker;
1185
+
1186
+ // packages/dts-plugin/src/server/createKoaServer.ts
1187
+ var import_fs_extra = __toESM(require("fs-extra"));
1188
+ var import_koa = __toESM(require("koa"));
1189
+
1190
+ // packages/dts-plugin/src/core/lib/archiveHandler.ts
1191
+ var retrieveTypesZipPath = (mfTypesPath, remoteOptions) => (0, import_path3.join)(
1192
+ mfTypesPath.replace(remoteOptions.typesFolder, ""),
1193
+ `${remoteOptions.typesFolder}.zip`
1194
+ );
1195
+ var createTypesArchive = async (tsConfig, remoteOptions) => {
1196
+ const mfTypesPath = retrieveMfTypesPath(tsConfig, remoteOptions);
1197
+ const zip = new import_adm_zip.default();
1198
+ zip.addLocalFolder(mfTypesPath);
1199
+ return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath, remoteOptions));
1200
+ };
1201
+ var downloadErrorLogger = (destinationFolder, fileToDownload) => (reason) => {
1202
+ throw {
1203
+ ...reason,
1204
+ message: `Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`
1205
+ };
1206
+ };
1207
+ var retrieveTypesArchiveDestinationPath = (hostOptions, destinationFolder) => {
1208
+ return (0, import_path3.resolve)(
1209
+ hostOptions.context,
1210
+ hostOptions.typesFolder,
1211
+ destinationFolder
1212
+ );
1213
+ };
1214
+ var downloadTypesArchive = (hostOptions) => {
1215
+ let retries = 0;
1216
+ return async ([destinationFolder, fileToDownload]) => {
1217
+ const destinationPath = retrieveTypesArchiveDestinationPath(
1218
+ hostOptions,
1219
+ destinationFolder
1220
+ );
1221
+ while (retries++ < hostOptions.maxRetries) {
1222
+ try {
1223
+ const url = replaceLocalhost(fileToDownload);
1224
+ const response = await import_axios.default.get(url, { responseType: "arraybuffer" }).catch(downloadErrorLogger(destinationFolder, url));
1225
+ const zip = new import_adm_zip.default(Buffer.from(response.data));
1226
+ zip.extractAllTo(destinationPath, true);
1227
+ return [destinationFolder, destinationPath];
1228
+ } catch (error2) {
1229
+ fileLog(
1230
+ `Error during types archive download: ${(error2 == null ? void 0 : error2.message) || "unknown error"}`,
1231
+ "downloadTypesArchive",
1232
+ "error"
1233
+ );
1234
+ if (retries >= hostOptions.maxRetries) {
1235
+ if (hostOptions.abortOnError !== false) {
1236
+ throw error2;
1237
+ }
1238
+ return void 0;
1239
+ }
1240
+ }
1241
+ }
1242
+ };
1243
+ };
1244
+
464
1245
  // packages/dts-plugin/src/core/lib/DTSManager.ts
465
1246
  var import_axios2 = __toESM(require("axios"));
466
1247
  var DTSManager = class {
467
1248
  constructor(options) {
468
- this.options = (0, import_lodash.default)(options, (_value, key) => {
1249
+ this.options = (0, import_lodash2.default)(options, (_value, key) => {
469
1250
  if (key === "manifest") {
470
1251
  return false;
471
1252
  }
472
1253
  });
473
1254
  this.runtimePkgs = [
474
1255
  "@module-federation/runtime",
1256
+ "@module-federation/enhanced/runtime",
475
1257
  "@module-federation/runtime-tools"
476
1258
  ];
477
1259
  this.loadedRemoteAPIAlias = [];
@@ -555,20 +1337,20 @@ var DTSManager = class {
555
1337
  force: true
556
1338
  });
557
1339
  }
558
- console.log(import_ansi_colors3.default.green("Federated types created correctly"));
559
- } catch (error) {
1340
+ console.log(import_ansi_colors2.default.green("Federated types created correctly"));
1341
+ } catch (error2) {
560
1342
  if (((_a = this.options.remote) == null ? void 0 : _a.abortOnError) === false) {
561
1343
  console.error(
562
- import_ansi_colors3.default.red(`Unable to compile federated types, ${error}`)
1344
+ import_ansi_colors2.default.red(`Unable to compile federated types, ${error2}`)
563
1345
  );
564
1346
  } else {
565
- throw error;
1347
+ throw error2;
566
1348
  }
567
1349
  }
568
1350
  }
569
1351
  async requestRemoteManifest(remoteInfo) {
570
1352
  try {
571
- if (!remoteInfo.url.includes(import_sdk2.MANIFEST_EXT)) {
1353
+ if (!remoteInfo.url.includes(import_sdk4.MANIFEST_EXT)) {
572
1354
  return remoteInfo;
573
1355
  }
574
1356
  const url = replaceLocalhost(remoteInfo.url);
@@ -600,7 +1382,11 @@ var DTSManager = class {
600
1382
  ).href;
601
1383
  return remoteInfo;
602
1384
  } catch (_err) {
603
- console.error(_err);
1385
+ fileLog(
1386
+ `fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`,
1387
+ "requestRemoteManifest",
1388
+ "error"
1389
+ );
604
1390
  return remoteInfo;
605
1391
  }
606
1392
  }
@@ -628,10 +1414,10 @@ var DTSManager = class {
628
1414
  import_fs2.default.writeFileSync(filePath, apiTypeFile);
629
1415
  this.loadedRemoteAPIAlias.push(remoteInfo.alias);
630
1416
  } catch (err) {
631
- console.error(
632
- import_ansi_colors3.default.red(
633
- `Unable to download "${remoteInfo.name}" api types, ${err}`
634
- )
1417
+ fileLog(
1418
+ `Unable to download "${remoteInfo.name}" api types, ${err}`,
1419
+ "consumeTargetRemotes",
1420
+ "error"
635
1421
  );
636
1422
  }
637
1423
  }
@@ -680,8 +1466,10 @@ var DTSManager = class {
680
1466
  recursive: true,
681
1467
  force: true
682
1468
  }).catch(
683
- (error) => console.error(
684
- import_ansi_colors3.default.red(`Unable to remove types folder, ${error}`)
1469
+ (error2) => fileLog(
1470
+ `Unable to remove types folder, ${error2}`,
1471
+ "consumeArchiveTypes",
1472
+ "error"
685
1473
  )
686
1474
  );
687
1475
  }
@@ -732,11 +1520,13 @@ var DTSManager = class {
732
1520
  );
733
1521
  this.consumeAPITypes(hostOptions);
734
1522
  }
735
- console.log(import_ansi_colors3.default.green("Federated types extraction completed"));
1523
+ console.log(import_ansi_colors2.default.green("Federated types extraction completed"));
736
1524
  } catch (err) {
737
1525
  if (((_a = this.options.host) == null ? void 0 : _a.abortOnError) === false) {
738
- console.error(
739
- import_ansi_colors3.default.red(`Unable to consume federated types, ${err}`)
1526
+ fileLog(
1527
+ `Unable to consume federated types, ${err}`,
1528
+ "consumeTypes",
1529
+ "error"
740
1530
  );
741
1531
  } else {
742
1532
  throw err;
@@ -785,7 +1575,7 @@ var DTSManager = class {
785
1575
  };
786
1576
 
787
1577
  // packages/dts-plugin/src/core/lib/utils.ts
788
- var import_ansi_colors4 = __toESM(require("ansi-colors"));
1578
+ var import_ansi_colors3 = __toESM(require("ansi-colors"));
789
1579
  function getDTSManagerConstructor(implementation) {
790
1580
  if (implementation) {
791
1581
  const NewConstructor = require(implementation);
@@ -801,9 +1591,6 @@ var validateOptions = (options) => {
801
1591
  function replaceLocalhost(url) {
802
1592
  return url.replace("localhost", "127.0.0.1");
803
1593
  }
804
- function isDebugMode() {
805
- return Boolean(process.env["FEDERATION_DEBUG"]);
806
- }
807
1594
 
808
1595
  // packages/dts-plugin/src/core/lib/generateTypes.ts
809
1596
  async function generateTypes(options) {