itd-api 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as withNamespace, a as createTokenStorage, c as KeyValueStore, d as MemoryKeyValueStore, f as RecordKeyValueStoreSource, g as withCodec, h as isEnumerableKeyValueStore, i as TokenStorageAdapterOptions, l as KeyValueStoreKeys, m as createRecordKeyValueStore, n as MemoryTokenStorage, o as EnumerableKeyValueStore, p as createKeyValueStore, r as TokenStorage, s as KeyValueCodec, t as ItdSession, u as KeyValueStoreResult } from "./storage-Doe3lpFQ.js";
2
- import { _ as UrlFile, a as scopedTokenStorage, c as FileContent, d as FileStreamContent, f as FileStreamOptions, g as StreamFile, h as LazyFile, i as createMultiTokenStorage, l as FileContext, m as FromStreamOptions, n as MultiTokenStorage, o as DEFAULT_FILE_STREAM_BUFFER_BYTES, p as FileTransferMode, r as MultiTokenStorageAdapterOptions, s as DEFAULT_URL_FILE_MAX_BYTES, t as MemoryMultiTokenStorage, u as FileInput, v as UrlFileOptions } from "./multi-storage-CLqmzq07.js";
1
+ import { _ as withNamespace, a as createTokenStorage, c as KeyValueStore, d as MemoryKeyValueStore, f as RecordKeyValueStoreSource, g as withCodec, h as isEnumerableKeyValueStore, i as TokenStorageAdapterOptions, l as KeyValueStoreKeys, m as createRecordKeyValueStore, n as MemoryTokenStorage, o as EnumerableKeyValueStore, p as createKeyValueStore, r as TokenStorage, s as KeyValueCodec, t as ItdSession, u as KeyValueStoreResult } from "./storage-BqMxs76Y.js";
2
+ import { a as scopedTokenStorage, c as FileInput, d as FileTransferMode, f as FromStreamOptions, g as UrlFileOptions, h as UrlFile, i as createMultiTokenStorage, l as FileStreamContent, m as StreamFile, n as MultiTokenStorage, o as FileContent, p as LazyFile, r as MultiTokenStorageAdapterOptions, s as FileContext, t as MemoryMultiTokenStorage, u as FileStreamOptions } from "./multi-storage-CQSlI_kn.js";
3
3
  //#region src/types/enums.d.ts
4
4
  /**
5
5
  * Перечисления API итд.com.
@@ -372,6 +372,55 @@ interface Span {
372
372
  id?: string;
373
373
  }
374
374
  //#endregion
375
+ //#region src/core/buckets.d.ts
376
+ /**
377
+ * Ёмкость серверных счётчиков частоты, запросов в минуту.
378
+ *
379
+ * Таблица действует до первого ответа бакета; дальше ёмкость берётся из заголовка
380
+ * `x-ratelimit-limit` и заменяет табличную. `default` — счётчик любого пути без
381
+ * собственного правила на сервере.
382
+ */
383
+ declare const BUCKET_LIMITS: Readonly<{
384
+ readonly 'posts.stats': 180;
385
+ readonly default: 150;
386
+ readonly feed: 90;
387
+ readonly 'posts.like': 85;
388
+ readonly 'posts.comments': 80;
389
+ readonly hashtags: 50;
390
+ readonly users: 40;
391
+ readonly notifications: 40;
392
+ readonly 'files.get': 40;
393
+ readonly auth: 35;
394
+ readonly 'auth.refresh': 25;
395
+ readonly search: 25;
396
+ readonly 'comments.like': 22;
397
+ readonly 'files.upload': 15;
398
+ readonly 'files.remove': 15;
399
+ readonly 'posts.comment': 14;
400
+ readonly 'hashtags.trending': 13;
401
+ readonly 'posts.repost': 7;
402
+ readonly 'users.follow': 7;
403
+ readonly 'verification.status': 6;
404
+ readonly 'posts.create': 5;
405
+ readonly 'users.updateMe': 3;
406
+ readonly 'reports.create': 3;
407
+ readonly 'verification.submit': 3;
408
+ }>;
409
+ /** Имя встроенного бакета. */
410
+ type RateLimitBucket = keyof typeof BUCKET_LIMITS;
411
+ /** Счётчик, из которого списывается путь без собственного правила на сервере. */
412
+ declare const DEFAULT_RATE_LIMIT_BUCKET: RateLimitBucket;
413
+ /** Реакция на остаток лимита из заголовков ответа. */
414
+ declare const RateLimitPacing: Readonly<{
415
+ /** Задержек нет, пока в бакете есть остаток; исчерпанный бакет ждёт `60000 / limit`. */
416
+ readonly React: "react";
417
+ /** Ровный темп в пределах минутного лимита: задержки идут с первого запроса. */
418
+ readonly Smooth: "smooth";
419
+ /** Остаток на темп не влияет; остаётся пауза после `429`. */
420
+ readonly Off: "off";
421
+ }>;
422
+ type RateLimitPacing = (typeof RateLimitPacing)[keyof typeof RateLimitPacing];
423
+ //#endregion
375
424
  //#region src/core/clock.d.ts
376
425
  /**
377
426
  * Часы, которыми клиент измеряет время и планирует отложенную работу.
@@ -405,6 +454,13 @@ type RetrySafety = (typeof RetrySafety)[keyof typeof RetrySafety];
405
454
  interface OperationDefinition {
406
455
  readonly method: OperationMethod;
407
456
  readonly retrySafety: RetrySafety;
457
+ /**
458
+ * Бакет операции. Опущено — операция списывает из `default`.
459
+ *
460
+ * Счётчик определяется парой «путь + метод»: `GET /api/users/me` — 40 запросов
461
+ * в минуту, `PUT` того же пути — 3, `DELETE` — 150.
462
+ */
463
+ readonly bucket?: RateLimitBucket;
408
464
  }
