@mtkruto/node 0.1.190 → 0.1.191

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.
Files changed (47) hide show
  1. package/esm/0_errors.d.ts +12 -0
  2. package/esm/0_errors.js +19 -0
  3. package/esm/client/0_client_abstract.js +3 -2
  4. package/esm/client/0_html.js +4 -3
  5. package/esm/client/0_markdown.js +6 -5
  6. package/esm/client/0_types.d.ts +0 -2
  7. package/esm/client/0_types.js +1 -2
  8. package/esm/client/0_utilities.js +2 -1
  9. package/esm/client/1_client_encrypted.js +1 -1
  10. package/esm/client/1_client_plain.js +3 -4
  11. package/esm/client/1_composer.js +3 -2
  12. package/esm/client/1_file_manager.js +4 -4
  13. package/esm/client/2_message_manager.js +41 -43
  14. package/esm/client/3_chat_list_manager.js +3 -2
  15. package/esm/client/3_story_manager.js +2 -1
  16. package/esm/client/4_client.d.ts +1 -1
  17. package/esm/client/4_client.js +13 -4
  18. package/esm/mod.d.ts +1 -0
  19. package/esm/mod.js +1 -0
  20. package/esm/types/0__file_id.js +2 -1
  21. package/esm/types/0_chat_photo.d.ts +1 -0
  22. package/esm/types/0_chat_photo.js +7 -4
  23. package/esm/types/5_callback_query.js +2 -1
  24. package/package.json +1 -1
  25. package/script/0_errors.d.ts +12 -0
  26. package/script/0_errors.js +27 -0
  27. package/script/client/0_client_abstract.js +3 -2
  28. package/script/client/0_html.js +4 -3
  29. package/script/client/0_markdown.js +6 -5
  30. package/script/client/0_types.d.ts +0 -2
  31. package/script/client/0_types.js +0 -4
  32. package/script/client/0_utilities.js +2 -1
  33. package/script/client/1_client_encrypted.js +2 -2
  34. package/script/client/1_client_plain.js +3 -4
  35. package/script/client/1_composer.js +3 -2
  36. package/script/client/1_file_manager.js +5 -5
  37. package/script/client/2_message_manager.js +41 -43
  38. package/script/client/3_chat_list_manager.js +3 -2
  39. package/script/client/3_story_manager.js +2 -1
  40. package/script/client/4_client.d.ts +1 -1
  41. package/script/client/4_client.js +13 -4
  42. package/script/mod.d.ts +1 -0
  43. package/script/mod.js +1 -0
  44. package/script/types/0__file_id.js +2 -1
  45. package/script/types/0_chat_photo.d.ts +1 -0
  46. package/script/types/0_chat_photo.js +7 -4
  47. package/script/types/5_callback_query.js +2 -1
@@ -0,0 +1,12 @@
1
+ export declare class MtkrutoError extends Error {
2
+ }
3
+ export declare class ConnectionError extends MtkrutoError {
4
+ }
5
+ export declare class AccessError extends MtkrutoError {
6
+ }
7
+ export declare class InputError extends MtkrutoError {
8
+ }
9
+ export declare class TransportError extends MtkrutoError {
10
+ readonly code: number;
11
+ constructor(code: number);
12
+ }
@@ -0,0 +1,19 @@
1
+ export class MtkrutoError extends Error {
2
+ }
3
+ export class ConnectionError extends MtkrutoError {
4
+ }
5
+ export class AccessError extends MtkrutoError {
6
+ }
7
+ export class InputError extends MtkrutoError {
8
+ }
9
+ export class TransportError extends MtkrutoError {
10
+ constructor(code) {
11
+ super(`Transport error: ${code}`);
12
+ Object.defineProperty(this, "code", {
13
+ enumerable: true,
14
+ configurable: true,
15
+ writable: true,
16
+ value: code
17
+ });
18
+ }
19
+ }
@@ -11,6 +11,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
11
11
  };
12
12
  var _ClientAbstract_dc;
13
13
  import { initTgCrypto } from "../0_deps.js";
14
+ import { ConnectionError } from "../0_errors.js";
14
15
  import { transportProviderWebSocket } from "../3_transport.js";
15
16
  import { INITIAL_DC } from "../4_constants.js";
