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