@module-federation/dts-plugin 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/CHANGELOG.md +27 -0
  2. package/dist/{DtsWorker-d731dc2b.d.ts → DtsWorker-7113d2b0.d.ts} +6 -3
  3. package/dist/core.d.mts +85 -0
  4. package/dist/core.d.ts +5 -5
  5. package/dist/core.js +1105 -1008
  6. package/dist/dynamic-remote-type-hints-plugin.d.mts +5 -0
  7. package/dist/dynamic-remote-type-hints-plugin.d.ts +5 -0
  8. package/dist/dynamic-remote-type-hints-plugin.js +198 -0
  9. package/dist/esm/chunk-55BKSNZ4.js +2372 -0
  10. package/dist/esm/chunk-G7ONFBMA.js +24 -0
  11. package/dist/esm/chunk-MQRIERJP.js +236 -0
  12. package/dist/esm/core.js +44 -0
  13. package/dist/esm/dynamic-remote-type-hints-plugin.js +73 -0
  14. package/dist/esm/fork-dev-worker.js +141 -0
  15. package/dist/esm/fork-generate-dts.js +26 -0
  16. package/dist/esm/index.js +406 -0
  17. package/dist/esm/start-broker.js +36 -0
  18. package/dist/fork-dev-worker.d.ts +15 -0
  19. package/dist/fork-dev-worker.js +2543 -0
  20. package/dist/{forkGenerateDts.d.ts → fork-generate-dts.d.mts} +1 -1
  21. package/dist/fork-generate-dts.d.ts +9 -0
  22. package/dist/fork-generate-dts.js +1902 -0
  23. package/dist/iife/launch-web-client.js +91 -42
  24. package/dist/index.d.mts +10 -0
  25. package/dist/index.js +1287 -1181
  26. package/dist/package.json +11 -2
  27. package/dist/{startBroker.d.ts → start-broker.d.mts} +2 -0
  28. package/dist/start-broker.d.ts +42 -0
  29. package/dist/start-broker.js +1273 -0
  30. package/package.json +14 -5
  31. package/dist/forkDevWorker.js +0 -2523
  32. package/dist/forkGenerateDts.js +0 -1618
  33. package/dist/launch-web-client.d.ts +0 -2
  34. package/dist/startBroker.js +0 -902
  35. /package/dist/{forkDevWorker.d.ts → fork-dev-worker.d.mts} +0 -0
