itd-api 0.10.4 → 0.12.0
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 +2 -1
- package/dist/events/index.cjs +27 -25
- package/dist/events/index.d.cts +3 -3
- package/dist/events/index.d.ts +3 -3
- package/dist/events/index.js +5 -5
- package/dist/index.cjs +155 -155
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +35 -20
- package/dist/index.d.ts +35 -20
- package/dist/index.js +65 -72
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +13 -13
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +7 -8
- package/dist/node/index.d.ts +7 -8
- package/dist/node/index.js +5 -5
- package/dist/node/index.js.map +1 -1
- package/dist/rest/index.cjs +46 -40
- package/dist/rest/index.cjs.map +1 -1
- package/dist/rest/index.d.cts +5 -5
- package/dist/rest/index.d.ts +5 -5
- package/dist/rest/index.js +6 -6
- package/dist/rest/index.js.map +1 -1
- package/dist/shared/{events-CK3zHntT.d.cts → events-9L0Fonak.d.cts} +2 -2
- package/dist/shared/{events-DGdU8q1X.d.ts → events-BpLAIiMj.d.ts} +2 -2
- package/dist/shared/{events-B8cjz_Ed.cjs → events-C2DJZyI0.cjs} +306 -112
- package/dist/shared/events-C2DJZyI0.cjs.map +1 -0
- package/dist/shared/{events-D2n7Yu1P.js → events-D1BfefBT.js} +262 -68
- package/dist/shared/events-D1BfefBT.js.map +1 -0
- package/dist/shared/{key-value-store-B5GYVEYZ.cjs → key-value-store-DYSPsqwq.cjs} +11 -14
- package/dist/shared/key-value-store-DYSPsqwq.cjs.map +1 -0
- package/dist/shared/{key-value-store-Bt2PSMxY.js → key-value-store-w1Dn5Pjb.js} +5 -8
- package/dist/shared/key-value-store-w1Dn5Pjb.js.map +1 -0
- package/dist/shared/{multi-storage-s-fPtjoy.cjs → multi-storage-7Y3KCseI.cjs} +8 -8
- package/dist/shared/multi-storage-7Y3KCseI.cjs.map +1 -0
- package/dist/shared/{multi-storage-C3Ngtop1.js → multi-storage-DiBSx64p.js} +6 -6
- package/dist/shared/multi-storage-DiBSx64p.js.map +1 -0
- package/dist/shared/{options-DjEtbVaf.cjs → options-D5ttspWk.cjs} +13 -13
- package/dist/shared/{options-DjEtbVaf.cjs.map → options-D5ttspWk.cjs.map} +1 -1
- package/dist/shared/{options-i4LrKfqx.js → options-DLlaETn_.js} +3 -3
- package/dist/shared/{options-i4LrKfqx.js.map → options-DLlaETn_.js.map} +1 -1
- package/dist/shared/{redact-lAmck1Z6.cjs → redact-BbhtA9o-.cjs} +121 -26
- package/dist/shared/redact-BbhtA9o-.cjs.map +1 -0
- package/dist/shared/{redact-DJV0XM3n.js → redact-DSfdmeY7.js} +91 -20
- package/dist/shared/redact-DSfdmeY7.js.map +1 -0
- package/dist/shared/{render-BrrZOSV5.cjs → render-CrGXcj6L.cjs} +346 -284
- package/dist/shared/render-CrGXcj6L.cjs.map +1 -0
- package/dist/shared/{render-C6CJ343E.js → render-D3vSEbLL.js} +240 -178
- package/dist/shared/render-D3vSEbLL.js.map +1 -0
- package/dist/shared/{render-9F_kR6sq.d.cts → render-Dzw3KeN5.d.cts} +236 -278
- package/dist/shared/{render-UsOGMRzS.d.ts → render-UsQ1hb2U.d.ts} +236 -278
- package/dist/shared/{storage-DiDe0PZM.js → storage-86wiHeXD.js} +3 -3
- package/dist/shared/storage-86wiHeXD.js.map +1 -0
- package/dist/shared/{storage-CZJZoaz9.cjs → storage-CIjejZDt.cjs} +4 -4
- package/dist/shared/storage-CIjejZDt.cjs.map +1 -0
- package/dist/shared/{url-BNTKqBMB.cjs → url-B21Bdmw_.cjs} +869 -717
- package/dist/shared/url-B21Bdmw_.cjs.map +1 -0
- package/dist/shared/{url-yB6T_H_-.d.cts → url-C9YADYNg.d.cts} +221 -103
- package/dist/shared/{url-yB6T_H_-.d.ts → url-C9YADYNg.d.ts} +221 -103
- package/dist/shared/{url-Dc7wLikf.js → url-Dg1u29cu.js} +744 -598
- package/dist/shared/url-Dg1u29cu.js.map +1 -0
- package/dist/shared/{errors-BmP3TKoW.cjs → validate-CFx2dISs.cjs} +84 -5
- package/dist/shared/validate-CFx2dISs.cjs.map +1 -0
- package/dist/shared/{errors-GI10kZxk.js → validate-D7_kq3g5.js} +55 -6
- package/dist/shared/validate-D7_kq3g5.js.map +1 -0
- package/dist/web/index.cjs +4 -4
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +4 -5
- package/dist/web/index.d.ts +4 -5
- package/dist/web/index.js +3 -3
- package/dist/web/index.js.map +1 -1
- package/package.json +11 -11
- package/dist/shared/errors-BmP3TKoW.cjs.map +0 -1
- package/dist/shared/errors-GI10kZxk.js.map +0 -1
- package/dist/shared/events-B8cjz_Ed.cjs.map +0 -1
- package/dist/shared/events-D2n7Yu1P.js.map +0 -1
- package/dist/shared/key-value-store-B5GYVEYZ.cjs.map +0 -1
- package/dist/shared/key-value-store-Bt2PSMxY.js.map +0 -1
- package/dist/shared/multi-storage-C3Ngtop1.js.map +0 -1
- package/dist/shared/multi-storage-s-fPtjoy.cjs.map +0 -1
- package/dist/shared/redact-DJV0XM3n.js.map +0 -1
- package/dist/shared/redact-lAmck1Z6.cjs.map +0 -1
- package/dist/shared/render-BrrZOSV5.cjs.map +0 -1
- package/dist/shared/render-C6CJ343E.js.map +0 -1
- package/dist/shared/storage-CZJZoaz9.cjs.map +0 -1
- package/dist/shared/storage-DiDe0PZM.js.map +0 -1
- package/dist/shared/url-BNTKqBMB.cjs.map +0 -1
- package/dist/shared/url-Dc7wLikf.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
const require_url = require("./url-
|
|
2
|
-
const
|
|
3
|
-
const require_redact = require("./redact-
|
|
1
|
+
const require_url = require("./url-B21Bdmw_.cjs");
|
|
2
|
+
const require_validate = require("./validate-CFx2dISs.cjs");
|
|
3
|
+
const require_redact = require("./redact-BbhtA9o-.cjs");
|
|
4
4
|
//#region src/core/emitter.ts
|
|
5
5
|
/**
|
|
6
6
|
* Минимальный типизированный источник событий.
|
|
@@ -68,20 +68,15 @@ var Emitter = class {
|
|
|
68
68
|
}
|
|
69
69
|
};
|
|
70
70
|
/**
|
|
71
|
-
* Сообщает об исключении из пользовательского обработчика
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
* Ошибка чужого обработчика не должна ронять библиотеку, но и пропадать молча ей нельзя:
|
|
75
|
-
* иначе подписка, падающая на каждом событии, выглядит как её отсутствие.
|
|
71
|
+
* Сообщает об исключении из пользовательского обработчика события; без логгера —
|
|
72
|
+
* в {@link fallbackLogger}.
|
|
76
73
|
*
|
|
77
74
|
* @param scope о чьих событиях речь — попадает в текст сообщения
|
|
78
75
|
*
|
|
79
76
|
* @internal
|
|
80
77
|
*/
|
|
81
78
|
function reportListenerError(logger, scope, error) {
|
|
82
|
-
|
|
83
|
-
if (logger) logger.error(message, error);
|
|
84
|
-
else console.error(`[itd-api] ${message}`, error);
|
|
79
|
+
(logger ?? require_redact.fallbackLogger).error(`Ошибка в обработчике события ${scope}`, error);
|
|
85
80
|
}
|
|
86
81
|
//#endregion
|
|
87
82
|
//#region src/events/middleware.ts
|
|
@@ -103,7 +98,7 @@ function withEventMiddlewareSnapshot(middleware, capture) {
|
|
|
103
98
|
function deferEventMiddleware(source) {
|
|
104
99
|
const capture = () => {
|
|
105
100
|
const middleware = source.middleware();
|
|
106
|
-
if (typeof middleware !== "function") throw new
|
|
101
|
+
if (typeof middleware !== "function") throw new require_validate.ItdConfigError("events middleware() должен возвращать функцию обработки");
|
|
107
102
|
return captureEventMiddleware(middleware);
|
|
108
103
|
};
|
|
109
104
|
const deferred = (context, next) => capture()(context, next);
|
|
@@ -320,25 +315,28 @@ function setEventChannelGiveUpHook(channel, hook) {
|
|
|
320
315
|
function resolveEventChannelOptions(options = {}) {
|
|
321
316
|
const positiveInteger = (value, name) => {
|
|
322
317
|
if (value === void 0) return;
|
|
323
|
-
if (!Number.isInteger(value) || value < 0) throw new
|
|
318
|
+
if (!Number.isInteger(value) || value < 0) throw new require_validate.ItdConfigError(`events.${name} должен быть целым неотрицательным числом, получено: ${value}`);
|
|
324
319
|
};
|
|
325
320
|
const duration = (value, name) => {
|
|
326
|
-
if (!Number.isFinite(value) || value < 0) throw new
|
|
321
|
+
if (!Number.isFinite(value) || value < 0) throw new require_validate.ItdConfigError(`events.${name} должен быть числом не меньше 0, получено: ${value}`);
|
|
327
322
|
};
|
|
328
323
|
positiveInteger(options.maxAttempts, "maxAttempts");
|
|
329
324
|
positiveInteger(options.concurrency, "concurrency");
|
|
330
|
-
if (options.concurrency === 0) throw new
|
|
331
|
-
if (options.jitter !== void 0 && !(options.jitter >= 0 && options.jitter <= 1)) throw new
|
|
325
|
+
if (options.concurrency === 0) throw new require_validate.ItdConfigError("events.concurrency должен быть больше нуля");
|
|
326
|
+
if (options.jitter !== void 0 && !(options.jitter >= 0 && options.jitter <= 1)) throw new require_validate.ItdConfigError(`events.jitter должен быть в диапазоне 0…1, получено: ${options.jitter}`);
|
|
332
327
|
if (options.backoff !== void 0) {
|
|
333
|
-
if (!Array.isArray(options.backoff) || options.backoff.length === 0) throw new
|
|
328
|
+
if (!Array.isArray(options.backoff) || options.backoff.length === 0) throw new require_validate.ItdConfigError("events.backoff должен быть непустым списком пауз");
|
|
334
329
|
for (const delay of options.backoff) duration(delay, "backoff");
|
|
335
330
|
}
|
|
336
|
-
if (options.sequentialize !== void 0 && typeof options.sequentialize !== "function") throw new
|
|
331
|
+
if (options.sequentialize !== void 0 && typeof options.sequentialize !== "function") throw new require_validate.ItdConfigError("events.sequentialize должен быть функцией");
|
|
337
332
|
return Object.freeze({
|
|
338
333
|
...options,
|
|
339
334
|
...options.backoff ? { backoff: Object.freeze([...options.backoff]) } : {}
|
|
340
335
|
});
|
|
341
336
|
}
|
|
337
|
+
function describe(error) {
|
|
338
|
+
return error instanceof Error ? error.message : String(error);
|
|
339
|
+
}
|
|
342
340
|
/**
|
|
343
341
|
* Общая механика потока событий: соединение, переподключение с задержкой, обновление
|
|
344
342
|
* токена, реакция на среду, статусы и очередь обработчиков.
|
|
@@ -419,7 +417,7 @@ var EventChannel = class {
|
|
|
419
417
|
/** Добавляет промежуточный обработчик. @returns функция его удаления */
|
|
420
418
|
use(middleware) {
|
|
421
419
|
if (typeof middleware === "function") return this.#dispatcher.use(middleware);
|
|
422
|
-
if (typeof middleware !== "object" || middleware === null || typeof middleware.middleware !== "function") throw new
|
|
420
|
+
if (typeof middleware !== "object" || middleware === null || typeof middleware.middleware !== "function") throw new require_validate.ItdConfigError("events.use() принимает функцию обработки или объект с middleware()");
|
|
423
421
|
return this.#dispatcher.use(deferEventMiddleware(middleware));
|
|
424
422
|
}
|
|
425
423
|
/** Подписывает обработчик обновлений, подходящих под условие. */
|
|
@@ -447,6 +445,7 @@ var EventChannel = class {
|
|
|
447
445
|
}
|
|
448
446
|
/** Закрывает соединение и отменяет запланированные попытки. */
|
|
449
447
|
disconnect() {
|
|
448
|
+
const wasActive = this.#wanted;
|
|
450
449
|
this.#wanted = false;
|
|
451
450
|
this.#generation += 1;
|
|
452
451
|
this.#starting = void 0;
|
|
@@ -456,10 +455,11 @@ var EventChannel = class {
|
|
|
456
455
|
}
|
|
457
456
|
this.#detachEnvironment?.();
|
|
458
457
|
this.#detachEnvironment = void 0;
|
|
459
|
-
this.#abortSession(new
|
|
458
|
+
this.#abortSession(new require_validate.ItdAbortError("Событийное соединение остановлено"));
|
|
460
459
|
this.#attempt = 0;
|
|
461
460
|
this.#dispatcher.clearPending();
|
|
462
461
|
this.#setStatus(require_url.EventChannelStatus.Disconnected);
|
|
462
|
+
if (wasActive) this.#deps.logger?.info("поток событий остановлен");
|
|
463
463
|
}
|
|
464
464
|
/**
|
|
465
465
|
* Ждёт обработчики и полное завершение уже остановленной сессии соединения.
|
|
@@ -491,9 +491,10 @@ var EventChannel = class {
|
|
|
491
491
|
const session = this.#session;
|
|
492
492
|
if (!this.#wanted || !session) return;
|
|
493
493
|
const generation = session.generation;
|
|
494
|
-
this.#abortSession(new
|
|
494
|
+
this.#abortSession(new require_validate.ItdAbortError("Очередь событий переполнена"));
|
|
495
495
|
this.#setStatus(require_url.EventChannelStatus.Error);
|
|
496
496
|
const error = /* @__PURE__ */ new Error("Обработчики не успевают за потоком: очередь обновлений переполнена");
|
|
497
|
+
this.#deps.logger?.warn("очередь обновлений потока переполнена; соединение восстановится, когда обработчики её разберут");
|
|
497
498
|
this.#dispatcher.drain().then(() => {
|
|
498
499
|
if (this.#isCurrentGeneration(generation) && !this.#session) this.#scheduleReconnect(error);
|
|
499
500
|
});
|
|
@@ -501,7 +502,7 @@ var EventChannel = class {
|
|
|
501
502
|
/** Создаёт новую попытку соединения и выполняет её подготовку. */
|
|
502
503
|
async #startAttempt(reason) {
|
|
503
504
|
if (!this.#wanted) return;
|
|
504
|
-
this.#abortSession(new
|
|
505
|
+
this.#abortSession(new require_validate.ItdAbortError("Событийное соединение заменено новой попыткой"));
|
|
505
506
|
const session = this.#createSession(++this.#generation);
|
|
506
507
|
this.#session = session;
|
|
507
508
|
try {
|
|
@@ -536,7 +537,7 @@ var EventChannel = class {
|
|
|
536
537
|
await task;
|
|
537
538
|
} catch (error) {
|
|
538
539
|
if (this.#deps.initializationRequired) throw error;
|
|
539
|
-
this.#deps.logger?.
|
|
540
|
+
this.#deps.logger?.warn(`не удалось синхронизировать поток событий (${reason})`, error);
|
|
540
541
|
}
|
|
541
542
|
}
|
|
542
543
|
/** Запускает транспорт одной попытки. */
|
|
@@ -548,9 +549,11 @@ var EventChannel = class {
|
|
|
548
549
|
signal: session.controller.signal,
|
|
549
550
|
onOpen: () => {
|
|
550
551
|
if (!this.#isCurrentSession(session)) return;
|
|
552
|
+
const reconnected = this.#attempt > 0;
|
|
551
553
|
this.#attempt = 0;
|
|
552
554
|
session.resolveOpened();
|
|
553
555
|
this.#setStatus(require_url.EventChannelStatus.Connected);
|
|
556
|
+
this.#deps.logger?.info(reconnected ? "поток событий переподключён" : "поток событий подключён");
|
|
554
557
|
},
|
|
555
558
|
onEvent: (event) => {
|
|
556
559
|
if (this.#isCurrentSession(session)) this.#handleEvent(session, event);
|
|
@@ -594,8 +597,7 @@ var EventChannel = class {
|
|
|
594
597
|
return;
|
|
595
598
|
}
|
|
596
599
|
const message = event === "middlewareError" ? "Ошибка в промежуточном обработчике потока" : "Ошибка в обработчике обновления потока";
|
|
597
|
-
|
|
598
|
-
else console.error(`[itd-api] ${message}`, error);
|
|
600
|
+
(this.#deps.logger ?? require_redact.fallbackLogger).error(message, error);
|
|
599
601
|
}
|
|
600
602
|
#handleFailure(error) {
|
|
601
603
|
this.#abortSession(error);
|
|
@@ -626,6 +628,7 @@ var EventChannel = class {
|
|
|
626
628
|
}
|
|
627
629
|
const delay = reconnectDelay(this.#attempt, this.#options);
|
|
628
630
|
this.#attempt += 1;
|
|
631
|
+
this.#deps.logger?.warn(`поток событий оборван (${describe(error)}); переподключение ${this.#attempt} из ${this.#maxAttempts} через ${delay} мс`);
|
|
629
632
|
this.#emitEngine("error", {
|
|
630
633
|
error,
|
|
631
634
|
willReconnect: true
|
|
@@ -663,6 +666,7 @@ var EventChannel = class {
|
|
|
663
666
|
this.#abortSession(error);
|
|
664
667
|
this.#detachEnvironment?.();
|
|
665
668
|
this.#detachEnvironment = void 0;
|
|
669
|
+
this.#deps.logger?.warn(`поток событий остановлен без переподключения (${describe(error)}); для возобновления вызовите connect()`);
|
|
666
670
|
EVENT_CHANNEL_GIVEUP_HOOKS.get(this)?.();
|
|
667
671
|
this.#emitEngine("error", {
|
|
668
672
|
error,
|
|
@@ -877,7 +881,7 @@ var PollTransport = class {
|
|
|
877
881
|
signal
|
|
878
882
|
});
|
|
879
883
|
} catch (error) {
|
|
880
|
-
if (
|
|
884
|
+
if (require_validate.isItdAuthError(error)) throw new UnauthorizedStreamError();
|
|
881
885
|
throw error;
|
|
882
886
|
}
|
|
883
887
|
}
|
|
@@ -908,82 +912,228 @@ var PollTransport = class {
|
|
|
908
912
|
}
|
|
909
913
|
};
|
|
910
914
|
//#endregion
|
|
911
|
-
//#region node_modules/eventsource-parser/dist/
|
|
915
|
+
//#region node_modules/eventsource-parser/dist/errors.js
|
|
916
|
+
/**
|
|
917
|
+
* Error thrown when encountering an issue during parsing.
|
|
918
|
+
*
|
|
919
|
+
* @public
|
|
920
|
+
*/
|
|
912
921
|
var ParseError = class extends Error {
|
|
913
922
|
constructor(message, options) {
|
|
914
|
-
super(message)
|
|
923
|
+
super(message);
|
|
924
|
+
this.name = "ParseError";
|
|
925
|
+
this.type = options.type;
|
|
926
|
+
this.field = options.field;
|
|
927
|
+
this.value = options.value;
|
|
928
|
+
this.line = options.line;
|
|
915
929
|
}
|
|
916
930
|
};
|
|
931
|
+
//#endregion
|
|
932
|
+
//#region node_modules/eventsource-parser/dist/parse.js
|
|
933
|
+
/**
|
|
934
|
+
* EventSource/Server-Sent Events parser
|
|
935
|
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html
|
|
936
|
+
*/
|
|
917
937
|
const LF = 10;
|
|
918
938
|
const CR = 13;
|
|
919
939
|
const SPACE = 32;
|
|
920
|
-
|
|
940
|
+
const MAX_FIELD_PREFIX_LENGTH = 6;
|
|
941
|
+
/**
|
|
942
|
+
* Creates a new EventSource parser.
|
|
943
|
+
*
|
|
944
|
+
* @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})
|
|
945
|
+
* and options like `maxBufferSize` (see {@link ParserConfig}).
|
|
946
|
+
*
|
|
947
|
+
* @returns A new EventSource parser, with `feed` and `reset` methods.
|
|
948
|
+
* @public
|
|
949
|
+
*/
|
|
921
950
|
function createParser(config) {
|
|
922
|
-
if (typeof config
|
|
923
|
-
const {
|
|
924
|
-
|
|
951
|
+
if (typeof config === "function") throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");
|
|
952
|
+
const { maxBufferSize, onComment, onError, onEvent, onId, onRetry } = config;
|
|
953
|
+
const pendingFragments = [];
|
|
954
|
+
let pendingFragmentsLength = 0;
|
|
955
|
+
let bomPrefix = "";
|
|
956
|
+
let id;
|
|
957
|
+
let data = "";
|
|
958
|
+
let dataLines = 0;
|
|
959
|
+
let eventType;
|
|
960
|
+
let terminated = false;
|
|
961
|
+
let skippingLine = false;
|
|
962
|
+
let skipNextLineFeed = false;
|
|
963
|
+
/**
|
|
964
|
+
* Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do
|
|
965
|
+
* not yet form a complete line are held back and prepended to the next chunk,
|
|
966
|
+
* so callers can pass arbitrary slices of the stream without worrying about
|
|
967
|
+
* line boundaries.
|
|
968
|
+
*
|
|
969
|
+
* Per the SSE spec, one leading UTF-8 BOM is stripped before parsing,
|
|
970
|
+
* even when split across chunks. This handles both the raw 3-byte form (0xEF 0xBB
|
|
971
|
+
* 0xBF) and a single decoded U+FEFF, so a leading BOM is ignored regardless of
|
|
972
|
+
* how the caller decoded the bytes.
|
|
973
|
+
*
|
|
974
|
+
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream
|
|
975
|
+
*/
|
|
925
976
|
function feed(chunk) {
|
|
926
977
|
if (terminated) throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");
|
|
927
|
-
if (
|
|
928
|
-
|
|
929
|
-
|
|
978
|
+
if (bomPrefix !== void 0) {
|
|
979
|
+
chunk = bomPrefix + chunk;
|
|
980
|
+
if (chunk === "" || chunk === "ï" || chunk === "ï»") {
|
|
981
|
+
bomPrefix = chunk;
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
bomPrefix = void 0;
|
|
985
|
+
chunk = chunk.replace(/^(?:\uFEFF|\xEF\xBB\xBF)/, "");
|
|
986
|
+
}
|
|
987
|
+
if (skippingLine || skipNextLineFeed) {
|
|
988
|
+
chunk = resumeAfterSkip(chunk);
|
|
989
|
+
if (!chunk) return;
|
|
990
|
+
}
|
|
991
|
+
if (!pendingFragments.length) {
|
|
992
|
+
const trailing = processLines(chunk);
|
|
993
|
+
if (trailing !== "") storeTrailing(trailing);
|
|
994
|
+
checkBufferSize();
|
|
930
995
|
return;
|
|
931
996
|
}
|
|
932
|
-
if (chunk.indexOf(
|
|
933
|
-
|
|
934
|
-
|
|
997
|
+
if (chunk.indexOf("\n") === -1 && chunk.indexOf("\r") === -1) {
|
|
998
|
+
if (pendingFragmentsLength < MAX_FIELD_PREFIX_LENGTH) {
|
|
999
|
+
if (!shouldBufferTrailing(pendingFragments.join("") + chunk.slice(0, MAX_FIELD_PREFIX_LENGTH - pendingFragmentsLength))) {
|
|
1000
|
+
pendingFragments.length = 0;
|
|
1001
|
+
pendingFragmentsLength = 0;
|
|
1002
|
+
skippingLine = true;
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
pendingFragments.push(chunk);
|
|
1007
|
+
pendingFragmentsLength += chunk.length;
|
|
1008
|
+
checkBufferSize();
|
|
935
1009
|
return;
|
|
936
1010
|
}
|
|
937
1011
|
pendingFragments.push(chunk);
|
|
938
1012
|
const input = pendingFragments.join("");
|
|
939
|
-
pendingFragments.length = 0
|
|
940
|
-
|
|
941
|
-
|
|
1013
|
+
pendingFragments.length = 0;
|
|
1014
|
+
pendingFragmentsLength = 0;
|
|
1015
|
+
storeTrailing(processLines(input));
|
|
1016
|
+
checkBufferSize();
|
|
1017
|
+
}
|
|
1018
|
+
function resumeAfterSkip(chunk) {
|
|
1019
|
+
if (chunk.length === 0) return chunk;
|
|
1020
|
+
if (skipNextLineFeed) {
|
|
1021
|
+
skipNextLineFeed = false;
|
|
1022
|
+
return chunk.charCodeAt(0) === LF ? chunk.slice(1) : chunk;
|
|
1023
|
+
}
|
|
1024
|
+
const crIndex = chunk.indexOf("\r");
|
|
1025
|
+
const lfIndex = chunk.indexOf("\n");
|
|
1026
|
+
const lineEnd = crIndex === -1 ? lfIndex : lfIndex === -1 ? crIndex : crIndex < lfIndex ? crIndex : lfIndex;
|
|
1027
|
+
if (lineEnd === -1) return "";
|
|
1028
|
+
if (lineEnd === chunk.length - 1 && chunk.charCodeAt(lineEnd) === CR) {
|
|
1029
|
+
skippingLine = false;
|
|
1030
|
+
skipNextLineFeed = true;
|
|
1031
|
+
return "";
|
|
1032
|
+
}
|
|
1033
|
+
skippingLine = false;
|
|
1034
|
+
return chunk.slice(lineEnd + (chunk.charCodeAt(lineEnd) === CR && chunk.charCodeAt(lineEnd + 1) === LF ? 2 : 1));
|
|
1035
|
+
}
|
|
1036
|
+
function storeTrailing(trailing) {
|
|
1037
|
+
if (!trailing) return;
|
|
1038
|
+
if (trailing.charCodeAt(trailing.length - 1) === CR) {
|
|
1039
|
+
parseLine(trailing, 0, trailing.length - 1);
|
|
1040
|
+
skipNextLineFeed = true;
|
|
1041
|
+
return;
|
|
1042
|
+
}
|
|
1043
|
+
if (shouldBufferTrailing(trailing)) {
|
|
1044
|
+
pendingFragments.push(trailing);
|
|
1045
|
+
pendingFragmentsLength = trailing.length;
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
skippingLine = true;
|
|
1049
|
+
}
|
|
1050
|
+
function shouldBufferTrailing(trailing) {
|
|
1051
|
+
const firstCharCode = trailing.charCodeAt(0);
|
|
1052
|
+
return firstCharCode === 58 && !!onComment || firstCharCode === 100 && isPotentialField(trailing, "data") || firstCharCode === 101 && isPotentialField(trailing, "event") || firstCharCode === 105 && isPotentialField(trailing, "id") || firstCharCode === 114 && isPotentialField(trailing, "retry");
|
|
942
1053
|
}
|
|
943
1054
|
function checkBufferSize() {
|
|
944
|
-
|
|
1055
|
+
if (maxBufferSize === void 0) return;
|
|
1056
|
+
if (pendingFragmentsLength + data.length <= maxBufferSize) return;
|
|
1057
|
+
terminated = true;
|
|
1058
|
+
pendingFragments.length = 0;
|
|
1059
|
+
pendingFragmentsLength = 0;
|
|
1060
|
+
id = void 0;
|
|
1061
|
+
data = "";
|
|
1062
|
+
dataLines = 0;
|
|
1063
|
+
eventType = void 0;
|
|
1064
|
+
skippingLine = false;
|
|
1065
|
+
skipNextLineFeed = false;
|
|
1066
|
+
onError === null || onError === void 0 || onError(new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, { type: "max-buffer-size-exceeded" }));
|
|
945
1067
|
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Splits `chunk` into SSE lines and dispatches each to the appropriate handler.
|
|
1070
|
+
* Returns any trailing bytes that did not terminate with a line break, so the
|
|
1071
|
+
* caller can prepend them to the next chunk.
|
|
1072
|
+
*
|
|
1073
|
+
* The SSE spec permits three line terminators: `\n`, `\r`, and `\r\n`. Real-world
|
|
1074
|
+
* streams almost always use plain `\n`, so we take a fast path when no `\r` is
|
|
1075
|
+
* present in the chunk. The slow path is spec-correct but does more work per line.
|
|
1076
|
+
*/
|
|
946
1077
|
function processLines(chunk) {
|
|
947
1078
|
let searchIndex = 0;
|
|
948
1079
|
if (chunk.indexOf("\r") === -1) {
|
|
949
|
-
let lfIndex = chunk.indexOf(
|
|
950
|
-
|
|
951
|
-
for (; lfIndex !== -1;) {
|
|
1080
|
+
let lfIndex = chunk.indexOf("\n", searchIndex);
|
|
1081
|
+
while (lfIndex !== -1) {
|
|
952
1082
|
if (searchIndex === lfIndex) {
|
|
953
|
-
|
|
1083
|
+
if (id !== void 0) onId === null || onId === void 0 || onId(id);
|
|
1084
|
+
if (dataLines > 0) onEvent === null || onEvent === void 0 || onEvent({
|
|
954
1085
|
id,
|
|
955
1086
|
event: eventType,
|
|
956
1087
|
data
|
|
957
|
-
})
|
|
958
|
-
|
|
1088
|
+
});
|
|
1089
|
+
id = void 0;
|
|
1090
|
+
data = "";
|
|
1091
|
+
dataLines = 0;
|
|
1092
|
+
eventType = void 0;
|
|
1093
|
+
searchIndex = lfIndex + 1;
|
|
1094
|
+
lfIndex = chunk.indexOf("\n", searchIndex);
|
|
959
1095
|
continue;
|
|
960
1096
|
}
|
|
961
1097
|
const firstCharCode = chunk.charCodeAt(searchIndex);
|
|
962
1098
|
if (isDataPrefix(chunk, searchIndex, firstCharCode)) {
|
|
963
|
-
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5
|
|
1099
|
+
const valueStart = chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5;
|
|
1100
|
+
const value = chunk.slice(valueStart, lfIndex);
|
|
964
1101
|
if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {
|
|
965
|
-
|
|
1102
|
+
if (id !== void 0) onId === null || onId === void 0 || onId(id);
|
|
1103
|
+
onEvent === null || onEvent === void 0 || onEvent({
|
|
966
1104
|
id,
|
|
967
1105
|
event: eventType,
|
|
968
1106
|
data: value
|
|
969
|
-
})
|
|
970
|
-
|
|
1107
|
+
});
|
|
1108
|
+
id = void 0;
|
|
1109
|
+
data = "";
|
|
1110
|
+
eventType = void 0;
|
|
1111
|
+
searchIndex = lfIndex + 2;
|
|
1112
|
+
lfIndex = chunk.indexOf("\n", searchIndex);
|
|
971
1113
|
continue;
|
|
972
1114
|
}
|
|
973
|
-
data = dataLines === 0 ? value : `${data}
|
|
974
|
-
|
|
975
|
-
} else isEventPrefix(chunk, searchIndex, firstCharCode)
|
|
976
|
-
|
|
977
|
-
|
|
1115
|
+
data = dataLines === 0 ? value : `${data}\n${value}`;
|
|
1116
|
+
dataLines++;
|
|
1117
|
+
} else if (isEventPrefix(chunk, searchIndex, firstCharCode)) eventType = chunk.slice(chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6, lfIndex) || void 0;
|
|
1118
|
+
else parseLine(chunk, searchIndex, lfIndex);
|
|
1119
|
+
searchIndex = lfIndex + 1;
|
|
1120
|
+
lfIndex = chunk.indexOf("\n", searchIndex);
|
|
978
1121
|
}
|
|
979
1122
|
return chunk.slice(searchIndex);
|
|
980
1123
|
}
|
|
981
|
-
|
|
982
|
-
const crIndex = chunk.indexOf("\r", searchIndex)
|
|
983
|
-
|
|
1124
|
+
while (searchIndex < chunk.length) {
|
|
1125
|
+
const crIndex = chunk.indexOf("\r", searchIndex);
|
|
1126
|
+
const lfIndex = chunk.indexOf("\n", searchIndex);
|
|
984
1127
|
let lineEnd = -1;
|
|
985
|
-
if (crIndex !== -1 && lfIndex !== -1
|
|
986
|
-
|
|
1128
|
+
if (crIndex !== -1 && lfIndex !== -1) lineEnd = crIndex < lfIndex ? crIndex : lfIndex;
|
|
1129
|
+
else if (crIndex !== -1) {
|
|
1130
|
+
if (crIndex === chunk.length - 1) lineEnd = -1;
|
|
1131
|
+
else lineEnd = crIndex;
|
|
1132
|
+
} else if (lfIndex !== -1) lineEnd = lfIndex;
|
|
1133
|
+
if (lineEnd === -1) break;
|
|
1134
|
+
parseLine(chunk, searchIndex, lineEnd);
|
|
1135
|
+
searchIndex = lineEnd + 1;
|
|
1136
|
+
if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) searchIndex++;
|
|
987
1137
|
}
|
|
988
1138
|
return chunk.slice(searchIndex);
|
|
989
1139
|
}
|
|
@@ -994,9 +1144,10 @@ ${value}`, dataLines++;
|
|
|
994
1144
|
}
|
|
995
1145
|
const firstCharCode = chunk.charCodeAt(start);
|
|
996
1146
|
if (isDataPrefix(chunk, start, firstCharCode)) {
|
|
997
|
-
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5
|
|
998
|
-
|
|
999
|
-
${
|
|
1147
|
+
const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5;
|
|
1148
|
+
const value = chunk.slice(valueStart, end);
|
|
1149
|
+
data = dataLines === 0 ? value : `${data}\n${value}`;
|
|
1150
|
+
dataLines++;
|
|
1000
1151
|
return;
|
|
1001
1152
|
}
|
|
1002
1153
|
if (isEventPrefix(chunk, start, firstCharCode)) {
|
|
@@ -1004,23 +1155,25 @@ ${value2}`, dataLines++;
|
|
|
1004
1155
|
return;
|
|
1005
1156
|
}
|
|
1006
1157
|
if (firstCharCode === 105 && chunk.charCodeAt(start + 1) === 100 && chunk.charCodeAt(start + 2) === 58) {
|
|
1007
|
-
const
|
|
1008
|
-
|
|
1158
|
+
const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end);
|
|
1159
|
+
if (!value.includes("\0")) id = value;
|
|
1009
1160
|
return;
|
|
1010
1161
|
}
|
|
1011
1162
|
if (firstCharCode === 58) {
|
|
1012
1163
|
if (onComment) {
|
|
1013
|
-
const
|
|
1014
|
-
onComment(
|
|
1164
|
+
const line = chunk.slice(start, end);
|
|
1165
|
+
onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1));
|
|
1015
1166
|
}
|
|
1016
1167
|
return;
|
|
1017
1168
|
}
|
|
1018
|
-
const line = chunk.slice(start, end)
|
|
1169
|
+
const line = chunk.slice(start, end);
|
|
1170
|
+
const fieldSeparatorIndex = line.indexOf(":");
|
|
1019
1171
|
if (fieldSeparatorIndex === -1) {
|
|
1020
1172
|
processField(line, "", line);
|
|
1021
1173
|
return;
|
|
1022
1174
|
}
|
|
1023
|
-
const field = line.slice(0, fieldSeparatorIndex)
|
|
1175
|
+
const field = line.slice(0, fieldSeparatorIndex);
|
|
1176
|
+
const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1;
|
|
1024
1177
|
processField(field, line.slice(fieldSeparatorIndex + offset), line);
|
|
1025
1178
|
}
|
|
1026
1179
|
function processField(field, value, line) {
|
|
@@ -1029,20 +1182,21 @@ ${value2}`, dataLines++;
|
|
|
1029
1182
|
eventType = value || void 0;
|
|
1030
1183
|
break;
|
|
1031
1184
|
case "data":
|
|
1032
|
-
data = dataLines === 0 ? value : `${data}
|
|
1033
|
-
|
|
1185
|
+
data = dataLines === 0 ? value : `${data}\n${value}`;
|
|
1186
|
+
dataLines++;
|
|
1034
1187
|
break;
|
|
1035
1188
|
case "id":
|
|
1036
|
-
value.includes("\0")
|
|
1189
|
+
if (!value.includes("\0")) id = value;
|
|
1037
1190
|
break;
|
|
1038
1191
|
case "retry":
|
|
1039
|
-
/^\d+$/.test(value)
|
|
1192
|
+
if (/^\d+$/.test(value)) onRetry === null || onRetry === void 0 || onRetry(parseInt(value, 10));
|
|
1193
|
+
else onError === null || onError === void 0 || onError(new ParseError(`Invalid \`retry\` value: "${value}"`, {
|
|
1040
1194
|
type: "invalid-retry",
|
|
1041
1195
|
value,
|
|
1042
1196
|
line
|
|
1043
1197
|
}));
|
|
1044
1198
|
break;
|
|
1045
|
-
default: onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}
|
|
1199
|
+
default: onError === null || onError === void 0 || onError(new ParseError(`Unknown field "${field.length > 20 ? `${field.slice(0, 20)}…` : field}"`, {
|
|
1046
1200
|
type: "unknown-field",
|
|
1047
1201
|
field,
|
|
1048
1202
|
value,
|
|
@@ -1051,30 +1205,70 @@ ${value}`, dataLines++;
|
|
|
1051
1205
|
}
|
|
1052
1206
|
}
|
|
1053
1207
|
function dispatchEvent() {
|
|
1054
|
-
|
|
1208
|
+
if (id !== void 0) onId === null || onId === void 0 || onId(id);
|
|
1209
|
+
if (dataLines > 0) onEvent === null || onEvent === void 0 || onEvent({
|
|
1055
1210
|
id,
|
|
1056
1211
|
event: eventType,
|
|
1057
1212
|
data
|
|
1058
|
-
})
|
|
1213
|
+
});
|
|
1214
|
+
id = void 0;
|
|
1215
|
+
data = "";
|
|
1216
|
+
dataLines = 0;
|
|
1217
|
+
eventType = void 0;
|
|
1059
1218
|
}
|
|
1060
1219
|
function reset(options = {}) {
|
|
1061
1220
|
if (options.consume && pendingFragments.length > 0) {
|
|
1062
1221
|
const incompleteLine = pendingFragments.join("");
|
|
1063
1222
|
parseLine(incompleteLine, 0, incompleteLine.length);
|
|
1064
1223
|
}
|
|
1065
|
-
|
|
1224
|
+
bomPrefix = "";
|
|
1225
|
+
id = void 0;
|
|
1226
|
+
data = "";
|
|
1227
|
+
dataLines = 0;
|
|
1228
|
+
eventType = void 0;
|
|
1229
|
+
pendingFragments.length = 0;
|
|
1230
|
+
pendingFragmentsLength = 0;
|
|
1231
|
+
terminated = false;
|
|
1232
|
+
skippingLine = false;
|
|
1233
|
+
skipNextLineFeed = false;
|
|
1066
1234
|
}
|
|
1067
1235
|
return {
|
|
1068
1236
|
feed,
|
|
1069
1237
|
reset
|
|
1070
1238
|
};
|
|
1071
1239
|
}
|
|
1240
|
+
/**
|
|
1241
|
+
* Checks if `chunk` starts with the literal `data:` at index `i`.
|
|
1242
|
+
*
|
|
1243
|
+
* Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this
|
|
1244
|
+
* hand-unrolled char-code comparison is ~20% faster on common event types.
|
|
1245
|
+
* The caller passes `firstCharCode` (the code at `i`) so it can be reused
|
|
1246
|
+
* across prefix checks.
|
|
1247
|
+
*
|
|
1248
|
+
* ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58
|
|
1249
|
+
*/
|
|
1072
1250
|
function isDataPrefix(chunk, i, firstCharCode) {
|
|
1073
1251
|
return firstCharCode === 100 && chunk.charCodeAt(i + 1) === 97 && chunk.charCodeAt(i + 2) === 116 && chunk.charCodeAt(i + 3) === 97 && chunk.charCodeAt(i + 4) === 58;
|
|
1074
1252
|
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Checks if `chunk` starts with the literal `event:` at index `i`.
|
|
1255
|
+
*
|
|
1256
|
+
* See {@link isDataPrefix} for why this is hand-unrolled rather than using
|
|
1257
|
+
* `String.prototype.startsWith`.
|
|
1258
|
+
*
|
|
1259
|
+
* ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58
|
|
1260
|
+
*/
|
|
1075
1261
|
function isEventPrefix(chunk, i, firstCharCode) {
|
|
1076
1262
|
return firstCharCode === 101 && chunk.charCodeAt(i + 1) === 118 && chunk.charCodeAt(i + 2) === 101 && chunk.charCodeAt(i + 3) === 110 && chunk.charCodeAt(i + 4) === 116 && chunk.charCodeAt(i + 5) === 58;
|
|
1077
1263
|
}
|
|
1264
|
+
function isPotentialField(line, field) {
|
|
1265
|
+
let i = 1;
|
|
1266
|
+
while (i < line.length && i < field.length) {
|
|
1267
|
+
if (line.charCodeAt(i) !== field.charCodeAt(i)) return false;
|
|
1268
|
+
i++;
|
|
1269
|
+
}
|
|
1270
|
+
return line.length <= field.length || line.charCodeAt(field.length) === 58;
|
|
1271
|
+
}
|
|
1078
1272
|
//#endregion
|
|
1079
1273
|
//#region src/events/transports/sse.ts
|
|
1080
1274
|
/** Путь потока уведомлений. */
|
|
@@ -1202,22 +1396,22 @@ const NotificationUpdateOrigin = Object.freeze({
|
|
|
1202
1396
|
/** Проверяет форму фильтра уведомлений. */
|
|
1203
1397
|
function validateNotificationSelector(selector) {
|
|
1204
1398
|
if (typeof selector === "string") {
|
|
1205
|
-
if (selector.length === 0) throw new
|
|
1399
|
+
if (selector.length === 0) throw new require_validate.ItdConfigError("Тип уведомления не должен быть пустым");
|
|
1206
1400
|
return;
|
|
1207
1401
|
}
|
|
1208
1402
|
if (Array.isArray(selector)) {
|
|
1209
|
-
if (selector.length === 0 || selector.some((type) => typeof type !== "string" || !type)) throw new
|
|
1403
|
+
if (selector.length === 0 || selector.some((type) => typeof type !== "string" || !type)) throw new require_validate.ItdConfigError("Список типов уведомлений должен содержать непустые строки");
|
|
1210
1404
|
return;
|
|
1211
1405
|
}
|
|
1212
|
-
if (typeof selector !== "object" || selector === null) throw new
|
|
1406
|
+
if (typeof selector !== "object" || selector === null) throw new require_validate.ItdConfigError("Фильтр уведомлений должен быть строкой, списком или объектом");
|
|
1213
1407
|
const filter = selector;
|
|
1214
1408
|
if (filter.type !== void 0) validateNotificationSelector(filter.type);
|
|
1215
|
-
if (filter.actorId !== void 0 && typeof filter.actorId !== "string") throw new
|
|
1409
|
+
if (filter.actorId !== void 0 && typeof filter.actorId !== "string") throw new require_validate.ItdConfigError("Фильтр уведомлений: actorId должен быть строкой");
|
|
1216
1410
|
for (const field of ["entityId", "parentEntityId"]) {
|
|
1217
1411
|
const value = filter[field];
|
|
1218
|
-
if (value !== void 0 && value !== null && typeof value !== "string") throw new
|
|
1412
|
+
if (value !== void 0 && value !== null && typeof value !== "string") throw new require_validate.ItdConfigError(`Фильтр уведомлений: ${field} должен быть строкой или null`);
|
|
1219
1413
|
}
|
|
1220
|
-
if (filter.predicate !== void 0 && typeof filter.predicate !== "function") throw new
|
|
1414
|
+
if (filter.predicate !== void 0 && typeof filter.predicate !== "function") throw new require_validate.ItdConfigError("Фильтр уведомлений: predicate должен быть функцией");
|
|
1221
1415
|
}
|
|
1222
1416
|
/** Преобразует транспортный кадр в одно логическое обновление. */
|
|
1223
1417
|
function readNotificationEventsUpdate(event) {
|
|
@@ -1271,7 +1465,7 @@ function resolveNotificationEventsOptions(options = {}) {
|
|
|
1271
1465
|
resolveEventChannelOptions(options);
|
|
1272
1466
|
const duration = (value, name, min) => {
|
|
1273
1467
|
if (value === void 0) return;
|
|
1274
|
-
if (!Number.isFinite(value) || value < min) throw new
|
|
1468
|
+
if (!Number.isFinite(value) || value < min) throw new require_validate.ItdConfigError(`events.notifications.${name} должен быть числом не меньше ${min}, получено: ${value}`);
|
|
1275
1469
|
};
|
|
1276
1470
|
duration(options.pollInterval, "pollInterval", 1);
|
|
1277
1471
|
duration(options.idleTimeout, "idleTimeout", 0);
|
|
@@ -1382,8 +1576,8 @@ var NotificationEvents = class {
|
|
|
1382
1576
|
onUpdate(selectorOrHandler, selectedHandler) {
|
|
1383
1577
|
const selectAll = selectedHandler === void 0;
|
|
1384
1578
|
const handler = selectAll ? selectorOrHandler : selectedHandler;
|
|
1385
|
-
if (typeof handler !== "function") throw new
|
|
1386
|
-
if (!selectAll && typeof selectorOrHandler !== "function" && !Object.values(NotificationUpdateType).includes(selectorOrHandler)) throw new
|
|
1579
|
+
if (typeof handler !== "function") throw new require_validate.ItdConfigError("events.onUpdate() принимает функцию обработчика");
|
|
1580
|
+
if (!selectAll && typeof selectorOrHandler !== "function" && !Object.values(NotificationUpdateType).includes(selectorOrHandler)) throw new require_validate.ItdConfigError(`Неизвестный тип обновления потока: ${String(selectorOrHandler)}`);
|
|
1387
1581
|
let predicate;
|
|
1388
1582
|
if (selectAll) predicate = () => true;
|
|
1389
1583
|
else {
|
|
@@ -1393,7 +1587,7 @@ var NotificationEvents = class {
|
|
|
1393
1587
|
return this.#engine.onUpdate(predicate, handler);
|
|
1394
1588
|
}
|
|
1395
1589
|
onNotification(selector, handler) {
|
|
1396
|
-
if (typeof handler !== "function") throw new
|
|
1590
|
+
if (typeof handler !== "function") throw new require_validate.ItdConfigError("events.onNotification() принимает функцию обработчика");
|
|
1397
1591
|
if (typeof selector !== "function") validateNotificationSelector(selector);
|
|
1398
1592
|
const predicate = (context) => {
|
|
1399
1593
|
if (!isNotificationContext(context)) return false;
|
|
@@ -1480,7 +1674,7 @@ function createTransport(deps, options) {
|
|
|
1480
1674
|
const kind = options.transport ?? NotificationEventsTransport.Auto;
|
|
1481
1675
|
if (typeof kind === "object") return kind;
|
|
1482
1676
|
if (kind === NotificationEventsTransport.Poll || kind === NotificationEventsTransport.Auto && !require_redact.supportsStreamingBody()) {
|
|
1483
|
-
if (!deps.request) throw new
|
|
1677
|
+
if (!deps.request) throw new require_validate.ItdConfigError("Poll transport requires a notification request adapter");
|
|
1484
1678
|
return new PollTransport({
|
|
1485
1679
|
request: deps.request,
|
|
1486
1680
|
...deps.clock ? { clock: deps.clock } : {},
|
|
@@ -1508,7 +1702,7 @@ const OPEN = 1;
|
|
|
1508
1702
|
const NORMAL_CLOSURE = 1e3;
|
|
1509
1703
|
const UNAUTHORIZED_CLOSE_CODES = /* @__PURE__ */ new Set([1008, 4401]);
|
|
1510
1704
|
function validateDuration(value, name) {
|
|
1511
|
-
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new
|
|
1705
|
+
if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new require_validate.ItdConfigError(`WebSocketTransport.${name} должен быть числом не меньше 0, получено: ${value}`);
|
|
1512
1706
|
}
|
|
1513
1707
|
function isWebSocketConnection(value) {
|
|
1514
1708
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -1565,12 +1759,12 @@ var WebSocketTransport = class {
|
|
|
1565
1759
|
#clock;
|
|
1566
1760
|
constructor(options = {}) {
|
|
1567
1761
|
const path = options.path ?? "/api/ws";
|
|
1568
|
-
if (typeof path !== "string" || path.trim() === "" || path.includes("?") || path.includes("#") || /^[a-z][a-z\d+.-]*:/i.test(path)) throw new
|
|
1569
|
-
if (options.webSocketImpl !== void 0 && typeof options.webSocketImpl !== "function") throw new
|
|
1570
|
-
if (options.classifyOpenFailure !== void 0 && typeof options.classifyOpenFailure !== "function") throw new
|
|
1762
|
+
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");
|
|
1763
|
+
if (options.webSocketImpl !== void 0 && typeof options.webSocketImpl !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.webSocketImpl должен быть конструктором");
|
|
1764
|
+
if (options.classifyOpenFailure !== void 0 && typeof options.classifyOpenFailure !== "function") throw new require_validate.ItdConfigError("WebSocketTransport.classifyOpenFailure должен быть функцией");
|
|
1571
1765
|
const auth = options.auth ?? "auto";
|
|
1572
|
-
if (auth !== "auto" && auth !== "query" && auth !== "header") throw new
|
|
1573
|
-
if (auth === "header" && !options.webSocketImpl) throw new
|
|
1766
|
+
if (auth !== "auto" && auth !== "query" && auth !== "header") throw new require_validate.ItdConfigError(`Неизвестный способ авторизации WebSocket: ${String(auth)}`);
|
|
1767
|
+
if (auth === "header" && !options.webSocketImpl) throw new require_validate.ItdConfigError("WebSocketTransport.auth=\"header\" требует webSocketImpl с поддержкой заголовков");
|
|
1574
1768
|
validateDuration(options.idleTimeout, "idleTimeout");
|
|
1575
1769
|
validateDuration(options.keepAlive, "keepAlive");
|
|
1576
1770
|
validateDuration(options.handshakeTimeout, "handshakeTimeout");
|
|
@@ -1610,7 +1804,7 @@ var WebSocketTransport = class {
|
|
|
1610
1804
|
const detail = safeDetail(error, url, token);
|
|
1611
1805
|
throw new Error(`Не удалось создать WebSocket ${require_redact.redactUrl(url)}${detail ? `: ${detail}` : ""}`);
|
|
1612
1806
|
}
|
|
1613
|
-
if (!isWebSocketConnection(value)) throw new
|
|
1807
|
+
if (!isWebSocketConnection(value)) throw new require_validate.ItdConfigError("webSocketImpl вернул объект без WebSocket-методов addEventListener, send и close");
|
|
1614
1808
|
try {
|
|
1615
1809
|
value.binaryType = "arraybuffer";
|
|
1616
1810
|
} catch {}
|
|
@@ -1618,7 +1812,7 @@ var WebSocketTransport = class {
|
|
|
1618
1812
|
}
|
|
1619
1813
|
#globalImplementation() {
|
|
1620
1814
|
const implementation = Reflect.get(globalThis, "WebSocket");
|
|
1621
|
-
if (typeof implementation !== "function") throw new
|
|
1815
|
+
if (typeof implementation !== "function") throw new require_validate.ItdConfigError("В этой среде нет WebSocket: передайте реализацию через webSocketImpl");
|
|
1622
1816
|
return implementation;
|
|
1623
1817
|
}
|
|
1624
1818
|
#urls(baseUrl) {
|
|
@@ -1626,7 +1820,7 @@ var WebSocketTransport = class {
|
|
|
1626
1820
|
const socket = new URL(request);
|
|
1627
1821
|
if (request.protocol === "https:") socket.protocol = "wss:";
|
|
1628
1822
|
else if (request.protocol === "http:") socket.protocol = "ws:";
|
|
1629
|
-
else throw new
|
|
1823
|
+
else throw new require_validate.ItdConfigError(`WebSocketTransport требует baseUrl с http или https, получено: ${request.protocol}`);
|
|
1630
1824
|
return {
|
|
1631
1825
|
requestUrl: request.toString(),
|
|
1632
1826
|
socketUrl: socket.toString()
|
|
@@ -1847,7 +2041,7 @@ var NotificationEventsClient = class NotificationEventsClient extends Notificati
|
|
|
1847
2041
|
this.#runtime = runtime;
|
|
1848
2042
|
setNotificationEventsConnectGuard(this, () => {
|
|
1849
2043
|
if (!this.#disposed) return;
|
|
1850
|
-
throw new
|
|
2044
|
+
throw new require_validate.ItdStateError("Поток уже окончательно освобождён через dispose(); нельзя подключить его снова. Создайте новый");
|
|
1851
2045
|
});
|
|
1852
2046
|
}
|
|
1853
2047
|
/**
|
|
@@ -1949,12 +2143,12 @@ var EventRouter = class {
|
|
|
1949
2143
|
#routes = /* @__PURE__ */ new Map();
|
|
1950
2144
|
#fallback = [];
|
|
1951
2145
|
constructor(selector) {
|
|
1952
|
-
if (typeof selector !== "function") throw new
|
|
2146
|
+
if (typeof selector !== "function") throw new require_validate.ItdConfigError("EventRouter принимает функцию выбора маршрута");
|
|
1953
2147
|
this.#selector = selector;
|
|
1954
2148
|
}
|
|
1955
2149
|
/** Добавляет промежуточные обработчики к маршруту и возвращает функцию их удаления. */
|
|
1956
2150
|
route(key, ...middleware) {
|
|
1957
|
-
if (!isPropertyKey(key)) throw new
|
|
2151
|
+
if (!isPropertyKey(key)) throw new require_validate.ItdConfigError("Ключ маршрута событий должен быть PropertyKey");
|
|
1958
2152
|
const registration = this.#registration(middleware);
|
|
1959
2153
|
const registrations = this.#routes.get(key) ?? [];
|
|
1960
2154
|
registrations.push(registration);
|
|
@@ -1987,7 +2181,7 @@ var EventRouter = class {
|
|
|
1987
2181
|
const fallback = this.#fallback.flatMap(({ middleware }) => middleware).map(captureEventMiddleware);
|
|
1988
2182
|
return async (context, next) => {
|
|
1989
2183
|
const key = await this.#selector(context);
|
|
1990
|
-
if (key != null && !isPropertyKey(key)) throw new
|
|
2184
|
+
if (key != null && !isPropertyKey(key)) throw new require_validate.ItdConfigError("Функция выбора маршрута должна возвращать PropertyKey, null или undefined");
|
|
1991
2185
|
const route = key == null ? void 0 : routes.get(key);
|
|
1992
2186
|
const chain = route && route.length > 0 ? route : fallback;
|
|
1993
2187
|
if (chain.length === 0) {
|
|
@@ -1998,8 +2192,8 @@ var EventRouter = class {
|
|
|
1998
2192
|
};
|
|
1999
2193
|
}
|
|
2000
2194
|
#registration(middleware) {
|
|
2001
|
-
if (middleware.length === 0) throw new
|
|
2002
|
-
for (const item of middleware) if (typeof item !== "function") throw new
|
|
2195
|
+
if (middleware.length === 0) throw new require_validate.ItdConfigError("Маршрут должен содержать хотя бы один обработчик");
|
|
2196
|
+
for (const item of middleware) if (typeof item !== "function") throw new require_validate.ItdConfigError("Маршрут принимает только функции обработки");
|
|
2003
2197
|
return { middleware: [...middleware] };
|
|
2004
2198
|
}
|
|
2005
2199
|
};
|
|
@@ -2010,12 +2204,12 @@ function isPropertyKey(value) {
|
|
|
2010
2204
|
//#region src/events/composer.ts
|
|
2011
2205
|
function middlewareFunction(middleware) {
|
|
2012
2206
|
if (typeof middleware === "function") return middleware;
|
|
2013
|
-
if (typeof middleware !== "object" || middleware === null || typeof middleware.middleware !== "function") throw new
|
|
2207
|
+
if (typeof middleware !== "object" || middleware === null || typeof middleware.middleware !== "function") throw new require_validate.ItdConfigError("EventComposer принимает функцию обработки или объект с middleware()");
|
|
2014
2208
|
return deferEventMiddleware(middleware);
|
|
2015
2209
|
}
|
|
2016
2210
|
function middlewareGroup(group) {
|
|
2017
2211
|
const middleware = Array.isArray(group) ? group : [group];
|
|
2018
|
-
if (middleware.length === 0) throw new
|
|
2212
|
+
if (middleware.length === 0) throw new require_validate.ItdConfigError("Ветка EventComposer должна содержать хотя бы один middleware");
|
|
2019
2213
|
return middleware.map((item) => middlewareFunction(item));
|
|
2020
2214
|
}
|
|
2021
2215
|
function boundaryContinuation() {
|
|
@@ -2077,7 +2271,7 @@ var EventComposer = class EventComposer {
|
|
|
2077
2271
|
return this;
|
|
2078
2272
|
}
|
|
2079
2273
|
filter(predicate, ...middleware) {
|
|
2080
|
-
if (typeof predicate !== "function") throw new
|
|
2274
|
+
if (typeof predicate !== "function") throw new require_validate.ItdConfigError("EventComposer.filter() принимает функцию условия");
|
|
2081
2275
|
const child = new EventComposer(...middleware);
|
|
2082
2276
|
this.#middleware.push(deferEventMiddleware({ middleware: () => {
|
|
2083
2277
|
const nested = captureEventMiddleware(child.middleware());
|
|
@@ -2095,7 +2289,7 @@ var EventComposer = class EventComposer {
|
|
|
2095
2289
|
* динамической регистрации и числовых ключей используйте {@link EventRouter} напрямую.
|
|
2096
2290
|
*/
|
|
2097
2291
|
route(selector, routes, fallback) {
|
|
2098
|
-
if (typeof routes !== "object" || routes === null || Array.isArray(routes)) throw new
|
|
2292
|
+
if (typeof routes !== "object" || routes === null || Array.isArray(routes)) throw new require_validate.ItdConfigError("EventComposer.route() принимает объект именованных веток");
|
|
2099
2293
|
const router = new EventRouter(selector);
|
|
2100
2294
|
let registrations = 0;
|
|
2101
2295
|
for (const key of Reflect.ownKeys(routes)) {
|
|
@@ -2108,7 +2302,7 @@ var EventComposer = class EventComposer {
|
|
|
2108
2302
|
router.otherwise(...middlewareGroup(fallback));
|
|
2109
2303
|
registrations += 1;
|
|
2110
2304
|
}
|
|
2111
|
-
if (registrations === 0) throw new
|
|
2305
|
+
if (registrations === 0) throw new require_validate.ItdConfigError("EventComposer.route() требует хотя бы одну ветку или fallback");
|
|
2112
2306
|
return this.use(router);
|
|
2113
2307
|
}
|
|
2114
2308
|
/**
|
|
@@ -2118,7 +2312,7 @@ var EventComposer = class EventComposer {
|
|
|
2118
2312
|
* продолжает внешнюю цепочку.
|
|
2119
2313
|
*/
|
|
2120
2314
|
errorBoundary(handler, ...middleware) {
|
|
2121
|
-
if (typeof handler !== "function") throw new
|
|
2315
|
+
if (typeof handler !== "function") throw new require_validate.ItdConfigError("EventComposer.errorBoundary() принимает обработчик ошибки");
|
|
2122
2316
|
const child = new EventComposer(...middleware);
|
|
2123
2317
|
this.#middleware.push(deferEventMiddleware({ middleware: () => {
|
|
2124
2318
|
const nested = captureEventMiddleware(child.middleware());
|
|
@@ -2258,4 +2452,4 @@ Object.defineProperty(exports, "setNotificationEventsConnectGuard", {
|
|
|
2258
2452
|
}
|
|
2259
2453
|
});
|
|
2260
2454
|
|
|
2261
|
-
//# sourceMappingURL=events-
|
|
2455
|
+
//# sourceMappingURL=events-C2DJZyI0.cjs.map
|