itd-api 0.14.0 → 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 +3 -3
- 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 +34 -20
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -6
- package/dist/index.d.ts +10 -6
- package/dist/index.js +28 -21
- 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 +11 -4
- package/dist/rest/index.d.cts +3 -3
- package/dist/rest/index.d.ts +3 -3
- package/dist/rest/index.js +5 -5
- package/dist/shared/{cookies-Bw5HAxTB.js → cookies-YP0m72v2.js} +3 -2
- package/dist/shared/cookies-YP0m72v2.js.map +1 -0
- package/dist/shared/{cookies-DRYS-vZm.cjs → cookies-u2hXCcpR.cjs} +3 -2
- package/dist/shared/cookies-u2hXCcpR.cjs.map +1 -0
- package/dist/shared/{events-Dl27rIA0.d.cts → events-BmYzFrRC.d.cts} +1 -1
- package/dist/shared/{events-DXLOZXNe.js → events-BnL_gckg.js} +12 -12
- package/dist/shared/events-BnL_gckg.js.map +1 -0
- package/dist/shared/{events-g5XfBnc3.d.ts → events-Bw7VaSDs.d.ts} +1 -1
- package/dist/shared/{events--hwTmeN2.cjs → events-DUFuPzVO.cjs} +12 -12
- package/dist/shared/events-DUFuPzVO.cjs.map +1 -0
- package/dist/shared/{multi-storage-DDQKI9yT.cjs → multi-storage-BIeeBDV6.cjs} +2 -2
- package/dist/shared/{multi-storage-DDQKI9yT.cjs.map → multi-storage-BIeeBDV6.cjs.map} +1 -1
- package/dist/shared/{multi-storage-BDwZ3sOJ.js → multi-storage-DmUOaXbC.js} +2 -2
- package/dist/shared/{multi-storage-BDwZ3sOJ.js.map → multi-storage-DmUOaXbC.js.map} +1 -1
- package/dist/shared/{options-RfX5uXP5.js → options-D-8h06B_.js} +2 -2
- package/dist/shared/{options-RfX5uXP5.js.map → options-D-8h06B_.js.map} +1 -1
- package/dist/shared/{options-BrA90TVm.cjs → options-hZolLxgs.cjs} +2 -2
- package/dist/shared/{options-BrA90TVm.cjs.map → options-hZolLxgs.cjs.map} +1 -1
- package/dist/shared/{render-B6sj0OJ5.js → render-CgSQp84V.js} +1708 -1277
- package/dist/shared/render-CgSQp84V.js.map +1 -0
- package/dist/shared/{render-C11kvqb5.d.ts → render-DPXlBr5L.d.ts} +726 -248
- package/dist/shared/{render-D_pGoEH3.d.cts → render-DcIXTSuo.d.cts} +726 -248
- package/dist/shared/{render-DHeGjOzq.cjs → render-dKMV-872.cjs} +1713 -1240
- package/dist/shared/render-dKMV-872.cjs.map +1 -0
- package/dist/shared/{url-BPqHN_CZ.d.ts → url-B_TELARK.d.ts} +85 -17
- package/dist/shared/{url-W5GQOtlk.cjs → url-CQbNqbJX.cjs} +160 -91
- package/dist/shared/url-CQbNqbJX.cjs.map +1 -0
- package/dist/shared/{url-B6_um5qJ.d.cts → url-D7U9qjXD.d.cts} +85 -17
- package/dist/shared/{url-CY2NxyqI.js → url-DYGRJqxh.js} +161 -92
- package/dist/shared/url-DYGRJqxh.js.map +1 -0
- package/package.json +1 -1
- package/dist/shared/cookies-Bw5HAxTB.js.map +0 -1
- package/dist/shared/cookies-DRYS-vZm.cjs.map +0 -1
- package/dist/shared/events--hwTmeN2.cjs.map +0 -1
- package/dist/shared/events-DXLOZXNe.js.map +0 -1
- package/dist/shared/render-B6sj0OJ5.js.map +0 -1
- package/dist/shared/render-DHeGjOzq.cjs.map +0 -1
- package/dist/shared/url-CY2NxyqI.js.map +0 -1
- package/dist/shared/url-W5GQOtlk.cjs.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { T as isItdApiError, a as ItdAbortError, d as ItdError, l as ItdConfigError, m as ItdFileErrorReason, n as isRecord, p as ItdFileError, x as ItdStateError } from "./validate-BQzL_oJ4.js";
|
|
2
|
-
import { A as passthroughOperation, D as pickNumber, E as pickBoolean,
|
|
3
|
-
import { _ as redactUrl, b as isBlob, h as redactErrorCause, s as encodePathSegment, x as isFile, y as createDeviceId } from "./cookies-
|
|
4
|
-
import { a as fileTooLarge, c as FileTransferMode, i as isReadableByteStream, n as boundedFileStream, o as optionalBytes, r as isBoundedFileStream, s as DEFAULT_URL_FILE_MAX_BYTES, t as resolveFileStreamOptions } from "./options-
|
|
2
|
+
import { A as passthroughOperation, B as OperationMethod, D as pickNumber, E as pickBoolean, H as defineOperation, K as requestAbortError, N as defineBuiltInOperation, O as pickObject, T as pickArray, U as identityResult, V as RetrySafety, W as voidResult, b as STATUS_SERVICE, dt as ReportTargetType, j as voidOperation, k as pickString, m as mergeService, o as normalizeNotification, pt as SpanType, q as waitForRequest, rt as InteractionType, ut as ReportReason, vt as createDeadline, y as DEFAULT_STATUS_BASE_URL } from "./url-DYGRJqxh.js";
|
|
3
|
+
import { _ as redactUrl, b as isBlob, h as redactErrorCause, s as encodePathSegment, x as isFile, y as createDeviceId } from "./cookies-YP0m72v2.js";
|
|
4
|
+
import { a as fileTooLarge, c as FileTransferMode, i as isReadableByteStream, n as boundedFileStream, o as optionalBytes, r as isBoundedFileStream, s as DEFAULT_URL_FILE_MAX_BYTES, t as resolveFileStreamOptions } from "./options-D-8h06B_.js";
|
|
5
5
|
import { r as createKeyValueStore } from "./key-value-store-BwXlaoD4.js";
|
|
6
6
|
// src/models/chats.ts
|
|
7
7
|
/** Тип реакции на сообщение. */
|
|
@@ -36,6 +36,7 @@ const ChatUpdateType = Object.freeze({
|
|
|
36
36
|
MessagesDeleted: "messages_deleted",
|
|
37
37
|
MessagesRead: "messages_read",
|
|
38
38
|
Presence: "presence",
|
|
39
|
+
/** Действие собеседника. Конкретное действие передаётся в `action`. */
|
|
39
40
|
Typing: "typing",
|
|
40
41
|
ChatCreated: "chat_created",
|
|
41
42
|
ChatDeleted: "chat_deleted",
|
|
@@ -258,14 +259,15 @@ function normalizeReadCursor(body) {
|
|
|
258
259
|
}
|
|
259
260
|
/** Читает страницу истории. Ключи карты прочтения — ID участников. */
|
|
260
261
|
function normalizeChatHistory(body) {
|
|
261
|
-
const { messages, read_cursors, my_last_read, has_older, has_newer, event_seq, ...rest } = body;
|
|
262
|
+
const { messages, read_cursors, my_last_read, has_older, has_newer, event_seq, target_message_id, ...rest } = body;
|
|
262
263
|
return withFields(rest, {
|
|
263
264
|
messages: mapItems(messages, normalizeMessage),
|
|
264
265
|
readCursors: read_cursors == null ? read_cursors : Object.fromEntries(Object.entries(read_cursors).map(([userId, cursor]) => [userId, normalizeReadCursor(cursor)])),
|
|
265
266
|
myLastRead: normalizeReadCursor(my_last_read),
|
|
266
267
|
hasOlder: has_older,
|
|
267
268
|
hasNewer: has_newer,
|
|
268
|
-
eventSeq: event_seq
|
|
269
|
+
eventSeq: event_seq,
|
|
270
|
+
targetMessageId: target_message_id
|
|
269
271
|
});
|
|
270
272
|
}
|
|
271
273
|
/** Читает страницу вложений из истории чата. */
|
|
@@ -342,10 +344,13 @@ function normalizeChatEdited(body) {
|
|
|
342
344
|
function normalizeChatForwarded(body) {
|
|
343
345
|
const { ok, ...rest } = body;
|
|
344
346
|
return withFields({ ...changeFields(rest) }, { ok: mapItems(ok, (item) => {
|
|
345
|
-
const { source_message_id, message_id, ...fields } = item;
|
|
347
|
+
const { source_message_id, message_id, created_at, forwarded_from_sender_id, forwarded_from_name, ...fields } = item;
|
|
346
348
|
return withFields(fields, {
|
|
347
349
|
sourceMessageId: source_message_id,
|
|
348
|
-
messageId: message_id
|
|
350
|
+
messageId: message_id,
|
|
351
|
+
...isoField("createdAt", created_at),
|
|
352
|
+
forwardedFromSenderId: forwarded_from_sender_id,
|
|
353
|
+
forwardedFromName: forwarded_from_name
|
|
349
354
|
});
|
|
350
355
|
}) });
|
|
351
356
|
}
|
|
@@ -378,7 +383,7 @@ function normalizeChatUpdate(body) {
|
|
|
378
383
|
unreadCount: unread_count
|
|
379
384
|
});
|
|
380
385
|
}
|
|
381
|
-
/** Читает страницу
|
|
386
|
+
/** Читает страницу событий и сводки изменившихся чатов. */
|
|
382
387
|
function normalizeChatUpdates(body) {
|
|
383
388
|
const { events, next_event_seq, reset_required, chats, ...rest } = body;
|
|
384
389
|
return withFields(rest, {
|
|
@@ -406,830 +411,1344 @@ function writeChatReaction(reaction) {
|
|
|
406
411
|
emoji: reaction.emoji
|
|
407
412
|
};
|
|
408
413
|
}
|
|
409
|
-
// src/
|
|
410
|
-
/**
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
"
|
|
415
|
-
|
|
416
|
-
"image/avif",
|
|
417
|
-
"image/heic",
|
|
418
|
-
"image/heif"
|
|
419
|
-
]);
|
|
420
|
-
/** Видео, которые принимает `POST /api/files/upload`. */
|
|
421
|
-
const VIDEO_MIME_TYPES = Object.freeze([
|
|
422
|
-
"video/mp4",
|
|
423
|
-
"video/webm",
|
|
424
|
-
"video/quicktime"
|
|
425
|
-
]);
|
|
426
|
-
/** Аудио для голосовых комментариев. */
|
|
427
|
-
const AUDIO_MIME_TYPES = Object.freeze(["audio/ogg"]);
|
|
428
|
-
/** Все типы, которые принимает загрузка. */
|
|
429
|
-
const ALLOWED_MIME_TYPES = Object.freeze([
|
|
430
|
-
...IMAGE_MIME_TYPES,
|
|
431
|
-
...VIDEO_MIME_TYPES,
|
|
432
|
-
...AUDIO_MIME_TYPES
|
|
433
|
-
]);
|
|
414
|
+
// src/builders/base.ts
|
|
415
|
+
/** Метка билдера. Через `Symbol.for` — чтобы распознавание переживало смешивание ESM и CJS. */
|
|
416
|
+
const BUILDER = Symbol.for("itd.builder");
|
|
417
|
+
/** Является ли значение билдером. */
|
|
418
|
+
function isBuilder(value) {
|
|
419
|
+
return typeof value === "object" && value !== null && BUILDER in value;
|
|
420
|
+
}
|
|
434
421
|
/**
|
|
435
|
-
*
|
|
422
|
+
* Приводит любую из трёх форм входа к готовому объекту.
|
|
436
423
|
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
424
|
+
* Проверка выполняется всегда, независимо от формы: обычный объект проходит ровно те же
|
|
425
|
+
* правила, что и результат билдера.
|
|
426
|
+
*
|
|
427
|
+
* @param input то, что передал пользователь
|
|
428
|
+
* @param factory создаёт пустой билдер для формы с функцией
|
|
429
|
+
* @param validate проверяет собранный объект
|
|
439
430
|
*/
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
avif: "image/avif",
|
|
448
|
-
heic: "image/heic",
|
|
449
|
-
heif: "image/heif",
|
|
450
|
-
mp4: "video/mp4",
|
|
451
|
-
m4v: "video/mp4",
|
|
452
|
-
webm: "video/webm",
|
|
453
|
-
mov: "video/quicktime",
|
|
454
|
-
qt: "video/quicktime",
|
|
455
|
-
ogg: "audio/ogg",
|
|
456
|
-
oga: "audio/ogg",
|
|
457
|
-
opus: "audio/ogg"
|
|
458
|
-
});
|
|
459
|
-
/** Определяет MIME-тип по расширению имени файла. */
|
|
460
|
-
function mimeFromFilename(filename) {
|
|
461
|
-
const dot = filename.lastIndexOf(".");
|
|
462
|
-
if (dot < 0) return void 0;
|
|
463
|
-
return EXTENSION_TO_MIME[filename.slice(dot + 1).toLowerCase()];
|
|
464
|
-
}
|
|
465
|
-
/** Разрешён ли тип к загрузке. */
|
|
466
|
-
function isAllowedMime(mimeType) {
|
|
467
|
-
return ALLOWED_MIME_TYPES.includes(mimeType.toLowerCase());
|
|
431
|
+
function resolveInput(input, factory, validate) {
|
|
432
|
+
if (typeof input === "function") {
|
|
433
|
+
const result = input(factory());
|
|
434
|
+
return isBuilder(result) ? result.build() : validate(result);
|
|
435
|
+
}
|
|
436
|
+
if (isBuilder(input)) return input.build();
|
|
437
|
+
return validate(input);
|
|
468
438
|
}
|
|
439
|
+
// src/spans/validate.ts
|
|
469
440
|
/**
|
|
470
|
-
*
|
|
471
|
-
*
|
|
472
|
-
* Отказ на стороне клиента экономит и время, и трафик: тот же `UNSUPPORTED_FILE_TYPE`
|
|
473
|
-
* пришёл бы с сервера, но уже после загрузки всего файла.
|
|
441
|
+
* Проверяет, что spans целиком лежат внутри текста.
|
|
474
442
|
*
|
|
475
|
-
*
|
|
443
|
+
* Возвращает копии, чтобы последующая мутация входного массива не меняла уже собранные данные.
|
|
476
444
|
*/
|
|
477
|
-
function
|
|
478
|
-
if (!
|
|
479
|
-
if (
|
|
445
|
+
function validateSpans(content, spans) {
|
|
446
|
+
if (!Array.isArray(spans)) throw new ItdConfigError("spans должен быть массивом");
|
|
447
|
+
if (content.length === 0 && spans.length > 0) throw new ItdConfigError("Нельзя задать spans без текста: сначала укажите непустой content");
|
|
448
|
+
return spans.map((span, index) => {
|
|
449
|
+
if (!span || typeof span !== "object") throw new ItdConfigError(`Некорректный span №${index + 1}: ожидался объект`);
|
|
450
|
+
const candidate = span;
|
|
451
|
+
if (typeof candidate.type !== "string" || !Number.isInteger(candidate.offset) || !Number.isInteger(candidate.length) || (candidate.offset ?? -1) < 0 || (candidate.length ?? 0) <= 0 || (candidate.offset ?? 0) + (candidate.length ?? 0) > content.length) throw new ItdConfigError(`Некорректный span №${index + 1}: offset и length должны указывать на непустой фрагмент content`);
|
|
452
|
+
return { ...candidate };
|
|
453
|
+
});
|
|
480
454
|
}
|
|
481
|
-
// src/
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
const FINALIZE_UPLOAD = passthroughOperation("chats.upload.finalize");
|
|
489
|
-
function sizeMismatch() {
|
|
490
|
-
return new ItdFileError("Размер потока вложения отличается от объявленного", { reason: ItdFileErrorReason.Read });
|
|
455
|
+
// src/builders/markup.ts
|
|
456
|
+
function validateMarkup(value) {
|
|
457
|
+
if (!value || typeof value.content !== "string" || !Array.isArray(value.spans)) throw new ItdConfigError("Разметка должна содержать строку content и массив spans");
|
|
458
|
+
return {
|
|
459
|
+
content: value.content,
|
|
460
|
+
spans: validateSpans(value.content, value.spans).sort((left, right) => left.offset - right.offset || right.length - left.length)
|
|
461
|
+
};
|
|
491
462
|
}
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
if (
|
|
495
|
-
|
|
496
|
-
|
|
463
|
+
function entityName(value, prefix, label) {
|
|
464
|
+
const name = value.startsWith(prefix) ? value.slice(prefix.length) : value;
|
|
465
|
+
if (name === "" || /\s/u.test(name)) throw new ItdConfigError(`${label} должен быть непустым и не содержать пробелов`);
|
|
466
|
+
return name;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Неизменяемый билдер текста с разметкой.
|
|
470
|
+
*
|
|
471
|
+
* Каждый метод дописывает фрагмент и сам считает `offset` и `length` в единицах UTF-16 —
|
|
472
|
+
* именно такие индексы использует JavaScript-редактор сайта.
|
|
473
|
+
*/
|
|
474
|
+
var MarkupBuilder = class MarkupBuilder {
|
|
475
|
+
/** @internal */
|
|
476
|
+
[BUILDER] = true;
|
|
477
|
+
#content;
|
|
478
|
+
#spans;
|
|
479
|
+
/** @internal Создавайте билдер функцией {@link markup}. */
|
|
480
|
+
constructor(content, spans) {
|
|
481
|
+
this.#content = content;
|
|
482
|
+
this.#spans = spans;
|
|
497
483
|
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
let part = new Uint8Array(Math.min(PART_BYTES, remaining));
|
|
502
|
-
let filled = 0;
|
|
503
|
-
for (;;) {
|
|
504
|
-
const next = await reader.read();
|
|
505
|
-
if (next.done) break;
|
|
506
|
-
const chunk = next.value;
|
|
507
|
-
if (chunk.byteLength > remaining) throw sizeMismatch();
|
|
508
|
-
let offset = 0;
|
|
509
|
-
while (offset < chunk.byteLength) {
|
|
510
|
-
const length = Math.min(part.byteLength - filled, chunk.byteLength - offset);
|
|
511
|
-
part.set(chunk.subarray(offset, offset + length), filled);
|
|
512
|
-
offset += length;
|
|
513
|
-
filled += length;
|
|
514
|
-
remaining -= length;
|
|
515
|
-
if (filled === part.byteLength) {
|
|
516
|
-
yield part;
|
|
517
|
-
part = new Uint8Array(Math.min(PART_BYTES, remaining));
|
|
518
|
-
filled = 0;
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
if (remaining !== 0) throw sizeMismatch();
|
|
523
|
-
} finally {
|
|
524
|
-
reader.releaseLock();
|
|
484
|
+
/** Дописывает обычный текст без разметки. */
|
|
485
|
+
text(value) {
|
|
486
|
+
return new MarkupBuilder(this.#content + value, this.#spans);
|
|
525
487
|
}
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
488
|
+
/** Дописывает переводы строк. */
|
|
489
|
+
newline(count = 1) {
|
|
490
|
+
if (!Number.isInteger(count) || count < 0) throw new ItdConfigError("Количество переводов строк должно быть целым неотрицательным");
|
|
491
|
+
return this.text("\n".repeat(count));
|
|
492
|
+
}
|
|
493
|
+
/** @internal Добавляет готовый фрагмент и сдвигает его spans к текущему концу текста. */
|
|
494
|
+
#formatted(value, outerSpans) {
|
|
495
|
+
const fragment = typeof value === "string" ? {
|
|
496
|
+
content: value,
|
|
497
|
+
spans: []
|
|
498
|
+
} : resolveMarkup(value);
|
|
499
|
+
if (fragment.content.length === 0) throw new ItdConfigError("Размечаемый фрагмент не может быть пустым");
|
|
500
|
+
const offset = this.#content.length;
|
|
501
|
+
const shifted = fragment.spans.map((span) => ({
|
|
502
|
+
...span,
|
|
503
|
+
offset: span.offset + offset
|
|
504
|
+
}));
|
|
505
|
+
const outer = outerSpans.map((span) => ({
|
|
506
|
+
...span,
|
|
507
|
+
offset,
|
|
508
|
+
length: fragment.content.length
|
|
509
|
+
}));
|
|
510
|
+
return new MarkupBuilder(this.#content + fragment.content, [
|
|
511
|
+
...this.#spans,
|
|
512
|
+
...shifted,
|
|
513
|
+
...outer
|
|
514
|
+
]);
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Дописывает фрагмент с произвольным типом разметки.
|
|
518
|
+
*
|
|
519
|
+
* Вложенный билдер позволяет форматировать часть фрагмента дополнительным стилем.
|
|
520
|
+
* Для нескольких стилей на всём фрагменте используйте {@link styled}.
|
|
521
|
+
*/
|
|
522
|
+
span(value, span) {
|
|
523
|
+
return this.#formatted(value, [span]);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Дописывает фрагмент с несколькими стилями на одном диапазоне.
|
|
527
|
+
*
|
|
528
|
+
* Для `link`, которому нужен `url`, используйте {@link link}; произвольные spans с
|
|
529
|
+
* метаданными можно объединять через вложенные вызовы {@link span}.
|
|
530
|
+
*/
|
|
531
|
+
styled(value, ...types) {
|
|
532
|
+
if (types.length === 0) return this.#formatted(value, []);
|
|
533
|
+
return this.#formatted(value, types.map((type) => ({ type })));
|
|
534
|
+
}
|
|
535
|
+
/** Дописывает `#хэштег` и сохраняет имя без решётки в `tag`. */
|
|
536
|
+
hashtag(tag) {
|
|
537
|
+
const name = entityName(tag, "#", "Хэштег");
|
|
538
|
+
return this.span(`#${name}`, {
|
|
539
|
+
type: SpanType.Hashtag,
|
|
540
|
+
tag: name
|
|
546
541
|
});
|
|
547
|
-
task = Promise.resolve().then(() => executeUpload(http, host.files, input, upload, {
|
|
548
|
-
...request,
|
|
549
|
-
deadline: 0,
|
|
550
|
-
signal: scope.signal
|
|
551
|
-
})).finally(unmanage);
|
|
552
|
-
return await waitForRequest(task, scope.signal);
|
|
553
|
-
} catch (error) {
|
|
554
|
-
throw requestAbortError(scope, operation, error);
|
|
555
|
-
} finally {
|
|
556
|
-
scope.cleanup();
|
|
557
542
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
filename,
|
|
565
|
-
contentType,
|
|
566
|
-
maxBytes: MAX_FILE_BYTES,
|
|
567
|
-
requireKnownSize: true
|
|
568
|
-
}, { signal: request.signal });
|
|
569
|
-
try {
|
|
570
|
-
const size = source.size;
|
|
571
|
-
if (size === void 0 || size === 0) throw new ItdConfigError("Для загрузки вложения чата нужен известный ненулевой размер");
|
|
572
|
-
const name = source.filename;
|
|
573
|
-
const mime = source.contentType ?? (name && mimeFromFilename(name)) ?? "application/octet-stream";
|
|
574
|
-
const { uploadId } = await http.execute(INIT_UPLOAD, {
|
|
575
|
-
path: `${UPLOAD_PATH}/init`,
|
|
576
|
-
body: {
|
|
577
|
-
mime,
|
|
578
|
-
size,
|
|
579
|
-
totalParts: Math.ceil(size / PART_BYTES)
|
|
580
|
-
},
|
|
581
|
-
...request
|
|
543
|
+
/** Дописывает `@username` и сохраняет имя пользователя в `username`. */
|
|
544
|
+
mention(username) {
|
|
545
|
+
const name = entityName(username, "@", "Упоминание");
|
|
546
|
+
return this.span(`@${name}`, {
|
|
547
|
+
type: SpanType.Mention,
|
|
548
|
+
username: name
|
|
582
549
|
});
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
});
|
|
597
|
-
uploaded += part instanceof Uint8Array ? part.byteLength : part.size;
|
|
598
|
-
onProgress?.(uploaded, size);
|
|
599
|
-
}
|
|
600
|
-
return await http.execute(FINALIZE_UPLOAD, {
|
|
601
|
-
path: `${path}/finalize`,
|
|
602
|
-
body: {
|
|
603
|
-
filename: name,
|
|
604
|
-
width,
|
|
605
|
-
height,
|
|
606
|
-
durationMs,
|
|
607
|
-
waveform,
|
|
608
|
-
thumbhash,
|
|
609
|
-
thumb
|
|
610
|
-
},
|
|
611
|
-
...request
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Дописывает ссылку.
|
|
553
|
+
*
|
|
554
|
+
* Для строки адрес по умолчанию становится и текстом ссылки. Вложенному форматированному
|
|
555
|
+
* фрагменту URL нужно передать явно.
|
|
556
|
+
*/
|
|
557
|
+
link(content, url) {
|
|
558
|
+
const resolvedUrl = url ?? (typeof content === "string" ? content : void 0);
|
|
559
|
+
if (resolvedUrl === void 0) throw new ItdConfigError("Для форматированного текста ссылки нужно явно передать URL");
|
|
560
|
+
return this.span(content, {
|
|
561
|
+
type: SpanType.Link,
|
|
562
|
+
url: resolvedUrl
|
|
612
563
|
});
|
|
613
|
-
} finally {
|
|
614
|
-
if (source.mode === FileTransferMode.Stream) await source.close();
|
|
615
564
|
}
|
|
565
|
+
bold(content) {
|
|
566
|
+
return this.span(content, { type: SpanType.Bold });
|
|
567
|
+
}
|
|
568
|
+
italic(content) {
|
|
569
|
+
return this.span(content, { type: SpanType.Italic });
|
|
570
|
+
}
|
|
571
|
+
underline(content) {
|
|
572
|
+
return this.span(content, { type: SpanType.Underline });
|
|
573
|
+
}
|
|
574
|
+
strike(content) {
|
|
575
|
+
return this.span(content, { type: SpanType.Strike });
|
|
576
|
+
}
|
|
577
|
+
spoiler(content) {
|
|
578
|
+
return this.span(content, { type: SpanType.Spoiler });
|
|
579
|
+
}
|
|
580
|
+
monospace(content) {
|
|
581
|
+
return this.span(content, { type: SpanType.Monospace });
|
|
582
|
+
}
|
|
583
|
+
quote(content) {
|
|
584
|
+
return this.span(content, { type: SpanType.Quote });
|
|
585
|
+
}
|
|
586
|
+
build() {
|
|
587
|
+
return validateMarkup({
|
|
588
|
+
content: this.#content,
|
|
589
|
+
spans: this.#spans
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
toJSON() {
|
|
593
|
+
return this.build();
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
/** Начинает сборку текста с автоматически вычисляемыми смещениями. */
|
|
597
|
+
function markup(content = "") {
|
|
598
|
+
return new MarkupBuilder(content, []);
|
|
616
599
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
/** Следующая страница запрашивается непрозрачным курсором. */
|
|
621
|
-
Cursor: "cursor",
|
|
622
|
-
/** Следующая страница запрашивается номером. */
|
|
623
|
-
Page: "page",
|
|
624
|
-
/** Следующая страница запрашивается смещением от начала списка. */
|
|
625
|
-
Offset: "offset"
|
|
626
|
-
});
|
|
627
|
-
/** Применяет преобразование к элементам страницы, сохраняя сведения о пагинации. */
|
|
628
|
-
function mapPage(page, map) {
|
|
629
|
-
return {
|
|
630
|
-
...page,
|
|
631
|
-
items: page.items.map(map)
|
|
632
|
-
};
|
|
600
|
+
/** Приводит любую форму разметки к тексту и массиву spans. */
|
|
601
|
+
function resolveMarkup(input) {
|
|
602
|
+
return resolveInput(input, () => markup(), validateMarkup);
|
|
633
603
|
}
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
const
|
|
646
|
-
|
|
604
|
+
function trimUrlEnd(value) {
|
|
605
|
+
let result = value;
|
|
606
|
+
const pairs = [
|
|
607
|
+
["(", ")"],
|
|
608
|
+
["[", "]"],
|
|
609
|
+
["{", "}"]
|
|
610
|
+
];
|
|
611
|
+
let changed;
|
|
612
|
+
do {
|
|
613
|
+
const before = result;
|
|
614
|
+
while (/[.,!?;:…'"»”]$/u.test(result)) result = result.slice(0, -1);
|
|
615
|
+
for (const [open, close] of pairs) while (result.endsWith(close) && result.split(close).length > result.split(open).length) result = result.slice(0, -1);
|
|
616
|
+
changed = result !== before;
|
|
617
|
+
} while (changed);
|
|
618
|
+
return result;
|
|
619
|
+
}
|
|
620
|
+
function overlaps(span, start, end) {
|
|
621
|
+
return span.offset < end && start < span.offset + span.length;
|
|
622
|
+
}
|
|
623
|
+
function isHttpUrl(value) {
|
|
624
|
+
try {
|
|
625
|
+
const url = new URL(value);
|
|
626
|
+
return (url.protocol === "http:" || url.protocol === "https:") && url.hostname !== "";
|
|
627
|
+
} catch {
|
|
628
|
+
return false;
|
|
647
629
|
}
|
|
648
|
-
const primary = fields[0];
|
|
649
|
-
return primary === void 0 ? [] : pickArray(body, primary);
|
|
650
630
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
const meta = pickObject(body, "meta");
|
|
660
|
-
const metaCursor = pickObject(meta, "cursor");
|
|
661
|
-
return pickString(pagination, "nextCursor") ?? pickString(body, "nextCursor") ?? pickString(body, "cursor") ?? pickString(metaCursor, "next") ?? null;
|
|
631
|
+
function previousCodePoint(text, index) {
|
|
632
|
+
if (index <= 0) return "";
|
|
633
|
+
const last = text.charCodeAt(index - 1);
|
|
634
|
+
if (last >= 56320 && last <= 57343 && index >= 2) {
|
|
635
|
+
const first = text.charCodeAt(index - 2);
|
|
636
|
+
if (first >= 55296 && first <= 56319) return text.slice(index - 2, index);
|
|
637
|
+
}
|
|
638
|
+
return text[index - 1] ?? "";
|
|
662
639
|
}
|
|
663
640
|
/**
|
|
664
|
-
*
|
|
665
|
-
*
|
|
666
|
-
* Используется лентой, постами пользователя и постами по хэштегу.
|
|
641
|
+
* Находит в тексте те сущности, которые сайт получает после серверного разбора:
|
|
642
|
+
* HTTP(S)-ссылки, `#хэштеги` и `@упоминания`.
|
|
667
643
|
*
|
|
668
|
-
*
|
|
644
|
+
* Смещения выражены в UTF-16 code units, поэтому совпадают с `String#slice`,
|
|
645
|
+
* `substring`, DOM Selection и wire-форматом сайта даже при наличии эмодзи.
|
|
669
646
|
*/
|
|
670
|
-
function
|
|
671
|
-
const
|
|
672
|
-
const
|
|
673
|
-
const
|
|
647
|
+
function autoSpans(text, options = {}) {
|
|
648
|
+
const includeLinks = options.links ?? true;
|
|
649
|
+
const includeHashtags = options.hashtags ?? true;
|
|
650
|
+
const includeMentions = options.mentions ?? true;
|
|
651
|
+
const spans = [];
|
|
652
|
+
const links = [];
|
|
653
|
+
for (const match of text.matchAll(/https?:\/\/[^\s<>"'`]+/giu)) {
|
|
654
|
+
const raw = trimUrlEnd(match[0]);
|
|
655
|
+
if (raw.length === 0 || match.index === void 0 || !isHttpUrl(raw)) continue;
|
|
656
|
+
links.push({
|
|
657
|
+
type: SpanType.Link,
|
|
658
|
+
offset: match.index,
|
|
659
|
+
length: raw.length,
|
|
660
|
+
url: raw
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
if (includeLinks) spans.push(...links);
|
|
664
|
+
if (includeHashtags || includeMentions) for (const match of text.matchAll(/#([\p{L}\p{M}\p{N}_]+)|@([a-z\d](?:[a-z\d_]*[a-z\d])?)/giu)) {
|
|
665
|
+
if (match.index === void 0) continue;
|
|
666
|
+
const offset = match.index;
|
|
667
|
+
const previous = previousCodePoint(text, offset);
|
|
668
|
+
if (/[\p{L}\p{M}\p{N}_#@.]/u.test(previous)) continue;
|
|
669
|
+
const end = offset + match[0].length;
|
|
670
|
+
if (links.some((span) => overlaps(span, offset, end))) continue;
|
|
671
|
+
const hashtag = match[1];
|
|
672
|
+
const username = match[2];
|
|
673
|
+
if (hashtag !== void 0 && includeHashtags) spans.push({
|
|
674
|
+
type: SpanType.Hashtag,
|
|
675
|
+
offset,
|
|
676
|
+
length: match[0].length,
|
|
677
|
+
tag: hashtag
|
|
678
|
+
});
|
|
679
|
+
else if (username !== void 0 && includeMentions) spans.push({
|
|
680
|
+
type: SpanType.Mention,
|
|
681
|
+
offset,
|
|
682
|
+
length: username.length + 1,
|
|
683
|
+
username
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
return spans.sort((left, right) => left.offset - right.offset || right.length - left.length);
|
|
687
|
+
}
|
|
688
|
+
// src/builders/message-markup.ts
|
|
689
|
+
/** Приводит фрагмент сообщения к формату общего билдера разметки. */
|
|
690
|
+
function markupContent(value) {
|
|
691
|
+
if (typeof value === "string") return value;
|
|
692
|
+
const { text: content, entities: spans } = resolveMessageMarkup(value);
|
|
674
693
|
return {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
nextCursor,
|
|
678
|
-
limit: pickNumber(pagination, "limit", 0) || void 0,
|
|
679
|
-
raw: body
|
|
694
|
+
content,
|
|
695
|
+
spans
|
|
680
696
|
};
|
|
681
697
|
}
|
|
682
|
-
/**
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
*/
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
const nextCursor = readCursor(body);
|
|
691
|
-
const total = pickNumber(body, "total", -1);
|
|
692
|
-
return {
|
|
693
|
-
items,
|
|
694
|
-
hasMore: pickBoolean(body, "hasMore", nextCursor !== null),
|
|
695
|
-
nextCursor,
|
|
696
|
-
...total >= 0 ? { total } : {},
|
|
697
|
-
raw: body
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
/**
|
|
701
|
-
* Читает страницу постраничной схемы: `data.pagination.{page,limit,total,hasMore}`.
|
|
702
|
-
*
|
|
703
|
-
* Если сервер вместо этого прислал курсор, он тоже подхватывается — некоторые списки
|
|
704
|
-
* отвечают в курсорной форме, хотя документация описывает постраничную.
|
|
705
|
-
*/
|
|
706
|
-
function readPagedPage(body, ...fields) {
|
|
707
|
-
const pagination = pickObject(body, "pagination");
|
|
708
|
-
const items = readItems(body, fields);
|
|
709
|
-
const nextCursor = readCursor(body);
|
|
710
|
-
return {
|
|
711
|
-
items,
|
|
712
|
-
hasMore: pickBoolean(pagination, "hasMore", pickBoolean(body, "hasMore", nextCursor !== null)),
|
|
713
|
-
page: pickNumber(pagination, "page", 1),
|
|
714
|
-
limit: pickNumber(pagination, "limit", 0) || void 0,
|
|
715
|
-
total: pickNumber(pagination, "total", 0),
|
|
716
|
-
...nextCursor !== null ? { nextCursor } : {},
|
|
717
|
-
raw: body
|
|
718
|
-
};
|
|
719
|
-
}
|
|
720
|
-
/**
|
|
721
|
-
* Читает страницу схемы со смещением.
|
|
722
|
-
*
|
|
723
|
-
* Используется для списков со смещением, включая уведомления.
|
|
724
|
-
*/
|
|
725
|
-
function readOffsetPage(body, field, offset) {
|
|
726
|
-
const items = pickArray(body, field);
|
|
727
|
-
return {
|
|
728
|
-
items,
|
|
729
|
-
hasMore: pickBoolean(body, "hasMore"),
|
|
730
|
-
nextOffset: offset + items.length,
|
|
731
|
-
raw: body
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
/** Создаёт единый контракт пагинированной операции. */
|
|
735
|
-
function pageOperation(id, read) {
|
|
736
|
-
return defineBuiltInOperation(id, read);
|
|
737
|
-
}
|
|
738
|
-
/**
|
|
739
|
-
* Перебор страниц списка.
|
|
740
|
-
*
|
|
741
|
-
* Скрывает различия трёх схем пагинации: перебор элементов, страниц и сбор в массив
|
|
742
|
-
* выглядят одинаково независимо от эндпоинта.
|
|
743
|
-
*
|
|
744
|
-
* **Одноразовый.** Позиция хранится внутри, поэтому повторный перебор того же объекта
|
|
745
|
-
* ничего не вернёт: он продолжится с места, где закончился прошлый. Нужен второй проход —
|
|
746
|
-
* возьмите новый перебор у того же метода ресурса.
|
|
747
|
-
*
|
|
748
|
-
* @example Перебор элементов
|
|
749
|
-
* ```ts
|
|
750
|
-
* for await (const post of itd.posts.iterate({ tab: 'following' })) {
|
|
751
|
-
* console.log(post.content);
|
|
752
|
-
* }
|
|
753
|
-
* ```
|
|
754
|
-
*
|
|
755
|
-
* @example Первые сто элементов
|
|
756
|
-
* ```ts
|
|
757
|
-
* const posts = await itd.posts.iterate({ tab: 'popular' }).collect(100);
|
|
758
|
-
* ```
|
|
759
|
-
*
|
|
760
|
-
* @example Постранично
|
|
761
|
-
* ```ts
|
|
762
|
-
* for await (const page of itd.users.followers('nowkie').pages()) {
|
|
763
|
-
* console.log(page.items.length, 'из', page.total);
|
|
764
|
-
* }
|
|
765
|
-
* ```
|
|
766
|
-
*/
|
|
767
|
-
var Paginator = class {
|
|
768
|
-
#options;
|
|
769
|
-
#maxPages;
|
|
770
|
-
#state;
|
|
771
|
-
#finished = false;
|
|
772
|
-
#pagesLoaded = 0;
|
|
773
|
-
constructor(options) {
|
|
774
|
-
if (options.maxPages !== void 0 && (!Number.isInteger(options.maxPages) || options.maxPages < 1)) throw new ItdConfigError(`maxPages должен быть целым числом не меньше 1, получено: ${options.maxPages}`);
|
|
775
|
-
this.#options = options;
|
|
776
|
-
this.#maxPages = options.maxPages ?? 1e3;
|
|
777
|
-
this.#state = options.start ?? {};
|
|
698
|
+
/** Неизменяемый билдер разметки для сообщений чата. */
|
|
699
|
+
var MessageMarkupBuilder = class MessageMarkupBuilder {
|
|
700
|
+
/** @internal */
|
|
701
|
+
[BUILDER] = true;
|
|
702
|
+
#markup;
|
|
703
|
+
/** @internal Создавайте билдер функцией {@link messageMarkup}. */
|
|
704
|
+
constructor(builder) {
|
|
705
|
+
this.#markup = builder;
|
|
778
706
|
}
|
|
779
|
-
/**
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
* @returns страница либо `null`, если перебор закончен
|
|
783
|
-
*/
|
|
784
|
-
async next() {
|
|
785
|
-
if (this.#finished) return null;
|
|
786
|
-
if (this.#options.signal?.aborted) return null;
|
|
787
|
-
if (this.#pagesLoaded >= this.#maxPages) {
|
|
788
|
-
this.#finished = true;
|
|
789
|
-
return null;
|
|
790
|
-
}
|
|
791
|
-
const previous = this.#state;
|
|
792
|
-
const page = await this.#options.load(previous);
|
|
793
|
-
this.#pagesLoaded += 1;
|
|
794
|
-
this.#state = this.#advance(previous, page);
|
|
795
|
-
return page;
|
|
707
|
+
/** Дописывает текст без форматирования. */
|
|
708
|
+
text(value) {
|
|
709
|
+
return new MessageMarkupBuilder(this.#markup.text(value));
|
|
796
710
|
}
|
|
797
|
-
/**
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
* Полезно, когда нужны сведения о самой странице — например `total`.
|
|
801
|
-
*/
|
|
802
|
-
async *pages() {
|
|
803
|
-
for (;;) {
|
|
804
|
-
const page = await this.next();
|
|
805
|
-
if (!page) return;
|
|
806
|
-
yield page;
|
|
807
|
-
}
|
|
711
|
+
/** Дописывает переводы строк. */
|
|
712
|
+
newline(count = 1) {
|
|
713
|
+
return new MessageMarkupBuilder(this.#markup.newline(count));
|
|
808
714
|
}
|
|
809
|
-
/**
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
if (this.#options.signal?.aborted) return;
|
|
813
|
-
yield item;
|
|
814
|
-
}
|
|
715
|
+
/** Дописывает фрагмент с указанным типом разметки сообщения. */
|
|
716
|
+
span(content, entity) {
|
|
717
|
+
return new MessageMarkupBuilder(this.#markup.span(markupContent(content), entity));
|
|
815
718
|
}
|
|
816
|
-
/**
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
* @param max сколько элементов достаточно; без него перебираются все страницы
|
|
820
|
-
*/
|
|
821
|
-
async collect(max) {
|
|
822
|
-
if (max !== void 0 && max <= 0) return [];
|
|
823
|
-
const result = [];
|
|
824
|
-
for await (const item of this) {
|
|
825
|
-
result.push(item);
|
|
826
|
-
if (max !== void 0 && result.length >= max) break;
|
|
827
|
-
}
|
|
828
|
-
return result;
|
|
719
|
+
/** Дописывает жирный текст. */
|
|
720
|
+
bold(content) {
|
|
721
|
+
return this.span(content, { type: SpanType.Bold });
|
|
829
722
|
}
|
|
830
|
-
/**
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
* Здесь же стоят предохранители: пустая страница при `hasMore`, неизменившийся курсор
|
|
834
|
-
* и отсутствие курсора останавливают перебор. Без них ошибка на сервере превратилась бы
|
|
835
|
-
* в бесконечный цикл запросов.
|
|
836
|
-
*/
|
|
837
|
-
#advance(previous, page) {
|
|
838
|
-
if (!page.hasMore || page.items.length === 0) {
|
|
839
|
-
this.#finished = true;
|
|
840
|
-
return previous;
|
|
841
|
-
}
|
|
842
|
-
if (this.#options.mode === PaginationMode.Cursor) {
|
|
843
|
-
const cursor = page.nextCursor ?? void 0;
|
|
844
|
-
if (!cursor || cursor === previous.cursor) {
|
|
845
|
-
this.#finished = true;
|
|
846
|
-
return previous;
|
|
847
|
-
}
|
|
848
|
-
return { cursor };
|
|
849
|
-
}
|
|
850
|
-
if (this.#options.mode === PaginationMode.Page) return { page: (previous.page ?? 1) + 1 };
|
|
851
|
-
return { offset: page.nextOffset ?? (previous.offset ?? 0) + page.items.length };
|
|
723
|
+
/** Дописывает курсивный текст. */
|
|
724
|
+
italic(content) {
|
|
725
|
+
return this.span(content, { type: SpanType.Italic });
|
|
852
726
|
}
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
var BaseResource = class {
|
|
857
|
-
/** @internal */
|
|
858
|
-
http;
|
|
859
|
-
constructor(http) {
|
|
860
|
-
this.http = http;
|
|
727
|
+
/** Дописывает подчёркнутый текст. */
|
|
728
|
+
underline(content) {
|
|
729
|
+
return this.span(content, { type: SpanType.Underline });
|
|
861
730
|
}
|
|
862
|
-
/**
|
|
863
|
-
|
|
864
|
-
return this.
|
|
731
|
+
/** Дописывает зачёркнутый текст. */
|
|
732
|
+
strike(content) {
|
|
733
|
+
return this.span(content, { type: SpanType.Strike });
|
|
734
|
+
}
|
|
735
|
+
/** Дописывает текст под спойлером. */
|
|
736
|
+
spoiler(content) {
|
|
737
|
+
return this.span(content, { type: SpanType.Spoiler });
|
|
738
|
+
}
|
|
739
|
+
/** Дописывает фрагмент кода. */
|
|
740
|
+
code(content) {
|
|
741
|
+
return this.span(content, { type: "code" });
|
|
865
742
|
}
|
|
866
743
|
/**
|
|
867
|
-
*
|
|
868
|
-
*
|
|
869
|
-
* @param mode схема пагинации эндпоинта
|
|
870
|
-
* @param load загружает одну страницу для указанной позиции
|
|
871
|
-
* @param options только управление самим перебором: предел, отмена и начальная позиция
|
|
744
|
+
* Дописывает ссылку. Для строки без явного URL сама строка служит адресом ссылки.
|
|
745
|
+
* Для вложенного форматированного фрагмента передайте адрес отдельно.
|
|
872
746
|
*/
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
...options?.start !== void 0 ? { start: options.start } : {}
|
|
747
|
+
link(content, url) {
|
|
748
|
+
const address = url ?? (typeof content === "string" ? content : void 0);
|
|
749
|
+
if (address === void 0) throw new ItdConfigError("Для форматированного текста ссылки нужно явно передать URL");
|
|
750
|
+
return this.span(content, {
|
|
751
|
+
type: "text_link",
|
|
752
|
+
url: address
|
|
880
753
|
});
|
|
881
754
|
}
|
|
882
|
-
/**
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
* Путь, параметры запроса и разбор ответа задаются один раз; `list` и `iterate`
|
|
886
|
-
* строятся из них.
|
|
887
|
-
*
|
|
888
|
-
* @example
|
|
889
|
-
* ```ts
|
|
890
|
-
* #feed = this.paginated<Post, FeedParams>({
|
|
891
|
-
* operation: POSTS_LIST,
|
|
892
|
-
* path: () => '/api/posts',
|
|
893
|
-
* query: (p) => ({ tab: p.tab, limit: p.limit }),
|
|
894
|
-
* start: (p) => (p.cursor ? { cursor: p.cursor } : {}),
|
|
895
|
-
* mode: PaginationMode.Cursor,
|
|
896
|
-
* });
|
|
897
|
-
* ```
|
|
898
|
-
*/
|
|
899
|
-
paginated(spec) {
|
|
900
|
-
const load = async (params, state, options = {}) => {
|
|
901
|
-
const operation = typeof spec.operation === "function" ? spec.operation(params) : spec.operation;
|
|
902
|
-
return this.http.execute(operation, {
|
|
903
|
-
path: spec.path(params),
|
|
904
|
-
query: withPageState(spec.query(params), state),
|
|
905
|
-
...options
|
|
906
|
-
});
|
|
907
|
-
};
|
|
755
|
+
/** Возвращает содержимое для отправки или редактирования сообщения. */
|
|
756
|
+
build() {
|
|
757
|
+
const { content: text, spans: entities } = this.#markup.build();
|
|
908
758
|
return {
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
const { maxPages, ...requestOptions } = options;
|
|
912
|
-
return this.paginate(spec.mode, (state) => load(params, state, requestOptions), {
|
|
913
|
-
...maxPages !== void 0 ? { maxPages } : {},
|
|
914
|
-
...requestOptions.signal !== void 0 ? { signal: requestOptions.signal } : {},
|
|
915
|
-
start: spec.start(params)
|
|
916
|
-
});
|
|
917
|
-
}
|
|
759
|
+
text,
|
|
760
|
+
entities
|
|
918
761
|
};
|
|
919
762
|
}
|
|
763
|
+
/** Возвращает содержимое сообщения для сериализации. */
|
|
764
|
+
toJSON() {
|
|
765
|
+
return this.build();
|
|
766
|
+
}
|
|
920
767
|
};
|
|
921
|
-
/**
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
768
|
+
/**
|
|
769
|
+
* Начинает сборку форматированного текста сообщения.
|
|
770
|
+
*
|
|
771
|
+
* @example
|
|
772
|
+
* ```ts
|
|
773
|
+
* const message = messageMarkup().bold('Пример').text(' ').code('itd.chats').build();
|
|
774
|
+
* await itd.chats.sendMessage(chatId, message);
|
|
775
|
+
* ```
|
|
776
|
+
*/
|
|
777
|
+
function messageMarkup(text = "") {
|
|
778
|
+
return new MessageMarkupBuilder(markup(text));
|
|
929
779
|
}
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
const DEFAULT_AROUND_LIMIT = 40;
|
|
934
|
-
const HISTORY_PAGE_LIMIT = 50;
|
|
935
|
-
const LIST = defineBuiltInOperation("chats.list", normalizeChatList);
|
|
936
|
-
const GET = defineBuiltInOperation("chats.get", normalizeChatSummary);
|
|
937
|
-
const UNREAD = defineBuiltInOperation("chats.unread", normalizeChatUnread);
|
|
938
|
-
const MESSAGES = defineBuiltInOperation("chats.messages", normalizeChatHistory);
|
|
939
|
-
const MESSAGES_AROUND = defineBuiltInOperation("chats.messagesAround", normalizeChatHistory);
|
|
940
|
-
const MEDIA = defineBuiltInOperation("chats.media", normalizeChatMedia);
|
|
941
|
-
const FILE_LINKS = defineBuiltInOperation("chats.fileLinks", (body) => body.links);
|
|
942
|
-
const PRESENCE = defineBuiltInOperation("chats.presence");
|
|
943
|
-
const PRESENCE_MANY = defineBuiltInOperation("chats.presenceMany", (body) => body.presence);
|
|
944
|
-
const REACTION_CATALOG = defineBuiltInOperation("chats.reactionCatalog", normalizeChatReactionCatalog);
|
|
945
|
-
const REACTIONS = defineBuiltInOperation("chats.reactions", normalizeChatReactions);
|
|
946
|
-
const HEARD_MESSAGES = defineBuiltInOperation("chats.heardMessages", (body) => body.message_ids);
|
|
947
|
-
const UPDATES = defineBuiltInOperation("chats.updates", normalizeChatUpdates);
|
|
948
|
-
const CREATE_DIRECT = defineBuiltInOperation("chats.createDirect", normalizeChatDirect);
|
|
949
|
-
const SEND_MESSAGE = defineBuiltInOperation("chats.sendMessage", normalizeChatSent);
|
|
950
|
-
const SEND_MESSAGE_TO_USER = defineBuiltInOperation("chats.sendMessageToUser", normalizeChatFirstMessage);
|
|
951
|
-
const EDIT_MESSAGE = defineBuiltInOperation("chats.editMessage", normalizeChatEdited);
|
|
952
|
-
const FORWARD_MESSAGES = defineBuiltInOperation("chats.forwardMessages", normalizeChatForwarded);
|
|
953
|
-
const DELETE_MESSAGES_FOR_ME = defineBuiltInOperation("chats.deleteMessagesForMe", normalizeChatDeleted);
|
|
954
|
-
const DELETE_MESSAGES_FOR_ALL = defineBuiltInOperation("chats.deleteMessagesForAll", normalizeChatDeleted);
|
|
955
|
-
const SET_PINNED = defineBuiltInOperation("chats.setPinned", voidResult);
|
|
956
|
-
const SET_MUTED = defineBuiltInOperation("chats.setMuted", voidResult);
|
|
957
|
-
const SET_UNREAD = defineBuiltInOperation("chats.setUnread", voidResult);
|
|
958
|
-
const MARK_READ = defineBuiltInOperation("chats.markRead", normalizeChatRead);
|
|
959
|
-
const ACCEPT_REQUEST = defineBuiltInOperation("chats.acceptRequest", voidResult);
|
|
960
|
-
const MARK_HEARD = defineBuiltInOperation("chats.markHeard", voidResult);
|
|
961
|
-
const SEND_ACTION = defineBuiltInOperation("chats.sendAction", voidResult);
|
|
962
|
-
const CLEAR_HISTORY = defineBuiltInOperation("chats.clearHistory", normalizeChatChange);
|
|
963
|
-
const CLEAR_HISTORY_FOR_ALL = defineBuiltInOperation("chats.clearHistoryForAll", normalizeChatChange);
|
|
964
|
-
const DELETE = defineBuiltInOperation("chats.delete", normalizeChatChange);
|
|
965
|
-
const SET_REACTIONS = defineBuiltInOperation("chats.setReactions", normalizeChatReactions);
|
|
966
|
-
function chatPath(chatId) {
|
|
967
|
-
return `${CHATS_PATH}/${encodePathSegment(chatId, "идентификатор чата")}`;
|
|
968
|
-
}
|
|
969
|
-
function messageSegment(messageId) {
|
|
970
|
-
return encodePathSegment(messageId, "идентификатор сообщения");
|
|
780
|
+
/** Собирает разметку сообщения из любой формы ввода. @internal */
|
|
781
|
+
function resolveMessageMarkup(input) {
|
|
782
|
+
return resolveInput(input, messageMarkup, (value) => value);
|
|
971
783
|
}
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
784
|
+
// src/builders/message.ts
|
|
785
|
+
/** Неизменяемый билдер сообщения для чата. Создаётся через {@link message}. */
|
|
786
|
+
var MessageBuilder = class MessageBuilder {
|
|
975
787
|
/** @internal */
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
* Возвращает страницу чатов текущего пользователя.
|
|
982
|
-
*
|
|
983
|
-
* @example
|
|
984
|
-
* ```ts
|
|
985
|
-
* const page = await itd.chats.list({ limit: 20 });
|
|
986
|
-
* if (page.nextBefore) await itd.chats.list({ before: page.nextBefore, limit: 20 });
|
|
987
|
-
* ```
|
|
988
|
-
*/
|
|
989
|
-
list(params = {}, options = {}) {
|
|
990
|
-
return this.http.execute(LIST, {
|
|
991
|
-
path: CHATS_PATH,
|
|
992
|
-
query: {
|
|
993
|
-
before: params.before,
|
|
994
|
-
limit: params.limit,
|
|
995
|
-
manual_unread: 1
|
|
996
|
-
},
|
|
997
|
-
...options
|
|
998
|
-
});
|
|
999
|
-
}
|
|
1000
|
-
/**
|
|
1001
|
-
* Перебирает чаты текущего пользователя по курсору списка.
|
|
1002
|
-
*
|
|
1003
|
-
* @example
|
|
1004
|
-
* ```ts
|
|
1005
|
-
* for await (const chat of itd.chats.iterate({ limit: 20 })) {
|
|
1006
|
-
* console.log(chat.chatId, chat.unreadCount);
|
|
1007
|
-
* }
|
|
1008
|
-
* ```
|
|
1009
|
-
*/
|
|
1010
|
-
iterate(params = {}, options = {}) {
|
|
1011
|
-
return this.paginate(PaginationMode.Cursor, async ({ cursor }) => {
|
|
1012
|
-
const page = await this.list({
|
|
1013
|
-
...params,
|
|
1014
|
-
before: cursor
|
|
1015
|
-
}, options);
|
|
1016
|
-
return {
|
|
1017
|
-
items: page.chats,
|
|
1018
|
-
hasMore: Boolean(page.nextBefore),
|
|
1019
|
-
nextCursor: page.nextBefore,
|
|
1020
|
-
raw: page
|
|
1021
|
-
};
|
|
1022
|
-
}, {
|
|
1023
|
-
...options,
|
|
1024
|
-
start: { cursor: params.before }
|
|
1025
|
-
});
|
|
1026
|
-
}
|
|
1027
|
-
/** Возвращает сводку чата по его идентификатору. */
|
|
1028
|
-
get(chatId, options = {}) {
|
|
1029
|
-
return this.http.execute(GET, {
|
|
1030
|
-
path: chatPath(chatId),
|
|
1031
|
-
query: { manual_unread: 1 },
|
|
1032
|
-
...options
|
|
1033
|
-
});
|
|
1034
|
-
}
|
|
1035
|
-
/** Возвращает число непрочитанных и число чатов с непрочитанным. */
|
|
1036
|
-
unread(options = {}) {
|
|
1037
|
-
return this.http.execute(UNREAD, {
|
|
1038
|
-
path: `${CHATS_PATH}/unread`,
|
|
1039
|
-
query: { manual_unread: 1 },
|
|
1040
|
-
...options
|
|
1041
|
-
});
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Загружает историю, начиная с последних сообщений.
|
|
1045
|
-
*
|
|
1046
|
-
* Для следующей страницы передайте ID последнего сообщения страницы в `before`.
|
|
1047
|
-
* Для последовательного чтения используйте {@link iterateMessages}.
|
|
1048
|
-
*/
|
|
1049
|
-
messages(chatId, params = {}, options = {}) {
|
|
1050
|
-
return this.http.execute(MESSAGES, {
|
|
1051
|
-
path: `${chatPath(chatId)}/messages`,
|
|
1052
|
-
query: {
|
|
1053
|
-
before: params.before,
|
|
1054
|
-
limit: params.limit
|
|
1055
|
-
},
|
|
1056
|
-
...options
|
|
1057
|
-
});
|
|
1058
|
-
}
|
|
1059
|
-
/**
|
|
1060
|
-
* Перебирает сообщения от новых к старым, подставляя ID последнего сообщения как курсор.
|
|
1061
|
-
*
|
|
1062
|
-
* @example
|
|
1063
|
-
* ```ts
|
|
1064
|
-
* for await (const message of itd.chats.iterateMessages(chatId)) {
|
|
1065
|
-
* console.log(message.text);
|
|
1066
|
-
* }
|
|
1067
|
-
* ```
|
|
1068
|
-
*/
|
|
1069
|
-
iterateMessages(chatId, params = {}, options = {}) {
|
|
1070
|
-
const limit = params.limit ?? HISTORY_PAGE_LIMIT;
|
|
1071
|
-
return this.paginate(PaginationMode.Cursor, async ({ cursor }) => {
|
|
1072
|
-
const page = await this.messages(chatId, {
|
|
1073
|
-
limit,
|
|
1074
|
-
before: cursor
|
|
1075
|
-
}, options);
|
|
1076
|
-
const nextCursor = page.messages.at(-1)?.messageId;
|
|
1077
|
-
return {
|
|
1078
|
-
items: page.messages,
|
|
1079
|
-
hasMore: nextCursor !== void 0 && (page.hasOlder ?? page.messages.length >= limit),
|
|
1080
|
-
nextCursor,
|
|
1081
|
-
raw: page
|
|
1082
|
-
};
|
|
1083
|
-
}, {
|
|
1084
|
-
...options,
|
|
1085
|
-
start: { cursor: params.before }
|
|
1086
|
-
});
|
|
1087
|
-
}
|
|
1088
|
-
/** Загружает часть истории вокруг указанного сообщения. */
|
|
1089
|
-
messagesAround(chatId, messageId, limit = DEFAULT_AROUND_LIMIT, options = {}) {
|
|
1090
|
-
return this.http.execute(MESSAGES_AROUND, {
|
|
1091
|
-
path: `${chatPath(chatId)}/messages/around/${messageSegment(messageId)}`,
|
|
1092
|
-
query: { limit },
|
|
1093
|
-
...options
|
|
1094
|
-
});
|
|
788
|
+
[BUILDER] = true;
|
|
789
|
+
#state;
|
|
790
|
+
/** @internal */
|
|
791
|
+
constructor(state) {
|
|
792
|
+
this.#state = state;
|
|
1095
793
|
}
|
|
1096
|
-
/**
|
|
1097
|
-
|
|
1098
|
-
return
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
before: params.before,
|
|
1103
|
-
limit: params.limit
|
|
1104
|
-
},
|
|
1105
|
-
...options
|
|
794
|
+
/** Заменяет текст и его форматирование, сохраняя карточки постов и файлы. */
|
|
795
|
+
text(text) {
|
|
796
|
+
return new MessageBuilder({
|
|
797
|
+
...this.#state,
|
|
798
|
+
text,
|
|
799
|
+
entities: []
|
|
1106
800
|
});
|
|
1107
801
|
}
|
|
1108
|
-
/**
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
* ```ts
|
|
1114
|
-
* const { fileId } = await itd.chats.uploadFile(file);
|
|
1115
|
-
* await itd.chats.sendMessage(chatId, { text: '', attachmentIds: [fileId] });
|
|
1116
|
-
* ```
|
|
1117
|
-
*/
|
|
1118
|
-
uploadFile(file, uploadOptions = {}, options = {}) {
|
|
1119
|
-
return uploadChatFile(this.http, this.#host, file, uploadOptions, options);
|
|
1120
|
-
}
|
|
1121
|
-
/** Получает свежие ссылки для файлов из указанного чата. */
|
|
1122
|
-
fileLinks(chatId, fileIds, options = {}) {
|
|
1123
|
-
return this.http.execute(FILE_LINKS, {
|
|
1124
|
-
path: `${chatPath(chatId)}/file-links`,
|
|
1125
|
-
body: { file_ids: fileIds },
|
|
1126
|
-
...options
|
|
802
|
+
/** Заменяет текст и форматирование результатом {@link MessageMarkupInput}. */
|
|
803
|
+
markup(input) {
|
|
804
|
+
return new MessageBuilder({
|
|
805
|
+
...this.#state,
|
|
806
|
+
...resolveMessageMarkup(input)
|
|
1127
807
|
});
|
|
1128
808
|
}
|
|
1129
|
-
/**
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
...
|
|
809
|
+
/** Добавляет карточку поста по его ID. Сообщение с карточкой можно отправить без текста. */
|
|
810
|
+
post(postId) {
|
|
811
|
+
const posts = this.#state.posts ?? [];
|
|
812
|
+
return new MessageBuilder({
|
|
813
|
+
...this.#state,
|
|
814
|
+
posts: [...posts, {
|
|
815
|
+
type: "post",
|
|
816
|
+
postId
|
|
817
|
+
}]
|
|
1134
818
|
});
|
|
1135
819
|
}
|
|
1136
|
-
/**
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
...
|
|
820
|
+
/** Прикладывает файл, который клиент загрузит перед отправкой сообщения. */
|
|
821
|
+
attach(file) {
|
|
822
|
+
const files = this.#state.files ?? [];
|
|
823
|
+
return new MessageBuilder({
|
|
824
|
+
...this.#state,
|
|
825
|
+
files: [...files, file]
|
|
1142
826
|
});
|
|
1143
827
|
}
|
|
1144
|
-
/**
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
...
|
|
828
|
+
/** Прикладывает файл, уже загруженный в мессенджер. */
|
|
829
|
+
attachId(fileId) {
|
|
830
|
+
const ids = this.#state.attachmentIds ?? [];
|
|
831
|
+
return new MessageBuilder({
|
|
832
|
+
...this.#state,
|
|
833
|
+
attachmentIds: [...ids, fileId]
|
|
1149
834
|
});
|
|
1150
835
|
}
|
|
1151
|
-
/**
|
|
1152
|
-
|
|
1153
|
-
return
|
|
1154
|
-
|
|
1155
|
-
|
|
836
|
+
/** Убирает все вложения, в том числе при редактировании отправленного сообщения. */
|
|
837
|
+
clearAttachments() {
|
|
838
|
+
return new MessageBuilder({
|
|
839
|
+
...this.#state,
|
|
840
|
+
files: [],
|
|
841
|
+
attachmentIds: []
|
|
1156
842
|
});
|
|
1157
843
|
}
|
|
1158
|
-
/**
|
|
1159
|
-
|
|
1160
|
-
return
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
...options
|
|
844
|
+
/** Отвечает на сообщение в этом чате. */
|
|
845
|
+
replyTo(messageId) {
|
|
846
|
+
return new MessageBuilder({
|
|
847
|
+
...this.#state,
|
|
848
|
+
replyToId: messageId
|
|
1164
849
|
});
|
|
1165
850
|
}
|
|
1166
|
-
/**
|
|
1167
|
-
|
|
1168
|
-
return
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
since,
|
|
1172
|
-
limit,
|
|
1173
|
-
capabilities: "chat_settings",
|
|
1174
|
-
manual_unread: 1
|
|
1175
|
-
},
|
|
1176
|
-
...options
|
|
851
|
+
/** Задаёт UUIDv7, по которому сервер распознаёт повторную отправку. */
|
|
852
|
+
clientMessageId(id) {
|
|
853
|
+
return new MessageBuilder({
|
|
854
|
+
...this.#state,
|
|
855
|
+
clientMessageId: id
|
|
1177
856
|
});
|
|
1178
857
|
}
|
|
1179
|
-
/**
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
...options
|
|
1185
|
-
});
|
|
858
|
+
/** Собирает данные сообщения. */
|
|
859
|
+
build() {
|
|
860
|
+
const { posts, ...input } = this.#state;
|
|
861
|
+
if (posts) input.entities = [...input.entities ?? [], ...posts];
|
|
862
|
+
return input;
|
|
1186
863
|
}
|
|
1187
|
-
/**
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
* @example
|
|
1191
|
-
* ```ts
|
|
1192
|
-
* const sent = await itd.chats.sendMessage(chatId, { text: 'Привет!' });
|
|
1193
|
-
* console.log(sent.messageId);
|
|
1194
|
-
* ```
|
|
1195
|
-
*/
|
|
1196
|
-
sendMessage(chatId, input, options = {}) {
|
|
1197
|
-
return this.http.execute(SEND_MESSAGE, {
|
|
1198
|
-
path: `${chatPath(chatId)}/messages`,
|
|
1199
|
-
body: {
|
|
1200
|
-
text: input.text,
|
|
1201
|
-
reply_to_id: input.replyToId ?? null,
|
|
1202
|
-
attachments: input.attachmentIds?.length ? input.attachmentIds : void 0,
|
|
1203
|
-
entities: input.entities?.length ? input.entities.map(writeChatEntity) : void 0,
|
|
1204
|
-
client_message_id: input.clientMessageId
|
|
1205
|
-
},
|
|
1206
|
-
...options
|
|
1207
|
-
});
|
|
864
|
+
/** Возвращает данные сообщения для сериализации. */
|
|
865
|
+
toJSON() {
|
|
866
|
+
return this.build();
|
|
1208
867
|
}
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
868
|
+
};
|
|
869
|
+
/**
|
|
870
|
+
* Начинает сборку сообщения для чата.
|
|
871
|
+
*
|
|
872
|
+
* @example
|
|
873
|
+
* ```ts
|
|
874
|
+
* await itd.chats.sendMessage(chatId, message('Посмотрите этот пост').post(postId));
|
|
875
|
+
* ```
|
|
876
|
+
*/
|
|
877
|
+
function message(text = "") {
|
|
878
|
+
return new MessageBuilder({ text });
|
|
879
|
+
}
|
|
880
|
+
/** Собирает данные сообщения из любой формы ввода. @internal */
|
|
881
|
+
function resolveMessage(input) {
|
|
882
|
+
return resolveInput(input, message, (value) => value);
|
|
883
|
+
}
|
|
884
|
+
// src/domain/mime.ts
|
|
885
|
+
/** Изображения, которые принимает `POST /api/files/upload`. */
|
|
886
|
+
const IMAGE_MIME_TYPES = Object.freeze([
|
|
887
|
+
"image/jpeg",
|
|
888
|
+
"image/png",
|
|
889
|
+
"image/gif",
|
|
890
|
+
"image/webp",
|
|
891
|
+
"image/avif",
|
|
892
|
+
"image/heic",
|
|
893
|
+
"image/heif"
|
|
894
|
+
]);
|
|
895
|
+
/** Видео, которые принимает `POST /api/files/upload`. */
|
|
896
|
+
const VIDEO_MIME_TYPES = Object.freeze([
|
|
897
|
+
"video/mp4",
|
|
898
|
+
"video/webm",
|
|
899
|
+
"video/quicktime"
|
|
900
|
+
]);
|
|
901
|
+
/** Аудио для голосовых комментариев. */
|
|
902
|
+
const AUDIO_MIME_TYPES = Object.freeze(["audio/ogg"]);
|
|
903
|
+
/** Все типы, которые принимает загрузка. */
|
|
904
|
+
const ALLOWED_MIME_TYPES = Object.freeze([
|
|
905
|
+
...IMAGE_MIME_TYPES,
|
|
906
|
+
...VIDEO_MIME_TYPES,
|
|
907
|
+
...AUDIO_MIME_TYPES
|
|
908
|
+
]);
|
|
909
|
+
/**
|
|
910
|
+
* Соответствие расширения и MIME-типа.
|
|
911
|
+
*
|
|
912
|
+
* Своя маленькая таблица вместо зависимости: библиотеке нужны ровно те типы,
|
|
913
|
+
* которые принимает API.
|
|
914
|
+
*/
|
|
915
|
+
const EXTENSION_TO_MIME = Object.freeze({
|
|
916
|
+
jpg: "image/jpeg",
|
|
917
|
+
jpeg: "image/jpeg",
|
|
918
|
+
jfif: "image/jpeg",
|
|
919
|
+
png: "image/png",
|
|
920
|
+
gif: "image/gif",
|
|
921
|
+
webp: "image/webp",
|
|
922
|
+
avif: "image/avif",
|
|
923
|
+
heic: "image/heic",
|
|
924
|
+
heif: "image/heif",
|
|
925
|
+
mp4: "video/mp4",
|
|
926
|
+
m4v: "video/mp4",
|
|
927
|
+
webm: "video/webm",
|
|
928
|
+
mov: "video/quicktime",
|
|
929
|
+
qt: "video/quicktime",
|
|
930
|
+
ogg: "audio/ogg",
|
|
931
|
+
oga: "audio/ogg",
|
|
932
|
+
opus: "audio/ogg"
|
|
933
|
+
});
|
|
934
|
+
/** Определяет MIME-тип по расширению имени файла. */
|
|
935
|
+
function mimeFromFilename(filename) {
|
|
936
|
+
const dot = filename.lastIndexOf(".");
|
|
937
|
+
if (dot < 0) return void 0;
|
|
938
|
+
return EXTENSION_TO_MIME[filename.slice(dot + 1).toLowerCase()];
|
|
939
|
+
}
|
|
940
|
+
/** Разрешён ли тип к загрузке. */
|
|
941
|
+
function isAllowedMime(mimeType) {
|
|
942
|
+
return ALLOWED_MIME_TYPES.includes(mimeType.toLowerCase());
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Проверяет тип файла до отправки.
|
|
946
|
+
*
|
|
947
|
+
* Отказ на стороне клиента экономит и время, и трафик: тот же `UNSUPPORTED_FILE_TYPE`
|
|
948
|
+
* пришёл бы с сервера, но уже после загрузки всего файла.
|
|
949
|
+
*
|
|
950
|
+
* @throws {ItdConfigError} если тип не поддерживается
|
|
951
|
+
*/
|
|
952
|
+
function assertAllowedMime(mimeType, filename) {
|
|
953
|
+
if (!mimeType) throw new ItdConfigError(`Не удалось определить тип файла${filename ? ` «${filename}»` : ""}. Укажите его явно: { file, filename, contentType }.`);
|
|
954
|
+
if (!isAllowedMime(mimeType)) throw new ItdConfigError(`Тип «${mimeType}» не поддерживается загрузкой. Допустимые: ${ALLOWED_MIME_TYPES.join(", ")}.`);
|
|
955
|
+
}
|
|
956
|
+
// src/uploads/chat.ts
|
|
957
|
+
const UPLOAD_PATH = "/api/v1/messenger/media/upload";
|
|
958
|
+
const PART_BYTES = 5242880;
|
|
959
|
+
const MAX_FILE_BYTES = 0x80000000;
|
|
960
|
+
const PART_TIMEOUT = 3e5;
|
|
961
|
+
const INIT_UPLOAD = passthroughOperation("chats.upload.init");
|
|
962
|
+
const UPLOAD_PART = voidOperation("chats.upload.part");
|
|
963
|
+
const FINALIZE_UPLOAD = passthroughOperation("chats.upload.finalize");
|
|
964
|
+
function sizeMismatch() {
|
|
965
|
+
return new ItdFileError("Размер потока вложения отличается от объявленного", { reason: ItdFileErrorReason.Read });
|
|
966
|
+
}
|
|
967
|
+
/** Читает поток частями фиксированного размера без накопления всего файла. */
|
|
968
|
+
async function* readParts(source, size) {
|
|
969
|
+
if (source.mode === FileTransferMode.Buffer) {
|
|
970
|
+
for (let offset = 0; offset < size; offset += PART_BYTES) yield source.blob.slice(offset, offset + PART_BYTES);
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
const reader = source.stream.getReader();
|
|
974
|
+
try {
|
|
975
|
+
let remaining = size;
|
|
976
|
+
let part = new Uint8Array(Math.min(PART_BYTES, remaining));
|
|
977
|
+
let filled = 0;
|
|
978
|
+
for (;;) {
|
|
979
|
+
const next = await reader.read();
|
|
980
|
+
if (next.done) break;
|
|
981
|
+
const chunk = next.value;
|
|
982
|
+
if (chunk.byteLength > remaining) throw sizeMismatch();
|
|
983
|
+
let offset = 0;
|
|
984
|
+
while (offset < chunk.byteLength) {
|
|
985
|
+
const length = Math.min(part.byteLength - filled, chunk.byteLength - offset);
|
|
986
|
+
part.set(chunk.subarray(offset, offset + length), filled);
|
|
987
|
+
offset += length;
|
|
988
|
+
filled += length;
|
|
989
|
+
remaining -= length;
|
|
990
|
+
if (filled === part.byteLength) {
|
|
991
|
+
yield part;
|
|
992
|
+
part = new Uint8Array(Math.min(PART_BYTES, remaining));
|
|
993
|
+
filled = 0;
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (remaining !== 0) throw sizeMismatch();
|
|
998
|
+
} finally {
|
|
999
|
+
reader.releaseLock();
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
/** Загружает вложение и отменяет передачу при закрытии клиента или смене аккаунта. @internal */
|
|
1003
|
+
async function uploadChatFile(http, host, input, upload, request) {
|
|
1004
|
+
const controller = new AbortController();
|
|
1005
|
+
const operation = {
|
|
1006
|
+
method: "POST",
|
|
1007
|
+
path: UPLOAD_PATH
|
|
1008
|
+
};
|
|
1009
|
+
const scope = http.createDeadlineScope({
|
|
1010
|
+
...request,
|
|
1011
|
+
...operation
|
|
1012
|
+
}, controller.signal);
|
|
1013
|
+
let task;
|
|
1014
|
+
try {
|
|
1015
|
+
const unmanage = host.manage({
|
|
1016
|
+
kind: "chats:upload",
|
|
1017
|
+
stop: () => controller.abort(),
|
|
1018
|
+
drain: async () => {
|
|
1019
|
+
await task?.catch(() => {});
|
|
1020
|
+
}
|
|
1021
|
+
});
|
|
1022
|
+
task = Promise.resolve().then(() => executeUpload(http, host.files, input, upload, {
|
|
1023
|
+
...request,
|
|
1024
|
+
deadline: 0,
|
|
1025
|
+
signal: scope.signal
|
|
1026
|
+
})).finally(unmanage);
|
|
1027
|
+
return await waitForRequest(task, scope.signal);
|
|
1028
|
+
} catch (error) {
|
|
1029
|
+
throw requestAbortError(scope, operation, error);
|
|
1030
|
+
} finally {
|
|
1031
|
+
scope.cleanup();
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
/** Выполняет запросы загрузки с одним источником и сигналом отмены. */
|
|
1035
|
+
async function executeUpload(http, files, input, upload, request) {
|
|
1036
|
+
request.signal?.throwIfAborted();
|
|
1037
|
+
const { filename, contentType, width, height, durationMs, waveform, thumbhash, thumb, onProgress } = upload;
|
|
1038
|
+
const source = await files.resolve(input, {
|
|
1039
|
+
filename,
|
|
1040
|
+
contentType,
|
|
1041
|
+
maxBytes: MAX_FILE_BYTES,
|
|
1042
|
+
requireKnownSize: true
|
|
1043
|
+
}, { signal: request.signal });
|
|
1044
|
+
try {
|
|
1045
|
+
const size = source.size;
|
|
1046
|
+
if (size === void 0 || size === 0) throw new ItdConfigError("Для загрузки вложения чата нужен известный ненулевой размер");
|
|
1047
|
+
const name = source.filename;
|
|
1048
|
+
const mime = source.contentType ?? (name && mimeFromFilename(name)) ?? "application/octet-stream";
|
|
1049
|
+
const { uploadId } = await http.execute(INIT_UPLOAD, {
|
|
1050
|
+
path: `${UPLOAD_PATH}/init`,
|
|
1051
|
+
body: {
|
|
1052
|
+
mime,
|
|
1053
|
+
size,
|
|
1054
|
+
totalParts: Math.ceil(size / PART_BYTES)
|
|
1055
|
+
},
|
|
1056
|
+
...request
|
|
1057
|
+
});
|
|
1058
|
+
const path = `${UPLOAD_PATH}/${encodePathSegment(uploadId, "идентификатор загрузки")}`;
|
|
1059
|
+
const headers = new Headers(request.headers);
|
|
1060
|
+
headers.set("Content-Type", "application/octet-stream");
|
|
1061
|
+
const partHeaders = Object.fromEntries(headers);
|
|
1062
|
+
let index = 0;
|
|
1063
|
+
let uploaded = 0;
|
|
1064
|
+
for await (const part of readParts(source, size)) {
|
|
1065
|
+
await http.execute(UPLOAD_PART, {
|
|
1066
|
+
...request,
|
|
1067
|
+
path: `${path}/part/${index++}`,
|
|
1068
|
+
body: part,
|
|
1069
|
+
headers: partHeaders,
|
|
1070
|
+
timeout: request.timeout ?? PART_TIMEOUT
|
|
1071
|
+
});
|
|
1072
|
+
uploaded += part instanceof Uint8Array ? part.byteLength : part.size;
|
|
1073
|
+
onProgress?.(uploaded, size);
|
|
1074
|
+
}
|
|
1075
|
+
return await http.execute(FINALIZE_UPLOAD, {
|
|
1076
|
+
path: `${path}/finalize`,
|
|
1213
1077
|
body: {
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1078
|
+
filename: name,
|
|
1079
|
+
width,
|
|
1080
|
+
height,
|
|
1081
|
+
durationMs,
|
|
1082
|
+
waveform,
|
|
1083
|
+
thumbhash,
|
|
1084
|
+
thumb
|
|
1085
|
+
},
|
|
1086
|
+
...request
|
|
1087
|
+
});
|
|
1088
|
+
} finally {
|
|
1089
|
+
if (source.mode === FileTransferMode.Stream) await source.close();
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
// src/resources/pagination.ts
|
|
1093
|
+
/** Схема пагинации эндпоинта. */
|
|
1094
|
+
const PaginationMode = Object.freeze({
|
|
1095
|
+
/** Следующая страница запрашивается непрозрачным курсором. */
|
|
1096
|
+
Cursor: "cursor",
|
|
1097
|
+
/** Следующая страница запрашивается номером. */
|
|
1098
|
+
Page: "page",
|
|
1099
|
+
/** Следующая страница запрашивается смещением от начала списка. */
|
|
1100
|
+
Offset: "offset"
|
|
1101
|
+
});
|
|
1102
|
+
/** Применяет преобразование к элементам страницы, сохраняя сведения о пагинации. */
|
|
1103
|
+
function mapPage(page, map) {
|
|
1104
|
+
return {
|
|
1105
|
+
...page,
|
|
1106
|
+
items: page.items.map(map)
|
|
1107
|
+
};
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Достаёт список из ответа, перебирая все формы, которые встречаются у сервера.
|
|
1111
|
+
*
|
|
1112
|
+
* Список может прийти под именем сущности, под её альтернативным именем
|
|
1113
|
+
* (`followers` вместо `users`) либо голым массивом.
|
|
1114
|
+
*
|
|
1115
|
+
* @param fields имена полей в порядке предпочтения
|
|
1116
|
+
*/
|
|
1117
|
+
function readItems(body, fields) {
|
|
1118
|
+
if (Array.isArray(body)) return body;
|
|
1119
|
+
for (const field of fields) {
|
|
1120
|
+
const items = pickArray(body, field);
|
|
1121
|
+
if (items.length > 0) return items;
|
|
1122
|
+
}
|
|
1123
|
+
const primary = fields[0];
|
|
1124
|
+
return primary === void 0 ? [] : pickArray(body, primary);
|
|
1125
|
+
}
|
|
1126
|
+
/**
|
|
1127
|
+
* Достаёт курсор следующей страницы.
|
|
1128
|
+
*
|
|
1129
|
+
* Проверяются все известные места: внутри `pagination`, рядом со списком и во вложенном
|
|
1130
|
+
* объекте `meta.cursor.next`.
|
|
1131
|
+
*/
|
|
1132
|
+
function readCursor(body) {
|
|
1133
|
+
const pagination = pickObject(body, "pagination");
|
|
1134
|
+
const meta = pickObject(body, "meta");
|
|
1135
|
+
const metaCursor = pickObject(meta, "cursor");
|
|
1136
|
+
return pickString(pagination, "nextCursor") ?? pickString(body, "nextCursor") ?? pickString(body, "cursor") ?? pickString(metaCursor, "next") ?? null;
|
|
1137
|
+
}
|
|
1138
|
+
/**
|
|
1139
|
+
* Читает страницу курсорной схемы.
|
|
1140
|
+
*
|
|
1141
|
+
* Используется лентой, постами пользователя и постами по хэштегу.
|
|
1142
|
+
*
|
|
1143
|
+
* @param fields имена возможных полей со списком; первое — основное
|
|
1144
|
+
*/
|
|
1145
|
+
function readCursorPage(body, ...fields) {
|
|
1146
|
+
const pagination = pickObject(body, "pagination");
|
|
1147
|
+
const items = readItems(body, fields);
|
|
1148
|
+
const nextCursor = readCursor(body);
|
|
1149
|
+
return {
|
|
1150
|
+
items,
|
|
1151
|
+
hasMore: pickBoolean(pagination, "hasMore", pickBoolean(body, "hasMore", nextCursor !== null)),
|
|
1152
|
+
nextCursor,
|
|
1153
|
+
limit: pickNumber(pagination, "limit", 0) || void 0,
|
|
1154
|
+
raw: body
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Читает страницу курсорной схемы с курсором рядом со списком.
|
|
1159
|
+
*
|
|
1160
|
+
* Так устроены комментарии к посту и ответы на комментарий: `nextCursor` и `hasMore`
|
|
1161
|
+
* лежат на одном уровне со списком, а не внутри объекта `pagination`.
|
|
1162
|
+
*/
|
|
1163
|
+
function readFlatCursorPage(body, ...fields) {
|
|
1164
|
+
const items = readItems(body, fields);
|
|
1165
|
+
const nextCursor = readCursor(body);
|
|
1166
|
+
const total = pickNumber(body, "total", -1);
|
|
1167
|
+
return {
|
|
1168
|
+
items,
|
|
1169
|
+
hasMore: pickBoolean(body, "hasMore", nextCursor !== null),
|
|
1170
|
+
nextCursor,
|
|
1171
|
+
...total >= 0 ? { total } : {},
|
|
1172
|
+
raw: body
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Читает страницу постраничной схемы: `data.pagination.{page,limit,total,hasMore}`.
|
|
1177
|
+
*
|
|
1178
|
+
* Если сервер вместо этого прислал курсор, он тоже подхватывается — некоторые списки
|
|
1179
|
+
* отвечают в курсорной форме, хотя документация описывает постраничную.
|
|
1180
|
+
*/
|
|
1181
|
+
function readPagedPage(body, ...fields) {
|
|
1182
|
+
const pagination = pickObject(body, "pagination");
|
|
1183
|
+
const items = readItems(body, fields);
|
|
1184
|
+
const nextCursor = readCursor(body);
|
|
1185
|
+
return {
|
|
1186
|
+
items,
|
|
1187
|
+
hasMore: pickBoolean(pagination, "hasMore", pickBoolean(body, "hasMore", nextCursor !== null)),
|
|
1188
|
+
page: pickNumber(pagination, "page", 1),
|
|
1189
|
+
limit: pickNumber(pagination, "limit", 0) || void 0,
|
|
1190
|
+
total: pickNumber(pagination, "total", 0),
|
|
1191
|
+
...nextCursor !== null ? { nextCursor } : {},
|
|
1192
|
+
raw: body
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Читает страницу схемы со смещением.
|
|
1197
|
+
*
|
|
1198
|
+
* Используется для списков со смещением, включая уведомления.
|
|
1199
|
+
*/
|
|
1200
|
+
function readOffsetPage(body, field, offset) {
|
|
1201
|
+
const items = pickArray(body, field);
|
|
1202
|
+
return {
|
|
1203
|
+
items,
|
|
1204
|
+
hasMore: pickBoolean(body, "hasMore"),
|
|
1205
|
+
nextOffset: offset + items.length,
|
|
1206
|
+
raw: body
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
/** Создаёт единый контракт пагинированной операции. */
|
|
1210
|
+
function pageOperation(id, read) {
|
|
1211
|
+
return defineBuiltInOperation(id, read);
|
|
1212
|
+
}
|
|
1213
|
+
/**
|
|
1214
|
+
* Перебор страниц списка.
|
|
1215
|
+
*
|
|
1216
|
+
* Скрывает различия трёх схем пагинации: перебор элементов, страниц и сбор в массив
|
|
1217
|
+
* выглядят одинаково независимо от эндпоинта.
|
|
1218
|
+
*
|
|
1219
|
+
* **Одноразовый.** Позиция хранится внутри, поэтому повторный перебор того же объекта
|
|
1220
|
+
* ничего не вернёт: он продолжится с места, где закончился прошлый. Нужен второй проход —
|
|
1221
|
+
* возьмите новый перебор у того же метода ресурса.
|
|
1222
|
+
*
|
|
1223
|
+
* @example Перебор элементов
|
|
1224
|
+
* ```ts
|
|
1225
|
+
* for await (const post of itd.posts.iterate({ tab: 'following' })) {
|
|
1226
|
+
* console.log(post.content);
|
|
1227
|
+
* }
|
|
1228
|
+
* ```
|
|
1229
|
+
*
|
|
1230
|
+
* @example Первые сто элементов
|
|
1231
|
+
* ```ts
|
|
1232
|
+
* const posts = await itd.posts.iterate({ tab: 'popular' }).collect(100);
|
|
1233
|
+
* ```
|
|
1234
|
+
*
|
|
1235
|
+
* @example Постранично
|
|
1236
|
+
* ```ts
|
|
1237
|
+
* for await (const page of itd.users.followers('nowkie').pages()) {
|
|
1238
|
+
* console.log(page.items.length, 'из', page.total);
|
|
1239
|
+
* }
|
|
1240
|
+
* ```
|
|
1241
|
+
*/
|
|
1242
|
+
var Paginator = class {
|
|
1243
|
+
#options;
|
|
1244
|
+
#maxPages;
|
|
1245
|
+
#state;
|
|
1246
|
+
#finished = false;
|
|
1247
|
+
#pagesLoaded = 0;
|
|
1248
|
+
constructor(options) {
|
|
1249
|
+
if (options.maxPages !== void 0 && (!Number.isInteger(options.maxPages) || options.maxPages < 1)) throw new ItdConfigError(`maxPages должен быть целым числом не меньше 1, получено: ${options.maxPages}`);
|
|
1250
|
+
this.#options = options;
|
|
1251
|
+
this.#maxPages = options.maxPages ?? 1e3;
|
|
1252
|
+
this.#state = options.start ?? {};
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Загружает следующую страницу.
|
|
1256
|
+
*
|
|
1257
|
+
* @returns страница либо `null`, если перебор закончен
|
|
1258
|
+
*/
|
|
1259
|
+
async next() {
|
|
1260
|
+
if (this.#finished) return null;
|
|
1261
|
+
if (this.#options.signal?.aborted) return null;
|
|
1262
|
+
if (this.#pagesLoaded >= this.#maxPages) {
|
|
1263
|
+
this.#finished = true;
|
|
1264
|
+
return null;
|
|
1265
|
+
}
|
|
1266
|
+
const previous = this.#state;
|
|
1267
|
+
const page = await this.#options.load(previous);
|
|
1268
|
+
this.#pagesLoaded += 1;
|
|
1269
|
+
this.#state = this.#advance(previous, page);
|
|
1270
|
+
return page;
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Перебирает страницы целиком.
|
|
1274
|
+
*
|
|
1275
|
+
* Полезно, когда нужны сведения о самой странице — например `total`.
|
|
1276
|
+
*/
|
|
1277
|
+
async *pages() {
|
|
1278
|
+
for (;;) {
|
|
1279
|
+
const page = await this.next();
|
|
1280
|
+
if (!page) return;
|
|
1281
|
+
yield page;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
/** Перебирает элементы всех страниц подряд. */
|
|
1285
|
+
async *[Symbol.asyncIterator]() {
|
|
1286
|
+
for await (const page of this.pages()) for (const item of page.items) {
|
|
1287
|
+
if (this.#options.signal?.aborted) return;
|
|
1288
|
+
yield item;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Собирает элементы в массив.
|
|
1293
|
+
*
|
|
1294
|
+
* @param max сколько элементов достаточно; без него перебираются все страницы
|
|
1295
|
+
*/
|
|
1296
|
+
async collect(max) {
|
|
1297
|
+
if (max !== void 0 && max <= 0) return [];
|
|
1298
|
+
const result = [];
|
|
1299
|
+
for await (const item of this) {
|
|
1300
|
+
result.push(item);
|
|
1301
|
+
if (max !== void 0 && result.length >= max) break;
|
|
1302
|
+
}
|
|
1303
|
+
return result;
|
|
1304
|
+
}
|
|
1305
|
+
/**
|
|
1306
|
+
* Вычисляет позицию следующей страницы и решает, продолжать ли.
|
|
1307
|
+
*
|
|
1308
|
+
* Здесь же стоят предохранители: пустая страница при `hasMore`, неизменившийся курсор
|
|
1309
|
+
* и отсутствие курсора останавливают перебор. Без них ошибка на сервере превратилась бы
|
|
1310
|
+
* в бесконечный цикл запросов.
|
|
1311
|
+
*/
|
|
1312
|
+
#advance(previous, page) {
|
|
1313
|
+
if (!page.hasMore || page.items.length === 0) {
|
|
1314
|
+
this.#finished = true;
|
|
1315
|
+
return previous;
|
|
1316
|
+
}
|
|
1317
|
+
if (this.#options.mode === PaginationMode.Cursor) {
|
|
1318
|
+
const cursor = page.nextCursor ?? void 0;
|
|
1319
|
+
if (!cursor || cursor === previous.cursor) {
|
|
1320
|
+
this.#finished = true;
|
|
1321
|
+
return previous;
|
|
1322
|
+
}
|
|
1323
|
+
return { cursor };
|
|
1324
|
+
}
|
|
1325
|
+
if (this.#options.mode === PaginationMode.Page) return { page: (previous.page ?? 1) + 1 };
|
|
1326
|
+
return { offset: page.nextOffset ?? (previous.offset ?? 0) + page.items.length };
|
|
1327
|
+
}
|
|
1328
|
+
};
|
|
1329
|
+
// src/resources/base.ts
|
|
1330
|
+
/** Общая основа всех групп методов клиента. */
|
|
1331
|
+
var BaseResource = class {
|
|
1332
|
+
/** @internal */
|
|
1333
|
+
http;
|
|
1334
|
+
constructor(http) {
|
|
1335
|
+
this.http = http;
|
|
1336
|
+
}
|
|
1337
|
+
/** Выполняет операцию без возвращаемого значения и отбрасывает служебное тело ответа. */
|
|
1338
|
+
voidOperation(operation, options) {
|
|
1339
|
+
return this.http.execute(operation, options);
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Собирает перебор страниц.
|
|
1343
|
+
*
|
|
1344
|
+
* @param mode схема пагинации эндпоинта
|
|
1345
|
+
* @param load загружает одну страницу для указанной позиции
|
|
1346
|
+
* @param options только управление самим перебором: предел, отмена и начальная позиция
|
|
1347
|
+
*/
|
|
1348
|
+
paginate(mode, load, options) {
|
|
1349
|
+
return new Paginator({
|
|
1350
|
+
mode,
|
|
1351
|
+
load,
|
|
1352
|
+
...options?.maxPages !== void 0 ? { maxPages: options.maxPages } : {},
|
|
1353
|
+
...options?.signal !== void 0 ? { signal: options.signal } : {},
|
|
1354
|
+
...options?.start !== void 0 ? { start: options.start } : {}
|
|
1355
|
+
});
|
|
1356
|
+
}
|
|
1357
|
+
/**
|
|
1358
|
+
* Собирает пару «загрузка страницы + перебор» из одного описания.
|
|
1359
|
+
*
|
|
1360
|
+
* Путь, параметры запроса и разбор ответа задаются один раз; `list` и `iterate`
|
|
1361
|
+
* строятся из них.
|
|
1362
|
+
*
|
|
1363
|
+
* @example
|
|
1364
|
+
* ```ts
|
|
1365
|
+
* #feed = this.paginated<Post, FeedParams>({
|
|
1366
|
+
* operation: POSTS_LIST,
|
|
1367
|
+
* path: () => '/api/posts',
|
|
1368
|
+
* query: (p) => ({ tab: p.tab, limit: p.limit }),
|
|
1369
|
+
* start: (p) => (p.cursor ? { cursor: p.cursor } : {}),
|
|
1370
|
+
* mode: PaginationMode.Cursor,
|
|
1371
|
+
* });
|
|
1372
|
+
* ```
|
|
1373
|
+
*/
|
|
1374
|
+
paginated(spec) {
|
|
1375
|
+
const load = async (params, state, options = {}) => {
|
|
1376
|
+
const operation = typeof spec.operation === "function" ? spec.operation(params) : spec.operation;
|
|
1377
|
+
return this.http.execute(operation, {
|
|
1378
|
+
path: spec.path(params),
|
|
1379
|
+
query: withPageState(spec.query(params), state),
|
|
1380
|
+
...options
|
|
1381
|
+
});
|
|
1382
|
+
};
|
|
1383
|
+
return {
|
|
1384
|
+
list: (params, options) => load(params, spec.start(params), options),
|
|
1385
|
+
iterate: (params, options = {}) => {
|
|
1386
|
+
const { maxPages, ...requestOptions } = options;
|
|
1387
|
+
return this.paginate(spec.mode, (state) => load(params, state, requestOptions), {
|
|
1388
|
+
...maxPages !== void 0 ? { maxPages } : {},
|
|
1389
|
+
...requestOptions.signal !== void 0 ? { signal: requestOptions.signal } : {},
|
|
1390
|
+
start: spec.start(params)
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
};
|
|
1396
|
+
/** Добавляет позицию страницы в параметры запроса. */
|
|
1397
|
+
function withPageState(query, state) {
|
|
1398
|
+
return {
|
|
1399
|
+
...query,
|
|
1400
|
+
...state.cursor !== void 0 ? { cursor: state.cursor } : {},
|
|
1401
|
+
...state.page !== void 0 ? { page: state.page } : {},
|
|
1402
|
+
...state.offset !== void 0 ? { offset: state.offset } : {}
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
// src/resources/chats.ts
|
|
1406
|
+
const MESSENGER_PATH = "/api/v1/messenger";
|
|
1407
|
+
const CHATS_PATH = `${MESSENGER_PATH}/chats`;
|
|
1408
|
+
const DEFAULT_AROUND_LIMIT = 40;
|
|
1409
|
+
const HISTORY_PAGE_LIMIT = 50;
|
|
1410
|
+
const LIST = defineBuiltInOperation("chats.list", normalizeChatList);
|
|
1411
|
+
const GET = defineBuiltInOperation("chats.get", normalizeChatSummary);
|
|
1412
|
+
const UNREAD = defineBuiltInOperation("chats.unread", normalizeChatUnread);
|
|
1413
|
+
const MESSAGES = defineBuiltInOperation("chats.messages", normalizeChatHistory);
|
|
1414
|
+
const MESSAGES_AROUND = defineBuiltInOperation("chats.messagesAround", normalizeChatHistory);
|
|
1415
|
+
const MEDIA = defineBuiltInOperation("chats.media", normalizeChatMedia);
|
|
1416
|
+
const FILE_LINKS = defineBuiltInOperation("chats.fileLinks", (body) => body.links);
|
|
1417
|
+
const PRESENCE = defineBuiltInOperation("chats.presence");
|
|
1418
|
+
const PRESENCE_MANY = defineBuiltInOperation("chats.presenceMany", (body) => body.presence);
|
|
1419
|
+
const REACTION_CATALOG = defineBuiltInOperation("chats.reactionCatalog", normalizeChatReactionCatalog);
|
|
1420
|
+
const REACTIONS = defineBuiltInOperation("chats.reactions", normalizeChatReactions);
|
|
1421
|
+
const HEARD_MESSAGES = defineBuiltInOperation("chats.heardMessages", (body) => body.message_ids);
|
|
1422
|
+
const UPDATES = defineBuiltInOperation("chats.updates", normalizeChatUpdates);
|
|
1423
|
+
const CREATE_DIRECT = defineBuiltInOperation("chats.createDirect", normalizeChatDirect);
|
|
1424
|
+
const SEND_MESSAGE = defineBuiltInOperation("chats.sendMessage", normalizeChatSent);
|
|
1425
|
+
const SEND_MESSAGE_TO_USER = defineBuiltInOperation("chats.sendMessageToUser", normalizeChatFirstMessage);
|
|
1426
|
+
const EDIT_MESSAGE = defineBuiltInOperation("chats.editMessage", normalizeChatEdited);
|
|
1427
|
+
const FORWARD_MESSAGES = defineBuiltInOperation("chats.forwardMessages", normalizeChatForwarded);
|
|
1428
|
+
const DELETE_MESSAGES_FOR_ME = defineBuiltInOperation("chats.deleteMessagesForMe", normalizeChatDeleted);
|
|
1429
|
+
const DELETE_MESSAGES_FOR_ALL = defineBuiltInOperation("chats.deleteMessagesForAll", normalizeChatDeleted);
|
|
1430
|
+
const SET_PINNED = defineBuiltInOperation("chats.setPinned", voidResult);
|
|
1431
|
+
const SET_MUTED = defineBuiltInOperation("chats.setMuted", voidResult);
|
|
1432
|
+
const SET_UNREAD = defineBuiltInOperation("chats.setUnread", voidResult);
|
|
1433
|
+
const MARK_READ = defineBuiltInOperation("chats.markRead", normalizeChatRead);
|
|
1434
|
+
const ACCEPT_REQUEST = defineBuiltInOperation("chats.acceptRequest", voidResult);
|
|
1435
|
+
const MARK_HEARD = defineBuiltInOperation("chats.markHeard", voidResult);
|
|
1436
|
+
const SEND_ACTION = defineBuiltInOperation("chats.sendAction", voidResult);
|
|
1437
|
+
const CLEAR_HISTORY = defineBuiltInOperation("chats.clearHistory", normalizeChatChange);
|
|
1438
|
+
const CLEAR_HISTORY_FOR_ALL = defineBuiltInOperation("chats.clearHistoryForAll", normalizeChatChange);
|
|
1439
|
+
const DELETE = defineBuiltInOperation("chats.delete", normalizeChatChange);
|
|
1440
|
+
const SET_REACTIONS = defineBuiltInOperation("chats.setReactions", normalizeChatReactions);
|
|
1441
|
+
function chatPath(chatId) {
|
|
1442
|
+
return `${CHATS_PATH}/${encodePathSegment(chatId, "идентификатор чата")}`;
|
|
1443
|
+
}
|
|
1444
|
+
function messageSegment(messageId) {
|
|
1445
|
+
return encodePathSegment(messageId, "идентификатор сообщения");
|
|
1446
|
+
}
|
|
1447
|
+
/** Чаты, сообщения, вложения и события. Доступен как `itd.chats`. */
|
|
1448
|
+
var ChatsResource = class extends BaseResource {
|
|
1449
|
+
#host;
|
|
1450
|
+
/** @internal */
|
|
1451
|
+
constructor(http, host) {
|
|
1452
|
+
super(http);
|
|
1453
|
+
this.#host = host;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Возвращает страницу чатов текущего пользователя.
|
|
1457
|
+
*
|
|
1458
|
+
* @example
|
|
1459
|
+
* ```ts
|
|
1460
|
+
* const page = await itd.chats.list({ limit: 20 });
|
|
1461
|
+
* if (page.nextBefore) await itd.chats.list({ before: page.nextBefore, limit: 20 });
|
|
1462
|
+
* ```
|
|
1463
|
+
*/
|
|
1464
|
+
list(params = {}, options = {}) {
|
|
1465
|
+
return this.http.execute(LIST, {
|
|
1466
|
+
path: CHATS_PATH,
|
|
1467
|
+
query: {
|
|
1468
|
+
before: params.before,
|
|
1469
|
+
limit: params.limit,
|
|
1470
|
+
manual_unread: 1
|
|
1471
|
+
},
|
|
1472
|
+
...options
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* Перебирает чаты текущего пользователя по курсору списка.
|
|
1477
|
+
*
|
|
1478
|
+
* @example
|
|
1479
|
+
* ```ts
|
|
1480
|
+
* for await (const chat of itd.chats.iterate({ limit: 20 })) {
|
|
1481
|
+
* console.log(chat.chatId, chat.unreadCount);
|
|
1482
|
+
* }
|
|
1483
|
+
* ```
|
|
1484
|
+
*/
|
|
1485
|
+
iterate(params = {}, options = {}) {
|
|
1486
|
+
return this.paginate(PaginationMode.Cursor, async ({ cursor }) => {
|
|
1487
|
+
const page = await this.list({
|
|
1488
|
+
...params,
|
|
1489
|
+
before: cursor
|
|
1490
|
+
}, options);
|
|
1491
|
+
return {
|
|
1492
|
+
items: page.chats,
|
|
1493
|
+
hasMore: Boolean(page.nextBefore),
|
|
1494
|
+
nextCursor: page.nextBefore,
|
|
1495
|
+
raw: page
|
|
1496
|
+
};
|
|
1497
|
+
}, {
|
|
1498
|
+
...options,
|
|
1499
|
+
start: { cursor: params.before }
|
|
1500
|
+
});
|
|
1501
|
+
}
|
|
1502
|
+
/** Возвращает сводку чата по его идентификатору. */
|
|
1503
|
+
get(chatId, options = {}) {
|
|
1504
|
+
return this.http.execute(GET, {
|
|
1505
|
+
path: chatPath(chatId),
|
|
1506
|
+
query: { manual_unread: 1 },
|
|
1507
|
+
...options
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
/** Возвращает число непрочитанных и число чатов с непрочитанным. */
|
|
1511
|
+
unread(options = {}) {
|
|
1512
|
+
return this.http.execute(UNREAD, {
|
|
1513
|
+
path: `${CHATS_PATH}/unread`,
|
|
1514
|
+
query: { manual_unread: 1 },
|
|
1515
|
+
...options
|
|
1516
|
+
});
|
|
1517
|
+
}
|
|
1518
|
+
/**
|
|
1519
|
+
* Загружает историю, начиная с последних сообщений.
|
|
1520
|
+
*
|
|
1521
|
+
* Для следующей страницы передайте ID последнего сообщения страницы в `before`.
|
|
1522
|
+
* Для последовательного чтения используйте {@link iterateMessages}.
|
|
1523
|
+
*/
|
|
1524
|
+
messages(chatId, params = {}, options = {}) {
|
|
1525
|
+
return this.http.execute(MESSAGES, {
|
|
1526
|
+
path: `${chatPath(chatId)}/messages`,
|
|
1527
|
+
query: {
|
|
1528
|
+
before: params.before,
|
|
1529
|
+
limit: params.limit
|
|
1530
|
+
},
|
|
1531
|
+
...options
|
|
1532
|
+
});
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Перебирает сообщения от новых к старым, подставляя ID последнего сообщения как курсор.
|
|
1536
|
+
*
|
|
1537
|
+
* @example
|
|
1538
|
+
* ```ts
|
|
1539
|
+
* for await (const message of itd.chats.iterateMessages(chatId)) {
|
|
1540
|
+
* console.log(message.text);
|
|
1541
|
+
* }
|
|
1542
|
+
* ```
|
|
1543
|
+
*/
|
|
1544
|
+
iterateMessages(chatId, params = {}, options = {}) {
|
|
1545
|
+
const limit = params.limit ?? HISTORY_PAGE_LIMIT;
|
|
1546
|
+
return this.paginate(PaginationMode.Cursor, async ({ cursor }) => {
|
|
1547
|
+
const page = await this.messages(chatId, {
|
|
1548
|
+
limit,
|
|
1549
|
+
before: cursor
|
|
1550
|
+
}, options);
|
|
1551
|
+
const nextCursor = page.messages.at(-1)?.messageId;
|
|
1552
|
+
return {
|
|
1553
|
+
items: page.messages,
|
|
1554
|
+
hasMore: nextCursor !== void 0 && (page.hasOlder ?? page.messages.length >= limit),
|
|
1555
|
+
nextCursor,
|
|
1556
|
+
raw: page
|
|
1557
|
+
};
|
|
1558
|
+
}, {
|
|
1559
|
+
...options,
|
|
1560
|
+
start: { cursor: params.before }
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
/** Загружает часть истории вокруг сообщения. По умолчанию запрашивает до 40 сообщений. */
|
|
1564
|
+
messagesAround(chatId, messageId, limit = DEFAULT_AROUND_LIMIT, options = {}) {
|
|
1565
|
+
return this.http.execute(MESSAGES_AROUND, {
|
|
1566
|
+
path: `${chatPath(chatId)}/messages/around/${messageSegment(messageId)}`,
|
|
1567
|
+
query: { limit },
|
|
1568
|
+
...options
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
/** Загружает вложения выбранной категории. Для следующей страницы передайте `nextBefore`. */
|
|
1572
|
+
media(chatId, category, params = {}, options = {}) {
|
|
1573
|
+
return this.http.execute(MEDIA, {
|
|
1574
|
+
path: `${chatPath(chatId)}/media`,
|
|
1575
|
+
query: {
|
|
1576
|
+
category,
|
|
1577
|
+
before: params.before,
|
|
1578
|
+
limit: params.limit
|
|
1579
|
+
},
|
|
1580
|
+
...options
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Загружает файл в мессенджер. Потоковый источник должен сообщить размер заранее.
|
|
1585
|
+
* `deadline` охватывает чтение файла, отправку частей и завершение загрузки.
|
|
1586
|
+
*
|
|
1587
|
+
* @example
|
|
1588
|
+
* ```ts
|
|
1589
|
+
* const { fileId } = await itd.chats.uploadFile(file);
|
|
1590
|
+
* await itd.chats.sendMessage(chatId, { text: '', attachmentIds: [fileId] });
|
|
1591
|
+
* ```
|
|
1592
|
+
*/
|
|
1593
|
+
uploadFile(file, uploadOptions = {}, options = {}) {
|
|
1594
|
+
return uploadChatFile(this.http, this.#host, file, uploadOptions, options);
|
|
1595
|
+
}
|
|
1596
|
+
/** Получает временные ссылки на файлы чата. Срок действия каждой ссылки указан в `expiresIn`. */
|
|
1597
|
+
fileLinks(chatId, fileIds, options = {}) {
|
|
1598
|
+
return this.http.execute(FILE_LINKS, {
|
|
1599
|
+
path: `${chatPath(chatId)}/file-links`,
|
|
1600
|
+
body: { file_ids: fileIds },
|
|
1601
|
+
...options
|
|
1602
|
+
});
|
|
1603
|
+
}
|
|
1604
|
+
/** Возвращает статус присутствия одного пользователя. */
|
|
1605
|
+
presence(userId, options = {}) {
|
|
1606
|
+
return this.http.execute(PRESENCE, {
|
|
1607
|
+
path: `${MESSENGER_PATH}/presence/${encodePathSegment(userId, "идентификатор пользователя")}`,
|
|
1608
|
+
...options
|
|
1609
|
+
});
|
|
1610
|
+
}
|
|
1611
|
+
/** Возвращает карту `ID → онлайн` одним запросом. */
|
|
1612
|
+
presenceMany(userIds, options = {}) {
|
|
1613
|
+
return this.http.execute(PRESENCE_MANY, {
|
|
1614
|
+
path: `${MESSENGER_PATH}/presence`,
|
|
1615
|
+
body: { user_ids: userIds },
|
|
1616
|
+
...options
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
/** Загружает список доступных реакций. */
|
|
1620
|
+
reactionCatalog(options = {}) {
|
|
1621
|
+
return this.http.execute(REACTION_CATALOG, {
|
|
1622
|
+
path: `${MESSENGER_PATH}/reactions/available`,
|
|
1623
|
+
...options
|
|
1624
|
+
});
|
|
1625
|
+
}
|
|
1626
|
+
/** Возвращает суммарные реакции на сообщение и версию их состояния. */
|
|
1627
|
+
reactions(chatId, messageId, options = {}) {
|
|
1628
|
+
return this.http.execute(REACTIONS, {
|
|
1629
|
+
path: `${chatPath(chatId)}/messages/${messageSegment(messageId)}/reactions`,
|
|
1630
|
+
...options
|
|
1631
|
+
});
|
|
1632
|
+
}
|
|
1633
|
+
/** Возвращает ID прослушанных сообщений из переданного списка. */
|
|
1634
|
+
heardMessages(chatId, messageIds, options = {}) {
|
|
1635
|
+
return this.http.execute(HEARD_MESSAGES, {
|
|
1636
|
+
path: `${chatPath(chatId)}/heard`,
|
|
1637
|
+
body: { message_ids: messageIds },
|
|
1638
|
+
...options
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
/**
|
|
1642
|
+
* Загружает изменения после `eventSeq` из списка чатов или `nextEventSeq` предыдущей страницы.
|
|
1643
|
+
* Передайте возвращённый `nextEventSeq` в следующий вызов. При `resetRequired` перечитайте список чатов.
|
|
1644
|
+
*/
|
|
1645
|
+
updates(since, limit, options = {}) {
|
|
1646
|
+
return this.http.execute(UPDATES, {
|
|
1647
|
+
path: `${MESSENGER_PATH}/updates`,
|
|
1648
|
+
query: {
|
|
1649
|
+
since,
|
|
1650
|
+
limit,
|
|
1651
|
+
capabilities: "chat_settings",
|
|
1652
|
+
manual_unread: 1
|
|
1218
1653
|
},
|
|
1219
1654
|
...options
|
|
1220
1655
|
});
|
|
1221
1656
|
}
|
|
1222
|
-
/**
|
|
1657
|
+
/** Возвращает ID личного чата по ID собеседника. `created` показывает, создан ли новый чат. */
|
|
1658
|
+
createDirect(userId, options = {}) {
|
|
1659
|
+
return this.http.execute(CREATE_DIRECT, {
|
|
1660
|
+
path: `${CHATS_PATH}/dm`,
|
|
1661
|
+
body: { target_user_id: userId },
|
|
1662
|
+
...options
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
/**
|
|
1666
|
+
* Отправляет сообщение в существующий чат. Файлы из `files` загружаются до отправки.
|
|
1667
|
+
*
|
|
1668
|
+
* @example
|
|
1669
|
+
* ```ts
|
|
1670
|
+
* const sent = await itd.chats.sendMessage(chatId, (m) => m.text('Привет!').attach(file));
|
|
1671
|
+
* console.log(sent.messageId);
|
|
1672
|
+
* ```
|
|
1673
|
+
*/
|
|
1674
|
+
sendMessage(chatId, input, options = {}) {
|
|
1675
|
+
const data = resolveMessage(input);
|
|
1676
|
+
const path = `${chatPath(chatId)}/messages`;
|
|
1677
|
+
return this.#withAttachments(data, {
|
|
1678
|
+
method: "POST",
|
|
1679
|
+
path
|
|
1680
|
+
}, options, (attachments, request) => this.http.execute(SEND_MESSAGE, {
|
|
1681
|
+
path,
|
|
1682
|
+
body: {
|
|
1683
|
+
text: data.text,
|
|
1684
|
+
reply_to_id: data.replyToId ?? null,
|
|
1685
|
+
attachments: attachments?.length ? attachments : void 0,
|
|
1686
|
+
entities: data.entities?.length ? data.entities.map(writeChatEntity) : void 0,
|
|
1687
|
+
client_message_id: data.clientMessageId
|
|
1688
|
+
},
|
|
1689
|
+
...request
|
|
1690
|
+
}));
|
|
1691
|
+
}
|
|
1692
|
+
/** Отправляет сообщение по ID собеседника. Если диалога ещё нет, сервер создаёт его. */
|
|
1693
|
+
sendMessageToUser(userId, input, options = {}) {
|
|
1694
|
+
const data = resolveMessage(input);
|
|
1695
|
+
const path = `${MESSENGER_PATH}/users/${encodePathSegment(userId, "идентификатор пользователя")}/messages`;
|
|
1696
|
+
return this.#withAttachments(data, {
|
|
1697
|
+
method: "POST",
|
|
1698
|
+
path
|
|
1699
|
+
}, options, (attachments, request) => this.http.execute(SEND_MESSAGE_TO_USER, {
|
|
1700
|
+
path,
|
|
1701
|
+
body: {
|
|
1702
|
+
text: data.text,
|
|
1703
|
+
attachments: attachments?.length ? attachments : void 0,
|
|
1704
|
+
entities: data.entities?.length ? data.entities.map(writeChatEntity) : void 0,
|
|
1705
|
+
client_message_id: data.clientMessageId
|
|
1706
|
+
},
|
|
1707
|
+
...request
|
|
1708
|
+
}));
|
|
1709
|
+
}
|
|
1710
|
+
/** Меняет содержимое сообщения. Пустые `entities` и `attachmentIds` удаляют разметку с карточками и файлы соответственно. */
|
|
1223
1711
|
editMessage(chatId, messageId, input, options = {}) {
|
|
1224
|
-
|
|
1225
|
-
|
|
1712
|
+
const data = resolveMessage(input);
|
|
1713
|
+
const path = `${chatPath(chatId)}/messages/${messageSegment(messageId)}`;
|
|
1714
|
+
return this.#withAttachments(data, {
|
|
1715
|
+
method: "PATCH",
|
|
1716
|
+
path
|
|
1717
|
+
}, options, (attachments, request) => this.http.execute(EDIT_MESSAGE, {
|
|
1718
|
+
path,
|
|
1226
1719
|
body: {
|
|
1227
|
-
text:
|
|
1228
|
-
attachments
|
|
1229
|
-
entities:
|
|
1720
|
+
text: data.text,
|
|
1721
|
+
attachments,
|
|
1722
|
+
entities: data.entities?.map(writeChatEntity)
|
|
1230
1723
|
},
|
|
1231
|
-
...
|
|
1724
|
+
...request
|
|
1725
|
+
}));
|
|
1726
|
+
}
|
|
1727
|
+
/** Загружает файлы перед запросом с общим сроком выполнения. */
|
|
1728
|
+
async #withAttachments({ attachmentIds, files }, operation, options, send) {
|
|
1729
|
+
if (!files?.length) return send(attachmentIds, options);
|
|
1730
|
+
const scope = this.http.createDeadlineScope({
|
|
1731
|
+
...options,
|
|
1732
|
+
...operation
|
|
1232
1733
|
});
|
|
1734
|
+
const request = {
|
|
1735
|
+
...options,
|
|
1736
|
+
deadline: 0,
|
|
1737
|
+
signal: scope.signal
|
|
1738
|
+
};
|
|
1739
|
+
const ids = [...attachmentIds ?? []];
|
|
1740
|
+
try {
|
|
1741
|
+
for (const file of files) {
|
|
1742
|
+
const { fileId } = await this.uploadFile(file, void 0, request);
|
|
1743
|
+
ids.push(fileId);
|
|
1744
|
+
}
|
|
1745
|
+
scope.signal.throwIfAborted();
|
|
1746
|
+
return await send(ids, request);
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
throw requestAbortError(scope, operation, error);
|
|
1749
|
+
} finally {
|
|
1750
|
+
scope.cleanup();
|
|
1751
|
+
}
|
|
1233
1752
|
}
|
|
1234
1753
|
/** Пересылает сообщения из другого чата. Результат содержит успешные и отклонённые элементы. */
|
|
1235
1754
|
forwardMessages(chatId, input, options = {}) {
|
|
@@ -1335,7 +1854,7 @@ var ChatsResource = class extends BaseResource {
|
|
|
1335
1854
|
/**
|
|
1336
1855
|
* Заменяет реакции текущего пользователя. Пустой список снимает его реакции.
|
|
1337
1856
|
*
|
|
1338
|
-
*
|
|
1857
|
+
* В `expectedVersion` передайте `reactionVersion` из {@link reactions}. При конфликте перечитайте
|
|
1339
1858
|
* состояние перед повторной записью.
|
|
1340
1859
|
*/
|
|
1341
1860
|
setReactions(chatId, messageId, input, options = {}) {
|
|
@@ -2327,40 +2846,15 @@ function createStatusFeature() {
|
|
|
2327
2846
|
name: STATUS_SERVICE,
|
|
2328
2847
|
baseUrl: DEFAULT_STATUS_BASE_URL,
|
|
2329
2848
|
auth: false
|
|
2330
|
-
}],
|
|
2331
|
-
operations: { get: {
|
|
2332
|
-
method: "GET",
|
|
2333
|
-
retrySafety: RetrySafety.Safe,
|
|
2334
|
-
service: STATUS_SERVICE,
|
|
2335
|
-
read: (body) => normalizeStatus(body)
|
|
2336
|
-
} },
|
|
2337
|
-
setup: (context) => ({ api: new StatusResource(context) })
|
|
2338
|
-
};
|
|
2339
|
-
}
|
|
2340
|
-
// src/builders/base.ts
|
|
2341
|
-
/** Метка билдера. Через `Symbol.for` — чтобы распознавание переживало смешивание ESM и CJS. */
|
|
2342
|
-
const BUILDER = Symbol.for("itd.builder");
|
|
2343
|
-
/** Является ли значение билдером. */
|
|
2344
|
-
function isBuilder(value) {
|
|
2345
|
-
return typeof value === "object" && value !== null && BUILDER in value;
|
|
2346
|
-
}
|
|
2347
|
-
/**
|
|
2348
|
-
* Приводит любую из трёх форм входа к готовому объекту.
|
|
2349
|
-
*
|
|
2350
|
-
* Проверка выполняется всегда, независимо от формы: обычный объект проходит ровно те же
|
|
2351
|
-
* правила, что и результат билдера.
|
|
2352
|
-
*
|
|
2353
|
-
* @param input то, что передал пользователь
|
|
2354
|
-
* @param factory создаёт пустой билдер для формы с функцией
|
|
2355
|
-
* @param validate проверяет собранный объект
|
|
2356
|
-
*/
|
|
2357
|
-
function resolveInput(input, factory, validate) {
|
|
2358
|
-
if (typeof input === "function") {
|
|
2359
|
-
const result = input(factory());
|
|
2360
|
-
return isBuilder(result) ? result.build() : validate(result);
|
|
2361
|
-
}
|
|
2362
|
-
if (isBuilder(input)) return input.build();
|
|
2363
|
-
return validate(input);
|
|
2849
|
+
}],
|
|
2850
|
+
operations: { get: {
|
|
2851
|
+
method: "GET",
|
|
2852
|
+
retrySafety: RetrySafety.Safe,
|
|
2853
|
+
service: STATUS_SERVICE,
|
|
2854
|
+
read: (body) => normalizeStatus(body)
|
|
2855
|
+
} },
|
|
2856
|
+
setup: (context) => ({ api: new StatusResource(context) })
|
|
2857
|
+
};
|
|
2364
2858
|
}
|
|
2365
2859
|
// src/builders/comment.ts
|
|
2366
2860
|
/**
|
|
@@ -2995,22 +3489,6 @@ var PlatformResource = class extends BaseResource {
|
|
|
2995
3489
|
return this.#status.get(options);
|
|
2996
3490
|
}
|
|
2997
3491
|
};
|
|
2998
|
-
// src/spans/validate.ts
|
|
2999
|
-
/**
|
|
3000
|
-
* Проверяет, что spans целиком лежат внутри текста.
|
|
3001
|
-
*
|
|
3002
|
-
* Возвращает копии, чтобы последующая мутация входного массива не меняла уже собранные данные.
|
|
3003
|
-
*/
|
|
3004
|
-
function validateSpans(content, spans) {
|
|
3005
|
-
if (!Array.isArray(spans)) throw new ItdConfigError("spans должен быть массивом");
|
|
3006
|
-
if (content.length === 0 && spans.length > 0) throw new ItdConfigError("Нельзя задать spans без текста: сначала укажите непустой content");
|
|
3007
|
-
return spans.map((span, index) => {
|
|
3008
|
-
if (!span || typeof span !== "object") throw new ItdConfigError(`Некорректный span №${index + 1}: ожидался объект`);
|
|
3009
|
-
const candidate = span;
|
|
3010
|
-
if (typeof candidate.type !== "string" || !Number.isInteger(candidate.offset) || !Number.isInteger(candidate.length) || (candidate.offset ?? -1) < 0 || (candidate.length ?? 0) <= 0 || (candidate.offset ?? 0) + (candidate.length ?? 0) > content.length) throw new ItdConfigError(`Некорректный span №${index + 1}: offset и length должны указывать на непустой фрагмент content`);
|
|
3011
|
-
return { ...candidate };
|
|
3012
|
-
});
|
|
3013
|
-
}
|
|
3014
3492
|
// src/spans/parse.ts
|
|
3015
3493
|
const HTML_BLOCK_TAGS = /* @__PURE__ */ new Set([
|
|
3016
3494
|
"address",
|
|
@@ -3228,485 +3706,252 @@ function parseMarkdownInline(source, output, protocols) {
|
|
|
3228
3706
|
}
|
|
3229
3707
|
}
|
|
3230
3708
|
if (source.slice(index, index + 3).toLowerCase() === "<u>") {
|
|
3231
|
-
const close = source.toLowerCase().indexOf("</u>", index + 3);
|
|
3232
|
-
if (close > index + 3) {
|
|
3233
|
-
const start = output.content.length;
|
|
3234
|
-
parseMarkdownInline(source.slice(index + 3, close), output, protocols);
|
|
3235
|
-
addSpan(output, start, { type: SpanType.Underline });
|
|
3236
|
-
index = close + 4;
|
|
3237
|
-
continue;
|
|
3238
|
-
}
|
|
3239
|
-
}
|
|
3240
|
-
if (character === "<") {
|
|
3241
|
-
const close = source.indexOf(">", index + 1);
|
|
3242
|
-
if (close > index + 1) {
|
|
3243
|
-
const candidate = decodeEntities(source.slice(index + 1, close));
|
|
3244
|
-
const url = safeLink(candidate, protocols);
|
|
3245
|
-
if (url) {
|
|
3246
|
-
const start = output.content.length;
|
|
3247
|
-
append(output, candidate);
|
|
3248
|
-
addSpan(output, start, {
|
|
3249
|
-
type: SpanType.Link,
|
|
3250
|
-
url
|
|
3251
|
-
});
|
|
3252
|
-
index = close + 1;
|
|
3253
|
-
continue;
|
|
3254
|
-
}
|
|
3255
|
-
}
|
|
3256
|
-
}
|
|
3257
|
-
const style = markdownStyle(source, index);
|
|
3258
|
-
if (style) {
|
|
3259
|
-
const close = findClosing(source, style.marker, index + style.marker.length);
|
|
3260
|
-
if (close > index + style.marker.length) {
|
|
3261
|
-
const start = output.content.length;
|
|
3262
|
-
parseMarkdownInline(source.slice(index + style.marker.length, close), output, protocols);
|
|
3263
|
-
addSpan(output, start, { type: style.type });
|
|
3264
|
-
index = close + style.marker.length;
|
|
3265
|
-
continue;
|
|
3266
|
-
}
|
|
3267
|
-
}
|
|
3268
|
-
if (character === "&") {
|
|
3269
|
-
const entity = source.slice(index).match(/^&(?:#(?:x[\da-f]+|\d+)|[a-z][a-z\d]+);/iu)?.[0];
|
|
3270
|
-
if (entity) {
|
|
3271
|
-
append(output, decodeEntities(entity));
|
|
3272
|
-
index += entity.length;
|
|
3273
|
-
continue;
|
|
3274
|
-
}
|
|
3275
|
-
}
|
|
3276
|
-
append(output, character);
|
|
3277
|
-
index += 1;
|
|
3278
|
-
}
|
|
3279
|
-
}
|
|
3280
|
-
function lineEnd(source, from) {
|
|
3281
|
-
const found = source.indexOf("\n", from);
|
|
3282
|
-
return found < 0 ? source.length : found;
|
|
3283
|
-
}
|
|
3284
|
-
/**
|
|
3285
|
-
* Преобразует безопасное подмножество Markdown в текст и wire-spans.
|
|
3286
|
-
*
|
|
3287
|
-
* Поддерживаются bold, italic, strike, spoiler, inline/fenced code, ссылки, underline
|
|
3288
|
-
* через `<u>` и цитаты `>`. Неподдерживаемая и незакрытая разметка остаётся текстом.
|
|
3289
|
-
* У изображений сохраняется alt-текст без URL.
|
|
3290
|
-
*/
|
|
3291
|
-
function parseMarkdown(source, options = {}) {
|
|
3292
|
-
const output = {
|
|
3293
|
-
content: "",
|
|
3294
|
-
spans: []
|
|
3295
|
-
};
|
|
3296
|
-
const protocols = allowedProtocols(options);
|
|
3297
|
-
let position = 0;
|
|
3298
|
-
while (position < source.length) {
|
|
3299
|
-
const end = lineEnd(source, position);
|
|
3300
|
-
const line = source.slice(position, end);
|
|
3301
|
-
const hasNewline = end < source.length;
|
|
3302
|
-
const fence = line.match(/^ {0,3}(`{3,}|~{3,})[^\n]*$/u)?.[1];
|
|
3303
|
-
if (fence) {
|
|
3304
|
-
let closeStart = hasNewline ? end + 1 : source.length;
|
|
3305
|
-
let closeEnd = closeStart;
|
|
3306
|
-
let found = false;
|
|
3307
|
-
while (closeStart < source.length) {
|
|
3308
|
-
closeEnd = lineEnd(source, closeStart);
|
|
3309
|
-
const marker = source.slice(closeStart, closeEnd).match(/^ {0,3}(`{3,}|~{3,})\s*$/u)?.[1];
|
|
3310
|
-
if (marker !== void 0 && marker[0] === fence[0] && marker.length >= fence.length) {
|
|
3311
|
-
found = true;
|
|
3312
|
-
break;
|
|
3313
|
-
}
|
|
3314
|
-
closeStart = closeEnd < source.length ? closeEnd + 1 : source.length;
|
|
3315
|
-
}
|
|
3316
|
-
if (found) {
|
|
3317
|
-
const bodyStart = end + 1;
|
|
3318
|
-
let body = source.slice(bodyStart, closeStart);
|
|
3319
|
-
if (body.endsWith("\n")) body = body.slice(0, -1);
|
|
3320
|
-
const start = output.content.length;
|
|
3321
|
-
append(output, body);
|
|
3322
|
-
addSpan(output, start, { type: SpanType.Monospace });
|
|
3323
|
-
if (closeEnd < source.length) append(output, "\n");
|
|
3324
|
-
position = closeEnd < source.length ? closeEnd + 1 : source.length;
|
|
3325
|
-
continue;
|
|
3326
|
-
}
|
|
3327
|
-
}
|
|
3328
|
-
const quote = line.match(/^ {0,3}> ?(.*)$/u);
|
|
3329
|
-
if (quote) {
|
|
3330
|
-
const start = output.content.length;
|
|
3331
|
-
parseMarkdownInline(quote[1] ?? "", output, protocols);
|
|
3332
|
-
addSpan(output, start, { type: SpanType.Quote });
|
|
3333
|
-
} else parseMarkdownInline(line, output, protocols);
|
|
3334
|
-
if (hasNewline) append(output, "\n");
|
|
3335
|
-
position = hasNewline ? end + 1 : source.length;
|
|
3336
|
-
}
|
|
3337
|
-
return finish(output);
|
|
3338
|
-
}
|
|
3339
|
-
function readAttribute(source, name) {
|
|
3340
|
-
const pattern = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\\x60]+))`, "iu");
|
|
3341
|
-
const match = source.match(pattern);
|
|
3342
|
-
const value = match?.[1] ?? match?.[2] ?? match?.[3];
|
|
3343
|
-
return value === void 0 ? void 0 : decodeEntities(value);
|
|
3344
|
-
}
|
|
3345
|
-
function htmlSpan(tag, attributes, protocols) {
|
|
3346
|
-
switch (tag) {
|
|
3347
|
-
case "b":
|
|
3348
|
-
case "strong": return { type: SpanType.Bold };
|
|
3349
|
-
case "em":
|
|
3350
|
-
case "i": return { type: SpanType.Italic };
|
|
3351
|
-
case "u": return { type: SpanType.Underline };
|
|
3352
|
-
case "del":
|
|
3353
|
-
case "s":
|
|
3354
|
-
case "strike": return { type: SpanType.Strike };
|
|
3355
|
-
case "code":
|
|
3356
|
-
case "pre": return { type: SpanType.Monospace };
|
|
3357
|
-
case "blockquote": return { type: SpanType.Quote };
|
|
3358
|
-
case "a": {
|
|
3359
|
-
const href = readAttribute(attributes, "href");
|
|
3360
|
-
const url = href ? safeLink(href, protocols) : null;
|
|
3361
|
-
return url ? {
|
|
3362
|
-
type: SpanType.Link,
|
|
3363
|
-
url
|
|
3364
|
-
} : void 0;
|
|
3365
|
-
}
|
|
3366
|
-
case "span": {
|
|
3367
|
-
const classes = readAttribute(attributes, "class")?.split(/\s+/u) ?? [];
|
|
3368
|
-
if (readAttribute(attributes, "data-spoiler") === "true" || classes.some((value) => value.endsWith("-spoiler"))) return { type: SpanType.Spoiler };
|
|
3369
|
-
if (classes.some((value) => value.endsWith("-quote"))) return { type: SpanType.Quote };
|
|
3370
|
-
return;
|
|
3371
|
-
}
|
|
3372
|
-
default: return;
|
|
3373
|
-
}
|
|
3374
|
-
}
|
|
3375
|
-
function ensureBlockBreak(output) {
|
|
3376
|
-
if (output.content !== "" && !output.content.endsWith("\n")) append(output, "\n");
|
|
3377
|
-
}
|
|
3378
|
-
function findHtmlTagEnd(source, from) {
|
|
3379
|
-
let quote;
|
|
3380
|
-
for (let index = from; index < source.length; index += 1) {
|
|
3381
|
-
const character = source[index];
|
|
3382
|
-
if (quote) {
|
|
3383
|
-
if (character === quote) quote = void 0;
|
|
3384
|
-
continue;
|
|
3385
|
-
}
|
|
3386
|
-
if (character === "\"" || character === "'") {
|
|
3387
|
-
quote = character;
|
|
3388
|
-
continue;
|
|
3389
|
-
}
|
|
3390
|
-
if (character === ">") return index;
|
|
3391
|
-
}
|
|
3392
|
-
return -1;
|
|
3393
|
-
}
|
|
3394
|
-
/**
|
|
3395
|
-
* Преобразует ограниченный HTML в обычный текст и wire-spans.
|
|
3396
|
-
*
|
|
3397
|
-
* Разрешены только семантические теги форматирования. Атрибуты событий игнорируются,
|
|
3398
|
-
* содержимое `script`, `style`, `iframe`, `object`, SVG и подобных активных элементов
|
|
3399
|
-
* удаляется. Опасный `href` сохраняет текст ссылки, но не создаёт span.
|
|
3400
|
-
*/
|
|
3401
|
-
function parseHtml(source, options = {}) {
|
|
3402
|
-
const output = {
|
|
3403
|
-
content: "",
|
|
3404
|
-
spans: []
|
|
3405
|
-
};
|
|
3406
|
-
const protocols = allowedProtocols(options);
|
|
3407
|
-
const stack = [];
|
|
3408
|
-
let position = 0;
|
|
3409
|
-
const closeTag = (tag) => {
|
|
3410
|
-
for (let index = stack.length - 1; index >= 0; index -= 1) {
|
|
3411
|
-
const open = stack[index];
|
|
3412
|
-
if (open?.tag !== tag) continue;
|
|
3413
|
-
stack.splice(index, 1);
|
|
3414
|
-
addSpan(output, open.start, open.span);
|
|
3415
|
-
return;
|
|
3416
|
-
}
|
|
3417
|
-
};
|
|
3418
|
-
while (position < source.length) {
|
|
3419
|
-
if (source.startsWith("<!--", position)) {
|
|
3420
|
-
const end = source.indexOf("-->", position + 4);
|
|
3421
|
-
position = end < 0 ? source.length : end + 3;
|
|
3422
|
-
continue;
|
|
3423
|
-
}
|
|
3424
|
-
if (source[position] === "<") {
|
|
3425
|
-
const end = findHtmlTagEnd(source, position + 1);
|
|
3426
|
-
if (end >= 0) {
|
|
3427
|
-
const parsed = source.slice(position, end + 1).match(/^<\s*(\/?)\s*([a-z][\w-]*)([\s\S]*?)\/?\s*>$/iu);
|
|
3428
|
-
if (parsed) {
|
|
3429
|
-
const closing = parsed[1] === "/";
|
|
3430
|
-
const tag = (parsed[2] ?? "").toLowerCase();
|
|
3431
|
-
const attributes = parsed[3] ?? "";
|
|
3432
|
-
if (!closing && HTML_DROPPED_TAGS.has(tag)) {
|
|
3433
|
-
const closingPattern = new RegExp(`<\\s*\\/\\s*${tag}\\s*>`, "igu");
|
|
3434
|
-
closingPattern.lastIndex = end + 1;
|
|
3435
|
-
const match = closingPattern.exec(source);
|
|
3436
|
-
position = match ? match.index + match[0].length : source.length;
|
|
3437
|
-
continue;
|
|
3438
|
-
}
|
|
3439
|
-
if (tag === "br" && !closing) {
|
|
3440
|
-
append(output, "\n");
|
|
3441
|
-
position = end + 1;
|
|
3442
|
-
continue;
|
|
3443
|
-
}
|
|
3444
|
-
if (tag === "img" && !closing) {
|
|
3445
|
-
append(output, readAttribute(attributes, "alt") ?? "");
|
|
3446
|
-
position = end + 1;
|
|
3447
|
-
continue;
|
|
3448
|
-
}
|
|
3449
|
-
if (closing) {
|
|
3450
|
-
closeTag(tag);
|
|
3451
|
-
if (HTML_BLOCK_TAGS.has(tag)) ensureBlockBreak(output);
|
|
3452
|
-
} else {
|
|
3453
|
-
if (HTML_BLOCK_TAGS.has(tag)) ensureBlockBreak(output);
|
|
3454
|
-
const span = htmlSpan(tag, attributes, protocols);
|
|
3455
|
-
if (span) stack.push({
|
|
3456
|
-
tag,
|
|
3457
|
-
start: output.content.length,
|
|
3458
|
-
span
|
|
3459
|
-
});
|
|
3460
|
-
}
|
|
3461
|
-
position = end + 1;
|
|
3709
|
+
const close = source.toLowerCase().indexOf("</u>", index + 3);
|
|
3710
|
+
if (close > index + 3) {
|
|
3711
|
+
const start = output.content.length;
|
|
3712
|
+
parseMarkdownInline(source.slice(index + 3, close), output, protocols);
|
|
3713
|
+
addSpan(output, start, { type: SpanType.Underline });
|
|
3714
|
+
index = close + 4;
|
|
3715
|
+
continue;
|
|
3716
|
+
}
|
|
3717
|
+
}
|
|
3718
|
+
if (character === "<") {
|
|
3719
|
+
const close = source.indexOf(">", index + 1);
|
|
3720
|
+
if (close > index + 1) {
|
|
3721
|
+
const candidate = decodeEntities(source.slice(index + 1, close));
|
|
3722
|
+
const url = safeLink(candidate, protocols);
|
|
3723
|
+
if (url) {
|
|
3724
|
+
const start = output.content.length;
|
|
3725
|
+
append(output, candidate);
|
|
3726
|
+
addSpan(output, start, {
|
|
3727
|
+
type: SpanType.Link,
|
|
3728
|
+
url
|
|
3729
|
+
});
|
|
3730
|
+
index = close + 1;
|
|
3462
3731
|
continue;
|
|
3463
3732
|
}
|
|
3464
3733
|
}
|
|
3465
3734
|
}
|
|
3466
|
-
const
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
|
|
3472
|
-
|
|
3473
|
-
|
|
3735
|
+
const style = markdownStyle(source, index);
|
|
3736
|
+
if (style) {
|
|
3737
|
+
const close = findClosing(source, style.marker, index + style.marker.length);
|
|
3738
|
+
if (close > index + style.marker.length) {
|
|
3739
|
+
const start = output.content.length;
|
|
3740
|
+
parseMarkdownInline(source.slice(index + style.marker.length, close), output, protocols);
|
|
3741
|
+
addSpan(output, start, { type: style.type });
|
|
3742
|
+
index = close + style.marker.length;
|
|
3743
|
+
continue;
|
|
3744
|
+
}
|
|
3745
|
+
}
|
|
3746
|
+
if (character === "&") {
|
|
3747
|
+
const entity = source.slice(index).match(/^&(?:#(?:x[\da-f]+|\d+)|[a-z][a-z\d]+);/iu)?.[0];
|
|
3748
|
+
if (entity) {
|
|
3749
|
+
append(output, decodeEntities(entity));
|
|
3750
|
+
index += entity.length;
|
|
3751
|
+
continue;
|
|
3752
|
+
}
|
|
3753
|
+
}
|
|
3754
|
+
append(output, character);
|
|
3755
|
+
index += 1;
|
|
3474
3756
|
}
|
|
3475
|
-
while (output.content.endsWith("\n")) output.content = output.content.slice(0, -1);
|
|
3476
|
-
return finish(output);
|
|
3477
|
-
}
|
|
3478
|
-
// src/builders/markup.ts
|
|
3479
|
-
function validateMarkup(value) {
|
|
3480
|
-
if (!value || typeof value.content !== "string" || !Array.isArray(value.spans)) throw new ItdConfigError("Разметка должна содержать строку content и массив spans");
|
|
3481
|
-
return {
|
|
3482
|
-
content: value.content,
|
|
3483
|
-
spans: validateSpans(value.content, value.spans).sort((left, right) => left.offset - right.offset || right.length - left.length)
|
|
3484
|
-
};
|
|
3485
3757
|
}
|
|
3486
|
-
function
|
|
3487
|
-
const
|
|
3488
|
-
|
|
3489
|
-
return name;
|
|
3758
|
+
function lineEnd(source, from) {
|
|
3759
|
+
const found = source.indexOf("\n", from);
|
|
3760
|
+
return found < 0 ? source.length : found;
|
|
3490
3761
|
}
|
|
3491
3762
|
/**
|
|
3492
|
-
*
|
|
3763
|
+
* Преобразует безопасное подмножество Markdown в текст и wire-spans.
|
|
3493
3764
|
*
|
|
3494
|
-
*
|
|
3495
|
-
*
|
|
3765
|
+
* Поддерживаются bold, italic, strike, spoiler, inline/fenced code, ссылки, underline
|
|
3766
|
+
* через `<u>` и цитаты `>`. Неподдерживаемая и незакрытая разметка остаётся текстом.
|
|
3767
|
+
* У изображений сохраняется alt-текст без URL.
|
|
3496
3768
|
*/
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
|
|
3503
|
-
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
|
|
3517
|
-
|
|
3518
|
-
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3522
|
-
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
|
|
3526
|
-
|
|
3527
|
-
|
|
3528
|
-
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
|
|
3544
|
-
*/
|
|
3545
|
-
span(value, span) {
|
|
3546
|
-
return this.#formatted(value, [span]);
|
|
3547
|
-
}
|
|
3548
|
-
/**
|
|
3549
|
-
* Дописывает фрагмент с несколькими стилями на одном диапазоне.
|
|
3550
|
-
*
|
|
3551
|
-
* Для `link`, которому нужен `url`, используйте {@link link}; произвольные spans с
|
|
3552
|
-
* метаданными можно объединять через вложенные вызовы {@link span}.
|
|
3553
|
-
*/
|
|
3554
|
-
styled(value, ...types) {
|
|
3555
|
-
if (types.length === 0) return this.#formatted(value, []);
|
|
3556
|
-
return this.#formatted(value, types.map((type) => ({ type })));
|
|
3557
|
-
}
|
|
3558
|
-
/** Дописывает `#хэштег` и сохраняет имя без решётки в `tag`. */
|
|
3559
|
-
hashtag(tag) {
|
|
3560
|
-
const name = entityName(tag, "#", "Хэштег");
|
|
3561
|
-
return this.span(`#${name}`, {
|
|
3562
|
-
type: SpanType.Hashtag,
|
|
3563
|
-
tag: name
|
|
3564
|
-
});
|
|
3565
|
-
}
|
|
3566
|
-
/** Дописывает `@username` и сохраняет имя пользователя в `username`. */
|
|
3567
|
-
mention(username) {
|
|
3568
|
-
const name = entityName(username, "@", "Упоминание");
|
|
3569
|
-
return this.span(`@${name}`, {
|
|
3570
|
-
type: SpanType.Mention,
|
|
3571
|
-
username: name
|
|
3572
|
-
});
|
|
3573
|
-
}
|
|
3574
|
-
/**
|
|
3575
|
-
* Дописывает ссылку.
|
|
3576
|
-
*
|
|
3577
|
-
* Для строки адрес по умолчанию становится и текстом ссылки. Вложенному форматированному
|
|
3578
|
-
* фрагменту URL нужно передать явно.
|
|
3579
|
-
*/
|
|
3580
|
-
link(content, url) {
|
|
3581
|
-
const resolvedUrl = url ?? (typeof content === "string" ? content : void 0);
|
|
3582
|
-
if (resolvedUrl === void 0) throw new ItdConfigError("Для форматированного текста ссылки нужно явно передать URL");
|
|
3583
|
-
return this.span(content, {
|
|
3584
|
-
type: SpanType.Link,
|
|
3585
|
-
url: resolvedUrl
|
|
3586
|
-
});
|
|
3587
|
-
}
|
|
3588
|
-
bold(content) {
|
|
3589
|
-
return this.span(content, { type: SpanType.Bold });
|
|
3590
|
-
}
|
|
3591
|
-
italic(content) {
|
|
3592
|
-
return this.span(content, { type: SpanType.Italic });
|
|
3593
|
-
}
|
|
3594
|
-
underline(content) {
|
|
3595
|
-
return this.span(content, { type: SpanType.Underline });
|
|
3596
|
-
}
|
|
3597
|
-
strike(content) {
|
|
3598
|
-
return this.span(content, { type: SpanType.Strike });
|
|
3599
|
-
}
|
|
3600
|
-
spoiler(content) {
|
|
3601
|
-
return this.span(content, { type: SpanType.Spoiler });
|
|
3602
|
-
}
|
|
3603
|
-
monospace(content) {
|
|
3604
|
-
return this.span(content, { type: SpanType.Monospace });
|
|
3605
|
-
}
|
|
3606
|
-
quote(content) {
|
|
3607
|
-
return this.span(content, { type: SpanType.Quote });
|
|
3608
|
-
}
|
|
3609
|
-
build() {
|
|
3610
|
-
return validateMarkup({
|
|
3611
|
-
content: this.#content,
|
|
3612
|
-
spans: this.#spans
|
|
3613
|
-
});
|
|
3614
|
-
}
|
|
3615
|
-
toJSON() {
|
|
3616
|
-
return this.build();
|
|
3617
|
-
}
|
|
3618
|
-
};
|
|
3619
|
-
/** Начинает сборку текста с автоматически вычисляемыми смещениями. */
|
|
3620
|
-
function markup(content = "") {
|
|
3621
|
-
return new MarkupBuilder(content, []);
|
|
3622
|
-
}
|
|
3623
|
-
/** Приводит любую форму разметки к тексту и массиву spans. */
|
|
3624
|
-
function resolveMarkup(input) {
|
|
3625
|
-
return resolveInput(input, () => markup(), validateMarkup);
|
|
3626
|
-
}
|
|
3627
|
-
function trimUrlEnd(value) {
|
|
3628
|
-
let result = value;
|
|
3629
|
-
const pairs = [
|
|
3630
|
-
["(", ")"],
|
|
3631
|
-
["[", "]"],
|
|
3632
|
-
["{", "}"]
|
|
3633
|
-
];
|
|
3634
|
-
let changed;
|
|
3635
|
-
do {
|
|
3636
|
-
const before = result;
|
|
3637
|
-
while (/[.,!?;:…'"»”]$/u.test(result)) result = result.slice(0, -1);
|
|
3638
|
-
for (const [open, close] of pairs) while (result.endsWith(close) && result.split(close).length > result.split(open).length) result = result.slice(0, -1);
|
|
3639
|
-
changed = result !== before;
|
|
3640
|
-
} while (changed);
|
|
3641
|
-
return result;
|
|
3769
|
+
function parseMarkdown(source, options = {}) {
|
|
3770
|
+
const output = {
|
|
3771
|
+
content: "",
|
|
3772
|
+
spans: []
|
|
3773
|
+
};
|
|
3774
|
+
const protocols = allowedProtocols(options);
|
|
3775
|
+
let position = 0;
|
|
3776
|
+
while (position < source.length) {
|
|
3777
|
+
const end = lineEnd(source, position);
|
|
3778
|
+
const line = source.slice(position, end);
|
|
3779
|
+
const hasNewline = end < source.length;
|
|
3780
|
+
const fence = line.match(/^ {0,3}(`{3,}|~{3,})[^\n]*$/u)?.[1];
|
|
3781
|
+
if (fence) {
|
|
3782
|
+
let closeStart = hasNewline ? end + 1 : source.length;
|
|
3783
|
+
let closeEnd = closeStart;
|
|
3784
|
+
let found = false;
|
|
3785
|
+
while (closeStart < source.length) {
|
|
3786
|
+
closeEnd = lineEnd(source, closeStart);
|
|
3787
|
+
const marker = source.slice(closeStart, closeEnd).match(/^ {0,3}(`{3,}|~{3,})\s*$/u)?.[1];
|
|
3788
|
+
if (marker !== void 0 && marker[0] === fence[0] && marker.length >= fence.length) {
|
|
3789
|
+
found = true;
|
|
3790
|
+
break;
|
|
3791
|
+
}
|
|
3792
|
+
closeStart = closeEnd < source.length ? closeEnd + 1 : source.length;
|
|
3793
|
+
}
|
|
3794
|
+
if (found) {
|
|
3795
|
+
const bodyStart = end + 1;
|
|
3796
|
+
let body = source.slice(bodyStart, closeStart);
|
|
3797
|
+
if (body.endsWith("\n")) body = body.slice(0, -1);
|
|
3798
|
+
const start = output.content.length;
|
|
3799
|
+
append(output, body);
|
|
3800
|
+
addSpan(output, start, { type: SpanType.Monospace });
|
|
3801
|
+
if (closeEnd < source.length) append(output, "\n");
|
|
3802
|
+
position = closeEnd < source.length ? closeEnd + 1 : source.length;
|
|
3803
|
+
continue;
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
const quote = line.match(/^ {0,3}> ?(.*)$/u);
|
|
3807
|
+
if (quote) {
|
|
3808
|
+
const start = output.content.length;
|
|
3809
|
+
parseMarkdownInline(quote[1] ?? "", output, protocols);
|
|
3810
|
+
addSpan(output, start, { type: SpanType.Quote });
|
|
3811
|
+
} else parseMarkdownInline(line, output, protocols);
|
|
3812
|
+
if (hasNewline) append(output, "\n");
|
|
3813
|
+
position = hasNewline ? end + 1 : source.length;
|
|
3814
|
+
}
|
|
3815
|
+
return finish(output);
|
|
3642
3816
|
}
|
|
3643
|
-
function
|
|
3644
|
-
|
|
3817
|
+
function readAttribute(source, name) {
|
|
3818
|
+
const pattern = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\\x60]+))`, "iu");
|
|
3819
|
+
const match = source.match(pattern);
|
|
3820
|
+
const value = match?.[1] ?? match?.[2] ?? match?.[3];
|
|
3821
|
+
return value === void 0 ? void 0 : decodeEntities(value);
|
|
3645
3822
|
}
|
|
3646
|
-
function
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
return
|
|
3823
|
+
function htmlSpan(tag, attributes, protocols) {
|
|
3824
|
+
switch (tag) {
|
|
3825
|
+
case "b":
|
|
3826
|
+
case "strong": return { type: SpanType.Bold };
|
|
3827
|
+
case "em":
|
|
3828
|
+
case "i": return { type: SpanType.Italic };
|
|
3829
|
+
case "u": return { type: SpanType.Underline };
|
|
3830
|
+
case "del":
|
|
3831
|
+
case "s":
|
|
3832
|
+
case "strike": return { type: SpanType.Strike };
|
|
3833
|
+
case "code":
|
|
3834
|
+
case "pre": return { type: SpanType.Monospace };
|
|
3835
|
+
case "blockquote": return { type: SpanType.Quote };
|
|
3836
|
+
case "a": {
|
|
3837
|
+
const href = readAttribute(attributes, "href");
|
|
3838
|
+
const url = href ? safeLink(href, protocols) : null;
|
|
3839
|
+
return url ? {
|
|
3840
|
+
type: SpanType.Link,
|
|
3841
|
+
url
|
|
3842
|
+
} : void 0;
|
|
3843
|
+
}
|
|
3844
|
+
case "span": {
|
|
3845
|
+
const classes = readAttribute(attributes, "class")?.split(/\s+/u) ?? [];
|
|
3846
|
+
if (readAttribute(attributes, "data-spoiler") === "true" || classes.some((value) => value.endsWith("-spoiler"))) return { type: SpanType.Spoiler };
|
|
3847
|
+
if (classes.some((value) => value.endsWith("-quote"))) return { type: SpanType.Quote };
|
|
3848
|
+
return;
|
|
3849
|
+
}
|
|
3850
|
+
default: return;
|
|
3652
3851
|
}
|
|
3653
3852
|
}
|
|
3654
|
-
function
|
|
3655
|
-
if (
|
|
3656
|
-
|
|
3657
|
-
|
|
3658
|
-
|
|
3659
|
-
|
|
3853
|
+
function ensureBlockBreak(output) {
|
|
3854
|
+
if (output.content !== "" && !output.content.endsWith("\n")) append(output, "\n");
|
|
3855
|
+
}
|
|
3856
|
+
function findHtmlTagEnd(source, from) {
|
|
3857
|
+
let quote;
|
|
3858
|
+
for (let index = from; index < source.length; index += 1) {
|
|
3859
|
+
const character = source[index];
|
|
3860
|
+
if (quote) {
|
|
3861
|
+
if (character === quote) quote = void 0;
|
|
3862
|
+
continue;
|
|
3863
|
+
}
|
|
3864
|
+
if (character === "\"" || character === "'") {
|
|
3865
|
+
quote = character;
|
|
3866
|
+
continue;
|
|
3867
|
+
}
|
|
3868
|
+
if (character === ">") return index;
|
|
3660
3869
|
}
|
|
3661
|
-
return
|
|
3870
|
+
return -1;
|
|
3662
3871
|
}
|
|
3663
3872
|
/**
|
|
3664
|
-
*
|
|
3665
|
-
* HTTP(S)-ссылки, `#хэштеги` и `@упоминания`.
|
|
3873
|
+
* Преобразует ограниченный HTML в обычный текст и wire-spans.
|
|
3666
3874
|
*
|
|
3667
|
-
*
|
|
3668
|
-
* `
|
|
3875
|
+
* Разрешены только семантические теги форматирования. Атрибуты событий игнорируются,
|
|
3876
|
+
* содержимое `script`, `style`, `iframe`, `object`, SVG и подобных активных элементов
|
|
3877
|
+
* удаляется. Опасный `href` сохраняет текст ссылки, но не создаёт span.
|
|
3669
3878
|
*/
|
|
3670
|
-
function
|
|
3671
|
-
const
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
const
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
3684
|
-
|
|
3879
|
+
function parseHtml(source, options = {}) {
|
|
3880
|
+
const output = {
|
|
3881
|
+
content: "",
|
|
3882
|
+
spans: []
|
|
3883
|
+
};
|
|
3884
|
+
const protocols = allowedProtocols(options);
|
|
3885
|
+
const stack = [];
|
|
3886
|
+
let position = 0;
|
|
3887
|
+
const closeTag = (tag) => {
|
|
3888
|
+
for (let index = stack.length - 1; index >= 0; index -= 1) {
|
|
3889
|
+
const open = stack[index];
|
|
3890
|
+
if (open?.tag !== tag) continue;
|
|
3891
|
+
stack.splice(index, 1);
|
|
3892
|
+
addSpan(output, open.start, open.span);
|
|
3893
|
+
return;
|
|
3894
|
+
}
|
|
3895
|
+
};
|
|
3896
|
+
while (position < source.length) {
|
|
3897
|
+
if (source.startsWith("<!--", position)) {
|
|
3898
|
+
const end = source.indexOf("-->", position + 4);
|
|
3899
|
+
position = end < 0 ? source.length : end + 3;
|
|
3900
|
+
continue;
|
|
3901
|
+
}
|
|
3902
|
+
if (source[position] === "<") {
|
|
3903
|
+
const end = findHtmlTagEnd(source, position + 1);
|
|
3904
|
+
if (end >= 0) {
|
|
3905
|
+
const parsed = source.slice(position, end + 1).match(/^<\s*(\/?)\s*([a-z][\w-]*)([\s\S]*?)\/?\s*>$/iu);
|
|
3906
|
+
if (parsed) {
|
|
3907
|
+
const closing = parsed[1] === "/";
|
|
3908
|
+
const tag = (parsed[2] ?? "").toLowerCase();
|
|
3909
|
+
const attributes = parsed[3] ?? "";
|
|
3910
|
+
if (!closing && HTML_DROPPED_TAGS.has(tag)) {
|
|
3911
|
+
const closingPattern = new RegExp(`<\\s*\\/\\s*${tag}\\s*>`, "igu");
|
|
3912
|
+
closingPattern.lastIndex = end + 1;
|
|
3913
|
+
const match = closingPattern.exec(source);
|
|
3914
|
+
position = match ? match.index + match[0].length : source.length;
|
|
3915
|
+
continue;
|
|
3916
|
+
}
|
|
3917
|
+
if (tag === "br" && !closing) {
|
|
3918
|
+
append(output, "\n");
|
|
3919
|
+
position = end + 1;
|
|
3920
|
+
continue;
|
|
3921
|
+
}
|
|
3922
|
+
if (tag === "img" && !closing) {
|
|
3923
|
+
append(output, readAttribute(attributes, "alt") ?? "");
|
|
3924
|
+
position = end + 1;
|
|
3925
|
+
continue;
|
|
3926
|
+
}
|
|
3927
|
+
if (closing) {
|
|
3928
|
+
closeTag(tag);
|
|
3929
|
+
if (HTML_BLOCK_TAGS.has(tag)) ensureBlockBreak(output);
|
|
3930
|
+
} else {
|
|
3931
|
+
if (HTML_BLOCK_TAGS.has(tag)) ensureBlockBreak(output);
|
|
3932
|
+
const span = htmlSpan(tag, attributes, protocols);
|
|
3933
|
+
if (span) stack.push({
|
|
3934
|
+
tag,
|
|
3935
|
+
start: output.content.length,
|
|
3936
|
+
span
|
|
3937
|
+
});
|
|
3938
|
+
}
|
|
3939
|
+
position = end + 1;
|
|
3940
|
+
continue;
|
|
3941
|
+
}
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
const next = source.indexOf("<", position + 1);
|
|
3945
|
+
const end = next < 0 ? source.length : next;
|
|
3946
|
+
append(output, decodeEntities(source.slice(position, end)));
|
|
3947
|
+
position = end;
|
|
3685
3948
|
}
|
|
3686
|
-
|
|
3687
|
-
|
|
3688
|
-
if (
|
|
3689
|
-
const offset = match.index;
|
|
3690
|
-
const previous = previousCodePoint(text, offset);
|
|
3691
|
-
if (/[\p{L}\p{M}\p{N}_#@.]/u.test(previous)) continue;
|
|
3692
|
-
const end = offset + match[0].length;
|
|
3693
|
-
if (links.some((span) => overlaps(span, offset, end))) continue;
|
|
3694
|
-
const hashtag = match[1];
|
|
3695
|
-
const username = match[2];
|
|
3696
|
-
if (hashtag !== void 0 && includeHashtags) spans.push({
|
|
3697
|
-
type: SpanType.Hashtag,
|
|
3698
|
-
offset,
|
|
3699
|
-
length: match[0].length,
|
|
3700
|
-
tag: hashtag
|
|
3701
|
-
});
|
|
3702
|
-
else if (username !== void 0 && includeMentions) spans.push({
|
|
3703
|
-
type: SpanType.Mention,
|
|
3704
|
-
offset,
|
|
3705
|
-
length: username.length + 1,
|
|
3706
|
-
username
|
|
3707
|
-
});
|
|
3949
|
+
while (stack.length > 0) {
|
|
3950
|
+
const open = stack.pop();
|
|
3951
|
+
if (open) addSpan(output, open.start, open.span);
|
|
3708
3952
|
}
|
|
3709
|
-
|
|
3953
|
+
while (output.content.endsWith("\n")) output.content = output.content.slice(0, -1);
|
|
3954
|
+
return finish(output);
|
|
3710
3955
|
}
|
|
3711
3956
|
// src/builders/poll.ts
|
|
3712
3957
|
/** Минимальное число вариантов ответа. */
|
|
@@ -4750,10 +4995,70 @@ var ShopResource = class {
|
|
|
4750
4995
|
this.consents = new ShopConsentsResource(http);
|
|
4751
4996
|
}
|
|
4752
4997
|
};
|
|
4998
|
+
// src/models/subscription.ts
|
|
4999
|
+
/** Известные типы способов оплаты. */
|
|
5000
|
+
const PaymentMethodType = Object.freeze({
|
|
5001
|
+
/** Банковская карта. */
|
|
5002
|
+
BankCard: "bank_card" });
|
|
5003
|
+
/** Для кого оформляется подписка. */
|
|
5004
|
+
const SubscriptionCheckoutKind = Object.freeze({
|
|
5005
|
+
/** Покупка для себя. */
|
|
5006
|
+
Self: "self",
|
|
5007
|
+
/** Подарок другому пользователю. */
|
|
5008
|
+
Gift: "gift"
|
|
5009
|
+
});
|
|
5010
|
+
/** Состояние оформления или попытки оплаты. */
|
|
5011
|
+
const SubscriptionCheckoutStatus = Object.freeze({
|
|
5012
|
+
/** Можно выбрать предложение и начать оплату. */
|
|
5013
|
+
Ready: "ready",
|
|
5014
|
+
/** Платёж ждёт подтверждения. */
|
|
5015
|
+
Pending: "pending",
|
|
5016
|
+
/** Платёж обрабатывается. */
|
|
5017
|
+
Processing: "processing",
|
|
5018
|
+
/** Оплата завершена. */
|
|
5019
|
+
Succeeded: "succeeded",
|
|
5020
|
+
/** Платёж отменён. */
|
|
5021
|
+
Canceled: "canceled",
|
|
5022
|
+
/** Платёж завершился ошибкой. */
|
|
5023
|
+
Failed: "failed",
|
|
5024
|
+
/** Платёж требует проверки. */
|
|
5025
|
+
ReviewRequired: "review_required"
|
|
5026
|
+
});
|
|
5027
|
+
/** Известные платёжные сервисы. */
|
|
5028
|
+
const SubscriptionPaymentProvider = Object.freeze({
|
|
5029
|
+
/** ЮKassa. */
|
|
5030
|
+
YooKassa: "yookassa",
|
|
5031
|
+
/** bePaid. */
|
|
5032
|
+
BePaid: "bepaid"
|
|
5033
|
+
});
|
|
5034
|
+
/** Результат запроса международной оплаты. */
|
|
5035
|
+
const InternationalSubscriptionCheckoutMode = Object.freeze({
|
|
5036
|
+
/** Доступна информационная страница. */
|
|
5037
|
+
Informational: "informational",
|
|
5038
|
+
/** Доступна форма перехода к оплате. */
|
|
5039
|
+
Checkout: "checkout"
|
|
5040
|
+
});
|
|
4753
5041
|
// src/resources/subscription.ts
|
|
4754
|
-
|
|
5042
|
+
/** Версия протокола оплаты по выбранному предложению. */
|
|
5043
|
+
const SUBSCRIPTION_CHECKOUT_VERSION = 2;
|
|
5044
|
+
const SUBSCRIPTION_METHODS = defineBuiltInOperation("subscription.methods", (body) => Array.isArray(body) ? body.map((method) => ({
|
|
5045
|
+
...method,
|
|
5046
|
+
...method.last4 === void 0 && method.cardLast4 != null ? { last4: method.cardLast4 } : {},
|
|
5047
|
+
...method.brand === void 0 && method.cardBrand != null ? { brand: method.cardBrand } : {}
|
|
5048
|
+
})) : []);
|
|
4755
5049
|
const SUBSCRIPTION_STATUS = passthroughOperation("subscription.status");
|
|
5050
|
+
const SUBSCRIPTION_CHECKOUT_STATE = passthroughOperation("subscription.checkoutState");
|
|
5051
|
+
const SUBSCRIPTION_PAYMENT = passthroughOperation("subscription.payment");
|
|
5052
|
+
const SUBSCRIPTION_GIFT = passthroughOperation("subscription.gift");
|
|
5053
|
+
const SUBSCRIPTION_GIFT_GIVER = passthroughOperation("subscription.giftGiver");
|
|
5054
|
+
const SUBSCRIPTION_INTERNATIONAL_CAPABILITY = passthroughOperation("subscription.internationalCheckoutCapability");
|
|
4756
5055
|
const SUBSCRIPTION_PAY = passthroughOperation("subscription.pay");
|
|
5056
|
+
const SUBSCRIPTION_PAY_CHECKOUT = passthroughOperation("subscription.payCheckout");
|
|
5057
|
+
const SUBSCRIPTION_CREATE_GIFT = passthroughOperation("subscription.createGift");
|
|
5058
|
+
const SUBSCRIPTION_RELEASE_CHECKOUT = passthroughOperation("subscription.releaseCheckout");
|
|
5059
|
+
const SUBSCRIPTION_INTERNATIONAL_CHECKOUT = passthroughOperation("subscription.internationalCheckout");
|
|
5060
|
+
const SUBSCRIPTION_RESUME_INTERNATIONAL_CHECKOUT = passthroughOperation("subscription.resumeInternationalCheckout");
|
|
5061
|
+
const SUBSCRIPTION_RELEASE_INTERNATIONAL_CHECKOUT = passthroughOperation("subscription.releaseInternationalCheckout");
|
|
4757
5062
|
const SUBSCRIPTION_SET_AUTO_RENEWAL = passthroughOperation("subscription.setAutoRenewal");
|
|
4758
5063
|
const SUBSCRIPTION_BIND_CARD = passthroughOperation("subscription.bindCard");
|
|
4759
5064
|
const SUBSCRIPTION_SET_DEFAULT_METHOD = passthroughOperation("subscription.setDefaultMethod");
|
|
@@ -4771,14 +5076,107 @@ var SubscriptionResource = class extends BaseResource {
|
|
|
4771
5076
|
...options
|
|
4772
5077
|
});
|
|
4773
5078
|
}
|
|
4774
|
-
/**
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4778
|
-
|
|
4779
|
-
|
|
5079
|
+
/** Загружает предложения и состояние попытки для себя или получателя подарка. */
|
|
5080
|
+
checkoutState(input, options = {}) {
|
|
5081
|
+
return this.http.execute(SUBSCRIPTION_CHECKOUT_STATE, {
|
|
5082
|
+
path: "/api/v1/subscription/checkout-state",
|
|
5083
|
+
query: {
|
|
5084
|
+
kind: input.kind,
|
|
5085
|
+
recipientUserId: input.recipientUserId,
|
|
5086
|
+
idempotencyKey: input.idempotencyKey
|
|
5087
|
+
},
|
|
5088
|
+
...options
|
|
5089
|
+
});
|
|
5090
|
+
}
|
|
5091
|
+
/** Загружает состояние оплаты по ID платежа. */
|
|
5092
|
+
payment(paymentId, options = {}) {
|
|
5093
|
+
return this.http.execute(SUBSCRIPTION_PAYMENT, {
|
|
5094
|
+
path: `/api/v1/subscription/payments/${encodePathSegment(paymentId, "paymentId")}`,
|
|
5095
|
+
...options
|
|
5096
|
+
});
|
|
5097
|
+
}
|
|
5098
|
+
/** Загружает состояние подарка по ID. */
|
|
5099
|
+
gift(giftId, options = {}) {
|
|
5100
|
+
return this.http.execute(SUBSCRIPTION_GIFT, {
|
|
5101
|
+
path: `/api/v1/subscription/gifts/${encodePathSegment(giftId, "giftId")}`,
|
|
5102
|
+
...options
|
|
5103
|
+
});
|
|
5104
|
+
}
|
|
5105
|
+
/** Загружает число подаренных пользователем подписок. */
|
|
5106
|
+
giftGiver(userId, options = {}) {
|
|
5107
|
+
return this.http.execute(SUBSCRIPTION_GIFT_GIVER, {
|
|
5108
|
+
path: `/api/v1/subscription/gift-giver/${encodePathSegment(userId, "userId")}`,
|
|
5109
|
+
...options
|
|
5110
|
+
});
|
|
5111
|
+
}
|
|
5112
|
+
/** Загружает доступность международной оплаты, предложения и действующий обменный курс. */
|
|
5113
|
+
internationalCheckoutCapability(options = {}) {
|
|
5114
|
+
return this.http.execute(SUBSCRIPTION_INTERNATIONAL_CAPABILITY, {
|
|
5115
|
+
path: "/api/v1/subscription/international-checkouts/capability",
|
|
5116
|
+
...options
|
|
5117
|
+
});
|
|
5118
|
+
}
|
|
5119
|
+
/** Запускает обычную оплату подписки с выбранным способом оплаты, если он указан. */
|
|
5120
|
+
pay({ methodId, ...options } = {}) {
|
|
4780
5121
|
return this.http.execute(SUBSCRIPTION_PAY, {
|
|
4781
5122
|
path: "/api/v1/subscription/pay",
|
|
5123
|
+
...methodId !== void 0 ? { body: { methodId } } : {},
|
|
5124
|
+
...options
|
|
5125
|
+
});
|
|
5126
|
+
}
|
|
5127
|
+
/** Запускает оплату своей подписки по выбранному предложению из {@link checkoutState}. */
|
|
5128
|
+
payCheckout(input, options = {}) {
|
|
5129
|
+
return this.http.execute(SUBSCRIPTION_PAY_CHECKOUT, {
|
|
5130
|
+
path: "/api/v1/subscription/pay",
|
|
5131
|
+
body: {
|
|
5132
|
+
...input,
|
|
5133
|
+
checkoutVersion: SUBSCRIPTION_CHECKOUT_VERSION,
|
|
5134
|
+
autoRenewal: input.autoRenewal ?? false
|
|
5135
|
+
},
|
|
5136
|
+
...options
|
|
5137
|
+
});
|
|
5138
|
+
}
|
|
5139
|
+
/** Запускает оплату подарка по выбранному предложению из {@link checkoutState}. */
|
|
5140
|
+
createGift(input, options = {}) {
|
|
5141
|
+
return this.http.execute(SUBSCRIPTION_CREATE_GIFT, {
|
|
5142
|
+
path: "/api/v1/subscription/gifts",
|
|
5143
|
+
body: {
|
|
5144
|
+
...input,
|
|
5145
|
+
checkoutVersion: SUBSCRIPTION_CHECKOUT_VERSION,
|
|
5146
|
+
autoRenewal: false
|
|
5147
|
+
},
|
|
5148
|
+
...options
|
|
5149
|
+
});
|
|
5150
|
+
}
|
|
5151
|
+
/** Освобождает ожидающую попытку оплаты, если её состояние допускает это действие. */
|
|
5152
|
+
releaseCheckout(input, options = {}) {
|
|
5153
|
+
return this.http.execute(SUBSCRIPTION_RELEASE_CHECKOUT, {
|
|
5154
|
+
path: "/api/v1/subscription/checkout-release",
|
|
5155
|
+
body: input,
|
|
5156
|
+
...options
|
|
5157
|
+
});
|
|
5158
|
+
}
|
|
5159
|
+
/** Запрашивает данные для перехода к международной оплате. */
|
|
5160
|
+
internationalCheckout(input, options = {}) {
|
|
5161
|
+
return this.http.execute(SUBSCRIPTION_INTERNATIONAL_CHECKOUT, {
|
|
5162
|
+
path: "/api/v1/subscription/international-checkouts",
|
|
5163
|
+
body: input,
|
|
5164
|
+
...options
|
|
5165
|
+
});
|
|
5166
|
+
}
|
|
5167
|
+
/** Получает ссылку для продолжения существующей попытки международной оплаты. */
|
|
5168
|
+
resumeInternationalCheckout(attemptId, options = {}) {
|
|
5169
|
+
return this.http.execute(SUBSCRIPTION_RESUME_INTERNATIONAL_CHECKOUT, {
|
|
5170
|
+
path: "/api/v1/subscription/international-checkouts/resume",
|
|
5171
|
+
body: { attemptId },
|
|
5172
|
+
...options
|
|
5173
|
+
});
|
|
5174
|
+
}
|
|
5175
|
+
/** Освобождает попытку международной оплаты. */
|
|
5176
|
+
releaseInternationalCheckout(input, options = {}) {
|
|
5177
|
+
return this.http.execute(SUBSCRIPTION_RELEASE_INTERNATIONAL_CHECKOUT, {
|
|
5178
|
+
path: "/api/v1/subscription/international-checkouts/release",
|
|
5179
|
+
body: input,
|
|
4782
5180
|
...options
|
|
4783
5181
|
});
|
|
4784
5182
|
}
|
|
@@ -4791,9 +5189,10 @@ var SubscriptionResource = class extends BaseResource {
|
|
|
4791
5189
|
});
|
|
4792
5190
|
}
|
|
4793
5191
|
/** Запускает привязку карты. */
|
|
4794
|
-
bindCard(options = {}) {
|
|
5192
|
+
bindCard({ type = PaymentMethodType.BankCard, ...options } = {}) {
|
|
4795
5193
|
return this.http.execute(SUBSCRIPTION_BIND_CARD, {
|
|
4796
5194
|
path: "/api/v1/subscription/bind-card",
|
|
5195
|
+
body: { type },
|
|
4797
5196
|
...options
|
|
4798
5197
|
});
|
|
4799
5198
|
}
|
|
@@ -5168,6 +5567,9 @@ const USERS_FOLLOW = passthroughOperation("users.follow");
|
|
|
5168
5567
|
const USERS_FOLLOW_STATUS = passthroughOperation("users.followStatus");
|
|
5169
5568
|
const USERS_GET_PRIVACY = passthroughOperation("users.getPrivacy");
|
|
5170
5569
|
const USERS_UPDATE_PRIVACY = passthroughOperation("users.updatePrivacy");
|
|
5570
|
+
const USERS_MESSAGE_ALLOWLIST = pageOperation("users.messageAllowlist", (body) => readPagedPage(body, "users"));
|
|
5571
|
+
const USERS_ADD_TO_MESSAGE_ALLOWLIST = passthroughOperation("users.addToMessageAllowlist");
|
|
5572
|
+
const USERS_REMOVE_FROM_MESSAGE_ALLOWLIST = passthroughOperation("users.removeFromMessageAllowlist");
|
|
5171
5573
|
const USERS_UNFOLLOW = voidOperation("users.unfollow");
|
|
5172
5574
|
const USERS_BLOCK = voidOperation("users.block");
|
|
5173
5575
|
const USERS_UNBLOCK = voidOperation("users.unblock");
|
|
@@ -5199,6 +5601,13 @@ var UsersResource = class extends BaseResource {
|
|
|
5199
5601
|
start: (p) => p.page !== void 0 ? { page: p.page } : {},
|
|
5200
5602
|
mode: PaginationMode.Page
|
|
5201
5603
|
});
|
|
5604
|
+
#messageAllowlist = this.paginated({
|
|
5605
|
+
operation: USERS_MESSAGE_ALLOWLIST,
|
|
5606
|
+
path: () => "/api/users/me/message-allowlist",
|
|
5607
|
+
query: ({ limit }) => ({ limit }),
|
|
5608
|
+
start: ({ page }) => page !== void 0 ? { page } : {},
|
|
5609
|
+
mode: PaginationMode.Page
|
|
5610
|
+
});
|
|
5202
5611
|
/** Загружает свой профиль — с подпиской и признаком подтверждённого телефона. */
|
|
5203
5612
|
me(options = {}) {
|
|
5204
5613
|
return this.http.execute(USERS_ME, {
|
|
@@ -5395,6 +5804,28 @@ var UsersResource = class extends BaseResource {
|
|
|
5395
5804
|
...options
|
|
5396
5805
|
});
|
|
5397
5806
|
}
|
|
5807
|
+
/** Загружает страницу списка пользователей, которым разрешено писать вам личные сообщения. */
|
|
5808
|
+
messageAllowlist(params = {}, options = {}) {
|
|
5809
|
+
return this.#messageAllowlist.list(params, options);
|
|
5810
|
+
}
|
|
5811
|
+
/** Перебирает список исключений для личных сообщений, начиная с указанной страницы. */
|
|
5812
|
+
iterateMessageAllowlist(params = {}, options = {}) {
|
|
5813
|
+
return this.#messageAllowlist.iterate(params, options);
|
|
5814
|
+
}
|
|
5815
|
+
/** Добавляет пользователя по ID в список исключений для входящих личных сообщений. */
|
|
5816
|
+
addToMessageAllowlist(userId, options = {}) {
|
|
5817
|
+
return this.http.execute(USERS_ADD_TO_MESSAGE_ALLOWLIST, {
|
|
5818
|
+
path: `/api/users/${encodePathSegment(userId, "userId")}/message-allowlist`,
|
|
5819
|
+
...options
|
|
5820
|
+
});
|
|
5821
|
+
}
|
|
5822
|
+
/** Удаляет исключение по ID пользователя. Дальше действуют общие настройки личных сообщений. */
|
|
5823
|
+
removeFromMessageAllowlist(userId, options = {}) {
|
|
5824
|
+
return this.http.execute(USERS_REMOVE_FROM_MESSAGE_ALLOWLIST, {
|
|
5825
|
+
path: `/api/users/${encodePathSegment(userId, "userId")}/message-allowlist`,
|
|
5826
|
+
...options
|
|
5827
|
+
});
|
|
5828
|
+
}
|
|
5398
5829
|
/**
|
|
5399
5830
|
* Загружает значки профиля и выбранный из них.
|
|
5400
5831
|
*
|
|
@@ -6051,6 +6482,6 @@ function renderSpans(content, spans = [], options = {}) {
|
|
|
6051
6482
|
}
|
|
6052
6483
|
return result;
|
|
6053
6484
|
}
|
|
6054
|
-
export {
|
|
6485
|
+
export { ChatReactionType as $, AccountLifecycleResource as A, AUDIO_MIME_TYPES as B, poll as C, LegalDocumentScope as D, LegalDocumentBlockType as E, BaseResource as F, autoSpans as G, VIDEO_MIME_TYPES as H, PaginationMode as I, normalizeChatUpdate as J, markup as K, Paginator as L, createFeatureHost as M, ExtensibleOperationCatalog as N, comment as O, ChatsResource as P, ChatMediaCategory as Q, mapPage as R, post as S, parseMarkdown as T, message as U, IMAGE_MIME_TYPES as V, messageMarkup as W, utcStampToIso as X, toDate as Y, ChatActionType as Z, PaymentMethodType as _, createShopOrderAccessStorage as a, SubscriptionPaymentProvider as b, ShopOrderStatus as c, isMyProfile as d, ChatUpdateType as et, BannerDrawingTool as f, InternationalSubscriptionCheckoutMode as g, createResources as h, MemoryShopOrderAccessStorage as i, NotificationsResource as j, createStatusFeature as k, ShopProductCategory as l, fromUrl as m, renderSpans as n, statusDays as o, fromStream as p, isBuilder as q, createShopFeature as r, ShopConsentKind as s, SpanRenderFormat as t, ShopProductStatus as u, SubscriptionCheckoutKind as v, parseHtml as w, report as x, SubscriptionCheckoutStatus as y, ALLOWED_MIME_TYPES as z };
|
|
6055
6486
|
|
|
6056
|
-
//# sourceMappingURL=render-
|
|
6487
|
+
//# sourceMappingURL=render-CgSQp84V.js.map
|