@@ -1,902 +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/server/broker/startBroker.ts
31
- var startBroker_exports = {};
32
- __export(startBroker_exports, {
33
- getBroker: () => getBroker
34
- });
35
- module.exports = __toCommonJS(startBroker_exports);
36
-
37
- // packages/dts-plugin/src/server/broker/Broker.ts
38
- var import_http = require("http");
39
-
40
- // packages/dts-plugin/src/core/configurations/remotePlugin.ts
41
- var import_managers2 = require("@module-federation/managers");
42
- var import_typescript2 = __toESM(require("typescript"));
43
-
44
- // packages/dts-plugin/src/core/lib/DTSManager.ts
45
- var import_ansi_colors2 = __toESM(require("ansi-colors"));
46
- var import_sdk4 = require("@module-federation/sdk");
47
- var import_lodash = __toESM(require("lodash.clonedeepwith"));
48
-
49
- // packages/dts-plugin/src/core/lib/archiveHandler.ts
50
- var import_adm_zip = __toESM(require("adm-zip"));
51
- var import_axios = __toESM(require("axios"));
52
-
53
- // packages/dts-plugin/src/core/lib/typeScriptCompiler.ts
54
- var import_ansi_colors = __toESM(require("ansi-colors"));
55
- var import_typescript = __toESM(require("typescript"));
56
- var import_third_party_dts_extractor = require("@module-federation/third-party-dts-extractor");
57
-
58
- // packages/dts-plugin/src/server/message/Message.ts
59
- var Message = class {
60
- constructor(type, kind) {
61
- this.type = type;
62
- this.kind = kind;
63
- this.time = Date.now();
64
- }
65
- };
66
-
67
- // packages/dts-plugin/src/server/message/API/API.ts
68
- var API = class extends Message {
69
- constructor(content, kind) {
70
- super("API", kind);
71
- const { code, payload } = content;
72
- this.code = code;
73
- this.payload = payload;
74
- }
75
- };
76
-
77
- // packages/dts-plugin/src/server/message/API/UpdateSubscriber.ts
78
- var UpdateSubscriberAPI = class extends API {
79
- constructor(payload) {
80
- super(
81
- {
82
- code: 0,
83
- payload
84
- },
85
- "UPDATE_SUBSCRIBER" /* UPDATE_SUBSCRIBER */
86
- );
87
- }
88
- };
89
-
90
- // packages/dts-plugin/src/server/message/API/ReloadWebClient.ts
91
- var ReloadWebClientAPI = class extends API {
92
- constructor(payload) {
93
- super(
94
- {
95
- code: 0,
96
- payload
97
- },
98
- "RELOAD_WEB_CLIENT" /* RELOAD_WEB_CLIENT */
99
- );
100
- }
101
- };
102
-
103
- // packages/dts-plugin/src/server/utils/index.ts
104
- var import_sdk2 = require("@module-federation/sdk");
105
-
106
- // packages/dts-plugin/src/server/utils/logTransform.ts
107
- var import_chalk = __toESM(require("chalk"));
108
-
109
- // packages/dts-plugin/src/server/message/Log/Log.ts
110
- var Log = class extends Message {
111
- constructor(level, kind, ignoreVerbose = false) {
112
- super("Log", kind);
113
- this.ignoreVerbose = false;
114
- this.level = level;
115
- this.ignoreVerbose = ignoreVerbose;
116
- }
117
- };
118
-
119
- // packages/dts-plugin/src/server/message/Log/BrokerExitLog.ts
120
- var BrokerExitLog = class extends Log {
121
- constructor() {
122
- super("LOG" /* LOG */, "BrokerExitLog" /* BrokerExitLog */);
123
- }
124
- };
125
-
126
- // packages/dts-plugin/src/server/utils/log.ts
127
- var import_sdk = require("@module-federation/sdk");
128
- var log4js = __toESM(require("log4js"));
129
- var import_chalk2 = __toESM(require("chalk"));
130
-
131
- // packages/dts-plugin/src/server/constant.ts
132
- var DEFAULT_WEB_SOCKET_PORT = 16322;
133
- var WEB_SOCKET_CONNECT_MAGIC_ID = "1hpzW-zo2z-o8io-gfmV1-2cb1d82";
134
-
135
- // packages/dts-plugin/src/server/utils/log.ts
136
- function fileLog(msg, module2, level) {
137
- var _a, _b;
138
- if (!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a["FEDERATION_DEBUG"])) {
139
- return;
140
- }
141
- log4js.configure({
142
- appenders: {
143
- [module2]: { type: "file", filename: ".mf/typesGenerate.log" },
144
- default: { type: "file", filename: ".mf/typesGenerate.log" }
145
- },
146
- categories: {
147
- [module2]: { appenders: [module2], level: "error" },
148
- default: { appenders: ["default"], level: "trace" }
149
- }
150
- });
151
- const logger4 = log4js.getLogger(module2);
152
- logger4.level = "debug";
153
- (_b = logger4[level]) == null ? void 0 : _b.call(logger4, msg);
154
- }
155
- function error(error2, action, from) {
156
- const err = error2 instanceof Error ? error2 : new Error(`${action} error`);
157
- fileLog(`[${action}] error: ${err}`, from, "fatal");
158
- return err.toString();
159
- }
160
-
161
- // packages/dts-plugin/src/server/utils/index.ts
162
- function getIdentifier(options) {
163
- const { ip, name } = options;
164
- return `mf ${import_sdk2.SEPARATOR}${name}${ip ? `${import_sdk2.SEPARATOR}${ip}` : ""}`;
165
- }
166
-
167
- // packages/dts-plugin/src/server/Publisher.ts
168
- var Publisher = class {
169
- constructor(ctx) {
170
- this._name = ctx.name;
171
- this._ip = ctx.ip;
172
- this._remoteTypeTarPath = ctx.remoteTypeTarPath;
173
- this._subscribers = /* @__PURE__ */ new Map();
174
- }
175
- get identifier() {
176
- return getIdentifier({
177
- name: this._name,
178
- ip: this._ip
179
- });
180
- }
181
- get name() {
182
- return this._name;
183
- }
184
- get ip() {
185
- return this._ip;
186
- }
187
- get remoteTypeTarPath() {
188
- return this._remoteTypeTarPath;
189
- }
190
- get hasSubscribes() {
191
- return Boolean(this._subscribers.size);
192
- }
193
- get subscribers() {
194
- return this._subscribers;
195
- }
196
- addSubscriber(identifier, subscriber) {
197
- fileLog(`${this.name} set subscriber: ${identifier}`, "Publisher", "info");
198
- this._subscribers.set(identifier, subscriber);
199
- }
200
- removeSubscriber(identifier) {
201
- if (this._subscribers.has(identifier)) {
202
- fileLog(
203
- `${this.name} removeSubscriber: ${identifier}`,
204
- "Publisher",
205
- "warn"
206
- );
207
- this._subscribers.delete(identifier);
208
- }
209
- }
210
- notifySubscriber(subscriberIdentifier, options) {
211
- const subscriber = this._subscribers.get(subscriberIdentifier);
212
- if (!subscriber) {
213
- fileLog(
214
- `[notifySubscriber] ${this.name} notifySubscriber: ${subscriberIdentifier}, does not exits`,
215
- "Publisher",
216
- "error"
217
- );
218
- return;
219
- }
220
- const api = new UpdateSubscriberAPI(options);
221
- subscriber.send(JSON.stringify(api));
222
- fileLog(
223
- `[notifySubscriber] ${this.name} notifySubscriber: ${JSON.stringify(
224
- subscriberIdentifier
225
- )}, message: ${JSON.stringify(api)}`,
226
- "Publisher",
227
- "info"
228
- );
229
- }
230
- notifySubscribers(options) {
231
- const api = new UpdateSubscriberAPI(options);
232
- this.broadcast(api);
233
- }
234
- broadcast(message) {
235
- if (this.hasSubscribes) {
236
- this._subscribers.forEach((subscriber, key) => {
237
- fileLog(
238
- `[BroadCast] ${this.name} notifySubscriber: ${key}, PID: ${process.pid}, message: ${JSON.stringify(message)}`,
239
- "Publisher",
240
- "info"
241
- );
242
- subscriber.send(JSON.stringify(message));
243
- });
244
- } else {
245
- fileLog(
246
- `[BroadCast] ${this.name}'s subscribe is empty`,
247
- "Publisher",
248
- "warn"
249
- );
250
- }
251
- }
252
- close() {
253
- this._subscribers.forEach((_subscriber, identifier) => {
254
- fileLog(
255
- `[BroadCast] close ${this.name} remove: ${identifier}`,
256
- "Publisher",
257
- "warn"
258
- );
259
- this.removeSubscriber(identifier);
260
- });
261
- }
262
- };
263
-
264
- // packages/dts-plugin/src/server/DevServer.ts
265
- var import_isomorphic_ws = __toESM(require("isomorphic-ws"));
266
-
267
- // packages/dts-plugin/src/server/createKoaServer.ts
268
- var import_fs_extra = __toESM(require("fs-extra"));
269
- var import_koa = __toESM(require("koa"));
270
-
271
- // packages/dts-plugin/src/core/configurations/hostPlugin.ts
272
- var import_sdk3 = require("@module-federation/sdk");
273
- var import_managers = require("@module-federation/managers");
274
- var defaultOptions = {
275
- typesFolder: "@mf-types",
276
- remoteTypesFolder: "@mf-types",
277
- deleteTypesFolder: true,
278
- maxRetries: 3,
279
- implementation: "",
280
- context: process.cwd(),
281
- abortOnError: true,
282
- consumeAPITypes: false
283
- };
284
-
285
- // packages/dts-plugin/src/core/lib/DTSManager.ts
286
- var import_axios2 = __toESM(require("axios"));
287
-
288
- // packages/dts-plugin/src/core/lib/utils.ts
289
- var import_ansi_colors3 = __toESM(require("ansi-colors"));
290
-
291
- // packages/dts-plugin/src/core/configurations/remotePlugin.ts
292
- var defaultOptions2 = {
293
- tsConfigPath: "./tsconfig.json",
294
- typesFolder: "@mf-types",
295
- compiledTypesFolder: "compiled-types",
296
- hostRemoteTypesFolder: "@mf-types",
297
- deleteTypesFolder: true,
298
- additionalFilesToCompile: [],
299
- compilerInstance: "tsc",
300
- compileInChildProcess: false,
301
- implementation: "",
302
- generateAPITypes: false,
303
- context: process.cwd(),
304
- abortOnError: true,
305
- extractRemoteTypes: false,
306
- extractThirdParty: false
307
- };
308
-
309
- // packages/dts-plugin/src/core/lib/DtsWorker.ts
310
- var import_lodash2 = __toESM(require("lodash.clonedeepwith"));
311
-
312
- // packages/dts-plugin/src/server/broker/Broker.ts
313
- var import_isomorphic_ws2 = __toESM(require("isomorphic-ws"));
314
- var import_node_schedule = __toESM(require("node-schedule"));
315
- var import_url = require("url");
316
- var _Broker = class _Broker {
317
- constructor() {
318
- // 1.5h
319
- this._publisherMap = /* @__PURE__ */ new Map();
320
- this._webClientMap = /* @__PURE__ */ new Map();
321
- this._tmpSubscriberShelter = /* @__PURE__ */ new Map();
322
- this._scheduleJob = null;
323
- this._setSchedule();
324
- this._startWsServer();
325
- this._stopWhenSIGTERMOrSIGINT();
326
- this._handleUnexpectedExit();
327
- }
328
- get hasPublishers() {
329
- return Boolean(this._publisherMap.size);
330
- }
331
- async _startWsServer() {
332
- const wsHandler = (ws, req) => {
333
- const { url: reqUrl = "" } = req;
334
- const { query } = (0, import_url.parse)(reqUrl, true);
335
- const { WEB_SOCKET_CONNECT_MAGIC_ID: WEB_SOCKET_CONNECT_MAGIC_ID2 } = query;
336
- if (WEB_SOCKET_CONNECT_MAGIC_ID2 === _Broker.WEB_SOCKET_CONNECT_MAGIC_ID) {
337
- ws.on("message", (message) => {
338
- try {
339
- const text = message.toString();
340
- const action = JSON.parse(text);
341
- fileLog(`${action == null ? void 0 : action.kind} action received `, "Broker", "info");
342
- this._takeAction(action, ws);
343
- } catch (error2) {
344
- fileLog(`parse action message error: ${error2}`, "Broker", "error");
345
- }
346
- });
347
- ws.on("error", (e) => {
348
- fileLog(`parse action message error: ${e}`, "Broker", "error");
349
- });
350
- } else {
351
- ws.send("Invalid CONNECT ID.");
352
- fileLog("Invalid CONNECT ID.", "Broker", "warn");
353
- ws.close();
354
- }
355
- };
356
- const server = (0, import_http.createServer)();
357
- this._webSocketServer = new import_isomorphic_ws2.default.Server({ noServer: true });
358
- this._webSocketServer.on("error", (err) => {
359
- fileLog(`ws error:
360
- ${err.message}
361
- ${err.stack}`, "Broker", "error");
362
- });
363
- this._webSocketServer.on("listening", () => {
364
- fileLog(
365
- `WebSocket server is listening on port ${_Broker.DEFAULT_WEB_SOCKET_PORT}`,
366
- "Broker",
367
- "info"
368
- );
369
- });
370
- this._webSocketServer.on("connection", wsHandler);
371
- this._webSocketServer.on("close", (code) => {
372
- fileLog(`WebSocket Server Close with Code ${code}`, "Broker", "warn");
373
- this._webSocketServer && this._webSocketServer.close();
374
- this._webSocketServer = void 0;
375
- });
376
- server.on("upgrade", (req, socket, head) => {
377
- var _a;
378
- if (req.url) {
379
- const { pathname } = (0, import_url.parse)(req.url);
380
- if (pathname === "/") {
381
- (_a = this._webSocketServer) == null ? void 0 : _a.handleUpgrade(req, socket, head, (ws) => {
382
- var _a2;
383
- (_a2 = this._webSocketServer) == null ? void 0 : _a2.emit("connection", ws, req);
384
- });
385
- }
386
- }
387
- });
388
- server.listen(_Broker.DEFAULT_WEB_SOCKET_PORT);
389
- }
390
- async _takeAction(action, client) {
391
- const { kind, payload } = action;
392
- if (kind === "ADD_PUBLISHER" /* ADD_PUBLISHER */) {
393
- await this._addPublisher(payload, client);
394
- }
395
- if (kind === "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */) {
396
- await this._updatePublisher(
397
- payload,
398
- client
399
- );
400
- }
401
- if (kind === "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */) {
402
- await this._addSubscriber(payload, client);
403
- }
404
- if (kind === "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */) {
405
- await this._removeSubscriber(
406
- payload,
407
- client
408
- );
409
- }
410
- if (kind === "EXIT_PUBLISHER" /* EXIT_PUBLISHER */) {
411
- await this._removePublisher(payload, client);
412
- }
413
- if (kind === "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */) {
414
- await this._addWebClient(payload, client);
415
- }
416
- if (kind === "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */) {
417
- await this._notifyWebClient(
418
- payload,
419
- client
420
- );
421
- }
422
- }
423
- async _addPublisher(context, client) {
424
- const { name, ip, remoteTypeTarPath } = context ?? {};
425
- const identifier = getIdentifier({ name, ip });
426
- if (this._publisherMap.has(identifier)) {
427
- fileLog(
428
- `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} has been added, this action will be ignored`,
429
- "Broker",
430
- "warn"
431
- );
432
- return;
433
- }
434
- try {
435
- const publisher = new Publisher({ name, ip, remoteTypeTarPath });
436
- this._publisherMap.set(identifier, publisher);
437
- fileLog(
438
- `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] ${identifier} Adding Publisher Succeed`,
439
- "Broker",
440
- "info"
441
- );
442
- const tmpSubScribers = this._getTmpSubScribers(identifier);
443
- if (tmpSubScribers) {
444
- fileLog(
445
- `[${"ADD_PUBLISHER" /* ADD_PUBLISHER */}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `,
446
- "Broker",
447
- "info"
448
- );
449
- this._consumeTmpSubScribers(publisher, tmpSubScribers);
450
- this._clearTmpSubScriberRelation(identifier);
451
- }
452
- } catch (err) {
453
- const msg = error(err, "ADD_PUBLISHER" /* ADD_PUBLISHER */, "Broker");
454
- client.send(msg);
455
- client.close();
456
- }
457
- }
458
- async _updatePublisher(context, client) {
459
- const {
460
- name,
461
- updateMode,
462
- updateKind,
463
- updateSourcePaths,
464
- remoteTypeTarPath,
465
- ip
466
- } = context ?? {};
467
- const identifier = getIdentifier({ name, ip });
468
- if (!this._publisherMap.has(identifier)) {
469
- fileLog(
470
- `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} has not been started, this action will be ignored
471
- this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
472
- `,
473
- "Broker",
474
- "warn"
475
- );
476
- return;
477
- }
478
- try {
479
- const publisher = this._publisherMap.get(identifier);
480
- fileLog(
481
- // eslint-disable-next-line max-len
482
- `[${"UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */}] ${identifier} update, and notify subscribers to update`,
483
- "Broker",
484
- "info"
485
- );
486
- if (publisher) {
487
- publisher.notifySubscribers({
488
- remoteTypeTarPath,
489
- name,
490
- updateMode,
491
- updateKind,
492
- updateSourcePaths: updateSourcePaths || []
493
- });
494
- }
495
- } catch (err) {
496
- const msg = error(err, "UPDATE_PUBLISHER" /* UPDATE_PUBLISHER */, "Broker");
497
- client.send(msg);
498
- client.close();
499
- }
500
- }
501
- // app1 consumes provider1,provider2. Dependencies at this time: publishers: [provider1, provider2], subscriberName: app1
502
- // provider1 is app1's remote
503
- async _addSubscriber(context, client) {
504
- const { publishers, name: subscriberName } = context ?? {};
505
- publishers.forEach((publisher) => {
506
- const { name, ip } = publisher;
507
- const identifier = getIdentifier({ name, ip });
508
- if (!this._publisherMap.has(identifier)) {
509
- fileLog(
510
- `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`,
511
- "Broker",
512
- "warn"
513
- );
514
- this._addTmpSubScriberRelation(
515
- {
516
- name: getIdentifier({
517
- name: context.name,
518
- ip: context.ip
519
- }),
520
- client
521
- },
522
- publisher
523
- );
524
- return;
525
- }
526
- try {
527
- const registeredPublisher = this._publisherMap.get(identifier);
528
- if (registeredPublisher) {
529
- registeredPublisher.addSubscriber(
530
- getIdentifier({
531
- name: subscriberName,
532
- ip: context.ip
533
- }),
534
- client
535
- );
536
- fileLog(
537
- // eslint-disable-next-line @ies/eden/max-calls-in-template
538
- `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(
539
- Array.from(this._publisherMap.entries())
540
- )}`,
541
- "Broker",
542
- "info"
543
- );
544
- registeredPublisher.notifySubscriber(
545
- getIdentifier({
546
- name: subscriberName,
547
- ip: context.ip
548
- }),
549
- {
550
- updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
551
- updateMode: "PASSIVE" /* PASSIVE */,
552
- updateSourcePaths: [registeredPublisher.name],
553
- remoteTypeTarPath: registeredPublisher.remoteTypeTarPath,
554
- name: registeredPublisher.name
555
- }
556
- );
557
- fileLog(
558
- // eslint-disable-next-line @ies/eden/max-calls-in-template
559
- `[${"ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,
560
- "Broker",
561
- "info"
562
- );
563
- }
564
- } catch (err) {
565
- const msg = error(err, "ADD_SUBSCRIBER" /* ADD_SUBSCRIBER */, "Broker");
566
- client.send(msg);
567
- client.close();
568
- }
569
- });
570
- }
571
- // Trigger while consumer exit
572
- async _removeSubscriber(context, client) {
573
- const { publishers } = context ?? {};
574
- const subscriberIdentifier = getIdentifier({
575
- name: context == null ? void 0 : context.name,
576
- ip: context == null ? void 0 : context.ip
577
- });
578
- publishers.forEach((publisher) => {
579
- const { name, ip } = publisher;
580
- const identifier = getIdentifier({
581
- name,
582
- ip
583
- });
584
- const registeredPublisher = this._publisherMap.get(identifier);
585
- if (!registeredPublisher) {
586
- fileLog(
587
- `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} does not exit `,
588
- "Broker",
589
- "warn"
590
- );
591
- return;
592
- }
593
- try {
594
- fileLog(
595
- `[${"EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */}], ${identifier} will exit `,
596
- "Broker",
597
- "INFO"
598
- );
599
- registeredPublisher.removeSubscriber(subscriberIdentifier);
600
- this._clearTmpSubScriberRelation(identifier);
601
- if (!registeredPublisher.hasSubscribes) {
602
- this._publisherMap.delete(identifier);
603
- }
604
- if (!this.hasPublishers) {
605
- this.exit();
606
- }
607
- } catch (err) {
608
- const msg = error(err, "EXIT_SUBSCRIBER" /* EXIT_SUBSCRIBER */, "Broker");
609
- client.send(msg);
610
- client.close();
611
- }
612
- });
613
- }
614
- async _removePublisher(context, client) {
615
- const { name, ip } = context ?? {};
616
- const identifier = getIdentifier({
617
- name,
618
- ip
619
- });
620
- const publisher = this._publisherMap.get(identifier);
621
- if (!publisher) {
622
- fileLog(
623
- `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier}} has not been added, this action will be ingored`,
624
- "Broker",
625
- "warn"
626
- );
627
- return;
628
- }
629
- try {
630
- const { subscribers } = publisher;
631
- subscribers.forEach((subscriber, subscriberIdentifier) => {
632
- this._addTmpSubScriberRelation(
633
- {
634
- name: subscriberIdentifier,
635
- client: subscriber
636
- },
637
- { name: publisher.name, ip: publisher.ip }
638
- );
639
- fileLog(
640
- // eslint-disable-next-line max-len
641
- `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,
642
- "Broker",
643
- "info"
644
- );
645
- });
646
- this._publisherMap.delete(identifier);
647
- fileLog(
648
- `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: ${identifier} is removed `,
649
- "Broker",
650
- "info"
651
- );
652
- if (!this.hasPublishers) {
653
- fileLog(
654
- `[${"EXIT_PUBLISHER" /* EXIT_PUBLISHER */}]: _publisherMap is empty, all server will exit `,
655
- "Broker",
656
- "warn"
657
- );
658
- this.exit();
659
- }
660
- } catch (err) {
661
- const msg = error(err, "EXIT_PUBLISHER" /* EXIT_PUBLISHER */, "Broker");
662
- client.send(msg);
663
- client.close();
664
- }
665
- }
666
- async _addWebClient(context, client) {
667
- const { name } = context ?? {};
668
- const identifier = getIdentifier({
669
- name
670
- });
671
- if (this._webClientMap.has(identifier)) {
672
- fileLog(
673
- `${identifier}} has been added, this action will override prev WebClient`,
674
- "Broker",
675
- "warn"
676
- );
677
- }
678
- try {
679
- this._webClientMap.set(identifier, client);
680
- fileLog(`${identifier} adding WebClient Succeed`, "Broker", "info");
681
- } catch (err) {
682
- const msg = error(err, "ADD_WEB_CLIENT" /* ADD_WEB_CLIENT */, "Broker");
683
- client.send(msg);
684
- client.close();
685
- }
686
- }
687
- async _notifyWebClient(context, client) {
688
- const { name, updateMode } = context ?? {};
689
- const identifier = getIdentifier({
690
- name
691
- });
692
- const webClient = this._webClientMap.get(identifier);
693
- if (!webClient) {
694
- fileLog(
695
- `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] ${identifier} has not been added, this action will be ignored`,
696
- "Broker",
697
- "warn"
698
- );
699
- return;
700
- }
701
- try {
702
- const api = new ReloadWebClientAPI({ name, updateMode });
703
- webClient.send(JSON.stringify(api));
704
- fileLog(
705
- `[${"NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */}] Notify ${name} WebClient Succeed`,
706
- "Broker",
707
- "info"
708
- );
709
- } catch (err) {
710
- const msg = error(err, "NOTIFY_WEB_CLIENT" /* NOTIFY_WEB_CLIENT */, "Broker");
711
- client.send(msg);
712
- client.close();
713
- }
714
- }
715
- // app1 consumes provider1, and provider1 not launch. this._tmpSubscriberShelter at this time: {provider1: Map{subscribers: Map{app1: app1+ip+client'}, timestamp: 'xx'} }
716
- _addTmpSubScriberRelation(subscriber, publisher) {
717
- const publisherIdentifier = getIdentifier({
718
- name: publisher.name,
719
- ip: publisher.ip
720
- });
721
- const subscriberIdentifier = subscriber.name;
722
- const shelter = this._tmpSubscriberShelter.get(publisherIdentifier);
723
- if (!shelter) {
724
- const map = /* @__PURE__ */ new Map();
725
- map.set(subscriberIdentifier, subscriber);
726
- this._tmpSubscriberShelter.set(publisherIdentifier, {
727
- subscribers: map,
728
- timestamp: Date.now()
729
- });
730
- fileLog(
731
- `[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `,
732
- "Broker",
733
- "info"
734
- );
735
- return;
736
- }
737
- const tmpSubScriberShelterSubscriber = shelter.subscribers.get(subscriberIdentifier);
738
- if (tmpSubScriberShelterSubscriber) {
739
- fileLog(
740
- `[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`,
741
- "Broker",
742
- "warn"
743
- );
744
- shelter.subscribers.set(subscriberIdentifier, subscriber);
745
- shelter.timestamp = Date.now();
746
- } else {
747
- fileLog(
748
- // eslint-disable-next-line max-len
749
- `AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,
750
- "Broker",
751
- "warn"
752
- );
753
- shelter.subscribers.set(subscriberIdentifier, subscriber);
754
- }
755
- }
756
- _getTmpSubScribers(publisherIdentifier) {
757
- var _a;
758
- return (_a = this._tmpSubscriberShelter.get(publisherIdentifier)) == null ? void 0 : _a.subscribers;
759
- }
760
- // after adding publisher, it will change the temp subscriber to regular subscriber
761
- _consumeTmpSubScribers(publisher, tmpSubScribers) {
762
- tmpSubScribers.forEach((tmpSubScriber, identifier) => {
763
- fileLog(
764
- `notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `,
765
- "Broker",
766
- "warn"
767
- );
768
- publisher.addSubscriber(identifier, tmpSubScriber.client);
769
- publisher.notifySubscriber(identifier, {
770
- updateKind: "UPDATE_TYPE" /* UPDATE_TYPE */,
771
- updateMode: "PASSIVE" /* PASSIVE */,
772
- updateSourcePaths: [publisher.name],
773
- remoteTypeTarPath: publisher.remoteTypeTarPath,
774
- name: publisher.name
775
- });
776
- });
777
- }
778
- _clearTmpSubScriberRelation(identifier) {
779
- this._tmpSubscriberShelter.delete(identifier);
780
- }
781
- _clearTmpSubScriberRelations() {
782
- this._tmpSubscriberShelter.clear();
783
- }
784
- _disconnect() {
785
- this._publisherMap.forEach((publisher) => {
786
- publisher.close();
787
- });
788
- }
789
- // Every day on 0/6/9/12/15//18, Publishers that have not been connected within 1.5 hours will be cleared regularly.
790
- // If process.env.FEDERATION_SERVER_TEST is set, it will be read at a specified time.
791
- _setSchedule() {
792
- const rule = new import_node_schedule.default.RecurrenceRule();
793
- if (Number(process.env["FEDERATION_SERVER_TEST"])) {
794
- const interval = Number(process.env["FEDERATION_SERVER_TEST"]) / 1e3;
795
- const second = [];
796
- for (let i = 0; i < 60; i = i + interval) {
797
- second.push(i);
798
- }
799
- rule.second = second;
800
- } else {
801
- rule.second = 0;
802
- rule.hour = [0, 3, 6, 9, 12, 15, 18];
803
- rule.minute = 0;
804
- }
805
- const serverTest = Number(process.env["FEDERATION_SERVER_TEST"]);
806
- this._scheduleJob = import_node_schedule.default.scheduleJob(rule, () => {
807
- this._tmpSubscriberShelter.forEach((tmpSubscriber, identifier) => {
808
- fileLog(
809
- ` _clearTmpSubScriberRelation ${identifier}, ${Date.now() - tmpSubscriber.timestamp >= (process.env["GARFISH_MODULE_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)}`,
810
- "Broker",
811
- "info"
812
- );
813
- if (Date.now() - tmpSubscriber.timestamp >= (process.env["FEDERATION_SERVER_TEST"] ? serverTest : _Broker.DEFAULT_WAITING_TIME)) {
814
- this._clearTmpSubScriberRelation(identifier);
815
- }
816
- });
817
- });
818
- }
819
- _clearSchedule() {
820
- if (!this._scheduleJob) {
821
- return;
822
- }
823
- this._scheduleJob.cancel();
824
- this._scheduleJob = null;
825
- }
826
- _stopWhenSIGTERMOrSIGINT() {
827
- process.on("SIGTERM", () => {
828
- this.exit();
829
- });
830
- process.on("SIGINT", () => {
831
- this.exit();
832
- });
833
- }
834
- _handleUnexpectedExit() {
835
- process.on("unhandledRejection", (error2) => {
836
- console.error("Unhandled Rejection Error: ", error2);
837
- fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
838
- process.exit(1);
839
- });
840
- process.on("uncaughtException", (error2) => {
841
- console.error("Unhandled Exception Error: ", error2);
842
- fileLog(`Unhandled Rejection Error: ${error2}`, "Broker", "fatal");
843
- process.exit(1);
844
- });
845
- }
846
- async start() {
847
- }
848
- exit() {
849
- const brokerExitLog = new BrokerExitLog();
850
- this.broadcast(JSON.stringify(brokerExitLog));
851
- this._disconnect();
852
- this._clearSchedule();
853
- this._clearTmpSubScriberRelations();
854
- this._webSocketServer && this._webSocketServer.close();
855
- this._secureWebSocketServer && this._secureWebSocketServer.close();
856
- process.exit(0);
857
- }
858
- broadcast(message) {
859
- var _a, _b;
860
- fileLog(
861
- `[broadcast] exit info : ${JSON.stringify(message)}`,
862
- "Broker",
863
- "warn"
864
- );
865
- (_a = this._webSocketServer) == null ? void 0 : _a.clients.forEach((client) => {
866
- client.send(JSON.stringify(message));
867
- });
868
- (_b = this._secureWebSocketServer) == null ? void 0 : _b.clients.forEach((client) => {
869
- client.send(JSON.stringify(message));
870
- });
871
- }
872
- };
873
- _Broker.WEB_SOCKET_CONNECT_MAGIC_ID = WEB_SOCKET_CONNECT_MAGIC_ID;
874
- _Broker.DEFAULT_WEB_SOCKET_PORT = DEFAULT_WEB_SOCKET_PORT;
875
- _Broker.DEFAULT_SECURE_WEB_SOCKET_PORT = 16324;
876
- _Broker.DEFAULT_WAITING_TIME = 1.5 * 60 * 60 * 1e3;
877
- var Broker = _Broker;
878
-
879
- // packages/dts-plugin/src/server/broker/startBroker.ts
880
- var broker;
881
- function getBroker() {
882
- return broker;
883
- }
884
- async function startBroker() {
885
- var _a;
886
- if (getBroker()) {
887
- return;
888
- }
889
- broker = new Broker();
890
- await broker.start();
891
- (_a = process.send) == null ? void 0 : _a.call(process, "ready");
892
- }
893
- process.on("message", (message) => {
894
- if (message === "start") {
895
- fileLog(`startBroker... ${process.pid}`, "StartBroker", "info");
896
- startBroker();
897
- }
898
- });
899
- // Annotate the CommonJS export names for ESM import in node:
900
- 0 && (module.exports = {
901
- getBroker
902
- });