itd-api 0.2.0 → 0.3.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 +5 -4
- package/dist/index.cjs +652 -218
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +228 -42
- package/dist/index.d.ts +228 -42
- package/dist/index.js +649 -219
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -945,6 +945,22 @@ declare function toDate(value: IsoDate | null | undefined): Date | null;
|
|
|
945
945
|
*/
|
|
946
946
|
declare function statusDays(service: ServiceStatus): (StatusDay | null)[];
|
|
947
947
|
//#endregion
|
|
948
|
+
//#region src/core/clock.d.ts
|
|
949
|
+
/**
|
|
950
|
+
* Часы, которыми клиент измеряет время и планирует отложенную работу.
|
|
951
|
+
*
|
|
952
|
+
* Своя реализация нужна прежде всего в тестах: она позволяет проверять тайм-ауты,
|
|
953
|
+
* повторы и переподключение без ожидания в реальном времени.
|
|
954
|
+
*/
|
|
955
|
+
interface ItdClock {
|
|
956
|
+
/** Текущее время в миллисекундах с начала эпохи Unix. */
|
|
957
|
+
now(): number;
|
|
958
|
+
/** Планирует вызов после завершения текущего стека и возвращает функцию отмены. */
|
|
959
|
+
schedule(callback: () => void, delay: number): () => void;
|
|
960
|
+
}
|
|
961
|
+
/** Системные часы, используемые клиентом по умолчанию. */
|
|
962
|
+
declare const systemClock: ItdClock;
|
|
963
|
+
//#endregion
|
|
948
964
|
//#region src/core/runtime.d.ts
|
|
949
965
|
/**
|
|
950
966
|
* Как библиотека обращается с cookie.
|
|
@@ -1227,6 +1243,8 @@ interface ItdClientOptions {
|
|
|
1227
1243
|
reloginOnRefreshFailure?: boolean | undefined;
|
|
1228
1244
|
/** Своя реализация `fetch`: для Deno, React Native, тестов или прокси. */
|
|
1229
1245
|
fetch?: typeof fetch | undefined;
|
|
1246
|
+
/** Часы для тайм-аутов, повторов и очередей. Обычно подменяются только в тестах. */
|
|
1247
|
+
clock?: ItdClock | undefined;
|
|
1230
1248
|
/** Таймаут запроса в мс. По умолчанию 30000 — столько же использует сайт итд.com. `0` снимает ограничение. */
|
|
1231
1249
|
timeout?: number | undefined;
|
|
1232
1250
|
/** Повторные попытки. `false` отключает их полностью. */
|
|
@@ -1326,7 +1344,7 @@ interface RawRequestOptions extends RequestOptions {
|
|
|
1326
1344
|
//#endregion
|
|
1327
1345
|
//#region src/core/version.d.ts
|
|
1328
1346
|
/** Версия библиотеки. Попадает в `User-Agent`. */
|
|
1329
|
-
declare const LIBRARY_VERSION = "0.
|
|
1347
|
+
declare const LIBRARY_VERSION = "0.3.0";
|
|
1330
1348
|
//#endregion
|
|
1331
1349
|
//#region src/core/config.d.ts
|
|
1332
1350
|
/** Базовый URL API итд.com. Домен записан в punycode: `итд.com`. */
|
|
@@ -1349,7 +1367,7 @@ declare const DEFAULT_TIMEOUT = 30000;
|
|
|
1349
1367
|
* В браузере заголовок не выставляется — `User-Agent` там запрещён к изменению, и среда
|
|
1350
1368
|
* молча его игнорирует.
|
|
1351
1369
|
*/
|
|
1352
|
-
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.
|
|
1370
|
+
declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.3.0; +https://github.com/KiowDev/itd-api)";
|
|
1353
1371
|
/** Настройки очереди со всеми значениями по умолчанию. */
|
|
1354
1372
|
interface ResolvedRateLimitOptions {
|
|
1355
1373
|
concurrency: number;
|
|
@@ -1366,6 +1384,7 @@ interface ResolvedRateLimitOptions {
|
|
|
1366
1384
|
*/
|
|
1367
1385
|
interface AuthConfig {
|
|
1368
1386
|
baseUrl: string;
|
|
1387
|
+
clock: ItdClock;
|
|
1369
1388
|
auth: AuthInput | undefined;
|
|
1370
1389
|
storage: TokenStorage;
|
|
1371
1390
|
useCookieJar: boolean;
|
|
@@ -1872,7 +1891,7 @@ declare class PluginRegistry {
|
|
|
1872
1891
|
*/
|
|
1873
1892
|
declare class RequestQueue {
|
|
1874
1893
|
#private;
|
|
1875
|
-
constructor(options: ResolvedRateLimitOptions);
|
|
1894
|
+
constructor(options: ResolvedRateLimitOptions, clock?: ItdClock);
|
|
1876
1895
|
/** Сколько задач выполняется прямо сейчас. */
|
|
1877
1896
|
get active(): number;
|
|
1878
1897
|
/** Сколько задач ждёт очереди. */
|
|
@@ -1903,7 +1922,7 @@ declare class RequestQueue {
|
|
|
1903
1922
|
*/
|
|
1904
1923
|
declare class RequestQueuePool {
|
|
1905
1924
|
#private;
|
|
1906
|
-
constructor(options: ResolvedRateLimitOptions);
|
|
1925
|
+
constructor(options: ResolvedRateLimitOptions, clock?: ItdClock);
|
|
1907
1926
|
/** Очередь хоста. */
|
|
1908
1927
|
for(service: string | undefined): RequestQueue;
|
|
1909
1928
|
/** Останавливает все очереди. */
|
|
@@ -1960,32 +1979,6 @@ declare function readNotificationEvent(data: unknown): NotificationEvent;
|
|
|
1960
1979
|
*/
|
|
1961
1980
|
declare function readUnreadCountEvent(data: unknown): number | undefined;
|
|
1962
1981
|
//#endregion
|
|
1963
|
-
//#region src/realtime/reconnect.d.ts
|
|
1964
|
-
/**
|
|
1965
|
-
* Паузы перед попытками переподключения, мс.
|
|
1966
|
-
*
|
|
1967
|
-
* Значения совпадают с теми, что использует сайт итд.com, — поведение библиотеки
|
|
1968
|
-
* не отличается от привычного пользователю.
|
|
1969
|
-
*/
|
|
1970
|
-
declare const RECONNECT_BACKOFF: readonly number[];
|
|
1971
|
-
/** Доля случайного разброса паузы. */
|
|
1972
|
-
declare const RECONNECT_JITTER = 0.3;
|
|
1973
|
-
/**
|
|
1974
|
-
* Сколько раз пытаться переподключиться подряд.
|
|
1975
|
-
*
|
|
1976
|
-
* После исчерпания поток сообщает `giveup` и ждёт ручного `connect()`.
|
|
1977
|
-
*/
|
|
1978
|
-
declare const MAX_RECONNECT_ATTEMPTS = 15;
|
|
1979
|
-
/** Настройки переподключения. */
|
|
1980
|
-
interface ReconnectOptions {
|
|
1981
|
-
/** Таблица пауз. Последнее значение действует для всех дальнейших попыток. */
|
|
1982
|
-
backoff?: readonly number[];
|
|
1983
|
-
/** Доля разброса, 0…1. */
|
|
1984
|
-
jitter?: number;
|
|
1985
|
-
/** Предел числа попыток. */
|
|
1986
|
-
maxAttempts?: number;
|
|
1987
|
-
}
|
|
1988
|
-
//#endregion
|
|
1989
1982
|
//#region src/realtime/transport.d.ts
|
|
1990
1983
|
/** Событие, пришедшее по каналу реального времени. */
|
|
1991
1984
|
interface TransportEvent {
|
|
@@ -2041,6 +2034,120 @@ declare class UnauthorizedStreamError extends Error {
|
|
|
2041
2034
|
constructor();
|
|
2042
2035
|
}
|
|
2043
2036
|
//#endregion
|
|
2037
|
+
//#region src/realtime/updates.d.ts
|
|
2038
|
+
/** Типы нормализованных обновлений потока. */
|
|
2039
|
+
declare const RealtimeUpdateType: Readonly<{
|
|
2040
|
+
readonly Notification: "notification";
|
|
2041
|
+
readonly UnreadCount: "unreadCount";
|
|
2042
|
+
readonly Unknown: "unknown";
|
|
2043
|
+
}>;
|
|
2044
|
+
/** Источники нормализованных обновлений потока. */
|
|
2045
|
+
declare const RealtimeUpdateOrigin: Readonly<{
|
|
2046
|
+
readonly Stream: "stream";
|
|
2047
|
+
readonly Sync: "sync";
|
|
2048
|
+
}>;
|
|
2049
|
+
type RealtimeUpdateOrigin = (typeof RealtimeUpdateOrigin)[keyof typeof RealtimeUpdateOrigin];
|
|
2050
|
+
/** Уведомление с типом, суженным фильтром потока. */
|
|
2051
|
+
type NotificationOfType<T extends NotificationType> = Omit<Notification, 'type'> & {
|
|
2052
|
+
type: T;
|
|
2053
|
+
};
|
|
2054
|
+
/** Конверт уведомления с типом, суженным фильтром потока. */
|
|
2055
|
+
type NotificationEventOfType<T extends NotificationType> = Omit<NotificationEvent, 'notification'> & {
|
|
2056
|
+
notification: NotificationOfType<T>;
|
|
2057
|
+
};
|
|
2058
|
+
/** Нормализованное уведомление из потока. */
|
|
2059
|
+
interface RealtimeNotificationUpdate<T extends NotificationType = NotificationType> {
|
|
2060
|
+
readonly type: typeof RealtimeUpdateType.Notification;
|
|
2061
|
+
readonly data: NotificationEventOfType<T>;
|
|
2062
|
+
}
|
|
2063
|
+
/** Актуальное число непрочитанных уведомлений. */
|
|
2064
|
+
interface RealtimeUnreadCountUpdate {
|
|
2065
|
+
readonly type: typeof RealtimeUpdateType.UnreadCount;
|
|
2066
|
+
readonly data: number;
|
|
2067
|
+
}
|
|
2068
|
+
/** Неизвестное библиотеке событие потока. */
|
|
2069
|
+
interface RealtimeUnknownUpdate {
|
|
2070
|
+
readonly type: typeof RealtimeUpdateType.Unknown;
|
|
2071
|
+
readonly name: string;
|
|
2072
|
+
readonly data: unknown;
|
|
2073
|
+
}
|
|
2074
|
+
/** Данные, проходящие через промежуточные обработчики потока. */
|
|
2075
|
+
type RealtimeUpdate = RealtimeNotificationUpdate | RealtimeUnreadCountUpdate | RealtimeUnknownUpdate;
|
|
2076
|
+
/** Тип нормализованного обновления потока. */
|
|
2077
|
+
type RealtimeUpdateType = RealtimeUpdate['type'];
|
|
2078
|
+
/** Обновление потока указанного типа. */
|
|
2079
|
+
type RealtimeUpdateOfType<T extends RealtimeUpdateType> = Extract<RealtimeUpdate, {
|
|
2080
|
+
type: T;
|
|
2081
|
+
}>;
|
|
2082
|
+
/** Контекст обработки одного обновления потока. */
|
|
2083
|
+
interface RealtimeContext<U extends RealtimeUpdate = RealtimeUpdate> {
|
|
2084
|
+
/** Нормализованные данные обновления. */
|
|
2085
|
+
readonly update: U;
|
|
2086
|
+
/** Поток, который получил обновление. */
|
|
2087
|
+
readonly stream: ItdRealtime;
|
|
2088
|
+
/** Исходный кадр транспорта. Для начальной REST-синхронизации равен `undefined`. */
|
|
2089
|
+
readonly raw: TransportEvent | undefined;
|
|
2090
|
+
/** Откуда получены данные. */
|
|
2091
|
+
readonly origin: RealtimeUpdateOrigin;
|
|
2092
|
+
}
|
|
2093
|
+
/** Контекст уведомления с типом, суженным фильтром. */
|
|
2094
|
+
type RealtimeNotificationContext<T extends NotificationType = NotificationType> = RealtimeContext<RealtimeNotificationUpdate<T>>;
|
|
2095
|
+
/** Условия отбора уведомлений. Все указанные поля объединяются через логическое И. */
|
|
2096
|
+
interface RealtimeNotificationFilter<T extends NotificationType = NotificationType> {
|
|
2097
|
+
/** Один или несколько канонических типов уведомления. */
|
|
2098
|
+
type?: T | readonly T[];
|
|
2099
|
+
/** Идентификатор хотя бы одного участника уведомления. */
|
|
2100
|
+
actorId?: string;
|
|
2101
|
+
/** Идентификатор объекта события. */
|
|
2102
|
+
entityId?: string | null;
|
|
2103
|
+
/** Идентификатор родительского объекта. */
|
|
2104
|
+
parentEntityId?: string | null;
|
|
2105
|
+
/** Дополнительная проверка после сопоставления полей. */
|
|
2106
|
+
predicate?: (context: RealtimeNotificationContext<T>) => boolean;
|
|
2107
|
+
}
|
|
2108
|
+
/** Краткая или объектная форма фильтра уведомлений. */
|
|
2109
|
+
type RealtimeNotificationSelector<T extends NotificationType = NotificationType> = T | readonly T[] | RealtimeNotificationFilter<T>;
|
|
2110
|
+
//#endregion
|
|
2111
|
+
//#region src/realtime/middleware.d.ts
|
|
2112
|
+
/** Продолжает цепочку промежуточных обработчиков потока. */
|
|
2113
|
+
type RealtimeNext = () => Promise<void>;
|
|
2114
|
+
/** Обрабатывает обновление потока до его передачи подписчикам. */
|
|
2115
|
+
type RealtimeMiddleware<C extends RealtimeContext = RealtimeContext> = (context: C, next: RealtimeNext) => void | Promise<void>;
|
|
2116
|
+
/** Асинхронный обработчик нормализованного обновления потока. */
|
|
2117
|
+
type RealtimeHandler<C extends RealtimeContext = RealtimeContext> = (context: C) => unknown | Promise<unknown>;
|
|
2118
|
+
/** Условие отбора контекста потока. */
|
|
2119
|
+
type RealtimePredicate = (context: RealtimeContext) => boolean;
|
|
2120
|
+
/** Проверка, сужающая тип контекста потока. */
|
|
2121
|
+
type RealtimeTypeGuard<C extends RealtimeContext> = (context: RealtimeContext) => context is C;
|
|
2122
|
+
/** Ключи, по которым обновления нельзя обрабатывать одновременно. */
|
|
2123
|
+
type RealtimeSequentializer = (context: RealtimeContext) => PropertyKey | readonly PropertyKey[] | undefined;
|
|
2124
|
+
//#endregion
|
|
2125
|
+
//#region src/realtime/reconnect.d.ts
|
|
2126
|
+
/**
|
|
2127
|
+
* Паузы перед попытками переподключения, мс.
|
|
2128
|
+
*
|
|
2129
|
+
* Значения совпадают с теми, что использует сайт итд.com, — поведение библиотеки
|
|
2130
|
+
* не отличается от привычного пользователю.
|
|
2131
|
+
*/
|
|
2132
|
+
declare const RECONNECT_BACKOFF: readonly number[];
|
|
2133
|
+
/** Доля случайного разброса паузы. */
|
|
2134
|
+
declare const RECONNECT_JITTER = 0.3;
|
|
2135
|
+
/**
|
|
2136
|
+
* Сколько раз пытаться переподключиться подряд.
|
|
2137
|
+
*
|
|
2138
|
+
* После исчерпания поток сообщает `giveup` и ждёт ручного `connect()`.
|
|
2139
|
+
*/
|
|
2140
|
+
declare const MAX_RECONNECT_ATTEMPTS = 15;
|
|
2141
|
+
/** Настройки переподключения. */
|
|
2142
|
+
interface ReconnectOptions {
|
|
2143
|
+
/** Таблица пауз. Последнее значение действует для всех дальнейших попыток. */
|
|
2144
|
+
backoff?: readonly number[];
|
|
2145
|
+
/** Доля разброса, 0…1. */
|
|
2146
|
+
jitter?: number;
|
|
2147
|
+
/** Предел числа попыток. */
|
|
2148
|
+
maxAttempts?: number;
|
|
2149
|
+
}
|
|
2150
|
+
//#endregion
|
|
2044
2151
|
//#region src/realtime/stream.d.ts
|
|
2045
2152
|
/** События потока уведомлений. */
|
|
2046
2153
|
interface RealtimeEvents {
|
|
@@ -2081,10 +2188,17 @@ interface RealtimeEvents {
|
|
|
2081
2188
|
};
|
|
2082
2189
|
/** Попытки исчерпаны — соединение восстановится только ручным `connect()`. */
|
|
2083
2190
|
giveup: undefined;
|
|
2084
|
-
/**
|
|
2085
|
-
message:
|
|
2086
|
-
|
|
2087
|
-
|
|
2191
|
+
/** Любой исходный кадр транспорта. Отправляется до нормализации и промежуточных обработчиков. */
|
|
2192
|
+
message: TransportEvent;
|
|
2193
|
+
/** Промежуточный обработчик потока завершился исключением. */
|
|
2194
|
+
middlewareError: {
|
|
2195
|
+
error: unknown;
|
|
2196
|
+
context: RealtimeContext;
|
|
2197
|
+
};
|
|
2198
|
+
/** Обработчик `onUpdate` завершился исключением. */
|
|
2199
|
+
handlerError: {
|
|
2200
|
+
error: unknown;
|
|
2201
|
+
context: RealtimeContext;
|
|
2088
2202
|
};
|
|
2089
2203
|
}
|
|
2090
2204
|
/** Способ получения событий. */
|
|
@@ -2138,11 +2252,16 @@ interface RealtimeOptions extends ReconnectOptions {
|
|
|
2138
2252
|
reconnectOnVisible?: boolean;
|
|
2139
2253
|
/** Переподключаться при восстановлении сети. По умолчанию `true`. Только в браузере. */
|
|
2140
2254
|
reconnectOnOnline?: boolean;
|
|
2255
|
+
/** Максимальное число одновременно обрабатываемых обновлений. По умолчанию 1. */
|
|
2256
|
+
concurrency?: number;
|
|
2257
|
+
/** Возвращает ключи обновлений, которые нельзя обрабатывать одновременно. */
|
|
2258
|
+
sequentialize?: RealtimeSequentializer;
|
|
2141
2259
|
}
|
|
2142
2260
|
/** Что поток получает от клиента. */
|
|
2143
2261
|
interface RealtimeDeps {
|
|
2144
2262
|
baseUrl: string;
|
|
2145
2263
|
fetch: typeof fetch;
|
|
2264
|
+
clock?: ItdClock;
|
|
2146
2265
|
/** Общие заголовки клиента для адреса — см. {@link TransportContext.baseHeaders}. */
|
|
2147
2266
|
baseHeaders: (url: string) => Promise<Headers>;
|
|
2148
2267
|
/** Идентификаторы аккаунта и сессии создавшего поток клиента. */
|
|
@@ -2156,6 +2275,8 @@ interface RealtimeDeps {
|
|
|
2156
2275
|
fetchUnreadCount: () => Promise<number>;
|
|
2157
2276
|
/** Вызывается при явном закрытии потока. */
|
|
2158
2277
|
onClose?: (() => void) | undefined;
|
|
2278
|
+
/** Вызывается при запуске ранее закрытого потока. */
|
|
2279
|
+
onConnect?: (() => void) | undefined;
|
|
2159
2280
|
logger?: Logger | undefined;
|
|
2160
2281
|
}
|
|
2161
2282
|
/**
|
|
@@ -2166,16 +2287,19 @@ interface RealtimeDeps {
|
|
|
2166
2287
|
*
|
|
2167
2288
|
* @example
|
|
2168
2289
|
* ```ts
|
|
2290
|
+
* import { NotificationType } from 'itd-api';
|
|
2291
|
+
*
|
|
2169
2292
|
* const stream = itd.realtime();
|
|
2170
2293
|
*
|
|
2171
|
-
* stream.
|
|
2172
|
-
*
|
|
2294
|
+
* stream.onNotification(NotificationType.PostComment, async ({ update }) => {
|
|
2295
|
+
* await saveCommentNotification(update.data.notification);
|
|
2173
2296
|
* });
|
|
2174
2297
|
* stream.on('status', (status) => console.log('соединение:', status));
|
|
2175
2298
|
*
|
|
2176
2299
|
* await stream.connect();
|
|
2177
2300
|
* // …позже
|
|
2178
2301
|
* stream.disconnect();
|
|
2302
|
+
* await stream.drain();
|
|
2179
2303
|
* ```
|
|
2180
2304
|
*/
|
|
2181
2305
|
declare class ItdRealtime {
|
|
@@ -2195,6 +2319,29 @@ declare class ItdRealtime {
|
|
|
2195
2319
|
on<K extends keyof RealtimeEvents>(event: K, listener: Listener<RealtimeEvents[K]>): Unsubscribe;
|
|
2196
2320
|
/** Подписывается на одно срабатывание. */
|
|
2197
2321
|
once<K extends keyof RealtimeEvents>(event: K, listener: Listener<RealtimeEvents[K]>): Unsubscribe;
|
|
2322
|
+
/**
|
|
2323
|
+
* Добавляет промежуточный обработчик нормализованных обновлений.
|
|
2324
|
+
*
|
|
2325
|
+
* Обработчики выполняются в порядке регистрации. Если `next()` не вызван, обновление не
|
|
2326
|
+
* передаётся дальше по цепочке, асинхронным обработчикам и слушателям событий.
|
|
2327
|
+
*
|
|
2328
|
+
* @returns функция удаления обработчика
|
|
2329
|
+
*/
|
|
2330
|
+
use(middleware: RealtimeMiddleware): Unsubscribe;
|
|
2331
|
+
/** Подписывает асинхронный обработчик на все нормализованные обновления. */
|
|
2332
|
+
onUpdate(handler: RealtimeHandler): Unsubscribe;
|
|
2333
|
+
/** Подписывает асинхронный обработчик на обновление указанного типа. */
|
|
2334
|
+
onUpdate<T extends RealtimeUpdateType>(type: T, handler: RealtimeHandler<RealtimeContext<RealtimeUpdateOfType<T>>>): Unsubscribe;
|
|
2335
|
+
/** Подписывает асинхронный обработчик по функции сужения типа. */
|
|
2336
|
+
onUpdate<C extends RealtimeContext>(guard: RealtimeTypeGuard<C>, handler: RealtimeHandler<C>): Unsubscribe;
|
|
2337
|
+
/** Подписывает асинхронный обработчик по пользовательскому условию. */
|
|
2338
|
+
onUpdate(predicate: RealtimePredicate, handler: RealtimeHandler): Unsubscribe;
|
|
2339
|
+
/** Подписывает асинхронный обработчик на уведомления, подходящие под фильтр. */
|
|
2340
|
+
onNotification<T extends NotificationType>(selector: RealtimeNotificationSelector<T>, handler: RealtimeHandler<RealtimeNotificationContext<T>>): Unsubscribe;
|
|
2341
|
+
/** Подписывает асинхронный обработчик по функции сужения типа уведомления. */
|
|
2342
|
+
onNotification<C extends RealtimeNotificationContext>(guard: (context: RealtimeNotificationContext) => context is C, handler: RealtimeHandler<C>): Unsubscribe;
|
|
2343
|
+
/** Подписывает асинхронный обработчик по пользовательскому условию. */
|
|
2344
|
+
onNotification(predicate: (context: RealtimeNotificationContext) => boolean, handler: RealtimeHandler<RealtimeNotificationContext>): Unsubscribe;
|
|
2198
2345
|
/**
|
|
2199
2346
|
* Поднимает соединение.
|
|
2200
2347
|
*
|
|
@@ -2206,7 +2353,9 @@ declare class ItdRealtime {
|
|
|
2206
2353
|
connect(): Promise<void>;
|
|
2207
2354
|
/** Закрывает соединение и отменяет запланированные попытки. */
|
|
2208
2355
|
disconnect(): void;
|
|
2209
|
-
/**
|
|
2356
|
+
/** Ждёт завершения всех принятых обновлений. */
|
|
2357
|
+
drain(): Promise<void>;
|
|
2358
|
+
/** Снимает подписки `on()` и `once()`. Остальные обработчики остаются. */
|
|
2210
2359
|
removeAllListeners(): void;
|
|
2211
2360
|
}
|
|
2212
2361
|
//#endregion
|
|
@@ -4189,10 +4338,12 @@ declare class ItdClient {
|
|
|
4189
4338
|
*
|
|
4190
4339
|
* @example
|
|
4191
4340
|
* ```ts
|
|
4341
|
+
* import { NotificationType } from 'itd-api';
|
|
4342
|
+
*
|
|
4192
4343
|
* const stream = itd.realtime();
|
|
4193
4344
|
*
|
|
4194
|
-
* stream.
|
|
4195
|
-
*
|
|
4345
|
+
* stream.onNotification(NotificationType.PostComment, async ({ update }) => {
|
|
4346
|
+
* await handleComment(update.data.notification);
|
|
4196
4347
|
* });
|
|
4197
4348
|
* stream.on('unreadCount', (count) => setBadge(count));
|
|
4198
4349
|
*
|
|
@@ -4204,8 +4355,8 @@ declare class ItdClient {
|
|
|
4204
4355
|
* Освобождает ресурсы клиента: закрывает все потоки уведомлений, отправляет открытые
|
|
4205
4356
|
* накопители {@link telemetry}, затем останавливает очередь запросов.
|
|
4206
4357
|
*
|
|
4207
|
-
* После вызова клиентом можно пользоваться
|
|
4208
|
-
*
|
|
4358
|
+
* Метод дожидается активных обработчиков потока. После вызова клиентом можно пользоваться
|
|
4359
|
+
* снова; ранее созданный поток можно запустить повторным `connect()`.
|
|
4209
4360
|
*
|
|
4210
4361
|
* Общая очередь, полученная от {@link ItdAccounts}, не останавливается: её гасит сам
|
|
4211
4362
|
* контейнер, когда закрывает все аккаунты разом.
|
|
@@ -4926,17 +5077,52 @@ declare function resolveNotificationUrl(notification: Notification): string;
|
|
|
4926
5077
|
//#region src/realtime/poll.d.ts
|
|
4927
5078
|
/** Настройки опроса. */
|
|
4928
5079
|
interface PollTransportOptions {
|
|
5080
|
+
/** Часы опроса. Обычно подменяются только в тестах. */
|
|
5081
|
+
clock?: ItdClock;
|
|
4929
5082
|
/** Как часто опрашивать сервер, мс. По умолчанию 15 000. */
|
|
4930
5083
|
interval?: number;
|
|
4931
5084
|
/** Сколько уведомлений запрашивать за раз. По умолчанию 20. */
|
|
4932
5085
|
limit?: number;
|
|
4933
5086
|
}
|
|
4934
5087
|
//#endregion
|
|
5088
|
+
//#region src/realtime/router.d.ts
|
|
5089
|
+
/** Выбирает маршрут обновления. `undefined` и `null` означают отсутствие маршрута. */
|
|
5090
|
+
type RealtimeRouteSelector<K extends PropertyKey> = (context: RealtimeContext) => K | null | undefined | Promise<K | null | undefined>;
|
|
5091
|
+
/**
|
|
5092
|
+
* Направляет обновления потока в именованные цепочки промежуточных обработчиков.
|
|
5093
|
+
*
|
|
5094
|
+
* @example
|
|
5095
|
+
* ```ts
|
|
5096
|
+
* import { RealtimeRouter, RealtimeUpdateType } from 'itd-api';
|
|
5097
|
+
*
|
|
5098
|
+
* const router = new RealtimeRouter((context) => context.update.type);
|
|
5099
|
+
* router.route(RealtimeUpdateType.Notification, async (context, next) => {
|
|
5100
|
+
* if (context.update.type === RealtimeUpdateType.Notification) {
|
|
5101
|
+
* await handleNotification(context.update.data.notification);
|
|
5102
|
+
* }
|
|
5103
|
+
* await next();
|
|
5104
|
+
* });
|
|
5105
|
+
* stream.use(router.middleware());
|
|
5106
|
+
* ```
|
|
5107
|
+
*/
|
|
5108
|
+
declare class RealtimeRouter<K extends PropertyKey = PropertyKey> {
|
|
5109
|
+
#private;
|
|
5110
|
+
constructor(selector: RealtimeRouteSelector<K>);
|
|
5111
|
+
/** Добавляет промежуточные обработчики к маршруту и возвращает функцию их удаления. */
|
|
5112
|
+
route(key: K, ...middleware: readonly RealtimeMiddleware[]): Unsubscribe;
|
|
5113
|
+
/** Добавляет промежуточные обработчики для обновлений без зарегистрированного маршрута. */
|
|
5114
|
+
otherwise(...middleware: readonly RealtimeMiddleware[]): Unsubscribe;
|
|
5115
|
+
/** Возвращает промежуточный обработчик для `stream.use()`. */
|
|
5116
|
+
middleware(): RealtimeMiddleware;
|
|
5117
|
+
}
|
|
5118
|
+
//#endregion
|
|
4935
5119
|
//#region src/realtime/sse.d.ts
|
|
4936
5120
|
/** Путь потока уведомлений. */
|
|
4937
5121
|
declare const STREAM_PATH = "/api/notifications/stream";
|
|
4938
5122
|
/** Настройки SSE-транспорта. */
|
|
4939
5123
|
interface SseTransportOptions {
|
|
5124
|
+
/** Часы потока. Обычно подменяются только в тестах. */
|
|
5125
|
+
clock?: ItdClock;
|
|
4940
5126
|
/**
|
|
4941
5127
|
* Сколько миллисекунд ждать данных, прежде чем считать соединение мёртвым.
|
|
4942
5128
|
*
|
|
@@ -4986,5 +5172,5 @@ interface RenderSpansOptions {
|
|
|
4986
5172
|
*/
|
|
4987
5173
|
declare function renderSpans(content: string, spans?: readonly Span[] | null | undefined, options?: RenderSpansOptions): string;
|
|
4988
5174
|
//#endregion
|
|
4989
|
-
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AUTH_FLAG_COOKIE, AUTH_PATHS, AccessType, type AccountEvents, type Actor, type AddAccountOptions, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AudioMimeType, type AuthEvents, type AuthIdentity, type AuthInput, type AuthResource, type AuthState, type Author, type AutoSpansOptions, BUILT_IN_SERVICES, type BuilderInput, type CaptchaCredentials, type ChangelogEntry, type Clan, type ClientHooks, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostInput, type CreateReportInput, type Credentials, type CredentialsAuth, DEFAULT_BASE_URL, DEFAULT_FILE_STREAM_BUFFER_BYTES, DEFAULT_STATUS_BASE_URL, DEFAULT_TIMEOUT, DEFAULT_UPLOAD_TIMEOUT, DEFAULT_URL_FILE_MAX_BYTES, DEFAULT_USER_AGENT, DEVICE_ID_HEADER, DetectedRuntime, type DwellEntry, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type ForgotPasswordInput, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdAccounts, type ItdAccountsOptions, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, ItdClient, type ItdClientOptions, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, type ItdPlugin, ItdRateLimitError, ItdRealtime, ItdServerError, type ItdSession, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, MAX_RECONNECT_ATTEMPTS, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, MemoryMultiTokenStorage, MemoryTokenStorage, type MultiTokenStorage, type MyProfile, NOTIFICATION_TYPE_ALIASES, type Notification, type NotificationEvent, type NotificationListParams, type NotificationSettings, NotificationType, type NotificationsResource, type Page, type PageState, PaginationMode, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginContext, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type PollTransportOptions, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, RECONNECT_BACKOFF, RECONNECT_JITTER, REFRESH_COOKIE, REFRESH_COOKIE_PATH, REQUEST_OPTION_KEYS, type RateLimitOptions, type RateLimitScope, type RawRequestOptions, type RealtimeDeps, type RealtimeEvents, type RealtimeOptions, RealtimeStatus, type RealtimeTransport, RealtimeTransportKind, type ReconnectOptions, type RecordStorageSource, type RemoveAccountOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestOptions, type ResetPasswordInput, type ResponseContext, type RetryContext, type RetryOptions, RuntimeMode, STATUS_SERVICE, STREAM_PATH, type SearchResource, type SearchResult, type ServiceDefinition, ServiceRegistry, ServiceState, type ServiceStatus, type Session, type SignInResult, SignInStatus, type Span, SpanRenderFormat, SpanType, type SseTransportOptions, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, TURNSTILE_SITE_KEY, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type TokenStorage, type Transformer, type TransportContext, type TransportEvent, UnauthorizedStreamError, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, autoSpans, canonicalNotificationType, comment, createAccounts, createClient, createMultiTokenStorage, createRecordMultiStorage, createTokenStorage, formatNotificationText, fromStream, fromUrl, isBuilder, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, parseHtml, parseMarkdown, poll, post, readNotificationEvent, readUnreadCountEvent, renderSpans, report, resolveNotificationUrl, scopedTokenStorage, statusDays, toDate, utcStampToIso };
|
|
5175
|
+
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AUTH_FLAG_COOKIE, AUTH_PATHS, AccessType, type AccountEvents, type Actor, type AddAccountOptions, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AudioMimeType, type AuthEvents, type AuthIdentity, type AuthInput, type AuthResource, type AuthState, type Author, type AutoSpansOptions, BUILT_IN_SERVICES, type BuilderInput, type CaptchaCredentials, type ChangelogEntry, type Clan, type ClientHooks, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostInput, type CreateReportInput, type Credentials, type CredentialsAuth, DEFAULT_BASE_URL, DEFAULT_FILE_STREAM_BUFFER_BYTES, DEFAULT_STATUS_BASE_URL, DEFAULT_TIMEOUT, DEFAULT_UPLOAD_TIMEOUT, DEFAULT_URL_FILE_MAX_BYTES, DEFAULT_USER_AGENT, DEVICE_ID_HEADER, DetectedRuntime, type DwellEntry, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type ForgotPasswordInput, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdAccounts, type ItdAccountsOptions, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, ItdClient, type ItdClientOptions, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, type ItdPlugin, ItdRateLimitError, ItdRealtime, ItdServerError, type ItdSession, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, MAX_RECONNECT_ATTEMPTS, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, MemoryMultiTokenStorage, MemoryTokenStorage, type MultiTokenStorage, type MyProfile, NOTIFICATION_TYPE_ALIASES, type Notification, type NotificationEvent, type NotificationEventOfType, type NotificationListParams, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationsResource, type Page, type PageState, PaginationMode, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginContext, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type PollTransportOptions, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, RECONNECT_BACKOFF, RECONNECT_JITTER, REFRESH_COOKIE, REFRESH_COOKIE_PATH, REQUEST_OPTION_KEYS, type RateLimitOptions, type RateLimitScope, type RawRequestOptions, type RealtimeContext, type RealtimeDeps, type RealtimeEvents, type RealtimeHandler, type RealtimeMiddleware, type RealtimeNext, type RealtimeNotificationContext, type RealtimeNotificationFilter, type RealtimeNotificationSelector, type RealtimeNotificationUpdate, type RealtimeOptions, type RealtimePredicate, type RealtimeRouteSelector, RealtimeRouter, type RealtimeSequentializer, RealtimeStatus, type RealtimeTransport, RealtimeTransportKind, type RealtimeTypeGuard, type RealtimeUnknownUpdate, type RealtimeUnreadCountUpdate, type RealtimeUpdate, type RealtimeUpdateOfType, RealtimeUpdateOrigin, RealtimeUpdateType, type ReconnectOptions, type RecordStorageSource, type RemoveAccountOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestOptions, type ResetPasswordInput, type ResponseContext, type RetryContext, type RetryOptions, RuntimeMode, STATUS_SERVICE, STREAM_PATH, type SearchResource, type SearchResult, type ServiceDefinition, ServiceRegistry, ServiceState, type ServiceStatus, type Session, type SignInResult, SignInStatus, type Span, SpanRenderFormat, SpanType, type SseTransportOptions, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, TURNSTILE_SITE_KEY, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type TokenStorage, type Transformer, type TransportContext, type TransportEvent, UnauthorizedStreamError, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, autoSpans, canonicalNotificationType, comment, createAccounts, createClient, createMultiTokenStorage, createRecordMultiStorage, createTokenStorage, formatNotificationText, fromStream, fromUrl, isBuilder, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, parseHtml, parseMarkdown, poll, post, readNotificationEvent, readUnreadCountEvent, renderSpans, report, resolveNotificationUrl, scopedTokenStorage, statusDays, systemClock, toDate, utcStampToIso };
|
|
4990
5176
|
//# sourceMappingURL=index.d.cts.map
|