!function(e,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.telegram=n():e.telegram=n()}(self,()=>(()=>{var __webpack_modules__={"./node_modules/@cryptography/aes/dist/es/aes.js": /*!*******************************************************!*\ !*** ./node_modules/@cryptography/aes/dist/es/aes.js ***! \*******************************************************/(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{"use strict";eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */ \"CTR\": () => (/* binding */ AES_IGE$1),\n/* harmony export */ \"IGE\": () => (/* binding */ AES_IGE),\n/* harmony export */ \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\nvar S = new Uint8Array(256);\nvar Si = new Uint8Array(256);\nvar T1 = new Uint32Array(256);\nvar T2 = new Uint32Array(256);\nvar T3 = new Uint32Array(256);\nvar T4 = new Uint32Array(256);\nvar T5 = new Uint32Array(256);\nvar T6 = new Uint32Array(256);\nvar T7 = new Uint32Array(256);\nvar T8 = new Uint32Array(256);\nfunction computeTables() {\n var d = new Uint8Array(256);\n var t = new Uint8Array(256);\n var x2;\n var x4;\n var x8;\n var s;\n var tEnc;\n var tDec;\n var x = 0;\n var xInv = 0;\n // Compute double and third tables\n for (var i = 0; i < 256; i++) {\n d[i] = i << 1 ^ (i >> 7) * 283;\n t[d[i] ^ i] = i;\n }\n for (; !S[x]; x ^= x2 || 1) {\n // Compute sbox\n s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;\n s = s >> 8 ^ s & 255 ^ 99;\n S[x] = s;\n Si[s] = x;\n // Compute MixColumns\n x8 = d[x4 = d[x2 = d[x]]];\n tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;\n tEnc = d[s] * 0x101 ^ s * 0x1010100;\n T1[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T2[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T3[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T4[x] = tEnc = tEnc << 24 ^ tEnc >>> 8;\n T5[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T6[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T7[s] = tDec = tDec << 24 ^ tDec >>> 8;\n T8[s] = tDec = tDec << 24 ^ tDec >>> 8;\n xInv = t[xInv] || 1;\n }\n}\n\n/**\n * Gets a uint32 from string in big-endian order order\n */\nfunction s2i(str, pos) {\n return (str.charCodeAt(pos) << 24\n ^ str.charCodeAt(pos + 1) << 16\n ^ str.charCodeAt(pos + 2) << 8\n ^ str.charCodeAt(pos + 3));\n}\n\n/* eslint-disable import/prefer-default-export */\n/**\n * Helper function for transforming string key to Uint32Array\n */\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n if (typeof key === 'string') {\n if (key.length % 4 !== 0)\n for (var i = key.length % 4; i <= 4; i++)\n key += '\\0x00';\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4)\n buf[i / 4] = s2i(key, i);\n return buf;\n }\n if (key instanceof Uint8Array) {\n var buf = new Uint32Array(key.length / 4);\n for (var i = 0; i < key.length; i += 4) {\n buf[i / 4] = (key[i] << 24\n ^ key[i + 1] << 16\n ^ key[i + 2] << 8\n ^ key[i + 3]);\n }\n return buf;\n }\n throw new Error('Unable to create 32-bit words');\n}\nfunction xor(left, right, to) {\n if (to === void 0) { to = left; }\n for (var i = 0; i < left.length; i++)\n to[i] = left[i] ^ right[i];\n}\n\ncomputeTables();\n/**\n * Low-level AES Cipher\n */\nvar AES = /** @class */ (function () {\n function AES(_key) {\n var key = getWords(_key);\n if (key.length !== 4 && key.length !== 6 && key.length !== 8) {\n throw new Error('Invalid key size');\n }\n this.encKey = new Uint32Array(4 * key.length + 28);\n this.decKey = new Uint32Array(4 * key.length + 28);\n this.encKey.set(key);\n var rcon = 1;\n var i = key.length;\n var tmp;\n // schedule encryption keys\n for (; i < 4 * key.length + 28; i++) {\n tmp = this.encKey[i - 1];\n // apply sbox\n if (i % key.length === 0 || (key.length === 8 && i % key.length === 4)) {\n tmp = S[tmp >>> 24] << 24 ^ S[(tmp >> 16) & 255] << 16 ^ S[(tmp >> 8) & 255] << 8 ^ S[tmp & 255];\n // shift rows and add rcon\n if (i % key.length === 0) {\n tmp = tmp << 8 ^ tmp >>> 24 ^ (rcon << 24);\n rcon = rcon << 1 ^ (rcon >> 7) * 283;\n }\n }\n this.encKey[i] = this.encKey[i - key.length] ^ tmp;\n }\n // schedule decryption keys\n for (var j = 0; i; j++, i--) {\n tmp = this.encKey[j & 3 ? i : i - 4];\n if (i <= 4 || j < 4) {\n this.decKey[j] = tmp;\n }\n else {\n this.decKey[j] = (T5[S[tmp >>> 24]]\n ^ T6[S[(tmp >> 16) & 255]]\n ^ T7[S[(tmp >> 8) & 255]]\n ^ T8[S[tmp & 255]]);\n }\n }\n }\n AES.prototype.encrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.encKey[0];\n var b = message[1] ^ this.encKey[1];\n var c = message[2] ^ this.encKey[2];\n var d = message[3] ^ this.encKey[3];\n var rounds = this.encKey.length / 4 - 2;\n var k = 4;\n var a2;\n var b2;\n var c2;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T1[a >>> 24] ^ T2[(b >> 16) & 255] ^ T3[(c >> 8) & 255] ^ T4[d & 255] ^ this.encKey[k];\n b2 = T1[b >>> 24] ^ T2[(c >> 16) & 255] ^ T3[(d >> 8) & 255] ^ T4[a & 255] ^ this.encKey[k + 1];\n c2 = T1[c >>> 24] ^ T2[(d >> 16) & 255] ^ T3[(a >> 8) & 255] ^ T4[b & 255] ^ this.encKey[k + 2];\n d = T1[d >>> 24] ^ T2[(a >> 16) & 255] ^ T3[(b >> 8) & 255] ^ T4[c & 255] ^ this.encKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n // console.log(a, b, c, d);\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[i] = (S[a >>> 24] << 24\n ^ S[(b >> 16) & 255] << 16\n ^ S[(c >> 8) & 255] << 8\n ^ S[d & 255]\n ^ this.encKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n AES.prototype.decrypt = function (_message) {\n var message = getWords(_message);\n var out = new Uint32Array(4);\n var a = message[0] ^ this.decKey[0];\n var b = message[3] ^ this.decKey[1];\n var c = message[2] ^ this.decKey[2];\n var d = message[1] ^ this.decKey[3];\n var rounds = this.decKey.length / 4 - 2;\n var a2;\n var b2;\n var c2;\n var k = 4;\n // Inner rounds. Cribbed from OpenSSL.\n for (var i = 0; i < rounds; i++) {\n a2 = T5[a >>> 24] ^ T6[(b >> 16) & 255] ^ T7[(c >> 8) & 255] ^ T8[d & 255] ^ this.decKey[k];\n b2 = T5[b >>> 24] ^ T6[(c >> 16) & 255] ^ T7[(d >> 8) & 255] ^ T8[a & 255] ^ this.decKey[k + 1];\n c2 = T5[c >>> 24] ^ T6[(d >> 16) & 255] ^ T7[(a >> 8) & 255] ^ T8[b & 255] ^ this.decKey[k + 2];\n d = T5[d >>> 24] ^ T6[(a >> 16) & 255] ^ T7[(b >> 8) & 255] ^ T8[c & 255] ^ this.decKey[k + 3];\n a = a2;\n b = b2;\n c = c2;\n k += 4;\n }\n // Last round.\n for (var i = 0; i < 4; i++) {\n out[3 & -i] = (Si[a >>> 24] << 24\n ^ Si[(b >> 16) & 255] << 16\n ^ Si[(c >> 8) & 255] << 8\n ^ Si[d & 255]\n ^ this.decKey[k++]);\n a2 = a;\n a = b;\n b = c;\n c = d;\n d = a2;\n }\n return out;\n };\n return AES;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE = /** @class */ (function () {\n function AES_IGE(key, iv, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.key = getWords(key);\n this.iv = getWords(iv);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var prevX = this.iv.subarray(this.blockSize, this.iv.length);\n var prevY = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = text.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.encrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n cipherText[j] = y[k];\n }\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n var cipherText = getWords(message);\n var text = buf || new Uint32Array(cipherText.length);\n var prevY = this.iv.subarray(this.blockSize, this.iv.length);\n var prevX = this.iv.subarray(0, this.blockSize);\n var yXOR = new Uint32Array(this.blockSize);\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = cipherText.subarray(i, i + this.blockSize);\n xor(x, prevY, yXOR);\n var y = this.cipher.decrypt(yXOR);\n xor(y, prevX);\n prevX = x;\n prevY = y;\n for (var j = i, k = 0; j < text.length && k < 4; j++, k++)\n text[j] = y[k];\n }\n return text;\n };\n return AES_IGE;\n}());\n\n/**\n * AES-IGE mode.\n */\nvar AES_IGE$1 = /** @class */ (function () {\n function AES_IGE(key, counter, blockSize) {\n if (blockSize === void 0) { blockSize = 16; }\n this.offset = 0;\n this.key = getWords(key);\n this.counter = getWords(counter);\n this.cipher = new AES(key);\n this.blockSize = blockSize / 4;\n if (this.counter.length !== 4) {\n throw new Error('AES-CTR mode counter must be 16 bytes length');\n }\n }\n /**\n * Encrypts plain text with AES-IGE mode.\n */\n AES_IGE.prototype.encrypt = function (message, buf) {\n var text = getWords(message);\n var cipherText = buf || new Uint32Array(text.length);\n var offset = this.offset;\n for (var i = 0; i < text.length; i += this.blockSize) {\n var x = this.cipher.encrypt(this.counter);\n for (var j = i, k = offset; j < text.length && k < this.blockSize; j++, k++)\n cipherText[j] = x[k] ^ text[j];\n if (text.length - i >= this.blockSize)\n this.incrementCounter();\n if (offset) {\n i -= offset;\n offset = 0;\n }\n }\n this.offset = (this.offset + (text.length % 4)) % 4;\n return cipherText;\n };\n /**\n * Decrypts cipher text with AES-IGE mode.\n */\n AES_IGE.prototype.decrypt = function (message, buf) {\n return this.encrypt(message, buf);\n };\n AES_IGE.prototype.incrementCounter = function () {\n // increment counter\n for (var carry = this.counter.length - 1; carry >= 0; carry--) {\n if (++this.counter[carry] < 0xFFFFFFFF)\n break; // If overflowing, it'll be 0 and we'll have to continue propagating the carry\n }\n };\n return AES_IGE;\n}());\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (AES);\n\n\n\n//# sourceURL=webpack://telegram/./node_modules/@cryptography/aes/dist/es/aes.js?")},"./node_modules/async-mutex/lib/Mutex.js": /*!***********************************************!*\ !*** ./node_modules/async-mutex/lib/Mutex.js ***! \***********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nvar tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");\nvar Semaphore_1 = __webpack_require__(/*! ./Semaphore */ "./node_modules/async-mutex/lib/Semaphore.js");\nvar Mutex = /** @class */ (function () {\n function Mutex(cancelError) {\n this._semaphore = new Semaphore_1.default(1, cancelError);\n }\n Mutex.prototype.acquire = function () {\n return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {\n var _a, releaser;\n return (0, tslib_1.__generator)(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this._semaphore.acquire()];\n case 1:\n _a = _b.sent(), releaser = _a[1];\n return [2 /*return*/, releaser];\n }\n });\n });\n };\n Mutex.prototype.runExclusive = function (callback) {\n return this._semaphore.runExclusive(function () { return callback(); });\n };\n Mutex.prototype.isLocked = function () {\n return this._semaphore.isLocked();\n };\n Mutex.prototype.waitForUnlock = function () {\n return this._semaphore.waitForUnlock();\n };\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n Mutex.prototype.release = function () {\n this._semaphore.release();\n };\n Mutex.prototype.cancel = function () {\n return this._semaphore.cancel();\n };\n return Mutex;\n}());\nexports["default"] = Mutex;\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/Mutex.js?')},"./node_modules/async-mutex/lib/Semaphore.js": /*!***************************************************!*\ !*** ./node_modules/async-mutex/lib/Semaphore.js ***! \***************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nvar tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");\nvar errors_1 = __webpack_require__(/*! ./errors */ "./node_modules/async-mutex/lib/errors.js");\nvar Semaphore = /** @class */ (function () {\n function Semaphore(_maxConcurrency, _cancelError) {\n if (_cancelError === void 0) { _cancelError = errors_1.E_CANCELED; }\n this._maxConcurrency = _maxConcurrency;\n this._cancelError = _cancelError;\n this._queue = [];\n this._waiters = [];\n if (_maxConcurrency <= 0) {\n throw new Error(\'semaphore must be initialized to a positive value\');\n }\n this._value = _maxConcurrency;\n }\n Semaphore.prototype.acquire = function () {\n var _this = this;\n var locked = this.isLocked();\n var ticketPromise = new Promise(function (resolve, reject) {\n return _this._queue.push({ resolve: resolve, reject: reject });\n });\n if (!locked)\n this._dispatch();\n return ticketPromise;\n };\n Semaphore.prototype.runExclusive = function (callback) {\n return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {\n var _a, value, release;\n return (0, tslib_1.__generator)(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, this.acquire()];\n case 1:\n _a = _b.sent(), value = _a[0], release = _a[1];\n _b.label = 2;\n case 2:\n _b.trys.push([2, , 4, 5]);\n return [4 /*yield*/, callback(value)];\n case 3: return [2 /*return*/, _b.sent()];\n case 4:\n release();\n return [7 /*endfinally*/];\n case 5: return [2 /*return*/];\n }\n });\n });\n };\n Semaphore.prototype.waitForUnlock = function () {\n return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {\n var waitPromise;\n var _this = this;\n return (0, tslib_1.__generator)(this, function (_a) {\n if (!this.isLocked()) {\n return [2 /*return*/, Promise.resolve()];\n }\n waitPromise = new Promise(function (resolve) { return _this._waiters.push({ resolve: resolve }); });\n return [2 /*return*/, waitPromise];\n });\n });\n };\n Semaphore.prototype.isLocked = function () {\n return this._value <= 0;\n };\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n Semaphore.prototype.release = function () {\n if (this._maxConcurrency > 1) {\n throw new Error(\'this method is unavailable on semaphores with concurrency > 1; use the scoped release returned by acquire instead\');\n }\n if (this._currentReleaser) {\n var releaser = this._currentReleaser;\n this._currentReleaser = undefined;\n releaser();\n }\n };\n Semaphore.prototype.cancel = function () {\n var _this = this;\n this._queue.forEach(function (ticket) { return ticket.reject(_this._cancelError); });\n this._queue = [];\n };\n Semaphore.prototype._dispatch = function () {\n var _this = this;\n var nextTicket = this._queue.shift();\n if (!nextTicket)\n return;\n var released = false;\n this._currentReleaser = function () {\n if (released)\n return;\n released = true;\n _this._value++;\n _this._resolveWaiters();\n _this._dispatch();\n };\n nextTicket.resolve([this._value--, this._currentReleaser]);\n };\n Semaphore.prototype._resolveWaiters = function () {\n this._waiters.forEach(function (waiter) { return waiter.resolve(); });\n this._waiters = [];\n };\n return Semaphore;\n}());\nexports["default"] = Semaphore;\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/Semaphore.js?')},"./node_modules/async-mutex/lib/errors.js": /*!************************************************!*\ !*** ./node_modules/async-mutex/lib/errors.js ***! \************************************************/(__unused_webpack_module,exports)=>{"use strict";eval("\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.E_CANCELED = exports.E_ALREADY_LOCKED = exports.E_TIMEOUT = void 0;\nexports.E_TIMEOUT = new Error('timeout while waiting for mutex to become available');\nexports.E_ALREADY_LOCKED = new Error('mutex already locked');\nexports.E_CANCELED = new Error('request for lock canceled');\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/errors.js?")},"./node_modules/async-mutex/lib/index.js": /*!***********************************************!*\ !*** ./node_modules/async-mutex/lib/index.js ***! \***********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nexports.tryAcquire = exports.withTimeout = exports.Semaphore = exports.Mutex = void 0;\nvar tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");\nvar Mutex_1 = __webpack_require__(/*! ./Mutex */ "./node_modules/async-mutex/lib/Mutex.js");\nObject.defineProperty(exports, "Mutex", ({ enumerable: true, get: function () { return Mutex_1.default; } }));\nvar Semaphore_1 = __webpack_require__(/*! ./Semaphore */ "./node_modules/async-mutex/lib/Semaphore.js");\nObject.defineProperty(exports, "Semaphore", ({ enumerable: true, get: function () { return Semaphore_1.default; } }));\nvar withTimeout_1 = __webpack_require__(/*! ./withTimeout */ "./node_modules/async-mutex/lib/withTimeout.js");\nObject.defineProperty(exports, "withTimeout", ({ enumerable: true, get: function () { return withTimeout_1.withTimeout; } }));\nvar tryAcquire_1 = __webpack_require__(/*! ./tryAcquire */ "./node_modules/async-mutex/lib/tryAcquire.js");\nObject.defineProperty(exports, "tryAcquire", ({ enumerable: true, get: function () { return tryAcquire_1.tryAcquire; } }));\n(0, tslib_1.__exportStar)(__webpack_require__(/*! ./errors */ "./node_modules/async-mutex/lib/errors.js"), exports);\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/index.js?')},"./node_modules/async-mutex/lib/tryAcquire.js": /*!****************************************************!*\ !*** ./node_modules/async-mutex/lib/tryAcquire.js ***! \****************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nexports.tryAcquire = void 0;\nvar errors_1 = __webpack_require__(/*! ./errors */ "./node_modules/async-mutex/lib/errors.js");\nvar withTimeout_1 = __webpack_require__(/*! ./withTimeout */ "./node_modules/async-mutex/lib/withTimeout.js");\n// eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types\nfunction tryAcquire(sync, alreadyAcquiredError) {\n if (alreadyAcquiredError === void 0) { alreadyAcquiredError = errors_1.E_ALREADY_LOCKED; }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (0, withTimeout_1.withTimeout)(sync, 0, alreadyAcquiredError);\n}\nexports.tryAcquire = tryAcquire;\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/tryAcquire.js?')},"./node_modules/async-mutex/lib/withTimeout.js": /*!*****************************************************!*\ !*** ./node_modules/async-mutex/lib/withTimeout.js ***! \*****************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nexports.withTimeout = void 0;\nvar tslib_1 = __webpack_require__(/*! tslib */ "./node_modules/tslib/tslib.es6.js");\nvar errors_1 = __webpack_require__(/*! ./errors */ "./node_modules/async-mutex/lib/errors.js");\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nfunction withTimeout(sync, timeout, timeoutError) {\n var _this = this;\n if (timeoutError === void 0) { timeoutError = errors_1.E_TIMEOUT; }\n return {\n acquire: function () {\n return new Promise(function (resolve, reject) { return (0, tslib_1.__awaiter)(_this, void 0, void 0, function () {\n var isTimeout, handle, ticket, release, e_1;\n return (0, tslib_1.__generator)(this, function (_a) {\n switch (_a.label) {\n case 0:\n isTimeout = false;\n handle = setTimeout(function () {\n isTimeout = true;\n reject(timeoutError);\n }, timeout);\n _a.label = 1;\n case 1:\n _a.trys.push([1, 3, , 4]);\n return [4 /*yield*/, sync.acquire()];\n case 2:\n ticket = _a.sent();\n if (isTimeout) {\n release = Array.isArray(ticket) ? ticket[1] : ticket;\n release();\n }\n else {\n clearTimeout(handle);\n resolve(ticket);\n }\n return [3 /*break*/, 4];\n case 3:\n e_1 = _a.sent();\n if (!isTimeout) {\n clearTimeout(handle);\n reject(e_1);\n }\n return [3 /*break*/, 4];\n case 4: return [2 /*return*/];\n }\n });\n }); });\n },\n runExclusive: function (callback) {\n return (0, tslib_1.__awaiter)(this, void 0, void 0, function () {\n var release, ticket;\n return (0, tslib_1.__generator)(this, function (_a) {\n switch (_a.label) {\n case 0:\n release = function () { return undefined; };\n _a.label = 1;\n case 1:\n _a.trys.push([1, , 7, 8]);\n return [4 /*yield*/, this.acquire()];\n case 2:\n ticket = _a.sent();\n if (!Array.isArray(ticket)) return [3 /*break*/, 4];\n release = ticket[1];\n return [4 /*yield*/, callback(ticket[0])];\n case 3: return [2 /*return*/, _a.sent()];\n case 4:\n release = ticket;\n return [4 /*yield*/, callback()];\n case 5: return [2 /*return*/, _a.sent()];\n case 6: return [3 /*break*/, 8];\n case 7:\n release();\n return [7 /*endfinally*/];\n case 8: return [2 /*return*/];\n }\n });\n });\n },\n /** @deprecated Deprecated in 0.3.0, will be removed in 0.4.0. Use runExclusive instead. */\n release: function () {\n sync.release();\n },\n cancel: function () {\n return sync.cancel();\n },\n waitForUnlock: function () { return sync.waitForUnlock(); },\n isLocked: function () { return sync.isLocked(); },\n };\n}\nexports.withTimeout = withTimeout;\n\n\n//# sourceURL=webpack://telegram/./node_modules/async-mutex/lib/withTimeout.js?')},"./browser/CryptoFile.js": /*!*******************************!*\ !*** ./browser/CryptoFile.js ***! \*******************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\n\nconst crypto = __importStar(__webpack_require__(/*! ./crypto/crypto */ "./browser/crypto/crypto.js"));\n\nexports["default"] = crypto;\n\n//# sourceURL=webpack://telegram/./browser/CryptoFile.js?')},"./browser/Helpers.js": /*!****************************!*\ !*** ./browser/Helpers.js ***! \****************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports._entityType = exports._EntityType = exports.TotalList = exports.crc32 = exports.bufferXor = exports.sleep = exports.getRandomInt = exports.getMinBigInt = exports.returnBigInt = exports.getByteArray = exports.modExp = exports.sha256 = exports.sha1 = exports.convertToLittle = exports.generateKeyDataFromNonce = exports.stripText = exports.generateRandomBytes = exports.bigIntMod = exports.mod = exports.generateRandomLong = exports.readBufferFromBigInt = exports.toSignedLittleBuffer = exports.isArrayLike = exports.betterConsoleLog = exports.groupBy = exports.escapeRegex = exports.generateRandomBigInt = exports.readBigIntFromBuffer = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst CryptoFile_1 = __importDefault(__webpack_require__(/*! ./CryptoFile */ "./browser/CryptoFile.js"));\n/**\n * converts a buffer to big int\n * @param buffer\n * @param little\n * @param signed\n * @returns {bigInt.BigInteger}\n */\n\n\nfunction readBigIntFromBuffer(buffer, little = true, signed = false) {\n let randBuffer = buffer_1.Buffer.from(buffer);\n const bytesNumber = randBuffer.length;\n\n if (little) {\n randBuffer = randBuffer.reverse();\n }\n\n let bigIntVar = (0, big_integer_1.default)(randBuffer.toString("hex"), 16);\n\n if (signed && Math.floor(bigIntVar.toString(2).length / 8) >= bytesNumber) {\n bigIntVar = bigIntVar.subtract((0, big_integer_1.default)(2).pow((0, big_integer_1.default)(bytesNumber * 8)));\n }\n\n return bigIntVar;\n}\n\nexports.readBigIntFromBuffer = readBigIntFromBuffer;\n\nfunction generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), false);\n}\n\nexports.generateRandomBigInt = generateRandomBigInt;\n\nfunction escapeRegex(string) {\n return string.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, "\\\\$&");\n}\n\nexports.escapeRegex = escapeRegex;\n\nfunction groupBy(list, keyGetter) {\n const map = new Map();\n list.forEach(item => {\n const key = keyGetter(item);\n const collection = map.get(key);\n\n if (!collection) {\n map.set(key, [item]);\n } else {\n collection.push(item);\n }\n });\n return map;\n}\n\nexports.groupBy = groupBy;\n/**\n * Outputs the object in a better way by hiding all the private methods/attributes.\n * @param object - the class to use\n */\n\nfunction betterConsoleLog(object) {\n const toPrint = {};\n\n for (const key in object) {\n if (object.hasOwnProperty(key)) {\n if (!key.startsWith("_") && key != "originalArgs") {\n toPrint[key] = object[key];\n }\n }\n }\n\n return toPrint;\n}\n\nexports.betterConsoleLog = betterConsoleLog;\n/**\n * Helper to find if a given object is an array (or similar)\n */\n\nconst isArrayLike = x => x && typeof x.length === "number" && typeof x !== "function" && typeof x !== "string";\n\nexports.isArrayLike = isArrayLike;\n/*\nexport function addSurrogate(text: string) {\n let temp = "";\n for (const letter of text) {\n const t = letter.charCodeAt(0);\n if (0x1000 < t && t < 0x10FFFF) {\n const b = Buffer.from(letter, "utf16le");\n const r = String.fromCharCode(b.readUInt16LE(0)) + String.fromCharCode(b.readUInt16LE(2));\n temp += r;\n } else {\n text += letter;\n }\n }\n return temp;\n}\n\n */\n\n/**\n * Special case signed little ints\n * @param big\n * @param number\n * @returns {Buffer}\n */\n\nfunction toSignedLittleBuffer(big, number = 8) {\n const bigNumber = returnBigInt(big);\n const byteArray = [];\n\n for (let i = 0; i < number; i++) {\n byteArray[i] = bigNumber.shiftRight(8 * i).and(255);\n } // smh hacks\n\n\n return buffer_1.Buffer.from(byteArray);\n}\n\nexports.toSignedLittleBuffer = toSignedLittleBuffer;\n/**\n * converts a big int to a buffer\n * @param bigIntVar {BigInteger}\n * @param bytesNumber\n * @param little\n * @param signed\n * @returns {Buffer}\n */\n\nfunction readBufferFromBigInt(bigIntVar, bytesNumber, little = true, signed = false) {\n bigIntVar = (0, big_integer_1.default)(bigIntVar);\n const bitLength = bigIntVar.bitLength().toJSNumber();\n const bytes = Math.ceil(bitLength / 8);\n\n if (bytesNumber < bytes) {\n throw new Error("OverflowError: int too big to convert");\n }\n\n if (!signed && bigIntVar.lesser((0, big_integer_1.default)(0))) {\n throw new Error("Cannot convert to unsigned");\n }\n\n let below = false;\n\n if (bigIntVar.lesser((0, big_integer_1.default)(0))) {\n below = true;\n bigIntVar = bigIntVar.abs();\n }\n\n const hex = bigIntVar.toString(16).padStart(bytesNumber * 2, "0");\n let buffer = buffer_1.Buffer.from(hex, "hex");\n\n if (signed && below) {\n buffer[buffer.length - 1] = 256 - buffer[buffer.length - 1];\n\n for (let i = 0; i < buffer.length - 1; i++) {\n buffer[i] = 255 - buffer[i];\n }\n }\n\n if (little) {\n buffer = buffer.reverse();\n }\n\n return buffer;\n}\n\nexports.readBufferFromBigInt = readBufferFromBigInt;\n/**\n * Generates a random long integer (8 bytes), which is optionally signed\n * @returns {BigInteger}\n */\n\nfunction generateRandomLong(signed = true) {\n return readBigIntFromBuffer(generateRandomBytes(8), true, signed);\n}\n\nexports.generateRandomLong = generateRandomLong;\n/**\n * .... really javascript\n * @param n {number}\n * @param m {number}\n * @returns {number}\n */\n\nfunction mod(n, m) {\n return (n % m + m) % m;\n}\n\nexports.mod = mod;\n/**\n * returns a positive bigInt\n * @param n {bigInt.BigInteger}\n * @param m {bigInt.BigInteger}\n * @returns {bigInt.BigInteger}\n */\n\nfunction bigIntMod(n, m) {\n return n.remainder(m).add(m).remainder(m);\n}\n\nexports.bigIntMod = bigIntMod;\n/**\n * Generates a random bytes array\n * @param count\n * @returns {Buffer}\n */\n\nfunction generateRandomBytes(count) {\n return buffer_1.Buffer.from(CryptoFile_1.default.randomBytes(count));\n}\n\nexports.generateRandomBytes = generateRandomBytes;\n/**\n * Calculate the key based on Telegram guidelines, specifying whether it\'s the client or not\n * @param sharedKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n/*CONTEST\nthis is mtproto 1 (mostly used for secret chats)\nasync function calcKey(sharedKey, msgKey, client) {\n const x = client === true ? 0 : 8\n const [sha1a, sha1b, sha1c, sha1d] = await Promise.all([\n sha1(Buffer.concat([msgKey, sharedKey.slice(x, x + 32)])),\n sha1(Buffer.concat([sharedKey.slice(x + 32, x + 48), msgKey, sharedKey.slice(x + 48, x + 64)])),\n sha1(Buffer.concat([sharedKey.slice(x + 64, x + 96), msgKey])),\n sha1(Buffer.concat([msgKey, sharedKey.slice(x + 96, x + 128)]))\n ])\n const key = Buffer.concat([sha1a.slice(0, 8), sha1b.slice(8, 20), sha1c.slice(4, 16)])\n const iv = Buffer.concat([sha1a.slice(8, 20), sha1b.slice(0, 8), sha1c.slice(16, 20), sha1d.slice(0, 8)])\n return {\n key,\n iv\n }\n}\n\n */\n\nfunction stripText(text, entities) {\n if (!entities || !entities.length) {\n return text.trim();\n }\n\n while (text && text[text.length - 1].trim() === "") {\n const e = entities[entities.length - 1];\n\n if (e.offset + e.length == text.length) {\n if (e.length == 1) {\n entities.pop();\n\n if (!entities.length) {\n return text.trim();\n }\n } else {\n e.length -= 1;\n }\n }\n\n text = text.slice(0, -1);\n }\n\n while (text && text[0].trim() === "") {\n for (let i = 0; i < entities.length; i++) {\n const e = entities[i];\n\n if (e.offset != 0) {\n e.offset--;\n continue;\n }\n\n if (e.length == 1) {\n entities.shift();\n\n if (!entities.length) {\n return text.trimLeft();\n }\n } else {\n e.length -= 1;\n }\n }\n\n text = text.slice(1);\n }\n\n return text;\n}\n\nexports.stripText = stripText;\n/**\n * Generates the key data corresponding to the given nonces\n * @param serverNonceBigInt\n * @param newNonceBigInt\n * @returns {{key: Buffer, iv: Buffer}}\n */\n\nasync function generateKeyDataFromNonce(serverNonceBigInt, newNonceBigInt) {\n const serverNonce = toSignedLittleBuffer(serverNonceBigInt, 16);\n const newNonce = toSignedLittleBuffer(newNonceBigInt, 32);\n const [hash1, hash2, hash3] = await Promise.all([sha1(buffer_1.Buffer.concat([newNonce, serverNonce])), sha1(buffer_1.Buffer.concat([serverNonce, newNonce])), sha1(buffer_1.Buffer.concat([newNonce, newNonce]))]);\n const keyBuffer = buffer_1.Buffer.concat([hash1, hash2.slice(0, 12)]);\n const ivBuffer = buffer_1.Buffer.concat([hash2.slice(12, 20), hash3, newNonce.slice(0, 4)]);\n return {\n key: keyBuffer,\n iv: ivBuffer\n };\n}\n\nexports.generateKeyDataFromNonce = generateKeyDataFromNonce;\n\nfunction convertToLittle(buf) {\n const correct = buffer_1.Buffer.alloc(buf.length * 4);\n\n for (let i = 0; i < buf.length; i++) {\n correct.writeUInt32BE(buf[i], i * 4);\n }\n\n return correct;\n}\n\nexports.convertToLittle = convertToLittle;\n/**\n * Calculates the SHA1 digest for the given data\n * @param data\n * @returns {Promise}\n */\n\nfunction sha1(data) {\n const shaSum = CryptoFile_1.default.createHash("sha1");\n shaSum.update(data); // @ts-ignore\n\n return shaSum.digest();\n}\n\nexports.sha1 = sha1;\n/**\n * Calculates the SHA256 digest for the given data\n * @param data\n * @returns {Promise}\n */\n\nfunction sha256(data) {\n const shaSum = CryptoFile_1.default.createHash("sha256");\n shaSum.update(data); // @ts-ignore\n\n return shaSum.digest();\n}\n\nexports.sha256 = sha256;\n/**\n * Fast mod pow for RSA calculation. a^b % n\n * @param a\n * @param b\n * @param n\n * @returns {bigInt.BigInteger}\n */\n\nfunction modExp(a, b, n) {\n a = a.remainder(n);\n let result = big_integer_1.default.one;\n let x = a;\n\n while (b.greater(big_integer_1.default.zero)) {\n const leastSignificantBit = b.remainder((0, big_integer_1.default)(2));\n b = b.divide((0, big_integer_1.default)(2));\n\n if (leastSignificantBit.eq(big_integer_1.default.one)) {\n result = result.multiply(x);\n result = result.remainder(n);\n }\n\n x = x.multiply(x);\n x = x.remainder(n);\n }\n\n return result;\n}\n\nexports.modExp = modExp;\n/**\n * Gets the arbitrary-length byte array corresponding to the given integer\n * @param integer {number,BigInteger}\n * @param signed {boolean}\n * @returns {Buffer}\n */\n\nfunction getByteArray(integer, signed = false) {\n const bits = integer.toString(2).length;\n const byteLength = Math.floor((bits + 8 - 1) / 8);\n return readBufferFromBigInt(typeof integer == "number" ? (0, big_integer_1.default)(integer) : integer, byteLength, false, signed);\n}\n\nexports.getByteArray = getByteArray;\n\nfunction returnBigInt(num) {\n if (big_integer_1.default.isInstance(num)) {\n return num;\n }\n\n if (typeof num == "number") {\n return (0, big_integer_1.default)(num);\n }\n\n if (typeof num == "bigint") {\n return (0, big_integer_1.default)(num);\n }\n\n return (0, big_integer_1.default)(num);\n}\n\nexports.returnBigInt = returnBigInt;\n/**\n * Helper function to return the smaller big int in an array\n * @param arrayOfBigInts\n */\n\nfunction getMinBigInt(arrayOfBigInts) {\n if (arrayOfBigInts.length == 0) {\n return big_integer_1.default.zero;\n }\n\n if (arrayOfBigInts.length == 1) {\n return returnBigInt(arrayOfBigInts[0]);\n }\n\n let smallest = returnBigInt(arrayOfBigInts[0]);\n\n for (let i = 1; i < arrayOfBigInts.length; i++) {\n if (returnBigInt(arrayOfBigInts[i]).lesser(smallest)) {\n smallest = returnBigInt(arrayOfBigInts[i]);\n }\n }\n\n return smallest;\n}\n\nexports.getMinBigInt = getMinBigInt;\n/**\n * returns a random int from min (inclusive) and max (inclusive)\n * @param min\n * @param max\n * @returns {number}\n */\n\nfunction getRandomInt(min, max) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n}\n\nexports.getRandomInt = getRandomInt;\n/**\n * Sleeps a specified amount of time\n * @param ms time in milliseconds\n * @returns {Promise}\n */\n\nconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));\n\nexports.sleep = sleep;\n/**\n * Helper to export two buffers of same length\n * @returns {Buffer}\n */\n\nfunction bufferXor(a, b) {\n const res = [];\n\n for (let i = 0; i < a.length; i++) {\n res.push(a[i] ^ b[i]);\n }\n\n return buffer_1.Buffer.from(res);\n}\n\nexports.bufferXor = bufferXor; // Taken from https://stackoverflow.com/questions/18638900/javascript-crc32/18639999#18639999\n\nfunction makeCRCTable() {\n let c;\n const crcTable = [];\n\n for (let n = 0; n < 256; n++) {\n c = n;\n\n for (let k = 0; k < 8; k++) {\n c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1;\n }\n\n crcTable[n] = c;\n }\n\n return crcTable;\n}\n\nlet crcTable = undefined;\n\nfunction crc32(buf) {\n if (!crcTable) {\n crcTable = makeCRCTable();\n }\n\n if (!buffer_1.Buffer.isBuffer(buf)) {\n buf = buffer_1.Buffer.from(buf);\n }\n\n let crc = -1;\n\n for (let index = 0; index < buf.length; index++) {\n const byte = buf[index];\n crc = crcTable[(crc ^ byte) & 0xff] ^ crc >>> 8;\n }\n\n return (crc ^ -1) >>> 0;\n}\n\nexports.crc32 = crc32;\n\nclass TotalList extends Array {\n constructor() {\n super();\n this.total = 0;\n }\n\n}\n\nexports.TotalList = TotalList;\nexports._EntityType = {\n USER: 0,\n CHAT: 1,\n CHANNEL: 2\n};\nObject.freeze(exports._EntityType);\n\nfunction _entityType(entity) {\n if (typeof entity !== "object" || !("SUBCLASS_OF_ID" in entity)) {\n throw new Error(`${entity} is not a TLObject, cannot determine entity type`);\n }\n\n if (![0x2d45687, 0xc91c90b6, 0xe669bf46, 0x40f202fd, 0x2da17977, 0xc5af5d94, 0x1f4661b9, 0xd49a2697 // crc32(\'ChatFull\')\n ].includes(entity.SUBCLASS_OF_ID)) {\n throw new Error(`${entity} does not have any entity type`);\n }\n\n const name = entity.className;\n\n if (name.includes("User")) {\n return exports._EntityType.USER;\n } else if (name.includes("Chat")) {\n return exports._EntityType.CHAT;\n } else if (name.includes("Channel")) {\n return exports._EntityType.CHANNEL;\n } else if (name.includes("Self")) {\n return exports._EntityType.USER;\n } // \'Empty\' in name or not found, we don\'t care, not a valid entity.\n\n\n throw new Error(`${entity} does not have any entity type`);\n}\n\nexports._entityType = _entityType;\n\n//# sourceURL=webpack://telegram/./browser/Helpers.js?')},"./browser/Password.js": /*!*****************************!*\ !*** ./browser/Password.js ***! \*****************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.computeDigest = exports.computeCheck = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst tl_1 = __webpack_require__(/*! ./tl */ "./browser/tl/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ./Helpers */ "./browser/Helpers.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst CryptoFile_1 = __importDefault(__webpack_require__(/*! ./CryptoFile */ "./browser/CryptoFile.js"));\n\nconst SIZE_FOR_HASH = 256;\n/**\n *\n *\n * @param prime{BigInteger}\n * @param g{BigInteger}\n */\n\n/*\nWe don\'t support changing passwords yet\nfunction checkPrimeAndGoodCheck(prime, g) {\n console.error(\'Unsupported function `checkPrimeAndGoodCheck` call. Arguments:\', prime, g)\n\n const goodPrimeBitsCount = 2048\n if (prime < 0 || prime.bitLength() !== goodPrimeBitsCount) {\n throw new Error(`bad prime count ${prime.bitLength()},expected ${goodPrimeBitsCount}`)\n }\n // TODO this is kinda slow\n if (Factorizator.factorize(prime)[0] !== 1) {\n throw new Error(\'give "prime" is not prime\')\n }\n if (g.eq(bigInt(2))) {\n if ((prime.remainder(bigInt(8))).neq(bigInt(7))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 8}`)\n }\n } else if (g.eq(bigInt(3))) {\n if ((prime.remainder(bigInt(3))).neq(bigInt(2))) {\n throw new Error(`bad g ${g}, mod3 ${prime % 3}`)\n }\n // eslint-disable-next-line no-empty\n } else if (g.eq(bigInt(4))) {\n\n } else if (g.eq(bigInt(5))) {\n if (!([ bigInt(1), bigInt(4) ].includes(prime.remainder(bigInt(5))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 5}`)\n }\n } else if (g.eq(bigInt(6))) {\n if (!([ bigInt(19), bigInt(23) ].includes(prime.remainder(bigInt(24))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 24}`)\n }\n } else if (g.eq(bigInt(7))) {\n if (!([ bigInt(3), bigInt(5), bigInt(6) ].includes(prime.remainder(bigInt(7))))) {\n throw new Error(`bad g ${g}, mod8 ${prime % 7}`)\n }\n } else {\n throw new Error(`bad g ${g}`)\n }\n const primeSub1Div2 = (prime.subtract(bigInt(1))).divide(bigInt(2))\n if (Factorizator.factorize(primeSub1Div2)[0] !== 1) {\n throw new Error(\'(prime - 1) // 2 is not prime\')\n }\n}\n*/\n\n/**\n *\n * @param primeBytes{Buffer}\n * @param g{number}\n */\n\nfunction checkPrimeAndGood(primeBytes, g) {\n const goodPrime = buffer_1.Buffer.from([0xc7, 0x1c, 0xae, 0xb9, 0xc6, 0xb1, 0xc9, 0x04, 0x8e, 0x6c, 0x52, 0x2f, 0x70, 0xf1, 0x3f, 0x73, 0x98, 0x0d, 0x40, 0x23, 0x8e, 0x3e, 0x21, 0xc1, 0x49, 0x34, 0xd0, 0x37, 0x56, 0x3d, 0x93, 0x0f, 0x48, 0x19, 0x8a, 0x0a, 0xa7, 0xc1, 0x40, 0x58, 0x22, 0x94, 0x93, 0xd2, 0x25, 0x30, 0xf4, 0xdb, 0xfa, 0x33, 0x6f, 0x6e, 0x0a, 0xc9, 0x25, 0x13, 0x95, 0x43, 0xae, 0xd4, 0x4c, 0xce, 0x7c, 0x37, 0x20, 0xfd, 0x51, 0xf6, 0x94, 0x58, 0x70, 0x5a, 0xc6, 0x8c, 0xd4, 0xfe, 0x6b, 0x6b, 0x13, 0xab, 0xdc, 0x97, 0x46, 0x51, 0x29, 0x69, 0x32, 0x84, 0x54, 0xf1, 0x8f, 0xaf, 0x8c, 0x59, 0x5f, 0x64, 0x24, 0x77, 0xfe, 0x96, 0xbb, 0x2a, 0x94, 0x1d, 0x5b, 0xcd, 0x1d, 0x4a, 0xc8, 0xcc, 0x49, 0x88, 0x07, 0x08, 0xfa, 0x9b, 0x37, 0x8e, 0x3c, 0x4f, 0x3a, 0x90, 0x60, 0xbe, 0xe6, 0x7c, 0xf9, 0xa4, 0xa4, 0xa6, 0x95, 0x81, 0x10, 0x51, 0x90, 0x7e, 0x16, 0x27, 0x53, 0xb5, 0x6b, 0x0f, 0x6b, 0x41, 0x0d, 0xba, 0x74, 0xd8, 0xa8, 0x4b, 0x2a, 0x14, 0xb3, 0x14, 0x4e, 0x0e, 0xf1, 0x28, 0x47, 0x54, 0xfd, 0x17, 0xed, 0x95, 0x0d, 0x59, 0x65, 0xb4, 0xb9, 0xdd, 0x46, 0x58, 0x2d, 0xb1, 0x17, 0x8d, 0x16, 0x9c, 0x6b, 0xc4, 0x65, 0xb0, 0xd6, 0xff, 0x9c, 0xa3, 0x92, 0x8f, 0xef, 0x5b, 0x9a, 0xe4, 0xe4, 0x18, 0xfc, 0x15, 0xe8, 0x3e, 0xbe, 0xa0, 0xf8, 0x7f, 0xa9, 0xff, 0x5e, 0xed, 0x70, 0x05, 0x0d, 0xed, 0x28, 0x49, 0xf4, 0x7b, 0xf9, 0x59, 0xd9, 0x56, 0x85, 0x0c, 0xe9, 0x29, 0x85, 0x1f, 0x0d, 0x81, 0x15, 0xf6, 0x35, 0xb1, 0x05, 0xee, 0x2e, 0x4e, 0x15, 0xd0, 0x4b, 0x24, 0x54, 0xbf, 0x6f, 0x4f, 0xad, 0xf0, 0x34, 0xb1, 0x04, 0x03, 0x11, 0x9c, 0xd8, 0xe3, 0xb9, 0x2f, 0xcc, 0x5b]);\n\n if (goodPrime.equals(primeBytes)) {\n if ([3, 4, 5, 7].includes(g)) {\n return; // It\'s good\n }\n }\n\n throw new Error("Changing passwords unsupported"); //checkPrimeAndGoodCheck(readBigIntFromBuffer(primeBytes, false), g)\n}\n/**\n *\n * @param number{BigInteger}\n * @param p{BigInteger}\n * @returns {boolean}\n */\n\n\nfunction isGoodLarge(number, p) {\n return number.greater((0, big_integer_1.default)(0)) && p.subtract(number).greater((0, big_integer_1.default)(0));\n}\n/**\n *\n * @param number {Buffer}\n * @returns {Buffer}\n */\n\n\nfunction numBytesForHash(number) {\n return buffer_1.Buffer.concat([buffer_1.Buffer.alloc(SIZE_FOR_HASH - number.length), number]);\n}\n/**\n *\n * @param g {bigInt}\n * @returns {Buffer}\n */\n\n\nfunction bigNumForHash(g) {\n return (0, Helpers_1.readBufferFromBigInt)(g, SIZE_FOR_HASH, false);\n}\n/**\n *\n * @param modexp {BigInteger}\n * @param prime {BigInteger}\n * @returns {Boolean}\n */\n\n\nfunction isGoodModExpFirst(modexp, prime) {\n const diff = prime.subtract(modexp);\n const minDiffBitsCount = 2048 - 64;\n const maxModExpSize = 256;\n return !(diff.lesser((0, big_integer_1.default)(0)) || diff.bitLength().toJSNumber() < minDiffBitsCount || modexp.bitLength().toJSNumber() < minDiffBitsCount || Math.floor((modexp.bitLength().toJSNumber() + 7) / 8) > maxModExpSize);\n}\n\nfunction xor(a, b) {\n const length = Math.min(a.length, b.length);\n\n for (let i = 0; i < length; i++) {\n a[i] = a[i] ^ b[i];\n }\n\n return a;\n}\n/**\n *\n * @param password{Buffer}\n * @param salt{Buffer}\n * @param iterations{number}\n * @returns {*}\n */\n\n\nfunction pbkdf2sha512(password, salt, iterations) {\n return CryptoFile_1.default.pbkdf2Sync(password, salt, iterations, 64, "sha512");\n}\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n * @returns {Buffer|*}\n */\n\n\nasync function computeHash(algo, password) {\n const hash1 = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([algo.salt1, buffer_1.Buffer.from(password, "utf-8"), algo.salt1]));\n const hash2 = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([algo.salt2, hash1, algo.salt2]));\n const hash3 = await pbkdf2sha512(hash2, algo.salt1, 100000);\n return (0, Helpers_1.sha256)(buffer_1.Buffer.concat([algo.salt2, hash3, algo.salt2]));\n}\n/**\n *\n * @param algo {constructors.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow}\n * @param password\n */\n\n\nasync function computeDigest(algo, password) {\n try {\n checkPrimeAndGood(algo.p, algo.g);\n } catch (e) {\n throw new Error("bad p/g in password");\n }\n\n const value = (0, Helpers_1.modExp)((0, big_integer_1.default)(algo.g), (0, Helpers_1.readBigIntFromBuffer)(await computeHash(algo, password), false), (0, Helpers_1.readBigIntFromBuffer)(algo.p, false));\n return bigNumForHash(value);\n}\n\nexports.computeDigest = computeDigest;\n/**\n *\n * @param request {constructors.account.Password}\n * @param password {string}\n */\n\nasync function computeCheck(request, password) {\n const algo = request.currentAlgo;\n\n if (!(algo instanceof tl_1.Api.PasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow)) {\n throw new Error(`Unsupported password algorithm ${algo === null || algo === void 0 ? void 0 : algo.className}`);\n }\n\n const srp_B = request.srp_B;\n const srpId = request.srpId;\n\n if (!srp_B || !srpId) {\n throw new Error(`Undefined srp_b ${request}`);\n }\n\n const pwHash = await computeHash(algo, password);\n const p = (0, Helpers_1.readBigIntFromBuffer)(algo.p, false);\n const g = algo.g;\n const B = (0, Helpers_1.readBigIntFromBuffer)(srp_B, false);\n\n try {\n checkPrimeAndGood(algo.p, g);\n } catch (e) {\n throw new Error("bad /g in password");\n }\n\n if (!isGoodLarge(B, p)) {\n throw new Error("bad b in check");\n }\n\n const x = (0, Helpers_1.readBigIntFromBuffer)(pwHash, false);\n const pForHash = numBytesForHash(algo.p);\n const gForHash = bigNumForHash((0, big_integer_1.default)(g));\n const bForHash = numBytesForHash(srp_B);\n const gX = (0, Helpers_1.modExp)((0, big_integer_1.default)(g), x, p);\n const k = (0, Helpers_1.readBigIntFromBuffer)(await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([pForHash, gForHash])), false);\n const kgX = (0, Helpers_1.bigIntMod)(k.multiply(gX), p);\n\n const generateAndCheckRandom = async () => {\n const randomSize = 256; // eslint-disable-next-line no-constant-condition\n\n while (true) {\n const random = (0, Helpers_1.generateRandomBytes)(randomSize);\n const a = (0, Helpers_1.readBigIntFromBuffer)(random, false);\n const A = (0, Helpers_1.modExp)((0, big_integer_1.default)(g), a, p);\n\n if (isGoodModExpFirst(A, p)) {\n const aForHash = bigNumForHash(A);\n const u = (0, Helpers_1.readBigIntFromBuffer)(await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([aForHash, bForHash])), false);\n\n if (u.greater((0, big_integer_1.default)(0))) {\n return {\n a: a,\n aForHash: aForHash,\n u: u\n };\n }\n }\n }\n };\n\n const {\n a,\n aForHash,\n u\n } = await generateAndCheckRandom();\n const gB = (0, Helpers_1.bigIntMod)(B.subtract(kgX), p);\n\n if (!isGoodModExpFirst(gB, p)) {\n throw new Error("bad gB");\n }\n\n const ux = u.multiply(x);\n const aUx = a.add(ux);\n const S = (0, Helpers_1.modExp)(gB, aUx, p);\n const [K, pSha, gSha, salt1Sha, salt2Sha] = await Promise.all([(0, Helpers_1.sha256)(bigNumForHash(S)), (0, Helpers_1.sha256)(pForHash), (0, Helpers_1.sha256)(gForHash), (0, Helpers_1.sha256)(algo.salt1), (0, Helpers_1.sha256)(algo.salt2)]);\n const M1 = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([xor(pSha, gSha), salt1Sha, salt2Sha, aForHash, bForHash, K]));\n return new tl_1.Api.InputCheckPasswordSRP({\n srpId: srpId,\n A: buffer_1.Buffer.from(aForHash),\n M1: M1\n });\n}\n\nexports.computeCheck = computeCheck;\n\n//# sourceURL=webpack://telegram/./browser/Password.js?')},"./browser/Utils.js": /*!**************************!*\ !*** ./browser/Utils.js ***! \**************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.getDisplayName = exports.rtrim = exports.parseUsername = exports.resolveInviteLink = exports.parseID = exports.parsePhone = exports.getMessageId = exports.resolveId = exports.getPeerId = exports.sanitizeParseMode = exports.getPeer = exports.getAppropriatedPartSize = exports.getInputMedia = exports.getInputGeo = exports.getAttributes = exports.getExtension = exports.isImage = exports.isAudio = exports.getInputDocument = exports.getInputPhoto = exports.strippedPhotoToJpg = exports.getInputChatPhoto = exports.getInputMessage = exports.getInputUser = exports.getInputChannel = exports.getInnerText = exports._getEntityPair = exports._photoSizeByteCount = exports.getInputPeer = exports.chunks = exports.getFileInfo = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst tl_1 = __webpack_require__(/*! ./tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst mime_1 = __importDefault(__webpack_require__(/*! mime */ "./node_modules/mime/index.js"));\n\nconst markdown_1 = __webpack_require__(/*! ./extensions/markdown */ "./browser/extensions/markdown.js");\n\nfunction getFileInfo(fileLocation) {\n if (!fileLocation || !fileLocation.SUBCLASS_OF_ID) {\n _raiseCastFail(fileLocation, "InputFileLocation");\n }\n\n if (fileLocation.SUBCLASS_OF_ID == 354669666) {\n return {\n dcId: undefined,\n location: fileLocation,\n size: undefined\n };\n }\n\n let location;\n\n if (fileLocation instanceof tl_1.Api.Message) {\n location = fileLocation.media;\n }\n\n if (fileLocation instanceof tl_1.Api.MessageMediaDocument) {\n location = fileLocation.document;\n } else if (fileLocation instanceof tl_1.Api.MessageMediaPhoto) {\n location = fileLocation.photo;\n }\n\n if (location instanceof tl_1.Api.Document) {\n return {\n dcId: location.dcId,\n location: new tl_1.Api.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: ""\n }),\n size: location.size\n };\n } else if (location instanceof tl_1.Api.Photo) {\n return {\n dcId: location.dcId,\n location: new tl_1.Api.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type\n }),\n size: (0, big_integer_1.default)(_photoSizeByteCount(location.sizes[location.sizes.length - 1]) || 0)\n };\n }\n\n _raiseCastFail(fileLocation, "InputFileLocation");\n}\n\nexports.getFileInfo = getFileInfo;\n/**\n * Turns the given iterable into chunks of the specified size,\n * which is 100 by default since that\'s what Telegram uses the most.\n */\n\nfunction* chunks(arr, size = 100) {\n for (let i = 0; i < arr.length; i += size) {\n yield arr.slice(i, i + size);\n }\n}\n\nexports.chunks = chunks;\n\nconst html_1 = __webpack_require__(/*! ./extensions/html */ "./browser/extensions/html.js");\n\nconst Helpers_1 = __webpack_require__(/*! ./Helpers */ "./browser/Helpers.js");\n\nconst USERNAME_RE = new RegExp("@|(?:https?:\\\\/\\\\/)?(?:www\\\\.)?" + "(?:telegram\\\\.(?:me|dog)|t\\\\.me)\\\\/(@|joinchat\\\\/)?", "i");\nconst JPEG_HEADER = buffer_1.Buffer.from("ffd8ffe000104a46494600010100000100010000ffdb004300281c1e231e19282321232d2b28303c64413c37373c7b585d4964918099968f808c8aa0b4e6c3a0aadaad8a8cc8ffcbdaeef5ffffff9bc1fffffffaffe6fdfff8ffdb0043012b2d2d3c353c76414176f8a58ca5f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8f8ffc00011080000000003012200021101031101ffc4001f0000010501010101010100000000000000000102030405060708090a0bffc400b5100002010303020403050504040000017d01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9faffc4001f0100030101010101010101010000000000000102030405060708090a0bffc400b51100020102040403040705040400010277000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9faffda000c03010002110311003f00", "hex");\nconst JPEG_FOOTER = buffer_1.Buffer.from("ffd9", "hex");\nconst TG_JOIN_RE = new RegExp("tg:\\\\/\\\\/(join)\\\\?invite=", "i");\nconst VALID_USERNAME_RE = new RegExp("^([a-z]((?!__)[\\\\w\\\\d]){3,30}[a-z\\\\d]|gif|vid|" + "pic|bing|wiki|imdb|bold|vote|like|coub)$", "i");\n\nfunction _raiseCastFail(entity, target) {\n let toWrite = entity;\n\n if (typeof entity === "object" && "className" in entity) {\n toWrite = entity.className;\n }\n\n throw new Error(`Cannot cast ${toWrite} to any kind of ${target}`);\n}\n/**\n Gets the input peer for the given "entity" (user, chat or channel).\n\n A ``TypeError`` is raised if the given entity isn\'t a supported type\n or if ``check_hash is True`` but the entity\'s ``accessHash is None``\n *or* the entity contains ``min`` information. In this case, the hash\n cannot be used for general purposes, and thus is not returned to avoid\n any issues which can derive from invalid access hashes.\n\n Note that ``checkHash`` **is ignored** if an input peer is already\n passed since in that case we assume the user knows what they\'re doing.\n This is key to getting entities by explicitly passing ``hash = 0``.\n\n * @param entity\n * @param allowSelf\n * @param checkHash\n */\n\n\nfunction getInputPeer(entity, allowSelf = true, checkHash = true) {\n if (entity.SUBCLASS_OF_ID === undefined) {\n // e.g. custom.Dialog (can\'t cyclic import).\n if (allowSelf && "inputEntity" in entity) {\n return entity.inputEntity;\n } else if ("entity" in entity) {\n return getInputPeer(entity.entity);\n } else {\n _raiseCastFail(entity, "InputPeer");\n }\n }\n\n if (entity.SUBCLASS_OF_ID === 0xc91c90b6) {\n // crc32(b\'InputPeer\')\n return entity;\n }\n\n if (entity instanceof tl_1.Api.User) {\n if (entity.self && allowSelf) {\n return new tl_1.Api.InputPeerSelf();\n } else if (entity.accessHash !== undefined && !entity.min || !checkHash) {\n return new tl_1.Api.InputPeerUser({\n userId: entity.id,\n accessHash: entity.accessHash || (0, big_integer_1.default)(0)\n });\n } else {\n throw new Error("User without accessHash or min cannot be input");\n }\n }\n\n if (entity instanceof tl_1.Api.Chat || entity instanceof tl_1.Api.ChatEmpty || entity instanceof tl_1.Api.ChatForbidden) {\n return new tl_1.Api.InputPeerChat({\n chatId: entity.id\n });\n }\n\n if (entity instanceof tl_1.Api.Channel) {\n if (entity.accessHash !== undefined && !entity.min || !checkHash) {\n return new tl_1.Api.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || (0, big_integer_1.default)(0)\n });\n } else {\n throw new TypeError("Channel without accessHash or min info cannot be input");\n }\n }\n\n if (entity instanceof tl_1.Api.ChannelForbidden) {\n // "channelForbidden are never min", and since their hash is\n // also not optional, we assume that this truly is the case.\n return new tl_1.Api.InputPeerChannel({\n channelId: entity.id,\n accessHash: entity.accessHash\n });\n }\n\n if (entity instanceof tl_1.Api.InputUser) {\n return new tl_1.Api.InputPeerUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n });\n }\n\n if (entity instanceof tl_1.Api.InputChannel) {\n return new tl_1.Api.InputPeerChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n });\n }\n\n if (entity instanceof tl_1.Api.UserEmpty) {\n return new tl_1.Api.InputPeerEmpty();\n }\n\n if (entity instanceof tl_1.Api.UserFull) {\n return getInputPeer(entity.id);\n }\n\n if (entity instanceof tl_1.Api.ChatFull) {\n return new tl_1.Api.InputPeerChat({\n chatId: entity.id\n });\n }\n\n if (entity instanceof tl_1.Api.PeerChat) {\n return new tl_1.Api.InputPeerChat({\n chatId: entity.chatId\n });\n }\n\n _raiseCastFail(entity, "InputPeer");\n}\n\nexports.getInputPeer = getInputPeer;\n\nfunction _photoSizeByteCount(size) {\n if (size instanceof tl_1.Api.PhotoSize) {\n return size.size;\n } else if (size instanceof tl_1.Api.PhotoStrippedSize) {\n if (size.bytes.length < 3 || size.bytes[0] != 1) {\n return size.bytes.length;\n }\n\n return size.bytes.length + 622;\n } else if (size instanceof tl_1.Api.PhotoCachedSize) {\n return size.bytes.length;\n } else if (size instanceof tl_1.Api.PhotoSizeEmpty) {\n return 0;\n } else {\n return undefined;\n }\n}\n\nexports._photoSizeByteCount = _photoSizeByteCount;\n\nfunction _getEntityPair(entityId, entities, cache, getInputPeerFunction = getInputPeer) {\n const entity = entities.get(entityId);\n let inputEntity;\n\n try {\n inputEntity = cache.get(entityId);\n } catch (e) {\n try {\n inputEntity = getInputPeerFunction(inputEntity);\n } catch (e) {}\n }\n\n return [entity, inputEntity];\n}\n\nexports._getEntityPair = _getEntityPair;\n\nfunction getInnerText(text, entities) {\n const result = [];\n entities.forEach(function (value, key) {\n const start = value.offset;\n const end = value.offset + value.length;\n result.push(text.slice(start, end));\n });\n return result;\n}\n\nexports.getInnerText = getInnerText;\n/**\n Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`\'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n * @returns {InputChannel|*}\n */\n\nfunction getInputChannel(entity) {\n if (typeof entity === "string" || typeof entity == "number" || typeof entity == "bigint" || big_integer_1.default.isInstance(entity)) {\n _raiseCastFail(entity, "InputChannel");\n }\n\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, "InputChannel");\n }\n\n if (entity.SUBCLASS_OF_ID === 0x40f202fd) {\n // crc32(b\'InputChannel\')\n return entity;\n }\n\n if (entity instanceof tl_1.Api.Channel || entity instanceof tl_1.Api.ChannelForbidden) {\n return new tl_1.Api.InputChannel({\n channelId: entity.id,\n accessHash: entity.accessHash || big_integer_1.default.zero\n });\n }\n\n if (entity instanceof tl_1.Api.InputPeerChannel) {\n return new tl_1.Api.InputChannel({\n channelId: entity.channelId,\n accessHash: entity.accessHash\n });\n }\n\n _raiseCastFail(entity, "InputChannel");\n}\n\nexports.getInputChannel = getInputChannel;\n/**\n Similar to :meth:`getInputPeer`, but for :tl:`InputUser`\'s alone.\n\n .. important::\n\n This method does not validate for invalid general-purpose access\n hashes, unlike `get_input_peer`. Consider using instead:\n ``get_input_channel(get_input_peer(channel))``.\n\n * @param entity\n */\n\nfunction getInputUser(entity) {\n if (typeof entity === "string" || typeof entity == "number" || typeof entity == "bigint" || big_integer_1.default.isInstance(entity)) {\n _raiseCastFail(entity, "InputUser");\n }\n\n if (entity.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(entity, "InputUser");\n }\n\n if (entity.SUBCLASS_OF_ID === 0xe669bf46) {\n // crc32(b\'InputUser\')\n return entity;\n }\n\n if (entity instanceof tl_1.Api.User) {\n if (entity.self) {\n return new tl_1.Api.InputUserSelf();\n } else {\n return new tl_1.Api.InputUser({\n userId: entity.id,\n accessHash: entity.accessHash || big_integer_1.default.zero\n });\n }\n }\n\n if (entity instanceof tl_1.Api.InputPeerSelf) {\n return new tl_1.Api.InputUserSelf();\n }\n\n if (entity instanceof tl_1.Api.UserEmpty || entity instanceof tl_1.Api.InputPeerEmpty) {\n return new tl_1.Api.InputUserEmpty();\n }\n\n if (entity instanceof tl_1.Api.UserFull) {\n return getInputUser(entity);\n }\n\n if (entity instanceof tl_1.Api.InputPeerUser) {\n return new tl_1.Api.InputUser({\n userId: entity.userId,\n accessHash: entity.accessHash\n });\n }\n\n if (entity instanceof tl_1.Api.InputPeerUserFromMessage) {\n return new tl_1.Api.InputUserFromMessage({\n userId: entity.userId,\n peer: entity.peer,\n msgId: entity.msgId\n });\n }\n\n _raiseCastFail(entity, "InputUser");\n}\n\nexports.getInputUser = getInputUser;\n/**\n Similar to :meth:`get_input_peer`, but for dialogs\n * @param dialog\n */\n\n/*CONTEST\nfunction getInputDialog(dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID === 0xa21c9795) { // crc32(b\'InputDialogPeer\')\n return dialog\n }\n if (dialog.SUBCLASS_OF_ID === 0xc91c90b6) { // crc32(b\'InputPeer\')\n return new Api.InputDialogPeer({ peer: dialog })\n }\n } catch (e) {\n _raiseCastFail(dialog, \'InputDialogPeer\')\n }\n\n try {\n return new Api.InputDialogPeer(getInputPeer(dialog))\n // eslint-disable-next-line no-empty\n } catch (e) {\n\n }\n _raiseCastFail(dialog, \'InputDialogPeer\')\n}\n*/\n\n/**\n * Similar to :meth:`get_input_peer`, but for input messages.\n */\n\nfunction getInputMessage(message) {\n if (typeof message === "number") {\n return new tl_1.Api.InputMessageID({\n id: message\n });\n }\n\n if (message === undefined || message.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(message, "InputMessage");\n }\n\n if (message.SUBCLASS_OF_ID === 0x54b6bcc5) {\n // crc32(b\'InputMessage\')\n return message;\n } else if (message.SUBCLASS_OF_ID === 0x790009e3) {\n // crc32(b\'Message\'):\n return new tl_1.Api.InputMessageID({\n id: message.id\n });\n }\n\n _raiseCastFail(message, "InputMessage");\n}\n\nexports.getInputMessage = getInputMessage;\n/**\n * Similar to :meth:`get_input_peer`, but for input messages.\n */\n\nfunction getInputChatPhoto(photo) {\n if (photo === undefined || photo.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(photo, "InputChatPhoto");\n }\n\n if (photo.SUBCLASS_OF_ID === 0xd4eb2d74) {\n //crc32(b\'InputChatPhoto\')\n return photo;\n } else if (photo.SUBCLASS_OF_ID === 0xe7655f1f) {\n // crc32(b\'InputFile\'):\n return new tl_1.Api.InputChatUploadedPhoto({\n file: photo\n });\n }\n\n photo = getInputPhoto(photo);\n\n if (photo instanceof tl_1.Api.InputPhoto) {\n return new tl_1.Api.InputChatPhoto({\n id: photo\n });\n } else if (photo instanceof tl_1.Api.InputPhotoEmpty) {\n return new tl_1.Api.InputChatPhotoEmpty();\n }\n\n _raiseCastFail(photo, "InputChatPhoto");\n}\n\nexports.getInputChatPhoto = getInputChatPhoto;\n/**\n * Adds the JPG header and footer to a stripped image.\n * Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225\n\n * @param stripped{Buffer}\n * @returns {Buffer}\n */\n\nfunction strippedPhotoToJpg(stripped) {\n // Note: Changes here should update _stripped_real_length\n if (stripped.length < 3 || stripped[0] !== 1) {\n return stripped;\n }\n\n const header = buffer_1.Buffer.from(JPEG_HEADER);\n header[164] = stripped[1];\n header[166] = stripped[2];\n return buffer_1.Buffer.concat([header, stripped.slice(3), JPEG_FOOTER]);\n}\n\nexports.strippedPhotoToJpg = strippedPhotoToJpg;\n/*CONTEST\nfunction getInputLocation(location) {\n try {\n if (!location.SUBCLASS_OF_ID) {\n throw new Error()\n }\n if (location.SUBCLASS_OF_ID === 0x1523d462) {\n return {\n dcId: null,\n inputLocation: location\n }\n }\n } catch (e) {\n _raiseCastFail(location, \'InputFileLocation\')\n }\n if (location instanceof Api.Message) {\n location = location.media\n }\n\n if (location instanceof Api.MessageMediaDocument) {\n location = location.document\n } else if (location instanceof Api.MessageMediaPhoto) {\n location = location.photo\n }\n\n if (location instanceof Api.Document) {\n return {\n dcId: location.dcId,\n inputLocation: new Api.InputDocumentFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: \'\', // Presumably to download one of its thumbnails\n }),\n }\n } else if (location instanceof Api.Photo) {\n return {\n dcId: location.dcId,\n inputLocation: new Api.InputPhotoFileLocation({\n id: location.id,\n accessHash: location.accessHash,\n fileReference: location.fileReference,\n thumbSize: location.sizes[location.sizes.length - 1].type,\n }),\n }\n }\n\n if (location instanceof Api.FileLocationToBeDeprecated) {\n throw new Error(\'Unavailable location cannot be used as input\')\n }\n _raiseCastFail(location, \'InputFileLocation\')\n}\n*/\n\n/**\n * Similar to :meth:`get_input_peer`, but for photos\n */\n\nfunction getInputPhoto(photo) {\n if (photo.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(photo, "InputPhoto");\n }\n\n if (photo.SUBCLASS_OF_ID === 2221106144) {\n return photo;\n }\n\n if (photo instanceof tl_1.Api.Message) {\n photo = photo.media;\n }\n\n if (photo instanceof tl_1.Api.photos.Photo || photo instanceof tl_1.Api.MessageMediaPhoto) {\n photo = photo.photo;\n }\n\n if (photo instanceof tl_1.Api.Photo) {\n return new tl_1.Api.InputPhoto({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference\n });\n }\n\n if (photo instanceof tl_1.Api.PhotoEmpty) {\n return new tl_1.Api.InputPhotoEmpty();\n }\n\n if (photo instanceof tl_1.Api.messages.ChatFull) {\n photo = photo.fullChat;\n }\n\n if (photo instanceof tl_1.Api.ChannelFull) {\n return getInputPhoto(photo.chatPhoto);\n } else {\n if (photo instanceof tl_1.Api.UserFull) {\n return getInputPhoto(photo.profilePhoto);\n } else {\n if (photo instanceof tl_1.Api.Channel || photo instanceof tl_1.Api.Chat || photo instanceof tl_1.Api.User) {\n return getInputPhoto(photo.photo);\n }\n }\n }\n\n if (photo instanceof tl_1.Api.UserEmpty || photo instanceof tl_1.Api.ChatEmpty || photo instanceof tl_1.Api.ChatForbidden || photo instanceof tl_1.Api.ChannelForbidden) {\n return new tl_1.Api.InputPhotoEmpty();\n }\n\n _raiseCastFail(photo, "InputPhoto");\n}\n\nexports.getInputPhoto = getInputPhoto;\n/**\n * Similar to :meth:`get_input_peer`, but for documents\n */\n\nfunction getInputDocument(document) {\n if (document.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(document, "InputDocument");\n }\n\n if (document.SUBCLASS_OF_ID === 0xf33fdb68) {\n return document;\n }\n\n if (document instanceof tl_1.Api.Document) {\n return new tl_1.Api.InputDocument({\n id: document.id,\n accessHash: document.accessHash,\n fileReference: document.fileReference\n });\n }\n\n if (document instanceof tl_1.Api.DocumentEmpty) {\n return new tl_1.Api.InputDocumentEmpty();\n }\n\n if (document instanceof tl_1.Api.MessageMediaDocument) {\n return getInputDocument(document.document);\n }\n\n if (document instanceof tl_1.Api.Message) {\n return getInputDocument(document.media);\n }\n\n _raiseCastFail(document, "InputDocument");\n}\n\nexports.getInputDocument = getInputDocument;\n/**\n * Returns `True` if the file has an audio mime type.\n */\n\nfunction isAudio(file) {\n const ext = _getExtension(file);\n\n if (!ext) {\n const metadata = _getMetadata(file);\n\n return (metadata.get("mimeType") || "").startsWith("audio/");\n } else {\n file = "a" + ext;\n return (mime_1.default.getType(file) || "").startsWith("audio/");\n }\n}\n\nexports.isAudio = isAudio;\n/**\n * Returns `True` if the file has an image mime type.\n */\n\nfunction isImage(file) {\n const ext = _getExtension(file).toLowerCase();\n\n return ext.endsWith(".png") || ext.endsWith(".jpg") || ext.endsWith(".jpeg");\n}\n\nexports.isImage = isImage;\n\nfunction getExtension(media) {\n // Photos are always compressed as .jpg by Telegram\n try {\n getInputPhoto(media);\n return ".jpg";\n } catch (e) {}\n\n if (media instanceof tl_1.Api.UserProfilePhoto || media instanceof tl_1.Api.ChatPhoto) {\n return ".jpg";\n }\n\n if (media instanceof tl_1.Api.MessageMediaDocument) {\n media = media.document;\n }\n\n if (media instanceof tl_1.Api.Document || media instanceof tl_1.Api.WebDocument || media instanceof tl_1.Api.WebDocumentNoProxy) {\n if (media.mimeType === "application/octet-stream") {\n // Octet stream are just bytes, which have no default extension\n return "";\n } else {\n return mime_1.default.getExtension(media.mimeType) || "";\n }\n }\n\n return "";\n}\n\nexports.getExtension = getExtension;\n/**\n * Gets the extension for the given file, which can be either a\n * str or an ``open()``\'ed file (which has a ``.name`` attribute).\n */\n\nfunction _getExtension(file) {\n if (typeof file === "string") {\n return "." + file.split(".").pop();\n } else if ("name" in file) {\n return _getExtension(file.name);\n } else {\n return getExtension(file);\n }\n}\n\nfunction _getMetadata(file) {\n //TODO Return nothing for now until we find a better way\n return new Map();\n}\n\nfunction isVideo(file) {\n var _a;\n\n const ext = _getExtension(file);\n\n if (!ext) {\n const metadata = _getMetadata(file);\n\n if (metadata.has("mimeType")) {\n return ((_a = metadata.get("mimeType")) === null || _a === void 0 ? void 0 : _a.startsWith("video/")) || false;\n } else {\n return false;\n }\n } else {\n file = "a" + ext;\n return (mime_1.default.getType(file) || "").startsWith("video/");\n }\n}\n/**\n Get a list of attributes for the given file and\n the mime type as a tuple ([attribute], mime_type).\n */\n\n\nfunction getAttributes(file, {\n attributes = null,\n mimeType = undefined,\n forceDocument = false,\n voiceNote = false,\n videoNote = false,\n supportsStreaming = false,\n thumb = null\n}) {\n var _a, _b, _c, _d;\n\n const name = typeof file == "string" ? file : file.name || "unnamed";\n\n if (mimeType === undefined) {\n mimeType = mime_1.default.getType(name) || "application/octet-stream";\n }\n\n const attrObj = new Map();\n attrObj.set(tl_1.Api.DocumentAttributeFilename, new tl_1.Api.DocumentAttributeFilename({\n fileName: name.split(/[\\\\/]/).pop() || ""\n }));\n\n if (isAudio(file)) {\n const m = _getMetadata(file);\n\n attrObj.set(tl_1.Api.DocumentAttributeAudio, new tl_1.Api.DocumentAttributeAudio({\n voice: voiceNote,\n title: m.has("title") ? m.get("title") : undefined,\n performer: m.has("author") ? m.get("author") : undefined,\n duration: Number.parseInt((_a = m.get("duration")) !== null && _a !== void 0 ? _a : "0")\n }));\n }\n\n if (!forceDocument && isVideo(file)) {\n let doc;\n\n if (thumb) {\n const t_m = _getMetadata(thumb);\n\n const width = Number.parseInt((t_m === null || t_m === void 0 ? void 0 : t_m.get("width")) || "1");\n const height = Number.parseInt((t_m === null || t_m === void 0 ? void 0 : t_m.get("height")) || "1");\n doc = new tl_1.Api.DocumentAttributeVideo({\n duration: 0,\n h: height,\n w: width,\n roundMessage: videoNote,\n supportsStreaming: supportsStreaming\n });\n } else {\n const m = _getMetadata(file);\n\n doc = new tl_1.Api.DocumentAttributeVideo({\n roundMessage: videoNote,\n w: Number.parseInt((_b = m.get("width")) !== null && _b !== void 0 ? _b : "1"),\n h: Number.parseInt((_c = m.get("height")) !== null && _c !== void 0 ? _c : "1"),\n duration: Number.parseInt((_d = m.get("duration")) !== null && _d !== void 0 ? _d : "0"),\n supportsStreaming: supportsStreaming\n });\n }\n\n attrObj.set(tl_1.Api.DocumentAttributeVideo, doc);\n }\n\n if (videoNote) {\n if (attrObj.has(tl_1.Api.DocumentAttributeAudio)) {\n attrObj.get(tl_1.Api.DocumentAttributeAudio).voice = true;\n } else {\n attrObj.set(tl_1.Api.DocumentAttributeAudio, new tl_1.Api.DocumentAttributeAudio({\n duration: 0,\n voice: true\n }));\n }\n }\n /* Now override the attributes if any. As we have a dict of\n {cls: instance}, we can override any class with the list\n of attributes provided by the user easily.\n */\n\n\n if (attributes) {\n for (const a of attributes) {\n attrObj.set(a.constructor, a);\n }\n }\n\n return {\n attrs: Array.from(attrObj.values()),\n mimeType: mimeType\n };\n}\n\nexports.getAttributes = getAttributes;\n/**\n * Similar to :meth:`get_input_peer`, but for geo points\n */\n\nfunction getInputGeo(geo) {\n if (geo === undefined || geo.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(geo, "InputGeoPoint");\n }\n\n if (geo.SUBCLASS_OF_ID === 0x430d225) {\n // crc32(b\'InputGeoPoint\'):\n return geo;\n }\n\n if (geo instanceof tl_1.Api.GeoPoint) {\n return new tl_1.Api.InputGeoPoint({\n lat: geo.lat,\n long: geo.long\n });\n }\n\n if (geo instanceof tl_1.Api.GeoPointEmpty) {\n return new tl_1.Api.InputGeoPointEmpty();\n }\n\n if (geo instanceof tl_1.Api.MessageMediaGeo) {\n return getInputGeo(geo.geo);\n }\n\n if (geo instanceof tl_1.Api.Message) {\n return getInputGeo(geo.media);\n }\n\n _raiseCastFail(geo, "InputGeoPoint");\n}\n\nexports.getInputGeo = getInputGeo;\n/**\n *\n Similar to :meth:`get_input_peer`, but for media.\n\n If the media is :tl:`InputFile` and ``is_photo`` is known to be `True`,\n it will be treated as an :tl:`InputMediaUploadedPhoto`. Else, the rest\n of parameters will indicate how to treat it.\n * @param media\n * @param isPhoto - whether it\'s a photo or not\n * @param attributes\n * @param forceDocument\n * @param voiceNote\n * @param videoNote\n * @param supportsStreaming\n */\n\nfunction getInputMedia(media, {\n isPhoto = false,\n attributes = undefined,\n forceDocument = false,\n voiceNote = false,\n videoNote = false,\n supportsStreaming = false\n} = {}) {\n if (media.SUBCLASS_OF_ID === undefined) {\n _raiseCastFail(media, "InputMedia");\n }\n\n if (media.SUBCLASS_OF_ID === 0xfaf846f4) {\n // crc32(b\'InputMedia\')\n return media;\n } else {\n if (media.SUBCLASS_OF_ID === 2221106144) {\n // crc32(b\'InputPhoto\')\n return new tl_1.Api.InputMediaPhoto({\n id: media\n });\n } else {\n if (media.SUBCLASS_OF_ID === 4081048424) {\n // crc32(b\'InputDocument\')\n return new tl_1.Api.InputMediaDocument({\n id: media\n });\n }\n }\n }\n\n if (media instanceof tl_1.Api.MessageMediaPhoto) {\n return new tl_1.Api.InputMediaPhoto({\n id: getInputPhoto(media.photo),\n ttlSeconds: media.ttlSeconds\n });\n }\n\n if (media instanceof tl_1.Api.Photo || media instanceof tl_1.Api.photos.Photo || media instanceof tl_1.Api.PhotoEmpty) {\n return new tl_1.Api.InputMediaPhoto({\n id: getInputPhoto(media)\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaDocument) {\n return new tl_1.Api.InputMediaDocument({\n id: getInputDocument(media.document),\n ttlSeconds: media.ttlSeconds\n });\n }\n\n if (media instanceof tl_1.Api.Document || media instanceof tl_1.Api.DocumentEmpty) {\n return new tl_1.Api.InputMediaDocument({\n id: getInputDocument(media)\n });\n }\n\n if (media instanceof tl_1.Api.InputFile || media instanceof tl_1.Api.InputFileBig) {\n if (isPhoto) {\n return new tl_1.Api.InputMediaUploadedPhoto({\n file: media\n });\n } else {\n const {\n attrs,\n mimeType\n } = getAttributes(media, {\n attributes: attributes,\n forceDocument: forceDocument,\n voiceNote: voiceNote,\n videoNote: videoNote,\n supportsStreaming: supportsStreaming\n });\n return new tl_1.Api.InputMediaUploadedDocument({\n file: media,\n mimeType: mimeType,\n attributes: attrs,\n forceFile: forceDocument\n });\n }\n }\n\n if (media instanceof tl_1.Api.MessageMediaGame) {\n return new tl_1.Api.InputMediaGame({\n id: new tl_1.Api.InputGameID({\n id: media.game.id,\n accessHash: media.game.accessHash\n })\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaContact) {\n return new tl_1.Api.InputMediaContact({\n phoneNumber: media.phoneNumber,\n firstName: media.firstName,\n lastName: media.lastName,\n vcard: ""\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaGeo) {\n return new tl_1.Api.InputMediaGeoPoint({\n geoPoint: getInputGeo(media.geo)\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaVenue) {\n return new tl_1.Api.InputMediaVenue({\n geoPoint: getInputGeo(media.geo),\n title: media.title,\n address: media.address,\n provider: media.provider,\n venueId: media.venueId,\n venueType: ""\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaDice) {\n return new tl_1.Api.InputMediaDice({\n emoticon: media.emoticon\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaEmpty || media instanceof tl_1.Api.MessageMediaUnsupported || media instanceof tl_1.Api.ChatPhotoEmpty || media instanceof tl_1.Api.UserProfilePhotoEmpty || media instanceof tl_1.Api.ChatPhoto || media instanceof tl_1.Api.UserProfilePhoto) {\n return new tl_1.Api.InputMediaEmpty();\n }\n\n if (media instanceof tl_1.Api.Message) {\n return getInputMedia(media.media, {\n isPhoto: isPhoto\n });\n }\n\n if (media instanceof tl_1.Api.MessageMediaPoll) {\n let correctAnswers;\n\n if (media.poll.quiz) {\n if (!media.results.results) {\n throw new Error("Cannot cast unanswered quiz to any kind of InputMedia.");\n }\n\n correctAnswers = [];\n\n for (const r of media.results.results) {\n if (r.correct) {\n correctAnswers.push(r.option);\n }\n }\n } else {\n correctAnswers = undefined;\n }\n\n return new tl_1.Api.InputMediaPoll({\n poll: media.poll,\n correctAnswers: correctAnswers,\n solution: media.results.solution,\n solutionEntities: media.results.solutionEntities\n });\n }\n\n if (media instanceof tl_1.Api.Poll) {\n return new tl_1.Api.InputMediaPoll({\n poll: media\n });\n }\n\n _raiseCastFail(media, "InputMedia");\n}\n\nexports.getInputMedia = getInputMedia;\n/**\n * Gets the appropriated part size when uploading or downloading files,\n * given an initial file size.\n * @param fileSize\n * @returns {Number}\n */\n\nfunction getAppropriatedPartSize(fileSize) {\n if (fileSize.lesser(104857600)) {\n // 100MB\n return 128;\n }\n\n if (fileSize.lesser(786432000)) {\n // 750MB\n return 256;\n }\n\n return 512;\n}\n\nexports.getAppropriatedPartSize = getAppropriatedPartSize;\n\nfunction getPeer(peer) {\n if (!peer) {\n _raiseCastFail(peer, "undefined");\n }\n\n if (typeof peer === "string") {\n _raiseCastFail(peer, "peer");\n }\n\n if (typeof peer == "number" || typeof peer == "bigint") {\n peer = (0, Helpers_1.returnBigInt)(peer);\n }\n\n try {\n if (big_integer_1.default.isInstance(peer)) {\n const res = resolveId(peer);\n\n if (res[1] === tl_1.Api.PeerChannel) {\n return new tl_1.Api.PeerChannel({\n channelId: res[0]\n });\n } else if (res[1] === tl_1.Api.PeerChat) {\n return new tl_1.Api.PeerChat({\n chatId: res[0]\n });\n } else {\n return new tl_1.Api.PeerUser({\n userId: res[0]\n });\n }\n }\n\n if (peer.SUBCLASS_OF_ID === undefined) {\n throw new Error();\n }\n\n if (peer.SUBCLASS_OF_ID === 0x2d45687) {\n // crc32(\'Peer\')\n return peer;\n } else if (peer instanceof tl_1.Api.contacts.ResolvedPeer || peer instanceof tl_1.Api.InputNotifyPeer || peer instanceof tl_1.Api.TopPeer || peer instanceof tl_1.Api.Dialog || peer instanceof tl_1.Api.DialogPeer) {\n return peer.peer;\n } else if (peer instanceof tl_1.Api.ChannelFull) {\n return new tl_1.Api.PeerChannel({\n channelId: peer.id\n });\n }\n\n if (peer.SUBCLASS_OF_ID === 0x7d7c6f86 || peer.SUBCLASS_OF_ID === 0xd9c7fc18) {\n // ChatParticipant, ChannelParticipant\n if ("userId" in peer) {\n return new tl_1.Api.PeerUser({\n userId: peer.userId\n });\n }\n }\n\n peer = getInputPeer(peer, false, false);\n\n if (peer instanceof tl_1.Api.InputPeerUser) {\n return new tl_1.Api.PeerUser({\n userId: peer.userId\n });\n } else if (peer instanceof tl_1.Api.InputPeerChat) {\n return new tl_1.Api.PeerChat({\n chatId: peer.chatId\n });\n } else if (peer instanceof tl_1.Api.InputPeerChannel) {\n return new tl_1.Api.PeerChannel({\n channelId: peer.channelId\n });\n }\n } catch (e) {}\n\n _raiseCastFail(peer, "peer");\n}\n\nexports.getPeer = getPeer;\n\nfunction sanitizeParseMode(mode) {\n if (mode === "md" || mode === "markdown") {\n return markdown_1.MarkdownParser;\n }\n\n if (mode == "html") {\n return html_1.HTMLParser;\n }\n\n if (typeof mode == "object") {\n if ("parse" in mode && "unparse" in mode) {\n return mode;\n }\n }\n\n throw new Error(`Invalid parse mode type ${mode}`);\n}\n\nexports.sanitizeParseMode = sanitizeParseMode;\n/**\n Convert the given peer into its marked ID by default.\n\n This "mark" comes from the "bot api" format, and with it the peer type\n can be identified back. User ID is left unmodified, chat ID is negated,\n and channel ID is prefixed with -100:\n\n * ``userId``\n * ``-chatId``\n * ``-100channel_id``\n\n The original ID and the peer type class can be returned with\n a call to :meth:`resolve_id(marked_id)`.\n * @param peer\n * @param addMark\n */\n\nfunction getPeerId(peer, addMark = true) {\n if (typeof peer == "string" && parseID(peer)) {\n peer = (0, Helpers_1.returnBigInt)(peer);\n } // First we assert it\'s a Peer TLObject, or early return for integers\n\n\n if (big_integer_1.default.isInstance(peer)) {\n return addMark ? peer.toString() : resolveId(peer)[0].toString();\n } // Tell the user to use their client to resolve InputPeerSelf if we got one\n\n\n if (peer instanceof tl_1.Api.InputPeerSelf) {\n _raiseCastFail(peer, "int (you might want to use client.get_peer_id)");\n }\n\n try {\n peer = getPeer(peer);\n } catch (e) {\n _raiseCastFail(peer, "int");\n }\n\n if (peer instanceof tl_1.Api.PeerUser) {\n return peer.userId.toString();\n } else if (peer instanceof tl_1.Api.PeerChat) {\n // Check in case the user mixed things up to avoid blowing up\n peer.chatId = resolveId((0, Helpers_1.returnBigInt)(peer.chatId))[0];\n return addMark ? peer.chatId.negate().toString() : peer.chatId.toString();\n } else if (typeof peer == "object" && "channelId" in peer) {\n // if (peer instanceof Api.PeerChannel)\n // Check in case the user mixed things up to avoid blowing up\n peer.channelId = resolveId((0, Helpers_1.returnBigInt)(peer.channelId))[0];\n\n if (!addMark) {\n return peer.channelId.toString();\n } // Concat -100 through math tricks, .to_supergroup() on\n // Madeline IDs will be strictly positive -> log works.\n\n\n return "-100" + peer.channelId.toString();\n }\n\n _raiseCastFail(peer, "int");\n}\n\nexports.getPeerId = getPeerId;\n/**\n * Given a marked ID, returns the original ID and its :tl:`Peer` type.\n * @param markedId\n */\n\nfunction resolveId(markedId) {\n if (markedId.greaterOrEquals(big_integer_1.default.zero)) {\n return [markedId, tl_1.Api.PeerUser];\n } // There have been report of chat IDs being 10000xyz, which means their\n // marked version is -10000xyz, which in turn looks like a channel but\n // it becomes 00xyz (= xyz). Hence, we must assert that there are only\n // two zeroes.\n\n\n const m = markedId.toString().match(/-100([^0]\\d*)/);\n\n if (m) {\n return [(0, big_integer_1.default)(m[1]), tl_1.Api.PeerChannel];\n }\n\n return [markedId.negate(), tl_1.Api.PeerChat];\n}\n\nexports.resolveId = resolveId;\n/**\n * returns an entity pair\n * @param entityId\n * @param entities\n * @param cache\n * @param getInputPeer\n * @returns {{inputEntity: *, entity: *}}\n * @private\n */\n\n/*CONTEST\n\nexport function _getEntityPair(entityId, entities, cache, getInputPeer = getInputPeer) {\n const entity = entities.get(entityId)\n let inputEntity = cache[entityId]\n if (inputEntity === undefined) {\n try {\n inputEntity = getInputPeer(inputEntity)\n } catch (e) {\n inputEntity = null\n }\n }\n return {\n entity,\n inputEntity\n }\n}\n*/\n\nfunction getMessageId(message) {\n if (!message) {\n return undefined;\n } else if (typeof message === "number") {\n return message;\n } else if (message.SUBCLASS_OF_ID === 0x790009e3 || "id" in message) {\n // crc32(b\'Message\')\n return message.id;\n } else {\n throw new Error(`Invalid message type: ${message.constructor.name}`);\n }\n}\n\nexports.getMessageId = getMessageId;\n/**\n * Parses the given phone, or returns `undefined` if it\'s invalid.\n * @param phone\n */\n\nfunction parsePhone(phone) {\n phone = phone.toString().replace(/[()\\s-]/gm, "");\n\n if (phone.startsWith("+") && phone.split("+").length - 1 == 1) {\n return !isNaN(Number(phone)) ? phone.replace("+", "") : undefined;\n }\n}\n\nexports.parsePhone = parsePhone;\n/**\n * Parses a string ID into a big int\n * @param id\n */\n\nfunction parseID(id) {\n const isValid = /^(-?[0-9][0-9]*)$/.test(id);\n return isValid ? (0, big_integer_1.default)(id) : undefined;\n}\n\nexports.parseID = parseID;\n\nfunction resolveInviteLink(link) {\n throw new Error("not implemented");\n}\n\nexports.resolveInviteLink = resolveInviteLink;\n/**\n Parses the given username or channel access hash, given\n a string, username or URL. Returns a tuple consisting of\n both the stripped, lowercase username and whether it is\n a joinchat/ hash (in which case is not lowercase\'d).\n\n Returns ``(undefined, false)`` if the ``username`` or link is not valid.\n\n * @param username {string}\n */\n\nfunction parseUsername(username) {\n username = username.trim();\n const m = username.match(USERNAME_RE) || username.match(TG_JOIN_RE);\n\n if (m) {\n username = username.replace(m[0], "");\n\n if (m[1]) {\n return {\n username: username,\n isInvite: true\n };\n } else {\n username = rtrim(username, "/");\n }\n }\n\n if (username.match(VALID_USERNAME_RE)) {\n return {\n username: username.toLowerCase(),\n isInvite: false\n };\n } else {\n return {\n username: undefined,\n isInvite: false\n };\n }\n}\n\nexports.parseUsername = parseUsername;\n\nfunction rtrim(s, mask) {\n while (~mask.indexOf(s[s.length - 1])) {\n s = s.slice(0, -1);\n }\n\n return s;\n}\n\nexports.rtrim = rtrim;\n/**\n * Gets the display name for the given :tl:`User`,\n :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise\n * @param entity\n */\n\nfunction getDisplayName(entity) {\n if (entity instanceof tl_1.Api.User) {\n if (entity.lastName && entity.firstName) {\n return `${entity.firstName} ${entity.lastName}`;\n } else if (entity.firstName) {\n return entity.firstName;\n } else if (entity.lastName) {\n return entity.lastName;\n } else {\n return "";\n }\n } else if (entity instanceof tl_1.Api.Chat || entity instanceof tl_1.Api.Channel) {\n return entity.title;\n }\n\n return "";\n}\n\nexports.getDisplayName = getDisplayName;\n/**\n * check if a given item is an array like or not\n * @param item\n * @returns {boolean}\n */\n\n/*CONTEST\nDuplicate ?\nexport function isListLike(item) {\n return (\n Array.isArray(item) ||\n (!!item &&\n typeof item === \'object\' &&\n typeof (item.length) === \'number\' &&\n (item.length === 0 ||\n (item.length > 0 &&\n (item.length - 1) in item)\n )\n )\n )\n}\n*/\n\n//# sourceURL=webpack://telegram/./browser/Utils.js?')},"./browser/Version.js": /*!****************************!*\ !*** ./browser/Version.js ***! \****************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.version = void 0;\nexports.version = "2.17.0";\n\n//# sourceURL=webpack://telegram/./browser/Version.js?')},"./browser/client/2fa.js": /*!*******************************!*\ !*** ./browser/client/2fa.js ***! \*******************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.updateTwoFaSettings = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst Password_1 = __webpack_require__(/*! ../Password */ "./browser/Password.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n/**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n\n Has no effect if both current and new password are omitted.\n\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n * @param onEmailCodeError: Called when an error happens while sending an email.\n\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n\n * @returns Promise\n * @throws this method can throw:\n "PASSWORD_HASH_INVALID" if you entered a wrong password (or set it to undefined).\n "EMAIL_INVALID" if the entered email is wrong\n "EMAIL_HASH_EXPIRED" if the user took too long to verify their email\n */\n\n\nasync function updateTwoFaSettings(client, {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = "",\n email,\n emailCodeCallback,\n onEmailCodeError\n}) {\n if (!newPassword && !currentPassword) {\n throw new Error("Neither `currentPassword` nor `newPassword` is present");\n }\n\n if (email && !(emailCodeCallback && onEmailCodeError)) {\n throw new Error("`email` present without `emailCodeCallback` and `onEmailCodeError`");\n }\n\n const pwd = await client.invoke(new tl_1.Api.account.GetPassword());\n\n if (!(pwd.newAlgo instanceof tl_1.Api.PasswordKdfAlgoUnknown)) {\n pwd.newAlgo.salt1 = buffer_1.Buffer.concat([pwd.newAlgo.salt1, (0, Helpers_1.generateRandomBytes)(32)]);\n }\n\n if (!pwd.hasPassword && currentPassword) {\n currentPassword = undefined;\n }\n\n const password = currentPassword ? await (0, Password_1.computeCheck)(pwd, currentPassword) : new tl_1.Api.InputCheckPasswordEmpty();\n\n if (isCheckPassword) {\n await client.invoke(new tl_1.Api.auth.CheckPassword({\n password\n }));\n return;\n }\n\n if (pwd.newAlgo instanceof tl_1.Api.PasswordKdfAlgoUnknown) {\n throw new Error("Unknown password encryption method");\n }\n\n try {\n await client.invoke(new tl_1.Api.account.UpdatePasswordSettings({\n password,\n newSettings: new tl_1.Api.account.PasswordInputSettings({\n newAlgo: pwd.newAlgo,\n newPasswordHash: newPassword ? await (0, Password_1.computeDigest)(pwd.newAlgo, newPassword) : buffer_1.Buffer.alloc(0),\n hint,\n email,\n // not explained what it does and it seems to always be set to empty in tdesktop\n newSecureSettings: undefined\n })\n }));\n } catch (e) {\n if (e instanceof index_1.errors.EmailUnconfirmedError) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const code = await emailCodeCallback(e.codeLength);\n\n if (!code) {\n throw new Error("Code is empty");\n }\n\n await client.invoke(new tl_1.Api.account.ConfirmPasswordEmail({\n code\n }));\n break;\n } catch (err) {\n onEmailCodeError(err);\n }\n }\n } else {\n throw e;\n }\n }\n}\n\nexports.updateTwoFaSettings = updateTwoFaSettings;\n\n//# sourceURL=webpack://telegram/./browser/client/2fa.js?')},"./browser/client/TelegramClient.js": /*!******************************************!*\ !*** ./browser/client/TelegramClient.js ***! \******************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.TelegramClient = void 0;\n\nconst telegramBaseClient_1 = __webpack_require__(/*! ./telegramBaseClient */ "./browser/client/telegramBaseClient.js");\n\nconst authMethods = __importStar(__webpack_require__(/*! ./auth */ "./browser/client/auth.js"));\n\nconst botMethods = __importStar(__webpack_require__(/*! ./bots */ "./browser/client/bots.js"));\n\nconst buttonsMethods = __importStar(__webpack_require__(/*! ./buttons */ "./browser/client/buttons.js"));\n\nconst downloadMethods = __importStar(__webpack_require__(/*! ./downloads */ "./browser/client/downloads.js"));\n\nconst parseMethods = __importStar(__webpack_require__(/*! ./messageParse */ "./browser/client/messageParse.js"));\n\nconst messageMethods = __importStar(__webpack_require__(/*! ./messages */ "./browser/client/messages.js"));\n\nconst updateMethods = __importStar(__webpack_require__(/*! ./updates */ "./browser/client/updates.js"));\n\nconst uploadMethods = __importStar(__webpack_require__(/*! ./uploads */ "./browser/client/uploads.js"));\n\nconst userMethods = __importStar(__webpack_require__(/*! ./users */ "./browser/client/users.js"));\n\nconst chatMethods = __importStar(__webpack_require__(/*! ./chats */ "./browser/client/chats.js"));\n\nconst dialogMethods = __importStar(__webpack_require__(/*! ./dialogs */ "./browser/client/dialogs.js"));\n\nconst twoFA = __importStar(__webpack_require__(/*! ./2fa */ "./browser/client/2fa.js"));\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst network_1 = __webpack_require__(/*! ../network */ "./browser/network/index.js");\n\nconst AllTLObjects_1 = __webpack_require__(/*! ../tl/AllTLObjects */ "./browser/tl/AllTLObjects.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst updates_1 = __webpack_require__(/*! ./updates */ "./browser/client/updates.js");\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js");\n\nconst inspect_1 = __webpack_require__(/*! ../inspect */ "./browser/inspect.js");\n\nconst platform_1 = __webpack_require__(/*! ../platform */ "./browser/platform.js");\n/**\n * The TelegramClient uses several methods in different files to provide all the common functionality in a nice interface.
\n * **In short, to create a client you must do:**\n *\n * ```ts\n * import {TelegramClient} from "telegram";\n *\n * const client = new TelegramClient(new StringSession(\'\'),apiId,apiHash,{});\n * ```\n *\n * You don\'t need to import any methods that are inside the TelegramClient class as they binding in it.\n */\n\n\nclass TelegramClient extends telegramBaseClient_1.TelegramBaseClient {\n /**\n * @param session - a session to be used to save the connection and auth key to. This can be a custom session that inherits MemorySession.\n * @param apiId - The API ID you obtained from https://my.telegram.org.\n * @param apiHash - The API hash you obtained from https://my.telegram.org.\n * @param clientParams - see {@link TelegramClientParams}\n */\n constructor(session, apiId, apiHash, clientParams) {\n super(session, apiId, apiHash, clientParams);\n } // region auth\n\n /**\n * Used to handle all aspects of connecting to telegram.
\n * This method will connect to the telegram servers and check if the user is already logged in.
\n * in the case of a new connection this will sign in if the phone already exists or sign up otherwise
\n * By using this method you are **agreeing to Telegram\'s Terms of Service** https://core.telegram.org/api/terms.
\n * this method also calls {@link getMe} to tell telegram that we want to receive updates.
\n * @param authParams - see UserAuthParams and BotAuthParams\n * @return nothing\n * @example\n * ```ts\n * // this example assumes you\'ve installed and imported the input package. npm i input.\n * // This package uses CLI to receive input from the user. you can use your own callback function.\n * import { TelegramClient } from "telegram";\n * import { StringSession } from "telegram/sessions";\n *\n * const client = new TelegramClient(new StringSession(\'\'), apiId, apiHash, {});\n * // logging in as a bot account\n * await client.start(botToken="123456:abcdfgh123456789);\n * // logging in as a user account\n * await client.start({\n * phoneNumber: async () => await input.text("number ?"),\n * password: async () => await input.text("password?"),\n * phoneCode: async () => await input.text("Code ?"),\n * onError: (err) => console.log(err),\n * });\n * >Number ? +1234567897\n * >Code ? 12345\n * >password ? 111111\n * Logged in as user...\n *\n * You can now use the client instance to call other api requests.\n */\n\n\n start(authParams) {\n return authMethods.start(this, authParams);\n }\n /**\n * Checks whether the current client is authorized or not. (logged in as a user)\n * @example\n * ```ts\n * await client.connect();\n * if (await client.checkAuthorization()){\n * console.log("I am logged in!");\n * }else{\n * console.log("I am connected to telegram servers but not logged in with any account/bot");\n * }\n * ```\n * @return boolean (true of authorized else false)\n */\n\n\n checkAuthorization() {\n return authMethods.checkAuthorization(this);\n }\n /**\n * Logs in as a user. Should only be used when not already logged in.
\n * This method will send a code when needed.
\n * This will also sign up if needed.\n * @example\n * ```ts\n * await client.connect();\n * // we should only use this when we are not already authorized.\n * // This function is very similar to `client.start`\n * // The minor difference that start checks if already authorized and supports bots as well.\n * if (!await client.checkAuthorization()){\n * const phoneNumber = "+123456789";\n * await client.signIn({\n * apiId:132456,\n * apiHash:"132456",\n * },{\n * phoneNumber: async () => await input.text("number ?"),\n * password: async () => await input.text("password?"),\n * phoneCode: async () => await input.text("Code ?"),\n * onError: (err) => console.log(err),\n * })\n * }\n * ```\n * @param apiCredentials - credentials to be used.\n * @param authParams - user auth params.\n */\n\n\n signInUser(apiCredentials, authParams) {\n return authMethods.signInUser(this, apiCredentials, authParams);\n }\n /**\n * logs the user using a QR code to be scanned.
\n * this function generates the QR code that needs to be scanned by mobile.\n * @example\n * \'\'\'ts\n * await client.connect();\n * const user = await client.signInUserWithQrCode({ apiId, apiHash },\n * {\n * onError: async function(p1: Error) {\n * console.log("error", p1);\n * // true = stop the authentication processes\n * return true;\n * },\n * qrCode: async (code) => {\n * console.log("Convert the next string to a QR code and scan it");\n * console.log(\n * `tg://login?token=${code.token.toString("base64url")}`\n * );\n * },\n * password: async (hint) => {\n * // password if needed\n * return "1111";\n * }\n * }\n * );\n * console.log("user is", user);\n *\n * \'\'\'\n * @param apiCredentials - credentials to be used.\n * @param authParams - user auth params.\n */\n\n\n signInUserWithQrCode(apiCredentials, authParams) {\n return authMethods.signInUserWithQrCode(this, apiCredentials, authParams);\n }\n /**\n * Sends a telegram authentication code to the phone number.\n * @example\n * ```ts\n * await client.connect();\n * const {phoneCodeHash,isCodeViaApp} = await client.sendCode({\n * apiId:1234,\n * apiHash:"123456789abcfghj",\n * },"+123456798"});\n * ```\n * @param apiCredentials - credentials to be used.\n * @param phoneNumber - the phone number to send the code to\n * @param forceSMS - whether to send it as an SMS or a normal in app message\n * @return the phone code hash and whether it was sent via app\n */\n\n\n sendCode(apiCredentials, phoneNumber, forceSMS = false) {\n return authMethods.sendCode(this, apiCredentials, phoneNumber, forceSMS);\n }\n /**\n * Uses the 2FA password to sign in the account.
\n * This function should be used after the user has signed in with the code they received.\n * @param apiCredentials - credentials to be used.\n * @param authParams - user auth params.\n * @returns the logged in user.\n */\n\n\n signInWithPassword(apiCredentials, authParams) {\n return authMethods.signInWithPassword(this, apiCredentials, authParams);\n }\n /**\n * Used to sign in as a bot.\n * @example\n * ```ts\n * await client.connect();\n * const bot = await client.signInBot({\n * apiId:1234,\n * apiHash:"12345",\n * },{\n * botToken:"123456:abcdfghae4fg654",\n * });\n * // we are now logged in as a bot\n * console.log("Logged in",bot);\n * ```\n * @param apiCredentials - credentials to be used.\n * @param authParams - user auth params.\n * @return instance User of the logged in bot.\n */\n\n\n signInBot(apiCredentials, authParams) {\n return authMethods.signInBot(this, apiCredentials, authParams);\n }\n /**\n * Changes the 2FA settings of the logged in user.\n Note that this method may be *incredibly* slow depending on the\n prime numbers that must be used during the process to make sure\n that everything is safe.\n Has no effect if both current and new password are omitted.\n * @param client: The telegram client instance\n * @param isCheckPassword: Must be ``true`` if you want to check the current password\n * @param currentPassword: The current password, to authorize changing to ``new_password``.\n Must be set if changing existing 2FA settings.\n Must **not** be set if 2FA is currently disabled.\n Passing this by itself will remove 2FA (if correct).\n * @param newPassword: The password to set as 2FA.\n If 2FA was already enabled, ``currentPassword`` **must** be set.\n Leaving this blank or `undefined` will remove the password.\n * @param hint: Hint to be displayed by Telegram when it asks for 2FA.\n Must be set when changing or creating a new password.\n Has no effect if ``newPassword`` is not set.\n * @param email: Recovery and verification email. If present, you must also\n set `emailCodeCallback`, else it raises an Error.\n * @param emailCodeCallback: If an email is provided, a callback that returns the code sent\n to it must also be set. This callback may be asynchronous.\n It should return a string with the code. The length of the\n code will be passed to the callback as an input parameter.\n * @param onEmailCodeError: Called when an error happens while sending an email.\n If the callback returns an invalid code, it will raise an rpc error with the message\n ``CODE_INVALID``\n * @returns Promise\n * @throws this method can throw:\n "PASSWORD_HASH_INVALID" if you entered a wrong password (or set it to undefined).\n "EMAIL_INVALID" if the entered email is wrong\n "EMAIL_HASH_EXPIRED" if the user took too long to verify their email\n */\n\n\n async updateTwoFaSettings({\n isCheckPassword,\n currentPassword,\n newPassword,\n hint = "",\n email,\n emailCodeCallback,\n onEmailCodeError\n }) {\n return twoFA.updateTwoFaSettings(this, {\n isCheckPassword,\n currentPassword,\n newPassword,\n hint,\n email,\n emailCodeCallback,\n onEmailCodeError\n });\n } //endregion auth\n //region bot\n\n /**\n * Makes an inline query to the specified bot and gets the result list.
\n * This is equivalent to writing `@pic something` in clients\n * @param bot - the bot entity to which the inline query should be made\n * @param query - the query string that should be made for that bot (up to 512 characters). can be empty\n * @param entity - The entity where the inline query is being made from.
\n * Certain bots use this to display different results depending on where it\'s used, such as private chats, groups or channels.
\n * If specified, it will also be the default entity where the message will be sent after clicked.
\n * Otherwise, the “empty peer” will be used, which some bots may not handle correctly.\n * @param offset - String offset of the results to be returned. can be empty\n * @param geoPoint - The geo point location information to send to the bot for localised results. Available under some bots.\n * @return a list of InlineResults\n * @example\n * ```ts\n * // Makes the query to @pic\n * const results = await client.inlineQuery("pic", "something");\n * // clicks on the first result\n * await results[0].click();\n * ```\n */\n\n\n inlineQuery(bot, query, entity, offset, geoPoint) {\n return botMethods.inlineQuery(this, bot, query, entity, offset, geoPoint);\n } //endregion\n //region buttons\n\n /**\n * Builds a ReplyInlineMarkup or ReplyKeyboardMarkup for the given buttons.

\n * Does nothing if either no buttons are provided or the provided argument is already a reply markup.

\n * this function is called internally when passing an array of buttons.\n * @param buttons - The button, array of buttons, array of array of buttons or markup to convert into a markup.\n * @param inlineOnly - Whether the buttons **must** be inline buttons only or not.\n * @example\n * ```ts\n * import {Button} from "telegram";\n * // PS this function is not async\n * const markup = client.buildReplyMarkup(Button.inline("Hello!"));\n *\n * await client.sendMessage(chat, {\n * message: "click me!",\n * buttons: markup,\n * }\n *\n * // The following example can also be used in a simpler way like so\n *\n * await client.sendMessage(chat, {\n * message: "click me!",\n * buttons: [Button.inline("Hello!")],\n * }\n * ```\n */\n\n\n buildReplyMarkup(buttons, inlineOnly = false) {\n return buttonsMethods.buildReplyMarkup(buttons, inlineOnly);\n } //endregion\n //region download\n\n /**\n * Low-level method to download files from their input location.\n * downloadMedia should generally be used over this.\n * @param inputLocation - The file location from which the file will be downloaded. See getInputLocation source for a complete list of supported types.\n * @param fileParams - {@link DownloadFileParams}\n * @return a Buffer downloaded from the inputFile.\n * @example\n * ```ts\n * const photo = message.photo;\n * const buffer = await client.downloadFile(\n * new Api.InputPhotoFileLocation({\n * id: photo.id,\n * accessHash: photo.accessHash,\n * fileReference: photo.fileReference,\n * thumbSize: size.type\n * }),\n * {\n * dcId: photo.dcId,\n * fileSize: "m",\n * }\n * );\n * ```\n */\n\n\n downloadFile(inputLocation, fileParams = {}) {\n return downloadMethods.downloadFileV2(this, inputLocation, fileParams);\n }\n /**\n * Iterates over a file download, yielding chunks of the file.\n * This method can be used to stream files in a more convenient way, since it offers more control (pausing, resuming, etc.)\n * @param iterFileParams - {@link IterDownloadFunction}\n * @return a Buffer downloaded from the inputFile.\n * @example\n * ```ts\n * const photo = message.photo;\n * for await (const chunk of client.iterDownload({\n * file: new Api.InputPhotoFileLocation({\n * id: photo.id,\n * accessHash: photo.accessHash,\n * fileReference: photo.fileReference,\n * thumbSize: size.type\n * }),\n * offset: start,\n * limit: end,\n * requestSize:2048*1024\n * )){\n * console.log("Downloaded chunk of size",chunk.length);\n * };\n * ```\n */\n\n\n iterDownload(iterFileParams) {\n return downloadMethods.iterDownload(this, iterFileParams);\n } //region download\n\n /**\n * Downloads the profile photo from the given user,chat or channel.
\n * This method will return an empty buffer in case of no profile photo.\n * @param entity - where to download the photo from.\n * @param downloadProfilePhotoParams - {@link DownloadProfilePhotoParams}\n * @return buffer containing the profile photo. can be empty in case of no profile photo.\n * @example\n * ```ts\n * // Download your own profile photo\n * const buffer = await client.downloadProfilePhoto(\'me\')\n * console.log("Downloaded image is",buffer);\n * // if you want to save it as a file you can use the fs module on node for that.\n * import { promises as fs } from \'fs\';\n * await fs.writeFile("picture.jpg",buffer);\n * ```\n */\n\n\n downloadProfilePhoto(entity, downloadProfilePhotoParams = {\n isBig: false\n }) {\n return downloadMethods.downloadProfilePhoto(this, entity, downloadProfilePhotoParams);\n }\n /**\n * Downloads the given media from a message or a media object.
\n * this will return an empty Buffer in case of wrong or empty media.\n * @param messageOrMedia - instance of a message or a media.\n * @param downloadParams {@link DownloadMediaInterface}\n * @return a buffer containing the downloaded data if outputFile is undefined else nothing.\n * @example ```ts\n * const buffer = await client.downloadMedia(message, {})\n * // to save it to a file later on using fs.\n * import { promises as fs } from \'fs\';\n * await fs.writeFile("file",buffer);\n * // to use a progress callback you can pass it like so.\n * const buffer = await client.downloadMedia(message, {\n * progressCallback : console.log\n * })\n * ```\n */\n\n\n downloadMedia(messageOrMedia, downloadParams) {\n return downloadMethods.downloadMedia(this, messageOrMedia, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.outputFile, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.thumb, downloadParams === null || downloadParams === void 0 ? void 0 : downloadParams.progressCallback);\n } //endregion\n //region message parse\n\n /**\n * This property is the default parse mode used when sending messages. Defaults to {@link MarkdownParser}.
\n * It will always be either undefined or an object with parse and unparse methods.
\n * When setting a different value it should be one of:
\n *
\n * - Object with parse and unparse methods.
\n * - A str indicating the parse_mode. For Markdown \'md\' or \'markdown\' may be used. For HTML, \'html\' may be used.
\n * The parse method should be a function accepting a single parameter, the text to parse, and returning a tuple consisting of (parsed message str, [MessageEntity instances]).
\n *
\n * The unparse method should be the inverse of parse such that text == unparse(parse(text)).
\n *
\n * See {@link Api.TypeMessageEntity} for allowed message entities.\n * @example\n * ```ts\n * // gets the current parse mode.\n * console.log("parse mode is :", client.parseMode)\n * ```\n */\n\n\n get parseMode() {\n return this._parseMode;\n }\n /** Setter for parseMode.\n * {@link parseMode}\n * @param mode can be md,markdown for Markdown or html for html. can also pass a custom mode.\n * pass undefined for no parsing.\n * @example\n * // sets the mode to HTML\n * client.setParseMode("html");\n * await client.sendMessage("me",{message:"This is an underline text"});\n * // disable formatting\n * client.setParseMode(undefined);\n * await client.sendMessage("me",{message:" this will be sent as it is ** with no formatting **});\n */\n\n\n setParseMode(mode) {\n if (mode) {\n this._parseMode = (0, Utils_1.sanitizeParseMode)(mode);\n } else {\n this._parseMode = undefined;\n }\n } //endregion\n // region messages\n\n /**\n * Iterates over the messages for a given chat.\n *
\n * The default order is from newest to oldest but can be changed with the reverse param.
\n * If either `search`, `filter` or `fromUser` are provided this will use {@link Api.messages.Search} instead of {@link Api.messages.GetHistory}.\n * @remarks\n * Telegram limits GetHistory requests every 10 requests (1 000 messages) therefore a sleep of 1 seconds will be the default for this limit.\n * @param entity - The entity from whom to retrieve the message history.
\n * It may be undefined to perform a global search, or to get messages by their ID from no particular chat
\n * **Note** that some of the offsets will not work if this is the case.
\n * **Note** that if you want to perform a global search, you must set a non-empty search string, a filter. or fromUser.\n * @param iterParams - {@link IterMessagesParams}\n * @yield Instances of custom {@link Message}\n * @example\n * ```ts\n * // From most-recent to oldest\n * for await (const message of client.iterMessages(chat,{}){\n * console.log(message.id, message.text)\n * }\n *\n * // From oldest to most-recent\n * for await (const message of client.iterMessages(chat,{reverse:true}){\n * console.log(message.id, message.text)\n * }\n *\n * // Filter by sender\n * for await (const message of client.iterMessages(chat,{fromUser:"me"}){\n * console.log(message.id, message.text)\n * }\n *\n * // Server-side search with fuzzy text\n * for await (const message of client.iterMessages(chat,{search:"hello"}){\n * console.log(message.id, message.text)\n * }\n *\n * // Filter by message type:\n * import { Api } from "telegram";\n * for await (const message of client.iterMessages(chat,{filter: Api.InputMessagesFilterPhotos}){\n * console.log(message.id, message.photo)\n * }\n *\n * // Getting comments from a post in a channel:\n * * for await (const message of client.iterMessages(chat,{replyTo: 123}){\n * console.log(message.chat.title,, message.text)\n * }\n * ```\n */\n\n\n iterMessages(entity, iterParams = {}) {\n return messageMethods.iterMessages(this, entity, iterParams);\n }\n /**\n * Same as iterMessages() but returns a TotalList instead.
\n * if the `limit` is not set, it will be 1 by default unless both `minId` **and** `maxId` are set. in which case the entire range will be returned.
\n * @param entity - The entity from whom to retrieve the message history. see {@link iterMessages}.
\n * @param getMessagesParams - see {@link IterMessagesParams}.\n * @return {@link TotalList} of messages.\n * @example\n * ```ts\n * // The totalList has a .total attribute which will show the complete number of messages even if none are fetched.\n * // Get 0 photos and print the total to show how many photos there are\n * import { Api } from "telegram";\n * const photos = await client.getMessages(chat, {limit: 0, filter:Api.InputMessagesFilterPhotos})\n * console.log(photos.total)\n *\n * // Get all the photos\n * const photos = await client.getMessages(chat, {limit: undefined, filter:Api.InputMessagesFilterPhotos})\n *\n // Get messages by ID:\n * const messages = await client.getMessages(chat, {ids:1337})\n * const message_1337 = messages[0];\n * ```\n */\n\n\n getMessages(entity, getMessagesParams = {}) {\n return messageMethods.getMessages(this, entity, getMessagesParams);\n }\n /**\n * Sends a message to the specified user, chat or channel.
\n * The default parse mode is the same as the official applications (a custom flavour of markdown). **bold**, `code` or __italic__ are available.
\n * In addition you can send [links](https://example.com) and [mentions](@username) (or using IDs like in the Bot API: [mention](tg://user?id=123456789)) and pre blocks with three backticks.
\n *
\n * Sending a /start command with a parameter (like ?start=data) is also done through this method. Simply send \'/start data\' to the bot.
\n *
\n * See also Message.respond() and Message.reply().\n *\n * @param entity - Who to sent the message to.\n * @param sendMessageParams - see {@link SendMessageParams}\n * @return\n * The sent custom Message.\n * @example\n * ```ts\n * // Markdown is the default.\n * await client.sendMessage("me",{message:"Hello **world!**});\n *\n * // Defaults to another parse mode.\n * client.setParseMode("HTML");\n *\n * await client.sendMessage(\'me\', {message:\'Some bold and italic text\'})\n * await client.sendMessage(\'me\', {message:\'An URL\'})\n * await client.sendMessage(\'me\', {message:\'Mentions\'})\n *\n * // Explicit parse mode.\n * // No parse mode by default\n * client.setParseMode(undefined);\n * //...but here I want markdown\n * await client.sendMessage(\'me\', {message:\'Hello, **world**!\', {parseMode:"md"}})\n *\n * // ...and here I need HTML\n * await client.sendMessage(\'me\', {message:\'Hello, world!\', {parseMode=\'html\'}})\n *\n *\n * // Scheduling a message to be sent after 5 minutes\n *\n * await client.sendMessage(chat, {message:\'Hi, future!\', schedule:(60 * 5) + (Date.now() / 1000)})\n *\n * ```\n */\n\n\n sendMessage(entity, sendMessageParams = {}) {\n return messageMethods.sendMessage(this, entity, sendMessageParams);\n }\n /**\n * Forwards the given messages to the specified entity.
\n *
\n * If you want to "forward" a message without the forward header\n * (the "forwarded from" text), you should use `sendMessage` with\n * the original message instead. This will send a copy of it.\n *
\n * See also {@link Message.forwardTo}`.\n * @param entity - To which entity the message(s) will be forwarded.\n * @param forwardMessagesParams - see {@link ForwardMessagesParams}\n * @return The list of forwarded Message, Note.
\n * if some messages failed to be forwarded the returned list will have them as undefined.\n * @example ```ts\n * // a single one\n * await client.forwardMessages(chat, {messages: message});\n * // or\n * await client.forwardMessages(chat, {messages:messageId,fromPeer:fromChat});\n * // or\n * await message.forwardTo(chat)\n *\n * // multiple\n * await client.forwardMessages(chat, {messages:messages});\n * // or\n * await client.forwardMessages(chat, {messages:messageIds,fromPeer:fromChat});\n *\n * // Forwarding as a copy\n * await client.sendMessage(chat, {message:message});\n * ```\n */\n\n\n forwardMessages(entity, forwardMessagesParams) {\n return messageMethods.forwardMessages(this, entity, forwardMessagesParams);\n }\n /**\n * Used to edit a message by changing it\'s text or media\n * message refers to the message to be edited not what to edit\n * text refers to the new text\n * See also Message.edit()
\n * Notes: It is not possible to edit the media of a message that doesn\'t contain media.\n * @param entity - From which chat to edit the message.
\n * This can also be the message to be edited, and the entity will be inferred from it, so the next parameter will be assumed to be the message text.
\n * You may also pass a InputBotInlineMessageID, which is the only way to edit messages that were sent after the user selects an inline query result. Not supported yet!\n * @param editMessageParams - see {@link EditMessageParams}.\n * @return The edited Message.\n * @throws\n * `MESSAGE_AUTHOR_REQUIRED` if you\'re not the author of the message but tried editing it anyway.\n * `MESSAGE_NOT_MODIFIED` if the contents of the message were not modified at all.\n * `MESSAGE_ID_INVALID` if the ID of the message is invalid (the ID itself may be correct, but the message with that ID cannot be edited).
\n * For example, when trying to edit messages with a reply markup (or clear markup) this error will be raised.\n * @example\n * ```ts\n * const message = await client.sendMessage(chat,{message:"Hi!"});\n *\n * await client.editMessage(chat,{message:message,text:"Hello!"}\n * // or\n * await client.editMessage(chat,{message:message.id,text:"Hello!"}\n * ```\n */\n\n\n editMessage(entity, editMessageParams) {\n return messageMethods.editMessage(this, entity, editMessageParams);\n }\n /**\n * Deletes the given messages, optionally "for everyone".\n *\n * See also {@link Message.delete}`.\n *\n * @remarks This method does **not** validate that the message IDs belong to the chat that you passed! It\'s possible for the method to delete messages from different private chats and small group chats at once, so make sure to pass the right IDs.\n * @param entity - From who the message will be deleted. This can actually be `undefined` for normal chats, but **must** be present for channels and megagroups.\n * @param messageIds - The IDs (or ID) or messages to be deleted.\n * @param revoke - Whether the message should be deleted for everyone or not.\n * By default it has the opposite behaviour of official clients,\n * and it will delete the message for everyone.\n * Disabling this has no effect on channels or megagroups,\n * since it will unconditionally delete the message for everyone.\n * @return\n * A list of {@link AffectedMessages}, each item being the result for the delete calls of the messages in chunks of 100 each.\n * @example\n * ```ts\n * await client.deleteMessages(chat, messages);\n *\n * await client.deleteMessages(chat, messages, {revoke:false});\n * ```\n */\n\n\n deleteMessages(entity, messageIds, {\n revoke = true\n }) {\n return messageMethods.deleteMessages(this, entity, messageIds, {\n revoke: revoke\n });\n }\n\n pinMessage(entity, message, pinMessageParams) {\n return messageMethods.pinMessage(this, entity, message, pinMessageParams);\n }\n\n unpinMessage(entity, message, unpinMessageParams) {\n return messageMethods.unpinMessage(this, entity, message, unpinMessageParams);\n }\n /**\n * Marks messages as read and optionally clears mentions.
\n * This effectively marks a message as read (or more than one) in the given conversation.
\n * If a message or maximum ID is provided, all the messages up to and\n * including such ID will be marked as read (for all messages whose ID ≤ max_id).\n *\n * See also {@link Message.markRead}`.\n *\n * @remarks If neither message nor maximum ID are provided, all messages will be marked as read by assuming that `max_id = 0`.\n * @param entity - The chat where the message should be pinned.\n * @param message - The message or the message ID to pin. If it\'s `undefined`, all messages will be unpinned instead.\n * @param markAsReadParams - see {@link MarkAsReadParams}.\n * @return boolean\n * @example\n * ```ts\n * // using a Message object\n * const message = await client.sendMessage(chat, \'GramJS is awesome!\');\n * await client.markAsRead(chat, message)\n * // ...or using the int ID of a Message\n * await client.markAsRead(chat, message.id);\n *\n * // ...or passing a list of messages to mark as read\n * await client.markAsRead(chat, messages)\n * ```\n */\n\n\n markAsRead(entity, message, markAsReadParams) {\n return messageMethods.markAsRead(this, entity, message, markAsReadParams);\n } //endregion\n //region dialogs\n\n /**\n * Iterator over the dialogs (open conversations/subscribed channels) sequentially.
\n * The order is the same as the one seen in official applications. (dialogs that had recent messages come first)\n * @param iterDialogsParams - see {@link IterDialogsParams}\n * @yield instances of custom {@link Dialog}.\n * @example\n * ```ts\n * // logs all dialog IDs and their title.\n * for await (const dialog of client.iterDialogs({})){\n * console.log(`${dialog.id}: ${dialog.title}`);\n * }\n * ```\n */\n\n\n iterDialogs(iterDialogsParams = {}) {\n return dialogMethods.iterDialogs(this, iterDialogsParams);\n }\n /**\n * Same as iterDialogs but returns a TotalList instead of an iterator.\n * @param params - {@link IterDialogsParams}\n * @example\n * ```ts\n * // Get all open conversation, print the title of the first\n * const dialogs = await client.getDialogs({});\n * const first = dialogs[0];\n * console.log(first.title);\n *
\n * // Use the dialog somewhere else\n * await client.sendMessage(first, {message: "hi"});\n *
\n * // Getting only non-archived dialogs (both equivalent)\n * non_archived = await client.get_dialogs({folder:0})\n * non_archived = await client.get_dialogs({archived:false})\n *
\n * // Getting only archived dialogs (both equivalent)\n * archived = await client.get_dialogs({folder:1})\n * archived = await client.get_dialogs({archived:true})\n * ```\n */\n\n\n getDialogs(params = {}) {\n return dialogMethods.getDialogs(this, params);\n } //endregion\n //region chats\n\n /**\n * Iterates over the participants belonging to a specified chat , channel or supergroup.
\n *
\n * Channels can return a maximum of 200 users while supergroups can return up to 10 000.
\n * You must be an admin to retrieve users from a channel.
\n * @param entity - The entity from which to retrieve the participants list.\n * @param params - {@link IterParticipantsParams}\n * @remarks\n * The filter ChannelParticipantsBanned will return restricted users. If you want banned users you should use ChannelParticipantsKicked instead.\n * @yield The User objects returned by GetParticipants with an additional .participant attribute
\n * which is the matched ChannelParticipant type for channels/supergroup or ChatParticipants for normal chats.\n * @example\n * ```ts\n * // logs all user IDs in a chat.\n * for await (const user of client.iterParticipants(chat)){\n * console.log("User id",user.id);\n * }\n *\n * // Searches by name.\n * for await (const user of client.iterParticipants(chat, {search: "name"})){\n * console.log("Username is ",user.username); // Some users don\'t have a username so this can be undefined.\n * }\n *\n * // Filter by admins.\n * import { Api } from "telegram";\n *\n * for await (const user of client.iterParticipants(chat, {filter: Api.ChannelParticipantsAdmins})){\n * console.log("admin first name is ",user.firstName);\n * }\n * ```\n */\n\n\n iterParticipants(entity, params = {}) {\n return chatMethods.iterParticipants(this, entity, params);\n }\n /**\n * Exact same as iterParticipants but returns a TotalList instead.
\n * This can be used if you want to retrieve a list instead of iterating over the users.\n * @param entity - entity to get users from.\n * @param params - {@link IterParticipantsParams}.\n * @return\n */\n\n\n getParticipants(entity, params = {}) {\n return chatMethods.getParticipants(this, entity, params);\n } //endregion\n //region updates\n\n /** TODO */\n\n\n on(event) {\n return updateMethods.on(this, event);\n }\n\n addEventHandler(callback, event) {\n return updateMethods.addEventHandler(this, callback, event);\n }\n /**\n * Inverse operation of addEventHandler().
\n *\n * @param callback - the callback function to be removed.\n * @param event - the type of the event.\n */\n\n\n removeEventHandler(callback, event) {\n return updateMethods.removeEventHandler(this, callback, event);\n }\n /**\n * Lists all registered event handlers.\n * @return pair of [eventBuilder,CallableFunction]\n */\n\n\n listEventHandlers() {\n return updateMethods.listEventHandlers(this);\n } // region uploads\n\n /**\n * Uploads a file to Telegram\'s servers, without sending it.\n * @remarks generally it\'s better to use {@link sendFile} instead.\n * This method returns a handle (an instance of InputFile or InputFileBig, as required) which can be later used before it expires (they are usable during less than a day).
\n * Uploading a file will simply return a "handle" to the file stored remotely in the Telegram servers,\n * which can be later used on. This will not upload the file to your own chat or any chat at all.\n * This also can be used to update profile pictures\n * @param fileParams see {@link UploadFileParams}\n * @return {@link Api.InputFileBig} if the file size is larger than 10mb otherwise {@link Api.InputFile}\n * @example\n * ```ts\n * const toUpload = new CustomFile("photo.jpg", fs.statSync("../photo.jpg").size, "../photo.jpg");\n * const file = await client.uploadFile({\n * file: toUpload,\n * workers: 1,\n * });\n * await client.invoke(new Api.photos.UploadProfilePhoto({\n * file: file,\n * }));\n * ```\n */\n\n\n uploadFile(fileParams) {\n return uploadMethods.uploadFile(this, fileParams);\n }\n /**\n * Sends message with the given file to the specified entity.\n * This uses {@link uploadFile} internally so if you want more control over uploads you can use that.\n * @param entity - who will receive the file.\n * @param sendFileParams - see {@link SendFileInterface}\n * @example\n * ```\n * // Normal files like photos\n * await client.sendFile(chat, {file:\'/my/photos/me.jpg\', caption:"It\'s me!"})\n * // or\n * await client.sendMessage(chat, {message:"It\'s me!", file:\'/my/photos/me.jpg\'})\n *\n * Voice notes or round videos\n * await client.sendFile(chat, {file: \'/my/songs/song.mp3\', voiceNote:True})\n * await client.sendFile(chat, {file: \'/my/videos/video.mp4\', videoNote:True})\n *\n * // Custom thumbnails\n * await client.sendFile(chat, {file:\'/my/documents/doc.txt\', thumb:\'photo.jpg\'})\n *\n * // Only documents\n * await client.sendFile(chat, {file:\'/my/photos/photo.png\', forceDocument:True})\n *\n * //logging progress\n * await client.sendFile(chat, {file: file, progressCallback=console.log})\n *\n * // Dices, including dart and other future emoji\n * await client.sendFile(chat, {file:new Api.InputMediaDice("")})\n * await client.sendFile(chat, {file:new Api.InputMediaDice("🎯")})\n *\n * // Contacts\n * await client.sendFile(chat, {file: new Api.InputMediaContact({\n * phoneNumber:\'+1 123 456 789\',\n * firstName:\'Example\',\n * lastName:\'\',\n * vcard:\'\'\n * }))\n * ```\n */\n\n\n sendFile(entity, sendFileParams) {\n return uploadMethods.sendFile(this, entity, sendFileParams);\n } // endregion\n //region user methods\n\n /**\n * invokes raw Telegram requests.
\n * This is a low level method that can be used to call manually any Telegram API method.
\n * Generally this should only be used when there isn\'t a friendly method that does what you need.
\n * All available requests and types are found under the `Api.` namespace.\n * @param request - The request to send. this should be of type request.\n * @param sender - Optional sender to use to send the requests. defaults to main sender.\n * @return The response from Telegram.\n * @example\n * ```ts\n * //\n * const result = await client.invoke(new Api.account.CheckUsername({\n * username: \'some string here\'\n * }));\n * console.log("does this username exist?",result);\n *\n * ```\n */\n\n\n invoke(request, sender) {\n return userMethods.invoke(this, request, sender);\n }\n /**\n * Gets the current logged in {@link Api.User}.\n * If the user has not logged in this will throw an error.\n * @param inputPeer - Whether to return the input peer version {@link Api.InputPeerUser} or the whole user {@link Api.User}.\n * @return Your own {@link Api.User}\n * @example\n * ```ts\n * const me = await client.getMe();\n * console.log("My username is",me.username);\n * ```\n */\n\n\n getMe(inputPeer = false) {\n return userMethods.getMe(this, inputPeer);\n }\n /**\n * Return true if the signed-in user is a bot, false otherwise.\n * @example\n * ```ts\n * if (await client.isBot()){\n * console.log("I am a bot. PI is 3.14159265359);\n * } else {\n * console.log("I am a human. Pies are delicious);\n * }\n * ```\n */\n\n\n isBot() {\n return userMethods.isBot(this);\n }\n /**\n * Returns true if the user is authorized (logged in).\n * @example\n * if (await client.isUserAuthorized()){\n * console.log("I am authorized. I can call functions and use requests");\n * }else{\n * console.log("I am not logged in. I need to sign in first before being able to call methods");\n * }\n */\n\n\n isUserAuthorized() {\n return userMethods.isUserAuthorized(this);\n }\n\n getEntity(entity) {\n return userMethods.getEntity(this, entity);\n }\n /**\n * Turns the given entity into its input entity version.
\n * Almost all requests use this kind of InputPeer, so this is the most suitable call to make for those cases.
\n * **Generally you should let the library do its job** and don\'t worry about getting the input entity first, but if you\'re going to use an entity often, consider making the call.\n * @param entity - If a username or invite link is given, the library will use the cache.
\n * This means that it\'s possible to be using a username that changed or an old invite link (this only happens if an invite link for a small group chat is used after it was upgraded to a mega-group).\n *
\n * - If the username or ID from the invite link is not found in the cache, it will be fetched. The same rules apply to phone numbers (\'+34 123456789\') from people in your contact list.\n *
\n * - If an exact name is given, it must be in the cache too. This is not reliable as different people can share the same name and which entity is returned is arbitrary,
\n * and should be used only for quick tests.\n *
\n * - If a positive integer ID is given, the entity will be searched in cached users, chats or channels, without making any call.\n *
\n * - If a negative integer ID is given, the entity will be searched exactly as either a chat (prefixed with -) or as a channel (prefixed with -100).\n *
\n * - If a Peer is given, it will be searched exactly in the cache as either a user, chat or channel.\n *
\n * - If the given object can be turned into an input entity directly, said operation will be done.\n *
\n * -If the entity can\'t be found, this will throw an error.\n * @return\n * {@link Api.InputPeerUser} , {@link Api.InputPeerChat} , {@link Api.InputPeerChannel} or {@link Api.InputPeerSelf} if the parameter is "me" or "self"\n * @example\n * ```ts\n * // If you\'re going to use "username" often in your code\n * // (make a lot of calls), consider getting its input entity\n * // once, and then using the "user" everywhere instead.\n * user = await client.getInputEntity(\'username\')\n *\n * // The same applies to IDs, chats or channels.\n * chat = await client.getInputEntity(-123456789)\n * ```\n */\n\n\n getInputEntity(entity) {\n return userMethods.getInputEntity(this, entity);\n }\n /**\n * Gets the ID for the given entity.
\n * This method needs to be async because peer supports usernames, invite-links, phone numbers (from people in your contact list), etc.
\n *
\n * If addMark is false, then a positive ID will be returned instead. By default, bot-API style IDs (signed) are returned.\n * @param peer\n * @param addMark - whether to return a bot api style id.\n * @return the ID of the entity.\n * @example\n * ```ts\n * console.log(await client.getPeerId("me"));\n * ```\n */\n\n\n getPeerId(peer, addMark = true) {\n return userMethods.getPeerId(this, peer, addMark);\n }\n /** @hidden */\n\n\n _getInputDialog(peer) {\n return userMethods._getInputDialog(this, peer);\n }\n /** @hidden */\n\n\n _getInputNotify(notify) {\n return userMethods._getInputNotify(this, notify);\n } //endregion\n\n /** @hidden */\n\n\n async _handleReconnect() {\n try {\n await this.getMe();\n } catch (e) {\n this._log.error(`Error while trying to reconnect`);\n\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(e);\n }\n }\n } //region base methods\n\n\n async connect() {\n await this._initSession();\n\n if (this._sender === undefined) {\n this._sender = new network_1.MTProtoSender(this.session.getAuthKey(), {\n logger: this._log,\n dcId: this.session.dcId || 4,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n updateCallback: updates_1._handleUpdate.bind(this),\n isMainSender: true,\n client: this,\n securityChecks: this._securityChecks,\n autoReconnectCallback: this._handleReconnect.bind(this)\n });\n }\n\n const connection = new this._connection({\n ip: this.session.serverAddress,\n port: this.useWSS ? 443 : 80,\n dcId: this.session.dcId,\n loggers: this._log,\n proxy: this._proxy,\n socket: this.networkSocket,\n testServers: this.testServers\n });\n\n if (!(await this._sender.connect(connection))) {\n return;\n }\n\n this.session.setAuthKey(this._sender.authKey);\n this.session.save();\n this._initRequest.query = new tl_1.Api.help.GetConfig();\n\n this._log.info(`Using LAYER ${AllTLObjects_1.LAYER} for initial connect`);\n\n await this._sender.send(new tl_1.Api.InvokeWithLayer({\n layer: AllTLObjects_1.LAYER,\n query: this._initRequest\n }));\n (0, updates_1._updateLoop)(this);\n } //endregion\n // region Working with different connections/Data Centers\n\n /** @hidden */\n\n\n async _switchDC(newDc) {\n this._log.info(`Reconnecting to new data center ${newDc}`);\n\n const DC = await this.getDC(newDc);\n this.session.setDC(newDc, DC.ipAddress, DC.port); // authKey\'s are associated with a server, which has now changed\n // so it\'s not valid anymore. Set to undefined to force recreating it.\n\n await this._sender.authKey.setKey(undefined);\n this.session.setAuthKey(undefined);\n this.session.save();\n await this._disconnect();\n return await this.connect();\n }\n /**\n * Returns the DC ip in case of node or the DC web address in case of browser.
\n * This will do an API request to fill the cache if it\'s the first time it\'s called.\n * @param dcId The DC ID.\n * @param downloadDC whether to use -1 DCs or not\n * @param web if true this will get the web DCs.\n * TODO, hardcode IPs.\n * (These only support downloading/uploading and not creating a new AUTH key)\n */\n\n\n async getDC(dcId, downloadDC = false, web = false) {\n this._log.debug(`Getting DC ${dcId}`);\n\n if (!platform_1.isNode || web) {\n switch (dcId) {\n case 1:\n return {\n id: 1,\n ipAddress: `pluto${downloadDC ? "-1" : ""}.web.telegram.org`,\n port: 443\n };\n\n case 2:\n return {\n id: 2,\n ipAddress: `venus${downloadDC ? "-1" : ""}.web.telegram.org`,\n port: 443\n };\n\n case 3:\n return {\n id: 3,\n ipAddress: `aurora${downloadDC ? "-1" : ""}.web.telegram.org`,\n port: 443\n };\n\n case 4:\n return {\n id: 4,\n ipAddress: `vesta${downloadDC ? "-1" : ""}.web.telegram.org`,\n port: 443\n };\n\n case 5:\n return {\n id: 5,\n ipAddress: `flora${downloadDC ? "-1" : ""}.web.telegram.org`,\n port: 443\n };\n\n default:\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n }\n\n if (!this._config) {\n this._config = await this.invoke(new tl_1.Api.help.GetConfig());\n }\n\n for (const DC of this._config.dcOptions) {\n if (DC.id === dcId && !!DC.ipv6 === this._useIPV6) {\n return {\n id: DC.id,\n ipAddress: DC.ipAddress,\n port: 443\n };\n }\n }\n\n throw new Error(`Cannot find the DC with the ID of ${dcId}`);\n }\n /** @hidden */\n\n\n _removeSender(dcId) {\n delete this._borrowedSenderPromises[dcId];\n }\n /** @hidden */\n\n\n _getResponseMessage(req, result, inputChat) {\n return parseMethods._getResponseMessage(this, req, result, inputChat);\n }\n /** @hidden */\n\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n /**\n * Small hack for using it in browsers\n */\n\n\n static get events() {\n return __webpack_require__(/*! ../events */ "./browser/events/index.js");\n }\n\n}\n\nexports.TelegramClient = TelegramClient;\n\n//# sourceURL=webpack://telegram/./browser/client/TelegramClient.js?')},"./browser/client/auth.js": /*!********************************!*\ !*** ./browser/client/auth.js ***! \********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports._authFlow = exports.signInBot = exports.signInWithPassword = exports.sendCode = exports.signInUserWithQrCode = exports.signInUser = exports.checkAuthorization = exports.start = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst utils = __importStar(__webpack_require__(/*! ../Utils */ "./browser/Utils.js"));\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst Password_1 = __webpack_require__(/*! ../Password */ "./browser/Password.js");\n\nconst QR_CODE_TIMEOUT = 30000; // region public methods\n\n/** @hidden */\n\nasync function start(client, authParams) {\n if (!client.connected) {\n await client.connect();\n }\n\n if (await client.checkAuthorization()) {\n return;\n }\n\n const apiCredentials = {\n apiId: client.apiId,\n apiHash: client.apiHash\n };\n await _authFlow(client, apiCredentials, authParams);\n}\n\nexports.start = start;\n/** @hidden */\n\nasync function checkAuthorization(client) {\n try {\n await client.invoke(new tl_1.Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexports.checkAuthorization = checkAuthorization;\n/** @hidden */\n\nasync function signInUser(client, apiCredentials, authParams) {\n let phoneNumber;\n let phoneCodeHash;\n let isCodeViaApp = false;\n\n while (1) {\n try {\n if (typeof authParams.phoneNumber === "function") {\n try {\n phoneNumber = await authParams.phoneNumber();\n } catch (err) {\n if (err.errorMessage === "RESTART_AUTH_WITH_QR") {\n return client.signInUserWithQrCode(apiCredentials, authParams);\n }\n\n throw err;\n }\n } else {\n phoneNumber = authParams.phoneNumber;\n }\n\n const sendCodeResult = await client.sendCode(apiCredentials, phoneNumber, authParams.forceSMS);\n phoneCodeHash = sendCodeResult.phoneCodeHash;\n isCodeViaApp = sendCodeResult.isCodeViaApp;\n\n if (typeof phoneCodeHash !== "string") {\n throw new Error("Failed to retrieve phone code hash");\n }\n\n break;\n } catch (err) {\n if (typeof authParams.phoneNumber !== "function") {\n throw err;\n }\n\n const shouldWeStop = await authParams.onError(err);\n\n if (shouldWeStop) {\n throw new Error("AUTH_USER_CANCEL");\n }\n }\n }\n\n let phoneCode;\n let isRegistrationRequired = false;\n let termsOfService;\n\n while (1) {\n try {\n try {\n phoneCode = await authParams.phoneCode(isCodeViaApp);\n } catch (err) {\n // This is the support for changing phone number from the phone code screen.\n if (err.errorMessage === "RESTART_AUTH") {\n return client.signInUser(apiCredentials, authParams);\n }\n }\n\n if (!phoneCode) {\n throw new Error("Code is empty");\n } // May raise PhoneCodeEmptyError, PhoneCodeExpiredError,\n // PhoneCodeHashEmptyError or PhoneCodeInvalidError.\n\n\n const result = await client.invoke(new tl_1.Api.auth.SignIn({\n phoneNumber,\n phoneCodeHash,\n phoneCode\n }));\n\n if (result instanceof tl_1.Api.auth.AuthorizationSignUpRequired) {\n isRegistrationRequired = true;\n termsOfService = result.termsOfService;\n break;\n }\n\n return result.user;\n } catch (err) {\n if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {\n return client.signInWithPassword(apiCredentials, authParams);\n } else {\n const shouldWeStop = await authParams.onError(err);\n\n if (shouldWeStop) {\n throw new Error("AUTH_USER_CANCEL");\n }\n }\n }\n }\n\n if (isRegistrationRequired) {\n while (1) {\n try {\n let lastName;\n let firstName = "first name";\n\n if (authParams.firstAndLastNames) {\n const result = await authParams.firstAndLastNames();\n firstName = result[0];\n lastName = result[1];\n }\n\n if (!firstName) {\n throw new Error("First name is required");\n }\n\n const {\n user\n } = await client.invoke(new tl_1.Api.auth.SignUp({\n phoneNumber,\n phoneCodeHash,\n firstName,\n lastName\n }));\n\n if (termsOfService) {\n // This is a violation of Telegram rules: the user should be presented with and accept TOS.\n await client.invoke(new tl_1.Api.help.AcceptTermsOfService({\n id: termsOfService.id\n }));\n }\n\n return user;\n } catch (err) {\n const shouldWeStop = await authParams.onError(err);\n\n if (shouldWeStop) {\n throw new Error("AUTH_USER_CANCEL");\n }\n }\n }\n }\n\n await authParams.onError(new Error("Auth failed"));\n return client.signInUser(apiCredentials, authParams);\n}\n\nexports.signInUser = signInUser;\n/** @hidden */\n\nasync function signInUserWithQrCode(client, apiCredentials, authParams) {\n let isScanningComplete = false;\n\n if (authParams.qrCode == undefined) {\n throw new Error("qrCode callback not defined");\n }\n\n const inputPromise = (async () => {\n while (1) {\n if (isScanningComplete) {\n break;\n }\n\n const result = await client.invoke(new tl_1.Api.auth.ExportLoginToken({\n apiId: Number(apiCredentials.apiId),\n apiHash: apiCredentials.apiHash,\n exceptIds: []\n }));\n\n if (!(result instanceof tl_1.Api.auth.LoginToken)) {\n throw new Error("Unexpected");\n }\n\n const {\n token,\n expires\n } = result;\n await Promise.race([authParams.qrCode({\n token,\n expires\n }), (0, Helpers_1.sleep)(QR_CODE_TIMEOUT)]);\n await (0, Helpers_1.sleep)(QR_CODE_TIMEOUT);\n }\n })();\n\n const updatePromise = new Promise(resolve => {\n client.addEventHandler(update => {\n if (update instanceof tl_1.Api.UpdateLoginToken) {\n resolve(undefined);\n }\n });\n });\n\n try {\n await Promise.race([updatePromise, inputPromise]);\n } catch (err) {\n throw err;\n } finally {\n isScanningComplete = true;\n }\n\n try {\n const result2 = await client.invoke(new tl_1.Api.auth.ExportLoginToken({\n apiId: Number(apiCredentials.apiId),\n apiHash: apiCredentials.apiHash,\n exceptIds: []\n }));\n\n if (result2 instanceof tl_1.Api.auth.LoginTokenSuccess && result2.authorization instanceof tl_1.Api.auth.Authorization) {\n return result2.authorization.user;\n } else if (result2 instanceof tl_1.Api.auth.LoginTokenMigrateTo) {\n await client._switchDC(result2.dcId);\n const migratedResult = await client.invoke(new tl_1.Api.auth.ImportLoginToken({\n token: result2.token\n }));\n\n if (migratedResult instanceof tl_1.Api.auth.LoginTokenSuccess && migratedResult.authorization instanceof tl_1.Api.auth.Authorization) {\n return migratedResult.authorization.user;\n } else {\n client._log.error(`Received unknown result while scanning QR ${result2.className}`);\n\n throw new Error(`Received unknown result while scanning QR ${result2.className}`);\n }\n } else {\n client._log.error(`Received unknown result while scanning QR ${result2.className}`);\n\n throw new Error(`Received unknown result while scanning QR ${result2.className}`);\n }\n } catch (err) {\n if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {\n return client.signInWithPassword(apiCredentials, authParams);\n }\n\n throw err;\n }\n\n await authParams.onError(new Error("QR auth failed"));\n throw new Error("QR auth failed");\n}\n\nexports.signInUserWithQrCode = signInUserWithQrCode;\n/** @hidden */\n\nasync function sendCode(client, apiCredentials, phoneNumber, forceSMS = false) {\n try {\n const {\n apiId,\n apiHash\n } = apiCredentials;\n const sendResult = await client.invoke(new tl_1.Api.auth.SendCode({\n phoneNumber,\n apiId,\n apiHash,\n settings: new tl_1.Api.CodeSettings({})\n }));\n if (sendResult instanceof tl_1.Api.auth.SentCodeSuccess) throw new Error("logged in right after sending the code"); // If we already sent a SMS, do not resend the phoneCode (hash may be empty)\n\n if (!forceSMS || sendResult.type instanceof tl_1.Api.auth.SentCodeTypeSms) {\n return {\n phoneCodeHash: sendResult.phoneCodeHash,\n isCodeViaApp: sendResult.type instanceof tl_1.Api.auth.SentCodeTypeApp\n };\n }\n\n const resendResult = await client.invoke(new tl_1.Api.auth.ResendCode({\n phoneNumber,\n phoneCodeHash: sendResult.phoneCodeHash\n }));\n if (resendResult instanceof tl_1.Api.auth.SentCodeSuccess) throw new Error("logged in right after resending the code");\n return {\n phoneCodeHash: resendResult.phoneCodeHash,\n isCodeViaApp: resendResult.type instanceof tl_1.Api.auth.SentCodeTypeApp\n };\n } catch (err) {\n if (err.errorMessage === "AUTH_RESTART") {\n return client.sendCode(apiCredentials, phoneNumber, forceSMS);\n } else {\n throw err;\n }\n }\n}\n\nexports.sendCode = sendCode;\n/** @hidden */\n\nasync function signInWithPassword(client, apiCredentials, authParams) {\n let emptyPassword = false;\n\n while (1) {\n try {\n const passwordSrpResult = await client.invoke(new tl_1.Api.account.GetPassword());\n\n if (!authParams.password) {\n emptyPassword = true;\n break;\n }\n\n const password = await authParams.password(passwordSrpResult.hint);\n\n if (!password) {\n throw new Error("Password is empty");\n }\n\n const passwordSrpCheck = await (0, Password_1.computeCheck)(passwordSrpResult, password);\n const {\n user\n } = await client.invoke(new tl_1.Api.auth.CheckPassword({\n password: passwordSrpCheck\n }));\n return user;\n } catch (err) {\n const shouldWeStop = await authParams.onError(err);\n\n if (shouldWeStop) {\n throw new Error("AUTH_USER_CANCEL");\n }\n }\n }\n\n if (emptyPassword) {\n throw new Error("Account has 2FA enabled.");\n }\n\n return undefined; // Never reached (TypeScript fix)\n}\n\nexports.signInWithPassword = signInWithPassword;\n/** @hidden */\n\nasync function signInBot(client, apiCredentials, authParams) {\n const {\n apiId,\n apiHash\n } = apiCredentials;\n let {\n botAuthToken\n } = authParams;\n\n if (!botAuthToken) {\n throw new Error("a valid BotToken is required");\n }\n\n if (typeof botAuthToken === "function") {\n let token;\n\n while (true) {\n token = await botAuthToken();\n\n if (token) {\n botAuthToken = token;\n break;\n }\n }\n }\n\n const {\n user\n } = await client.invoke(new tl_1.Api.auth.ImportBotAuthorization({\n apiId,\n apiHash,\n botAuthToken\n }));\n return user;\n}\n\nexports.signInBot = signInBot;\n/** @hidden */\n\nasync function _authFlow(client, apiCredentials, authParams) {\n const me = "phoneNumber" in authParams ? await client.signInUser(apiCredentials, authParams) : await client.signInBot(apiCredentials, authParams);\n\n client._log.info("Signed in successfully as " + utils.getDisplayName(me));\n}\n\nexports._authFlow = _authFlow;\n\n//# sourceURL=webpack://telegram/./browser/client/auth.js?')},"./browser/client/bots.js": /*!********************************!*\ !*** ./browser/client/bots.js ***! \********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.inlineQuery = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst inlineResults_1 = __webpack_require__(/*! ../tl/custom/inlineResults */ "./browser/tl/custom/inlineResults.js");\n\nvar GetInlineBotResults = tl_1.Api.messages.GetInlineBotResults; // BotMethods\n\n/** @hidden */\n\nasync function inlineQuery(client, bot, query, entity, offset, geoPoint) {\n bot = await client.getInputEntity(bot);\n let peer = new tl_1.Api.InputPeerSelf();\n\n if (entity) {\n peer = await client.getInputEntity(entity);\n }\n\n const result = await client.invoke(new GetInlineBotResults({\n bot: bot,\n peer: peer,\n query: query,\n offset: offset || "",\n geoPoint: geoPoint\n }));\n return new inlineResults_1.InlineResults(client, result, entity ? peer : undefined);\n}\n\nexports.inlineQuery = inlineQuery;\n\n//# sourceURL=webpack://telegram/./browser/client/bots.js?')},"./browser/client/buttons.js": /*!***********************************!*\ !*** ./browser/client/buttons.js ***! \***********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.buildReplyMarkup = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst button_1 = __webpack_require__(/*! ../tl/custom/button */ "./browser/tl/custom/button.js");\n\nconst messageButton_1 = __webpack_require__(/*! ../tl/custom/messageButton */ "./browser/tl/custom/messageButton.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js"); // ButtonMethods\n\n/** @hidden */\n\n\nfunction buildReplyMarkup(buttons, inlineOnly = false) {\n if (buttons == undefined) {\n return undefined;\n }\n\n if ("SUBCLASS_OF_ID" in buttons) {\n if (buttons.SUBCLASS_OF_ID == 0xe2e10ef2) {\n return buttons;\n }\n }\n\n if (!(0, Helpers_1.isArrayLike)(buttons)) {\n buttons = [[buttons]];\n } else if (!buttons || !(0, Helpers_1.isArrayLike)(buttons[0])) {\n // @ts-ignore\n buttons = [buttons];\n }\n\n let isInline = false;\n let isNormal = false;\n let resize = undefined;\n const singleUse = false;\n const selective = false;\n const rows = []; // @ts-ignore\n\n for (const row of buttons) {\n const current = [];\n\n for (let button of row) {\n if (button instanceof button_1.Button) {\n if (button.resize != undefined) {\n resize = button.resize;\n }\n\n if (button.singleUse != undefined) {\n resize = button.singleUse;\n }\n\n if (button.selective != undefined) {\n resize = button.selective;\n }\n\n button = button.button;\n } else if (button instanceof messageButton_1.MessageButton) {\n button = button.button;\n }\n\n const inline = button_1.Button._isInline(button);\n\n if (!isInline && inline) {\n isInline = true;\n }\n\n if (!isNormal && inline) {\n isNormal = false;\n }\n\n if (button.SUBCLASS_OF_ID == 0xbad74a3) {\n // 0xbad74a3 == crc32(b\'KeyboardButton\')\n current.push(button);\n }\n }\n\n if (current) {\n rows.push(new tl_1.Api.KeyboardButtonRow({\n buttons: current\n }));\n }\n }\n\n if (inlineOnly && isNormal) {\n throw new Error("You cannot use non-inline buttons here");\n } else if (isInline === isNormal && isNormal) {\n throw new Error("You cannot mix inline with normal buttons");\n } else if (isInline) {\n return new tl_1.Api.ReplyInlineMarkup({\n rows: rows\n });\n }\n\n return new tl_1.Api.ReplyKeyboardMarkup({\n rows: rows,\n resize: resize,\n singleUse: singleUse,\n selective: selective\n });\n}\n\nexports.buildReplyMarkup = buildReplyMarkup;\n\n//# sourceURL=webpack://telegram/./browser/client/buttons.js?')},"./browser/client/chats.js": /*!*********************************!*\ !*** ./browser/client/chats.js ***! \*********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.getParticipants = exports.iterParticipants = exports._ParticipantsIter = void 0;\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst requestIter_1 = __webpack_require__(/*! ../requestIter */ "./browser/requestIter.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst inspect_1 = __webpack_require__(/*! ../inspect */ "./browser/inspect.js");\n\nconst _MAX_PARTICIPANTS_CHUNK_SIZE = 200;\nconst _MAX_ADMIN_LOG_CHUNK_SIZE = 100;\nconst _MAX_PROFILE_PHOTO_CHUNK_SIZE = 100;\n\nclass _ChatAction {\n constructor(client, chat, action, params = {\n delay: 4,\n autoCancel: true\n }) {\n this._client = client;\n this._chat = chat;\n this._action = action;\n this._delay = params.delay;\n this.autoCancel = params.autoCancel;\n this._request = undefined;\n this._task = null;\n this._running = false;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n async start() {\n this._request = new tl_1.Api.messages.SetTyping({\n peer: this._chat,\n action: this._action\n });\n this._running = true;\n\n this._update();\n }\n\n async stop() {\n this._running = false;\n\n if (this.autoCancel) {\n await this._client.invoke(new tl_1.Api.messages.SetTyping({\n peer: this._chat,\n action: new tl_1.Api.SendMessageCancelAction()\n }));\n }\n }\n\n async _update() {\n while (this._running) {\n if (this._request != undefined) {\n await this._client.invoke(this._request);\n }\n\n await (0, Helpers_1.sleep)(this._delay * 1000);\n }\n }\n\n progress(current, total) {\n if ("progress" in this._action) {\n this._action.progress = 100 * Math.round(current / total);\n }\n }\n\n}\n\n_ChatAction._str_mapping = {\n typing: new tl_1.Api.SendMessageTypingAction(),\n contact: new tl_1.Api.SendMessageChooseContactAction(),\n game: new tl_1.Api.SendMessageGamePlayAction(),\n location: new tl_1.Api.SendMessageGeoLocationAction(),\n "record-audio": new tl_1.Api.SendMessageRecordAudioAction(),\n "record-voice": new tl_1.Api.SendMessageRecordAudioAction(),\n "record-round": new tl_1.Api.SendMessageRecordRoundAction(),\n "record-video": new tl_1.Api.SendMessageRecordVideoAction(),\n audio: new tl_1.Api.SendMessageUploadAudioAction({\n progress: 1\n }),\n voice: new tl_1.Api.SendMessageUploadAudioAction({\n progress: 1\n }),\n song: new tl_1.Api.SendMessageUploadAudioAction({\n progress: 1\n }),\n round: new tl_1.Api.SendMessageUploadRoundAction({\n progress: 1\n }),\n video: new tl_1.Api.SendMessageUploadVideoAction({\n progress: 1\n }),\n photo: new tl_1.Api.SendMessageUploadPhotoAction({\n progress: 1\n }),\n document: new tl_1.Api.SendMessageUploadDocumentAction({\n progress: 1\n }),\n file: new tl_1.Api.SendMessageUploadDocumentAction({\n progress: 1\n }),\n cancel: new tl_1.Api.SendMessageCancelAction()\n};\n\nclass _ParticipantsIter extends requestIter_1.RequestIter {\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n async _init({\n entity,\n filter,\n offset,\n search,\n showTotal\n }) {\n var _a, _b;\n\n if (!offset) {\n offset = 0;\n }\n\n if (filter && filter.constructor === Function) {\n if ([tl_1.Api.ChannelParticipantsBanned, tl_1.Api.ChannelParticipantsKicked, tl_1.Api.ChannelParticipantsSearch, tl_1.Api.ChannelParticipantsContacts].includes(filter)) {\n filter = new filter({\n q: ""\n });\n } else {\n filter = new filter();\n }\n }\n\n entity = await this.client.getInputEntity(entity);\n\n const ty = __1.helpers._entityType(entity);\n\n if (search && (filter || ty != __1.helpers._EntityType.CHANNEL)) {\n // We need to \'search\' ourselves unless we have a PeerChannel\n search = search.toLowerCase();\n\n this.filterEntity = entity => {\n return __1.utils.getDisplayName(entity).toLowerCase().includes(search) || ("username" in entity ? entity.username || "" : "").toLowerCase().includes(search);\n };\n } else {\n this.filterEntity = entity => true;\n } // Only used for channels, but we should always set the attribute\n\n\n this.requests = [];\n\n if (ty == __1.helpers._EntityType.CHANNEL) {\n if (showTotal) {\n const channel = await this.client.invoke(new tl_1.Api.channels.GetFullChannel({\n channel: entity\n }));\n\n if (!(channel.fullChat instanceof tl_1.Api.ChatFull)) {\n this.total = channel.fullChat.participantsCount;\n }\n }\n\n if (this.total && this.total <= 0) {\n return false;\n }\n\n this.requests.push(new tl_1.Api.channels.GetParticipants({\n channel: entity,\n filter: filter || new tl_1.Api.ChannelParticipantsSearch({\n q: search || ""\n }),\n offset,\n limit: _MAX_PARTICIPANTS_CHUNK_SIZE,\n hash: big_integer_1.default.zero\n }));\n } else if (ty == __1.helpers._EntityType.CHAT) {\n if (!("chatId" in entity)) {\n throw new Error("Found chat without id " + JSON.stringify(entity));\n }\n\n const full = await this.client.invoke(new tl_1.Api.messages.GetFullChat({\n chatId: entity.chatId\n }));\n\n if (full.fullChat instanceof tl_1.Api.ChatFull) {\n if (!(full.fullChat.participants instanceof tl_1.Api.ChatParticipantsForbidden)) {\n this.total = full.fullChat.participants.participants.length;\n } else {\n this.total = 0;\n return false;\n }\n\n const users = new Map();\n\n for (const user of full.users) {\n users.set(user.id.toString(), user);\n }\n\n for (const participant of full.fullChat.participants.participants) {\n const user = users.get(participant.userId.toString());\n\n if (!this.filterEntity(user)) {\n continue;\n }\n\n user.participant = participant;\n (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.push(user);\n }\n\n return true;\n }\n } else {\n this.total = 1;\n\n if (this.limit != 0) {\n const user = await this.client.getEntity(entity);\n\n if (this.filterEntity(user)) {\n user.participant = undefined;\n (_b = this.buffer) === null || _b === void 0 ? void 0 : _b.push(user);\n }\n }\n\n return true;\n }\n }\n\n async _loadNextChunk() {\n var _a, _b;\n\n if (!((_a = this.requests) === null || _a === void 0 ? void 0 : _a.length)) {\n return true;\n }\n\n this.requests[0].limit = Math.min(this.limit - this.requests[0].offset, _MAX_PARTICIPANTS_CHUNK_SIZE);\n const results = [];\n\n for (const request of this.requests) {\n results.push(await this.client.invoke(request));\n }\n\n for (let i = this.requests.length - 1; i >= 0; i--) {\n const participants = results[i];\n\n if (participants instanceof tl_1.Api.channels.ChannelParticipantsNotModified || !participants.users.length) {\n this.requests.splice(i, 1);\n continue;\n }\n\n this.requests[i].offset += participants.participants.length;\n const users = new Map();\n\n for (const user of participants.users) {\n users.set(user.id.toString(), user);\n }\n\n for (const participant of participants.participants) {\n if (!("userId" in participant)) {\n continue;\n }\n\n const user = users.get(participant.userId.toString());\n\n if (this.filterEntity && !this.filterEntity(user)) {\n continue;\n }\n\n user.participant = participant;\n (_b = this.buffer) === null || _b === void 0 ? void 0 : _b.push(user);\n }\n }\n\n return undefined;\n }\n\n [Symbol.asyncIterator]() {\n return super[Symbol.asyncIterator]();\n }\n\n}\n\nexports._ParticipantsIter = _ParticipantsIter;\n\nclass _AdminLogIter extends requestIter_1.RequestIter {\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n async _init(entity, searchArgs, filterArgs) {\n let eventsFilter = undefined;\n\n if (filterArgs && Object.values(filterArgs).find(element => element === true)) {\n eventsFilter = new tl_1.Api.ChannelAdminLogEventsFilter(Object.assign({}, filterArgs));\n }\n\n this.entity = await this.client.getInputEntity(entity);\n const adminList = [];\n\n if (searchArgs && searchArgs.admins) {\n for (const admin of searchArgs.admins) {\n adminList.push(await this.client.getInputEntity(admin));\n }\n }\n\n this.request = new tl_1.Api.channels.GetAdminLog({\n channel: this.entity,\n q: (searchArgs === null || searchArgs === void 0 ? void 0 : searchArgs.search) || "",\n minId: searchArgs === null || searchArgs === void 0 ? void 0 : searchArgs.minId,\n maxId: searchArgs === null || searchArgs === void 0 ? void 0 : searchArgs.maxId,\n limit: 0,\n eventsFilter: eventsFilter,\n admins: adminList || undefined\n });\n }\n\n async _loadNextChunk() {\n if (!this.request) {\n return true;\n }\n\n this.request.limit = Math.min(this.left, _MAX_ADMIN_LOG_CHUNK_SIZE);\n const r = await this.client.invoke(this.request);\n const entities = new Map();\n\n for (const entity of [...r.users, ...r.chats]) {\n entities.set(__1.utils.getPeerId(entity), entity);\n }\n\n const eventIds = [];\n\n for (const e of r.events) {\n eventIds.push(e.id);\n }\n\n this.request.maxId = (0, Helpers_1.getMinBigInt)([big_integer_1.default.zero, ...eventIds]);\n\n for (const ev of r.events) {\n if (ev.action instanceof tl_1.Api.ChannelAdminLogEventActionEditMessage) {// @ts-ignore\n // TODO ev.action.prevMessage._finishInit(this.client, entities, this.entity);\n // @ts-ignore\n // TODO ev.action.newMessage._finishInit(this.client, entities, this.entity);\n }\n }\n }\n\n}\n/** @hidden */\n\n\nfunction iterParticipants(client, entity, {\n limit,\n offset,\n search,\n filter,\n showTotal = true\n}) {\n return new _ParticipantsIter(client, limit !== null && limit !== void 0 ? limit : Number.MAX_SAFE_INTEGER, {}, {\n entity: entity,\n filter: filter,\n offset: offset !== null && offset !== void 0 ? offset : 0,\n search: search,\n showTotal: showTotal\n });\n}\n\nexports.iterParticipants = iterParticipants;\n/** @hidden */\n\nasync function getParticipants(client, entity, params) {\n const it = client.iterParticipants(entity, params);\n return await it.collect();\n}\n\nexports.getParticipants = getParticipants;\n\n//# sourceURL=webpack://telegram/./browser/client/chats.js?')},"./browser/client/dialogs.js": /*!***********************************!*\ !*** ./browser/client/dialogs.js ***! \***********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.getDialogs = exports.iterDialogs = exports._DialogsIter = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst requestIter_1 = __webpack_require__(/*! ../requestIter */ "./browser/requestIter.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n\nconst dialog_1 = __webpack_require__(/*! ../tl/custom/dialog */ "./browser/tl/custom/dialog.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js");\n\nconst _MAX_CHUNK_SIZE = 100;\n/**\n Get the key to get messages from a dialog.\n\n We cannot just use the message ID because channels share message IDs,\n and the peer ID is required to distinguish between them. But it is not\n necessary in small group chats and private chats.\n * @param {Api.TypePeer} [peer] the dialog peer\n * @param {number} [messageId] the message id\n * @return {[number,number]} the channel id and message id\n */\n\nfunction _dialogMessageKey(peer, messageId) {\n // can\'t use arrays as keys for map :( need to convert to string.\n return "" + [peer instanceof tl_1.Api.PeerChannel ? peer.channelId : undefined, messageId];\n}\n\nclass _DialogsIter extends requestIter_1.RequestIter {\n async _init({\n offsetDate,\n offsetId,\n offsetPeer,\n ignorePinned,\n ignoreMigrated,\n folder\n }) {\n this.request = new tl_1.Api.messages.GetDialogs({\n offsetDate,\n offsetId,\n offsetPeer,\n limit: 1,\n hash: big_integer_1.default.zero,\n excludePinned: ignorePinned,\n folderId: folder\n });\n\n if (this.limit <= 0) {\n // Special case, get a single dialog and determine count\n const dialogs = await this.client.invoke(this.request);\n\n if ("count" in dialogs) {\n this.total = dialogs.count;\n } else {\n this.total = dialogs.dialogs.length;\n }\n\n return true;\n }\n\n this.seen = new Set();\n this.offsetDate = offsetDate;\n this.ignoreMigrated = ignoreMigrated;\n }\n\n [Symbol.asyncIterator]() {\n return super[Symbol.asyncIterator]();\n }\n\n async _loadNextChunk() {\n if (!this.request || !this.seen || !this.buffer) {\n return;\n }\n\n this.request.limit = Math.min(this.left, _MAX_CHUNK_SIZE);\n const r = await this.client.invoke(this.request);\n\n if (r instanceof tl_1.Api.messages.DialogsNotModified) {\n return;\n }\n\n if ("count" in r) {\n this.total = r.count;\n } else {\n this.total = r.dialogs.length;\n }\n\n const entities = new Map();\n const messages = new Map();\n\n for (const entity of [...r.users, ...r.chats]) {\n if (entity instanceof tl_1.Api.UserEmpty || entity instanceof tl_1.Api.ChatEmpty) {\n continue;\n }\n\n entities.set(index_1.utils.getPeerId(entity), entity);\n }\n\n for (const m of r.messages) {\n let message = m;\n\n try {\n // todo make sure this never fails\n message._finishInit(this.client, entities, undefined);\n } catch (e) {\n this.client._log.error("Got error while trying to finish init message with id " + m.id);\n\n if (this.client._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(e);\n }\n }\n\n messages.set(_dialogMessageKey(message.peerId, message.id), message);\n }\n\n for (const d of r.dialogs) {\n if (d instanceof tl_1.Api.DialogFolder) {\n continue;\n }\n\n const message = messages.get(_dialogMessageKey(d.peer, d.topMessage));\n\n if (this.offsetDate != undefined) {\n const date = message === null || message === void 0 ? void 0 : message.date;\n\n if (date == undefined || date > this.offsetDate) {\n continue;\n }\n }\n\n const peerId = index_1.utils.getPeerId(d.peer);\n\n if (!this.seen.has(peerId)) {\n this.seen.add(peerId);\n\n if (!entities.has(peerId)) {\n /*\n > In which case can a UserEmpty appear in the list of banned members?\n > In a very rare cases. This is possible but isn\'t an expected behavior.\n Real world example: https://t.me/TelethonChat/271471\n */\n continue;\n }\n\n const cd = new dialog_1.Dialog(this.client, d, entities, message);\n\n if (!this.ignoreMigrated || cd.entity != undefined && "migratedTo" in cd.entity) {\n this.buffer.push(cd);\n }\n }\n }\n\n if (r.dialogs.length < this.request.limit || !(r instanceof tl_1.Api.messages.DialogsSlice)) {\n return true;\n }\n\n let lastMessage;\n\n for (let dialog of r.dialogs.reverse()) {\n lastMessage = messages.get(_dialogMessageKey(dialog.peer, dialog.topMessage));\n\n if (lastMessage) {\n break;\n }\n }\n\n this.request.excludePinned = true;\n this.request.offsetId = lastMessage ? lastMessage.id : 0;\n this.request.offsetDate = lastMessage ? lastMessage.date : 0;\n this.request.offsetPeer = this.buffer[this.buffer.length - 1].inputEntity;\n }\n\n}\n\nexports._DialogsIter = _DialogsIter;\n/** @hidden */\n\nfunction iterDialogs(client, {\n limit = undefined,\n offsetDate = undefined,\n offsetId = 0,\n offsetPeer = new tl_1.Api.InputPeerEmpty(),\n ignorePinned = false,\n ignoreMigrated = false,\n folder = undefined,\n archived = undefined\n}) {\n if (archived != undefined) {\n folder = archived ? 1 : 0;\n }\n\n return new _DialogsIter(client, limit, {}, {\n offsetDate,\n offsetId,\n offsetPeer,\n ignorePinned,\n ignoreMigrated,\n folder\n });\n}\n\nexports.iterDialogs = iterDialogs;\n/** @hidden */\n\nasync function getDialogs(client, params) {\n return await client.iterDialogs(params).collect();\n}\n\nexports.getDialogs = getDialogs;\n\n//# sourceURL=webpack://telegram/./browser/client/dialogs.js?')},"./browser/client/downloads.js": /*!*************************************!*\ !*** ./browser/client/downloads.js ***! \*************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nvar __asyncValues = this && this.__asyncValues || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var m = o[Symbol.asyncIterator],\n i;\n return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {\n return this;\n }, i);\n\n function verb(n) {\n i[n] = o[n] && function (v) {\n return new Promise(function (resolve, reject) {\n v = o[n](v), settle(resolve, reject, v.done, v.value);\n });\n };\n }\n\n function settle(resolve, reject, d, v) {\n Promise.resolve(v).then(function (v) {\n resolve({\n value: v,\n done: d\n });\n }, reject);\n }\n};\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.downloadProfilePhoto = exports._downloadPhoto = exports._downloadCachedPhotoSize = exports._downloadWebDocument = exports._downloadContact = exports._downloadDocument = exports.downloadMedia = exports.downloadFileV2 = exports.iterDownload = exports.GenericDownloadIter = exports.DirectDownloadIter = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst requestIter_1 = __webpack_require__(/*! ../requestIter */ "./browser/requestIter.js");\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nconst fs_1 = __webpack_require__(/*! ./fs */ "./browser/client/fs.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst fs = __importStar(__webpack_require__(/*! ./fs */ "./browser/client/fs.js"));\n\nconst path_1 = __importDefault(__webpack_require__(/*! ./path */ "./browser/client/path.js"));\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js")); // All types\n\n\nconst sizeTypes = ["w", "y", "d", "x", "c", "m", "b", "a", "s"]; // Chunk sizes for `upload.getFile` must be multiple of the smallest size\n\nconst MIN_CHUNK_SIZE = 4096;\nconst DEFAULT_CHUNK_SIZE = 64; // kb\n\nconst ONE_MB = 1024 * 1024;\nconst REQUEST_TIMEOUT = 15000;\nconst DISCONNECT_SLEEP = 1000;\nconst TIMED_OUT_SLEEP = 1000;\nconst MAX_CHUNK_SIZE = 512 * 1024;\n\nclass DirectDownloadIter extends requestIter_1.RequestIter {\n constructor() {\n super(...arguments);\n this._timedOut = false;\n }\n\n async _init({\n fileLocation,\n dcId,\n offset,\n stride,\n chunkSize,\n requestSize,\n fileSize,\n msgData\n }) {\n this.request = new tl_1.Api.upload.GetFile({\n location: fileLocation,\n offset,\n limit: requestSize\n });\n this.total = fileSize;\n this._stride = stride;\n this._chunkSize = chunkSize;\n this._lastPart = undefined; //this._msgData = msgData;\n\n this._timedOut = false;\n this._sender = await this.client.getSender(dcId);\n }\n\n async _loadNextChunk() {\n const current = await this._request();\n this.buffer.push(current);\n\n if (current.length < this.request.limit) {\n // we finished downloading\n this.left = this.buffer.length;\n await this.close();\n return true;\n } else {\n this.request.offset = this.request.offset.add(this._stride);\n }\n }\n\n async _request() {\n try {\n this._sender = await this.client.getSender(this._sender.dcId);\n const result = await this.client.invoke(this.request, this._sender);\n this._timedOut = false;\n\n if (result instanceof tl_1.Api.upload.FileCdnRedirect) {\n throw new Error("CDN Not supported. Please Add an issue in github");\n }\n\n return result.bytes;\n } catch (e) {\n if (e.errorMessage == "TIMEOUT") {\n if (this._timedOut) {\n this.client._log.warn("Got two timeouts in a row while downloading file");\n\n throw e;\n }\n\n this._timedOut = true;\n\n this.client._log.info("Got timeout while downloading file, retrying once");\n\n await (0, Helpers_1.sleep)(TIMED_OUT_SLEEP);\n return await this._request();\n } else if (e instanceof errors_1.FileMigrateError) {\n this.client._log.info("File lives in another DC");\n\n this._sender = await this.client.getSender(e.newDc);\n return await this._request();\n } else if (e.errorMessage == "FILEREF_UPGRADE_NEEDED") {\n // TODO later\n throw e;\n } else {\n throw e;\n }\n }\n }\n\n async close() {\n this.client._log.debug("Finished downloading file ...");\n }\n\n [Symbol.asyncIterator]() {\n return super[Symbol.asyncIterator]();\n }\n\n}\n\nexports.DirectDownloadIter = DirectDownloadIter;\n\nclass GenericDownloadIter extends DirectDownloadIter {\n async _loadNextChunk() {\n // 1. Fetch enough for one chunk\n let data = buffer_1.Buffer.alloc(0); // 1.1. ``bad`` is how much into the data we have we need to offset\n\n const bad = this.request.offset.mod(this.request.limit).toJSNumber();\n const before = this.request.offset; // 1.2. We have to fetch from a valid offset, so remove that bad part\n\n this.request.offset = this.request.offset.subtract(bad);\n let done = false;\n\n while (!done && data.length - bad < this._chunkSize) {\n const current = await this._request();\n this.request.offset = this.request.offset.add(this.request.limit);\n data = buffer_1.Buffer.concat([data, current]);\n done = current.length < this.request.limit;\n } // 1.3 Restore our last desired offset\n\n\n this.request.offset = before; // 2. Fill the buffer with the data we have\n // 2.1. The current chunk starts at ``bad`` offset into the data,\n // and each new chunk is ``stride`` bytes apart of the other\n\n for (let i = bad; i < data.length; i += this._stride) {\n this.buffer.push(data.slice(i, i + this._chunkSize)); // 2.2. We will yield this offset, so move to the next one\n\n this.request.offset = this.request.offset.add(this._stride);\n } // 2.3. If we are in the last chunk, we will return the last partial data\n\n\n if (done) {\n this.left = this.buffer.length;\n await this.close();\n return;\n } // 2.4 If we are not done, we can\'t return incomplete chunks.\n\n\n if (this.buffer[this.buffer.length - 1].length != this._chunkSize) {\n this._lastPart = this.buffer.pop(); // 3. Be careful with the offsets. Re-fetching a bit of data\n // is fine, since it greatly simplifies things.\n // TODO Try to not re-fetch data\n\n this.request.offset = this.request.offset.subtract(this._stride);\n }\n }\n\n}\n\nexports.GenericDownloadIter = GenericDownloadIter;\n/** @hidden */\n\nfunction iterDownload(client, {\n file,\n offset = big_integer_1.default.zero,\n stride,\n limit,\n chunkSize,\n requestSize = MAX_CHUNK_SIZE,\n fileSize,\n dcId,\n msgData\n}) {\n // we\'re ignoring here to make it more flexible (which is probably a bad idea)\n // @ts-ignore\n const info = __1.utils.getFileInfo(file);\n\n if (info.dcId != undefined) {\n dcId = info.dcId;\n }\n\n if (fileSize == undefined) {\n fileSize = info.size;\n }\n\n file = info.location;\n\n if (chunkSize == undefined) {\n chunkSize = requestSize;\n }\n\n if (limit == undefined && fileSize != undefined) {\n limit = Math.floor(fileSize.add(chunkSize).subtract(1).divide(chunkSize).toJSNumber());\n }\n\n if (stride == undefined) {\n stride = chunkSize;\n } else if (stride < chunkSize) {\n throw new Error("Stride must be >= chunkSize");\n }\n\n requestSize -= requestSize % MIN_CHUNK_SIZE;\n\n if (requestSize < MIN_CHUNK_SIZE) {\n requestSize = MIN_CHUNK_SIZE;\n } else if (requestSize > MAX_CHUNK_SIZE) {\n requestSize = MAX_CHUNK_SIZE;\n }\n\n let cls;\n\n if (chunkSize == requestSize && offset.divide(MAX_CHUNK_SIZE).eq(big_integer_1.default.zero) && stride % MIN_CHUNK_SIZE == 0 && (limit == undefined || offset.divide(limit).eq(big_integer_1.default.zero))) {\n cls = DirectDownloadIter;\n\n client._log.info(`Starting direct file download in chunks of ${requestSize} at ${offset}, stride ${stride}`);\n } else {\n cls = GenericDownloadIter;\n\n client._log.info(`Starting indirect file download in chunks of ${requestSize} at ${offset}, stride ${stride}`);\n }\n\n return new cls(client, limit, {}, {\n fileLocation: file,\n dcId,\n offset,\n stride,\n chunkSize,\n requestSize,\n fileSize,\n msgData\n });\n}\n\nexports.iterDownload = iterDownload;\n\nfunction getWriter(outputFile) {\n if (!outputFile || buffer_1.Buffer.isBuffer(outputFile)) {\n return new extensions_1.BinaryWriter(buffer_1.Buffer.alloc(0));\n } else if (typeof outputFile == "string") {\n // We want to make sure that the path exists.\n return (0, fs_1.createWriteStream)(outputFile);\n } else {\n return outputFile;\n }\n}\n\nfunction closeWriter(writer) {\n if ("close" in writer && writer.close) {\n writer.close();\n }\n}\n\nfunction returnWriterValue(writer) {\n if (writer instanceof extensions_1.BinaryWriter) {\n return writer.getValue();\n }\n\n if (writer instanceof fs.WriteStream) {\n if (typeof writer.path == "string") {\n return path_1.default.resolve(writer.path);\n } else {\n return buffer_1.Buffer.from(writer.path);\n }\n }\n}\n/** @hidden */\n\n\nasync function downloadFileV2(client, inputLocation, {\n outputFile = undefined,\n partSizeKb = undefined,\n fileSize = undefined,\n progressCallback = undefined,\n dcId = undefined,\n msgData = undefined\n}) {\n var e_1, _a;\n\n if (!partSizeKb) {\n if (!fileSize) {\n partSizeKb = 64;\n } else {\n partSizeKb = __1.utils.getAppropriatedPartSize(fileSize);\n }\n }\n\n const partSize = Math.floor(partSizeKb * 1024);\n\n if (partSize % MIN_CHUNK_SIZE != 0) {\n throw new Error("The part size must be evenly divisible by 4096");\n }\n\n const writer = getWriter(outputFile);\n let downloaded = big_integer_1.default.zero;\n\n try {\n try {\n for (var _b = __asyncValues(iterDownload(client, {\n file: inputLocation,\n requestSize: partSize,\n dcId: dcId,\n msgData: msgData\n })), _c; _c = await _b.next(), !_c.done;) {\n const chunk = _c.value;\n await writer.write(chunk);\n\n if (progressCallback) {\n await progressCallback(downloaded, (0, big_integer_1.default)(fileSize || big_integer_1.default.zero));\n }\n\n downloaded = downloaded.add(chunk.length);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return returnWriterValue(writer);\n } finally {\n closeWriter(writer);\n }\n}\n\nexports.downloadFileV2 = downloadFileV2;\n\nclass Foreman {\n constructor(maxWorkers) {\n this.maxWorkers = maxWorkers;\n this.activeWorkers = 0;\n }\n\n requestWorker() {\n this.activeWorkers++;\n\n if (this.activeWorkers > this.maxWorkers) {\n this.deferred = createDeferred();\n return this.deferred.promise;\n }\n\n return Promise.resolve();\n }\n\n releaseWorker() {\n this.activeWorkers--;\n\n if (this.deferred && this.activeWorkers <= this.maxWorkers) {\n this.deferred.resolve();\n }\n }\n\n}\n\nfunction createDeferred() {\n let resolve;\n const promise = new Promise(_resolve => {\n resolve = _resolve;\n });\n return {\n promise,\n resolve: resolve\n };\n}\n/** @hidden */\n\n\nasync function downloadMedia(client, messageOrMedia, outputFile, thumb, progressCallback) {\n /*\n Downloading large documents may be slow enough to require a new file reference\n to be obtained mid-download. Store (input chat, message id) so that the message\n can be re-fetched.\n */\n let msgData;\n let date;\n let media;\n\n if (messageOrMedia instanceof tl_1.Api.Message) {\n media = messageOrMedia.media;\n date = messageOrMedia.date;\n msgData = messageOrMedia.inputChat ? [messageOrMedia.inputChat, messageOrMedia.id] : undefined;\n } else {\n media = messageOrMedia;\n date = Date.now();\n }\n\n if (typeof media == "string") {\n throw new Error("not implemented");\n }\n\n if (media instanceof tl_1.Api.MessageMediaWebPage) {\n if (media.webpage instanceof tl_1.Api.WebPage) {\n media = media.webpage.document || media.webpage.photo;\n }\n }\n\n if (media instanceof tl_1.Api.MessageMediaPhoto || media instanceof tl_1.Api.Photo) {\n return _downloadPhoto(client, media, outputFile, date, thumb, progressCallback);\n } else if (media instanceof tl_1.Api.MessageMediaDocument || media instanceof tl_1.Api.Document) {\n return _downloadDocument(client, media, outputFile, date, thumb, progressCallback, msgData);\n } else if (media instanceof tl_1.Api.MessageMediaContact) {\n return _downloadContact(client, media, {});\n } else if (media instanceof tl_1.Api.WebDocument || media instanceof tl_1.Api.WebDocumentNoProxy) {\n return _downloadWebDocument(client, media, {});\n } else {\n return buffer_1.Buffer.alloc(0);\n }\n}\n\nexports.downloadMedia = downloadMedia;\n/** @hidden */\n\nasync function _downloadDocument(client, doc, outputFile, date, thumb, progressCallback, msgData) {\n if (doc instanceof tl_1.Api.MessageMediaDocument) {\n if (!doc.document) {\n return buffer_1.Buffer.alloc(0);\n }\n\n doc = doc.document;\n }\n\n if (!(doc instanceof tl_1.Api.Document)) {\n return buffer_1.Buffer.alloc(0);\n }\n\n let size;\n\n if (thumb == undefined) {\n outputFile = getProperFilename(outputFile, "document", "." + (__1.utils.getExtension(doc) || "bin"), date);\n } else {\n outputFile = getProperFilename(outputFile, "photo", ".jpg", date);\n size = getThumb(doc.thumbs || [], thumb);\n\n if (size instanceof tl_1.Api.PhotoCachedSize || size instanceof tl_1.Api.PhotoStrippedSize) {\n return _downloadCachedPhotoSize(size, outputFile);\n }\n }\n\n return await downloadFileV2(client, new tl_1.Api.InputDocumentFileLocation({\n id: doc.id,\n accessHash: doc.accessHash,\n fileReference: doc.fileReference,\n thumbSize: size && "type" in size ? size.type : ""\n }), {\n outputFile: outputFile,\n fileSize: size && "size" in size ? (0, big_integer_1.default)(size.size) : doc.size,\n progressCallback: progressCallback,\n msgData: msgData\n });\n}\n\nexports._downloadDocument = _downloadDocument;\n/** @hidden */\n\nasync function _downloadContact(client, media, args) {\n throw new Error("not implemented");\n}\n\nexports._downloadContact = _downloadContact;\n/** @hidden */\n\nasync function _downloadWebDocument(client, media, args) {\n throw new Error("not implemented");\n}\n\nexports._downloadWebDocument = _downloadWebDocument;\n\nfunction pickFileSize(sizes, sizeType) {\n if (!sizeType || !sizes || !sizes.length) {\n return undefined;\n }\n\n const indexOfSize = sizeTypes.indexOf(sizeType);\n let size;\n\n for (let i = indexOfSize; i < sizeTypes.length; i++) {\n size = sizes.find(s => s.type === sizeTypes[i]);\n\n if (size && !(size instanceof tl_1.Api.PhotoPathSize)) {\n return size;\n }\n }\n\n return undefined;\n}\n/** @hidden */\n\n\nfunction getThumb(thumbs, thumb) {\n function sortThumb(thumb) {\n if (thumb instanceof tl_1.Api.PhotoStrippedSize) {\n return thumb.bytes.length;\n }\n\n if (thumb instanceof tl_1.Api.PhotoCachedSize) {\n return thumb.bytes.length;\n }\n\n if (thumb instanceof tl_1.Api.PhotoSize) {\n return thumb.size;\n }\n\n if (thumb instanceof tl_1.Api.PhotoSizeProgressive) {\n return Math.max(...thumb.sizes);\n }\n\n if (thumb instanceof tl_1.Api.VideoSize) {\n return thumb.size;\n }\n\n return 0;\n }\n\n thumbs = thumbs.sort((a, b) => sortThumb(a) - sortThumb(b));\n const correctThumbs = [];\n\n for (const t of thumbs) {\n if (!(t instanceof tl_1.Api.PhotoPathSize)) {\n correctThumbs.push(t);\n }\n }\n\n if (thumb == undefined) {\n return correctThumbs.pop();\n } else if (typeof thumb == "number") {\n return correctThumbs[thumb];\n } else if (typeof thumb == "string") {\n for (const t of correctThumbs) {\n if ("type" in t && t.type == thumb) {\n return t;\n }\n }\n } else if (thumb instanceof tl_1.Api.PhotoSize || thumb instanceof tl_1.Api.PhotoCachedSize || thumb instanceof tl_1.Api.PhotoStrippedSize || thumb instanceof tl_1.Api.VideoSize) {\n return thumb;\n }\n}\n/** @hidden */\n\n\nasync function _downloadCachedPhotoSize(size, outputFile) {\n // No need to download anything, simply write the bytes\n let data;\n\n if (size instanceof tl_1.Api.PhotoStrippedSize) {\n data = (0, Utils_1.strippedPhotoToJpg)(size.bytes);\n } else {\n data = size.bytes;\n }\n\n const writer = getWriter(outputFile);\n\n try {\n await writer.write(data);\n } finally {\n closeWriter(writer);\n }\n\n return returnWriterValue(writer);\n}\n\nexports._downloadCachedPhotoSize = _downloadCachedPhotoSize;\n/** @hidden */\n\nfunction getProperFilename(file, fileType, extension, date) {\n if (!file || typeof file != "string") {\n return file;\n }\n\n if (fs.existsSync(file) && fs.lstatSync(file).isDirectory()) {\n let fullName = fileType + date + extension;\n return path_1.default.join(file, fullName);\n }\n\n return file;\n}\n/** @hidden */\n\n\nasync function _downloadPhoto(client, photo, file, date, thumb, progressCallback) {\n if (photo instanceof tl_1.Api.MessageMediaPhoto) {\n if (photo.photo instanceof tl_1.Api.PhotoEmpty || !photo.photo) {\n return buffer_1.Buffer.alloc(0);\n }\n\n photo = photo.photo;\n }\n\n if (!(photo instanceof tl_1.Api.Photo)) {\n return buffer_1.Buffer.alloc(0);\n }\n\n const photoSizes = [...(photo.sizes || []), ...(photo.videoSizes || [])];\n const size = getThumb(photoSizes, thumb);\n\n if (!size || size instanceof tl_1.Api.PhotoSizeEmpty) {\n return buffer_1.Buffer.alloc(0);\n }\n\n if (!date) {\n date = Date.now();\n }\n\n file = getProperFilename(file, "photo", ".jpg", date);\n\n if (size instanceof tl_1.Api.PhotoCachedSize || size instanceof tl_1.Api.PhotoStrippedSize) {\n return _downloadCachedPhotoSize(size, file);\n }\n\n let fileSize;\n\n if (size instanceof tl_1.Api.PhotoSizeProgressive) {\n fileSize = Math.max(...size.sizes);\n } else {\n fileSize = "size" in size ? size.size : 512;\n }\n\n return downloadFileV2(client, new tl_1.Api.InputPhotoFileLocation({\n id: photo.id,\n accessHash: photo.accessHash,\n fileReference: photo.fileReference,\n thumbSize: "type" in size ? size.type : ""\n }), {\n outputFile: file,\n fileSize: (0, big_integer_1.default)(fileSize),\n progressCallback: progressCallback,\n dcId: photo.dcId\n });\n}\n\nexports._downloadPhoto = _downloadPhoto;\n/** @hidden */\n\nasync function downloadProfilePhoto(client, entity, fileParams) {\n let photo;\n\n if (typeof entity == "object" && "photo" in entity) {\n photo = entity.photo;\n } else {\n entity = await client.getEntity(entity);\n\n if ("photo" in entity) {\n photo = entity.photo;\n } else {\n throw new Error(`Could not get photo from ${entity ? entity.className : undefined}`);\n }\n }\n\n let dcId;\n let loc;\n\n if (photo instanceof tl_1.Api.UserProfilePhoto || photo instanceof tl_1.Api.ChatPhoto) {\n dcId = photo.dcId;\n loc = new tl_1.Api.InputPeerPhotoFileLocation({\n peer: __1.utils.getInputPeer(entity),\n photoId: photo.photoId,\n big: fileParams.isBig\n });\n } else {\n return buffer_1.Buffer.alloc(0);\n }\n\n return client.downloadFile(loc, {\n outputFile: fileParams.outputFile,\n dcId\n });\n}\n\nexports.downloadProfilePhoto = downloadProfilePhoto;\n\n//# sourceURL=webpack://telegram/./browser/client/downloads.js?')},"./browser/client/fs.js": /*!******************************!*\ !*** ./browser/client/fs.js ***! \******************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.existsSync = exports.lstatSync = exports.WriteStream = exports.createWriteStream = exports.promises = void 0;\nexports.promises = {\n lstat: (...args) => {},\n stat: (...args) => {},\n readFile: (...args) => {},\n open: (...args) => {}\n};\nexports.createWriteStream = {};\nexports.WriteStream = {};\nexports.lstatSync = {};\nexports.existsSync = {};\n\n//# sourceURL=webpack://telegram/./browser/client/fs.js?')},"./browser/client/index.js": /*!*********************************!*\ !*** ./browser/client/index.js ***! \*********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.users = exports.uploads = exports.updates = exports.tgClient = exports.telegramBaseClient = exports.message = exports.messageParse = exports.downloads = exports.dialogs = exports.chats = exports.buttons = exports.bots = exports.auth = exports.twoFA = void 0;\n\nconst twoFA = __importStar(__webpack_require__(/*! ./2fa */ "./browser/client/2fa.js"));\n\nexports.twoFA = twoFA;\n\nconst auth = __importStar(__webpack_require__(/*! ./auth */ "./browser/client/auth.js"));\n\nexports.auth = auth;\n\nconst bots = __importStar(__webpack_require__(/*! ./bots */ "./browser/client/bots.js"));\n\nexports.bots = bots;\n\nconst buttons = __importStar(__webpack_require__(/*! ./buttons */ "./browser/client/buttons.js"));\n\nexports.buttons = buttons;\n\nconst chats = __importStar(__webpack_require__(/*! ./chats */ "./browser/client/chats.js"));\n\nexports.chats = chats;\n\nconst dialogs = __importStar(__webpack_require__(/*! ./dialogs */ "./browser/client/dialogs.js"));\n\nexports.dialogs = dialogs;\n\nconst downloads = __importStar(__webpack_require__(/*! ./downloads */ "./browser/client/downloads.js"));\n\nexports.downloads = downloads;\n\nconst messageParse = __importStar(__webpack_require__(/*! ./messageParse */ "./browser/client/messageParse.js"));\n\nexports.messageParse = messageParse;\n\nconst message = __importStar(__webpack_require__(/*! ./messages */ "./browser/client/messages.js"));\n\nexports.message = message;\n\nconst telegramBaseClient = __importStar(__webpack_require__(/*! ./telegramBaseClient */ "./browser/client/telegramBaseClient.js"));\n\nexports.telegramBaseClient = telegramBaseClient;\n\nconst tgClient = __importStar(__webpack_require__(/*! ./TelegramClient */ "./browser/client/TelegramClient.js"));\n\nexports.tgClient = tgClient;\n\nconst updates = __importStar(__webpack_require__(/*! ./updates */ "./browser/client/updates.js"));\n\nexports.updates = updates;\n\nconst uploads = __importStar(__webpack_require__(/*! ./uploads */ "./browser/client/uploads.js"));\n\nexports.uploads = uploads;\n\nconst users = __importStar(__webpack_require__(/*! ./users */ "./browser/client/users.js"));\n\nexports.users = users;\n\n//# sourceURL=webpack://telegram/./browser/client/index.js?')},"./browser/client/messageParse.js": /*!****************************************!*\ !*** ./browser/client/messageParse.js ***! \****************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports._getResponseMessage = exports._parseMessageText = exports._replaceWithMention = exports.DEFAULT_DELIMITERS = void 0;\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst api_1 = __webpack_require__(/*! ../tl/api */ "./browser/tl/api.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nexports.DEFAULT_DELIMITERS = {\n "**": api_1.Api.MessageEntityBold,\n __: api_1.Api.MessageEntityItalic,\n "~~": api_1.Api.MessageEntityStrike,\n "`": api_1.Api.MessageEntityCode,\n "```": api_1.Api.MessageEntityPre\n};\n/** @hidden */\n\nasync function _replaceWithMention(client, entities, i, user) {\n try {\n entities[i] = new api_1.Api.InputMessageEntityMentionName({\n offset: entities[i].offset,\n length: entities[i].length,\n userId: await client.getInputEntity(user)\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexports._replaceWithMention = _replaceWithMention;\n/** @hidden */\n\nasync function _parseMessageText(client, message, parseMode) {\n if (parseMode == false) {\n return [message, []];\n }\n\n if (parseMode == undefined) {\n if (client.parseMode == undefined) {\n return [message, []];\n }\n\n parseMode = client.parseMode;\n } else if (typeof parseMode === "string") {\n parseMode = (0, Utils_1.sanitizeParseMode)(parseMode);\n }\n\n const [rawMessage, msgEntities] = parseMode.parse(message);\n\n for (let i = msgEntities.length - 1; i >= 0; i--) {\n const e = msgEntities[i];\n\n if (e instanceof api_1.Api.MessageEntityTextUrl) {\n const m = /^@|\\+|tg:\\/\\/user\\?id=(\\d+)/.exec(e.url);\n\n if (m) {\n const userIdOrUsername = m[1] ? Number(m[1]) : e.url;\n const isMention = await _replaceWithMention(client, msgEntities, i, userIdOrUsername);\n\n if (!isMention) {\n msgEntities.splice(i, 1);\n }\n }\n }\n }\n\n return [rawMessage, msgEntities];\n}\n\nexports._parseMessageText = _parseMessageText;\n/** @hidden */\n\nfunction _getResponseMessage(client, request, result, inputChat) {\n let updates = [];\n let entities = new Map();\n\n if (result instanceof api_1.Api.UpdateShort) {\n updates = [result.update];\n } else if (result instanceof api_1.Api.Updates || result instanceof api_1.Api.UpdatesCombined) {\n updates = result.updates;\n\n for (const x of [...result.users, ...result.chats]) {\n entities.set(index_1.utils.getPeerId(x), x);\n }\n } else {\n return;\n }\n\n const randomToId = new Map();\n const idToMessage = new Map();\n let schedMessage;\n\n for (const update of updates) {\n if (update instanceof api_1.Api.UpdateMessageID) {\n randomToId.set(update.randomId.toString(), update.id);\n } else if (update instanceof api_1.Api.UpdateNewChannelMessage || update instanceof api_1.Api.UpdateNewMessage) {\n update.message._finishInit(client, entities, inputChat);\n\n if ("randomId" in request || (0, Helpers_1.isArrayLike)(request)) {\n idToMessage.set(update.message.id, update.message);\n } else {\n return update.message;\n }\n } else if (update instanceof api_1.Api.UpdateEditMessage && "peer" in request && (0, Helpers_1._entityType)(request.peer) != Helpers_1._EntityType.CHANNEL) {\n update.message._finishInit(client, entities, inputChat);\n\n if ("randomId" in request) {\n idToMessage.set(update.message.id, update.message);\n } else if ("id" in request && request.id === update.message.id) {\n return update.message;\n }\n } else if (update instanceof api_1.Api.UpdateEditChannelMessage && "peer" in request && (0, Utils_1.getPeerId)(request.peer) == (0, Utils_1.getPeerId)(update.message.peerId)) {\n if (request.id == update.message.id) {\n update.message._finishInit(client, entities, inputChat);\n\n return update.message;\n }\n } else if (update instanceof api_1.Api.UpdateNewScheduledMessage) {\n update.message._finishInit(client, entities, inputChat);\n\n schedMessage = update.message;\n idToMessage.set(update.message.id, update.message);\n } else if (update instanceof api_1.Api.UpdateMessagePoll) {\n if (request.media.poll.id == update.pollId) {\n const m = new api_1.Api.Message({\n id: request.id,\n peerId: index_1.utils.getPeerId(request.peer),\n media: new api_1.Api.MessageMediaPoll({\n poll: update.poll,\n results: update.results\n }),\n message: "",\n date: 0\n });\n\n m._finishInit(client, entities, inputChat);\n\n return m;\n }\n }\n }\n\n if (request == undefined) {\n return idToMessage;\n }\n\n let randomId;\n\n if ((0, Helpers_1.isArrayLike)(request) || typeof request == "number" || big_integer_1.default.isInstance(request)) {\n randomId = request;\n } else {\n randomId = request.randomId;\n }\n\n if (!randomId) {\n if (schedMessage) {\n return schedMessage;\n }\n\n client._log.warn(`No randomId in ${request} to map to. returning undefined for ${result}`);\n\n return undefined;\n }\n\n if (!(0, Helpers_1.isArrayLike)(randomId)) {\n let msg = idToMessage.get(randomToId.get(randomId.toString()));\n\n if (!msg) {\n client._log.warn(`Request ${request.className} had missing message mapping ${result.className}`);\n }\n\n return msg;\n }\n\n const final = [];\n let warned = false;\n\n for (const rnd of randomId) {\n const tmp = randomToId.get(rnd.toString());\n\n if (!tmp) {\n warned = true;\n break;\n }\n\n const tmp2 = idToMessage.get(tmp);\n\n if (!tmp2) {\n warned = true;\n break;\n }\n\n final.push(tmp2);\n }\n\n if (warned) {\n client._log.warn(`Request ${request.className} had missing message mapping ${result.className}`);\n }\n\n const finalToReturn = [];\n\n for (const rnd of randomId) {\n finalToReturn.push(idToMessage.get(randomToId.get(rnd.toString())));\n }\n\n return finalToReturn;\n}\n\nexports._getResponseMessage = _getResponseMessage;\n\n//# sourceURL=webpack://telegram/./browser/client/messageParse.js?')},"./browser/client/messages.js": /*!************************************!*\ !*** ./browser/client/messages.js ***! \************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __asyncValues = this && this.__asyncValues || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var m = o[Symbol.asyncIterator],\n i;\n return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {\n return this;\n }, i);\n\n function verb(n) {\n i[n] = o[n] && function (v) {\n return new Promise(function (resolve, reject) {\n v = o[n](v), settle(resolve, reject, v.done, v.value);\n });\n };\n }\n\n function settle(resolve, reject, d, v) {\n Promise.resolve(v).then(function (v) {\n resolve({\n value: v,\n done: d\n });\n }, reject);\n }\n};\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.getCommentData = exports.markAsRead = exports._pin = exports.unpinMessage = exports.pinMessage = exports.deleteMessages = exports.editMessage = exports.forwardMessages = exports.sendMessage = exports.getMessages = exports.iterMessages = exports._IDsIter = exports._MessagesIter = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst requestIter_1 = __webpack_require__(/*! ../requestIter */ "./browser/requestIter.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst messageParse_1 = __webpack_require__(/*! ./messageParse */ "./browser/client/messageParse.js");\n\nconst users_1 = __webpack_require__(/*! ./users */ "./browser/client/users.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst uploads_1 = __webpack_require__(/*! ./uploads */ "./browser/client/uploads.js");\n\nconst _MAX_CHUNK_SIZE = 100;\n\nclass _MessagesIter extends requestIter_1.RequestIter {\n async _init({\n entity,\n offsetId,\n minId,\n maxId,\n fromUser,\n offsetDate,\n addOffset,\n filter,\n search,\n replyTo\n }) {\n var e_1, _a;\n\n if (entity) {\n this.entity = await this.client.getInputEntity(entity);\n } else {\n this.entity = undefined;\n\n if (this.reverse) {\n throw new Error("Cannot reverse global search");\n }\n }\n\n if (this.reverse) {\n offsetId = Math.max(offsetId, minId);\n\n if (offsetId && maxId) {\n if (maxId - offsetId <= 1) {\n return false;\n }\n }\n\n if (!maxId) {\n maxId = Number.MAX_SAFE_INTEGER;\n }\n } else {\n offsetId = Math.max(offsetId, maxId);\n\n if (offsetId && minId) {\n if (offsetId - minId <= 1) {\n return false;\n }\n }\n }\n\n if (this.reverse) {\n if (offsetId) {\n offsetId += 1;\n } else if (!offsetDate) {\n offsetId = 1;\n }\n }\n\n if (fromUser) {\n fromUser = await this.client.getInputEntity(fromUser);\n }\n\n if (!this.entity && fromUser) {\n this.entity = new tl_1.Api.InputPeerEmpty();\n }\n\n if (!filter) {\n filter = new tl_1.Api.InputMessagesFilterEmpty();\n }\n\n if (!this.entity) {\n this.request = new tl_1.Api.messages.SearchGlobal({\n q: search || "",\n filter: filter,\n minDate: undefined,\n // TODO fix this smh\n maxDate: offsetDate,\n offsetRate: undefined,\n offsetPeer: new tl_1.Api.InputPeerEmpty(),\n offsetId: offsetId,\n limit: 1\n });\n } else if (replyTo !== undefined) {\n this.request = new tl_1.Api.messages.GetReplies({\n peer: this.entity,\n msgId: replyTo,\n offsetId: offsetId,\n offsetDate: offsetDate,\n addOffset: addOffset,\n limit: 0,\n maxId: 0,\n minId: 0,\n hash: big_integer_1.default.zero\n });\n } else if (search !== undefined || !(filter instanceof tl_1.Api.InputMessagesFilterEmpty) || fromUser !== undefined) {\n this.request = new tl_1.Api.messages.Search({\n peer: this.entity,\n q: search || "",\n filter: typeof filter === "function" ? new filter() : filter,\n minDate: undefined,\n maxDate: offsetDate,\n offsetId: offsetId,\n addOffset: addOffset,\n limit: 0,\n maxId: 0,\n minId: 0,\n hash: (0, Helpers_1.generateRandomBigInt)(),\n fromId: fromUser\n });\n\n if (!(filter instanceof tl_1.Api.InputMessagesFilterEmpty) && offsetDate && !search && !offsetId) {\n try {\n for (var _b = __asyncValues(this.client.iterMessages(this.entity, {\n limit: 1,\n offsetDate: offsetDate\n })), _c; _c = await _b.next(), !_c.done;) {\n const m = _c.value;\n this.request.offsetId = m.id + 1;\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n }\n } else {\n this.request = new tl_1.Api.messages.GetHistory({\n peer: this.entity,\n limit: 1,\n offsetDate: offsetDate,\n offsetId: offsetId,\n minId: 0,\n maxId: 0,\n addOffset: addOffset,\n hash: big_integer_1.default.zero\n });\n }\n\n if (this.limit <= 0) {\n const result = await this.client.invoke(this.request);\n\n if (result instanceof tl_1.Api.messages.MessagesNotModified) {\n this.total = result.count;\n } else {\n if ("count" in result) {\n this.total = result.count;\n } else {\n this.total = result.messages.length;\n }\n }\n\n return false;\n }\n\n if (!this.waitTime) {\n this.waitTime = this.limit > 3000 ? 1 : 0;\n }\n\n if (this.reverse && !(this.request instanceof tl_1.Api.messages.SearchGlobal)) {\n this.request.addOffset -= _MAX_CHUNK_SIZE;\n }\n\n this.addOffset = addOffset;\n this.maxId = maxId;\n this.minId = minId;\n this.lastId = this.reverse ? 0 : Number.MAX_SAFE_INTEGER;\n }\n\n async _loadNextChunk() {\n var _a;\n\n if (!this.request) {\n throw new Error("Request not set yet");\n }\n\n this.request.limit = Math.min(this.left, _MAX_CHUNK_SIZE);\n\n if (this.reverse && this.request.limit != _MAX_CHUNK_SIZE) {\n if (!(this.request instanceof tl_1.Api.messages.SearchGlobal)) {\n this.request.addOffset = this.addOffset - this.request.limit;\n }\n }\n\n const r = await this.client.invoke(this.request);\n\n if (r instanceof tl_1.Api.messages.MessagesNotModified) {\n return true;\n }\n\n if ("count" in r) {\n this.total = r.count;\n } else {\n this.total = r.messages.length;\n }\n\n const entities = new Map();\n\n for (const x of [...r.users, ...r.chats]) {\n entities.set((0, Utils_1.getPeerId)(x), x);\n }\n\n const messages = this.reverse ? r.messages.reverse() : r.messages;\n\n for (const message of messages) {\n if (!this._messageInRange(message)) {\n return true;\n }\n\n this.lastId = message.id;\n\n try {\n // if this fails it shouldn\'t be a big problem\n message._finishInit(this.client, entities, this.entity);\n } catch (e) {}\n\n message._entities = entities;\n (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.push(message);\n }\n\n if (r.messages.length < this.request.limit) {\n return true;\n }\n\n if (this.buffer) {\n this._updateOffset(this.buffer[this.buffer.length - 1], r);\n } else {\n return true;\n }\n }\n\n _messageInRange(message) {\n if (this.entity) {\n if (this.reverse) {\n if (message.id <= this.lastId || message.id >= this.maxId) {\n return false;\n }\n } else {\n if (message.id >= this.lastId || message.id <= this.minId) {\n return false;\n }\n }\n }\n\n return true;\n }\n\n [Symbol.asyncIterator]() {\n return super[Symbol.asyncIterator]();\n }\n\n _updateOffset(lastMessage, response) {\n if (!this.request) {\n throw new Error("Request not set yet");\n }\n\n this.request.offsetId = Number(lastMessage.id);\n\n if (this.reverse) {\n this.request.offsetId += 1;\n }\n\n if (this.request instanceof tl_1.Api.messages.Search) {\n this.request.maxDate = -1;\n } else {\n if (!(this.request instanceof tl_1.Api.messages.SearchGlobal)) {\n this.request.offsetDate = lastMessage.date;\n }\n }\n\n if (this.request instanceof tl_1.Api.messages.SearchGlobal) {\n if (lastMessage.inputChat) {\n this.request.offsetPeer = lastMessage.inputChat;\n } else {\n this.request.offsetPeer = new tl_1.Api.InputPeerEmpty();\n }\n\n this.request.offsetRate = response.nextRate;\n }\n }\n\n}\n\nexports._MessagesIter = _MessagesIter;\n\nclass _IDsIter extends requestIter_1.RequestIter {\n async _init({\n entity,\n ids\n }) {\n this.total = ids.length;\n this._ids = this.reverse ? ids.reverse() : ids;\n this._offset = 0;\n this._entity = entity ? await this.client.getInputEntity(entity) : undefined;\n this._ty = this._entity ? (0, Helpers_1._entityType)(this._entity) : undefined;\n\n if (!this.waitTime) {\n this.waitTime = this.limit > 300 ? 10 : 0;\n }\n }\n\n [Symbol.asyncIterator]() {\n return super[Symbol.asyncIterator]();\n }\n\n async _loadNextChunk() {\n var _a, _b, _c;\n\n const ids = this._ids.slice(this._offset, this._offset + _MAX_CHUNK_SIZE);\n\n if (!ids.length) {\n return false;\n }\n\n this._offset += _MAX_CHUNK_SIZE;\n let fromId;\n let r;\n\n if (this._ty == Helpers_1._EntityType.CHANNEL) {\n try {\n r = await this.client.invoke(new tl_1.Api.channels.GetMessages({\n channel: this._entity,\n id: ids\n }));\n } catch (e) {\n if (e.errorMessage == "MESSAGE_IDS_EMPTY") {\n r = new tl_1.Api.messages.MessagesNotModified({\n count: ids.length\n });\n } else {\n throw e;\n }\n }\n } else {\n r = await this.client.invoke(new tl_1.Api.messages.GetMessages({\n id: ids\n }));\n\n if (this._entity) {\n fromId = await (0, users_1._getPeer)(this.client, this._entity);\n }\n }\n\n if (r instanceof tl_1.Api.messages.MessagesNotModified) {\n (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.push(...Array(ids.length));\n return;\n }\n\n const entities = new Map();\n\n for (const entity of [...r.users, ...r.chats]) {\n entities.set(__1.utils.getPeerId(entity), entity);\n }\n\n let message;\n\n for (message of r.messages) {\n if (message instanceof tl_1.Api.MessageEmpty || fromId && __1.utils.getPeerId(message.peerId) != __1.utils.getPeerId(fromId)) {\n (_b = this.buffer) === null || _b === void 0 ? void 0 : _b.push(undefined);\n } else {\n const temp = message;\n\n temp._finishInit(this.client, entities, this._entity);\n\n temp._entities = entities;\n (_c = this.buffer) === null || _c === void 0 ? void 0 : _c.push(temp);\n }\n }\n }\n\n}\n\nexports._IDsIter = _IDsIter;\nconst IterMessagesDefaults = {\n limit: undefined,\n offsetDate: undefined,\n offsetId: 0,\n maxId: 0,\n minId: 0,\n addOffset: 0,\n search: undefined,\n filter: undefined,\n fromUser: undefined,\n waitTime: undefined,\n ids: undefined,\n reverse: false,\n replyTo: undefined,\n scheduled: false\n};\n/** @hidden */\n\nfunction iterMessages(client, entity, options) {\n const {\n limit,\n offsetDate,\n offsetId,\n maxId,\n minId,\n addOffset,\n search,\n filter,\n fromUser,\n waitTime,\n ids,\n reverse,\n replyTo\n } = Object.assign(Object.assign({}, IterMessagesDefaults), options);\n\n if (ids) {\n let idsArray;\n\n if (!(0, Helpers_1.isArrayLike)(ids)) {\n idsArray = [ids];\n } else {\n idsArray = ids;\n }\n\n return new _IDsIter(client, idsArray.length, {\n reverse: reverse,\n waitTime: waitTime\n }, {\n entity: entity,\n ids: idsArray\n });\n }\n\n return new _MessagesIter(client, limit, {\n waitTime: waitTime,\n reverse: reverse\n }, {\n entity: entity,\n offsetId: offsetId,\n minId: minId,\n maxId: maxId,\n fromUser: fromUser,\n offsetDate: offsetDate,\n addOffset: addOffset,\n filter: filter,\n search: search,\n replyTo: replyTo\n });\n}\n\nexports.iterMessages = iterMessages;\n/** @hidden */\n\nasync function getMessages(client, entity, params) {\n var e_2, _a;\n\n if (Object.keys(params).length == 1 && params.limit === undefined) {\n if (params.minId === undefined && params.maxId === undefined) {\n params.limit = undefined;\n } else {\n params.limit = 1;\n }\n }\n\n const it = client.iterMessages(entity, params);\n const ids = params.ids;\n\n if (ids && !(0, Helpers_1.isArrayLike)(ids)) {\n try {\n for (var it_1 = __asyncValues(it), it_1_1; it_1_1 = await it_1.next(), !it_1_1.done;) {\n const message = it_1_1.value;\n return [message];\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (it_1_1 && !it_1_1.done && (_a = it_1.return)) await _a.call(it_1);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n return [];\n }\n\n return await it.collect();\n}\n\nexports.getMessages = getMessages; // region Message\n\n/** @hidden */\n\nasync function sendMessage(client,\n/** To who will it be sent. */\nentity,\n/** The message to be sent, or another message object to resend as a copy.
\n * The maximum length for a message is 35,000 bytes or 4,096 characters.
\n * Longer messages will not be sliced automatically, and you should slice them manually if the text to send is longer than said length. */\n{\n message,\n replyTo,\n attributes,\n parseMode,\n formattingEntities,\n linkPreview = true,\n file,\n thumb,\n forceDocument,\n clearDraft,\n buttons,\n silent,\n supportStreaming,\n schedule,\n noforwards,\n commentTo,\n topMsgId\n} = {}) {\n if (file) {\n return client.sendFile(entity, {\n file: file,\n caption: message ? typeof message == "string" ? message : message.message : "",\n forceDocument: forceDocument,\n clearDraft: clearDraft,\n replyTo: replyTo,\n attributes: attributes,\n thumb: thumb,\n supportsStreaming: supportStreaming,\n parseMode: parseMode,\n formattingEntities: formattingEntities,\n silent: silent,\n scheduleDate: schedule,\n buttons: buttons,\n noforwards: noforwards,\n commentTo: commentTo,\n topMsgId: topMsgId\n });\n }\n\n entity = await client.getInputEntity(entity);\n\n if (commentTo != undefined) {\n const discussionData = await getCommentData(client, entity, commentTo);\n entity = discussionData.entity;\n replyTo = discussionData.replyTo;\n }\n\n let markup, request;\n\n if (message && message instanceof tl_1.Api.Message) {\n if (buttons == undefined) {\n markup = message.replyMarkup;\n } else {\n markup = client.buildReplyMarkup(buttons);\n }\n\n if (silent == undefined) {\n silent = message.silent;\n }\n\n if (message.media && !(message.media instanceof tl_1.Api.MessageMediaWebPage)) {\n return client.sendFile(entity, {\n file: message.media,\n caption: message.message,\n silent: silent,\n replyTo: replyTo,\n buttons: markup,\n formattingEntities: message.entities,\n scheduleDate: schedule\n });\n }\n\n request = new tl_1.Api.messages.SendMessage({\n peer: entity,\n message: message.message || "",\n silent: silent,\n replyToMsgId: (0, Utils_1.getMessageId)(replyTo),\n topMsgId: (0, Utils_1.getMessageId)(topMsgId),\n replyMarkup: markup,\n entities: message.entities,\n clearDraft: clearDraft,\n noWebpage: !(message.media instanceof tl_1.Api.MessageMediaWebPage),\n scheduleDate: schedule,\n noforwards: noforwards\n });\n message = message.message;\n } else {\n if (formattingEntities == undefined) {\n [message, formattingEntities] = await (0, messageParse_1._parseMessageText)(client, message || "", parseMode);\n }\n\n if (!message) {\n throw new Error("The message cannot be empty unless a file is provided");\n }\n\n request = new tl_1.Api.messages.SendMessage({\n peer: entity,\n message: message.toString(),\n entities: formattingEntities,\n noWebpage: !linkPreview,\n replyToMsgId: (0, Utils_1.getMessageId)(replyTo),\n clearDraft: clearDraft,\n silent: silent,\n replyMarkup: client.buildReplyMarkup(buttons),\n scheduleDate: schedule,\n noforwards: noforwards\n });\n }\n\n const result = await client.invoke(request);\n\n if (result instanceof tl_1.Api.UpdateShortSentMessage) {\n const msg = new tl_1.Api.Message({\n id: result.id,\n peerId: await (0, users_1._getPeer)(client, entity),\n message: message,\n date: result.date,\n out: result.out,\n media: result.media,\n entities: result.entities,\n replyMarkup: request.replyMarkup,\n ttlPeriod: result.ttlPeriod\n });\n\n msg._finishInit(client, new Map(), entity);\n\n return msg;\n }\n\n return client._getResponseMessage(request, result, entity);\n}\n\nexports.sendMessage = sendMessage;\n/** @hidden */\n\nasync function forwardMessages(client, entity, {\n messages,\n fromPeer,\n silent,\n schedule,\n noforwards,\n dropAuthor\n}) {\n if (!(0, Helpers_1.isArrayLike)(messages)) {\n messages = [messages];\n }\n\n entity = await client.getInputEntity(entity);\n let fromPeerId;\n\n if (fromPeer) {\n fromPeer = await client.getInputEntity(fromPeer);\n fromPeerId = await client.getPeerId(fromPeer);\n }\n\n const getKey = m => {\n if (m instanceof tl_1.Api.Message) {\n return m.chatId;\n }\n\n let msgId = (0, Utils_1.parseID)(m);\n\n if (msgId) {\n if (fromPeerId !== undefined) {\n return fromPeerId;\n }\n\n throw new Error("fromPeer must be given if integer IDs are used");\n } else {\n throw new Error(`Cannot forward ${m}`);\n }\n };\n\n const sent = [];\n\n for (let [chatId, chunk] of (0, Helpers_1.groupBy)(messages, getKey)) {\n let chat;\n let numbers = [];\n\n if (typeof chunk[0] == "number") {\n chat = fromPeer;\n numbers = chunk;\n } else {\n chat = await chunk[0].getInputChat();\n numbers = chunk.map(m => m.id);\n }\n\n chunk.push();\n const request = new tl_1.Api.messages.ForwardMessages({\n fromPeer: chat,\n id: numbers,\n toPeer: entity,\n silent: silent,\n scheduleDate: schedule,\n noforwards: noforwards,\n dropAuthor: dropAuthor\n });\n const result = await client.invoke(request);\n sent.push(client._getResponseMessage(request, result, entity));\n }\n\n return sent;\n}\n\nexports.forwardMessages = forwardMessages;\n/** @hidden */\n\nasync function editMessage(client, entity, {\n message,\n text,\n parseMode,\n formattingEntities,\n linkPreview = true,\n file,\n forceDocument,\n buttons,\n schedule\n}) {\n if (typeof message === "number" && typeof text === "undefined" && !file && !schedule) {\n throw Error("You have to provide either file or text or schedule property.");\n }\n\n entity = await client.getInputEntity(entity);\n let id;\n let markup;\n let entities;\n let inputMedia;\n\n if (file) {\n const {\n fileHandle,\n media,\n image\n } = await (0, uploads_1._fileToMedia)(client, {\n file,\n forceDocument\n });\n inputMedia = media;\n }\n\n if (message instanceof tl_1.Api.Message) {\n id = (0, Utils_1.getMessageId)(message);\n text = message.message;\n entities = message.entities;\n\n if (buttons == undefined) {\n markup = message.replyMarkup;\n } else {\n markup = client.buildReplyMarkup(buttons);\n }\n\n if (message.media) {\n inputMedia = (0, Utils_1.getInputMedia)(message.media, {\n forceDocument\n });\n }\n } else {\n if (typeof message !== "number") {\n throw Error("editMessageParams.message must be either a number or a Api.Message type");\n }\n\n id = message;\n\n if (formattingEntities == undefined) {\n [text, entities] = await (0, messageParse_1._parseMessageText)(client, text || "", parseMode);\n } else {\n entities = formattingEntities;\n }\n\n markup = client.buildReplyMarkup(buttons);\n }\n\n const request = new tl_1.Api.messages.EditMessage({\n peer: entity,\n id,\n message: text,\n noWebpage: !linkPreview,\n entities,\n media: inputMedia,\n replyMarkup: markup,\n scheduleDate: schedule\n });\n const result = await client.invoke(request);\n return client._getResponseMessage(request, result, entity);\n}\n\nexports.editMessage = editMessage;\n/** @hidden */\n\nasync function deleteMessages(client, entity, messageIds, {\n revoke = false\n}) {\n let ty = Helpers_1._EntityType.USER;\n\n if (entity) {\n entity = await client.getInputEntity(entity);\n ty = (0, Helpers_1._entityType)(entity);\n }\n\n const ids = [];\n\n for (const messageId of messageIds) {\n if (messageId instanceof tl_1.Api.Message || messageId instanceof tl_1.Api.MessageService || messageId instanceof tl_1.Api.MessageEmpty) {\n ids.push(messageId.id);\n } else if (typeof messageId === "number") {\n ids.push(messageId);\n } else {\n throw new Error(`Cannot convert ${messageId} to an integer`);\n }\n }\n\n const results = [];\n\n if (ty == Helpers_1._EntityType.CHANNEL) {\n for (const chunk of __1.utils.chunks(ids)) {\n results.push(client.invoke(new tl_1.Api.channels.DeleteMessages({\n channel: entity,\n id: chunk\n })));\n }\n } else {\n for (const chunk of __1.utils.chunks(ids)) {\n results.push(client.invoke(new tl_1.Api.messages.DeleteMessages({\n id: chunk,\n revoke: revoke\n })));\n }\n }\n\n return Promise.all(results);\n}\n\nexports.deleteMessages = deleteMessages;\n/** @hidden */\n\nasync function pinMessage(client, entity, message, pinMessageParams) {\n return await _pin(client, entity, message, false, pinMessageParams === null || pinMessageParams === void 0 ? void 0 : pinMessageParams.notify, pinMessageParams === null || pinMessageParams === void 0 ? void 0 : pinMessageParams.pmOneSide);\n}\n\nexports.pinMessage = pinMessage;\n/** @hidden */\n\nasync function unpinMessage(client, entity, message, unpinMessageParams) {\n return await _pin(client, entity, message, true, unpinMessageParams === null || unpinMessageParams === void 0 ? void 0 : unpinMessageParams.notify, unpinMessageParams === null || unpinMessageParams === void 0 ? void 0 : unpinMessageParams.pmOneSide);\n}\n\nexports.unpinMessage = unpinMessage;\n/** @hidden */\n\nasync function _pin(client, entity, message, unpin, notify = false, pmOneSide = false) {\n message = __1.utils.getMessageId(message) || 0;\n\n if (message === 0) {\n return await client.invoke(new tl_1.Api.messages.UnpinAllMessages({\n peer: entity\n }));\n }\n\n entity = await client.getInputEntity(entity);\n const request = new tl_1.Api.messages.UpdatePinnedMessage({\n silent: !notify,\n unpin,\n pmOneside: pmOneSide,\n peer: entity,\n id: message\n });\n const result = await client.invoke(request);\n /**\n * Unpinning does not produce a service message.\n * Pinning a message that was already pinned also produces no service message.\n * Pinning a message in your own chat does not produce a service message,\n * but pinning on a private conversation with someone else does.\n */\n\n if (unpin || !("updates" in result) || "updates" in result && !result.updates) {\n return;\n } // Pinning a message that doesn\'t exist would RPC-error earlier\n\n\n return client._getResponseMessage(request, result, entity);\n}\n\nexports._pin = _pin;\n/** @hidden */\n\nasync function markAsRead(client, entity, message, markAsReadParams) {\n let maxId = (markAsReadParams === null || markAsReadParams === void 0 ? void 0 : markAsReadParams.maxId) || 0;\n const maxIdIsUndefined = (markAsReadParams === null || markAsReadParams === void 0 ? void 0 : markAsReadParams.maxId) === undefined;\n\n if (maxIdIsUndefined) {\n if (message) {\n if (Array.isArray(message)) {\n maxId = Math.max(...message.map(v => __1.utils.getMessageId(v)));\n } else {\n maxId = __1.utils.getMessageId(message);\n }\n }\n }\n\n entity = await client.getInputEntity(entity);\n\n if (markAsReadParams && !markAsReadParams.clearMentions) {\n await client.invoke(new tl_1.Api.messages.ReadMentions({\n peer: entity\n }));\n\n if (maxIdIsUndefined && message === undefined) {\n return true;\n }\n }\n\n if ((0, Helpers_1._entityType)(entity) === Helpers_1._EntityType.CHANNEL) {\n return await client.invoke(new tl_1.Api.channels.ReadHistory({\n channel: entity,\n maxId\n }));\n } else {\n await client.invoke(new tl_1.Api.messages.ReadHistory({\n peer: entity,\n maxId\n }));\n return true;\n }\n}\n\nexports.markAsRead = markAsRead;\n/** @hidden */\n\nasync function getCommentData(client, entity, message) {\n const result = await client.invoke(new tl_1.Api.messages.GetDiscussionMessage({\n peer: entity,\n msgId: __1.utils.getMessageId(message)\n }));\n const relevantMessage = result.messages[0];\n let chat;\n\n for (const c of result.chats) {\n if (relevantMessage.peerId instanceof tl_1.Api.PeerChannel && c.id.eq(relevantMessage.peerId.channelId)) {\n chat = c;\n break;\n }\n }\n\n return {\n entity: __1.utils.getInputPeer(chat),\n replyTo: relevantMessage.id\n };\n}\n\nexports.getCommentData = getCommentData; // TODO do the rest\n\n//# sourceURL=webpack://telegram/./browser/client/messages.js?')},"./browser/client/os.js": /*!******************************!*\ !*** ./browser/client/os.js ***! \******************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports["default"] = {\n type: () => {\n return "Browser";\n },\n release: () => {\n return "1.0";\n }\n};\n\n//# sourceURL=webpack://telegram/./browser/client/os.js?')},"./browser/client/path.js": /*!********************************!*\ !*** ./browser/client/path.js ***! \********************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports["default"] = {\n basename(...args) {},\n\n resolve(...args) {},\n\n path(...args) {},\n\n join(...args) {}\n\n};\n\n//# sourceURL=webpack://telegram/./browser/client/path.js?')},"./browser/client/telegramBaseClient.js": /*!**********************************************!*\ !*** ./browser/client/telegramBaseClient.js ***! \**********************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.TelegramBaseClient = void 0;\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst connection_1 = __webpack_require__(/*! ../network/connection */ "./browser/network/connection/index.js");\n\nconst sessions_1 = __webpack_require__(/*! ../sessions */ "./browser/sessions/index.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst os_1 = __importDefault(__webpack_require__(/*! ./os */ "./browser/client/os.js"));\n\nconst entityCache_1 = __webpack_require__(/*! ../entityCache */ "./browser/entityCache.js");\n\nconst markdown_1 = __webpack_require__(/*! ../extensions/markdown */ "./browser/extensions/markdown.js");\n\nconst network_1 = __webpack_require__(/*! ../network */ "./browser/network/index.js");\n\nconst AllTLObjects_1 = __webpack_require__(/*! ../tl/AllTLObjects */ "./browser/tl/AllTLObjects.js");\n\nconst TCPMTProxy_1 = __webpack_require__(/*! ../network/connection/TCPMTProxy */ "./browser/network/connection/TCPMTProxy.js");\n\nconst async_mutex_1 = __webpack_require__(/*! async-mutex */ "./node_modules/async-mutex/lib/index.js");\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js");\n\nconst platform_1 = __webpack_require__(/*! ../platform */ "./browser/platform.js");\n\nconst EXPORTED_SENDER_RECONNECT_TIMEOUT = 1000; // 1 sec\n\nconst EXPORTED_SENDER_RELEASE_TIMEOUT = 30000; // 30 sec\n\nconst DEFAULT_DC_ID = 4;\nconst DEFAULT_IPV4_IP = platform_1.isNode ? "149.154.167.91" : "vesta.web.telegram.org";\nconst DEFAULT_IPV6_IP = "2001:067c:04e8:f004:0000:0000:0000:000a";\nconst clientParamsDefault = {\n connection: platform_1.isNode ? connection_1.ConnectionTCPFull : connection_1.ConnectionTCPObfuscated,\n networkSocket: platform_1.isNode ? extensions_1.PromisedNetSockets : extensions_1.PromisedWebSockets,\n useIPV6: false,\n timeout: 10,\n requestRetries: 5,\n connectionRetries: Infinity,\n retryDelay: 1000,\n downloadRetries: 5,\n autoReconnect: true,\n sequentialUpdates: false,\n floodSleepThreshold: 60,\n deviceModel: "",\n systemVersion: "",\n appVersion: "",\n langCode: "en",\n systemLangCode: "en",\n _securityChecks: true,\n useWSS: platform_1.isBrowser ? window.location.protocol == "https:" : false,\n testServers: false\n};\n\nclass TelegramBaseClient {\n constructor(session, apiId, apiHash, clientParams) {\n var _a;\n /** The current gramJS version. */\n\n\n this.__version__ = __1.version;\n /** @hidden */\n\n this._ALBUMS = new Map();\n /** @hidden */\n\n this._exportedSenderPromises = new Map();\n /** @hidden */\n\n this._exportedSenderReleaseTimeouts = new Map();\n clientParams = Object.assign(Object.assign({}, clientParamsDefault), clientParams);\n\n if (!apiId || !apiHash) {\n throw new Error("Your API ID or Hash cannot be empty or undefined");\n }\n\n if (clientParams.baseLogger) {\n this._log = clientParams.baseLogger;\n } else {\n this._log = new extensions_1.Logger();\n }\n\n this._log.info("Running gramJS version " + __1.version);\n\n if (session && typeof session == "string") {\n session = new sessions_1.StoreSession(session);\n }\n\n if (!(session instanceof sessions_1.Session)) {\n throw new Error("Only StringSession and StoreSessions are supported currently :( ");\n }\n\n this._floodSleepThreshold = clientParams.floodSleepThreshold;\n this.session = session;\n this.apiId = apiId;\n this.apiHash = apiHash;\n this._useIPV6 = clientParams.useIPV6;\n this._requestRetries = clientParams.requestRetries;\n this._downloadRetries = clientParams.downloadRetries;\n this._connectionRetries = clientParams.connectionRetries;\n this._retryDelay = clientParams.retryDelay || 0;\n this._timeout = clientParams.timeout;\n this._autoReconnect = clientParams.autoReconnect;\n this._proxy = clientParams.proxy;\n this._semaphore = new async_mutex_1.Semaphore(clientParams.maxConcurrentDownloads || 1);\n this.testServers = clientParams.testServers || false;\n this.networkSocket = clientParams.networkSocket || extensions_1.PromisedNetSockets;\n\n if (!(clientParams.connection instanceof Function)) {\n throw new Error("Connection should be a class not an instance");\n }\n\n this._connection = clientParams.connection;\n let initProxy;\n\n if ((_a = this._proxy) === null || _a === void 0 ? void 0 : _a.MTProxy) {\n this._connection = TCPMTProxy_1.ConnectionTCPMTProxyAbridged;\n initProxy = new tl_1.Api.InputClientProxy({\n address: this._proxy.ip,\n port: this._proxy.port\n });\n }\n\n this._initRequest = new tl_1.Api.InitConnection({\n apiId: this.apiId,\n deviceModel: clientParams.deviceModel || os_1.default.type().toString() || "Unknown",\n systemVersion: clientParams.systemVersion || os_1.default.release().toString() || "1.0",\n appVersion: clientParams.appVersion || "1.0",\n langCode: clientParams.langCode,\n langPack: "",\n systemLangCode: clientParams.systemLangCode,\n proxy: initProxy\n });\n this._eventBuilders = [];\n this._floodWaitedRequests = {};\n this._borrowedSenderPromises = {};\n this._bot = undefined;\n this._selfInputPeer = undefined;\n this.useWSS = clientParams.useWSS;\n this._securityChecks = !!clientParams.securityChecks;\n\n if (this.useWSS && this._proxy) {\n throw new Error("Cannot use SSL with proxies. You need to disable the useWSS client param in TelegramClient");\n }\n\n this._entityCache = new entityCache_1.EntityCache(); // These will be set later\n\n this._config = undefined;\n this._loopStarted = false;\n this._reconnecting = false;\n this._destroyed = false; // parse mode\n\n this._parseMode = markdown_1.MarkdownParser;\n }\n\n get floodSleepThreshold() {\n return this._floodSleepThreshold;\n }\n\n set floodSleepThreshold(value) {\n this._floodSleepThreshold = Math.min(value || 0, 24 * 60 * 60);\n }\n\n set maxConcurrentDownloads(value) {\n // @ts-ignore\n this._semaphore._value = value;\n } // region connecting\n\n\n async _initSession() {\n await this.session.load();\n\n if (!this.session.serverAddress) {\n this.session.setDC(DEFAULT_DC_ID, this._useIPV6 ? DEFAULT_IPV6_IP : DEFAULT_IPV4_IP, this.useWSS ? 443 : 80);\n } else {\n this._useIPV6 = this.session.serverAddress.includes(":");\n }\n }\n\n get connected() {\n return this._sender && this._sender.isConnected();\n }\n\n async disconnect() {\n await this._disconnect();\n await Promise.all(Object.values(this._exportedSenderPromises).map(promise => {\n return promise && promise.then(sender => {\n if (sender) {\n return sender.disconnect();\n }\n\n return undefined;\n });\n }));\n this._exportedSenderPromises = new Map(); // TODO cancel hanging promises\n }\n\n get disconnected() {\n return !this._sender || this._sender._disconnected;\n }\n\n async _disconnect() {\n var _a;\n\n await ((_a = this._sender) === null || _a === void 0 ? void 0 : _a.disconnect());\n }\n /**\n * Disconnects all senders and removes all handlers\n * Disconnect is safer as it will not remove your event handlers\n */\n\n\n async destroy() {\n this._destroyed = true;\n await Promise.all([this.disconnect(), ...Object.values(this._borrowedSenderPromises).map(promise => {\n return promise.then(sender => sender.disconnect());\n })]);\n this._eventBuilders = [];\n }\n /** @hidden */\n\n\n async _authKeyCallback(authKey, dcId) {\n this.session.setAuthKey(authKey, dcId);\n await this.session.save();\n }\n /** @hidden */\n\n\n async _cleanupExportedSender(dcId) {\n if (this.session.dcId !== dcId) {\n this.session.setAuthKey(undefined, dcId);\n }\n\n let sender = await this._exportedSenderPromises.get(dcId);\n\n this._exportedSenderPromises.delete(dcId);\n\n await (sender === null || sender === void 0 ? void 0 : sender.disconnect());\n }\n /** @hidden */\n\n\n async _connectSender(sender, dcId) {\n // if we don\'t already have an auth key we want to use normal DCs not -1\n const dc = await this.getDC(dcId, !!sender.authKey.getKey());\n\n while (true) {\n try {\n await sender.connect(new this._connection({\n ip: dc.ipAddress,\n port: dc.port,\n dcId: dcId,\n loggers: this._log,\n proxy: this._proxy,\n testServers: this.testServers,\n socket: this.networkSocket\n }));\n\n if (this.session.dcId !== dcId && !sender._authenticated) {\n this._log.info(`Exporting authorization for data center ${dc.ipAddress} with layer ${AllTLObjects_1.LAYER}`);\n\n const auth = await this.invoke(new tl_1.Api.auth.ExportAuthorization({\n dcId: dcId\n }));\n this._initRequest.query = new tl_1.Api.auth.ImportAuthorization({\n id: auth.id,\n bytes: auth.bytes\n });\n const req = new tl_1.Api.InvokeWithLayer({\n layer: AllTLObjects_1.LAYER,\n query: this._initRequest\n });\n await sender.send(req);\n sender._authenticated = true;\n }\n\n sender.dcId = dcId;\n sender.userDisconnected = false;\n return sender;\n } catch (err) {\n if (err.errorMessage === "DC_ID_INVALID") {\n sender._authenticated = true;\n sender.userDisconnected = false;\n return sender;\n }\n\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(err);\n }\n\n await (0, Helpers_1.sleep)(1000);\n await sender.disconnect();\n }\n }\n }\n /** @hidden */\n\n\n async _borrowExportedSender(dcId, shouldReconnect, existingSender) {\n if (!this._exportedSenderPromises.get(dcId) || shouldReconnect) {\n this._exportedSenderPromises.set(dcId, this._connectSender(existingSender || this._createExportedSender(dcId), dcId));\n }\n\n let sender;\n\n try {\n sender = await this._exportedSenderPromises.get(dcId);\n\n if (!sender.isConnected()) {\n if (sender.isConnecting) {\n await (0, Helpers_1.sleep)(EXPORTED_SENDER_RECONNECT_TIMEOUT);\n return this._borrowExportedSender(dcId, false, sender);\n } else {\n return this._borrowExportedSender(dcId, true, sender);\n }\n }\n } catch (err) {\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(err);\n }\n\n return this._borrowExportedSender(dcId, true);\n }\n\n if (this._exportedSenderReleaseTimeouts.get(dcId)) {\n clearTimeout(this._exportedSenderReleaseTimeouts.get(dcId));\n\n this._exportedSenderReleaseTimeouts.delete(dcId);\n }\n\n this._exportedSenderReleaseTimeouts.set(dcId, setTimeout(() => {\n this._exportedSenderReleaseTimeouts.delete(dcId);\n\n sender.disconnect();\n }, EXPORTED_SENDER_RELEASE_TIMEOUT));\n\n return sender;\n }\n /** @hidden */\n\n\n _createExportedSender(dcId) {\n return new network_1.MTProtoSender(this.session.getAuthKey(dcId), {\n logger: this._log,\n dcId,\n retries: this._connectionRetries,\n delay: this._retryDelay,\n autoReconnect: this._autoReconnect,\n connectTimeout: this._timeout,\n authKeyCallback: this._authKeyCallback.bind(this),\n isMainSender: dcId === this.session.dcId,\n onConnectionBreak: this._cleanupExportedSender.bind(this),\n client: this,\n securityChecks: this._securityChecks\n });\n }\n /** @hidden */\n\n\n getSender(dcId) {\n return dcId ? this._borrowExportedSender(dcId) : Promise.resolve(this._sender);\n } // endregion\n\n\n async getDC(dcId, download) {\n throw new Error("Cannot be called from here!");\n }\n\n invoke(request) {\n throw new Error("Cannot be called from here!");\n }\n\n setLogLevel(level) {\n this._log.setLevel(level);\n }\n\n get logger() {\n return this._log;\n }\n\n}\n\nexports.TelegramBaseClient = TelegramBaseClient;\n\n//# sourceURL=webpack://telegram/./browser/client/telegramBaseClient.js?')},"./browser/client/updates.js": /*!***********************************!*\ !*** ./browser/client/updates.js ***! \***********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports._updateLoop = exports._dispatchUpdate = exports._processUpdate = exports._handleUpdate = exports.catchUp = exports.listEventHandlers = exports.removeEventHandler = exports.addEventHandler = exports.on = exports.StopPropagation = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst network_1 = __webpack_require__(/*! ../network */ "./browser/network/index.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst PING_INTERVAL = 9000; // 9 sec\n\nconst PING_TIMEOUT = 10000; // 10 sec\n\nconst PING_FAIL_ATTEMPTS = 3;\nconst PING_FAIL_INTERVAL = 100; // ms\n\nconst PING_DISCONNECT_DELAY = 60000; // 1 min\n\n/**\n If this exception is raised in any of the handlers for a given event,\n it will stop the execution of all other registered event handlers.\n It can be seen as the ``StopIteration`` in a for loop but for events.\n */\n\nclass StopPropagation extends Error {}\n\nexports.StopPropagation = StopPropagation;\n/** @hidden */\n\nfunction on(client, event) {\n return f => {\n client.addEventHandler(f, event);\n return f;\n };\n}\n\nexports.on = on;\n/** @hidden */\n\nfunction addEventHandler(client, callback, event) {\n if (event == undefined) {\n // recursive imports :(\n const raw = (__webpack_require__(/*! ../events/Raw */ "./browser/events/Raw.js").Raw);\n\n event = new raw({});\n }\n\n event.client = client;\n\n client._eventBuilders.push([event, callback]);\n}\n\nexports.addEventHandler = addEventHandler;\n/** @hidden */\n\nfunction removeEventHandler(client, callback, event) {\n client._eventBuilders = client._eventBuilders.filter(function (item) {\n return item[0] !== event && item[1] !== callback;\n });\n}\n\nexports.removeEventHandler = removeEventHandler;\n/** @hidden */\n\nfunction listEventHandlers(client) {\n return client._eventBuilders;\n}\n\nexports.listEventHandlers = listEventHandlers;\n/** @hidden */\n\nfunction catchUp() {// TODO\n}\n\nexports.catchUp = catchUp;\n/** @hidden */\n\nfunction _handleUpdate(client, update) {\n if (typeof update === "number") {\n if ([-1, 0, 1].includes(update)) {\n _dispatchUpdate(client, {\n update: new network_1.UpdateConnectionState(update)\n });\n\n return;\n }\n } //this.session.processEntities(update)\n\n\n client._entityCache.add(update);\n\n client.session.processEntities(update);\n\n if (update instanceof tl_1.Api.Updates || update instanceof tl_1.Api.UpdatesCombined) {\n // TODO deal with entities\n const entities = new Map();\n\n for (const x of [...update.users, ...update.chats]) {\n entities.set(index_1.utils.getPeerId(x), x);\n }\n\n for (const u of update.updates) {\n _processUpdate(client, u, update.updates, entities);\n }\n } else if (update instanceof tl_1.Api.UpdateShort) {\n _processUpdate(client, update.update, null);\n } else {\n _processUpdate(client, update, null);\n }\n}\n\nexports._handleUpdate = _handleUpdate;\n/** @hidden */\n\nfunction _processUpdate(client, update, others, entities) {\n update._entities = entities || new Map();\n const args = {\n update: update,\n others: others\n };\n\n _dispatchUpdate(client, args);\n}\n\nexports._processUpdate = _processUpdate;\n/** @hidden */\n\nasync function _dispatchUpdate(client, args) {\n for (const [builder, callback] of client._eventBuilders) {\n if (!builder || !callback) {\n continue;\n }\n\n if (!builder.resolved) {\n await builder.resolve(client);\n }\n\n let event = args.update;\n\n if (event) {\n if (!client._selfInputPeer) {\n try {\n await client.getMe(true);\n } catch (e) {// do nothing\n }\n }\n\n if (!(event instanceof network_1.UpdateConnectionState)) {// TODO fix me\n } // TODO fix others not being passed\n\n\n event = builder.build(event, callback, client._selfInputPeer ? (0, Helpers_1.returnBigInt)(client._selfInputPeer.userId) : undefined);\n\n if (event) {\n event._client = client;\n\n if ("_eventName" in event) {\n event._setClient(client);\n\n event.originalUpdate = args.update;\n event._entities = args.update._entities;\n }\n\n const filter = await builder.filter(event);\n\n if (!filter) {\n continue;\n }\n\n try {\n await callback(event);\n } catch (e) {\n if (e instanceof StopPropagation) {\n break;\n }\n\n console.error(e);\n }\n }\n }\n }\n}\n\nexports._dispatchUpdate = _dispatchUpdate;\n/** @hidden */\n\nasync function _updateLoop(client) {\n var _a;\n\n while (client.connected) {\n try {\n await (0, Helpers_1.sleep)(60 * 1000);\n\n if (!((_a = client._sender) === null || _a === void 0 ? void 0 : _a._transportConnected())) {\n continue;\n }\n\n await client.invoke(new tl_1.Api.Ping({\n pingId: (0, big_integer_1.default)((0, Helpers_1.getRandomInt)(Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER))\n }));\n } catch (e) {\n return;\n }\n\n client.session.save();\n\n if (new Date().getTime() - (client._lastRequest || 0) > 30 * 60 * 1000) {\n try {\n await client.invoke(new tl_1.Api.updates.GetState());\n } catch (e) {// we don\'t care about errors here\n }\n }\n }\n}\n\nexports._updateLoop = _updateLoop;\n/** @hidden */\n\nasync function attempts(cb, times, pause) {\n for (let i = 0; i < times; i++) {\n try {\n // We need to `return await` here so it can be caught locally\n return await cb();\n } catch (err) {\n if (i === times - 1) {\n throw err;\n }\n\n await (0, Helpers_1.sleep)(pause);\n }\n }\n\n return undefined;\n}\n/** @hidden */\n\n\nfunction timeout(promise, ms) {\n return Promise.race([promise, (0, Helpers_1.sleep)(ms).then(() => Promise.reject(new Error("TIMEOUT")))]);\n}\n\n//# sourceURL=webpack://telegram/./browser/client/updates.js?')},"./browser/client/uploads.js": /*!***********************************!*\ !*** ./browser/client/uploads.js ***! \***********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.sendFile = exports._sendAlbum = exports._fileToMedia = exports.uploadFile = exports.CustomFile = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst path_1 = __importDefault(__webpack_require__(/*! ./path */ "./browser/client/path.js"));\n\nconst fs_1 = __webpack_require__(/*! ./fs */ "./browser/client/fs.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n\nconst messageParse_1 = __webpack_require__(/*! ./messageParse */ "./browser/client/messageParse.js");\n\nconst messages_1 = __webpack_require__(/*! ./messages */ "./browser/client/messages.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n/**\n * A custom file class that mimics the browser\'s File class.
\n * You should use this whenever you want to upload a file.\n */\n\n\nclass CustomFile {\n constructor(name, size, path, buffer) {\n this.name = name;\n this.size = size;\n this.path = path;\n this.buffer = buffer;\n }\n\n}\n\nexports.CustomFile = CustomFile;\n\nclass CustomBuffer {\n constructor(options) {\n this.options = options;\n\n if (!options.buffer && !options.filePath) {\n throw new Error("Either one of `buffer` or `filePath` should be specified");\n }\n }\n\n async slice(begin, end) {\n const {\n buffer,\n filePath\n } = this.options;\n\n if (buffer) {\n return buffer.slice(begin, end);\n } else if (filePath) {\n const buffSize = end - begin;\n const buff = buffer_1.Buffer.alloc(buffSize);\n const fHandle = await fs_1.promises.open(filePath, "r");\n await fHandle.read(buff, 0, buffSize, begin);\n await fHandle.close();\n return buffer_1.Buffer.from(buff);\n }\n\n return buffer_1.Buffer.alloc(0);\n }\n\n}\n\nconst KB_TO_BYTES = 1024;\nconst LARGE_FILE_THRESHOLD = 10 * 1024 * 1024;\nconst UPLOAD_TIMEOUT = 15 * 1000;\nconst DISCONNECT_SLEEP = 1000;\nconst BUFFER_SIZE_2GB = 2 ** 31;\n\nasync function getFileBuffer(file, fileSize, maxBufferSize) {\n const options = {};\n\n if (fileSize > maxBufferSize && file instanceof CustomFile) {\n options.filePath = file.path;\n } else {\n options.buffer = buffer_1.Buffer.from(await fileToBuffer(file));\n }\n\n return new CustomBuffer(options);\n}\n/** @hidden */\n\n\nasync function uploadFile(client, fileParams) {\n const {\n file,\n onProgress\n } = fileParams;\n let {\n workers\n } = fileParams;\n const {\n name,\n size\n } = file;\n const fileId = (0, Helpers_1.readBigIntFromBuffer)((0, Helpers_1.generateRandomBytes)(8), true, true);\n const isLarge = size > LARGE_FILE_THRESHOLD;\n const partSize = (0, Utils_1.getAppropriatedPartSize)((0, big_integer_1.default)(size)) * KB_TO_BYTES;\n const partCount = Math.floor((size + partSize - 1) / partSize);\n const buffer = await getFileBuffer(file, size, fileParams.maxBufferSize || BUFFER_SIZE_2GB - 1); // Make sure a new sender can be created before starting upload\n\n await client.getSender(client.session.dcId);\n\n if (!workers || !size) {\n workers = 1;\n }\n\n if (workers >= partCount) {\n workers = partCount;\n }\n\n let progress = 0;\n\n if (onProgress) {\n onProgress(progress);\n }\n\n for (let i = 0; i < partCount; i += workers) {\n const sendingParts = [];\n let end = i + workers;\n\n if (end > partCount) {\n end = partCount;\n }\n\n for (let j = i; j < end; j++) {\n const bytes = await buffer.slice(j * partSize, (j + 1) * partSize); // eslint-disable-next-line no-loop-func\n\n sendingParts.push((async (jMemo, bytesMemo) => {\n while (true) {\n let sender;\n\n try {\n // We always upload from the DC we are in\n sender = await client.getSender(client.session.dcId);\n await sender.send(isLarge ? new tl_1.Api.upload.SaveBigFilePart({\n fileId,\n filePart: jMemo,\n fileTotalParts: partCount,\n bytes: bytesMemo\n }) : new tl_1.Api.upload.SaveFilePart({\n fileId,\n filePart: jMemo,\n bytes: bytesMemo\n }));\n } catch (err) {\n if (sender && !sender.isConnected()) {\n await (0, Helpers_1.sleep)(DISCONNECT_SLEEP);\n continue;\n } else if (err instanceof index_1.errors.FloodWaitError) {\n await (0, Helpers_1.sleep)(err.seconds * 1000);\n continue;\n }\n\n throw err;\n }\n\n if (onProgress) {\n if (onProgress.isCanceled) {\n throw new Error("USER_CANCELED");\n }\n\n progress += 1 / partCount;\n onProgress(progress);\n }\n\n break;\n }\n })(j, bytes));\n }\n\n await Promise.all(sendingParts);\n }\n\n return isLarge ? new tl_1.Api.InputFileBig({\n id: fileId,\n parts: partCount,\n name\n }) : new tl_1.Api.InputFile({\n id: fileId,\n parts: partCount,\n name,\n md5Checksum: "" // This is not a "flag", so not sure if we can make it optional.\n\n });\n}\n\nexports.uploadFile = uploadFile;\n/** @hidden */\n\nasync function _fileToMedia(client, {\n file,\n forceDocument,\n fileSize,\n progressCallback,\n attributes,\n thumb,\n voiceNote = false,\n videoNote = false,\n supportsStreaming = false,\n mimeType,\n asImage,\n workers = 1\n}) {\n if (!file) {\n return {\n fileHandle: undefined,\n media: undefined,\n image: undefined\n };\n }\n\n const isImage = index_1.utils.isImage(file);\n\n if (asImage == undefined) {\n asImage = isImage && !forceDocument;\n }\n\n if (typeof file == "object" && !buffer_1.Buffer.isBuffer(file) && !(file instanceof tl_1.Api.InputFile) && !(file instanceof tl_1.Api.InputFileBig) && !(file instanceof CustomFile) && !("read" in file)) {\n try {\n return {\n fileHandle: undefined,\n media: index_1.utils.getInputMedia(file, {\n isPhoto: asImage,\n attributes: attributes,\n forceDocument: forceDocument,\n voiceNote: voiceNote,\n videoNote: videoNote,\n supportsStreaming: supportsStreaming\n }),\n image: asImage\n };\n } catch (e) {\n return {\n fileHandle: undefined,\n media: undefined,\n image: isImage\n };\n }\n }\n\n let media;\n let fileHandle;\n let createdFile;\n\n if (file instanceof tl_1.Api.InputFile || file instanceof tl_1.Api.InputFileBig) {\n fileHandle = file;\n } else if (typeof file == "string" && (file.startsWith("https://") || file.startsWith("http://"))) {\n if (asImage) {\n media = new tl_1.Api.InputMediaPhotoExternal({\n url: file\n });\n } else {\n media = new tl_1.Api.InputMediaDocumentExternal({\n url: file\n });\n }\n } else if (!(typeof file == "string") || (await fs_1.promises.lstat(file)).isFile()) {\n if (typeof file == "string") {\n createdFile = new CustomFile(path_1.default.basename(file), (await fs_1.promises.stat(file)).size, file);\n } else if (typeof File !== "undefined" && file instanceof File || file instanceof CustomFile) {\n createdFile = file;\n } else {\n let name;\n\n if ("name" in file) {\n // @ts-ignore\n name = file.name;\n } else {\n name = "unnamed";\n }\n\n if (buffer_1.Buffer.isBuffer(file)) {\n createdFile = new CustomFile(name, file.length, "", file);\n }\n }\n\n if (!createdFile) {\n throw new Error(`Could not create file from ${JSON.stringify(file)}`);\n }\n\n fileHandle = await uploadFile(client, {\n file: createdFile,\n onProgress: progressCallback,\n workers: workers\n });\n } else {\n throw new Error(`"Not a valid path nor a url ${file}`);\n }\n\n if (media != undefined) {} else if (fileHandle == undefined) {\n throw new Error(`Failed to convert ${file} to media. Not an existing file or an HTTP URL`);\n } else if (asImage) {\n media = new tl_1.Api.InputMediaUploadedPhoto({\n file: fileHandle\n });\n } else {\n // @ts-ignore\n let res = index_1.utils.getAttributes(file, {\n mimeType: mimeType,\n attributes: attributes,\n forceDocument: forceDocument && !isImage,\n voiceNote: voiceNote,\n videoNote: videoNote,\n supportsStreaming: supportsStreaming,\n thumb: thumb\n });\n attributes = res.attrs;\n mimeType = res.mimeType;\n let uploadedThumb;\n\n if (!thumb) {\n uploadedThumb = undefined;\n } else {\n // todo refactor\n if (typeof thumb == "string") {\n uploadedThumb = new CustomFile(path_1.default.basename(thumb), (await fs_1.promises.stat(thumb)).size, thumb);\n } else if (typeof File !== "undefined" && thumb instanceof File) {\n uploadedThumb = thumb;\n } else {\n let name;\n\n if ("name" in thumb) {\n name = thumb.name;\n } else {\n name = "unnamed";\n }\n\n if (buffer_1.Buffer.isBuffer(thumb)) {\n uploadedThumb = new CustomFile(name, thumb.length, "", thumb);\n }\n }\n\n if (!uploadedThumb) {\n throw new Error(`Could not create file from ${file}`);\n }\n\n uploadedThumb = await uploadFile(client, {\n file: uploadedThumb,\n workers: 1\n });\n }\n\n media = new tl_1.Api.InputMediaUploadedDocument({\n file: fileHandle,\n mimeType: mimeType,\n attributes: attributes,\n thumb: uploadedThumb,\n forceFile: forceDocument && !isImage\n });\n }\n\n return {\n fileHandle: fileHandle,\n media: media,\n image: asImage\n };\n}\n\nexports._fileToMedia = _fileToMedia;\n/** @hidden */\n\nasync function _sendAlbum(client, entity, {\n file,\n caption,\n forceDocument = false,\n fileSize,\n clearDraft = false,\n progressCallback,\n replyTo,\n attributes,\n thumb,\n parseMode,\n voiceNote = false,\n videoNote = false,\n silent,\n supportsStreaming = false,\n scheduleDate,\n workers = 1,\n noforwards,\n commentTo,\n topMsgId\n}) {\n entity = await client.getInputEntity(entity);\n let files = [];\n\n if (!Array.isArray(file)) {\n files = [file];\n } else {\n files = file;\n }\n\n if (!Array.isArray(caption)) {\n if (!caption) {\n caption = "";\n }\n\n caption = [caption];\n }\n\n const captions = [];\n\n for (const c of caption) {\n captions.push(await (0, messageParse_1._parseMessageText)(client, c, parseMode));\n }\n\n if (commentTo != undefined) {\n const discussionData = await (0, messages_1.getCommentData)(client, entity, commentTo);\n entity = discussionData.entity;\n replyTo = discussionData.replyTo;\n } else {\n replyTo = index_1.utils.getMessageId(replyTo);\n }\n\n const albumFiles = [];\n\n for (const file of files) {\n let {\n fileHandle,\n media,\n image\n } = await _fileToMedia(client, {\n file: file,\n forceDocument: forceDocument,\n fileSize: fileSize,\n progressCallback: progressCallback,\n attributes: attributes,\n thumb: thumb,\n voiceNote: voiceNote,\n videoNote: videoNote,\n supportsStreaming: supportsStreaming,\n workers: workers\n });\n\n if (media instanceof tl_1.Api.InputMediaUploadedPhoto || media instanceof tl_1.Api.InputMediaPhotoExternal) {\n const r = await client.invoke(new tl_1.Api.messages.UploadMedia({\n peer: entity,\n media\n }));\n\n if (r instanceof tl_1.Api.MessageMediaPhoto) {\n media = (0, Utils_1.getInputMedia)(r.photo);\n }\n } else if (media instanceof tl_1.Api.InputMediaUploadedDocument) {\n const r = await client.invoke(new tl_1.Api.messages.UploadMedia({\n peer: entity,\n media\n }));\n\n if (r instanceof tl_1.Api.MessageMediaDocument) {\n media = (0, Utils_1.getInputMedia)(r.document);\n }\n }\n\n let text = "";\n let msgEntities = [];\n\n if (captions.length) {\n [text, msgEntities] = captions.shift();\n }\n\n albumFiles.push(new tl_1.Api.InputSingleMedia({\n media: media,\n message: text,\n entities: msgEntities\n }));\n }\n\n const result = await client.invoke(new tl_1.Api.messages.SendMultiMedia({\n peer: entity,\n replyToMsgId: replyTo,\n topMsgId: index_1.utils.getMessageId(topMsgId),\n multiMedia: albumFiles,\n silent: silent,\n scheduleDate: scheduleDate,\n clearDraft: clearDraft,\n noforwards: noforwards\n }));\n const randomIds = albumFiles.map(m => m.randomId);\n return client._getResponseMessage(randomIds, result, entity);\n}\n\nexports._sendAlbum = _sendAlbum;\n/** @hidden */\n\nasync function sendFile(client, entity, {\n file,\n caption,\n forceDocument = false,\n fileSize,\n clearDraft = false,\n progressCallback,\n replyTo,\n attributes,\n thumb,\n parseMode,\n formattingEntities,\n voiceNote = false,\n videoNote = false,\n buttons,\n silent,\n supportsStreaming = false,\n scheduleDate,\n workers = 1,\n noforwards,\n commentTo,\n topMsgId\n}) {\n if (!file) {\n throw new Error("You need to specify a file");\n }\n\n if (!caption) {\n caption = "";\n }\n\n entity = await client.getInputEntity(entity);\n\n if (commentTo != undefined) {\n const discussionData = await (0, messages_1.getCommentData)(client, entity, commentTo);\n entity = discussionData.entity;\n replyTo = discussionData.replyTo;\n } else {\n replyTo = index_1.utils.getMessageId(replyTo);\n }\n\n if (Array.isArray(file)) {\n return await _sendAlbum(client, entity, {\n file: file,\n caption: caption,\n replyTo: replyTo,\n parseMode: parseMode,\n silent: silent,\n scheduleDate: scheduleDate,\n supportsStreaming: supportsStreaming,\n clearDraft: clearDraft,\n forceDocument: forceDocument,\n noforwards: noforwards\n });\n }\n\n if (Array.isArray(caption)) {\n caption = caption[0] || "";\n }\n\n let msgEntities;\n\n if (formattingEntities != undefined) {\n msgEntities = formattingEntities;\n } else {\n [caption, msgEntities] = await (0, messageParse_1._parseMessageText)(client, caption, parseMode);\n }\n\n const {\n fileHandle,\n media,\n image\n } = await _fileToMedia(client, {\n file: file,\n forceDocument: forceDocument,\n fileSize: fileSize,\n progressCallback: progressCallback,\n attributes: attributes,\n thumb: thumb,\n voiceNote: voiceNote,\n videoNote: videoNote,\n supportsStreaming: supportsStreaming,\n workers: workers\n });\n\n if (media == undefined) {\n throw new Error(`Cannot use ${file} as file.`);\n }\n\n const markup = client.buildReplyMarkup(buttons);\n const request = new tl_1.Api.messages.SendMedia({\n peer: entity,\n media: media,\n replyToMsgId: replyTo,\n topMsgId: index_1.utils.getMessageId(topMsgId),\n message: caption,\n entities: msgEntities,\n replyMarkup: markup,\n silent: silent,\n scheduleDate: scheduleDate,\n clearDraft: clearDraft,\n noforwards: noforwards\n });\n const result = await client.invoke(request);\n return client._getResponseMessage(request, result, entity);\n}\n\nexports.sendFile = sendFile;\n\nfunction fileToBuffer(file) {\n if (typeof File !== "undefined" && file instanceof File) {\n return new Response(file).arrayBuffer();\n } else if (file instanceof CustomFile) {\n if (file.buffer != undefined) {\n return file.buffer;\n } else {\n return fs_1.promises.readFile(file.path);\n }\n } else {\n throw new Error("Could not create buffer from file " + file);\n }\n}\n\n//# sourceURL=webpack://telegram/./browser/client/uploads.js?')},"./browser/client/users.js": /*!*********************************!*\ !*** ./browser/client/users.js ***! \*********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports._selfId = exports._getInputNotify = exports._getInputDialog = exports._getPeer = exports.getPeerId = exports._getEntityFromString = exports.getInputEntity = exports.getEntity = exports.isUserAuthorized = exports.isBot = exports.getMe = exports.invoke = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js"); // UserMethods {\n// region Invoking Telegram request\n\n/** @hidden */\n\n\nasync function invoke(client, request, sender) {\n if (request.classType !== "request") {\n throw new Error("You can only invoke MTProtoRequests");\n }\n\n if (!sender) {\n sender = client._sender;\n }\n\n if (sender == undefined) {\n throw new Error("Cannot send requests while disconnected. You need to call .connect()");\n }\n\n await request.resolve(client, __1.utils);\n client._lastRequest = new Date().getTime();\n let attempt;\n\n for (attempt = 0; attempt < client._requestRetries; attempt++) {\n try {\n const promise = sender.send(request);\n const result = await promise;\n client.session.processEntities(result);\n\n client._entityCache.add(result);\n\n return result;\n } catch (e) {\n if (e instanceof __1.errors.ServerError || e.errorMessage === "RPC_CALL_FAIL" || e.errorMessage === "RPC_MCGET_FAIL") {\n client._log.warn(`Telegram is having internal issues ${e.constructor.name}`);\n\n await (0, Helpers_1.sleep)(2000);\n } else if (e instanceof __1.errors.FloodWaitError || e instanceof __1.errors.FloodTestPhoneWaitError) {\n if (e.seconds <= client.floodSleepThreshold) {\n client._log.info(`Sleeping for ${e.seconds}s on flood wait (Caused by ${request.className})`);\n\n await (0, Helpers_1.sleep)(e.seconds * 1000);\n } else {\n throw e;\n }\n } else if (e instanceof __1.errors.PhoneMigrateError || e instanceof __1.errors.NetworkMigrateError || e instanceof __1.errors.UserMigrateError) {\n client._log.info(`Phone migrated to ${e.newDc}`);\n\n const shouldRaise = e instanceof __1.errors.PhoneMigrateError || e instanceof __1.errors.NetworkMigrateError;\n\n if (shouldRaise && (await client.isUserAuthorized())) {\n throw e;\n }\n\n await client._switchDC(e.newDc);\n } else {\n throw e;\n }\n }\n }\n\n throw new Error(`Request was unsuccessful ${attempt} time(s)`);\n}\n\nexports.invoke = invoke;\n/** @hidden */\n\nasync function getMe(client, inputPeer = false) {\n if (inputPeer && client._selfInputPeer) {\n return client._selfInputPeer;\n }\n\n const me = (await client.invoke(new tl_1.Api.users.GetUsers({\n id: [new tl_1.Api.InputUserSelf()]\n })))[0];\n client._bot = me.bot;\n\n if (!client._selfInputPeer) {\n client._selfInputPeer = __1.utils.getInputPeer(me, false);\n }\n\n return inputPeer ? client._selfInputPeer : me;\n}\n\nexports.getMe = getMe;\n/** @hidden */\n\nasync function isBot(client) {\n if (client._bot === undefined) {\n const me = await client.getMe();\n\n if (me) {\n return !(me instanceof tl_1.Api.InputPeerUser) ? me.bot : undefined;\n }\n }\n\n return client._bot;\n}\n\nexports.isBot = isBot;\n/** @hidden */\n\nasync function isUserAuthorized(client) {\n try {\n await client.invoke(new tl_1.Api.updates.GetState());\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexports.isUserAuthorized = isUserAuthorized;\n/** @hidden */\n\nasync function getEntity(client, entity) {\n const single = !(0, Helpers_1.isArrayLike)(entity);\n let entityArray = [];\n\n if ((0, Helpers_1.isArrayLike)(entity)) {\n entityArray = entity;\n } else {\n entityArray.push(entity);\n }\n\n const inputs = [];\n\n for (const x of entityArray) {\n if (typeof x === "string") {\n const valid = (0, Utils_1.parseID)(x);\n\n if (valid) {\n inputs.push(await client.getInputEntity(valid));\n } else {\n inputs.push(x);\n }\n } else {\n inputs.push(await client.getInputEntity(x));\n }\n }\n\n const lists = new Map([[Helpers_1._EntityType.USER, []], [Helpers_1._EntityType.CHAT, []], [Helpers_1._EntityType.CHANNEL, []]]);\n\n for (const x of inputs) {\n try {\n lists.get((0, Helpers_1._entityType)(x)).push(x);\n } catch (e) {}\n }\n\n let users = lists.get(Helpers_1._EntityType.USER);\n let chats = lists.get(Helpers_1._EntityType.CHAT);\n let channels = lists.get(Helpers_1._EntityType.CHANNEL);\n\n if (users.length) {\n users = await client.invoke(new tl_1.Api.users.GetUsers({\n id: users\n }));\n }\n\n if (chats.length) {\n const chatIds = chats.map(x => x.chatId);\n chats = (await client.invoke(new tl_1.Api.messages.GetChats({\n id: chatIds\n }))).chats;\n }\n\n if (channels.length) {\n channels = (await client.invoke(new tl_1.Api.channels.GetChannels({\n id: channels\n }))).chats;\n }\n\n const idEntity = new Map();\n\n for (const user of users) {\n idEntity.set((0, Utils_1.getPeerId)(user), user);\n }\n\n for (const channel of channels) {\n idEntity.set((0, Utils_1.getPeerId)(channel), channel);\n }\n\n for (const chat of chats) {\n idEntity.set((0, Utils_1.getPeerId)(chat), chat);\n }\n\n const result = [];\n\n for (const x of inputs) {\n if (typeof x === "string") {\n result.push(await _getEntityFromString(client, x));\n } else if (!(x instanceof tl_1.Api.InputPeerSelf)) {\n result.push(idEntity.get((0, Utils_1.getPeerId)(x)));\n } else {\n for (const [key, u] of idEntity.entries()) {\n if (u instanceof tl_1.Api.User && u.self) {\n result.push(u);\n break;\n }\n }\n }\n }\n\n return single ? result[0] : result;\n}\n\nexports.getEntity = getEntity;\n/** @hidden */\n\nasync function getInputEntity(client, peer) {\n // Short-circuit if the input parameter directly maps to an InputPeer\n try {\n return __1.utils.getInputPeer(peer); // eslint-disable-next-line no-empty\n } catch (e) {} // Next in priority is having a peer (or its ID) cached in-memory\n\n\n try {\n if (typeof peer == "string") {\n const valid = (0, Utils_1.parseID)(peer);\n\n if (valid) {\n const res = client._entityCache.get(peer);\n\n if (res) {\n return res;\n }\n }\n }\n\n if (typeof peer === "number" || typeof peer === "bigint" || big_integer_1.default.isInstance(peer)) {\n const res = client._entityCache.get(peer.toString());\n\n if (res) {\n return res;\n }\n } // 0x2d45687 == crc32(b\'Peer\')\n\n\n if (typeof peer == "object" && !big_integer_1.default.isInstance(peer) && peer.SUBCLASS_OF_ID === 0x2d45687) {\n const res = client._entityCache.get(__1.utils.getPeerId(peer));\n\n if (res) {\n return res;\n }\n } // eslint-disable-next-line no-empty\n\n } catch (e) {} // Then come known strings that take precedence\n\n\n if (typeof peer == "string") {\n if (["me", "this", "self"].includes(peer)) {\n return new tl_1.Api.InputPeerSelf();\n }\n } // No InputPeer, cached peer, or known string. Fetch from disk cache\n\n\n try {\n if (peer != undefined) {\n return client.session.getInputEntity(peer);\n } // eslint-disable-next-line no-empty\n\n } catch (e) {} // Only network left to try\n\n\n if (typeof peer === "string") {\n return __1.utils.getInputPeer(await _getEntityFromString(client, peer));\n } // If we\'re a bot and the user has messaged us privately users.getUsers\n // will work with accessHash = 0. Similar for channels.getChannels.\n // If we\'re not a bot but the user is in our contacts, it seems to work\n // regardless. These are the only two special-cased requests.\n\n\n if (typeof peer === "number") {\n peer = (0, Helpers_1.returnBigInt)(peer);\n }\n\n peer = __1.utils.getPeer(peer);\n\n if (peer instanceof tl_1.Api.PeerUser) {\n const users = await client.invoke(new tl_1.Api.users.GetUsers({\n id: [new tl_1.Api.InputUser({\n userId: peer.userId,\n accessHash: big_integer_1.default.zero\n })]\n }));\n\n if (users.length && !(users[0] instanceof tl_1.Api.UserEmpty)) {\n // If the user passed a valid ID they expect to work for\n // channels but would be valid for users, we get UserEmpty.\n // Avoid returning the invalid empty input peer for that.\n //\n // We *could* try to guess if it\'s a channel first, and if\n // it\'s not, work as a chat and try to validate it through\n // another request, but that becomes too much work.\n return __1.utils.getInputPeer(users[0]);\n }\n } else if (peer instanceof tl_1.Api.PeerChat) {\n return new tl_1.Api.InputPeerChat({\n chatId: peer.chatId\n });\n } else if (peer instanceof tl_1.Api.PeerChannel) {\n try {\n const channels = await client.invoke(new tl_1.Api.channels.GetChannels({\n id: [new tl_1.Api.InputChannel({\n channelId: peer.channelId,\n accessHash: big_integer_1.default.zero\n })]\n }));\n return __1.utils.getInputPeer(channels.chats[0]);\n } catch (e) {\n if (client._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(e);\n }\n }\n }\n\n throw new Error(`Could not find the input entity for ${JSON.stringify(peer)}.\n Please read https://` + "docs.telethon.dev/en/stable/concepts/entities.html to" + " find out more details.");\n}\n\nexports.getInputEntity = getInputEntity;\n/** @hidden */\n\nasync function _getEntityFromString(client, string) {\n const phone = __1.utils.parsePhone(string);\n\n if (phone) {\n try {\n const result = await client.invoke(new tl_1.Api.contacts.GetContacts({\n hash: big_integer_1.default.zero\n }));\n\n if (!(result instanceof tl_1.Api.contacts.ContactsNotModified)) {\n for (const user of result.users) {\n if (user instanceof tl_1.Api.User && user.phone === phone) {\n return user;\n }\n }\n }\n } catch (e) {\n if (e.errorMessage === "BOT_METHOD_INVALID") {\n throw new Error("Cannot get entity by phone number as a " + "bot (try using integer IDs, not strings)");\n }\n\n throw e;\n }\n }\n\n const id = __1.utils.parseID(string);\n\n if (id != undefined) {\n return getInputEntity(client, id);\n } else if (["me", "this"].includes(string.toLowerCase())) {\n return client.getMe();\n } else {\n const {\n username,\n isInvite\n } = __1.utils.parseUsername(string);\n\n if (isInvite) {\n const invite = await client.invoke(new tl_1.Api.messages.CheckChatInvite({\n hash: username\n }));\n\n if (invite instanceof tl_1.Api.ChatInvite) {\n throw new Error("Cannot get entity from a channel (or group) " + "that you are not part of. Join the group and retry");\n } else if (invite instanceof tl_1.Api.ChatInviteAlready) {\n return invite.chat;\n }\n } else if (username) {\n try {\n const result = await client.invoke(new tl_1.Api.contacts.ResolveUsername({\n username: username\n }));\n\n const pid = __1.utils.getPeerId(result.peer, false);\n\n if (result.peer instanceof tl_1.Api.PeerUser) {\n for (const x of result.users) {\n if ((0, Helpers_1.returnBigInt)(x.id).equals((0, Helpers_1.returnBigInt)(pid))) {\n return x;\n }\n }\n } else {\n for (const x of result.chats) {\n if ((0, Helpers_1.returnBigInt)(x.id).equals((0, Helpers_1.returnBigInt)(pid))) {\n return x;\n }\n }\n }\n } catch (e) {\n if (e.errorMessage === "USERNAME_NOT_OCCUPIED") {\n throw new Error(`No user has "${username}" as username`);\n }\n\n throw e;\n }\n }\n }\n\n throw new Error(`Cannot find any entity corresponding to "${string}"`);\n}\n\nexports._getEntityFromString = _getEntityFromString;\n/** @hidden */\n\nasync function getPeerId(client, peer, addMark = true) {\n if (typeof peer == "string") {\n const valid = (0, Utils_1.parseID)(peer);\n\n if (valid) {\n return __1.utils.getPeerId(peer, addMark);\n } else {\n peer = await client.getInputEntity(peer);\n }\n }\n\n if (typeof peer == "number" || typeof peer == "bigint" || big_integer_1.default.isInstance(peer)) {\n return __1.utils.getPeerId(peer, addMark);\n }\n\n if (peer.SUBCLASS_OF_ID == 0x2d45687 || peer.SUBCLASS_OF_ID == 0xc91c90b6) {\n peer = await client.getInputEntity(peer);\n }\n\n if (peer instanceof tl_1.Api.InputPeerSelf) {\n peer = await client.getMe(true);\n }\n\n return __1.utils.getPeerId(peer, addMark);\n}\n\nexports.getPeerId = getPeerId;\n/** @hidden */\n\nasync function _getPeer(client, peer) {\n if (!peer) {\n return undefined;\n }\n\n const [i, cls] = __1.utils.resolveId((0, Helpers_1.returnBigInt)(await client.getPeerId(peer)));\n\n return new cls({\n userId: i,\n channelId: i,\n chatId: i\n });\n}\n\nexports._getPeer = _getPeer;\n/** @hidden */\n\nasync function _getInputDialog(client, dialog) {\n try {\n if (dialog.SUBCLASS_OF_ID == 0xa21c9795) {\n // crc32(b\'InputDialogPeer\')\n dialog.peer = await client.getInputEntity(dialog.peer);\n return dialog;\n } else if (dialog.SUBCLASS_OF_ID == 0xc91c90b6) {\n //crc32(b\'InputPeer\')\n return new tl_1.Api.InputDialogPeer({\n peer: dialog\n });\n }\n } catch (e) {}\n\n return new tl_1.Api.InputDialogPeer({\n peer: dialog\n });\n}\n\nexports._getInputDialog = _getInputDialog;\n/** @hidden */\n\nasync function _getInputNotify(client, notify) {\n try {\n if (notify.SUBCLASS_OF_ID == 0x58981615) {\n if (notify instanceof tl_1.Api.InputNotifyPeer) {\n notify.peer = await client.getInputEntity(notify.peer);\n }\n\n return notify;\n }\n } catch (e) {}\n\n return new tl_1.Api.InputNotifyPeer({\n peer: await client.getInputEntity(notify)\n });\n}\n\nexports._getInputNotify = _getInputNotify;\n/** @hidden */\n\nfunction _selfId(client) {\n return client._selfInputPeer ? client._selfInputPeer.userId : undefined;\n}\n\nexports._selfId = _selfId;\n\n//# sourceURL=webpack://telegram/./browser/client/users.js?')},"./browser/crypto/AuthKey.js": /*!***********************************!*\ !*** ./browser/crypto/AuthKey.js ***! \***********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.AuthKey = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst Helpers_2 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nclass AuthKey {\n constructor(value, hash) {\n if (!hash || !value) {\n return;\n }\n\n this._key = value;\n this._hash = hash;\n const reader = new extensions_1.BinaryReader(hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async setKey(value) {\n if (!value) {\n this._key = this.auxHash = this.keyId = this._hash = undefined;\n return;\n }\n\n if (value instanceof AuthKey) {\n this._key = value._key;\n this.auxHash = value.auxHash;\n this.keyId = value.keyId;\n this._hash = value._hash;\n return;\n }\n\n this._key = value;\n this._hash = await (0, Helpers_1.sha1)(this._key);\n const reader = new extensions_1.BinaryReader(this._hash);\n this.auxHash = reader.readLong(false);\n reader.read(4);\n this.keyId = reader.readLong(false);\n }\n\n async waitForKey() {\n while (!this.keyId) {\n await (0, Helpers_2.sleep)(20);\n }\n }\n\n getKey() {\n return this._key;\n } // TODO : This doesn\'t really fit here, it\'s only used in authentication\n\n /**\n * Calculates the new nonce hash based on the current class fields\' values\n * @param newNonce\n * @param number\n * @returns {bigInt.BigInteger}\n */\n\n\n async calcNewNonceHash(newNonce, number) {\n if (this.auxHash) {\n const nonce = (0, Helpers_1.toSignedLittleBuffer)(newNonce, 32);\n const n = buffer_1.Buffer.alloc(1);\n n.writeUInt8(number, 0);\n const data = buffer_1.Buffer.concat([nonce, buffer_1.Buffer.concat([n, (0, Helpers_1.readBufferFromBigInt)(this.auxHash, 8, true)])]); // Calculates the message key from the given data\n\n const shaData = (await (0, Helpers_1.sha1)(data)).slice(4, 20);\n return (0, Helpers_1.readBigIntFromBuffer)(shaData, true, true);\n }\n\n throw new Error("Auth key not set");\n }\n\n equals(other) {\n var _a;\n\n return other instanceof this.constructor && this._key && buffer_1.Buffer.isBuffer(other.getKey()) && ((_a = other.getKey()) === null || _a === void 0 ? void 0 : _a.equals(this._key));\n }\n\n}\n\nexports.AuthKey = AuthKey;\n\n//# sourceURL=webpack://telegram/./browser/crypto/AuthKey.js?')},"./browser/crypto/CTR.js": /*!*******************************!*\ !*** ./browser/crypto/CTR.js ***! \*******************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.CTR = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst crypto = __importStar(__webpack_require__(/*! ./crypto */ "./browser/crypto/crypto.js"));\n\nclass CTR {\n constructor(key, iv) {\n if (!buffer_1.Buffer.isBuffer(key) || !buffer_1.Buffer.isBuffer(iv) || iv.length !== 16) {\n throw new Error("Key and iv need to be a buffer");\n }\n\n this.cipher = crypto.createCipheriv("AES-256-CTR", key, iv);\n }\n\n encrypt(data) {\n return buffer_1.Buffer.from(this.cipher.update(data));\n }\n\n}\n\nexports.CTR = CTR;\n\n//# sourceURL=webpack://telegram/./browser/crypto/CTR.js?')},"./browser/crypto/Factorizator.js": /*!****************************************!*\ !*** ./browser/crypto/Factorizator.js ***! \****************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Factorizator = void 0;\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nclass Factorizator {\n /**\n * Calculates the greatest common divisor\n * @param a {BigInteger}\n * @param b {BigInteger}\n * @returns {BigInteger}\n */\n static gcd(a, b) {\n while (b.neq(big_integer_1.default.zero)) {\n const temp = b;\n b = a.remainder(b);\n a = temp;\n }\n\n return a;\n }\n /**\n * Factorizes the given number and returns both the divisor and the number divided by the divisor\n * @param pq {BigInteger}\n * @returns {{p: *, q: *}}\n */\n\n\n static factorize(pq) {\n if (pq.remainder(2).equals(big_integer_1.default.zero)) {\n return {\n p: (0, big_integer_1.default)(2),\n q: pq.divide((0, big_integer_1.default)(2))\n };\n }\n\n let y = big_integer_1.default.randBetween((0, big_integer_1.default)(1), pq.minus(1));\n const c = big_integer_1.default.randBetween((0, big_integer_1.default)(1), pq.minus(1));\n const m = big_integer_1.default.randBetween((0, big_integer_1.default)(1), pq.minus(1));\n let g = big_integer_1.default.one;\n let r = big_integer_1.default.one;\n let q = big_integer_1.default.one;\n let x = big_integer_1.default.zero;\n let ys = big_integer_1.default.zero;\n let k;\n\n while (g.eq(big_integer_1.default.one)) {\n x = y;\n\n for (let i = 0; (0, big_integer_1.default)(i).lesser(r); i++) {\n y = (0, Helpers_1.modExp)(y, (0, big_integer_1.default)(2), pq).add(c).remainder(pq);\n }\n\n k = big_integer_1.default.zero;\n\n while (k.lesser(r) && g.eq(big_integer_1.default.one)) {\n ys = y;\n const condition = big_integer_1.default.min(m, r.minus(k));\n\n for (let i = 0; (0, big_integer_1.default)(i).lesser(condition); i++) {\n y = (0, Helpers_1.modExp)(y, (0, big_integer_1.default)(2), pq).add(c).remainder(pq);\n q = q.multiply(x.minus(y).abs()).remainder(pq);\n }\n\n g = Factorizator.gcd(q, pq);\n k = k.add(m);\n }\n\n r = r.multiply(2);\n }\n\n if (g.eq(pq)) {\n while (true) {\n ys = (0, Helpers_1.modExp)(ys, (0, big_integer_1.default)(2), pq).add(c).remainder(pq);\n g = Factorizator.gcd(x.minus(ys).abs(), pq);\n\n if (g.greater(1)) {\n break;\n }\n }\n }\n\n const p = g;\n q = pq.divide(g);\n return p < q ? {\n p: p,\n q: q\n } : {\n p: q,\n q: p\n };\n }\n\n}\n\nexports.Factorizator = Factorizator;\n\n//# sourceURL=webpack://telegram/./browser/crypto/Factorizator.js?')},"./browser/crypto/IGE.js": /*!*******************************!*\ !*** ./browser/crypto/IGE.js ***! \*******************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.IGE = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst {\n IGE: aes_ige\n} = __webpack_require__(/*! @cryptography/aes */ "./node_modules/@cryptography/aes/dist/es/aes.js");\n\nclass IGENEW {\n constructor(key, iv) {\n this.ige = new aes_ige(key, iv);\n }\n /**\n * Decrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param cipherText {Buffer}\n * @returns {Buffer}\n */\n\n\n decryptIge(cipherText) {\n return Helpers.convertToLittle(this.ige.decrypt(cipherText));\n }\n /**\n * Encrypts the given text in 16-bytes blocks by using the given key and 32-bytes initialization vector\n * @param plainText {Buffer}\n * @returns {Buffer}\n */\n\n\n encryptIge(plainText) {\n const padding = plainText.length % 16;\n\n if (padding) {\n plainText = buffer_1.Buffer.concat([plainText, Helpers.generateRandomBytes(16 - padding)]);\n }\n\n return Helpers.convertToLittle(this.ige.encrypt(plainText));\n }\n\n}\n\nexports.IGE = IGENEW;\n\n//# sourceURL=webpack://telegram/./browser/crypto/IGE.js?')},"./browser/crypto/RSA.js": /*!*******************************!*\ !*** ./browser/crypto/RSA.js ***! \*******************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __rest = this && this.__rest || function (s, e) {\n var t = {};\n\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];\n\n if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];\n }\n return t;\n};\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.encrypt = exports._serverKeys = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst PUBLIC_KEYS = [{\n fingerprint: (0, big_integer_1.default)("-3414540481677951611"),\n n: (0, big_integer_1.default)("2937959817066933702298617714945612856538843112005886376816255642404751219133084745514657634448776440866" + "1701890505066208632169112269581063774293102577308490531282748465986139880977280302242772832972539403531" + "3160108704012876427630091361567343395380424193887227773571344877461690935390938502512438971889287359033" + "8945177273024525306296338410881284207988753897636046529094613963869149149606209957083647645485599631919" + "2747663615955633778034897140982517446405334423701359108810182097749467210509584293428076654573384828809" + "574217079944388301239431309115013843331317877374435868468779972014486325557807783825502498215169806323"),\n e: 65537\n}, {\n fingerprint: (0, big_integer_1.default)("-5595554452916591101"),\n n: (0, big_integer_1.default)("2534288944884041556497168959071347320689884775908477905258202659454602246385394058588521595116849196570822" + "26493991806038180742006204637761354248846321625124031637930839216416315647409595294193595958529411668489405859523" + "37613333022396096584117954892216031229237302943701877588456738335398602461675225081791820393153757504952636234951" + "32323782003654358104782690612092797248736680529211579223142368426126233039432475078545094258975175539015664775146" + "07193514399690599495696153028090507215003302390050778898553239175099482557220816446894421272976054225797071426466" + "60768825302832201908302295573257427896031830742328565032949"),\n e: 65537\n}];\nexports._serverKeys = new Map();\nPUBLIC_KEYS.forEach(_a => {\n var {\n fingerprint\n } = _a,\n keyInfo = __rest(_a, ["fingerprint"]);\n\n exports._serverKeys.set(fingerprint.toString(), keyInfo);\n});\n/**\n * Encrypts the given data known the fingerprint to be used\n * in the way Telegram requires us to do so (sha1(data) + data + padding)\n\n * @param fingerprint the fingerprint of the RSA key.\n * @param data the data to be encrypted.\n * @returns {Buffer|*|undefined} the cipher text, or undefined if no key matching this fingerprint is found.\n */\n\nasync function encrypt(fingerprint, data) {\n const key = exports._serverKeys.get(fingerprint.toString());\n\n if (!key) {\n return undefined;\n } // len(sha1.digest) is always 20, so we\'re left with 255 - 20 - x padding\n\n\n const rand = (0, Helpers_1.generateRandomBytes)(235 - data.length);\n const toEncrypt = buffer_1.Buffer.concat([await (0, Helpers_1.sha1)(data), data, rand]); // rsa module rsa.encrypt adds 11 bits for padding which we don\'t want\n // rsa module uses rsa.transform.bytes2int(to_encrypt), easier way:\n\n const payload = (0, Helpers_1.readBigIntFromBuffer)(toEncrypt, false);\n const encrypted = (0, Helpers_1.modExp)(payload, (0, big_integer_1.default)(key.e), key.n); // rsa module uses transform.int2bytes(encrypted, keylength), easier:\n\n return (0, Helpers_1.readBufferFromBigInt)(encrypted, 256, false);\n}\n\nexports.encrypt = encrypt;\n\n//# sourceURL=webpack://telegram/./browser/crypto/RSA.js?')},"./browser/crypto/converters.js": /*!**************************************!*\ !*** ./browser/crypto/converters.js ***! \**************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ab2i = exports.i2ab = exports.isBigEndian = exports.ab2iBig = exports.ab2iLow = exports.i2abBig = exports.i2abLow = void 0;\n/**\n * Uint32Array -> ArrayBuffer (low-endian os)\n */\n\nfunction i2abLow(buf) {\n const uint8 = new Uint8Array(buf.length * 4);\n let i = 0;\n\n for (let j = 0; j < buf.length; j++) {\n const int = buf[j];\n uint8[i++] = int >>> 24;\n uint8[i++] = int >> 16 & 0xff;\n uint8[i++] = int >> 8 & 0xff;\n uint8[i++] = int & 0xff;\n }\n\n return uint8.buffer;\n}\n\nexports.i2abLow = i2abLow;\n/**\n * Uint32Array -> ArrayBuffer (big-endian os)\n */\n\nfunction i2abBig(buf) {\n return buf.buffer;\n}\n\nexports.i2abBig = i2abBig;\n/**\n * ArrayBuffer -> Uint32Array (low-endian os)\n */\n\nfunction ab2iLow(ab) {\n const uint8 = new Uint8Array(ab);\n const buf = new Uint32Array(uint8.length / 4);\n\n for (let i = 0; i < uint8.length; i += 4) {\n buf[i / 4] = uint8[i] << 24 ^ uint8[i + 1] << 16 ^ uint8[i + 2] << 8 ^ uint8[i + 3];\n }\n\n return buf;\n}\n\nexports.ab2iLow = ab2iLow;\n/**\n * ArrayBuffer -> Uint32Array (big-endian os)\n */\n\nfunction ab2iBig(ab) {\n return new Uint32Array(ab);\n}\n\nexports.ab2iBig = ab2iBig;\nexports.isBigEndian = new Uint8Array(new Uint32Array([0x01020304]))[0] === 0x01;\nexports.i2ab = exports.isBigEndian ? i2abBig : i2abLow;\nexports.ab2i = exports.isBigEndian ? ab2iBig : ab2iLow;\n\n//# sourceURL=webpack://telegram/./browser/crypto/converters.js?')},"./browser/crypto/crypto.js": /*!**********************************!*\ !*** ./browser/crypto/crypto.js ***! \**********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.createHash = exports.pbkdf2Sync = exports.Hash = exports.randomBytes = exports.createCipheriv = exports.createDecipheriv = exports.CTR = exports.Counter = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst aes_1 = __importDefault(__webpack_require__(/*! @cryptography/aes */ "./node_modules/@cryptography/aes/dist/es/aes.js"));\n\nconst converters_1 = __webpack_require__(/*! ./converters */ "./browser/crypto/converters.js");\n\nconst words_1 = __webpack_require__(/*! ./words */ "./browser/crypto/words.js");\n\nclass Counter {\n constructor(initialValue) {\n this._counter = buffer_1.Buffer.from(initialValue);\n }\n\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (this._counter[i] === 255) {\n this._counter[i] = 0;\n } else {\n this._counter[i]++;\n break;\n }\n }\n }\n\n}\n\nexports.Counter = Counter;\n\nclass CTR {\n constructor(key, counter) {\n if (!(counter instanceof Counter)) {\n counter = new Counter(counter);\n }\n\n this._counter = counter;\n this._remainingCounter = undefined;\n this._remainingCounterIndex = 16;\n this._aes = new aes_1.default((0, words_1.getWords)(key));\n }\n\n update(plainText) {\n return this.encrypt(plainText);\n }\n\n encrypt(plainText) {\n const encrypted = buffer_1.Buffer.from(plainText);\n\n for (let i = 0; i < encrypted.length; i++) {\n if (this._remainingCounterIndex === 16) {\n this._remainingCounter = buffer_1.Buffer.from((0, converters_1.i2ab)(this._aes.encrypt((0, converters_1.ab2i)(this._counter._counter))));\n this._remainingCounterIndex = 0;\n\n this._counter.increment();\n }\n\n if (this._remainingCounter) {\n encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++];\n }\n }\n\n return encrypted;\n }\n\n}\n\nexports.CTR = CTR; // endregion\n\nfunction createDecipheriv(algorithm, key, iv) {\n if (algorithm.includes("ECB")) {\n throw new Error("Not supported");\n } else {\n return new CTR(key, iv);\n }\n}\n\nexports.createDecipheriv = createDecipheriv;\n\nfunction createCipheriv(algorithm, key, iv) {\n if (algorithm.includes("ECB")) {\n throw new Error("Not supported");\n } else {\n return new CTR(key, iv);\n }\n}\n\nexports.createCipheriv = createCipheriv;\n\nfunction randomBytes(count) {\n const bytes = new Uint8Array(count);\n crypto.getRandomValues(bytes);\n return bytes;\n}\n\nexports.randomBytes = randomBytes;\n\nclass Hash {\n constructor(algorithm) {\n this.algorithm = algorithm;\n }\n\n update(data) {\n //We shouldn\'t be needing new Uint8Array but it doesn\'t\n //work without it\n this.data = new Uint8Array(data);\n }\n\n async digest() {\n if (this.data) {\n if (this.algorithm === "sha1") {\n return buffer_1.Buffer.from(await self.crypto.subtle.digest("SHA-1", this.data));\n } else if (this.algorithm === "sha256") {\n return buffer_1.Buffer.from(await self.crypto.subtle.digest("SHA-256", this.data));\n }\n }\n\n return buffer_1.Buffer.alloc(0);\n }\n\n}\n\nexports.Hash = Hash;\n\nasync function pbkdf2Sync(password, salt, iterations, ...args) {\n const passwordKey = await crypto.subtle.importKey("raw", password, {\n name: "PBKDF2"\n }, false, ["deriveBits"]);\n return buffer_1.Buffer.from(await crypto.subtle.deriveBits({\n name: "PBKDF2",\n hash: "SHA-512",\n salt,\n iterations\n }, passwordKey, 512));\n}\n\nexports.pbkdf2Sync = pbkdf2Sync;\n\nfunction createHash(algorithm) {\n return new Hash(algorithm);\n}\n\nexports.createHash = createHash;\n\n//# sourceURL=webpack://telegram/./browser/crypto/crypto.js?')},"./browser/crypto/words.js": /*!*********************************!*\ !*** ./browser/crypto/words.js ***! \*********************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n/*\n * Imported from https://github.com/spalt08/cryptography/blob/master/packages/aes/src/utils/words.ts\n */\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.xor = exports.getWords = exports.s2i = void 0;\n\nfunction s2i(str, pos) {\n return str.charCodeAt(pos) << 24 ^ str.charCodeAt(pos + 1) << 16 ^ str.charCodeAt(pos + 2) << 8 ^ str.charCodeAt(pos + 3);\n}\n\nexports.s2i = s2i;\n/**\n * Helper function for transforming string key to Uint32Array\n */\n\nfunction getWords(key) {\n if (key instanceof Uint32Array) {\n return key;\n }\n\n if (typeof key === "string") {\n if (key.length % 4 !== 0) for (let i = key.length % 4; i <= 4; i++) key += "\\0x00";\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) buf[i / 4] = s2i(key, i);\n\n return buf;\n }\n\n if (key instanceof Uint8Array) {\n const buf = new Uint32Array(key.length / 4);\n\n for (let i = 0; i < key.length; i += 4) {\n buf[i / 4] = key[i] << 24 ^ key[i + 1] << 16 ^ key[i + 2] << 8 ^ key[i + 3];\n }\n\n return buf;\n }\n\n throw new Error("Unable to create 32-bit words");\n}\n\nexports.getWords = getWords;\n\nfunction xor(left, right, to = left) {\n for (let i = 0; i < left.length; i++) to[i] = left[i] ^ right[i];\n}\n\nexports.xor = xor;\n\n//# sourceURL=webpack://telegram/./browser/crypto/words.js?')},"./browser/entityCache.js": /*!********************************!*\ !*** ./browser/entityCache.js ***! \********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval(' // Which updates have the following fields?\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.EntityCache = void 0;\n\nconst Utils_1 = __webpack_require__(/*! ./Utils */ "./browser/Utils.js");\n\nconst Helpers_1 = __webpack_require__(/*! ./Helpers */ "./browser/Helpers.js");\n\nconst tl_1 = __webpack_require__(/*! ./tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nclass EntityCache {\n constructor() {\n this.cacheMap = new Map();\n }\n\n add(entities) {\n const temp = [];\n\n if (!(0, Helpers_1.isArrayLike)(entities)) {\n if (entities != undefined) {\n if (typeof entities == "object") {\n if ("chats" in entities) {\n temp.push(...entities.chats);\n }\n\n if ("users" in entities) {\n temp.push(...entities.users);\n }\n\n if ("user" in entities) {\n temp.push(entities.user);\n }\n }\n }\n\n if (temp.length) {\n entities = temp;\n } else {\n return;\n }\n }\n\n for (const entity of entities) {\n try {\n const pid = (0, Utils_1.getPeerId)(entity);\n\n if (!this.cacheMap.has(pid.toString())) {\n this.cacheMap.set(pid.toString(), (0, Utils_1.getInputPeer)(entity));\n }\n } catch (e) {}\n }\n }\n\n get(item) {\n if (item == undefined) {\n throw new Error("No cached entity for the given key");\n }\n\n item = (0, Helpers_1.returnBigInt)(item);\n\n if (item.lesser(big_integer_1.default.zero)) {\n let res;\n\n try {\n res = this.cacheMap.get((0, Utils_1.getPeerId)(item).toString());\n\n if (res) {\n return res;\n }\n } catch (e) {\n throw new Error("Invalid key will not have entity");\n }\n }\n\n for (const cls of [tl_1.Api.PeerUser, tl_1.Api.PeerChat, tl_1.Api.PeerChannel]) {\n const result = this.cacheMap.get((0, Utils_1.getPeerId)(new cls({\n userId: item,\n chatId: item,\n channelId: item\n })).toString());\n\n if (result) {\n return result;\n }\n }\n\n throw new Error("No cached entity for the given key");\n }\n\n}\n\nexports.EntityCache = EntityCache;\n\n//# sourceURL=webpack://telegram/./browser/entityCache.js?')},"./browser/errors/Common.js": /*!**********************************!*\ !*** ./browser/errors/Common.js ***! \**********************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.BadMessageError = exports.CdnFileTamperedError = exports.SecurityError = exports.InvalidBufferError = exports.InvalidChecksumError = exports.TypeNotFoundError = exports.ReadCancelledError = void 0;\n/**\n * Occurs when a read operation was cancelled.\n */\n\nclass ReadCancelledError extends Error {\n constructor() {\n super("The read operation was cancelled.");\n }\n\n}\n\nexports.ReadCancelledError = ReadCancelledError;\n/**\n * Occurs when a type is not found, for example,\n * when trying to read a TLObject with an invalid constructor code.\n */\n\nclass TypeNotFoundError extends Error {\n constructor(invalidConstructorId, remaining) {\n super(`Could not find a matching Constructor ID for the TLObject that was supposed to be\n read with ID ${invalidConstructorId}. Most likely, a TLObject was trying to be read when\n it should not be read. Remaining bytes: ${remaining.length}`);\n\n if (typeof alert !== "undefined") {\n alert(`Missing MTProto Entity: Please, make sure to add TL definition for ID ${invalidConstructorId}`);\n }\n\n this.invalidConstructorId = invalidConstructorId;\n this.remaining = remaining;\n }\n\n}\n\nexports.TypeNotFoundError = TypeNotFoundError;\n/**\n * Occurs when using the TCP full mode and the checksum of a received\n * packet doesn\'t match the expected checksum.\n */\n\nclass InvalidChecksumError extends Error {\n constructor(checksum, validChecksum) {\n super(`Invalid checksum (${checksum} when ${validChecksum} was expected). This packet should be skipped.`);\n this.checksum = checksum;\n this.validChecksum = validChecksum;\n }\n\n}\n\nexports.InvalidChecksumError = InvalidChecksumError;\n/**\n * Occurs when the buffer is invalid, and may contain an HTTP error code.\n * For instance, 404 means "forgotten/broken authorization key", while\n */\n\nclass InvalidBufferError extends Error {\n constructor(payload) {\n let code = undefined;\n\n if (payload.length === 4) {\n code = -payload.readInt32LE(0);\n super(`Invalid response buffer (HTTP code ${code})`);\n } else {\n super(`Invalid response buffer (too short ${payload})`);\n }\n\n this.code = code;\n this.payload = payload;\n }\n\n}\n\nexports.InvalidBufferError = InvalidBufferError;\n/**\n * Generic security error, mostly used when generating a new AuthKey.\n */\n\nclass SecurityError extends Error {\n constructor(...args) {\n if (!args.length) {\n args = ["A security check failed."];\n }\n\n super(...args);\n }\n\n}\n\nexports.SecurityError = SecurityError;\n/**\n * Occurs when there\'s a hash mismatch between the decrypted CDN file\n * and its expected hash.\n */\n\nclass CdnFileTamperedError extends SecurityError {\n constructor() {\n super("The CDN file has been altered and its download cancelled.");\n }\n\n}\n\nexports.CdnFileTamperedError = CdnFileTamperedError;\n/**\n * Occurs when handling a badMessageNotification\n */\n\nclass BadMessageError extends Error {\n constructor(request, code) {\n let errorMessage = BadMessageError.ErrorMessages[code] || `Unknown error code (this should not happen): ${code}.`;\n errorMessage += ` Caused by ${request.className}`;\n super(errorMessage);\n this.errorMessage = errorMessage;\n this.code = code;\n }\n\n}\n\nexports.BadMessageError = BadMessageError;\nBadMessageError.ErrorMessages = {\n 16: "msg_id too low (most likely, client time is wrong it would be worthwhile to " + "synchronize it using msg_id notifications and re-send the original message " + "with the “correct” msg_id or wrap it in a container with a new msg_id if the " + "original message had waited too long on the client to be transmitted).",\n 17: "msg_id too high (similar to the previous case, the client time has to be " + "synchronized, and the message re-sent with the correct msg_id).",\n 18: "Incorrect two lower order msg_id bits (the server expects client message msg_id " + "to be divisible by 4).",\n 19: "Container msg_id is the same as msg_id of a previously received message " + "(this must never happen).",\n 20: "Message too old, and it cannot be verified whether the server has received a " + "message with this msg_id or not.",\n 32: "msg_seqno too low (the server has already received a message with a lower " + "msg_id but with either a higher or an equal and odd seqno).",\n 33: "msg_seqno too high (similarly, there is a message with a higher msg_id but with " + "either a lower or an equal and odd seqno).",\n 34: "An even msg_seqno expected (irrelevant message), but odd received.",\n 35: "Odd msg_seqno expected (relevant message), but even received.",\n 48: "Incorrect server salt (in this case, the bad_server_salt response is received with " + "the correct salt, and the message is to be re-sent with it).",\n 64: "Invalid container."\n};\n\n//# sourceURL=webpack://telegram/./browser/errors/Common.js?')},"./browser/errors/RPCBaseErrors.js": /*!*****************************************!*\ !*** ./browser/errors/RPCBaseErrors.js ***! \*****************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.TimedOutError = exports.ServerError = exports.FloodError = exports.AuthKeyError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.InvalidDCError = exports.RPCError = void 0;\n\nconst ts_custom_error_1 = __webpack_require__(/*! ts-custom-error */ "./node_modules/ts-custom-error/dist/custom-error.mjs");\n\nclass RPCError extends ts_custom_error_1.CustomError {\n constructor(message, request, code) {\n super("{0}: {1}{2}".replace("{0}", (code === null || code === void 0 ? void 0 : code.toString()) || "").replace("{1}", message || "").replace("{2}", RPCError._fmtRequest(request)));\n this.code = code;\n this.errorMessage = message;\n }\n\n static _fmtRequest(request) {\n // TODO fix this\n if (request) {\n return ` (caused by ${request.className})`;\n } else {\n return "";\n }\n }\n\n}\n\nexports.RPCError = RPCError;\n/**\n * The request must be repeated, but directed to a different data center.\n */\n\nclass InvalidDCError extends RPCError {\n constructor(message, request, code) {\n super(message, request, code);\n this.code = code || 303;\n this.errorMessage = message || "ERROR_SEE_OTHER";\n }\n\n}\n\nexports.InvalidDCError = InvalidDCError;\n/**\n * The query contains errors. In the event that a request was created\n * using a form and contains user generated data, the user should be\n * notified that the data must be corrected before the query is repeated.\n */\n\nclass BadRequestError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 400;\n this.errorMessage = "BAD_REQUEST";\n }\n\n}\n\nexports.BadRequestError = BadRequestError;\n/**\n * There was an unauthorized attempt to use functionality available only\n * to authorized users.\n */\n\nclass UnauthorizedError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 401;\n this.errorMessage = "UNAUTHORIZED";\n }\n\n}\n\nexports.UnauthorizedError = UnauthorizedError;\n/**\n * Privacy violation. For example, an attempt to write a message to\n * someone who has blacklisted the current user.\n */\n\nclass ForbiddenError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 403;\n this.errorMessage = "FORBIDDEN";\n }\n\n}\n\nexports.ForbiddenError = ForbiddenError;\n/**\n * An attempt to invoke a non-existent object, such as a method.\n */\n\nclass NotFoundError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 404;\n this.errorMessage = "NOT_FOUND";\n }\n\n}\n\nexports.NotFoundError = NotFoundError;\n/**\n * Errors related to invalid authorization key, like\n * AUTH_KEY_DUPLICATED which can cause the connection to fail.\n */\n\nclass AuthKeyError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 406;\n this.errorMessage = "AUTH_KEY";\n }\n\n}\n\nexports.AuthKeyError = AuthKeyError;\n/**\n * The maximum allowed number of attempts to invoke the given method\n * with the given input parameters has been exceeded. For example, in an\n * attempt to request a large number of text messages (SMS) for the same\n * phone number.\n */\n\nclass FloodError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 420;\n this.errorMessage = "FLOOD";\n }\n\n}\n\nexports.FloodError = FloodError;\n/**\n * An internal server error occurred while a request was being processed\n * for example, there was a disruption while accessing a database or file\n * storage\n */\n\nclass ServerError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 500; // Also witnessed as -500\n\n this.errorMessage = "INTERNAL";\n }\n\n}\n\nexports.ServerError = ServerError;\n/**\n * Clicking the inline buttons of bots that never (or take to long to)\n * call ``answerCallbackQuery`` will result in this "special" RPCError.\n */\n\nclass TimedOutError extends RPCError {\n constructor() {\n super(...arguments);\n this.code = 503; // Only witnessed as -503\n\n this.errorMessage = "Timeout";\n }\n\n}\n\nexports.TimedOutError = TimedOutError;\n\n//# sourceURL=webpack://telegram/./browser/errors/RPCBaseErrors.js?')},"./browser/errors/RPCErrorList.js": /*!****************************************!*\ !*** ./browser/errors/RPCErrorList.js ***! \****************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.rpcErrorRe = exports.MsgWaitError = exports.EmailUnconfirmedError = exports.NetworkMigrateError = exports.FileMigrateError = exports.FloodTestPhoneWaitError = exports.FloodWaitError = exports.SlowModeWaitError = exports.PhoneMigrateError = exports.UserMigrateError = void 0;\n\nconst RPCBaseErrors_1 = __webpack_require__(/*! ./RPCBaseErrors */ "./browser/errors/RPCBaseErrors.js");\n\nclass UserMigrateError extends RPCBaseErrors_1.InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `The user whose identity is being used to execute queries is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.newDc = newDc;\n }\n\n}\n\nexports.UserMigrateError = UserMigrateError;\n\nclass PhoneMigrateError extends RPCBaseErrors_1.InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `The phone number a user is trying to use for authorization is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.newDc = newDc;\n }\n\n}\n\nexports.PhoneMigrateError = PhoneMigrateError;\n\nclass SlowModeWaitError extends RPCBaseErrors_1.FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required before sending another message in this chat` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `A wait of ${seconds} seconds is required before sending another message in this chat` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.seconds = seconds;\n }\n\n}\n\nexports.SlowModeWaitError = SlowModeWaitError;\n\nclass FloodWaitError extends RPCBaseErrors_1.FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `A wait of ${seconds} seconds is required` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.seconds = seconds;\n }\n\n}\n\nexports.FloodWaitError = FloodWaitError;\n\nclass FloodTestPhoneWaitError extends RPCBaseErrors_1.FloodError {\n constructor(args) {\n const seconds = Number(args.capture || 0);\n super(`A wait of ${seconds} seconds is required in the test servers` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `A wait of ${seconds} seconds is required in the test servers` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.seconds = seconds;\n }\n\n}\n\nexports.FloodTestPhoneWaitError = FloodTestPhoneWaitError;\n\nclass FileMigrateError extends RPCBaseErrors_1.InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The file to be accessed is currently stored in DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `The file to be accessed is currently stored in DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.newDc = newDc;\n }\n\n}\n\nexports.FileMigrateError = FileMigrateError;\n\nclass NetworkMigrateError extends RPCBaseErrors_1.InvalidDCError {\n constructor(args) {\n const newDc = Number(args.capture || 0);\n super(`The source IP address is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request), args.request);\n this.message = `The source IP address is associated with DC ${newDc}` + RPCBaseErrors_1.RPCError._fmtRequest(args.request);\n this.newDc = newDc;\n }\n\n}\n\nexports.NetworkMigrateError = NetworkMigrateError;\n\nclass EmailUnconfirmedError extends RPCBaseErrors_1.BadRequestError {\n constructor(args) {\n const codeLength = Number(args.capture || 0);\n super(`Email unconfirmed, the length of the code must be ${codeLength}${RPCBaseErrors_1.RPCError._fmtRequest(args.request)}`, args.request, 400); // eslint-disable-next-line max-len\n\n this.message = `Email unconfirmed, the length of the code must be ${codeLength}${RPCBaseErrors_1.RPCError._fmtRequest(args.request)}`;\n this.codeLength = codeLength;\n }\n\n}\n\nexports.EmailUnconfirmedError = EmailUnconfirmedError;\n\nclass MsgWaitError extends RPCBaseErrors_1.FloodError {\n constructor(args) {\n super(`Message failed to be sent.${RPCBaseErrors_1.RPCError._fmtRequest(args.request)}`, args.request);\n this.message = `Message failed to be sent.${RPCBaseErrors_1.RPCError._fmtRequest(args.request)}`;\n }\n\n}\n\nexports.MsgWaitError = MsgWaitError;\nexports.rpcErrorRe = new Map([[/FILE_MIGRATE_(\\d+)/, FileMigrateError], [/FLOOD_TEST_PHONE_WAIT_(\\d+)/, FloodTestPhoneWaitError], [/FLOOD_WAIT_(\\d+)/, FloodWaitError], [/MSG_WAIT_(.*)/, MsgWaitError], [/PHONE_MIGRATE_(\\d+)/, PhoneMigrateError], [/SLOWMODE_WAIT_(\\d+)/, SlowModeWaitError], [/USER_MIGRATE_(\\d+)/, UserMigrateError], [/NETWORK_MIGRATE_(\\d+)/, NetworkMigrateError], [/EMAIL_UNCONFIRMED_(\\d+)/, EmailUnconfirmedError]]);\n\n//# sourceURL=webpack://telegram/./browser/errors/RPCErrorList.js?')},"./browser/errors/index.js": /*!*********************************!*\ !*** ./browser/errors/index.js ***! \*********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __exportStar = this && this.__exportStar || function (m, exports) {\n for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.RPCMessageToError = void 0;\n\nconst RPCBaseErrors_1 = __webpack_require__(/*! ./RPCBaseErrors */ "./browser/errors/RPCBaseErrors.js");\n\nconst RPCErrorList_1 = __webpack_require__(/*! ./RPCErrorList */ "./browser/errors/RPCErrorList.js");\n\nfunction RPCMessageToError(rpcError, request) {\n for (const [msgRegex, Cls] of RPCErrorList_1.rpcErrorRe) {\n const m = rpcError.errorMessage.match(msgRegex);\n\n if (m) {\n const capture = m.length === 2 ? parseInt(m[1]) : null;\n return new Cls({\n request: request,\n capture: capture\n });\n }\n }\n\n return new RPCBaseErrors_1.RPCError(rpcError.errorMessage, request, rpcError.errorCode);\n}\n\nexports.RPCMessageToError = RPCMessageToError;\n\n__exportStar(__webpack_require__(/*! ./Common */ "./browser/errors/Common.js"), exports);\n\n__exportStar(__webpack_require__(/*! ./RPCBaseErrors */ "./browser/errors/RPCBaseErrors.js"), exports);\n\n__exportStar(__webpack_require__(/*! ./RPCErrorList */ "./browser/errors/RPCErrorList.js"), exports);\n\n//# sourceURL=webpack://telegram/./browser/errors/index.js?')},"./browser/events/NewMessage.js": /*!**************************************!*\ !*** ./browser/events/NewMessage.js ***! \**************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.NewMessageEvent = exports.NewMessage = void 0;\n\nconst common_1 = __webpack_require__(/*! ./common */ "./browser/events/common.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js");\n/**\n * Occurs whenever a new text message or a message with media arrives.\n * @example\n * ```ts\n * async function eventPrint(event: NewMessageEvent) {\n * const message = event.message;\n *\n * // Checks if it\'s a private message (from user or bot)\n * if (event.isPrivate){\n * // prints sender id\n * console.log(message.senderId);\n * // read message\n * if (message.text == "hello"){\n * const sender = await message.getSender();\n * console.log("sender is",sender);\n * await client.sendMessage(sender,{\n * message:`hi your id is ${message.senderId}`\n * });\n * }\n * }\n * }\n * // adds an event handler for new messages\n * client.addEventHandler(eventPrint, new NewMessage({}));\n * ```\n */\n\n\nclass NewMessage extends common_1.EventBuilder {\n constructor(newMessageParams = {}) {\n let {\n chats,\n func,\n incoming,\n outgoing,\n fromUsers,\n forwards,\n pattern,\n blacklistChats = false\n } = newMessageParams;\n\n if (incoming && outgoing) {\n incoming = outgoing = undefined;\n } else if (incoming != undefined && outgoing == undefined) {\n outgoing = !incoming;\n } else if (outgoing != undefined && incoming == undefined) {\n incoming = !outgoing;\n } else if (outgoing == false && incoming == false) {\n throw new Error("Don\'t create an event handler if you don\'t want neither incoming nor outgoing!");\n }\n\n super({\n chats,\n blacklistChats,\n func\n });\n this.incoming = incoming;\n this.outgoing = outgoing;\n this.fromUsers = fromUsers;\n this.forwards = forwards;\n this.pattern = pattern;\n this._noCheck = [incoming, outgoing, chats, pattern, fromUsers, forwards, func].every(v => v == undefined);\n }\n\n async _resolve(client) {\n await super._resolve(client);\n this.fromUsers = await (0, common_1._intoIdSet)(client, this.fromUsers);\n }\n\n build(update, callback, selfId) {\n if (update instanceof tl_1.Api.UpdateNewMessage || update instanceof tl_1.Api.UpdateNewChannelMessage) {\n if (!(update.message instanceof tl_1.Api.Message)) {\n return undefined;\n }\n\n const event = new NewMessageEvent(update.message, update);\n this.addAttributes(event);\n return event;\n } else if (update instanceof tl_1.Api.UpdateShortMessage) {\n return new NewMessageEvent(new tl_1.Api.Message({\n out: update.out,\n mentioned: update.mentioned,\n mediaUnread: update.mediaUnread,\n silent: update.silent,\n id: update.id,\n peerId: new tl_1.Api.PeerUser({\n userId: update.userId\n }),\n fromId: new tl_1.Api.PeerUser({\n userId: update.out ? selfId : update.userId\n }),\n message: update.message,\n date: update.date,\n fwdFrom: update.fwdFrom,\n viaBotId: update.viaBotId,\n replyTo: update.replyTo,\n entities: update.entities,\n ttlPeriod: update.ttlPeriod\n }), update);\n } else if (update instanceof tl_1.Api.UpdateShortChatMessage) {\n return new NewMessageEvent(new tl_1.Api.Message({\n out: update.out,\n mentioned: update.mentioned,\n mediaUnread: update.mediaUnread,\n silent: update.silent,\n id: update.id,\n peerId: new tl_1.Api.PeerChat({\n chatId: update.chatId\n }),\n fromId: new tl_1.Api.PeerUser({\n userId: update.out ? selfId : update.fromId\n }),\n message: update.message,\n date: update.date,\n fwdFrom: update.fwdFrom,\n viaBotId: update.viaBotId,\n replyTo: update.replyTo,\n entities: update.entities,\n ttlPeriod: update.ttlPeriod\n }), update);\n }\n }\n\n filter(event) {\n var _a;\n\n if (this._noCheck) {\n return event;\n }\n\n if (this.incoming && event.message.out) {\n return;\n }\n\n if (this.outgoing && !event.message.out) {\n return;\n }\n\n if (this.forwards != undefined) {\n if (this.forwards != !!event.message.fwdFrom) {\n return;\n }\n }\n\n if (this.fromUsers != undefined) {\n if (!event.message.senderId || !this.fromUsers.includes(event.message.senderId.toString())) {\n return;\n }\n }\n\n if (this.pattern) {\n const match = (_a = event.message.message) === null || _a === void 0 ? void 0 : _a.match(this.pattern);\n\n if (!match) {\n return;\n }\n\n event.message.patternMatch = match;\n }\n\n return super.filter(event);\n }\n\n addAttributes(update) {//update.patternMatch =\n }\n\n}\n\nexports.NewMessage = NewMessage;\n\nclass NewMessageEvent extends common_1.EventCommon {\n constructor(message, originalUpdate) {\n super({\n msgId: message.id,\n chatPeer: message.peerId,\n broadcast: message.post\n });\n this.originalUpdate = originalUpdate;\n this.message = message;\n }\n\n _setClient(client) {\n super._setClient(client);\n\n const m = this.message;\n\n try {\n // todo make sure this never fails\n m._finishInit(client, this.originalUpdate._entities || new Map(), undefined);\n } catch (e) {\n client._log.error("Got error while trying to finish init message with id " + m.id);\n\n if (client._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(e);\n }\n }\n }\n\n}\n\nexports.NewMessageEvent = NewMessageEvent;\n\n//# sourceURL=webpack://telegram/./browser/events/NewMessage.js?')},"./browser/events/Raw.js": /*!*******************************!*\ !*** ./browser/events/Raw.js ***! \*******************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Raw = void 0;\n\nconst common_1 = __webpack_require__(/*! ./common */ "./browser/events/common.js");\n/**\n * The RAW updates that telegram sends. these are {@link Api.TypeUpdate} objects.\n * The are useful to handle custom events that you need like user typing or games.\n * @example\n * ```ts\n * client.addEventHandler((update) => {\n * console.log("Received new Update");\n * console.log(update);\n * });\n * ```\n */\n\n\nclass Raw extends common_1.EventBuilder {\n constructor(params) {\n super({\n func: params.func\n });\n this.types = params.types;\n }\n\n async resolve(client) {\n this.resolved = true;\n }\n\n build(update) {\n return update;\n }\n\n filter(event) {\n if (this.types) {\n let correct = false;\n\n for (const type of this.types) {\n if (event instanceof type) {\n correct = true;\n break;\n }\n }\n\n if (!correct) {\n return;\n }\n }\n\n return super.filter(event);\n }\n\n}\n\nexports.Raw = Raw;\n\n//# sourceURL=webpack://telegram/./browser/events/Raw.js?')},"./browser/events/common.js": /*!**********************************!*\ !*** ./browser/events/common.js ***! \**********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.EventCommonSender = exports.EventCommon = exports.EventBuilder = exports._intoIdSet = void 0;\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst custom_1 = __webpack_require__(/*! ../tl/custom */ "./browser/tl/custom/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst senderGetter_1 = __webpack_require__(/*! ../tl/custom/senderGetter */ "./browser/tl/custom/senderGetter.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n/** @hidden */\n\n\nasync function _intoIdSet(client, chats) {\n if (chats == undefined) {\n return undefined;\n }\n\n if (!(0, Helpers_1.isArrayLike)(chats)) {\n chats = [chats];\n }\n\n const result = new Set();\n\n for (let chat of chats) {\n if (typeof chat == "number" || typeof chat == "bigint" || typeof chat == "string" && (0, Utils_1.parseID)(chat) || big_integer_1.default.isInstance(chat)) {\n chat = (0, Helpers_1.returnBigInt)(chat);\n\n if (chat.lesser(0)) {\n result.add(chat.toString());\n } else {\n result.add(__1.utils.getPeerId(new tl_1.Api.PeerUser({\n userId: chat\n })));\n result.add(__1.utils.getPeerId(new tl_1.Api.PeerChat({\n chatId: chat\n })));\n result.add(__1.utils.getPeerId(new tl_1.Api.PeerChannel({\n channelId: chat\n })));\n }\n } else if (typeof chat == "object" && chat.SUBCLASS_OF_ID == 0x2d45687) {\n result.add(__1.utils.getPeerId(chat));\n } else {\n chat = await client.getInputEntity(chat);\n\n if (chat instanceof tl_1.Api.InputPeerSelf) {\n chat = await client.getMe(true);\n }\n\n result.add(__1.utils.getPeerId(chat));\n }\n }\n\n return Array.from(result);\n}\n\nexports._intoIdSet = _intoIdSet;\n/**\n * The common event builder, with builtin support to filter per chat.
\n * All events inherit this.\n */\n\nclass EventBuilder {\n constructor(eventParams) {\n var _a;\n\n this.chats = (_a = eventParams.chats) === null || _a === void 0 ? void 0 : _a.map(x => x.toString());\n this.blacklistChats = eventParams.blacklistChats || false;\n this.resolved = false;\n this.func = eventParams.func;\n }\n\n build(update, callback, selfId) {\n if (update) return update;\n }\n\n async resolve(client) {\n if (this.resolved) {\n return;\n }\n\n await this._resolve(client);\n this.resolved = true;\n }\n\n async _resolve(client) {\n this.chats = await _intoIdSet(client, this.chats);\n }\n\n filter(event) {\n if (!this.resolved) {\n return;\n }\n\n if (this.chats != undefined) {\n if (event.chatId == undefined) {\n return;\n }\n\n const inside = this.chats.includes(event.chatId.toString());\n\n if (inside == this.blacklistChats) {\n // If this chat matches but it\'s a blacklist ignore.\n // If it doesn\'t match but it\'s a whitelist ignore.\n return;\n }\n }\n\n if (this.func && !this.func(event)) {\n return;\n }\n\n return event;\n }\n\n}\n\nexports.EventBuilder = EventBuilder;\n\nclass EventCommon extends custom_1.ChatGetter {\n constructor({\n chatPeer = undefined,\n msgId = undefined,\n broadcast = undefined\n }) {\n super();\n this._eventName = "Event";\n custom_1.ChatGetter.initChatClass(this, {\n chatPeer,\n broadcast\n });\n this._entities = new Map();\n this._client = undefined;\n this._messageId = msgId;\n }\n\n _setClient(client) {\n this._client = client;\n }\n\n get client() {\n return this._client;\n }\n\n}\n\nexports.EventCommon = EventCommon;\n\nclass EventCommonSender extends senderGetter_1.SenderGetter {\n constructor({\n chatPeer = undefined,\n msgId = undefined,\n broadcast = undefined\n }) {\n super();\n this._eventName = "Event";\n custom_1.ChatGetter.initChatClass(this, {\n chatPeer,\n broadcast\n });\n senderGetter_1.SenderGetter.initChatClass(this, {\n chatPeer,\n broadcast\n });\n this._entities = new Map();\n this._client = undefined;\n this._messageId = msgId;\n }\n\n _setClient(client) {\n this._client = client;\n }\n\n get client() {\n return this._client;\n }\n\n}\n\nexports.EventCommonSender = EventCommonSender;\n\n//# sourceURL=webpack://telegram/./browser/events/common.js?')},"./browser/events/index.js": /*!*********************************!*\ !*** ./browser/events/index.js ***! \*********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.NewMessageEvent = exports.NewMessage = exports.Raw = void 0;\n\nvar Raw_1 = __webpack_require__(/*! ./Raw */ "./browser/events/Raw.js");\n\nObject.defineProperty(exports, "Raw", ({\n enumerable: true,\n get: function () {\n return Raw_1.Raw;\n }\n}));\n\nvar NewMessage_1 = __webpack_require__(/*! ./NewMessage */ "./browser/events/NewMessage.js");\n\nObject.defineProperty(exports, "NewMessage", ({\n enumerable: true,\n get: function () {\n return NewMessage_1.NewMessage;\n }\n}));\nObject.defineProperty(exports, "NewMessageEvent", ({\n enumerable: true,\n get: function () {\n return NewMessage_1.NewMessageEvent;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/events/index.js?')},"./browser/extensions/AsyncQueue.js": /*!******************************************!*\ !*** ./browser/extensions/AsyncQueue.js ***! \******************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.AsyncQueue = void 0;\n\nclass AsyncQueue {\n constructor() {\n this._queue = [];\n this.canPush = true;\n\n this.resolvePush = value => {};\n\n this.resolveGet = value => {};\n\n this.canGet = new Promise(resolve => {\n this.resolveGet = resolve;\n });\n }\n\n async push(value) {\n await this.canPush;\n\n this._queue.push(value);\n\n this.resolveGet(true);\n this.canPush = new Promise(resolve => {\n this.resolvePush = resolve;\n });\n }\n\n async pop() {\n await this.canGet;\n\n const returned = this._queue.pop();\n\n this.resolvePush(true);\n this.canGet = new Promise(resolve => {\n this.resolveGet = resolve;\n });\n return returned;\n }\n\n}\n\nexports.AsyncQueue = AsyncQueue;\n\n//# sourceURL=webpack://telegram/./browser/extensions/AsyncQueue.js?')},"./browser/extensions/BinaryReader.js": /*!********************************************!*\ !*** ./browser/extensions/BinaryReader.js ***! \********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.BinaryReader = void 0;\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nconst core_1 = __webpack_require__(/*! ../tl/core */ "./browser/tl/core/index.js");\n\nconst AllTLObjects_1 = __webpack_require__(/*! ../tl/AllTLObjects */ "./browser/tl/AllTLObjects.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nclass BinaryReader {\n /**\n * Small utility class to read binary data.\n * @param data {Buffer}\n */\n constructor(data) {\n this.stream = data;\n this._last = undefined;\n this.offset = 0;\n } // region Reading\n // "All numbers are written as little endian."\n // https://core.telegram.org/mtproto\n\n /**\n * Reads a single byte value.\n */\n\n\n readByte() {\n return this.read(1)[0];\n }\n /**\n * Reads an integer (4 bytes or 32 bits) value.\n * @param signed {Boolean}\n */\n\n\n readInt(signed = true) {\n let res;\n\n if (signed) {\n res = this.stream.readInt32LE(this.offset);\n } else {\n res = this.stream.readUInt32LE(this.offset);\n }\n\n this.offset += 4;\n return res;\n }\n /**\n * Reads a long integer (8 bytes or 64 bits) value.\n * @param signed\n * @returns {BigInteger}\n */\n\n\n readLong(signed = true) {\n return this.readLargeInt(64, signed);\n }\n /**\n * Reads a real floating point (4 bytes) value.\n * @returns {number}\n */\n\n\n readFloat() {\n return this.read(4).readFloatLE(0);\n }\n /**\n * Reads a real floating point (8 bytes) value.\n * @returns {BigInteger}\n */\n\n\n readDouble() {\n // was this a bug ? it should have been 0) {\n padding = 4 - padding;\n this.read(padding);\n }\n\n return data;\n }\n /**\n * Reads a Telegram-encoded string.\n * @returns {string}\n */\n\n\n tgReadString() {\n return this.tgReadBytes().toString("utf-8");\n }\n /**\n * Reads a Telegram boolean value.\n * @returns {boolean}\n */\n\n\n tgReadBool() {\n const value = this.readInt(false);\n\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else {\n throw new Error(`Invalid boolean code ${value.toString(16)}`);\n }\n }\n /**\n * Reads and converts Unix time (used by Telegram)\n * into a Javascript {Date} object.\n * @returns {Date}\n */\n\n\n tgReadDate() {\n const value = this.readInt();\n return new Date(value * 1000);\n }\n /**\n * Reads a Telegram object.\n */\n\n\n tgReadObject() {\n const constructorId = this.readInt(false);\n let clazz = AllTLObjects_1.tlobjects[constructorId];\n\n if (clazz === undefined) {\n /**\n * The class was undefined, but there\'s still a\n * chance of it being a manually parsed value like bool!\n */\n const value = constructorId;\n\n if (value === 0x997275b5) {\n // boolTrue\n return true;\n } else if (value === 0xbc799737) {\n // boolFalse\n return false;\n } else if (value === 0x1cb5c415) {\n // Vector\n const temp = [];\n const length = this.readInt();\n\n for (let i = 0; i < length; i++) {\n temp.push(this.tgReadObject());\n }\n\n return temp;\n }\n\n clazz = core_1.coreObjects.get(constructorId);\n\n if (clazz === undefined) {\n // If there was still no luck, give up\n this.seek(-4); // Go back\n\n const pos = this.tellPosition();\n const error = new errors_1.TypeNotFoundError(constructorId, this.read());\n this.setPosition(pos);\n throw error;\n }\n }\n\n return clazz.fromReader(this);\n }\n /**\n * Reads a vector (a list) of Telegram objects.\n * @returns {[Buffer]}\n */\n\n\n tgReadVector() {\n if (this.readInt(false) !== 0x1cb5c415) {\n throw new Error("Invalid constructor code, vector was expected");\n }\n\n const count = this.readInt();\n const temp = [];\n\n for (let i = 0; i < count; i++) {\n temp.push(this.tgReadObject());\n }\n\n return temp;\n } // endregion\n // region Position related\n\n /**\n * Tells the current position on the stream.\n * @returns {number}\n */\n\n\n tellPosition() {\n return this.offset;\n }\n /**\n * Sets the current position on the stream.\n * @param position\n */\n\n\n setPosition(position) {\n this.offset = position;\n }\n /**\n * Seeks the stream position given an offset from the current position.\n * The offset may be negative.\n * @param offset\n */\n\n\n seek(offset) {\n this.offset += offset;\n }\n\n}\n\nexports.BinaryReader = BinaryReader;\n\n//# sourceURL=webpack://telegram/./browser/extensions/BinaryReader.js?')},"./browser/extensions/BinaryWriter.js": /*!********************************************!*\ !*** ./browser/extensions/BinaryWriter.js ***! \********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.BinaryWriter = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nclass BinaryWriter {\n constructor(stream) {\n this._stream = stream;\n }\n\n write(buffer) {\n this._stream = buffer_1.Buffer.concat([this._stream, buffer]);\n }\n\n getValue() {\n return this._stream;\n }\n\n}\n\nexports.BinaryWriter = BinaryWriter;\n\n//# sourceURL=webpack://telegram/./browser/extensions/BinaryWriter.js?')},"./browser/extensions/Logger.js": /*!**************************************!*\ !*** ./browser/extensions/Logger.js ***! \**************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval(' // let _level: string | undefined = undefined;\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Logger = exports.LogLevel = void 0;\n\nconst platform_1 = __webpack_require__(/*! ../platform */ "./browser/platform.js");\n\nvar LogLevel;\n\n(function (LogLevel) {\n LogLevel["NONE"] = "none";\n LogLevel["ERROR"] = "error";\n LogLevel["WARN"] = "warn";\n LogLevel["INFO"] = "info";\n LogLevel["DEBUG"] = "debug";\n})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));\n\nclass Logger {\n constructor(level) {\n this.levels = ["error", "warn", "info", "debug"]; // if (!_level) {\n // _level = level || "info"; // defaults to info\n // }\n\n this._logLevel = level || LogLevel.INFO;\n this.isBrowser = !platform_1.isNode;\n\n if (!this.isBrowser) {\n this.colors = {\n start: "\\x1b[2m",\n warn: "\\x1b[35m",\n info: "\\x1b[33m",\n debug: "\\x1b[36m",\n error: "\\x1b[31m",\n end: "\\x1b[0m"\n };\n } else {\n this.colors = {\n start: "%c",\n warn: "color : #ff00ff",\n info: "color : #ffff00",\n debug: "color : #00ffff",\n error: "color : #ff0000",\n end: ""\n };\n }\n\n this.messageFormat = "[%t] [%l] - [%m]";\n this.tzOffset = new Date().getTimezoneOffset() * 60000;\n }\n /**\n *\n * @param level {string}\n * @returns {boolean}\n */\n\n\n canSend(level) {\n return this._logLevel ? this.levels.indexOf(this._logLevel) >= this.levels.indexOf(level) : false;\n }\n /**\n * @param message {string}\n */\n\n\n warn(message) {\n this._log(LogLevel.WARN, message, this.colors.warn);\n }\n /**\n * @param message {string}\n */\n\n\n info(message) {\n this._log(LogLevel.INFO, message, this.colors.info);\n }\n /**\n * @param message {string}\n */\n\n\n debug(message) {\n this._log(LogLevel.DEBUG, message, this.colors.debug);\n }\n /**\n * @param message {string}\n */\n\n\n error(message) {\n this._log(LogLevel.ERROR, message, this.colors.error);\n }\n\n format(message, level) {\n return this.messageFormat.replace("%t", this.getDateTime()).replace("%l", level.toUpperCase()).replace("%m", message);\n }\n\n get logLevel() {\n return this._logLevel;\n }\n\n setLevel(level) {\n this._logLevel = level;\n }\n\n static setLevel(level) {\n console.log("Logger.setLevel is deprecated, it will has no effect. Please, use client.setLogLevel instead.");\n }\n /**\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n\n\n _log(level, message, color) {\n if (this.canSend(level)) {\n this.log(level, message, color);\n } else {\n return;\n }\n }\n /**\n * Override this function for custom Logger.
\n *\n * @remarks use `this.isBrowser` to check and handle for different environment.\n * @param level {string}\n * @param message {string}\n * @param color {string}\n */\n\n\n log(level, message, color) {\n if (!this.isBrowser) {\n console.log(color + this.format(message, level) + this.colors.end);\n } else {\n console.log(this.colors.start + this.format(message, level), color);\n }\n }\n\n getDateTime() {\n return new Date(Date.now() - this.tzOffset).toISOString().slice(0, -1);\n }\n\n}\n\nexports.Logger = Logger;\n\n//# sourceURL=webpack://telegram/./browser/extensions/Logger.js?')},"./browser/extensions/MessagePacker.js": /*!*********************************************!*\ !*** ./browser/extensions/MessagePacker.js ***! \*********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MessagePacker = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst core_1 = __webpack_require__(/*! ../tl/core */ "./browser/tl/core/index.js");\n\nconst core_2 = __webpack_require__(/*! ../tl/core */ "./browser/tl/core/index.js");\n\nconst BinaryWriter_1 = __webpack_require__(/*! ./BinaryWriter */ "./browser/extensions/BinaryWriter.js");\n\nclass MessagePacker {\n constructor(state, logger) {\n this._state = state;\n this._queue = [];\n this._pendingStates = [];\n this._ready = new Promise(resolve => {\n this.setReady = resolve;\n });\n this._log = logger;\n }\n\n values() {\n return this._queue;\n }\n\n append(state) {\n this._queue.push(state);\n\n if (this.setReady) {\n this.setReady(true);\n }\n }\n\n extend(states) {\n for (const state of states) {\n this.append(state);\n }\n }\n\n async get() {\n if (!this._queue.length) {\n this._ready = new Promise(resolve => {\n this.setReady = resolve;\n });\n await this._ready;\n }\n\n let data;\n let buffer = new BinaryWriter_1.BinaryWriter(buffer_1.Buffer.alloc(0));\n const batch = [];\n let size = 0;\n\n while (this._queue.length && batch.length <= core_1.MessageContainer.MAXIMUM_LENGTH) {\n const state = this._queue.shift();\n\n size += state.data.length + core_2.TLMessage.SIZE_OVERHEAD;\n\n if (size <= core_1.MessageContainer.MAXIMUM_SIZE) {\n let afterId;\n\n if (state.after) {\n afterId = state.after.msgId;\n }\n\n state.msgId = await this._state.writeDataAsMessage(buffer, state.data, state.request.classType === "request", afterId);\n\n this._log.debug(`Assigned msgId = ${state.msgId} to ${state.request.className || state.request.constructor.name}`);\n\n batch.push(state);\n continue;\n }\n\n if (batch.length) {\n this._queue.unshift(state);\n\n break;\n }\n\n this._log.warn(`Message payload for ${state.request.className || state.request.constructor.name} is too long ${state.data.length} and cannot be sent`);\n\n state.promise.reject("Request Payload is too big");\n size = 0;\n }\n\n if (!batch.length) {\n return null;\n }\n\n if (batch.length > 1) {\n const b = buffer_1.Buffer.alloc(8);\n b.writeUInt32LE(core_1.MessageContainer.CONSTRUCTOR_ID, 0);\n b.writeInt32LE(batch.length, 4);\n data = buffer_1.Buffer.concat([b, buffer.getValue()]);\n buffer = new BinaryWriter_1.BinaryWriter(buffer_1.Buffer.alloc(0));\n const containerId = await this._state.writeDataAsMessage(buffer, data, false);\n\n for (const s of batch) {\n s.containerId = containerId;\n }\n }\n\n data = buffer.getValue();\n return {\n batch,\n data\n };\n }\n\n rejectAll() {\n this._pendingStates.forEach(requestState => {\n var _a;\n\n requestState.reject(new Error("Disconnect (caused from " + ((_a = requestState === null || requestState === void 0 ? void 0 : requestState.request) === null || _a === void 0 ? void 0 : _a.className) + ")"));\n });\n }\n\n}\n\nexports.MessagePacker = MessagePacker;\n\n//# sourceURL=webpack://telegram/./browser/extensions/MessagePacker.js?')},"./browser/extensions/PromisedNetSockets.js": /*!**************************************************!*\ !*** ./browser/extensions/PromisedNetSockets.js ***! \**************************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.PromisedNetSockets = void 0;\n\nclass PromisedNetSockets {\n constructor(...args) {}\n\n connect(...args) {}\n\n close(...args) {}\n\n write(...args) {}\n\n readExactly(...args) {}\n\n read(...args) {}\n\n}\n\nexports.PromisedNetSockets = PromisedNetSockets;\n\n//# sourceURL=webpack://telegram/./browser/extensions/PromisedNetSockets.js?')},"./browser/extensions/PromisedWebSockets.js": /*!**************************************************!*\ !*** ./browser/extensions/PromisedWebSockets.js ***! \**************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.PromisedWebSockets = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst websocket_1 = __webpack_require__(/*! websocket */ "./node_modules/websocket/lib/browser.js");\n\nconst async_mutex_1 = __webpack_require__(/*! async-mutex */ "./node_modules/async-mutex/lib/index.js");\n\nconst platform_1 = __webpack_require__(/*! ../platform */ "./browser/platform.js");\n\nconst mutex = new async_mutex_1.Mutex();\nconst closeError = new Error("WebSocket was closed");\n\nclass PromisedWebSockets {\n constructor() {\n this.client = undefined;\n this.stream = buffer_1.Buffer.alloc(0);\n this.closed = true;\n }\n\n async readExactly(number) {\n let readData = buffer_1.Buffer.alloc(0);\n\n while (true) {\n const thisTime = await this.read(number);\n readData = buffer_1.Buffer.concat([readData, thisTime]);\n number = number - thisTime.length;\n\n if (!number) {\n return readData;\n }\n }\n }\n\n async read(number) {\n if (this.closed) {\n throw closeError;\n }\n\n await this.canRead;\n\n if (this.closed) {\n throw closeError;\n }\n\n const toReturn = this.stream.slice(0, number);\n this.stream = this.stream.slice(number);\n\n if (this.stream.length === 0) {\n this.canRead = new Promise(resolve => {\n this.resolveRead = resolve;\n });\n }\n\n return toReturn;\n }\n\n async readAll() {\n if (this.closed || !(await this.canRead)) {\n throw closeError;\n }\n\n const toReturn = this.stream;\n this.stream = buffer_1.Buffer.alloc(0);\n this.canRead = new Promise(resolve => {\n this.resolveRead = resolve;\n });\n return toReturn;\n }\n\n getWebSocketLink(ip, port, testServers) {\n if (port === 443) {\n return `wss://${ip}:${port}/apiws${testServers ? "_test" : ""}`;\n } else {\n return `ws://${ip}:${port}/apiws${testServers ? "_test" : ""}`;\n }\n }\n\n async connect(port, ip, testServers = false) {\n this.stream = buffer_1.Buffer.alloc(0);\n this.canRead = new Promise(resolve => {\n this.resolveRead = resolve;\n });\n this.closed = false;\n this.website = this.getWebSocketLink(ip, port, testServers);\n this.client = new websocket_1.w3cwebsocket(this.website, "binary");\n return new Promise((resolve, reject) => {\n if (this.client) {\n this.client.onopen = () => {\n this.receive();\n resolve(this);\n };\n\n this.client.onerror = error => {\n reject(error);\n };\n\n this.client.onclose = () => {\n if (this.resolveRead) {\n this.resolveRead(false);\n }\n\n this.closed = true;\n }; //CONTEST\n\n\n if (platform_1.isBrowser) {\n window.addEventListener("offline", async () => {\n await this.close();\n\n if (this.resolveRead) {\n this.resolveRead(false);\n }\n });\n }\n }\n });\n }\n\n write(data) {\n if (this.closed) {\n throw closeError;\n }\n\n if (this.client) {\n this.client.send(data);\n }\n }\n\n async close() {\n if (this.client) {\n await this.client.close();\n }\n\n this.closed = true;\n }\n\n async receive() {\n if (this.client) {\n this.client.onmessage = async message => {\n const release = await mutex.acquire();\n\n try {\n let data; //CONTEST BROWSER\n\n data = buffer_1.Buffer.from(await new Response(message.data).arrayBuffer());\n this.stream = buffer_1.Buffer.concat([this.stream, data]);\n\n if (this.resolveRead) {\n this.resolveRead(true);\n }\n } finally {\n release();\n }\n };\n }\n }\n\n toString() {\n return "PromisedWebSocket";\n }\n\n}\n\nexports.PromisedWebSockets = PromisedWebSockets;\n\n//# sourceURL=webpack://telegram/./browser/extensions/PromisedWebSockets.js?')},"./browser/extensions/html.js": /*!************************************!*\ !*** ./browser/extensions/html.js ***! \************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.HTMLParser = void 0;\n\nconst htmlparser2_1 = __webpack_require__(/*! htmlparser2 */ "./node_modules/htmlparser2/lib/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst index_1 = __webpack_require__(/*! ../index */ "./browser/index.js");\n\nclass HTMLToTelegramParser {\n constructor() {\n this.text = "";\n this.entities = [];\n this._buildingEntities = new Map();\n this._openTags = [];\n this._openTagsMeta = [];\n }\n\n onopentag(name, attributes) {\n /*\n * This fires when a new tag is opened.\n *\n * If you don\'t need an aggregated `attributes` object,\n * have a look at the `onopentagname` and `onattribute` events.\n */\n this._openTags.unshift(name);\n\n this._openTagsMeta.unshift(undefined);\n\n let EntityType;\n const args = {};\n\n if (name == "strong" || name == "b") {\n EntityType = tl_1.Api.MessageEntityBold;\n } else if (name == "spoiler") {\n EntityType = tl_1.Api.MessageEntitySpoiler;\n } else if (name == "em" || name == "i") {\n EntityType = tl_1.Api.MessageEntityItalic;\n } else if (name == "u") {\n EntityType = tl_1.Api.MessageEntityUnderline;\n } else if (name == "del" || name == "s") {\n EntityType = tl_1.Api.MessageEntityStrike;\n } else if (name == "blockquote") {\n EntityType = tl_1.Api.MessageEntityBlockquote;\n } else if (name == "code") {\n const pre = this._buildingEntities.get("pre");\n\n if (pre && pre instanceof tl_1.Api.MessageEntityPre) {\n try {\n pre.language = attributes.class.slice("language-".length, attributes.class.length);\n } catch (e) {// no language block\n }\n } else {\n EntityType = tl_1.Api.MessageEntityCode;\n }\n } else if (name == "pre") {\n EntityType = tl_1.Api.MessageEntityPre;\n args["language"] = "";\n } else if (name == "a") {\n let url = attributes.href;\n\n if (!url) {\n return;\n }\n\n if (url.startsWith("mailto:")) {\n url = url.slice("mailto:".length, url.length);\n EntityType = tl_1.Api.MessageEntityEmail;\n } else {\n EntityType = tl_1.Api.MessageEntityTextUrl;\n args["url"] = url;\n url = undefined;\n }\n\n this._openTagsMeta.shift();\n\n this._openTagsMeta.unshift(url);\n }\n\n if (EntityType && !this._buildingEntities.has(name)) {\n this._buildingEntities.set(name, new EntityType(Object.assign({\n offset: this.text.length,\n length: 0\n }, args)));\n }\n }\n\n ontext(text) {\n const previousTag = this._openTags.length > 0 ? this._openTags[0] : "";\n\n if (previousTag == "a") {\n const url = this._openTagsMeta[0];\n\n if (url) {\n text = url;\n }\n }\n\n for (let [tag, entity] of this._buildingEntities) {\n entity.length += text.length;\n }\n\n this.text += text;\n }\n\n onclosetag(tagname) {\n this._openTagsMeta.shift();\n\n this._openTags.shift();\n\n const entity = this._buildingEntities.get(tagname);\n\n if (entity) {\n this._buildingEntities.delete(tagname);\n\n this.entities.push(entity);\n }\n }\n\n onattribute(name, value, quote) {}\n\n oncdataend() {}\n\n oncdatastart() {}\n\n oncomment(data) {}\n\n oncommentend() {}\n\n onend() {}\n\n onerror(error) {}\n\n onopentagname(name) {}\n\n onparserinit(parser) {}\n\n onprocessinginstruction(name, data) {}\n\n onreset() {}\n\n}\n\nclass HTMLParser {\n static parse(html) {\n if (!html) {\n return [html, []];\n }\n\n const handler = new HTMLToTelegramParser();\n const parser = new htmlparser2_1.Parser(handler);\n parser.write(html);\n parser.end();\n const text = index_1.helpers.stripText(handler.text, handler.entities);\n return [text, handler.entities];\n }\n\n static unparse(text, entities, _offset = 0, _length) {\n if (!text || !entities || !entities.length) {\n return text;\n }\n\n if (_length == undefined) {\n _length = text.length;\n }\n\n const html = [];\n let lastOffset = 0;\n\n for (let i = 0; i < entities.length; i++) {\n const entity = entities[i];\n\n if (entity.offset >= _offset + _length) {\n break;\n }\n\n let relativeOffset = entity.offset - _offset;\n\n if (relativeOffset > lastOffset) {\n html.push(text.slice(lastOffset, relativeOffset));\n } else if (relativeOffset < lastOffset) {\n continue;\n }\n\n let skipEntity = false;\n let length = entity.length;\n let entityText = this.unparse(text.slice(relativeOffset, relativeOffset + length), entities.slice(i + 1, entities.length), entity.offset, length);\n\n if (entity instanceof tl_1.Api.MessageEntityBold) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntitySpoiler) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityItalic) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityCode) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityUnderline) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityStrike) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityBlockquote) {\n html.push(`
${entityText}
`);\n } else if (entity instanceof tl_1.Api.MessageEntityPre) {\n if (entity.language) {\n html.push(`
\n\n    ${entityText}\n\n
`);\n } else {\n html.push(`
${entityText}
`);\n }\n } else if (entity instanceof tl_1.Api.MessageEntityEmail) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityUrl) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityTextUrl) {\n html.push(`${entityText}`);\n } else if (entity instanceof tl_1.Api.MessageEntityMentionName) {\n html.push(`${entityText}`);\n } else {\n skipEntity = true;\n }\n\n lastOffset = relativeOffset + (skipEntity ? 0 : length);\n }\n\n html.push(text.slice(lastOffset, text.length));\n return html.join("");\n }\n\n}\n\nexports.HTMLParser = HTMLParser;\n\n//# sourceURL=webpack://telegram/./browser/extensions/html.js?')},"./browser/extensions/index.js": /*!*************************************!*\ !*** ./browser/extensions/index.js ***! \*************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.AsyncQueue = exports.MessagePacker = exports.PromisedNetSockets = exports.PromisedWebSockets = exports.BinaryReader = exports.BinaryWriter = exports.Logger = void 0;\n\nvar Logger_1 = __webpack_require__(/*! ./Logger */ "./browser/extensions/Logger.js");\n\nObject.defineProperty(exports, "Logger", ({\n enumerable: true,\n get: function () {\n return Logger_1.Logger;\n }\n}));\n\nvar BinaryWriter_1 = __webpack_require__(/*! ./BinaryWriter */ "./browser/extensions/BinaryWriter.js");\n\nObject.defineProperty(exports, "BinaryWriter", ({\n enumerable: true,\n get: function () {\n return BinaryWriter_1.BinaryWriter;\n }\n}));\n\nvar BinaryReader_1 = __webpack_require__(/*! ./BinaryReader */ "./browser/extensions/BinaryReader.js");\n\nObject.defineProperty(exports, "BinaryReader", ({\n enumerable: true,\n get: function () {\n return BinaryReader_1.BinaryReader;\n }\n}));\n\nvar PromisedWebSockets_1 = __webpack_require__(/*! ./PromisedWebSockets */ "./browser/extensions/PromisedWebSockets.js");\n\nObject.defineProperty(exports, "PromisedWebSockets", ({\n enumerable: true,\n get: function () {\n return PromisedWebSockets_1.PromisedWebSockets;\n }\n}));\n\nvar PromisedNetSockets_1 = __webpack_require__(/*! ./PromisedNetSockets */ "./browser/extensions/PromisedNetSockets.js");\n\nObject.defineProperty(exports, "PromisedNetSockets", ({\n enumerable: true,\n get: function () {\n return PromisedNetSockets_1.PromisedNetSockets;\n }\n}));\n\nvar MessagePacker_1 = __webpack_require__(/*! ./MessagePacker */ "./browser/extensions/MessagePacker.js");\n\nObject.defineProperty(exports, "MessagePacker", ({\n enumerable: true,\n get: function () {\n return MessagePacker_1.MessagePacker;\n }\n}));\n\nvar AsyncQueue_1 = __webpack_require__(/*! ./AsyncQueue */ "./browser/extensions/AsyncQueue.js");\n\nObject.defineProperty(exports, "AsyncQueue", ({\n enumerable: true,\n get: function () {\n return AsyncQueue_1.AsyncQueue;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/extensions/index.js?')},"./browser/extensions/markdown.js": /*!****************************************!*\ !*** ./browser/extensions/markdown.js ***! \****************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MarkdownParser = void 0;\n\nconst messageParse_1 = __webpack_require__(/*! ../client/messageParse */ "./browser/client/messageParse.js");\n\nclass MarkdownParser {\n // TODO maybe there is a better way :shrug:\n static parse(message) {\n let i = 0;\n const keys = {};\n\n for (const k in messageParse_1.DEFAULT_DELIMITERS) {\n keys[k] = false;\n }\n\n const entities = [];\n const tempEntities = {};\n\n while (i < message.length) {\n let foundIndex = -1;\n let foundDelim = undefined;\n\n for (const key of Object.keys(messageParse_1.DEFAULT_DELIMITERS)) {\n const index = message.indexOf(key, i);\n\n if (index > -1 && (foundIndex === -1 || index < foundIndex)) {\n foundIndex = index;\n foundDelim = key;\n }\n }\n\n if (foundIndex === -1 || foundDelim == undefined) {\n break;\n }\n\n if (!keys[foundDelim]) {\n tempEntities[foundDelim] = new messageParse_1.DEFAULT_DELIMITERS[foundDelim]({\n offset: foundIndex,\n length: -1,\n language: ""\n });\n keys[foundDelim] = true;\n } else {\n keys[foundDelim] = false;\n tempEntities[foundDelim].length = foundIndex - tempEntities[foundDelim].offset;\n entities.push(tempEntities[foundDelim]);\n }\n\n message = message.replace(foundDelim, "");\n i = foundIndex;\n }\n\n return [message, entities];\n }\n\n static unparse(text, entities) {\n const delimiters = messageParse_1.DEFAULT_DELIMITERS;\n\n if (!text || !entities) {\n return text;\n }\n\n let insertAt = [];\n const tempDelimiters = new Map();\n Object.keys(delimiters).forEach(key => {\n tempDelimiters.set(delimiters[key].className, key);\n });\n\n for (const entity of entities) {\n const s = entity.offset;\n const e = entity.offset + entity.length;\n const delimiter = tempDelimiters.get(entity.className);\n\n if (delimiter) {\n insertAt.push([s, delimiter]);\n insertAt.push([e, delimiter]);\n }\n }\n\n insertAt = insertAt.sort((a, b) => {\n return a[0] - b[0];\n });\n\n while (insertAt.length) {\n const [at, what] = insertAt.pop();\n text = text.slice(0, at) + what + text.slice(at);\n }\n\n return text;\n }\n\n}\n\nexports.MarkdownParser = MarkdownParser;\n\n//# sourceURL=webpack://telegram/./browser/extensions/markdown.js?')},"./browser/index.js": /*!**************************!*\ !*** ./browser/index.js ***! \**************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.client = exports.password = exports.tl = exports.helpers = exports.extensions = exports.sessions = exports.errors = exports.utils = exports.Logger = exports.version = exports.Connection = exports.TelegramClient = exports.Api = void 0;\n\nvar tl_1 = __webpack_require__(/*! ./tl */ "./browser/tl/index.js");\n\nObject.defineProperty(exports, "Api", ({\n enumerable: true,\n get: function () {\n return tl_1.Api;\n }\n}));\n\nconst tl = __importStar(__webpack_require__(/*! ./tl */ "./browser/tl/index.js"));\n\nexports.tl = tl;\n\nvar TelegramClient_1 = __webpack_require__(/*! ./client/TelegramClient */ "./browser/client/TelegramClient.js");\n\nObject.defineProperty(exports, "TelegramClient", ({\n enumerable: true,\n get: function () {\n return TelegramClient_1.TelegramClient;\n }\n}));\n\nvar network_1 = __webpack_require__(/*! ./network */ "./browser/network/index.js");\n\nObject.defineProperty(exports, "Connection", ({\n enumerable: true,\n get: function () {\n return network_1.Connection;\n }\n}));\n\nvar Version_1 = __webpack_require__(/*! ./Version */ "./browser/Version.js");\n\nObject.defineProperty(exports, "version", ({\n enumerable: true,\n get: function () {\n return Version_1.version;\n }\n}));\n\nvar Logger_1 = __webpack_require__(/*! ./extensions/Logger */ "./browser/extensions/Logger.js");\n\nObject.defineProperty(exports, "Logger", ({\n enumerable: true,\n get: function () {\n return Logger_1.Logger;\n }\n}));\n\nconst utils = __importStar(__webpack_require__(/*! ./Utils */ "./browser/Utils.js"));\n\nexports.utils = utils;\n\nconst errors = __importStar(__webpack_require__(/*! ./errors */ "./browser/errors/index.js"));\n\nexports.errors = errors;\n\nconst sessions = __importStar(__webpack_require__(/*! ./sessions */ "./browser/sessions/index.js"));\n\nexports.sessions = sessions;\n\nconst extensions = __importStar(__webpack_require__(/*! ./extensions */ "./browser/extensions/index.js"));\n\nexports.extensions = extensions;\n\nconst helpers = __importStar(__webpack_require__(/*! ./Helpers */ "./browser/Helpers.js"));\n\nexports.helpers = helpers;\n\nconst client = __importStar(__webpack_require__(/*! ./client */ "./browser/client/index.js"));\n\nexports.client = client;\n\nconst password = __importStar(__webpack_require__(/*! ./Password */ "./browser/Password.js"));\n\nexports.password = password;\n\n//# sourceURL=webpack://telegram/./browser/index.js?')},"./browser/inspect.js": /*!****************************!*\ !*** ./browser/inspect.js ***! \****************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.inspect = void 0;\nexports.inspect = {\n custom: ""\n};\n\n//# sourceURL=webpack://telegram/./browser/inspect.js?')},"./browser/network/Authenticator.js": /*!******************************************!*\ !*** ./browser/network/Authenticator.js ***! \******************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.doAuthentication = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nconst Factorizator_1 = __webpack_require__(/*! ../crypto/Factorizator */ "./browser/crypto/Factorizator.js");\n\nconst RSA_1 = __webpack_require__(/*! ../crypto/RSA */ "./browser/crypto/RSA.js");\n\nconst IGE_1 = __webpack_require__(/*! ../crypto/IGE */ "./browser/crypto/IGE.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst AuthKey_1 = __webpack_require__(/*! ../crypto/AuthKey */ "./browser/crypto/AuthKey.js");\n\nconst RETRIES = 20;\n\nasync function doAuthentication(sender, log) {\n // Step 1 sending: PQ Request, endianness doesn\'t matter since it\'s random\n let bytes = (0, Helpers_1.generateRandomBytes)(16);\n const nonce = (0, Helpers_1.readBigIntFromBuffer)(bytes, false, true);\n const resPQ = await sender.send(new tl_1.Api.ReqPqMulti({\n nonce\n }));\n log.debug("Starting authKey generation step 1");\n\n if (!(resPQ instanceof tl_1.Api.ResPQ)) {\n throw new errors_1.SecurityError(`Step 1 answer was ${resPQ}`);\n }\n\n if (resPQ.nonce.neq(nonce)) {\n throw new errors_1.SecurityError("Step 1 invalid nonce from server");\n }\n\n const pq = (0, Helpers_1.readBigIntFromBuffer)(resPQ.pq, false, true);\n log.debug("Finished authKey generation step 1"); // Step 2 sending: DH Exchange\n\n const {\n p,\n q\n } = Factorizator_1.Factorizator.factorize(pq);\n const pBuffer = (0, Helpers_1.getByteArray)(p);\n const qBuffer = (0, Helpers_1.getByteArray)(q);\n bytes = (0, Helpers_1.generateRandomBytes)(32);\n const newNonce = (0, Helpers_1.readBigIntFromBuffer)(bytes, true, true);\n const pqInnerData = new tl_1.Api.PQInnerData({\n pq: (0, Helpers_1.getByteArray)(pq),\n p: pBuffer,\n q: qBuffer,\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n newNonce\n }).getBytes();\n\n if (pqInnerData.length > 144) {\n throw new errors_1.SecurityError("Step 1 invalid nonce from server");\n }\n\n let targetFingerprint;\n let targetKey;\n\n for (const fingerprint of resPQ.serverPublicKeyFingerprints) {\n targetKey = RSA_1._serverKeys.get(fingerprint.toString());\n\n if (targetKey !== undefined) {\n targetFingerprint = fingerprint;\n break;\n }\n }\n\n if (targetFingerprint === undefined || targetKey === undefined) {\n throw new errors_1.SecurityError("Step 2 could not find a valid key for fingerprints");\n } // Value should be padded to be made 192 exactly\n\n\n const padding = (0, Helpers_1.generateRandomBytes)(192 - pqInnerData.length);\n const dataWithPadding = buffer_1.Buffer.concat([pqInnerData, padding]);\n const dataPadReversed = buffer_1.Buffer.from(dataWithPadding).reverse();\n let encryptedData;\n\n for (let i = 0; i < RETRIES; i++) {\n const tempKey = (0, Helpers_1.generateRandomBytes)(32);\n const shaDigestKeyWithData = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([tempKey, dataWithPadding]));\n const dataWithHash = buffer_1.Buffer.concat([dataPadReversed, shaDigestKeyWithData]);\n const ige = new IGE_1.IGE(tempKey, buffer_1.Buffer.alloc(32));\n const aesEncrypted = ige.encryptIge(dataWithHash);\n const tempKeyXor = (0, Helpers_1.bufferXor)(tempKey, await (0, Helpers_1.sha256)(aesEncrypted));\n const keyAesEncrypted = buffer_1.Buffer.concat([tempKeyXor, aesEncrypted]);\n const keyAesEncryptedInt = (0, Helpers_1.readBigIntFromBuffer)(keyAesEncrypted, false, false);\n\n if (keyAesEncryptedInt.greaterOrEquals(targetKey.n)) {\n log.debug("Aes key greater than RSA. retrying");\n continue;\n }\n\n const encryptedDataBuffer = (0, Helpers_1.modExp)(keyAesEncryptedInt, (0, big_integer_1.default)(targetKey.e), targetKey.n);\n encryptedData = (0, Helpers_1.readBufferFromBigInt)(encryptedDataBuffer, 256, false, false);\n break;\n }\n\n if (encryptedData === undefined) {\n throw new errors_1.SecurityError("Step 2 could create a secure encrypted key");\n }\n\n log.debug("Step 2 : Generated a secure aes encrypted data");\n const serverDhParams = await sender.send(new tl_1.Api.ReqDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n p: pBuffer,\n q: qBuffer,\n publicKeyFingerprint: targetFingerprint,\n encryptedData\n }));\n\n if (!(serverDhParams instanceof tl_1.Api.ServerDHParamsOk || serverDhParams instanceof tl_1.Api.ServerDHParamsFail)) {\n throw new Error(`Step 2.1 answer was ${serverDhParams}`);\n }\n\n if (serverDhParams.nonce.neq(resPQ.nonce)) {\n throw new errors_1.SecurityError("Step 2 invalid nonce from server");\n }\n\n if (serverDhParams.serverNonce.neq(resPQ.serverNonce)) {\n throw new errors_1.SecurityError("Step 2 invalid server nonce from server");\n }\n\n if (serverDhParams instanceof tl_1.Api.ServerDHParamsFail) {\n const sh = await (0, Helpers_1.sha1)((0, Helpers_1.toSignedLittleBuffer)(newNonce, 32).slice(4, 20));\n const nnh = (0, Helpers_1.readBigIntFromBuffer)(sh, true, true);\n\n if (serverDhParams.newNonceHash.neq(nnh)) {\n throw new errors_1.SecurityError("Step 2 invalid DH fail nonce from server");\n }\n }\n\n if (!(serverDhParams instanceof tl_1.Api.ServerDHParamsOk)) {\n throw new Error(`Step 2.2 answer was ${serverDhParams}`);\n }\n\n log.debug("Finished authKey generation step 2");\n log.debug("Starting authKey generation step 3"); // Step 3 sending: Complete DH Exchange\n\n const {\n key,\n iv\n } = await (0, Helpers_1.generateKeyDataFromNonce)(resPQ.serverNonce, newNonce);\n\n if (serverDhParams.encryptedAnswer.length % 16 !== 0) {\n // See PR#453\n throw new errors_1.SecurityError("Step 3 AES block size mismatch");\n }\n\n const ige = new IGE_1.IGE(key, iv);\n const plainTextAnswer = ige.decryptIge(serverDhParams.encryptedAnswer);\n const reader = new extensions_1.BinaryReader(plainTextAnswer);\n reader.read(20); // hash sum\n\n const serverDhInner = reader.tgReadObject();\n\n if (!(serverDhInner instanceof tl_1.Api.ServerDHInnerData)) {\n throw new Error(`Step 3 answer was ${serverDhInner}`);\n }\n\n if (serverDhInner.nonce.neq(resPQ.nonce)) {\n throw new errors_1.SecurityError("Step 3 Invalid nonce in encrypted answer");\n }\n\n if (serverDhInner.serverNonce.neq(resPQ.serverNonce)) {\n throw new errors_1.SecurityError("Step 3 Invalid server nonce in encrypted answer");\n }\n\n const dhPrime = (0, Helpers_1.readBigIntFromBuffer)(serverDhInner.dhPrime, false, false);\n const ga = (0, Helpers_1.readBigIntFromBuffer)(serverDhInner.gA, false, false);\n const timeOffset = serverDhInner.serverTime - Math.floor(new Date().getTime() / 1000);\n const b = (0, Helpers_1.readBigIntFromBuffer)((0, Helpers_1.generateRandomBytes)(256), false, false);\n const gb = (0, Helpers_1.modExp)((0, big_integer_1.default)(serverDhInner.g), b, dhPrime);\n const gab = (0, Helpers_1.modExp)(ga, b, dhPrime); // Prepare client DH Inner Data\n\n const clientDhInner = new tl_1.Api.ClientDHInnerData({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n retryId: big_integer_1.default.zero,\n gB: (0, Helpers_1.getByteArray)(gb, false)\n }).getBytes();\n const clientDdhInnerHashed = buffer_1.Buffer.concat([await (0, Helpers_1.sha1)(clientDhInner), clientDhInner]); // Encryption\n\n const clientDhEncrypted = ige.encryptIge(clientDdhInnerHashed);\n const dhGen = await sender.send(new tl_1.Api.SetClientDHParams({\n nonce: resPQ.nonce,\n serverNonce: resPQ.serverNonce,\n encryptedData: clientDhEncrypted\n }));\n const nonceTypes = [tl_1.Api.DhGenOk, tl_1.Api.DhGenRetry, tl_1.Api.DhGenFail]; // TS being weird again.\n\n const nonceTypesString = ["DhGenOk", "DhGenRetry", "DhGenFail"];\n\n if (!(dhGen instanceof nonceTypes[0] || dhGen instanceof nonceTypes[1] || dhGen instanceof nonceTypes[2])) {\n throw new Error(`Step 3.1 answer was ${dhGen}`);\n }\n\n const {\n name\n } = dhGen.constructor;\n\n if (dhGen.nonce.neq(resPQ.nonce)) {\n throw new errors_1.SecurityError(`Step 3 invalid ${name} nonce from server`);\n }\n\n if (dhGen.serverNonce.neq(resPQ.serverNonce)) {\n throw new errors_1.SecurityError(`Step 3 invalid ${name} server nonce from server`);\n }\n\n const authKey = new AuthKey_1.AuthKey();\n await authKey.setKey((0, Helpers_1.getByteArray)(gab));\n const nonceNumber = 1 + nonceTypesString.indexOf(dhGen.className);\n const newNonceHash = await authKey.calcNewNonceHash(newNonce, nonceNumber); // @ts-ignore\n\n const dhHash = dhGen[`newNonceHash${nonceNumber}`];\n\n if (dhHash.neq(newNonceHash)) {\n throw new errors_1.SecurityError("Step 3 invalid new nonce hash");\n }\n\n if (!(dhGen instanceof tl_1.Api.DhGenOk)) {\n throw new Error(`Step 3.2 answer was ${dhGen}`);\n }\n\n log.debug("Finished authKey generation step 3");\n return {\n authKey,\n timeOffset\n };\n}\n\nexports.doAuthentication = doAuthentication;\n\n//# sourceURL=webpack://telegram/./browser/network/Authenticator.js?')},"./browser/network/MTProtoPlainSender.js": /*!***********************************************!*\ !*** ./browser/network/MTProtoPlainSender.js ***! \***********************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MTProtoPlainSender = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n/**\n * This module contains the class used to communicate with Telegram\'s servers\n * in plain text, when no authorization key has been created yet.\n */\n\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst MTProtoState_1 = __webpack_require__(/*! ./MTProtoState */ "./browser/network/MTProtoState.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n/**\n * MTProto Mobile Protocol plain sender (https://core.telegram.org/mtproto/description#unencrypted-messages)\n */\n\n\nclass MTProtoPlainSender {\n /**\n * Initializes the MTProto plain sender.\n * @param connection connection: the Connection to be used.\n * @param loggers\n */\n constructor(connection, loggers) {\n this._state = new MTProtoState_1.MTProtoState(undefined, loggers);\n this._connection = connection;\n }\n /**\n * Sends and receives the result for the given request.\n * @param request\n */\n\n\n async send(request) {\n let body = request.getBytes();\n\n let msgId = this._state._getNewMsgId();\n\n const m = (0, Helpers_1.toSignedLittleBuffer)(msgId, 8);\n const b = buffer_1.Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const res = buffer_1.Buffer.concat([buffer_1.Buffer.concat([buffer_1.Buffer.alloc(8), m, b]), body]);\n await this._connection.send(res);\n body = await this._connection.recv();\n\n if (body.length < 8) {\n throw new errors_1.InvalidBufferError(body);\n }\n\n const reader = new extensions_1.BinaryReader(body);\n const authKeyId = reader.readLong();\n\n if (authKeyId.neq((0, big_integer_1.default)(0))) {\n throw new Error("Bad authKeyId");\n }\n\n msgId = reader.readLong();\n\n if (msgId.eq((0, big_integer_1.default)(0))) {\n throw new Error("Bad msgId");\n }\n /** ^ We should make sure that the read ``msg_id`` is greater\n * than our own ``msg_id``. However, under some circumstances\n * (bad system clock/working behind proxies) this seems to not\n * be the case, which would cause endless assertion errors.\n */\n\n\n const length = reader.readInt();\n\n if (length <= 0) {\n throw new Error("Bad length");\n }\n /**\n * We could read length bytes and use those in a new reader to read\n * the next TLObject without including the padding, but since the\n * reader isn\'t used for anything else after this, it\'s unnecessary.\n */\n\n\n return reader.tgReadObject();\n }\n\n}\n\nexports.MTProtoPlainSender = MTProtoPlainSender;\n\n//# sourceURL=webpack://telegram/./browser/network/MTProtoPlainSender.js?')},"./browser/network/MTProtoSender.js": /*!******************************************!*\ !*** ./browser/network/MTProtoSender.js ***! \******************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MTProtoSender = void 0;\n/**\n * MTProto Mobile Protocol sender\n * (https://core.telegram.org/mtproto/description)\n * This class is responsible for wrapping requests into `TLMessage`\'s,\n * sending them over the network and receiving them in a safe manner.\n *\n * Automatic reconnection due to temporary network issues is a concern\n * for this class as well, including retry of messages that could not\n * be sent successfully.\n *\n * A new authorization key will be generated on connection if no other\n * key exists yet.\n */\n\nconst AuthKey_1 = __webpack_require__(/*! ../crypto/AuthKey */ "./browser/crypto/AuthKey.js");\n\nconst MTProtoState_1 = __webpack_require__(/*! ./MTProtoState */ "./browser/network/MTProtoState.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst extensions_2 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst core_1 = __webpack_require__(/*! ../tl/core */ "./browser/tl/core/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst RequestState_1 = __webpack_require__(/*! ./RequestState */ "./browser/network/RequestState.js");\n\nconst Authenticator_1 = __webpack_require__(/*! ./Authenticator */ "./browser/network/Authenticator.js");\n\nconst MTProtoPlainSender_1 = __webpack_require__(/*! ./MTProtoPlainSender */ "./browser/network/MTProtoPlainSender.js");\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nconst _1 = __webpack_require__(/*! ./ */ "./browser/network/index.js");\n\nconst Logger_1 = __webpack_require__(/*! ../extensions/Logger */ "./browser/extensions/Logger.js");\n\nconst async_mutex_1 = __webpack_require__(/*! async-mutex */ "./node_modules/async-mutex/lib/index.js");\n\nconst real_cancellable_promise_1 = __webpack_require__(/*! real-cancellable-promise */ "./node_modules/real-cancellable-promise/dist/index.mjs");\n\nclass MTProtoSender {\n /**\n * @param authKey\n * @param opts\n */\n constructor(authKey, opts) {\n const args = Object.assign(Object.assign({}, MTProtoSender.DEFAULT_OPTIONS), opts);\n this._cancelSend = false;\n this._connection = undefined;\n this._log = args.logger;\n this._dcId = args.dcId;\n this._retries = args.retries;\n this._delay = args.delay;\n this._autoReconnect = args.autoReconnect;\n this._connectTimeout = args.connectTimeout;\n this._authKeyCallback = args.authKeyCallback;\n this._updateCallback = args.updateCallback;\n this._autoReconnectCallback = args.autoReconnectCallback;\n this._isMainSender = args.isMainSender;\n this._senderCallback = args.senderCallback;\n this._client = args.client;\n this._onConnectionBreak = args.onConnectionBreak;\n this._securityChecks = args.securityChecks;\n this._connectMutex = new async_mutex_1.Mutex();\n /**\n * whether we disconnected ourself or telegram did it.\n */\n\n this.userDisconnected = false;\n /**\n * If a disconnection happens for any other reason and it\n * was *not* user action then the pending messages won\'t\n * be cleared but on explicit user disconnection all the\n * pending futures should be cancelled.\n */\n\n this.isConnecting = false;\n this._authenticated = false;\n this._userConnected = false;\n this._reconnecting = false;\n this._disconnected = true;\n /**\n * We need to join the loops upon disconnection\n */\n\n this._sendLoopHandle = null;\n this._recvLoopHandle = null;\n /**\n * Preserving the references of the AuthKey and state is important\n */\n\n this.authKey = authKey || new AuthKey_1.AuthKey();\n this._state = new MTProtoState_1.MTProtoState(this.authKey, this._log, this._securityChecks);\n /**\n * Outgoing messages are put in a queue and sent in a batch.\n * Note that here we\'re also storing their ``_RequestState``.\n */\n\n this._sendQueue = new extensions_2.MessagePacker(this._state, this._log);\n /**\n * Sent states are remembered until a response is received.\n */\n\n this._pendingState = new Map();\n /**\n * Responses must be acknowledged, and we can also batch these.\n */\n\n this._pendingAck = new Set();\n /**\n * Similar to pending_messages but only for the last acknowledges.\n * These can\'t go in pending_messages because no acknowledge for them\n * is received, but we may still need to resend their state on bad salts.\n */\n\n this._lastAcks = [];\n /**\n * Jump table from response ID to method that handles it\n */\n\n this._handlers = {\n [core_1.RPCResult.CONSTRUCTOR_ID.toString()]: this._handleRPCResult.bind(this),\n [core_1.MessageContainer.CONSTRUCTOR_ID.toString()]: this._handleContainer.bind(this),\n [core_1.GZIPPacked.CONSTRUCTOR_ID.toString()]: this._handleGzipPacked.bind(this),\n [tl_1.Api.Pong.CONSTRUCTOR_ID.toString()]: this._handlePong.bind(this),\n [tl_1.Api.BadServerSalt.CONSTRUCTOR_ID.toString()]: this._handleBadServerSalt.bind(this),\n [tl_1.Api.BadMsgNotification.CONSTRUCTOR_ID.toString()]: this._handleBadNotification.bind(this),\n [tl_1.Api.MsgDetailedInfo.CONSTRUCTOR_ID.toString()]: this._handleDetailedInfo.bind(this),\n [tl_1.Api.MsgNewDetailedInfo.CONSTRUCTOR_ID.toString()]: this._handleNewDetailedInfo.bind(this),\n [tl_1.Api.NewSessionCreated.CONSTRUCTOR_ID.toString()]: this._handleNewSessionCreated.bind(this),\n [tl_1.Api.MsgsAck.CONSTRUCTOR_ID.toString()]: this._handleAck.bind(this),\n [tl_1.Api.FutureSalts.CONSTRUCTOR_ID.toString()]: this._handleFutureSalts.bind(this),\n [tl_1.Api.MsgsStateReq.CONSTRUCTOR_ID.toString()]: this._handleStateForgotten.bind(this),\n [tl_1.Api.MsgResendReq.CONSTRUCTOR_ID.toString()]: this._handleStateForgotten.bind(this),\n [tl_1.Api.MsgsAllInfo.CONSTRUCTOR_ID.toString()]: this._handleMsgAll.bind(this)\n };\n }\n\n set dcId(dcId) {\n this._dcId = dcId;\n }\n\n get dcId() {\n return this._dcId;\n } // Public API\n\n /**\n * Connects to the specified given connection using the given auth key.\n */\n\n\n async connect(connection) {\n const release = await this._connectMutex.acquire();\n\n try {\n if (this._userConnected) {\n this._log.info("User is already connected!");\n\n return false;\n }\n\n this._connection = connection;\n await this._connect();\n this._userConnected = true;\n return true;\n } finally {\n release();\n }\n }\n\n isConnected() {\n return this._userConnected;\n }\n\n _transportConnected() {\n return !this._reconnecting && this._connection && this._connection._connected;\n }\n /**\n * Cleanly disconnects the instance from the network, cancels\n * all pending requests, and closes the send and receive loops.\n */\n\n\n async disconnect() {\n const release = await this._connectMutex.acquire();\n\n try {\n await this._disconnect();\n } catch (e) {\n this._log.error(e);\n } finally {\n release();\n }\n }\n /**\n *\n This method enqueues the given request to be sent. Its send\n state will be saved until a response arrives, and a ``Future``\n that will be resolved when the response arrives will be returned:\n .. code-block:: javascript\n async def method():\n # Sending (enqueued for the send loop)\n future = sender.send(request)\n # Receiving (waits for the receive loop to read the result)\n result = await future\n Designed like this because Telegram may send the response at\n any point, and it can send other items while one waits for it.\n Once the response for this future arrives, it is set with the\n received result, quite similar to how a ``receive()`` call\n would otherwise work.\n Since the receiving part is "built in" the future, it\'s\n impossible to await receive a result that was never sent.\n * @param request\n * @returns {RequestState}\n */\n\n\n send(request) {\n if (!this._userConnected) {\n throw new Error("Cannot send requests while disconnected. You need to call .connect()");\n }\n\n const state = new RequestState_1.RequestState(request);\n\n this._sendQueue.append(state);\n\n return state.promise;\n }\n /**\n * Performs the actual connection, retrying, generating the\n * authorization key if necessary, and starting the send and\n * receive loops.\n * @returns {Promise}\n * @private\n */\n\n\n async _connect() {\n this._log.info("Connecting to {0} using {1}".replace("{0}", this._connection.toString()).replace("{1}", this._connection.socket.toString()));\n\n let connected = false;\n\n for (let attempt = 0; attempt < this._retries; attempt++) {\n if (!connected) {\n connected = await this._tryConnect(attempt);\n\n if (!connected) {\n continue;\n }\n }\n\n if (!this.authKey.getKey()) {\n try {\n if (!(await this._tryGenAuthKey(attempt))) {\n continue;\n }\n } catch (err) {\n this._log.warn(`Connection error ${attempt} during auth_key gen`);\n\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(err);\n }\n\n await this._connection.disconnect();\n connected = false;\n await (0, Helpers_1.sleep)(this._delay);\n continue;\n }\n } else {\n this._authenticated = true;\n\n this._log.debug("Already have an auth key ...");\n }\n\n break;\n }\n\n if (!connected) {\n throw new Error(`Connection to telegram failed after ${this._retries} time(s)`);\n }\n\n if (!this.authKey.getKey()) {\n const error = new Error(`auth key generation failed after ${this._retries} time(s)`);\n await this._disconnect(error);\n throw error;\n }\n\n this._userConnected = true;\n\n this._log.debug("Starting receive loop");\n\n this._recvLoopHandle = this._recvLoop();\n\n this._log.debug("Starting send loop");\n\n this._sendLoopHandle = this._sendLoop();\n\n this._log.info("Connection to %s complete!".replace("%s", this._connection.toString()));\n }\n\n async _disconnect(error) {\n if (!this._connection) {\n this._log.info("Not disconnecting (already have no connection)");\n\n return;\n }\n\n this._log.info("Disconnecting from %s...".replace("%s", this._connection.toString()));\n\n this._userConnected = false;\n\n try {\n this._log.debug("Closing current connection...");\n\n await this._connection.disconnect();\n } finally {\n this._log.debug(`Cancelling ${this._pendingState.size} pending message(s)...`);\n\n for (const state of this._pendingState.values()) {\n if (error && !state.result) {\n state.reject(error);\n } else {\n state.reject("disconnected");\n }\n }\n\n this._pendingState.clear();\n\n this._cancelLoops();\n\n this._log.info("Disconnecting from %s complete!".replace("%s", this._connection.toString()));\n\n this._connection = undefined;\n }\n }\n\n _cancelLoops() {\n this._cancelSend = true;\n this.cancellableRecvLoopPromise.cancel();\n }\n /**\n * This loop is responsible for popping items off the send\n * queue, encrypting them, and sending them over the network.\n * Besides `connect`, only this method ever sends data.\n * @returns {Promise}\n * @private\n */\n\n\n async _sendLoop() {\n this._cancelSend = false;\n\n while (this._userConnected && !this._reconnecting && !this._cancelSend) {\n if (this._pendingAck.size) {\n const ack = new RequestState_1.RequestState(new tl_1.Api.MsgsAck({\n msgIds: Array(...this._pendingAck)\n }));\n\n this._sendQueue.append(ack);\n\n this._lastAcks.push(ack);\n\n if (this._lastAcks.length >= 10) {\n this._lastAcks.shift();\n }\n\n this._pendingAck.clear();\n }\n\n this._log.debug("Waiting for messages to send..." + this._reconnecting); // TODO Wait for the connection send queue to be empty?\n // This means that while it\'s not empty we can wait for\n // more messages to be added to the send queue.\n\n\n const res = await this._sendQueue.get();\n\n if (!res) {\n continue;\n }\n\n let {\n data\n } = res;\n const {\n batch\n } = res;\n\n this._log.debug(`Encrypting ${batch.length} message(s) in ${data.length} bytes for sending`);\n\n data = await this._state.encryptMessageData(data);\n\n for (const state of batch) {\n if (!Array.isArray(state)) {\n if (state.request.classType === "request") {\n this._pendingState.set(state.msgId.toString(), state);\n }\n } else {\n for (const s of state) {\n if (s.request.classType === "request") {\n this._pendingState.set(s.msgId.toString(), s);\n }\n }\n }\n }\n\n try {\n await this._connection.send(data);\n } catch (e) {\n this._log.error(e);\n\n this._log.info("Connection closed while sending data");\n\n this._startReconnecting(e);\n\n return;\n }\n\n this._log.debug("Encrypted messages put in a queue to be sent");\n }\n }\n\n async _recvLoop() {\n let body;\n let message;\n\n while (this._userConnected && !this._reconnecting) {\n this._log.debug("Receiving items from the network...");\n\n try {\n this.cancellableRecvLoopPromise = (0, real_cancellable_promise_1.pseudoCancellable)(this._connection.recv());\n body = await this.cancellableRecvLoopPromise;\n } catch (e) {\n if (e instanceof real_cancellable_promise_1.Cancellation) {\n return;\n }\n\n this._log.error(e);\n\n this._log.warn("Connection closed while receiving data...");\n\n this._startReconnecting(e);\n\n return;\n }\n\n try {\n message = await this._state.decryptMessageData(body);\n } catch (e) {\n if (e instanceof errors_1.TypeNotFoundError) {\n // Received object which we don\'t know how to deserialize\n this._log.info(`Type ${e.invalidConstructorId} not found, remaining data ${e.remaining}`);\n\n continue;\n } else if (e instanceof errors_1.SecurityError) {\n // A step while decoding had the incorrect data. This message\n // should not be considered safe and it should be ignored.\n this._log.warn(`Security error while unpacking a received message: ${e}`);\n\n continue;\n } else if (e instanceof errors_1.InvalidBufferError) {\n // 404 means that the server has "forgotten" our auth key and we need to create a new one.\n if (e.code === 404) {\n this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`);\n\n if (this._updateCallback && this._isMainSender) {\n this._updateCallback(this._client, new _1.UpdateConnectionState(_1.UpdateConnectionState.broken));\n } else if (this._onConnectionBreak && !this._isMainSender) {\n // Deletes the current sender from the object\n this._onConnectionBreak(this._dcId);\n }\n\n await this._disconnect(e);\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // reconnecting should be enough usually\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${e.code} for dc ${this._dcId}`);\n\n this._startReconnecting(e);\n }\n\n return;\n } else {\n this._log.error("Unhandled error while receiving data");\n\n this._log.error(e);\n\n this._startReconnecting(e);\n\n return;\n }\n }\n\n try {\n await this._processMessage(message);\n } catch (e) {\n this._log.error("Unhandled error while processing data");\n\n this._log.error(e);\n }\n }\n } // Response Handlers\n\n /**\n * Adds the given message to the list of messages that must be\n * acknowledged and dispatches control to different ``_handle_*``\n * method based on its type.\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _processMessage(message) {\n this._pendingAck.add(message.msgId);\n\n message.obj = await message.obj;\n\n let handler = this._handlers[message.obj.CONSTRUCTOR_ID.toString()];\n\n if (!handler) {\n handler = this._handleUpdate.bind(this);\n }\n\n await handler(message);\n }\n /**\n * Pops the states known to match the given ID from pending messages.\n * This method should be used when the response isn\'t specific.\n * @param msgId\n * @returns {*[]}\n * @private\n */\n\n\n _popStates(msgId) {\n let state = this._pendingState.get(msgId.toString());\n\n if (state) {\n this._pendingState.delete(msgId.toString());\n\n return [state];\n }\n\n const toPop = [];\n\n for (const state of this._pendingState.values()) {\n if (state.containerId && state.containerId.equals(msgId)) {\n toPop.push(state.msgId);\n }\n }\n\n if (toPop.length) {\n const temp = [];\n\n for (const x of toPop) {\n temp.push(this._pendingState.get(x.toString()));\n\n this._pendingState.delete(x.toString());\n }\n\n return temp;\n }\n\n for (const ack of this._lastAcks) {\n if (ack.msgId === msgId) {\n return [ack];\n }\n }\n\n return [];\n }\n /**\n * Handles the result for Remote Procedure Calls:\n * rpc_result#f35c6d01 req_msg_id:long result:bytes = RpcResult;\n * This is where the future results for sent requests are set.\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n _handleRPCResult(message) {\n const RPCResult = message.obj;\n\n const state = this._pendingState.get(RPCResult.reqMsgId.toString());\n\n if (state) {\n this._pendingState.delete(RPCResult.reqMsgId.toString());\n }\n\n this._log.debug(`Handling RPC result for message ${RPCResult.reqMsgId}`);\n\n if (!state) {\n // TODO We should not get responses to things we never sent\n // However receiving a File() with empty bytes is "common".\n // See #658, #759 and #958. They seem to happen in a container\n // which contain the real response right after.\n try {\n const reader = new extensions_1.BinaryReader(RPCResult.body);\n\n if (!(reader.tgReadObject() instanceof tl_1.Api.upload.File)) {\n throw new Error("Not an upload.File");\n }\n } catch (e) {\n this._log.error(e);\n\n if (e instanceof errors_1.TypeNotFoundError) {\n this._log.info(`Received response without parent request: ${RPCResult.body}`);\n\n return;\n } else {\n throw e;\n }\n }\n\n return;\n }\n\n if (RPCResult.error && state.msgId) {\n const error = (0, errors_1.RPCMessageToError)(RPCResult.error, state.request);\n\n this._sendQueue.append(new RequestState_1.RequestState(new tl_1.Api.MsgsAck({\n msgIds: [state.msgId]\n })));\n\n state.reject(error);\n } else {\n try {\n const reader = new extensions_1.BinaryReader(RPCResult.body);\n const read = state.request.readResult(reader);\n state.resolve(read);\n } catch (e) {\n state.reject(e);\n }\n }\n }\n /**\n * Processes the inner messages of a container with many of them:\n * msg_container#73f1f8dc messages:vector<%Message> = MessageContainer;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleContainer(message) {\n this._log.debug("Handling container");\n\n for (const innerMessage of message.obj.messages) {\n await this._processMessage(innerMessage);\n }\n }\n /**\n * Unpacks the data from a gzipped object and processes it:\n * gzip_packed#3072cfa1 packed_data:bytes = Object;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleGzipPacked(message) {\n this._log.debug("Handling gzipped data");\n\n const reader = new extensions_1.BinaryReader(message.obj.data);\n message.obj = reader.tgReadObject();\n await this._processMessage(message);\n }\n\n async _handleUpdate(message) {\n if (message.obj.SUBCLASS_OF_ID !== 0x8af52aac) {\n // crc32(b\'Updates\')\n this._log.warn(`Note: ${message.obj.className} is not an update, not dispatching it`);\n\n return;\n }\n\n this._log.debug("Handling update " + message.obj.className);\n\n if (this._updateCallback) {\n this._updateCallback(this._client, message.obj);\n }\n }\n /**\n * Handles pong results, which don\'t come inside a ``RPCResult``\n * but are still sent through a request:\n * pong#347773c5 msg_id:long ping_id:long = Pong;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handlePong(message) {\n const pong = message.obj;\n\n this._log.debug(`Handling pong for message ${pong.msgId}`);\n\n const state = this._pendingState.get(pong.msgId.toString());\n\n this._pendingState.delete(pong.msgId.toString()); // Todo Check result\n\n\n if (state) {\n state.resolve(pong);\n }\n }\n /**\n * Corrects the currently used server salt to use the right value\n * before enqueuing the rejected message to be re-sent:\n * bad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int\n * error_code:int new_server_salt:long = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleBadServerSalt(message) {\n const badSalt = message.obj;\n\n this._log.debug(`Handling bad salt for message ${badSalt.badMsgId}`);\n\n this._state.salt = badSalt.newServerSalt;\n\n const states = this._popStates(badSalt.badMsgId);\n\n this._sendQueue.extend(states);\n\n this._log.debug(`${states.length} message(s) will be resent`);\n }\n /**\n * Adjusts the current state to be correct based on the\n * received bad message notification whenever possible:\n * bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int\n * error_code:int = BadMsgNotification;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleBadNotification(message) {\n const badMsg = message.obj;\n\n const states = this._popStates(badMsg.badMsgId);\n\n this._log.debug(`Handling bad msg ${JSON.stringify(badMsg)}`);\n\n if ([16, 17].includes(badMsg.errorCode)) {\n // Sent msg_id too low or too high (respectively).\n // Use the current msg_id to determine the right time offset.\n const to = this._state.updateTimeOffset((0, big_integer_1.default)(message.msgId));\n\n this._log.info(`System clock is wrong, set time offset to ${to}s`);\n } else if (badMsg.errorCode === 32) {\n // msg_seqno too low, so just pump it up by some "large" amount\n // TODO A better fix would be to start with a new fresh session ID\n this._state._sequence += 64;\n } else if (badMsg.errorCode === 33) {\n // msg_seqno too high never seems to happen but just in case\n this._state._sequence -= 16;\n } else {\n for (const state of states) {\n state.reject(new errors_1.BadMessageError(state.request, badMsg.errorCode));\n }\n\n return;\n } // Messages are to be re-sent once we\'ve corrected the issue\n\n\n this._sendQueue.extend(states);\n\n this._log.debug(`${states.length} messages will be resent due to bad msg`);\n }\n /**\n * Updates the current status with the received detailed information:\n * msg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n\n this._log.debug(`Handling detailed info for message ${msgId}`);\n\n this._pendingAck.add(msgId);\n }\n /**\n * Updates the current status with the received detailed information:\n * msg_new_detailed_info#809db6df answer_msg_id:long\n * bytes:int status:int = MsgDetailedInfo;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleNewDetailedInfo(message) {\n // TODO https://goo.gl/VvpCC6\n const msgId = message.obj.answerMsgId;\n\n this._log.debug(`Handling new detailed info for message ${msgId}`);\n\n this._pendingAck.add(msgId);\n }\n /**\n * Updates the current status with the received session information:\n * new_session_created#9ec20908 first_msg_id:long unique_id:long\n * server_salt:long = NewSession;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleNewSessionCreated(message) {\n // TODO https://goo.gl/LMyN7A\n this._log.debug("Handling new session created");\n\n this._state.salt = message.obj.serverSalt;\n }\n /**\n * Handles a server acknowledge about our messages. Normally\n * these can be ignored except in the case of ``auth.logOut``:\n *\n * auth.logOut#5717da40 = Bool;\n *\n * Telegram doesn\'t seem to send its result so we need to confirm\n * it manually. No other request is known to have this behaviour.\n * Since the ID of sent messages consisting of a container is\n * never returned (unless on a bad notification), this method\n * also removes containers messages when any of their inner\n * messages are acknowledged.\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleAck(message) {\n const ack = message.obj;\n\n this._log.debug(`Handling acknowledge for ${ack.msgIds}`);\n\n for (const msgId of ack.msgIds) {\n const state = this._pendingState.get(msgId);\n\n if (state && state.request instanceof tl_1.Api.auth.LogOut) {\n this._pendingState.delete(msgId);\n\n state.resolve(true);\n }\n }\n }\n /**\n * Handles future salt results, which don\'t come inside a\n * ``rpc_result`` but are still sent through a request:\n * future_salts#ae500895 req_msg_id:long now:int\n * salts:vector = FutureSalts;\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleFutureSalts(message) {\n // TODO save these salts and automatically adjust to the\n // correct one whenever the salt in use expires.\n this._log.debug(`Handling future salts for message ${message.msgId}`);\n\n const state = this._pendingState.get(message.msgId.toString());\n\n if (state) {\n this._pendingState.delete(message.msgId.toString());\n\n state.resolve(message.obj);\n }\n }\n /**\n * Handles both :tl:`MsgsStateReq` and :tl:`MsgResendReq` by\n * enqueuing a :tl:`MsgsStateInfo` to be sent at a later point.\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleStateForgotten(message) {\n this._sendQueue.append(new RequestState_1.RequestState(new tl_1.Api.MsgsStateInfo({\n reqMsgId: message.msgId,\n info: String.fromCharCode(1).repeat(message.obj.msgIds)\n })));\n }\n /**\n * Handles :tl:`MsgsAllInfo` by doing nothing (yet).\n * @param message\n * @returns {Promise}\n * @private\n */\n\n\n async _handleMsgAll(message) {}\n\n async _reconnect(lastError) {\n this._log.debug("Closing current connection...");\n\n await this._connection.disconnect();\n\n this._cancelLoops();\n\n this._reconnecting = false;\n\n this._state.reset();\n\n let attempt;\n let ok = true;\n\n for (attempt = 0; attempt < this._retries; attempt++) {\n try {\n await this._connect();\n await (0, Helpers_1.sleep)(1000);\n\n this._sendQueue.extend([...this._pendingState.values()]);\n\n this._pendingState.clear();\n\n if (this._autoReconnectCallback) {\n this._autoReconnectCallback();\n }\n\n break;\n } catch (err) {\n if (attempt == this._retries - 1) {\n ok = false;\n }\n\n if (err instanceof errors_1.InvalidBufferError) {\n if (err.code === 404) {\n this._log.warn(`Broken authorization key for dc ${this._dcId}; resetting`);\n\n await this.authKey.setKey(undefined);\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(undefined);\n }\n\n ok = false;\n break;\n } else {\n // this happens sometimes when telegram is having some internal issues.\n // since the data we sent and received is probably wrong now.\n this._log.warn(`Invalid buffer ${err.code} for dc ${this._dcId}`);\n }\n }\n\n this._log.error(`Unexpected exception reconnecting on attempt ${attempt}`);\n\n await (0, Helpers_1.sleep)(this._delay);\n lastError = err;\n }\n }\n\n if (!ok) {\n this._log.error(`Automatic reconnection failed ${attempt} time(s)`);\n\n await this._disconnect(lastError ? lastError : undefined);\n }\n }\n\n async _tryConnect(attempt) {\n try {\n this._log.debug(`Connection attempt ${attempt}...`);\n\n await this._connection.connect();\n\n this._log.debug("Connection success!");\n\n return true;\n } catch (err) {\n this._log.warn(`Attempt ${attempt} at connecting failed`);\n\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(err);\n }\n\n await (0, Helpers_1.sleep)(this._delay);\n return false;\n }\n }\n\n async _tryGenAuthKey(attempt) {\n const plain = new MTProtoPlainSender_1.MTProtoPlainSender(this._connection, this._log);\n\n try {\n this._log.debug(`New auth_key attempt ${attempt}...`);\n\n this._log.debug("New auth_key attempt ...");\n\n const res = await (0, Authenticator_1.doAuthentication)(plain, this._log);\n\n this._log.debug("Generated new auth_key successfully");\n\n await this.authKey.setKey(res.authKey);\n this._state.timeOffset = res.timeOffset;\n\n if (this._authKeyCallback) {\n await this._authKeyCallback(this.authKey, this._dcId);\n }\n\n this._log.debug("auth_key generation success!");\n\n return true;\n } catch (err) {\n this._log.warn(`Attempt ${attempt} at generating auth key failed`);\n\n if (this._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(err);\n }\n\n return false;\n }\n }\n\n _startReconnecting(error) {\n this._log.info(`Starting reconnect...`);\n\n if (this._userConnected && !this._reconnecting) {\n this._reconnecting = true;\n\n this._reconnect(error);\n }\n }\n\n}\n\nexports.MTProtoSender = MTProtoSender;\nMTProtoSender.DEFAULT_OPTIONS = {\n logger: null,\n retries: Infinity,\n delay: 2000,\n autoReconnect: true,\n connectTimeout: null,\n authKeyCallback: null,\n updateCallback: null,\n autoReconnectCallback: null,\n isMainSender: null,\n senderCallback: null,\n onConnectionBreak: undefined,\n securityChecks: true\n};\n\n//# sourceURL=webpack://telegram/./browser/network/MTProtoSender.js?')},"./browser/network/MTProtoState.js": /*!*****************************************!*\ !*** ./browser/network/MTProtoState.js ***! \*****************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MTProtoState = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst core_1 = __webpack_require__(/*! ../tl/core */ "./browser/tl/core/index.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst IGE_1 = __webpack_require__(/*! ../crypto/IGE */ "./browser/crypto/IGE.js");\n\nconst errors_1 = __webpack_require__(/*! ../errors */ "./browser/errors/index.js");\n\nclass MTProtoState {\n /**\n *\n `telethon.network.mtprotosender.MTProtoSender` needs to hold a state\n in order to be able to encrypt and decrypt incoming/outgoing messages,\n as well as generating the message IDs. Instances of this class hold\n together all the required information.\n It doesn\'t make sense to use `telethon.sessions.abstract.Session` for\n the sender because the sender should *not* be concerned about storing\n this information to disk, as one may create as many senders as they\n desire to any other data center, or some CDN. Using the same session\n for all these is not a good idea as each need their own authkey, and\n the concept of "copying" sessions with the unnecessary entities or\n updates state for these connections doesn\'t make sense.\n While it would be possible to have a `MTProtoPlainState` that does no\n encryption so that it was usable through the `MTProtoLayer` and thus\n avoid the need for a `MTProtoPlainSender`, the `MTProtoLayer` is more\n focused to efficiency and this state is also more advanced (since it\n supports gzipping and invoking after other message IDs). There are too\n many methods that would be needed to make it convenient to use for the\n authentication process, at which point the `MTProtoPlainSender` is better\n * @param authKey\n * @param loggers\n * @param securityChecks\n */\n constructor(authKey, loggers, securityChecks = true) {\n this.authKey = authKey;\n this._log = loggers;\n this.timeOffset = 0;\n this.salt = big_integer_1.default.zero;\n this._sequence = 0;\n this.id = this._lastMsgId = big_integer_1.default.zero;\n this.msgIds = [];\n this.securityChecks = securityChecks;\n this.reset();\n }\n /**\n * Resets the state\n */\n\n\n reset() {\n // Session IDs can be random on every connection\n this.id = __1.helpers.generateRandomLong(true);\n this._sequence = 0;\n this._lastMsgId = big_integer_1.default.zero;\n this.msgIds = [];\n }\n /**\n * Updates the message ID to a new one,\n * used when the time offset changed.\n * @param message\n */\n\n\n updateMessageId(message) {\n message.msgId = this._getNewMsgId();\n }\n /**\n * Calculate the key based on Telegram guidelines, specifying whether it\'s the client or not\n * @param authKey\n * @param msgKey\n * @param client\n * @returns {{iv: Buffer, key: Buffer}}\n */\n\n\n async _calcKey(authKey, msgKey, client) {\n const x = client ? 0 : 8;\n const [sha256a, sha256b] = await Promise.all([(0, Helpers_1.sha256)(buffer_1.Buffer.concat([msgKey, authKey.slice(x, x + 36)])), (0, Helpers_1.sha256)(buffer_1.Buffer.concat([authKey.slice(x + 40, x + 76), msgKey]))]);\n const key = buffer_1.Buffer.concat([sha256a.slice(0, 8), sha256b.slice(8, 24), sha256a.slice(24, 32)]);\n const iv = buffer_1.Buffer.concat([sha256b.slice(0, 8), sha256a.slice(8, 24), sha256b.slice(24, 32)]);\n return {\n key,\n iv\n };\n }\n /**\n * Writes a message containing the given data into buffer.\n * Returns the message id.\n * @param buffer\n * @param data\n * @param contentRelated\n * @param afterId\n */\n\n\n async writeDataAsMessage(buffer, data, contentRelated, afterId) {\n const msgId = this._getNewMsgId();\n\n const seqNo = this._getSeqNo(contentRelated);\n\n let body;\n\n if (!afterId) {\n body = await core_1.GZIPPacked.gzipIfSmaller(contentRelated, data);\n } else {\n body = await core_1.GZIPPacked.gzipIfSmaller(contentRelated, new tl_1.Api.InvokeAfterMsg({\n msgId: afterId,\n query: {\n getBytes() {\n return data;\n }\n\n }\n }).getBytes());\n }\n\n const s = buffer_1.Buffer.alloc(4);\n s.writeInt32LE(seqNo, 0);\n const b = buffer_1.Buffer.alloc(4);\n b.writeInt32LE(body.length, 0);\n const m = (0, Helpers_1.toSignedLittleBuffer)(msgId, 8);\n buffer.write(buffer_1.Buffer.concat([m, s, b]));\n buffer.write(body);\n return msgId;\n }\n /**\n * Encrypts the given message data using the current authorization key\n * following MTProto 2.0 guidelines core.telegram.org/mtproto/description.\n * @param data\n */\n\n\n async encryptMessageData(data) {\n if (!this.authKey) {\n throw new Error("Auth key unset");\n }\n\n await this.authKey.waitForKey();\n const authKey = this.authKey.getKey();\n\n if (!authKey) {\n throw new Error("Auth key unset");\n }\n\n if (!this.salt || !this.id || !authKey || !this.authKey.keyId) {\n throw new Error("Unset params");\n }\n\n const s = (0, Helpers_1.toSignedLittleBuffer)(this.salt, 8);\n const i = (0, Helpers_1.toSignedLittleBuffer)(this.id, 8);\n data = buffer_1.Buffer.concat([buffer_1.Buffer.concat([s, i]), data]);\n\n const padding = __1.helpers.generateRandomBytes(__1.helpers.mod(-(data.length + 12), 16) + 12); // Being substr(what, offset, length); x = 0 for client\n // "msg_key_large = SHA256(substr(auth_key, 88+x, 32) + pt + padding)"\n\n\n const msgKeyLarge = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([authKey.slice(88, 88 + 32), data, padding])); // "msg_key = substr (msg_key_large, 8, 16)"\n\n const msgKey = msgKeyLarge.slice(8, 24);\n const {\n iv,\n key\n } = await this._calcKey(authKey, msgKey, true);\n\n const keyId = __1.helpers.readBufferFromBigInt(this.authKey.keyId, 8);\n\n return buffer_1.Buffer.concat([keyId, msgKey, new IGE_1.IGE(key, iv).encryptIge(buffer_1.Buffer.concat([data, padding]))]);\n }\n /**\n * Inverse of `encrypt_message_data` for incoming server messages.\n * @param body\n */\n\n\n async decryptMessageData(body) {\n if (!this.authKey) {\n throw new Error("Auth key unset");\n }\n\n if (body.length < 8) {\n throw new errors_1.InvalidBufferError(body);\n } // TODO Check salt,sessionId, and sequenceNumber\n\n\n const keyId = __1.helpers.readBigIntFromBuffer(body.slice(0, 8));\n\n if (!this.authKey.keyId || keyId.neq(this.authKey.keyId)) {\n throw new errors_1.SecurityError("Server replied with an invalid auth key");\n }\n\n const authKey = this.authKey.getKey();\n\n if (!authKey) {\n throw new errors_1.SecurityError("Unset AuthKey");\n }\n\n const msgKey = body.slice(8, 24);\n const {\n iv,\n key\n } = await this._calcKey(authKey, msgKey, false);\n body = new IGE_1.IGE(key, iv).decryptIge(body.slice(24)); // https://core.telegram.org/mtproto/security_guidelines\n // Sections "checking sha256 hash" and "message length"\n\n const ourKey = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([authKey.slice(96, 96 + 32), body]));\n\n if (!msgKey.equals(ourKey.slice(8, 24))) {\n throw new errors_1.SecurityError("Received msg_key doesn\'t match with expected one");\n }\n\n const reader = new extensions_1.BinaryReader(body);\n reader.readLong(); // removeSalt\n\n const serverId = reader.readLong();\n\n if (serverId.neq(this.id)) {// throw new SecurityError(\'Server replied with a wrong session ID\');\n }\n\n const remoteMsgId = reader.readLong();\n\n if (this.msgIds.includes(remoteMsgId.toString()) && this.securityChecks) {\n throw new errors_1.SecurityError("Duplicate msgIds");\n }\n\n if (this.msgIds.length > 500) {\n this.msgIds.shift();\n }\n\n this.msgIds.push(remoteMsgId.toString());\n const remoteSequence = reader.readInt();\n reader.readInt(); // msgLen for the inner object, padding ignored\n // We could read msg_len bytes and use those in a new reader to read\n // the next TLObject without including the padding, but since the\n // reader isn\'t used for anything else after this, it\'s unnecessary.\n\n const obj = reader.tgReadObject();\n return new core_1.TLMessage(remoteMsgId, remoteSequence, obj);\n }\n /**\n * Generates a new unique message ID based on the current\n * time (in ms) since epoch, applying a known time offset.\n * @private\n */\n\n\n _getNewMsgId() {\n const now = new Date().getTime() / 1000 + this.timeOffset;\n const nanoseconds = Math.floor((now - Math.floor(now)) * 1e9);\n let newMsgId = (0, big_integer_1.default)(Math.floor(now)).shiftLeft((0, big_integer_1.default)(32)).or((0, big_integer_1.default)(nanoseconds).shiftLeft((0, big_integer_1.default)(2)));\n\n if (this._lastMsgId.greaterOrEquals(newMsgId)) {\n newMsgId = this._lastMsgId.add((0, big_integer_1.default)(4));\n }\n\n this._lastMsgId = newMsgId;\n return newMsgId;\n }\n /**\n * Updates the time offset to the correct\n * one given a known valid message ID.\n * @param correctMsgId {BigInteger}\n */\n\n\n updateTimeOffset(correctMsgId) {\n const bad = this._getNewMsgId();\n\n const old = this.timeOffset;\n const now = Math.floor(new Date().getTime() / 1000);\n const correct = correctMsgId.shiftRight((0, big_integer_1.default)(32)).toJSNumber();\n this.timeOffset = correct - now;\n\n if (this.timeOffset !== old) {\n this._lastMsgId = big_integer_1.default.zero;\n\n this._log.debug(`Updated time offset (old offset ${old}, bad ${bad}, good ${correctMsgId}, new ${this.timeOffset})`);\n }\n\n return this.timeOffset;\n }\n /**\n * Generates the next sequence number depending on whether\n * it should be for a content-related query or not.\n * @param contentRelated\n * @private\n */\n\n\n _getSeqNo(contentRelated) {\n if (contentRelated) {\n const result = this._sequence * 2 + 1;\n this._sequence += 1;\n return result;\n } else {\n return this._sequence * 2;\n }\n }\n\n}\n\nexports.MTProtoState = MTProtoState;\n\n//# sourceURL=webpack://telegram/./browser/network/MTProtoState.js?')},"./browser/network/RequestState.js": /*!*****************************************!*\ !*** ./browser/network/RequestState.js ***! \*****************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.RequestState = void 0;\n\nclass RequestState {\n constructor(request, after = undefined) {\n this.containerId = undefined;\n this.msgId = undefined;\n this.request = request;\n this.data = request.getBytes();\n this.after = after;\n this.result = undefined;\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n\n}\n\nexports.RequestState = RequestState;\n\n//# sourceURL=webpack://telegram/./browser/network/RequestState.js?')},"./browser/network/connection/Connection.js": /*!**************************************************!*\ !*** ./browser/network/connection/Connection.js ***! \**************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ObfuscatedConnection = exports.PacketCodec = exports.Connection = void 0;\n\nconst extensions_1 = __webpack_require__(/*! ../../extensions */ "./browser/extensions/index.js");\n\nconst real_cancellable_promise_1 = __webpack_require__(/*! real-cancellable-promise */ "./node_modules/real-cancellable-promise/dist/index.mjs");\n/**\n * The `Connection` class is a wrapper around ``asyncio.open_connection``.\n *\n * Subclasses will implement different transport modes as atomic operations,\n * which this class eases doing since the exposed interface simply puts and\n * gets complete data payloads to and from queues.\n *\n * The only error that will raise from send and receive methods is\n * ``ConnectionError``, which will raise when attempting to send if\n * the client is disconnected (includes remote disconnections).\n */\n\n\nclass Connection {\n constructor({\n ip,\n port,\n dcId,\n loggers,\n proxy,\n socket,\n testServers\n }) {\n this._ip = ip;\n this._port = port;\n this._dcId = dcId;\n this._log = loggers;\n this._proxy = proxy;\n this._connected = false;\n this._sendTask = undefined;\n this._recvTask = undefined;\n this._codec = undefined;\n this._obfuscation = undefined; // TcpObfuscated and MTProxy\n\n this._sendArray = new extensions_1.AsyncQueue();\n this._recvArray = new extensions_1.AsyncQueue();\n this.socket = new socket(proxy);\n this._testServers = testServers;\n }\n\n async _connect() {\n this._log.debug("Connecting");\n\n this._codec = new this.PacketCodecClass(this);\n await this.socket.connect(this._port, this._ip, this._testServers);\n\n this._log.debug("Finished connecting"); // await this.socket.connect({host: this._ip, port: this._port});\n\n\n await this._initConn();\n }\n\n async connect() {\n await this._connect();\n this._connected = true;\n this._sendTask = this._sendLoop();\n this._recvTask = this._recvLoop();\n }\n\n _cancelLoops() {\n this.recvCancel.cancel();\n this.sendCancel.cancel();\n }\n\n async disconnect() {\n this._connected = false;\n\n this._cancelLoops();\n\n try {\n await this.socket.close();\n } catch (e) {\n this._log.error("error while closing socket connection");\n }\n }\n\n async send(data) {\n if (!this._connected) {\n throw new Error("Not connected");\n }\n\n await this._sendArray.push(data);\n }\n\n async recv() {\n while (this._connected) {\n const result = await this._recvArray.pop();\n\n if (result && result.length) {\n return result;\n }\n }\n\n throw new Error("Not connected");\n }\n\n async _sendLoop() {\n try {\n while (this._connected) {\n this.sendCancel = (0, real_cancellable_promise_1.pseudoCancellable)(this._sendArray.pop());\n const data = await this.sendCancel;\n\n if (!data) {\n continue;\n }\n\n await this._send(data);\n }\n } catch (e) {\n if (e instanceof real_cancellable_promise_1.Cancellation) {\n return;\n }\n\n this._log.info("The server closed the connection while sending");\n\n await this.disconnect();\n }\n }\n\n async _recvLoop() {\n let data;\n\n while (this._connected) {\n try {\n this.recvCancel = (0, real_cancellable_promise_1.pseudoCancellable)(this._recv());\n data = await this.recvCancel;\n } catch (e) {\n if (e instanceof real_cancellable_promise_1.Cancellation) {\n return;\n }\n\n this._log.info("The server closed the connection");\n\n await this.disconnect();\n\n if (!this._recvArray._queue.length) {\n await this._recvArray.push(undefined);\n }\n\n break;\n }\n\n try {\n await this._recvArray.push(data);\n } catch (e) {\n break;\n }\n }\n }\n\n async _initConn() {\n if (this._codec.tag) {\n await this.socket.write(this._codec.tag);\n }\n }\n\n async _send(data) {\n const encodedPacket = this._codec.encodePacket(data);\n\n this.socket.write(encodedPacket);\n }\n\n async _recv() {\n return await this._codec.readPacket(this.socket);\n }\n\n toString() {\n return `${this._ip}:${this._port}/${this.constructor.name.replace("Connection", "")}`;\n }\n\n}\n\nexports.Connection = Connection;\n\nclass ObfuscatedConnection extends Connection {\n constructor() {\n super(...arguments);\n this.ObfuscatedIO = undefined;\n }\n\n async _initConn() {\n this._obfuscation = new this.ObfuscatedIO(this);\n await this._obfuscation.initHeader();\n this.socket.write(this._obfuscation.header);\n }\n\n async _send(data) {\n this._obfuscation.write(this._codec.encodePacket(data));\n }\n\n async _recv() {\n return await this._codec.readPacket(this._obfuscation);\n }\n\n}\n\nexports.ObfuscatedConnection = ObfuscatedConnection;\n\nclass PacketCodec {\n constructor(connection) {\n this._conn = connection;\n }\n\n encodePacket(data) {\n throw new Error("Not Implemented"); // Override\n }\n\n async readPacket(reader) {\n // override\n throw new Error("Not Implemented");\n }\n\n}\n\nexports.PacketCodec = PacketCodec;\n\n//# sourceURL=webpack://telegram/./browser/network/connection/Connection.js?')},"./browser/network/connection/TCPAbridged.js": /*!***************************************************!*\ !*** ./browser/network/connection/TCPAbridged.js ***! \***************************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPAbridged = exports.AbridgedPacketCodec = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst Connection_1 = __webpack_require__(/*! ./Connection */ "./browser/network/connection/Connection.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nclass AbridgedPacketCodec extends Connection_1.PacketCodec {\n constructor(props) {\n super(props);\n this.tag = AbridgedPacketCodec.tag;\n this.obfuscateTag = AbridgedPacketCodec.obfuscateTag;\n }\n\n encodePacket(data) {\n let length = data.length >> 2;\n let temp;\n\n if (length < 127) {\n const b = buffer_1.Buffer.alloc(1);\n b.writeUInt8(length, 0);\n temp = b;\n } else {\n temp = buffer_1.Buffer.concat([buffer_1.Buffer.from("7f", "hex"), (0, Helpers_1.readBufferFromBigInt)((0, big_integer_1.default)(length), 3)]);\n }\n\n return buffer_1.Buffer.concat([temp, data]);\n }\n\n async readPacket(reader) {\n const readData = await reader.read(1);\n let length = readData[0];\n\n if (length >= 127) {\n length = buffer_1.Buffer.concat([await reader.read(3), buffer_1.Buffer.alloc(1)]).readInt32LE(0);\n }\n\n return reader.read(length << 2);\n }\n\n}\n\nexports.AbridgedPacketCodec = AbridgedPacketCodec;\nAbridgedPacketCodec.tag = buffer_1.Buffer.from("ef", "hex");\nAbridgedPacketCodec.obfuscateTag = buffer_1.Buffer.from("efefefef", "hex");\n/**\n * This is the mode with the lowest overhead, as it will\n * only require 1 byte if the packet length is less than\n * 508 bytes (127 << 2, which is very common).\n */\n\nclass ConnectionTCPAbridged extends Connection_1.Connection {\n constructor() {\n super(...arguments);\n this.PacketCodecClass = AbridgedPacketCodec;\n }\n\n}\n\nexports.ConnectionTCPAbridged = ConnectionTCPAbridged;\n\n//# sourceURL=webpack://telegram/./browser/network/connection/TCPAbridged.js?')},"./browser/network/connection/TCPFull.js": /*!***********************************************!*\ !*** ./browser/network/connection/TCPFull.js ***! \***********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPFull = exports.FullPacketCodec = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Connection_1 = __webpack_require__(/*! ./Connection */ "./browser/network/connection/Connection.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst errors_1 = __webpack_require__(/*! ../../errors */ "./browser/errors/index.js");\n\nclass FullPacketCodec extends Connection_1.PacketCodec {\n constructor(connection) {\n super(connection);\n this._sendCounter = 0; // Telegram will ignore us otherwise\n }\n\n encodePacket(data) {\n // https://core.telegram.org/mtproto#tcp-transport\n // total length, sequence number, packet and checksum (CRC32)\n const length = data.length + 12;\n const e = buffer_1.Buffer.alloc(8);\n e.writeInt32LE(length, 0);\n e.writeInt32LE(this._sendCounter, 4);\n data = buffer_1.Buffer.concat([e, data]);\n const crc = buffer_1.Buffer.alloc(4);\n crc.writeUInt32LE((0, Helpers_1.crc32)(data), 0);\n this._sendCounter += 1;\n return buffer_1.Buffer.concat([data, crc]);\n }\n /**\n *\n * @param reader {PromisedWebSockets}\n * @returns {Promise<*>}\n */\n\n\n async readPacket(reader) {\n const packetLenSeq = await reader.readExactly(8); // 4 and 4\n\n if (packetLenSeq === undefined) {\n // Return empty buffer in case of issue\n return buffer_1.Buffer.alloc(0);\n }\n\n const packetLen = packetLenSeq.readInt32LE(0);\n let body = await reader.readExactly(packetLen - 8);\n const checksum = body.slice(-4).readUInt32LE(0);\n body = body.slice(0, -4);\n const validChecksum = (0, Helpers_1.crc32)(buffer_1.Buffer.concat([packetLenSeq, body]));\n\n if (!(validChecksum === checksum)) {\n throw new errors_1.InvalidChecksumError(checksum, validChecksum);\n }\n\n return body;\n }\n\n}\n\nexports.FullPacketCodec = FullPacketCodec;\n\nclass ConnectionTCPFull extends Connection_1.Connection {\n constructor() {\n super(...arguments);\n this.PacketCodecClass = FullPacketCodec;\n }\n\n}\n\nexports.ConnectionTCPFull = ConnectionTCPFull;\n\n//# sourceURL=webpack://telegram/./browser/network/connection/TCPFull.js?')},"./browser/network/connection/TCPMTProxy.js": /*!**************************************************!*\ !*** ./browser/network/connection/TCPMTProxy.js ***! \**************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPMTProxyAbridged = exports.TCPMTProxy = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Connection_1 = __webpack_require__(/*! ./Connection */ "./browser/network/connection/Connection.js");\n\nconst TCPAbridged_1 = __webpack_require__(/*! ./TCPAbridged */ "./browser/network/connection/TCPAbridged.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst CTR_1 = __webpack_require__(/*! ../../crypto/CTR */ "./browser/crypto/CTR.js");\n\nclass MTProxyIO {\n constructor(connection) {\n this.header = undefined;\n this.connection = connection.socket;\n this._packetClass = connection.PacketCodecClass;\n this._secret = connection._secret;\n this._dcId = connection._dcId;\n }\n\n async initHeader() {\n let secret = this._secret;\n const isDD = secret.length == 17 && secret[0] == 0xdd;\n secret = isDD ? secret.slice(1) : secret;\n\n if (secret.length != 16) {\n throw new Error("MTProxy secret must be a hex-string representing 16 bytes");\n }\n\n const keywords = [buffer_1.Buffer.from("50567247", "hex"), buffer_1.Buffer.from("474554", "hex"), buffer_1.Buffer.from("504f5354", "hex"), buffer_1.Buffer.from("eeeeeeee", "hex")];\n let random; // eslint-disable-next-line no-constant-condition\n\n while (true) {\n random = (0, Helpers_1.generateRandomBytes)(64);\n\n if (random[0] !== 0xef && !random.slice(4, 8).equals(buffer_1.Buffer.alloc(4))) {\n let ok = true;\n\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n\n if (ok) {\n break;\n }\n }\n }\n\n random = random.toJSON().data;\n const randomReversed = buffer_1.Buffer.from(random.slice(8, 56)).reverse(); // Encryption has "continuous buffer" enabled\n\n const encryptKey = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(8, 40)), secret]));\n const encryptIv = buffer_1.Buffer.from(random.slice(40, 56));\n const decryptKey = await (0, Helpers_1.sha256)(buffer_1.Buffer.concat([buffer_1.Buffer.from(randomReversed.slice(0, 32)), secret]));\n const decryptIv = buffer_1.Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR_1.CTR(encryptKey, encryptIv);\n const decryptor = new CTR_1.CTR(decryptKey, decryptIv);\n random = buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(0, 56)), this._packetClass.obfuscateTag, buffer_1.Buffer.from(random.slice(60))]);\n const dcIdBytes = buffer_1.Buffer.alloc(2);\n dcIdBytes.writeInt8(this._dcId, 0);\n random = buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(0, 60)), dcIdBytes, buffer_1.Buffer.from(random.slice(62))]);\n random = buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(0, 56)), buffer_1.Buffer.from(encryptor.encrypt(random).slice(56, 64)), buffer_1.Buffer.from(random.slice(64))]);\n this.header = random;\n this._encrypt = encryptor;\n this._decrypt = decryptor;\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n\n}\n\nclass TCPMTProxy extends Connection_1.ObfuscatedConnection {\n constructor({\n ip,\n port,\n dcId,\n loggers,\n proxy,\n socket,\n testServers\n }) {\n super({\n ip: proxy.ip,\n port: proxy.port,\n dcId: dcId,\n loggers: loggers,\n socket: socket,\n proxy: proxy,\n testServers: testServers\n });\n this.ObfuscatedIO = MTProxyIO;\n\n if (!proxy.MTProxy) {\n throw new Error("This connection only supports MPTProxies");\n }\n\n if (!proxy.secret) {\n throw new Error("You need to provide the secret for the MTProxy");\n }\n\n if (proxy.secret && proxy.secret.match(/^[0-9a-f]+$/i)) {\n // probably hex\n this._secret = buffer_1.Buffer.from(proxy.secret, "hex");\n } else {\n // probably b64\n this._secret = buffer_1.Buffer.from(proxy.secret, "base64");\n }\n }\n\n}\n\nexports.TCPMTProxy = TCPMTProxy;\n\nclass ConnectionTCPMTProxyAbridged extends TCPMTProxy {\n constructor() {\n super(...arguments);\n this.PacketCodecClass = TCPAbridged_1.AbridgedPacketCodec;\n }\n\n}\n\nexports.ConnectionTCPMTProxyAbridged = ConnectionTCPMTProxyAbridged;\n\n//# sourceURL=webpack://telegram/./browser/network/connection/TCPMTProxy.js?')},"./browser/network/connection/TCPObfuscated.js": /*!*****************************************************!*\ !*** ./browser/network/connection/TCPObfuscated.js ***! \*****************************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPObfuscated = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst Connection_1 = __webpack_require__(/*! ./Connection */ "./browser/network/connection/Connection.js");\n\nconst TCPAbridged_1 = __webpack_require__(/*! ./TCPAbridged */ "./browser/network/connection/TCPAbridged.js");\n\nconst CTR_1 = __webpack_require__(/*! ../../crypto/CTR */ "./browser/crypto/CTR.js");\n\nclass ObfuscatedIO {\n constructor(connection) {\n this.header = undefined;\n this.connection = connection.socket;\n this._packetClass = connection.PacketCodecClass;\n }\n\n async initHeader() {\n // Obfuscated messages secrets cannot start with any of these\n const keywords = [buffer_1.Buffer.from("50567247", "hex"), buffer_1.Buffer.from("474554", "hex"), buffer_1.Buffer.from("504f5354", "hex"), buffer_1.Buffer.from("eeeeeeee", "hex")];\n let random; // eslint-disable-next-line no-constant-condition\n\n while (true) {\n random = (0, Helpers_1.generateRandomBytes)(64);\n\n if (random[0] !== 0xef && !random.slice(4, 8).equals(buffer_1.Buffer.alloc(4))) {\n let ok = true;\n\n for (const key of keywords) {\n if (key.equals(random.slice(0, 4))) {\n ok = false;\n break;\n }\n }\n\n if (ok) {\n break;\n }\n }\n }\n\n random = random.toJSON().data;\n const randomReversed = buffer_1.Buffer.from(random.slice(8, 56)).reverse(); // Encryption has "continuous buffer" enabled\n\n const encryptKey = buffer_1.Buffer.from(random.slice(8, 40));\n const encryptIv = buffer_1.Buffer.from(random.slice(40, 56));\n const decryptKey = buffer_1.Buffer.from(randomReversed.slice(0, 32));\n const decryptIv = buffer_1.Buffer.from(randomReversed.slice(32, 48));\n const encryptor = new CTR_1.CTR(encryptKey, encryptIv);\n const decryptor = new CTR_1.CTR(decryptKey, decryptIv);\n random = buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(0, 56)), this._packetClass.obfuscateTag, buffer_1.Buffer.from(random.slice(60))]);\n random = buffer_1.Buffer.concat([buffer_1.Buffer.from(random.slice(0, 56)), buffer_1.Buffer.from(encryptor.encrypt(random).slice(56, 64)), buffer_1.Buffer.from(random.slice(64))]);\n this.header = random;\n this._encrypt = encryptor;\n this._decrypt = decryptor;\n }\n\n async read(n) {\n const data = await this.connection.readExactly(n);\n return this._decrypt.encrypt(data);\n }\n\n write(data) {\n this.connection.write(this._encrypt.encrypt(data));\n }\n\n}\n\nclass ConnectionTCPObfuscated extends Connection_1.ObfuscatedConnection {\n constructor() {\n super(...arguments);\n this.ObfuscatedIO = ObfuscatedIO;\n this.PacketCodecClass = TCPAbridged_1.AbridgedPacketCodec;\n }\n\n}\n\nexports.ConnectionTCPObfuscated = ConnectionTCPObfuscated;\n\n//# sourceURL=webpack://telegram/./browser/network/connection/TCPObfuscated.js?')},"./browser/network/connection/index.js": /*!*********************************************!*\ !*** ./browser/network/connection/index.js ***! \*********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPObfuscated = exports.ConnectionTCPAbridged = exports.ConnectionTCPFull = exports.Connection = void 0;\n\nvar Connection_1 = __webpack_require__(/*! ./Connection */ "./browser/network/connection/Connection.js");\n\nObject.defineProperty(exports, "Connection", ({\n enumerable: true,\n get: function () {\n return Connection_1.Connection;\n }\n}));\n\nvar TCPFull_1 = __webpack_require__(/*! ./TCPFull */ "./browser/network/connection/TCPFull.js");\n\nObject.defineProperty(exports, "ConnectionTCPFull", ({\n enumerable: true,\n get: function () {\n return TCPFull_1.ConnectionTCPFull;\n }\n}));\n\nvar TCPAbridged_1 = __webpack_require__(/*! ./TCPAbridged */ "./browser/network/connection/TCPAbridged.js");\n\nObject.defineProperty(exports, "ConnectionTCPAbridged", ({\n enumerable: true,\n get: function () {\n return TCPAbridged_1.ConnectionTCPAbridged;\n }\n}));\n\nvar TCPObfuscated_1 = __webpack_require__(/*! ./TCPObfuscated */ "./browser/network/connection/TCPObfuscated.js");\n\nObject.defineProperty(exports, "ConnectionTCPObfuscated", ({\n enumerable: true,\n get: function () {\n return TCPObfuscated_1.ConnectionTCPObfuscated;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/network/connection/index.js?')},"./browser/network/index.js": /*!**********************************!*\ !*** ./browser/network/index.js ***! \**********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ConnectionTCPObfuscated = exports.ConnectionTCPAbridged = exports.ConnectionTCPFull = exports.Connection = exports.UpdateConnectionState = exports.MTProtoSender = exports.doAuthentication = exports.MTProtoPlainSender = void 0;\n\nvar MTProtoPlainSender_1 = __webpack_require__(/*! ./MTProtoPlainSender */ "./browser/network/MTProtoPlainSender.js");\n\nObject.defineProperty(exports, "MTProtoPlainSender", ({\n enumerable: true,\n get: function () {\n return MTProtoPlainSender_1.MTProtoPlainSender;\n }\n}));\n\nvar Authenticator_1 = __webpack_require__(/*! ./Authenticator */ "./browser/network/Authenticator.js");\n\nObject.defineProperty(exports, "doAuthentication", ({\n enumerable: true,\n get: function () {\n return Authenticator_1.doAuthentication;\n }\n}));\n\nvar MTProtoSender_1 = __webpack_require__(/*! ./MTProtoSender */ "./browser/network/MTProtoSender.js");\n\nObject.defineProperty(exports, "MTProtoSender", ({\n enumerable: true,\n get: function () {\n return MTProtoSender_1.MTProtoSender;\n }\n}));\n\nclass UpdateConnectionState {\n constructor(state) {\n this.state = state;\n }\n\n}\n\nexports.UpdateConnectionState = UpdateConnectionState;\nUpdateConnectionState.disconnected = -1;\nUpdateConnectionState.connected = 1;\nUpdateConnectionState.broken = 0;\n\nvar connection_1 = __webpack_require__(/*! ./connection */ "./browser/network/connection/index.js");\n\nObject.defineProperty(exports, "Connection", ({\n enumerable: true,\n get: function () {\n return connection_1.Connection;\n }\n}));\nObject.defineProperty(exports, "ConnectionTCPFull", ({\n enumerable: true,\n get: function () {\n return connection_1.ConnectionTCPFull;\n }\n}));\nObject.defineProperty(exports, "ConnectionTCPAbridged", ({\n enumerable: true,\n get: function () {\n return connection_1.ConnectionTCPAbridged;\n }\n}));\nObject.defineProperty(exports, "ConnectionTCPObfuscated", ({\n enumerable: true,\n get: function () {\n return connection_1.ConnectionTCPObfuscated;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/network/index.js?')},"./browser/platform.js": /*!*****************************!*\ !*** ./browser/platform.js ***! \*****************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.isNode = exports.isBrowser = exports.isDeno = void 0;\nexports.isDeno = "Deno" in globalThis;\nexports.isBrowser = !exports.isDeno && typeof window !== "undefined";\nexports.isNode = !exports.isBrowser;\n\n//# sourceURL=webpack://telegram/./browser/platform.js?')},"./browser/requestIter.js": /*!********************************!*\ !*** ./browser/requestIter.js ***! \********************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __asyncValues = this && this.__asyncValues || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var m = o[Symbol.asyncIterator],\n i;\n return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {\n return this;\n }, i);\n\n function verb(n) {\n i[n] = o[n] && function (v) {\n return new Promise(function (resolve, reject) {\n v = o[n](v), settle(resolve, reject, v.done, v.value);\n });\n };\n }\n\n function settle(resolve, reject, d, v) {\n Promise.resolve(v).then(function (v) {\n resolve({\n value: v,\n done: d\n });\n }, reject);\n }\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.RequestIter = void 0;\n\nconst Helpers_1 = __webpack_require__(/*! ./Helpers */ "./browser/Helpers.js");\n\nconst _1 = __webpack_require__(/*! ./ */ "./browser/index.js");\n\nclass RequestIter {\n constructor(client, limit, params = {}, args = {}) {\n this.client = client;\n this.reverse = params.reverse;\n this.waitTime = params.waitTime;\n this.limit = Math.max(!limit ? Number.MAX_SAFE_INTEGER : limit, 0);\n this.left = this.limit;\n this.buffer = undefined;\n this.kwargs = args;\n this.index = 0;\n this.total = undefined;\n this.lastLoad = 0;\n }\n\n async _init(kwargs) {// for overload\n }\n\n [Symbol.asyncIterator]() {\n this.buffer = undefined;\n this.index = 0;\n this.lastLoad = 0;\n this.left = this.limit;\n return {\n next: async () => {\n if (this.buffer == undefined) {\n this.buffer = [];\n\n if (await this._init(this.kwargs)) {\n this.left = this.buffer.length;\n }\n }\n\n if (this.left <= 0) {\n return {\n value: undefined,\n done: true\n };\n }\n\n if (this.index == this.buffer.length) {\n if (this.waitTime) {\n await (0, Helpers_1.sleep)(this.waitTime - (new Date().getTime() / 1000 - this.lastLoad));\n }\n\n this.lastLoad = new Date().getTime() / 1000;\n this.index = 0;\n this.buffer = [];\n const nextChunk = await this._loadNextChunk();\n\n if (nextChunk === false) {\n // we exit;\n return {\n value: undefined,\n done: true\n };\n }\n\n if (nextChunk) {\n this.left = this.buffer.length;\n }\n }\n\n if (!this.buffer || !this.buffer.length) {\n return {\n value: undefined,\n done: true\n };\n }\n\n const result = this.buffer[this.index];\n this.left -= 1;\n this.index += 1;\n return {\n value: result,\n done: false\n };\n }\n };\n }\n\n async collect() {\n var e_1, _a;\n\n const result = new _1.helpers.TotalList();\n\n try {\n for (var _b = __asyncValues(this), _c; _c = await _b.next(), !_c.done;) {\n const message = _c.value;\n result.push(message);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n result.total = this.total;\n return result;\n }\n\n async _loadNextChunk() {\n throw new Error("Not Implemented");\n }\n\n}\n\nexports.RequestIter = RequestIter;\n\n//# sourceURL=webpack://telegram/./browser/requestIter.js?')},"./browser/sessions/Abstract.js": /*!**************************************!*\ !*** ./browser/sessions/Abstract.js ***! \**************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Session = void 0;\n\nclass Session {}\n\nexports.Session = Session;\n\n//# sourceURL=webpack://telegram/./browser/sessions/Abstract.js?')},"./browser/sessions/Memory.js": /*!************************************!*\ !*** ./browser/sessions/Memory.js ***! \************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MemorySession = void 0;\n\nconst Abstract_1 = __webpack_require__(/*! ./Abstract */ "./browser/sessions/Abstract.js");\n\nconst tl_1 = __webpack_require__(/*! ../tl */ "./browser/tl/index.js");\n\nconst big_integer_1 = __importDefault(__webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js"));\n\nconst Utils_1 = __webpack_require__(/*! ../Utils */ "./browser/Utils.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/index.js");\n\nclass MemorySession extends Abstract_1.Session {\n constructor() {\n super();\n this._serverAddress = undefined;\n this._dcId = 0;\n this._port = undefined;\n this._takeoutId = undefined;\n this._entities = new Set();\n this._updateStates = {};\n }\n\n setDC(dcId, serverAddress, port) {\n this._dcId = dcId | 0;\n this._serverAddress = serverAddress;\n this._port = port;\n }\n\n get dcId() {\n return this._dcId;\n }\n\n get serverAddress() {\n return this._serverAddress;\n }\n\n get port() {\n return this._port;\n }\n\n get authKey() {\n return this._authKey;\n }\n\n set authKey(value) {\n this._authKey = value;\n }\n\n get takeoutId() {\n return this._takeoutId;\n }\n\n set takeoutId(value) {\n this._takeoutId = value;\n }\n\n getAuthKey(dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n return this.authKey;\n }\n\n setAuthKey(authKey, dcId) {\n if (dcId && dcId !== this.dcId) {\n // Not supported.\n return undefined;\n }\n\n this.authKey = authKey;\n }\n\n close() {}\n\n save() {}\n\n async load() {}\n\n delete() {}\n\n _entityValuesToRow(id, hash, username, phone, name) {\n // While this is a simple implementation it might be overrode by,\n // other classes so they don\'t need to implement the plural form\n // of the method. Don\'t remove.\n return [id, hash, username, phone, name];\n }\n\n _entityToRow(e) {\n if (!(e.classType === "constructor")) {\n return;\n }\n\n let p;\n let markedId;\n\n try {\n p = (0, Utils_1.getInputPeer)(e, false);\n markedId = (0, Utils_1.getPeerId)(p);\n } catch (e) {\n return;\n }\n\n let pHash;\n\n if (p instanceof tl_1.Api.InputPeerUser || p instanceof tl_1.Api.InputPeerChannel) {\n pHash = p.accessHash;\n } else if (p instanceof tl_1.Api.InputPeerChat) {\n pHash = big_integer_1.default.zero;\n } else {\n return;\n }\n\n let username = e.username;\n\n if (username) {\n username = username.toLowerCase();\n }\n\n const phone = e.phone;\n const name = (0, Utils_1.getDisplayName)(e);\n return this._entityValuesToRow(markedId, pHash, username, phone, name);\n }\n\n _entitiesToRows(tlo) {\n let entities = [];\n\n if (!(tlo.classType === "constructor") && (0, Helpers_1.isArrayLike)(tlo)) {\n // This may be a list of users already for instance\n entities = tlo;\n } else {\n if (typeof tlo === "object") {\n if ("user" in tlo) {\n entities.push(tlo.user);\n }\n\n if ("chat" in tlo) {\n entities.push(tlo.chat);\n }\n\n if ("channel" in tlo) {\n entities.push(tlo.channel);\n }\n\n if ("chats" in tlo && (0, Helpers_1.isArrayLike)(tlo.chats)) {\n entities = entities.concat(tlo.chats);\n }\n\n if ("users" in tlo && (0, Helpers_1.isArrayLike)(tlo.users)) {\n entities = entities.concat(tlo.users);\n }\n }\n }\n\n const rows = []; // Rows to add (id, hash, username, phone, name)\n\n for (const e of entities) {\n const row = this._entityToRow(e);\n\n if (row) {\n rows.push(row);\n }\n }\n\n return rows;\n }\n\n processEntities(tlo) {\n const entitiesSet = this._entitiesToRows(tlo);\n\n for (const e of entitiesSet) {\n this._entities.add(e);\n }\n }\n\n getEntityRowsByPhone(phone) {\n for (const e of this._entities) {\n // id, hash, username, phone, name\n if (e[3] === phone) {\n return [e[0], e[1]];\n }\n }\n }\n\n getEntityRowsByUsername(username) {\n for (const e of this._entities) {\n // id, hash, username, phone, name\n if (e[2] === username) {\n return [e[0], e[1]];\n }\n }\n }\n\n getEntityRowsByName(name) {\n for (const e of this._entities) {\n // id, hash, username, phone, name\n if (e[4] === name) {\n return [e[0], e[1]];\n }\n }\n }\n\n getEntityRowsById(id, exact = true) {\n if (exact) {\n for (const e of this._entities) {\n // id, hash, username, phone, name\n if (e[0] === id) {\n return [e[0], e[1]];\n }\n }\n } else {\n const ids = [__1.utils.getPeerId(new tl_1.Api.PeerUser({\n userId: (0, Helpers_1.returnBigInt)(id)\n })), __1.utils.getPeerId(new tl_1.Api.PeerChat({\n chatId: (0, Helpers_1.returnBigInt)(id)\n })), __1.utils.getPeerId(new tl_1.Api.PeerChannel({\n channelId: (0, Helpers_1.returnBigInt)(id)\n }))];\n\n for (const e of this._entities) {\n // id, hash, username, phone, name\n if (ids.includes(e[0])) {\n return [e[0], e[1]];\n }\n }\n }\n }\n\n getInputEntity(key) {\n let exact;\n\n if (typeof key === "object" && !big_integer_1.default.isInstance(key) && key.SUBCLASS_OF_ID) {\n if (key.SUBCLASS_OF_ID == 0xc91c90b6 || key.SUBCLASS_OF_ID == 0xe669bf46 || key.SUBCLASS_OF_ID == 0x40f202fd) {\n // @ts-ignore\n return key;\n } // Try to early return if this key can be casted as input peer\n\n\n return __1.utils.getInputPeer(key);\n } else {\n // Not a TLObject or can\'t be cast into InputPeer\n if (typeof key === "object") {\n key = __1.utils.getPeerId(key);\n exact = true;\n } else {\n exact = false;\n }\n }\n\n if (big_integer_1.default.isInstance(key) || typeof key == "bigint" || typeof key == "number") {\n key = key.toString();\n }\n\n let result = undefined;\n\n if (typeof key === "string") {\n const phone = __1.utils.parsePhone(key);\n\n if (phone) {\n result = this.getEntityRowsByPhone(phone);\n } else {\n const {\n username,\n isInvite\n } = __1.utils.parseUsername(key);\n\n if (username && !isInvite) {\n result = this.getEntityRowsByUsername(username);\n }\n }\n\n if (!result) {\n const id = __1.utils.parseID(key);\n\n if (id) {\n result = this.getEntityRowsById(id, exact);\n }\n }\n\n if (!result) {\n result = this.getEntityRowsByName(key);\n }\n }\n\n if (result) {\n let entityId = result[0]; // unpack resulting tuple\n\n const entityHash = (0, big_integer_1.default)(result[1]);\n\n const resolved = __1.utils.resolveId((0, Helpers_1.returnBigInt)(entityId));\n\n entityId = resolved[0];\n const kind = resolved[1]; // removes the mark and returns type of entity\n\n if (kind === tl_1.Api.PeerUser) {\n return new tl_1.Api.InputPeerUser({\n userId: entityId,\n accessHash: entityHash\n });\n } else if (kind === tl_1.Api.PeerChat) {\n return new tl_1.Api.InputPeerChat({\n chatId: entityId\n });\n } else if (kind === tl_1.Api.PeerChannel) {\n return new tl_1.Api.InputPeerChannel({\n channelId: entityId,\n accessHash: entityHash\n });\n }\n } else {\n throw new Error("Could not find input entity with key " + key);\n }\n\n throw new Error("Could not find input entity with key " + key);\n }\n\n}\n\nexports.MemorySession = MemorySession;\n\n//# sourceURL=webpack://telegram/./browser/sessions/Memory.js?')},"./browser/sessions/StoreSession.js": /*!******************************************!*\ !*** ./browser/sessions/StoreSession.js ***! \******************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __importDefault = this && this.__importDefault || function (mod) {\n return mod && mod.__esModule ? mod : {\n "default": mod\n };\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.StoreSession = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Memory_1 = __webpack_require__(/*! ./Memory */ "./browser/sessions/Memory.js");\n\nconst store2_1 = __importDefault(__webpack_require__(/*! store2 */ "./node_modules/store2/dist/store2.js"));\n\nconst AuthKey_1 = __webpack_require__(/*! ../crypto/AuthKey */ "./browser/crypto/AuthKey.js");\n\nclass StoreSession extends Memory_1.MemorySession {\n constructor(sessionName, divider = ":") {\n super();\n\n if (typeof localStorage === "undefined" || localStorage === null) {\n const LocalStorage = (__webpack_require__(/*! ./localStorage */ "./browser/sessions/localStorage.js").LocalStorage);\n\n this.store = store2_1.default.area(sessionName, new LocalStorage("./" + sessionName));\n } else {\n this.store = store2_1.default.area(sessionName, localStorage);\n }\n\n if (divider == undefined) {\n divider = ":";\n }\n\n this.sessionName = sessionName + divider;\n }\n\n async load() {\n let authKey = this.store.get(this.sessionName + "authKey");\n\n if (authKey && typeof authKey === "object") {\n this._authKey = new AuthKey_1.AuthKey();\n\n if ("data" in authKey) {\n authKey = buffer_1.Buffer.from(authKey.data);\n }\n\n await this._authKey.setKey(authKey);\n }\n\n const dcId = this.store.get(this.sessionName + "dcId");\n\n if (dcId) {\n this._dcId = dcId;\n }\n\n const port = this.store.get(this.sessionName + "port");\n\n if (port) {\n this._port = port;\n }\n\n const serverAddress = this.store.get(this.sessionName + "serverAddress");\n\n if (serverAddress) {\n this._serverAddress = serverAddress;\n }\n }\n\n setDC(dcId, serverAddress, port) {\n this.store.set(this.sessionName + "dcId", dcId);\n this.store.set(this.sessionName + "port", port);\n this.store.set(this.sessionName + "serverAddress", serverAddress);\n super.setDC(dcId, serverAddress, port);\n }\n\n set authKey(value) {\n this._authKey = value;\n this.store.set(this.sessionName + "authKey", value === null || value === void 0 ? void 0 : value.getKey());\n }\n\n get authKey() {\n return this._authKey;\n }\n\n processEntities(tlo) {\n const rows = this._entitiesToRows(tlo);\n\n if (!rows) {\n return;\n }\n\n for (const row of rows) {\n row.push(new Date().getTime().toString());\n this.store.set(this.sessionName + row[0], row);\n }\n }\n\n getEntityRowsById(id, exact = true) {\n return this.store.get(this.sessionName + id.toString());\n }\n\n}\n\nexports.StoreSession = StoreSession;\n\n//# sourceURL=webpack://telegram/./browser/sessions/StoreSession.js?')},"./browser/sessions/StringSession.js": /*!*******************************************!*\ !*** ./browser/sessions/StringSession.js ***! \*******************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.StringSession = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Memory_1 = __webpack_require__(/*! ./Memory */ "./browser/sessions/Memory.js");\n\nconst extensions_1 = __webpack_require__(/*! ../extensions */ "./browser/extensions/index.js");\n\nconst AuthKey_1 = __webpack_require__(/*! ../crypto/AuthKey */ "./browser/crypto/AuthKey.js");\n\nconst CURRENT_VERSION = "1";\n\nclass StringSession extends Memory_1.MemorySession {\n /**\n * This session file can be easily saved and loaded as a string. According\n * to the initial design, it contains only the data that is necessary for\n * successful connection and authentication, so takeout ID is not stored.\n * It is thought to be used where you don\'t want to create any on-disk\n * files but would still like to be able to save and load existing sessions\n * by other means.\n * You can use custom `encode` and `decode` functions, if present:\n * `encode` definition must be ``function encode(value: Buffer) -> string:``.\n * `decode` definition must be ``function decode(value: string) -> Buffer:``.\n * @param session {string|null}\n */\n constructor(session) {\n super();\n\n if (session) {\n if (session[0] !== CURRENT_VERSION) {\n throw new Error("Not a valid string");\n }\n\n session = session.slice(1);\n const r = StringSession.decode(session);\n const reader = new extensions_1.BinaryReader(r);\n this._dcId = reader.read(1).readUInt8(0);\n\n if (session.length == 352) {\n // Telethon session\n const ip_v4 = reader.read(4); // TODO looks ugly smh\n\n this._serverAddress = ip_v4[0].toString() + "." + ip_v4[1].toString() + "." + ip_v4[2].toString() + "." + ip_v4[3].toString();\n } else {\n // TODO find a better of doing this\n const serverAddressLen = reader.read(2).readInt16BE(0);\n\n if (serverAddressLen > 100) {\n reader.offset -= 2;\n this._serverAddress = reader.read(16).toString("hex").match(/.{1,4}/g).map(val => val.replace(/^0+/, "")).join(":").replace(/0000\\:/g, ":").replace(/:{2,}/g, "::");\n } else {\n this._serverAddress = reader.read(serverAddressLen).toString();\n }\n }\n\n this._port = reader.read(2).readInt16BE(0);\n this._key = reader.read(-1);\n }\n }\n /**\n * @param x {Buffer}\n * @returns {string}\n */\n\n\n static encode(x) {\n return x.toString("base64");\n }\n /**\n * @param x {string}\n * @returns {Buffer}\n */\n\n\n static decode(x) {\n return buffer_1.Buffer.from(x, "base64");\n }\n\n async load() {\n if (this._key) {\n this._authKey = new AuthKey_1.AuthKey();\n await this._authKey.setKey(this._key);\n }\n }\n\n save() {\n if (!this.authKey || !this.serverAddress || !this.port) {\n return "";\n } // TS is weird\n\n\n const key = this.authKey.getKey();\n\n if (!key) {\n return "";\n }\n\n const dcBuffer = buffer_1.Buffer.from([this.dcId]);\n const addressBuffer = buffer_1.Buffer.from(this.serverAddress);\n const addressLengthBuffer = buffer_1.Buffer.alloc(2);\n addressLengthBuffer.writeInt16BE(addressBuffer.length, 0);\n const portBuffer = buffer_1.Buffer.alloc(2);\n portBuffer.writeInt16BE(this.port, 0);\n return CURRENT_VERSION + StringSession.encode(buffer_1.Buffer.concat([dcBuffer, addressLengthBuffer, addressBuffer, portBuffer, key]));\n }\n\n}\n\nexports.StringSession = StringSession;\n\n//# sourceURL=webpack://telegram/./browser/sessions/StringSession.js?')},"./browser/sessions/index.js": /*!***********************************!*\ !*** ./browser/sessions/index.js ***! \***********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Session = exports.StoreSession = exports.StringSession = exports.MemorySession = void 0;\n\nvar Memory_1 = __webpack_require__(/*! ./Memory */ "./browser/sessions/Memory.js");\n\nObject.defineProperty(exports, "MemorySession", ({\n enumerable: true,\n get: function () {\n return Memory_1.MemorySession;\n }\n}));\n\nvar StringSession_1 = __webpack_require__(/*! ./StringSession */ "./browser/sessions/StringSession.js");\n\nObject.defineProperty(exports, "StringSession", ({\n enumerable: true,\n get: function () {\n return StringSession_1.StringSession;\n }\n}));\n\nvar StoreSession_1 = __webpack_require__(/*! ./StoreSession */ "./browser/sessions/StoreSession.js");\n\nObject.defineProperty(exports, "StoreSession", ({\n enumerable: true,\n get: function () {\n return StoreSession_1.StoreSession;\n }\n}));\n\nvar Abstract_1 = __webpack_require__(/*! ./Abstract */ "./browser/sessions/Abstract.js");\n\nObject.defineProperty(exports, "Session", ({\n enumerable: true,\n get: function () {\n return Abstract_1.Session;\n }\n})); // @ts-ignore\n//export {CacheApiSession} from \'./CacheApiSession\';\n\n//# sourceURL=webpack://telegram/./browser/sessions/index.js?')},"./browser/sessions/localStorage.js": /*!******************************************!*\ !*** ./browser/sessions/localStorage.js ***! \******************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.LocalStorage = void 0;\n\nclass LocalStorage {\n constructor(location) {\n throw new Error("Do not call me");\n }\n\n}\n\nexports.LocalStorage = LocalStorage;\n\n//# sourceURL=webpack://telegram/./browser/sessions/localStorage.js?')},"./browser/tl/AllTLObjects.js": /*!************************************!*\ !*** ./browser/tl/AllTLObjects.js ***! \************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.tlobjects = exports.LAYER = void 0;\nexports.LAYER = 158;\n\nconst _1 = __webpack_require__(/*! ./ */ "./browser/tl/index.js");\n\nconst tlobjects = {};\nexports.tlobjects = tlobjects;\n\nfor (const tl of Object.values(_1.Api)) {\n if ("CONSTRUCTOR_ID" in tl) {\n tlobjects[tl.CONSTRUCTOR_ID] = tl;\n } else {\n for (const sub of Object.values(tl)) {\n tlobjects[sub.CONSTRUCTOR_ID] = sub;\n }\n }\n}\n\n//# sourceURL=webpack://telegram/./browser/tl/AllTLObjects.js?')},"./browser/tl/api.js": /*!***************************!*\ !*** ./browser/tl/api.js ***! \***************************/(module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst {\n inspect\n} = __webpack_require__(/*! ../inspect */ "./browser/inspect.js");\n\nconst bigInt = __webpack_require__(/*! big-integer */ "./node_modules/big-integer/BigInteger.js");\n\nconst {\n generateRandomBytes,\n readBigIntFromBuffer,\n isArrayLike,\n betterConsoleLog\n} = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst tlContent = __webpack_require__(/*! ./apiTl.js */ "./browser/tl/apiTl.js");\n\nconst schemeContent = __webpack_require__(/*! ./schemaTl.js */ "./browser/tl/schemaTl.js");\n\nfunction generateRandomBigInt() {\n return readBigIntFromBuffer(generateRandomBytes(8), false, true);\n}\n\nconst {\n parseTl,\n serializeBytes,\n serializeDate\n} = __webpack_require__(/*! ./generationHelpers */ "./browser/tl/generationHelpers.js");\n\nconst {\n toSignedLittleBuffer\n} = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst NAMED_AUTO_CASTS = new Set(["chatId,int"]);\nconst NAMED_BLACKLIST = new Set(["discardEncryption"]);\nconst AUTO_CASTS = new Set(["InputPeer", "InputChannel", "InputUser", "InputDialogPeer", "InputNotifyPeer", "InputMedia", "InputPhoto", "InputMessage", "InputDocument", "InputChatPhoto"]);\n\nclass CastError extends Error {\n constructor(objectName, expected, actual, ...params) {\n // Pass remaining arguments (including vendor specific ones) to parent constructor\n const message = "Found wrong type for " + objectName + ". expected " + expected + " but received " + actual + ".If you think this is a mistake please report it.";\n super(message, ...params); // Maintains proper stack trace for where our error was thrown (only available on V8)\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CastError);\n }\n\n this.name = "CastError"; // Custom debugging information\n }\n\n}\n\nconst CACHING_SUPPORTED = typeof self !== "undefined" && self.localStorage !== undefined;\nconst CACHE_KEY = "GramJs:apiCache";\n\nfunction buildApiFromTlSchema() {\n let definitions;\n const fromCache = CACHING_SUPPORTED && loadFromCache();\n\n if (fromCache) {\n definitions = fromCache;\n } else {\n definitions = loadFromTlSchemas();\n\n if (CACHING_SUPPORTED) {\n localStorage.setItem(CACHE_KEY, JSON.stringify(definitions));\n }\n }\n\n return createClasses("all", definitions);\n}\n\nfunction loadFromCache() {\n const jsonCache = localStorage.getItem(CACHE_KEY);\n return jsonCache && JSON.parse(jsonCache);\n}\n\nfunction loadFromTlSchemas() {\n const [constructorParamsApi, functionParamsApi] = extractParams(tlContent);\n const [constructorParamsSchema, functionParamsSchema] = extractParams(schemeContent);\n const constructors = [].concat(constructorParamsApi, constructorParamsSchema);\n const requests = [].concat(functionParamsApi, functionParamsSchema);\n return [].concat(constructors, requests);\n}\n\nfunction extractParams(fileContent) {\n const f = parseTl(fileContent, 109);\n const constructors = [];\n const functions = [];\n\n for (const d of f) {\n d.isFunction ? functions.push(d) : constructors.push(d);\n }\n\n return [constructors, functions];\n}\n\nfunction argToBytes(x, type, argName, requestName) {\n switch (type) {\n case "int":\n const i = buffer_1.Buffer.alloc(4);\n i.writeInt32LE(x, 0);\n return i;\n\n case "long":\n return toSignedLittleBuffer(x, 8);\n\n case "int128":\n return toSignedLittleBuffer(x, 16);\n\n case "int256":\n return toSignedLittleBuffer(x, 32);\n\n case "double":\n const d = buffer_1.Buffer.alloc(8);\n d.writeDoubleLE(x, 0);\n return d;\n\n case "string":\n return serializeBytes(x);\n\n case "Bool":\n return x ? buffer_1.Buffer.from("b5757299", "hex") : buffer_1.Buffer.from("379779bc", "hex");\n\n case "true":\n return buffer_1.Buffer.alloc(0);\n\n case "bytes":\n return serializeBytes(x);\n\n case "date":\n return serializeDate(x);\n\n default:\n if (x === undefined || typeof x.getBytes !== "function") {\n throw new Error(`Required object ${argName} of ${requestName} is undefined`);\n }\n\n return x.getBytes();\n }\n}\n\nasync function getInputFromResolve(utils, client, peer, peerType) {\n switch (peerType) {\n case "InputPeer":\n return utils.getInputPeer(await client.getInputEntity(peer));\n\n case "InputChannel":\n return utils.getInputChannel(await client.getInputEntity(peer));\n\n case "InputUser":\n return utils.getInputUser(await client.getInputEntity(peer));\n\n case "InputDialogPeer":\n return await client._getInputDialog(peer);\n\n case "InputNotifyPeer":\n return await client._getInputNotify(peer);\n\n case "InputMedia":\n return utils.getInputMedia(peer);\n\n case "InputPhoto":\n return utils.getInputPhoto(peer);\n\n case "InputMessage":\n return utils.getInputMessage(peer);\n\n case "InputDocument":\n return utils.getInputDocument(peer);\n\n case "InputChatPhoto":\n return utils.getInputChatPhoto(peer);\n\n case "chatId,int":\n return await client.getPeerId(peer, false);\n\n default:\n throw new Error("unsupported peer type : " + peerType);\n }\n}\n\nfunction getArgFromReader(reader, arg) {\n if (arg.isVector) {\n if (arg.useVectorId) {\n reader.readInt();\n }\n\n const temp = [];\n const len = reader.readInt();\n arg.isVector = false;\n\n for (let i = 0; i < len; i++) {\n temp.push(getArgFromReader(reader, arg));\n }\n\n arg.isVector = true;\n return temp;\n } else if (arg.flagIndicator) {\n return reader.readInt();\n } else {\n switch (arg.type) {\n case "int":\n return reader.readInt();\n\n case "long":\n return reader.readLong();\n\n case "int128":\n return reader.readLargeInt(128);\n\n case "int256":\n return reader.readLargeInt(256);\n\n case "double":\n return reader.readDouble();\n\n case "string":\n return reader.tgReadString();\n\n case "Bool":\n return reader.tgReadBool();\n\n case "true":\n return true;\n\n case "bytes":\n return reader.tgReadBytes();\n\n case "date":\n return reader.tgReadDate();\n\n default:\n if (!arg.skipConstructorId) {\n return reader.tgReadObject();\n } else {\n return api.constructors[arg.type].fromReader(reader);\n }\n\n }\n }\n}\n\nfunction compareType(value, type) {\n let correct = true;\n\n switch (type) {\n case "number":\n correct = typeof value === "number" || value === undefined;\n break;\n\n case "string":\n case "boolean":\n correct = typeof value === type;\n break;\n\n case "bigInt":\n correct = bigInt.isInstance(value) || typeof value === "bigint" || typeof value === "number" || typeof value === "string" || value === undefined;\n break;\n\n case "true":\n // true value is always correct\n break;\n\n case "buffer":\n correct = buffer_1.Buffer.isBuffer(value);\n break;\n\n case "date":\n correct = value && Object.prototype.toString.call(value) === "[object Date]" && !isNaN(value) || typeof value === "number";\n break;\n\n default:\n console.error(new Error("Unknown type." + type));\n }\n\n return correct;\n}\n\nfunction createClasses(classesType, params) {\n const classes = {};\n\n for (const classParams of params) {\n const {\n name,\n constructorId,\n subclassOfId,\n argsConfig,\n namespace,\n isFunction,\n result\n } = classParams;\n const fullName = [namespace, name].join(".").replace(/^\\./, "");\n\n class VirtualClass {\n constructor(args) {\n this.CONSTRUCTOR_ID = constructorId;\n this.SUBCLASS_OF_ID = subclassOfId;\n this.className = fullName;\n this.classType = isFunction ? "request" : "constructor";\n args = args || {};\n this.originalArgs = args;\n this.init(args);\n\n for (const argName in argsConfig) {\n if (argName === "randomId" && !args[argName]) {\n if (argsConfig[argName].isVector) {\n const rands = [];\n\n for (let i = 0; i < args["id"].length; i++) {\n rands.push(generateRandomBigInt());\n }\n\n this[argName] = rands;\n } else {\n this[argName] = generateRandomBigInt();\n }\n } else {\n this[argName] = args[argName];\n }\n }\n }\n\n init(args) {}\n\n static fromReader(reader) {\n const args = {};\n\n for (const argName in argsConfig) {\n if (argsConfig.hasOwnProperty(argName)) {\n const arg = argsConfig[argName];\n\n if (arg.isFlag) {\n if (arg.type === "true") {\n args[argName] = Boolean(args[arg.flagName] & 1 << arg.flagIndex);\n continue;\n }\n\n if (args[arg.flagName] & 1 << arg.flagIndex) {\n args[argName] = getArgFromReader(reader, arg);\n } else {\n args[argName] = null;\n }\n } else {\n if (arg.flagIndicator) {\n arg.name = argName;\n }\n\n args[argName] = getArgFromReader(reader, arg);\n }\n }\n }\n\n return new this(args);\n }\n\n validate() {\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].flagIndicator || argsConfig[arg].isFlag) {\n // we don\'t care about flags\n continue;\n }\n\n const currentValue = this[arg];\n this.assertType(arg, argsConfig[arg], currentValue);\n }\n }\n }\n\n assertType(objectName, object, value) {\n let expected;\n\n if (object["isVector"]) {\n if (!isArrayLike(value)) {\n console.error(new CastError(objectName, "array", value));\n }\n\n if (value == undefined) {\n value = [];\n }\n\n for (const o of value) {\n this.assertType(objectName, Object.assign(Object.assign({}, object), {\n isVector: false\n }), o);\n }\n } else {\n switch (object["type"]) {\n case "int":\n expected = "number";\n break;\n\n case "long":\n case "int128":\n case "int256":\n expected = "bigInt";\n break;\n\n case "double":\n expected = "number";\n break;\n\n case "string":\n expected = "string";\n break;\n\n case "Bool":\n expected = "boolean";\n break;\n\n case "true":\n expected = "true";\n break;\n\n case "bytes":\n expected = "buffer";\n break;\n\n case "date":\n expected = "date";\n break;\n\n default:\n expected = "object";\n }\n\n if (expected === "object") {// will be validated in get byte();\n } else {\n const isCorrectType = compareType(value, expected);\n\n if (isCorrectType !== true) {\n console.error(new CastError(objectName, expected, value));\n }\n }\n }\n }\n\n getBytes() {\n try {\n this.validate();\n } catch (e) {// feature still in alpha so errors are expected.\n }\n\n const idForBytes = this.CONSTRUCTOR_ID;\n const c = buffer_1.Buffer.alloc(4);\n c.writeUInt32LE(idForBytes, 0);\n const buffers = [c];\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (argsConfig[arg].isFlag) {\n if (this[arg] === false && argsConfig[arg].type !== "Bool" || this[arg] === null || this[arg] === undefined || argsConfig[arg].type === "true") {\n continue;\n }\n }\n\n if (argsConfig[arg].isVector) {\n if (argsConfig[arg].useVectorId) {\n buffers.push(buffer_1.Buffer.from("15c4b51c", "hex"));\n }\n\n const l = buffer_1.Buffer.alloc(4);\n l.writeInt32LE(this[arg].length, 0);\n buffers.push(l, buffer_1.Buffer.concat(this[arg].map(x => argToBytes(x, argsConfig[arg].type, fullName))));\n } else if (argsConfig[arg].flagIndicator) {\n if (!Object.values(argsConfig).some(f => f.isFlag)) {\n buffers.push(buffer_1.Buffer.alloc(4));\n } else {\n let flagCalculate = 0;\n\n for (const f in argsConfig) {\n if (argsConfig[f].isFlag && arg === argsConfig[f].flagName) {\n if (this[f] === false && argsConfig[f].type !== "Bool" || this[f] === undefined || this[f] === null) {\n flagCalculate |= 0;\n } else {\n flagCalculate |= 1 << argsConfig[f].flagIndex;\n }\n }\n }\n\n const f = buffer_1.Buffer.alloc(4);\n f.writeUInt32LE(flagCalculate, 0);\n buffers.push(f);\n }\n } else {\n buffers.push(argToBytes(this[arg], argsConfig[arg].type, arg, fullName));\n\n if (this[arg] && typeof this[arg].getBytes === "function") {\n let boxed = argsConfig[arg].type.charAt(argsConfig[arg].type.indexOf(".") + 1);\n boxed = boxed === boxed.toUpperCase();\n\n if (!boxed) {\n buffers.shift();\n }\n }\n }\n }\n }\n\n return buffer_1.Buffer.concat(buffers);\n }\n\n readResult(reader) {\n if (!isFunction) {\n throw new Error("`readResult()` called for non-request instance");\n }\n\n const m = result.match(/Vector<(int|long)>/);\n\n if (m) {\n reader.readInt();\n const temp = [];\n const len = reader.readInt();\n\n if (m[1] === "int") {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readInt());\n }\n } else {\n for (let i = 0; i < len; i++) {\n temp.push(reader.readLong());\n }\n }\n\n return temp;\n } else {\n return reader.tgReadObject();\n }\n }\n\n async resolve(client, utils) {\n if (!isFunction) {\n throw new Error("`resolve()` called for non-request instance");\n }\n\n for (const arg in argsConfig) {\n if (argsConfig.hasOwnProperty(arg)) {\n if (!AUTO_CASTS.has(argsConfig[arg].type)) {\n if (!NAMED_AUTO_CASTS.has(`${argsConfig[arg].name},${argsConfig[arg].type}`)) {\n continue;\n }\n }\n\n if (argsConfig[arg].isFlag) {\n if (!this[arg]) {\n continue;\n }\n }\n\n if (argsConfig[arg].isVector) {\n const temp = [];\n\n for (const x of this[arg]) {\n temp.push(await getInputFromResolve(utils, client, x, argsConfig[arg].type));\n }\n\n this[arg] = temp;\n } else {\n this[arg] = await getInputFromResolve(utils, client, this[arg], argsConfig[arg].type);\n }\n }\n }\n }\n\n [inspect.custom]() {\n return betterConsoleLog(this);\n }\n\n toJSON() {\n return Object.assign(Object.assign({}, this.originalArgs), {\n className: fullName\n });\n }\n\n }\n\n VirtualClass.CONSTRUCTOR_ID = constructorId;\n VirtualClass.SUBCLASS_OF_ID = subclassOfId;\n VirtualClass.className = fullName;\n VirtualClass.classType = isFunction ? "request" : "constructor";\n\n if (namespace) {\n if (!classes[namespace]) {\n classes[namespace] = {};\n }\n\n classes[namespace][name] = VirtualClass;\n } else {\n classes[name] = VirtualClass;\n }\n }\n\n return classes;\n}\n\nconst api = buildApiFromTlSchema();\nmodule.exports = {\n Api: api\n};\n\n//# sourceURL=webpack://telegram/./browser/tl/api.js?')},"./browser/tl/apiTl.js": /*!*****************************!*\ !*** ./browser/tl/apiTl.js ***! \*****************************/module=>{"use strict";eval("\n\nmodule.exports = `\nboolFalse#bc799737 = Bool;\nboolTrue#997275b5 = Bool;\ntrue#3fedd339 = True;\nvector#1cb5c415 {t:Type} # [ t ] = Vector t;\nerror#c4b9f9bb code:int text:string = Error;\nnull#56730bcc = Null;\ninputPeerEmpty#7f3b18ea = InputPeer;\ninputPeerSelf#7da07ec9 = InputPeer;\ninputPeerChat#35a95cb9 chat_id:long = InputPeer;\ninputPeerUser#dde8a54c user_id:long access_hash:long = InputPeer;\ninputPeerChannel#27bcbbfc channel_id:long access_hash:long = InputPeer;\ninputPeerUserFromMessage#a87b0a1c peer:InputPeer msg_id:int user_id:long = InputPeer;\ninputPeerChannelFromMessage#bd2a0840 peer:InputPeer msg_id:int channel_id:long = InputPeer;\ninputUserEmpty#b98886cf = InputUser;\ninputUserSelf#f7c1b13f = InputUser;\ninputUser#f21158c6 user_id:long access_hash:long = InputUser;\ninputUserFromMessage#1da448e2 peer:InputPeer msg_id:int user_id:long = InputUser;\ninputPhoneContact#f392b7f4 client_id:long phone:string first_name:string last_name:string = InputContact;\ninputFile#f52ff27f id:long parts:int name:string md5_checksum:string = InputFile;\ninputFileBig#fa4f0bb5 id:long parts:int name:string = InputFile;\ninputMediaEmpty#9664f57f = InputMedia;\ninputMediaUploadedPhoto#1e287d04 flags:# spoiler:flags.2?true file:InputFile stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaPhoto#b3ba0635 flags:# spoiler:flags.1?true id:InputPhoto ttl_seconds:flags.0?int = InputMedia;\ninputMediaGeoPoint#f9c44144 geo_point:InputGeoPoint = InputMedia;\ninputMediaContact#f8ab7dfb phone_number:string first_name:string last_name:string vcard:string = InputMedia;\ninputMediaUploadedDocument#5b38c6c1 flags:# nosound_video:flags.3?true force_file:flags.4?true spoiler:flags.5?true file:InputFile thumb:flags.2?InputFile mime_type:string attributes:Vector stickers:flags.0?Vector ttl_seconds:flags.1?int = InputMedia;\ninputMediaDocument#33473058 flags:# spoiler:flags.2?true id:InputDocument ttl_seconds:flags.0?int query:flags.1?string = InputMedia;\ninputMediaVenue#c13d1c11 geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string = InputMedia;\ninputMediaPhotoExternal#e5bbfe1a flags:# spoiler:flags.1?true url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaDocumentExternal#fb52dc99 flags:# spoiler:flags.1?true url:string ttl_seconds:flags.0?int = InputMedia;\ninputMediaGame#d33f43f3 id:InputGame = InputMedia;\ninputMediaInvoice#8eb5a6d5 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON start_param:flags.1?string extended_media:flags.2?InputMedia = InputMedia;\ninputMediaGeoLive#971fa843 flags:# stopped:flags.0?true geo_point:InputGeoPoint heading:flags.2?int period:flags.1?int proximity_notification_radius:flags.3?int = InputMedia;\ninputMediaPoll#f94e5f1 flags:# poll:Poll correct_answers:flags.0?Vector solution:flags.1?string solution_entities:flags.1?Vector = InputMedia;\ninputMediaDice#e66fbf7b emoticon:string = InputMedia;\ninputChatPhotoEmpty#1ca48f57 = InputChatPhoto;\ninputChatUploadedPhoto#bdcdaec0 flags:# file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double video_emoji_markup:flags.3?VideoSize = InputChatPhoto;\ninputChatPhoto#8953ad37 id:InputPhoto = InputChatPhoto;\ninputGeoPointEmpty#e4c123d6 = InputGeoPoint;\ninputGeoPoint#48222faf flags:# lat:double long:double accuracy_radius:flags.0?int = InputGeoPoint;\ninputPhotoEmpty#1cd7bf0d = InputPhoto;\ninputPhoto#3bb3b94a id:long access_hash:long file_reference:bytes = InputPhoto;\ninputFileLocation#dfdaabe1 volume_id:long local_id:int secret:long file_reference:bytes = InputFileLocation;\ninputEncryptedFileLocation#f5235d55 id:long access_hash:long = InputFileLocation;\ninputDocumentFileLocation#bad07584 id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputSecureFileLocation#cbc7ee28 id:long access_hash:long = InputFileLocation;\ninputTakeoutFileLocation#29be5899 = InputFileLocation;\ninputPhotoFileLocation#40181ffe id:long access_hash:long file_reference:bytes thumb_size:string = InputFileLocation;\ninputPhotoLegacyFileLocation#d83466f3 id:long access_hash:long file_reference:bytes volume_id:long local_id:int secret:long = InputFileLocation;\ninputPeerPhotoFileLocation#37257e99 flags:# big:flags.0?true peer:InputPeer photo_id:long = InputFileLocation;\ninputStickerSetThumb#9d84f3db stickerset:InputStickerSet thumb_version:int = InputFileLocation;\ninputGroupCallStream#598a92a flags:# call:InputGroupCall time_ms:long scale:int video_channel:flags.0?int video_quality:flags.0?int = InputFileLocation;\npeerUser#59511722 user_id:long = Peer;\npeerChat#36c6019a chat_id:long = Peer;\npeerChannel#a2a5371e channel_id:long = Peer;\nstorage.fileUnknown#aa963b05 = storage.FileType;\nstorage.filePartial#40bc6f52 = storage.FileType;\nstorage.fileJpeg#7efe0e = storage.FileType;\nstorage.fileGif#cae1aadf = storage.FileType;\nstorage.filePng#a4f63c0 = storage.FileType;\nstorage.filePdf#ae1e508d = storage.FileType;\nstorage.fileMp3#528a0677 = storage.FileType;\nstorage.fileMov#4b09ebbc = storage.FileType;\nstorage.fileMp4#b3cea0e4 = storage.FileType;\nstorage.fileWebp#1081464c = storage.FileType;\nuserEmpty#d3bc4b7a id:long = User;\nuser#8f97c628 flags:# self:flags.10?true contact:flags.11?true mutual_contact:flags.12?true deleted:flags.13?true bot:flags.14?true bot_chat_history:flags.15?true bot_nochats:flags.16?true verified:flags.17?true restricted:flags.18?true min:flags.20?true bot_inline_geo:flags.21?true support:flags.23?true scam:flags.24?true apply_min_photo:flags.25?true fake:flags.26?true bot_attach_menu:flags.27?true premium:flags.28?true attach_menu_enabled:flags.29?true flags2:# bot_can_edit:flags2.1?true id:long access_hash:flags.0?long first_name:flags.1?string last_name:flags.2?string username:flags.3?string phone:flags.4?string photo:flags.5?UserProfilePhoto status:flags.6?UserStatus bot_info_version:flags.14?int restriction_reason:flags.18?Vector bot_inline_placeholder:flags.19?string lang_code:flags.22?string emoji_status:flags.30?EmojiStatus usernames:flags2.0?Vector = User;\nuserProfilePhotoEmpty#4f11bae1 = UserProfilePhoto;\nuserProfilePhoto#82d1f706 flags:# has_video:flags.0?true personal:flags.2?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = UserProfilePhoto;\nuserStatusEmpty#9d05049 = UserStatus;\nuserStatusOnline#edb93949 expires:int = UserStatus;\nuserStatusOffline#8c703f was_online:int = UserStatus;\nuserStatusRecently#e26f42f1 = UserStatus;\nuserStatusLastWeek#7bf09fc = UserStatus;\nuserStatusLastMonth#77ebc742 = UserStatus;\nchatEmpty#29562865 id:long = Chat;\nchat#41cbf256 flags:# creator:flags.0?true left:flags.2?true deactivated:flags.5?true call_active:flags.23?true call_not_empty:flags.24?true noforwards:flags.25?true id:long title:string photo:ChatPhoto participants_count:int date:int version:int migrated_to:flags.6?InputChannel admin_rights:flags.14?ChatAdminRights default_banned_rights:flags.18?ChatBannedRights = Chat;\nchatForbidden#6592a1a7 id:long title:string = Chat;\nchannel#83259464 flags:# creator:flags.0?true left:flags.2?true broadcast:flags.5?true verified:flags.7?true megagroup:flags.8?true restricted:flags.9?true signatures:flags.11?true min:flags.12?true scam:flags.19?true has_link:flags.20?true has_geo:flags.21?true slowmode_enabled:flags.22?true call_active:flags.23?true call_not_empty:flags.24?true fake:flags.25?true gigagroup:flags.26?true noforwards:flags.27?true join_to_send:flags.28?true join_request:flags.29?true forum:flags.30?true flags2:# id:long access_hash:flags.13?long title:string username:flags.6?string photo:ChatPhoto date:int restriction_reason:flags.9?Vector admin_rights:flags.14?ChatAdminRights banned_rights:flags.15?ChatBannedRights default_banned_rights:flags.18?ChatBannedRights participants_count:flags.17?int usernames:flags2.0?Vector = Chat;\nchannelForbidden#17d493d5 flags:# broadcast:flags.5?true megagroup:flags.8?true id:long access_hash:long title:string until_date:flags.16?int = Chat;\nchatFull#c9d31138 flags:# can_set_username:flags.7?true has_scheduled:flags.8?true translations_disabled:flags.19?true id:long about:string participants:ChatParticipants chat_photo:flags.2?Photo notify_settings:PeerNotifySettings exported_invite:flags.13?ExportedChatInvite bot_info:flags.3?Vector pinned_msg_id:flags.6?int folder_id:flags.11?int call:flags.12?InputGroupCall ttl_period:flags.14?int groupcall_default_join_as:flags.15?Peer theme_emoticon:flags.16?string requests_pending:flags.17?int recent_requesters:flags.17?Vector available_reactions:flags.18?ChatReactions = ChatFull;\nchannelFull#f2355507 flags:# can_view_participants:flags.3?true can_set_username:flags.6?true can_set_stickers:flags.7?true hidden_prehistory:flags.10?true can_set_location:flags.16?true has_scheduled:flags.19?true can_view_stats:flags.20?true blocked:flags.22?true flags2:# can_delete_channel:flags2.0?true antispam:flags2.1?true participants_hidden:flags2.2?true translations_disabled:flags2.3?true id:long about:string participants_count:flags.0?int admins_count:flags.1?int kicked_count:flags.2?int banned_count:flags.2?int online_count:flags.13?int read_inbox_max_id:int read_outbox_max_id:int unread_count:int chat_photo:Photo notify_settings:PeerNotifySettings exported_invite:flags.23?ExportedChatInvite bot_info:Vector migrated_from_chat_id:flags.4?long migrated_from_max_id:flags.4?int pinned_msg_id:flags.5?int stickerset:flags.8?StickerSet available_min_id:flags.9?int folder_id:flags.11?int linked_chat_id:flags.14?long location:flags.15?ChannelLocation slowmode_seconds:flags.17?int slowmode_next_send_date:flags.18?int stats_dc:flags.12?int pts:int call:flags.21?InputGroupCall ttl_period:flags.24?int pending_suggestions:flags.25?Vector groupcall_default_join_as:flags.26?Peer theme_emoticon:flags.27?string requests_pending:flags.28?int recent_requesters:flags.28?Vector default_send_as:flags.29?Peer available_reactions:flags.30?ChatReactions = ChatFull;\nchatParticipant#c02d4007 user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantCreator#e46bcee4 user_id:long = ChatParticipant;\nchatParticipantAdmin#a0933f5b user_id:long inviter_id:long date:int = ChatParticipant;\nchatParticipantsForbidden#8763d3e1 flags:# chat_id:long self_participant:flags.0?ChatParticipant = ChatParticipants;\nchatParticipants#3cbc93f8 chat_id:long participants:Vector version:int = ChatParticipants;\nchatPhotoEmpty#37c1011c = ChatPhoto;\nchatPhoto#1c6e1c11 flags:# has_video:flags.0?true photo_id:long stripped_thumb:flags.1?bytes dc_id:int = ChatPhoto;\nmessageEmpty#90a6ca84 flags:# id:int peer_id:flags.0?Peer = Message;\nmessage#38116ee0 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true from_scheduled:flags.18?true legacy:flags.19?true edit_hide:flags.21?true pinned:flags.24?true noforwards:flags.26?true id:int from_id:flags.8?Peer peer_id:Peer fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader date:int message:string media:flags.9?MessageMedia reply_markup:flags.6?ReplyMarkup entities:flags.7?Vector views:flags.10?int forwards:flags.10?int replies:flags.23?MessageReplies edit_date:flags.15?int post_author:flags.16?string grouped_id:flags.17?long reactions:flags.20?MessageReactions restriction_reason:flags.22?Vector ttl_period:flags.25?int = Message;\nmessageService#2b085862 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true post:flags.14?true legacy:flags.19?true id:int from_id:flags.8?Peer peer_id:Peer reply_to:flags.3?MessageReplyHeader date:int action:MessageAction ttl_period:flags.25?int = Message;\nmessageMediaEmpty#3ded6320 = MessageMedia;\nmessageMediaPhoto#695150d7 flags:# spoiler:flags.3?true photo:flags.0?Photo ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaGeo#56e0d474 geo:GeoPoint = MessageMedia;\nmessageMediaContact#70322949 phone_number:string first_name:string last_name:string vcard:string user_id:long = MessageMedia;\nmessageMediaUnsupported#9f84f49e = MessageMedia;\nmessageMediaDocument#9cb070d7 flags:# nopremium:flags.3?true spoiler:flags.4?true document:flags.0?Document ttl_seconds:flags.2?int = MessageMedia;\nmessageMediaWebPage#a32dd600 webpage:WebPage = MessageMedia;\nmessageMediaVenue#2ec0533f geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string = MessageMedia;\nmessageMediaGame#fdb19008 game:Game = MessageMedia;\nmessageMediaInvoice#f6a548d3 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument receipt_msg_id:flags.2?int currency:string total_amount:long start_param:string extended_media:flags.4?MessageExtendedMedia = MessageMedia;\nmessageMediaGeoLive#b940c666 flags:# geo:GeoPoint heading:flags.0?int period:int proximity_notification_radius:flags.1?int = MessageMedia;\nmessageMediaPoll#4bd6e798 poll:Poll results:PollResults = MessageMedia;\nmessageMediaDice#3f7ee58b value:int emoticon:string = MessageMedia;\nmessageActionEmpty#b6aef7b0 = MessageAction;\nmessageActionChatCreate#bd47cbad title:string users:Vector = MessageAction;\nmessageActionChatEditTitle#b5a1ce5a title:string = MessageAction;\nmessageActionChatEditPhoto#7fcb13a8 photo:Photo = MessageAction;\nmessageActionChatDeletePhoto#95e3fbef = MessageAction;\nmessageActionChatAddUser#15cefd00 users:Vector = MessageAction;\nmessageActionChatDeleteUser#a43f30cc user_id:long = MessageAction;\nmessageActionChatJoinedByLink#31224c3 inviter_id:long = MessageAction;\nmessageActionChannelCreate#95d2ac92 title:string = MessageAction;\nmessageActionChatMigrateTo#e1037f92 channel_id:long = MessageAction;\nmessageActionChannelMigrateFrom#ea3948e9 title:string chat_id:long = MessageAction;\nmessageActionPinMessage#94bd38ed = MessageAction;\nmessageActionHistoryClear#9fbab604 = MessageAction;\nmessageActionGameScore#92a72876 game_id:long score:int = MessageAction;\nmessageActionPaymentSentMe#8f31b327 flags:# recurring_init:flags.2?true recurring_used:flags.3?true currency:string total_amount:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string charge:PaymentCharge = MessageAction;\nmessageActionPaymentSent#96163f56 flags:# recurring_init:flags.2?true recurring_used:flags.3?true currency:string total_amount:long invoice_slug:flags.0?string = MessageAction;\nmessageActionPhoneCall#80e11a7f flags:# video:flags.2?true call_id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = MessageAction;\nmessageActionScreenshotTaken#4792929b = MessageAction;\nmessageActionCustomAction#fae69f56 message:string = MessageAction;\nmessageActionBotAllowed#c516d679 flags:# attach_menu:flags.1?true domain:flags.0?string app:flags.2?BotApp = MessageAction;\nmessageActionSecureValuesSentMe#1b287353 values:Vector credentials:SecureCredentialsEncrypted = MessageAction;\nmessageActionSecureValuesSent#d95c6154 types:Vector = MessageAction;\nmessageActionContactSignUp#f3f25f76 = MessageAction;\nmessageActionGeoProximityReached#98e0d697 from_id:Peer to_id:Peer distance:int = MessageAction;\nmessageActionGroupCall#7a0d7f42 flags:# call:InputGroupCall duration:flags.0?int = MessageAction;\nmessageActionInviteToGroupCall#502f92f7 call:InputGroupCall users:Vector = MessageAction;\nmessageActionSetMessagesTTL#3c134d7b flags:# period:int auto_setting_from:flags.0?long = MessageAction;\nmessageActionGroupCallScheduled#b3a07661 call:InputGroupCall schedule_date:int = MessageAction;\nmessageActionSetChatTheme#aa786345 emoticon:string = MessageAction;\nmessageActionChatJoinedByRequest#ebbca3cb = MessageAction;\nmessageActionWebViewDataSentMe#47dd8079 text:string data:string = MessageAction;\nmessageActionWebViewDataSent#b4c38cb5 text:string = MessageAction;\nmessageActionGiftPremium#c83d6aec flags:# currency:string amount:long months:int crypto_currency:flags.0?string crypto_amount:flags.0?long = MessageAction;\nmessageActionTopicCreate#d999256 flags:# title:string icon_color:int icon_emoji_id:flags.0?long = MessageAction;\nmessageActionTopicEdit#c0944820 flags:# title:flags.0?string icon_emoji_id:flags.1?long closed:flags.2?Bool hidden:flags.3?Bool = MessageAction;\nmessageActionSuggestProfilePhoto#57de635e photo:Photo = MessageAction;\nmessageActionRequestedPeer#fe77345d button_id:int peer:Peer = MessageAction;\nmessageActionSetChatWallPaper#bc44a927 wallpaper:WallPaper = MessageAction;\nmessageActionSetSameChatWallPaper#c0787d6d wallpaper:WallPaper = MessageAction;\ndialog#d58a08c6 flags:# pinned:flags.2?true unread_mark:flags.3?true peer:Peer top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int notify_settings:PeerNotifySettings pts:flags.0?int draft:flags.1?DraftMessage folder_id:flags.4?int ttl_period:flags.5?int = Dialog;\ndialogFolder#71bd134c flags:# pinned:flags.2?true folder:Folder peer:Peer top_message:int unread_muted_peers_count:int unread_unmuted_peers_count:int unread_muted_messages_count:int unread_unmuted_messages_count:int = Dialog;\nphotoEmpty#2331b22d id:long = Photo;\nphoto#fb197a65 flags:# has_stickers:flags.0?true id:long access_hash:long file_reference:bytes date:int sizes:Vector video_sizes:flags.1?Vector dc_id:int = Photo;\nphotoSizeEmpty#e17e23c type:string = PhotoSize;\nphotoSize#75c78e60 type:string w:int h:int size:int = PhotoSize;\nphotoCachedSize#21e1ad6 type:string w:int h:int bytes:bytes = PhotoSize;\nphotoStrippedSize#e0b0bc2e type:string bytes:bytes = PhotoSize;\nphotoSizeProgressive#fa3efb95 type:string w:int h:int sizes:Vector = PhotoSize;\nphotoPathSize#d8214d41 type:string bytes:bytes = PhotoSize;\ngeoPointEmpty#1117dd5f = GeoPoint;\ngeoPoint#b2a2f663 flags:# long:double lat:double access_hash:long accuracy_radius:flags.0?int = GeoPoint;\nauth.sentCode#5e002502 flags:# type:auth.SentCodeType phone_code_hash:string next_type:flags.1?auth.CodeType timeout:flags.2?int = auth.SentCode;\nauth.sentCodeSuccess#2390fe44 authorization:auth.Authorization = auth.SentCode;\nauth.authorization#2ea2c0d4 flags:# setup_password_required:flags.1?true otherwise_relogin_days:flags.1?int tmp_sessions:flags.0?int future_auth_token:flags.2?bytes user:User = auth.Authorization;\nauth.authorizationSignUpRequired#44747e9a flags:# terms_of_service:flags.0?help.TermsOfService = auth.Authorization;\nauth.exportedAuthorization#b434e2b8 id:long bytes:bytes = auth.ExportedAuthorization;\ninputNotifyPeer#b8bc5b0c peer:InputPeer = InputNotifyPeer;\ninputNotifyUsers#193b4417 = InputNotifyPeer;\ninputNotifyChats#4a95e84e = InputNotifyPeer;\ninputNotifyBroadcasts#b1db7c7e = InputNotifyPeer;\ninputNotifyForumTopic#5c467992 peer:InputPeer top_msg_id:int = InputNotifyPeer;\ninputPeerNotifySettings#df1f002b flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int sound:flags.3?NotificationSound = InputPeerNotifySettings;\npeerNotifySettings#a83b0426 flags:# show_previews:flags.0?Bool silent:flags.1?Bool mute_until:flags.2?int ios_sound:flags.3?NotificationSound android_sound:flags.4?NotificationSound other_sound:flags.5?NotificationSound = PeerNotifySettings;\npeerSettings#a518110d flags:# report_spam:flags.0?true add_contact:flags.1?true block_contact:flags.2?true share_contact:flags.3?true need_contacts_exception:flags.4?true report_geo:flags.5?true autoarchived:flags.7?true invite_members:flags.8?true request_chat_broadcast:flags.10?true geo_distance:flags.6?int request_chat_title:flags.9?string request_chat_date:flags.9?int = PeerSettings;\nwallPaper#a437c3ed id:long flags:# creator:flags.0?true default:flags.1?true pattern:flags.3?true dark:flags.4?true access_hash:long slug:string document:Document settings:flags.2?WallPaperSettings = WallPaper;\nwallPaperNoFile#e0804116 id:long flags:# default:flags.1?true dark:flags.4?true settings:flags.2?WallPaperSettings = WallPaper;\ninputReportReasonSpam#58dbcab8 = ReportReason;\ninputReportReasonViolence#1e22c78d = ReportReason;\ninputReportReasonPornography#2e59d922 = ReportReason;\ninputReportReasonChildAbuse#adf44ee3 = ReportReason;\ninputReportReasonOther#c1e4a2b1 = ReportReason;\ninputReportReasonCopyright#9b89f93a = ReportReason;\ninputReportReasonGeoIrrelevant#dbd4feed = ReportReason;\ninputReportReasonFake#f5ddd6e7 = ReportReason;\ninputReportReasonIllegalDrugs#a8eb2be = ReportReason;\ninputReportReasonPersonalDetails#9ec7863d = ReportReason;\nuserFull#93eadb53 flags:# blocked:flags.0?true phone_calls_available:flags.4?true phone_calls_private:flags.5?true can_pin_message:flags.7?true has_scheduled:flags.12?true video_calls_available:flags.13?true voice_messages_forbidden:flags.20?true translations_disabled:flags.23?true id:long about:flags.1?string settings:PeerSettings personal_photo:flags.21?Photo profile_photo:flags.2?Photo fallback_photo:flags.22?Photo notify_settings:PeerNotifySettings bot_info:flags.3?BotInfo pinned_msg_id:flags.6?int common_chats_count:int folder_id:flags.11?int ttl_period:flags.14?int theme_emoticon:flags.15?string private_forward_name:flags.16?string bot_group_admin_rights:flags.17?ChatAdminRights bot_broadcast_admin_rights:flags.18?ChatAdminRights premium_gifts:flags.19?Vector wallpaper:flags.24?WallPaper = UserFull;\ncontact#145ade0b user_id:long mutual:Bool = Contact;\nimportedContact#c13e3c50 user_id:long client_id:long = ImportedContact;\ncontactStatus#16d9703b user_id:long status:UserStatus = ContactStatus;\ncontacts.contactsNotModified#b74ba9d2 = contacts.Contacts;\ncontacts.contacts#eae87e42 contacts:Vector saved_count:int users:Vector = contacts.Contacts;\ncontacts.importedContacts#77d01c3b imported:Vector popular_invites:Vector retry_contacts:Vector users:Vector = contacts.ImportedContacts;\ncontacts.blocked#ade1591 blocked:Vector chats:Vector users:Vector = contacts.Blocked;\ncontacts.blockedSlice#e1664194 count:int blocked:Vector chats:Vector users:Vector = contacts.Blocked;\nmessages.dialogs#15ba6c40 dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsSlice#71e094f3 count:int dialogs:Vector messages:Vector chats:Vector users:Vector = messages.Dialogs;\nmessages.dialogsNotModified#f0e3e596 count:int = messages.Dialogs;\nmessages.messages#8c718e87 messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesSlice#3a54685e flags:# inexact:flags.1?true count:int next_rate:flags.0?int offset_id_offset:flags.2?int messages:Vector chats:Vector users:Vector = messages.Messages;\nmessages.channelMessages#c776ba4e flags:# inexact:flags.1?true pts:int count:int offset_id_offset:flags.2?int messages:Vector topics:Vector chats:Vector users:Vector = messages.Messages;\nmessages.messagesNotModified#74535f21 count:int = messages.Messages;\nmessages.chats#64ff9fd5 chats:Vector = messages.Chats;\nmessages.chatsSlice#9cd81144 count:int chats:Vector = messages.Chats;\nmessages.chatFull#e5d7d19c full_chat:ChatFull chats:Vector users:Vector = messages.ChatFull;\nmessages.affectedHistory#b45c69d1 pts:int pts_count:int offset:int = messages.AffectedHistory;\ninputMessagesFilterEmpty#57e2f66c = MessagesFilter;\ninputMessagesFilterPhotos#9609a51c = MessagesFilter;\ninputMessagesFilterVideo#9fc00e65 = MessagesFilter;\ninputMessagesFilterPhotoVideo#56e9f0e4 = MessagesFilter;\ninputMessagesFilterDocument#9eddf188 = MessagesFilter;\ninputMessagesFilterUrl#7ef0dd87 = MessagesFilter;\ninputMessagesFilterGif#ffc86587 = MessagesFilter;\ninputMessagesFilterVoice#50f5c392 = MessagesFilter;\ninputMessagesFilterMusic#3751b49e = MessagesFilter;\ninputMessagesFilterChatPhotos#3a20ecb8 = MessagesFilter;\ninputMessagesFilterPhoneCalls#80c99768 flags:# missed:flags.0?true = MessagesFilter;\ninputMessagesFilterRoundVoice#7a7c17a4 = MessagesFilter;\ninputMessagesFilterRoundVideo#b549da53 = MessagesFilter;\ninputMessagesFilterMyMentions#c1f8e69a = MessagesFilter;\ninputMessagesFilterGeo#e7026d0d = MessagesFilter;\ninputMessagesFilterContacts#e062db83 = MessagesFilter;\ninputMessagesFilterPinned#1bb00451 = MessagesFilter;\nupdateNewMessage#1f2b0afd message:Message pts:int pts_count:int = Update;\nupdateMessageID#4e90bfd6 id:int random_id:long = Update;\nupdateDeleteMessages#a20db0e5 messages:Vector pts:int pts_count:int = Update;\nupdateUserTyping#c01e857f user_id:long action:SendMessageAction = Update;\nupdateChatUserTyping#83487af0 chat_id:long from_id:Peer action:SendMessageAction = Update;\nupdateChatParticipants#7761198 participants:ChatParticipants = Update;\nupdateUserStatus#e5bdf8de user_id:long status:UserStatus = Update;\nupdateUserName#a7848924 user_id:long first_name:string last_name:string usernames:Vector = Update;\nupdateNewEncryptedMessage#12bcbd9a message:EncryptedMessage qts:int = Update;\nupdateEncryptedChatTyping#1710f156 chat_id:int = Update;\nupdateEncryption#b4a2e88d chat:EncryptedChat date:int = Update;\nupdateEncryptedMessagesRead#38fe25b7 chat_id:int max_date:int date:int = Update;\nupdateChatParticipantAdd#3dda5451 chat_id:long user_id:long inviter_id:long date:int version:int = Update;\nupdateChatParticipantDelete#e32f3d77 chat_id:long user_id:long version:int = Update;\nupdateDcOptions#8e5e9873 dc_options:Vector = Update;\nupdateNotifySettings#bec268ef peer:NotifyPeer notify_settings:PeerNotifySettings = Update;\nupdateServiceNotification#ebe46819 flags:# popup:flags.0?true inbox_date:flags.1?int type:string message:string media:MessageMedia entities:Vector = Update;\nupdatePrivacy#ee3b272a key:PrivacyKey rules:Vector = Update;\nupdateUserPhone#5492a13 user_id:long phone:string = Update;\nupdateReadHistoryInbox#9c974fdf flags:# folder_id:flags.0?int peer:Peer max_id:int still_unread_count:int pts:int pts_count:int = Update;\nupdateReadHistoryOutbox#2f2f21bf peer:Peer max_id:int pts:int pts_count:int = Update;\nupdateWebPage#7f891213 webpage:WebPage pts:int pts_count:int = Update;\nupdateReadMessagesContents#68c13933 messages:Vector pts:int pts_count:int = Update;\nupdateChannelTooLong#108d941f flags:# channel_id:long pts:flags.0?int = Update;\nupdateChannel#635b4c09 channel_id:long = Update;\nupdateNewChannelMessage#62ba04d9 message:Message pts:int pts_count:int = Update;\nupdateReadChannelInbox#922e6e10 flags:# folder_id:flags.0?int channel_id:long max_id:int still_unread_count:int pts:int = Update;\nupdateDeleteChannelMessages#c32d5b12 channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChannelMessageViews#f226ac08 channel_id:long id:int views:int = Update;\nupdateChatParticipantAdmin#d7ca61a2 chat_id:long user_id:long is_admin:Bool version:int = Update;\nupdateNewStickerSet#688a30aa stickerset:messages.StickerSet = Update;\nupdateStickerSetsOrder#bb2d201 flags:# masks:flags.0?true emojis:flags.1?true order:Vector = Update;\nupdateStickerSets#31c24808 flags:# masks:flags.0?true emojis:flags.1?true = Update;\nupdateSavedGifs#9375341e = Update;\nupdateBotInlineQuery#496f379c flags:# query_id:long user_id:long query:string geo:flags.0?GeoPoint peer_type:flags.1?InlineQueryPeerType offset:string = Update;\nupdateBotInlineSend#12f12a07 flags:# user_id:long query:string geo:flags.0?GeoPoint id:string msg_id:flags.1?InputBotInlineMessageID = Update;\nupdateEditChannelMessage#1b3f4df7 message:Message pts:int pts_count:int = Update;\nupdateBotCallbackQuery#b9cfc48d flags:# query_id:long user_id:long peer:Peer msg_id:int chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateEditMessage#e40370a3 message:Message pts:int pts_count:int = Update;\nupdateInlineBotCallbackQuery#691e9052 flags:# query_id:long user_id:long msg_id:InputBotInlineMessageID chat_instance:long data:flags.0?bytes game_short_name:flags.1?string = Update;\nupdateReadChannelOutbox#b75f99a9 channel_id:long max_id:int = Update;\nupdateDraftMessage#1b49ec6d flags:# peer:Peer top_msg_id:flags.0?int draft:DraftMessage = Update;\nupdateReadFeaturedStickers#571d2742 = Update;\nupdateRecentStickers#9a422c20 = Update;\nupdateConfig#a229dd06 = Update;\nupdatePtsChanged#3354678f = Update;\nupdateChannelWebPage#2f2ba99f channel_id:long webpage:WebPage pts:int pts_count:int = Update;\nupdateDialogPinned#6e6fe51c flags:# pinned:flags.0?true folder_id:flags.1?int peer:DialogPeer = Update;\nupdatePinnedDialogs#fa0f3ca2 flags:# folder_id:flags.1?int order:flags.0?Vector = Update;\nupdateBotWebhookJSON#8317c0c3 data:DataJSON = Update;\nupdateBotWebhookJSONQuery#9b9240a6 query_id:long data:DataJSON timeout:int = Update;\nupdateBotShippingQuery#b5aefd7d query_id:long user_id:long payload:bytes shipping_address:PostAddress = Update;\nupdateBotPrecheckoutQuery#8caa9a96 flags:# query_id:long user_id:long payload:bytes info:flags.0?PaymentRequestedInfo shipping_option_id:flags.1?string currency:string total_amount:long = Update;\nupdatePhoneCall#ab0f6b1e phone_call:PhoneCall = Update;\nupdateLangPackTooLong#46560264 lang_code:string = Update;\nupdateLangPack#56022f4d difference:LangPackDifference = Update;\nupdateFavedStickers#e511996d = Update;\nupdateChannelReadMessagesContents#ea29055d flags:# channel_id:long top_msg_id:flags.0?int messages:Vector = Update;\nupdateContactsReset#7084a7be = Update;\nupdateChannelAvailableMessages#b23fc698 channel_id:long available_min_id:int = Update;\nupdateDialogUnreadMark#e16459c3 flags:# unread:flags.0?true peer:DialogPeer = Update;\nupdateMessagePoll#aca1657b flags:# poll_id:long poll:flags.0?Poll results:PollResults = Update;\nupdateChatDefaultBannedRights#54c01850 peer:Peer default_banned_rights:ChatBannedRights version:int = Update;\nupdateFolderPeers#19360dc0 folder_peers:Vector pts:int pts_count:int = Update;\nupdatePeerSettings#6a7e7366 peer:Peer settings:PeerSettings = Update;\nupdatePeerLocated#b4afcfb0 peers:Vector = Update;\nupdateNewScheduledMessage#39a51dfb message:Message = Update;\nupdateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update;\nupdateTheme#8216fba3 theme:Theme = Update;\nupdateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update;\nupdateLoginToken#564fe691 = Update;\nupdateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update;\nupdateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update;\nupdateDialogFilterOrder#a5d72105 order:Vector = Update;\nupdateDialogFilters#3504914f = Update;\nupdatePhoneCallSignalingData#2661bf09 phone_call_id:long data:bytes = Update;\nupdateChannelMessageForwards#d29a27f4 channel_id:long id:int forwards:int = Update;\nupdateReadChannelDiscussionInbox#d6b19546 flags:# channel_id:long top_msg_id:int read_max_id:int broadcast_id:flags.0?long broadcast_post:flags.0?int = Update;\nupdateReadChannelDiscussionOutbox#695c9e7c channel_id:long top_msg_id:int read_max_id:int = Update;\nupdatePeerBlocked#246a4b22 peer_id:Peer blocked:Bool = Update;\nupdateChannelUserTyping#8c88c923 flags:# channel_id:long top_msg_id:flags.0?int from_id:Peer action:SendMessageAction = Update;\nupdatePinnedMessages#ed85eab5 flags:# pinned:flags.0?true peer:Peer messages:Vector pts:int pts_count:int = Update;\nupdatePinnedChannelMessages#5bb98608 flags:# pinned:flags.0?true channel_id:long messages:Vector pts:int pts_count:int = Update;\nupdateChat#f89a6a4e chat_id:long = Update;\nupdateGroupCallParticipants#f2ebdb4e call:InputGroupCall participants:Vector version:int = Update;\nupdateGroupCall#14b24500 chat_id:long call:GroupCall = Update;\nupdatePeerHistoryTTL#bb9bb9a5 flags:# peer:Peer ttl_period:flags.0?int = Update;\nupdateChatParticipant#d087663a flags:# chat_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChatParticipant new_participant:flags.1?ChatParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateChannelParticipant#985d3abb flags:# via_chatlist:flags.3?true channel_id:long date:int actor_id:long user_id:long prev_participant:flags.0?ChannelParticipant new_participant:flags.1?ChannelParticipant invite:flags.2?ExportedChatInvite qts:int = Update;\nupdateBotStopped#c4870a49 user_id:long date:int stopped:Bool qts:int = Update;\nupdateGroupCallConnection#b783982 flags:# presentation:flags.0?true params:DataJSON = Update;\nupdateBotCommands#4d712f2e peer:Peer bot_id:long commands:Vector = Update;\nupdatePendingJoinRequests#7063c3db peer:Peer requests_pending:int recent_requesters:Vector = Update;\nupdateBotChatInviteRequester#11dfa986 peer:Peer date:int user_id:long about:string invite:ExportedChatInvite qts:int = Update;\nupdateMessageReactions#5e1b3cb8 flags:# peer:Peer msg_id:int top_msg_id:flags.0?int reactions:MessageReactions = Update;\nupdateAttachMenuBots#17b7a20b = Update;\nupdateWebViewResultSent#1592b79d query_id:long = Update;\nupdateBotMenuButton#14b85813 bot_id:long button:BotMenuButton = Update;\nupdateSavedRingtones#74d8be99 = Update;\nupdateTranscribedAudio#84cd5a flags:# pending:flags.0?true peer:Peer msg_id:int transcription_id:long text:string = Update;\nupdateReadFeaturedEmojiStickers#fb4c496c = Update;\nupdateUserEmojiStatus#28373599 user_id:long emoji_status:EmojiStatus = Update;\nupdateRecentEmojiStatuses#30f443db = Update;\nupdateRecentReactions#6f7863f4 = Update;\nupdateMoveStickerSetToTop#86fccf85 flags:# masks:flags.0?true emojis:flags.1?true stickerset:long = Update;\nupdateMessageExtendedMedia#5a73a98c peer:Peer msg_id:int extended_media:MessageExtendedMedia = Update;\nupdateChannelPinnedTopic#192efbe3 flags:# pinned:flags.0?true channel_id:long topic_id:int = Update;\nupdateChannelPinnedTopics#fe198602 flags:# channel_id:long order:flags.0?Vector = Update;\nupdateUser#20529438 user_id:long = Update;\nupdateAutoSaveSettings#ec05b097 = Update;\nupdateGroupInvitePrivacyForbidden#ccf08ad6 user_id:long = Update;\nupdates.state#a56c2a3e pts:int qts:int date:int seq:int unread_count:int = updates.State;\nupdates.differenceEmpty#5d75a138 date:int seq:int = updates.Difference;\nupdates.difference#f49ca0 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector state:updates.State = updates.Difference;\nupdates.differenceSlice#a8fb1981 new_messages:Vector new_encrypted_messages:Vector other_updates:Vector chats:Vector users:Vector intermediate_state:updates.State = updates.Difference;\nupdates.differenceTooLong#4afe8f6d pts:int = updates.Difference;\nupdatesTooLong#e317af7e = Updates;\nupdateShortMessage#313bc7f8 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int user_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShortChatMessage#4d6deea5 flags:# out:flags.1?true mentioned:flags.4?true media_unread:flags.5?true silent:flags.13?true id:int from_id:long chat_id:long message:string pts:int pts_count:int date:int fwd_from:flags.2?MessageFwdHeader via_bot_id:flags.11?long reply_to:flags.3?MessageReplyHeader entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nupdateShort#78d4dec1 update:Update date:int = Updates;\nupdatesCombined#725b04c3 updates:Vector users:Vector chats:Vector date:int seq_start:int seq:int = Updates;\nupdates#74ae4240 updates:Vector users:Vector chats:Vector date:int seq:int = Updates;\nupdateShortSentMessage#9015e101 flags:# out:flags.1?true id:int pts:int pts_count:int date:int media:flags.9?MessageMedia entities:flags.7?Vector ttl_period:flags.25?int = Updates;\nphotos.photos#8dca6aa5 photos:Vector users:Vector = photos.Photos;\nphotos.photosSlice#15051f54 count:int photos:Vector users:Vector = photos.Photos;\nphotos.photo#20212ca8 photo:Photo users:Vector = photos.Photo;\nupload.file#96a18d5 type:storage.FileType mtime:int bytes:bytes = upload.File;\nupload.fileCdnRedirect#f18cda44 dc_id:int file_token:bytes encryption_key:bytes encryption_iv:bytes file_hashes:Vector = upload.File;\ndcOption#18b7a10d flags:# ipv6:flags.0?true media_only:flags.1?true tcpo_only:flags.2?true cdn:flags.3?true static:flags.4?true this_port_only:flags.5?true id:int ip_address:string port:int secret:flags.10?bytes = DcOption;\nconfig#cc1a241e flags:# default_p2p_contacts:flags.3?true preload_featured_stickers:flags.4?true revoke_pm_inbox:flags.6?true blocked_mode:flags.8?true force_try_ipv6:flags.14?true date:int expires:int test_mode:Bool this_dc:int dc_options:Vector dc_txt_domain_name:string chat_size_max:int megagroup_size_max:int forwarded_count_max:int online_update_period_ms:int offline_blur_timeout_ms:int offline_idle_timeout_ms:int online_cloud_timeout_ms:int notify_cloud_delay_ms:int notify_default_delay_ms:int push_chat_period_ms:int push_chat_limit:int edit_time_limit:int revoke_time_limit:int revoke_pm_time_limit:int rating_e_decay:int stickers_recent_limit:int channels_read_media_period:int tmp_sessions:flags.0?int call_receive_timeout_ms:int call_ring_timeout_ms:int call_connect_timeout_ms:int call_packet_timeout_ms:int me_url_prefix:string autoupdate_url_prefix:flags.7?string gif_search_username:flags.9?string venue_search_username:flags.10?string img_search_username:flags.11?string static_maps_provider:flags.12?string caption_length_max:int message_length_max:int webfile_dc_id:int suggested_lang_code:flags.2?string lang_pack_version:flags.2?int base_lang_pack_version:flags.2?int reactions_default:flags.15?Reaction autologin_token:flags.16?string = Config;\nnearestDc#8e1a1775 country:string this_dc:int nearest_dc:int = NearestDc;\nhelp.appUpdate#ccbbce30 flags:# can_not_skip:flags.0?true id:int version:string text:string entities:Vector document:flags.1?Document url:flags.2?string sticker:flags.3?Document = help.AppUpdate;\nhelp.noAppUpdate#c45a6536 = help.AppUpdate;\nhelp.inviteText#18cb9f78 message:string = help.InviteText;\nencryptedChatEmpty#ab7ec0a0 id:int = EncryptedChat;\nencryptedChatWaiting#66b25953 id:int access_hash:long date:int admin_id:long participant_id:long = EncryptedChat;\nencryptedChatRequested#48f1d94c flags:# folder_id:flags.0?int id:int access_hash:long date:int admin_id:long participant_id:long g_a:bytes = EncryptedChat;\nencryptedChat#61f0d4c7 id:int access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long = EncryptedChat;\nencryptedChatDiscarded#1e1c7c45 flags:# history_deleted:flags.0?true id:int = EncryptedChat;\ninputEncryptedChat#f141b5e1 chat_id:int access_hash:long = InputEncryptedChat;\nencryptedFileEmpty#c21f497e = EncryptedFile;\nencryptedFile#a8008cd8 id:long access_hash:long size:long dc_id:int key_fingerprint:int = EncryptedFile;\ninputEncryptedFileEmpty#1837c364 = InputEncryptedFile;\ninputEncryptedFileUploaded#64bd0306 id:long parts:int md5_checksum:string key_fingerprint:int = InputEncryptedFile;\ninputEncryptedFile#5a17b5e5 id:long access_hash:long = InputEncryptedFile;\ninputEncryptedFileBigUploaded#2dc173c8 id:long parts:int key_fingerprint:int = InputEncryptedFile;\nencryptedMessage#ed18c118 random_id:long chat_id:int date:int bytes:bytes file:EncryptedFile = EncryptedMessage;\nencryptedMessageService#23734b06 random_id:long chat_id:int date:int bytes:bytes = EncryptedMessage;\nmessages.dhConfigNotModified#c0e24635 random:bytes = messages.DhConfig;\nmessages.dhConfig#2c221edd g:int p:bytes version:int random:bytes = messages.DhConfig;\nmessages.sentEncryptedMessage#560f8935 date:int = messages.SentEncryptedMessage;\nmessages.sentEncryptedFile#9493ff32 date:int file:EncryptedFile = messages.SentEncryptedMessage;\ninputDocumentEmpty#72f0eaae = InputDocument;\ninputDocument#1abfb575 id:long access_hash:long file_reference:bytes = InputDocument;\ndocumentEmpty#36f8c871 id:long = Document;\ndocument#8fd4c4d8 flags:# id:long access_hash:long file_reference:bytes date:int mime_type:string size:long thumbs:flags.0?Vector video_thumbs:flags.1?Vector dc_id:int attributes:Vector = Document;\nhelp.support#17c6b5f6 phone_number:string user:User = help.Support;\nnotifyPeer#9fd40bd8 peer:Peer = NotifyPeer;\nnotifyUsers#b4c83b4c = NotifyPeer;\nnotifyChats#c007cec3 = NotifyPeer;\nnotifyBroadcasts#d612e8ef = NotifyPeer;\nnotifyForumTopic#226e6308 peer:Peer top_msg_id:int = NotifyPeer;\nsendMessageTypingAction#16bf744e = SendMessageAction;\nsendMessageCancelAction#fd5ec8f5 = SendMessageAction;\nsendMessageRecordVideoAction#a187d66f = SendMessageAction;\nsendMessageUploadVideoAction#e9763aec progress:int = SendMessageAction;\nsendMessageRecordAudioAction#d52f73f7 = SendMessageAction;\nsendMessageUploadAudioAction#f351d7ab progress:int = SendMessageAction;\nsendMessageUploadPhotoAction#d1d34a26 progress:int = SendMessageAction;\nsendMessageUploadDocumentAction#aa0cd9e4 progress:int = SendMessageAction;\nsendMessageGeoLocationAction#176f8ba1 = SendMessageAction;\nsendMessageChooseContactAction#628cbc6f = SendMessageAction;\nsendMessageGamePlayAction#dd6a8f48 = SendMessageAction;\nsendMessageRecordRoundAction#88f27fbc = SendMessageAction;\nsendMessageUploadRoundAction#243e1c66 progress:int = SendMessageAction;\nspeakingInGroupCallAction#d92c2285 = SendMessageAction;\nsendMessageHistoryImportAction#dbda9246 progress:int = SendMessageAction;\nsendMessageChooseStickerAction#b05ac6b1 = SendMessageAction;\nsendMessageEmojiInteraction#25972bcb emoticon:string msg_id:int interaction:DataJSON = SendMessageAction;\nsendMessageEmojiInteractionSeen#b665902e emoticon:string = SendMessageAction;\ncontacts.found#b3134d9d my_results:Vector results:Vector chats:Vector users:Vector = contacts.Found;\ninputPrivacyKeyStatusTimestamp#4f96cb18 = InputPrivacyKey;\ninputPrivacyKeyChatInvite#bdfb0426 = InputPrivacyKey;\ninputPrivacyKeyPhoneCall#fabadc5f = InputPrivacyKey;\ninputPrivacyKeyPhoneP2P#db9e70d2 = InputPrivacyKey;\ninputPrivacyKeyForwards#a4dd4c08 = InputPrivacyKey;\ninputPrivacyKeyProfilePhoto#5719bacc = InputPrivacyKey;\ninputPrivacyKeyPhoneNumber#352dafa = InputPrivacyKey;\ninputPrivacyKeyAddedByPhone#d1219bdd = InputPrivacyKey;\ninputPrivacyKeyVoiceMessages#aee69d68 = InputPrivacyKey;\nprivacyKeyStatusTimestamp#bc2eab30 = PrivacyKey;\nprivacyKeyChatInvite#500e6dfa = PrivacyKey;\nprivacyKeyPhoneCall#3d662b7b = PrivacyKey;\nprivacyKeyPhoneP2P#39491cc8 = PrivacyKey;\nprivacyKeyForwards#69ec56a3 = PrivacyKey;\nprivacyKeyProfilePhoto#96151fed = PrivacyKey;\nprivacyKeyPhoneNumber#d19ae46d = PrivacyKey;\nprivacyKeyAddedByPhone#42ffd42b = PrivacyKey;\nprivacyKeyVoiceMessages#697f414 = PrivacyKey;\ninputPrivacyValueAllowContacts#d09e07b = InputPrivacyRule;\ninputPrivacyValueAllowAll#184b35ce = InputPrivacyRule;\ninputPrivacyValueAllowUsers#131cc67f users:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowContacts#ba52007 = InputPrivacyRule;\ninputPrivacyValueDisallowAll#d66b66c9 = InputPrivacyRule;\ninputPrivacyValueDisallowUsers#90110467 users:Vector = InputPrivacyRule;\ninputPrivacyValueAllowChatParticipants#840649cf chats:Vector = InputPrivacyRule;\ninputPrivacyValueDisallowChatParticipants#e94f0f86 chats:Vector = InputPrivacyRule;\nprivacyValueAllowContacts#fffe1bac = PrivacyRule;\nprivacyValueAllowAll#65427b82 = PrivacyRule;\nprivacyValueAllowUsers#b8905fb2 users:Vector = PrivacyRule;\nprivacyValueDisallowContacts#f888fa1a = PrivacyRule;\nprivacyValueDisallowAll#8b73e763 = PrivacyRule;\nprivacyValueDisallowUsers#e4621141 users:Vector = PrivacyRule;\nprivacyValueAllowChatParticipants#6b134e8e chats:Vector = PrivacyRule;\nprivacyValueDisallowChatParticipants#41c87565 chats:Vector = PrivacyRule;\naccount.privacyRules#50a04e45 rules:Vector chats:Vector users:Vector = account.PrivacyRules;\naccountDaysTTL#b8d0afdf days:int = AccountDaysTTL;\ndocumentAttributeImageSize#6c37c15c w:int h:int = DocumentAttribute;\ndocumentAttributeAnimated#11b58939 = DocumentAttribute;\ndocumentAttributeSticker#6319d612 flags:# mask:flags.1?true alt:string stickerset:InputStickerSet mask_coords:flags.0?MaskCoords = DocumentAttribute;\ndocumentAttributeVideo#ef02ce6 flags:# round_message:flags.0?true supports_streaming:flags.1?true duration:int w:int h:int = DocumentAttribute;\ndocumentAttributeAudio#9852f9c6 flags:# voice:flags.10?true duration:int title:flags.0?string performer:flags.1?string waveform:flags.2?bytes = DocumentAttribute;\ndocumentAttributeFilename#15590068 file_name:string = DocumentAttribute;\ndocumentAttributeHasStickers#9801d2f7 = DocumentAttribute;\ndocumentAttributeCustomEmoji#fd149899 flags:# free:flags.0?true text_color:flags.1?true alt:string stickerset:InputStickerSet = DocumentAttribute;\nmessages.stickersNotModified#f1749a22 = messages.Stickers;\nmessages.stickers#30a6ec7e hash:long stickers:Vector = messages.Stickers;\nstickerPack#12b299d4 emoticon:string documents:Vector = StickerPack;\nmessages.allStickersNotModified#e86602c3 = messages.AllStickers;\nmessages.allStickers#cdbbcebb hash:long sets:Vector = messages.AllStickers;\nmessages.affectedMessages#84d19185 pts:int pts_count:int = messages.AffectedMessages;\nwebPageEmpty#eb1477e8 id:long = WebPage;\nwebPagePending#c586da1c id:long date:int = WebPage;\nwebPage#e89c45b2 flags:# id:long url:string display_url:string hash:int type:flags.0?string site_name:flags.1?string title:flags.2?string description:flags.3?string photo:flags.4?Photo embed_url:flags.5?string embed_type:flags.5?string embed_width:flags.6?int embed_height:flags.6?int duration:flags.7?int author:flags.8?string document:flags.9?Document cached_page:flags.10?Page attributes:flags.12?Vector = WebPage;\nwebPageNotModified#7311ca11 flags:# cached_page_views:flags.0?int = WebPage;\nauthorization#ad01d61d flags:# current:flags.0?true official_app:flags.1?true password_pending:flags.2?true encrypted_requests_disabled:flags.3?true call_requests_disabled:flags.4?true hash:long device_model:string platform:string system_version:string api_id:int app_name:string app_version:string date_created:int date_active:int ip:string country:string region:string = Authorization;\naccount.authorizations#4bff8ea0 authorization_ttl_days:int authorizations:Vector = account.Authorizations;\naccount.password#957b50fb flags:# has_recovery:flags.0?true has_secure_values:flags.1?true has_password:flags.2?true current_algo:flags.2?PasswordKdfAlgo srp_B:flags.2?bytes srp_id:flags.2?long hint:flags.3?string email_unconfirmed_pattern:flags.4?string new_algo:PasswordKdfAlgo new_secure_algo:SecurePasswordKdfAlgo secure_random:bytes pending_reset_date:flags.5?int login_email_pattern:flags.6?string = account.Password;\naccount.passwordSettings#9a5c33e5 flags:# email:flags.0?string secure_settings:flags.1?SecureSecretSettings = account.PasswordSettings;\naccount.passwordInputSettings#c23727c9 flags:# new_algo:flags.0?PasswordKdfAlgo new_password_hash:flags.0?bytes hint:flags.0?string email:flags.1?string new_secure_settings:flags.2?SecureSecretSettings = account.PasswordInputSettings;\nauth.passwordRecovery#137948a5 email_pattern:string = auth.PasswordRecovery;\nreceivedNotifyMessage#a384b779 id:int flags:int = ReceivedNotifyMessage;\nchatInviteExported#ab4a819 flags:# revoked:flags.0?true permanent:flags.5?true request_needed:flags.6?true link:string admin_id:long date:int start_date:flags.4?int expire_date:flags.1?int usage_limit:flags.2?int usage:flags.3?int requested:flags.7?int title:flags.8?string = ExportedChatInvite;\nchatInvitePublicJoinRequests#ed107ab7 = ExportedChatInvite;\nchatInviteAlready#5a686d7c chat:Chat = ChatInvite;\nchatInvite#300c44c1 flags:# channel:flags.0?true broadcast:flags.1?true public:flags.2?true megagroup:flags.3?true request_needed:flags.6?true title:string about:flags.5?string photo:Photo participants_count:int participants:flags.4?Vector = ChatInvite;\nchatInvitePeek#61695cb0 chat:Chat expires:int = ChatInvite;\ninputStickerSetEmpty#ffb62b95 = InputStickerSet;\ninputStickerSetID#9de7a269 id:long access_hash:long = InputStickerSet;\ninputStickerSetShortName#861cc8a0 short_name:string = InputStickerSet;\ninputStickerSetAnimatedEmoji#28703c8 = InputStickerSet;\ninputStickerSetDice#e67f520e emoticon:string = InputStickerSet;\ninputStickerSetAnimatedEmojiAnimations#cde3739 = InputStickerSet;\ninputStickerSetPremiumGifts#c88b3b02 = InputStickerSet;\ninputStickerSetEmojiGenericAnimations#4c4d4ce = InputStickerSet;\ninputStickerSetEmojiDefaultStatuses#29d0f5ee = InputStickerSet;\ninputStickerSetEmojiDefaultTopicIcons#44c1f8e9 = InputStickerSet;\nstickerSet#2dd14edc flags:# archived:flags.1?true official:flags.2?true masks:flags.3?true animated:flags.5?true videos:flags.6?true emojis:flags.7?true installed_date:flags.0?int id:long access_hash:long title:string short_name:string thumbs:flags.4?Vector thumb_dc_id:flags.4?int thumb_version:flags.4?int thumb_document_id:flags.8?long count:int hash:int = StickerSet;\nmessages.stickerSet#6e153f16 set:StickerSet packs:Vector keywords:Vector documents:Vector = messages.StickerSet;\nmessages.stickerSetNotModified#d3f924eb = messages.StickerSet;\nbotCommand#c27ac8c7 command:string description:string = BotCommand;\nbotInfo#8f300b57 flags:# user_id:flags.0?long description:flags.1?string description_photo:flags.4?Photo description_document:flags.5?Document commands:flags.2?Vector menu_button:flags.3?BotMenuButton = BotInfo;\nkeyboardButton#a2fa4880 text:string = KeyboardButton;\nkeyboardButtonUrl#258aff05 text:string url:string = KeyboardButton;\nkeyboardButtonCallback#35bbdb6b flags:# requires_password:flags.0?true text:string data:bytes = KeyboardButton;\nkeyboardButtonRequestPhone#b16a6c29 text:string = KeyboardButton;\nkeyboardButtonRequestGeoLocation#fc796b3f text:string = KeyboardButton;\nkeyboardButtonSwitchInline#93b9fbb5 flags:# same_peer:flags.0?true text:string query:string peer_types:flags.1?Vector = KeyboardButton;\nkeyboardButtonGame#50f41ccf text:string = KeyboardButton;\nkeyboardButtonBuy#afd93fbb text:string = KeyboardButton;\nkeyboardButtonUrlAuth#10b78d29 flags:# text:string fwd_text:flags.0?string url:string button_id:int = KeyboardButton;\ninputKeyboardButtonUrlAuth#d02e7fd4 flags:# request_write_access:flags.0?true text:string fwd_text:flags.1?string url:string bot:InputUser = KeyboardButton;\nkeyboardButtonRequestPoll#bbc7515d flags:# quiz:flags.0?Bool text:string = KeyboardButton;\ninputKeyboardButtonUserProfile#e988037b text:string user_id:InputUser = KeyboardButton;\nkeyboardButtonUserProfile#308660c1 text:string user_id:long = KeyboardButton;\nkeyboardButtonWebView#13767230 text:string url:string = KeyboardButton;\nkeyboardButtonSimpleWebView#a0c0505c text:string url:string = KeyboardButton;\nkeyboardButtonRequestPeer#d0b468c text:string button_id:int peer_type:RequestPeerType = KeyboardButton;\nkeyboardButtonRow#77608b83 buttons:Vector = KeyboardButtonRow;\nreplyKeyboardHide#a03e5b85 flags:# selective:flags.2?true = ReplyMarkup;\nreplyKeyboardForceReply#86b40b08 flags:# single_use:flags.1?true selective:flags.2?true placeholder:flags.3?string = ReplyMarkup;\nreplyKeyboardMarkup#85dd99d1 flags:# resize:flags.0?true single_use:flags.1?true selective:flags.2?true persistent:flags.4?true rows:Vector placeholder:flags.3?string = ReplyMarkup;\nreplyInlineMarkup#48a30254 rows:Vector = ReplyMarkup;\nmessageEntityUnknown#bb92ba95 offset:int length:int = MessageEntity;\nmessageEntityMention#fa04579d offset:int length:int = MessageEntity;\nmessageEntityHashtag#6f635b0d offset:int length:int = MessageEntity;\nmessageEntityBotCommand#6cef8ac7 offset:int length:int = MessageEntity;\nmessageEntityUrl#6ed02538 offset:int length:int = MessageEntity;\nmessageEntityEmail#64e475c2 offset:int length:int = MessageEntity;\nmessageEntityBold#bd610bc9 offset:int length:int = MessageEntity;\nmessageEntityItalic#826f8b60 offset:int length:int = MessageEntity;\nmessageEntityCode#28a20571 offset:int length:int = MessageEntity;\nmessageEntityPre#73924be0 offset:int length:int language:string = MessageEntity;\nmessageEntityTextUrl#76a6d327 offset:int length:int url:string = MessageEntity;\nmessageEntityMentionName#dc7b1140 offset:int length:int user_id:long = MessageEntity;\ninputMessageEntityMentionName#208e68c9 offset:int length:int user_id:InputUser = MessageEntity;\nmessageEntityPhone#9b69e34b offset:int length:int = MessageEntity;\nmessageEntityCashtag#4c4e743f offset:int length:int = MessageEntity;\nmessageEntityUnderline#9c4e7e8b offset:int length:int = MessageEntity;\nmessageEntityStrike#bf0693d4 offset:int length:int = MessageEntity;\nmessageEntityBlockquote#20df5d0 offset:int length:int = MessageEntity;\nmessageEntityBankCard#761e6af4 offset:int length:int = MessageEntity;\nmessageEntitySpoiler#32ca960f offset:int length:int = MessageEntity;\nmessageEntityCustomEmoji#c8cf05f8 offset:int length:int document_id:long = MessageEntity;\ninputChannelEmpty#ee8c1e86 = InputChannel;\ninputChannel#f35aec28 channel_id:long access_hash:long = InputChannel;\ninputChannelFromMessage#5b934f9d peer:InputPeer msg_id:int channel_id:long = InputChannel;\ncontacts.resolvedPeer#7f077ad9 peer:Peer chats:Vector users:Vector = contacts.ResolvedPeer;\nmessageRange#ae30253 min_id:int max_id:int = MessageRange;\nupdates.channelDifferenceEmpty#3e11affb flags:# final:flags.0?true pts:int timeout:flags.1?int = updates.ChannelDifference;\nupdates.channelDifferenceTooLong#a4bcc6fe flags:# final:flags.0?true timeout:flags.1?int dialog:Dialog messages:Vector chats:Vector users:Vector = updates.ChannelDifference;\nupdates.channelDifference#2064674e flags:# final:flags.0?true pts:int timeout:flags.1?int new_messages:Vector other_updates:Vector chats:Vector users:Vector = updates.ChannelDifference;\nchannelMessagesFilterEmpty#94d42ee7 = ChannelMessagesFilter;\nchannelMessagesFilter#cd77d957 flags:# exclude_new_messages:flags.1?true ranges:Vector = ChannelMessagesFilter;\nchannelParticipant#c00c07c0 user_id:long date:int = ChannelParticipant;\nchannelParticipantSelf#35a8bfa7 flags:# via_request:flags.0?true user_id:long inviter_id:long date:int = ChannelParticipant;\nchannelParticipantCreator#2fe601d3 flags:# user_id:long admin_rights:ChatAdminRights rank:flags.0?string = ChannelParticipant;\nchannelParticipantAdmin#34c3bb53 flags:# can_edit:flags.0?true self:flags.1?true user_id:long inviter_id:flags.1?long promoted_by:long date:int admin_rights:ChatAdminRights rank:flags.2?string = ChannelParticipant;\nchannelParticipantBanned#6df8014e flags:# left:flags.0?true peer:Peer kicked_by:long date:int banned_rights:ChatBannedRights = ChannelParticipant;\nchannelParticipantLeft#1b03f006 peer:Peer = ChannelParticipant;\nchannelParticipantsRecent#de3f3c79 = ChannelParticipantsFilter;\nchannelParticipantsAdmins#b4608969 = ChannelParticipantsFilter;\nchannelParticipantsKicked#a3b54985 q:string = ChannelParticipantsFilter;\nchannelParticipantsBots#b0d1865b = ChannelParticipantsFilter;\nchannelParticipantsBanned#1427a5e1 q:string = ChannelParticipantsFilter;\nchannelParticipantsSearch#656ac4b q:string = ChannelParticipantsFilter;\nchannelParticipantsContacts#bb6ae88d q:string = ChannelParticipantsFilter;\nchannelParticipantsMentions#e04b5ceb flags:# q:flags.0?string top_msg_id:flags.1?int = ChannelParticipantsFilter;\nchannels.channelParticipants#9ab0feaf count:int participants:Vector chats:Vector users:Vector = channels.ChannelParticipants;\nchannels.channelParticipantsNotModified#f0173fe9 = channels.ChannelParticipants;\nchannels.channelParticipant#dfb80317 participant:ChannelParticipant chats:Vector users:Vector = channels.ChannelParticipant;\nhelp.termsOfService#780a0310 flags:# popup:flags.0?true id:DataJSON text:string entities:Vector min_age_confirm:flags.1?int = help.TermsOfService;\nmessages.savedGifsNotModified#e8025ca2 = messages.SavedGifs;\nmessages.savedGifs#84a02a0d hash:long gifs:Vector = messages.SavedGifs;\ninputBotInlineMessageMediaAuto#3380c786 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageText#3dcd7a87 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaGeo#96929a85 flags:# geo_point:InputGeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaVenue#417bbf11 flags:# geo_point:InputGeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaContact#a6edbffd flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageGame#4b425864 flags:# reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineMessageMediaInvoice#d7e78225 flags:# title:string description:string photo:flags.0?InputWebDocument invoice:Invoice payload:bytes provider:string provider_data:DataJSON reply_markup:flags.2?ReplyMarkup = InputBotInlineMessage;\ninputBotInlineResult#88bf9319 flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?InputWebDocument content:flags.5?InputWebDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultPhoto#a8d864a7 id:string type:string photo:InputPhoto send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultDocument#fff8fdc4 flags:# id:string type:string title:flags.1?string description:flags.2?string document:InputDocument send_message:InputBotInlineMessage = InputBotInlineResult;\ninputBotInlineResultGame#4fa417f2 id:string short_name:string send_message:InputBotInlineMessage = InputBotInlineResult;\nbotInlineMessageMediaAuto#764cf810 flags:# message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageText#8c7f65e2 flags:# no_webpage:flags.0?true message:string entities:flags.1?Vector reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaGeo#51846fd flags:# geo:GeoPoint heading:flags.0?int period:flags.1?int proximity_notification_radius:flags.3?int reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaVenue#8a86659c flags:# geo:GeoPoint title:string address:string provider:string venue_id:string venue_type:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaContact#18d1cdc2 flags:# phone_number:string first_name:string last_name:string vcard:string reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineMessageMediaInvoice#354a9b09 flags:# shipping_address_requested:flags.1?true test:flags.3?true title:string description:string photo:flags.0?WebDocument currency:string total_amount:long reply_markup:flags.2?ReplyMarkup = BotInlineMessage;\nbotInlineResult#11965f3a flags:# id:string type:string title:flags.1?string description:flags.2?string url:flags.3?string thumb:flags.4?WebDocument content:flags.5?WebDocument send_message:BotInlineMessage = BotInlineResult;\nbotInlineMediaResult#17db940b flags:# id:string type:string photo:flags.0?Photo document:flags.1?Document title:flags.2?string description:flags.3?string send_message:BotInlineMessage = BotInlineResult;\nmessages.botResults#e021f2f6 flags:# gallery:flags.0?true query_id:long next_offset:flags.1?string switch_pm:flags.2?InlineBotSwitchPM switch_webview:flags.3?InlineBotWebView results:Vector cache_time:int users:Vector = messages.BotResults;\nexportedMessageLink#5dab1af4 link:string html:string = ExportedMessageLink;\nmessageFwdHeader#5f777dce flags:# imported:flags.7?true from_id:flags.0?Peer from_name:flags.5?string date:int channel_post:flags.2?int post_author:flags.3?string saved_from_peer:flags.4?Peer saved_from_msg_id:flags.4?int psa_type:flags.6?string = MessageFwdHeader;\nauth.codeTypeSms#72a3158c = auth.CodeType;\nauth.codeTypeCall#741cd3e3 = auth.CodeType;\nauth.codeTypeFlashCall#226ccefb = auth.CodeType;\nauth.codeTypeMissedCall#d61ad6ee = auth.CodeType;\nauth.codeTypeFragmentSms#6ed998c = auth.CodeType;\nauth.sentCodeTypeApp#3dbb5986 length:int = auth.SentCodeType;\nauth.sentCodeTypeSms#c000bba2 length:int = auth.SentCodeType;\nauth.sentCodeTypeCall#5353e5a7 length:int = auth.SentCodeType;\nauth.sentCodeTypeFlashCall#ab03c6d9 pattern:string = auth.SentCodeType;\nauth.sentCodeTypeMissedCall#82006484 prefix:string length:int = auth.SentCodeType;\nauth.sentCodeTypeEmailCode#f450f59b flags:# apple_signin_allowed:flags.0?true google_signin_allowed:flags.1?true email_pattern:string length:int reset_available_period:flags.3?int reset_pending_date:flags.4?int = auth.SentCodeType;\nauth.sentCodeTypeSetUpEmailRequired#a5491dea flags:# apple_signin_allowed:flags.0?true google_signin_allowed:flags.1?true = auth.SentCodeType;\nauth.sentCodeTypeFragmentSms#d9565c39 url:string length:int = auth.SentCodeType;\nauth.sentCodeTypeFirebaseSms#e57b1432 flags:# nonce:flags.0?bytes receipt:flags.1?string push_timeout:flags.1?int length:int = auth.SentCodeType;\nmessages.botCallbackAnswer#36585ea4 flags:# alert:flags.1?true has_url:flags.3?true native_ui:flags.4?true message:flags.0?string url:flags.2?string cache_time:int = messages.BotCallbackAnswer;\nmessages.messageEditData#26b5dde6 flags:# caption:flags.0?true = messages.MessageEditData;\ninputBotInlineMessageID#890c3d89 dc_id:int id:long access_hash:long = InputBotInlineMessageID;\ninputBotInlineMessageID64#b6d915d7 dc_id:int owner_id:long id:int access_hash:long = InputBotInlineMessageID;\ninlineBotSwitchPM#3c20629f text:string start_param:string = InlineBotSwitchPM;\nmessages.peerDialogs#3371c354 dialogs:Vector messages:Vector chats:Vector users:Vector state:updates.State = messages.PeerDialogs;\ntopPeer#edcdc05b peer:Peer rating:double = TopPeer;\ntopPeerCategoryBotsPM#ab661b5b = TopPeerCategory;\ntopPeerCategoryBotsInline#148677e2 = TopPeerCategory;\ntopPeerCategoryCorrespondents#637b7ed = TopPeerCategory;\ntopPeerCategoryGroups#bd17a14a = TopPeerCategory;\ntopPeerCategoryChannels#161d9628 = TopPeerCategory;\ntopPeerCategoryPhoneCalls#1e76a78c = TopPeerCategory;\ntopPeerCategoryForwardUsers#a8406ca9 = TopPeerCategory;\ntopPeerCategoryForwardChats#fbeec0f0 = TopPeerCategory;\ntopPeerCategoryPeers#fb834291 category:TopPeerCategory count:int peers:Vector = TopPeerCategoryPeers;\ncontacts.topPeersNotModified#de266ef5 = contacts.TopPeers;\ncontacts.topPeers#70b772a8 categories:Vector chats:Vector users:Vector = contacts.TopPeers;\ncontacts.topPeersDisabled#b52c939d = contacts.TopPeers;\ndraftMessageEmpty#1b0c841a flags:# date:flags.0?int = DraftMessage;\ndraftMessage#fd8e711f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int message:string entities:flags.3?Vector date:int = DraftMessage;\nmessages.featuredStickersNotModified#c6dc0c66 count:int = messages.FeaturedStickers;\nmessages.featuredStickers#be382906 flags:# premium:flags.0?true hash:long count:int sets:Vector unread:Vector = messages.FeaturedStickers;\nmessages.recentStickersNotModified#b17f890 = messages.RecentStickers;\nmessages.recentStickers#88d37c56 hash:long packs:Vector stickers:Vector dates:Vector = messages.RecentStickers;\nmessages.archivedStickers#4fcba9c8 count:int sets:Vector = messages.ArchivedStickers;\nmessages.stickerSetInstallResultSuccess#38641628 = messages.StickerSetInstallResult;\nmessages.stickerSetInstallResultArchive#35e410a8 sets:Vector = messages.StickerSetInstallResult;\nstickerSetCovered#6410a5d2 set:StickerSet cover:Document = StickerSetCovered;\nstickerSetMultiCovered#3407e51b set:StickerSet covers:Vector = StickerSetCovered;\nstickerSetFullCovered#40d13c0e set:StickerSet packs:Vector keywords:Vector documents:Vector = StickerSetCovered;\nstickerSetNoCovered#77b15d1c set:StickerSet = StickerSetCovered;\nmaskCoords#aed6dbb2 n:int x:double y:double zoom:double = MaskCoords;\ninputStickeredMediaPhoto#4a992157 id:InputPhoto = InputStickeredMedia;\ninputStickeredMediaDocument#438865b id:InputDocument = InputStickeredMedia;\ngame#bdf9653b flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document = Game;\ninputGameID#32c3e77 id:long access_hash:long = InputGame;\ninputGameShortName#c331e80a bot_id:InputUser short_name:string = InputGame;\nhighScore#73a379eb pos:int user_id:long score:int = HighScore;\nmessages.highScores#9a3bfd99 scores:Vector users:Vector = messages.HighScores;\ntextEmpty#dc3d824f = RichText;\ntextPlain#744694e0 text:string = RichText;\ntextBold#6724abc4 text:RichText = RichText;\ntextItalic#d912a59c text:RichText = RichText;\ntextUnderline#c12622c4 text:RichText = RichText;\ntextStrike#9bf8bb95 text:RichText = RichText;\ntextFixed#6c3f19b9 text:RichText = RichText;\ntextUrl#3c2884c1 text:RichText url:string webpage_id:long = RichText;\ntextEmail#de5a0dd6 text:RichText email:string = RichText;\ntextConcat#7e6260d7 texts:Vector = RichText;\ntextSubscript#ed6a8504 text:RichText = RichText;\ntextSuperscript#c7fb5e01 text:RichText = RichText;\ntextMarked#34b8621 text:RichText = RichText;\ntextPhone#1ccb966a text:RichText phone:string = RichText;\ntextImage#81ccf4f document_id:long w:int h:int = RichText;\ntextAnchor#35553762 text:RichText name:string = RichText;\npageBlockUnsupported#13567e8a = PageBlock;\npageBlockTitle#70abc3fd text:RichText = PageBlock;\npageBlockSubtitle#8ffa9a1f text:RichText = PageBlock;\npageBlockAuthorDate#baafe5e0 author:RichText published_date:int = PageBlock;\npageBlockHeader#bfd064ec text:RichText = PageBlock;\npageBlockSubheader#f12bb6e1 text:RichText = PageBlock;\npageBlockParagraph#467a0766 text:RichText = PageBlock;\npageBlockPreformatted#c070d93e text:RichText language:string = PageBlock;\npageBlockFooter#48870999 text:RichText = PageBlock;\npageBlockDivider#db20b188 = PageBlock;\npageBlockAnchor#ce0d37b0 name:string = PageBlock;\npageBlockList#e4e88011 items:Vector = PageBlock;\npageBlockBlockquote#263d7c26 text:RichText caption:RichText = PageBlock;\npageBlockPullquote#4f4456d3 text:RichText caption:RichText = PageBlock;\npageBlockPhoto#1759c560 flags:# photo_id:long caption:PageCaption url:flags.0?string webpage_id:flags.0?long = PageBlock;\npageBlockVideo#7c8fe7b6 flags:# autoplay:flags.0?true loop:flags.1?true video_id:long caption:PageCaption = PageBlock;\npageBlockCover#39f23300 cover:PageBlock = PageBlock;\npageBlockEmbed#a8718dc5 flags:# full_width:flags.0?true allow_scrolling:flags.3?true url:flags.1?string html:flags.2?string poster_photo_id:flags.4?long w:flags.5?int h:flags.5?int caption:PageCaption = PageBlock;\npageBlockEmbedPost#f259a80b url:string webpage_id:long author_photo_id:long author:string date:int blocks:Vector caption:PageCaption = PageBlock;\npageBlockCollage#65a0fa4d items:Vector caption:PageCaption = PageBlock;\npageBlockSlideshow#31f9590 items:Vector caption:PageCaption = PageBlock;\npageBlockChannel#ef1751b5 channel:Chat = PageBlock;\npageBlockAudio#804361ea audio_id:long caption:PageCaption = PageBlock;\npageBlockKicker#1e148390 text:RichText = PageBlock;\npageBlockTable#bf4dea82 flags:# bordered:flags.0?true striped:flags.1?true title:RichText rows:Vector = PageBlock;\npageBlockOrderedList#9a8ae1e1 items:Vector = PageBlock;\npageBlockDetails#76768bed flags:# open:flags.0?true blocks:Vector title:RichText = PageBlock;\npageBlockRelatedArticles#16115a96 title:RichText articles:Vector = PageBlock;\npageBlockMap#a44f3ef6 geo:GeoPoint zoom:int w:int h:int caption:PageCaption = PageBlock;\nphoneCallDiscardReasonMissed#85e42301 = PhoneCallDiscardReason;\nphoneCallDiscardReasonDisconnect#e095c1a0 = PhoneCallDiscardReason;\nphoneCallDiscardReasonHangup#57adc690 = PhoneCallDiscardReason;\nphoneCallDiscardReasonBusy#faf7e8c9 = PhoneCallDiscardReason;\ndataJSON#7d748d04 data:string = DataJSON;\nlabeledPrice#cb296bf8 label:string amount:long = LabeledPrice;\ninvoice#3e85a91b flags:# test:flags.0?true name_requested:flags.1?true phone_requested:flags.2?true email_requested:flags.3?true shipping_address_requested:flags.4?true flexible:flags.5?true phone_to_provider:flags.6?true email_to_provider:flags.7?true recurring:flags.9?true currency:string prices:Vector max_tip_amount:flags.8?long suggested_tip_amounts:flags.8?Vector recurring_terms_url:flags.9?string = Invoice;\npaymentCharge#ea02c27e id:string provider_charge_id:string = PaymentCharge;\npostAddress#1e8caaeb street_line1:string street_line2:string city:string state:string country_iso2:string post_code:string = PostAddress;\npaymentRequestedInfo#909c3f94 flags:# name:flags.0?string phone:flags.1?string email:flags.2?string shipping_address:flags.3?PostAddress = PaymentRequestedInfo;\npaymentSavedCredentialsCard#cdc27a1f id:string title:string = PaymentSavedCredentials;\nwebDocument#1c570ed1 url:string access_hash:long size:int mime_type:string attributes:Vector = WebDocument;\nwebDocumentNoProxy#f9c8bcc6 url:string size:int mime_type:string attributes:Vector = WebDocument;\ninputWebDocument#9bed434d url:string size:int mime_type:string attributes:Vector = InputWebDocument;\ninputWebFileLocation#c239d686 url:string access_hash:long = InputWebFileLocation;\ninputWebFileGeoPointLocation#9f2221c9 geo_point:InputGeoPoint access_hash:long w:int h:int zoom:int scale:int = InputWebFileLocation;\ninputWebFileAudioAlbumThumbLocation#f46fe924 flags:# small:flags.2?true document:flags.0?InputDocument title:flags.1?string performer:flags.1?string = InputWebFileLocation;\nupload.webFile#21e753bc size:int mime_type:string file_type:storage.FileType mtime:int bytes:bytes = upload.WebFile;\npayments.paymentForm#a0058751 flags:# can_save_credentials:flags.2?true password_missing:flags.3?true form_id:long bot_id:long title:string description:string photo:flags.5?WebDocument invoice:Invoice provider_id:long url:string native_provider:flags.4?string native_params:flags.4?DataJSON additional_methods:flags.6?Vector saved_info:flags.0?PaymentRequestedInfo saved_credentials:flags.1?Vector users:Vector = payments.PaymentForm;\npayments.validatedRequestedInfo#d1451883 flags:# id:flags.0?string shipping_options:flags.1?Vector = payments.ValidatedRequestedInfo;\npayments.paymentResult#4e5f810d updates:Updates = payments.PaymentResult;\npayments.paymentVerificationNeeded#d8411139 url:string = payments.PaymentResult;\npayments.paymentReceipt#70c4fe03 flags:# date:int bot_id:long provider_id:long title:string description:string photo:flags.2?WebDocument invoice:Invoice info:flags.0?PaymentRequestedInfo shipping:flags.1?ShippingOption tip_amount:flags.3?long currency:string total_amount:long credentials_title:string users:Vector = payments.PaymentReceipt;\npayments.savedInfo#fb8fe43c flags:# has_saved_credentials:flags.1?true saved_info:flags.0?PaymentRequestedInfo = payments.SavedInfo;\ninputPaymentCredentialsSaved#c10eb2cf id:string tmp_password:bytes = InputPaymentCredentials;\ninputPaymentCredentials#3417d728 flags:# save:flags.0?true data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsApplePay#aa1c39f payment_data:DataJSON = InputPaymentCredentials;\ninputPaymentCredentialsGooglePay#8ac32801 payment_token:DataJSON = InputPaymentCredentials;\naccount.tmpPassword#db64fd34 tmp_password:bytes valid_until:int = account.TmpPassword;\nshippingOption#b6213cdf id:string title:string prices:Vector = ShippingOption;\ninputStickerSetItem#32da9e9c flags:# document:InputDocument emoji:string mask_coords:flags.0?MaskCoords keywords:flags.1?string = InputStickerSetItem;\ninputPhoneCall#1e36fded id:long access_hash:long = InputPhoneCall;\nphoneCallEmpty#5366c915 id:long = PhoneCall;\nphoneCallWaiting#c5226f17 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long protocol:PhoneCallProtocol receive_date:flags.0?int = PhoneCall;\nphoneCallRequested#14b0ed0c flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_hash:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCallAccepted#3660c311 flags:# video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_b:bytes protocol:PhoneCallProtocol = PhoneCall;\nphoneCall#967f7c67 flags:# p2p_allowed:flags.5?true video:flags.6?true id:long access_hash:long date:int admin_id:long participant_id:long g_a_or_b:bytes key_fingerprint:long protocol:PhoneCallProtocol connections:Vector start_date:int = PhoneCall;\nphoneCallDiscarded#50ca4de1 flags:# need_rating:flags.2?true need_debug:flags.3?true video:flags.6?true id:long reason:flags.0?PhoneCallDiscardReason duration:flags.1?int = PhoneCall;\nphoneConnection#9cc123c7 flags:# tcp:flags.0?true id:long ip:string ipv6:string port:int peer_tag:bytes = PhoneConnection;\nphoneConnectionWebrtc#635fe375 flags:# turn:flags.0?true stun:flags.1?true id:long ip:string ipv6:string port:int username:string password:string = PhoneConnection;\nphoneCallProtocol#fc878fc8 flags:# udp_p2p:flags.0?true udp_reflector:flags.1?true min_layer:int max_layer:int library_versions:Vector = PhoneCallProtocol;\nphone.phoneCall#ec82e140 phone_call:PhoneCall users:Vector = phone.PhoneCall;\nupload.cdnFileReuploadNeeded#eea8e46e request_token:bytes = upload.CdnFile;\nupload.cdnFile#a99fca4f bytes:bytes = upload.CdnFile;\ncdnPublicKey#c982eaba dc_id:int public_key:string = CdnPublicKey;\ncdnConfig#5725e40a public_keys:Vector = CdnConfig;\nlangPackString#cad181f6 key:string value:string = LangPackString;\nlangPackStringPluralized#6c47ac9f flags:# key:string zero_value:flags.0?string one_value:flags.1?string two_value:flags.2?string few_value:flags.3?string many_value:flags.4?string other_value:string = LangPackString;\nlangPackStringDeleted#2979eeb2 key:string = LangPackString;\nlangPackDifference#f385c1f6 lang_code:string from_version:int version:int strings:Vector = LangPackDifference;\nlangPackLanguage#eeca5ce3 flags:# official:flags.0?true rtl:flags.2?true beta:flags.3?true name:string native_name:string lang_code:string base_lang_code:flags.1?string plural_code:string strings_count:int translated_count:int translations_url:string = LangPackLanguage;\nchannelAdminLogEventActionChangeTitle#e6dfb825 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAbout#55188a2e prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsername#6a4afc38 prev_value:string new_value:string = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangePhoto#434bd2af prev_photo:Photo new_photo:Photo = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleInvites#1b7907ae new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSignatures#26ae0971 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionUpdatePinned#e9e82c18 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditMessage#709b2405 prev_message:Message new_message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteMessage#42e047bb message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoin#183040d3 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantLeave#f89777f2 = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantInvite#e31c34d8 participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleBan#e6d83d7e prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantToggleAdmin#d5676710 prev_participant:ChannelParticipant new_participant:ChannelParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeStickerSet#b1c3caa7 prev_stickerset:InputStickerSet new_stickerset:InputStickerSet = ChannelAdminLogEventAction;\nchannelAdminLogEventActionTogglePreHistoryHidden#5f5c95f1 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDefaultBannedRights#2df5fc0a prev_banned_rights:ChatBannedRights new_banned_rights:ChatBannedRights = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStopPoll#8f079643 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLinkedChat#50c7ac8 prev_value:long new_value:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeLocation#e6b76ae prev_value:ChannelLocation new_value:ChannelLocation = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleSlowMode#53909779 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionStartGroupCall#23209745 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDiscardGroupCall#db9f9140 call:InputGroupCall = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantMute#f92424d2 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantUnmute#e64429c0 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleGroupCallSetting#56d6a247 join_muted:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByInvite#fe9fc158 flags:# via_chatlist:flags.0?true invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteDelete#5a50fca4 invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteRevoke#410a134e invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionExportedInviteEdit#e90ebb59 prev_invite:ExportedChatInvite new_invite:ExportedChatInvite = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantVolume#3e7f6847 participant:GroupCallParticipant = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeHistoryTTL#6e941a38 prev_value:int new_value:int = ChannelAdminLogEventAction;\nchannelAdminLogEventActionParticipantJoinByRequest#afb6144a invite:ExportedChatInvite approved_by:long = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleNoForwards#cb2ac766 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionSendMessage#278f2868 message:Message = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeAvailableReactions#be4e0ef8 prev_value:ChatReactions new_value:ChatReactions = ChannelAdminLogEventAction;\nchannelAdminLogEventActionChangeUsernames#f04fb3a9 prev_value:Vector new_value:Vector = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleForum#2cc6383 new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEventActionCreateTopic#58707d28 topic:ForumTopic = ChannelAdminLogEventAction;\nchannelAdminLogEventActionEditTopic#f06fe208 prev_topic:ForumTopic new_topic:ForumTopic = ChannelAdminLogEventAction;\nchannelAdminLogEventActionDeleteTopic#ae168909 topic:ForumTopic = ChannelAdminLogEventAction;\nchannelAdminLogEventActionPinTopic#5d8d353b flags:# prev_topic:flags.0?ForumTopic new_topic:flags.1?ForumTopic = ChannelAdminLogEventAction;\nchannelAdminLogEventActionToggleAntiSpam#64f36dfc new_value:Bool = ChannelAdminLogEventAction;\nchannelAdminLogEvent#1fad68cd id:long date:int user_id:long action:ChannelAdminLogEventAction = ChannelAdminLogEvent;\nchannels.adminLogResults#ed8af74d events:Vector chats:Vector users:Vector = channels.AdminLogResults;\nchannelAdminLogEventsFilter#ea107ae4 flags:# join:flags.0?true leave:flags.1?true invite:flags.2?true ban:flags.3?true unban:flags.4?true kick:flags.5?true unkick:flags.6?true promote:flags.7?true demote:flags.8?true info:flags.9?true settings:flags.10?true pinned:flags.11?true edit:flags.12?true delete:flags.13?true group_call:flags.14?true invites:flags.15?true send:flags.16?true forums:flags.17?true = ChannelAdminLogEventsFilter;\npopularContact#5ce14175 client_id:long importers:int = PopularContact;\nmessages.favedStickersNotModified#9e8fa6d3 = messages.FavedStickers;\nmessages.favedStickers#2cb51097 hash:long packs:Vector stickers:Vector = messages.FavedStickers;\nrecentMeUrlUnknown#46e1d13d url:string = RecentMeUrl;\nrecentMeUrlUser#b92c09e2 url:string user_id:long = RecentMeUrl;\nrecentMeUrlChat#b2da71d2 url:string chat_id:long = RecentMeUrl;\nrecentMeUrlChatInvite#eb49081d url:string chat_invite:ChatInvite = RecentMeUrl;\nrecentMeUrlStickerSet#bc0a57dc url:string set:StickerSetCovered = RecentMeUrl;\nhelp.recentMeUrls#e0310d7 urls:Vector chats:Vector users:Vector = help.RecentMeUrls;\ninputSingleMedia#1cc6e91f flags:# media:InputMedia random_id:long message:string entities:flags.0?Vector = InputSingleMedia;\nwebAuthorization#a6f8f452 hash:long bot_id:long domain:string browser:string platform:string date_created:int date_active:int ip:string region:string = WebAuthorization;\naccount.webAuthorizations#ed56c9fc authorizations:Vector users:Vector = account.WebAuthorizations;\ninputMessageID#a676a322 id:int = InputMessage;\ninputMessageReplyTo#bad88395 id:int = InputMessage;\ninputMessagePinned#86872538 = InputMessage;\ninputMessageCallbackQuery#acfa1a7e id:int query_id:long = InputMessage;\ninputDialogPeer#fcaafeb7 peer:InputPeer = InputDialogPeer;\ninputDialogPeerFolder#64600527 folder_id:int = InputDialogPeer;\ndialogPeer#e56dbf05 peer:Peer = DialogPeer;\ndialogPeerFolder#514519e2 folder_id:int = DialogPeer;\nmessages.foundStickerSetsNotModified#d54b65d = messages.FoundStickerSets;\nmessages.foundStickerSets#8af09dd2 hash:long sets:Vector = messages.FoundStickerSets;\nfileHash#f39b035c offset:long limit:int hash:bytes = FileHash;\ninputClientProxy#75588b3f address:string port:int = InputClientProxy;\nhelp.termsOfServiceUpdateEmpty#e3309f7f expires:int = help.TermsOfServiceUpdate;\nhelp.termsOfServiceUpdate#28ecf961 expires:int terms_of_service:help.TermsOfService = help.TermsOfServiceUpdate;\ninputSecureFileUploaded#3334b0f0 id:long parts:int md5_checksum:string file_hash:bytes secret:bytes = InputSecureFile;\ninputSecureFile#5367e5be id:long access_hash:long = InputSecureFile;\nsecureFileEmpty#64199744 = SecureFile;\nsecureFile#7d09c27e id:long access_hash:long size:long dc_id:int date:int file_hash:bytes secret:bytes = SecureFile;\nsecureData#8aeabec3 data:bytes data_hash:bytes secret:bytes = SecureData;\nsecurePlainPhone#7d6099dd phone:string = SecurePlainData;\nsecurePlainEmail#21ec5a5f email:string = SecurePlainData;\nsecureValueTypePersonalDetails#9d2a81e3 = SecureValueType;\nsecureValueTypePassport#3dac6a00 = SecureValueType;\nsecureValueTypeDriverLicense#6e425c4 = SecureValueType;\nsecureValueTypeIdentityCard#a0d0744b = SecureValueType;\nsecureValueTypeInternalPassport#99a48f23 = SecureValueType;\nsecureValueTypeAddress#cbe31e26 = SecureValueType;\nsecureValueTypeUtilityBill#fc36954e = SecureValueType;\nsecureValueTypeBankStatement#89137c0d = SecureValueType;\nsecureValueTypeRentalAgreement#8b883488 = SecureValueType;\nsecureValueTypePassportRegistration#99e3806a = SecureValueType;\nsecureValueTypeTemporaryRegistration#ea02ec33 = SecureValueType;\nsecureValueTypePhone#b320aadb = SecureValueType;\nsecureValueTypeEmail#8e3ca7ee = SecureValueType;\nsecureValue#187fa0ca flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?SecureFile reverse_side:flags.2?SecureFile selfie:flags.3?SecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData hash:bytes = SecureValue;\ninputSecureValue#db21d0a7 flags:# type:SecureValueType data:flags.0?SecureData front_side:flags.1?InputSecureFile reverse_side:flags.2?InputSecureFile selfie:flags.3?InputSecureFile translation:flags.6?Vector files:flags.4?Vector plain_data:flags.5?SecurePlainData = InputSecureValue;\nsecureValueHash#ed1ecdb0 type:SecureValueType hash:bytes = SecureValueHash;\nsecureValueErrorData#e8a40bd9 type:SecureValueType data_hash:bytes field:string text:string = SecureValueError;\nsecureValueErrorFrontSide#be3dfa type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorReverseSide#868a2aa5 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorSelfie#e537ced6 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFile#7a700873 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorFiles#666220e9 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureValueError#869d758f type:SecureValueType hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFile#a1144770 type:SecureValueType file_hash:bytes text:string = SecureValueError;\nsecureValueErrorTranslationFiles#34636dd8 type:SecureValueType file_hash:Vector text:string = SecureValueError;\nsecureCredentialsEncrypted#33f0ea47 data:bytes hash:bytes secret:bytes = SecureCredentialsEncrypted;\naccount.authorizationForm#ad2e1cd8 flags:# required_types:Vector values:Vector errors:Vector users:Vector privacy_policy_url:flags.0?string = account.AuthorizationForm;\naccount.sentEmailCode#811f854f email_pattern:string length:int = account.SentEmailCode;\nhelp.deepLinkInfoEmpty#66afa166 = help.DeepLinkInfo;\nhelp.deepLinkInfo#6a4ee832 flags:# update_app:flags.0?true message:string entities:flags.1?Vector = help.DeepLinkInfo;\nsavedPhoneContact#1142bd56 phone:string first_name:string last_name:string date:int = SavedContact;\naccount.takeout#4dba4501 id:long = account.Takeout;\npasswordKdfAlgoUnknown#d45ab096 = PasswordKdfAlgo;\npasswordKdfAlgoSHA256SHA256PBKDF2HMACSHA512iter100000SHA256ModPow#3a912d4a salt1:bytes salt2:bytes g:int p:bytes = PasswordKdfAlgo;\nsecurePasswordKdfAlgoUnknown#4a8537 = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoPBKDF2HMACSHA512iter100000#bbf2dda0 salt:bytes = SecurePasswordKdfAlgo;\nsecurePasswordKdfAlgoSHA512#86471d92 salt:bytes = SecurePasswordKdfAlgo;\nsecureSecretSettings#1527bcac secure_algo:SecurePasswordKdfAlgo secure_secret:bytes secure_secret_id:long = SecureSecretSettings;\ninputCheckPasswordEmpty#9880f658 = InputCheckPasswordSRP;\ninputCheckPasswordSRP#d27ff082 srp_id:long A:bytes M1:bytes = InputCheckPasswordSRP;\nsecureRequiredType#829d99da flags:# native_names:flags.0?true selfie_required:flags.1?true translation_required:flags.2?true type:SecureValueType = SecureRequiredType;\nsecureRequiredTypeOneOf#27477b4 types:Vector = SecureRequiredType;\nhelp.passportConfigNotModified#bfb9f457 = help.PassportConfig;\nhelp.passportConfig#a098d6af hash:int countries_langs:DataJSON = help.PassportConfig;\ninputAppEvent#1d1b1245 time:double type:string peer:long data:JSONValue = InputAppEvent;\njsonObjectValue#c0de1bd9 key:string value:JSONValue = JSONObjectValue;\njsonNull#3f6d7b68 = JSONValue;\njsonBool#c7345e6a value:Bool = JSONValue;\njsonNumber#2be0dfa4 value:double = JSONValue;\njsonString#b71e767a value:string = JSONValue;\njsonArray#f7444763 value:Vector = JSONValue;\njsonObject#99c1d49d value:Vector = JSONValue;\npageTableCell#34566b6a flags:# header:flags.0?true align_center:flags.3?true align_right:flags.4?true valign_middle:flags.5?true valign_bottom:flags.6?true text:flags.7?RichText colspan:flags.1?int rowspan:flags.2?int = PageTableCell;\npageTableRow#e0c0c5e5 cells:Vector = PageTableRow;\npageCaption#6f747657 text:RichText credit:RichText = PageCaption;\npageListItemText#b92fb6cd text:RichText = PageListItem;\npageListItemBlocks#25e073fc blocks:Vector = PageListItem;\npageListOrderedItemText#5e068047 num:string text:RichText = PageListOrderedItem;\npageListOrderedItemBlocks#98dd8936 num:string blocks:Vector = PageListOrderedItem;\npageRelatedArticle#b390dc08 flags:# url:string webpage_id:long title:flags.0?string description:flags.1?string photo_id:flags.2?long author:flags.3?string published_date:flags.4?int = PageRelatedArticle;\npage#98657f0d flags:# part:flags.0?true rtl:flags.1?true v2:flags.2?true url:string blocks:Vector photos:Vector documents:Vector views:flags.3?int = Page;\nhelp.supportName#8c05f1c9 name:string = help.SupportName;\nhelp.userInfoEmpty#f3ae2eed = help.UserInfo;\nhelp.userInfo#1eb3758 message:string entities:Vector author:string date:int = help.UserInfo;\npollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer;\npoll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll;\npollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters;\npollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults;\nchatOnlines#f041e250 onlines:int = ChatOnlines;\nstatsURL#47a971e0 url:string = StatsURL;\nchatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true manage_topics:flags.13?true = ChatAdminRights;\nchatBannedRights#9f120418 flags:# view_messages:flags.0?true send_messages:flags.1?true send_media:flags.2?true send_stickers:flags.3?true send_gifs:flags.4?true send_games:flags.5?true send_inline:flags.6?true embed_links:flags.7?true send_polls:flags.8?true change_info:flags.10?true invite_users:flags.15?true pin_messages:flags.17?true manage_topics:flags.18?true send_photos:flags.19?true send_videos:flags.20?true send_roundvideos:flags.21?true send_audios:flags.22?true send_voices:flags.23?true send_docs:flags.24?true send_plain:flags.25?true until_date:int = ChatBannedRights;\ninputWallPaper#e630b979 id:long access_hash:long = InputWallPaper;\ninputWallPaperSlug#72091c80 slug:string = InputWallPaper;\ninputWallPaperNoFile#967a462e id:long = InputWallPaper;\naccount.wallPapersNotModified#1c199183 = account.WallPapers;\naccount.wallPapers#cdc3858c hash:long wallpapers:Vector = account.WallPapers;\ncodeSettings#ad253d78 flags:# allow_flashcall:flags.0?true current_number:flags.1?true allow_app_hash:flags.4?true allow_missed_call:flags.5?true allow_firebase:flags.7?true logout_tokens:flags.6?Vector token:flags.8?string app_sandbox:flags.8?Bool = CodeSettings;\nwallPaperSettings#1dc1bca4 flags:# blur:flags.1?true motion:flags.2?true background_color:flags.0?int second_background_color:flags.4?int third_background_color:flags.5?int fourth_background_color:flags.6?int intensity:flags.3?int rotation:flags.4?int = WallPaperSettings;\nautoDownloadSettings#8efab953 flags:# disabled:flags.0?true video_preload_large:flags.1?true audio_preload_next:flags.2?true phonecalls_less_data:flags.3?true photo_size_max:int video_size_max:long file_size_max:long video_upload_maxbitrate:int = AutoDownloadSettings;\naccount.autoDownloadSettings#63cacf26 low:AutoDownloadSettings medium:AutoDownloadSettings high:AutoDownloadSettings = account.AutoDownloadSettings;\nemojiKeyword#d5b3b9f9 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordDeleted#236df622 keyword:string emoticons:Vector = EmojiKeyword;\nemojiKeywordsDifference#5cc761bd lang_code:string from_version:int version:int keywords:Vector = EmojiKeywordsDifference;\nemojiURL#a575739d url:string = EmojiURL;\nemojiLanguage#b3fb5361 lang_code:string = EmojiLanguage;\nfolder#ff544e65 flags:# autofill_new_broadcasts:flags.0?true autofill_public_groups:flags.1?true autofill_new_correspondents:flags.2?true id:int title:string photo:flags.3?ChatPhoto = Folder;\ninputFolderPeer#fbd2c296 peer:InputPeer folder_id:int = InputFolderPeer;\nfolderPeer#e9baa668 peer:Peer folder_id:int = FolderPeer;\nmessages.searchCounter#e844ebff flags:# inexact:flags.1?true filter:MessagesFilter count:int = messages.SearchCounter;\nurlAuthResultRequest#92d33a0e flags:# request_write_access:flags.0?true bot:User domain:string = UrlAuthResult;\nurlAuthResultAccepted#8f8c0e4e url:string = UrlAuthResult;\nurlAuthResultDefault#a9d6db1f = UrlAuthResult;\nchannelLocationEmpty#bfb5ad8b = ChannelLocation;\nchannelLocation#209b82db geo_point:GeoPoint address:string = ChannelLocation;\npeerLocated#ca461b5d peer:Peer expires:int distance:int = PeerLocated;\npeerSelfLocated#f8ec284b expires:int = PeerLocated;\nrestrictionReason#d072acb4 platform:string reason:string text:string = RestrictionReason;\ninputTheme#3c5693e9 id:long access_hash:long = InputTheme;\ninputThemeSlug#f5890df1 slug:string = InputTheme;\ntheme#a00e67d6 flags:# creator:flags.0?true default:flags.1?true for_chat:flags.5?true id:long access_hash:long slug:string title:string document:flags.2?Document settings:flags.3?Vector emoticon:flags.6?string installs_count:flags.4?int = Theme;\naccount.themesNotModified#f41eb622 = account.Themes;\naccount.themes#9a3d8c6d hash:long themes:Vector = account.Themes;\nauth.loginToken#629f1980 expires:int token:bytes = auth.LoginToken;\nauth.loginTokenMigrateTo#68e9916 dc_id:int token:bytes = auth.LoginToken;\nauth.loginTokenSuccess#390d5c5e authorization:auth.Authorization = auth.LoginToken;\naccount.contentSettings#57e28221 flags:# sensitive_enabled:flags.0?true sensitive_can_change:flags.1?true = account.ContentSettings;\nmessages.inactiveChats#a927fec5 dates:Vector chats:Vector users:Vector = messages.InactiveChats;\nbaseThemeClassic#c3a12462 = BaseTheme;\nbaseThemeDay#fbd81688 = BaseTheme;\nbaseThemeNight#b7b31ea8 = BaseTheme;\nbaseThemeTinted#6d5f77ee = BaseTheme;\nbaseThemeArctic#5b11125a = BaseTheme;\ninputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings;\nthemeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings;\nwebPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute;\nmessageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote;\nmessageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote;\nmessageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote;\nmessages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList;\nbankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl;\npayments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData;\ndialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter;\ndialogFilterDefault#363293ae = DialogFilter;\ndialogFilterChatlist#d64a04a8 flags:# has_my_invites:flags.26?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector = DialogFilter;\ndialogFilterSuggested#77744d4a filter:DialogFilter description:string = DialogFilterSuggested;\nstatsDateRangeDays#b637edaf min_date:int max_date:int = StatsDateRangeDays;\nstatsAbsValueAndPrev#cb43acde current:double previous:double = StatsAbsValueAndPrev;\nstatsPercentValue#cbce2fe0 part:double total:double = StatsPercentValue;\nstatsGraphAsync#4a27eb2d token:string = StatsGraph;\nstatsGraphError#bedc9822 error:string = StatsGraph;\nstatsGraph#8ea464b6 flags:# json:DataJSON zoom_token:flags.0?string = StatsGraph;\nmessageInteractionCounters#ad4fc9bd msg_id:int views:int forwards:int = MessageInteractionCounters;\nstats.broadcastStats#bdf78394 period:StatsDateRangeDays followers:StatsAbsValueAndPrev views_per_post:StatsAbsValueAndPrev shares_per_post:StatsAbsValueAndPrev enabled_notifications:StatsPercentValue growth_graph:StatsGraph followers_graph:StatsGraph mute_graph:StatsGraph top_hours_graph:StatsGraph interactions_graph:StatsGraph iv_interactions_graph:StatsGraph views_by_source_graph:StatsGraph new_followers_by_source_graph:StatsGraph languages_graph:StatsGraph recent_message_interactions:Vector = stats.BroadcastStats;\nhelp.promoDataEmpty#98f6ac75 expires:int = help.PromoData;\nhelp.promoData#8c39793f flags:# proxy:flags.0?true expires:int peer:Peer chats:Vector users:Vector psa_type:flags.1?string psa_message:flags.2?string = help.PromoData;\nvideoSize#de33b094 flags:# type:string w:int h:int size:int video_start_ts:flags.0?double = VideoSize;\nvideoSizeEmojiMarkup#f85c413c emoji_id:long background_colors:Vector = VideoSize;\nvideoSizeStickerMarkup#da082fe stickerset:InputStickerSet sticker_id:long background_colors:Vector = VideoSize;\nstatsGroupTopPoster#9d04af9b user_id:long messages:int avg_chars:int = StatsGroupTopPoster;\nstatsGroupTopAdmin#d7584c87 user_id:long deleted:int kicked:int banned:int = StatsGroupTopAdmin;\nstatsGroupTopInviter#535f779d user_id:long invitations:int = StatsGroupTopInviter;\nstats.megagroupStats#ef7ff916 period:StatsDateRangeDays members:StatsAbsValueAndPrev messages:StatsAbsValueAndPrev viewers:StatsAbsValueAndPrev posters:StatsAbsValueAndPrev growth_graph:StatsGraph members_graph:StatsGraph new_members_by_source_graph:StatsGraph languages_graph:StatsGraph messages_graph:StatsGraph actions_graph:StatsGraph top_hours_graph:StatsGraph weekdays_graph:StatsGraph top_posters:Vector top_admins:Vector top_inviters:Vector users:Vector = stats.MegagroupStats;\nglobalPrivacySettings#bea2f424 flags:# archive_and_mute_new_noncontact_peers:flags.0?Bool = GlobalPrivacySettings;\nhelp.countryCode#4203c5ef flags:# country_code:string prefixes:flags.0?Vector patterns:flags.1?Vector = help.CountryCode;\nhelp.country#c3878e23 flags:# hidden:flags.0?true iso2:string default_name:string name:flags.1?string country_codes:Vector = help.Country;\nhelp.countriesListNotModified#93cc1f32 = help.CountriesList;\nhelp.countriesList#87d0759e countries:Vector hash:int = help.CountriesList;\nmessageViews#455b853d flags:# views:flags.0?int forwards:flags.1?int replies:flags.2?MessageReplies = MessageViews;\nmessages.messageViews#b6c4f543 views:Vector chats:Vector users:Vector = messages.MessageViews;\nmessages.discussionMessage#a6341782 flags:# messages:Vector max_id:flags.0?int read_inbox_max_id:flags.1?int read_outbox_max_id:flags.2?int unread_count:int chats:Vector users:Vector = messages.DiscussionMessage;\nmessageReplyHeader#a6d57763 flags:# reply_to_scheduled:flags.2?true forum_topic:flags.3?true reply_to_msg_id:int reply_to_peer_id:flags.0?Peer reply_to_top_id:flags.1?int = MessageReplyHeader;\nmessageReplies#83d60fc2 flags:# comments:flags.0?true replies:int replies_pts:int recent_repliers:flags.1?Vector channel_id:flags.0?long max_id:flags.2?int read_max_id:flags.3?int = MessageReplies;\npeerBlocked#e8fd8014 peer_id:Peer date:int = PeerBlocked;\nstats.messageStats#8999f295 views_graph:StatsGraph = stats.MessageStats;\ngroupCallDiscarded#7780bcb4 id:long access_hash:long duration:int = GroupCall;\ngroupCall#d597650c flags:# join_muted:flags.1?true can_change_join_muted:flags.2?true join_date_asc:flags.6?true schedule_start_subscribed:flags.8?true can_start_video:flags.9?true record_video_active:flags.11?true rtmp_stream:flags.12?true listeners_hidden:flags.13?true id:long access_hash:long participants_count:int title:flags.3?string stream_dc_id:flags.4?int record_start_date:flags.5?int schedule_date:flags.7?int unmuted_video_count:flags.10?int unmuted_video_limit:int version:int = GroupCall;\ninputGroupCall#d8aa840f id:long access_hash:long = InputGroupCall;\ngroupCallParticipant#eba636fe flags:# muted:flags.0?true left:flags.1?true can_self_unmute:flags.2?true just_joined:flags.4?true versioned:flags.5?true min:flags.8?true muted_by_you:flags.9?true volume_by_admin:flags.10?true self:flags.12?true video_joined:flags.15?true peer:Peer date:int active_date:flags.3?int source:int volume:flags.7?int about:flags.11?string raise_hand_rating:flags.13?long video:flags.6?GroupCallParticipantVideo presentation:flags.14?GroupCallParticipantVideo = GroupCallParticipant;\nphone.groupCall#9e727aad call:GroupCall participants:Vector participants_next_offset:string chats:Vector users:Vector = phone.GroupCall;\nphone.groupParticipants#f47751b6 count:int participants:Vector next_offset:string chats:Vector users:Vector version:int = phone.GroupParticipants;\ninlineQueryPeerTypeSameBotPM#3081ed9d = InlineQueryPeerType;\ninlineQueryPeerTypePM#833c0fac = InlineQueryPeerType;\ninlineQueryPeerTypeChat#d766c50a = InlineQueryPeerType;\ninlineQueryPeerTypeMegagroup#5ec4be43 = InlineQueryPeerType;\ninlineQueryPeerTypeBroadcast#6334ee9a = InlineQueryPeerType;\ninlineQueryPeerTypeBotPM#e3b2d0c = InlineQueryPeerType;\nmessages.historyImport#1662af0b id:long = messages.HistoryImport;\nmessages.historyImportParsed#5e0fb7b9 flags:# pm:flags.0?true group:flags.1?true title:flags.2?string = messages.HistoryImportParsed;\nmessages.affectedFoundMessages#ef8d3e6c pts:int pts_count:int offset:int messages:Vector = messages.AffectedFoundMessages;\nchatInviteImporter#8c5adfd9 flags:# requested:flags.0?true via_chatlist:flags.3?true user_id:long date:int about:flags.2?string approved_by:flags.1?long = ChatInviteImporter;\nmessages.exportedChatInvites#bdc62dcc count:int invites:Vector users:Vector = messages.ExportedChatInvites;\nmessages.exportedChatInvite#1871be50 invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.exportedChatInviteReplaced#222600ef invite:ExportedChatInvite new_invite:ExportedChatInvite users:Vector = messages.ExportedChatInvite;\nmessages.chatInviteImporters#81b6b00a count:int importers:Vector users:Vector = messages.ChatInviteImporters;\nchatAdminWithInvites#f2ecef23 admin_id:long invites_count:int revoked_invites_count:int = ChatAdminWithInvites;\nmessages.chatAdminsWithInvites#b69b72d7 admins:Vector users:Vector = messages.ChatAdminsWithInvites;\nmessages.checkedHistoryImportPeer#a24de717 confirm_text:string = messages.CheckedHistoryImportPeer;\nphone.joinAsPeers#afe5623f peers:Vector chats:Vector users:Vector = phone.JoinAsPeers;\nphone.exportedGroupCallInvite#204bd158 link:string = phone.ExportedGroupCallInvite;\ngroupCallParticipantVideoSourceGroup#dcb118b7 semantics:string sources:Vector = GroupCallParticipantVideoSourceGroup;\ngroupCallParticipantVideo#67753ac8 flags:# paused:flags.0?true endpoint:string source_groups:Vector audio_source:flags.1?int = GroupCallParticipantVideo;\nstickers.suggestedShortName#85fea03f short_name:string = stickers.SuggestedShortName;\nbotCommandScopeDefault#2f6cb2ab = BotCommandScope;\nbotCommandScopeUsers#3c4f04d8 = BotCommandScope;\nbotCommandScopeChats#6fe1a881 = BotCommandScope;\nbotCommandScopeChatAdmins#b9aa606a = BotCommandScope;\nbotCommandScopePeer#db9d897d peer:InputPeer = BotCommandScope;\nbotCommandScopePeerAdmins#3fd863d1 peer:InputPeer = BotCommandScope;\nbotCommandScopePeerUser#a1321f3 peer:InputPeer user_id:InputUser = BotCommandScope;\naccount.resetPasswordFailedWait#e3779861 retry_date:int = account.ResetPasswordResult;\naccount.resetPasswordRequestedWait#e9effc7d until_date:int = account.ResetPasswordResult;\naccount.resetPasswordOk#e926d63e = account.ResetPasswordResult;\nsponsoredMessage#fc25b828 flags:# recommended:flags.5?true show_peer_photo:flags.6?true random_id:bytes from_id:flags.3?Peer chat_invite:flags.4?ChatInvite chat_invite_hash:flags.4?string channel_post:flags.2?int start_param:flags.0?string message:string entities:flags.1?Vector sponsor_info:flags.7?string additional_info:flags.8?string = SponsoredMessage;\nmessages.sponsoredMessages#c9ee1d87 flags:# posts_between:flags.0?int messages:Vector chats:Vector users:Vector = messages.SponsoredMessages;\nmessages.sponsoredMessagesEmpty#1839490f = messages.SponsoredMessages;\nsearchResultsCalendarPeriod#c9b0539f date:int min_msg_id:int max_msg_id:int count:int = SearchResultsCalendarPeriod;\nmessages.searchResultsCalendar#147ee23c flags:# inexact:flags.0?true count:int min_date:int min_msg_id:int offset_id_offset:flags.1?int periods:Vector messages:Vector chats:Vector users:Vector = messages.SearchResultsCalendar;\nsearchResultPosition#7f648b67 msg_id:int date:int offset:int = SearchResultsPosition;\nmessages.searchResultsPositions#53b22baf count:int positions:Vector = messages.SearchResultsPositions;\nchannels.sendAsPeers#f496b0c6 peers:Vector chats:Vector users:Vector = channels.SendAsPeers;\nusers.userFull#3b6d152e full_user:UserFull chats:Vector users:Vector = users.UserFull;\nmessages.peerSettings#6880b94d settings:PeerSettings chats:Vector users:Vector = messages.PeerSettings;\nauth.loggedOut#c3a2835f flags:# future_auth_token:flags.0?bytes = auth.LoggedOut;\nreactionCount#a3d1cb80 flags:# chosen_order:flags.0?int reaction:Reaction count:int = ReactionCount;\nmessageReactions#4f2b9479 flags:# min:flags.0?true can_see_list:flags.2?true results:Vector recent_reactions:flags.1?Vector = MessageReactions;\nmessages.messageReactionsList#31bd492d flags:# count:int reactions:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.MessageReactionsList;\navailableReaction#c077ec01 flags:# inactive:flags.0?true premium:flags.2?true reaction:string title:string static_icon:Document appear_animation:Document select_animation:Document activate_animation:Document effect_animation:Document around_animation:flags.1?Document center_icon:flags.1?Document = AvailableReaction;\nmessages.availableReactionsNotModified#9f071957 = messages.AvailableReactions;\nmessages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions;\nmessagePeerReaction#8c79b63c flags:# big:flags.0?true unread:flags.1?true peer_id:Peer date:int reaction:Reaction = MessagePeerReaction;\ngroupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel;\nphone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels;\nphone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl;\nattachMenuBotIconColor#4576f3f0 name:string color:int = AttachMenuBotIconColor;\nattachMenuBotIcon#b2a7386b flags:# name:string icon:Document colors:flags.0?Vector = AttachMenuBotIcon;\nattachMenuBot#c8aa2cd2 flags:# inactive:flags.0?true has_settings:flags.1?true request_write_access:flags.2?true bot_id:long short_name:string peer_types:Vector icons:Vector = AttachMenuBot;\nattachMenuBotsNotModified#f1d88a5c = AttachMenuBots;\nattachMenuBots#3c4301c0 hash:long bots:Vector users:Vector = AttachMenuBots;\nattachMenuBotsBot#93bf667f bot:AttachMenuBot users:Vector = AttachMenuBotsBot;\nwebViewResultUrl#c14557c query_id:long url:string = WebViewResult;\nsimpleWebViewResultUrl#882f76bb url:string = SimpleWebViewResult;\nwebViewMessageSent#c94511c flags:# msg_id:flags.0?InputBotInlineMessageID = WebViewMessageSent;\nbotMenuButtonDefault#7533a588 = BotMenuButton;\nbotMenuButtonCommands#4258c205 = BotMenuButton;\nbotMenuButton#c7b57ce6 text:string url:string = BotMenuButton;\naccount.savedRingtonesNotModified#fbf6e8b1 = account.SavedRingtones;\naccount.savedRingtones#c1e92cc5 hash:long ringtones:Vector = account.SavedRingtones;\nnotificationSoundDefault#97e8bebe = NotificationSound;\nnotificationSoundNone#6f0c34df = NotificationSound;\nnotificationSoundLocal#830b9ae4 title:string data:string = NotificationSound;\nnotificationSoundRingtone#ff6c8049 id:long = NotificationSound;\naccount.savedRingtone#b7263f6d = account.SavedRingtone;\naccount.savedRingtoneConverted#1f307eb7 document:Document = account.SavedRingtone;\nattachMenuPeerTypeSameBotPM#7d6be90e = AttachMenuPeerType;\nattachMenuPeerTypeBotPM#c32bfa1a = AttachMenuPeerType;\nattachMenuPeerTypePM#f146d31f = AttachMenuPeerType;\nattachMenuPeerTypeChat#509113f = AttachMenuPeerType;\nattachMenuPeerTypeBroadcast#7bfbdefc = AttachMenuPeerType;\ninputInvoiceMessage#c5b56859 peer:InputPeer msg_id:int = InputInvoice;\ninputInvoiceSlug#c326caef slug:string = InputInvoice;\npayments.exportedInvoice#aed0cbd9 url:string = payments.ExportedInvoice;\nmessages.transcribedAudio#93752c52 flags:# pending:flags.0?true transcription_id:long text:string = messages.TranscribedAudio;\nhelp.premiumPromo#5334759c status_text:string status_entities:Vector video_sections:Vector videos:Vector period_options:Vector users:Vector = help.PremiumPromo;\ninputStorePaymentPremiumSubscription#a6751e66 flags:# restore:flags.0?true upgrade:flags.1?true = InputStorePaymentPurpose;\ninputStorePaymentGiftPremium#616f7fe8 user_id:InputUser currency:string amount:long = InputStorePaymentPurpose;\npremiumGiftOption#74c34319 flags:# months:int currency:string amount:long bot_url:string store_product:flags.0?string = PremiumGiftOption;\npaymentFormMethod#88f8f21b url:string title:string = PaymentFormMethod;\nemojiStatusEmpty#2de11aae = EmojiStatus;\nemojiStatus#929b619d document_id:long = EmojiStatus;\nemojiStatusUntil#fa30a8c7 document_id:long until:int = EmojiStatus;\naccount.emojiStatusesNotModified#d08ce645 = account.EmojiStatuses;\naccount.emojiStatuses#90c467d1 hash:long statuses:Vector = account.EmojiStatuses;\nreactionEmpty#79f5d419 = Reaction;\nreactionEmoji#1b2286b8 emoticon:string = Reaction;\nreactionCustomEmoji#8935fc73 document_id:long = Reaction;\nchatReactionsNone#eafc32bc = ChatReactions;\nchatReactionsAll#52928bca flags:# allow_custom:flags.0?true = ChatReactions;\nchatReactionsSome#661d4037 reactions:Vector = ChatReactions;\nmessages.reactionsNotModified#b06fdbdf = messages.Reactions;\nmessages.reactions#eafdf716 hash:long reactions:Vector = messages.Reactions;\nemailVerifyPurposeLoginSetup#4345be73 phone_number:string phone_code_hash:string = EmailVerifyPurpose;\nemailVerifyPurposeLoginChange#527d22eb = EmailVerifyPurpose;\nemailVerifyPurposePassport#bbf51685 = EmailVerifyPurpose;\nemailVerificationCode#922e55a9 code:string = EmailVerification;\nemailVerificationGoogle#db909ec2 token:string = EmailVerification;\nemailVerificationApple#96d074fd token:string = EmailVerification;\naccount.emailVerified#2b96cd1b email:string = account.EmailVerified;\naccount.emailVerifiedLogin#e1bb0d61 email:string sent_code:auth.SentCode = account.EmailVerified;\npremiumSubscriptionOption#5f2d1df2 flags:# current:flags.1?true can_purchase_upgrade:flags.2?true transaction:flags.3?string months:int currency:string amount:long bot_url:string store_product:flags.0?string = PremiumSubscriptionOption;\nsendAsPeer#b81c7034 flags:# premium_required:flags.0?true peer:Peer = SendAsPeer;\nmessageExtendedMediaPreview#ad628cc8 flags:# w:flags.0?int h:flags.0?int thumb:flags.1?PhotoSize video_duration:flags.2?int = MessageExtendedMedia;\nmessageExtendedMedia#ee479c64 media:MessageMedia = MessageExtendedMedia;\nstickerKeyword#fcfeb29c document_id:long keyword:Vector = StickerKeyword;\nusername#b4073647 flags:# editable:flags.0?true active:flags.1?true username:string = Username;\nforumTopicDeleted#23f109b id:int = ForumTopic;\nforumTopic#71701da9 flags:# my:flags.1?true closed:flags.2?true pinned:flags.3?true short:flags.5?true hidden:flags.6?true id:int date:int title:string icon_color:int icon_emoji_id:flags.0?long top_message:int read_inbox_max_id:int read_outbox_max_id:int unread_count:int unread_mentions_count:int unread_reactions_count:int from_id:Peer notify_settings:PeerNotifySettings draft:flags.4?DraftMessage = ForumTopic;\nmessages.forumTopics#367617d3 flags:# order_by_create_date:flags.0?true count:int topics:Vector messages:Vector chats:Vector users:Vector pts:int = messages.ForumTopics;\ndefaultHistoryTTL#43b46b20 period:int = DefaultHistoryTTL;\nexportedContactToken#41bf109b url:string expires:int = ExportedContactToken;\nrequestPeerTypeUser#5f3b8a00 flags:# bot:flags.0?Bool premium:flags.1?Bool = RequestPeerType;\nrequestPeerTypeChat#c9f06e1b flags:# creator:flags.0?true bot_participant:flags.5?true has_username:flags.3?Bool forum:flags.4?Bool user_admin_rights:flags.1?ChatAdminRights bot_admin_rights:flags.2?ChatAdminRights = RequestPeerType;\nrequestPeerTypeBroadcast#339bef6c flags:# creator:flags.0?true has_username:flags.3?Bool user_admin_rights:flags.1?ChatAdminRights bot_admin_rights:flags.2?ChatAdminRights = RequestPeerType;\nemojiListNotModified#481eadfa = EmojiList;\nemojiList#7a1e11d1 hash:long document_id:Vector = EmojiList;\nemojiGroup#7a9abda9 title:string icon_emoji_id:long emoticons:Vector = EmojiGroup;\nmessages.emojiGroupsNotModified#6fb4ad87 = messages.EmojiGroups;\nmessages.emojiGroups#881fb94b hash:int groups:Vector = messages.EmojiGroups;\ntextWithEntities#751f3146 text:string entities:Vector = TextWithEntities;\nmessages.translateResult#33db32f8 result:Vector = messages.TranslatedText;\nautoSaveSettings#c84834ce flags:# photos:flags.0?true videos:flags.1?true video_max_size:flags.2?long = AutoSaveSettings;\nautoSaveException#81602d47 peer:Peer settings:AutoSaveSettings = AutoSaveException;\naccount.autoSaveSettings#4c3e069d users_settings:AutoSaveSettings chats_settings:AutoSaveSettings broadcasts_settings:AutoSaveSettings exceptions:Vector chats:Vector users:Vector = account.AutoSaveSettings;\nhelp.appConfigNotModified#7cde641d = help.AppConfig;\nhelp.appConfig#dd18782e hash:int config:JSONValue = help.AppConfig;\ninputBotAppID#a920bd7a id:long access_hash:long = InputBotApp;\ninputBotAppShortName#908c0407 bot_id:InputUser short_name:string = InputBotApp;\nbotAppNotModified#5da674b7 = BotApp;\nbotApp#95fcd1d6 flags:# id:long access_hash:long short_name:string title:string description:string photo:Photo document:flags.0?Document hash:long = BotApp;\nmessages.botApp#eb50adf5 flags:# inactive:flags.0?true request_write_access:flags.1?true app:BotApp = messages.BotApp;\nappWebViewResultUrl#3c1b4f0d url:string = AppWebViewResult;\ninlineBotWebView#b57295d5 text:string url:string = InlineBotWebView;\nreadParticipantDate#4a4ff172 user_id:long date:int = ReadParticipantDate;\ninputChatlistDialogFilter#f3e0da33 filter_id:int = InputChatlist;\nexportedChatlistInvite#c5181ac flags:# title:string url:string peers:Vector = ExportedChatlistInvite;\nchatlists.exportedChatlistInvite#10e6e3a6 filter:DialogFilter invite:ExportedChatlistInvite = chatlists.ExportedChatlistInvite;\nchatlists.exportedInvites#10ab6dc7 invites:Vector chats:Vector users:Vector = chatlists.ExportedInvites;\nchatlists.chatlistInviteAlready#fa87f659 filter_id:int missing_peers:Vector already_peers:Vector chats:Vector users:Vector = chatlists.ChatlistInvite;\nchatlists.chatlistInvite#1dcd839d flags:# title:string emoticon:flags.0?string peers:Vector chats:Vector users:Vector = chatlists.ChatlistInvite;\nchatlists.chatlistUpdates#93bd878d missing_peers:Vector chats:Vector users:Vector = chatlists.ChatlistUpdates;\nbots.botInfo#e8a775b0 name:string about:string description:string = bots.BotInfo;\n---functions---\ninvokeAfterMsg#cb9f372d {X:Type} msg_id:long query:!X = X;\ninvokeAfterMsgs#3dc4b4f0 {X:Type} msg_ids:Vector query:!X = X;\ninitConnection#c1cd5ea9 {X:Type} flags:# api_id:int device_model:string system_version:string app_version:string system_lang_code:string lang_pack:string lang_code:string proxy:flags.0?InputClientProxy params:flags.1?JSONValue query:!X = X;\ninvokeWithLayer#da9b0d0d {X:Type} layer:int query:!X = X;\ninvokeWithoutUpdates#bf9459b7 {X:Type} query:!X = X;\ninvokeWithMessagesRange#365275f2 {X:Type} range:MessageRange query:!X = X;\ninvokeWithTakeout#aca9fd2e {X:Type} takeout_id:long query:!X = X;\nauth.sendCode#a677244f phone_number:string api_id:int api_hash:string settings:CodeSettings = auth.SentCode;\nauth.signUp#80eee427 phone_number:string phone_code_hash:string first_name:string last_name:string = auth.Authorization;\nauth.signIn#8d52a951 flags:# phone_number:string phone_code_hash:string phone_code:flags.0?string email_verification:flags.1?EmailVerification = auth.Authorization;\nauth.logOut#3e72ba19 = auth.LoggedOut;\nauth.resetAuthorizations#9fab0d1a = Bool;\nauth.exportAuthorization#e5bfffcd dc_id:int = auth.ExportedAuthorization;\nauth.importAuthorization#a57a7dad id:long bytes:bytes = auth.Authorization;\nauth.bindTempAuthKey#cdd42a05 perm_auth_key_id:long nonce:long expires_at:int encrypted_message:bytes = Bool;\nauth.importBotAuthorization#67a3ff2c flags:int api_id:int api_hash:string bot_auth_token:string = auth.Authorization;\nauth.checkPassword#d18b4d16 password:InputCheckPasswordSRP = auth.Authorization;\nauth.requestPasswordRecovery#d897bc66 = auth.PasswordRecovery;\nauth.recoverPassword#37096c70 flags:# code:string new_settings:flags.0?account.PasswordInputSettings = auth.Authorization;\nauth.resendCode#3ef1a9bf phone_number:string phone_code_hash:string = auth.SentCode;\nauth.cancelCode#1f040578 phone_number:string phone_code_hash:string = Bool;\nauth.dropTempAuthKeys#8e48a188 except_auth_keys:Vector = Bool;\nauth.exportLoginToken#b7e085fe api_id:int api_hash:string except_ids:Vector = auth.LoginToken;\nauth.importLoginToken#95ac5ce4 token:bytes = auth.LoginToken;\nauth.acceptLoginToken#e894ad4d token:bytes = Authorization;\nauth.checkRecoveryPassword#d36bf79 code:string = Bool;\nauth.importWebTokenAuthorization#2db873a9 api_id:int api_hash:string web_auth_token:string = auth.Authorization;\nauth.requestFirebaseSms#89464b50 flags:# phone_number:string phone_code_hash:string safety_net_token:flags.0?string ios_push_secret:flags.1?string = Bool;\nauth.resetLoginEmail#7e960193 phone_number:string phone_code_hash:string = auth.SentCode;\naccount.registerDevice#ec86017a flags:# no_muted:flags.0?true token_type:int token:string app_sandbox:Bool secret:bytes other_uids:Vector = Bool;\naccount.unregisterDevice#6a0d3206 token_type:int token:string other_uids:Vector = Bool;\naccount.updateNotifySettings#84be5b93 peer:InputNotifyPeer settings:InputPeerNotifySettings = Bool;\naccount.getNotifySettings#12b3ad31 peer:InputNotifyPeer = PeerNotifySettings;\naccount.resetNotifySettings#db7e1747 = Bool;\naccount.updateProfile#78515775 flags:# first_name:flags.0?string last_name:flags.1?string about:flags.2?string = User;\naccount.updateStatus#6628562c offline:Bool = Bool;\naccount.getWallPapers#7967d36 hash:long = account.WallPapers;\naccount.reportPeer#c5ba3d86 peer:InputPeer reason:ReportReason message:string = Bool;\naccount.checkUsername#2714d86c username:string = Bool;\naccount.updateUsername#3e0bdd7c username:string = User;\naccount.getPrivacy#dadbc950 key:InputPrivacyKey = account.PrivacyRules;\naccount.setPrivacy#c9f81ce8 key:InputPrivacyKey rules:Vector = account.PrivacyRules;\naccount.deleteAccount#a2c0cf74 flags:# reason:string password:flags.0?InputCheckPasswordSRP = Bool;\naccount.getAccountTTL#8fc711d = AccountDaysTTL;\naccount.setAccountTTL#2442485e ttl:AccountDaysTTL = Bool;\naccount.sendChangePhoneCode#82574ae5 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.changePhone#70c32edb phone_number:string phone_code_hash:string phone_code:string = User;\naccount.updateDeviceLocked#38df3532 period:int = Bool;\naccount.getAuthorizations#e320c158 = account.Authorizations;\naccount.resetAuthorization#df77f3bc hash:long = Bool;\naccount.getPassword#548a30f5 = account.Password;\naccount.getPasswordSettings#9cd4eaf9 password:InputCheckPasswordSRP = account.PasswordSettings;\naccount.updatePasswordSettings#a59b102f password:InputCheckPasswordSRP new_settings:account.PasswordInputSettings = Bool;\naccount.sendConfirmPhoneCode#1b3faa88 hash:string settings:CodeSettings = auth.SentCode;\naccount.confirmPhone#5f2178c3 phone_code_hash:string phone_code:string = Bool;\naccount.getTmpPassword#449e0b51 password:InputCheckPasswordSRP period:int = account.TmpPassword;\naccount.getWebAuthorizations#182e6d6f = account.WebAuthorizations;\naccount.resetWebAuthorization#2d01b9ef hash:long = Bool;\naccount.resetWebAuthorizations#682d2594 = Bool;\naccount.getAllSecureValues#b288bc7d = Vector;\naccount.getSecureValue#73665bc2 types:Vector = Vector;\naccount.saveSecureValue#899fe31d value:InputSecureValue secure_secret_id:long = SecureValue;\naccount.deleteSecureValue#b880bc4b types:Vector = Bool;\naccount.getAuthorizationForm#a929597a bot_id:long scope:string public_key:string = account.AuthorizationForm;\naccount.acceptAuthorization#f3ed4c73 bot_id:long scope:string public_key:string value_hashes:Vector credentials:SecureCredentialsEncrypted = Bool;\naccount.sendVerifyPhoneCode#a5a356f9 phone_number:string settings:CodeSettings = auth.SentCode;\naccount.verifyPhone#4dd3a7f6 phone_number:string phone_code_hash:string phone_code:string = Bool;\naccount.sendVerifyEmailCode#98e037bb purpose:EmailVerifyPurpose email:string = account.SentEmailCode;\naccount.verifyEmail#32da4cf purpose:EmailVerifyPurpose verification:EmailVerification = account.EmailVerified;\naccount.initTakeoutSession#8ef3eab0 flags:# contacts:flags.0?true message_users:flags.1?true message_chats:flags.2?true message_megagroups:flags.3?true message_channels:flags.4?true files:flags.5?true file_max_size:flags.5?long = account.Takeout;\naccount.finishTakeoutSession#1d2652ee flags:# success:flags.0?true = Bool;\naccount.confirmPasswordEmail#8fdf1920 code:string = Bool;\naccount.resendPasswordEmail#7a7f2a15 = Bool;\naccount.cancelPasswordEmail#c1cbd5b6 = Bool;\naccount.getContactSignUpNotification#9f07c728 = Bool;\naccount.setContactSignUpNotification#cff43f61 silent:Bool = Bool;\naccount.getNotifyExceptions#53577479 flags:# compare_sound:flags.1?true peer:flags.0?InputNotifyPeer = Updates;\naccount.getWallPaper#fc8ddbea wallpaper:InputWallPaper = WallPaper;\naccount.uploadWallPaper#e39a8f03 flags:# for_chat:flags.0?true file:InputFile mime_type:string settings:WallPaperSettings = WallPaper;\naccount.saveWallPaper#6c5a5b37 wallpaper:InputWallPaper unsave:Bool settings:WallPaperSettings = Bool;\naccount.installWallPaper#feed5769 wallpaper:InputWallPaper settings:WallPaperSettings = Bool;\naccount.resetWallPapers#bb3b9804 = Bool;\naccount.getAutoDownloadSettings#56da0b3f = account.AutoDownloadSettings;\naccount.saveAutoDownloadSettings#76f36233 flags:# low:flags.0?true high:flags.1?true settings:AutoDownloadSettings = Bool;\naccount.uploadTheme#1c3db333 flags:# file:InputFile thumb:flags.0?InputFile file_name:string mime_type:string = Document;\naccount.createTheme#652e4400 flags:# slug:string title:string document:flags.2?InputDocument settings:flags.3?Vector = Theme;\naccount.updateTheme#2bf40ccc flags:# format:string theme:InputTheme slug:flags.0?string title:flags.1?string document:flags.2?InputDocument settings:flags.3?Vector = Theme;\naccount.saveTheme#f257106c theme:InputTheme unsave:Bool = Bool;\naccount.installTheme#c727bb3b flags:# dark:flags.0?true theme:flags.1?InputTheme format:flags.2?string base_theme:flags.3?BaseTheme = Bool;\naccount.getTheme#3a5869ec format:string theme:InputTheme = Theme;\naccount.getThemes#7206e458 format:string hash:long = account.Themes;\naccount.setContentSettings#b574b16b flags:# sensitive_enabled:flags.0?true = Bool;\naccount.getContentSettings#8b9b4dae = account.ContentSettings;\naccount.getMultiWallPapers#65ad71dc wallpapers:Vector = Vector;\naccount.getGlobalPrivacySettings#eb2b4cf6 = GlobalPrivacySettings;\naccount.setGlobalPrivacySettings#1edaaac2 settings:GlobalPrivacySettings = GlobalPrivacySettings;\naccount.reportProfilePhoto#fa8cc6f5 peer:InputPeer photo_id:InputPhoto reason:ReportReason message:string = Bool;\naccount.resetPassword#9308ce1b = account.ResetPasswordResult;\naccount.declinePasswordReset#4c9409f6 = Bool;\naccount.getChatThemes#d638de89 hash:long = account.Themes;\naccount.setAuthorizationTTL#bf899aa0 authorization_ttl_days:int = Bool;\naccount.changeAuthorizationSettings#40f48462 flags:# hash:long encrypted_requests_disabled:flags.0?Bool call_requests_disabled:flags.1?Bool = Bool;\naccount.getSavedRingtones#e1902288 hash:long = account.SavedRingtones;\naccount.saveRingtone#3dea5b03 id:InputDocument unsave:Bool = account.SavedRingtone;\naccount.uploadRingtone#831a83a2 file:InputFile file_name:string mime_type:string = Document;\naccount.updateEmojiStatus#fbd3de6b emoji_status:EmojiStatus = Bool;\naccount.getDefaultEmojiStatuses#d6753386 hash:long = account.EmojiStatuses;\naccount.getRecentEmojiStatuses#f578105 hash:long = account.EmojiStatuses;\naccount.clearRecentEmojiStatuses#18201aae = Bool;\naccount.reorderUsernames#ef500eab order:Vector = Bool;\naccount.toggleUsername#58d6b376 username:string active:Bool = Bool;\naccount.getDefaultProfilePhotoEmojis#e2750328 hash:long = EmojiList;\naccount.getDefaultGroupPhotoEmojis#915860ae hash:long = EmojiList;\naccount.getAutoSaveSettings#adcbbcda = account.AutoSaveSettings;\naccount.saveAutoSaveSettings#d69b8361 flags:# users:flags.0?true chats:flags.1?true broadcasts:flags.2?true peer:flags.3?InputPeer settings:AutoSaveSettings = Bool;\naccount.deleteAutoSaveExceptions#53bc0020 = Bool;\nusers.getUsers#d91a548 id:Vector = Vector;\nusers.getFullUser#b60f5918 id:InputUser = users.UserFull;\nusers.setSecureValueErrors#90c894b5 id:InputUser errors:Vector = Bool;\ncontacts.getContactIDs#7adc669d hash:long = Vector;\ncontacts.getStatuses#c4a353ee = Vector;\ncontacts.getContacts#5dd69e12 hash:long = contacts.Contacts;\ncontacts.importContacts#2c800be5 contacts:Vector = contacts.ImportedContacts;\ncontacts.deleteContacts#96a0e00 id:Vector = Updates;\ncontacts.deleteByPhones#1013fd9e phones:Vector = Bool;\ncontacts.block#68cc1411 id:InputPeer = Bool;\ncontacts.unblock#bea65d50 id:InputPeer = Bool;\ncontacts.getBlocked#f57c350f offset:int limit:int = contacts.Blocked;\ncontacts.search#11f812d8 q:string limit:int = contacts.Found;\ncontacts.resolveUsername#f93ccba3 username:string = contacts.ResolvedPeer;\ncontacts.getTopPeers#973478b6 flags:# correspondents:flags.0?true bots_pm:flags.1?true bots_inline:flags.2?true phone_calls:flags.3?true forward_users:flags.4?true forward_chats:flags.5?true groups:flags.10?true channels:flags.15?true offset:int limit:int hash:long = contacts.TopPeers;\ncontacts.resetTopPeerRating#1ae373ac category:TopPeerCategory peer:InputPeer = Bool;\ncontacts.resetSaved#879537f1 = Bool;\ncontacts.getSaved#82f1e39f = Vector;\ncontacts.toggleTopPeers#8514bdda enabled:Bool = Bool;\ncontacts.addContact#e8f463d0 flags:# add_phone_privacy_exception:flags.0?true id:InputUser first_name:string last_name:string phone:string = Updates;\ncontacts.acceptContact#f831a20f id:InputUser = Updates;\ncontacts.getLocated#d348bc44 flags:# background:flags.1?true geo_point:InputGeoPoint self_expires:flags.0?int = Updates;\ncontacts.blockFromReplies#29a8962c flags:# delete_message:flags.0?true delete_history:flags.1?true report_spam:flags.2?true msg_id:int = Updates;\ncontacts.resolvePhone#8af94344 phone:string = contacts.ResolvedPeer;\ncontacts.exportContactToken#f8654027 = ExportedContactToken;\ncontacts.importContactToken#13005788 token:string = User;\nmessages.getMessages#63c66506 id:Vector = messages.Messages;\nmessages.getDialogs#a0f4cb4f flags:# exclude_pinned:flags.0?true folder_id:flags.1?int offset_date:int offset_id:int offset_peer:InputPeer limit:int hash:long = messages.Dialogs;\nmessages.getHistory#4423e6c5 peer:InputPeer offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.search#a0fda762 flags:# peer:InputPeer q:string from_id:flags.0?InputPeer top_msg_id:flags.1?int filter:MessagesFilter min_date:int max_date:int offset_id:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.readHistory#e306d3a peer:InputPeer max_id:int = messages.AffectedMessages;\nmessages.deleteHistory#b08f922a flags:# just_clear:flags.0?true revoke:flags.1?true peer:InputPeer max_id:int min_date:flags.2?int max_date:flags.3?int = messages.AffectedHistory;\nmessages.deleteMessages#e58e95d2 flags:# revoke:flags.0?true id:Vector = messages.AffectedMessages;\nmessages.receivedMessages#5a954c0 max_id:int = Vector;\nmessages.setTyping#58943ee2 flags:# peer:InputPeer top_msg_id:flags.0?int action:SendMessageAction = Bool;\nmessages.sendMessage#1cc20387 flags:# no_webpage:flags.1?true silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true update_stickersets_order:flags.15?true peer:InputPeer reply_to_msg_id:flags.0?int top_msg_id:flags.9?int message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.sendMedia#7547c966 flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true update_stickersets_order:flags.15?true peer:InputPeer reply_to_msg_id:flags.0?int top_msg_id:flags.9?int media:InputMedia message:string random_id:long reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.forwardMessages#c661bbc4 flags:# silent:flags.5?true background:flags.6?true with_my_score:flags.8?true drop_author:flags.11?true drop_media_captions:flags.12?true noforwards:flags.14?true from_peer:InputPeer id:Vector random_id:Vector to_peer:InputPeer top_msg_id:flags.9?int schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.reportSpam#cf1592db peer:InputPeer = Bool;\nmessages.getPeerSettings#efd9a6a2 peer:InputPeer = messages.PeerSettings;\nmessages.report#8953ab4e peer:InputPeer id:Vector reason:ReportReason message:string = Bool;\nmessages.getChats#49e9528f id:Vector = messages.Chats;\nmessages.getFullChat#aeb00b34 chat_id:long = messages.ChatFull;\nmessages.editChatTitle#73783ffd chat_id:long title:string = Updates;\nmessages.editChatPhoto#35ddd674 chat_id:long photo:InputChatPhoto = Updates;\nmessages.addChatUser#f24753e3 chat_id:long user_id:InputUser fwd_limit:int = Updates;\nmessages.deleteChatUser#a2185cab flags:# revoke_history:flags.0?true chat_id:long user_id:InputUser = Updates;\nmessages.createChat#34a818 flags:# users:Vector title:string ttl_period:flags.0?int = Updates;\nmessages.getDhConfig#26cf8950 version:int random_length:int = messages.DhConfig;\nmessages.requestEncryption#f64daf43 user_id:InputUser random_id:int g_a:bytes = EncryptedChat;\nmessages.acceptEncryption#3dbc0415 peer:InputEncryptedChat g_b:bytes key_fingerprint:long = EncryptedChat;\nmessages.discardEncryption#f393aea0 flags:# delete_history:flags.0?true chat_id:int = Bool;\nmessages.setEncryptedTyping#791451ed peer:InputEncryptedChat typing:Bool = Bool;\nmessages.readEncryptedHistory#7f4b690a peer:InputEncryptedChat max_date:int = Bool;\nmessages.sendEncrypted#44fa7a15 flags:# silent:flags.0?true peer:InputEncryptedChat random_id:long data:bytes = messages.SentEncryptedMessage;\nmessages.sendEncryptedFile#5559481d flags:# silent:flags.0?true peer:InputEncryptedChat random_id:long data:bytes file:InputEncryptedFile = messages.SentEncryptedMessage;\nmessages.sendEncryptedService#32d439a4 peer:InputEncryptedChat random_id:long data:bytes = messages.SentEncryptedMessage;\nmessages.receivedQueue#55a5bb66 max_qts:int = Vector;\nmessages.reportEncryptedSpam#4b0c8c0f peer:InputEncryptedChat = Bool;\nmessages.readMessageContents#36a73f77 id:Vector = messages.AffectedMessages;\nmessages.getStickers#d5a5d3a1 emoticon:string hash:long = messages.Stickers;\nmessages.getAllStickers#b8a0a1a8 hash:long = messages.AllStickers;\nmessages.getWebPagePreview#8b68b0cc flags:# message:string entities:flags.3?Vector = MessageMedia;\nmessages.exportChatInvite#a02ce5d5 flags:# legacy_revoke_permanent:flags.2?true request_needed:flags.3?true peer:InputPeer expire_date:flags.0?int usage_limit:flags.1?int title:flags.4?string = ExportedChatInvite;\nmessages.checkChatInvite#3eadb1bb hash:string = ChatInvite;\nmessages.importChatInvite#6c50051c hash:string = Updates;\nmessages.getStickerSet#c8a0ec74 stickerset:InputStickerSet hash:int = messages.StickerSet;\nmessages.installStickerSet#c78fe460 stickerset:InputStickerSet archived:Bool = messages.StickerSetInstallResult;\nmessages.uninstallStickerSet#f96e55de stickerset:InputStickerSet = Bool;\nmessages.startBot#e6df7378 bot:InputUser peer:InputPeer random_id:long start_param:string = Updates;\nmessages.getMessagesViews#5784d3e1 peer:InputPeer id:Vector increment:Bool = messages.MessageViews;\nmessages.editChatAdmin#a85bd1c2 chat_id:long user_id:InputUser is_admin:Bool = Bool;\nmessages.migrateChat#a2875319 chat_id:long = Updates;\nmessages.searchGlobal#4bc6589a flags:# folder_id:flags.0?int q:string filter:MessagesFilter min_date:int max_date:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nmessages.reorderStickerSets#78337739 flags:# masks:flags.0?true emojis:flags.1?true order:Vector = Bool;\nmessages.getDocumentByHash#b1f2061f sha256:bytes size:long mime_type:string = Document;\nmessages.getSavedGifs#5cf09635 hash:long = messages.SavedGifs;\nmessages.saveGif#327a30cb id:InputDocument unsave:Bool = Bool;\nmessages.getInlineBotResults#514e999d flags:# bot:InputUser peer:InputPeer geo_point:flags.0?InputGeoPoint query:string offset:string = messages.BotResults;\nmessages.setInlineBotResults#bb12a419 flags:# gallery:flags.0?true private:flags.1?true query_id:long results:Vector cache_time:int next_offset:flags.2?string switch_pm:flags.3?InlineBotSwitchPM switch_webview:flags.4?InlineBotWebView = Bool;\nmessages.sendInlineBotResult#d3fbdccb flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true hide_via:flags.11?true peer:InputPeer reply_to_msg_id:flags.0?int top_msg_id:flags.9?int random_id:long query_id:long id:string schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.getMessageEditData#fda68d36 peer:InputPeer id:int = messages.MessageEditData;\nmessages.editMessage#48f71778 flags:# no_webpage:flags.1?true peer:InputPeer id:int message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector schedule_date:flags.15?int = Updates;\nmessages.editInlineBotMessage#83557dba flags:# no_webpage:flags.1?true id:InputBotInlineMessageID message:flags.11?string media:flags.14?InputMedia reply_markup:flags.2?ReplyMarkup entities:flags.3?Vector = Bool;\nmessages.getBotCallbackAnswer#9342ca07 flags:# game:flags.1?true peer:InputPeer msg_id:int data:flags.0?bytes password:flags.2?InputCheckPasswordSRP = messages.BotCallbackAnswer;\nmessages.setBotCallbackAnswer#d58f130a flags:# alert:flags.1?true query_id:long message:flags.0?string url:flags.2?string cache_time:int = Bool;\nmessages.getPeerDialogs#e470bcfd peers:Vector = messages.PeerDialogs;\nmessages.saveDraft#b4331e3f flags:# no_webpage:flags.1?true reply_to_msg_id:flags.0?int top_msg_id:flags.2?int peer:InputPeer message:string entities:flags.3?Vector = Bool;\nmessages.getAllDrafts#6a3f8d65 = Updates;\nmessages.getFeaturedStickers#64780b14 hash:long = messages.FeaturedStickers;\nmessages.readFeaturedStickers#5b118126 id:Vector = Bool;\nmessages.getRecentStickers#9da9403b flags:# attached:flags.0?true hash:long = messages.RecentStickers;\nmessages.saveRecentSticker#392718f8 flags:# attached:flags.0?true id:InputDocument unsave:Bool = Bool;\nmessages.clearRecentStickers#8999602d flags:# attached:flags.0?true = Bool;\nmessages.getArchivedStickers#57f17692 flags:# masks:flags.0?true emojis:flags.1?true offset_id:long limit:int = messages.ArchivedStickers;\nmessages.getMaskStickers#640f82b8 hash:long = messages.AllStickers;\nmessages.getAttachedStickers#cc5b67cc media:InputStickeredMedia = Vector;\nmessages.setGameScore#8ef8ecc0 flags:# edit_message:flags.0?true force:flags.1?true peer:InputPeer id:int user_id:InputUser score:int = Updates;\nmessages.setInlineGameScore#15ad9f64 flags:# edit_message:flags.0?true force:flags.1?true id:InputBotInlineMessageID user_id:InputUser score:int = Bool;\nmessages.getGameHighScores#e822649d peer:InputPeer id:int user_id:InputUser = messages.HighScores;\nmessages.getInlineGameHighScores#f635e1b id:InputBotInlineMessageID user_id:InputUser = messages.HighScores;\nmessages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats;\nmessages.getAllChats#875f74be except_ids:Vector = messages.Chats;\nmessages.getWebPage#32ca8f91 url:string hash:int = WebPage;\nmessages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool;\nmessages.reorderPinnedDialogs#3b1adf37 flags:# force:flags.0?true folder_id:int order:Vector = Bool;\nmessages.getPinnedDialogs#d6b94df2 folder_id:int = messages.PeerDialogs;\nmessages.setBotShippingResults#e5f672fa flags:# query_id:long error:flags.0?string shipping_options:flags.1?Vector = Bool;\nmessages.setBotPrecheckoutResults#9c2dd95 flags:# success:flags.1?true query_id:long error:flags.0?string = Bool;\nmessages.uploadMedia#519bc2b1 peer:InputPeer media:InputMedia = MessageMedia;\nmessages.sendScreenshotNotification#c97df020 peer:InputPeer reply_to_msg_id:int random_id:long = Updates;\nmessages.getFavedStickers#4f1aaa9 hash:long = messages.FavedStickers;\nmessages.faveSticker#b9ffc55b id:InputDocument unfave:Bool = Bool;\nmessages.getUnreadMentions#f107e790 flags:# peer:InputPeer top_msg_id:flags.0?int offset_id:int add_offset:int limit:int max_id:int min_id:int = messages.Messages;\nmessages.readMentions#36e5bf4d flags:# peer:InputPeer top_msg_id:flags.0?int = messages.AffectedHistory;\nmessages.getRecentLocations#702a40e0 peer:InputPeer limit:int hash:long = messages.Messages;\nmessages.sendMultiMedia#b6f11a1c flags:# silent:flags.5?true background:flags.6?true clear_draft:flags.7?true noforwards:flags.14?true update_stickersets_order:flags.15?true peer:InputPeer reply_to_msg_id:flags.0?int top_msg_id:flags.9?int multi_media:Vector schedule_date:flags.10?int send_as:flags.13?InputPeer = Updates;\nmessages.uploadEncryptedFile#5057c497 peer:InputEncryptedChat file:InputEncryptedFile = EncryptedFile;\nmessages.searchStickerSets#35705b8a flags:# exclude_featured:flags.0?true q:string hash:long = messages.FoundStickerSets;\nmessages.getSplitRanges#1cff7e08 = Vector;\nmessages.markDialogUnread#c286d98f flags:# unread:flags.0?true peer:InputDialogPeer = Bool;\nmessages.getDialogUnreadMarks#22e24e22 = Vector;\nmessages.clearAllDrafts#7e58ee9c = Bool;\nmessages.updatePinnedMessage#d2aaf7ec flags:# silent:flags.0?true unpin:flags.1?true pm_oneside:flags.2?true peer:InputPeer id:int = Updates;\nmessages.sendVote#10ea6184 peer:InputPeer msg_id:int options:Vector = Updates;\nmessages.getPollResults#73bb643b peer:InputPeer msg_id:int = Updates;\nmessages.getOnlines#6e2be050 peer:InputPeer = ChatOnlines;\nmessages.editChatAbout#def60797 peer:InputPeer about:string = Bool;\nmessages.editChatDefaultBannedRights#a5866b41 peer:InputPeer banned_rights:ChatBannedRights = Updates;\nmessages.getEmojiKeywords#35a0e062 lang_code:string = EmojiKeywordsDifference;\nmessages.getEmojiKeywordsDifference#1508b6af lang_code:string from_version:int = EmojiKeywordsDifference;\nmessages.getEmojiKeywordsLanguages#4e9963b2 lang_codes:Vector = Vector;\nmessages.getEmojiURL#d5b10c26 lang_code:string = EmojiURL;\nmessages.getSearchCounters#ae7cc1 flags:# peer:InputPeer top_msg_id:flags.0?int filters:Vector = Vector;\nmessages.requestUrlAuth#198fb446 flags:# peer:flags.1?InputPeer msg_id:flags.1?int button_id:flags.1?int url:flags.2?string = UrlAuthResult;\nmessages.acceptUrlAuth#b12c7125 flags:# write_allowed:flags.0?true peer:flags.1?InputPeer msg_id:flags.1?int button_id:flags.1?int url:flags.2?string = UrlAuthResult;\nmessages.hidePeerSettingsBar#4facb138 peer:InputPeer = Bool;\nmessages.getScheduledHistory#f516760b peer:InputPeer hash:long = messages.Messages;\nmessages.getScheduledMessages#bdbb0464 peer:InputPeer id:Vector = messages.Messages;\nmessages.sendScheduledMessages#bd38850a peer:InputPeer id:Vector = Updates;\nmessages.deleteScheduledMessages#59ae2b16 peer:InputPeer id:Vector = Updates;\nmessages.getPollVotes#b86e380e flags:# peer:InputPeer id:int option:flags.0?bytes offset:flags.1?string limit:int = messages.VotesList;\nmessages.toggleStickerSets#b5052fea flags:# uninstall:flags.0?true archive:flags.1?true unarchive:flags.2?true stickersets:Vector = Bool;\nmessages.getDialogFilters#f19ed96d = Vector;\nmessages.getSuggestedDialogFilters#a29cd42c = Vector;\nmessages.updateDialogFilter#1ad4a04a flags:# id:int filter:flags.0?DialogFilter = Bool;\nmessages.updateDialogFiltersOrder#c563c1e4 order:Vector = Bool;\nmessages.getOldFeaturedStickers#7ed094a1 offset:int limit:int hash:long = messages.FeaturedStickers;\nmessages.getReplies#22ddd30c peer:InputPeer msg_id:int offset_id:int offset_date:int add_offset:int limit:int max_id:int min_id:int hash:long = messages.Messages;\nmessages.getDiscussionMessage#446972fd peer:InputPeer msg_id:int = messages.DiscussionMessage;\nmessages.readDiscussion#f731a9f4 peer:InputPeer msg_id:int read_max_id:int = Bool;\nmessages.unpinAllMessages#ee22b9a8 flags:# peer:InputPeer top_msg_id:flags.0?int = messages.AffectedHistory;\nmessages.deleteChat#5bd0ee50 chat_id:long = Bool;\nmessages.deletePhoneCallHistory#f9cbe409 flags:# revoke:flags.0?true = messages.AffectedFoundMessages;\nmessages.checkHistoryImport#43fe19f3 import_head:string = messages.HistoryImportParsed;\nmessages.initHistoryImport#34090c3b peer:InputPeer file:InputFile media_count:int = messages.HistoryImport;\nmessages.uploadImportedMedia#2a862092 peer:InputPeer import_id:long file_name:string media:InputMedia = MessageMedia;\nmessages.startHistoryImport#b43df344 peer:InputPeer import_id:long = Bool;\nmessages.getExportedChatInvites#a2b5a3f6 flags:# revoked:flags.3?true peer:InputPeer admin_id:InputUser offset_date:flags.2?int offset_link:flags.2?string limit:int = messages.ExportedChatInvites;\nmessages.getExportedChatInvite#73746f5c peer:InputPeer link:string = messages.ExportedChatInvite;\nmessages.editExportedChatInvite#bdca2f75 flags:# revoked:flags.2?true peer:InputPeer link:string expire_date:flags.0?int usage_limit:flags.1?int request_needed:flags.3?Bool title:flags.4?string = messages.ExportedChatInvite;\nmessages.deleteRevokedExportedChatInvites#56987bd5 peer:InputPeer admin_id:InputUser = Bool;\nmessages.deleteExportedChatInvite#d464a42b peer:InputPeer link:string = Bool;\nmessages.getAdminsWithInvites#3920e6ef peer:InputPeer = messages.ChatAdminsWithInvites;\nmessages.getChatInviteImporters#df04dd4e flags:# requested:flags.0?true peer:InputPeer link:flags.1?string q:flags.2?string offset_date:int offset_user:InputUser limit:int = messages.ChatInviteImporters;\nmessages.setHistoryTTL#b80e5fe4 peer:InputPeer period:int = Updates;\nmessages.checkHistoryImportPeer#5dc60f03 peer:InputPeer = messages.CheckedHistoryImportPeer;\nmessages.setChatTheme#e63be13f peer:InputPeer emoticon:string = Updates;\nmessages.getMessageReadParticipants#31c1c44f peer:InputPeer msg_id:int = Vector;\nmessages.getSearchResultsCalendar#49f0bde9 peer:InputPeer filter:MessagesFilter offset_id:int offset_date:int = messages.SearchResultsCalendar;\nmessages.getSearchResultsPositions#6e9583a3 peer:InputPeer filter:MessagesFilter offset_id:int limit:int = messages.SearchResultsPositions;\nmessages.hideChatJoinRequest#7fe7e815 flags:# approved:flags.0?true peer:InputPeer user_id:InputUser = Updates;\nmessages.hideAllChatJoinRequests#e085f4ea flags:# approved:flags.0?true peer:InputPeer link:flags.1?string = Updates;\nmessages.toggleNoForwards#b11eafa2 peer:InputPeer enabled:Bool = Updates;\nmessages.saveDefaultSendAs#ccfddf96 peer:InputPeer send_as:InputPeer = Bool;\nmessages.sendReaction#d30d78d4 flags:# big:flags.1?true add_to_recent:flags.2?true peer:InputPeer msg_id:int reaction:flags.0?Vector = Updates;\nmessages.getMessagesReactions#8bba90e6 peer:InputPeer id:Vector = Updates;\nmessages.getMessageReactionsList#461b3f48 flags:# peer:InputPeer id:int reaction:flags.0?Reaction offset:flags.1?string limit:int = messages.MessageReactionsList;\nmessages.setChatAvailableReactions#feb16771 peer:InputPeer available_reactions:ChatReactions = Updates;\nmessages.getAvailableReactions#18dea0ac hash:int = messages.AvailableReactions;\nmessages.setDefaultReaction#4f47a016 reaction:Reaction = Bool;\nmessages.translateText#63183030 flags:# peer:flags.0?InputPeer id:flags.0?Vector text:flags.1?Vector to_lang:string = messages.TranslatedText;\nmessages.getUnreadReactions#3223495b flags:# peer:InputPeer top_msg_id:flags.0?int offset_id:int add_offset:int limit:int max_id:int min_id:int = messages.Messages;\nmessages.readReactions#54aa7f8e flags:# peer:InputPeer top_msg_id:flags.0?int = messages.AffectedHistory;\nmessages.searchSentMedia#107e31a0 q:string filter:MessagesFilter limit:int = messages.Messages;\nmessages.getAttachMenuBots#16fcc2cb hash:long = AttachMenuBots;\nmessages.getAttachMenuBot#77216192 bot:InputUser = AttachMenuBotsBot;\nmessages.toggleBotInAttachMenu#69f59d69 flags:# write_allowed:flags.0?true bot:InputUser enabled:Bool = Bool;\nmessages.requestWebView#178b480b flags:# from_bot_menu:flags.4?true silent:flags.5?true peer:InputPeer bot:InputUser url:flags.1?string start_param:flags.3?string theme_params:flags.2?DataJSON platform:string reply_to_msg_id:flags.0?int top_msg_id:flags.9?int send_as:flags.13?InputPeer = WebViewResult;\nmessages.prolongWebView#7ff34309 flags:# silent:flags.5?true peer:InputPeer bot:InputUser query_id:long reply_to_msg_id:flags.0?int top_msg_id:flags.9?int send_as:flags.13?InputPeer = Bool;\nmessages.requestSimpleWebView#299bec8e flags:# from_switch_webview:flags.1?true bot:InputUser url:string theme_params:flags.0?DataJSON platform:string = SimpleWebViewResult;\nmessages.sendWebViewResultMessage#a4314f5 bot_query_id:string result:InputBotInlineResult = WebViewMessageSent;\nmessages.sendWebViewData#dc0242c8 bot:InputUser random_id:long button_text:string data:string = Updates;\nmessages.transcribeAudio#269e9a49 peer:InputPeer msg_id:int = messages.TranscribedAudio;\nmessages.rateTranscribedAudio#7f1d072f peer:InputPeer msg_id:int transcription_id:long good:Bool = Bool;\nmessages.getCustomEmojiDocuments#d9ab0f54 document_id:Vector = Vector;\nmessages.getEmojiStickers#fbfca18f hash:long = messages.AllStickers;\nmessages.getFeaturedEmojiStickers#ecf6736 hash:long = messages.FeaturedStickers;\nmessages.reportReaction#3f64c076 peer:InputPeer id:int reaction_peer:InputPeer = Bool;\nmessages.getTopReactions#bb8125ba limit:int hash:long = messages.Reactions;\nmessages.getRecentReactions#39461db2 limit:int hash:long = messages.Reactions;\nmessages.clearRecentReactions#9dfeefb4 = Bool;\nmessages.getExtendedMedia#84f80814 peer:InputPeer id:Vector = Updates;\nmessages.setDefaultHistoryTTL#9eb51445 period:int = Bool;\nmessages.getDefaultHistoryTTL#658b7188 = DefaultHistoryTTL;\nmessages.sendBotRequestedPeer#fe38d01b peer:InputPeer msg_id:int button_id:int requested_peer:InputPeer = Updates;\nmessages.getEmojiGroups#7488ce5b hash:int = messages.EmojiGroups;\nmessages.getEmojiStatusGroups#2ecd56cd hash:int = messages.EmojiGroups;\nmessages.getEmojiProfilePhotoGroups#21a548f3 hash:int = messages.EmojiGroups;\nmessages.searchCustomEmoji#2c11c0d7 emoticon:string hash:long = EmojiList;\nmessages.togglePeerTranslations#e47cb579 flags:# disabled:flags.0?true peer:InputPeer = Bool;\nmessages.getBotApp#34fdc5c3 app:InputBotApp hash:long = messages.BotApp;\nmessages.requestAppWebView#8c5a3b3c flags:# write_allowed:flags.0?true peer:InputPeer app:InputBotApp start_param:flags.1?string theme_params:flags.2?DataJSON platform:string = AppWebViewResult;\nmessages.setChatWallPaper#8ffacae1 flags:# peer:InputPeer wallpaper:flags.0?InputWallPaper settings:flags.2?WallPaperSettings id:flags.1?int = Updates;\nupdates.getState#edd4882a = updates.State;\nupdates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference;\nupdates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference;\nphotos.updateProfilePhoto#9e82039 flags:# fallback:flags.0?true bot:flags.1?InputUser id:InputPhoto = photos.Photo;\nphotos.uploadProfilePhoto#388a3b5 flags:# fallback:flags.3?true bot:flags.5?InputUser file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double video_emoji_markup:flags.4?VideoSize = photos.Photo;\nphotos.deletePhotos#87cf7f2f id:Vector = Vector;\nphotos.getUserPhotos#91cd32a8 user_id:InputUser offset:int max_id:long limit:int = photos.Photos;\nphotos.uploadContactProfilePhoto#e14c4a71 flags:# suggest:flags.3?true save:flags.4?true user_id:InputUser file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double video_emoji_markup:flags.5?VideoSize = photos.Photo;\nupload.saveFilePart#b304a621 file_id:long file_part:int bytes:bytes = Bool;\nupload.getFile#be5335be flags:# precise:flags.0?true cdn_supported:flags.1?true location:InputFileLocation offset:long limit:int = upload.File;\nupload.saveBigFilePart#de7b673d file_id:long file_part:int file_total_parts:int bytes:bytes = Bool;\nupload.getWebFile#24e6818d location:InputWebFileLocation offset:int limit:int = upload.WebFile;\nupload.getCdnFile#395f69da file_token:bytes offset:long limit:int = upload.CdnFile;\nupload.reuploadCdnFile#9b2754a8 file_token:bytes request_token:bytes = Vector;\nupload.getCdnFileHashes#91dc3f31 file_token:bytes offset:long = Vector;\nupload.getFileHashes#9156982a location:InputFileLocation offset:long = Vector;\nhelp.getConfig#c4f9186b = Config;\nhelp.getNearestDc#1fb33026 = NearestDc;\nhelp.getAppUpdate#522d5a7d source:string = help.AppUpdate;\nhelp.getInviteText#4d392343 = help.InviteText;\nhelp.getSupport#9cdf08cd = help.Support;\nhelp.getAppChangelog#9010ef6f prev_app_version:string = Updates;\nhelp.setBotUpdatesStatus#ec22cfcd pending_updates_count:int message:string = Bool;\nhelp.getCdnConfig#52029342 = CdnConfig;\nhelp.getRecentMeUrls#3dc0f114 referer:string = help.RecentMeUrls;\nhelp.getTermsOfServiceUpdate#2ca51fd1 = help.TermsOfServiceUpdate;\nhelp.acceptTermsOfService#ee72f79a id:DataJSON = Bool;\nhelp.getDeepLinkInfo#3fedc75f path:string = help.DeepLinkInfo;\nhelp.getAppConfig#61e3f854 hash:int = help.AppConfig;\nhelp.saveAppLog#6f02f748 events:Vector = Bool;\nhelp.getPassportConfig#c661ad08 hash:int = help.PassportConfig;\nhelp.getSupportName#d360e72c = help.SupportName;\nhelp.getUserInfo#38a08d3 user_id:InputUser = help.UserInfo;\nhelp.editUserInfo#66b91b70 user_id:InputUser message:string entities:Vector = help.UserInfo;\nhelp.getPromoData#c0977421 = help.PromoData;\nhelp.hidePromoData#1e251c95 peer:InputPeer = Bool;\nhelp.dismissSuggestion#f50dbaa1 peer:InputPeer suggestion:string = Bool;\nhelp.getCountriesList#735787a8 lang_code:string hash:int = help.CountriesList;\nhelp.getPremiumPromo#b81b93d4 = help.PremiumPromo;\nchannels.readHistory#cc104937 channel:InputChannel max_id:int = Bool;\nchannels.deleteMessages#84c1fd4e channel:InputChannel id:Vector = messages.AffectedMessages;\nchannels.reportSpam#f44a8315 channel:InputChannel participant:InputPeer id:Vector = Bool;\nchannels.getMessages#ad8c9a23 channel:InputChannel id:Vector = messages.Messages;\nchannels.getParticipants#77ced9d0 channel:InputChannel filter:ChannelParticipantsFilter offset:int limit:int hash:long = channels.ChannelParticipants;\nchannels.getParticipant#a0ab6cc6 channel:InputChannel participant:InputPeer = channels.ChannelParticipant;\nchannels.getChannels#a7f6bbb id:Vector = messages.Chats;\nchannels.getFullChannel#8736a09 channel:InputChannel = messages.ChatFull;\nchannels.createChannel#91006707 flags:# broadcast:flags.0?true megagroup:flags.1?true for_import:flags.3?true forum:flags.5?true title:string about:string geo_point:flags.2?InputGeoPoint address:flags.2?string ttl_period:flags.4?int = Updates;\nchannels.editAdmin#d33c8902 channel:InputChannel user_id:InputUser admin_rights:ChatAdminRights rank:string = Updates;\nchannels.editTitle#566decd0 channel:InputChannel title:string = Updates;\nchannels.editPhoto#f12e57c9 channel:InputChannel photo:InputChatPhoto = Updates;\nchannels.checkUsername#10e6bd2c channel:InputChannel username:string = Bool;\nchannels.updateUsername#3514b3de channel:InputChannel username:string = Bool;\nchannels.joinChannel#24b524c5 channel:InputChannel = Updates;\nchannels.leaveChannel#f836aa95 channel:InputChannel = Updates;\nchannels.inviteToChannel#199f3a6c channel:InputChannel users:Vector = Updates;\nchannels.deleteChannel#c0111fe3 channel:InputChannel = Updates;\nchannels.exportMessageLink#e63fadeb flags:# grouped:flags.0?true thread:flags.1?true channel:InputChannel id:int = ExportedMessageLink;\nchannels.toggleSignatures#1f69b606 channel:InputChannel enabled:Bool = Updates;\nchannels.getAdminedPublicChannels#f8b036af flags:# by_location:flags.0?true check_limit:flags.1?true = messages.Chats;\nchannels.editBanned#96e6cd81 channel:InputChannel participant:InputPeer banned_rights:ChatBannedRights = Updates;\nchannels.getAdminLog#33ddf480 flags:# channel:InputChannel q:string events_filter:flags.0?ChannelAdminLogEventsFilter admins:flags.1?Vector max_id:long min_id:long limit:int = channels.AdminLogResults;\nchannels.setStickers#ea8ca4f9 channel:InputChannel stickerset:InputStickerSet = Bool;\nchannels.readMessageContents#eab5dc38 channel:InputChannel id:Vector = Bool;\nchannels.deleteHistory#9baa9647 flags:# for_everyone:flags.0?true channel:InputChannel max_id:int = Updates;\nchannels.togglePreHistoryHidden#eabbb94c channel:InputChannel enabled:Bool = Updates;\nchannels.getLeftChannels#8341ecc0 offset:int = messages.Chats;\nchannels.getGroupsForDiscussion#f5dad378 = messages.Chats;\nchannels.setDiscussionGroup#40582bb2 broadcast:InputChannel group:InputChannel = Bool;\nchannels.editCreator#8f38cd1f channel:InputChannel user_id:InputUser password:InputCheckPasswordSRP = Updates;\nchannels.editLocation#58e63f6d channel:InputChannel geo_point:InputGeoPoint address:string = Bool;\nchannels.toggleSlowMode#edd49ef0 channel:InputChannel seconds:int = Updates;\nchannels.getInactiveChannels#11e831ee = messages.InactiveChats;\nchannels.convertToGigagroup#b290c69 channel:InputChannel = Updates;\nchannels.viewSponsoredMessage#beaedb94 channel:InputChannel random_id:bytes = Bool;\nchannels.getSponsoredMessages#ec210fbf channel:InputChannel = messages.SponsoredMessages;\nchannels.getSendAs#dc770ee peer:InputPeer = channels.SendAsPeers;\nchannels.deleteParticipantHistory#367544db channel:InputChannel participant:InputPeer = messages.AffectedHistory;\nchannels.toggleJoinToSend#e4cb9580 channel:InputChannel enabled:Bool = Updates;\nchannels.toggleJoinRequest#4c2985b6 channel:InputChannel enabled:Bool = Updates;\nchannels.reorderUsernames#b45ced1d channel:InputChannel order:Vector = Bool;\nchannels.toggleUsername#50f24105 channel:InputChannel username:string active:Bool = Bool;\nchannels.deactivateAllUsernames#a245dd3 channel:InputChannel = Bool;\nchannels.toggleForum#a4298b29 channel:InputChannel enabled:Bool = Updates;\nchannels.createForumTopic#f40c0224 flags:# channel:InputChannel title:string icon_color:flags.0?int icon_emoji_id:flags.3?long random_id:long send_as:flags.2?InputPeer = Updates;\nchannels.getForumTopics#de560d1 flags:# channel:InputChannel q:flags.0?string offset_date:int offset_id:int offset_topic:int limit:int = messages.ForumTopics;\nchannels.getForumTopicsByID#b0831eb9 channel:InputChannel topics:Vector = messages.ForumTopics;\nchannels.editForumTopic#f4dfa185 flags:# channel:InputChannel topic_id:int title:flags.0?string icon_emoji_id:flags.1?long closed:flags.2?Bool hidden:flags.3?Bool = Updates;\nchannels.updatePinnedForumTopic#6c2d9026 channel:InputChannel topic_id:int pinned:Bool = Updates;\nchannels.deleteTopicHistory#34435f2d channel:InputChannel top_msg_id:int = messages.AffectedHistory;\nchannels.reorderPinnedForumTopics#2950a18f flags:# force:flags.0?true channel:InputChannel order:Vector = Updates;\nchannels.toggleAntiSpam#68f3e4eb channel:InputChannel enabled:Bool = Updates;\nchannels.reportAntiSpamFalsePositive#a850a693 channel:InputChannel msg_id:int = Bool;\nchannels.toggleParticipantsHidden#6a6e7854 channel:InputChannel enabled:Bool = Updates;\nbots.sendCustomRequest#aa2769ed custom_method:string params:DataJSON = DataJSON;\nbots.answerWebhookJSONQuery#e6213f4d query_id:long data:DataJSON = Bool;\nbots.setBotCommands#517165a scope:BotCommandScope lang_code:string commands:Vector = Bool;\nbots.resetBotCommands#3d8de0f9 scope:BotCommandScope lang_code:string = Bool;\nbots.getBotCommands#e34c0dd6 scope:BotCommandScope lang_code:string = Vector;\nbots.setBotMenuButton#4504d54f user_id:InputUser button:BotMenuButton = Bool;\nbots.getBotMenuButton#9c60eb28 user_id:InputUser = BotMenuButton;\nbots.setBotBroadcastDefaultAdminRights#788464e1 admin_rights:ChatAdminRights = Bool;\nbots.setBotGroupDefaultAdminRights#925ec9ea admin_rights:ChatAdminRights = Bool;\nbots.setBotInfo#10cf3123 flags:# bot:flags.2?InputUser lang_code:string name:flags.3?string about:flags.0?string description:flags.1?string = Bool;\nbots.getBotInfo#dcd914fd flags:# bot:flags.0?InputUser lang_code:string = bots.BotInfo;\nbots.reorderUsernames#9709b1c2 bot:InputUser order:Vector = Bool;\nbots.toggleUsername#53ca973 bot:InputUser username:string active:Bool = Bool;\npayments.getPaymentForm#37148dbb flags:# invoice:InputInvoice theme_params:flags.0?DataJSON = payments.PaymentForm;\npayments.getPaymentReceipt#2478d1cc peer:InputPeer msg_id:int = payments.PaymentReceipt;\npayments.validateRequestedInfo#b6c8f12b flags:# save:flags.0?true invoice:InputInvoice info:PaymentRequestedInfo = payments.ValidatedRequestedInfo;\npayments.sendPaymentForm#2d03522f flags:# form_id:long invoice:InputInvoice requested_info_id:flags.0?string shipping_option_id:flags.1?string credentials:InputPaymentCredentials tip_amount:flags.2?long = payments.PaymentResult;\npayments.getSavedInfo#227d824b = payments.SavedInfo;\npayments.clearSavedInfo#d83d70c1 flags:# credentials:flags.0?true info:flags.1?true = Bool;\npayments.getBankCardData#2e79d779 number:string = payments.BankCardData;\npayments.exportInvoice#f91b065 invoice_media:InputMedia = payments.ExportedInvoice;\npayments.assignAppStoreTransaction#80ed747d receipt:bytes purpose:InputStorePaymentPurpose = Updates;\npayments.assignPlayMarketTransaction#dffd50d3 receipt:DataJSON purpose:InputStorePaymentPurpose = Updates;\npayments.canPurchasePremium#9fc19eb6 purpose:InputStorePaymentPurpose = Bool;\nstickers.createStickerSet#9021ab67 flags:# masks:flags.0?true animated:flags.1?true videos:flags.4?true emojis:flags.5?true text_color:flags.6?true user_id:InputUser title:string short_name:string thumb:flags.2?InputDocument stickers:Vector software:flags.3?string = messages.StickerSet;\nstickers.removeStickerFromSet#f7760f51 sticker:InputDocument = messages.StickerSet;\nstickers.changeStickerPosition#ffb6d4ca sticker:InputDocument position:int = messages.StickerSet;\nstickers.addStickerToSet#8653febe stickerset:InputStickerSet sticker:InputStickerSetItem = messages.StickerSet;\nstickers.setStickerSetThumb#a76a5392 flags:# stickerset:InputStickerSet thumb:flags.0?InputDocument thumb_document_id:flags.1?long = messages.StickerSet;\nstickers.checkShortName#284b3639 short_name:string = Bool;\nstickers.suggestShortName#4dafc503 title:string = stickers.SuggestedShortName;\nstickers.changeSticker#f5537ebc flags:# sticker:InputDocument emoji:flags.0?string mask_coords:flags.1?MaskCoords keywords:flags.2?string = messages.StickerSet;\nstickers.renameStickerSet#124b1c00 stickerset:InputStickerSet title:string = messages.StickerSet;\nstickers.deleteStickerSet#87704394 stickerset:InputStickerSet = Bool;\nphone.getCallConfig#55451fa9 = DataJSON;\nphone.requestCall#42ff96ed flags:# video:flags.0?true user_id:InputUser random_id:int g_a_hash:bytes protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.acceptCall#3bd2b4a0 peer:InputPhoneCall g_b:bytes protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.confirmCall#2efe1722 peer:InputPhoneCall g_a:bytes key_fingerprint:long protocol:PhoneCallProtocol = phone.PhoneCall;\nphone.receivedCall#17d54f61 peer:InputPhoneCall = Bool;\nphone.discardCall#b2cbc1c0 flags:# video:flags.0?true peer:InputPhoneCall duration:int reason:PhoneCallDiscardReason connection_id:long = Updates;\nphone.setCallRating#59ead627 flags:# user_initiative:flags.0?true peer:InputPhoneCall rating:int comment:string = Updates;\nphone.saveCallDebug#277add7e peer:InputPhoneCall debug:DataJSON = Bool;\nphone.sendSignalingData#ff7a9383 peer:InputPhoneCall data:bytes = Bool;\nphone.createGroupCall#48cdc6d8 flags:# rtmp_stream:flags.2?true peer:InputPeer random_id:int title:flags.0?string schedule_date:flags.1?int = Updates;\nphone.joinGroupCall#b132ff7b flags:# muted:flags.0?true video_stopped:flags.2?true call:InputGroupCall join_as:InputPeer invite_hash:flags.1?string params:DataJSON = Updates;\nphone.leaveGroupCall#500377f9 call:InputGroupCall source:int = Updates;\nphone.inviteToGroupCall#7b393160 call:InputGroupCall users:Vector = Updates;\nphone.discardGroupCall#7a777135 call:InputGroupCall = Updates;\nphone.toggleGroupCallSettings#74bbb43d flags:# reset_invite_hash:flags.1?true call:InputGroupCall join_muted:flags.0?Bool = Updates;\nphone.getGroupCall#41845db call:InputGroupCall limit:int = phone.GroupCall;\nphone.getGroupParticipants#c558d8ab call:InputGroupCall ids:Vector sources:Vector offset:string limit:int = phone.GroupParticipants;\nphone.checkGroupCall#b59cf977 call:InputGroupCall sources:Vector = Vector;\nphone.toggleGroupCallRecord#f128c708 flags:# start:flags.0?true video:flags.2?true call:InputGroupCall title:flags.1?string video_portrait:flags.2?Bool = Updates;\nphone.editGroupCallParticipant#a5273abf flags:# call:InputGroupCall participant:InputPeer muted:flags.0?Bool volume:flags.1?int raise_hand:flags.2?Bool video_stopped:flags.3?Bool video_paused:flags.4?Bool presentation_paused:flags.5?Bool = Updates;\nphone.editGroupCallTitle#1ca6ac0a call:InputGroupCall title:string = Updates;\nphone.getGroupCallJoinAs#ef7c213a peer:InputPeer = phone.JoinAsPeers;\nphone.exportGroupCallInvite#e6aa647f flags:# can_self_unmute:flags.0?true call:InputGroupCall = phone.ExportedGroupCallInvite;\nphone.toggleGroupCallStartSubscription#219c34e6 call:InputGroupCall subscribed:Bool = Updates;\nphone.startScheduledGroupCall#5680e342 call:InputGroupCall = Updates;\nphone.saveDefaultGroupCallJoinAs#575e1f8c peer:InputPeer join_as:InputPeer = Bool;\nphone.joinGroupCallPresentation#cbea6bc4 call:InputGroupCall params:DataJSON = Updates;\nphone.leaveGroupCallPresentation#1c50d144 call:InputGroupCall = Updates;\nphone.getGroupCallStreamChannels#1ab21940 call:InputGroupCall = phone.GroupCallStreamChannels;\nphone.getGroupCallStreamRtmpUrl#deb3abbf peer:InputPeer revoke:Bool = phone.GroupCallStreamRtmpUrl;\nphone.saveCallLog#41248786 peer:InputPhoneCall file:InputFile = Bool;\nlangpack.getLangPack#f2f2330a lang_pack:string lang_code:string = LangPackDifference;\nlangpack.getStrings#efea3803 lang_pack:string lang_code:string keys:Vector = Vector;\nlangpack.getDifference#cd984aa5 lang_pack:string lang_code:string from_version:int = LangPackDifference;\nlangpack.getLanguages#42c6978f lang_pack:string = Vector;\nlangpack.getLanguage#6a596502 lang_pack:string lang_code:string = LangPackLanguage;\nfolders.editPeerFolders#6847d0ab folder_peers:Vector = Updates;\nstats.getBroadcastStats#ab42441a flags:# dark:flags.0?true channel:InputChannel = stats.BroadcastStats;\nstats.loadAsyncGraph#621d5fa0 flags:# token:string x:flags.0?long = StatsGraph;\nstats.getMegagroupStats#dcdf8607 flags:# dark:flags.0?true channel:InputChannel = stats.MegagroupStats;\nstats.getMessagePublicForwards#5630281b channel:InputChannel msg_id:int offset_rate:int offset_peer:InputPeer offset_id:int limit:int = messages.Messages;\nstats.getMessageStats#b6e0a3f5 flags:# dark:flags.0?true channel:InputChannel msg_id:int = stats.MessageStats;\nchatlists.exportChatlistInvite#8472478e chatlist:InputChatlist title:string peers:Vector = chatlists.ExportedChatlistInvite;\nchatlists.deleteExportedInvite#719c5c5e chatlist:InputChatlist slug:string = Bool;\nchatlists.editExportedInvite#653db63d flags:# chatlist:InputChatlist slug:string title:flags.1?string peers:flags.2?Vector = ExportedChatlistInvite;\nchatlists.getExportedInvites#ce03da83 chatlist:InputChatlist = chatlists.ExportedInvites;\nchatlists.checkChatlistInvite#41c10fff slug:string = chatlists.ChatlistInvite;\nchatlists.joinChatlistInvite#a6b1e39a slug:string peers:Vector = Updates;\nchatlists.getChatlistUpdates#89419521 chatlist:InputChatlist = chatlists.ChatlistUpdates;\nchatlists.joinChatlistUpdates#e089f8f5 chatlist:InputChatlist peers:Vector = Updates;\nchatlists.hideChatlistUpdates#66e486fb chatlist:InputChatlist = Bool;\nchatlists.getLeaveChatlistSuggestions#fdbcd714 chatlist:InputChatlist = Vector;\nchatlists.leaveChatlist#74fae13a chatlist:InputChatlist peers:Vector = Updates;\n`;\n\n//# sourceURL=webpack://telegram/./browser/tl/apiTl.js?")},"./browser/tl/core/GZIPPacked.js": /*!***************************************!*\ !*** ./browser/tl/core/GZIPPacked.js ***! \***************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.GZIPPacked = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst __1 = __webpack_require__(/*! ../ */ "./browser/tl/index.js");\n\nconst pako_1 = __webpack_require__(/*! pako */ "./node_modules/pako/index.js");\n\nclass GZIPPacked {\n constructor(data) {\n this.data = data;\n this.CONSTRUCTOR_ID = 0x3072cfa1;\n this.classType = "constructor";\n }\n\n static async gzipIfSmaller(contentRelated, data) {\n if (contentRelated && data.length > 512) {\n const gzipped = await new GZIPPacked(data).toBytes();\n\n if (gzipped.length < data.length) {\n return gzipped;\n }\n }\n\n return data;\n }\n\n static gzip(input) {\n return buffer_1.Buffer.from(input); // TODO this usually makes it faster for large requests\n //return Buffer.from(deflate(input, { level: 9, gzip: true }))\n }\n\n static ungzip(input) {\n return buffer_1.Buffer.from((0, pako_1.inflate)(input));\n }\n\n async toBytes() {\n const g = buffer_1.Buffer.alloc(4);\n g.writeUInt32LE(GZIPPacked.CONSTRUCTOR_ID, 0);\n return buffer_1.Buffer.concat([g, (0, __1.serializeBytes)(await GZIPPacked.gzip(this.data))]);\n }\n\n static async read(reader) {\n const constructor = reader.readInt(false);\n\n if (constructor !== GZIPPacked.CONSTRUCTOR_ID) {\n throw new Error("not equal");\n }\n\n return GZIPPacked.gzip(reader.tgReadBytes());\n }\n\n static async fromReader(reader) {\n const data = reader.tgReadBytes();\n return new GZIPPacked(await GZIPPacked.ungzip(data));\n }\n\n}\n\nexports.GZIPPacked = GZIPPacked;\nGZIPPacked.CONSTRUCTOR_ID = 0x3072cfa1;\nGZIPPacked.classType = "constructor";\n\n//# sourceURL=webpack://telegram/./browser/tl/core/GZIPPacked.js?')},"./browser/tl/core/MessageContainer.js": /*!*********************************************!*\ !*** ./browser/tl/core/MessageContainer.js ***! \*********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MessageContainer = void 0;\n\nconst TLMessage_1 = __webpack_require__(/*! ./TLMessage */ "./browser/tl/core/TLMessage.js");\n\nclass MessageContainer {\n constructor(messages) {\n this.CONSTRUCTOR_ID = 0x73f1f8dc;\n this.messages = messages;\n this.classType = "constructor";\n }\n\n static async fromReader(reader) {\n const messages = [];\n const length = reader.readInt();\n\n for (let x = 0; x < length; x++) {\n const msgId = reader.readLong();\n const seqNo = reader.readInt();\n const length = reader.readInt();\n const before = reader.tellPosition();\n const obj = reader.tgReadObject();\n reader.setPosition(before + length);\n const tlMessage = new TLMessage_1.TLMessage(msgId, seqNo, obj);\n messages.push(tlMessage);\n }\n\n return new MessageContainer(messages);\n }\n\n}\n\nexports.MessageContainer = MessageContainer;\nMessageContainer.CONSTRUCTOR_ID = 0x73f1f8dc;\nMessageContainer.classType = "constructor"; // Maximum size in bytes for the inner payload of the container.\n// Telegram will close the connection if the payload is bigger.\n// The overhead of the container itself is subtracted.\n\nMessageContainer.MAXIMUM_SIZE = 1044456 - 8; // Maximum amount of messages that can\'t be sent inside a single\n// container, inclusive. Beyond this limit Telegram will respond\n// with BAD_MESSAGE 64 (invalid container).\n//\n// This limit is not 100% accurate and may in some cases be higher.\n// However, sending up to 100 requests at once in a single container\n// is a reasonable conservative value, since it could also depend on\n// other factors like size per request, but we cannot know this.\n\nMessageContainer.MAXIMUM_LENGTH = 100;\n\n//# sourceURL=webpack://telegram/./browser/tl/core/MessageContainer.js?')},"./browser/tl/core/RPCResult.js": /*!**************************************!*\ !*** ./browser/tl/core/RPCResult.js ***! \**************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.RPCResult = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst _1 = __webpack_require__(/*! ./ */ "./browser/tl/core/index.js");\n\nclass RPCResult {\n constructor(reqMsgId, body, error) {\n this.CONSTRUCTOR_ID = 0xf35c6d01;\n this.reqMsgId = reqMsgId;\n this.body = body;\n this.error = error;\n this.classType = "constructor";\n }\n\n static async fromReader(reader) {\n const msgId = reader.readLong();\n const innerCode = reader.readInt(false);\n\n if (innerCode === api_1.Api.RpcError.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, undefined, api_1.Api.RpcError.fromReader(reader));\n }\n\n if (innerCode === _1.GZIPPacked.CONSTRUCTOR_ID) {\n return new RPCResult(msgId, (await _1.GZIPPacked.fromReader(reader)).data);\n }\n\n reader.seek(-4); // This reader.read() will read more than necessary, but it\'s okay.\n // We could make use of MessageContainer\'s length here, but since\n // it\'s not necessary we don\'t need to care about it.\n\n return new RPCResult(msgId, reader.read(), undefined);\n }\n\n}\n\nexports.RPCResult = RPCResult;\nRPCResult.CONSTRUCTOR_ID = 0xf35c6d01;\nRPCResult.classType = "constructor";\n\n//# sourceURL=webpack://telegram/./browser/tl/core/RPCResult.js?')},"./browser/tl/core/TLMessage.js": /*!**************************************!*\ !*** ./browser/tl/core/TLMessage.js ***! \**************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.TLMessage = void 0;\n\nclass TLMessage {\n constructor(msgId, seqNo, obj) {\n this.msgId = msgId;\n this.seqNo = seqNo;\n this.obj = obj;\n this.classType = "constructor";\n }\n\n}\n\nexports.TLMessage = TLMessage;\nTLMessage.SIZE_OVERHEAD = 12;\nTLMessage.classType = "constructor";\n\n//# sourceURL=webpack://telegram/./browser/tl/core/TLMessage.js?')},"./browser/tl/core/index.js": /*!**********************************!*\ !*** ./browser/tl/core/index.js ***! \**********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.GZIPPacked = exports.MessageContainer = exports.TLMessage = exports.RPCResult = exports.coreObjects = void 0;\n\nconst TLMessage_1 = __webpack_require__(/*! ./TLMessage */ "./browser/tl/core/TLMessage.js");\n\nObject.defineProperty(exports, "TLMessage", ({\n enumerable: true,\n get: function () {\n return TLMessage_1.TLMessage;\n }\n}));\n\nconst RPCResult_1 = __webpack_require__(/*! ./RPCResult */ "./browser/tl/core/RPCResult.js");\n\nObject.defineProperty(exports, "RPCResult", ({\n enumerable: true,\n get: function () {\n return RPCResult_1.RPCResult;\n }\n}));\n\nconst MessageContainer_1 = __webpack_require__(/*! ./MessageContainer */ "./browser/tl/core/MessageContainer.js");\n\nObject.defineProperty(exports, "MessageContainer", ({\n enumerable: true,\n get: function () {\n return MessageContainer_1.MessageContainer;\n }\n}));\n\nconst GZIPPacked_1 = __webpack_require__(/*! ./GZIPPacked */ "./browser/tl/core/GZIPPacked.js");\n\nObject.defineProperty(exports, "GZIPPacked", ({\n enumerable: true,\n get: function () {\n return GZIPPacked_1.GZIPPacked;\n }\n}));\nexports.coreObjects = new Map([[RPCResult_1.RPCResult.CONSTRUCTOR_ID, RPCResult_1.RPCResult], [GZIPPacked_1.GZIPPacked.CONSTRUCTOR_ID, GZIPPacked_1.GZIPPacked], [MessageContainer_1.MessageContainer.CONSTRUCTOR_ID, MessageContainer_1.MessageContainer]]);\n\n//# sourceURL=webpack://telegram/./browser/tl/core/index.js?')},"./browser/tl/custom/button.js": /*!*************************************!*\ !*** ./browser/tl/custom/button.js ***! \*************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Button = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst __1 = __webpack_require__(/*! ../../ */ "./browser/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass Button {\n constructor(button, resize, singleUse, selective) {\n this.button = button;\n this.resize = resize;\n this.singleUse = singleUse;\n this.selective = selective;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n static _isInline(button) {\n return button instanceof api_1.Api.KeyboardButtonCallback || button instanceof api_1.Api.KeyboardButtonSwitchInline || button instanceof api_1.Api.KeyboardButtonUrl || button instanceof api_1.Api.KeyboardButtonUrlAuth || button instanceof api_1.Api.InputKeyboardButtonUrlAuth;\n }\n\n static inline(text, data) {\n if (!data) {\n data = buffer_1.Buffer.from(text, "utf-8");\n }\n\n if (data.length > 64) {\n throw new Error("Too many bytes for the data");\n }\n\n return new api_1.Api.KeyboardButtonCallback({\n text: text,\n data: data\n });\n }\n\n static switchInline(text, query = "", samePeer = false) {\n return new api_1.Api.KeyboardButtonSwitchInline({\n text,\n query,\n samePeer\n });\n }\n\n static url(text, url) {\n return new api_1.Api.KeyboardButtonUrl({\n text: text,\n url: url || text\n });\n }\n\n static auth(text, url, bot, writeAccess, fwdText) {\n return new api_1.Api.InputKeyboardButtonUrlAuth({\n text,\n url: url || text,\n bot: __1.utils.getInputUser(bot || new api_1.Api.InputUserSelf()),\n requestWriteAccess: writeAccess,\n fwdText: fwdText\n });\n }\n\n static text(text, resize, singleUse, selective) {\n return new this(new api_1.Api.KeyboardButton({\n text\n }), resize, singleUse, selective);\n }\n\n static requestLocation(text, resize, singleUse, selective) {\n return new this(new api_1.Api.KeyboardButtonRequestGeoLocation({\n text\n }), resize, singleUse, selective);\n }\n\n static requestPhone(text, resize, singleUse, selective) {\n return new this(new api_1.Api.KeyboardButtonRequestPhone({\n text\n }), resize, singleUse, selective);\n }\n\n static requestPoll(text, resize, singleUse, selective) {\n return new this(new api_1.Api.KeyboardButtonRequestPoll({\n text\n }), resize, singleUse, selective);\n }\n\n static clear() {\n return new api_1.Api.ReplyKeyboardHide({});\n }\n\n static forceReply() {\n return new api_1.Api.ReplyKeyboardForceReply({});\n }\n\n}\n\nexports.Button = Button;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/button.js?')},"./browser/tl/custom/chatGetter.js": /*!*****************************************!*\ !*** ./browser/tl/custom/chatGetter.js ***! \*****************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __asyncValues = this && this.__asyncValues || function (o) {\n if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");\n var m = o[Symbol.asyncIterator],\n i;\n return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {\n return this;\n }, i);\n\n function verb(n) {\n i[n] = o[n] && function (v) {\n return new Promise(function (resolve, reject) {\n v = o[n](v), settle(resolve, reject, v.done, v.value);\n });\n };\n }\n\n function settle(resolve, reject, d, v) {\n Promise.resolve(v).then(function (v) {\n resolve({\n value: v,\n done: d\n });\n }, reject);\n }\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ChatGetter = void 0;\n\nconst __1 = __webpack_require__(/*! ../../ */ "./browser/index.js");\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass ChatGetter {\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n static initChatClass(c, {\n chatPeer,\n inputChat,\n chat,\n broadcast\n }) {\n c._chatPeer = chatPeer;\n c._inputChat = inputChat;\n c._chat = chat;\n c._broadcast = broadcast;\n c._client = undefined;\n }\n\n get chat() {\n return this._chat;\n }\n\n async getChat() {\n var _a;\n\n if (!this._chat || "min" in this._chat && (await this.getInputChat())) {\n try {\n if (this._inputChat) {\n this._chat = await ((_a = this._client) === null || _a === void 0 ? void 0 : _a.getEntity(this._inputChat));\n }\n } catch (e) {\n await this._refetchChat();\n }\n }\n\n return this._chat;\n }\n\n get inputChat() {\n if (!this._inputChat && this._chatPeer && this._client) {\n try {\n this._inputChat = this._client._entityCache.get(__1.utils.getPeerId(this._chatPeer));\n } catch (e) {}\n }\n\n return this._inputChat;\n }\n\n async getInputChat() {\n var e_1, _a;\n\n if (!this.inputChat && this.chatId && this._client) {\n try {\n const target = this.chatId;\n\n try {\n for (var _b = __asyncValues(this._client.iterDialogs({\n limit: 100\n })), _c; _c = await _b.next(), !_c.done;) {\n const dialog = _c.value;\n\n if (dialog.id.eq(target)) {\n this._chat = dialog.entity;\n this._inputChat = dialog.inputEntity;\n break;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) await _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n } catch (e) {// do nothing\n }\n\n return this._inputChat;\n }\n\n return this._inputChat;\n }\n\n get chatId() {\n return this._chatPeer ? (0, Helpers_1.returnBigInt)(__1.utils.getPeerId(this._chatPeer)) : undefined;\n }\n\n get isPrivate() {\n return this._chatPeer ? this._chatPeer instanceof api_1.Api.PeerUser : undefined;\n }\n\n get isGroup() {\n if (!this._broadcast && this.chat && "broadcast" in this.chat) {\n this._broadcast = Boolean(this.chat.broadcast);\n }\n\n if (this._chatPeer instanceof api_1.Api.PeerChannel) {\n if (this._broadcast === undefined) {\n return undefined;\n } else {\n return !this._broadcast;\n }\n }\n\n return this._chatPeer instanceof api_1.Api.PeerChat;\n }\n\n get isChannel() {\n return this._chatPeer instanceof api_1.Api.PeerChannel;\n }\n\n async _refetchChat() {}\n\n}\n\nexports.ChatGetter = ChatGetter;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/chatGetter.js?')},"./browser/tl/custom/dialog.js": /*!*************************************!*\ !*** ./browser/tl/custom/dialog.js ***! \*************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Dialog = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst Utils_1 = __webpack_require__(/*! ../../Utils */ "./browser/Utils.js");\n\nconst draft_1 = __webpack_require__(/*! ./draft */ "./browser/tl/custom/draft.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass Dialog {\n constructor(client, dialog, entities, message) {\n this._client = client;\n this.dialog = dialog;\n this.pinned = !!dialog.pinned;\n this.folderId = dialog.folderId;\n this.archived = dialog.folderId != undefined;\n this.message = message;\n this.date = this.message.date;\n this.entity = entities.get((0, Utils_1.getPeerId)(dialog.peer));\n this.inputEntity = (0, Utils_1.getInputPeer)(this.entity);\n\n if (this.entity) {\n this.id = (0, Helpers_1.returnBigInt)((0, Utils_1.getPeerId)(this.entity)); // ^ May be InputPeerSelf();\n\n this.name = this.title = (0, Utils_1.getDisplayName)(this.entity);\n }\n\n this.unreadCount = dialog.unreadCount;\n this.unreadMentionsCount = dialog.unreadMentionsCount;\n\n if (!this.entity) {\n throw new Error("Entity not found for dialog");\n }\n\n this.draft = new draft_1.Draft(client, this.entity, this.dialog.draft);\n this.isUser = this.entity instanceof api_1.Api.User;\n this.isGroup = !!(this.entity instanceof api_1.Api.Chat || this.entity instanceof api_1.Api.ChatForbidden || this.entity instanceof api_1.Api.Channel && this.entity.megagroup);\n this.isChannel = this.entity instanceof api_1.Api.Channel;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n}\n\nexports.Dialog = Dialog;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/dialog.js?')},"./browser/tl/custom/draft.js": /*!************************************!*\ !*** ./browser/tl/custom/draft.js ***! \************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Draft = void 0;\n\nconst Utils_1 = __webpack_require__(/*! ../../Utils */ "./browser/Utils.js");\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass Draft {\n constructor(client, entity, draft) {\n this._client = client;\n this._peer = (0, Utils_1.getPeer)(entity);\n this._entity = entity;\n this._inputEntity = entity ? (0, Utils_1.getInputPeer)(entity) : undefined;\n\n if (!draft || !(draft instanceof api_1.Api.DraftMessage)) {\n draft = new api_1.Api.DraftMessage({\n message: "",\n date: -1\n });\n }\n\n if (!(draft instanceof api_1.Api.DraftMessageEmpty)) {\n this.linkPreview = !draft.noWebpage;\n this._text = client.parseMode ? client.parseMode.unparse(draft.message, draft.entities || []) : draft.message;\n this._rawText = draft.message;\n this.date = draft.date;\n this.replyToMsgId = draft.replyToMsgId;\n }\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n get entity() {\n return this._entity;\n }\n\n get inputEntity() {\n if (!this._inputEntity) {\n this._inputEntity = this._client._entityCache.get(this._peer);\n }\n\n return this._inputEntity;\n }\n\n}\n\nexports.Draft = Draft;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/draft.js?')},"./browser/tl/custom/file.js": /*!***********************************!*\ !*** ./browser/tl/custom/file.js ***! \***********************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.File = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst Utils_1 = __webpack_require__(/*! ../../Utils */ "./browser/Utils.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass File {\n constructor(media) {\n this.media = media;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n get id() {\n throw new Error("Unsupported");\n }\n\n get name() {\n return this._fromAttr(api_1.Api.DocumentAttributeFilename, "fileName");\n }\n\n get mimeType() {\n if (this.media instanceof api_1.Api.Photo) {\n return "image/jpeg";\n } else if (this.media instanceof api_1.Api.Document) {\n return this.media.mimeType;\n }\n }\n\n get width() {\n return this._fromAttr([api_1.Api.DocumentAttributeImageSize, api_1.Api.DocumentAttributeVideo], "w");\n }\n\n get height() {\n return this._fromAttr([api_1.Api.DocumentAttributeImageSize, api_1.Api.DocumentAttributeVideo], "h");\n }\n\n get duration() {\n return this._fromAttr([api_1.Api.DocumentAttributeAudio, api_1.Api.DocumentAttributeVideo], "duration");\n }\n\n get title() {\n return this._fromAttr(api_1.Api.DocumentAttributeAudio, "title");\n }\n\n get performer() {\n return this._fromAttr(api_1.Api.DocumentAttributeAudio, "performer");\n }\n\n get emoji() {\n return this._fromAttr(api_1.Api.DocumentAttributeSticker, "alt");\n }\n\n get stickerSet() {\n return this._fromAttr(api_1.Api.DocumentAttributeSticker, "stickerset");\n }\n\n get size() {\n if (this.media instanceof api_1.Api.Photo) {\n return (0, Utils_1._photoSizeByteCount)(this.media.sizes[-1]);\n } else if (this.media instanceof api_1.Api.Document) {\n return this.media.size;\n }\n }\n\n _fromAttr(cls, field) {\n if (this.media instanceof api_1.Api.Document) {\n for (const attr of this.media.attributes) {\n if (attr instanceof cls) {\n return attr[field];\n }\n }\n }\n }\n\n}\n\nexports.File = File;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/file.js?')},"./browser/tl/custom/forward.js": /*!**************************************!*\ !*** ./browser/tl/custom/forward.js ***! \**************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.Forward = void 0;\n\nconst chatGetter_1 = __webpack_require__(/*! ./chatGetter */ "./browser/tl/custom/chatGetter.js");\n\nconst senderGetter_1 = __webpack_require__(/*! ./senderGetter */ "./browser/tl/custom/senderGetter.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst Utils_1 = __webpack_require__(/*! ../../Utils */ "./browser/Utils.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass Forward extends senderGetter_1.SenderGetter {\n constructor(client, original, entities) {\n super(); // contains info for the original header sent by telegram.\n\n this.originalFwd = original;\n let senderId = undefined;\n let sender = undefined;\n let inputSender = undefined;\n let peer = undefined;\n let chat = undefined;\n let inputChat = undefined;\n\n if (original.fromId) {\n const ty = (0, Helpers_1._entityType)(original.fromId);\n\n if (ty === Helpers_1._EntityType.USER) {\n senderId = (0, Utils_1.getPeerId)(original.fromId);\n [sender, inputSender] = (0, Utils_1._getEntityPair)(senderId, entities, client._entityCache);\n } else if (ty === Helpers_1._EntityType.CHANNEL || ty === Helpers_1._EntityType.CHAT) {\n peer = original.fromId;\n [chat, inputChat] = (0, Utils_1._getEntityPair)((0, Utils_1.getPeerId)(peer), entities, client._entityCache);\n }\n }\n\n chatGetter_1.ChatGetter.initChatClass(this, {\n chatPeer: peer,\n inputChat: inputChat\n });\n senderGetter_1.SenderGetter.initSenderClass(this, {\n senderId: senderId ? (0, Helpers_1.returnBigInt)(senderId) : undefined,\n sender: sender,\n inputSender: inputSender\n });\n this._client = client;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n}\n\nexports.Forward = Forward;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/forward.js?')},"./browser/tl/custom/index.js": /*!************************************!*\ !*** ./browser/tl/custom/index.js ***! \************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.ChatGetter = void 0;\n\nvar chatGetter_1 = __webpack_require__(/*! ./chatGetter */ "./browser/tl/custom/chatGetter.js");\n\nObject.defineProperty(exports, "ChatGetter", ({\n enumerable: true,\n get: function () {\n return chatGetter_1.ChatGetter;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/index.js?')},"./browser/tl/custom/inlineResult.js": /*!*******************************************!*\ !*** ./browser/tl/custom/inlineResult.js ***! \*******************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.InlineResult = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst __1 = __webpack_require__(/*! ../../ */ "./browser/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass InlineResult {\n constructor(client, original, queryId, entity) {\n this._ARTICLE = "article";\n this._PHOTO = "photo";\n this._GIF = "gif";\n this._VIDEO = "video";\n this._VIDEO_GIF = "mpeg4_gif";\n this._AUDIO = "audio";\n this._DOCUMENT = "document";\n this._LOCATION = "location";\n this._VENUE = "venue";\n this._CONTACT = "contact";\n this._GAME = "game";\n this._client = client;\n this.result = original;\n this._queryId = queryId;\n this._entity = entity;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n get type() {\n return this.result.type;\n }\n\n get message() {\n return this.result.sendMessage;\n }\n\n get description() {\n return this.result.description;\n }\n\n get url() {\n if (this.result instanceof api_1.Api.BotInlineResult) {\n return this.result.url;\n }\n }\n\n get photo() {\n if (this.result instanceof api_1.Api.BotInlineResult) {\n return this.result.thumb;\n } else {\n return this.result.photo;\n }\n }\n\n get document() {\n if (this.result instanceof api_1.Api.BotInlineResult) {\n return this.result.content;\n } else {\n return this.result.document;\n }\n }\n\n async click(entity, replyTo, silent = false, clearDraft = false, hideVia = false) {\n if (entity) {\n entity = await this._client.getInputEntity(entity);\n } else if (this._entity) {\n entity = this._entity;\n } else {\n throw new Error("You must provide the entity where the result should be sent to");\n }\n\n const replyId = replyTo ? __1.utils.getMessageId(replyTo) : undefined;\n const request = new api_1.Api.messages.SendInlineBotResult({\n peer: entity,\n queryId: this._queryId,\n id: this.result.id,\n silent: silent,\n clearDraft: clearDraft,\n hideVia: hideVia,\n replyToMsgId: replyId\n });\n return await this._client.invoke(request);\n }\n\n}\n\nexports.InlineResult = InlineResult;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/inlineResult.js?')},"./browser/tl/custom/inlineResults.js": /*!********************************************!*\ !*** ./browser/tl/custom/inlineResults.js ***! \********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.InlineResults = void 0;\n\nconst inlineResult_1 = __webpack_require__(/*! ./inlineResult */ "./browser/tl/custom/inlineResult.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass InlineResults extends Array {\n constructor(client, original, entity) {\n super(...original.results.map(res => new inlineResult_1.InlineResult(client, res, original.queryId, entity)));\n this.result = original;\n this.queryId = original.queryId;\n this.cacheTime = original.cacheTime;\n this._validUntil = new Date().getTime() / 1000 + this.cacheTime;\n this.users = original.users;\n this.gallery = Boolean(original.gallery);\n this.nextOffset = original.nextOffset;\n this.switchPm = original.switchPm;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n resultsValid() {\n return new Date().getTime() / 1000 < this._validUntil;\n }\n\n}\n\nexports.InlineResults = InlineResults;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/inlineResults.js?')},"./browser/tl/custom/message.js": /*!**************************************!*\ !*** ./browser/tl/custom/message.js ***! \**************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\n\nvar __createBinding = this && this.__createBinding || (Object.create ? function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, {\n enumerable: true,\n get: function () {\n return m[k];\n }\n });\n} : function (o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nvar __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function (o, v) {\n Object.defineProperty(o, "default", {\n enumerable: true,\n value: v\n });\n} : function (o, v) {\n o["default"] = v;\n});\n\nvar __importStar = this && this.__importStar || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n\n __setModuleDefault(result, mod);\n\n return result;\n};\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.CustomMessage = void 0;\n\nconst senderGetter_1 = __webpack_require__(/*! ./senderGetter */ "./browser/tl/custom/senderGetter.js");\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst chatGetter_1 = __webpack_require__(/*! ./chatGetter */ "./browser/tl/custom/chatGetter.js");\n\nconst utils = __importStar(__webpack_require__(/*! ../../Utils */ "./browser/Utils.js"));\n\nconst forward_1 = __webpack_require__(/*! ./forward */ "./browser/tl/custom/forward.js");\n\nconst file_1 = __webpack_require__(/*! ./file */ "./browser/tl/custom/file.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst users_1 = __webpack_require__(/*! ../../client/users */ "./browser/client/users.js");\n\nconst Logger_1 = __webpack_require__(/*! ../../extensions/Logger */ "./browser/extensions/Logger.js");\n\nconst messageButton_1 = __webpack_require__(/*! ./messageButton */ "./browser/tl/custom/messageButton.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n/**\n * This custom class aggregates both {@link Api.Message} and {@link Api.MessageService} to ease accessing their members.
\n *
\n * Remember that this class implements {@link ChatGetter} and {@link SenderGetter}
\n * which means you have access to all their sender and chat properties and methods.\n */\n\n\nclass CustomMessage extends senderGetter_1.SenderGetter {\n constructor(args) {\n super();\n this.init(args);\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n init({\n id,\n peerId = undefined,\n date = undefined,\n out = undefined,\n mentioned = undefined,\n mediaUnread = undefined,\n silent = undefined,\n post = undefined,\n fromId = undefined,\n replyTo = undefined,\n message = undefined,\n fwdFrom = undefined,\n viaBotId = undefined,\n media = undefined,\n replyMarkup = undefined,\n entities = undefined,\n views = undefined,\n editDate = undefined,\n postAuthor = undefined,\n groupedId = undefined,\n fromScheduled = undefined,\n legacy = undefined,\n editHide = undefined,\n pinned = undefined,\n restrictionReason = undefined,\n forwards = undefined,\n replies = undefined,\n action = undefined,\n reactions = undefined,\n noforwards = undefined,\n ttlPeriod = undefined,\n _entities = new Map()\n }) {\n if (!id) throw new Error("id is a required attribute for Message");\n let senderId = undefined;\n\n if (fromId) {\n senderId = utils.getPeerId(fromId);\n } else if (peerId) {\n if (post || !out && peerId instanceof api_1.Api.PeerUser) {\n senderId = utils.getPeerId(peerId);\n }\n } // Common properties to all messages\n\n\n this._entities = _entities;\n this.out = out;\n this.mentioned = mentioned;\n this.mediaUnread = mediaUnread;\n this.silent = silent;\n this.post = post;\n this.post = post;\n this.fromScheduled = fromScheduled;\n this.legacy = legacy;\n this.editHide = editHide;\n this.ttlPeriod = ttlPeriod;\n this.id = id;\n this.fromId = fromId;\n this.peerId = peerId;\n this.fwdFrom = fwdFrom;\n this.viaBotId = viaBotId;\n this.replyTo = replyTo;\n this.date = date;\n this.message = message;\n this.media = media instanceof api_1.Api.MessageMediaEmpty ? media : undefined;\n this.replyMarkup = replyMarkup;\n this.entities = entities;\n this.views = views;\n this.forwards = forwards;\n this.replies = replies;\n this.editDate = editDate;\n this.pinned = pinned;\n this.postAuthor = postAuthor;\n this.groupedId = groupedId;\n this.restrictionReason = restrictionReason;\n this.action = action;\n this.noforwards = noforwards;\n this.reactions = reactions;\n this._client = undefined;\n this._text = undefined;\n this._file = undefined;\n this._replyMessage = undefined;\n this._buttons = undefined;\n this._buttonsFlat = undefined;\n this._buttonsCount = 0;\n this._viaBot = undefined;\n this._viaInputBot = undefined;\n this._actionEntities = undefined; // Note: these calls would reset the client\n\n chatGetter_1.ChatGetter.initChatClass(this, {\n chatPeer: peerId,\n broadcast: post\n });\n senderGetter_1.SenderGetter.initSenderClass(this, {\n senderId: senderId ? (0, Helpers_1.returnBigInt)(senderId) : undefined\n });\n this._forward = undefined;\n }\n\n _finishInit(client, entities, inputChat) {\n this._client = client;\n const cache = client._entityCache;\n\n if (this.senderId) {\n [this._sender, this._inputSender] = utils._getEntityPair(this.senderId.toString(), entities, cache);\n }\n\n if (this.chatId) {\n [this._chat, this._inputChat] = utils._getEntityPair(this.chatId.toString(), entities, cache);\n }\n\n if (inputChat) {\n // This has priority\n this._inputChat = inputChat;\n }\n\n if (this.viaBotId) {\n [this._viaBot, this._viaInputBot] = utils._getEntityPair(this.viaBotId.toString(), entities, cache);\n }\n\n if (this.fwdFrom) {\n this._forward = new forward_1.Forward(this._client, this.fwdFrom, entities);\n }\n\n if (this.action) {\n if (this.action instanceof api_1.Api.MessageActionChatAddUser || this.action instanceof api_1.Api.MessageActionChatCreate) {\n this._actionEntities = this.action.users.map(i => entities.get(i.toString()));\n } else if (this.action instanceof api_1.Api.MessageActionChatDeleteUser) {\n this._actionEntities = [entities.get(this.action.userId.toString())];\n } else if (this.action instanceof api_1.Api.MessageActionChatJoinedByLink) {\n this._actionEntities = [entities.get(utils.getPeerId(new api_1.Api.PeerChannel({\n channelId: this.action.inviterId\n })))];\n } else if (this.action instanceof api_1.Api.MessageActionChannelMigrateFrom) {\n this._actionEntities = [entities.get(utils.getPeerId(new api_1.Api.PeerChat({\n chatId: this.action.chatId\n })))];\n }\n }\n }\n\n get client() {\n return this._client;\n }\n\n get text() {\n if (this._text === undefined && this._client) {\n if (!this._client.parseMode) {\n this._text = this.message;\n } else {\n this._text = this._client.parseMode.unparse(this.message || "", this.entities || []);\n }\n }\n\n return this._text || "";\n }\n\n set text(value) {\n this._text = value;\n\n if (this._client && this._client.parseMode) {\n [this.message, this.entities] = this._client.parseMode.parse(value);\n } else {\n this.message = value;\n this.entities = [];\n }\n }\n\n get rawText() {\n return this.message || "";\n }\n /**\n * @param {string} value\n */\n\n\n set rawText(value) {\n this.message = value;\n this.entities = [];\n this._text = "";\n }\n\n get isReply() {\n return !!this.replyTo;\n }\n\n get forward() {\n return this._forward;\n }\n\n async _refetchSender() {\n await this._reloadMessage();\n }\n /**\n * Re-fetches this message to reload the sender and chat entities,\n * along with their input versions.\n * @private\n */\n\n\n async _reloadMessage() {\n if (!this._client) return;\n let msg = undefined;\n\n try {\n const chat = this.isChannel ? await this.getInputChat() : undefined;\n let temp = await this._client.getMessages(chat, {\n ids: this.id\n });\n\n if (temp) {\n msg = temp[0];\n }\n } catch (e) {\n this._client._log.error("Got error while trying to finish init message with id " + this.id);\n\n if (this._client._log.canSend(Logger_1.LogLevel.ERROR)) {\n console.error(e);\n }\n }\n\n if (msg == undefined) return;\n this._sender = msg._sender;\n this._inputSender = msg._inputSender;\n this._chat = msg._chat;\n this._inputChat = msg._inputChat;\n this._viaBot = msg._viaBot;\n this._viaInputBot = msg._viaInputBot;\n this._forward = msg._forward;\n this._actionEntities = msg._actionEntities;\n }\n /**\n * Returns a list of lists of `MessageButton `, if any.\n * Otherwise, it returns `undefined`.\n */\n\n\n get buttons() {\n if (!this._buttons && this.replyMarkup) {\n if (!this.inputChat) {\n return;\n }\n\n try {\n const bot = this._neededMarkupBot();\n\n this._setButtons(this.inputChat, bot);\n } catch (e) {\n return;\n }\n }\n\n return this._buttons;\n }\n /**\n * Returns `buttons` when that property fails (this is rarely needed).\n */\n\n\n async getButtons() {\n if (!this.buttons && this.replyMarkup) {\n const chat = await this.getInputChat();\n if (!chat) return;\n let bot;\n\n try {\n bot = this._neededMarkupBot();\n } catch (e) {\n await this._reloadMessage();\n bot = this._neededMarkupBot();\n }\n\n this._setButtons(chat, bot);\n }\n\n return this._buttons;\n }\n\n get buttonCount() {\n if (!this._buttonsCount) {\n if (this.replyMarkup instanceof api_1.Api.ReplyInlineMarkup || this.replyMarkup instanceof api_1.Api.ReplyKeyboardMarkup) {\n this._buttonsCount = this.replyMarkup.rows.map(r => r.buttons.length).reduce(function (a, b) {\n return a + b;\n }, 0);\n } else {\n this._buttonsCount = 0;\n }\n }\n\n return this._buttonsCount;\n }\n\n get file() {\n if (!this._file) {\n const media = this.photo || this.document;\n\n if (media) {\n this._file = new file_1.File(media);\n }\n }\n\n return this._file;\n }\n\n get photo() {\n if (this.media instanceof api_1.Api.MessageMediaPhoto) {\n if (this.media.photo instanceof api_1.Api.Photo) return this.media.photo;\n } else if (this.action instanceof api_1.Api.MessageActionChatEditPhoto) {\n return this.action.photo;\n } else {\n return this.webPreview && this.webPreview.photo instanceof api_1.Api.Photo ? this.webPreview.photo : undefined;\n }\n\n return undefined;\n }\n\n get document() {\n if (this.media instanceof api_1.Api.MessageMediaDocument) {\n if (this.media.document instanceof api_1.Api.Document) return this.media.document;\n } else {\n const web = this.webPreview;\n return web && web.document instanceof api_1.Api.Document ? web.document : undefined;\n }\n\n return undefined;\n }\n\n get webPreview() {\n if (this.media instanceof api_1.Api.MessageMediaWebPage) {\n if (this.media.webpage instanceof api_1.Api.WebPage) return this.media.webpage;\n }\n }\n\n get audio() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeAudio, attr => !attr.voice);\n }\n\n get voice() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeAudio, attr => !!attr.voice);\n }\n\n get video() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeVideo);\n }\n\n get videoNote() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeVideo, attr => !!attr.roundMessage);\n }\n\n get gif() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeAnimated);\n }\n\n get sticker() {\n return this._documentByAttribute(api_1.Api.DocumentAttributeSticker);\n }\n\n get contact() {\n if (this.media instanceof api_1.Api.MessageMediaContact) {\n return this.media;\n }\n }\n\n get game() {\n if (this.media instanceof api_1.Api.MessageMediaGame) {\n return this.media.game;\n }\n }\n\n get geo() {\n if (this.media instanceof api_1.Api.MessageMediaGeo || this.media instanceof api_1.Api.MessageMediaGeoLive || this.media instanceof api_1.Api.MessageMediaVenue) {\n return this.media.geo;\n }\n }\n\n get invoice() {\n if (this.media instanceof api_1.Api.MessageMediaInvoice) {\n return this.media;\n }\n }\n\n get poll() {\n if (this.media instanceof api_1.Api.MessageMediaPoll) {\n return this.media;\n }\n }\n\n get venue() {\n if (this.media instanceof api_1.Api.MessageMediaVenue) {\n return this.media;\n }\n }\n\n get dice() {\n if (this.media instanceof api_1.Api.MessageMediaDice) {\n return this.media;\n }\n }\n\n get actionEntities() {\n return this._actionEntities;\n }\n\n get viaBot() {\n return this._viaBot;\n }\n\n get viaInputBot() {\n return this._viaInputBot;\n }\n\n get replyToMsgId() {\n var _a;\n\n return (_a = this.replyTo) === null || _a === void 0 ? void 0 : _a.replyToMsgId;\n }\n\n get toId() {\n if (this._client && !this.out && this.isPrivate) {\n return new api_1.Api.PeerUser({\n userId: (0, users_1._selfId)(this._client)\n });\n }\n\n return this.peerId;\n }\n\n getEntitiesText(cls) {\n let ent = this.entities;\n if (!ent || ent.length == 0) return;\n\n if (cls) {\n ent = ent.filter(v => v instanceof cls);\n }\n\n const texts = utils.getInnerText(this.message || "", ent);\n\n const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]));\n\n return zip([ent, texts]);\n }\n\n async getReplyMessage() {\n if (!this._replyMessage && this._client) {\n if (!this.replyTo) return undefined; // Bots cannot access other bots\' messages by their ID.\n // However they can access them through replies...\n\n this._replyMessage = (await this._client.getMessages(this.isChannel ? await this.getInputChat() : undefined, {\n ids: new api_1.Api.InputMessageReplyTo({\n id: this.id\n })\n }))[0];\n\n if (!this._replyMessage) {\n // ...unless the current message got deleted.\n //\n // If that\'s the case, give it a second chance accessing\n // directly by its ID.\n this._replyMessage = (await this._client.getMessages(this.isChannel ? this._inputChat : undefined, {\n ids: this.replyToMsgId\n }))[0];\n }\n }\n\n return this._replyMessage;\n }\n\n async respond(params) {\n if (this._client) {\n return this._client.sendMessage(await this.getInputChat(), params);\n }\n }\n\n async reply(params) {\n if (this._client) {\n params.replyTo = this.id;\n return this._client.sendMessage(await this.getInputChat(), params);\n }\n }\n\n async forwardTo(entity) {\n if (this._client) {\n entity = await this._client.getInputEntity(entity);\n const params = {\n messages: [this.id],\n fromPeer: await this.getInputChat()\n };\n return this._client.forwardMessages(entity, params);\n }\n }\n\n async edit(params) {\n const param = params;\n if (this.fwdFrom || !this.out || !this._client) return undefined;\n\n if (param.linkPreview == undefined) {\n param.linkPreview = !!this.webPreview;\n }\n\n if (param.buttons == undefined) {\n param.buttons = this.replyMarkup;\n }\n\n param.message = this.id;\n return this._client.editMessage(await this.getInputChat(), param);\n }\n\n async delete({\n revoke\n } = {\n revoke: false\n }) {\n if (this._client) {\n return this._client.deleteMessages(await this.getInputChat(), [this.id], {\n revoke\n });\n }\n }\n\n async pin(params) {\n if (this._client) {\n const entity = await this.getInputChat();\n\n if (entity === undefined) {\n throw Error("Failed to pin message due to cannot get input chat.");\n }\n\n return this._client.pinMessage(entity, this.id, params);\n }\n }\n\n async unpin(params) {\n if (this._client) {\n const entity = await this.getInputChat();\n\n if (entity === undefined) {\n throw Error("Failed to unpin message due to cannot get input chat.");\n }\n\n return this._client.unpinMessage(entity, this.id, params);\n }\n }\n\n async downloadMedia(params) {\n // small hack for patched method\n if (this._client) return this._client.downloadMedia(this, params || {});\n }\n\n async markAsRead() {\n if (this._client) {\n const entity = await this.getInputChat();\n\n if (entity === undefined) {\n throw Error(`Failed to mark message id ${this.id} as read due to cannot get input chat.`);\n }\n\n return this._client.markAsRead(entity, this.id);\n }\n }\n\n async click({\n i,\n j,\n text,\n filter,\n data,\n sharePhone,\n shareGeo,\n password\n }) {\n if (!this.client) {\n return;\n }\n\n if (data) {\n const chat = await this.getInputChat();\n\n if (!chat) {\n return;\n }\n\n const button = new api_1.Api.KeyboardButtonCallback({\n text: "",\n data: data\n });\n return await new messageButton_1.MessageButton(this.client, button, chat, undefined, this.id).click({\n sharePhone: sharePhone,\n shareGeo: shareGeo,\n password: password\n });\n }\n\n if (this.poll) {\n function findPoll(answers) {\n if (i != undefined) {\n if (Array.isArray(i)) {\n const corrects = [];\n\n for (let x = 0; x < i.length; x++) {\n corrects.push(answers[x].option);\n }\n\n return corrects;\n }\n\n return [answers[i].option];\n }\n\n if (text != undefined) {\n if (typeof text == "function") {\n for (const answer of answers) {\n if (text(answer.text)) {\n return [answer.option];\n }\n }\n } else {\n for (const answer of answers) {\n if (answer.text == text) {\n return [answer.option];\n }\n }\n }\n\n return;\n }\n\n if (filter != undefined) {\n for (const answer of answers) {\n if (filter(answer)) {\n return [answer.option];\n }\n }\n\n return;\n }\n }\n\n const options = findPoll(this.poll.poll.answers) || [];\n return await this.client.invoke(new api_1.Api.messages.SendVote({\n peer: this.inputChat,\n msgId: this.id,\n options: options\n }));\n }\n\n if (!(await this.getButtons())) {\n return; // Accessing the property sets this._buttons[_flat]\n }\n\n function findButton(self) {\n if (!self._buttonsFlat || !self._buttons) {\n return;\n }\n\n if (Array.isArray(i)) {\n i = i[0];\n }\n\n if (text != undefined) {\n if (typeof text == "function") {\n for (const button of self._buttonsFlat) {\n if (text(button.text)) {\n return button;\n }\n }\n } else {\n for (const button of self._buttonsFlat) {\n if (button.text == text) {\n return button;\n }\n }\n }\n\n return;\n }\n\n if (filter != undefined) {\n for (const button of self._buttonsFlat) {\n if (filter(button)) {\n return button;\n }\n }\n\n return;\n }\n\n if (i == undefined) {\n i = 0;\n }\n\n if (j == undefined) {\n return self._buttonsFlat[i];\n } else {\n return self._buttons[i][j];\n }\n }\n\n const button = findButton(this);\n\n if (button) {\n return await button.click({\n sharePhone: sharePhone,\n shareGeo: shareGeo,\n password: password\n });\n }\n }\n /**\n * Helper methods to set the buttons given the input sender and chat.\n */\n\n\n _setButtons(chat, bot) {\n if (this.client && (this.replyMarkup instanceof api_1.Api.ReplyInlineMarkup || this.replyMarkup instanceof api_1.Api.ReplyKeyboardMarkup)) {\n this._buttons = [];\n this._buttonsFlat = [];\n\n for (const row of this.replyMarkup.rows) {\n const tmp = [];\n\n for (const button of row.buttons) {\n const btn = new messageButton_1.MessageButton(this.client, button, chat, bot, this.id);\n tmp.push(btn);\n\n this._buttonsFlat.push(btn);\n }\n\n this._buttons.push(tmp);\n }\n }\n }\n /**\n *Returns the input peer of the bot that\'s needed for the reply markup.\n This is necessary for `KeyboardButtonSwitchInline` since we need\n to know what bot we want to start. Raises ``Error`` if the bot\n cannot be found but is needed. Returns `None` if it\'s not needed.\n */\n\n\n _neededMarkupBot() {\n if (!this.client || this.replyMarkup == undefined) {\n return;\n }\n\n if (!(this.replyMarkup instanceof api_1.Api.ReplyInlineMarkup || this.replyMarkup instanceof api_1.Api.ReplyKeyboardMarkup)) {\n return;\n }\n\n for (const row of this.replyMarkup.rows) {\n for (const button of row.buttons) {\n if (button instanceof api_1.Api.KeyboardButtonSwitchInline) {\n if (button.samePeer || !this.viaBotId) {\n const bot = this._inputSender;\n if (!bot) throw new Error("No input sender");\n return bot;\n } else {\n const ent = this.client._entityCache.get(this.viaBotId);\n\n if (!ent) throw new Error("No input sender");\n return ent;\n }\n }\n }\n }\n } // TODO fix this\n\n\n _documentByAttribute(kind, condition) {\n const doc = this.document;\n\n if (doc) {\n for (const attr of doc.attributes) {\n if (attr instanceof kind) {\n if (condition == undefined || typeof condition == "function" && condition(attr)) {\n return doc;\n }\n\n return undefined;\n }\n }\n }\n }\n\n}\n\nexports.CustomMessage = CustomMessage;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/message.js?')},"./browser/tl/custom/messageButton.js": /*!********************************************!*\ !*** ./browser/tl/custom/messageButton.js ***! \********************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.MessageButton = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst button_1 = __webpack_require__(/*! ./button */ "./browser/tl/custom/button.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst Password_1 = __webpack_require__(/*! ../../Password */ "./browser/Password.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass MessageButton {\n constructor(client, original, chat, bot, msgId) {\n this.button = original;\n this._bot = bot;\n this._chat = chat;\n this._msgId = msgId;\n this._client = client;\n }\n\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n get client() {\n return this._client;\n }\n\n get text() {\n return !(this.button instanceof button_1.Button) ? this.button.text : "";\n }\n\n get data() {\n if (this.button instanceof api_1.Api.KeyboardButtonCallback) {\n return this.button.data;\n }\n }\n\n get inlineQuery() {\n if (this.button instanceof api_1.Api.KeyboardButtonSwitchInline) {\n return this.button.query;\n }\n }\n\n get url() {\n if (this.button instanceof api_1.Api.KeyboardButtonUrl) {\n return this.button.url;\n }\n }\n /**\n * Emulates the behaviour of clicking this button.\n If it\'s a normal `KeyboardButton` with text, a message will be\n sent, and the sent `Message ` returned.\n If it\'s an inline `KeyboardButtonCallback` with text and data,\n it will be "clicked" and the `BotCallbackAnswer` returned.\n If it\'s an inline `KeyboardButtonSwitchInline` button, the\n `StartBot` will be invoked and the resulting updates\n returned.\n If it\'s a `KeyboardButtonUrl`, the URL of the button will\n be returned.\n If it\'s a `KeyboardButtonRequestPhone`, you must indicate that you\n want to ``sharePhone=True`` in order to share it. Sharing it is not a\n default because it is a privacy concern and could happen accidentally.\n You may also use ``sharePhone=phone`` to share a specific number, in\n which case either `str` or `InputMediaContact` should be used.\n If it\'s a `KeyboardButtonRequestGeoLocation`, you must pass a\n tuple in ``shareGeo=[longitude, latitude]``. Note that Telegram seems\n to have some heuristics to determine impossible locations, so changing\n this value a lot quickly may not work as expected. You may also pass a\n `InputGeoPoint` if you find the order confusing.\n */\n\n\n async click({\n sharePhone = false,\n shareGeo = [0, 0],\n password\n }) {\n if (this.button instanceof api_1.Api.KeyboardButton) {\n return this._client.sendMessage(this._chat, {\n message: this.button.text,\n parseMode: undefined\n });\n } else if (this.button instanceof api_1.Api.KeyboardButtonCallback) {\n let encryptedPassword;\n\n if (password != undefined) {\n const pwd = await this.client.invoke(new api_1.Api.account.GetPassword());\n encryptedPassword = await (0, Password_1.computeCheck)(pwd, password);\n }\n\n const request = new api_1.Api.messages.GetBotCallbackAnswer({\n peer: this._chat,\n msgId: this._msgId,\n data: this.button.data,\n password: encryptedPassword\n });\n\n try {\n return await this._client.invoke(request);\n } catch (e) {\n if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {\n return null;\n }\n\n throw e;\n }\n } else if (this.button instanceof api_1.Api.KeyboardButtonSwitchInline) {\n return this._client.invoke(new api_1.Api.messages.StartBot({\n bot: this._bot,\n peer: this._chat,\n startParam: this.button.query\n }));\n } else if (this.button instanceof api_1.Api.KeyboardButtonUrl) {\n return this.button.url;\n } else if (this.button instanceof api_1.Api.KeyboardButtonGame) {\n const request = new api_1.Api.messages.GetBotCallbackAnswer({\n peer: this._chat,\n msgId: this._msgId,\n game: true\n });\n\n try {\n return await this._client.invoke(request);\n } catch (e) {\n if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {\n return null;\n }\n\n throw e;\n }\n } else if (this.button instanceof api_1.Api.KeyboardButtonRequestPhone) {\n if (!sharePhone) {\n throw new Error("cannot click on phone buttons unless sharePhone=true");\n }\n\n if (sharePhone == true || typeof sharePhone == "string") {\n const me = await this._client.getMe();\n sharePhone = new api_1.Api.InputMediaContact({\n phoneNumber: (sharePhone == true ? me.phone : sharePhone) || "",\n firstName: me.firstName || "",\n lastName: me.lastName || "",\n vcard: ""\n });\n }\n\n throw new Error("Not supported for now"); // TODO\n //return this._client.sendFile(this._chat, phoneMedia);\n } else if (this.button instanceof api_1.Api.InputWebFileGeoPointLocation) {\n if (!shareGeo) {\n throw new Error("cannot click on geo buttons unless shareGeo=[longitude, latitude]");\n }\n\n throw new Error("Not supported for now"); // TODO\n //return this._client.sendFile(this._chat, geoMedia);\n }\n }\n\n}\n\nexports.MessageButton = MessageButton;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/messageButton.js?')},"./browser/tl/custom/senderGetter.js": /*!*******************************************!*\ !*** ./browser/tl/custom/senderGetter.js ***! \*******************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.SenderGetter = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../../Helpers */ "./browser/Helpers.js");\n\nconst chatGetter_1 = __webpack_require__(/*! ./chatGetter */ "./browser/tl/custom/chatGetter.js");\n\nconst inspect_1 = __webpack_require__(/*! ../../inspect */ "./browser/inspect.js");\n\nclass SenderGetter extends chatGetter_1.ChatGetter {\n [inspect_1.inspect.custom]() {\n return (0, Helpers_1.betterConsoleLog)(this);\n }\n\n static initSenderClass(c, {\n senderId,\n sender,\n inputSender\n }) {\n c._senderId = senderId;\n c._sender = sender;\n c._inputSender = inputSender;\n c._client = undefined;\n }\n\n get sender() {\n return this._sender;\n }\n\n async getSender() {\n if (this._client && (!this._sender || this._sender instanceof api_1.Api.Channel && this._sender.min) && (await this.getInputSender())) {\n try {\n this._sender = await this._client.getEntity(this._inputSender);\n } catch (e) {\n await this._refetchSender();\n }\n }\n\n return this._sender;\n }\n\n get inputSender() {\n if (!this._inputSender && this._senderId && this._client) {\n try {\n this._inputSender = this._client._entityCache.get(this._senderId);\n } catch (e) {}\n }\n\n return this._inputSender;\n }\n\n async getInputSender() {\n if (!this.inputSender && this._senderId && this._client) {\n await this._refetchSender();\n }\n\n return this._inputSender;\n }\n\n get senderId() {\n return this._senderId;\n }\n\n async _refetchSender() {}\n\n}\n\nexports.SenderGetter = SenderGetter;\n\n//# sourceURL=webpack://telegram/./browser/tl/custom/senderGetter.js?')},"./browser/tl/generationHelpers.js": /*!*****************************************!*\ !*** ./browser/tl/generationHelpers.js ***! \*****************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.variableSnakeToCamelCase = exports.snakeToCamelCase = exports.CORE_TYPES = exports.fromLine = exports.buildArgConfig = exports.parseTl = exports.findAll = exports.serializeDate = exports.serializeBytes = void 0;\n\nconst buffer_1 = __webpack_require__(/*! buffer/ */ "./node_modules/buffer/index.js");\n\nconst Helpers_1 = __webpack_require__(/*! ../Helpers */ "./browser/Helpers.js");\n\nconst snakeToCamelCase = name => {\n const result = name.replace(/(?:^|_)([a-z])/g, (_, g) => g.toUpperCase());\n return result.replace(/_/g, "");\n};\n\nexports.snakeToCamelCase = snakeToCamelCase;\n\nconst variableSnakeToCamelCase = str => str.replace(/([-_][a-z])/g, group => group.toUpperCase().replace("-", "").replace("_", ""));\n\nexports.variableSnakeToCamelCase = variableSnakeToCamelCase;\nconst CORE_TYPES = new Set([0xbc799737, 0x997275b5, 0x3fedd339, 0xc4b9f9bb, 0x56730bcc // null#56730bcc = Null;\n]);\nexports.CORE_TYPES = CORE_TYPES;\nconst AUTH_KEY_TYPES = new Set([0x05162463, 0x83c95aec, 0xa9f55f95, 0x3c6a84d4, 0x56fddf88, 0xd0e8075c, 0xb5890dba, 0x6643b654, 0xd712e4be, 0xf5045f1f, 0x3072cfa1 // gzip_packed\n]);\n\nconst fromLine = (line, isFunction) => {\n const match = line.match(/([\\w.]+)(?:#([0-9a-fA-F]+))?(?:\\s{?\\w+:[\\w\\d<>#.?!]+}?)*\\s=\\s([\\w\\d<>#.?]+);$/);\n\n if (!match) {\n // Probably "vector#1cb5c415 {t:Type} # [ t ] = Vector t;"\n throw new Error(`Cannot parse TLObject ${line}`);\n }\n\n const argsMatch = findAll(/({)?(\\w+):([\\w\\d<>#.?!]+)}?/, line);\n const currentConfig = {\n name: match[1],\n constructorId: parseInt(match[2], 16),\n argsConfig: {},\n subclassOfId: (0, Helpers_1.crc32)(match[3]),\n result: match[3],\n isFunction: isFunction,\n namespace: undefined\n };\n\n if (!currentConfig.constructorId) {\n const hexId = "";\n let args;\n\n if (Object.values(currentConfig.argsConfig).length) {\n args = ` ${Object.keys(currentConfig.argsConfig).map(arg => arg.toString()).join(" ")}`;\n } else {\n args = "";\n }\n\n const representation = `${currentConfig.name}${hexId}${args} = ${currentConfig.result}`.replace(/(:|\\?)bytes /g, "$1string ").replace(/|{|}/g, "").replace(/ \\w+:flags(\\d+)?\\.\\d+\\?true/g, "");\n\n if (currentConfig.name === "inputMediaInvoice") {\n // eslint-disable-next-line no-empty\n if (currentConfig.name === "inputMediaInvoice") {}\n }\n\n currentConfig.constructorId = (0, Helpers_1.crc32)(buffer_1.Buffer.from(representation, "utf8"));\n }\n\n for (const [brace, name, argType] of argsMatch) {\n if (brace === undefined) {\n // @ts-ignore\n currentConfig.argsConfig[variableSnakeToCamelCase(name)] = buildArgConfig(name, argType);\n }\n }\n\n if (currentConfig.name.includes(".")) {\n [currentConfig.namespace, currentConfig.name] = currentConfig.name.split(/\\.(.+)/);\n }\n\n currentConfig.name = snakeToCamelCase(currentConfig.name);\n /*\n for (const arg in currentConfig.argsConfig){\n if (currentConfig.argsConfig.hasOwnProperty(arg)){\n if (currentConfig.argsConfig[arg].flagIndicator){\n delete currentConfig.argsConfig[arg]\n }\n }\n }*/\n\n return currentConfig;\n};\n\nexports.fromLine = fromLine;\n\nfunction buildArgConfig(name, argType) {\n name = name === "self" ? "is_self" : name; // Default values\n\n const currentConfig = {\n isVector: false,\n isFlag: false,\n skipConstructorId: false,\n flagName: null,\n flagIndex: -1,\n flagIndicator: true,\n type: null,\n useVectorId: null\n }; // Special case: some types can be inferred, which makes it\n // less annoying to type. Currently the only type that can\n // be inferred is if the name is \'random_id\', to which a\n // random ID will be assigned if left as None (the default)\n\n const canBeInferred = name === "random_id"; // The type can be an indicator that other arguments will be flags\n\n if (argType !== "#") {\n currentConfig.flagIndicator = false; // Strip the exclamation mark always to have only the name\n\n currentConfig.type = argType.replace(/^!+/, ""); // The type may be a flag (flags.IDX?REAL_TYPE)\n // Note that \'flags\' is NOT the flags name; this\n // is determined by a previous argument\n // However, we assume that the argument will always be starts with \'flags\'\n // @ts-ignore\n\n const flagMatch = currentConfig.type.match(/(flags(?:\\d+)?).(\\d+)\\?([\\w<>.]+)/);\n\n if (flagMatch) {\n currentConfig.isFlag = true; // As of layer 140, flagName can be "flags" or "flags2"\n\n currentConfig.flagName = flagMatch[1];\n currentConfig.flagIndex = Number(flagMatch[2]); // Update the type to match the exact type, not the "flagged" one\n\n currentConfig.type = flagMatch[3];\n } // Then check if the type is a Vector\n // @ts-ignore\n\n\n const vectorMatch = currentConfig.type.match(/[Vv]ector<([\\w\\d.]+)>/);\n\n if (vectorMatch) {\n currentConfig.isVector = true; // If the type\'s first letter is not uppercase, then\n // it is a constructor and we use (read/write) its ID.\n // @ts-ignore\n\n currentConfig.useVectorId = currentConfig.type.charAt(0) === "V"; // Update the type to match the one inside the vector\n\n [, currentConfig.type] = vectorMatch;\n } // See use_vector_id. An example of such case is ipPort in\n // help.configSpecial\n // @ts-ignore\n\n\n if (/^[a-z]$/.test(currentConfig.type.split(".").pop().charAt(0))) {\n currentConfig.skipConstructorId = true;\n } // The name may contain "date" in it, if this is the case and\n // the type is "int", we can safely assume that this should be\n // treated as a "date" object. Note that this is not a valid\n // Telegram object, but it\'s easier to work with\n // if (\n // this.type === \'int\' &&\n // (/(\\b|_)([dr]ate|until|since)(\\b|_)/.test(name) ||\n // [\'expires\', \'expires_at\', \'was_online\'].includes(name))\n // ) {\n // this.type = \'date\';\n // }\n\n } // workaround\n\n\n if (currentConfig.type == "future_salt") {\n currentConfig.type = "FutureSalt";\n }\n\n return currentConfig;\n}\n\nexports.buildArgConfig = buildArgConfig;\n\nconst parseTl = function* (content, layer, methods = [], ignoreIds = CORE_TYPES) {\n const methodInfo = (methods || []).reduce((o, m) => Object.assign(Object.assign({}, o), {\n [m.name]: m\n }), {});\n const objAll = [];\n const objByName = {};\n const objByType = {};\n const file = content;\n let isFunction = false;\n\n for (let line of file.split("\\n")) {\n const commentIndex = line.indexOf("//");\n\n if (commentIndex !== -1) {\n line = line.slice(0, commentIndex);\n }\n\n line = line.trim();\n\n if (!line) {\n continue;\n }\n\n const match = line.match(/---(\\w+)---/);\n\n if (match) {\n const [, followingTypes] = match;\n isFunction = followingTypes === "functions";\n continue;\n }\n\n try {\n const result = fromLine(line, isFunction);\n\n if (ignoreIds.has(result.constructorId)) {\n continue;\n }\n\n objAll.push(result);\n\n if (!result.isFunction) {\n if (!objByType[result.result]) {\n objByType[result.result] = [];\n }\n\n objByName[result.name] = result;\n objByType[result.result].push(result);\n }\n } catch (e) {\n if (!e.toString().includes("vector#1cb5c415")) {\n throw e;\n }\n }\n } // Once all objects have been parsed, replace the\n // string type from the arguments with references\n\n\n for (const obj of objAll) {\n if (AUTH_KEY_TYPES.has(obj.constructorId)) {\n for (const arg in obj.argsConfig) {\n if (obj.argsConfig[arg].type === "string") {\n obj.argsConfig[arg].type = "bytes";\n }\n }\n }\n }\n\n for (const obj of objAll) {\n yield obj;\n }\n};\n\nexports.parseTl = parseTl;\n\nconst findAll = (regex, str, matches = []) => {\n if (!regex.flags.includes("g")) {\n regex = new RegExp(regex.source, "g");\n }\n\n const res = regex.exec(str);\n\n if (res) {\n matches.push(res.slice(1));\n findAll(regex, str, matches);\n }\n\n return matches;\n};\n\nexports.findAll = findAll;\n\nfunction serializeBytes(data) {\n if (!(data instanceof buffer_1.Buffer)) {\n if (typeof data == "string") {\n data = buffer_1.Buffer.from(data);\n } else {\n throw Error(`Bytes or str expected, not ${data.constructor.name}`);\n }\n }\n\n const r = [];\n let padding;\n\n if (data.length < 254) {\n padding = (data.length + 1) % 4;\n\n if (padding !== 0) {\n padding = 4 - padding;\n }\n\n r.push(buffer_1.Buffer.from([data.length]));\n r.push(data);\n } else {\n padding = data.length % 4;\n\n if (padding !== 0) {\n padding = 4 - padding;\n }\n\n r.push(buffer_1.Buffer.from([254, data.length % 256, (data.length >> 8) % 256, (data.length >> 16) % 256]));\n r.push(data);\n }\n\n r.push(buffer_1.Buffer.alloc(padding).fill(0));\n return buffer_1.Buffer.concat(r);\n}\n\nexports.serializeBytes = serializeBytes;\n\nfunction serializeDate(dt) {\n if (!dt) {\n return buffer_1.Buffer.alloc(4).fill(0);\n }\n\n if (dt instanceof Date) {\n dt = Math.floor((Date.now() - dt.getTime()) / 1000);\n }\n\n if (typeof dt == "number") {\n const t = buffer_1.Buffer.alloc(4);\n t.writeInt32LE(dt, 0);\n return t;\n }\n\n throw Error(`Cannot interpret "${dt}" as a date`);\n}\n\nexports.serializeDate = serializeDate;\n\n//# sourceURL=webpack://telegram/./browser/tl/generationHelpers.js?')},"./browser/tl/index.js": /*!*****************************!*\ !*** ./browser/tl/index.js ***! \*****************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.serializeDate = exports.serializeBytes = exports.Api = void 0;\n\nconst api_1 = __webpack_require__(/*! ./api */ "./browser/tl/api.js");\n\nObject.defineProperty(exports, "Api", ({\n enumerable: true,\n get: function () {\n return api_1.Api;\n }\n}));\n\nconst patched_1 = __webpack_require__(/*! ./patched */ "./browser/tl/patched/index.js");\n\n(0, patched_1.patchAll)();\n\nvar generationHelpers_1 = __webpack_require__(/*! ./generationHelpers */ "./browser/tl/generationHelpers.js");\n\nObject.defineProperty(exports, "serializeBytes", ({\n enumerable: true,\n get: function () {\n return generationHelpers_1.serializeBytes;\n }\n}));\nObject.defineProperty(exports, "serializeDate", ({\n enumerable: true,\n get: function () {\n return generationHelpers_1.serializeDate;\n }\n}));\n\n//# sourceURL=webpack://telegram/./browser/tl/index.js?')},"./browser/tl/patched/index.js": /*!*************************************!*\ !*** ./browser/tl/patched/index.js ***! \*************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval('\n\nObject.defineProperty(exports, "__esModule", ({\n value: true\n}));\nexports.patchAll = void 0;\n\nconst api_1 = __webpack_require__(/*! ../api */ "./browser/tl/api.js");\n\nconst message_1 = __webpack_require__(/*! ../custom/message */ "./browser/tl/custom/message.js");\n\nfunction getGetter(obj, prop) {\n while (obj) {\n let getter = Object.getOwnPropertyDescriptor(obj, prop);\n\n if (getter && getter.get) {\n return getter.get;\n }\n\n obj = Object.getPrototypeOf(obj);\n }\n}\n\nfunction getSetter(obj, prop) {\n while (obj) {\n let getter = Object.getOwnPropertyDescriptor(obj, prop);\n\n if (getter && getter.set) {\n return getter.set;\n }\n\n obj = Object.getPrototypeOf(obj);\n }\n}\n\nconst getInstanceMethods = obj => {\n let keys = {\n methods: new Set(),\n setters: new Set(),\n getters: new Set()\n };\n let topObject = obj;\n\n const mapAllMethods = property => {\n const getter = getGetter(topObject, property);\n const setter = getSetter(topObject, property);\n\n if (getter) {\n keys["getters"].add(property);\n } else if (setter) {\n keys["setters"].add(property);\n } else {\n if (!(property == "constructor")) {\n keys["methods"].add(property);\n }\n }\n };\n\n do {\n Object.getOwnPropertyNames(obj).map(mapAllMethods); // walk-up the prototype chain\n\n obj = Object.getPrototypeOf(obj);\n } while ( // not the the Object prototype methods (hasOwnProperty, etc...)\n obj && Object.getPrototypeOf(obj));\n\n return keys;\n};\n\nfunction patchClass(clazz) {\n const {\n getters,\n setters,\n methods\n } = getInstanceMethods(message_1.CustomMessage.prototype);\n\n for (const getter of getters) {\n Object.defineProperty(clazz.prototype, getter, {\n get: getGetter(message_1.CustomMessage.prototype, getter)\n });\n }\n\n for (const setter of setters) {\n Object.defineProperty(clazz.prototype, setter, {\n set: getSetter(message_1.CustomMessage.prototype, setter)\n });\n }\n\n for (const method of methods) {\n clazz.prototype[method] = message_1.CustomMessage.prototype[method];\n }\n}\n\nfunction patchAll() {\n patchClass(api_1.Api.Message);\n patchClass(api_1.Api.MessageService);\n}\n\nexports.patchAll = patchAll;\n\n//# sourceURL=webpack://telegram/./browser/tl/patched/index.js?')},"./browser/tl/schemaTl.js": /*!********************************!*\ !*** ./browser/tl/schemaTl.js ***! \********************************/module=>{"use strict";eval("\n\nmodule.exports = `\nresPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector = ResPQ;\np_q_inner_data#83c95aec pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 = P_Q_inner_data;\np_q_inner_data_dc#a9f55f95 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int = P_Q_inner_data;\np_q_inner_data_temp#3c6a84d4 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 expires_in:int = P_Q_inner_data;\np_q_inner_data_temp_dc#56fddf88 pq:string p:string q:string nonce:int128 server_nonce:int128 new_nonce:int256 dc:int expires_in:int = P_Q_inner_data;\nbind_auth_key_inner#75a3f765 nonce:long temp_auth_key_id:long perm_auth_key_id:long temp_session_id:long expires_at:int = BindAuthKeyInner;\nserver_DH_params_fail#79cb045d nonce:int128 server_nonce:int128 new_nonce_hash:int128 = Server_DH_Params;\nserver_DH_params_ok#d0e8075c nonce:int128 server_nonce:int128 encrypted_answer:string = Server_DH_Params;\nserver_DH_inner_data#b5890dba nonce:int128 server_nonce:int128 g:int dh_prime:string g_a:string server_time:int = Server_DH_inner_data;\nclient_DH_inner_data#6643b654 nonce:int128 server_nonce:int128 retry_id:long g_b:string = Client_DH_Inner_Data;\ndh_gen_ok#3bcbf734 nonce:int128 server_nonce:int128 new_nonce_hash1:int128 = Set_client_DH_params_answer;\ndh_gen_retry#46dc1fb9 nonce:int128 server_nonce:int128 new_nonce_hash2:int128 = Set_client_DH_params_answer;\ndh_gen_fail#a69dae02 nonce:int128 server_nonce:int128 new_nonce_hash3:int128 = Set_client_DH_params_answer;\ndestroy_auth_key_ok#f660e1d4 = DestroyAuthKeyRes;\ndestroy_auth_key_none#0a9f2259 = DestroyAuthKeyRes;\ndestroy_auth_key_fail#ea109b13 = DestroyAuthKeyRes;\n---functions---\nreq_pq#60469778 nonce:int128 = ResPQ;\nreq_pq_multi#be7e8ef1 nonce:int128 = ResPQ;\nreq_DH_params#d712e4be nonce:int128 server_nonce:int128 p:string q:string public_key_fingerprint:long encrypted_data:string = Server_DH_Params;\nset_client_DH_params#f5045f1f nonce:int128 server_nonce:int128 encrypted_data:string = Set_client_DH_params_answer;\ndestroy_auth_key#d1435160 = DestroyAuthKeyRes;\n---types---\nmsgs_ack#62d6b459 msg_ids:Vector = MsgsAck;\nbad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification;\nbad_server_salt#edab447b bad_msg_id:long bad_msg_seqno:int error_code:int new_server_salt:long = BadMsgNotification;\nmsgs_state_req#da69fb52 msg_ids:Vector = MsgsStateReq;\nmsgs_state_info#04deb57d req_msg_id:long info:string = MsgsStateInfo;\nmsgs_all_info#8cc0d131 msg_ids:Vector info:string = MsgsAllInfo;\nmsg_detailed_info#276d3ec6 msg_id:long answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_new_detailed_info#809db6df answer_msg_id:long bytes:int status:int = MsgDetailedInfo;\nmsg_resend_req#7d861a08 msg_ids:Vector = MsgResendReq;\nrpc_error#2144ca19 error_code:int error_message:string = RpcError;\nrpc_answer_unknown#5e2ad36e = RpcDropAnswer;\nrpc_answer_dropped_running#cd78e586 = RpcDropAnswer;\nrpc_answer_dropped#a43ad8b7 msg_id:long seq_no:int bytes:int = RpcDropAnswer;\nfuture_salt#0949d9dc valid_since:int valid_until:int salt:long = FutureSalt;\nfuture_salts#ae500895 req_msg_id:long now:int salts:vector = FutureSalts;\npong#347773c5 msg_id:long ping_id:long = Pong;\ndestroy_session_ok#e22045fc session_id:long = DestroySessionRes;\ndestroy_session_none#62d350c9 session_id:long = DestroySessionRes;\nnew_session_created#9ec20908 first_msg_id:long unique_id:long server_salt:long = NewSession;\nhttp_wait#9299359f max_delay:int wait_after:int max_wait:int = HttpWait;\nipPort#d433ad73 ipv4:int port:int = IpPort;\nipPortSecret#37982646 ipv4:int port:int secret:bytes = IpPort;\naccessPointRule#4679b65f phone_prefix_rules:string dc_id:int ips:vector = AccessPointRule;\nhelp.configSimple#5a592a6c date:int expires:int rules:vector = help.ConfigSimple;\ntlsClientHello blocks:vector = TlsClientHello;\ntlsBlockString data:string = TlsBlock;\ntlsBlockRandom length:int = TlsBlock;\ntlsBlockZero length:int = TlsBlock;\ntlsBlockDomain = TlsBlock;\ntlsBlockGrease seed:int = TlsBlock;\ntlsBlockPublicKey = TlsBlock;\ntlsBlockScope entries:Vector = TlsBlock;\n---functions---\nrpc_drop_answer#58e4a740 req_msg_id:long = RpcDropAnswer;\nget_future_salts#b921bd04 num:int = FutureSalts;\nping#7abe77ec ping_id:long = Pong;\nping_delay_disconnect#f3427b8c ping_id:long disconnect_delay:int = Pong;\ndestroy_session#e7512126 session_id:long = DestroySessionRes;\n`;\n\n//# sourceURL=webpack://telegram/./browser/tl/schemaTl.js?")},"./node_modules/base64-js/index.js": /*!*****************************************!*\ !*** ./node_modules/base64-js/index.js ***! \*****************************************/(__unused_webpack_module,exports)=>{"use strict";eval("\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n\n//# sourceURL=webpack://telegram/./node_modules/base64-js/index.js?")},"./node_modules/big-integer/BigInteger.js": /*!************************************************!*\ !*** ./node_modules/big-integer/BigInteger.js ***! \************************************************/(module,exports,__webpack_require__)=>{eval('/* module decorator */ module = __webpack_require__.nmd(module);\nvar __WEBPACK_AMD_DEFINE_RESULT__;var bigInt = (function (undefined) {\r\n "use strict";\r\n\r\n var BASE = 1e7,\r\n LOG_BASE = 7,\r\n MAX_INT = 9007199254740992,\r\n MAX_INT_ARR = smallToArray(MAX_INT),\r\n DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";\r\n\r\n var supportsNativeBigInt = typeof BigInt === "function";\r\n\r\n function Integer(v, radix, alphabet, caseSensitive) {\r\n if (typeof v === "undefined") return Integer[0];\r\n if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);\r\n return parseValue(v);\r\n }\r\n\r\n function BigInteger(value, sign) {\r\n this.value = value;\r\n this.sign = sign;\r\n this.isSmall = false;\r\n }\r\n BigInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function SmallInteger(value) {\r\n this.value = value;\r\n this.sign = value < 0;\r\n this.isSmall = true;\r\n }\r\n SmallInteger.prototype = Object.create(Integer.prototype);\r\n\r\n function NativeBigInt(value) {\r\n this.value = value;\r\n }\r\n NativeBigInt.prototype = Object.create(Integer.prototype);\r\n\r\n function isPrecise(n) {\r\n return -MAX_INT < n && n < MAX_INT;\r\n }\r\n\r\n function smallToArray(n) { // For performance reasons doesn\'t reference BASE, need to change this function if BASE changes\r\n if (n < 1e7)\r\n return [n];\r\n if (n < 1e14)\r\n return [n % 1e7, Math.floor(n / 1e7)];\r\n return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];\r\n }\r\n\r\n function arrayToSmall(arr) { // If BASE changes this function may need to change\r\n trim(arr);\r\n var length = arr.length;\r\n if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {\r\n switch (length) {\r\n case 0: return 0;\r\n case 1: return arr[0];\r\n case 2: return arr[0] + arr[1] * BASE;\r\n default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;\r\n }\r\n }\r\n return arr;\r\n }\r\n\r\n function trim(v) {\r\n var i = v.length;\r\n while (v[--i] === 0);\r\n v.length = i + 1;\r\n }\r\n\r\n function createArray(length) { // function shamelessly stolen from Yaffle\'s library https://github.com/Yaffle/BigInteger\r\n var x = new Array(length);\r\n var i = -1;\r\n while (++i < length) {\r\n x[i] = 0;\r\n }\r\n return x;\r\n }\r\n\r\n function truncate(n) {\r\n if (n > 0) return Math.floor(n);\r\n return Math.ceil(n);\r\n }\r\n\r\n function add(a, b) { // assumes a and b are arrays with a.length >= b.length\r\n var l_a = a.length,\r\n l_b = b.length,\r\n r = new Array(l_a),\r\n carry = 0,\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l_b; i++) {\r\n sum = a[i] + b[i] + carry;\r\n carry = sum >= base ? 1 : 0;\r\n r[i] = sum - carry * base;\r\n }\r\n while (i < l_a) {\r\n sum = a[i] + carry;\r\n carry = sum === base ? 1 : 0;\r\n r[i++] = sum - carry * base;\r\n }\r\n if (carry > 0) r.push(carry);\r\n return r;\r\n }\r\n\r\n function addAny(a, b) {\r\n if (a.length >= b.length) return add(a, b);\r\n return add(b, a);\r\n }\r\n\r\n function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n sum, i;\r\n for (i = 0; i < l; i++) {\r\n sum = a[i] - base + carry;\r\n carry = Math.floor(sum / base);\r\n r[i] = sum - carry * base;\r\n carry += 1;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall) {\r\n return new BigInteger(addSmall(a, Math.abs(b)), this.sign);\r\n }\r\n return new BigInteger(addAny(a, b), this.sign);\r\n };\r\n BigInteger.prototype.plus = BigInteger.prototype.add;\r\n\r\n SmallInteger.prototype.add = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.subtract(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n if (isPrecise(a + b)) return new SmallInteger(a + b);\r\n b = smallToArray(Math.abs(b));\r\n }\r\n return new BigInteger(addSmall(b, Math.abs(a)), a < 0);\r\n };\r\n SmallInteger.prototype.plus = SmallInteger.prototype.add;\r\n\r\n NativeBigInt.prototype.add = function (v) {\r\n return new NativeBigInt(this.value + parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.plus = NativeBigInt.prototype.add;\r\n\r\n function subtract(a, b) { // assumes a and b are arrays with a >= b\r\n var a_l = a.length,\r\n b_l = b.length,\r\n r = new Array(a_l),\r\n borrow = 0,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < b_l; i++) {\r\n difference = a[i] - borrow - b[i];\r\n if (difference < 0) {\r\n difference += base;\r\n borrow = 1;\r\n } else borrow = 0;\r\n r[i] = difference;\r\n }\r\n for (i = b_l; i < a_l; i++) {\r\n difference = a[i] - borrow;\r\n if (difference < 0) difference += base;\r\n else {\r\n r[i++] = difference;\r\n break;\r\n }\r\n r[i] = difference;\r\n }\r\n for (; i < a_l; i++) {\r\n r[i] = a[i];\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function subtractAny(a, b, sign) {\r\n var value;\r\n if (compareAbs(a, b) >= 0) {\r\n value = subtract(a, b);\r\n } else {\r\n value = subtract(b, a);\r\n sign = !sign;\r\n }\r\n value = arrayToSmall(value);\r\n if (typeof value === "number") {\r\n if (sign) value = -value;\r\n return new SmallInteger(value);\r\n }\r\n return new BigInteger(value, sign);\r\n }\r\n\r\n function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT\r\n var l = a.length,\r\n r = new Array(l),\r\n carry = -b,\r\n base = BASE,\r\n i, difference;\r\n for (i = 0; i < l; i++) {\r\n difference = a[i] + carry;\r\n carry = Math.floor(difference / base);\r\n difference %= base;\r\n r[i] = difference < 0 ? difference + base : difference;\r\n }\r\n r = arrayToSmall(r);\r\n if (typeof r === "number") {\r\n if (sign) r = -r;\r\n return new SmallInteger(r);\r\n } return new BigInteger(r, sign);\r\n }\r\n\r\n BigInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n if (this.sign !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var a = this.value, b = n.value;\r\n if (n.isSmall)\r\n return subtractSmall(a, Math.abs(b), this.sign);\r\n return subtractAny(a, b, this.sign);\r\n };\r\n BigInteger.prototype.minus = BigInteger.prototype.subtract;\r\n\r\n SmallInteger.prototype.subtract = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value;\r\n if (a < 0 !== n.sign) {\r\n return this.add(n.negate());\r\n }\r\n var b = n.value;\r\n if (n.isSmall) {\r\n return new SmallInteger(a - b);\r\n }\r\n return subtractSmall(b, Math.abs(a), a >= 0);\r\n };\r\n SmallInteger.prototype.minus = SmallInteger.prototype.subtract;\r\n\r\n NativeBigInt.prototype.subtract = function (v) {\r\n return new NativeBigInt(this.value - parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;\r\n\r\n BigInteger.prototype.negate = function () {\r\n return new BigInteger(this.value, !this.sign);\r\n };\r\n SmallInteger.prototype.negate = function () {\r\n var sign = this.sign;\r\n var small = new SmallInteger(-this.value);\r\n small.sign = !sign;\r\n return small;\r\n };\r\n NativeBigInt.prototype.negate = function () {\r\n return new NativeBigInt(-this.value);\r\n }\r\n\r\n BigInteger.prototype.abs = function () {\r\n return new BigInteger(this.value, false);\r\n };\r\n SmallInteger.prototype.abs = function () {\r\n return new SmallInteger(Math.abs(this.value));\r\n };\r\n NativeBigInt.prototype.abs = function () {\r\n return new NativeBigInt(this.value >= 0 ? this.value : -this.value);\r\n }\r\n\r\n\r\n function multiplyLong(a, b) {\r\n var a_l = a.length,\r\n b_l = b.length,\r\n l = a_l + b_l,\r\n r = createArray(l),\r\n base = BASE,\r\n product, carry, i, a_i, b_j;\r\n for (i = 0; i < a_l; ++i) {\r\n a_i = a[i];\r\n for (var j = 0; j < b_l; ++j) {\r\n b_j = b[j];\r\n product = a_i * b_j + r[i + j];\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n r[i + j + 1] += carry;\r\n }\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE\r\n var l = a.length,\r\n r = new Array(l),\r\n base = BASE,\r\n carry = 0,\r\n product, i;\r\n for (i = 0; i < l; i++) {\r\n product = a[i] * b + carry;\r\n carry = Math.floor(product / base);\r\n r[i] = product - carry * base;\r\n }\r\n while (carry > 0) {\r\n r[i++] = carry % base;\r\n carry = Math.floor(carry / base);\r\n }\r\n return r;\r\n }\r\n\r\n function shiftLeft(x, n) {\r\n var r = [];\r\n while (n-- > 0) r.push(0);\r\n return r.concat(x);\r\n }\r\n\r\n function multiplyKaratsuba(x, y) {\r\n var n = Math.max(x.length, y.length);\r\n\r\n if (n <= 30) return multiplyLong(x, y);\r\n n = Math.ceil(n / 2);\r\n\r\n var b = x.slice(n),\r\n a = x.slice(0, n),\r\n d = y.slice(n),\r\n c = y.slice(0, n);\r\n\r\n var ac = multiplyKaratsuba(a, c),\r\n bd = multiplyKaratsuba(b, d),\r\n abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));\r\n\r\n var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));\r\n trim(product);\r\n return product;\r\n }\r\n\r\n // The following function is derived from a surface fit of a graph plotting the performance difference\r\n // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.\r\n function useKaratsuba(l1, l2) {\r\n return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;\r\n }\r\n\r\n BigInteger.prototype.multiply = function (v) {\r\n var n = parseValue(v),\r\n a = this.value, b = n.value,\r\n sign = this.sign !== n.sign,\r\n abs;\r\n if (n.isSmall) {\r\n if (b === 0) return Integer[0];\r\n if (b === 1) return this;\r\n if (b === -1) return this.negate();\r\n abs = Math.abs(b);\r\n if (abs < BASE) {\r\n return new BigInteger(multiplySmall(a, abs), sign);\r\n }\r\n b = smallToArray(abs);\r\n }\r\n if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes\r\n return new BigInteger(multiplyKaratsuba(a, b), sign);\r\n return new BigInteger(multiplyLong(a, b), sign);\r\n };\r\n\r\n BigInteger.prototype.times = BigInteger.prototype.multiply;\r\n\r\n function multiplySmallAndArray(a, b, sign) { // a >= 0\r\n if (a < BASE) {\r\n return new BigInteger(multiplySmall(b, a), sign);\r\n }\r\n return new BigInteger(multiplyLong(b, smallToArray(a)), sign);\r\n }\r\n SmallInteger.prototype._multiplyBySmall = function (a) {\r\n if (isPrecise(a.value * this.value)) {\r\n return new SmallInteger(a.value * this.value);\r\n }\r\n return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);\r\n };\r\n BigInteger.prototype._multiplyBySmall = function (a) {\r\n if (a.value === 0) return Integer[0];\r\n if (a.value === 1) return this;\r\n if (a.value === -1) return this.negate();\r\n return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);\r\n };\r\n SmallInteger.prototype.multiply = function (v) {\r\n return parseValue(v)._multiplyBySmall(this);\r\n };\r\n SmallInteger.prototype.times = SmallInteger.prototype.multiply;\r\n\r\n NativeBigInt.prototype.multiply = function (v) {\r\n return new NativeBigInt(this.value * parseValue(v).value);\r\n }\r\n NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;\r\n\r\n function square(a) {\r\n //console.assert(2 * BASE * BASE < MAX_INT);\r\n var l = a.length,\r\n r = createArray(l + l),\r\n base = BASE,\r\n product, carry, i, a_i, a_j;\r\n for (i = 0; i < l; i++) {\r\n a_i = a[i];\r\n carry = 0 - a_i * a_i;\r\n for (var j = i; j < l; j++) {\r\n a_j = a[j];\r\n product = 2 * (a_i * a_j) + r[i + j] + carry;\r\n carry = Math.floor(product / base);\r\n r[i + j] = product - carry * base;\r\n }\r\n r[i + l] = carry;\r\n }\r\n trim(r);\r\n return r;\r\n }\r\n\r\n BigInteger.prototype.square = function () {\r\n return new BigInteger(square(this.value), false);\r\n };\r\n\r\n SmallInteger.prototype.square = function () {\r\n var value = this.value * this.value;\r\n if (isPrecise(value)) return new SmallInteger(value);\r\n return new BigInteger(square(smallToArray(Math.abs(this.value))), false);\r\n };\r\n\r\n NativeBigInt.prototype.square = function (v) {\r\n return new NativeBigInt(this.value * this.value);\r\n }\r\n\r\n function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n base = BASE,\r\n result = createArray(b.length),\r\n divisorMostSignificantDigit = b[b_l - 1],\r\n // normalization\r\n lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),\r\n remainder = multiplySmall(a, lambda),\r\n divisor = multiplySmall(b, lambda),\r\n quotientDigit, shift, carry, borrow, i, l, q;\r\n if (remainder.length <= a_l) remainder.push(0);\r\n divisor.push(0);\r\n divisorMostSignificantDigit = divisor[b_l - 1];\r\n for (shift = a_l - b_l; shift >= 0; shift--) {\r\n quotientDigit = base - 1;\r\n if (remainder[shift + b_l] !== divisorMostSignificantDigit) {\r\n quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);\r\n }\r\n // quotientDigit <= base - 1\r\n carry = 0;\r\n borrow = 0;\r\n l = divisor.length;\r\n for (i = 0; i < l; i++) {\r\n carry += quotientDigit * divisor[i];\r\n q = Math.floor(carry / base);\r\n borrow += remainder[shift + i] - (carry - q * base);\r\n carry = q;\r\n if (borrow < 0) {\r\n remainder[shift + i] = borrow + base;\r\n borrow = -1;\r\n } else {\r\n remainder[shift + i] = borrow;\r\n borrow = 0;\r\n }\r\n }\r\n while (borrow !== 0) {\r\n quotientDigit -= 1;\r\n carry = 0;\r\n for (i = 0; i < l; i++) {\r\n carry += remainder[shift + i] - base + divisor[i];\r\n if (carry < 0) {\r\n remainder[shift + i] = carry + base;\r\n carry = 0;\r\n } else {\r\n remainder[shift + i] = carry;\r\n carry = 1;\r\n }\r\n }\r\n borrow += carry;\r\n }\r\n result[shift] = quotientDigit;\r\n }\r\n // denormalization\r\n remainder = divModSmall(remainder, lambda)[0];\r\n return [arrayToSmall(result), arrayToSmall(remainder)];\r\n }\r\n\r\n function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt\'s library http://silentmatt.com/biginteger/\r\n // Performs faster than divMod1 on larger input sizes.\r\n var a_l = a.length,\r\n b_l = b.length,\r\n result = [],\r\n part = [],\r\n base = BASE,\r\n guess, xlen, highx, highy, check;\r\n while (a_l) {\r\n part.unshift(a[--a_l]);\r\n trim(part);\r\n if (compareAbs(part, b) < 0) {\r\n result.push(0);\r\n continue;\r\n }\r\n xlen = part.length;\r\n highx = part[xlen - 1] * base + part[xlen - 2];\r\n highy = b[b_l - 1] * base + b[b_l - 2];\r\n if (xlen > b_l) {\r\n highx = (highx + 1) * base;\r\n }\r\n guess = Math.ceil(highx / highy);\r\n do {\r\n check = multiplySmall(b, guess);\r\n if (compareAbs(check, part) <= 0) break;\r\n guess--;\r\n } while (guess);\r\n result.push(guess);\r\n part = subtract(part, check);\r\n }\r\n result.reverse();\r\n return [arrayToSmall(result), arrayToSmall(part)];\r\n }\r\n\r\n function divModSmall(value, lambda) {\r\n var length = value.length,\r\n quotient = createArray(length),\r\n base = BASE,\r\n i, q, remainder, divisor;\r\n remainder = 0;\r\n for (i = length - 1; i >= 0; --i) {\r\n divisor = remainder * base + value[i];\r\n q = truncate(divisor / lambda);\r\n remainder = divisor - q * lambda;\r\n quotient[i] = q | 0;\r\n }\r\n return [quotient, remainder | 0];\r\n }\r\n\r\n function divModAny(self, v) {\r\n var value, n = parseValue(v);\r\n if (supportsNativeBigInt) {\r\n return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];\r\n }\r\n var a = self.value, b = n.value;\r\n var quotient;\r\n if (b === 0) throw new Error("Cannot divide by zero");\r\n if (self.isSmall) {\r\n if (n.isSmall) {\r\n return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];\r\n }\r\n return [Integer[0], self];\r\n }\r\n if (n.isSmall) {\r\n if (b === 1) return [self, Integer[0]];\r\n if (b == -1) return [self.negate(), Integer[0]];\r\n var abs = Math.abs(b);\r\n if (abs < BASE) {\r\n value = divModSmall(a, abs);\r\n quotient = arrayToSmall(value[0]);\r\n var remainder = value[1];\r\n if (self.sign) remainder = -remainder;\r\n if (typeof quotient === "number") {\r\n if (self.sign !== n.sign) quotient = -quotient;\r\n return [new SmallInteger(quotient), new SmallInteger(remainder)];\r\n }\r\n return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];\r\n }\r\n b = smallToArray(abs);\r\n }\r\n var comparison = compareAbs(a, b);\r\n if (comparison === -1) return [Integer[0], self];\r\n if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];\r\n\r\n // divMod1 is faster on smaller input sizes\r\n if (a.length + b.length <= 200)\r\n value = divMod1(a, b);\r\n else value = divMod2(a, b);\r\n\r\n quotient = value[0];\r\n var qSign = self.sign !== n.sign,\r\n mod = value[1],\r\n mSign = self.sign;\r\n if (typeof quotient === "number") {\r\n if (qSign) quotient = -quotient;\r\n quotient = new SmallInteger(quotient);\r\n } else quotient = new BigInteger(quotient, qSign);\r\n if (typeof mod === "number") {\r\n if (mSign) mod = -mod;\r\n mod = new SmallInteger(mod);\r\n } else mod = new BigInteger(mod, mSign);\r\n return [quotient, mod];\r\n }\r\n\r\n BigInteger.prototype.divmod = function (v) {\r\n var result = divModAny(this, v);\r\n return {\r\n quotient: result[0],\r\n remainder: result[1]\r\n };\r\n };\r\n NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;\r\n\r\n\r\n BigInteger.prototype.divide = function (v) {\r\n return divModAny(this, v)[0];\r\n };\r\n NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {\r\n return new NativeBigInt(this.value / parseValue(v).value);\r\n };\r\n SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;\r\n\r\n BigInteger.prototype.mod = function (v) {\r\n return divModAny(this, v)[1];\r\n };\r\n NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {\r\n return new NativeBigInt(this.value % parseValue(v).value);\r\n };\r\n SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;\r\n\r\n BigInteger.prototype.pow = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value,\r\n value, x, y;\r\n if (b === 0) return Integer[1];\r\n if (a === 0) return Integer[0];\r\n if (a === 1) return Integer[1];\r\n if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.sign) {\r\n return Integer[0];\r\n }\r\n if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");\r\n if (this.isSmall) {\r\n if (isPrecise(value = Math.pow(a, b)))\r\n return new SmallInteger(truncate(value));\r\n }\r\n x = this;\r\n y = Integer[1];\r\n while (true) {\r\n if (b & 1 === 1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === 0) break;\r\n b /= 2;\r\n x = x.square();\r\n }\r\n return y;\r\n };\r\n SmallInteger.prototype.pow = BigInteger.prototype.pow;\r\n\r\n NativeBigInt.prototype.pow = function (v) {\r\n var n = parseValue(v);\r\n var a = this.value, b = n.value;\r\n var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);\r\n if (b === _0) return Integer[1];\r\n if (a === _0) return Integer[0];\r\n if (a === _1) return Integer[1];\r\n if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];\r\n if (n.isNegative()) return new NativeBigInt(_0);\r\n var x = this;\r\n var y = Integer[1];\r\n while (true) {\r\n if ((b & _1) === _1) {\r\n y = y.times(x);\r\n --b;\r\n }\r\n if (b === _0) break;\r\n b /= _2;\r\n x = x.square();\r\n }\r\n return y;\r\n }\r\n\r\n BigInteger.prototype.modPow = function (exp, mod) {\r\n exp = parseValue(exp);\r\n mod = parseValue(mod);\r\n if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");\r\n var r = Integer[1],\r\n base = this.mod(mod);\r\n if (exp.isNegative()) {\r\n exp = exp.multiply(Integer[-1]);\r\n base = base.modInv(mod);\r\n }\r\n while (exp.isPositive()) {\r\n if (base.isZero()) return Integer[0];\r\n if (exp.isOdd()) r = r.multiply(base).mod(mod);\r\n exp = exp.divide(2);\r\n base = base.square().mod(mod);\r\n }\r\n return r;\r\n };\r\n NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;\r\n\r\n function compareAbs(a, b) {\r\n if (a.length !== b.length) {\r\n return a.length > b.length ? 1 : -1;\r\n }\r\n for (var i = a.length - 1; i >= 0; i--) {\r\n if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;\r\n }\r\n return 0;\r\n }\r\n\r\n BigInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) return 1;\r\n return compareAbs(a, b);\r\n };\r\n SmallInteger.prototype.compareAbs = function (v) {\r\n var n = parseValue(v),\r\n a = Math.abs(this.value),\r\n b = n.value;\r\n if (n.isSmall) {\r\n b = Math.abs(b);\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n return -1;\r\n };\r\n NativeBigInt.prototype.compareAbs = function (v) {\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n a = a >= 0 ? a : -a;\r\n b = b >= 0 ? b : -b;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n\r\n BigInteger.prototype.compare = function (v) {\r\n // See discussion about comparison with Infinity:\r\n // https://github.com/peterolson/BigInteger.js/issues/61\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (this.sign !== n.sign) {\r\n return n.sign ? 1 : -1;\r\n }\r\n if (n.isSmall) {\r\n return this.sign ? -1 : 1;\r\n }\r\n return compareAbs(a, b) * (this.sign ? -1 : 1);\r\n };\r\n BigInteger.prototype.compareTo = BigInteger.prototype.compare;\r\n\r\n SmallInteger.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n\r\n var n = parseValue(v),\r\n a = this.value,\r\n b = n.value;\r\n if (n.isSmall) {\r\n return a == b ? 0 : a > b ? 1 : -1;\r\n }\r\n if (a < 0 !== n.sign) {\r\n return a < 0 ? -1 : 1;\r\n }\r\n return a < 0 ? 1 : -1;\r\n };\r\n SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;\r\n\r\n NativeBigInt.prototype.compare = function (v) {\r\n if (v === Infinity) {\r\n return -1;\r\n }\r\n if (v === -Infinity) {\r\n return 1;\r\n }\r\n var a = this.value;\r\n var b = parseValue(v).value;\r\n return a === b ? 0 : a > b ? 1 : -1;\r\n }\r\n NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;\r\n\r\n BigInteger.prototype.equals = function (v) {\r\n return this.compare(v) === 0;\r\n };\r\n NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;\r\n\r\n BigInteger.prototype.notEquals = function (v) {\r\n return this.compare(v) !== 0;\r\n };\r\n NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;\r\n\r\n BigInteger.prototype.greater = function (v) {\r\n return this.compare(v) > 0;\r\n };\r\n NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;\r\n\r\n BigInteger.prototype.lesser = function (v) {\r\n return this.compare(v) < 0;\r\n };\r\n NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;\r\n\r\n BigInteger.prototype.greaterOrEquals = function (v) {\r\n return this.compare(v) >= 0;\r\n };\r\n NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;\r\n\r\n BigInteger.prototype.lesserOrEquals = function (v) {\r\n return this.compare(v) <= 0;\r\n };\r\n NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;\r\n\r\n BigInteger.prototype.isEven = function () {\r\n return (this.value[0] & 1) === 0;\r\n };\r\n SmallInteger.prototype.isEven = function () {\r\n return (this.value & 1) === 0;\r\n };\r\n NativeBigInt.prototype.isEven = function () {\r\n return (this.value & BigInt(1)) === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isOdd = function () {\r\n return (this.value[0] & 1) === 1;\r\n };\r\n SmallInteger.prototype.isOdd = function () {\r\n return (this.value & 1) === 1;\r\n };\r\n NativeBigInt.prototype.isOdd = function () {\r\n return (this.value & BigInt(1)) === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isPositive = function () {\r\n return !this.sign;\r\n };\r\n SmallInteger.prototype.isPositive = function () {\r\n return this.value > 0;\r\n };\r\n NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;\r\n\r\n BigInteger.prototype.isNegative = function () {\r\n return this.sign;\r\n };\r\n SmallInteger.prototype.isNegative = function () {\r\n return this.value < 0;\r\n };\r\n NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;\r\n\r\n BigInteger.prototype.isUnit = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isUnit = function () {\r\n return Math.abs(this.value) === 1;\r\n };\r\n NativeBigInt.prototype.isUnit = function () {\r\n return this.abs().value === BigInt(1);\r\n }\r\n\r\n BigInteger.prototype.isZero = function () {\r\n return false;\r\n };\r\n SmallInteger.prototype.isZero = function () {\r\n return this.value === 0;\r\n };\r\n NativeBigInt.prototype.isZero = function () {\r\n return this.value === BigInt(0);\r\n }\r\n\r\n BigInteger.prototype.isDivisibleBy = function (v) {\r\n var n = parseValue(v);\r\n if (n.isZero()) return false;\r\n if (n.isUnit()) return true;\r\n if (n.compareAbs(2) === 0) return this.isEven();\r\n return this.mod(n).isZero();\r\n };\r\n NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;\r\n\r\n function isBasicPrime(v) {\r\n var n = v.abs();\r\n if (n.isUnit()) return false;\r\n if (n.equals(2) || n.equals(3) || n.equals(5)) return true;\r\n if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;\r\n if (n.lesser(49)) return true;\r\n // we don\'t know if it\'s prime: let the other functions figure it out\r\n }\r\n\r\n function millerRabinTest(n, a) {\r\n var nPrev = n.prev(),\r\n b = nPrev,\r\n r = 0,\r\n d, t, i, x;\r\n while (b.isEven()) b = b.divide(2), r++;\r\n next: for (i = 0; i < a.length; i++) {\r\n if (n.lesser(a[i])) continue;\r\n x = bigInt(a[i]).modPow(b, n);\r\n if (x.isUnit() || x.equals(nPrev)) continue;\r\n for (d = r - 1; d != 0; d--) {\r\n x = x.square().mod(n);\r\n if (x.isUnit()) return false;\r\n if (x.equals(nPrev)) continue next;\r\n }\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2\r\n BigInteger.prototype.isPrime = function (strict) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var bits = n.bitLength();\r\n if (bits <= 64)\r\n return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);\r\n var logN = Math.log(2) * bits.toJSNumber();\r\n var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt(i + 2));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;\r\n\r\n BigInteger.prototype.isProbablePrime = function (iterations, rng) {\r\n var isPrime = isBasicPrime(this);\r\n if (isPrime !== undefined) return isPrime;\r\n var n = this.abs();\r\n var t = iterations === undefined ? 5 : iterations;\r\n for (var a = [], i = 0; i < t; i++) {\r\n a.push(bigInt.randBetween(2, n.minus(2), rng));\r\n }\r\n return millerRabinTest(n, a);\r\n };\r\n NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;\r\n\r\n BigInteger.prototype.modInv = function (n) {\r\n var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;\r\n while (!newR.isZero()) {\r\n q = r.divide(newR);\r\n lastT = t;\r\n lastR = r;\r\n t = newT;\r\n r = newR;\r\n newT = lastT.subtract(q.multiply(newT));\r\n newR = lastR.subtract(q.multiply(newR));\r\n }\r\n if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");\r\n if (t.compare(0) === -1) {\r\n t = t.add(n);\r\n }\r\n if (this.isNegative()) {\r\n return t.negate();\r\n }\r\n return t;\r\n };\r\n\r\n NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;\r\n\r\n BigInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return subtractSmall(value, 1, this.sign);\r\n }\r\n return new BigInteger(addSmall(value, 1), this.sign);\r\n };\r\n SmallInteger.prototype.next = function () {\r\n var value = this.value;\r\n if (value + 1 < MAX_INT) return new SmallInteger(value + 1);\r\n return new BigInteger(MAX_INT_ARR, false);\r\n };\r\n NativeBigInt.prototype.next = function () {\r\n return new NativeBigInt(this.value + BigInt(1));\r\n }\r\n\r\n BigInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (this.sign) {\r\n return new BigInteger(addSmall(value, 1), true);\r\n }\r\n return subtractSmall(value, 1, this.sign);\r\n };\r\n SmallInteger.prototype.prev = function () {\r\n var value = this.value;\r\n if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);\r\n return new BigInteger(MAX_INT_ARR, true);\r\n };\r\n NativeBigInt.prototype.prev = function () {\r\n return new NativeBigInt(this.value - BigInt(1));\r\n }\r\n\r\n var powersOfTwo = [1];\r\n while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);\r\n var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];\r\n\r\n function shift_isSmall(n) {\r\n return Math.abs(n) <= BASE;\r\n }\r\n\r\n BigInteger.prototype.shiftLeft = function (v) {\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + " is too large for shifting.");\r\n }\r\n if (n < 0) return this.shiftRight(-n);\r\n var result = this;\r\n if (result.isZero()) return result;\r\n while (n >= powers2Length) {\r\n result = result.multiply(highestPower2);\r\n n -= powers2Length - 1;\r\n }\r\n return result.multiply(powersOfTwo[n]);\r\n };\r\n NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;\r\n\r\n BigInteger.prototype.shiftRight = function (v) {\r\n var remQuo;\r\n var n = parseValue(v).toJSNumber();\r\n if (!shift_isSmall(n)) {\r\n throw new Error(String(n) + " is too large for shifting.");\r\n }\r\n if (n < 0) return this.shiftLeft(-n);\r\n var result = this;\r\n while (n >= powers2Length) {\r\n if (result.isZero() || (result.isNegative() && result.isUnit())) return result;\r\n remQuo = divModAny(result, highestPower2);\r\n result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n n -= powers2Length - 1;\r\n }\r\n remQuo = divModAny(result, powersOfTwo[n]);\r\n return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];\r\n };\r\n NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;\r\n\r\n function bitwise(x, y, fn) {\r\n y = parseValue(y);\r\n var xSign = x.isNegative(), ySign = y.isNegative();\r\n var xRem = xSign ? x.not() : x,\r\n yRem = ySign ? y.not() : y;\r\n var xDigit = 0, yDigit = 0;\r\n var xDivMod = null, yDivMod = null;\r\n var result = [];\r\n while (!xRem.isZero() || !yRem.isZero()) {\r\n xDivMod = divModAny(xRem, highestPower2);\r\n xDigit = xDivMod[1].toJSNumber();\r\n if (xSign) {\r\n xDigit = highestPower2 - 1 - xDigit; // two\'s complement for negative numbers\r\n }\r\n\r\n yDivMod = divModAny(yRem, highestPower2);\r\n yDigit = yDivMod[1].toJSNumber();\r\n if (ySign) {\r\n yDigit = highestPower2 - 1 - yDigit; // two\'s complement for negative numbers\r\n }\r\n\r\n xRem = xDivMod[0];\r\n yRem = yDivMod[0];\r\n result.push(fn(xDigit, yDigit));\r\n }\r\n var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);\r\n for (var i = result.length - 1; i >= 0; i -= 1) {\r\n sum = sum.multiply(highestPower2).add(bigInt(result[i]));\r\n }\r\n return sum;\r\n }\r\n\r\n BigInteger.prototype.not = function () {\r\n return this.negate().prev();\r\n };\r\n NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;\r\n\r\n BigInteger.prototype.and = function (n) {\r\n return bitwise(this, n, function (a, b) { return a & b; });\r\n };\r\n NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;\r\n\r\n BigInteger.prototype.or = function (n) {\r\n return bitwise(this, n, function (a, b) { return a | b; });\r\n };\r\n NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;\r\n\r\n BigInteger.prototype.xor = function (n) {\r\n return bitwise(this, n, function (a, b) { return a ^ b; });\r\n };\r\n NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;\r\n\r\n var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;\r\n function roughLOB(n) { // get lowestOneBit (rough)\r\n // SmallInteger: return Min(lowestOneBit(n), 1 << 30)\r\n // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]\r\n var v = n.value,\r\n x = typeof v === "number" ? v | LOBMASK_I :\r\n typeof v === "bigint" ? v | BigInt(LOBMASK_I) :\r\n v[0] + v[1] * BASE | LOBMASK_BI;\r\n return x & -x;\r\n }\r\n\r\n function integerLogarithm(value, base) {\r\n if (base.compareTo(value) <= 0) {\r\n var tmp = integerLogarithm(value, base.square(base));\r\n var p = tmp.p;\r\n var e = tmp.e;\r\n var t = p.multiply(base);\r\n return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };\r\n }\r\n return { p: bigInt(1), e: 0 };\r\n }\r\n\r\n BigInteger.prototype.bitLength = function () {\r\n var n = this;\r\n if (n.compareTo(bigInt(0)) < 0) {\r\n n = n.negate().subtract(bigInt(1));\r\n }\r\n if (n.compareTo(bigInt(0)) === 0) {\r\n return bigInt(0);\r\n }\r\n return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));\r\n }\r\n NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;\r\n\r\n function max(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.greater(b) ? a : b;\r\n }\r\n function min(a, b) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n return a.lesser(b) ? a : b;\r\n }\r\n function gcd(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n if (a.equals(b)) return a;\r\n if (a.isZero()) return b;\r\n if (b.isZero()) return a;\r\n var c = Integer[1], d, t;\r\n while (a.isEven() && b.isEven()) {\r\n d = min(roughLOB(a), roughLOB(b));\r\n a = a.divide(d);\r\n b = b.divide(d);\r\n c = c.multiply(d);\r\n }\r\n while (a.isEven()) {\r\n a = a.divide(roughLOB(a));\r\n }\r\n do {\r\n while (b.isEven()) {\r\n b = b.divide(roughLOB(b));\r\n }\r\n if (a.greater(b)) {\r\n t = b; b = a; a = t;\r\n }\r\n b = b.subtract(a);\r\n } while (!b.isZero());\r\n return c.isUnit() ? a : a.multiply(c);\r\n }\r\n function lcm(a, b) {\r\n a = parseValue(a).abs();\r\n b = parseValue(b).abs();\r\n return a.divide(gcd(a, b)).multiply(b);\r\n }\r\n function randBetween(a, b, rng) {\r\n a = parseValue(a);\r\n b = parseValue(b);\r\n var usedRNG = rng || Math.random;\r\n var low = min(a, b), high = max(a, b);\r\n var range = high.subtract(low).add(1);\r\n if (range.isSmall) return low.add(Math.floor(usedRNG() * range));\r\n var digits = toBase(range, BASE).value;\r\n var result = [], restricted = true;\r\n for (var i = 0; i < digits.length; i++) {\r\n var top = restricted ? digits[i] : BASE;\r\n var digit = truncate(usedRNG() * top);\r\n result.push(digit);\r\n if (digit < top) restricted = false;\r\n }\r\n return low.add(Integer.fromArray(result, BASE, false));\r\n }\r\n\r\n var parseBase = function (text, base, alphabet, caseSensitive) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n text = String(text);\r\n if (!caseSensitive) {\r\n text = text.toLowerCase();\r\n alphabet = alphabet.toLowerCase();\r\n }\r\n var length = text.length;\r\n var i;\r\n var absBase = Math.abs(base);\r\n var alphabetValues = {};\r\n for (i = 0; i < alphabet.length; i++) {\r\n alphabetValues[alphabet[i]] = i;\r\n }\r\n for (i = 0; i < length; i++) {\r\n var c = text[i];\r\n if (c === "-") continue;\r\n if (c in alphabetValues) {\r\n if (alphabetValues[c] >= absBase) {\r\n if (c === "1" && absBase === 1) continue;\r\n throw new Error(c + " is not a valid digit in base " + base + ".");\r\n }\r\n }\r\n }\r\n base = parseValue(base);\r\n var digits = [];\r\n var isNegative = text[0] === "-";\r\n for (i = isNegative ? 1 : 0; i < text.length; i++) {\r\n var c = text[i];\r\n if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));\r\n else if (c === "<") {\r\n var start = i;\r\n do { i++; } while (text[i] !== ">" && i < text.length);\r\n digits.push(parseValue(text.slice(start + 1, i)));\r\n }\r\n else throw new Error(c + " is not a valid character");\r\n }\r\n return parseBaseFromArray(digits, base, isNegative);\r\n };\r\n\r\n function parseBaseFromArray(digits, base, isNegative) {\r\n var val = Integer[0], pow = Integer[1], i;\r\n for (i = digits.length - 1; i >= 0; i--) {\r\n val = val.add(digits[i].times(pow));\r\n pow = pow.times(base);\r\n }\r\n return isNegative ? val.negate() : val;\r\n }\r\n\r\n function stringify(digit, alphabet) {\r\n alphabet = alphabet || DEFAULT_ALPHABET;\r\n if (digit < alphabet.length) {\r\n return alphabet[digit];\r\n }\r\n return "<" + digit + ">";\r\n }\r\n\r\n function toBase(n, base) {\r\n base = bigInt(base);\r\n if (base.isZero()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n throw new Error("Cannot convert nonzero numbers to base 0.");\r\n }\r\n if (base.equals(-1)) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n if (n.isNegative())\r\n return {\r\n value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))\r\n .map(Array.prototype.valueOf, [1, 0])\r\n ),\r\n isNegative: false\r\n };\r\n\r\n var arr = Array.apply(null, Array(n.toJSNumber() - 1))\r\n .map(Array.prototype.valueOf, [0, 1]);\r\n arr.unshift([1]);\r\n return {\r\n value: [].concat.apply([], arr),\r\n isNegative: false\r\n };\r\n }\r\n\r\n var neg = false;\r\n if (n.isNegative() && base.isPositive()) {\r\n neg = true;\r\n n = n.abs();\r\n }\r\n if (base.isUnit()) {\r\n if (n.isZero()) return { value: [0], isNegative: false };\r\n\r\n return {\r\n value: Array.apply(null, Array(n.toJSNumber()))\r\n .map(Number.prototype.valueOf, 1),\r\n isNegative: neg\r\n };\r\n }\r\n var out = [];\r\n var left = n, divmod;\r\n while (left.isNegative() || left.compareAbs(base) >= 0) {\r\n divmod = left.divmod(base);\r\n left = divmod.quotient;\r\n var digit = divmod.remainder;\r\n if (digit.isNegative()) {\r\n digit = base.minus(digit).abs();\r\n left = left.next();\r\n }\r\n out.push(digit.toJSNumber());\r\n }\r\n out.push(left.toJSNumber());\r\n return { value: out.reverse(), isNegative: neg };\r\n }\r\n\r\n function toBaseString(n, base, alphabet) {\r\n var arr = toBase(n, base);\r\n return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {\r\n return stringify(x, alphabet);\r\n }).join(\'\');\r\n }\r\n\r\n BigInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n SmallInteger.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n NativeBigInt.prototype.toArray = function (radix) {\r\n return toBase(this, radix);\r\n };\r\n\r\n BigInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix !== 10) return toBaseString(this, radix, alphabet);\r\n var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;\r\n while (--l >= 0) {\r\n digit = String(v[l]);\r\n str += zeros.slice(digit.length) + digit;\r\n }\r\n var sign = this.sign ? "-" : "";\r\n return sign + str;\r\n };\r\n\r\n SmallInteger.prototype.toString = function (radix, alphabet) {\r\n if (radix === undefined) radix = 10;\r\n if (radix != 10) return toBaseString(this, radix, alphabet);\r\n return String(this.value);\r\n };\r\n\r\n NativeBigInt.prototype.toString = SmallInteger.prototype.toString;\r\n\r\n NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }\r\n\r\n BigInteger.prototype.valueOf = function () {\r\n return parseInt(this.toString(), 10);\r\n };\r\n BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;\r\n\r\n SmallInteger.prototype.valueOf = function () {\r\n return this.value;\r\n };\r\n SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;\r\n NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {\r\n return parseInt(this.toString(), 10);\r\n }\r\n\r\n function parseStringValue(v) {\r\n if (isPrecise(+v)) {\r\n var x = +v;\r\n if (x === truncate(x))\r\n return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);\r\n throw new Error("Invalid integer: " + v);\r\n }\r\n var sign = v[0] === "-";\r\n if (sign) v = v.slice(1);\r\n var split = v.split(/e/i);\r\n if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));\r\n if (split.length === 2) {\r\n var exp = split[1];\r\n if (exp[0] === "+") exp = exp.slice(1);\r\n exp = +exp;\r\n if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");\r\n var text = split[0];\r\n var decimalPlace = text.indexOf(".");\r\n if (decimalPlace >= 0) {\r\n exp -= text.length - decimalPlace - 1;\r\n text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);\r\n }\r\n if (exp < 0) throw new Error("Cannot include negative exponent part for integers");\r\n text += (new Array(exp + 1)).join("0");\r\n v = text;\r\n }\r\n var isValid = /^([0-9][0-9]*)$/.test(v);\r\n if (!isValid) throw new Error("Invalid integer: " + v);\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(sign ? "-" + v : v));\r\n }\r\n var r = [], max = v.length, l = LOG_BASE, min = max - l;\r\n while (max > 0) {\r\n r.push(+v.slice(min, max));\r\n min -= l;\r\n if (min < 0) min = 0;\r\n max -= l;\r\n }\r\n trim(r);\r\n return new BigInteger(r, sign);\r\n }\r\n\r\n function parseNumberValue(v) {\r\n if (supportsNativeBigInt) {\r\n return new NativeBigInt(BigInt(v));\r\n }\r\n if (isPrecise(v)) {\r\n if (v !== truncate(v)) throw new Error(v + " is not an integer.");\r\n return new SmallInteger(v);\r\n }\r\n return parseStringValue(v.toString());\r\n }\r\n\r\n function parseValue(v) {\r\n if (typeof v === "number") {\r\n return parseNumberValue(v);\r\n }\r\n if (typeof v === "string") {\r\n return parseStringValue(v);\r\n }\r\n if (typeof v === "bigint") {\r\n return new NativeBigInt(v);\r\n }\r\n return v;\r\n }\r\n // Pre-define numbers in range [-999,999]\r\n for (var i = 0; i < 1000; i++) {\r\n Integer[i] = parseValue(i);\r\n if (i > 0) Integer[-i] = parseValue(-i);\r\n }\r\n // Backwards compatibility\r\n Integer.one = Integer[1];\r\n Integer.zero = Integer[0];\r\n Integer.minusOne = Integer[-1];\r\n Integer.max = max;\r\n Integer.min = min;\r\n Integer.gcd = gcd;\r\n Integer.lcm = lcm;\r\n Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };\r\n Integer.randBetween = randBetween;\r\n\r\n Integer.fromArray = function (digits, base, isNegative) {\r\n return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);\r\n };\r\n\r\n return Integer;\r\n})();\r\n\r\n// Node.js check\r\nif ( true && module.hasOwnProperty("exports")) {\r\n module.exports = bigInt;\r\n}\r\n\r\n//amd check\r\nif (true) {\r\n !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {\r\n return bigInt;\r\n }).call(exports, __webpack_require__, exports, module),\n\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\r\n}\r\n\n\n//# sourceURL=webpack://telegram/./node_modules/big-integer/BigInteger.js?')},"./node_modules/buffer/index.js": /*!**************************************!*\ !*** ./node_modules/buffer/index.js ***! \**************************************/(__unused_webpack_module,exports,__webpack_require__)=>{"use strict";eval("/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n\n\nconst base64 = __webpack_require__(/*! base64-js */ \"./node_modules/base64-js/index.js\")\nconst ieee754 = __webpack_require__(/*! ieee754 */ \"./node_modules/ieee754/index.js\")\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n\n\n//# sourceURL=webpack://telegram/./node_modules/buffer/index.js?")},"./node_modules/dom-serializer/lib/foreignNames.js": /*!*********************************************************!*\ !*** ./node_modules/dom-serializer/lib/foreignNames.js ***! \*********************************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nexports.attributeNames = exports.elementNames = void 0;\nexports.elementNames = new Map([\n ["altglyph", "altGlyph"],\n ["altglyphdef", "altGlyphDef"],\n ["altglyphitem", "altGlyphItem"],\n ["animatecolor", "animateColor"],\n ["animatemotion", "animateMotion"],\n ["animatetransform", "animateTransform"],\n ["clippath", "clipPath"],\n ["feblend", "feBlend"],\n ["fecolormatrix", "feColorMatrix"],\n ["fecomponenttransfer", "feComponentTransfer"],\n ["fecomposite", "feComposite"],\n ["feconvolvematrix", "feConvolveMatrix"],\n ["fediffuselighting", "feDiffuseLighting"],\n ["fedisplacementmap", "feDisplacementMap"],\n ["fedistantlight", "feDistantLight"],\n ["fedropshadow", "feDropShadow"],\n ["feflood", "feFlood"],\n ["fefunca", "feFuncA"],\n ["fefuncb", "feFuncB"],\n ["fefuncg", "feFuncG"],\n ["fefuncr", "feFuncR"],\n ["fegaussianblur", "feGaussianBlur"],\n ["feimage", "feImage"],\n ["femerge", "feMerge"],\n ["femergenode", "feMergeNode"],\n ["femorphology", "feMorphology"],\n ["feoffset", "feOffset"],\n ["fepointlight", "fePointLight"],\n ["fespecularlighting", "feSpecularLighting"],\n ["fespotlight", "feSpotLight"],\n ["fetile", "feTile"],\n ["feturbulence", "feTurbulence"],\n ["foreignobject", "foreignObject"],\n ["glyphref", "glyphRef"],\n ["lineargradient", "linearGradient"],\n ["radialgradient", "radialGradient"],\n ["textpath", "textPath"],\n]);\nexports.attributeNames = new Map([\n ["definitionurl", "definitionURL"],\n ["attributename", "attributeName"],\n ["attributetype", "attributeType"],\n ["basefrequency", "baseFrequency"],\n ["baseprofile", "baseProfile"],\n ["calcmode", "calcMode"],\n ["clippathunits", "clipPathUnits"],\n ["diffuseconstant", "diffuseConstant"],\n ["edgemode", "edgeMode"],\n ["filterunits", "filterUnits"],\n ["glyphref", "glyphRef"],\n ["gradienttransform", "gradientTransform"],\n ["gradientunits", "gradientUnits"],\n ["kernelmatrix", "kernelMatrix"],\n ["kernelunitlength", "kernelUnitLength"],\n ["keypoints", "keyPoints"],\n ["keysplines", "keySplines"],\n ["keytimes", "keyTimes"],\n ["lengthadjust", "lengthAdjust"],\n ["limitingconeangle", "limitingConeAngle"],\n ["markerheight", "markerHeight"],\n ["markerunits", "markerUnits"],\n ["markerwidth", "markerWidth"],\n ["maskcontentunits", "maskContentUnits"],\n ["maskunits", "maskUnits"],\n ["numoctaves", "numOctaves"],\n ["pathlength", "pathLength"],\n ["patterncontentunits", "patternContentUnits"],\n ["patterntransform", "patternTransform"],\n ["patternunits", "patternUnits"],\n ["pointsatx", "pointsAtX"],\n ["pointsaty", "pointsAtY"],\n ["pointsatz", "pointsAtZ"],\n ["preservealpha", "preserveAlpha"],\n ["preserveaspectratio", "preserveAspectRatio"],\n ["primitiveunits", "primitiveUnits"],\n ["refx", "refX"],\n ["refy", "refY"],\n ["repeatcount", "repeatCount"],\n ["repeatdur", "repeatDur"],\n ["requiredextensions", "requiredExtensions"],\n ["requiredfeatures", "requiredFeatures"],\n ["specularconstant", "specularConstant"],\n ["specularexponent", "specularExponent"],\n ["spreadmethod", "spreadMethod"],\n ["startoffset", "startOffset"],\n ["stddeviation", "stdDeviation"],\n ["stitchtiles", "stitchTiles"],\n ["surfacescale", "surfaceScale"],\n ["systemlanguage", "systemLanguage"],\n ["tablevalues", "tableValues"],\n ["targetx", "targetX"],\n ["targety", "targetY"],\n ["textlength", "textLength"],\n ["viewbox", "viewBox"],\n ["viewtarget", "viewTarget"],\n ["xchannelselector", "xChannelSelector"],\n ["ychannelselector", "yChannelSelector"],\n ["zoomandpan", "zoomAndPan"],\n]);\n\n\n//# sourceURL=webpack://telegram/./node_modules/dom-serializer/lib/foreignNames.js?')},"./node_modules/dom-serializer/lib/index.js": /*!**************************************************!*\ !*** ./node_modules/dom-serializer/lib/index.js ***! \**************************************************/function(__unused_webpack_module,exports,__webpack_require__){"use strict";eval('\nvar __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, "default", { enumerable: true, value: v });\n}) : function(o, v) {\n o["default"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, "__esModule", ({ value: true }));\n/*\n * Module dependencies\n */\nvar ElementType = __importStar(__webpack_require__(/*! domelementtype */ "./node_modules/domelementtype/lib/index.js"));\nvar entities_1 = __webpack_require__(/*! entities */ "./node_modules/entities/lib/index.js");\n/**\n * Mixed-case SVG and MathML tags & attributes\n * recognized by the HTML parser.\n *\n * @see https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign\n */\nvar foreignNames_1 = __webpack_require__(/*! ./foreignNames */ "./node_modules/dom-serializer/lib/foreignNames.js");\nvar unencodedElements = new Set([\n "style",\n "script",\n "xmp",\n "iframe",\n "noembed",\n "noframes",\n "plaintext",\n "noscript",\n]);\n/**\n * Format attributes\n */\nfunction formatAttributes(attributes, opts) {\n if (!attributes)\n return;\n return Object.keys(attributes)\n .map(function (key) {\n var _a, _b;\n var value = (_a = attributes[key]) !== null && _a !== void 0 ? _a : "";\n if (opts.xmlMode === "foreign") {\n /* Fix up mixed-case attribute names */\n key = (_b = foreignNames_1.attributeNames.get(key)) !== null && _b !== void 0 ? _b : key;\n }\n if (!opts.emptyAttrs && !opts.xmlMode && value === "") {\n return key;\n }\n return key + "=\\"" + (opts.decodeEntities !== false\n ? entities_1.encodeXML(value)\n : value.replace(/"/g, """)) + "\\"";\n })\n .join(" ");\n}\n/**\n * Self-enclosing tags\n */\nvar singleTag = new Set([\n "area",\n "base",\n "basefont",\n "br",\n "col",\n "command",\n "embed",\n "frame",\n "hr",\n "img",\n "input",\n "isindex",\n "keygen",\n "link",\n "meta",\n "param",\n "source",\n "track",\n "wbr",\n]);\n/**\n * Renders a DOM node or an array of DOM nodes to a string.\n *\n * Can be thought of as the equivalent of the `outerHTML` of the passed node(s).\n *\n * @param node Node to be rendered.\n * @param options Changes serialization behavior\n */\nfunction render(node, options) {\n if (options === void 0) { options = {}; }\n var nodes = "length" in node ? node : [node];\n var output = "";\n for (var i = 0; i < nodes.length; i++) {\n output += renderNode(nodes[i], options);\n }\n return output;\n}\nexports["default"] = render;\nfunction renderNode(node, options) {\n switch (node.type) {\n case ElementType.Root:\n return render(node.children, options);\n case ElementType.Directive:\n case ElementType.Doctype:\n return renderDirective(node);\n case ElementType.Comment:\n return renderComment(node);\n case ElementType.CDATA:\n return renderCdata(node);\n case ElementType.Script:\n case ElementType.Style:\n case ElementType.Tag:\n return renderTag(node, options);\n case ElementType.Text:\n return renderText(node, options);\n }\n}\nvar foreignModeIntegrationPoints = new Set([\n "mi",\n "mo",\n "mn",\n "ms",\n "mtext",\n "annotation-xml",\n "foreignObject",\n "desc",\n "title",\n]);\nvar foreignElements = new Set(["svg", "math"]);\nfunction renderTag(elem, opts) {\n var _a;\n // Handle SVG / MathML in HTML\n if (opts.xmlMode === "foreign") {\n /* Fix up mixed-case element names */\n elem.name = (_a = foreignNames_1.elementNames.get(elem.name)) !== null && _a !== void 0 ? _a : elem.name;\n /* Exit foreign mode at integration points */\n if (elem.parent &&\n foreignModeIntegrationPoints.has(elem.parent.name)) {\n opts = __assign(__assign({}, opts), { xmlMode: false });\n }\n }\n if (!opts.xmlMode && foreignElements.has(elem.name)) {\n opts = __assign(__assign({}, opts), { xmlMode: "foreign" });\n }\n var tag = "<" + elem.name;\n var attribs = formatAttributes(elem.attribs, opts);\n if (attribs) {\n tag += " " + attribs;\n }\n if (elem.children.length === 0 &&\n (opts.xmlMode\n ? // In XML mode or foreign mode, and user hasn\'t explicitly turned off self-closing tags\n opts.selfClosingTags !== false\n : // User explicitly asked for self-closing tags, even in HTML mode\n opts.selfClosingTags && singleTag.has(elem.name))) {\n if (!opts.xmlMode)\n tag += " ";\n tag += "/>";\n }\n else {\n tag += ">";\n if (elem.children.length > 0) {\n tag += render(elem.children, opts);\n }\n if (opts.xmlMode || !singleTag.has(elem.name)) {\n tag += "";\n }\n }\n return tag;\n}\nfunction renderDirective(elem) {\n return "<" + elem.data + ">";\n}\nfunction renderText(elem, opts) {\n var data = elem.data || "";\n // If entities weren\'t decoded, no need to encode them back\n if (opts.decodeEntities !== false &&\n !(!opts.xmlMode &&\n elem.parent &&\n unencodedElements.has(elem.parent.name))) {\n data = entities_1.encodeXML(data);\n }\n return data;\n}\nfunction renderCdata(elem) {\n return "";\n}\nfunction renderComment(elem) {\n return "\x3c!--" + elem.data + "--\x3e";\n}\n\n\n//# sourceURL=webpack://telegram/./node_modules/dom-serializer/lib/index.js?')},"./node_modules/domelementtype/lib/index.js": /*!**************************************************!*\ !*** ./node_modules/domelementtype/lib/index.js ***! \**************************************************/(__unused_webpack_module,exports)=>{"use strict";eval('\nObject.defineProperty(exports, "__esModule", ({ value: true }));\nexports.Doctype = exports.CDATA = exports.Tag = exports.Style = exports.Script = exports.Comment = exports.Directive = exports.Text = exports.Root = exports.isTag = exports.ElementType = void 0;\n/** Types of elements found in htmlparser2\'s DOM */\nvar ElementType;\n(function (ElementType) {\n /** Type for the root element of a document */\n ElementType["Root"] = "root";\n /** Type for Text */\n ElementType["Text"] = "text";\n /** Type for */\n ElementType["Directive"] = "directive";\n /** Type for \x3c!-- ... --\x3e */\n ElementType["Comment"] = "comment";\n /** Type for