itd-api 0.13.1 → 0.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/events/index.cjs +5 -5
- package/dist/events/index.d.cts +2 -2
- package/dist/events/index.d.ts +2 -2
- package/dist/events/index.js +3 -3
- package/dist/index.cjs +201 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +64 -4
- package/dist/index.d.ts +64 -4
- package/dist/index.js +177 -8
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +2 -2
- package/dist/node/index.js +2 -2
- package/dist/rest/index.cjs +25 -8
- package/dist/rest/index.cjs.map +1 -1
- package/dist/rest/index.d.cts +5 -3
- package/dist/rest/index.d.ts +5 -3
- package/dist/rest/index.js +12 -7
- package/dist/rest/index.js.map +1 -1
- package/dist/shared/{redact-BCmucE19.js → cookies-YP0m72v2.js} +125 -124
- package/dist/shared/cookies-YP0m72v2.js.map +1 -0
- package/dist/shared/{redact-BuXRKC1G.cjs → cookies-u2hXCcpR.cjs} +124 -123
- package/dist/shared/cookies-u2hXCcpR.cjs.map +1 -0
- package/dist/shared/{events-Bip3qvCc.d.cts → events-BmYzFrRC.d.cts} +213 -198
- package/dist/shared/{events-DRbBDq9p.js → events-BnL_gckg.js} +567 -530
- package/dist/shared/events-BnL_gckg.js.map +1 -0
- package/dist/shared/{events-DF1elRzZ.d.ts → events-Bw7VaSDs.d.ts} +18 -3
- package/dist/shared/{events-DcxmyPTX.cjs → events-DUFuPzVO.cjs} +582 -545
- package/dist/shared/events-DUFuPzVO.cjs.map +1 -0
- package/dist/shared/{multi-storage-Dp5x6OOl.cjs → multi-storage-BIeeBDV6.cjs} +5 -5
- package/dist/shared/{multi-storage-Dp5x6OOl.cjs.map → multi-storage-BIeeBDV6.cjs.map} +1 -1
- package/dist/shared/{multi-storage-DffEAzdc.js → multi-storage-DmUOaXbC.js} +2 -2
- package/dist/shared/{multi-storage-DffEAzdc.js.map → multi-storage-DmUOaXbC.js.map} +1 -1
- package/dist/shared/{options-Ddyc5qec.js → options-D-8h06B_.js} +2 -2
- package/dist/shared/{options-Ddyc5qec.js.map → options-D-8h06B_.js.map} +1 -1
- package/dist/shared/{options-DsmQRyx4.cjs → options-hZolLxgs.cjs} +5 -5
- package/dist/shared/{options-DsmQRyx4.cjs.map → options-hZolLxgs.cjs.map} +1 -1
- package/dist/shared/{render-DJKZqv9O.js → render-CgSQp84V.js} +2990 -1692
- package/dist/shared/render-CgSQp84V.js.map +1 -0
- package/dist/shared/{render-Bvv1V5Tp.d.ts → render-DPXlBr5L.d.ts} +1394 -441
- package/dist/shared/{render-D83t9ckd.d.cts → render-DcIXTSuo.d.cts} +1311 -369
- package/dist/shared/{render-C1lmsu1i.cjs → render-dKMV-872.cjs} +3071 -1695
- package/dist/shared/render-dKMV-872.cjs.map +1 -0
- package/dist/shared/{url-V4bCae35.d.ts → url-B_TELARK.d.ts} +372 -168
- package/dist/shared/{url-CXRaoR_w.cjs → url-CQbNqbJX.cjs} +3472 -3257
- package/dist/shared/url-CQbNqbJX.cjs.map +1 -0
- package/dist/shared/{url-n_h2pvHA.d.cts → url-D7U9qjXD.d.cts} +1809 -1594
- package/dist/shared/{url-aw_NZdVY.js → url-DYGRJqxh.js} +3463 -3254
- package/dist/shared/url-DYGRJqxh.js.map +1 -0
- package/package.json +5 -2
- package/dist/shared/events-DRbBDq9p.js.map +0 -1
- package/dist/shared/events-DcxmyPTX.cjs.map +0 -1
- package/dist/shared/redact-BCmucE19.js.map +0 -1
- package/dist/shared/redact-BuXRKC1G.cjs.map +0 -1
- package/dist/shared/render-C1lmsu1i.cjs.map +0 -1
- package/dist/shared/render-DJKZqv9O.js.map +0 -1
- package/dist/shared/url-CXRaoR_w.cjs.map +0 -1
- package/dist/shared/url-aw_NZdVY.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const require_url = require("./url-
|
|
1
|
+
const require_url = require("./url-CQbNqbJX.cjs");
|
|
2
2
|
const require_validate = require("./validate-BHKy_YMv.cjs");
|
|
3
|
-
const
|
|
3
|
+
const require_cookies = require("./cookies-u2hXCcpR.cjs");
|
|
4
4
|
// src/core/emitter.ts
|
|
5
5
|
/**
|
|
6
6
|
* Минимальный типизированный источник событий.
|
|
@@ -76,7 +76,7 @@ var Emitter = class {
|
|
|
76
76
|
* @internal
|
|
77
77
|
*/
|
|
78
78
|
function reportListenerError(logger, scope, error) {
|
|
79
|
-
(logger ??
|
|
79
|
+
(logger ?? require_cookies.fallbackLogger).error(`Ошибка в обработчике события ${scope}`, error);
|
|
80
80
|
}
|
|
81
81
|
// src/events/middleware.ts
|
|
82
82
|
const EVENT_MIDDLEWARE_SNAPSHOT = Symbol("itd-api.events.middlewareSnapshot");
|
|
@@ -365,6 +365,7 @@ var EventChannel = class {
|
|
|
365
365
|
#wanted = false;
|
|
366
366
|
#status = require_url.EventChannelStatus.Disconnected;
|
|
367
367
|
#attempt = 0;
|
|
368
|
+
#recovering = false;
|
|
368
369
|
#generation = 0;
|
|
369
370
|
#starting;
|
|
370
371
|
#cancelTimer;
|
|
@@ -390,6 +391,10 @@ var EventChannel = class {
|
|
|
390
391
|
get status() {
|
|
391
392
|
return this.#status;
|
|
392
393
|
}
|
|
394
|
+
/** Канал запущен или восстанавливает соединение. @internal */
|
|
395
|
+
get active() {
|
|
396
|
+
return this.#wanted;
|
|
397
|
+
}
|
|
393
398
|
/** Имя используемого транспорта. */
|
|
394
399
|
get transport() {
|
|
395
400
|
return this.#deps.transport.name;
|
|
@@ -453,9 +458,23 @@ var EventChannel = class {
|
|
|
453
458
|
this.#detachEnvironment = void 0;
|
|
454
459
|
this.#abortSession(new require_validate.ItdAbortError("Событийное соединение остановлено"));
|
|
455
460
|
this.#attempt = 0;
|
|
461
|
+
this.#recovering = false;
|
|
456
462
|
this.#dispatcher.clearPending();
|
|
457
463
|
this.#setStatus(require_url.EventChannelStatus.Disconnected);
|
|
458
|
-
if (wasActive) this.#deps.logger?.info("
|
|
464
|
+
if (wasActive) this.#deps.logger?.info("получение событий остановлено");
|
|
465
|
+
}
|
|
466
|
+
/** Отбрасывает очередь при разрыве последовательности и запускает новую синхронизацию. @internal */
|
|
467
|
+
recover(error) {
|
|
468
|
+
if (!this.#session) return;
|
|
469
|
+
this.#recovering = true;
|
|
470
|
+
this.#dispatcher.clearPending();
|
|
471
|
+
this.#handleFailure(error);
|
|
472
|
+
}
|
|
473
|
+
/** Сбрасывает счётчик восстановления, когда канал продвинулся после пропуска. @internal */
|
|
474
|
+
confirmRecovery() {
|
|
475
|
+
if (!this.#recovering) return;
|
|
476
|
+
this.#recovering = false;
|
|
477
|
+
this.#attempt = 0;
|
|
459
478
|
}
|
|
460
479
|
/**
|
|
461
480
|
* Ждёт обработчики и полное завершение уже остановленной сессии соединения.
|
|
@@ -489,8 +508,8 @@ var EventChannel = class {
|
|
|
489
508
|
const generation = session.generation;
|
|
490
509
|
this.#abortSession(new require_validate.ItdAbortError("Очередь событий переполнена"));
|
|
491
510
|
this.#setStatus(require_url.EventChannelStatus.Error);
|
|
492
|
-
const error = /* @__PURE__ */ new Error("
|
|
493
|
-
this.#deps.logger?.warn("очередь обновлений
|
|
511
|
+
const error = /* @__PURE__ */ new Error("Очередь обновлений переполнена");
|
|
512
|
+
this.#deps.logger?.warn("очередь обновлений переполнена. Соединение восстановится после обработки очереди");
|
|
494
513
|
this.#dispatcher.drain().then(() => {
|
|
495
514
|
if (this.#isCurrentGeneration(generation) && !this.#session) this.#scheduleReconnect(error);
|
|
496
515
|
});
|
|
@@ -533,7 +552,7 @@ var EventChannel = class {
|
|
|
533
552
|
await task;
|
|
534
553
|
} catch (error) {
|
|
535
554
|
if (this.#deps.initializationRequired) throw error;
|
|
536
|
-
this.#deps.logger?.warn(`не удалось синхронизировать
|
|
555
|
+
this.#deps.logger?.warn(`не удалось синхронизировать события (${reason})`, error);
|
|
537
556
|
}
|
|
538
557
|
}
|
|
539
558
|
/** Запускает транспорт одной попытки. */
|
|
@@ -546,10 +565,10 @@ var EventChannel = class {
|
|
|
546
565
|
onOpen: () => {
|
|
547
566
|
if (!this.#isCurrentSession(session)) return;
|
|
548
567
|
const reconnected = this.#attempt > 0;
|
|
549
|
-
this.#attempt = 0;
|
|
568
|
+
if (session.ready && !this.#recovering) this.#attempt = 0;
|
|
550
569
|
session.resolveOpened();
|
|
551
570
|
this.#setStatus(require_url.EventChannelStatus.Connected);
|
|
552
|
-
this.#deps.logger?.info(reconnected ? "
|
|
571
|
+
this.#deps.logger?.info(reconnected ? "соединение для получения событий восстановлено" : "соединение для получения событий установлено");
|
|
553
572
|
},
|
|
554
573
|
onEvent: (event) => {
|
|
555
574
|
if (this.#isCurrentSession(session)) this.#handleEvent(session, event);
|
|
@@ -561,7 +580,7 @@ var EventChannel = class {
|
|
|
561
580
|
});
|
|
562
581
|
}
|
|
563
582
|
})).then(() => {
|
|
564
|
-
if (this.#isCurrentSession(session)) this.#handleFailure(/* @__PURE__ */ new Error("Соединение
|
|
583
|
+
if (this.#isCurrentSession(session)) this.#handleFailure(/* @__PURE__ */ new Error("Соединение закрыто"));
|
|
565
584
|
}, (error) => {
|
|
566
585
|
if (this.#isCurrentSession(session)) this.#handleFailure(error);
|
|
567
586
|
}));
|
|
@@ -592,8 +611,8 @@ var EventChannel = class {
|
|
|
592
611
|
});
|
|
593
612
|
return;
|
|
594
613
|
}
|
|
595
|
-
const message = event === "middlewareError" ? "Ошибка в промежуточном обработчике
|
|
596
|
-
(this.#deps.logger ??
|
|
614
|
+
const message = event === "middlewareError" ? "Ошибка в промежуточном обработчике событий" : "Ошибка при обработке обновления";
|
|
615
|
+
(this.#deps.logger ?? require_cookies.fallbackLogger).error(message, error);
|
|
597
616
|
}
|
|
598
617
|
#handleFailure(error) {
|
|
599
618
|
this.#abortSession(error);
|
|
@@ -624,7 +643,7 @@ var EventChannel = class {
|
|
|
624
643
|
}
|
|
625
644
|
const delay = reconnectDelay(this.#attempt, this.#options);
|
|
626
645
|
this.#attempt += 1;
|
|
627
|
-
this.#deps.logger?.warn(
|
|
646
|
+
this.#deps.logger?.warn(`получение событий прервано (${describe(error)}). Попытка переподключения ${this.#attempt} из ${this.#maxAttempts} через ${delay} мс`);
|
|
628
647
|
this.#emitEngine("error", {
|
|
629
648
|
error,
|
|
630
649
|
willReconnect: true
|
|
@@ -640,7 +659,7 @@ var EventChannel = class {
|
|
|
640
659
|
}
|
|
641
660
|
/** Догон через REST идёт до сокета: он же обновляет протухший токен. */
|
|
642
661
|
async #reconnect() {
|
|
643
|
-
if (!this.#wanted || this.#
|
|
662
|
+
if (!this.#wanted || this.#session) return;
|
|
644
663
|
const starting = this.#startAttempt("reconnect");
|
|
645
664
|
this.#starting = starting;
|
|
646
665
|
try {
|
|
@@ -659,10 +678,11 @@ var EventChannel = class {
|
|
|
659
678
|
this.#generation += 1;
|
|
660
679
|
this.#starting = void 0;
|
|
661
680
|
this.#attempt = 0;
|
|
681
|
+
this.#recovering = false;
|
|
662
682
|
this.#abortSession(error);
|
|
663
683
|
this.#detachEnvironment?.();
|
|
664
684
|
this.#detachEnvironment = void 0;
|
|
665
|
-
this.#deps.logger?.warn(
|
|
685
|
+
this.#deps.logger?.warn(`получение событий остановлено (${describe(error)}). Для возобновления вызовите connect()`);
|
|
666
686
|
EVENT_CHANNEL_GIVEUP_HOOKS.get(this)?.();
|
|
667
687
|
this.#emitEngine("error", {
|
|
668
688
|
error,
|
|
@@ -683,7 +703,7 @@ var EventChannel = class {
|
|
|
683
703
|
const wake = () => {
|
|
684
704
|
if (this.#session || this.#cancelTimer || this.#starting) return;
|
|
685
705
|
if (this.#status === require_url.EventChannelStatus.Disconnected) return;
|
|
686
|
-
this.#attempt = 0;
|
|
706
|
+
if (!this.#recovering) this.#attempt = 0;
|
|
687
707
|
this.#reconnect();
|
|
688
708
|
};
|
|
689
709
|
const onVisibility = () => {
|
|
@@ -790,6 +810,9 @@ var EventChannel = class {
|
|
|
790
810
|
if (!this.#isCurrentSession(session)) break;
|
|
791
811
|
this.#dispatchFrame(event);
|
|
792
812
|
}
|
|
813
|
+
if (this.#deps.openBeforeInitialize && this.#attempt > 0) this.#dispatcher.drain().then(() => {
|
|
814
|
+
if (this.#isCurrentSession(session) && !this.#recovering) this.#attempt = 0;
|
|
815
|
+
});
|
|
793
816
|
}
|
|
794
817
|
#abortSession(reason) {
|
|
795
818
|
const session = this.#session;
|
|
@@ -808,161 +831,487 @@ var EventChannel = class {
|
|
|
808
831
|
this.#emitter.emit(event, payload);
|
|
809
832
|
}
|
|
810
833
|
};
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
834
|
+
const CONNECTING = 0;
|
|
835
|
+
const OPEN = 1;
|
|
836
|
+
const NORMAL_CLOSURE = 1e3;
|
|
837
|
+
const UNAUTHORIZED_CLOSE_CODES = [1008, 4401];
|
|
838
|
+
function validateDuration(value, name) {
|
|
839
|
+
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new require_validate.ItdConfigError(`WebSocketTransport.${name} должен быть числом не меньше 0, получено: ${value}`);
|
|
840
|
+
}
|
|
841
|
+
function isWebSocketConnection(value) {
|
|
842
|
+
if (typeof value !== "object" || value === null) return false;
|
|
843
|
+
const socket = value;
|
|
844
|
+
return typeof socket.readyState === "number" && typeof socket.addEventListener === "function" && typeof socket.removeEventListener === "function" && typeof socket.send === "function" && typeof socket.close === "function";
|
|
845
|
+
}
|
|
846
|
+
function abortError(signal) {
|
|
847
|
+
if (signal.reason !== void 0) return signal.reason;
|
|
848
|
+
const error = /* @__PURE__ */ new Error("WebSocket-подключение отменено");
|
|
849
|
+
error.name = "AbortError";
|
|
850
|
+
return error;
|
|
851
|
+
}
|
|
852
|
+
function errorMessage(error) {
|
|
853
|
+
if (error instanceof Error && error.message) return error.message;
|
|
854
|
+
if (typeof error === "object" && error !== null && "message" in error) {
|
|
855
|
+
const message = error.message;
|
|
856
|
+
if (typeof message === "string" && message) return message;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
function safeDetail(error, url, token) {
|
|
860
|
+
const message = errorMessage(error);
|
|
861
|
+
if (!message) return void 0;
|
|
862
|
+
const safe = message.replaceAll(url, require_cookies.redactUrl(url));
|
|
863
|
+
return token ? safe.replaceAll(token, require_cookies.maskSecret(token)) : safe;
|
|
864
|
+
}
|
|
865
|
+
function readCloseEvent(event) {
|
|
866
|
+
const close = typeof event === "object" && event !== null ? event : void 0;
|
|
867
|
+
return {
|
|
868
|
+
code: typeof close?.code === "number" ? close.code : 1006,
|
|
869
|
+
reason: typeof close?.reason === "string" ? close.reason : "",
|
|
870
|
+
wasClean: close?.wasClean === true
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
function readMessage(event) {
|
|
874
|
+
const data = typeof event === "object" && event !== null && "data" in event ? event.data : void 0;
|
|
875
|
+
if (typeof data === "string") return data;
|
|
876
|
+
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
877
|
+
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
878
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) return data.text();
|
|
879
|
+
}
|
|
880
|
+
function eventName(data) {
|
|
881
|
+
return typeof data === "object" && data !== null && "type" in data ? String(data.type) : "message";
|
|
882
|
+
}
|
|
883
|
+
/** Транспорт исходных событий поверх стандартного WebSocket. */
|
|
884
|
+
var WebSocketTransport = class {
|
|
885
|
+
name = "ws";
|
|
886
|
+
#path;
|
|
887
|
+
#query;
|
|
888
|
+
#webSocketImpl;
|
|
889
|
+
#auth;
|
|
890
|
+
#unauthorizedCloseCodes;
|
|
891
|
+
#idleTimeout;
|
|
892
|
+
#keepAlive;
|
|
893
|
+
#handshakeTimeout;
|
|
894
|
+
#classifyOpenFailure;
|
|
826
895
|
#clock;
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
896
|
+
constructor(options = {}) {
|
|
897
|
+
const path = options.path ?? "/api/ws";
|
|
898
|
+
if (typeof path !== "string" || path.trim() === "" || path.includes("?") || path.includes("#") || /^[a-z][a-z\d+.-]*:/i.test(path)) throw new require_validate.ItdConfigError("WebSocketTransport.path должен быть путём без query и fragment");
|
|
899
|
+
if (options.webSocketImpl !== void 0 && typeof options.webSocketImpl !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.webSocketImpl должен быть конструктором");
|
|
900
|
+
if (options.classifyOpenFailure !== void 0 && typeof options.classifyOpenFailure !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.classifyOpenFailure должен быть функцией");
|
|
901
|
+
const auth = options.auth ?? "auto";
|
|
902
|
+
if (auth !== "auto" && auth !== "query" && auth !== "header" && (typeof auth !== "object" || !auth || typeof auth.subprotocol !== "string" || !auth.subprotocol)) throw new require_validate.ItdConfigError("Неизвестный способ авторизации WebSocket");
|
|
903
|
+
if (auth === "header" && !options.webSocketImpl) throw new require_validate.ItdConfigError("WebSocketTransport.auth=\"header\" требует webSocketImpl с поддержкой заголовков");
|
|
904
|
+
validateDuration(options.idleTimeout, "idleTimeout");
|
|
905
|
+
validateDuration(options.keepAlive, "keepAlive");
|
|
906
|
+
validateDuration(options.handshakeTimeout, "handshakeTimeout");
|
|
907
|
+
this.#path = path;
|
|
908
|
+
this.#query = { ...options.query };
|
|
909
|
+
this.#webSocketImpl = options.webSocketImpl;
|
|
910
|
+
this.#auth = typeof auth === "object" ? { ...auth } : auth;
|
|
911
|
+
this.#unauthorizedCloseCodes = new Set(options.unauthorizedCloseCodes ?? UNAUTHORIZED_CLOSE_CODES);
|
|
912
|
+
this.#idleTimeout = options.idleTimeout ?? 9e4;
|
|
913
|
+
this.#keepAlive = options.keepAlive ?? 3e4;
|
|
914
|
+
this.#handshakeTimeout = options.handshakeTimeout ?? 2e4;
|
|
915
|
+
this.#classifyOpenFailure = options.classifyOpenFailure;
|
|
830
916
|
this.#clock = options.clock ?? require_url.systemClock;
|
|
831
|
-
this.#interval = options.interval ?? 15e3;
|
|
832
|
-
this.#limit = options.limit ?? 20;
|
|
833
917
|
}
|
|
834
918
|
async connect(context) {
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
}
|
|
855
|
-
|
|
856
|
-
if (count !== void 0 && count !== lastUnreadCount) {
|
|
857
|
-
lastUnreadCount = count;
|
|
858
|
-
context.onEvent({
|
|
859
|
-
name: "unread_count",
|
|
860
|
-
data: { payload: { count } }
|
|
861
|
-
});
|
|
862
|
-
}
|
|
863
|
-
firstRun = false;
|
|
864
|
-
await this.#wait(context.signal);
|
|
919
|
+
if (context.signal.aborted) throw abortError(context.signal);
|
|
920
|
+
const token = context.authorize ? await context.getToken() : null;
|
|
921
|
+
if (context.signal.aborted) throw abortError(context.signal);
|
|
922
|
+
if (context.authorize && !token) throw new UnauthorizedStreamError();
|
|
923
|
+
const injected = this.#webSocketImpl !== void 0;
|
|
924
|
+
const implementation = this.#webSocketImpl ?? this.#globalImplementation();
|
|
925
|
+
const auth = this.#auth === "auto" ? injected ? "header" : "query" : this.#auth;
|
|
926
|
+
const { requestUrl, socketUrl } = this.#urls(context.baseUrl);
|
|
927
|
+
const query = auth === "query" && token ? {
|
|
928
|
+
...this.#query,
|
|
929
|
+
token
|
|
930
|
+
} : this.#query;
|
|
931
|
+
const url = `${socketUrl}${require_cookies.buildQuery(query)}`;
|
|
932
|
+
const protocols = typeof auth === "object" ? [auth.subprotocol] : [];
|
|
933
|
+
if (typeof auth === "object" && token) protocols.push(`bearer.${token}`);
|
|
934
|
+
let headers;
|
|
935
|
+
if (injected) {
|
|
936
|
+
const resolved = await context.baseHeaders(requestUrl);
|
|
937
|
+
if (context.signal.aborted) throw abortError(context.signal);
|
|
938
|
+
if (auth === "header" && token) resolved.set("Authorization", `Bearer ${token}`);
|
|
939
|
+
headers = Object.fromEntries(resolved.entries());
|
|
865
940
|
}
|
|
866
|
-
|
|
867
|
-
async #readUpdates(request, signal) {
|
|
941
|
+
let value;
|
|
868
942
|
try {
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
limit: this.#limit,
|
|
874
|
-
offset: 0
|
|
875
|
-
},
|
|
876
|
-
signal
|
|
877
|
-
});
|
|
943
|
+
value = injected ? new implementation(url, protocols, {
|
|
944
|
+
...headers ? { headers } : {},
|
|
945
|
+
...this.#handshakeTimeout > 0 ? { handshakeTimeout: this.#handshakeTimeout } : {}
|
|
946
|
+
}) : protocols.length ? new implementation(url, protocols) : new implementation(url);
|
|
878
947
|
} catch (error) {
|
|
879
|
-
|
|
880
|
-
throw
|
|
948
|
+
const detail = safeDetail(error, url, token);
|
|
949
|
+
throw new Error(`Не удалось создать WebSocket ${require_cookies.redactUrl(url)}${detail ? `: ${detail}` : ""}`);
|
|
881
950
|
}
|
|
882
|
-
|
|
883
|
-
async #readCount(request, signal) {
|
|
951
|
+
if (!isWebSocketConnection(value)) throw new require_validate.ItdConfigError("webSocketImpl вернул объект без WebSocket-методов addEventListener, send и close");
|
|
884
952
|
try {
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
signal
|
|
889
|
-
});
|
|
890
|
-
return require_url.pickNumber(payload, "count", 0);
|
|
891
|
-
} catch {
|
|
892
|
-
return;
|
|
893
|
-
}
|
|
953
|
+
value.binaryType = "arraybuffer";
|
|
954
|
+
} catch {}
|
|
955
|
+
return this.#listen(value, url, token, context);
|
|
894
956
|
}
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
if (
|
|
898
|
-
return
|
|
899
|
-
const cancel = this.#clock.schedule(finish, this.#interval);
|
|
900
|
-
function finish() {
|
|
901
|
-
cancel();
|
|
902
|
-
signal.removeEventListener("abort", finish);
|
|
903
|
-
resolve();
|
|
904
|
-
}
|
|
905
|
-
signal.addEventListener("abort", finish, { once: true });
|
|
906
|
-
});
|
|
957
|
+
#globalImplementation() {
|
|
958
|
+
const implementation = Reflect.get(globalThis, "WebSocket");
|
|
959
|
+
if (typeof implementation !== "function") throw new require_validate.ItdConfigError("В этой среде нет WebSocket: передайте реализацию через webSocketImpl");
|
|
960
|
+
return implementation;
|
|
907
961
|
}
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
this.name = "ParseError";
|
|
919
|
-
this.type = options.type;
|
|
920
|
-
this.field = options.field;
|
|
921
|
-
this.value = options.value;
|
|
922
|
-
this.line = options.line;
|
|
962
|
+
#urls(baseUrl) {
|
|
963
|
+
const request = new URL(require_cookies.joinUrl(baseUrl, this.#path));
|
|
964
|
+
const socket = new URL(request);
|
|
965
|
+
if (request.protocol === "https:") socket.protocol = "wss:";
|
|
966
|
+
else if (request.protocol === "http:") socket.protocol = "ws:";
|
|
967
|
+
else throw new require_validate.ItdConfigError(`WebSocketTransport требует baseUrl с http или https, получено: ${request.protocol}`);
|
|
968
|
+
return {
|
|
969
|
+
requestUrl: request.toString(),
|
|
970
|
+
socketUrl: socket.toString()
|
|
971
|
+
};
|
|
923
972
|
}
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
973
|
+
#listen(socket, url, token, context) {
|
|
974
|
+
return new Promise((resolve, reject) => {
|
|
975
|
+
let settled = false;
|
|
976
|
+
let finishing = false;
|
|
977
|
+
let opened = false;
|
|
978
|
+
let discardMessages = false;
|
|
979
|
+
let socketError;
|
|
980
|
+
let messageQueue = Promise.resolve();
|
|
981
|
+
let pendingFrames = 0;
|
|
982
|
+
let cancelHandshake;
|
|
983
|
+
let cancelIdle;
|
|
984
|
+
let cancelKeepAlive;
|
|
985
|
+
const stopSocketListeners = () => {
|
|
986
|
+
cancelHandshake?.();
|
|
987
|
+
cancelIdle?.();
|
|
988
|
+
cancelKeepAlive?.();
|
|
989
|
+
cancelHandshake = void 0;
|
|
990
|
+
cancelIdle = void 0;
|
|
991
|
+
cancelKeepAlive = void 0;
|
|
992
|
+
socket.removeEventListener("open", onOpen);
|
|
993
|
+
socket.removeEventListener("message", onMessage);
|
|
994
|
+
socket.removeEventListener("error", onError);
|
|
995
|
+
socket.removeEventListener("close", onClose);
|
|
996
|
+
};
|
|
997
|
+
const finish = (error) => {
|
|
998
|
+
if (settled) return;
|
|
999
|
+
settled = true;
|
|
1000
|
+
stopSocketListeners();
|
|
1001
|
+
context.signal.removeEventListener("abort", onAbort);
|
|
1002
|
+
if (error !== void 0) reject(error);
|
|
1003
|
+
else resolve();
|
|
1004
|
+
};
|
|
1005
|
+
const closeWithError = (error, code = 4e3, reason = "transport error") => {
|
|
1006
|
+
if (settled || finishing) return;
|
|
1007
|
+
socketError = error;
|
|
1008
|
+
finishing = true;
|
|
1009
|
+
stopSocketListeners();
|
|
1010
|
+
try {
|
|
1011
|
+
if (socket.readyState === CONNECTING || socket.readyState === OPEN) socket.close(code, reason);
|
|
1012
|
+
} catch {}
|
|
1013
|
+
messageQueue.then(() => finish(error), (queueError) => finish(queueError));
|
|
1014
|
+
};
|
|
1015
|
+
const armIdleTimer = () => {
|
|
1016
|
+
cancelIdle?.();
|
|
1017
|
+
if (this.#idleTimeout <= 0) return;
|
|
1018
|
+
cancelIdle = this.#clock.schedule(() => {
|
|
1019
|
+
closeWithError(/* @__PURE__ */ new Error(`WebSocket ${require_cookies.redactUrl(url)} молчит дольше допустимого`), 4e3, "idle timeout");
|
|
1020
|
+
}, this.#idleTimeout);
|
|
1021
|
+
};
|
|
1022
|
+
const scheduleKeepAlive = () => {
|
|
1023
|
+
if (this.#keepAlive <= 0 || settled || finishing) return;
|
|
1024
|
+
cancelKeepAlive = this.#clock.schedule(() => {
|
|
1025
|
+
if (settled || finishing || socket.readyState !== OPEN) return;
|
|
1026
|
+
try {
|
|
1027
|
+
socket.send("ping");
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
const detail = safeDetail(error, url, token);
|
|
1030
|
+
closeWithError(/* @__PURE__ */ new Error(`Не удалось отправить WebSocket ping ${require_cookies.redactUrl(url)}` + (detail ? `: ${detail}` : "")));
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
scheduleKeepAlive();
|
|
1034
|
+
}, this.#keepAlive);
|
|
1035
|
+
};
|
|
1036
|
+
const onOpen = () => {
|
|
1037
|
+
if (settled || finishing || opened) return;
|
|
1038
|
+
opened = true;
|
|
1039
|
+
cancelHandshake?.();
|
|
1040
|
+
cancelHandshake = void 0;
|
|
1041
|
+
armIdleTimer();
|
|
1042
|
+
scheduleKeepAlive();
|
|
1043
|
+
try {
|
|
1044
|
+
context.onOpen();
|
|
1045
|
+
} catch (error) {
|
|
1046
|
+
closeWithError(error);
|
|
1047
|
+
}
|
|
1048
|
+
};
|
|
1049
|
+
const onMessage = (event) => {
|
|
1050
|
+
if (settled || finishing) return;
|
|
1051
|
+
armIdleTimer();
|
|
1052
|
+
let pending;
|
|
1053
|
+
try {
|
|
1054
|
+
const raw = readMessage(event);
|
|
1055
|
+
if (raw !== void 0) pending = Promise.resolve(raw).then((value) => ({ raw: value }), (error) => ({ error }));
|
|
1056
|
+
} catch (error) {
|
|
1057
|
+
pending = Promise.resolve({ error });
|
|
1058
|
+
}
|
|
1059
|
+
if (pending === void 0) return;
|
|
1060
|
+
if (pendingFrames >= 256) {
|
|
1061
|
+
closeWithError(/* @__PURE__ */ new Error(`WebSocket ${require_cookies.redactUrl(url)}: очередь кадров переполнена`), 4e3, "queue overflow");
|
|
1062
|
+
return;
|
|
1063
|
+
}
|
|
1064
|
+
pendingFrames += 1;
|
|
1065
|
+
messageQueue = messageQueue.then(async () => {
|
|
1066
|
+
pendingFrames -= 1;
|
|
1067
|
+
if (settled || discardMessages) return;
|
|
1068
|
+
const decoded = await pending;
|
|
1069
|
+
if ("error" in decoded) {
|
|
1070
|
+
context.onParseError(decoded.error, "[binary WebSocket frame]");
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
const { raw } = decoded;
|
|
1074
|
+
if (settled || discardMessages || raw === "pong") return;
|
|
1075
|
+
if (raw === "ping") {
|
|
1076
|
+
if (socket.readyState === OPEN) socket.send("pong");
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
let data;
|
|
1080
|
+
try {
|
|
1081
|
+
data = JSON.parse(raw);
|
|
1082
|
+
} catch (error) {
|
|
1083
|
+
context.onParseError(error, raw);
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
context.onEvent({
|
|
1087
|
+
name: eventName(data),
|
|
1088
|
+
data
|
|
1089
|
+
});
|
|
1090
|
+
}).catch((error) => {
|
|
1091
|
+
if (finishing) throw error;
|
|
1092
|
+
closeWithError(error);
|
|
1093
|
+
});
|
|
1094
|
+
};
|
|
1095
|
+
const onError = (event) => {
|
|
1096
|
+
if (settled || finishing) return;
|
|
1097
|
+
socketError = typeof event === "object" && event !== null && "error" in event ? event.error : event;
|
|
1098
|
+
};
|
|
1099
|
+
const finishClose = async (event) => {
|
|
1100
|
+
const { code, reason, wasClean } = readCloseEvent(event);
|
|
1101
|
+
let outcome;
|
|
1102
|
+
if (context.authorize && this.#unauthorizedCloseCodes.has(code)) outcome = new UnauthorizedStreamError();
|
|
1103
|
+
else if (socketError !== void 0) {
|
|
1104
|
+
const detail = safeDetail(socketError, url, token);
|
|
1105
|
+
outcome = /* @__PURE__ */ new Error(`WebSocket ${require_cookies.redactUrl(url)} завершился ошибкой${detail ? `: ${detail}` : ""}`);
|
|
1106
|
+
} else if (opened && code === NORMAL_CLOSURE && wasClean) outcome = void 0;
|
|
1107
|
+
else {
|
|
1108
|
+
const safeReason = token ? reason.replaceAll(token, require_cookies.maskSecret(token)) : reason;
|
|
1109
|
+
outcome = /* @__PURE__ */ new Error(`WebSocket ${require_cookies.redactUrl(url)} закрыт с кодом ${code}` + (safeReason ? `: ${safeReason}` : ""));
|
|
1110
|
+
}
|
|
1111
|
+
if (!opened && context.authorize && !(outcome instanceof UnauthorizedStreamError) && this.#classifyOpenFailure) try {
|
|
1112
|
+
if (await this.#classifyOpenFailure(outcome, context.signal)) outcome = new UnauthorizedStreamError();
|
|
1113
|
+
} catch {}
|
|
1114
|
+
if (context.signal.aborted) {
|
|
1115
|
+
discardMessages = true;
|
|
1116
|
+
finish(abortError(context.signal));
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
try {
|
|
1120
|
+
await messageQueue;
|
|
1121
|
+
finish(outcome);
|
|
1122
|
+
} catch (error) {
|
|
1123
|
+
finish(error);
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
const onClose = (event) => {
|
|
1127
|
+
if (settled || finishing) return;
|
|
1128
|
+
if (context.signal.aborted) {
|
|
1129
|
+
discardMessages = true;
|
|
1130
|
+
finish(abortError(context.signal));
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
finishing = true;
|
|
1134
|
+
stopSocketListeners();
|
|
1135
|
+
finishClose(event);
|
|
1136
|
+
};
|
|
1137
|
+
const onAbort = () => {
|
|
1138
|
+
if (settled) return;
|
|
1139
|
+
const error = abortError(context.signal);
|
|
1140
|
+
discardMessages = true;
|
|
1141
|
+
finishing = true;
|
|
1142
|
+
stopSocketListeners();
|
|
1143
|
+
try {
|
|
1144
|
+
if (socket.readyState === CONNECTING || socket.readyState === OPEN) socket.close(NORMAL_CLOSURE, "aborted");
|
|
1145
|
+
} catch {}
|
|
1146
|
+
finish(error);
|
|
1147
|
+
};
|
|
1148
|
+
socket.addEventListener("open", onOpen);
|
|
1149
|
+
socket.addEventListener("message", onMessage);
|
|
1150
|
+
socket.addEventListener("error", onError);
|
|
1151
|
+
socket.addEventListener("close", onClose);
|
|
1152
|
+
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
1153
|
+
if (this.#handshakeTimeout > 0) cancelHandshake = this.#clock.schedule(() => {
|
|
1154
|
+
closeWithError(/* @__PURE__ */ new Error(`Истёк таймаут установки WebSocket ${require_cookies.redactUrl(url)}`), 4e3, "handshake timeout");
|
|
1155
|
+
}, this.#handshakeTimeout);
|
|
1156
|
+
if (context.signal.aborted) onAbort();
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
};
|
|
1160
|
+
// src/events/transports/poll.ts
|
|
1161
|
+
/**
|
|
1162
|
+
* Запасной транспорт: обычный опрос REST вместо потока.
|
|
1163
|
+
*
|
|
1164
|
+
* Нужен там, где `fetch` не умеет отдавать тело по частям, — например в части сборок
|
|
1165
|
+
* React Native. Наружу выдаёт те же события, что и {@link SseTransport}, поэтому
|
|
1166
|
+
* вызывающий код разницы не замечает.
|
|
1167
|
+
*
|
|
1168
|
+
* Новыми считаются уведомления, которых не было в предыдущем ответе; чтобы список
|
|
1169
|
+
* известных не рос бесконечно, он ограничен последними двумя страницами.
|
|
1170
|
+
*/
|
|
1171
|
+
var PollTransport = class {
|
|
1172
|
+
name = "poll";
|
|
1173
|
+
#interval;
|
|
1174
|
+
#limit;
|
|
1175
|
+
#clock;
|
|
1176
|
+
#request;
|
|
1177
|
+
constructor(options) {
|
|
1178
|
+
this.#request = options.request;
|
|
1179
|
+
this.#clock = options.clock ?? require_url.systemClock;
|
|
1180
|
+
this.#interval = options.interval ?? 15e3;
|
|
1181
|
+
this.#limit = options.limit ?? 20;
|
|
1182
|
+
}
|
|
1183
|
+
async connect(context) {
|
|
1184
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1185
|
+
let firstRun = true;
|
|
1186
|
+
let lastUnreadCount;
|
|
1187
|
+
while (!context.signal.aborted) {
|
|
1188
|
+
const payload = await this.#readUpdates(this.#request, context.signal);
|
|
1189
|
+
context.onOpen();
|
|
1190
|
+
const items = require_url.pickArray(payload, "notifications");
|
|
1191
|
+
for (const item of [...items].reverse()) {
|
|
1192
|
+
const id = typeof item.id === "string" ? item.id : void 0;
|
|
1193
|
+
if (!id || seen.has(id)) continue;
|
|
1194
|
+
seen.add(id);
|
|
1195
|
+
if (!firstRun) context.onEvent({
|
|
1196
|
+
name: "notification",
|
|
1197
|
+
data: { payload: item }
|
|
1198
|
+
});
|
|
1199
|
+
}
|
|
1200
|
+
if (seen.size > this.#limit * 2) {
|
|
1201
|
+
const excess = [...seen].slice(0, seen.size - this.#limit * 2);
|
|
1202
|
+
for (const id of excess) seen.delete(id);
|
|
1203
|
+
}
|
|
1204
|
+
const count = await this.#readCount(this.#request, context.signal);
|
|
1205
|
+
if (count !== void 0 && count !== lastUnreadCount) {
|
|
1206
|
+
lastUnreadCount = count;
|
|
1207
|
+
context.onEvent({
|
|
1208
|
+
name: "unread_count",
|
|
1209
|
+
data: { payload: { count } }
|
|
1210
|
+
});
|
|
1211
|
+
}
|
|
1212
|
+
firstRun = false;
|
|
1213
|
+
await this.#wait(context.signal);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
async #readUpdates(request, signal) {
|
|
1217
|
+
try {
|
|
1218
|
+
return await request({
|
|
1219
|
+
operationId: "events.notifications.poll.updates",
|
|
1220
|
+
path: "/api/notifications/",
|
|
1221
|
+
query: {
|
|
1222
|
+
limit: this.#limit,
|
|
1223
|
+
offset: 0
|
|
1224
|
+
},
|
|
1225
|
+
signal
|
|
1226
|
+
});
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
if (require_validate.isItdAuthError(error)) throw new UnauthorizedStreamError();
|
|
1229
|
+
throw error;
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
async #readCount(request, signal) {
|
|
1233
|
+
try {
|
|
1234
|
+
const payload = await request({
|
|
1235
|
+
operationId: "events.notifications.poll.unread",
|
|
1236
|
+
path: "/api/notifications/count",
|
|
1237
|
+
signal
|
|
1238
|
+
});
|
|
1239
|
+
return require_url.pickNumber(payload, "count", 0);
|
|
1240
|
+
} catch {
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/** Ждёт следующего опроса, прерываясь при отмене. */
|
|
1245
|
+
#wait(signal) {
|
|
1246
|
+
if (signal.aborted) return Promise.resolve();
|
|
1247
|
+
return new Promise((resolve) => {
|
|
1248
|
+
const cancel = this.#clock.schedule(finish, this.#interval);
|
|
1249
|
+
function finish() {
|
|
1250
|
+
cancel();
|
|
1251
|
+
signal.removeEventListener("abort", finish);
|
|
1252
|
+
resolve();
|
|
1253
|
+
}
|
|
1254
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
// node_modules/eventsource-parser/dist/errors.js
|
|
1259
|
+
/**
|
|
1260
|
+
* Error thrown when encountering an issue during parsing.
|
|
1261
|
+
*
|
|
1262
|
+
* @public
|
|
1263
|
+
*/
|
|
1264
|
+
var ParseError = class extends Error {
|
|
1265
|
+
constructor(message, options) {
|
|
1266
|
+
super(message);
|
|
1267
|
+
this.name = "ParseError";
|
|
1268
|
+
this.type = options.type;
|
|
1269
|
+
this.field = options.field;
|
|
1270
|
+
this.value = options.value;
|
|
1271
|
+
this.line = options.line;
|
|
1272
|
+
}
|
|
1273
|
+
};
|
|
1274
|
+
// node_modules/eventsource-parser/dist/parse.js
|
|
1275
|
+
/**
|
|
1276
|
+
* EventSource/Server-Sent Events parser
|
|
1277
|
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html
|
|
1278
|
+
*/
|
|
1279
|
+
const LF = 10;
|
|
1280
|
+
const CR = 13;
|
|
1281
|
+
const SPACE = 32;
|
|
1282
|
+
const MAX_FIELD_PREFIX_LENGTH = 6;
|
|
1283
|
+
/**
|
|
1284
|
+
* Creates a new EventSource parser.
|
|
1285
|
+
*
|
|
1286
|
+
* @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})
|
|
1287
|
+
* and options like `maxBufferSize` (see {@link ParserConfig}).
|
|
1288
|
+
*
|
|
1289
|
+
* @returns A new EventSource parser, with `feed` and `reset` methods.
|
|
1290
|
+
* @public
|
|
1291
|
+
*/
|
|
1292
|
+
function createParser(config) {
|
|
1293
|
+
if (typeof config === "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
|
|
1294
|
+
const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;
|
|
1295
|
+
const pendingFragments = [];
|
|
1296
|
+
let pendingFragmentsLength = 0;
|
|
1297
|
+
let bomPrefix = "";
|
|
1298
|
+
let id;
|
|
1299
|
+
let data = "";
|
|
1300
|
+
let dataLines = 0;
|
|
1301
|
+
let eventType;
|
|
1302
|
+
let terminated = false;
|
|
1303
|
+
let skippingLine = false;
|
|
1304
|
+
let skipNextLineFeed = false;
|
|
1305
|
+
/**
|
|
1306
|
+
* Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do
|
|
1307
|
+
* not yet form a complete line are held back and prepended to the next chunk,
|
|
1308
|
+
* so callers can pass arbitrary slices of the stream without worrying about
|
|
1309
|
+
* line boundaries.
|
|
1310
|
+
*
|
|
1311
|
+
* Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,
|
|
1312
|
+
* even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB
|
|
1313
|
+
* 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of
|
|
1314
|
+
* how the caller decoded the bytes.
|
|
966
1315
|
*
|
|
967
1316
|
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream
|
|
968
1317
|
*/
|
|
@@ -1296,7 +1645,7 @@ var SseTransport = class {
|
|
|
1296
1645
|
async connect(context) {
|
|
1297
1646
|
const token = context.authorize ? await context.getToken() : null;
|
|
1298
1647
|
if (context.authorize && !token) throw new UnauthorizedStreamError();
|
|
1299
|
-
const url =
|
|
1648
|
+
const url = require_cookies.joinUrl(context.baseUrl, STREAM_PATH);
|
|
1300
1649
|
const headers = await context.baseHeaders(url);
|
|
1301
1650
|
headers.set("Accept", "text/event-stream");
|
|
1302
1651
|
if (token) headers.set("Authorization", `Bearer ${token}`);
|
|
@@ -1613,396 +1962,84 @@ var NotificationEvents = class {
|
|
|
1613
1962
|
}
|
|
1614
1963
|
}
|
|
1615
1964
|
/** Закрывает соединение и отменяет запланированные попытки. */
|
|
1616
|
-
disconnect() {
|
|
1617
|
-
this.#engine.disconnect();
|
|
1618
|
-
this.#closeLifecycle();
|
|
1619
|
-
}
|
|
1620
|
-
/** Ждёт завершения принятых обновлений и освобождения ресурсов остановленной сессии. */
|
|
1621
|
-
drain() {
|
|
1622
|
-
return this.#engine.drain();
|
|
1623
|
-
}
|
|
1624
|
-
/** Снимает подписки `on()` и `once()`. Остальные обработчики остаются. */
|
|
1625
|
-
removeAllListeners() {
|
|
1626
|
-
this.#engine.removeAllListeners();
|
|
1627
|
-
}
|
|
1628
|
-
#closeLifecycle() {
|
|
1629
|
-
if (!this.#lifecycleActive) return;
|
|
1630
|
-
this.#lifecycleActive = false;
|
|
1631
|
-
this.#deps.onClose?.();
|
|
1632
|
-
}
|
|
1633
|
-
/** Кадр `connected` — не обновление, а подтверждение подключения. */
|
|
1634
|
-
#handleFrame(event) {
|
|
1635
|
-
if (event.name !== "connected") return false;
|
|
1636
|
-
this.#engine.emit("ready", { userId: require_url.pickString(event.data, "userId") });
|
|
1637
|
-
return true;
|
|
1638
|
-
}
|
|
1639
|
-
/**
|
|
1640
|
-
* Загружает начальное число непрочитанных.
|
|
1641
|
-
*
|
|
1642
|
-
* Только при первом подключении: поток присылает счётчик сам, а лишний запрос
|
|
1643
|
-
* на каждой попытке переподключения нагружал бы сервер во время недоступности сети.
|
|
1644
|
-
*/
|
|
1645
|
-
async #syncUnreadCount(reason, signal, dispatch) {
|
|
1646
|
-
if (reason !== "initial") return;
|
|
1647
|
-
const count = await this.#deps.fetchUnreadCount(signal);
|
|
1648
|
-
dispatch({
|
|
1649
|
-
type: NotificationUpdateType.UnreadCount,
|
|
1650
|
-
data: count
|
|
1651
|
-
});
|
|
1652
|
-
}
|
|
1653
|
-
#deliver(update) {
|
|
1654
|
-
if (update.type === NotificationUpdateType.Notification) {
|
|
1655
|
-
this.#engine.emit("notification", update.data);
|
|
1656
|
-
if (update.data.unreadCount !== void 0) this.#engine.emit("unreadCount", update.data.unreadCount);
|
|
1657
|
-
return;
|
|
1658
|
-
}
|
|
1659
|
-
if (update.type === NotificationUpdateType.UnreadCount) {
|
|
1660
|
-
this.#engine.emit("unreadCount", update.data);
|
|
1661
|
-
return;
|
|
1662
|
-
}
|
|
1663
|
-
if (update.type === NotificationUpdateType.Unknown) return;
|
|
1664
|
-
assertNeverUpdate(update);
|
|
1665
|
-
}
|
|
1666
|
-
};
|
|
1667
|
-
/** Выбирает транспорт по настройкам и возможностям среды. */
|
|
1668
|
-
function createTransport(deps, options) {
|
|
1669
|
-
const kind = options.transport ?? NotificationEventsTransport.Auto;
|
|
1670
|
-
if (typeof kind === "object") return kind;
|
|
1671
|
-
if (kind === NotificationEventsTransport.Poll || kind === NotificationEventsTransport.Auto && !require_redact.supportsStreamingBody()) {
|
|
1672
|
-
if (!deps.request) throw new require_validate.ItdConfigError("Poll transport requires a notification request adapter");
|
|
1673
|
-
return new PollTransport({
|
|
1674
|
-
request: deps.request,
|
|
1675
|
-
...deps.clock ? { clock: deps.clock } : {},
|
|
1676
|
-
...options.pollInterval !== void 0 ? { interval: options.pollInterval } : {}
|
|
1677
|
-
});
|
|
1678
|
-
}
|
|
1679
|
-
return new SseTransport({
|
|
1680
|
-
...deps.clock ? { clock: deps.clock } : {},
|
|
1681
|
-
...options.idleTimeout !== void 0 ? { idleTimeout: options.idleTimeout } : {},
|
|
1682
|
-
...options.handshakeTimeout !== void 0 ? { handshakeTimeout: options.handshakeTimeout } : {}
|
|
1683
|
-
});
|
|
1684
|
-
}
|
|
1685
|
-
function assertNeverUpdate(update) {
|
|
1686
|
-
throw new TypeError(`Необработанное обновление потока: ${String(update)}`);
|
|
1687
|
-
}
|
|
1688
|
-
// src/operations/events.ts
|
|
1689
|
-
/** Контракты HTTP-запросов событийного канала. */
|
|
1690
|
-
const EVENT_OPERATIONS = Object.freeze({
|
|
1691
|
-
"events.notifications.poll.updates": require_url.passthroughOperation("events.notifications.poll.updates"),
|
|
1692
|
-
"events.notifications.poll.unread": require_url.passthroughOperation("events.notifications.poll.unread")
|
|
1693
|
-
});
|
|
1694
|
-
const CONNECTING = 0;
|
|
1695
|
-
const OPEN = 1;
|
|
1696
|
-
const NORMAL_CLOSURE = 1e3;
|
|
1697
|
-
const UNAUTHORIZED_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401]);
|
|
1698
|
-
function validateDuration(value, name) {
|
|
1699
|
-
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new require_validate.ItdConfigError(`WebSocketTransport.${name} должен быть числом не меньше 0, получено: ${value}`);
|
|
1700
|
-
}
|
|
1701
|
-
function isWebSocketConnection(value) {
|
|
1702
|
-
if (typeof value !== "object" || value === null) return false;
|
|
1703
|
-
const socket = value;
|
|
1704
|
-
return typeof socket.readyState === "number" && typeof socket.addEventListener === "function" && typeof socket.removeEventListener === "function" && typeof socket.send === "function" && typeof socket.close === "function";
|
|
1705
|
-
}
|
|
1706
|
-
function abortError(signal) {
|
|
1707
|
-
if (signal.reason !== void 0) return signal.reason;
|
|
1708
|
-
const error = /* @__PURE__ */ new Error("WebSocket-подключение отменено");
|
|
1709
|
-
error.name = "AbortError";
|
|
1710
|
-
return error;
|
|
1711
|
-
}
|
|
1712
|
-
function errorMessage(error) {
|
|
1713
|
-
if (error instanceof Error && error.message) return error.message;
|
|
1714
|
-
if (typeof error === "object" && error !== null && "message" in error) {
|
|
1715
|
-
const message = error.message;
|
|
1716
|
-
if (typeof message === "string" && message) return message;
|
|
1717
|
-
}
|
|
1718
|
-
}
|
|
1719
|
-
function safeDetail(error, url, token) {
|
|
1720
|
-
const message = errorMessage(error);
|
|
1721
|
-
if (!message) return void 0;
|
|
1722
|
-
const safe = message.replaceAll(url, require_redact.redactUrl(url));
|
|
1723
|
-
return token ? safe.replaceAll(token, require_redact.maskSecret(token)) : safe;
|
|
1724
|
-
}
|
|
1725
|
-
function readCloseEvent(event) {
|
|
1726
|
-
const close = typeof event === "object" && event !== null ? event : void 0;
|
|
1727
|
-
return {
|
|
1728
|
-
code: typeof close?.code === "number" ? close.code : 1006,
|
|
1729
|
-
reason: typeof close?.reason === "string" ? close.reason : "",
|
|
1730
|
-
wasClean: close?.wasClean === true
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
function readMessage(event) {
|
|
1734
|
-
const data = typeof event === "object" && event !== null && "data" in event ? event.data : void 0;
|
|
1735
|
-
if (typeof data === "string") return data;
|
|
1736
|
-
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
1737
|
-
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
1738
|
-
if (typeof Blob !== "undefined" && data instanceof Blob) return data.text();
|
|
1739
|
-
}
|
|
1740
|
-
function eventName(data) {
|
|
1741
|
-
return typeof data === "object" && data !== null && "type" in data ? String(data.type) : "message";
|
|
1742
|
-
}
|
|
1743
|
-
/** Транспорт исходных событий поверх стандартного WebSocket. */
|
|
1744
|
-
var WebSocketTransport = class {
|
|
1745
|
-
name = "ws";
|
|
1746
|
-
#path;
|
|
1747
|
-
#webSocketImpl;
|
|
1748
|
-
#auth;
|
|
1749
|
-
#idleTimeout;
|
|
1750
|
-
#keepAlive;
|
|
1751
|
-
#handshakeTimeout;
|
|
1752
|
-
#classifyOpenFailure;
|
|
1753
|
-
#clock;
|
|
1754
|
-
constructor(options = {}) {
|
|
1755
|
-
const path = options.path ?? "/api/ws";
|
|
1756
|
-
if (typeof path !== "string" || path.trim() === "" || path.includes("?") || path.includes("#") || /^[a-z][a-z\d+.-]*:/i.test(path)) throw new require_validate.ItdConfigError("WebSocketTransport.path должен быть путём без query и fragment");
|
|
1757
|
-
if (options.webSocketImpl !== void 0 && typeof options.webSocketImpl !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.webSocketImpl должен быть конструктором");
|
|
1758
|
-
if (options.classifyOpenFailure !== void 0 && typeof options.classifyOpenFailure !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.classifyOpenFailure должен быть функцией");
|
|
1759
|
-
const auth = options.auth ?? "auto";
|
|
1760
|
-
if (auth !== "auto" && auth !== "query" && auth !== "header") throw new require_validate.ItdConfigError(`Неизвестный способ авторизации WebSocket: ${String(auth)}`);
|
|
1761
|
-
if (auth === "header" && !options.webSocketImpl) throw new require_validate.ItdConfigError("WebSocketTransport.auth=\"header\" требует webSocketImpl с поддержкой заголовков");
|
|
1762
|
-
validateDuration(options.idleTimeout, "idleTimeout");
|
|
1763
|
-
validateDuration(options.keepAlive, "keepAlive");
|
|
1764
|
-
validateDuration(options.handshakeTimeout, "handshakeTimeout");
|
|
1765
|
-
this.#path = path;
|
|
1766
|
-
this.#webSocketImpl = options.webSocketImpl;
|
|
1767
|
-
this.#auth = auth;
|
|
1768
|
-
this.#idleTimeout = options.idleTimeout ?? 9e4;
|
|
1769
|
-
this.#keepAlive = options.keepAlive ?? 3e4;
|
|
1770
|
-
this.#handshakeTimeout = options.handshakeTimeout ?? 2e4;
|
|
1771
|
-
this.#classifyOpenFailure = options.classifyOpenFailure;
|
|
1772
|
-
this.#clock = options.clock ?? require_url.systemClock;
|
|
1773
|
-
}
|
|
1774
|
-
async connect(context) {
|
|
1775
|
-
if (context.signal.aborted) throw abortError(context.signal);
|
|
1776
|
-
const token = context.authorize ? await context.getToken() : null;
|
|
1777
|
-
if (context.signal.aborted) throw abortError(context.signal);
|
|
1778
|
-
if (context.authorize && !token) throw new UnauthorizedStreamError();
|
|
1779
|
-
const injected = this.#webSocketImpl !== void 0;
|
|
1780
|
-
const implementation = this.#webSocketImpl ?? this.#globalImplementation();
|
|
1781
|
-
const auth = this.#auth === "auto" ? injected ? "header" : "query" : this.#auth;
|
|
1782
|
-
const { requestUrl, socketUrl } = this.#urls(context.baseUrl);
|
|
1783
|
-
const url = auth === "query" && token ? `${socketUrl}${require_redact.buildQuery({ token })}` : socketUrl;
|
|
1784
|
-
let headers;
|
|
1785
|
-
if (injected) {
|
|
1786
|
-
const resolved = await context.baseHeaders(requestUrl);
|
|
1787
|
-
if (context.signal.aborted) throw abortError(context.signal);
|
|
1788
|
-
if (auth === "header" && token) resolved.set("Authorization", `Bearer ${token}`);
|
|
1789
|
-
headers = Object.fromEntries(resolved.entries());
|
|
1790
|
-
}
|
|
1791
|
-
let value;
|
|
1792
|
-
try {
|
|
1793
|
-
value = injected ? new implementation(url, [], {
|
|
1794
|
-
...headers ? { headers } : {},
|
|
1795
|
-
...this.#handshakeTimeout > 0 ? { handshakeTimeout: this.#handshakeTimeout } : {}
|
|
1796
|
-
}) : new implementation(url);
|
|
1797
|
-
} catch (error) {
|
|
1798
|
-
const detail = safeDetail(error, url, token);
|
|
1799
|
-
throw new Error(`Не удалось создать WebSocket ${require_redact.redactUrl(url)}${detail ? `: ${detail}` : ""}`);
|
|
1800
|
-
}
|
|
1801
|
-
if (!isWebSocketConnection(value)) throw new require_validate.ItdConfigError("webSocketImpl вернул объект без WebSocket-методов addEventListener, send и close");
|
|
1802
|
-
try {
|
|
1803
|
-
value.binaryType = "arraybuffer";
|
|
1804
|
-
} catch {}
|
|
1805
|
-
return this.#listen(value, url, token, context);
|
|
1965
|
+
disconnect() {
|
|
1966
|
+
this.#engine.disconnect();
|
|
1967
|
+
this.#closeLifecycle();
|
|
1806
1968
|
}
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
return implementation;
|
|
1969
|
+
/** Ждёт завершения принятых обновлений и освобождения ресурсов остановленной сессии. */
|
|
1970
|
+
drain() {
|
|
1971
|
+
return this.#engine.drain();
|
|
1811
1972
|
}
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
if (request.protocol === "https:") socket.protocol = "wss:";
|
|
1816
|
-
else if (request.protocol === "http:") socket.protocol = "ws:";
|
|
1817
|
-
else throw new require_validate.ItdConfigError(`WebSocketTransport требует baseUrl с http или https, получено: ${request.protocol}`);
|
|
1818
|
-
return {
|
|
1819
|
-
requestUrl: request.toString(),
|
|
1820
|
-
socketUrl: socket.toString()
|
|
1821
|
-
};
|
|
1973
|
+
/** Снимает подписки `on()` и `once()`. Остальные обработчики остаются. */
|
|
1974
|
+
removeAllListeners() {
|
|
1975
|
+
this.#engine.removeAllListeners();
|
|
1822
1976
|
}
|
|
1823
|
-
#
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
};
|
|
1847
|
-
const finish = (error) => {
|
|
1848
|
-
if (settled) return;
|
|
1849
|
-
settled = true;
|
|
1850
|
-
stopSocketListeners();
|
|
1851
|
-
context.signal.removeEventListener("abort", onAbort);
|
|
1852
|
-
if (error !== void 0) reject(error);
|
|
1853
|
-
else resolve();
|
|
1854
|
-
};
|
|
1855
|
-
const closeWithError = (error, code = 4e3, reason = "transport error") => {
|
|
1856
|
-
if (settled || finishing) return;
|
|
1857
|
-
socketError = error;
|
|
1858
|
-
finishing = true;
|
|
1859
|
-
stopSocketListeners();
|
|
1860
|
-
try {
|
|
1861
|
-
if (socket.readyState === CONNECTING || socket.readyState === OPEN) socket.close(code, reason);
|
|
1862
|
-
} catch {}
|
|
1863
|
-
messageQueue.then(() => finish(error), (queueError) => finish(queueError));
|
|
1864
|
-
};
|
|
1865
|
-
const armIdleTimer = () => {
|
|
1866
|
-
cancelIdle?.();
|
|
1867
|
-
if (this.#idleTimeout <= 0) return;
|
|
1868
|
-
cancelIdle = this.#clock.schedule(() => {
|
|
1869
|
-
closeWithError(/* @__PURE__ */ new Error(`WebSocket ${require_redact.redactUrl(url)} молчит дольше допустимого`), 4e3, "idle timeout");
|
|
1870
|
-
}, this.#idleTimeout);
|
|
1871
|
-
};
|
|
1872
|
-
const scheduleKeepAlive = () => {
|
|
1873
|
-
if (this.#keepAlive <= 0 || settled || finishing) return;
|
|
1874
|
-
cancelKeepAlive = this.#clock.schedule(() => {
|
|
1875
|
-
if (settled || finishing || socket.readyState !== OPEN) return;
|
|
1876
|
-
try {
|
|
1877
|
-
socket.send("ping");
|
|
1878
|
-
} catch (error) {
|
|
1879
|
-
const detail = safeDetail(error, url, token);
|
|
1880
|
-
closeWithError(/* @__PURE__ */ new Error(`Не удалось отправить WebSocket ping ${require_redact.redactUrl(url)}` + (detail ? `: ${detail}` : "")));
|
|
1881
|
-
return;
|
|
1882
|
-
}
|
|
1883
|
-
scheduleKeepAlive();
|
|
1884
|
-
}, this.#keepAlive);
|
|
1885
|
-
};
|
|
1886
|
-
const onOpen = () => {
|
|
1887
|
-
if (settled || finishing || opened) return;
|
|
1888
|
-
opened = true;
|
|
1889
|
-
cancelHandshake?.();
|
|
1890
|
-
cancelHandshake = void 0;
|
|
1891
|
-
armIdleTimer();
|
|
1892
|
-
scheduleKeepAlive();
|
|
1893
|
-
try {
|
|
1894
|
-
context.onOpen();
|
|
1895
|
-
} catch (error) {
|
|
1896
|
-
closeWithError(error);
|
|
1897
|
-
}
|
|
1898
|
-
};
|
|
1899
|
-
const onMessage = (event) => {
|
|
1900
|
-
if (settled || finishing) return;
|
|
1901
|
-
armIdleTimer();
|
|
1902
|
-
let pending;
|
|
1903
|
-
try {
|
|
1904
|
-
const raw = readMessage(event);
|
|
1905
|
-
if (raw !== void 0) pending = Promise.resolve(raw).then((value) => ({ raw: value }), (error) => ({ error }));
|
|
1906
|
-
} catch (error) {
|
|
1907
|
-
pending = Promise.resolve({ error });
|
|
1908
|
-
}
|
|
1909
|
-
if (pending === void 0) return;
|
|
1910
|
-
if (pendingFrames >= 256) {
|
|
1911
|
-
closeWithError(/* @__PURE__ */ new Error(`WebSocket ${require_redact.redactUrl(url)}: очередь кадров переполнена`), 4e3, "queue overflow");
|
|
1912
|
-
return;
|
|
1913
|
-
}
|
|
1914
|
-
pendingFrames += 1;
|
|
1915
|
-
messageQueue = messageQueue.then(async () => {
|
|
1916
|
-
pendingFrames -= 1;
|
|
1917
|
-
if (settled || discardMessages) return;
|
|
1918
|
-
const decoded = await pending;
|
|
1919
|
-
if ("error" in decoded) {
|
|
1920
|
-
context.onParseError(decoded.error, "[binary WebSocket frame]");
|
|
1921
|
-
return;
|
|
1922
|
-
}
|
|
1923
|
-
const { raw } = decoded;
|
|
1924
|
-
if (settled || discardMessages || raw === "pong") return;
|
|
1925
|
-
let data;
|
|
1926
|
-
try {
|
|
1927
|
-
data = JSON.parse(raw);
|
|
1928
|
-
} catch (error) {
|
|
1929
|
-
context.onParseError(error, raw);
|
|
1930
|
-
return;
|
|
1931
|
-
}
|
|
1932
|
-
context.onEvent({
|
|
1933
|
-
name: eventName(data),
|
|
1934
|
-
data
|
|
1935
|
-
});
|
|
1936
|
-
}).catch((error) => {
|
|
1937
|
-
if (finishing) throw error;
|
|
1938
|
-
closeWithError(error);
|
|
1939
|
-
});
|
|
1940
|
-
};
|
|
1941
|
-
const onError = (event) => {
|
|
1942
|
-
if (settled || finishing) return;
|
|
1943
|
-
socketError = typeof event === "object" && event !== null && "error" in event ? event.error : event;
|
|
1944
|
-
};
|
|
1945
|
-
const finishClose = async (event) => {
|
|
1946
|
-
const { code, reason, wasClean } = readCloseEvent(event);
|
|
1947
|
-
let outcome;
|
|
1948
|
-
if (context.authorize && UNAUTHORIZED_CLOSE_CODES.has(code)) outcome = new UnauthorizedStreamError();
|
|
1949
|
-
else if (socketError !== void 0) {
|
|
1950
|
-
const detail = safeDetail(socketError, url, token);
|
|
1951
|
-
outcome = /* @__PURE__ */ new Error(`WebSocket ${require_redact.redactUrl(url)} завершился ошибкой${detail ? `: ${detail}` : ""}`);
|
|
1952
|
-
} else if (opened && code === NORMAL_CLOSURE && wasClean) outcome = void 0;
|
|
1953
|
-
else {
|
|
1954
|
-
const safeReason = token ? reason.replaceAll(token, require_redact.maskSecret(token)) : reason;
|
|
1955
|
-
outcome = /* @__PURE__ */ new Error(`WebSocket ${require_redact.redactUrl(url)} закрыт с кодом ${code}` + (safeReason ? `: ${safeReason}` : ""));
|
|
1956
|
-
}
|
|
1957
|
-
if (!opened && context.authorize && !(outcome instanceof UnauthorizedStreamError) && this.#classifyOpenFailure) try {
|
|
1958
|
-
if (await this.#classifyOpenFailure(outcome, context.signal)) outcome = new UnauthorizedStreamError();
|
|
1959
|
-
} catch {}
|
|
1960
|
-
if (context.signal.aborted) {
|
|
1961
|
-
discardMessages = true;
|
|
1962
|
-
finish(abortError(context.signal));
|
|
1963
|
-
return;
|
|
1964
|
-
}
|
|
1965
|
-
try {
|
|
1966
|
-
await messageQueue;
|
|
1967
|
-
finish(outcome);
|
|
1968
|
-
} catch (error) {
|
|
1969
|
-
finish(error);
|
|
1970
|
-
}
|
|
1971
|
-
};
|
|
1972
|
-
const onClose = (event) => {
|
|
1973
|
-
if (settled || finishing) return;
|
|
1974
|
-
if (context.signal.aborted) {
|
|
1975
|
-
discardMessages = true;
|
|
1976
|
-
finish(abortError(context.signal));
|
|
1977
|
-
return;
|
|
1978
|
-
}
|
|
1979
|
-
finishing = true;
|
|
1980
|
-
stopSocketListeners();
|
|
1981
|
-
finishClose(event);
|
|
1982
|
-
};
|
|
1983
|
-
const onAbort = () => {
|
|
1984
|
-
if (settled) return;
|
|
1985
|
-
const error = abortError(context.signal);
|
|
1986
|
-
discardMessages = true;
|
|
1987
|
-
finishing = true;
|
|
1988
|
-
stopSocketListeners();
|
|
1989
|
-
try {
|
|
1990
|
-
if (socket.readyState === CONNECTING || socket.readyState === OPEN) socket.close(NORMAL_CLOSURE, "aborted");
|
|
1991
|
-
} catch {}
|
|
1992
|
-
finish(error);
|
|
1993
|
-
};
|
|
1994
|
-
socket.addEventListener("open", onOpen);
|
|
1995
|
-
socket.addEventListener("message", onMessage);
|
|
1996
|
-
socket.addEventListener("error", onError);
|
|
1997
|
-
socket.addEventListener("close", onClose);
|
|
1998
|
-
context.signal.addEventListener("abort", onAbort, { once: true });
|
|
1999
|
-
if (this.#handshakeTimeout > 0) cancelHandshake = this.#clock.schedule(() => {
|
|
2000
|
-
closeWithError(/* @__PURE__ */ new Error(`Истёк таймаут установки WebSocket ${require_redact.redactUrl(url)}`), 4e3, "handshake timeout");
|
|
2001
|
-
}, this.#handshakeTimeout);
|
|
2002
|
-
if (context.signal.aborted) onAbort();
|
|
1977
|
+
#closeLifecycle() {
|
|
1978
|
+
if (!this.#lifecycleActive) return;
|
|
1979
|
+
this.#lifecycleActive = false;
|
|
1980
|
+
this.#deps.onClose?.();
|
|
1981
|
+
}
|
|
1982
|
+
/** Кадр `connected` — не обновление, а подтверждение подключения. */
|
|
1983
|
+
#handleFrame(event) {
|
|
1984
|
+
if (event.name !== "connected") return false;
|
|
1985
|
+
this.#engine.emit("ready", { userId: require_url.pickString(event.data, "userId") });
|
|
1986
|
+
return true;
|
|
1987
|
+
}
|
|
1988
|
+
/**
|
|
1989
|
+
* Загружает начальное число непрочитанных.
|
|
1990
|
+
*
|
|
1991
|
+
* Только при первом подключении: поток присылает счётчик сам, а лишний запрос
|
|
1992
|
+
* на каждой попытке переподключения нагружал бы сервер во время недоступности сети.
|
|
1993
|
+
*/
|
|
1994
|
+
async #syncUnreadCount(reason, signal, dispatch) {
|
|
1995
|
+
if (reason !== "initial") return;
|
|
1996
|
+
const count = await this.#deps.fetchUnreadCount(signal);
|
|
1997
|
+
dispatch({
|
|
1998
|
+
type: NotificationUpdateType.UnreadCount,
|
|
1999
|
+
data: count
|
|
2003
2000
|
});
|
|
2004
2001
|
}
|
|
2002
|
+
#deliver(update) {
|
|
2003
|
+
if (update.type === NotificationUpdateType.Notification) {
|
|
2004
|
+
this.#engine.emit("notification", update.data);
|
|
2005
|
+
if (update.data.unreadCount !== void 0) this.#engine.emit("unreadCount", update.data.unreadCount);
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
if (update.type === NotificationUpdateType.UnreadCount) {
|
|
2009
|
+
this.#engine.emit("unreadCount", update.data);
|
|
2010
|
+
return;
|
|
2011
|
+
}
|
|
2012
|
+
if (update.type === NotificationUpdateType.Unknown) return;
|
|
2013
|
+
assertNeverUpdate(update);
|
|
2014
|
+
}
|
|
2005
2015
|
};
|
|
2016
|
+
/** Выбирает транспорт по настройкам и возможностям среды. */
|
|
2017
|
+
function createTransport(deps, options) {
|
|
2018
|
+
const kind = options.transport ?? NotificationEventsTransport.Auto;
|
|
2019
|
+
if (typeof kind === "object") return kind;
|
|
2020
|
+
if (kind === NotificationEventsTransport.Poll || kind === NotificationEventsTransport.Auto && !require_cookies.supportsStreamingBody()) {
|
|
2021
|
+
if (!deps.request) throw new require_validate.ItdConfigError("Poll transport requires a notification request adapter");
|
|
2022
|
+
return new PollTransport({
|
|
2023
|
+
request: deps.request,
|
|
2024
|
+
...deps.clock ? { clock: deps.clock } : {},
|
|
2025
|
+
...options.pollInterval !== void 0 ? { interval: options.pollInterval } : {}
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
return new SseTransport({
|
|
2029
|
+
...deps.clock ? { clock: deps.clock } : {},
|
|
2030
|
+
...options.idleTimeout !== void 0 ? { idleTimeout: options.idleTimeout } : {},
|
|
2031
|
+
...options.handshakeTimeout !== void 0 ? { handshakeTimeout: options.handshakeTimeout } : {}
|
|
2032
|
+
});
|
|
2033
|
+
}
|
|
2034
|
+
function assertNeverUpdate(update) {
|
|
2035
|
+
throw new TypeError(`Необработанное обновление потока: ${String(update)}`);
|
|
2036
|
+
}
|
|
2037
|
+
// src/operations/events.ts
|
|
2038
|
+
/** Контракты HTTP-запросов событийного канала. */
|
|
2039
|
+
const EVENT_OPERATIONS = Object.freeze({
|
|
2040
|
+
"events.notifications.poll.updates": require_url.passthroughOperation("events.notifications.poll.updates"),
|
|
2041
|
+
"events.notifications.poll.unread": require_url.passthroughOperation("events.notifications.poll.unread")
|
|
2042
|
+
});
|
|
2006
2043
|
// src/events/client.ts
|
|
2007
2044
|
/**
|
|
2008
2045
|
* Поток уведомлений с собственным конвейером запросов.
|
|
@@ -2442,4 +2479,4 @@ Object.defineProperty(exports, "setNotificationEventsConnectGuard", {
|
|
|
2442
2479
|
}
|
|
2443
2480
|
});
|
|
2444
2481
|
|
|
2445
|
-
//# sourceMappingURL=events-
|
|
2482
|
+
//# sourceMappingURL=events-DUFuPzVO.cjs.map
|