16
17
  export class ClientAbstract {
@@ -55,7 +56,7 @@ export class ClientAbstract {
55
56
  }
56
57
  get dcId() {
57
58
  if (!this.transport) {
58
- throw new Error("Not connected");
59
+ throw new ConnectionError("Not connected.");
59
60
  }
60
61
  return this.transport.dcId;
61
62
  }
@@ -82,7 +83,7 @@ export class ClientAbstract {
82
83
  }
83
84
  async disconnect() {
84
85
  if (!this.transport) {
85
- throw new Error("Not connected");
86
+ throw new ConnectionError("Not connected.");
86
87
  }
87
88
  await this.transport.transport.deinitialize();
88
89
  await this.transport.connection.close();
@@ -1,4 +1,5 @@
1
1
  import { Parser } from "../0_deps.js";
2
+ import { InputError } from "../0_errors.js";
2
3
  export function parseHtml(html) {
3
4
  html = html.trim();
4
5
  let text = "";
@@ -26,7 +27,7 @@ export function parseHtml(html) {
26
27
  case "a": {
27
28
  const url = attribs.href;
28
29
  if (!url) {
29
- throw new Error("Missing attribute href");
30
+ throw new InputError("Missing attribute: href");
30
31
  }
31
32
  stack.push({ type: "textLink", offset: text.length, length: 0, url });
32
33
  break;
@@ -41,7 +42,7 @@ export function parseHtml(html) {
41
42
  break;
42
43
  case "span":
43
44
  if (attribs.class != "tg-spoiler") {
44
- throw new Error("The class attribute must be tg-spoiler");
45
+ throw new InputError('The class attribute must be "tg-spoiler."');
45
46
  }
46
47
  // falls through
47
48
  case "tg-spoiler":
@@ -49,7 +50,7 @@ export function parseHtml(html) {
49
50
  break;
50
51
  case "tg-emoji":
51
52
  if (!attribs["emoji-id"]) {
52
- throw new Error("Missing attribute emoji-id");
53
+ throw new InputError("Missing attribute: emoji-id");
53
54
  }
54
55
  stack.push({ type: "spoiler", offset: text.length, length: 0 });
55
56
  break;
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { UNREACHABLE } from "../1_utilities.js";
6
6
  import { sortMessageEntities } from "../3_types.js";
7
+ import { InputError } from "../0_errors.js";
7
8
  const enc = new TextEncoder();
8
9
  const dec = new TextDecoder();
9
10
  export const CODEPOINTS = {
@@ -165,7 +166,7 @@ export function parseMarkdown(text_) {
165
166
  type = "spoiler";
166
167
  }
167
168
  else {
168
- throw new Error(`Character '${String.fromCharCode(c)}' is reserved and must be escaped with the preceding '\\'`);
169
+ throw new InputError(`The character "${String.fromCharCode(c)}" is reserved and must be escaped with a preceding backslash.`);
169
170
  }
170
171
  break;
171
172
  case CODEPOINTS["["]:
@@ -250,7 +251,7 @@ export function parseMarkdown(text_) {
250
251
  }
251
252
  url = Uint8Array.from(url_);
252
253
  if (text[i] !== CODEPOINTS[")"]) {
253
- throw new Error("Can't find end of a URL at byte offset " + urlBeginPos);
254
+ throw new Error(`Can't find the end of the URL that starts at offset ${urlBeginPos}.`);
254
255
  }
255
256
  }
256
257
  userId = getLinkUserId(dec.decode(url));
@@ -267,7 +268,7 @@ export function parseMarkdown(text_) {
267
268
  }
268
269
  case "customEmoji": {
269
270
  if (text[i + 1] !== CODEPOINTS["("]) {
270
- throw new Error("Custom emoji entity must contain a tg://emoji URL");
271
+ throw new InputError("Custom emoji entities must contain a tg://emoji URL.");
271
272
  }
272
273
  i += 2;
273
274
  const url_ = [];
@@ -282,7 +283,7 @@ export function parseMarkdown(text_) {
282
283
  }
283
284
  const url = Uint8Array.from(url_);
284
285
  if (text[i] !== CODEPOINTS[")"]) {
285
- throw new Error("Can't find end of a custom emoji URL at byte offset " + urlBeginPos);
286
+ throw new InputError(`Can't find the end of the custom emoji URL that starts at offset ${urlBeginPos}.`);
286
287
  }
287
288
  customEmojiId = getLinkCustomEmojiId(dec.decode(url));
288
289
  break;
@@ -314,7 +315,7 @@ export function parseMarkdown(text_) {
314
315
  }
315
316
  if (nestedEntities.length !== 0) {
316
317
  const last = nestedEntities[nestedEntities.length - 1];
317
- throw new Error(`Can't find end of ${last.type} entity at byte offset ${last.entityByteOffset}`);
318
+ throw new InputError(`Can't find the end of the ${last.type} entity that starts at offset ${last.entityByteOffset}.`);
318
319
  }
319
320
  entities = sortMessageEntities(entities);
320
321
  return [dec.decode(text.slice(0, resultSize)), entities];
@@ -41,6 +41,4 @@ export interface C {
41
41
  cdn: boolean;
42
42
  dropPendingUpdates?: boolean;
43
43
  }
44
- export declare class ConnectionError extends Error {
45
- }
46
44
  export {};
@@ -1,2 +1 @@
1
- export class ConnectionError extends Error {
2
- }
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  import * as dntShim from "../_dnt.shims.js";
2
2
  import { path } from "../0_deps.js";
3
+ import { InputError } from "../0_errors.js";
3
4
  import { UNREACHABLE } from "../1_utilities.js";
4
5
  import { types } from "../2_tl.js";
5
6
  export const resolve = () => Promise.resolve();
@@ -80,7 +81,7 @@ function isDigit(string) {
80
81
  const c = string.charCodeAt(0);
81
82
  return "0".charCodeAt(0) <= c && c <= "9".charCodeAt(0);
82
83
  }
83
- const errInvalidUsername = (u) => new Error("Invalid username: " + u);
84
+ const errInvalidUsername = (u) => new InputError(`Invalid username: ${u}`);
84
85
  function validateUsername(string, ignoreAt = false) {
85
86
  string = string.trim();
86
87
  if (ignoreAt && string.startsWith("@")) {
@@ -11,12 +11,12 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _ClientEncrypted_instances, _ClientEncrypted_authKey, _ClientEncrypted_authKeyId, _ClientEncrypted_sessionId, _ClientEncrypted_state, _ClientEncrypted_toAcknowledge, _ClientEncrypted_recentAcks, _ClientEncrypted_promises, _ClientEncrypted_L, _ClientEncrypted_LreceiveLoop, _ClientEncrypted_Linvoke, _ClientEncrypted_nextMessageId, _ClientEncrypted_nextSeqNo, _ClientEncrypted_sendMessage, _ClientEncrypted_receiveLoop;
13
13
  import { gunzip } from "../0_deps.js";
14
+ import { ConnectionError } from "../0_errors.js";
14
15
  import { bigIntFromBuffer, CacheMap, drop, getLogger, getRandomBigInt, sha1, UNREACHABLE } from "../1_utilities.js";
15
16
  import { Message_, MessageContainer, name, RPCResult, TLError, TLReader, types } from "../2_tl.js";
16
17
  import { upgradeInstance } from "../4_errors.js";
17
18
  import { ClientAbstract } from "./0_client_abstract.js";
18
19
  import { decryptMessage, encryptMessage, getMessageId } from "./0_message.js";
19
- import { ConnectionError } from "./0_types.js";
20
20
  // global ClientEncrypted ID counter for logs
21
21
  let id = 0;
22
22
  /**
@@ -11,6 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _ClientPlain_publicKeys, _ClientPlain_lastMsgId;
13
13
  import { assertEquals, assertInstanceOf, factorize, ige256Decrypt, ige256Encrypt } from "../0_deps.js";
14
+ import { ConnectionError, TransportError } from "../0_errors.js";
14
15
  import { bigIntFromBuffer, bufferFromBigInt, concat, getLogger, getRandomBigInt, modExp, rsaPad, sha1, UNREACHABLE } from "../1_utilities.js";
15
16
  import { functions, serialize, TLReader, types } from "../2_tl.js";
16
17
  import { PUBLIC_KEYS } from "../4_constants.js";
@@ -30,7 +31,7 @@ export class ClientPlain extends ClientAbstract {
30
31
  }
31
32
  async invoke(function_) {
32
33
  if (!this.transport) {
33
- throw new Error("Not connected");
34
+ throw new ConnectionError("Not connected.");
34
35
  }
35
36
  const msgId = __classPrivateFieldSet(this, _ClientPlain_lastMsgId, getMessageId(__classPrivateFieldGet(this, _ClientPlain_lastMsgId, "f")), "f");
36
37
  const payload = packUnencryptedMessage(function_[serialize](), msgId);
@@ -41,9 +42,7 @@ export class ClientPlain extends ClientAbstract {
41
42
  L.inBin(payload);
42
43
  if (buffer.length == 4) {
43
44
  const int = bigIntFromBuffer(buffer, true, true);
44
- if (int == -404n) {
45
- throw new Error("-404");
46
- }
45
+ throw new TransportError(Number(int));
47
46
  }
48
47
  const { message } = unpackUnencryptedMessage(buffer);
49
48
  const reader = new TLReader(message);
@@ -10,6 +10,7 @@ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (
10
10
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
11
11
  };
12
12
  var _Composer_handle, _Composer_prefixes;
13
+ import { InputError } from "../0_errors.js";
13
14
  import { match } from "./0_filters.js";
14
15
  export function flatten(mw) {
15
16
  return typeof mw === "function" ? mw : (ctx, next) => mw.middleware()(ctx, next);
@@ -34,7 +35,7 @@ export function skip(_ctx, next) {
34
35
  export class Composer {
35
36
  set prefixes(value) {
36
37
  if (__classPrivateFieldGet(this, _Composer_prefixes, "f") !== undefined) {
37
- throw new Error("Prefixes already set");
38
+ throw new InputError("Prefixes already set");
38
39
  }
39
40
  __classPrivateFieldSet(this, _Composer_prefixes, value, "f");
40
41
  }
@@ -84,7 +85,7 @@ export class Composer {
84
85
  continue;
85
86
  }
86
87
  if (left.startsWith(right) || right.startsWith(left)) {
87
- throw new Error("Intersecting prefixes");
88
+ throw new InputError("Intersecting prefixes");
88
89
  }
89
90
  }
90
91
  }
@@ -10,12 +10,12 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _FileManager_instances, _FileManager_c, _FileManager_Lupload, _FileManager_downloadInner;
13
+ import { ConnectionError, InputError } from "../0_errors.js";
13
14
  import { drop, getLogger, getRandomId, mod, UNREACHABLE } from "../1_utilities.js";
14
15
  import { as, types } from "../2_tl.js";
15
16
  import { constructSticker, deserializeFileId, FileType, PhotoSourceType, serializeFileId, toUniqueFileId } from "../3_types.js";
16
17
  import { STICKER_SET_NAME_TTL } from "../4_constants.js";
17
18
  import { FloodWait } from "../4_errors.js";
18
- import { ConnectionError } from "./0_types.js";
19
19
  export class FileManager {
20
20
  constructor(c) {
21
21
  _FileManager_instances.add(this);
@@ -29,7 +29,7 @@ export class FileManager {
29
29
  const isBig = contents.length > 1048576; // 10 MB
30
30
  const chunkSize = params?.chunkSize ?? 512 * 1024;
31
31
  if (mod(chunkSize, 1024) != 0) {
32
- throw new Error("chunkSize must be divisible by 1024");
32
+ throw new InputError("chunkSize must be divisible by 1024.");
33
33
  }
34
34
  const signal = params?.signal;
35
35
  __classPrivateFieldGet(this, _FileManager_Lupload, "f").debug("uploading " + (isBig ? "big " : "") + "file of size " + contents.length + " with chunk size of " + chunkSize);
@@ -170,7 +170,7 @@ export class FileManager {
170
170
  async getCustomEmojiStickers(id) {
171
171
  id = Array.isArray(id) ? id : [id];
172
172
  if (!id.length) {
173
- throw new Error("No custom emoji ID provided");
173
+ return [];
174
174
  }
175
175
  const stickers = new Array();
176
176
  let shouldFetch = false;
@@ -228,7 +228,7 @@ _FileManager_c = new WeakMap(), _FileManager_Lupload = new WeakMap(), _FileManag
228
228
  }
229
229
  const chunkSize = params?.chunkSize ?? 1024 * 1024;
230
230
  if (mod(chunkSize, 1024) != 0) {
231
- throw new Error("chunkSize must be divisible by 1024");
231
+ throw new InputError("chunkSize must be divisible by 1024.");
232
232
  }
233
233
  const { api, connect, disconnect } = __classPrivateFieldGet(this, _FileManager_c, "f").apiFactory(dcId);
234
234
  await connect();
@@ -11,6 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _MessageManager_instances, _MessageManager_c, _MessageManager_LresolveFileId, _MessageManager_updatesToMessages, _MessageManager_constructReplyMarkup, _MessageManager_resolveSendAs, _MessageManager_constructReplyTo, _MessageManager_sendDocumentInner, _MessageManager_sendMedia, _MessageManager_sendReaction, _MessageManager_toggleJoinRequests;
13
13
  import { contentType } from "../0_deps.js";
14
+ import { InputError } from "../0_errors.js";
14
15
  import { getLogger, getRandomId, toUnixTimestamp, UNREACHABLE } from "../1_utilities.js";
15
16
  import { as, getChannelChatId, peerToChatId, types } from "../2_tl.js";
16
17
  import { constructChatMemberUpdated, constructInviteLink, deserializeFileId } from "../3_types.js";
@@ -20,7 +21,7 @@ import { parseHtml } from "./0_html.js";
20
21
  import { parseMarkdown } from "./0_markdown.js";
21
22
  import { getFileContents, isHttpUrl } from "./0_utilities.js";
22
23
  const FALLBACK_MIME_TYPE = "application/octet-stream";
23
- const STICKER_MIME_TYPES = ["image/webp", "video/webp", "application/x-tgsticker"];
24
+ const STICKER_MIME_TYPES = ["image/webp", "video/webm", "application/x-tgsticker"];
24
25
  export class MessageManager {
25
26
  constructor(c) {
26
27
  _MessageManager_instances.add(this);
@@ -573,12 +574,9 @@ export class MessageManager {
573
574
  }
574
575
  }
575
576
  async deleteChatMemberMessages(chatId, memberId) {
576
- const channel = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
577
- if (!(channel instanceof types.InputPeerChannel)) {
578
- throw new Error("Invalid chat ID");
579
- }
577
+ const channel = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputChannel(chatId);
580
578
  const participant = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(memberId);
581
- await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.deleteParticipantHistory({ channel: new types.InputChannel(channel), participant });
579
+ await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.deleteParticipantHistory({ channel, participant });
582
580
  }
583
581
  async pinMessage(chatId, messageId, params) {
584
582
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.updatePinnedMessage({
@@ -738,7 +736,7 @@ export class MessageManager {
738
736
  action_ = new types.SendMessageUploadRoundAction({ progress: 0 });
739
737
  break;
740
738
  default:
741
- throw new Error("Invalid chat action: " + action);
739
+ throw new InputError(`Invalid chat action: ${action}`);
742
740
  }
743
741
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.setTyping({ peer: await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId), action: action_, top_msg_id: params?.messageThreadId });
744
742
  }
@@ -772,7 +770,7 @@ export class MessageManager {
772
770
  async banChatMember(chatId, memberId, params) {
773
771
  const chat = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
774
772
  if (!(chat instanceof types.InputPeerChannel) && !(chat instanceof types.InputPeerChat)) {
775
- throw new Error("Invalid chat ID");
773
+ throw new InputError("Expected a channel, supergroup, or group ID.");
776
774
  }
777
775
  const member = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(memberId);
778
776
  if (chat instanceof types.InputPeerChannel) {
@@ -802,7 +800,7 @@ export class MessageManager {
802
800
  }
803
801
  else if (chat instanceof types.InputPeerChat) {
804
802
  if (!(member instanceof types.InputPeerUser)) {
805
- throw new Error("Invalid user ID");
803
+ throw new InputError(`Invalid user ID: ${memberId}`);
806
804
  }
807
805
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.deleteChatUser({
808
806
  chat_id: chat.chat_id,
@@ -812,25 +810,19 @@ export class MessageManager {
812
810
  }
813
811
  }
814
812
  async unbanChatMember(chatId, memberId) {
815
- const chat = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
816
- if (!(chat instanceof types.InputPeerChannel)) {
817
- throw new Error("Invalid chat ID");
818
- }
813
+ const channel = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputChannel(chatId);
819
814
  const member = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(memberId);
820
815
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.editBanned({
821
- channel: new types.InputChannel(chat),
816
+ channel,
822
817
  participant: member,
823
818
  banned_rights: new types.ChatBannedRights({ until_date: 0 }),
824
819
  });
825
820
  }
826
821
  async setChatMemberRights(chatId, memberId, params) {
827
- const chat = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
828
- if (!(chat instanceof types.InputPeerChannel)) {
829
- throw new Error("Invalid chat ID");
830
- }
822
+ const channel = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputChannel(chatId);
831
823
  const member = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(memberId);
832
824
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.editBanned({
833
- channel: new types.InputChannel(chat),
825
+ channel,
834
826
  participant: member,
835
827
  banned_rights: chatMemberRightsToTlObject(params?.rights, params?.untilDate),
836
828
  });
@@ -909,7 +901,7 @@ export class MessageManager {
909
901
  }
910
902
  async createInviteLink(chatId, params) {
911
903
  if (params?.requireApproval && params?.limit) {
912
- throw new Error("createInviteLink: requireApproval cannot be true while limit is specified");
904
+ throw new InputError("requireApproval cannot be true while limit is specified.");
913
905
  }
914
906
  const result = await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.exportChatInvite({
915
907
  peer: await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId),
@@ -936,7 +928,7 @@ export class MessageManager {
936
928
  await __classPrivateFieldGet(this, _MessageManager_c, "f").storage.assertUser("joinChat");
937
929
  const peer = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
938
930
  if (peer instanceof types.InputPeerUser) {
939
- throw new Error("joinChat: cannot join private chats");
931
+ throw new InputError("Cannot join private chats.");
940
932
  }
941
933
  else if (peer instanceof types.InputPeerChannel) {
942
934
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.joinChannel({ channel: new types.InputChannel(peer) });
@@ -951,7 +943,7 @@ export class MessageManager {
951
943
  async leaveChat(chatId) {
952
944
  const peer = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId);
953
945
  if (peer instanceof types.InputPeerUser) {
954
- throw new Error("leaveChat: cannot leave private chats");
946
+ throw new InputError("Cannot leave private chats.");
955
947
  }
956
948
  else if (peer instanceof types.InputPeerChannel) {
957
949
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.channels.leaveChannel({ channel: new types.InputChannel(peer) });
@@ -967,7 +959,7 @@ export class MessageManager {
967
959
  await __classPrivateFieldGet(this, _MessageManager_c, "f").storage.assertUser("blockUser");
968
960
  const id = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(userId);
969
961
  if (!(id instanceof types.User)) {
970
- throw new Error("blockUser: only users can be blocked or unblocked");
962
+ throw new InputError("Only users can be blocked or unblocked.");
971
963
  }
972
964
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.contacts.block({ id });
973
965
  }
@@ -975,7 +967,7 @@ export class MessageManager {
975
967
  await __classPrivateFieldGet(this, _MessageManager_c, "f").storage.assertUser("unblockUser");
976
968
  const id = await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(userId);
977
969
  if (!(id instanceof types.User)) {
978
- throw new Error("unblockUser: only users can be blocked or unblocked");
970
+ throw new InputError("Only users can be blocked or unblocked.");
979
971
  }
980
972
  await __classPrivateFieldGet(this, _MessageManager_c, "f").api.contacts.unblock({ id });
981
973
  }
@@ -995,7 +987,7 @@ export class MessageManager {
995
987
  return await constructChatMember(participant, __classPrivateFieldGet(this, _MessageManager_c, "f").getEntity);
996
988
  }
997
989
  else {
998
- throw new Error("Invalid chat ID");
990
+ throw new InputError("Expected a channel, supergroup, or group ID. Got a user ID instead.");
999
991
  }
1000
992
  }
1001
993
  async setChatStickerSet(chatId, setName) {
@@ -1008,24 +1000,30 @@ export class MessageManager {
1008
1000
  }
1009
1001
  async stopPoll(chatId, messageId, params) {
1010
1002
  const message = await this.getMessage(chatId, messageId);
1011
- if (message && "poll" in message && !message.poll.isClosed) {
1012
- const result = await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.editMessage({
1013
- peer: await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId),
1014
- id: messageId,
1015
- media: new types.InputMediaPoll({
1016
- poll: new types.Poll({
1017
- id: BigInt(message.poll.id),
1018
- closed: true,
1019
- question: "",
1020
- answers: [],
1021
- }),
1022
- }),
1023
- reply_markup: await __classPrivateFieldGet(this, _MessageManager_instances, "m", _MessageManager_constructReplyMarkup).call(this, params),
1024
- });
1025
- const message_ = await __classPrivateFieldGet(this, _MessageManager_instances, "m", _MessageManager_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
1026
- return assertMessageType(message_, "poll").poll;
1003
+ if (!message) {
1004
+ throw new InputError("Message not found.");
1027
1005
  }
1028
- UNREACHABLE();
1006
+ if (!("poll" in message)) {
1007
+ throw new InputError("Message is not a poll.");
1008
+ }
1009
+ if (message.poll.isClosed) {
1010
+ throw new InputError("Poll is already stopped.");
1011
+ }
1012
+ const result = await __classPrivateFieldGet(this, _MessageManager_c, "f").api.messages.editMessage({
1013
+ peer: await __classPrivateFieldGet(this, _MessageManager_c, "f").getInputPeer(chatId),
1014
+ id: messageId,
1015
+ media: new types.InputMediaPoll({
1016
+ poll: new types.Poll({
1017
+ id: BigInt(message.poll.id),
1018
+ closed: true,
1019
+ question: "",
1020
+ answers: [],
1021
+ }),
1022
+ }),
1023
+ reply_markup: await __classPrivateFieldGet(this, _MessageManager_instances, "m", _MessageManager_constructReplyMarkup).call(this, params),
1024
+ });
1025
+ const message_ = await __classPrivateFieldGet(this, _MessageManager_instances, "m", _MessageManager_updatesToMessages).call(this, chatId, result).then((v) => v[0]);
1026
+ return assertMessageType(message_, "poll").poll;
1029
1027
  }
1030
1028
  async editMessageLiveLocation(chatId, messageId, latitude, longitude, params) {
1031
1029
  const message = await this.getMessage(chatId, messageId);
@@ -1120,7 +1118,7 @@ _MessageManager_c = new WeakMap(), _MessageManager_LresolveFileId = new WeakMap(
1120
1118
  if (media == null) {
1121
1119
  if (typeof document === "string" && isHttpUrl(document)) {
1122
1120
  if (!urlSupported) {
1123
- throw new Error("URL not supported");
1121
+ throw new InputError("URL not supported.");
1124
1122
  }
1125
1123
  media = new types.InputMediaDocumentExternal({ url: document, spoiler });
1126
1124
  }
@@ -10,6 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _ChatListManager_instances, _ChatListManager_c, _ChatListManager_LgetChats, _ChatListManager_sendChatUpdate, _ChatListManager_chats, _ChatListManager_archivedChats, _ChatListManager_chatsLoadedFromStorage, _ChatListManager_tryGetChatId, _ChatListManager_getChatAnywhere, _ChatListManager_getChatList, _ChatListManager_loadChatsFromStorage, _ChatListManager_getLoadedChats, _ChatListManager_pinnedChats, _ChatListManager_pinnedArchiveChats, _ChatListManager_storageHadPinnedChats, _ChatListManager_pinnedChatsLoaded, _ChatListManager_loadPinnedChats, _ChatListManager_fetchPinnedChats, _ChatListManager_getPinnedChats, _ChatListManager_updateOrAddChat, _ChatListManager_removeChat, _ChatListManager_handleUpdateFolderPeers, _ChatListManager_handleUpdatePinnedDialogs, _ChatListManager_handleUpdateChannel, _ChatListManager_handleUpdateChat, _ChatListManager_handleUpdateUser, _ChatListManager_fetchChats;
13
+ import { InputError } from "../0_errors.js";
13
14
  import { getLogger, toUnixTimestamp, UNREACHABLE } from "../1_utilities.js";
14
15
  import { as, peerToChatId, types } from "../2_tl.js";
15
16
  import { constructChat, constructChat2, constructChat3, constructChat4, getChatOrder } from "../3_types.js";
@@ -98,7 +99,7 @@ export class ChatListManager {
98
99
  await __classPrivateFieldGet(this, _ChatListManager_instances, "m", _ChatListManager_loadChatsFromStorage).call(this);
99
100
  }
100
101
  if (after && !__classPrivateFieldGet(this, _ChatListManager_chats, "f").get(after.id)) {
101
- throw new Error("Invalid after");
102
+ throw new InputError("Invalid after");
102
103
  }
103
104
  if (limit <= 0 || limit > 100) {
104
105
  limit = 100;
@@ -258,7 +259,7 @@ _ChatListManager_c = new WeakMap(), _ChatListManager_LgetChats = new WeakMap(),
258
259
  case 1:
259
260
  return __classPrivateFieldGet(this, _ChatListManager_archivedChats, "f");
260
261
  default:
261
- throw new Error("Invalid chat list: " + listId);
262
+ throw new Error(`Invalid chat list: ${listId}`);
262
263
  }
263
264
  }, _ChatListManager_loadChatsFromStorage = async function _ChatListManager_loadChatsFromStorage() {
264
265
  const chats = await __classPrivateFieldGet(this, _ChatListManager_c, "f").storage.getChats(0);
@@ -11,6 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _StoryManager_instances, _StoryManager_c, _StoryManager_updatesToStory, _StoryManager_togglePinned;
13
13
  import { contentType } from "../0_deps.js";
14
+ import { InputError } from "../0_errors.js";
14
15
  import { getRandomId, UNREACHABLE } from "../1_utilities.js";
15
16
  import { as, inputPeerToPeer, peerToChatId, types } from "../2_tl.js";
16
17
  import { constructStory, FileType, storyInteractiveAreaToTlObject, storyPrivacyToTlObject } from "../3_types.js";
@@ -35,7 +36,7 @@ export class StoryManager {
35
36
  }
36
37
  if (media == null) {
37
38
  if (typeof source === "string" && isHttpUrl(source)) {
38
- throw new Error("URL not supported");
39
+ throw new InputError("URL not supported.");
39
40
  }
40
41
  else {
41
42
  const [contents, fileName_] = await getFileContents(source);
@@ -229,7 +229,7 @@ export declare class Client<C extends Context = Context> extends Composer<C> {
229
229
  * Before establishing the connection, the session is saved.
230
230
  */
231
231
  connect(): Promise<void>;
232
- reconnect(dc: DC): Promise<void>;
232
+ reconnect(dc?: DC): Promise<void>;
233
233
  [handleMigrationError](err: Migrate): Promise<void>;
234
234
  disconnect(): Promise<void>;
235
235
  /**
@@ -10,6 +10,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
12
  var _Client_instances, _Client_client, _Client_guaranteeUpdateDelivery, _Client_updateManager, _Client_networkStatisticsManager, _Client_botInfoManager, _Client_fileManager, _Client_reactionManager, _Client_messageManager, _Client_storyManager, _Client_callbackQueryManager, _Client_inlineQueryManager, _Client_chatListManager, _Client_accountManager, _Client_parseMode, _Client_publicKeys, _Client_ignoreOutgoing, _Client_storeMessages, _Client_Lauthorize, _Client_LpingLoop, _Client_LhandleMigrationError, _Client_L$initConncetion, _Client_namespaceProxies, _Client_getApiId, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_stateChangeHandler, _Client_storageInited, _Client_initStorage, _Client_connectionInited, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_getSelfId, _Client_pingLoopStarted, _Client_pingLoopAbortController, _Client_pingInterval, _Client_lastUpdates, _Client_startPingLoop, _Client_pingLoop, _Client_invoke, _Client_handleInvokeError, _Client_getUserAccessHash, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_handleCtxUpdate, _Client_queueHandleCtxUpdate, _Client_handleUpdate, _Client_lastGetMe, _Client_getMe;
13
+ import { AccessError, InputError } from "../0_errors.js";
13
14
  import { cleanObject, drop, getLogger, getRandomId, mustPrompt, mustPromptOneOf, UNREACHABLE, ZERO_CHANNEL_ID } from "../1_utilities.js";
14
15
  import { as, chatIdToPeerId, functions, getChatIdPeerType, name, peerToChatId, types } from "../2_tl.js";
15
16
  import { StorageMemory } from "../3_storage.js";
@@ -664,6 +665,7 @@ export class Client extends Composer {
664
665
  try {
665
666
  const exportedAuth = await this.api.auth.exportAuthorization({ dc_id: dcId });
666
667
  await client.authorize(exportedAuth);
668
+ // throw 1;
667
669
  return true;
668
670
  }
669
671
  catch (err) {
@@ -806,7 +808,11 @@ export class Client extends Composer {
806
808
  await Promise.all([this.storage.setAuthKey(__classPrivateFieldGet(this, _Client_client, "f").authKey), this.storage.setDc(__classPrivateFieldGet(this, _Client_client, "f").dc), this.storage.setServerSalt(__classPrivateFieldGet(this, _Client_client, "f").serverSalt)]);
807
809
  }
808
810
  async reconnect(dc) {
809
- await __classPrivateFieldGet(this, _Client_client, "f").reconnect(dc);
811
+ await this.disconnect();
812
+ if (dc) {
813
+ await this.setDc(dc);
814
+ }
815
+ await this.connect();
810
816
  }
811
817
  async [(_Client_client = new WeakMap(), _Client_guaranteeUpdateDelivery = new WeakMap(), _Client_updateManager = new WeakMap(), _Client_networkStatisticsManager = new WeakMap(), _Client_botInfoManager = new WeakMap(), _Client_fileManager = new WeakMap(), _Client_reactionManager = new WeakMap(), _Client_messageManager = new WeakMap(), _Client_storyManager = new WeakMap(), _Client_callbackQueryManager = new WeakMap(), _Client_inlineQueryManager = new WeakMap(), _Client_chatListManager = new WeakMap(), _Client_accountManager = new WeakMap(), _Client_parseMode = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_ignoreOutgoing = new WeakMap(), _Client_storeMessages = new WeakMap(), _Client_Lauthorize = new WeakMap(), _Client_LpingLoop = new WeakMap(), _Client_LhandleMigrationError = new WeakMap(), _Client_L$initConncetion = new WeakMap(), _Client_namespaceProxies = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_stateChangeHandler = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_pingLoopAbortController = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_lastUpdates = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_lastGetMe = new WeakMap(), _Client_instances = new WeakSet(), _Client_getApiId = async function _Client_getApiId() {
812
818
  const apiId = this.apiId || await this.storage.getApiId();
@@ -1050,6 +1056,9 @@ export class Client extends Composer {
1050
1056
  inputPeer.access_hash = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getUserAccessHash).call(this, inputPeer.user_id);
1051
1057
  }
1052
1058
  }
1059
+ else {
1060
+ throw new AccessError(`Cannot access the chat ${id} because there is no access hash for it.`);
1061
+ }
1053
1062
  return inputPeer;
1054
1063
  }
1055
1064
  /**
@@ -1060,7 +1069,7 @@ export class Client extends Composer {
1060
1069
  async getInputChannel(id) {
1061
1070
  const inputPeer = await this.getInputPeer(id);
1062
1071
  if (!(inputPeer instanceof types.InputPeerChannel)) {
1063
- UNREACHABLE();
1072
+ throw new TypeError(`The chat ${id} is not a channel neither a supergroup.`);
1064
1073
  }
1065
1074
  return new types.InputChannel(inputPeer);
1066
1075
  }
@@ -1072,7 +1081,7 @@ export class Client extends Composer {
1072
1081
  async getInputUser(id) {
1073
1082
  const inputPeer = await this.getInputPeer(id);
1074
1083
  if (!(inputPeer instanceof types.InputPeerUser)) {
1075
- UNREACHABLE();
1084
+ throw new TypeError(`The chat ${id} is not a private chat.`);
1076
1085
  }
1077
1086
  return new types.InputUser(inputPeer);
1078
1087
  }
@@ -1227,7 +1236,7 @@ export class Client extends Composer {
1227
1236
  return new types.InputPeerChannel({ channel_id: chatIdToPeerId(id), access_hash: accessHash ?? 0n });
1228
1237
  }
1229
1238
  else {
1230
- throw new Error("ID format unknown or not implemented");
1239
+ throw new InputError("The ID is of an format unknown.");
1231
1240
  }
1232
1241
  }, getEntity)](peer) {
1233
1242
  const id = peerToChatId(peer);
package/esm/mod.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./0_errors.js";
1
2
  export { getColorFromPeerId, getColorName, getRandomId, setLogVerbosity } from "./1_utilities.js";
2
3
  export { checkPassword } from "./client/0_password.js";
3
4
  export * from "./2_connection.js";
package/esm/mod.js CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./0_errors.js";
1
2
  export { getColorFromPeerId, getColorName, getRandomId, setLogVerbosity } from "./1_utilities.js";
2
3
  export { checkPassword } from "./client/0_password.js";
3
4
  export * from "./2_connection.js";
@@ -1,3 +1,4 @@
1
+ import { InputError } from "../0_errors.js";
1
2
  import { base64DecodeUrlSafe, base64EncodeUrlSafe, rleDecode, rleEncode, UNREACHABLE } from "../1_utilities.js";
2
3
  import { TLReader, TLWriter } from "../2_tl.js";
3
4
  const NEXT_VERSION = 53;
@@ -215,7 +216,7 @@ function hasFileReference(fileType) {
215
216
  export function deserializeFileId(fileId) {
216
217
  const reader = new TLReader(rleDecode(base64DecodeUrlSafe(fileId)));
217
218
  if (reader.buffer[reader.buffer.length - 1] != PERSISTENT_ID_VERSION) {
218
- throw new Error("Unsupported version");
219
+ throw new InputError("Unsupported file ID format");
219
220
  }
220
221
  const originalType = reader.readInt32();
221
222
  const type = ((originalType & ~WEB_LOCATION_FLAG) & ~FILE_REFERENCE_FLAG);