409
465
  /**
410
466
  * Каталог встроенных операций.
@@ -420,58 +476,72 @@ declare const OPERATIONS: Readonly<{
420
476
  readonly 'auth.signUp': Readonly<{
421
477
  readonly method: "POST";
422
478
  readonly retrySafety: "unsafe";
479
+ readonly bucket: "auth";
423
480
  }>;
424
481
  readonly 'auth.signIn': Readonly<{
425
482
  readonly method: "POST";
426
483
  readonly retrySafety: "safe";
484
+ readonly bucket: "auth";
427
485
  }>;
428
486
  readonly 'auth.verifyOtp': Readonly<{
429
487
  readonly method: "POST";
430
488
  readonly retrySafety: "unsafe";
489
+ readonly bucket: "auth";
431
490
  }>;
432
491
  readonly 'auth.resendOtp': Readonly<{
433
492
  readonly method: "POST";
434
493
  readonly retrySafety: "unsafe";
494
+ readonly bucket: "auth";
435
495
  }>;
436
496
  readonly 'auth.refresh': Readonly<{
437
497
  readonly method: "POST";
438
498
  readonly retrySafety: "unsafe";
499
+ readonly bucket: "auth.refresh";
439
500
  }>;
440
501
  readonly 'auth.logout': Readonly<{
441
502
  readonly method: "POST";
442
503
  readonly retrySafety: "unsafe";
504
+ readonly bucket: "auth";
443
505
  }>;
444
506
  readonly 'auth.forgotPassword': Readonly<{
445
507
  readonly method: "POST";
446
508
  readonly retrySafety: "unsafe";
509
+ readonly bucket: "auth";
447
510
  }>;
448
511
  readonly 'auth.resetPassword': Readonly<{
449
512
  readonly method: "POST";
450
513
  readonly retrySafety: "unsafe";
514
+ readonly bucket: "auth";
451
515
  }>;
452
516
  readonly 'auth.changePassword': Readonly<{
453
517
  readonly method: "POST";
454
518
  readonly retrySafety: "unsafe";
519
+ readonly bucket: "auth";
455
520
  }>;
456
521
  readonly 'auth.sessions': Readonly<{
457
522
  readonly method: "GET";
458
523
  readonly retrySafety: "safe";
524
+ readonly bucket: "auth";
459
525
  }>;
460
526
  readonly 'auth.revokeSession': Readonly<{
461
527
  readonly method: "DELETE";
462
528
  readonly retrySafety: "unsafe";
529
+ readonly bucket: "auth";
463
530
  }>;
464
531
  readonly 'auth.revokeOtherSessions': Readonly<{
465
532
  readonly method: "DELETE";
466
533
  readonly retrySafety: "unsafe";
534
+ readonly bucket: "auth";
467
535
  }>;
468
536
  readonly 'users.me': Readonly<{
469
537
  readonly method: "GET";
470
538
  readonly retrySafety: "safe";
539
+ readonly bucket: "users";
471
540
  }>;
472
541
  readonly 'users.updateMe': Readonly<{
473
542
  readonly method: "PUT";
474
543
  readonly retrySafety: "idempotent";
544
+ readonly bucket: "users.updateMe";
475
545
  }>;
476
546
  readonly 'users.deactivate': Readonly<{
477
547
  readonly method: "DELETE";
@@ -488,38 +558,47 @@ declare const OPERATIONS: Readonly<{
488
558
  readonly 'users.get': Readonly<{
489
559
  readonly method: "GET";
490
560
  readonly retrySafety: "safe";
561
+ readonly bucket: "users";
491
562
  }>;
492
563
  readonly 'users.checkUsername': Readonly<{
493
564
  readonly method: "GET";
494
565
  readonly retrySafety: "safe";
566
+ readonly bucket: "users";
495
567
  }>;
496
568
  readonly 'users.search': Readonly<{
497
569
  readonly method: "GET";
498
570
  readonly retrySafety: "safe";
571
+ readonly bucket: "users";
499
572
  }>;
500
573
  readonly 'users.whoToFollow': Readonly<{
501
574
  readonly method: "GET";
502
575
  readonly retrySafety: "safe";
576
+ readonly bucket: "users";
503
577
  }>;
504
578
  readonly 'users.topClans': Readonly<{
505
579
  readonly method: "GET";
506
580
  readonly retrySafety: "safe";
581
+ readonly bucket: "users";
507
582
  }>;
508
583
  readonly 'users.follow': Readonly<{
509
584
  readonly method: "POST";
510
585
  readonly retrySafety: "unsafe";
586
+ readonly bucket: "users.follow";
511
587
  }>;
512
588
  readonly 'users.unfollow': Readonly<{
513
589
  readonly method: "DELETE";
514
590
  readonly retrySafety: "unsafe";
591
+ readonly bucket: "users.follow";
515
592
  }>;
516
593
  readonly 'users.followers': Readonly<{
517
594
  readonly method: "GET";
518
595
  readonly retrySafety: "safe";
596
+ readonly bucket: "users";
519
597
  }>;
520
598
  readonly 'users.following': Readonly<{
521
599
  readonly method: "GET";
522
600
  readonly retrySafety: "safe";
601
+ readonly bucket: "users";
523
602
  }>;
524
603
  readonly 'users.followStatus': Readonly<{
525
604
  readonly method: "POST";
@@ -536,10 +615,12 @@ declare const OPERATIONS: Readonly<{
536
615
  readonly 'users.blocked': Readonly<{
537
616
  readonly method: "GET";
538
617
  readonly retrySafety: "safe";
618
+ readonly bucket: "users";
539
619
  }>;
540
620
  readonly 'users.getPrivacy': Readonly<{
541
621
  readonly method: "GET";
542
622
  readonly retrySafety: "safe";
623
+ readonly bucket: "users";
543
624
  }>;
544
625
  readonly 'users.updatePrivacy': Readonly<{
545
626
  readonly method: "PUT";
@@ -548,6 +629,7 @@ declare const OPERATIONS: Readonly<{
548
629
  readonly 'users.pins': Readonly<{
549
630
  readonly method: "GET";
550
631
  readonly retrySafety: "safe";
632
+ readonly bucket: "users";
551
633
  }>;
552
634
  readonly 'users.setPin': Readonly<{
553
635
  readonly method: "PUT";
@@ -560,10 +642,12 @@ declare const OPERATIONS: Readonly<{
560
642
  readonly 'posts.list': Readonly<{
561
643
  readonly method: "GET";
562
644
  readonly retrySafety: "safe";
645
+ readonly bucket: "feed";
563
646
  }>;
564
647
  readonly 'posts.create': Readonly<{
565
648
  readonly method: "POST";
566
649
  readonly retrySafety: "unsafe";
650
+ readonly bucket: "posts.create";
567
651
  }>;
568
652
  readonly 'posts.get': Readonly<{
569
653
  readonly method: "GET";
@@ -584,18 +668,22 @@ declare const OPERATIONS: Readonly<{
584
668
  readonly 'posts.like': Readonly<{
585
669
  readonly method: "POST";
586
670
  readonly retrySafety: "unsafe";
671
+ readonly bucket: "posts.like";
587
672
  }>;
588
673
  readonly 'posts.unlike': Readonly<{
589
674
  readonly method: "DELETE";
590
675
  readonly retrySafety: "unsafe";
676
+ readonly bucket: "posts.like";
591
677
  }>;
592
678
  readonly 'posts.repost': Readonly<{
593
679
  readonly method: "POST";
594
680
  readonly retrySafety: "unsafe";
681
+ readonly bucket: "posts.repost";
595
682
  }>;
596
683
  readonly 'posts.unrepost': Readonly<{
597
684
  readonly method: "DELETE";
598
685
  readonly retrySafety: "unsafe";
686
+ readonly bucket: "posts.repost";
599
687
  }>;
600
688
  readonly 'posts.pin': Readonly<{
601
689
  readonly method: "POST";
@@ -612,6 +700,7 @@ declare const OPERATIONS: Readonly<{
612
700
  readonly 'posts.stats': Readonly<{
613
701
  readonly method: "POST";
614
702
  readonly retrySafety: "safe";
703
+ readonly bucket: "posts.stats";
615
704
  }>;
616
705
  readonly 'posts.byUser': Readonly<{
617
706
  readonly method: "GET";
@@ -624,10 +713,12 @@ declare const OPERATIONS: Readonly<{
624
713
  readonly 'posts.comments': Readonly<{
625
714
  readonly method: "GET";
626
715
  readonly retrySafety: "safe";
716
+ readonly bucket: "posts.comments";
627
717
  }>;
628
718
  readonly 'posts.comment': Readonly<{
629
719
  readonly method: "POST";
630
720
  readonly retrySafety: "unsafe";
721
+ readonly bucket: "posts.comment";
631
722
  }>;
632
723
  readonly 'comments.replies': Readonly<{
633
724
  readonly method: "GET";
@@ -652,30 +743,37 @@ declare const OPERATIONS: Readonly<{
652
743
  readonly 'comments.like': Readonly<{
653
744
  readonly method: "POST";
654
745
  readonly retrySafety: "unsafe";
746
+ readonly bucket: "comments.like";
655
747
  }>;
656
748
  readonly 'comments.unlike': Readonly<{
657
749
  readonly method: "DELETE";
658
750
  readonly retrySafety: "unsafe";
751
+ readonly bucket: "comments.like";
659
752
  }>;
660
753
  readonly 'files.upload': Readonly<{
661
754
  readonly method: "POST";
662
755
  readonly retrySafety: "unsafe";
756
+ readonly bucket: "files.upload";
663
757
  }>;
664
758
  readonly 'files.get': Readonly<{
665
759
  readonly method: "GET";
666
760
  readonly retrySafety: "safe";
761
+ readonly bucket: "files.get";
667
762
  }>;
668
763
  readonly 'files.remove': Readonly<{
669
764
  readonly method: "DELETE";
670
765
  readonly retrySafety: "unsafe";
766
+ readonly bucket: "files.remove";
671
767
  }>;
672
768
  readonly 'notifications.list': Readonly<{
673
769
  readonly method: "GET";
674
770
  readonly retrySafety: "safe";
771
+ readonly bucket: "notifications";
675
772
  }>;
676
773
  readonly 'notifications.count': Readonly<{
677
774
  readonly method: "GET";
678
775
  readonly retrySafety: "safe";
776
+ readonly bucket: "notifications";
679
777
  }>;
680
778
  readonly 'notifications.markRead': Readonly<{
681
779
  readonly method: "POST";
@@ -692,30 +790,46 @@ declare const OPERATIONS: Readonly<{
692
790
  readonly 'notifications.getSettings': Readonly<{
693
791
  readonly method: "GET";
694
792
  readonly retrySafety: "safe";
793
+ readonly bucket: "notifications";
695
794
  }>;
696
795
  readonly 'notifications.updateSettings': Readonly<{
697
796
  readonly method: "PUT";
698
797
  readonly retrySafety: "idempotent";
699
798
  }>;
799
+ readonly 'realtime.poll.updates': Readonly<{
800
+ readonly method: "GET";
801
+ readonly retrySafety: "safe";
802
+ readonly bucket: "notifications";
803
+ }>;
804
+ readonly 'realtime.poll.unread': Readonly<{
805
+ readonly method: "GET";
806
+ readonly retrySafety: "safe";
807
+ readonly bucket: "notifications";
808
+ }>;
700
809
  readonly 'hashtags.search': Readonly<{
701
810
  readonly method: "GET";
702
811
  readonly retrySafety: "safe";
812
+ readonly bucket: "hashtags";
703
813
  }>;
704
814
  readonly 'hashtags.trending': Readonly<{
705
815
  readonly method: "GET";
706
816
  readonly retrySafety: "safe";
817
+ readonly bucket: "hashtags.trending";
707
818
  }>;
708
819
  readonly 'hashtags.posts': Readonly<{
709
820
  readonly method: "GET";
710
821
  readonly retrySafety: "safe";
822
+ readonly bucket: "hashtags";
711
823
  }>;
712
824
  readonly 'search.all': Readonly<{
713
825
  readonly method: "GET";
714
826
  readonly retrySafety: "safe";
827
+ readonly bucket: "search";
715
828
  }>;
716
829
  readonly 'reports.create': Readonly<{
717
830
  readonly method: "POST";
718
831
  readonly retrySafety: "unsafe";
832
+ readonly bucket: "reports.create";
719
833
  }>;
720
834
  readonly 'subscription.status': Readonly<{
721
835
  readonly method: "GET";
@@ -748,10 +862,12 @@ declare const OPERATIONS: Readonly<{
748
862
  readonly 'verification.status': Readonly<{
749
863
  readonly method: "GET";
750
864
  readonly retrySafety: "safe";
865
+ readonly bucket: "verification.status";
751
866
  }>;
752
867
  readonly 'verification.submit': Readonly<{
753
868
  readonly method: "POST";
754
869
  readonly retrySafety: "unsafe";
870
+ readonly bucket: "verification.submit";
755
871
  }>;
756
872
  readonly 'platform.version': Readonly<{
757
873
  readonly method: "GET";
@@ -794,6 +910,13 @@ declare function isBuiltInOperationId(value: string): value is BuiltInOperationI
794
910
  declare function operationMethod(id: BuiltInOperationId): OperationMethod;
795
911
  /** Политика автоматического повтора встроенной операции. */
