@mtkruto/node 0.1.112 → 0.1.113

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.
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_errorHandler, _Client_publicKeys, _Client_autoStart, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingLoop, _Client_lastOutgoing, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
12
+ var _Client_instances, _a, _Client_auth, _Client_sessionId, _Client_state, _Client_promises, _Client_toAcknowledge, _Client_updateState, _Client_publicKeys, _Client_autoStart, _Client_constructContext, _Client_propagateConnectionState, _Client_lastPropagatedConnectionState, _Client_storageInited, _Client_setAuth, _Client_authKeyWasCreated, _Client_connectMutex, _Client_assertUser, _Client_assertBot, _Client_fetchState, _Client_connectionInited, _Client_initConnection, _Client_lastPropagatedAuthorizationState, _Client_propagateAuthorizationState, _Client_selfId, _Client_getSelfId, _Client_receiveLoop, _Client_pingInterval, _Client_pingLoop, _Client_pingLoopStarted, _Client_autoStarted, _Client_lastMsgId, _Client_invoke, _Client_handleInvokeError, _Client_processChats, _Client_processUsers, _Client_handleUpdateQueue, _Client_processUpdatesQueue, _Client_checkChannelGap, _Client_processUpdates, _Client_setUpdateStateDate, _Client_getLocalState, _Client_recoverUpdateGap, _Client_recoverChannelUpdateGap, _Client_getChannelAccessHash, _Client_getInputPeerInner, _Client_updatesToMessages, _Client_resolveSendAs, _Client_parseText, _Client_getMessagesInner, _Client_downloadInner, _Client_handleUpdate, _Client_usernameResolver, _Client_constructReplyMarkup, _Client_assertMsgHas, _Client_handle, _Client_setMyInfo, _Client_getMyInfo;
13
13
  import { debug, gunzip, Mutex } from "../0_deps.js";
14
14
  import { bigIntFromBuffer, drop, getRandomBigInt, getRandomId, mod, mustPrompt, mustPromptOneOf, Queue, sha1, UNREACHABLE } from "../1_utilities.js";
15
15
  import { as, functions, getChannelChatId, Message_, MessageContainer, peerToChatId, RPCResult, TLError, TLReader, types } from "../2_tl.js";
@@ -23,7 +23,7 @@ import { checkPassword } from "./0_password.js";
23
23
  import { isChannelPtsUpdate, isPtsUpdate, resolve } from "./0_utilities.js";
24
24
  import { ClientAbstract } from "./1_client_abstract.js";
25
25
  import { ClientPlain } from "./2_client_plain.js";
26
- import { skip } from "./3_types.js";
26
+ import { Composer, concat, flatten, skip } from "./4_composer.js";
27
27
  const d = debug("Client");
28
28
  const dGap = debug("Client/recoverUpdateGap");
29
29
  const dGapC = debug("Client/recoverChannelUpdateGap");
@@ -34,6 +34,9 @@ const getEntity = Symbol();
34
34
  const getStickerSetName = Symbol();
35
35
  export const handleMigrationError = Symbol();
36
36
  const getMessageWithReply = Symbol();
37
+ export function skipInvoke() {
38
+ return (_ctx, next) => next();
39
+ }
37
40
  export const restartAuth = Symbol();
38
41
  export class ConnectionError extends Error {
39
42
  }