796
912
  declare function operationRetrySafety(id: BuiltInOperationId): RetrySafety;
913
+ /**
914
+ * Бакет операции.
915
+ *
916
+ * `raw` и `custom:*` попадают в `default`; назвать бакет явно позволяет
917
+ * `rateLimitBucket` у запроса.
918
+ */
919
+ declare function operationBucket(id: OperationId): RateLimitBucket;
797
920
  //#endregion
798
921
  //#region src/core/runtime.d.ts
799
922
  /**
@@ -812,14 +935,6 @@ declare const RuntimeMode: Readonly<{
812
935
  readonly Server: "server";
813
936
  }>;
814
937
  type RuntimeMode = (typeof RuntimeMode)[keyof typeof RuntimeMode];
815
- /** Распознанная среда исполнения. */
816
- declare const DetectedRuntime: Readonly<{
817
- readonly Browser: "browser";
818
- /** Есть `window`, но нет `document`; cookie ведёт нативный сетевой слой. */
819
- readonly ReactNative: "react-native";
820
- readonly Server: "server";
821
- }>;
822
- type DetectedRuntime = (typeof DetectedRuntime)[keyof typeof DetectedRuntime];
823
938
  //#endregion
824
939
  //#region src/core/services.d.ts
825
940
  /** Сервис платформы на отдельном домене. */
@@ -838,48 +953,6 @@ interface ServiceDefinition {
838
953
  */
839
954
  auth?: boolean | undefined;
840
955
  }
841
- /**
842
- * Именованные сервисы клиента.
843
- *
844
- * @internal
845
- */
846
- declare class ServiceRegistry {
847
- #private;
848
- /** @param primaryBaseUrl базовый URL клиента */
849
- constructor(primaryBaseUrl?: string);
850
- /**
851
- * Регистрирует сервис. Имя очищается от краевых пробелов, базовый URL приводится
852
- * к каноничному виду, а незаданный `auth` выводится из хоста.
853
- *
854
- * @throws {ItdConfigError} если имя пустое, имя занято или `baseUrl` не абсолютный URL
855
- */
856
- define(definition: ServiceDefinition): void;
857
- /** Определение сервиса либо `undefined`, если такого нет. */
858
- get(name: string): ServiceDefinition | undefined;
859
- /** Зарегистрирован ли сервис с таким именем. */
860
- has(name: string): boolean;
861
- /**
862
- * Определение сервиса.
863
- *
864
- * @throws {ItdConfigError} если сервис не зарегистрирован
865
- */
866
- require(name: string): ServiceDefinition;
867
- /**
868
- * Базовый URL сервиса.
869
- *
870
- * @throws {ItdConfigError} если сервис не зарегистрирован
871
- */
872
- resolveBaseUrl(name: string): string;
873
- /**
874
- * Принадлежит ли URL основному хосту клиента или его поддомену.
875
- *
876
- * Используется для безопасного значения по умолчанию у разового `baseUrl`: Bearer-токен
877
- * не должен уходить на посторонний хост без явного `skipAuth: false`.
878
- *
879
- * @internal
880
- */
881
- isPrimarySite(baseUrl: string): boolean;
882
- }
883
956
  //#endregion
884
957
  //#region src/core/url.d.ts
885
958
  /** Значение параметра запроса. `undefined` и `null` в строку не попадают. */
@@ -956,31 +1029,65 @@ interface RetryDecisionContext {
956
1029
  method: string;
957
1030
  path: string;
958
1031
  }
1032
+ /** Поправка к одному бакету. */
1033
+ interface RateLimitBucketOverride {
1034
+ /** Одновременных запросов внутри бакета. */
1035
+ concurrency?: number | undefined;
1036
+ /** Ёмкость бакета до первого ответа, запросов в минуту. */
1037
+ limit?: number | undefined;
1038
+ }
1039
+ /** Что известно о запросе в момент выбора бакета. */
1040
+ interface RateLimitBucketContext {
1041
+ operationId: OperationId;
1042
+ method: string;
1043
+ path: string;
1044
+ }
959
1045
  /** Настройки ограничения нагрузки на API. */
960
1046
  interface RateLimitOptions {
961
- /** Сколько запросов выполняется одновременно. По умолчанию 6. */
1047
+ /** Одновременных запросов на всех бакетах вместе. По умолчанию 6. */
962
1048
  concurrency?: number | undefined;
963
1049
  /** Верхняя граница запросов в секунду. По умолчанию без ограничения. */
964
1050
  rps?: number | undefined;
965
1051
  /**
966
- * Паузы перед повторами при ответе `429`, мс.
967
- * По умолчанию `[1000, 5000, 30000, 60000, 90000]`.
1052
+ * Отдельная очередь на каждый бакет. По умолчанию `true`.
968
1053
  *
969
- * Сервер не сообщает, когда сбросится окно лимита, поэтому паузу приходится подбирать.
970
- * Лестница начинается с секунды: если окно почти истекло, работа продолжится почти
971
- * сразу, а если лимит исчерпан всерьёз паузы дорастут до полутора минут.
972
- * Когда лестница закончилась, {@link ItdRateLimitError} пробрасывается вызывающему коду.
1054
+ * `false` одна очередь на направление: её пауза придерживает все запросы разом.
1055
+ * В этом режиме ёмкость отдельного счётчика неизвестна, поэтому `bucketConcurrency`,
1056
+ * `bucketOverrides` и режим `pacing: 'smooth'` не действуют, а исчерпанный остаток
1057
+ * встречается первой ступенью `retryDelays`.
1058
+ */
1059
+ buckets?: boolean | undefined;
1060
+ /**
1061
+ * Одновременных запросов внутри одного бакета. По умолчанию равен `concurrency`.
973
1062
  *
974
- * Этот список не зависит от `retry.attempts`: тот управляет повторами при обрывах
975
- * сети и ошибках сервера, где уместен совсем другой темп.
1063
+ * Встроенное исключение `files.upload` с пределом 1. При `buckets: false` не действует.
976
1064
  */
977
- retryDelays?: readonly number[] | undefined;
1065
+ bucketConcurrency?: number | undefined;
1066
+ /**
1067
+ * Поправки для отдельных бакетов. Неизвестное имя — ошибка конфигурации.
1068
+ *
1069
+ * @example
1070
+ * ```ts
1071
+ * rateLimit: { bucketOverrides: { 'posts.create': { limit: 10 }, feed: { concurrency: 2 } } }
1072
+ * ```
1073
+ */
1074
+ bucketOverrides?: Record<string, RateLimitBucketOverride> | undefined;
1075
+ /**
1076
+ * Своё правило выбора бакета. `undefined` из функции отдаёт запрос встроенной карте.
1077
+ *
1078
+ * Возвращайте конечное множество имён: каждое заводит свою очередь.
1079
+ */
1080
+ bucket?: ((request: RateLimitBucketContext) => string | undefined) | undefined;
1081
+ /** Реакция на остаток, см. {@link RateLimitPacing}. По умолчанию `'react'`. */
1082
+ pacing?: RateLimitPacing | undefined;
978
1083
  /**
979
- * Тормозить ли очередь по заголовкам ответа. По умолчанию `true`.
1084
+ * Паузы перед повторами при ответе `429`, мс.
1085
+ * По умолчанию `[1000, 5000, 30000, 60000, 90000]`.
980
1086
  *
981
- * Выключите, если управляете темпом сами.
1087
+ * После последней ступени {@link ItdRateLimitError} пробрасывается вызывающему коду.
1088
+ * От `retry.attempts` не зависит: `retry: false` лестницу не отключает.
982
1089
  */
983
- respectHeaders?: boolean | undefined;
1090
+ retryDelays?: readonly number[] | undefined;
984
1091
  }
985
1092
  /** Данные о запросе, доступные хукам. */
986
1093
  interface RequestContext {
@@ -1081,22 +1188,6 @@ interface ItdClientOptions {
1081
1188
  * Работает, только когда в `auth` переданы email и пароль. По умолчанию `true`.
1082
1189
  */
1083
1190
  reloginOnRefreshFailure?: boolean | undefined;
1084
- /** Своя реализация `fetch`: для Deno, React Native, тестов или прокси. */
1085
- fetch?: typeof fetch | undefined;
1086
- /** Часы для тайм-аутов, повторов и очередей. Обычно подменяются только в тестах. */
1087
- clock?: ItdClock | undefined;
1088
- /** Таймаут запроса в мс. По умолчанию 30000 — столько же использует сайт итд.com. `0` снимает ограничение. */
1089
- timeout?: number | undefined;
1090
- /** Повторные попытки. `false` отключает их полностью. */
1091
- retry?: RetryOptions | false | undefined;
1092
- /** Ограничение нагрузки. `false` отключает очередь. */
1093
- rateLimit?: RateLimitOptions | false | undefined;
1094
- /** Перехватчики запросов. */
1095
- hooks?: ClientHooks | undefined;
1096
- /** Отладочный вывод. `true` — писать в `console`. */
1097
- logger?: Logger | boolean | undefined;
1098
- /** Заголовки, добавляемые ко всем запросам, — например `User-Agent` для бота. */
1099
- headers?: Record<string, string> | undefined;
1100
1191
  /**
1101
1192
  * Значение заголовка `X-Device-Id`, который уходит с каждым запросом.
1102
1193
  *
@@ -1105,6 +1196,28 @@ interface ItdClientOptions {
1105
1196
  * так что при постоянном хранилище он переживёт перезапуск процесса.
1106
1197
  */
1107
1198
  deviceId?: string | undefined;
1199
+ /** Таймаут запроса в мс. По умолчанию 30000 — столько же использует сайт итд.com. `0` снимает ограничение. */
1200
+ timeout?: number | undefined;
1201
+ /**
1202
+ * Сколько `close()` и `dispose()` ждут чужой код, мс. По умолчанию 10000.
1203
+ *
1204
+ * Ждут обработчиков realtime-потока и операций, вошедших в обёртки плагинов. По истечении
1205
+ * срока ресурсы всё равно освобождаются, а метод отклоняется `ItdStateError` с указанием
1206
+ * того, что удерживало остановку. `0` снимает ограничение.
1207
+ */
1208
+ shutdownTimeout?: number | undefined;
1209
+ /** Повторные попытки. `false` отключает их полностью. */
1210
+ retry?: RetryOptions | false | undefined;
1211
+ /** Ограничение нагрузки. `false` отключает очередь. */
1212
+ rateLimit?: RateLimitOptions | false | undefined;
1213
+ /** Своя реализация `fetch`: для Deno, React Native, тестов или прокси. */
1214
+ fetch?: typeof fetch | undefined;
1215
+ /** Часы для тайм-аутов, повторов и очередей. Обычно подменяются только в тестах. */
1216
+ clock?: ItdClock | undefined;
1217
+ /** Как обращаться с cookie. По умолчанию определяется по среде исполнения. */
1218
+ mode?: RuntimeMode | undefined;
1219
+ /** Заголовки, добавляемые ко всем запросам, — например `User-Agent` для бота. */
1220
+ headers?: Record<string, string> | undefined;
1108
1221
  /**
1109
1222
  * Значение заголовка `User-Agent`. `false` — не отправлять его вовсе.
1110
1223
  *
@@ -1113,8 +1226,10 @@ interface ItdClientOptions {
1113
1226
  * В браузере опция не действует — там заголовок менять запрещено.
1114
1227
  */
1115
1228
  userAgent?: string | false | undefined;
1116
- /** Как обращаться с cookie. По умолчанию определяется по среде исполнения. */
1117
- mode?: RuntimeMode | undefined;
1229
+ /** Перехватчики запросов. */
1230
+ hooks?: ClientHooks | undefined;
1231
+ /** Отладочный вывод. `true` — писать в `console`. */
1232
+ logger?: Logger | boolean | undefined;
1118
1233
  }
1119
1234
  /**
1120
1235
  * Namespaces расширений отдельной операции.
@@ -1140,6 +1255,17 @@ interface RequestOptions {
1140
1255
  * интеграциям и осознанному переопределению серверного контракта.
1141
1256
  */
1142
1257
  retrySafety?: RetrySafety | undefined;
1258
+ /**
1259
+ * Имя бакета, из которого списывается запрос.
1260
+ *
1261
+ * Встроенные resources берут его из каталога операций; низкоуровневый вызов без этой
1262
+ * опции попадает в `default`.
1263
+ *
1264
+ * Имя сверяется со встроенной картой — незнакомое отвергается {@link ItdConfigError}
1265
+ * до отправки, независимо от того, включена ли очередь. Своё правило `rateLimit.bucket`
1266
+ * заводит собственное пространство имён и проверку снимает.
1267
+ */
1268
+ rateLimitBucket?: string | undefined;
1143
1269
  /** Настройки подключённых operation extensions, сгруппированные по владельцу. */
1144
1270
  extensions?: RequestExtensions | undefined;
1145
1271
  }