@@ -66,7 +69,6 @@ export class Client extends ClientAbstract {
66
69
  _Client_promises.set(this, new Map());
67
70
  _Client_toAcknowledge.set(this, new Set());
68
71
  _Client_updateState.set(this, void 0);
69
- _Client_errorHandler.set(this, void 0);
70
72
  Object.defineProperty(this, "storage", {
71
73
  enumerable: true,
72
74
  configurable: true,
@@ -117,17 +119,81 @@ export class Client extends ClientAbstract {
117
119
  });
118
120
  _Client_publicKeys.set(this, void 0);
119
121
  _Client_autoStart.set(this, void 0);
122
+ _Client_constructContext.set(this, (update) => {
123
+ const msg = update.message ?? update.editedMessage ?? update.callbackQuery?.message;
124
+ const mustGetMsg = () => {
125
+ if (msg !== undefined) {
126
+ return msg;
127
+ }
128
+ else {
129
+ UNREACHABLE();
130
+ }
131
+ };
132
+ const chat = msg?.chat;
133
+ const from = update.callbackQuery?.from ?? update.inlineQuery?.from ?? update.message?.from ?? update.editedMessage?.from;
134
+ const senderChat = msg?.senderChat;
135
+ return {
136
+ ...update,
137
+ client: this,
138
+ msg,
139
+ chat,
140
+ from,
141
+ senderChat,
142
+ reply: (text, params) => {
143
+ const effectiveMessage = mustGetMsg();
144
+ const shouldQuote = params?.quote === undefined ? effectiveMessage.chat.type != "private" : params.quote;
145
+ return this.sendMessage(effectiveMessage.chat.id, text, { ...params, replyToMessageId: shouldQuote ? effectiveMessage.id : undefined });
146
+ },
147
+ replyPoll: (question, options, params) => {
148
+ const effectiveMessage = mustGetMsg();
149
+ return this.sendPoll(effectiveMessage.chat.id, question, options, params);
150
+ },
151
+ answerCallbackQuery: (params) => {
152
+ const { callbackQuery } = update;
153
+ if (callbackQuery === undefined) {
154
+ UNREACHABLE();
155
+ }
156
+ return this.answerCallbackQuery(callbackQuery.id, params);
157
+ },
158
+ answerInlineQuery: (results, params) => {
159
+ const { inlineQuery } = update;
160
+ if (inlineQuery == undefined) {
161
+ UNREACHABLE();
162
+ }
163
+ return this.answerInlineQuery(inlineQuery.id, results, params);
164
+ },
165
+ sendChatAction: (chatAction, params) => {
166
+ const effectiveMessage = mustGetMsg();
167
+ return this.sendChatAction(effectiveMessage.chat.id, chatAction, params);
168
+ },
169
+ editMessageText: (messageId, text, params) => {
170
+ const effectiveMessage = mustGetMsg();
171
+ return this.editMessageText(effectiveMessage.chat.id, messageId, text, params);
172
+ },
173
+ getMessage: (messageId) => {
174
+ const effectiveMessage = mustGetMsg();
175
+ return this.getMessage(effectiveMessage.chat.id, messageId);
176
+ },
177
+ getMessages: (messageIds) => {
178
+ const effectiveMessage = mustGetMsg();
179
+ return this.getMessages(effectiveMessage.chat.id, messageIds);
180
+ },
181
+ get toJSON() {
182
+ return () => update;
183
+ },
184
+ };
185
+ });
120
186
  _Client_lastPropagatedConnectionState.set(this, null);
121
187
  Object.defineProperty(this, "stateChangeHandler", {
122
188
  enumerable: true,
123
189
  configurable: true,
124
190
  writable: true,
125
191
  value: ((connected) => {
126
- __classPrivateFieldGet(this, _Client_connectMutex, "f").acquire().then(async (release) => {
192
+ __classPrivateFieldGet(this, _Client_connectMutex, "f").acquire().then((release) => {
127
193
  try {
128
194
  const connectionState = connected ? "ready" : "notConnected";
129
195
  if (this.connected == connected && __classPrivateFieldGet(this, _Client_lastPropagatedConnectionState, "f") != connectionState) {
130
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).call(this, connectionState);
196
+ __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).call(this, connectionState);
131
197
  __classPrivateFieldSet(this, _Client_lastPropagatedConnectionState, connectionState, "f");
132
198
  }
133
199
  }
@@ -143,16 +209,43 @@ export class Client extends ClientAbstract {
143
209
  _Client_connectionInited.set(this, false);
144
210
  _Client_lastPropagatedAuthorizationState.set(this, null);
145
211
  _Client_selfId.set(this, null);
146
- _Client_lastOutgoing.set(this, null);
212
+ _Client_pingInterval.set(this, 60 * 1000); // 60 seconds
147
213
  _Client_pingLoopStarted.set(this, false);
148
214
  _Client_autoStarted.set(this, false);
149
215
  _Client_lastMsgId.set(this, 0n);
216
+ _Client_handleInvokeError.set(this, skipInvoke());
217
+ /**
218
+ * Invokes a function waiting and returning its reply if the second parameter is not `true`. Requires the client
219
+ * to be connected.
220
+ *
221
+ * @param function_ The function to invoke.
222
+ */
223
+ Object.defineProperty(this, "invoke", {
224
+ enumerable: true,
225
+ configurable: true,
226
+ writable: true,
227
+ value: Object.assign(__classPrivateFieldGet(this, _Client_instances, "m", _Client_invoke), {
228
+ use: (handler) => {
229
+ const handle = __classPrivateFieldGet(this, _Client_handleInvokeError, "f");
230
+ __classPrivateFieldSet(this, _Client_handleInvokeError, async (ctx, next) => {
231
+ let result = null;
232
+ return await handle(ctx, async () => {
233
+ if (result != null)
234
+ return result;
235
+ result = await handler(ctx, next);
236
+ return result;
237
+ });
238
+ }, "f");
239
+ },
240
+ })
241
+ });
150
242
  _Client_handleUpdateQueue.set(this, new Queue("handleUpdate"));
151
243
  _Client_processUpdatesQueue.set(this, new Queue("processUpdates"));
152
244
  _Client_usernameResolver.set(this, async (v) => {
153
245
  const inputPeer = await this.getInputPeer(v).then((v) => v[as](types.InputPeerUser));
154
246
  return new types.InputUser({ userId: inputPeer.userId, accessHash: inputPeer.accessHash });
155
247
  });
248
+ //#region Composer
156
249
  _Client_handle.set(this, skip);
157
250
  this.storage = storage ?? new StorageMemory();
158
251
  this.parseMode = params?.parseMode ?? null;
@@ -164,7 +257,41 @@ export class Client extends ClientAbstract {
164
257
  this.systemVersion = params?.systemVersion ?? SYSTEM_VERSION;
165
258
  __classPrivateFieldSet(this, _Client_publicKeys, params?.publicKeys, "f");
166
259
  __classPrivateFieldSet(this, _Client_autoStart, params?.autoStart ?? true, "f");
167
- __classPrivateFieldSet(this, _Client_errorHandler, params?.errorHandler, "f");
260
+ if (params?.defaultHandlers ?? true) {
261
+ this.on("connectionState", ({ connectionState }, next) => {
262
+ drop((async () => {
263
+ if (connectionState == "notConnected") {
264
+ let delay = 5;
265
+ while (!this.connected) {
266
+ d("reconnecting");
267
+ try {
268
+ await this.connect();
269
+ d("reconnected");
270
+ break;
271
+ }
272
+ catch (err) {
273
+ d("failed to reconnect, retrying in %d: %o", delay, err);
274
+ }
275
+ await new Promise((r) => setTimeout(r, delay * 1000));
276
+ if (delay < 15) {
277
+ delay += 5;
278
+ }
279
+ }
280
+ }
281
+ })());
282
+ return next();
283
+ });
284
+ this.invoke.use(async ({ error }, next) => {
285
+ if (error instanceof FloodWait && error.seconds <= 10) {
286
+ d("sleeping for %d because of: %o", error.seconds, error);
287
+ await new Promise((r) => setTimeout(r, 1000 * error.seconds));
288
+ return true;
289
+ }
290
+ else {
291
+ return next();
292
+ }
293
+ });
294
+ }
168
295
  }
169
296
  /**
170
297
  * Sets the DC and resets the auth key stored in the session provider
@@ -231,14 +358,17 @@ export class Client extends ClientAbstract {
231
358
  }
232
359
  d("encrypted client connected");
233
360
  drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_receiveLoop).call(this));
361
+ if (__classPrivateFieldGet(this, _Client_pingLoopStarted, "f")) {
362
+ drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_pingLoop).call(this));
363
+ }
234
364
  }
235
365
  finally {
236
366
  release();
237
367
  }
238
368
  }
239
- async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_errorHandler = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_lastOutgoing = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
369
+ async [(_Client_auth = new WeakMap(), _Client_sessionId = new WeakMap(), _Client_state = new WeakMap(), _Client_promises = new WeakMap(), _Client_toAcknowledge = new WeakMap(), _Client_updateState = new WeakMap(), _Client_publicKeys = new WeakMap(), _Client_autoStart = new WeakMap(), _Client_constructContext = new WeakMap(), _Client_lastPropagatedConnectionState = new WeakMap(), _Client_storageInited = new WeakMap(), _Client_authKeyWasCreated = new WeakMap(), _Client_connectMutex = new WeakMap(), _Client_connectionInited = new WeakMap(), _Client_lastPropagatedAuthorizationState = new WeakMap(), _Client_selfId = new WeakMap(), _Client_pingInterval = new WeakMap(), _Client_pingLoopStarted = new WeakMap(), _Client_autoStarted = new WeakMap(), _Client_lastMsgId = new WeakMap(), _Client_handleInvokeError = new WeakMap(), _Client_handleUpdateQueue = new WeakMap(), _Client_processUpdatesQueue = new WeakMap(), _Client_usernameResolver = new WeakMap(), _Client_handle = new WeakMap(), _Client_instances = new WeakSet(), _Client_propagateConnectionState = function _Client_propagateConnectionState(connectionState) {
240
370
  __classPrivateFieldGet(this, _Client_handleUpdateQueue, "f").add(async () => {
241
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { connectionState }, resolve);
371
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { connectionState }), resolve);
242
372
  });
243
373
  }, _Client_setAuth = async function _Client_setAuth(key) {
244
374
  const hash = await sha1(key);
@@ -468,70 +598,6 @@ export class Client extends ClientAbstract {
468
598
  }
469
599
  await this.authorize(params);
470
600
  }
471
- async invoke(function_, noWait) {
472
- if (!__classPrivateFieldGet(this, _Client_auth, "f") || !this.transport) {
473
- if (__classPrivateFieldGet(this, _Client_autoStart, "f") && !__classPrivateFieldGet(this, _Client_autoStarted, "f")) {
474
- await this.start();
475
- }
476
- else {
477
- throw new ConnectionError("Not connected");
478
- }
479
- }
480
- if (!__classPrivateFieldGet(this, _Client_auth, "f") || !this.transport) {
481
- UNREACHABLE();
482
- }
483
- let n = 1;
484
- while (true) {
485
- try {
486
- let seqNo = __classPrivateFieldGet(this, _Client_state, "f").seqNo * 2;
487
- if (!(function_ instanceof functions.Ping) && !(function_ instanceof types.MsgsAck)) {
488
- seqNo++;
489
- __classPrivateFieldGet(this, _Client_state, "f").seqNo++;
490
- }
491
- const messageId = __classPrivateFieldSet(this, _Client_lastMsgId, getMessageId(__classPrivateFieldGet(this, _Client_lastMsgId, "f")), "f");
492
- const message = new Message_(messageId, seqNo, function_);
493
- await this.transport.transport.send(await encryptMessage(message, __classPrivateFieldGet(this, _Client_auth, "f").key, __classPrivateFieldGet(this, _Client_auth, "f").id, __classPrivateFieldGet(this, _Client_state, "f").salt, __classPrivateFieldGet(this, _Client_sessionId, "f")));
494
- __classPrivateFieldSet(this, _Client_lastOutgoing, new Date(), "f");
495
- d("invoked %s", function_.constructor.name);
496
- if (noWait) {
497
- return;
498
- }
499
- let result;
500
- try {
501
- result = await new Promise((resolve, reject) => {
502
- __classPrivateFieldGet(this, _Client_promises, "f").set(message.id, { resolve, reject });
503
- });
504
- }
505
- catch (err) {
506
- if (err instanceof AuthKeyUnregistered) {
507
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, false);
508
- }
509
- throw err;
510
- }
511
- if (result instanceof types.BadServerSalt) {
512
- return await this.invoke(function_);
513
- }
514
- else {
515
- if (!__classPrivateFieldGet(this, _Client_pingLoopStarted, "f")) {
516
- drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_pingLoop).call(this));
517
- __classPrivateFieldSet(this, _Client_pingLoopStarted, true, "f");
518
- }
519
- return result;
520
- }
521
- }
522
- catch (err) {
523
- if (__classPrivateFieldGet(this, _Client_errorHandler, "f") === undefined) {
524
- throw err;
525
- }
526
- if (__classPrivateFieldGet(this, _Client_errorHandler, "f") !== undefined && await __classPrivateFieldGet(this, _Client_errorHandler, "f").call(this, err, function_, n++)) {
527
- continue;
528
- }
529
- else {
530
- throw err;
531
- }
532
- }
533
- }
534
- }
535
601
  /**
536
602
  * Alias for `invoke` with its second parameter being `true`.
537
603
  */
@@ -586,7 +652,7 @@ export class Client extends ClientAbstract {
586
652
  }
587
653
  }, _Client_propagateAuthorizationState = async function _Client_propagateAuthorizationState(authorized) {
588
654
  if (__classPrivateFieldGet(this, _Client_lastPropagatedAuthorizationState, "f") != authorized) {
589
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { authorizationState: { authorized } }, resolve);
655
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { authorizationState: { authorized } }), resolve);
590
656
  __classPrivateFieldSet(this, _Client_lastPropagatedAuthorizationState, authorized, "f");
591
657
  }
592
658
  }, _Client_getSelfId = async function _Client_getSelfId() {
@@ -706,17 +772,81 @@ export class Client extends ClientAbstract {
706
772
  }
707
773
  }, _Client_pingLoop = async function _Client_pingLoop() {
708
774
  while (this.connected) {
709
- await new Promise((r) => setTimeout(r, 60 * 1000));
710
- if (!__classPrivateFieldGet(this, _Client_lastOutgoing, "f") || (Date.now() - __classPrivateFieldGet(this, _Client_lastOutgoing, "f").getTime() < 60 * 1000)) {
711
- continue;
712
- }
775
+ await new Promise((r) => setTimeout(r, __classPrivateFieldGet(this, _Client_pingInterval, "f")));
713
776
  try {
714
- await this.invoke(new functions.Ping({ pingId: getRandomBigInt(8, true, false) }));
777
+ await this.invoke(new functions.PingDelayDisconnect({ pingId: getRandomBigInt(8, true, false), disconnectDelay: __classPrivateFieldGet(this, _Client_pingInterval, "f") + 15 }));
715
778
  }
716
779
  catch (err) {
717
780
  d("ping loop error: %o", err);
718
781
  }
719
782
  }
783
+ }, _Client_invoke = async function _Client_invoke(function_, noWait) {
784
+ if (!__classPrivateFieldGet(this, _Client_auth, "f") || !this.transport) {
785
+ if (__classPrivateFieldGet(this, _Client_autoStart, "f") && !__classPrivateFieldGet(this, _Client_autoStarted, "f")) {
786
+ await this.start();
787
+ }
788
+ else {
789
+ throw new ConnectionError("Not connected");
790
+ }
791
+ }
792
+ if (!__classPrivateFieldGet(this, _Client_auth, "f") || !this.transport) {
793
+ UNREACHABLE();
794
+ }
795
+ let n = 1;
796
+ while (true) {
797
+ try {
798
+ let seqNo = __classPrivateFieldGet(this, _Client_state, "f").seqNo * 2;
799
+ if (!(function_ instanceof functions.Ping) && !(function_ instanceof types.MsgsAck)) {
800
+ seqNo++;
801
+ __classPrivateFieldGet(this, _Client_state, "f").seqNo++;
802
+ }
803
+ const messageId = __classPrivateFieldSet(this, _Client_lastMsgId, getMessageId(__classPrivateFieldGet(this, _Client_lastMsgId, "f")), "f");
804
+ const message = new Message_(messageId, seqNo, function_);
805
+ await this.transport.transport.send(await encryptMessage(message, __classPrivateFieldGet(this, _Client_auth, "f").key, __classPrivateFieldGet(this, _Client_auth, "f").id, __classPrivateFieldGet(this, _Client_state, "f").salt, __classPrivateFieldGet(this, _Client_sessionId, "f")));
806
+ d("invoked %s", function_.constructor.name);
807
+ if (noWait) {
808
+ __classPrivateFieldGet(this, _Client_promises, "f").set(message.id, {
809
+ resolve: (result) => {
810
+ if (result instanceof types.BadServerSalt) {
811
+ drop(this.invoke(function_, true));
812
+ }
813
+ },
814
+ reject: () => { },
815
+ });
816
+ return;
817
+ }
818
+ let result;
819
+ try {
820
+ result = await new Promise((resolve, reject) => {
821
+ __classPrivateFieldGet(this, _Client_promises, "f").set(message.id, { resolve, reject });
822
+ });
823
+ }
824
+ catch (err) {
825
+ if (err instanceof AuthKeyUnregistered) {
826
+ await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateAuthorizationState).call(this, false);
827
+ }
828
+ throw err;
829
+ }
830
+ if (result instanceof types.BadServerSalt) {
831
+ return await this.invoke(function_);
832
+ }
833
+ else {
834
+ if (!__classPrivateFieldGet(this, _Client_pingLoopStarted, "f")) {
835
+ drop(__classPrivateFieldGet(this, _Client_instances, "m", _Client_pingLoop).call(this));
836
+ __classPrivateFieldSet(this, _Client_pingLoopStarted, true, "f");
837
+ }
838
+ return result;
839
+ }
840
+ }
841
+ catch (err) {
842
+ if (await __classPrivateFieldGet(this, _Client_handleInvokeError, "f").call(this, Object.freeze({ client: this, error: err, function: function_, n: n++ }), () => Promise.resolve(false))) {
843
+ continue;
844
+ }
845
+ else {
846
+ throw err;
847
+ }
848
+ }
849
+ }
720
850
  }, _Client_processChats = async function _Client_processChats(chats) {
721
851
  for (const chat of chats) {
722
852
  if (chat instanceof types.Channel && chat.accessHash) {
@@ -908,7 +1038,7 @@ export class Client extends ClientAbstract {
908
1038
  return localState;
909
1039
  }, _Client_recoverUpdateGap = async function _Client_recoverUpdateGap(source) {
910
1040
  dGap("recovering from update gap [%s]", source);
911
- await __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).call(this, "updating");
1041
+ __classPrivateFieldGet(this, _Client_instances, "m", _Client_propagateConnectionState).call(this, "updating");
912
1042
  try {
913
1043
  let state = await __classPrivateFieldGet(this, _Client_instances, "m", _Client_getLocalState).call(this);
914
1044
  while (true) {
@@ -1685,20 +1815,15 @@ export class Client extends ClientAbstract {
1685
1815
  nextOffset: params?.nextOffset,
1686
1816
  }));
1687
1817
  }
1688
- use(handler) {
1689
- const handle = __classPrivateFieldGet(this, _Client_handle, "f");
1690
- __classPrivateFieldSet(this, _Client_handle, async (upd, next) => {
1691
- let called = false;
1692
- await handle(upd, async () => {
1693
- if (called)
1694
- return;
1695
- called = true;
1696
- await handler(upd, next);
1697
- });
1698
- }, "f");
1818
+ use(...middleware) {
1819
+ const composer = new Composer(...middleware);
1820
+ __classPrivateFieldSet(this, _Client_handle, concat(__classPrivateFieldGet(this, _Client_handle, "f"), flatten(composer)), "f");
1821
+ return composer;
1699
1822
  }
1700
- branch(predicate, trueHandler, falseHandler) {
1701
- this.use(async (upd, next) => {
1823
+ branch(predicate, trueHandler_, falseHandler_) {
1824
+ const trueHandler = flatten(trueHandler_);
1825
+ const falseHandler = flatten(falseHandler_);
1826
+ return this.use(async (upd, next) => {
1702
1827
  if (await predicate(upd)) {
1703
1828
  await trueHandler(upd, next);
1704
1829
  }
@@ -1707,19 +1832,19 @@ export class Client extends ClientAbstract {
1707
1832
  }
1708
1833
  });
1709
1834
  }
1710
- filter(predicate, handler) {
1711
- this.branch(predicate, handler, skip);
1835
+ filter(predicate, ...middleware) {
1836
+ return this.branch(predicate, middleware.length == 0 ? skip : middleware.map(flatten).reduce(concat), skip);
1712
1837
  }
1713
- on(filter, handler) {
1838
+ on(filter, ...middleawre) {
1714
1839
  const type = typeof filter === "string" ? filter : filter[0];
1715
1840
  const keys = Array.isArray(filter) ? filter.slice(1) : [];
1716
- this.filter((update) => {
1717
- if (type in update) {
1841
+ return this.filter((ctx) => {
1842
+ if (type in ctx) {
1718
1843
  if (keys.length > 0) {
1719
1844
  for (const key of keys) {
1720
1845
  // deno-lint-ignore ban-ts-comment
1721
1846
  // @ts-ignore
1722
- if (!(key in update[type])) {
1847
+ if (!(key in ctx[type])) {
1723
1848
  return false;
1724
1849
  }
1725
1850
  }
@@ -1729,7 +1854,7 @@ export class Client extends ClientAbstract {
1729
1854
  else {
1730
1855
  return false;
1731
1856
  }
1732
- }, handler);
1857
+ }, ...middleawre);
1733
1858
  }
1734
1859
  /**
1735
1860
  * Set the bot's description in the given language. Bot-only.
@@ -1845,7 +1970,7 @@ async function _Client_handleUpdate(update) {
1845
1970
  const key = update instanceof types.UpdateNewMessage || update instanceof types.UpdateNewChannelMessage ? "message" : "editedMessage";
1846
1971
  if (!(update.message instanceof types.MessageEmpty)) {
1847
1972
  const message = await constructMessage(update.message, this[getEntity].bind(this), this.getMessage.bind(this), this[getStickerSetName].bind(this));
1848
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { [key]: message }, resolve);
1973
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { [key]: message }), resolve);
1849
1974
  }
1850
1975
  }
1851
1976
  if (update instanceof types.UpdateDeleteMessages) {
@@ -1861,7 +1986,7 @@ async function _Client_handleUpdate(update) {
1861
1986
  }
1862
1987
  }
1863
1988
  if (deletedMessages.length > 0) {
1864
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { deletedMessages: deletedMessages }, resolve);
1989
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
1865
1990
  }
1866
1991
  }
1867
1992
  else if (update instanceof types.UpdateDeleteChannelMessages) {
@@ -1875,14 +2000,14 @@ async function _Client_handleUpdate(update) {
1875
2000
  await this.storage.setMessage(chatId, messageId, null);
1876
2001
  }
1877
2002
  if (deletedMessages.length > 0) {
1878
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { deletedMessages: deletedMessages }, resolve);
2003
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { deletedMessages: deletedMessages }), resolve);
1879
2004
  }
1880
2005
  }
1881
2006
  if (update instanceof types.UpdateBotCallbackQuery || update instanceof types.UpdateInlineBotCallbackQuery) {
1882
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }, resolve);
2007
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { callbackQuery: await constructCallbackQuery(update, this[getEntity].bind(this), this[getMessageWithReply].bind(this)) }), resolve);
1883
2008
  }
1884
2009
  else if (update instanceof types.UpdateBotInlineQuery) {
1885
- await __classPrivateFieldGet(this, _Client_handle, "f").call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }, resolve);
2010
+ await __classPrivateFieldGet(this, _Client_handle, "f").call(this, __classPrivateFieldGet(this, _Client_constructContext, "f").call(this, { inlineQuery: await constructInlineQuery(update, this[getEntity].bind(this)) }), resolve);
1886
2011
  }
1887
2012
  }, _Client_constructReplyMarkup = async function _Client_constructReplyMarkup(params) {
1888
2013
  if (params?.replyMarkup) {
@@ -1894,7 +2019,9 @@ async function _Client_handleUpdate(update) {
1894
2019
  UNREACHABLE();
1895
2020
  }
1896
2021
  return message;
1897
- }, _Client_setMyInfo = async function _Client_setMyInfo(info) {
2022
+ }, _Client_setMyInfo =
2023
+ //#endregion
2024
+ async function _Client_setMyInfo(info) {
1898
2025
  await this.invoke(new functions.BotsSetBotInfo({ bot: new types.InputUserSelf(), ...info }));
1899
2026
  }, _Client_getMyInfo = function _Client_getMyInfo(languageCode) {
1900
2027
  return this.invoke(new functions.BotsGetBotInfo({ bot: new types.InputUserSelf(), langCode: languageCode ?? "" }));
@@ -0,0 +1,4 @@
1
+ import { Composer as Composer_ } from "./4_composer.js";
2
+ import { Context } from "./5_client.js";
3
+ export declare class Composer<C extends Context = Context> extends Composer_<C> {
4
+ }
@@ -0,0 +1,3 @@
1
+ import { Composer as Composer_ } from "./4_composer.js";
2
+ export class Composer extends Composer_ {
3
+ }
@@ -8,6 +8,7 @@ export declare class TLRawReader {
8
8
  readInt24(signed?: boolean): number;
9
9
  readInt32(signed?: boolean): number;
10
10
  readInt64(signed?: boolean): bigint;
11
+ readDouble(): number;
11
12
  readInt128(signed?: boolean): bigint;
12
13
  readInt256(signed?: boolean): bigint;
13
14
  readBytes(): Uint8Array;
@@ -33,6 +33,9 @@ export class TLRawReader {
33
33
  const buffer = this.read(64 / 8);
34
34
  return bigIntFromBuffer(buffer, true, signed);
35
35
  }
36
+ readDouble() {
37
+ return new DataView(this.read(8).buffer).getFloat64(0, true); // TODO: cover in tests
38
+ }
36
39
  readInt128(signed = true) {
37
40
  const buffer = this.read(128 / 8);
38
41
  return bigIntFromBuffer(buffer, true, signed);
@@ -28,7 +28,12 @@ function deserializeSingleParam(reader, type, ntype) {
28
28
  case "boolean":
29
29
  return reader.readInt32(false) == 0x997275B5;
30
30
  case "number":
31
- return reader.readInt32();
31
+ if (ntype == "double") {
32
+ return reader.readDouble();
33
+ }
34
+ else {
35
+ return reader.readInt32();
36
+ }
32
37
  case "string":
33
38
  return reader.readString();
34
39
  case "true":
@@ -64,7 +69,7 @@ export function deserialize(reader, paramDesc, constructor) {
64
69
  continue;
65
70
  }
66
71
  const value = deserializeSingleParam(reader, type, ntype);
67
- if (value) {
72
+ if (typeof value !== "boolean" || value) {
68
73
  params[name] = value;
69
74
  }
70
75
  }
@@ -158,11 +158,13 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
158
158
  replyMarkup,
159
159
  });
160
160
  const title = "title" in result_ ? result_.title : undefined;
161
+ const description = "description" in result_ ? result_.description : undefined;
161
162
  if (document != null) {
162
163
  return new types.InputBotInlineResult({
163
164
  id,
164
165
  type,
165
166
  title,
167
+ description,
166
168
  thumb: thumb == null ? undefined : thumb,
167
169
  content: document,
168
170
  sendMessage: new types.InputBotInlineMessageMediaAuto({
@@ -178,6 +180,7 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
178
180
  id,
179
181
  type,
180
182
  title,
183
+ description,
181
184
  document: new types.InputDocument({
182
185
  id: fileId.params.mediaId,
183
186
  accessHash: fileId.params.accessHash,
@@ -191,6 +194,7 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
191
194
  id,
192
195
  type,
193
196
  title,
197
+ description,
194
198
  sendMessage: new types.InputBotInlineMessageMediaGeo({
195
199
  geoPoint: new types.InputGeoPoint({
196
200
  lat: result_.latitude,
@@ -209,6 +213,7 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
209
213
  id,
210
214
  type,
211
215
  title,
216
+ description,
212
217
  sendMessage: new types.InputBotInlineMessageGame({
213
218
  replyMarkup,
214
219
  }),
@@ -223,6 +228,7 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
223
228
  id,
224
229
  type,
225
230
  title,
231
+ description,
226
232
  sendMessage: new types.InputBotInlineMessageText({
227
233
  message,
228
234
  entities,
@@ -239,6 +245,7 @@ export async function inlineQueryResultToTlObject(result_, parseText, usernameRe
239
245
  id,
240
246
  type,
241
247
  title,
248
+ description,
242
249
  sendMessage: new types.InputBotInlineMessageMediaVenue({
243
250
  geoPoint: new types.InputGeoPoint({ long: result_.longitude, lat: result_.latitude }),
244
251
  address: result_.address,
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "module": "./esm/mod.js",
3
3
  "main": "./script/mod.js",
4
4
  "name": "@mtkruto/node",
5
- "version": "0.1.112",
5
+ "version": "0.1.113",
6
6
  "description": "MTKruto for Node.js",
7
7
  "author": "Roj <rojvv@icloud.com>",
8
8
  "license": "LGPL-3.0-or-later",
@@ -5,7 +5,7 @@ export declare const PUBLIC_KEYS: PublicKeys;
5
5
  export declare const VECTOR_CONSTRUCTOR = 481674261;
6
6
  export declare const INITIAL_DC: DC;
7
7
  export declare const LAYER = 166;
8
- export declare const APP_VERSION = "MTKruto 0.1.112";
8
+ export declare const APP_VERSION = "MTKruto 0.1.113";
9
9
  export declare const DEVICE_MODEL: string;
10
10
  export declare const LANG_CODE: string;
11
11
  export declare const LANG_PACK = "";
@@ -80,7 +80,7 @@ exports.PUBLIC_KEYS = Object.freeze([
80
80
  exports.VECTOR_CONSTRUCTOR = 0x1CB5C415;
81
81
  exports.INITIAL_DC = "2";
82
82
  exports.LAYER = 166;
83
- exports.APP_VERSION = "MTKruto 0.1.112";
83
+ exports.APP_VERSION = "MTKruto 0.1.113";
84
84
  // @ts-ignore: lib
85
85
  exports.DEVICE_MODEL = typeof dntShim.Deno === "undefined" ? typeof navigator === "undefined" ? typeof process === "undefined" ? "Unknown" : process.platform + "-" + process.arch : navigator.userAgent.split(" ")[0] : dntShim.Deno.build.os + "-" + dntShim.Deno.build.arch;
86
86
  exports.LANG_CODE = typeof navigator === "undefined" ? "en" : navigator.language.split("-")[0];