@@ -1199,30 +1325,13 @@ interface OperationRequestOptions extends RawRequestOptions {
1199
1325
  //#endregion
1200
1326
  //#region src/core/version.d.ts
1201
1327
  /** Версия библиотеки. Попадает в `User-Agent`. */
1202
- declare const LIBRARY_VERSION = "0.5.0";
1328
+ declare const LIBRARY_VERSION = "0.7.0";
1203
1329
  //#endregion
1204
1330
  //#region src/core/config.d.ts
1205
1331
  /** Базовый URL API итд.com. Домен записан в punycode: `итд.com`. */
1206
1332
  declare const DEFAULT_BASE_URL = "https://xn--d1ah4a.com";
1207
- /** Базовый URL страницы статуса. Домен записан в punycode: `статус.итд.com`. */
1208
- declare const DEFAULT_STATUS_BASE_URL = "https://xn--80a7abcbg.xn--d1ah4a.com";
1209
1333
  /** Имя встроенного сервиса статуса. */
1210
1334
  declare const STATUS_SERVICE = "status";
1211
- /** Сервисы, зарегистрированные у любого клиента. */
1212
- declare const BUILT_IN_SERVICES: readonly ServiceDefinition[];
1213
- /** Таймаут запроса по умолчанию — 30 секунд. */
1214
- declare const DEFAULT_TIMEOUT = 30000;
1215
- /**
1216
- * `User-Agent` по умолчанию.
1217
- *
1218
- * Сайт стоит за DDoS-Guard, и запросы вовсе без `User-Agent` (так делает `fetch` в Node)
1219
- * имеют шанс не пройти фильтр. Префикс `Mozilla/5.0` — дань традиции таких фильтров,
1220
- * дальше идёт честное имя библиотеки: подделываться под браузер она не должна.
1221
- *
1222
- * В браузере заголовок не выставляется — `User-Agent` там запрещён к изменению, и среда
1223
- * молча его игнорирует.
1224
- */
1225
- declare const DEFAULT_USER_AGENT = "Mozilla/5.0 (compatible; itd-api/0.5.0; +https://github.com/KiowDev/itd-api)";
1226
1335
  /**
1227
1336
  * Срез конфигурации, нужный слою авторизации.
1228
1337
  *
@@ -1242,18 +1351,6 @@ interface AuthConfig {
1242
1351
  }
1243
1352
  //#endregion
1244
1353
  //#region src/core/cookies.d.ts
1245
- /** Имя cookie-флага «есть refresh-сессия». Ставится сайтом итд.com рядом с refresh-токеном. */
1246
- declare const AUTH_FLAG_COOKIE = "is_auth";
1247
- /**
1248
- * Имя cookie с refresh-токеном.
1249
- *
1250
- * `POST /api/v1/auth/refresh` читает токен **только отсюда** — тело запроса сервер игнорирует.
1251
- * Cookie помечена `HttpOnly`, поэтому в браузере её не прочитать и не выставить; вне браузера
1252
- * она проходит через jar, и туда же кладётся токен, переданный строкой.
1253
- */
1254
- declare const REFRESH_COOKIE = "refresh_token";
1255
- /** Путь, которым сервер ограничивает {@link REFRESH_COOKIE}. */
1256
- declare const REFRESH_COOKIE_PATH = "/api/v1/auth";
1257
1354
  /**
1258
1355
  * Минимальное хранилище cookie для сред без своего.
1259
1356
  *
@@ -1406,25 +1503,17 @@ type PipelineRequestInput = Omit<PipelineRequest, 'operationId'> & {
1406
1503
  type RequestHandler = (request: PipelineRequest) => Promise<unknown>;
1407
1504
  //#endregion
1408
1505
  //#region src/core/auth.d.ts
1409
- /** Пути эндпоинтов авторизации. */
1410
- declare const AUTH_PATHS: {
1411
- readonly signUp: "/api/v1/auth/sign-up";
1412
- readonly signIn: "/api/v1/auth/sign-in";
1413
- readonly verifyOtp: "/api/v1/auth/verify-otp";
1414
- readonly resendOtp: "/api/v1/auth/resend-otp";
1415
- readonly refresh: "/api/v1/auth/refresh";
1416
- readonly logout: "/api/v1/auth/logout";
1417
- readonly forgotPassword: "/api/v1/auth/forgot-password";
1418
- readonly resetPassword: "/api/v1/auth/reset-password";
1419
- readonly changePassword: "/api/v1/auth/change-password";
1420
- readonly sessions: "/api/v1/auth/sessions";
1421
- };
1422
1506
  /**
1423
1507
  * Публичный ключ Cloudflare Turnstile платформы итд.com.
1424
1508
  *
1425
1509
  * Нужен, чтобы отрисовать виджет капчи и получить токен для `signIn`, `signUp`
1426
1510
  * и `forgotPassword`.
1427
1511
  *
1512
+ * Ключ привязан к домену: на чужом origin Cloudflare отказывает виджету с кодом `110200`.
1513
+ * Поэтому отрисовать его может только код, выполняемый на самом итд.com. Остальным
1514
+ * подходит `@itd-api/turnstile`, готовый токен из другого источника или вовсе вход
1515
+ * без капчи — по сохранённой сессии либо по токенам, взятым в браузере.
1516
+ *
1428
1517
  * @example
1429
1518
  * ```ts
1430
1519
  * turnstile.render('#captcha', {
@@ -1434,8 +1523,6 @@ declare const AUTH_PATHS: {
1434
1523
  * ```
1435
1524
  */
1436
1525
  declare const TURNSTILE_SITE_KEY = "0x4AAAAAACHhxczw6fJGwPBg";
1437
- /** Заголовок с идентификатором устройства. Сервер связывает с ним запись в списке сессий. */
1438
- declare const DEVICE_ID_HEADER = "X-Device-Id";
1439
1526
  /** События слоя авторизации. */
1440
1527
  interface AuthEvents {
1441
1528
  /** Токен получен или обновлён. */
@@ -1726,6 +1813,22 @@ interface ClientPlugin {
1726
1813
  install(api: PluginApi): void | PluginTeardown;
1727
1814
  }
1728
1815
  //#endregion
1816
+ //#region src/core/rate-limit.d.ts
1817
+ /** Снимок одного бакета. */
1818
+ interface RateLimitBucketState {
1819
+ /** Origin, на котором ведётся счётчик. `undefined` — очередь без известного направления. */
1820
+ destination: string | undefined;
1821
+ bucket: string;
1822
+ /** Ёмкость из последнего ответа; `undefined`, пока ответов не было. */
1823
+ limit: number | undefined;
1824
+ /** Остаток из последнего ответа. */
1825
+ remaining: number | undefined;
1826
+ /** Запросов бакета прошло в общую очередь и ещё не завершилось. */
1827
+ active: number;
1828
+ /** Запросов бакета ждёт своей очереди — из-за паузы или предела одновременности. */
1829
+ pending: number;
1830
+ }
1831
+ //#endregion
1729
1832
  //#region src/models/users.d.ts
1730
1833
  /** Значок-«пин» в профиле — награда или отметка платформы. */
1731
1834
  interface Pin {
@@ -2006,21 +2109,22 @@ interface NotificationEvent {
2006
2109
  * ```
2007
2110
  */
2008
2111
  declare function normalizeNotification(input: unknown): Notification;
2112
+ //#endregion
2113
+ //#region src/realtime/transport.d.ts
2114
+ /** Запрос транспорта к конвейеру клиента. */
2115
+ interface RealtimeRequestInput {
2116
+ operationId: BuiltInOperationId;
2117
+ path: string;
2118
+ query?: QueryParams | undefined;
2119
+ signal: AbortSignal;
2120
+ }
2009
2121
  /**
2010
- * Разбирает событие `notification` из потока.
2011
- *
2012
- * Кроме самого уведомления событие несёт служебные поля уровня конверта: актуальный
2013
- * счётчик непрочитанных и признак звука.
2014
- */
2015
- declare function readNotificationEvent(data: unknown): NotificationEvent;
2016
- /**
2017
- * Разбирает событие `unread_count` из потока.
2122
+ * Порт к конвейеру клиента: очередь, авторизация, повторы, плагины и хуки.
2018
2123
  *
2019
- * Возвращает `undefined`, если сервер прислал событие без вложенного `payload`.
2124
+ * Ответ приходит уже разобранным и без обёртки `{ data: }`, а неудача типизированной
2125
+ * ошибкой библиотеки.
2020
2126
  */
2021
- declare function readUnreadCountEvent(data: unknown): number | undefined;
2022
- //#endregion
2023
- //#region src/realtime/transport.d.ts
2127
+ type RealtimeRequest = (input: RealtimeRequestInput) => Promise<unknown>;
2024
2128
  /** Событие, пришедшее по каналу реального времени. */
2025
2129
  interface TransportEvent {
2026
2130
  /** Имя события: `notification`, `unread_count` и другие. */
@@ -2036,6 +2140,12 @@ interface TransportContext {
2036
2140
  authorize: boolean;
2037
2141
  /** Реализация `fetch`. */
2038
2142
  fetch: typeof fetch;
2143
+ /**
2144
+ * Выполнение обычных HTTP-запросов транспорта через конвейер клиента.
2145
+ *
2146
+ * Есть только у потока, созданного клиентом: конвейер принадлежит ему.
2147
+ */
2148
+ request?: RealtimeRequest | undefined;
2039
2149
  /**
2040
2150
  * Общие заголовки клиента: `User-Agent`, `X-Device-Id`, заголовки конфигурации
2041
2151
  * и cookie для указанного адреса.
@@ -2175,21 +2285,6 @@ type RealtimeSequentializer<C extends RealtimeContextBase = RealtimeContext> = (
2175
2285
  declare function runRealtimeMiddleware<C extends RealtimeContextBase>(middleware: readonly RealtimeMiddleware<C>[], context: C, terminal: RealtimeNext): Promise<void>;
2176
2286
  //#endregion
2177
2287
  //#region src/realtime/reconnect.d.ts
2178
- /**
2179
- * Паузы перед попытками переподключения, мс.
2180
- *
2181
- * Значения совпадают с теми, что использует сайт итд.com, — поведение библиотеки
2182
- * не отличается от привычного пользователю.
2183
- */
2184
- declare const RECONNECT_BACKOFF: readonly number[];
2185
- /** Доля случайного разброса паузы. */
2186
- declare const RECONNECT_JITTER = 0.3;
2187
- /**
2188
- * Сколько раз пытаться переподключиться подряд.
2189
- *
2190
- * После исчерпания поток сообщает `giveup` и ждёт ручного `connect()`.
2191
- */
2192
- declare const MAX_RECONNECT_ATTEMPTS = 15;
2193
2288
  /** Настройки переподключения. */
2194
2289
  interface ReconnectOptions {
2195
2290
  /** Таблица пауз. Последнее значение действует для всех дальнейших попыток. */
@@ -2330,6 +2425,8 @@ interface RealtimeDeps {
2330
2425
  /** Разрешено ли транспорту передавать токен этому сервису. */
2331
2426
  authorize?: boolean | undefined;
2332
2427
  fetch: typeof fetch;
2428
+ /** Конвейер клиента — см. {@link TransportContext.request}. */
2429
+ request?: RealtimeRequest | undefined;
2333
2430
  clock?: ItdClock;
2334
2431
  /** Общие заголовки клиента для адреса — см. {@link TransportContext.baseHeaders}. */
2335
2432
  baseHeaders: (url: string) => Promise<Headers>;
@@ -3308,8 +3405,6 @@ interface UploadOptions {
3308
3405
  /** Размер очереди библиотеки при потоковой передаче. */
3309
3406
  streamBufferBytes?: number | undefined;
3310
3407
  }
3311
- /** Таймаут одной попытки загрузки файла — 5 минут. */
3312
- declare const DEFAULT_UPLOAD_TIMEOUT = 300000;
3313
3408
  /** Файлы и медиа. */
3314
3409
  declare class FilesResource extends BaseResource {
3315
3410
  #private;
@@ -4604,6 +4699,20 @@ declare class ItdClient {
4604
4699
  * @throws {ItdStateError} если клиент уже освобождён через {@link dispose}
4605
4700
  */
4606
4701
  request<T = unknown>(options: RawRequestOptions): Promise<T>;
4702
+ /**
4703
+ * Остаток серверных лимитов по бакетам, через которые уже проходили запросы.
4704
+ *
4705
+ * Значения берутся из последнего ответа каждого бакета и быстро устаревают: сервер
4706
+ * восстанавливает квоту линейно и границу окна не сообщает. Пустой массив при
4707
+ * `rateLimit: false`. {@link close} снимок сохраняет, {@link dispose} очищает.
4708
+ *
4709
+ * @example
4710
+ * ```ts
4711
+ * const posts = itd.rateLimitState().find((state) => state.bucket === 'posts.create');
4712
+ * if ((posts?.remaining ?? Number.POSITIVE_INFINITY) < 3) await sleep(60_000);
4713
+ * ```
4714
+ */
4715
+ rateLimitState(): RateLimitBucketState[];
4607
4716
  /**
4608
4717
  * Подключает плагин.
4609
4718
  *
@@ -4715,23 +4824,29 @@ declare class ItdClient {
4715
4824
  * Освобождает ресурсы клиента: закрывает все потоки уведомлений, отправляет открытые
4716
4825
  * накопители {@link telemetry}, затем останавливает очередь запросов.
4717
4826
  *
4718
- * Метод дожидается активных обработчиков потока. После вызова клиентом можно пользоваться
4719
- * снова; ранее созданный поток можно запустить повторным `connect()`.
4827
+ * Метод дожидается активных обработчиков потока, но не дольше `shutdownTimeout`. После
4828
+ * вызова клиентом можно пользоваться снова; ранее созданный поток можно запустить
4829
+ * повторным `connect()`.
4720
4830
  *
4721
4831
  * Общая очередь, полученная от {@link ItdAccounts}, не останавливается: её гасит сам
4722
4832
  * контейнер, когда закрывает все аккаунты разом.
4723
4833
  *
4724
4834
  * Терминальное освобождение — это {@link dispose}.
4835
+ *
4836
+ * @throws {ItdStateError} если обработчики потока не завершились за отведённый срок
4725
4837
  */
4726
4838
  close(): Promise<void>;
4727
4839
  /**
4728
- * Окончательно освобождает клиент: выполняет {@link close} и отключает все плагины.
4840
+ * Окончательно освобождает клиент: выполняет {@link close}, отменяет незавершённые
4841
+ * запросы и отключает все плагины.
4729
4842
  *
4730
4843
  * Терминальное состояние устанавливается сразу при первом вызове. После этого новые
4731
4844
  * запросы, подключение плагинов, регистрация сервисов и создание или повторный запуск
4732
4845
  * realtime-потоков завершаются с {@link ItdStateError}. Повторные вызовы возвращают
4733
4846
  * тот же результат очистки.
4734
4847
  *
4848
+ * Ожидание обработчиков потока и операций плагинов ограничено `shutdownTimeout`.
4849
+ *
4735
4850
  * @example
4736
4851
  * ```ts
4737
4852
  * await using itd = new ItdClient({ auth: token });
@@ -4801,16 +4916,14 @@ interface ItdAccountsOptions extends Omit<ItdClientOptions, 'auth' | 'storage' |
4801
4916
  /** Плагины, подключаемые каждому аккаунту, в том числе добавленному позже. */
4802
4917
  plugins?: readonly ClientPlugin[] | undefined;
4803
4918
  /**
4804
- * Как делить очередь запросов. По умолчанию `'account'` — своя у каждого.
4919
+ * Как делить очередь запросов. По умолчанию `'shared'` — одна на всех.
4805
4920
  *
4806
- * Лимиты итд.com считаются по аккаунту, а при работе через разные прокси общая очередь
4807
- * только мешает. Она нужна в другом случае: когда все аккаунты сидят на одном IP
4808
- * и упираются в ограничение по адресу, — тогда `'shared'` разводит их запросы во времени
4809
- * все разом, а не поаккаунтно.
4921
+ * Лимиты итд.com считаются по IP, поэтому аккаунты с одного адреса тратят общую квоту.
4922
+ * `'account'` даёт каждому свою очередь и нужен, когда у аккаунтов разные адреса
4923
+ * например, при своём прокси у каждого.
4810
4924
  *
4811
- * Настройки самой очереди берутся из общей опции `rateLimit`. Личный объект `rateLimit`
4812
- * в этом режиме запрещён, потому что не может изменить уже созданную очередь;
4813
- * `rateLimit: false` у отдельного аккаунта выводит его из неё.
4925
+ * В режиме `'shared'` настройки очереди берутся из общей опции `rateLimit`; аккаунту
4926
+ * разрешён только `rateLimit: false`, выводящий его из общей очереди.
4814
4927
  */
4815
4928
  rateLimitScope?: RateLimitScope | undefined;
4816
4929
  }
@@ -4818,8 +4931,9 @@ interface ItdAccountsOptions extends Omit<ItdClientOptions, 'auth' | 'storage' |
4818
4931
  * Настройки одного аккаунта. Общее мультихранилище задаёт контейнер, а аккаунт получает
4819
4932
  * свой срез автоматически; остальное — как у `ItdClient`.
4820
4933
  *
4821
- * При `rateLimitScope: 'shared'` объект `rateLimit` задаётся только контейнеру; аккаунту
4822
- * разрешено передать `false`, чтобы не ставить его запросы в общую очередь.
4934
+ * При `rateLimitScope: 'shared'` (умолчание) объект `rateLimit` задаётся только
4935
+ * контейнеру; аккаунту разрешено передать `false`, чтобы не ставить его запросы
4936
+ * в общую очередь.
4823
4937
  */
4824
4938
  type AddAccountOptions = Omit<ItdClientOptions, 'storage'>;
4825
4939
  /** Что можно уточнить при удалении аккаунта. */
@@ -5468,17 +5582,6 @@ declare function statusDays(service: ServiceStatus): (StatusDay | null)[];
5468
5582
  declare function formatNotificationText(notification: Notification): string;
5469
5583
  //#endregion
5470
5584
  //#region src/notifications/type-map.d.ts
5471
- /**
5472
- * Соответствие коротких имён типов уведомлений развёрнутым.
5473
- *
5474
- * Сервер — и в списке, и в потоке событий — присылает короткие имена: `like`, `comment`,
5475
- * `reply`, `repost`, `comment_like`. Развёрнутые (`post_reaction`, `post_comment`)
5476
- * встречаются в оформлении интерфейса, поэтому библиотека приводит типы к ним:
5477
- * они однозначно называют и объект, и действие.
5478
- *
5479
- * Пришедшее значение всегда остаётся в поле `rawType`.
5480
- */
5481
- declare const NOTIFICATION_TYPE_ALIASES: Readonly<Record<string, NotificationType>>;
5482
5585
  /**
5483
5586
  * Приводит имя типа к каноническому.
5484
5587
  *
@@ -5609,45 +5712,7 @@ declare class RealtimeComposer<C extends RealtimeContextBase = RealtimeContext>
5609
5712
  middleware(): RealtimeMiddleware<C>;
5610
5713
  }
5611
5714
  //#endregion
5612
- //#region src/realtime/poll.d.ts
5613
- /** Настройки опроса. */
5614
- interface PollTransportOptions {
5615
- /** Часы опроса. Обычно подменяются только в тестах. */
5616
- clock?: ItdClock;
5617
- /** Как часто опрашивать сервер, мс. По умолчанию 15 000. */
5618
- interval?: number;
5619
- /** Сколько уведомлений запрашивать за раз. По умолчанию 20. */
5620
- limit?: number;
5621
- }
5622
- //#endregion
5623
- //#region src/realtime/sse.d.ts
5624
- /** Путь потока уведомлений. */
5625
- declare const STREAM_PATH = "/api/notifications/stream";
5626
- /** Настройки SSE-транспорта. */
5627
- interface SseTransportOptions {
5628
- /** Часы потока. Обычно подменяются только в тестах. */
5629
- clock?: ItdClock;
5630
- /**
5631
- * Сколько миллисекунд ждать данных, прежде чем считать соединение мёртвым.
5632
- *
5633
- * Сервер не присылает keep-alive, а оборванное TCP-соединение может не закрыться
5634
- * само — без этой проверки поток «тихо умирает» и новых уведомлений не приходит.
5635
- * По умолчанию 90 000. `0` отключает проверку.
5636
- */
5637
- idleTimeout?: number;
5638
- /**
5639
- * Сколько миллисекунд ждать ответа на запрос потока, прежде чем оборвать попытку.
5640
- *
5641
- * Проверка молчания ({@link idleTimeout}) начинается только после получения тела ответа.
5642
- * Если `fetch` завис на установке соединения, без этого таймаута переподключение не
5643
- * запустится до системного сетевого таймаута. По умолчанию 20 000. `0` отключает проверку.
5644
- */
5645
- handshakeTimeout?: number;
5646
- }
5647
- //#endregion
5648
5715
  //#region src/realtime/websocket.d.ts
5649
- /** Стандартный путь WebSocket-подключения. */
5650
- declare const WEBSOCKET_PATH = "/api/ws";
5651
5716
  /** Дополнительные параметры конструктора, поддерживаемые Node-реализациями вроде `ws`. */
5652
5717
  interface WebSocketImplementationOptions {
5653
5718
  headers?: Record<string, string> | undefined;
@@ -5720,5 +5785,5 @@ interface RenderSpansOptions {
5720
5785
  */
5721
5786
  declare function renderSpans(content: string, spans?: readonly Span[] | null | undefined, options?: RenderSpansOptions): string;
5722
5787
  //#endregion
5723
- export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AUTH_FLAG_COOKIE, AUTH_PATHS, AccessType, type AccountEvents, type Actor, type AddAccountOptions, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthEvents, type AuthIdentity, type AuthInput, type AuthResource, type AuthState, type Author, type AutoSpansOptions, BUILT_IN_SERVICES, type BuilderInput, type BuiltInOperationId, type CaptchaCredentials, type ChangelogEntry, type Clan, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type Credentials, type CredentialsAuth, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_FILE_STREAM_BUFFER_BYTES, DEFAULT_STATUS_BASE_URL, DEFAULT_TIMEOUT, DEFAULT_UPLOAD_TIMEOUT, DEFAULT_URL_FILE_MAX_BYTES, DEFAULT_USER_AGENT, DEVICE_ID_HEADER, DetectedRuntime, type DwellEntry, type EnumerableKeyValueStore, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type ForgotPasswordInput, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdAccounts, type ItdAccountsOptions, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, ItdClient, type ItdClientOptions, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRealtime, ItdServerError, type ItdSession, ItdStateError, ItdTimeoutError, ItdValidationError, type KeyValueCodec, type KeyValueStore, type KeyValueStoreKeys, type KeyValueStoreResult, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, MAX_RECONNECT_ATTEMPTS, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, MemoryKeyValueStore, MemoryMultiTokenStorage, MemoryTokenStorage, type MultiTokenStorage, type MultiTokenStorageAdapterOptions, type MyProfile, NOTIFICATION_TYPE_ALIASES, type Notification, type NotificationEvent, type NotificationEventOfType, type NotificationListParams, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type PollTransportOptions, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, RECONNECT_BACKOFF, RECONNECT_JITTER, REFRESH_COOKIE, REFRESH_COOKIE_PATH, type RateLimitOptions, type RateLimitScope, type RawRequestOptions, RealtimeComposer, type RealtimeContext, type RealtimeContextBase, type RealtimeDeps, type RealtimeEngineEvents, type RealtimeErrorBoundary, type RealtimeErrorContext, type RealtimeEvents, type RealtimeFilter, type RealtimeHandler, type RealtimeMiddleware, type RealtimeMiddlewareGroup, type RealtimeMiddlewareLike, type RealtimeMiddlewareObj, type RealtimeNext, type RealtimeNotificationContext, type RealtimeNotificationFilter, type RealtimeNotificationSelector, type RealtimeNotificationUpdate, type RealtimeOptions, type RealtimePredicate, type RealtimeRouteSelector, type RealtimeRouteTable, RealtimeRouter, type RealtimeSequentializer, RealtimeStatus, type RealtimeTransport, RealtimeTransportKind, type RealtimeTypeGuard, type RealtimeUnknownUpdate, type RealtimeUnreadCountUpdate, type RealtimeUpdate, type RealtimeUpdateOfType, RealtimeUpdateOrigin, RealtimeUpdateType, type ReconnectOptions, type RecordKeyValueStoreSource, type RemoveAccountOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResetPasswordInput, type ResponseContext, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, STATUS_SERVICE, STREAM_PATH, type SearchResource, type SearchResult, type ServiceDefinition, ServiceRegistry, ServiceState, type ServiceStatus, type Session, type SignInResult, SignInStatus, type Span, SpanRenderFormat, SpanType, type SseTransportOptions, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, TURNSTILE_SITE_KEY, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type TokenStorage, type TokenStorageAdapterOptions, type TransportContext, type TransportEvent, UnauthorizedStreamError, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WEBSOCKET_PATH, WallAccess, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, autoSpans, canonicalNotificationType, comment, createAccounts, createClient, createKeyValueStore, createMultiTokenStorage, createRecordKeyValueStore, createTokenStorage, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isEnumerableKeyValueStore, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, readNotificationEvent, readUnreadCountEvent, renderSpans, report, resolveNotificationUrl, runRealtimeMiddleware, scopedTokenStorage, statusDays, systemClock, toDate, utcStampToIso, withCodec, withNamespace };
5788
+ export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, type AccountEvents, type Actor, type AddAccountOptions, type AllowedMimeType, type Announcement, type AnnouncementButton, type Attachment, AttachmentType, type AttemptContext, type AttemptExtensions, type AttemptInterceptor, type AttemptNext, type AudioMimeType, type AuthEvents, type AuthIdentity, type AuthInput, type AuthResource, type AuthState, type Author, type AutoSpansOptions, BUCKET_LIMITS, type BuilderInput, type BuiltInOperationId, type CaptchaCredentials, type ChangelogEntry, type Clan, type ClientHooks, type ClientPlugin, type Comment, type CommentBuilder, type CommentInput, type CommentReplyTo, CommentSort, type CommentsParams, type CommentsResource, type CreateCommentInput, type CreatePollInput, type CreatePostData, type CreatePostInput, type CreateReportInput, type Credentials, type CredentialsAuth, type CustomOperationId, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, type DwellEntry, type EnumerableKeyValueStore, type ErrorContextHook, type FeedParams, FeedTab, type FileContent, type FileContext, type FileInput, type FileStreamContent, type FileStreamOptions, FileTransferMode, type FilesResource, type FollowResult, type ForgotPasswordInput, type FromStreamOptions, type Hashtag, type HashtagPostsParams, type HashtagsResource, IMAGE_MIME_TYPES, type ImageMimeType, IncidentKind, type InteractionEntry, InteractionType, type IsoDate, ItdAbortError, ItdAccounts, type ItdAccountsOptions, ItdApiError, type ItdApiErrorInit, ItdApiErrorKind, ItdAuthError, type ItdBuilder, ItdClient, type ItdClientOptions, type ItdClock, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, type ItdFieldErrors, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdRealtime, ItdServerError, type ItdSession, ItdStateError, ItdTimeoutError, ItdValidationError, type KeyValueCodec, type KeyValueStore, type KeyValueStoreKeys, type KeyValueStoreResult, LIBRARY_VERSION, type LazyFile, type LikeResult, LikesVisibility, type Listener, type Logger, type Loose, type MarkupBuilder, type MarkupContent, type MarkupInput, type MarkupSpan, MemoryKeyValueStore, MemoryMultiTokenStorage, MemoryTokenStorage, type MultiTokenStorage, type MultiTokenStorageAdapterOptions, type MyProfile, type Notification, type NotificationEvent, type NotificationEventOfType, type NotificationListParams, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationsResource, OPERATIONS, type OperationDefinition, type OperationExtensions, type OperationId, type OperationMethod, type OperationRequestOptions, type OperationTransformer, type Page, type PageState, PaginationMode, type PaginationOptions, Paginator, type PaginatorOptions, type ParseMarkupOptions, type PaymentMethod, type PhotoOpenInput, type Pin, type PinPostResult, type PinsResult, type PlatformClientVersion, type PlatformResource, type PlatformStatus, type PlatformVersions, type PluginApi, type PluginTeardown, type Poll, type PollBuilder, type PollInput, type PollOption, type Portal, type Post, type PostBuilder, type PostInput, type PostStats, type PostUpdateInput, type PostsResource, type PrivacySettings, type Profile, type PublicProfile, type QueryParams, type QueryValue, type RateLimitBucket, type RateLimitBucketContext, type RateLimitBucketOverride, type RateLimitBucketState, type RateLimitOptions, RateLimitPacing, type RateLimitScope, type RawRequestOptions, RealtimeComposer, type RealtimeContext, type RealtimeContextBase, type RealtimeEngineEvents, type RealtimeErrorBoundary, type RealtimeErrorContext, type RealtimeEvents, type RealtimeFilter, type RealtimeHandler, type RealtimeMiddleware, type RealtimeMiddlewareGroup, type RealtimeMiddlewareLike, type RealtimeMiddlewareObj, type RealtimeNext, type RealtimeNotificationContext, type RealtimeNotificationFilter, type RealtimeNotificationSelector, type RealtimeNotificationUpdate, type RealtimeOptions, type RealtimePredicate, type RealtimeRequest, type RealtimeRequestInput, type RealtimeRouteSelector, type RealtimeRouteTable, RealtimeRouter, type RealtimeSequentializer, RealtimeStatus, type RealtimeTransport, RealtimeTransportKind, type RealtimeTypeGuard, type RealtimeUnknownUpdate, type RealtimeUnreadCountUpdate, type RealtimeUpdate, type RealtimeUpdateOfType, RealtimeUpdateOrigin, RealtimeUpdateType, type ReconnectOptions, type RecordKeyValueStoreSource, type RemoveAccountOptions, type RenderSpansOptions, type RepliesParams, type Report, type ReportBuilder, type ReportInput, ReportReason, ReportTargetType, type ReportsResource, type RequestContext, type RequestExtensions, type RequestOptions, type ResetPasswordInput, type ResponseContext, type RetryContext, type RetryDecisionContext, type RetryOptions, RetrySafety, RuntimeMode, STATUS_SERVICE, type SearchResource, type SearchResult, type ServiceDefinition, ServiceState, type ServiceStatus, type Session, type SignInResult, SignInStatus, type Span, SpanRenderFormat, SpanType, type StatusDay, type StatusIncidentLine, type StreamFile, type Subscription, type SubscriptionResource, type SubscriptionState, TURNSTILE_SITE_KEY, type TelemetryBatch, type TelemetryBatchOptions, type TelemetryClock, type TelemetryOptions, type TelemetryResource, type TextMarkup, type TokenStorage, type TokenStorageAdapterOptions, type TransportContext, type TransportEvent, UnauthorizedStreamError, type Unsubscribe, type UpdateNotificationSettingsInput, type UpdatePostInput, type UpdatePrivacyInput, type UpdateProfileInput, type UploadOptions, type UploadedFile, type UrlFile, type UrlFileOptions, type UserId, type UserListParams, type UserPostsParams, type UserRef, type UserSummary, type UsersResource, VIDEO_MIME_TYPES, type VerificationResource, type VerificationStatus, type VideoMimeType, type VideoProgressInput, ViewReason, ViewSource, type ViewTracker, type ViewTrackerInput, type ViewTrackerOptions, WallAccess, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, autoSpans, canonicalNotificationType, comment, createAccounts, createClient, createKeyValueStore, createMultiTokenStorage, createRecordKeyValueStore, createTokenStorage, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isEnumerableKeyValueStore, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, runRealtimeMiddleware, scopedTokenStorage, statusDays, systemClock, toDate, utcStampToIso, withCodec, withNamespace };
5724
5789
  //# sourceMappingURL=index.d.ts.map